text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```objective-c
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
/* config.h. Manually generated for Xcode. */
/* Default visibility */
#define DEFAULT_VISIBILITY /**/
/* Message logging */
// #define ENABLE_LOGGING 1
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have the <poll.h> header file. */
#define HAVE_POLL_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Darwin backend */
#define OS_DARWIN 1
/* type of second poll() argument */
#define POLL_NFDS_TYPE nfds_t
/* Use POSIX Threads */
#define THREADS_POSIX 1
/* Use GNU extensions */
#define _GNU_SOURCE 1
``` | /content/code_sandbox/libs/push2/libusb/config_xcode.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 387 |
```objective-c
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#if defined(__APPLE__)
#include "config_xcode.h"
#elif defined(WIN32)
#include "config_msvc.h"
#else
#include "config_linux.h"
#endif
``` | /content/code_sandbox/libs/push2/libusb/config.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 254 |
```objective-c
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
/* config.h. Manual config for MSVC. */
#ifndef _MSC_VER
#warn "msvc/config.h shouldn't be included for your development environment."
#error "Please make sure the msvc/ directory is removed from your build path."
#endif
/* Disable: warning C4200: nonstandard extension used : zero-sized array in struct/union */
#pragma warning(disable:4200)
/* Disable: warning C6258: Using TerminateThread does not allow proper thread clean up */
#pragma warning(disable: 6258)
#if defined(_PREFAST_)
/* Disable "Banned API" errors when using the MS's WDK OACR/Prefast */
#pragma warning(disable:28719)
/* Disable "The function 'InitializeCriticalSection' must be called from within a try/except block" */
#pragma warning(disable:28125)
#endif
/* Default visibility */
#define DEFAULT_VISIBILITY /**/
/* Enable global message logging */
//#define ENABLE_LOGGING 1
/* Uncomment to start with debug message logging enabled */
// #define ENABLE_DEBUG_LOGGING 1
/* Uncomment to enabling logging to system log */
// #define USE_SYSTEM_LOGGING_FACILITY
/* type of second poll() argument */
#define POLL_NFDS_TYPE unsigned int
/* Windows/WinCE backend */
#if defined(_WIN32_WCE)
#define OS_WINCE 1
#define HAVE_MISSING_H
#else
#define OS_WINDOWS 1
#define HAVE_SIGNAL_H 1
#define HAVE_SYS_TYPES_H 1
#endif
``` | /content/code_sandbox/libs/push2/libusb/config_msvc.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 531 |
```c++
/*
******************************************************************
* C++ Mathematical Expression Toolkit Library *
* *
* Author: Arash Partow (1999-2023) *
* URL: path_to_url *
* *
* Free use of the C++ Mathematical Expression Toolkit Library is *
* permitted under the guidelines and in accordance with the most *
* path_to_url *
* *
* Example expressions: *
* (00) (y + x / y) * (x - y / x) *
* (01) (x^2 / sin(2 * pi / y)) - x / 2 *
* (02) sqrt(1 - (x^2)) *
* (03) 1 - sin(2 * x) + cos(pi / y) *
* (04) a * exp(2 * t) + c *
* (05) if(((x + 2) == 3) and ((y + 5) <= 9),1 + w, 2 / z) *
* (06) (avg(x,y) <= x + y ? x - y : x * y) + 2 * pi / x *
* (07) z := x + sin(2 * pi / y) *
* (08) u := 2 * (pi * z) / (w := x + cos(y / pi)) *
* (09) clamp(-1,sin(2 * pi * x) + cos(y / 2 * pi),+1) *
* (10) inrange(-2,m,+2) == if(({-2 <= m} and [m <= +2]),1,0) *
* (11) (2sin(x)cos(2y)7 + 1) == (2 * sin(x) * cos(2*y) * 7 + 1) *
* (12) (x ilike 's*ri?g') and [y < (3 z^7 + w)] *
* *
******************************************************************
*/
#ifndef INCLUDE_EXPRTK_HPP
#define INCLUDE_EXPRTK_HPP
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <exception>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace exprtk
{
#ifdef exprtk_enable_debugging
#define exprtk_debug(params) printf params
#else
#define exprtk_debug(params) (void)0
#endif
#define exprtk_error_location \
"exprtk.hpp:" + details::to_str(__LINE__) \
#if defined(__GNUC__) && (__GNUC__ >= 7)
#define exprtk_disable_fallthrough_begin \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") \
#define exprtk_disable_fallthrough_end \
_Pragma ("GCC diagnostic pop") \
#else
#define exprtk_disable_fallthrough_begin (void)0;
#define exprtk_disable_fallthrough_end (void)0;
#endif
#if __cplusplus >= 201103L
#define exprtk_override override
#define exprtk_final final
#define exprtk_delete = delete
#else
#define exprtk_override
#define exprtk_final
#define exprtk_delete
#endif
namespace details
{
typedef char char_t;
typedef char_t* char_ptr;
typedef char_t const* char_cptr;
typedef unsigned char uchar_t;
typedef uchar_t* uchar_ptr;
typedef uchar_t const* uchar_cptr;
typedef unsigned long long int _uint64_t;
typedef long long int _int64_t;
inline bool is_whitespace(const char_t c)
{
return (' ' == c) || ('\n' == c) ||
('\r' == c) || ('\t' == c) ||
('\b' == c) || ('\v' == c) ||
('\f' == c) ;
}
inline bool is_operator_char(const char_t c)
{
return ('+' == c) || ('-' == c) ||
('*' == c) || ('/' == c) ||
('^' == c) || ('<' == c) ||
('>' == c) || ('=' == c) ||
(',' == c) || ('!' == c) ||
('(' == c) || (')' == c) ||
('[' == c) || (']' == c) ||
('{' == c) || ('}' == c) ||
('%' == c) || (':' == c) ||
('?' == c) || ('&' == c) ||
('|' == c) || (';' == c) ;
}
inline bool is_letter(const char_t c)
{
return (('a' <= c) && (c <= 'z')) ||
(('A' <= c) && (c <= 'Z')) ;
}
inline bool is_digit(const char_t c)
{
return ('0' <= c) && (c <= '9');
}
inline bool is_letter_or_digit(const char_t c)
{
return is_letter(c) || is_digit(c);
}
inline bool is_left_bracket(const char_t c)
{
return ('(' == c) || ('[' == c) || ('{' == c);
}
inline bool is_right_bracket(const char_t c)
{
return (')' == c) || (']' == c) || ('}' == c);
}
inline bool is_bracket(const char_t c)
{
return is_left_bracket(c) || is_right_bracket(c);
}
inline bool is_sign(const char_t c)
{
return ('+' == c) || ('-' == c);
}
inline bool is_invalid(const char_t c)
{
return !is_whitespace (c) &&
!is_operator_char(c) &&
!is_letter (c) &&
!is_digit (c) &&
('.' != c) &&
('_' != c) &&
('$' != c) &&
('~' != c) &&
('\'' != c);
}
inline bool is_valid_string_char(const char_t c)
{
return std::isprint(static_cast<uchar_t>(c)) ||
is_whitespace(c);
}
#ifndef exprtk_disable_caseinsensitivity
inline void case_normalise(std::string& s)
{
for (std::size_t i = 0; i < s.size(); ++i)
{
s[i] = static_cast<std::string::value_type>(std::tolower(s[i]));
}
}
inline bool imatch(const char_t c1, const char_t c2)
{
return std::tolower(c1) == std::tolower(c2);
}
inline bool imatch(const std::string& s1, const std::string& s2)
{
if (s1.size() == s2.size())
{
for (std::size_t i = 0; i < s1.size(); ++i)
{
if (std::tolower(s1[i]) != std::tolower(s2[i]))
{
return false;
}
}
return true;
}
return false;
}
struct ilesscompare
{
inline bool operator() (const std::string& s1, const std::string& s2) const
{
const std::size_t length = std::min(s1.size(),s2.size());
for (std::size_t i = 0; i < length; ++i)
{
const char_t c1 = static_cast<char_t>(std::tolower(s1[i]));
const char_t c2 = static_cast<char_t>(std::tolower(s2[i]));
if (c1 > c2)
return false;
else if (c1 < c2)
return true;
}
return s1.size() < s2.size();
}
};
#else
inline void case_normalise(std::string&)
{}
inline bool imatch(const char_t c1, const char_t c2)
{
return c1 == c2;
}
inline bool imatch(const std::string& s1, const std::string& s2)
{
return s1 == s2;
}
struct ilesscompare
{
inline bool operator() (const std::string& s1, const std::string& s2) const
{
return s1 < s2;
}
};
#endif
inline bool is_valid_sf_symbol(const std::string& symbol)
{
// Special function: $f12 or $F34
return (4 == symbol.size()) &&
('$' == symbol[0]) &&
imatch('f',symbol[1]) &&
is_digit(symbol[2]) &&
is_digit(symbol[3]);
}
inline const char_t& front(const std::string& s)
{
return s[0];
}
inline const char_t& back(const std::string& s)
{
return s[s.size() - 1];
}
inline std::string to_str(int i)
{
if (0 == i)
return std::string("0");
std::string result;
const int sign = (i < 0) ? -1 : 1;
for ( ; i; i /= 10)
{
result += '0' + static_cast<char_t>(sign * (i % 10));
}
if (sign < 0)
{
result += '-';
}
std::reverse(result.begin(), result.end());
return result;
}
inline std::string to_str(std::size_t i)
{
return to_str(static_cast<int>(i));
}
inline bool is_hex_digit(const uchar_t digit)
{
return (('0' <= digit) && (digit <= '9')) ||
(('A' <= digit) && (digit <= 'F')) ||
(('a' <= digit) && (digit <= 'f')) ;
}
inline uchar_t hex_to_bin(uchar_t h)
{
if (('0' <= h) && (h <= '9'))
return (h - '0');
else
return static_cast<uchar_t>(std::toupper(h) - 'A');
}
template <typename Iterator>
inline bool parse_hex(Iterator& itr, Iterator end,
char_t& result)
{
if (
(end == (itr )) ||
(end == (itr + 1)) ||
(end == (itr + 2)) ||
(end == (itr + 3)) ||
('0' != *(itr )) ||
('X' != std::toupper(*(itr + 1))) ||
(!is_hex_digit(*(itr + 2))) ||
(!is_hex_digit(*(itr + 3)))
)
{
return false;
}
result = hex_to_bin(static_cast<uchar_t>(*(itr + 2))) << 4 |
hex_to_bin(static_cast<uchar_t>(*(itr + 3))) ;
return true;
}
inline bool cleanup_escapes(std::string& s)
{
typedef std::string::iterator str_itr_t;
str_itr_t itr1 = s.begin();
str_itr_t itr2 = s.begin();
str_itr_t end = s.end ();
std::size_t removal_count = 0;
while (end != itr1)
{
if ('\\' == (*itr1))
{
if (end == ++itr1)
{
return false;
}
else if (parse_hex(itr1, end, *itr2))
{
itr1+= 4;
itr2+= 1;
removal_count +=4;
}
else if ('a' == (*itr1)) { (*itr2++) = '\a'; ++itr1; ++removal_count; }
else if ('b' == (*itr1)) { (*itr2++) = '\b'; ++itr1; ++removal_count; }
else if ('f' == (*itr1)) { (*itr2++) = '\f'; ++itr1; ++removal_count; }
else if ('n' == (*itr1)) { (*itr2++) = '\n'; ++itr1; ++removal_count; }
else if ('r' == (*itr1)) { (*itr2++) = '\r'; ++itr1; ++removal_count; }
else if ('t' == (*itr1)) { (*itr2++) = '\t'; ++itr1; ++removal_count; }
else if ('v' == (*itr1)) { (*itr2++) = '\v'; ++itr1; ++removal_count; }
else if ('0' == (*itr1)) { (*itr2++) = '\0'; ++itr1; ++removal_count; }
else
{
(*itr2++) = (*itr1++);
++removal_count;
}
continue;
}
else
(*itr2++) = (*itr1++);
}
if ((removal_count > s.size()) || (0 == removal_count))
return false;
s.resize(s.size() - removal_count);
return true;
}
class build_string
{
public:
explicit build_string(const std::size_t& initial_size = 64)
{
data_.reserve(initial_size);
}
inline build_string& operator << (const std::string& s)
{
data_ += s;
return (*this);
}
inline build_string& operator << (char_cptr s)
{
data_ += std::string(s);
return (*this);
}
inline operator std::string () const
{
return data_;
}
inline std::string as_string() const
{
return data_;
}
private:
std::string data_;
};
static const std::string reserved_words[] =
{
"break", "case", "continue", "default", "false", "for",
"if", "else", "ilike", "in", "like", "and", "nand", "nor",
"not", "null", "or", "repeat", "return", "shl", "shr",
"swap", "switch", "true", "until", "var", "while", "xnor",
"xor", "&", "|"
};
static const std::size_t reserved_words_size = sizeof(reserved_words) / sizeof(std::string);
static const std::string reserved_symbols[] =
{
"abs", "acos", "acosh", "and", "asin", "asinh", "atan",
"atanh", "atan2", "avg", "break", "case", "ceil", "clamp",
"continue", "cos", "cosh", "cot", "csc", "default",
"deg2grad", "deg2rad", "equal", "erf", "erfc", "exp",
"expm1", "false", "floor", "for", "frac", "grad2deg",
"hypot", "iclamp", "if", "else", "ilike", "in", "inrange",
"like", "log", "log10", "log2", "logn", "log1p", "mand",
"max", "min", "mod", "mor", "mul", "ncdf", "nand", "nor",
"not", "not_equal", "null", "or", "pow", "rad2deg",
"repeat", "return", "root", "round", "roundn", "sec", "sgn",
"shl", "shr", "sin", "sinc", "sinh", "sqrt", "sum", "swap",
"switch", "tan", "tanh", "true", "trunc", "until", "var",
"while", "xnor", "xor", "&", "|"
};
static const std::size_t reserved_symbols_size = sizeof(reserved_symbols) / sizeof(std::string);
static const std::string base_function_list[] =
{
"abs", "acos", "acosh", "asin", "asinh", "atan", "atanh",
"atan2", "avg", "ceil", "clamp", "cos", "cosh", "cot",
"csc", "equal", "erf", "erfc", "exp", "expm1", "floor",
"frac", "hypot", "iclamp", "like", "log", "log10", "log2",
"logn", "log1p", "mand", "max", "min", "mod", "mor", "mul",
"ncdf", "pow", "root", "round", "roundn", "sec", "sgn",
"sin", "sinc", "sinh", "sqrt", "sum", "swap", "tan", "tanh",
"trunc", "not_equal", "inrange", "deg2grad", "deg2rad",
"rad2deg", "grad2deg"
};
static const std::size_t base_function_list_size = sizeof(base_function_list) / sizeof(std::string);
static const std::string logic_ops_list[] =
{
"and", "nand", "nor", "not", "or", "xnor", "xor", "&", "|"
};
static const std::size_t logic_ops_list_size = sizeof(logic_ops_list) / sizeof(std::string);
static const std::string cntrl_struct_list[] =
{
"if", "switch", "for", "while", "repeat", "return"
};
static const std::size_t cntrl_struct_list_size = sizeof(cntrl_struct_list) / sizeof(std::string);
static const std::string arithmetic_ops_list[] =
{
"+", "-", "*", "/", "%", "^"
};
static const std::size_t arithmetic_ops_list_size = sizeof(arithmetic_ops_list) / sizeof(std::string);
static const std::string assignment_ops_list[] =
{
":=", "+=", "-=",
"*=", "/=", "%="
};
static const std::size_t assignment_ops_list_size = sizeof(assignment_ops_list) / sizeof(std::string);
static const std::string inequality_ops_list[] =
{
"<", "<=", "==",
"=", "!=", "<>",
">=", ">"
};
static const std::size_t inequality_ops_list_size = sizeof(inequality_ops_list) / sizeof(std::string);
inline bool is_reserved_word(const std::string& symbol)
{
for (std::size_t i = 0; i < reserved_words_size; ++i)
{
if (imatch(symbol, reserved_words[i]))
{
return true;
}
}
return false;
}
inline bool is_reserved_symbol(const std::string& symbol)
{
for (std::size_t i = 0; i < reserved_symbols_size; ++i)
{
if (imatch(symbol, reserved_symbols[i]))
{
return true;
}
}
return false;
}
inline bool is_base_function(const std::string& function_name)
{
for (std::size_t i = 0; i < base_function_list_size; ++i)
{
if (imatch(function_name, base_function_list[i]))
{
return true;
}
}
return false;
}
inline bool is_control_struct(const std::string& cntrl_strct)
{
for (std::size_t i = 0; i < cntrl_struct_list_size; ++i)
{
if (imatch(cntrl_strct, cntrl_struct_list[i]))
{
return true;
}
}
return false;
}
inline bool is_logic_opr(const std::string& lgc_opr)
{
for (std::size_t i = 0; i < logic_ops_list_size; ++i)
{
if (imatch(lgc_opr, logic_ops_list[i]))
{
return true;
}
}
return false;
}
struct cs_match
{
static inline bool cmp(const char_t c0, const char_t c1)
{
return (c0 == c1);
}
};
struct cis_match
{
static inline bool cmp(const char_t c0, const char_t c1)
{
return (std::tolower(c0) == std::tolower(c1));
}
};
template <typename Iterator, typename Compare>
inline bool match_impl(const Iterator pattern_begin,
const Iterator pattern_end ,
const Iterator data_begin ,
const Iterator data_end ,
const typename std::iterator_traits<Iterator>::value_type& zero_or_more,
const typename std::iterator_traits<Iterator>::value_type& exactly_one )
{
typedef typename std::iterator_traits<Iterator>::value_type type;
const Iterator null_itr(0);
Iterator p_itr = pattern_begin;
Iterator d_itr = data_begin;
Iterator np_itr = null_itr;
Iterator nd_itr = null_itr;
for ( ; ; )
{
if (p_itr != pattern_end)
{
const type c = *(p_itr);
if ((data_end != d_itr) && (Compare::cmp(c,*(d_itr)) || (exactly_one == c)))
{
++d_itr;
++p_itr;
continue;
}
else if (zero_or_more == c)
{
while ((pattern_end != p_itr) && (zero_or_more == *(p_itr)))
{
++p_itr;
}
const type d = *(p_itr);
while ((data_end != d_itr) && !(Compare::cmp(d,*(d_itr)) || (exactly_one == d)))
{
++d_itr;
}
// set backtrack iterators
np_itr = p_itr - 1;
nd_itr = d_itr + 1;
continue;
}
}
else if (data_end == d_itr)
return true;
if ((data_end == d_itr) || (null_itr == nd_itr))
return false;
p_itr = np_itr;
d_itr = nd_itr;
}
return true;
}
inline bool wc_match(const std::string& wild_card,
const std::string& str)
{
return match_impl<char_cptr,cs_match>(
wild_card.data(),
wild_card.data() + wild_card.size(),
str.data(),
str.data() + str.size(),
'*', '?');
}
inline bool wc_imatch(const std::string& wild_card,
const std::string& str)
{
return match_impl<char_cptr,cis_match>(
wild_card.data(),
wild_card.data() + wild_card.size(),
str.data(),
str.data() + str.size(),
'*', '?');
}
inline bool sequence_match(const std::string& pattern,
const std::string& str,
std::size_t& diff_index,
char_t& diff_value)
{
if (str.empty())
{
return ("Z" == pattern);
}
else if ('*' == pattern[0])
return false;
typedef std::string::const_iterator itr_t;
itr_t p_itr = pattern.begin();
itr_t s_itr = str .begin();
const itr_t p_end = pattern.end();
const itr_t s_end = str .end();
while ((s_end != s_itr) && (p_end != p_itr))
{
if ('*' == (*p_itr))
{
const char_t target = static_cast<char_t>(std::toupper(*(p_itr - 1)));
if ('*' == target)
{
diff_index = static_cast<std::size_t>(std::distance(str.begin(),s_itr));
diff_value = static_cast<char_t>(std::toupper(*p_itr));
return false;
}
else
++p_itr;
while (s_itr != s_end)
{
if (target != std::toupper(*s_itr))
break;
else
++s_itr;
}
continue;
}
else if (
('?' != *p_itr) &&
std::toupper(*p_itr) != std::toupper(*s_itr)
)
{
diff_index = static_cast<std::size_t>(std::distance(str.begin(),s_itr));
diff_value = static_cast<char_t>(std::toupper(*p_itr));
return false;
}
++p_itr;
++s_itr;
}
return (
(s_end == s_itr) &&
(
(p_end == p_itr) ||
('*' == *p_itr)
)
);
}
static const double pow10[] = {
1.0,
1.0E+001, 1.0E+002, 1.0E+003, 1.0E+004,
1.0E+005, 1.0E+006, 1.0E+007, 1.0E+008,
1.0E+009, 1.0E+010, 1.0E+011, 1.0E+012,
1.0E+013, 1.0E+014, 1.0E+015, 1.0E+016
};
static const std::size_t pow10_size = sizeof(pow10) / sizeof(double);
namespace numeric
{
namespace constant
{
static const double e = 2.71828182845904523536028747135266249775724709369996;
static const double pi = 3.14159265358979323846264338327950288419716939937510;
static const double pi_2 = 1.57079632679489661923132169163975144209858469968755;
static const double pi_4 = 0.78539816339744830961566084581987572104929234984378;
static const double pi_180 = 0.01745329251994329576923690768488612713442871888542;
static const double _1_pi = 0.31830988618379067153776752674502872406891929148091;
static const double _2_pi = 0.63661977236758134307553505349005744813783858296183;
static const double _180_pi = 57.29577951308232087679815481410517033240547246656443;
static const double log2 = 0.69314718055994530941723212145817656807550013436026;
static const double sqrt2 = 1.41421356237309504880168872420969807856967187537695;
}
namespace details
{
struct unknown_type_tag { unknown_type_tag() {} };
struct real_type_tag { real_type_tag () {} };
struct int_type_tag { int_type_tag () {} };
template <typename T>
struct number_type
{
typedef unknown_type_tag type;
number_type() {}
};
#define exprtk_register_real_type_tag(T) \
template <> struct number_type<T> \
{ typedef real_type_tag type; number_type() {} }; \
#define exprtk_register_int_type_tag(T) \
template <> struct number_type<T> \
{ typedef int_type_tag type; number_type() {} }; \
exprtk_register_real_type_tag(double )
exprtk_register_real_type_tag(long double)
exprtk_register_real_type_tag(float )
exprtk_register_int_type_tag(short )
exprtk_register_int_type_tag(int )
exprtk_register_int_type_tag(_int64_t )
exprtk_register_int_type_tag(unsigned short)
exprtk_register_int_type_tag(unsigned int )
exprtk_register_int_type_tag(_uint64_t )
#undef exprtk_register_real_type_tag
#undef exprtk_register_int_type_tag
template <typename T>
struct epsilon_type {};
#define exprtk_define_epsilon_type(Type, Epsilon) \
template <> struct epsilon_type<Type> \
{ \
static inline Type value() \
{ \
const Type epsilon = static_cast<Type>(Epsilon); \
return epsilon; \
} \
}; \
exprtk_define_epsilon_type(float , 0.00000100000f)
exprtk_define_epsilon_type(double , 0.000000000100)
exprtk_define_epsilon_type(long double, 0.000000000001)
#undef exprtk_define_epsilon_type
template <typename T>
inline bool is_nan_impl(const T v, real_type_tag)
{
return std::not_equal_to<T>()(v,v);
}
template <typename T>
inline int to_int32_impl(const T v, real_type_tag)
{
return static_cast<int>(v);
}
template <typename T>
inline _int64_t to_int64_impl(const T v, real_type_tag)
{
return static_cast<_int64_t>(v);
}
template <typename T>
inline bool is_true_impl(const T v)
{
return std::not_equal_to<T>()(T(0),v);
}
template <typename T>
inline bool is_false_impl(const T v)
{
return std::equal_to<T>()(T(0),v);
}
template <typename T>
inline T abs_impl(const T v, real_type_tag)
{
return ((v < T(0)) ? -v : v);
}
template <typename T>
inline T min_impl(const T v0, const T v1, real_type_tag)
{
return std::min<T>(v0,v1);
}
template <typename T>
inline T max_impl(const T v0, const T v1, real_type_tag)
{
return std::max<T>(v0,v1);
}
template <typename T>
inline T equal_impl(const T v0, const T v1, real_type_tag)
{
const T epsilon = epsilon_type<T>::value();
return (abs_impl(v0 - v1,real_type_tag()) <= (std::max(T(1),std::max(abs_impl(v0,real_type_tag()),abs_impl(v1,real_type_tag()))) * epsilon)) ? T(1) : T(0);
}
inline float equal_impl(const float v0, const float v1, real_type_tag)
{
const float epsilon = epsilon_type<float>::value();
return (abs_impl(v0 - v1,real_type_tag()) <= (std::max(1.0f,std::max(abs_impl(v0,real_type_tag()),abs_impl(v1,real_type_tag()))) * epsilon)) ? 1.0f : 0.0f;
}
template <typename T>
inline T equal_impl(const T v0, const T v1, int_type_tag)
{
return (v0 == v1) ? 1 : 0;
}
template <typename T>
inline T expm1_impl(const T v, real_type_tag)
{
// return std::expm1<T>(v);
if (abs_impl(v,real_type_tag()) < T(0.00001))
return v + (T(0.5) * v * v);
else
return std::exp(v) - T(1);
}
template <typename T>
inline T expm1_impl(const T v, int_type_tag)
{
return T(std::exp<double>(v)) - T(1);
}
template <typename T>
inline T nequal_impl(const T v0, const T v1, real_type_tag)
{
typedef real_type_tag rtg;
const T epsilon = epsilon_type<T>::value();
return (abs_impl(v0 - v1,rtg()) > (std::max(T(1),std::max(abs_impl(v0,rtg()),abs_impl(v1,rtg()))) * epsilon)) ? T(1) : T(0);
}
inline float nequal_impl(const float v0, const float v1, real_type_tag)
{
typedef real_type_tag rtg;
const float epsilon = epsilon_type<float>::value();
return (abs_impl(v0 - v1,rtg()) > (std::max(1.0f,std::max(abs_impl(v0,rtg()),abs_impl(v1,rtg()))) * epsilon)) ? 1.0f : 0.0f;
}
template <typename T>
inline T nequal_impl(const T v0, const T v1, int_type_tag)
{
return (v0 != v1) ? 1 : 0;
}
template <typename T>
inline T modulus_impl(const T v0, const T v1, real_type_tag)
{
return std::fmod(v0,v1);
}
template <typename T>
inline T modulus_impl(const T v0, const T v1, int_type_tag)
{
return v0 % v1;
}
template <typename T>
inline T pow_impl(const T v0, const T v1, real_type_tag)
{
return std::pow(v0,v1);
}
template <typename T>
inline T pow_impl(const T v0, const T v1, int_type_tag)
{
return std::pow(static_cast<double>(v0),static_cast<double>(v1));
}
template <typename T>
inline T logn_impl(const T v0, const T v1, real_type_tag)
{
return std::log(v0) / std::log(v1);
}
template <typename T>
inline T logn_impl(const T v0, const T v1, int_type_tag)
{
return static_cast<T>(logn_impl<double>(static_cast<double>(v0),static_cast<double>(v1),real_type_tag()));
}
template <typename T>
inline T log1p_impl(const T v, real_type_tag)
{
if (v > T(-1))
{
if (abs_impl(v,real_type_tag()) > T(0.0001))
{
return std::log(T(1) + v);
}
else
return (T(-0.5) * v + T(1)) * v;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
template <typename T>
inline T log1p_impl(const T v, int_type_tag)
{
if (v > T(-1))
{
return std::log(T(1) + v);
}
else
return std::numeric_limits<T>::quiet_NaN();
}
template <typename T>
inline T root_impl(const T v0, const T v1, real_type_tag)
{
if (v1 < T(0))
return std::numeric_limits<T>::quiet_NaN();
const std::size_t n = static_cast<std::size_t>(v1);
if ((v0 < T(0)) && (0 == (n % 2)))
return std::numeric_limits<T>::quiet_NaN();
return std::pow(v0, T(1) / n);
}
template <typename T>
inline T root_impl(const T v0, const T v1, int_type_tag)
{
return root_impl<double>(static_cast<double>(v0),static_cast<double>(v1),real_type_tag());
}
template <typename T>
inline T round_impl(const T v, real_type_tag)
{
return ((v < T(0)) ? std::ceil(v - T(0.5)) : std::floor(v + T(0.5)));
}
template <typename T>
inline T roundn_impl(const T v0, const T v1, real_type_tag)
{
const int index = std::max<int>(0, std::min<int>(pow10_size - 1, static_cast<int>(std::floor(v1))));
const T p10 = T(pow10[index]);
if (v0 < T(0))
return T(std::ceil ((v0 * p10) - T(0.5)) / p10);
else
return T(std::floor((v0 * p10) + T(0.5)) / p10);
}
template <typename T>
inline T roundn_impl(const T v0, const T, int_type_tag)
{
return v0;
}
template <typename T>
inline T hypot_impl(const T v0, const T v1, real_type_tag)
{
return std::sqrt((v0 * v0) + (v1 * v1));
}
template <typename T>
inline T hypot_impl(const T v0, const T v1, int_type_tag)
{
return static_cast<T>(std::sqrt(static_cast<double>((v0 * v0) + (v1 * v1))));
}
template <typename T>
inline T atan2_impl(const T v0, const T v1, real_type_tag)
{
return std::atan2(v0,v1);
}
template <typename T>
inline T atan2_impl(const T, const T, int_type_tag)
{
return 0;
}
template <typename T>
inline T shr_impl(const T v0, const T v1, real_type_tag)
{
return v0 * (T(1) / std::pow(T(2),static_cast<T>(static_cast<int>(v1))));
}
template <typename T>
inline T shr_impl(const T v0, const T v1, int_type_tag)
{
return v0 >> v1;
}
template <typename T>
inline T shl_impl(const T v0, const T v1, real_type_tag)
{
return v0 * std::pow(T(2),static_cast<T>(static_cast<int>(v1)));
}
template <typename T>
inline T shl_impl(const T v0, const T v1, int_type_tag)
{
return v0 << v1;
}
template <typename T>
inline T sgn_impl(const T v, real_type_tag)
{
if (v > T(0)) return T(+1);
else if (v < T(0)) return T(-1);
else return T( 0);
}
template <typename T>
inline T sgn_impl(const T v, int_type_tag)
{
if (v > T(0)) return T(+1);
else if (v < T(0)) return T(-1);
else return T( 0);
}
template <typename T>
inline T and_impl(const T v0, const T v1, real_type_tag)
{
return (is_true_impl(v0) && is_true_impl(v1)) ? T(1) : T(0);
}
template <typename T>
inline T and_impl(const T v0, const T v1, int_type_tag)
{
return v0 && v1;
}
template <typename T>
inline T nand_impl(const T v0, const T v1, real_type_tag)
{
return (is_false_impl(v0) || is_false_impl(v1)) ? T(1) : T(0);
}
template <typename T>
inline T nand_impl(const T v0, const T v1, int_type_tag)
{
return !(v0 && v1);
}
template <typename T>
inline T or_impl(const T v0, const T v1, real_type_tag)
{
return (is_true_impl(v0) || is_true_impl(v1)) ? T(1) : T(0);
}
template <typename T>
inline T or_impl(const T v0, const T v1, int_type_tag)
{
return (v0 || v1);
}
template <typename T>
inline T nor_impl(const T v0, const T v1, real_type_tag)
{
return (is_false_impl(v0) && is_false_impl(v1)) ? T(1) : T(0);
}
template <typename T>
inline T nor_impl(const T v0, const T v1, int_type_tag)
{
return !(v0 || v1);
}
template <typename T>
inline T xor_impl(const T v0, const T v1, real_type_tag)
{
return (is_false_impl(v0) != is_false_impl(v1)) ? T(1) : T(0);
}
template <typename T>
inline T xor_impl(const T v0, const T v1, int_type_tag)
{
return v0 ^ v1;
}
template <typename T>
inline T xnor_impl(const T v0, const T v1, real_type_tag)
{
const bool v0_true = is_true_impl(v0);
const bool v1_true = is_true_impl(v1);
if ((v0_true && v1_true) || (!v0_true && !v1_true))
return T(1);
else
return T(0);
}
template <typename T>
inline T xnor_impl(const T v0, const T v1, int_type_tag)
{
const bool v0_true = is_true_impl(v0);
const bool v1_true = is_true_impl(v1);
if ((v0_true && v1_true) || (!v0_true && !v1_true))
return T(1);
else
return T(0);
}
#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || !defined(_MSC_VER)
#define exprtk_define_erf(TT, impl) \
inline TT erf_impl(const TT v) { return impl(v); } \
exprtk_define_erf( float,::erff)
exprtk_define_erf( double,::erf )
exprtk_define_erf(long double,::erfl)
#undef exprtk_define_erf
#endif
template <typename T>
inline T erf_impl(const T v, real_type_tag)
{
#if defined(_MSC_VER) && (_MSC_VER < 1900)
// Credits: Abramowitz & Stegun Equations 7.1.25-28
static const T c[] = {
T( 1.26551223), T(1.00002368),
T( 0.37409196), T(0.09678418),
T(-0.18628806), T(0.27886807),
T(-1.13520398), T(1.48851587),
T(-0.82215223), T(0.17087277)
};
const T t = T(1) / (T(1) + T(0.5) * abs_impl(v,real_type_tag()));
const T result = T(1) - t * std::exp((-v * v) -
c[0] + t * (c[1] + t *
(c[2] + t * (c[3] + t *
(c[4] + t * (c[5] + t *
(c[6] + t * (c[7] + t *
(c[8] + t * (c[9]))))))))));
return (v >= T(0)) ? result : -result;
#else
return erf_impl(v);
#endif
}
template <typename T>
inline T erf_impl(const T v, int_type_tag)
{
return erf_impl(static_cast<double>(v),real_type_tag());
}
#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || !defined(_MSC_VER)
#define exprtk_define_erfc(TT, impl) \
inline TT erfc_impl(const TT v) { return impl(v); } \
exprtk_define_erfc(float ,::erfcf)
exprtk_define_erfc(double ,::erfc )
exprtk_define_erfc(long double,::erfcl)
#undef exprtk_define_erfc
#endif
template <typename T>
inline T erfc_impl(const T v, real_type_tag)
{
#if defined(_MSC_VER) && (_MSC_VER < 1900)
return T(1) - erf_impl(v,real_type_tag());
#else
return erfc_impl(v);
#endif
}
template <typename T>
inline T erfc_impl(const T v, int_type_tag)
{
return erfc_impl(static_cast<double>(v),real_type_tag());
}
template <typename T>
inline T ncdf_impl(const T v, real_type_tag)
{
const T cnd = T(0.5) * (T(1) +
erf_impl(abs_impl(v,real_type_tag()) /
T(numeric::constant::sqrt2),real_type_tag()));
return (v < T(0)) ? (T(1) - cnd) : cnd;
}
template <typename T>
inline T ncdf_impl(const T v, int_type_tag)
{
return ncdf_impl(static_cast<double>(v),real_type_tag());
}
template <typename T>
inline T sinc_impl(const T v, real_type_tag)
{
if (std::abs(v) >= std::numeric_limits<T>::epsilon())
return(std::sin(v) / v);
else
return T(1);
}
template <typename T>
inline T sinc_impl(const T v, int_type_tag)
{
return sinc_impl(static_cast<double>(v),real_type_tag());
}
template <typename T> inline T acos_impl(const T v, real_type_tag) { return std::acos (v); }
template <typename T> inline T acosh_impl(const T v, real_type_tag) { return std::log(v + std::sqrt((v * v) - T(1))); }
template <typename T> inline T asin_impl(const T v, real_type_tag) { return std::asin (v); }
template <typename T> inline T asinh_impl(const T v, real_type_tag) { return std::log(v + std::sqrt((v * v) + T(1))); }
template <typename T> inline T atan_impl(const T v, real_type_tag) { return std::atan (v); }
template <typename T> inline T atanh_impl(const T v, real_type_tag) { return (std::log(T(1) + v) - std::log(T(1) - v)) / T(2); }
template <typename T> inline T ceil_impl(const T v, real_type_tag) { return std::ceil (v); }
template <typename T> inline T cos_impl(const T v, real_type_tag) { return std::cos (v); }
template <typename T> inline T cosh_impl(const T v, real_type_tag) { return std::cosh (v); }
template <typename T> inline T exp_impl(const T v, real_type_tag) { return std::exp (v); }
template <typename T> inline T floor_impl(const T v, real_type_tag) { return std::floor(v); }
template <typename T> inline T log_impl(const T v, real_type_tag) { return std::log (v); }
template <typename T> inline T log10_impl(const T v, real_type_tag) { return std::log10(v); }
template <typename T> inline T log2_impl(const T v, real_type_tag) { return std::log(v)/T(numeric::constant::log2); }
template <typename T> inline T neg_impl(const T v, real_type_tag) { return -v; }
template <typename T> inline T pos_impl(const T v, real_type_tag) { return +v; }
template <typename T> inline T sin_impl(const T v, real_type_tag) { return std::sin (v); }
template <typename T> inline T sinh_impl(const T v, real_type_tag) { return std::sinh (v); }
template <typename T> inline T sqrt_impl(const T v, real_type_tag) { return std::sqrt (v); }
template <typename T> inline T tan_impl(const T v, real_type_tag) { return std::tan (v); }
template <typename T> inline T tanh_impl(const T v, real_type_tag) { return std::tanh (v); }
template <typename T> inline T cot_impl(const T v, real_type_tag) { return T(1) / std::tan(v); }
template <typename T> inline T sec_impl(const T v, real_type_tag) { return T(1) / std::cos(v); }
template <typename T> inline T csc_impl(const T v, real_type_tag) { return T(1) / std::sin(v); }
template <typename T> inline T r2d_impl(const T v, real_type_tag) { return (v * T(numeric::constant::_180_pi)); }
template <typename T> inline T d2r_impl(const T v, real_type_tag) { return (v * T(numeric::constant::pi_180)); }
template <typename T> inline T d2g_impl(const T v, real_type_tag) { return (v * T(10.0/9.0)); }
template <typename T> inline T g2d_impl(const T v, real_type_tag) { return (v * T(9.0/10.0)); }
template <typename T> inline T notl_impl(const T v, real_type_tag) { return (std::not_equal_to<T>()(T(0),v) ? T(0) : T(1)); }
template <typename T> inline T frac_impl(const T v, real_type_tag) { return (v - static_cast<long long>(v)); }
template <typename T> inline T trunc_impl(const T v, real_type_tag) { return T(static_cast<long long>(v)); }
template <typename T> inline T const_pi_impl(real_type_tag) { return T(numeric::constant::pi); }
template <typename T> inline T const_e_impl(real_type_tag) { return T(numeric::constant::e); }
template <typename T> inline T const_qnan_impl(real_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T abs_impl(const T v, int_type_tag) { return ((v >= T(0)) ? v : -v); }
template <typename T> inline T exp_impl(const T v, int_type_tag) { return std::exp (v); }
template <typename T> inline T log_impl(const T v, int_type_tag) { return std::log (v); }
template <typename T> inline T log10_impl(const T v, int_type_tag) { return std::log10(v); }
template <typename T> inline T log2_impl(const T v, int_type_tag) { return std::log(v)/T(numeric::constant::log2); }
template <typename T> inline T neg_impl(const T v, int_type_tag) { return -v; }
template <typename T> inline T pos_impl(const T v, int_type_tag) { return +v; }
template <typename T> inline T ceil_impl(const T v, int_type_tag) { return v; }
template <typename T> inline T floor_impl(const T v, int_type_tag) { return v; }
template <typename T> inline T round_impl(const T v, int_type_tag) { return v; }
template <typename T> inline T notl_impl(const T v, int_type_tag) { return !v; }
template <typename T> inline T sqrt_impl(const T v, int_type_tag) { return std::sqrt (v); }
template <typename T> inline T frac_impl(const T , int_type_tag) { return T(0); }
template <typename T> inline T trunc_impl(const T v, int_type_tag) { return v; }
template <typename T> inline T acos_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T acosh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T asin_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T asinh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T atan_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T atanh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T cos_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T cosh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T sin_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T sinh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T tan_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T tanh_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T cot_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T sec_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T> inline T csc_impl(const T , int_type_tag) { return std::numeric_limits<T>::quiet_NaN(); }
template <typename T>
inline bool is_integer_impl(const T& v, real_type_tag)
{
return std::equal_to<T>()(T(0),std::fmod(v,T(1)));
}
template <typename T>
inline bool is_integer_impl(const T&, int_type_tag)
{
return true;
}
}
template <typename Type>
struct numeric_info { enum { length = 0, size = 32, bound_length = 0, min_exp = 0, max_exp = 0 }; };
template <> struct numeric_info<int > { enum { length = 10, size = 16, bound_length = 9 }; };
template <> struct numeric_info<float > { enum { min_exp = -38, max_exp = +38 }; };
template <> struct numeric_info<double > { enum { min_exp = -308, max_exp = +308 }; };
template <> struct numeric_info<long double> { enum { min_exp = -308, max_exp = +308 }; };
template <typename T>
inline int to_int32(const T v)
{
const typename details::number_type<T>::type num_type;
return to_int32_impl(v, num_type);
}
template <typename T>
inline _int64_t to_int64(const T v)
{
const typename details::number_type<T>::type num_type;
return to_int64_impl(v, num_type);
}
template <typename T>
inline bool is_nan(const T v)
{
const typename details::number_type<T>::type num_type;
return is_nan_impl(v, num_type);
}
template <typename T>
inline T min(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return min_impl(v0, v1, num_type);
}
template <typename T>
inline T max(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return max_impl(v0, v1, num_type);
}
template <typename T>
inline T equal(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return equal_impl(v0, v1, num_type);
}
template <typename T>
inline T nequal(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return nequal_impl(v0, v1, num_type);
}
template <typename T>
inline T modulus(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return modulus_impl(v0, v1, num_type);
}
template <typename T>
inline T pow(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return pow_impl(v0, v1, num_type);
}
template <typename T>
inline T logn(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return logn_impl(v0, v1, num_type);
}
template <typename T>
inline T root(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return root_impl(v0, v1, num_type);
}
template <typename T>
inline T roundn(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return roundn_impl(v0, v1, num_type);
}
template <typename T>
inline T hypot(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return hypot_impl(v0, v1, num_type);
}
template <typename T>
inline T atan2(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return atan2_impl(v0, v1, num_type);
}
template <typename T>
inline T shr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return shr_impl(v0, v1, num_type);
}
template <typename T>
inline T shl(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return shl_impl(v0, v1, num_type);
}
template <typename T>
inline T and_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return and_impl(v0, v1, num_type);
}
template <typename T>
inline T nand_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return nand_impl(v0, v1, num_type);
}
template <typename T>
inline T or_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return or_impl(v0, v1, num_type);
}
template <typename T>
inline T nor_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return nor_impl(v0, v1, num_type);
}
template <typename T>
inline T xor_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return xor_impl(v0, v1, num_type);
}
template <typename T>
inline T xnor_opr(const T v0, const T v1)
{
const typename details::number_type<T>::type num_type;
return xnor_impl(v0, v1, num_type);
}
template <typename T>
inline bool is_integer(const T v)
{
const typename details::number_type<T>::type num_type;
return is_integer_impl(v, num_type);
}
template <typename T, unsigned int N>
struct fast_exp
{
static inline T result(T v)
{
unsigned int k = N;
T l = T(1);
while (k)
{
if (1 == (k % 2))
{
l *= v;
--k;
}
v *= v;
k /= 2;
}
return l;
}
};
template <typename T> struct fast_exp<T,10> { static inline T result(const T v) { T v_5 = fast_exp<T,5>::result(v); return v_5 * v_5; } };
template <typename T> struct fast_exp<T, 9> { static inline T result(const T v) { return fast_exp<T,8>::result(v) * v; } };
template <typename T> struct fast_exp<T, 8> { static inline T result(const T v) { T v_4 = fast_exp<T,4>::result(v); return v_4 * v_4; } };
template <typename T> struct fast_exp<T, 7> { static inline T result(const T v) { return fast_exp<T,6>::result(v) * v; } };
template <typename T> struct fast_exp<T, 6> { static inline T result(const T v) { T v_3 = fast_exp<T,3>::result(v); return v_3 * v_3; } };
template <typename T> struct fast_exp<T, 5> { static inline T result(const T v) { return fast_exp<T,4>::result(v) * v; } };
template <typename T> struct fast_exp<T, 4> { static inline T result(const T v) { T v_2 = v * v; return v_2 * v_2; } };
template <typename T> struct fast_exp<T, 3> { static inline T result(const T v) { return v * v * v; } };
template <typename T> struct fast_exp<T, 2> { static inline T result(const T v) { return v * v; } };
template <typename T> struct fast_exp<T, 1> { static inline T result(const T v) { return v; } };
template <typename T> struct fast_exp<T, 0> { static inline T result(const T ) { return T(1); } };
#define exprtk_define_unary_function(FunctionName) \
template <typename T> \
inline T FunctionName (const T v) \
{ \
const typename details::number_type<T>::type num_type; \
return FunctionName##_impl(v,num_type); \
} \
exprtk_define_unary_function(abs )
exprtk_define_unary_function(acos )
exprtk_define_unary_function(acosh)
exprtk_define_unary_function(asin )
exprtk_define_unary_function(asinh)
exprtk_define_unary_function(atan )
exprtk_define_unary_function(atanh)
exprtk_define_unary_function(ceil )
exprtk_define_unary_function(cos )
exprtk_define_unary_function(cosh )
exprtk_define_unary_function(exp )
exprtk_define_unary_function(expm1)
exprtk_define_unary_function(floor)
exprtk_define_unary_function(log )
exprtk_define_unary_function(log10)
exprtk_define_unary_function(log2 )
exprtk_define_unary_function(log1p)
exprtk_define_unary_function(neg )
exprtk_define_unary_function(pos )
exprtk_define_unary_function(round)
exprtk_define_unary_function(sin )
exprtk_define_unary_function(sinc )
exprtk_define_unary_function(sinh )
exprtk_define_unary_function(sqrt )
exprtk_define_unary_function(tan )
exprtk_define_unary_function(tanh )
exprtk_define_unary_function(cot )
exprtk_define_unary_function(sec )
exprtk_define_unary_function(csc )
exprtk_define_unary_function(r2d )
exprtk_define_unary_function(d2r )
exprtk_define_unary_function(d2g )
exprtk_define_unary_function(g2d )
exprtk_define_unary_function(notl )
exprtk_define_unary_function(sgn )
exprtk_define_unary_function(erf )
exprtk_define_unary_function(erfc )
exprtk_define_unary_function(ncdf )
exprtk_define_unary_function(frac )
exprtk_define_unary_function(trunc)
#undef exprtk_define_unary_function
}
template <typename T>
inline T compute_pow10(T d, const int exponent)
{
static const double fract10[] =
{
0.0,
1.0E+001, 1.0E+002, 1.0E+003, 1.0E+004, 1.0E+005, 1.0E+006, 1.0E+007, 1.0E+008, 1.0E+009, 1.0E+010,
1.0E+011, 1.0E+012, 1.0E+013, 1.0E+014, 1.0E+015, 1.0E+016, 1.0E+017, 1.0E+018, 1.0E+019, 1.0E+020,
1.0E+021, 1.0E+022, 1.0E+023, 1.0E+024, 1.0E+025, 1.0E+026, 1.0E+027, 1.0E+028, 1.0E+029, 1.0E+030,
1.0E+031, 1.0E+032, 1.0E+033, 1.0E+034, 1.0E+035, 1.0E+036, 1.0E+037, 1.0E+038, 1.0E+039, 1.0E+040,
1.0E+041, 1.0E+042, 1.0E+043, 1.0E+044, 1.0E+045, 1.0E+046, 1.0E+047, 1.0E+048, 1.0E+049, 1.0E+050,
1.0E+051, 1.0E+052, 1.0E+053, 1.0E+054, 1.0E+055, 1.0E+056, 1.0E+057, 1.0E+058, 1.0E+059, 1.0E+060,
1.0E+061, 1.0E+062, 1.0E+063, 1.0E+064, 1.0E+065, 1.0E+066, 1.0E+067, 1.0E+068, 1.0E+069, 1.0E+070,
1.0E+071, 1.0E+072, 1.0E+073, 1.0E+074, 1.0E+075, 1.0E+076, 1.0E+077, 1.0E+078, 1.0E+079, 1.0E+080,
1.0E+081, 1.0E+082, 1.0E+083, 1.0E+084, 1.0E+085, 1.0E+086, 1.0E+087, 1.0E+088, 1.0E+089, 1.0E+090,
1.0E+091, 1.0E+092, 1.0E+093, 1.0E+094, 1.0E+095, 1.0E+096, 1.0E+097, 1.0E+098, 1.0E+099, 1.0E+100,
1.0E+101, 1.0E+102, 1.0E+103, 1.0E+104, 1.0E+105, 1.0E+106, 1.0E+107, 1.0E+108, 1.0E+109, 1.0E+110,
1.0E+111, 1.0E+112, 1.0E+113, 1.0E+114, 1.0E+115, 1.0E+116, 1.0E+117, 1.0E+118, 1.0E+119, 1.0E+120,
1.0E+121, 1.0E+122, 1.0E+123, 1.0E+124, 1.0E+125, 1.0E+126, 1.0E+127, 1.0E+128, 1.0E+129, 1.0E+130,
1.0E+131, 1.0E+132, 1.0E+133, 1.0E+134, 1.0E+135, 1.0E+136, 1.0E+137, 1.0E+138, 1.0E+139, 1.0E+140,
1.0E+141, 1.0E+142, 1.0E+143, 1.0E+144, 1.0E+145, 1.0E+146, 1.0E+147, 1.0E+148, 1.0E+149, 1.0E+150,
1.0E+151, 1.0E+152, 1.0E+153, 1.0E+154, 1.0E+155, 1.0E+156, 1.0E+157, 1.0E+158, 1.0E+159, 1.0E+160,
1.0E+161, 1.0E+162, 1.0E+163, 1.0E+164, 1.0E+165, 1.0E+166, 1.0E+167, 1.0E+168, 1.0E+169, 1.0E+170,
1.0E+171, 1.0E+172, 1.0E+173, 1.0E+174, 1.0E+175, 1.0E+176, 1.0E+177, 1.0E+178, 1.0E+179, 1.0E+180,
1.0E+181, 1.0E+182, 1.0E+183, 1.0E+184, 1.0E+185, 1.0E+186, 1.0E+187, 1.0E+188, 1.0E+189, 1.0E+190,
1.0E+191, 1.0E+192, 1.0E+193, 1.0E+194, 1.0E+195, 1.0E+196, 1.0E+197, 1.0E+198, 1.0E+199, 1.0E+200,
1.0E+201, 1.0E+202, 1.0E+203, 1.0E+204, 1.0E+205, 1.0E+206, 1.0E+207, 1.0E+208, 1.0E+209, 1.0E+210,
1.0E+211, 1.0E+212, 1.0E+213, 1.0E+214, 1.0E+215, 1.0E+216, 1.0E+217, 1.0E+218, 1.0E+219, 1.0E+220,
1.0E+221, 1.0E+222, 1.0E+223, 1.0E+224, 1.0E+225, 1.0E+226, 1.0E+227, 1.0E+228, 1.0E+229, 1.0E+230,
1.0E+231, 1.0E+232, 1.0E+233, 1.0E+234, 1.0E+235, 1.0E+236, 1.0E+237, 1.0E+238, 1.0E+239, 1.0E+240,
1.0E+241, 1.0E+242, 1.0E+243, 1.0E+244, 1.0E+245, 1.0E+246, 1.0E+247, 1.0E+248, 1.0E+249, 1.0E+250,
1.0E+251, 1.0E+252, 1.0E+253, 1.0E+254, 1.0E+255, 1.0E+256, 1.0E+257, 1.0E+258, 1.0E+259, 1.0E+260,
1.0E+261, 1.0E+262, 1.0E+263, 1.0E+264, 1.0E+265, 1.0E+266, 1.0E+267, 1.0E+268, 1.0E+269, 1.0E+270,
1.0E+271, 1.0E+272, 1.0E+273, 1.0E+274, 1.0E+275, 1.0E+276, 1.0E+277, 1.0E+278, 1.0E+279, 1.0E+280,
1.0E+281, 1.0E+282, 1.0E+283, 1.0E+284, 1.0E+285, 1.0E+286, 1.0E+287, 1.0E+288, 1.0E+289, 1.0E+290,
1.0E+291, 1.0E+292, 1.0E+293, 1.0E+294, 1.0E+295, 1.0E+296, 1.0E+297, 1.0E+298, 1.0E+299, 1.0E+300,
1.0E+301, 1.0E+302, 1.0E+303, 1.0E+304, 1.0E+305, 1.0E+306, 1.0E+307, 1.0E+308
};
static const int fract10_size = static_cast<int>(sizeof(fract10) / sizeof(double));
const int e = std::abs(exponent);
if (exponent >= std::numeric_limits<T>::min_exponent10)
{
if (e < fract10_size)
{
if (exponent > 0)
return T(d * fract10[e]);
else
return T(d / fract10[e]);
}
else
return T(d * std::pow(10.0, 10.0 * exponent));
}
else
{
d /= T(fract10[ -std::numeric_limits<T>::min_exponent10]);
return T(d / fract10[-exponent + std::numeric_limits<T>::min_exponent10]);
}
}
template <typename Iterator, typename T>
inline bool string_to_type_converter_impl_ref(Iterator& itr, const Iterator end, T& result)
{
if (itr == end)
return false;
const bool negative = ('-' == (*itr));
if (negative || ('+' == (*itr)))
{
if (end == ++itr)
return false;
}
static const uchar_t zero = static_cast<uchar_t>('0');
while ((end != itr) && (zero == (*itr))) ++itr;
bool return_result = true;
unsigned int digit = 0;
const std::size_t length = static_cast<std::size_t>(std::distance(itr,end));
if (length <= 4)
{
exprtk_disable_fallthrough_begin
switch (length)
{
#ifdef exprtk_use_lut
#define exprtk_process_digit \
if ((digit = details::digit_table[(int)*itr++]) < 10) \
result = result * 10 + (digit); \
else \
{ \
return_result = false; \
break; \
} \
#else
#define exprtk_process_digit \
if ((digit = (*itr++ - zero)) < 10) \
result = result * T(10) + digit; \
else \
{ \
return_result = false; \
break; \
} \
#endif
case 4 : exprtk_process_digit
case 3 : exprtk_process_digit
case 2 : exprtk_process_digit
case 1 : if ((digit = (*itr - zero))>= 10)
{
digit = 0;
return_result = false;
}
#undef exprtk_process_digit
}
exprtk_disable_fallthrough_end
}
else
return_result = false;
if (length && return_result)
{
result = result * 10 + static_cast<T>(digit);
++itr;
}
result = negative ? -result : result;
return return_result;
}
template <typename Iterator, typename T>
static inline bool parse_nan(Iterator& itr, const Iterator end, T& t)
{
typedef typename std::iterator_traits<Iterator>::value_type type;
static const std::size_t nan_length = 3;
if (std::distance(itr,end) != static_cast<int>(nan_length))
return false;
if (static_cast<type>('n') == (*itr))
{
if (
(static_cast<type>('a') != *(itr + 1)) ||
(static_cast<type>('n') != *(itr + 2))
)
{
return false;
}
}
else if (
(static_cast<type>('A') != *(itr + 1)) ||
(static_cast<type>('N') != *(itr + 2))
)
{
return false;
}
t = std::numeric_limits<T>::quiet_NaN();
return true;
}
template <typename Iterator, typename T>
static inline bool parse_inf(Iterator& itr, const Iterator end, T& t, const bool negative)
{
static const char_t inf_uc[] = "INFINITY";
static const char_t inf_lc[] = "infinity";
static const std::size_t inf_length = 8;
const std::size_t length = static_cast<std::size_t>(std::distance(itr,end));
if ((3 != length) && (inf_length != length))
return false;
char_cptr inf_itr = ('i' == (*itr)) ? inf_lc : inf_uc;
while (end != itr)
{
if (*inf_itr == static_cast<char_t>(*itr))
{
++itr;
++inf_itr;
continue;
}
else
return false;
}
if (negative)
t = -std::numeric_limits<T>::infinity();
else
t = std::numeric_limits<T>::infinity();
return true;
}
template <typename T>
inline bool valid_exponent(const int exponent, numeric::details::real_type_tag)
{
using namespace details::numeric;
return (numeric_info<T>::min_exp <= exponent) && (exponent <= numeric_info<T>::max_exp);
}
template <typename Iterator, typename T>
inline bool string_to_real(Iterator& itr_external, const Iterator end, T& t, numeric::details::real_type_tag)
{
if (end == itr_external) return false;
Iterator itr = itr_external;
T d = T(0);
const bool negative = ('-' == (*itr));
if (negative || '+' == (*itr))
{
if (end == ++itr)
return false;
}
bool instate = false;
static const char_t zero = static_cast<uchar_t>('0');
#define parse_digit_1(d) \
if ((digit = (*itr - zero)) < 10) \
{ d = d * T(10) + digit; } \
else \
{ break; } \
if (end == ++itr) break; \
#define parse_digit_2(d) \
if ((digit = (*itr - zero)) < 10) \
{ d = d * T(10) + digit; } \
else \
{ break; } \
++itr; \
if ('.' != (*itr))
{
const Iterator curr = itr;
while ((end != itr) && (zero == (*itr))) ++itr;
while (end != itr)
{
unsigned int digit;
parse_digit_1(d)
parse_digit_1(d)
parse_digit_2(d)
}
if (curr != itr) instate = true;
}
int exponent = 0;
if (end != itr)
{
if ('.' == (*itr))
{
const Iterator curr = ++itr;
T tmp_d = T(0);
while (end != itr)
{
unsigned int digit;
parse_digit_1(tmp_d)
parse_digit_1(tmp_d)
parse_digit_2(tmp_d)
}
if (curr != itr)
{
instate = true;
const int frac_exponent = static_cast<int>(-std::distance(curr, itr));
if (!valid_exponent<T>(frac_exponent, numeric::details::real_type_tag()))
return false;
d += compute_pow10(tmp_d, frac_exponent);
}
#undef parse_digit_1
#undef parse_digit_2
}
if (end != itr)
{
typename std::iterator_traits<Iterator>::value_type c = (*itr);
if (('e' == c) || ('E' == c))
{
int exp = 0;
if (!details::string_to_type_converter_impl_ref(++itr, end, exp))
{
if (end == itr)
return false;
else
c = (*itr);
}
exponent += exp;
}
if (end != itr)
{
if (('f' == c) || ('F' == c) || ('l' == c) || ('L' == c))
++itr;
else if ('#' == c)
{
if (end == ++itr)
return false;
else if (('I' <= (*itr)) && ((*itr) <= 'n'))
{
if (('i' == (*itr)) || ('I' == (*itr)))
{
return parse_inf(itr, end, t, negative);
}
else if (('n' == (*itr)) || ('N' == (*itr)))
{
return parse_nan(itr, end, t);
}
else
return false;
}
else
return false;
}
else if (('I' <= (*itr)) && ((*itr) <= 'n'))
{
if (('i' == (*itr)) || ('I' == (*itr)))
{
return parse_inf(itr, end, t, negative);
}
else if (('n' == (*itr)) || ('N' == (*itr)))
{
return parse_nan(itr, end, t);
}
else
return false;
}
else
return false;
}
}
}
if ((end != itr) || (!instate))
return false;
else if (!valid_exponent<T>(exponent, numeric::details::real_type_tag()))
return false;
else if (exponent)
d = compute_pow10(d,exponent);
t = static_cast<T>((negative) ? -d : d);
return true;
}
template <typename T>
inline bool string_to_real(const std::string& s, T& t)
{
const typename numeric::details::number_type<T>::type num_type;
char_cptr begin = s.data();
char_cptr end = s.data() + s.size();
return string_to_real(begin, end, t, num_type);
}
template <typename T>
struct functor_t
{
/*
Note: The following definitions for Type, may require tweaking
based on the compiler and target architecture. The benchmark
should provide enough information to make the right choice.
*/
//typedef T Type;
//typedef const T Type;
typedef const T& Type;
typedef T& RefType;
typedef T (*qfunc_t)(Type t0, Type t1, Type t2, Type t3);
typedef T (*tfunc_t)(Type t0, Type t1, Type t2);
typedef T (*bfunc_t)(Type t0, Type t1);
typedef T (*ufunc_t)(Type t0);
};
} // namespace details
struct loop_runtime_check
{
enum loop_types
{
e_invalid = 0,
e_for_loop = 1,
e_while_loop = 2,
e_repeat_until_loop = 4,
e_all_loops = 7
};
enum violation_type
{
e_unknown = 0,
e_iteration_count = 1,
e_timeout = 2
};
loop_types loop_set;
loop_runtime_check()
: loop_set(e_invalid)
, max_loop_iterations(0)
{}
details::_uint64_t max_loop_iterations;
struct violation_context
{
loop_types loop;
violation_type violation;
details::_uint64_t iteration_count;
};
virtual bool check()
{
return true;
}
virtual void handle_runtime_violation(const violation_context&)
{
throw std::runtime_error("ExprTk Loop run-time violation.");
}
virtual ~loop_runtime_check() {}
};
typedef loop_runtime_check* loop_runtime_check_ptr;
namespace lexer
{
struct token
{
enum token_type
{
e_none = 0, e_error = 1, e_err_symbol = 2,
e_err_number = 3, e_err_string = 4, e_err_sfunc = 5,
e_eof = 6, e_number = 7, e_symbol = 8,
e_string = 9, e_assign = 10, e_addass = 11,
e_subass = 12, e_mulass = 13, e_divass = 14,
e_modass = 15, e_shr = 16, e_shl = 17,
e_lte = 18, e_ne = 19, e_gte = 20,
e_swap = 21, e_lt = '<', e_gt = '>',
e_eq = '=', e_rbracket = ')', e_lbracket = '(',
e_rsqrbracket = ']', e_lsqrbracket = '[', e_rcrlbracket = '}',
e_lcrlbracket = '{', e_comma = ',', e_add = '+',
e_sub = '-', e_div = '/', e_mul = '*',
e_mod = '%', e_pow = '^', e_colon = ':',
e_ternary = '?'
};
token()
: type(e_none)
, value("")
, position(std::numeric_limits<std::size_t>::max())
{}
void clear()
{
type = e_none;
value = "";
position = std::numeric_limits<std::size_t>::max();
}
template <typename Iterator>
inline token& set_operator(const token_type tt,
const Iterator begin, const Iterator end,
const Iterator base_begin = Iterator(0))
{
type = tt;
value.assign(begin,end);
if (base_begin)
position = static_cast<std::size_t>(std::distance(base_begin,begin));
return (*this);
}
template <typename Iterator>
inline token& set_symbol(const Iterator begin, const Iterator end, const Iterator base_begin = Iterator(0))
{
type = e_symbol;
value.assign(begin,end);
if (base_begin)
position = static_cast<std::size_t>(std::distance(base_begin,begin));
return (*this);
}
template <typename Iterator>
inline token& set_numeric(const Iterator begin, const Iterator end, const Iterator base_begin = Iterator(0))
{
type = e_number;
value.assign(begin,end);
if (base_begin)
position = static_cast<std::size_t>(std::distance(base_begin,begin));
return (*this);
}
template <typename Iterator>
inline token& set_string(const Iterator begin, const Iterator end, const Iterator base_begin = Iterator(0))
{
type = e_string;
value.assign(begin,end);
if (base_begin)
position = static_cast<std::size_t>(std::distance(base_begin,begin));
return (*this);
}
inline token& set_string(const std::string& s, const std::size_t p)
{
type = e_string;
value = s;
position = p;
return (*this);
}
template <typename Iterator>
inline token& set_error(const token_type et,
const Iterator begin, const Iterator end,
const Iterator base_begin = Iterator(0))
{
if (
(e_error == et) ||
(e_err_symbol == et) ||
(e_err_number == et) ||
(e_err_string == et) ||
(e_err_sfunc == et)
)
{
type = et;
}
else
type = e_error;
value.assign(begin,end);
if (base_begin)
position = static_cast<std::size_t>(std::distance(base_begin,begin));
return (*this);
}
static inline std::string to_str(token_type t)
{
switch (t)
{
case e_none : return "NONE";
case e_error : return "ERROR";
case e_err_symbol : return "ERROR_SYMBOL";
case e_err_number : return "ERROR_NUMBER";
case e_err_string : return "ERROR_STRING";
case e_eof : return "EOF";
case e_number : return "NUMBER";
case e_symbol : return "SYMBOL";
case e_string : return "STRING";
case e_assign : return ":=";
case e_addass : return "+=";
case e_subass : return "-=";
case e_mulass : return "*=";
case e_divass : return "/=";
case e_modass : return "%=";
case e_shr : return ">>";
case e_shl : return "<<";
case e_lte : return "<=";
case e_ne : return "!=";
case e_gte : return ">=";
case e_lt : return "<";
case e_gt : return ">";
case e_eq : return "=";
case e_rbracket : return ")";
case e_lbracket : return "(";
case e_rsqrbracket : return "]";
case e_lsqrbracket : return "[";
case e_rcrlbracket : return "}";
case e_lcrlbracket : return "{";
case e_comma : return ",";
case e_add : return "+";
case e_sub : return "-";
case e_div : return "/";
case e_mul : return "*";
case e_mod : return "%";
case e_pow : return "^";
case e_colon : return ":";
case e_ternary : return "?";
case e_swap : return "<=>";
default : return "UNKNOWN";
}
}
inline bool is_error() const
{
return (
(e_error == type) ||
(e_err_symbol == type) ||
(e_err_number == type) ||
(e_err_string == type) ||
(e_err_sfunc == type)
);
}
token_type type;
std::string value;
std::size_t position;
};
class generator
{
public:
typedef token token_t;
typedef std::vector<token_t> token_list_t;
typedef token_list_t::iterator token_list_itr_t;
typedef details::char_t char_t;
generator()
: base_itr_(0)
, s_itr_ (0)
, s_end_ (0)
{
clear();
}
inline void clear()
{
base_itr_ = 0;
s_itr_ = 0;
s_end_ = 0;
token_list_.clear();
token_itr_ = token_list_.end();
store_token_itr_ = token_list_.end();
}
inline bool process(const std::string& str)
{
base_itr_ = str.data();
s_itr_ = str.data();
s_end_ = str.data() + str.size();
eof_token_.set_operator(token_t::e_eof,s_end_,s_end_,base_itr_);
token_list_.clear();
while (!is_end(s_itr_))
{
scan_token();
if (!token_list_.empty() && token_list_.back().is_error())
return false;
}
return true;
}
inline bool empty() const
{
return token_list_.empty();
}
inline std::size_t size() const
{
return token_list_.size();
}
inline void begin()
{
token_itr_ = token_list_.begin();
store_token_itr_ = token_list_.begin();
}
inline void store()
{
store_token_itr_ = token_itr_;
}
inline void restore()
{
token_itr_ = store_token_itr_;
}
inline token_t& next_token()
{
if (token_list_.end() != token_itr_)
{
return *token_itr_++;
}
else
return eof_token_;
}
inline token_t& peek_next_token()
{
if (token_list_.end() != token_itr_)
{
return *token_itr_;
}
else
return eof_token_;
}
inline token_t& operator[](const std::size_t& index)
{
if (index < token_list_.size())
return token_list_[index];
else
return eof_token_;
}
inline token_t operator[](const std::size_t& index) const
{
if (index < token_list_.size())
return token_list_[index];
else
return eof_token_;
}
inline bool finished() const
{
return (token_list_.end() == token_itr_);
}
inline void insert_front(token_t::token_type tk_type)
{
if (
!token_list_.empty() &&
(token_list_.end() != token_itr_)
)
{
token_t t = *token_itr_;
t.type = tk_type;
token_itr_ = token_list_.insert(token_itr_,t);
}
}
inline std::string substr(const std::size_t& begin, const std::size_t& end) const
{
const details::char_cptr begin_itr = ((base_itr_ + begin) < s_end_) ? (base_itr_ + begin) : s_end_;
const details::char_cptr end_itr = ((base_itr_ + end ) < s_end_) ? (base_itr_ + end ) : s_end_;
return std::string(begin_itr,end_itr);
}
inline std::string remaining() const
{
if (finished())
return "";
else if (token_list_.begin() != token_itr_)
return std::string(base_itr_ + (token_itr_ - 1)->position, s_end_);
else
return std::string(base_itr_ + token_itr_->position, s_end_);
}
private:
inline bool is_end(details::char_cptr itr) const
{
return (s_end_ == itr);
}
#ifndef exprtk_disable_comments
inline bool is_comment_start(details::char_cptr itr) const
{
const char_t c0 = *(itr + 0);
const char_t c1 = *(itr + 1);
if ('#' == c0)
return true;
else if (!is_end(itr + 1))
{
if (('/' == c0) && ('/' == c1)) return true;
if (('/' == c0) && ('*' == c1)) return true;
}
return false;
}
#else
inline bool is_comment_start(details::char_cptr) const
{
return false;
}
#endif
inline void skip_whitespace()
{
while (!is_end(s_itr_) && details::is_whitespace(*s_itr_))
{
++s_itr_;
}
}
inline void skip_comments()
{
#ifndef exprtk_disable_comments
// The following comment styles are supported:
// 1. // .... \n
// 2. # .... \n
// 3. /* .... */
struct test
{
static inline bool comment_start(const char_t c0, const char_t c1, int& mode, int& incr)
{
mode = 0;
if ('#' == c0) { mode = 1; incr = 1; }
else if ('/' == c0)
{
if ('/' == c1) { mode = 1; incr = 2; }
else if ('*' == c1) { mode = 2; incr = 2; }
}
return (0 != mode);
}
static inline bool comment_end(const char_t c0, const char_t c1, int& mode)
{
if (
((1 == mode) && ('\n' == c0)) ||
((2 == mode) && ( '*' == c0) && ('/' == c1))
)
{
mode = 0;
return true;
}
else
return false;
}
};
int mode = 0;
int increment = 0;
if (is_end(s_itr_))
return;
else if (!test::comment_start(*s_itr_, *(s_itr_ + 1), mode, increment))
return;
details::char_cptr cmt_start = s_itr_;
s_itr_ += increment;
while (!is_end(s_itr_))
{
if ((1 == mode) && test::comment_end(*s_itr_, 0, mode))
{
++s_itr_;
return;
}
if ((2 == mode))
{
if (!is_end((s_itr_ + 1)) && test::comment_end(*s_itr_, *(s_itr_ + 1), mode))
{
s_itr_ += 2;
return;
}
}
++s_itr_;
}
if (2 == mode)
{
token_t t;
t.set_error(token::e_error, cmt_start, cmt_start + mode, base_itr_);
token_list_.push_back(t);
}
#endif
}
inline void scan_token()
{
if (details::is_whitespace(*s_itr_))
{
skip_whitespace();
return;
}
else if (is_comment_start(s_itr_))
{
skip_comments();
return;
}
else if (details::is_operator_char(*s_itr_))
{
scan_operator();
return;
}
else if (details::is_letter(*s_itr_))
{
scan_symbol();
return;
}
else if (details::is_digit((*s_itr_)) || ('.' == (*s_itr_)))
{
scan_number();
return;
}
else if ('$' == (*s_itr_))
{
scan_special_function();
return;
}
#ifndef exprtk_disable_string_capabilities
else if ('\'' == (*s_itr_))
{
scan_string();
return;
}
#endif
else if ('~' == (*s_itr_))
{
token_t t;
t.set_symbol(s_itr_, s_itr_ + 1, base_itr_);
token_list_.push_back(t);
++s_itr_;
return;
}
else
{
token_t t;
t.set_error(token::e_error, s_itr_, s_itr_ + 2, base_itr_);
token_list_.push_back(t);
++s_itr_;
}
}
inline void scan_operator()
{
token_t t;
const char_t c0 = s_itr_[0];
if (!is_end(s_itr_ + 1))
{
const char_t c1 = s_itr_[1];
if (!is_end(s_itr_ + 2))
{
const char_t c2 = s_itr_[2];
if ((c0 == '<') && (c1 == '=') && (c2 == '>'))
{
t.set_operator(token_t::e_swap, s_itr_, s_itr_ + 3, base_itr_);
token_list_.push_back(t);
s_itr_ += 3;
return;
}
}
token_t::token_type ttype = token_t::e_none;
if ((c0 == '<') && (c1 == '=')) ttype = token_t::e_lte;
else if ((c0 == '>') && (c1 == '=')) ttype = token_t::e_gte;
else if ((c0 == '<') && (c1 == '>')) ttype = token_t::e_ne;
else if ((c0 == '!') && (c1 == '=')) ttype = token_t::e_ne;
else if ((c0 == '=') && (c1 == '=')) ttype = token_t::e_eq;
else if ((c0 == ':') && (c1 == '=')) ttype = token_t::e_assign;
else if ((c0 == '<') && (c1 == '<')) ttype = token_t::e_shl;
else if ((c0 == '>') && (c1 == '>')) ttype = token_t::e_shr;
else if ((c0 == '+') && (c1 == '=')) ttype = token_t::e_addass;
else if ((c0 == '-') && (c1 == '=')) ttype = token_t::e_subass;
else if ((c0 == '*') && (c1 == '=')) ttype = token_t::e_mulass;
else if ((c0 == '/') && (c1 == '=')) ttype = token_t::e_divass;
else if ((c0 == '%') && (c1 == '=')) ttype = token_t::e_modass;
if (token_t::e_none != ttype)
{
t.set_operator(ttype, s_itr_, s_itr_ + 2, base_itr_);
token_list_.push_back(t);
s_itr_ += 2;
return;
}
}
if ('<' == c0)
t.set_operator(token_t::e_lt , s_itr_, s_itr_ + 1, base_itr_);
else if ('>' == c0)
t.set_operator(token_t::e_gt , s_itr_, s_itr_ + 1, base_itr_);
else if (';' == c0)
t.set_operator(token_t::e_eof, s_itr_, s_itr_ + 1, base_itr_);
else if ('&' == c0)
t.set_symbol(s_itr_, s_itr_ + 1, base_itr_);
else if ('|' == c0)
t.set_symbol(s_itr_, s_itr_ + 1, base_itr_);
else
t.set_operator(token_t::token_type(c0), s_itr_, s_itr_ + 1, base_itr_);
token_list_.push_back(t);
++s_itr_;
}
inline void scan_symbol()
{
details::char_cptr initial_itr = s_itr_;
while (!is_end(s_itr_))
{
if (!details::is_letter_or_digit(*s_itr_) && ('_' != (*s_itr_)))
{
if ('.' != (*s_itr_))
break;
/*
Permit symbols that contain a 'dot'
Allowed : abc.xyz, a123.xyz, abc.123, abc_.xyz a123_.xyz abc._123
Disallowed: .abc, abc.<white-space>, abc.<eof>, abc.<operator +,-,*,/...>
*/
if (
(s_itr_ != initial_itr) &&
!is_end(s_itr_ + 1) &&
!details::is_letter_or_digit(*(s_itr_ + 1)) &&
('_' != (*(s_itr_ + 1)))
)
break;
}
++s_itr_;
}
token_t t;
t.set_symbol(initial_itr,s_itr_,base_itr_);
token_list_.push_back(t);
}
inline void scan_number()
{
/*
Attempt to match a valid numeric value in one of the following formats:
(01) 123456
(02) 123456.
(03) 123.456
(04) 123.456e3
(05) 123.456E3
(06) 123.456e+3
(07) 123.456E+3
(08) 123.456e-3
(09) 123.456E-3
(00) .1234
(11) .1234e3
(12) .1234E+3
(13) .1234e+3
(14) .1234E-3
(15) .1234e-3
*/
details::char_cptr initial_itr = s_itr_;
bool dot_found = false;
bool e_found = false;
bool post_e_sign_found = false;
bool post_e_digit_found = false;
token_t t;
while (!is_end(s_itr_))
{
if ('.' == (*s_itr_))
{
if (dot_found)
{
t.set_error(token::e_err_number, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
dot_found = true;
++s_itr_;
continue;
}
else if ('e' == std::tolower(*s_itr_))
{
const char_t& c = *(s_itr_ + 1);
if (is_end(s_itr_ + 1))
{
t.set_error(token::e_err_number, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
else if (
('+' != c) &&
('-' != c) &&
!details::is_digit(c)
)
{
t.set_error(token::e_err_number, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
e_found = true;
++s_itr_;
continue;
}
else if (e_found && details::is_sign(*s_itr_) && !post_e_digit_found)
{
if (post_e_sign_found)
{
t.set_error(token::e_err_number, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
post_e_sign_found = true;
++s_itr_;
continue;
}
else if (e_found && details::is_digit(*s_itr_))
{
post_e_digit_found = true;
++s_itr_;
continue;
}
else if (('.' != (*s_itr_)) && !details::is_digit(*s_itr_))
break;
else
++s_itr_;
}
t.set_numeric(initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
inline void scan_special_function()
{
details::char_cptr initial_itr = s_itr_;
token_t t;
// $fdd(x,x,x) = at least 11 chars
if (std::distance(s_itr_,s_end_) < 11)
{
t.set_error(
token::e_err_sfunc,
initial_itr, std::min(initial_itr + 11, s_end_),
base_itr_);
token_list_.push_back(t);
return;
}
if (
!(('$' == *s_itr_) &&
(details::imatch ('f',*(s_itr_ + 1))) &&
(details::is_digit(*(s_itr_ + 2))) &&
(details::is_digit(*(s_itr_ + 3))))
)
{
t.set_error(
token::e_err_sfunc,
initial_itr, std::min(initial_itr + 4, s_end_),
base_itr_);
token_list_.push_back(t);
return;
}
s_itr_ += 4; // $fdd = 4chars
t.set_symbol(initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
#ifndef exprtk_disable_string_capabilities
inline void scan_string()
{
details::char_cptr initial_itr = s_itr_ + 1;
token_t t;
if (std::distance(s_itr_,s_end_) < 2)
{
t.set_error(token::e_err_string, s_itr_, s_end_, base_itr_);
token_list_.push_back(t);
return;
}
++s_itr_;
bool escaped_found = false;
bool escaped = false;
while (!is_end(s_itr_))
{
if (!details::is_valid_string_char(*s_itr_))
{
t.set_error(token::e_err_string, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
else if (!escaped && ('\\' == *s_itr_))
{
escaped_found = true;
escaped = true;
++s_itr_;
continue;
}
else if (!escaped)
{
if ('\'' == *s_itr_)
break;
}
else if (escaped)
{
if (
!is_end(s_itr_) && ('0' == *(s_itr_)) &&
((s_itr_ + 4) <= s_end_)
)
{
const bool x_seperator = ('X' == std::toupper(*(s_itr_ + 1)));
const bool both_digits = details::is_hex_digit(*(s_itr_ + 2)) &&
details::is_hex_digit(*(s_itr_ + 3)) ;
if (!(x_seperator && both_digits))
{
t.set_error(token::e_err_string, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
else
s_itr_ += 3;
}
escaped = false;
}
++s_itr_;
}
if (is_end(s_itr_))
{
t.set_error(token::e_err_string, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
if (!escaped_found)
t.set_string(initial_itr, s_itr_, base_itr_);
else
{
std::string parsed_string(initial_itr,s_itr_);
if (!details::cleanup_escapes(parsed_string))
{
t.set_error(token::e_err_string, initial_itr, s_itr_, base_itr_);
token_list_.push_back(t);
return;
}
t.set_string(
parsed_string,
static_cast<std::size_t>(std::distance(base_itr_,initial_itr)));
}
token_list_.push_back(t);
++s_itr_;
return;
}
#endif
private:
token_list_t token_list_;
token_list_itr_t token_itr_;
token_list_itr_t store_token_itr_;
token_t eof_token_;
details::char_cptr base_itr_;
details::char_cptr s_itr_;
details::char_cptr s_end_;
friend class token_scanner;
friend class token_modifier;
friend class token_inserter;
friend class token_joiner;
}; // class generator
class helper_interface
{
public:
virtual void init() { }
virtual void reset() { }
virtual bool result() { return true; }
virtual std::size_t process(generator&) { return 0; }
virtual ~helper_interface() { }
};
class token_scanner : public helper_interface
{
public:
virtual ~token_scanner() {}
explicit token_scanner(const std::size_t& stride)
: stride_(stride)
{
if (stride > 4)
{
throw std::invalid_argument("token_scanner() - Invalid stride value");
}
}
inline std::size_t process(generator& g) exprtk_override
{
if (g.token_list_.size() >= stride_)
{
for (std::size_t i = 0; i < (g.token_list_.size() - stride_ + 1); ++i)
{
token t;
switch (stride_)
{
case 1 :
{
const token& t0 = g.token_list_[i];
if (!operator()(t0))
{
return i;
}
}
break;
case 2 :
{
const token& t0 = g.token_list_[i ];
const token& t1 = g.token_list_[i + 1];
if (!operator()(t0, t1))
{
return i;
}
}
break;
case 3 :
{
const token& t0 = g.token_list_[i ];
const token& t1 = g.token_list_[i + 1];
const token& t2 = g.token_list_[i + 2];
if (!operator()(t0, t1, t2))
{
return i;
}
}
break;
case 4 :
{
const token& t0 = g.token_list_[i ];
const token& t1 = g.token_list_[i + 1];
const token& t2 = g.token_list_[i + 2];
const token& t3 = g.token_list_[i + 3];
if (!operator()(t0, t1, t2, t3))
{
return i;
}
}
break;
}
}
}
return (g.token_list_.size() - stride_ + 1);
}
virtual bool operator() (const token&)
{
return false;
}
virtual bool operator() (const token&, const token&)
{
return false;
}
virtual bool operator() (const token&, const token&, const token&)
{
return false;
}
virtual bool operator() (const token&, const token&, const token&, const token&)
{
return false;
}
private:
const std::size_t stride_;
}; // class token_scanner
class token_modifier : public helper_interface
{
public:
inline std::size_t process(generator& g) exprtk_override
{
std::size_t changes = 0;
for (std::size_t i = 0; i < g.token_list_.size(); ++i)
{
if (modify(g.token_list_[i])) changes++;
}
return changes;
}
virtual bool modify(token& t) = 0;
};
class token_inserter : public helper_interface
{
public:
explicit token_inserter(const std::size_t& stride)
: stride_(stride)
{
if (stride > 5)
{
throw std::invalid_argument("token_inserter() - Invalid stride value");
}
}
inline std::size_t process(generator& g) exprtk_override
{
if (g.token_list_.empty())
return 0;
else if (g.token_list_.size() < stride_)
return 0;
std::size_t changes = 0;
typedef std::pair<std::size_t, token> insert_t;
std::vector<insert_t> insert_list;
insert_list.reserve(10000);
for (std::size_t i = 0; i < (g.token_list_.size() - stride_ + 1); ++i)
{
int insert_index = -1;
token t;
switch (stride_)
{
case 1 : insert_index = insert(g.token_list_[i],t);
break;
case 2 : insert_index = insert(g.token_list_[i], g.token_list_[i + 1], t);
break;
case 3 : insert_index = insert(g.token_list_[i], g.token_list_[i + 1], g.token_list_[i + 2], t);
break;
case 4 : insert_index = insert(g.token_list_[i], g.token_list_[i + 1], g.token_list_[i + 2], g.token_list_[i + 3], t);
break;
case 5 : insert_index = insert(g.token_list_[i], g.token_list_[i + 1], g.token_list_[i + 2], g.token_list_[i + 3], g.token_list_[i + 4], t);
break;
}
if ((insert_index >= 0) && (insert_index <= (static_cast<int>(stride_) + 1)))
{
insert_list.push_back(insert_t(i, t));
changes++;
}
}
if (!insert_list.empty())
{
generator::token_list_t token_list;
std::size_t insert_index = 0;
for (std::size_t i = 0; i < g.token_list_.size(); ++i)
{
token_list.push_back(g.token_list_[i]);
if (
(insert_index < insert_list.size()) &&
(insert_list[insert_index].first == i)
)
{
token_list.push_back(insert_list[insert_index].second);
insert_index++;
}
}
std::swap(g.token_list_,token_list);
}
return changes;
}
#define token_inserter_empty_body \
{ \
return -1; \
} \
inline virtual int insert(const token&, token&)
token_inserter_empty_body
inline virtual int insert(const token&, const token&, token&)
token_inserter_empty_body
inline virtual int insert(const token&, const token&, const token&, token&)
token_inserter_empty_body
inline virtual int insert(const token&, const token&, const token&, const token&, token&)
token_inserter_empty_body
inline virtual int insert(const token&, const token&, const token&, const token&, const token&, token&)
token_inserter_empty_body
#undef token_inserter_empty_body
private:
const std::size_t stride_;
};
class token_joiner : public helper_interface
{
public:
explicit token_joiner(const std::size_t& stride)
: stride_(stride)
{}
inline std::size_t process(generator& g) exprtk_override
{
if (g.token_list_.empty())
return 0;
switch (stride_)
{
case 2 : return process_stride_2(g);
case 3 : return process_stride_3(g);
default : return 0;
}
}
virtual bool join(const token&, const token&, token&) { return false; }
virtual bool join(const token&, const token&, const token&, token&) { return false; }
private:
inline std::size_t process_stride_2(generator& g)
{
if (g.token_list_.size() < 2)
return 0;
std::size_t changes = 0;
generator::token_list_t token_list;
token_list.reserve(10000);
for (int i = 0; i < static_cast<int>(g.token_list_.size() - 1); ++i)
{
token t;
for ( ; ; )
{
if (!join(g[i], g[i + 1], t))
{
token_list.push_back(g[i]);
break;
}
token_list.push_back(t);
++changes;
i+=2;
if (static_cast<std::size_t>(i) >= (g.token_list_.size() - 1))
break;
}
}
token_list.push_back(g.token_list_.back());
assert(token_list.size() <= g.token_list_.size());
std::swap(token_list, g.token_list_);
return changes;
}
inline std::size_t process_stride_3(generator& g)
{
if (g.token_list_.size() < 3)
return 0;
std::size_t changes = 0;
generator::token_list_t token_list;
token_list.reserve(10000);
for (int i = 0; i < static_cast<int>(g.token_list_.size() - 2); ++i)
{
token t;
for ( ; ; )
{
if (!join(g[i], g[i + 1], g[i + 2], t))
{
token_list.push_back(g[i]);
break;
}
token_list.push_back(t);
++changes;
i+=3;
if (static_cast<std::size_t>(i) >= (g.token_list_.size() - 2))
break;
}
}
token_list.push_back(*(g.token_list_.begin() + g.token_list_.size() - 2));
token_list.push_back(*(g.token_list_.begin() + g.token_list_.size() - 1));
assert(token_list.size() <= g.token_list_.size());
std::swap(token_list, g.token_list_);
return changes;
}
const std::size_t stride_;
};
namespace helper
{
inline void dump(const lexer::generator& generator)
{
for (std::size_t i = 0; i < generator.size(); ++i)
{
const lexer::token& t = generator[i];
printf("Token[%02d] @ %03d %6s --> '%s'\n",
static_cast<int>(i),
static_cast<int>(t.position),
t.to_str(t.type).c_str(),
t.value.c_str());
}
}
class commutative_inserter : public lexer::token_inserter
{
public:
using lexer::token_inserter::insert;
commutative_inserter()
: lexer::token_inserter(2)
{}
inline void ignore_symbol(const std::string& symbol)
{
ignore_set_.insert(symbol);
}
inline int insert(const lexer::token& t0, const lexer::token& t1, lexer::token& new_token) exprtk_override
{
bool match = false;
new_token.type = lexer::token::e_mul;
new_token.value = "*";
new_token.position = t1.position;
if (t0.type == lexer::token::e_symbol)
{
if (ignore_set_.end() != ignore_set_.find(t0.value))
{
return -1;
}
else if (!t0.value.empty() && ('$' == t0.value[0]))
{
return -1;
}
}
if (t1.type == lexer::token::e_symbol)
{
if (ignore_set_.end() != ignore_set_.find(t1.value))
{
return -1;
}
}
if ((t0.type == lexer::token::e_number ) && (t1.type == lexer::token::e_symbol )) match = true;
else if ((t0.type == lexer::token::e_number ) && (t1.type == lexer::token::e_lbracket )) match = true;
else if ((t0.type == lexer::token::e_number ) && (t1.type == lexer::token::e_lcrlbracket)) match = true;
else if ((t0.type == lexer::token::e_number ) && (t1.type == lexer::token::e_lsqrbracket)) match = true;
else if ((t0.type == lexer::token::e_symbol ) && (t1.type == lexer::token::e_number )) match = true;
else if ((t0.type == lexer::token::e_rbracket ) && (t1.type == lexer::token::e_number )) match = true;
else if ((t0.type == lexer::token::e_rcrlbracket) && (t1.type == lexer::token::e_number )) match = true;
else if ((t0.type == lexer::token::e_rsqrbracket) && (t1.type == lexer::token::e_number )) match = true;
else if ((t0.type == lexer::token::e_rbracket ) && (t1.type == lexer::token::e_symbol )) match = true;
else if ((t0.type == lexer::token::e_rcrlbracket) && (t1.type == lexer::token::e_symbol )) match = true;
else if ((t0.type == lexer::token::e_rsqrbracket) && (t1.type == lexer::token::e_symbol )) match = true;
else if ((t0.type == lexer::token::e_symbol ) && (t1.type == lexer::token::e_symbol )) match = true;
return (match) ? 1 : -1;
}
private:
std::set<std::string,details::ilesscompare> ignore_set_;
};
class operator_joiner : public token_joiner
{
public:
explicit operator_joiner(const std::size_t& stride)
: token_joiner(stride)
{}
inline bool join(const lexer::token& t0, const lexer::token& t1, lexer::token& t) exprtk_override
{
// ': =' --> ':='
if ((t0.type == lexer::token::e_colon) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_assign;
t.value = ":=";
t.position = t0.position;
return true;
}
// '+ =' --> '+='
else if ((t0.type == lexer::token::e_add) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_addass;
t.value = "+=";
t.position = t0.position;
return true;
}
// '- =' --> '-='
else if ((t0.type == lexer::token::e_sub) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_subass;
t.value = "-=";
t.position = t0.position;
return true;
}
// '* =' --> '*='
else if ((t0.type == lexer::token::e_mul) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_mulass;
t.value = "*=";
t.position = t0.position;
return true;
}
// '/ =' --> '/='
else if ((t0.type == lexer::token::e_div) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_divass;
t.value = "/=";
t.position = t0.position;
return true;
}
// '% =' --> '%='
else if ((t0.type == lexer::token::e_mod) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_modass;
t.value = "%=";
t.position = t0.position;
return true;
}
// '> =' --> '>='
else if ((t0.type == lexer::token::e_gt) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_gte;
t.value = ">=";
t.position = t0.position;
return true;
}
// '< =' --> '<='
else if ((t0.type == lexer::token::e_lt) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_lte;
t.value = "<=";
t.position = t0.position;
return true;
}
// '= =' --> '=='
else if ((t0.type == lexer::token::e_eq) && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_eq;
t.value = "==";
t.position = t0.position;
return true;
}
// '! =' --> '!='
else if ((static_cast<details::char_t>(t0.type) == '!') && (t1.type == lexer::token::e_eq))
{
t.type = lexer::token::e_ne;
t.value = "!=";
t.position = t0.position;
return true;
}
// '< >' --> '<>'
else if ((t0.type == lexer::token::e_lt) && (t1.type == lexer::token::e_gt))
{
t.type = lexer::token::e_ne;
t.value = "<>";
t.position = t0.position;
return true;
}
// '<= >' --> '<=>'
else if ((t0.type == lexer::token::e_lte) && (t1.type == lexer::token::e_gt))
{
t.type = lexer::token::e_swap;
t.value = "<=>";
t.position = t0.position;
return true;
}
// '+ -' --> '-'
else if ((t0.type == lexer::token::e_add) && (t1.type == lexer::token::e_sub))
{
t.type = lexer::token::e_sub;
t.value = "-";
t.position = t0.position;
return true;
}
// '- +' --> '-'
else if ((t0.type == lexer::token::e_sub) && (t1.type == lexer::token::e_add))
{
t.type = lexer::token::e_sub;
t.value = "-";
t.position = t0.position;
return true;
}
// '- -' --> '+'
else if ((t0.type == lexer::token::e_sub) && (t1.type == lexer::token::e_sub))
{
/*
Note: May need to reconsider this when wanting to implement
pre/postfix decrement operator
*/
t.type = lexer::token::e_add;
t.value = "+";
t.position = t0.position;
return true;
}
else
return false;
}
inline bool join(const lexer::token& t0,
const lexer::token& t1,
const lexer::token& t2,
lexer::token& t) exprtk_override
{
// '[ * ]' --> '[*]'
if (
(t0.type == lexer::token::e_lsqrbracket) &&
(t1.type == lexer::token::e_mul ) &&
(t2.type == lexer::token::e_rsqrbracket)
)
{
t.type = lexer::token::e_symbol;
t.value = "[*]";
t.position = t0.position;
return true;
}
else
return false;
}
};
class bracket_checker : public lexer::token_scanner
{
public:
using lexer::token_scanner::operator();
bracket_checker()
: token_scanner(1)
, state_(true)
{}
bool result()
{
if (!stack_.empty())
{
lexer::token t;
t.value = stack_.top().first;
t.position = stack_.top().second;
error_token_ = t;
state_ = false;
return false;
}
else
return state_;
}
lexer::token error_token()
{
return error_token_;
}
void reset()
{
// Why? because msvc doesn't support swap properly.
stack_ = std::stack<std::pair<char,std::size_t> >();
state_ = true;
error_token_.clear();
}
bool operator() (const lexer::token& t)
{
if (
!t.value.empty() &&
(lexer::token::e_string != t.type) &&
(lexer::token::e_symbol != t.type) &&
exprtk::details::is_bracket(t.value[0])
)
{
details::char_t c = t.value[0];
if (t.type == lexer::token::e_lbracket ) stack_.push(std::make_pair(')',t.position));
else if (t.type == lexer::token::e_lcrlbracket) stack_.push(std::make_pair('}',t.position));
else if (t.type == lexer::token::e_lsqrbracket) stack_.push(std::make_pair(']',t.position));
else if (exprtk::details::is_right_bracket(c))
{
if (stack_.empty())
{
state_ = false;
error_token_ = t;
return false;
}
else if (c != stack_.top().first)
{
state_ = false;
error_token_ = t;
return false;
}
else
stack_.pop();
}
}
return true;
}
private:
bool state_;
std::stack<std::pair<char,std::size_t> > stack_;
lexer::token error_token_;
};
template <typename T>
class numeric_checker exprtk_final : public lexer::token_scanner
{
public:
using lexer::token_scanner::operator();
numeric_checker()
: token_scanner (1)
, current_index_(0)
{}
bool result()
{
return error_list_.empty();
}
void reset()
{
error_list_.clear();
current_index_ = 0;
}
bool operator() (const lexer::token& t)
{
if (token::e_number == t.type)
{
T v;
if (!exprtk::details::string_to_real(t.value,v))
{
error_list_.push_back(current_index_);
}
}
++current_index_;
return true;
}
std::size_t error_count() const
{
return error_list_.size();
}
std::size_t error_index(const std::size_t& i)
{
if (i < error_list_.size())
return error_list_[i];
else
return std::numeric_limits<std::size_t>::max();
}
void clear_errors()
{
error_list_.clear();
}
private:
std::size_t current_index_;
std::vector<std::size_t> error_list_;
};
class symbol_replacer : public lexer::token_modifier
{
private:
typedef std::map<std::string,std::pair<std::string,token::token_type>,details::ilesscompare> replace_map_t;
public:
bool remove(const std::string& target_symbol)
{
const replace_map_t::iterator itr = replace_map_.find(target_symbol);
if (replace_map_.end() == itr)
return false;
replace_map_.erase(itr);
return true;
}
bool add_replace(const std::string& target_symbol,
const std::string& replace_symbol,
const lexer::token::token_type token_type = lexer::token::e_symbol)
{
const replace_map_t::iterator itr = replace_map_.find(target_symbol);
if (replace_map_.end() != itr)
{
return false;
}
replace_map_[target_symbol] = std::make_pair(replace_symbol,token_type);
return true;
}
void clear()
{
replace_map_.clear();
}
private:
bool modify(lexer::token& t)
{
if (lexer::token::e_symbol == t.type)
{
if (replace_map_.empty())
return false;
const replace_map_t::iterator itr = replace_map_.find(t.value);
if (replace_map_.end() != itr)
{
t.value = itr->second.first;
t.type = itr->second.second;
return true;
}
}
return false;
}
replace_map_t replace_map_;
};
class sequence_validator exprtk_final : public lexer::token_scanner
{
private:
typedef std::pair<lexer::token::token_type,lexer::token::token_type> token_pair_t;
typedef std::set<token_pair_t> set_t;
public:
using lexer::token_scanner::operator();
sequence_validator()
: lexer::token_scanner(2)
{
add_invalid(lexer::token::e_number, lexer::token::e_number);
add_invalid(lexer::token::e_string, lexer::token::e_string);
add_invalid(lexer::token::e_number, lexer::token::e_string);
add_invalid(lexer::token::e_string, lexer::token::e_number);
add_invalid_set1(lexer::token::e_assign );
add_invalid_set1(lexer::token::e_shr );
add_invalid_set1(lexer::token::e_shl );
add_invalid_set1(lexer::token::e_lte );
add_invalid_set1(lexer::token::e_ne );
add_invalid_set1(lexer::token::e_gte );
add_invalid_set1(lexer::token::e_lt );
add_invalid_set1(lexer::token::e_gt );
add_invalid_set1(lexer::token::e_eq );
add_invalid_set1(lexer::token::e_comma );
add_invalid_set1(lexer::token::e_add );
add_invalid_set1(lexer::token::e_sub );
add_invalid_set1(lexer::token::e_div );
add_invalid_set1(lexer::token::e_mul );
add_invalid_set1(lexer::token::e_mod );
add_invalid_set1(lexer::token::e_pow );
add_invalid_set1(lexer::token::e_colon );
add_invalid_set1(lexer::token::e_ternary);
}
bool result()
{
return error_list_.empty();
}
bool operator() (const lexer::token& t0, const lexer::token& t1)
{
const set_t::value_type p = std::make_pair(t0.type,t1.type);
if (invalid_bracket_check(t0.type,t1.type))
{
error_list_.push_back(std::make_pair(t0,t1));
}
else if (invalid_comb_.find(p) != invalid_comb_.end())
{
error_list_.push_back(std::make_pair(t0,t1));
}
return true;
}
std::size_t error_count() const
{
return error_list_.size();
}
std::pair<lexer::token,lexer::token> error(const std::size_t index)
{
if (index < error_list_.size())
{
return error_list_[index];
}
else
{
static const lexer::token error_token;
return std::make_pair(error_token,error_token);
}
}
void clear_errors()
{
error_list_.clear();
}
private:
void add_invalid(const lexer::token::token_type base, const lexer::token::token_type t)
{
invalid_comb_.insert(std::make_pair(base,t));
}
void add_invalid_set1(const lexer::token::token_type t)
{
add_invalid(t, lexer::token::e_assign);
add_invalid(t, lexer::token::e_shr );
add_invalid(t, lexer::token::e_shl );
add_invalid(t, lexer::token::e_lte );
add_invalid(t, lexer::token::e_ne );
add_invalid(t, lexer::token::e_gte );
add_invalid(t, lexer::token::e_lt );
add_invalid(t, lexer::token::e_gt );
add_invalid(t, lexer::token::e_eq );
add_invalid(t, lexer::token::e_comma );
add_invalid(t, lexer::token::e_div );
add_invalid(t, lexer::token::e_mul );
add_invalid(t, lexer::token::e_mod );
add_invalid(t, lexer::token::e_pow );
add_invalid(t, lexer::token::e_colon );
}
bool invalid_bracket_check(const lexer::token::token_type base, const lexer::token::token_type t)
{
if (details::is_right_bracket(static_cast<details::char_t>(base)))
{
switch (t)
{
case lexer::token::e_assign : return (']' != base);
case lexer::token::e_string : return (')' != base);
default : return false;
}
}
else if (details::is_left_bracket(static_cast<details::char_t>(base)))
{
if (details::is_right_bracket(static_cast<details::char_t>(t)))
return false;
else if (details::is_left_bracket(static_cast<details::char_t>(t)))
return false;
else
{
switch (t)
{
case lexer::token::e_number : return false;
case lexer::token::e_symbol : return false;
case lexer::token::e_string : return false;
case lexer::token::e_add : return false;
case lexer::token::e_sub : return false;
case lexer::token::e_colon : return false;
case lexer::token::e_ternary : return false;
default : return true ;
}
}
}
else if (details::is_right_bracket(static_cast<details::char_t>(t)))
{
switch (base)
{
case lexer::token::e_number : return false;
case lexer::token::e_symbol : return false;
case lexer::token::e_string : return false;
case lexer::token::e_eof : return false;
case lexer::token::e_colon : return false;
case lexer::token::e_ternary : return false;
default : return true ;
}
}
else if (details::is_left_bracket(static_cast<details::char_t>(t)))
{
switch (base)
{
case lexer::token::e_rbracket : return true;
case lexer::token::e_rsqrbracket : return true;
case lexer::token::e_rcrlbracket : return true;
default : return false;
}
}
return false;
}
set_t invalid_comb_;
std::vector<std::pair<lexer::token,lexer::token> > error_list_;
};
class sequence_validator_3tokens exprtk_final : public lexer::token_scanner
{
private:
typedef lexer::token::token_type token_t;
typedef std::pair<token_t,std::pair<token_t,token_t> > token_triplet_t;
typedef std::set<token_triplet_t> set_t;
public:
using lexer::token_scanner::operator();
sequence_validator_3tokens()
: lexer::token_scanner(3)
{
add_invalid(lexer::token::e_number , lexer::token::e_number , lexer::token::e_number);
add_invalid(lexer::token::e_string , lexer::token::e_string , lexer::token::e_string);
add_invalid(lexer::token::e_comma , lexer::token::e_comma , lexer::token::e_comma );
add_invalid(lexer::token::e_add , lexer::token::e_add , lexer::token::e_add );
add_invalid(lexer::token::e_sub , lexer::token::e_sub , lexer::token::e_sub );
add_invalid(lexer::token::e_div , lexer::token::e_div , lexer::token::e_div );
add_invalid(lexer::token::e_mul , lexer::token::e_mul , lexer::token::e_mul );
add_invalid(lexer::token::e_mod , lexer::token::e_mod , lexer::token::e_mod );
add_invalid(lexer::token::e_pow , lexer::token::e_pow , lexer::token::e_pow );
add_invalid(lexer::token::e_add , lexer::token::e_sub , lexer::token::e_add );
add_invalid(lexer::token::e_sub , lexer::token::e_add , lexer::token::e_sub );
add_invalid(lexer::token::e_div , lexer::token::e_mul , lexer::token::e_div );
add_invalid(lexer::token::e_mul , lexer::token::e_div , lexer::token::e_mul );
add_invalid(lexer::token::e_mod , lexer::token::e_pow , lexer::token::e_mod );
add_invalid(lexer::token::e_pow , lexer::token::e_mod , lexer::token::e_pow );
}
bool result()
{
return error_list_.empty();
}
bool operator() (const lexer::token& t0, const lexer::token& t1, const lexer::token& t2)
{
const set_t::value_type p = std::make_pair(t0.type,std::make_pair(t1.type,t2.type));
if (invalid_comb_.find(p) != invalid_comb_.end())
{
error_list_.push_back(std::make_pair(t0,t1));
}
return true;
}
std::size_t error_count() const
{
return error_list_.size();
}
std::pair<lexer::token,lexer::token> error(const std::size_t index)
{
if (index < error_list_.size())
{
return error_list_[index];
}
else
{
static const lexer::token error_token;
return std::make_pair(error_token,error_token);
}
}
void clear_errors()
{
error_list_.clear();
}
private:
void add_invalid(const token_t t0, const token_t t1, const token_t t2)
{
invalid_comb_.insert(std::make_pair(t0,std::make_pair(t1,t2)));
}
set_t invalid_comb_;
std::vector<std::pair<lexer::token,lexer::token> > error_list_;
};
struct helper_assembly
{
inline bool register_scanner(lexer::token_scanner* scanner)
{
if (token_scanner_list.end() != std::find(token_scanner_list.begin(),
token_scanner_list.end (),
scanner))
{
return false;
}
token_scanner_list.push_back(scanner);
return true;
}
inline bool register_modifier(lexer::token_modifier* modifier)
{
if (token_modifier_list.end() != std::find(token_modifier_list.begin(),
token_modifier_list.end (),
modifier))
{
return false;
}
token_modifier_list.push_back(modifier);
return true;
}
inline bool register_joiner(lexer::token_joiner* joiner)
{
if (token_joiner_list.end() != std::find(token_joiner_list.begin(),
token_joiner_list.end (),
joiner))
{
return false;
}
token_joiner_list.push_back(joiner);
return true;
}
inline bool register_inserter(lexer::token_inserter* inserter)
{
if (token_inserter_list.end() != std::find(token_inserter_list.begin(),
token_inserter_list.end (),
inserter))
{
return false;
}
token_inserter_list.push_back(inserter);
return true;
}
inline bool run_modifiers(lexer::generator& g)
{
error_token_modifier = reinterpret_cast<lexer::token_modifier*>(0);
for (std::size_t i = 0; i < token_modifier_list.size(); ++i)
{
lexer::token_modifier& modifier = (*token_modifier_list[i]);
modifier.reset();
modifier.process(g);
if (!modifier.result())
{
error_token_modifier = token_modifier_list[i];
return false;
}
}
return true;
}
inline bool run_joiners(lexer::generator& g)
{
error_token_joiner = reinterpret_cast<lexer::token_joiner*>(0);
for (std::size_t i = 0; i < token_joiner_list.size(); ++i)
{
lexer::token_joiner& joiner = (*token_joiner_list[i]);
joiner.reset();
joiner.process(g);
if (!joiner.result())
{
error_token_joiner = token_joiner_list[i];
return false;
}
}
return true;
}
inline bool run_inserters(lexer::generator& g)
{
error_token_inserter = reinterpret_cast<lexer::token_inserter*>(0);
for (std::size_t i = 0; i < token_inserter_list.size(); ++i)
{
lexer::token_inserter& inserter = (*token_inserter_list[i]);
inserter.reset();
inserter.process(g);
if (!inserter.result())
{
error_token_inserter = token_inserter_list[i];
return false;
}
}
return true;
}
inline bool run_scanners(lexer::generator& g)
{
error_token_scanner = reinterpret_cast<lexer::token_scanner*>(0);
for (std::size_t i = 0; i < token_scanner_list.size(); ++i)
{
lexer::token_scanner& scanner = (*token_scanner_list[i]);
scanner.reset();
scanner.process(g);
if (!scanner.result())
{
error_token_scanner = token_scanner_list[i];
return false;
}
}
return true;
}
std::vector<lexer::token_scanner*> token_scanner_list;
std::vector<lexer::token_modifier*> token_modifier_list;
std::vector<lexer::token_joiner*> token_joiner_list;
std::vector<lexer::token_inserter*> token_inserter_list;
lexer::token_scanner* error_token_scanner;
lexer::token_modifier* error_token_modifier;
lexer::token_joiner* error_token_joiner;
lexer::token_inserter* error_token_inserter;
};
}
class parser_helper
{
public:
typedef token token_t;
typedef generator generator_t;
inline bool init(const std::string& str)
{
if (!lexer_.process(str))
{
return false;
}
lexer_.begin();
next_token();
return true;
}
inline generator_t& lexer()
{
return lexer_;
}
inline const generator_t& lexer() const
{
return lexer_;
}
inline void store_token()
{
lexer_.store();
store_current_token_ = current_token_;
}
inline void restore_token()
{
lexer_.restore();
current_token_ = store_current_token_;
}
inline void next_token()
{
current_token_ = lexer_.next_token();
}
inline const token_t& current_token() const
{
return current_token_;
}
enum token_advance_mode
{
e_hold = 0,
e_advance = 1
};
inline void advance_token(const token_advance_mode mode)
{
if (e_advance == mode)
{
next_token();
}
}
inline bool token_is(const token_t::token_type& ttype, const token_advance_mode mode = e_advance)
{
if (current_token().type != ttype)
{
return false;
}
advance_token(mode);
return true;
}
inline bool token_is(const token_t::token_type& ttype,
const std::string& value,
const token_advance_mode mode = e_advance)
{
if (
(current_token().type != ttype) ||
!exprtk::details::imatch(value,current_token().value)
)
{
return false;
}
advance_token(mode);
return true;
}
inline bool peek_token_is(const token_t::token_type& ttype)
{
return (lexer_.peek_next_token().type == ttype);
}
inline bool peek_token_is(const std::string& s)
{
return (exprtk::details::imatch(lexer_.peek_next_token().value,s));
}
private:
generator_t lexer_;
token_t current_token_;
token_t store_current_token_;
};
}
template <typename T>
class vector_view
{
public:
typedef T* data_ptr_t;
vector_view(data_ptr_t data, const std::size_t& size)
: size_(size)
, data_(data)
, data_ref_(0)
{}
vector_view(const vector_view<T>& vv)
: size_(vv.size_)
, data_(vv.data_)
, data_ref_(0)
{}
inline void rebase(data_ptr_t data)
{
data_ = data;
if (!data_ref_.empty())
{
for (std::size_t i = 0; i < data_ref_.size(); ++i)
{
(*data_ref_[i]) = data;
}
}
}
inline data_ptr_t data() const
{
return data_;
}
inline std::size_t size() const
{
return size_;
}
inline const T& operator[](const std::size_t index) const
{
return data_[index];
}
inline T& operator[](const std::size_t index)
{
return data_[index];
}
void set_ref(data_ptr_t* data_ref)
{
data_ref_.push_back(data_ref);
}
private:
const std::size_t size_;
data_ptr_t data_;
std::vector<data_ptr_t*> data_ref_;
};
template <typename T>
inline vector_view<T> make_vector_view(T* data,
const std::size_t size, const std::size_t offset = 0)
{
return vector_view<T>(data + offset, size);
}
template <typename T>
inline vector_view<T> make_vector_view(std::vector<T>& v,
const std::size_t size, const std::size_t offset = 0)
{
return vector_view<T>(v.data() + offset, size);
}
template <typename T> class results_context;
template <typename T>
struct type_store
{
enum store_type
{
e_unknown,
e_scalar ,
e_vector ,
e_string
};
type_store()
: data(0)
, size(0)
, type(e_unknown)
{}
union
{
void* data;
T* vec_data;
};
std::size_t size;
store_type type;
class parameter_list
{
public:
explicit parameter_list(std::vector<type_store>& pl)
: parameter_list_(pl)
{}
inline bool empty() const
{
return parameter_list_.empty();
}
inline std::size_t size() const
{
return parameter_list_.size();
}
inline type_store& operator[](const std::size_t& index)
{
return parameter_list_[index];
}
inline const type_store& operator[](const std::size_t& index) const
{
return parameter_list_[index];
}
inline type_store& front()
{
return parameter_list_[0];
}
inline const type_store& front() const
{
return parameter_list_[0];
}
inline type_store& back()
{
return parameter_list_.back();
}
inline const type_store& back() const
{
return parameter_list_.back();
}
private:
std::vector<type_store>& parameter_list_;
friend class results_context<T>;
};
template <typename ViewType>
struct type_view
{
typedef type_store<T> type_store_t;
typedef ViewType value_t;
explicit type_view(type_store_t& ts)
: ts_(ts)
, data_(reinterpret_cast<value_t*>(ts_.data))
{}
explicit type_view(const type_store_t& ts)
: ts_(const_cast<type_store_t&>(ts))
, data_(reinterpret_cast<value_t*>(ts_.data))
{}
inline std::size_t size() const
{
return ts_.size;
}
inline value_t& operator[](const std::size_t& i)
{
return data_[i];
}
inline const value_t& operator[](const std::size_t& i) const
{
return data_[i];
}
inline const value_t* begin() const { return data_; }
inline value_t* begin() { return data_; }
inline const value_t* end() const
{
return static_cast<value_t*>(data_ + ts_.size);
}
inline value_t* end()
{
return static_cast<value_t*>(data_ + ts_.size);
}
type_store_t& ts_;
value_t* data_;
};
typedef type_view<T> vector_view;
typedef type_view<char> string_view;
struct scalar_view
{
typedef type_store<T> type_store_t;
typedef T value_t;
explicit scalar_view(type_store_t& ts)
: v_(*reinterpret_cast<value_t*>(ts.data))
{}
explicit scalar_view(const type_store_t& ts)
: v_(*reinterpret_cast<value_t*>(const_cast<type_store_t&>(ts).data))
{}
inline value_t& operator() ()
{
return v_;
}
inline const value_t& operator() () const
{
return v_;
}
template <typename IntType>
inline bool to_int(IntType& i) const
{
if (!exprtk::details::numeric::is_integer(v_))
return false;
i = static_cast<IntType>(v_);
return true;
}
template <typename UIntType>
inline bool to_uint(UIntType& u) const
{
if (v_ < T(0))
return false;
else if (!exprtk::details::numeric::is_integer(v_))
return false;
u = static_cast<UIntType>(v_);
return true;
}
T& v_;
};
};
template <typename StringView>
inline std::string to_str(const StringView& view)
{
return std::string(view.begin(),view.size());
}
#ifndef exprtk_disable_return_statement
namespace details
{
template <typename T> class return_node;
template <typename T> class return_envelope_node;
}
#endif
template <typename T>
class results_context
{
public:
typedef type_store<T> type_store_t;
results_context()
: results_available_(false)
{}
inline std::size_t count() const
{
if (results_available_)
return parameter_list_.size();
else
return 0;
}
inline type_store_t& operator[](const std::size_t& index)
{
return parameter_list_[index];
}
inline const type_store_t& operator[](const std::size_t& index) const
{
return parameter_list_[index];
}
private:
inline void clear()
{
results_available_ = false;
}
typedef std::vector<type_store_t> ts_list_t;
typedef typename type_store_t::parameter_list parameter_list_t;
inline void assign(const parameter_list_t& pl)
{
parameter_list_ = pl.parameter_list_;
results_available_ = true;
}
bool results_available_;
ts_list_t parameter_list_;
#ifndef exprtk_disable_return_statement
friend class details::return_node<T>;
friend class details::return_envelope_node<T>;
#endif
};
namespace details
{
enum operator_type
{
e_default , e_null , e_add , e_sub ,
e_mul , e_div , e_mod , e_pow ,
e_atan2 , e_min , e_max , e_avg ,
e_sum , e_prod , e_lt , e_lte ,
e_eq , e_equal , e_ne , e_nequal ,
e_gte , e_gt , e_and , e_nand ,
e_or , e_nor , e_xor , e_xnor ,
e_mand , e_mor , e_scand , e_scor ,
e_shr , e_shl , e_abs , e_acos ,
e_acosh , e_asin , e_asinh , e_atan ,
e_atanh , e_ceil , e_cos , e_cosh ,
e_exp , e_expm1 , e_floor , e_log ,
e_log10 , e_log2 , e_log1p , e_logn ,
e_neg , e_pos , e_round , e_roundn ,
e_root , e_sqrt , e_sin , e_sinc ,
e_sinh , e_sec , e_csc , e_tan ,
e_tanh , e_cot , e_clamp , e_iclamp ,
e_inrange , e_sgn , e_r2d , e_d2r ,
e_d2g , e_g2d , e_hypot , e_notl ,
e_erf , e_erfc , e_ncdf , e_frac ,
e_trunc , e_assign , e_addass , e_subass ,
e_mulass , e_divass , e_modass , e_in ,
e_like , e_ilike , e_multi , e_smulti ,
e_swap ,
// Do not add new functions/operators after this point.
e_sf00 = 1000, e_sf01 = 1001, e_sf02 = 1002, e_sf03 = 1003,
e_sf04 = 1004, e_sf05 = 1005, e_sf06 = 1006, e_sf07 = 1007,
e_sf08 = 1008, e_sf09 = 1009, e_sf10 = 1010, e_sf11 = 1011,
e_sf12 = 1012, e_sf13 = 1013, e_sf14 = 1014, e_sf15 = 1015,
e_sf16 = 1016, e_sf17 = 1017, e_sf18 = 1018, e_sf19 = 1019,
e_sf20 = 1020, e_sf21 = 1021, e_sf22 = 1022, e_sf23 = 1023,
e_sf24 = 1024, e_sf25 = 1025, e_sf26 = 1026, e_sf27 = 1027,
e_sf28 = 1028, e_sf29 = 1029, e_sf30 = 1030, e_sf31 = 1031,
e_sf32 = 1032, e_sf33 = 1033, e_sf34 = 1034, e_sf35 = 1035,
e_sf36 = 1036, e_sf37 = 1037, e_sf38 = 1038, e_sf39 = 1039,
e_sf40 = 1040, e_sf41 = 1041, e_sf42 = 1042, e_sf43 = 1043,
e_sf44 = 1044, e_sf45 = 1045, e_sf46 = 1046, e_sf47 = 1047,
e_sf48 = 1048, e_sf49 = 1049, e_sf50 = 1050, e_sf51 = 1051,
e_sf52 = 1052, e_sf53 = 1053, e_sf54 = 1054, e_sf55 = 1055,
e_sf56 = 1056, e_sf57 = 1057, e_sf58 = 1058, e_sf59 = 1059,
e_sf60 = 1060, e_sf61 = 1061, e_sf62 = 1062, e_sf63 = 1063,
e_sf64 = 1064, e_sf65 = 1065, e_sf66 = 1066, e_sf67 = 1067,
e_sf68 = 1068, e_sf69 = 1069, e_sf70 = 1070, e_sf71 = 1071,
e_sf72 = 1072, e_sf73 = 1073, e_sf74 = 1074, e_sf75 = 1075,
e_sf76 = 1076, e_sf77 = 1077, e_sf78 = 1078, e_sf79 = 1079,
e_sf80 = 1080, e_sf81 = 1081, e_sf82 = 1082, e_sf83 = 1083,
e_sf84 = 1084, e_sf85 = 1085, e_sf86 = 1086, e_sf87 = 1087,
e_sf88 = 1088, e_sf89 = 1089, e_sf90 = 1090, e_sf91 = 1091,
e_sf92 = 1092, e_sf93 = 1093, e_sf94 = 1094, e_sf95 = 1095,
e_sf96 = 1096, e_sf97 = 1097, e_sf98 = 1098, e_sf99 = 1099,
e_sffinal = 1100,
e_sf4ext00 = 2000, e_sf4ext01 = 2001, e_sf4ext02 = 2002, e_sf4ext03 = 2003,
e_sf4ext04 = 2004, e_sf4ext05 = 2005, e_sf4ext06 = 2006, e_sf4ext07 = 2007,
e_sf4ext08 = 2008, e_sf4ext09 = 2009, e_sf4ext10 = 2010, e_sf4ext11 = 2011,
e_sf4ext12 = 2012, e_sf4ext13 = 2013, e_sf4ext14 = 2014, e_sf4ext15 = 2015,
e_sf4ext16 = 2016, e_sf4ext17 = 2017, e_sf4ext18 = 2018, e_sf4ext19 = 2019,
e_sf4ext20 = 2020, e_sf4ext21 = 2021, e_sf4ext22 = 2022, e_sf4ext23 = 2023,
e_sf4ext24 = 2024, e_sf4ext25 = 2025, e_sf4ext26 = 2026, e_sf4ext27 = 2027,
e_sf4ext28 = 2028, e_sf4ext29 = 2029, e_sf4ext30 = 2030, e_sf4ext31 = 2031,
e_sf4ext32 = 2032, e_sf4ext33 = 2033, e_sf4ext34 = 2034, e_sf4ext35 = 2035,
e_sf4ext36 = 2036, e_sf4ext37 = 2037, e_sf4ext38 = 2038, e_sf4ext39 = 2039,
e_sf4ext40 = 2040, e_sf4ext41 = 2041, e_sf4ext42 = 2042, e_sf4ext43 = 2043,
e_sf4ext44 = 2044, e_sf4ext45 = 2045, e_sf4ext46 = 2046, e_sf4ext47 = 2047,
e_sf4ext48 = 2048, e_sf4ext49 = 2049, e_sf4ext50 = 2050, e_sf4ext51 = 2051,
e_sf4ext52 = 2052, e_sf4ext53 = 2053, e_sf4ext54 = 2054, e_sf4ext55 = 2055,
e_sf4ext56 = 2056, e_sf4ext57 = 2057, e_sf4ext58 = 2058, e_sf4ext59 = 2059,
e_sf4ext60 = 2060, e_sf4ext61 = 2061
};
inline std::string to_str(const operator_type opr)
{
switch (opr)
{
case e_add : return "+" ;
case e_sub : return "-" ;
case e_mul : return "*" ;
case e_div : return "/" ;
case e_mod : return "%" ;
case e_pow : return "^" ;
case e_assign : return ":=" ;
case e_addass : return "+=" ;
case e_subass : return "-=" ;
case e_mulass : return "*=" ;
case e_divass : return "/=" ;
case e_modass : return "%=" ;
case e_lt : return "<" ;
case e_lte : return "<=" ;
case e_eq : return "==" ;
case e_equal : return "=" ;
case e_ne : return "!=" ;
case e_nequal : return "<>" ;
case e_gte : return ">=" ;
case e_gt : return ">" ;
case e_and : return "and" ;
case e_or : return "or" ;
case e_xor : return "xor" ;
case e_nand : return "nand";
case e_nor : return "nor" ;
case e_xnor : return "xnor";
default : return "N/A" ;
}
}
struct base_operation_t
{
base_operation_t(const operator_type t, const unsigned int& np)
: type(t)
, num_params(np)
{}
operator_type type;
unsigned int num_params;
};
namespace loop_unroll
{
#ifndef exprtk_disable_superscalar_unroll
const unsigned int global_loop_batch_size = 16;
#else
const unsigned int global_loop_batch_size = 4;
#endif
struct details
{
explicit details(const std::size_t& vsize,
const unsigned int loop_batch_size = global_loop_batch_size)
: batch_size(loop_batch_size )
, remainder (vsize % batch_size)
, upper_bound(static_cast<int>(vsize - (remainder ? loop_batch_size : 0)))
{}
unsigned int batch_size;
int remainder;
int upper_bound;
};
}
#ifdef exprtk_enable_debugging
inline void dump_ptr(const std::string& s, const void* ptr, const std::size_t size = 0)
{
if (size)
exprtk_debug(("%s - addr: %p size: %d\n",
s.c_str(),
ptr,
static_cast<unsigned int>(size)));
else
exprtk_debug(("%s - addr: %p\n",s.c_str(),ptr));
}
#else
inline void dump_ptr(const std::string&, const void*) {}
inline void dump_ptr(const std::string&, const void*, const std::size_t) {}
#endif
template <typename T>
class vec_data_store
{
public:
typedef vec_data_store<T> type;
typedef T* data_t;
private:
struct control_block
{
control_block()
: ref_count(1)
, size (0)
, data (0)
, destruct (true)
{}
explicit control_block(const std::size_t& dsize)
: ref_count(1 )
, size (dsize)
, data (0 )
, destruct (true )
{ create_data(); }
control_block(const std::size_t& dsize, data_t dptr, bool dstrct = false)
: ref_count(1 )
, size (dsize )
, data (dptr )
, destruct (dstrct)
{}
~control_block()
{
if (data && destruct && (0 == ref_count))
{
dump_ptr("~vec_data_store::control_block() data",data);
delete[] data;
data = reinterpret_cast<data_t>(0);
}
}
static inline control_block* create(const std::size_t& dsize, data_t data_ptr = data_t(0), bool dstrct = false)
{
if (dsize)
{
if (0 == data_ptr)
return (new control_block(dsize));
else
return (new control_block(dsize, data_ptr, dstrct));
}
else
return (new control_block);
}
static inline void destroy(control_block*& cntrl_blck)
{
if (cntrl_blck)
{
if (
(0 != cntrl_blck->ref_count) &&
(0 == --cntrl_blck->ref_count)
)
{
delete cntrl_blck;
}
cntrl_blck = 0;
}
}
std::size_t ref_count;
std::size_t size;
data_t data;
bool destruct;
private:
control_block(const control_block&) exprtk_delete;
control_block& operator=(const control_block&) exprtk_delete;
inline void create_data()
{
destruct = true;
data = new T[size];
std::fill_n(data, size, T(0));
dump_ptr("control_block::create_data() - data", data, size);
}
};
public:
vec_data_store()
: control_block_(control_block::create(0))
{}
explicit vec_data_store(const std::size_t& size)
: control_block_(control_block::create(size,reinterpret_cast<data_t>(0),true))
{}
vec_data_store(const std::size_t& size, data_t data, bool dstrct = false)
: control_block_(control_block::create(size, data, dstrct))
{}
vec_data_store(const type& vds)
{
control_block_ = vds.control_block_;
control_block_->ref_count++;
}
~vec_data_store()
{
control_block::destroy(control_block_);
}
type& operator=(const type& vds)
{
if (this != &vds)
{
std::size_t final_size = min_size(control_block_, vds.control_block_);
vds.control_block_->size = final_size;
control_block_->size = final_size;
if (control_block_->destruct || (0 == control_block_->data))
{
control_block::destroy(control_block_);
control_block_ = vds.control_block_;
control_block_->ref_count++;
}
}
return (*this);
}
inline data_t data()
{
return control_block_->data;
}
inline data_t data() const
{
return control_block_->data;
}
inline std::size_t size() const
{
return control_block_->size;
}
inline data_t& ref()
{
return control_block_->data;
}
inline void dump() const
{
#ifdef exprtk_enable_debugging
exprtk_debug(("size: %d\taddress:%p\tdestruct:%c\n",
size(),
data(),
(control_block_->destruct ? 'T' : 'F')));
for (std::size_t i = 0; i < size(); ++i)
{
if (5 == i)
exprtk_debug(("\n"));
exprtk_debug(("%15.10f ",data()[i]));
}
exprtk_debug(("\n"));
#endif
}
static inline void match_sizes(type& vds0, type& vds1)
{
const std::size_t size = min_size(vds0.control_block_,vds1.control_block_);
vds0.control_block_->size = size;
vds1.control_block_->size = size;
}
private:
static inline std::size_t min_size(const control_block* cb0, const control_block* cb1)
{
const std::size_t size0 = cb0->size;
const std::size_t size1 = cb1->size;
if (size0 && size1)
return std::min(size0,size1);
else
return (size0) ? size0 : size1;
}
control_block* control_block_;
};
namespace numeric
{
namespace details
{
template <typename T>
inline T process_impl(const operator_type operation, const T arg)
{
switch (operation)
{
case e_abs : return numeric::abs (arg);
case e_acos : return numeric::acos (arg);
case e_acosh : return numeric::acosh(arg);
case e_asin : return numeric::asin (arg);
case e_asinh : return numeric::asinh(arg);
case e_atan : return numeric::atan (arg);
case e_atanh : return numeric::atanh(arg);
case e_ceil : return numeric::ceil (arg);
case e_cos : return numeric::cos (arg);
case e_cosh : return numeric::cosh (arg);
case e_exp : return numeric::exp (arg);
case e_expm1 : return numeric::expm1(arg);
case e_floor : return numeric::floor(arg);
case e_log : return numeric::log (arg);
case e_log10 : return numeric::log10(arg);
case e_log2 : return numeric::log2 (arg);
case e_log1p : return numeric::log1p(arg);
case e_neg : return numeric::neg (arg);
case e_pos : return numeric::pos (arg);
case e_round : return numeric::round(arg);
case e_sin : return numeric::sin (arg);
case e_sinc : return numeric::sinc (arg);
case e_sinh : return numeric::sinh (arg);
case e_sqrt : return numeric::sqrt (arg);
case e_tan : return numeric::tan (arg);
case e_tanh : return numeric::tanh (arg);
case e_cot : return numeric::cot (arg);
case e_sec : return numeric::sec (arg);
case e_csc : return numeric::csc (arg);
case e_r2d : return numeric::r2d (arg);
case e_d2r : return numeric::d2r (arg);
case e_d2g : return numeric::d2g (arg);
case e_g2d : return numeric::g2d (arg);
case e_notl : return numeric::notl (arg);
case e_sgn : return numeric::sgn (arg);
case e_erf : return numeric::erf (arg);
case e_erfc : return numeric::erfc (arg);
case e_ncdf : return numeric::ncdf (arg);
case e_frac : return numeric::frac (arg);
case e_trunc : return numeric::trunc(arg);
default : exprtk_debug(("numeric::details::process_impl<T> - Invalid unary operation.\n"));
return std::numeric_limits<T>::quiet_NaN();
}
}
template <typename T>
inline T process_impl(const operator_type operation, const T arg0, const T arg1)
{
switch (operation)
{
case e_add : return (arg0 + arg1);
case e_sub : return (arg0 - arg1);
case e_mul : return (arg0 * arg1);
case e_div : return (arg0 / arg1);
case e_mod : return modulus<T>(arg0,arg1);
case e_pow : return pow<T>(arg0,arg1);
case e_atan2 : return atan2<T>(arg0,arg1);
case e_min : return std::min<T>(arg0,arg1);
case e_max : return std::max<T>(arg0,arg1);
case e_logn : return logn<T>(arg0,arg1);
case e_lt : return (arg0 < arg1) ? T(1) : T(0);
case e_lte : return (arg0 <= arg1) ? T(1) : T(0);
case e_eq : return std::equal_to<T>()(arg0,arg1) ? T(1) : T(0);
case e_ne : return std::not_equal_to<T>()(arg0,arg1) ? T(1) : T(0);
case e_gte : return (arg0 >= arg1) ? T(1) : T(0);
case e_gt : return (arg0 > arg1) ? T(1) : T(0);
case e_and : return and_opr <T>(arg0,arg1);
case e_nand : return nand_opr<T>(arg0,arg1);
case e_or : return or_opr <T>(arg0,arg1);
case e_nor : return nor_opr <T>(arg0,arg1);
case e_xor : return xor_opr <T>(arg0,arg1);
case e_xnor : return xnor_opr<T>(arg0,arg1);
case e_root : return root <T>(arg0,arg1);
case e_roundn : return roundn <T>(arg0,arg1);
case e_equal : return equal (arg0,arg1);
case e_nequal : return nequal (arg0,arg1);
case e_hypot : return hypot <T>(arg0,arg1);
case e_shr : return shr <T>(arg0,arg1);
case e_shl : return shl <T>(arg0,arg1);
default : exprtk_debug(("numeric::details::process_impl<T> - Invalid binary operation.\n"));
return std::numeric_limits<T>::quiet_NaN();
}
}
template <typename T>
inline T process_impl(const operator_type operation, const T arg0, const T arg1, int_type_tag)
{
switch (operation)
{
case e_add : return (arg0 + arg1);
case e_sub : return (arg0 - arg1);
case e_mul : return (arg0 * arg1);
case e_div : return (arg0 / arg1);
case e_mod : return arg0 % arg1;
case e_pow : return pow<T>(arg0,arg1);
case e_min : return std::min<T>(arg0,arg1);
case e_max : return std::max<T>(arg0,arg1);
case e_logn : return logn<T>(arg0,arg1);
case e_lt : return (arg0 < arg1) ? T(1) : T(0);
case e_lte : return (arg0 <= arg1) ? T(1) : T(0);
case e_eq : return (arg0 == arg1) ? T(1) : T(0);
case e_ne : return (arg0 != arg1) ? T(1) : T(0);
case e_gte : return (arg0 >= arg1) ? T(1) : T(0);
case e_gt : return (arg0 > arg1) ? T(1) : T(0);
case e_and : return ((arg0 != T(0)) && (arg1 != T(0))) ? T(1) : T(0);
case e_nand : return ((arg0 != T(0)) && (arg1 != T(0))) ? T(0) : T(1);
case e_or : return ((arg0 != T(0)) || (arg1 != T(0))) ? T(1) : T(0);
case e_nor : return ((arg0 != T(0)) || (arg1 != T(0))) ? T(0) : T(1);
case e_xor : return arg0 ^ arg1;
case e_xnor : return !(arg0 ^ arg1);
case e_root : return root<T>(arg0,arg1);
case e_equal : return arg0 == arg1;
case e_nequal : return arg0 != arg1;
case e_hypot : return hypot<T>(arg0,arg1);
case e_shr : return arg0 >> arg1;
case e_shl : return arg0 << arg1;
default : exprtk_debug(("numeric::details::process_impl<IntType> - Invalid binary operation.\n"));
return std::numeric_limits<T>::quiet_NaN();
}
}
}
template <typename T>
inline T process(const operator_type operation, const T arg)
{
return exprtk::details::numeric::details::process_impl(operation,arg);
}
template <typename T>
inline T process(const operator_type operation, const T arg0, const T arg1)
{
return exprtk::details::numeric::details::process_impl(operation, arg0, arg1);
}
}
template <typename Node>
struct node_collector_interface
{
typedef Node* node_ptr_t;
typedef Node** node_pp_t;
typedef std::vector<node_pp_t> noderef_list_t;
virtual ~node_collector_interface() {}
virtual void collect_nodes(noderef_list_t&) {}
};
template <typename Node>
struct node_depth_base;
template <typename T>
class expression_node : public node_collector_interface<expression_node<T> >,
public node_depth_base<expression_node<T> >
{
public:
enum node_type
{
e_none , e_null , e_constant , e_unary ,
e_binary , e_binary_ext , e_trinary , e_quaternary ,
e_vararg , e_conditional , e_while , e_repeat ,
e_for , e_switch , e_mswitch , e_return ,
e_retenv , e_variable , e_stringvar , e_stringconst ,
e_stringvarrng , e_cstringvarrng , e_strgenrange , e_strconcat ,
e_stringvarsize , e_strswap , e_stringsize , e_stringvararg ,
e_function , e_vafunction , e_genfunction , e_strfunction ,
e_strcondition , e_strccondition , e_add , e_sub ,
e_mul , e_div , e_mod , e_pow ,
e_lt , e_lte , e_gt , e_gte ,
e_eq , e_ne , e_and , e_nand ,
e_or , e_nor , e_xor , e_xnor ,
e_in , e_like , e_ilike , e_inranges ,
e_ipow , e_ipowinv , e_abs , e_acos ,
e_acosh , e_asin , e_asinh , e_atan ,
e_atanh , e_ceil , e_cos , e_cosh ,
e_exp , e_expm1 , e_floor , e_log ,
e_log10 , e_log2 , e_log1p , e_neg ,
e_pos , e_round , e_sin , e_sinc ,
e_sinh , e_sqrt , e_tan , e_tanh ,
e_cot , e_sec , e_csc , e_r2d ,
e_d2r , e_d2g , e_g2d , e_notl ,
e_sgn , e_erf , e_erfc , e_ncdf ,
e_frac , e_trunc , e_uvouv , e_vov ,
e_cov , e_voc , e_vob , e_bov ,
e_cob , e_boc , e_vovov , e_vovoc ,
e_vocov , e_covov , e_covoc , e_vovovov ,
e_vovovoc , e_vovocov , e_vocovov , e_covovov ,
e_covocov , e_vocovoc , e_covovoc , e_vococov ,
e_sf3ext , e_sf4ext , e_nulleq , e_strass ,
e_vector , e_vecelem , e_rbvecelem , e_rbveccelem ,
e_vecdefass , e_vecvalass , e_vecvecass , e_vecopvalass ,
e_vecopvecass , e_vecfunc , e_vecvecswap , e_vecvecineq ,
e_vecvalineq , e_valvecineq , e_vecvecarith , e_vecvalarith ,
e_valvecarith , e_vecunaryop , e_vecondition , e_break ,
e_continue , e_swap
};
typedef T value_type;
typedef expression_node<T>* expression_ptr;
typedef node_collector_interface<expression_node<T> > nci_t;
typedef typename nci_t::noderef_list_t noderef_list_t;
typedef node_depth_base<expression_node<T> > ndb_t;
virtual ~expression_node() {}
inline virtual T value() const
{
return std::numeric_limits<T>::quiet_NaN();
}
inline virtual expression_node<T>* branch(const std::size_t& index = 0) const
{
return reinterpret_cast<expression_ptr>(index * 0);
}
inline virtual node_type type() const
{
return e_none;
}
}; // class expression_node
template <typename T>
inline bool is_generally_string_node(const expression_node<T>* node);
inline bool is_true(const double v)
{
return std::not_equal_to<double>()(0.0,v);
}
inline bool is_true(const long double v)
{
return std::not_equal_to<long double>()(0.0L,v);
}
inline bool is_true(const float v)
{
return std::not_equal_to<float>()(0.0f,v);
}
template <typename T>
inline bool is_true(const expression_node<T>* node)
{
return std::not_equal_to<T>()(T(0),node->value());
}
template <typename T>
inline bool is_true(const std::pair<expression_node<T>*,bool>& node)
{
return std::not_equal_to<T>()(T(0),node.first->value());
}
template <typename T>
inline bool is_false(const expression_node<T>* node)
{
return std::equal_to<T>()(T(0),node->value());
}
template <typename T>
inline bool is_false(const std::pair<expression_node<T>*,bool>& node)
{
return std::equal_to<T>()(T(0),node.first->value());
}
template <typename T>
inline bool is_unary_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_unary == node->type());
}
template <typename T>
inline bool is_neg_unary_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_neg == node->type());
}
template <typename T>
inline bool is_binary_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_binary == node->type());
}
template <typename T>
inline bool is_variable_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_variable == node->type());
}
template <typename T>
inline bool is_ivariable_node(const expression_node<T>* node)
{
return node &&
(
details::expression_node<T>::e_variable == node->type() ||
details::expression_node<T>::e_vecelem == node->type() ||
details::expression_node<T>::e_rbvecelem == node->type() ||
details::expression_node<T>::e_rbveccelem == node->type()
);
}
template <typename T>
inline bool is_vector_elem_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_vecelem == node->type());
}
template <typename T>
inline bool is_rebasevector_elem_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_rbvecelem == node->type());
}
template <typename T>
inline bool is_rebasevector_celem_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_rbveccelem == node->type());
}
template <typename T>
inline bool is_vector_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_vector == node->type());
}
template <typename T>
inline bool is_ivector_node(const expression_node<T>* node)
{
if (node)
{
switch (node->type())
{
case details::expression_node<T>::e_vector :
case details::expression_node<T>::e_vecvalass :
case details::expression_node<T>::e_vecvecass :
case details::expression_node<T>::e_vecopvalass :
case details::expression_node<T>::e_vecopvecass :
case details::expression_node<T>::e_vecvecswap :
case details::expression_node<T>::e_vecvecarith :
case details::expression_node<T>::e_vecvalarith :
case details::expression_node<T>::e_valvecarith :
case details::expression_node<T>::e_vecunaryop :
case details::expression_node<T>::e_vecondition : return true;
default : return false;
}
}
else
return false;
}
template <typename T>
inline bool is_constant_node(const expression_node<T>* node)
{
return node &&
(
details::expression_node<T>::e_constant == node->type() ||
details::expression_node<T>::e_stringconst == node->type()
);
}
template <typename T>
inline bool is_null_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_null == node->type());
}
template <typename T>
inline bool is_break_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_break == node->type());
}
template <typename T>
inline bool is_continue_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_continue == node->type());
}
template <typename T>
inline bool is_swap_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_swap == node->type());
}
template <typename T>
inline bool is_function(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_function == node->type());
}
template <typename T>
inline bool is_return_node(const expression_node<T>* node)
{
return node && (details::expression_node<T>::e_return == node->type());
}
template <typename T> class unary_node;
template <typename T>
inline bool is_negate_node(const expression_node<T>* node)
{
if (node && is_unary_node(node))
{
return (details::e_neg == static_cast<const unary_node<T>*>(node)->operation());
}
else
return false;
}
template <typename T>
inline bool branch_deletable(const expression_node<T>* node)
{
return (0 != node) &&
!is_variable_node(node) &&
!is_string_node (node) ;
}
template <std::size_t N, typename T>
inline bool all_nodes_valid(expression_node<T>* const (&b)[N])
{
for (std::size_t i = 0; i < N; ++i)
{
if (0 == b[i]) return false;
}
return true;
}
template <typename T,
typename Allocator,
template <typename, typename> class Sequence>
inline bool all_nodes_valid(const Sequence<expression_node<T>*,Allocator>& b)
{
for (std::size_t i = 0; i < b.size(); ++i)
{
if (0 == b[i]) return false;
}
return true;
}
template <std::size_t N, typename T>
inline bool all_nodes_variables(expression_node<T>* const (&b)[N])
{
for (std::size_t i = 0; i < N; ++i)
{
if (0 == b[i])
return false;
else if (!is_variable_node(b[i]))
return false;
}
return true;
}
template <typename T,
typename Allocator,
template <typename, typename> class Sequence>
inline bool all_nodes_variables(const Sequence<expression_node<T>*,Allocator>& b)
{
for (std::size_t i = 0; i < b.size(); ++i)
{
if (0 == b[i])
return false;
else if (!is_variable_node(b[i]))
return false;
}
return true;
}
template <typename Node>
class node_collection_destructor
{
public:
typedef node_collector_interface<Node> nci_t;
typedef typename nci_t::node_ptr_t node_ptr_t;
typedef typename nci_t::node_pp_t node_pp_t;
typedef typename nci_t::noderef_list_t noderef_list_t;
static void delete_nodes(node_ptr_t& root)
{
std::vector<node_pp_t> node_delete_list;
node_delete_list.reserve(1000);
collect_nodes(root, node_delete_list);
for (std::size_t i = 0; i < node_delete_list.size(); ++i)
{
node_ptr_t& node = *node_delete_list[i];
exprtk_debug(("ncd::delete_nodes() - deleting: %p\n", static_cast<void*>(node)));
delete node;
node = reinterpret_cast<node_ptr_t>(0);
}
}
private:
static void collect_nodes(node_ptr_t& root, noderef_list_t& node_delete_list)
{
std::deque<node_ptr_t> node_list;
node_list.push_back(root);
node_delete_list.push_back(&root);
noderef_list_t child_node_delete_list;
child_node_delete_list.reserve(1000);
while (!node_list.empty())
{
node_list.front()->collect_nodes(child_node_delete_list);
if (!child_node_delete_list.empty())
{
for (std::size_t i = 0; i < child_node_delete_list.size(); ++i)
{
node_pp_t& node = child_node_delete_list[i];
if (0 == (*node))
{
exprtk_debug(("ncd::collect_nodes() - null node encountered.\n"));
}
node_list.push_back(*node);
}
node_delete_list.insert(
node_delete_list.end(),
child_node_delete_list.begin(), child_node_delete_list.end());
child_node_delete_list.clear();
}
node_list.pop_front();
}
std::reverse(node_delete_list.begin(), node_delete_list.end());
}
};
template <typename NodeAllocator, typename T, std::size_t N>
inline void free_all_nodes(NodeAllocator& node_allocator, expression_node<T>* (&b)[N])
{
for (std::size_t i = 0; i < N; ++i)
{
free_node(node_allocator,b[i]);
}
}
template <typename NodeAllocator,
typename T,
typename Allocator,
template <typename, typename> class Sequence>
inline void free_all_nodes(NodeAllocator& node_allocator, Sequence<expression_node<T>*,Allocator>& b)
{
for (std::size_t i = 0; i < b.size(); ++i)
{
free_node(node_allocator,b[i]);
}
b.clear();
}
template <typename NodeAllocator, typename T>
inline void free_node(NodeAllocator&, expression_node<T>*& node)
{
if ((0 == node) || is_variable_node(node) || is_string_node(node))
{
return;
}
node_collection_destructor<expression_node<T> >
::delete_nodes(node);
}
template <typename T>
inline void destroy_node(expression_node<T>*& node)
{
if (0 != node)
{
node_collection_destructor<expression_node<T> >
::delete_nodes(node);
}
}
template <typename Node>
struct node_depth_base
{
typedef Node* node_ptr_t;
typedef std::pair<node_ptr_t,bool> nb_pair_t;
node_depth_base()
: depth_set(false)
, depth(0)
{}
virtual ~node_depth_base() {}
virtual std::size_t node_depth() const { return 1; }
std::size_t compute_node_depth(const Node* const& node) const
{
if (!depth_set)
{
depth = 1 + (node ? node->node_depth() : 0);
depth_set = true;
}
return depth;
}
std::size_t compute_node_depth(const nb_pair_t& branch) const
{
if (!depth_set)
{
depth = 1 + (branch.first ? branch.first->node_depth() : 0);
depth_set = true;
}
return depth;
}
template <std::size_t N>
std::size_t compute_node_depth(const nb_pair_t (&branch)[N]) const
{
if (!depth_set)
{
depth = 0;
for (std::size_t i = 0; i < N; ++i)
{
if (branch[i].first)
{
depth = std::max(depth,branch[i].first->node_depth());
}
}
depth += 1;
depth_set = true;
}
return depth;
}
template <typename BranchType>
std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1) const
{
if (!depth_set)
{
depth = 1 + std::max(compute_node_depth(n0), compute_node_depth(n1));
depth_set = true;
}
return depth;
}
template <typename BranchType>
std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1,
const BranchType& n2) const
{
if (!depth_set)
{
depth = 1 + std::max(
std::max(compute_node_depth(n0), compute_node_depth(n1)),
compute_node_depth(n2));
depth_set = true;
}
return depth;
}
template <typename BranchType>
std::size_t compute_node_depth(const BranchType& n0, const BranchType& n1,
const BranchType& n2, const BranchType& n3) const
{
if (!depth_set)
{
depth = 1 + std::max(
std::max(compute_node_depth(n0), compute_node_depth(n1)),
std::max(compute_node_depth(n2), compute_node_depth(n3)));
depth_set = true;
}
return depth;
}
template <typename Allocator,
template <typename, typename> class Sequence>
std::size_t compute_node_depth(const Sequence<node_ptr_t, Allocator>& branch_list) const
{
if (!depth_set)
{
for (std::size_t i = 0; i < branch_list.size(); ++i)
{
if (branch_list[i])
{
depth = std::max(depth, compute_node_depth(branch_list[i]));
}
}
depth_set = true;
}
return depth;
}
template <typename Allocator,
template <typename, typename> class Sequence>
std::size_t compute_node_depth(const Sequence<nb_pair_t,Allocator>& branch_list) const
{
if (!depth_set)
{
for (std::size_t i = 0; i < branch_list.size(); ++i)
{
if (branch_list[i].first)
{
depth = std::max(depth, compute_node_depth(branch_list[i].first));
}
}
depth_set = true;
}
return depth;
}
mutable bool depth_set;
mutable std::size_t depth;
template <typename NodeSequence>
void collect(node_ptr_t const& node,
const bool deletable,
NodeSequence& delete_node_list) const
{
if ((0 != node) && deletable)
{
delete_node_list.push_back(const_cast<node_ptr_t*>(&node));
}
}
template <typename NodeSequence>
void collect(const nb_pair_t& branch,
NodeSequence& delete_node_list) const
{
collect(branch.first, branch.second, delete_node_list);
}
template <typename NodeSequence>
void collect(Node*& node,
NodeSequence& delete_node_list) const
{
collect(node, branch_deletable(node), delete_node_list);
}
template <std::size_t N, typename NodeSequence>
void collect(const nb_pair_t(&branch)[N],
NodeSequence& delete_node_list) const
{
for (std::size_t i = 0; i < N; ++i)
{
collect(branch[i].first, branch[i].second, delete_node_list);
}
}
template <typename Allocator,
template <typename, typename> class Sequence,
typename NodeSequence>
void collect(const Sequence<nb_pair_t, Allocator>& branch,
NodeSequence& delete_node_list) const
{
for (std::size_t i = 0; i < branch.size(); ++i)
{
collect(branch[i].first, branch[i].second, delete_node_list);
}
}
template <typename Allocator,
template <typename, typename> class Sequence,
typename NodeSequence>
void collect(const Sequence<node_ptr_t, Allocator>& branch_list,
NodeSequence& delete_node_list) const
{
for (std::size_t i = 0; i < branch_list.size(); ++i)
{
collect(branch_list[i], branch_deletable(branch_list[i]), delete_node_list);
}
}
template <typename Boolean,
typename AllocatorT,
typename AllocatorB,
template <typename, typename> class Sequence,
typename NodeSequence>
void collect(const Sequence<node_ptr_t, AllocatorT>& branch_list,
const Sequence<Boolean, AllocatorB>& branch_deletable_list,
NodeSequence& delete_node_list) const
{
for (std::size_t i = 0; i < branch_list.size(); ++i)
{
collect(branch_list[i], branch_deletable_list[i], delete_node_list);
}
}
};
template <typename Type>
class vector_holder
{
private:
typedef Type value_type;
typedef value_type* value_ptr;
typedef const value_ptr const_value_ptr;
class vector_holder_base
{
public:
virtual ~vector_holder_base() {}
inline value_ptr operator[](const std::size_t& index) const
{
return value_at(index);
}
inline std::size_t size() const
{
return vector_size();
}
inline value_ptr data() const
{
return value_at(0);
}
virtual inline bool rebaseable() const
{
return false;
}
virtual void set_ref(value_ptr*) {}
protected:
virtual value_ptr value_at(const std::size_t&) const = 0;
virtual std::size_t vector_size() const = 0;
};
class array_vector_impl : public vector_holder_base
{
public:
array_vector_impl(const Type* vec, const std::size_t& vec_size)
: vec_(vec)
, size_(vec_size)
{}
protected:
value_ptr value_at(const std::size_t& index) const exprtk_override
{
if (index < size_)
return const_cast<const_value_ptr>(vec_ + index);
else
return const_value_ptr(0);
}
std::size_t vector_size() const exprtk_override
{
return size_;
}
private:
array_vector_impl(const array_vector_impl&) exprtk_delete;
array_vector_impl& operator=(const array_vector_impl&) exprtk_delete;
const Type* vec_;
const std::size_t size_;
};
template <typename Allocator,
template <typename, typename> class Sequence>
class sequence_vector_impl : public vector_holder_base
{
public:
typedef Sequence<Type,Allocator> sequence_t;
explicit sequence_vector_impl(sequence_t& seq)
: sequence_(seq)
{}
protected:
value_ptr value_at(const std::size_t& index) const exprtk_override
{
return (index < sequence_.size()) ? (&sequence_[index]) : const_value_ptr(0);
}
std::size_t vector_size() const exprtk_override
{
return sequence_.size();
}
private:
sequence_vector_impl(const sequence_vector_impl&) exprtk_delete;
sequence_vector_impl& operator=(const sequence_vector_impl&) exprtk_delete;
sequence_t& sequence_;
};
class vector_view_impl : public vector_holder_base
{
public:
typedef exprtk::vector_view<Type> vector_view_t;
vector_view_impl(vector_view_t& vec_view)
: vec_view_(vec_view)
{}
void set_ref(value_ptr* ref)
{
vec_view_.set_ref(ref);
}
virtual inline bool rebaseable() const
{
return true;
}
protected:
value_ptr value_at(const std::size_t& index) const
{
return (index < vec_view_.size()) ? (&vec_view_[index]) : const_value_ptr(0);
}
std::size_t vector_size() const
{
return vec_view_.size();
}
private:
vector_view_impl(const vector_view_impl&) exprtk_delete;
vector_view_impl& operator=(const vector_view_impl&) exprtk_delete;
vector_view_t& vec_view_;
};
public:
typedef typename details::vec_data_store<Type> vds_t;
vector_holder(Type* vec, const std::size_t& vec_size)
: vector_holder_base_(new(buffer)array_vector_impl(vec,vec_size))
{}
explicit vector_holder(const vds_t& vds)
: vector_holder_base_(new(buffer)array_vector_impl(vds.data(),vds.size()))
{}
template <typename Allocator>
explicit vector_holder(std::vector<Type,Allocator>& vec)
: vector_holder_base_(new(buffer)sequence_vector_impl<Allocator,std::vector>(vec))
{}
explicit vector_holder(exprtk::vector_view<Type>& vec)
: vector_holder_base_(new(buffer)vector_view_impl(vec))
{}
inline value_ptr operator[](const std::size_t& index) const
{
return (*vector_holder_base_)[index];
}
inline std::size_t size() const
{
return vector_holder_base_->size();
}
inline value_ptr data() const
{
return vector_holder_base_->data();
}
void set_ref(value_ptr* ref)
{
vector_holder_base_->set_ref(ref);
}
bool rebaseable() const
{
return vector_holder_base_->rebaseable();
}
private:
mutable vector_holder_base* vector_holder_base_;
uchar_t buffer[64];
};
template <typename T>
class null_node exprtk_final : public expression_node<T>
{
public:
inline T value() const exprtk_override
{
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_null;
}
};
template <typename T, std::size_t N>
inline void construct_branch_pair(std::pair<expression_node<T>*,bool> (&branch)[N],
expression_node<T>* b,
const std::size_t& index)
{
if (b && (index < N))
{
branch[index] = std::make_pair(b,branch_deletable(b));
}
}
template <typename T>
inline void construct_branch_pair(std::pair<expression_node<T>*,bool>& branch, expression_node<T>* b)
{
if (b)
{
branch = std::make_pair(b,branch_deletable(b));
}
}
template <std::size_t N, typename T>
inline void init_branches(std::pair<expression_node<T>*,bool> (&branch)[N],
expression_node<T>* b0,
expression_node<T>* b1 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b2 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b3 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b4 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b5 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b6 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b7 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b8 = reinterpret_cast<expression_node<T>*>(0),
expression_node<T>* b9 = reinterpret_cast<expression_node<T>*>(0))
{
construct_branch_pair(branch, b0, 0);
construct_branch_pair(branch, b1, 1);
construct_branch_pair(branch, b2, 2);
construct_branch_pair(branch, b3, 3);
construct_branch_pair(branch, b4, 4);
construct_branch_pair(branch, b5, 5);
construct_branch_pair(branch, b6, 6);
construct_branch_pair(branch, b7, 7);
construct_branch_pair(branch, b8, 8);
construct_branch_pair(branch, b9, 9);
}
template <typename T>
class null_eq_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
explicit null_eq_node(expression_ptr branch, const bool equality = true)
: equality_(equality)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
const T v = branch_.first->value();
const bool result = details::numeric::is_nan(v);
if (result)
return equality_ ? T(1) : T(0);
else
return equality_ ? T(0) : T(1);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_nulleq;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
bool equality_;
branch_t branch_;
};
template <typename T>
class literal_node exprtk_final : public expression_node<T>
{
public:
explicit literal_node(const T& v)
: value_(v)
{}
inline T value() const exprtk_override
{
return value_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_constant;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return reinterpret_cast<expression_node<T>*>(0);
}
private:
literal_node(const literal_node<T>&) exprtk_delete;
literal_node<T>& operator=(const literal_node<T>&) exprtk_delete;
const T value_;
};
template <typename T>
struct range_pack;
template <typename T>
struct range_data_type;
template <typename T>
class range_interface
{
public:
typedef range_pack<T> range_t;
virtual ~range_interface() {}
virtual range_t& range_ref() = 0;
virtual const range_t& range_ref() const = 0;
};
#ifndef exprtk_disable_string_capabilities
template <typename T>
class string_base_node
{
public:
typedef range_data_type<T> range_data_type_t;
virtual ~string_base_node() {}
virtual std::string str () const = 0;
virtual char_cptr base() const = 0;
virtual std::size_t size() const = 0;
};
template <typename T>
class string_literal_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef range_pack<T> range_t;
explicit string_literal_node(const std::string& v)
: value_(v)
{
rp_.n0_c = std::make_pair<bool,std::size_t>(true,0);
rp_.n1_c = std::make_pair<bool,std::size_t>(true,v.size() - 1);
rp_.cache.first = rp_.n0_c.second;
rp_.cache.second = rp_.n1_c.second;
}
inline T value() const exprtk_override
{
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringconst;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return reinterpret_cast<expression_node<T>*>(0);
}
std::string str() const exprtk_override
{
return value_;
}
char_cptr base() const exprtk_override
{
return value_.data();
}
std::size_t size() const exprtk_override
{
return value_.size();
}
range_t& range_ref() exprtk_override
{
return rp_;
}
const range_t& range_ref() const exprtk_override
{
return rp_;
}
private:
string_literal_node(const string_literal_node<T>&) exprtk_delete;
string_literal_node<T>& operator=(const string_literal_node<T>&) exprtk_delete;
const std::string value_;
range_t rp_;
};
#endif
template <typename T>
class unary_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
unary_node(const operator_type& opr, expression_ptr branch)
: operation_(opr)
{
construct_branch_pair(branch_,branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
const T arg = branch_.first->value();
return numeric::process<T>(operation_,arg);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_unary;
}
inline operator_type operation()
{
return operation_;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
inline void release()
{
branch_.second = false;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_final
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
operator_type operation_;
branch_t branch_;
};
template <typename T>
class binary_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
binary_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: operation_(opr)
{
init_branches<2>(branch_, branch0, branch1);
}
inline T value() const exprtk_override
{
assert(branch_[0].first);
assert(branch_[1].first);
const T arg0 = branch_[0].first->value();
const T arg1 = branch_[1].first->value();
return numeric::process<T>(operation_, arg0, arg1);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_binary;
}
inline operator_type operation()
{
return operation_;
}
inline expression_node<T>* branch(const std::size_t& index = 0) const exprtk_override
{
if (0 == index)
return branch_[0].first;
else if (1 == index)
return branch_[1].first;
else
return reinterpret_cast<expression_ptr>(0);
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_final
{
return expression_node<T>::ndb_t::template compute_node_depth<2>(branch_);
}
private:
operator_type operation_;
branch_t branch_[2];
};
template <typename T, typename Operation>
class binary_ext_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
binary_ext_node(expression_ptr branch0, expression_ptr branch1)
{
init_branches<2>(branch_, branch0, branch1);
}
inline T value() const exprtk_override
{
assert(branch_[0].first);
assert(branch_[1].first);
const T arg0 = branch_[0].first->value();
const T arg1 = branch_[1].first->value();
return Operation::process(arg0,arg1);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_binary_ext;
}
inline operator_type operation()
{
return Operation::operation();
}
inline expression_node<T>* branch(const std::size_t& index = 0) const exprtk_override
{
if (0 == index)
return branch_[0].first;
else if (1 == index)
return branch_[1].first;
else
return reinterpret_cast<expression_ptr>(0);
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::template compute_node_depth<2>(branch_);
}
protected:
branch_t branch_[2];
};
template <typename T>
class trinary_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
trinary_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1,
expression_ptr branch2)
: operation_(opr)
{
init_branches<3>(branch_, branch0, branch1, branch2);
}
inline T value() const exprtk_override
{
assert(branch_[0].first);
assert(branch_[1].first);
assert(branch_[2].first);
const T arg0 = branch_[0].first->value();
const T arg1 = branch_[1].first->value();
const T arg2 = branch_[2].first->value();
switch (operation_)
{
case e_inrange : return (arg1 < arg0) ? T(0) : ((arg1 > arg2) ? T(0) : T(1));
case e_clamp : return (arg1 < arg0) ? arg0 : (arg1 > arg2 ? arg2 : arg1);
case e_iclamp : if ((arg1 <= arg0) || (arg1 >= arg2))
return arg1;
else
return ((T(2) * arg1 <= (arg2 + arg0)) ? arg0 : arg2);
default : exprtk_debug(("trinary_node::value() - Error: Invalid operation\n"));
return std::numeric_limits<T>::quiet_NaN();
}
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_trinary;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override exprtk_final
{
return expression_node<T>::ndb_t::template compute_node_depth<3>(branch_);
}
protected:
operator_type operation_;
branch_t branch_[3];
};
template <typename T>
class quaternary_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
quaternary_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1,
expression_ptr branch2,
expression_ptr branch3)
: operation_(opr)
{
init_branches<4>(branch_, branch0, branch1, branch2, branch3);
}
inline T value() const exprtk_override
{
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_quaternary;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override exprtk_final
{
return expression_node<T>::ndb_t::template compute_node_depth<4>(branch_);
}
protected:
operator_type operation_;
branch_t branch_[4];
};
template <typename T>
class conditional_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
conditional_node(expression_ptr condition,
expression_ptr consequent,
expression_ptr alternative)
{
construct_branch_pair(condition_ , condition );
construct_branch_pair(consequent_ , consequent );
construct_branch_pair(alternative_, alternative);
}
inline T value() const exprtk_override
{
assert(condition_ .first);
assert(consequent_ .first);
assert(alternative_.first);
if (is_true(condition_))
return consequent_.first->value();
else
return alternative_.first->value();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_conditional;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(consequent_ , node_delete_list);
expression_node<T>::ndb_t::collect(alternative_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth
(condition_, consequent_, alternative_);
}
private:
branch_t condition_;
branch_t consequent_;
branch_t alternative_;
};
template <typename T>
class cons_conditional_node exprtk_final : public expression_node<T>
{
public:
// Consequent only conditional statement node
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
cons_conditional_node(expression_ptr condition,
expression_ptr consequent)
{
construct_branch_pair(condition_ , condition );
construct_branch_pair(consequent_, consequent);
}
inline T value() const exprtk_override
{
assert(condition_ .first);
assert(consequent_.first);
if (is_true(condition_))
return consequent_.first->value();
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_conditional;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(consequent_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::
compute_node_depth(condition_, consequent_);
}
private:
branch_t condition_;
branch_t consequent_;
};
#ifndef exprtk_disable_break_continue
template <typename T>
class break_exception
{
public:
explicit break_exception(const T& v)
: value(v)
{}
T value;
};
class continue_exception {};
template <typename T>
class break_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
break_node(expression_ptr ret = expression_ptr(0))
{
construct_branch_pair(return_, ret);
}
inline T value() const exprtk_override
{
const T result = return_.first ?
return_.first->value() :
std::numeric_limits<T>::quiet_NaN();
throw break_exception<T>(result);
#ifndef _MSC_VER
return std::numeric_limits<T>::quiet_NaN();
#endif
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_break;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(return_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(return_);
}
private:
branch_t return_;
};
template <typename T>
class continue_node exprtk_final : public expression_node<T>
{
public:
inline T value() const exprtk_override
{
throw continue_exception();
#ifndef _MSC_VER
return std::numeric_limits<T>::quiet_NaN();
#endif
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_break;
}
};
#endif
struct loop_runtime_checker
{
loop_runtime_checker(loop_runtime_check_ptr loop_runtime_check,
loop_runtime_check::loop_types lp_typ = loop_runtime_check::e_invalid)
: iteration_count_(0)
, loop_runtime_check_(loop_runtime_check)
, max_loop_iterations_(loop_runtime_check_->max_loop_iterations)
, loop_type_(lp_typ)
{
assert(loop_runtime_check_);
}
inline void reset(const _uint64_t initial_value = 0) const
{
iteration_count_ = initial_value;
}
inline bool check() const
{
if (
(0 == loop_runtime_check_) ||
((++iteration_count_ <= max_loop_iterations_) && loop_runtime_check_->check())
)
{
return true;
}
loop_runtime_check::violation_context ctxt;
ctxt.loop = loop_type_;
ctxt.violation = loop_runtime_check::e_iteration_count;
loop_runtime_check_->handle_runtime_violation(ctxt);
return false;
}
mutable _uint64_t iteration_count_;
mutable loop_runtime_check_ptr loop_runtime_check_;
const details::_uint64_t& max_loop_iterations_;
loop_runtime_check::loop_types loop_type_;
};
template <typename T>
class while_loop_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
while_loop_node(expression_ptr condition,
expression_ptr loop_body)
{
construct_branch_pair(condition_, condition);
construct_branch_pair(loop_body_, loop_body);
}
inline T value() const exprtk_override
{
assert(condition_.first);
assert(loop_body_.first);
T result = T(0);
while (is_true(condition_))
{
result = loop_body_.first->value();
}
return result;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_while;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(loop_body_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(condition_, loop_body_);
}
protected:
branch_t condition_;
branch_t loop_body_;
};
template <typename T>
class while_loop_rtc_node exprtk_final
: public while_loop_node<T>
, public loop_runtime_checker
{
public:
typedef while_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
while_loop_rtc_node(expression_ptr condition,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(condition, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_while_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset();
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
result = parent_t::loop_body_.first->value();
}
return result;
}
};
template <typename T>
class repeat_until_loop_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
repeat_until_loop_node(expression_ptr condition,
expression_ptr loop_body)
{
construct_branch_pair(condition_, condition);
construct_branch_pair(loop_body_, loop_body);
}
inline T value() const exprtk_override
{
assert(condition_.first);
assert(loop_body_.first);
T result = T(0);
do
{
result = loop_body_.first->value();
}
while (is_false(condition_.first));
return result;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_repeat;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(loop_body_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(condition_, loop_body_);
}
protected:
branch_t condition_;
branch_t loop_body_;
};
template <typename T>
class repeat_until_loop_rtc_node exprtk_final
: public repeat_until_loop_node<T>
, public loop_runtime_checker
{
public:
typedef repeat_until_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
repeat_until_loop_rtc_node(expression_ptr condition,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(condition, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_repeat_until_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset(1);
do
{
result = parent_t::loop_body_.first->value();
}
while (is_false(parent_t::condition_.first) && loop_runtime_checker::check());
return result;
}
};
template <typename T>
class for_loop_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
for_loop_node(expression_ptr initialiser,
expression_ptr condition,
expression_ptr incrementor,
expression_ptr loop_body)
{
construct_branch_pair(initialiser_, initialiser);
construct_branch_pair(condition_ , condition );
construct_branch_pair(incrementor_, incrementor);
construct_branch_pair(loop_body_ , loop_body );
}
inline T value() const exprtk_override
{
assert(condition_.first);
assert(loop_body_.first);
T result = T(0);
if (initialiser_.first)
initialiser_.first->value();
if (incrementor_.first)
{
while (is_true(condition_))
{
result = loop_body_.first->value();
incrementor_.first->value();
}
}
else
{
while (is_true(condition_))
{
result = loop_body_.first->value();
}
}
return result;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_for;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(initialiser_ , node_delete_list);
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(incrementor_ , node_delete_list);
expression_node<T>::ndb_t::collect(loop_body_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth
(initialiser_, condition_, incrementor_, loop_body_);
}
protected:
branch_t initialiser_;
branch_t condition_ ;
branch_t incrementor_;
branch_t loop_body_ ;
};
template <typename T>
class for_loop_rtc_node exprtk_final
: public for_loop_node<T>
, public loop_runtime_checker
{
public:
typedef for_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
for_loop_rtc_node(expression_ptr initialiser,
expression_ptr condition,
expression_ptr incrementor,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(initialiser, condition, incrementor, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_for_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset();
if (parent_t::initialiser_.first)
parent_t::initialiser_.first->value();
if (parent_t::incrementor_.first)
{
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
result = parent_t::loop_body_.first->value();
parent_t::incrementor_.first->value();
}
}
else
{
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
result = parent_t::loop_body_.first->value();
}
}
return result;
}
};
#ifndef exprtk_disable_break_continue
template <typename T>
class while_loop_bc_node : public while_loop_node<T>
{
public:
typedef while_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
while_loop_bc_node(expression_ptr condition,
expression_ptr loop_body)
: parent_t(condition, loop_body)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
while (is_true(parent_t::condition_))
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
return result;
}
};
template <typename T>
class while_loop_bc_rtc_node exprtk_final
: public while_loop_bc_node<T>
, public loop_runtime_checker
{
public:
typedef while_loop_bc_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
while_loop_bc_rtc_node(expression_ptr condition,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(condition, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_while_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset();
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
return result;
}
};
template <typename T>
class repeat_until_loop_bc_node : public repeat_until_loop_node<T>
{
public:
typedef repeat_until_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
repeat_until_loop_bc_node(expression_ptr condition,
expression_ptr loop_body)
: parent_t(condition, loop_body)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
do
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
while (is_false(parent_t::condition_.first));
return result;
}
};
template <typename T>
class repeat_until_loop_bc_rtc_node exprtk_final
: public repeat_until_loop_bc_node<T>,
public loop_runtime_checker
{
public:
typedef repeat_until_loop_bc_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
repeat_until_loop_bc_rtc_node(expression_ptr condition,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(condition, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_repeat_until_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset();
do
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
while (is_false(parent_t::condition_.first) && loop_runtime_checker::check());
return result;
}
};
template <typename T>
class for_loop_bc_node : public for_loop_node<T>
{
public:
typedef for_loop_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
for_loop_bc_node(expression_ptr initialiser,
expression_ptr condition,
expression_ptr incrementor,
expression_ptr loop_body)
: parent_t(initialiser, condition, incrementor, loop_body)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
if (parent_t::initialiser_.first)
parent_t::initialiser_.first->value();
if (parent_t::incrementor_.first)
{
while (is_true(parent_t::condition_))
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
parent_t::incrementor_.first->value();
}
}
else
{
while (is_true(parent_t::condition_))
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
}
return result;
}
};
template <typename T>
class for_loop_bc_rtc_node exprtk_final
: public for_loop_bc_node<T>
, public loop_runtime_checker
{
public:
typedef for_loop_bc_node<T> parent_t;
typedef expression_node<T>* expression_ptr;
for_loop_bc_rtc_node(expression_ptr initialiser,
expression_ptr condition,
expression_ptr incrementor,
expression_ptr loop_body,
loop_runtime_check_ptr loop_rt_chk)
: parent_t(initialiser, condition, incrementor, loop_body)
, loop_runtime_checker(loop_rt_chk, loop_runtime_check::e_for_loop)
{}
inline T value() const exprtk_override
{
assert(parent_t::condition_.first);
assert(parent_t::loop_body_.first);
T result = T(0);
loop_runtime_checker::reset();
if (parent_t::initialiser_.first)
parent_t::initialiser_.first->value();
if (parent_t::incrementor_.first)
{
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
parent_t::incrementor_.first->value();
}
}
else
{
while (is_true(parent_t::condition_) && loop_runtime_checker::check())
{
try
{
result = parent_t::loop_body_.first->value();
}
catch(const break_exception<T>& e)
{
return e.value;
}
catch(const continue_exception&)
{}
}
}
return result;
}
};
#endif
template <typename T>
class switch_node : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit switch_node(const Sequence<expression_ptr,Allocator>& arg_list)
{
if (1 != (arg_list.size() & 1))
return;
arg_list_.resize(arg_list.size());
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (arg_list[i])
{
construct_branch_pair(arg_list_[i], arg_list[i]);
}
else
{
arg_list_.clear();
return;
}
}
}
inline T value() const exprtk_override
{
if (!arg_list_.empty())
{
const std::size_t upper_bound = (arg_list_.size() - 1);
for (std::size_t i = 0; i < upper_bound; i += 2)
{
expression_ptr condition = arg_list_[i ].first;
expression_ptr consequent = arg_list_[i + 1].first;
if (is_true(condition))
{
return consequent->value();
}
}
return arg_list_[upper_bound].first->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override exprtk_final
{
return expression_node<T>::e_switch;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(arg_list_, node_delete_list);
}
std::size_t node_depth() const exprtk_override exprtk_final
{
return expression_node<T>::ndb_t::compute_node_depth(arg_list_);
}
protected:
std::vector<branch_t> arg_list_;
};
template <typename T, typename Switch_N>
class switch_n_node exprtk_final : public switch_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit switch_n_node(const Sequence<expression_ptr,Allocator>& arg_list)
: switch_node<T>(arg_list)
{}
inline T value() const exprtk_override
{
return Switch_N::process(switch_node<T>::arg_list_);
}
};
template <typename T>
class multi_switch_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit multi_switch_node(const Sequence<expression_ptr,Allocator>& arg_list)
{
if (0 != (arg_list.size() & 1))
return;
arg_list_.resize(arg_list.size());
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (arg_list[i])
{
construct_branch_pair(arg_list_[i], arg_list[i]);
}
else
{
arg_list_.clear();
return;
}
}
}
inline T value() const exprtk_override
{
T result = T(0);
if (arg_list_.empty())
{
return std::numeric_limits<T>::quiet_NaN();
}
const std::size_t upper_bound = (arg_list_.size() - 1);
for (std::size_t i = 0; i < upper_bound; i += 2)
{
expression_ptr condition = arg_list_[i ].first;
expression_ptr consequent = arg_list_[i + 1].first;
if (is_true(condition))
{
result = consequent->value();
}
}
return result;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_mswitch;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(arg_list_, node_delete_list);
}
std::size_t node_depth() const exprtk_override exprtk_final
{
return expression_node<T>::ndb_t::compute_node_depth(arg_list_);
}
private:
std::vector<branch_t> arg_list_;
};
template <typename T>
class ivariable
{
public:
virtual ~ivariable() {}
virtual T& ref() = 0;
virtual const T& ref() const = 0;
};
template <typename T>
class variable_node exprtk_final
: public expression_node<T>,
public ivariable <T>
{
public:
static T null_value;
explicit variable_node()
: value_(&null_value)
{}
explicit variable_node(T& v)
: value_(&v)
{}
inline bool operator <(const variable_node<T>& v) const
{
return this < (&v);
}
inline T value() const exprtk_override
{
return (*value_);
}
inline T& ref() exprtk_override
{
return (*value_);
}
inline const T& ref() const exprtk_override
{
return (*value_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_variable;
}
private:
T* value_;
};
template <typename T>
T variable_node<T>::null_value = T(std::numeric_limits<T>::quiet_NaN());
template <typename T>
struct range_pack
{
typedef expression_node<T>* expression_node_ptr;
typedef std::pair<std::size_t,std::size_t> cached_range_t;
range_pack()
: n0_e (std::make_pair(false,expression_node_ptr(0)))
, n1_e (std::make_pair(false,expression_node_ptr(0)))
, n0_c (std::make_pair(false,0))
, n1_c (std::make_pair(false,0))
, cache(std::make_pair(0,0))
{}
void clear()
{
n0_e = std::make_pair(false,expression_node_ptr(0));
n1_e = std::make_pair(false,expression_node_ptr(0));
n0_c = std::make_pair(false,0);
n1_c = std::make_pair(false,0);
cache = std::make_pair(0,0);
}
void free()
{
if (n0_e.first && n0_e.second)
{
n0_e.first = false;
if (
!is_variable_node(n0_e.second) &&
!is_string_node (n0_e.second)
)
{
destroy_node(n0_e.second);
}
}
if (n1_e.first && n1_e.second)
{
n1_e.first = false;
if (
!is_variable_node(n1_e.second) &&
!is_string_node (n1_e.second)
)
{
destroy_node(n1_e.second);
}
}
}
bool const_range() const
{
return ( n0_c.first && n1_c.first) &&
(!n0_e.first && !n1_e.first);
}
bool var_range() const
{
return ( n0_e.first && n1_e.first) &&
(!n0_c.first && !n1_c.first);
}
bool operator() (std::size_t& r0, std::size_t& r1,
const std::size_t& size = std::numeric_limits<std::size_t>::max()) const
{
if (n0_c.first)
r0 = n0_c.second;
else if (n0_e.first)
{
r0 = static_cast<std::size_t>(details::numeric::to_int64(n0_e.second->value()));
}
else
return false;
if (n1_c.first)
r1 = n1_c.second;
else if (n1_e.first)
{
r1 = static_cast<std::size_t>(details::numeric::to_int64(n1_e.second->value()));
}
else
return false;
if (
(std::numeric_limits<std::size_t>::max() != size) &&
(std::numeric_limits<std::size_t>::max() == r1 )
)
{
r1 = size - 1;
}
cache.first = r0;
cache.second = r1;
#ifndef exprtk_enable_range_runtime_checks
return (r0 <= r1);
#else
return range_runtime_check(r0, r1, size);
#endif
}
inline std::size_t const_size() const
{
return (n1_c.second - n0_c.second + 1);
}
inline std::size_t cache_size() const
{
return (cache.second - cache.first + 1);
}
std::pair<bool,expression_node_ptr> n0_e;
std::pair<bool,expression_node_ptr> n1_e;
std::pair<bool,std::size_t > n0_c;
std::pair<bool,std::size_t > n1_c;
mutable cached_range_t cache;
#ifdef exprtk_enable_range_runtime_checks
bool range_runtime_check(const std::size_t r0,
const std::size_t r1,
const std::size_t size) const
{
if (r0 >= size)
{
throw std::runtime_error("range error: (r0 < 0) || (r0 >= size)");
return false;
}
if (r1 >= size)
{
throw std::runtime_error("range error: (r1 < 0) || (r1 >= size)");
return false;
}
return (r0 <= r1);
}
#endif
};
template <typename T>
class string_base_node;
template <typename T>
struct range_data_type
{
typedef range_pack<T> range_t;
typedef string_base_node<T>* strbase_ptr_t;
range_data_type()
: range(0)
, data (0)
, size (0)
, type_size(0)
, str_node (0)
{}
range_t* range;
void* data;
std::size_t size;
std::size_t type_size;
strbase_ptr_t str_node;
};
template <typename T> class vector_node;
template <typename T>
class vector_interface
{
public:
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
virtual ~vector_interface() {}
virtual std::size_t size () const = 0;
virtual vector_node_ptr vec() const = 0;
virtual vector_node_ptr vec() = 0;
virtual vds_t& vds () = 0;
virtual const vds_t& vds () const = 0;
virtual bool side_effect () const { return false; }
};
template <typename T>
class vector_node exprtk_final
: public expression_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_holder<T> vector_holder_t;
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
explicit vector_node(vector_holder_t* vh)
: vector_holder_(vh)
, vds_((*vector_holder_).size(),(*vector_holder_)[0])
{
vector_holder_->set_ref(&vds_.ref());
}
vector_node(const vds_t& vds, vector_holder_t* vh)
: vector_holder_(vh)
, vds_(vds)
{}
inline T value() const exprtk_override
{
return vds().data()[0];
}
vector_node_ptr vec() const exprtk_override
{
return const_cast<vector_node_ptr>(this);
}
vector_node_ptr vec() exprtk_override
{
return this;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vector;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
inline vector_holder_t& vec_holder()
{
return (*vector_holder_);
}
private:
vector_holder_t* vector_holder_;
vds_t vds_;
};
template <typename T>
class vector_elem_node exprtk_final
: public expression_node<T>,
public ivariable <T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_holder<T> vector_holder_t;
typedef vector_holder_t* vector_holder_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
vector_elem_node(expression_ptr index, vector_holder_ptr vec_holder)
: vec_holder_(vec_holder)
, vector_base_((*vec_holder)[0])
{
construct_branch_pair(index_, index);
}
inline T value() const exprtk_override
{
return *(vector_base_ + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline T& ref() exprtk_override
{
return *(vector_base_ + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline const T& ref() const exprtk_override
{
return *(vector_base_ + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecelem;
}
inline vector_holder_t& vec_holder()
{
return (*vec_holder_);
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(index_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(index_);
}
private:
vector_holder_ptr vec_holder_;
T* vector_base_;
branch_t index_;
};
template <typename T>
class rebasevector_elem_node exprtk_final
: public expression_node<T>,
public ivariable <T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_holder<T> vector_holder_t;
typedef vector_holder_t* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
typedef std::pair<expression_ptr,bool> branch_t;
rebasevector_elem_node(expression_ptr index, vector_holder_ptr vec_holder)
: vector_holder_(vec_holder)
, vds_((*vector_holder_).size(),(*vector_holder_)[0])
{
vector_holder_->set_ref(&vds_.ref());
construct_branch_pair(index_, index);
}
inline T value() const exprtk_override
{
return *(vds_.data() + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline T& ref() exprtk_override
{
return *(vds_.data() + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline const T& ref() const exprtk_override
{
return *(vds_.data() + static_cast<std::size_t>(details::numeric::to_int64(index_.first->value())));
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_rbvecelem;
}
inline vector_holder_t& vec_holder()
{
return (*vector_holder_);
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(index_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(index_);
}
private:
vector_holder_ptr vector_holder_;
vds_t vds_;
branch_t index_;
};
template <typename T>
class rebasevector_celem_node exprtk_final
: public expression_node<T>,
public ivariable <T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_holder<T> vector_holder_t;
typedef vector_holder_t* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
rebasevector_celem_node(const std::size_t index, vector_holder_ptr vec_holder)
: index_(index)
, vector_holder_(vec_holder)
, vds_((*vector_holder_).size(),(*vector_holder_)[0])
{
vector_holder_->set_ref(&vds_.ref());
}
inline T value() const exprtk_override
{
return *(vds_.data() + index_);
}
inline T& ref() exprtk_override
{
return *(vds_.data() + index_);
}
inline const T& ref() const exprtk_override
{
return *(vds_.data() + index_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_rbveccelem;
}
inline vector_holder_t& vec_holder()
{
return (*vector_holder_);
}
private:
const std::size_t index_;
vector_holder_ptr vector_holder_;
vds_t vds_;
};
template <typename T>
class vector_assignment_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
vector_assignment_node(T* vector_base,
const std::size_t& size,
const std::vector<expression_ptr>& initialiser_list,
const bool single_value_initialse)
: vector_base_(vector_base)
, initialiser_list_(initialiser_list)
, size_(size)
, single_value_initialse_(single_value_initialse)
{}
inline T value() const exprtk_override
{
if (single_value_initialse_)
{
for (std::size_t i = 0; i < size_; ++i)
{
*(vector_base_ + i) = initialiser_list_[0]->value();
}
}
else
{
const std::size_t initialiser_list_size = initialiser_list_.size();
for (std::size_t i = 0; i < initialiser_list_size; ++i)
{
*(vector_base_ + i) = initialiser_list_[i]->value();
}
if (initialiser_list_size < size_)
{
for (std::size_t i = initialiser_list_size; i < size_; ++i)
{
*(vector_base_ + i) = T(0);
}
}
}
return *(vector_base_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecdefass;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(initialiser_list_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(initialiser_list_);
}
private:
vector_assignment_node(const vector_assignment_node<T>&) exprtk_delete;
vector_assignment_node<T>& operator=(const vector_assignment_node<T>&) exprtk_delete;
mutable T* vector_base_;
std::vector<expression_ptr> initialiser_list_;
const std::size_t size_;
const bool single_value_initialse_;
};
template <typename T>
class swap_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef variable_node<T>* variable_node_ptr;
swap_node(variable_node_ptr var0, variable_node_ptr var1)
: var0_(var0)
, var1_(var1)
{}
inline T value() const exprtk_override
{
std::swap(var0_->ref(),var1_->ref());
return var1_->ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_swap;
}
private:
variable_node_ptr var0_;
variable_node_ptr var1_;
};
template <typename T>
class swap_generic_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef ivariable<T>* ivariable_ptr;
swap_generic_node(expression_ptr var0, expression_ptr var1)
: binary_node<T>(details::e_swap, var0, var1)
, var0_(dynamic_cast<ivariable_ptr>(var0))
, var1_(dynamic_cast<ivariable_ptr>(var1))
{}
inline T value() const exprtk_override
{
std::swap(var0_->ref(),var1_->ref());
return var1_->ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_swap;
}
private:
ivariable_ptr var0_;
ivariable_ptr var1_;
};
template <typename T>
class swap_vecvec_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node <T>* vector_node_ptr;
typedef vec_data_store <T> vds_t;
using binary_node<T>::branch;
swap_vecvec_node(expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(details::e_swap, branch0, branch1)
, vec0_node_ptr_(0)
, vec1_node_ptr_(0)
, vec_size_ (0)
, initialised_ (false)
{
if (is_ivector_node(branch(0)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(0))))
{
vec0_node_ptr_ = vi->vec();
vds() = vi->vds();
}
}
if (is_ivector_node(branch(1)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(1))))
{
vec1_node_ptr_ = vi->vec();
}
}
if (vec0_node_ptr_ && vec1_node_ptr_)
{
vec_size_ = std::min(vec0_node_ptr_->vds().size(),
vec1_node_ptr_->vds().size());
initialised_ = true;
}
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
binary_node<T>::branch(0)->value();
binary_node<T>::branch(1)->value();
T* vec0 = vec0_node_ptr_->vds().data();
T* vec1 = vec1_node_ptr_->vds().data();
for (std::size_t i = 0; i < vec_size_; ++i)
{
std::swap(vec0[i],vec1[i]);
}
return vec1_node_ptr_->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return vec0_node_ptr_;
}
vector_node_ptr vec() exprtk_override
{
return vec0_node_ptr_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvecswap;
}
std::size_t size() const exprtk_override
{
return vec_size_;
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node<T>* vec0_node_ptr_;
vector_node<T>* vec1_node_ptr_;
std::size_t vec_size_;
bool initialised_;
vds_t vds_;
};
#ifndef exprtk_disable_string_capabilities
template <typename T>
class stringvar_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
static std::string null_value;
explicit stringvar_node()
: value_(&null_value)
{}
explicit stringvar_node(std::string& v)
: value_(&v)
{
rp_.n0_c = std::make_pair<bool,std::size_t>(true,0);
rp_.n1_c = std::make_pair<bool,std::size_t>(true,v.size() - 1);
rp_.cache.first = rp_.n0_c.second;
rp_.cache.second = rp_.n1_c.second;
}
inline bool operator <(const stringvar_node<T>& v) const
{
return this < (&v);
}
inline T value() const exprtk_override
{
rp_.n1_c.second = (*value_).size() - 1;
rp_.cache.second = rp_.n1_c.second;
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return ref();
}
char_cptr base() const exprtk_override
{
return &(*value_)[0];
}
std::size_t size() const exprtk_override
{
return ref().size();
}
std::string& ref()
{
return (*value_);
}
const std::string& ref() const
{
return (*value_);
}
range_t& range_ref() exprtk_override
{
return rp_;
}
const range_t& range_ref() const exprtk_override
{
return rp_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringvar;
}
void rebase(std::string& s)
{
value_ = &s;
rp_.n0_c = std::make_pair<bool,std::size_t>(true,0);
rp_.n1_c = std::make_pair<bool,std::size_t>(true,value_->size() - 1);
rp_.cache.first = rp_.n0_c.second;
rp_.cache.second = rp_.n1_c.second;
}
private:
std::string* value_;
mutable range_t rp_;
};
template <typename T>
std::string stringvar_node<T>::null_value = std::string("");
template <typename T>
class string_range_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
static std::string null_value;
explicit string_range_node(std::string& v, const range_t& rp)
: value_(&v)
, rp_(rp)
{}
virtual ~string_range_node()
{
rp_.free();
}
inline bool operator <(const string_range_node<T>& v) const
{
return this < (&v);
}
inline T value() const exprtk_override
{
return std::numeric_limits<T>::quiet_NaN();
}
inline std::string str() const exprtk_override
{
return (*value_);
}
char_cptr base() const exprtk_override
{
return &(*value_)[0];
}
std::size_t size() const exprtk_override
{
return ref().size();
}
inline range_t range() const
{
return rp_;
}
inline virtual std::string& ref()
{
return (*value_);
}
inline virtual const std::string& ref() const
{
return (*value_);
}
inline range_t& range_ref() exprtk_override
{
return rp_;
}
inline const range_t& range_ref() const exprtk_override
{
return rp_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringvarrng;
}
private:
std::string* value_;
range_t rp_;
};
template <typename T>
std::string string_range_node<T>::null_value = std::string("");
template <typename T>
class const_string_range_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
explicit const_string_range_node(const std::string& v, const range_t& rp)
: value_(v)
, rp_(rp)
{}
~const_string_range_node()
{
rp_.free();
}
inline T value() const exprtk_override
{
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return value_;
}
char_cptr base() const exprtk_override
{
return value_.data();
}
std::size_t size() const exprtk_override
{
return value_.size();
}
range_t range() const
{
return rp_;
}
range_t& range_ref() exprtk_override
{
return rp_;
}
const range_t& range_ref() const exprtk_override
{
return rp_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_cstringvarrng;
}
private:
const_string_range_node(const const_string_range_node<T>&) exprtk_delete;
const_string_range_node<T>& operator=(const const_string_range_node<T>&) exprtk_delete;
const std::string value_;
range_t rp_;
};
template <typename T>
class generic_string_range_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef expression_node <T>* expression_ptr;
typedef stringvar_node <T>* strvar_node_ptr;
typedef string_base_node<T>* str_base_ptr;
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface<T> irange_t;
typedef irange_t* irange_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
generic_string_range_node(expression_ptr str_branch, const range_t& brange)
: initialised_(false)
, str_base_ptr_ (0)
, str_range_ptr_(0)
, base_range_(brange)
{
range_.n0_c = std::make_pair<bool,std::size_t>(true,0);
range_.n1_c = std::make_pair<bool,std::size_t>(true,0);
range_.cache.first = range_.n0_c.second;
range_.cache.second = range_.n1_c.second;
construct_branch_pair(branch_, str_branch);
if (is_generally_string_node(branch_.first))
{
str_base_ptr_ = dynamic_cast<str_base_ptr>(branch_.first);
if (0 == str_base_ptr_)
return;
str_range_ptr_ = dynamic_cast<irange_ptr>(branch_.first);
if (0 == str_range_ptr_)
return;
}
initialised_ = (str_base_ptr_ && str_range_ptr_);
assert(initialised_);
}
~generic_string_range_node()
{
base_range_.free();
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch_.first);
branch_.first->value();
std::size_t str_r0 = 0;
std::size_t str_r1 = 0;
std::size_t r0 = 0;
std::size_t r1 = 0;
const range_t& range = str_range_ptr_->range_ref();
const std::size_t base_str_size = str_base_ptr_->size();
if (
range (str_r0, str_r1, base_str_size) &&
base_range_( r0, r1, base_str_size - str_r0)
)
{
const std::size_t size = (r1 - r0) + 1;
range_.n1_c.second = size - 1;
range_.cache.second = range_.n1_c.second;
value_.assign(str_base_ptr_->base() + str_r0 + r0, size);
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return value_;
}
char_cptr base() const exprtk_override
{
return &value_[0];
}
std::size_t size() const exprtk_override
{
return value_.size();
}
range_t& range_ref() exprtk_override
{
return range_;
}
const range_t& range_ref() const exprtk_override
{
return range_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strgenrange;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
bool initialised_;
branch_t branch_;
str_base_ptr str_base_ptr_;
irange_ptr str_range_ptr_;
mutable range_t base_range_;
mutable range_t range_;
mutable std::string value_;
};
template <typename T>
class string_concat_node exprtk_final
: public binary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_interface<T> irange_t;
typedef irange_t* irange_ptr;
typedef range_t* range_ptr;
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
using binary_node<T>::branch;
string_concat_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, initialised_(false)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_range_ptr_(0)
, str1_range_ptr_(0)
{
range_.n0_c = std::make_pair<bool,std::size_t>(true,0);
range_.n1_c = std::make_pair<bool,std::size_t>(true,0);
range_.cache.first = range_.n0_c.second;
range_.cache.second = range_.n1_c.second;
if (is_generally_string_node(branch(0)))
{
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
if (0 == str0_base_ptr_)
return;
str0_range_ptr_ = dynamic_cast<irange_ptr>(branch(0));
if (0 == str0_range_ptr_)
return;
}
if (is_generally_string_node(branch(1)))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(branch(1));
if (0 == str1_base_ptr_)
return;
str1_range_ptr_ = dynamic_cast<irange_ptr>(branch(1));
if (0 == str1_range_ptr_)
return;
}
initialised_ = str0_base_ptr_ &&
str1_base_ptr_ &&
str0_range_ptr_ &&
str1_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
std::size_t str0_r0 = 0;
std::size_t str0_r1 = 0;
std::size_t str1_r0 = 0;
std::size_t str1_r1 = 0;
const range_t& range0 = str0_range_ptr_->range_ref();
const range_t& range1 = str1_range_ptr_->range_ref();
if (
range0(str0_r0, str0_r1, str0_base_ptr_->size()) &&
range1(str1_r0, str1_r1, str1_base_ptr_->size())
)
{
const std::size_t size0 = (str0_r1 - str0_r0) + 1;
const std::size_t size1 = (str1_r1 - str1_r0) + 1;
value_.assign(str0_base_ptr_->base() + str0_r0, size0);
value_.append(str1_base_ptr_->base() + str1_r0, size1);
range_.n1_c.second = value_.size() - 1;
range_.cache.second = range_.n1_c.second;
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return value_;
}
char_cptr base() const exprtk_override
{
return &value_[0];
}
std::size_t size() const exprtk_override
{
return value_.size();
}
range_t& range_ref() exprtk_override
{
return range_;
}
const range_t& range_ref() const exprtk_override
{
return range_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strconcat;
}
private:
bool initialised_;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
irange_ptr str0_range_ptr_;
irange_ptr str1_range_ptr_;
mutable range_t range_;
mutable std::string value_;
};
template <typename T>
class swap_string_node exprtk_final
: public binary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface<T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef stringvar_node <T>* strvar_node_ptr;
typedef string_base_node<T>* str_base_ptr;
using binary_node<T>::branch;
swap_string_node(expression_ptr branch0, expression_ptr branch1)
: binary_node<T>(details::e_swap, branch0, branch1),
initialised_(false),
str0_node_ptr_(0),
str1_node_ptr_(0)
{
if (is_string_node(branch(0)))
{
str0_node_ptr_ = static_cast<strvar_node_ptr>(branch(0));
}
if (is_string_node(branch(1)))
{
str1_node_ptr_ = static_cast<strvar_node_ptr>(branch(1));
}
initialised_ = (str0_node_ptr_ && str1_node_ptr_);
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
std::swap(str0_node_ptr_->ref(), str1_node_ptr_->ref());
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return str0_node_ptr_->str();
}
char_cptr base() const exprtk_override
{
return str0_node_ptr_->base();
}
std::size_t size() const exprtk_override
{
return str0_node_ptr_->size();
}
range_t& range_ref() exprtk_override
{
return str0_node_ptr_->range_ref();
}
const range_t& range_ref() const exprtk_override
{
return str0_node_ptr_->range_ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strswap;
}
private:
bool initialised_;
strvar_node_ptr str0_node_ptr_;
strvar_node_ptr str1_node_ptr_;
};
template <typename T>
class swap_genstrings_node exprtk_final : public binary_node<T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface<T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
using binary_node<T>::branch;
swap_genstrings_node(expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(details::e_default, branch0, branch1)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_range_ptr_(0)
, str1_range_ptr_(0)
, initialised_(false)
{
if (is_generally_string_node(branch(0)))
{
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
if (0 == str0_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(0));
if (0 == range)
return;
str0_range_ptr_ = &(range->range_ref());
}
if (is_generally_string_node(branch(1)))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(branch(1));
if (0 == str1_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(1));
if (0 == range)
return;
str1_range_ptr_ = &(range->range_ref());
}
initialised_ = str0_base_ptr_ &&
str1_base_ptr_ &&
str0_range_ptr_ &&
str1_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
std::size_t str0_r0 = 0;
std::size_t str0_r1 = 0;
std::size_t str1_r0 = 0;
std::size_t str1_r1 = 0;
const range_t& range0 = (*str0_range_ptr_);
const range_t& range1 = (*str1_range_ptr_);
if (
range0(str0_r0, str0_r1, str0_base_ptr_->size()) &&
range1(str1_r0, str1_r1, str1_base_ptr_->size())
)
{
const std::size_t size0 = range0.cache_size();
const std::size_t size1 = range1.cache_size();
const std::size_t max_size = std::min(size0,size1);
char_ptr s0 = const_cast<char_ptr>(str0_base_ptr_->base() + str0_r0);
char_ptr s1 = const_cast<char_ptr>(str1_base_ptr_->base() + str1_r0);
loop_unroll::details lud(max_size);
char_cptr upper_bound = s0 + lud.upper_bound;
while (s0 < upper_bound)
{
#define exprtk_loop(N) \
std::swap(s0[N], s1[N]); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
s0 += lud.batch_size;
s1 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { std::swap(s0[i], s1[i]); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strswap;
}
private:
swap_genstrings_node(const swap_genstrings_node<T>&) exprtk_delete;
swap_genstrings_node<T>& operator=(const swap_genstrings_node<T>&) exprtk_delete;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
range_ptr str0_range_ptr_;
range_ptr str1_range_ptr_;
bool initialised_;
};
template <typename T>
class stringvar_size_node exprtk_final : public expression_node<T>
{
public:
static std::string null_value;
explicit stringvar_size_node()
: value_(&null_value)
{}
explicit stringvar_size_node(std::string& v)
: value_(&v)
{}
inline T value() const exprtk_override
{
return T((*value_).size());
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringvarsize;
}
private:
std::string* value_;
};
template <typename T>
std::string stringvar_size_node<T>::null_value = std::string("");
template <typename T>
class string_size_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
explicit string_size_node(expression_ptr branch)
: str_base_ptr_(0)
{
construct_branch_pair(branch_, branch);
if (is_generally_string_node(branch_.first))
{
str_base_ptr_ = dynamic_cast<str_base_ptr>(branch_.first);
if (0 == str_base_ptr_)
return;
}
}
inline T value() const exprtk_override
{
T result = std::numeric_limits<T>::quiet_NaN();
if (str_base_ptr_)
{
branch_.first->value();
result = T(str_base_ptr_->size());
}
return result;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringsize;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
branch_t branch_;
str_base_ptr str_base_ptr_;
};
struct asn_assignment
{
static inline void execute(std::string& s, char_cptr data, const std::size_t size)
{ s.assign(data,size); }
};
struct asn_addassignment
{
static inline void execute(std::string& s, char_cptr data, const std::size_t size)
{ s.append(data,size); }
};
template <typename T, typename AssignmentProcess = asn_assignment>
class assignment_string_node exprtk_final
: public binary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef stringvar_node <T>* strvar_node_ptr;
typedef string_base_node<T>* str_base_ptr;
using binary_node<T>::branch;
assignment_string_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, initialised_(false)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_node_ptr_ (0)
, str1_range_ptr_(0)
{
if (is_string_node(branch(0)))
{
str0_node_ptr_ = static_cast<strvar_node_ptr>(branch(0));
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
}
if (is_generally_string_node(branch(1)))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(branch(1));
if (0 == str1_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(1));
if (0 == range)
return;
str1_range_ptr_ = &(range->range_ref());
}
initialised_ = str0_base_ptr_ &&
str1_base_ptr_ &&
str0_node_ptr_ &&
str1_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(1)->value();
std::size_t r0 = 0;
std::size_t r1 = 0;
const range_t& range = (*str1_range_ptr_);
if (range(r0, r1, str1_base_ptr_->size()))
{
AssignmentProcess::execute(str0_node_ptr_->ref(),
str1_base_ptr_->base() + r0,
(r1 - r0) + 1);
branch(0)->value();
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return str0_node_ptr_->str();
}
char_cptr base() const exprtk_override
{
return str0_node_ptr_->base();
}
std::size_t size() const exprtk_override
{
return str0_node_ptr_->size();
}
range_t& range_ref() exprtk_override
{
return str0_node_ptr_->range_ref();
}
const range_t& range_ref() const exprtk_override
{
return str0_node_ptr_->range_ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strass;
}
private:
bool initialised_;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
strvar_node_ptr str0_node_ptr_;
range_ptr str1_range_ptr_;
};
template <typename T, typename AssignmentProcess = asn_assignment>
class assignment_string_range_node exprtk_final
: public binary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef stringvar_node <T>* strvar_node_ptr;
typedef string_range_node<T>* str_rng_node_ptr;
typedef string_base_node <T>* str_base_ptr;
using binary_node<T>::branch;
assignment_string_range_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, initialised_(false)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_rng_node_ptr_(0)
, str0_range_ptr_ (0)
, str1_range_ptr_ (0)
{
if (is_string_range_node(branch(0)))
{
str0_rng_node_ptr_ = static_cast<str_rng_node_ptr>(branch(0));
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
irange_ptr range = dynamic_cast<irange_ptr>(branch(0));
if (0 == range)
return;
str0_range_ptr_ = &(range->range_ref());
}
if (is_generally_string_node(branch(1)))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(branch(1));
if (0 == str1_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(1));
if (0 == range)
return;
str1_range_ptr_ = &(range->range_ref());
}
initialised_ = str0_base_ptr_ &&
str1_base_ptr_ &&
str0_rng_node_ptr_ &&
str0_range_ptr_ &&
str1_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
std::size_t s0_r0 = 0;
std::size_t s0_r1 = 0;
std::size_t s1_r0 = 0;
std::size_t s1_r1 = 0;
const range_t& range0 = (*str0_range_ptr_);
const range_t& range1 = (*str1_range_ptr_);
if (
range0(s0_r0, s0_r1, str0_base_ptr_->size()) &&
range1(s1_r0, s1_r1, str1_base_ptr_->size())
)
{
const std::size_t size = std::min((s0_r1 - s0_r0), (s1_r1 - s1_r0)) + 1;
std::copy(str1_base_ptr_->base() + s1_r0,
str1_base_ptr_->base() + s1_r0 + size,
const_cast<char_ptr>(base() + s0_r0));
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return str0_base_ptr_->str();
}
char_cptr base() const exprtk_override
{
return str0_base_ptr_->base();
}
std::size_t size() const exprtk_override
{
return str0_base_ptr_->size();
}
range_t& range_ref() exprtk_override
{
return str0_rng_node_ptr_->range_ref();
}
const range_t& range_ref() const exprtk_override
{
return str0_rng_node_ptr_->range_ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strass;
}
private:
bool initialised_;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
str_rng_node_ptr str0_rng_node_ptr_;
range_ptr str0_range_ptr_;
range_ptr str1_range_ptr_;
};
template <typename T>
class conditional_string_node exprtk_final
: public trinary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
conditional_string_node(expression_ptr condition,
expression_ptr consequent,
expression_ptr alternative)
: trinary_node<T>(details::e_default, consequent, alternative, condition)
, initialised_(false)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_range_ptr_(0)
, str1_range_ptr_(0)
, condition_ (condition )
, consequent_ (consequent )
, alternative_(alternative)
{
range_.n0_c = std::make_pair<bool,std::size_t>(true,0);
range_.n1_c = std::make_pair<bool,std::size_t>(true,0);
range_.cache.first = range_.n0_c.second;
range_.cache.second = range_.n1_c.second;
if (is_generally_string_node(trinary_node<T>::branch_[0].first))
{
str0_base_ptr_ = dynamic_cast<str_base_ptr>(trinary_node<T>::branch_[0].first);
if (0 == str0_base_ptr_)
return;
str0_range_ptr_ = dynamic_cast<irange_ptr>(trinary_node<T>::branch_[0].first);
if (0 == str0_range_ptr_)
return;
}
if (is_generally_string_node(trinary_node<T>::branch_[1].first))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(trinary_node<T>::branch_[1].first);
if (0 == str1_base_ptr_)
return;
str1_range_ptr_ = dynamic_cast<irange_ptr>(trinary_node<T>::branch_[1].first);
if (0 == str1_range_ptr_)
return;
}
initialised_ = str0_base_ptr_ &&
str1_base_ptr_ &&
str0_range_ptr_ &&
str1_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(condition_ );
assert(consequent_ );
assert(alternative_);
std::size_t r0 = 0;
std::size_t r1 = 0;
if (is_true(condition_))
{
consequent_->value();
const range_t& range = str0_range_ptr_->range_ref();
if (range(r0, r1, str0_base_ptr_->size()))
{
const std::size_t size = (r1 - r0) + 1;
value_.assign(str0_base_ptr_->base() + r0, size);
range_.n1_c.second = value_.size() - 1;
range_.cache.second = range_.n1_c.second;
return T(1);
}
}
else
{
alternative_->value();
const range_t& range = str1_range_ptr_->range_ref();
if (range(r0, r1, str1_base_ptr_->size()))
{
const std::size_t size = (r1 - r0) + 1;
value_.assign(str1_base_ptr_->base() + r0, size);
range_.n1_c.second = value_.size() - 1;
range_.cache.second = range_.n1_c.second;
return T(0);
}
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return value_;
}
char_cptr base() const exprtk_override
{
return &value_[0];
}
std::size_t size() const exprtk_override
{
return value_.size();
}
range_t& range_ref() exprtk_override
{
return range_;
}
const range_t& range_ref() const exprtk_override
{
return range_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strcondition;
}
private:
bool initialised_;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
irange_ptr str0_range_ptr_;
irange_ptr str1_range_ptr_;
mutable range_t range_;
mutable std::string value_;
expression_ptr condition_;
expression_ptr consequent_;
expression_ptr alternative_;
};
template <typename T>
class cons_conditional_str_node exprtk_final
: public binary_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
using binary_node<T>::branch;
cons_conditional_str_node(expression_ptr condition,
expression_ptr consequent)
: binary_node<T>(details::e_default, consequent, condition)
, initialised_(false)
, str0_base_ptr_ (0)
, str0_range_ptr_(0)
, condition_ (condition )
, consequent_(consequent)
{
range_.n0_c = std::make_pair<bool,std::size_t>(true,0);
range_.n1_c = std::make_pair<bool,std::size_t>(true,0);
range_.cache.first = range_.n0_c.second;
range_.cache.second = range_.n1_c.second;
if (is_generally_string_node(branch(0)))
{
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
if (0 == str0_base_ptr_)
return;
str0_range_ptr_ = dynamic_cast<irange_ptr>(branch(0));
if (0 == str0_range_ptr_)
return;
}
initialised_ = str0_base_ptr_ && str0_range_ptr_ ;
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(condition_ );
assert(consequent_);
if (is_true(condition_))
{
consequent_->value();
const range_t& range = str0_range_ptr_->range_ref();
std::size_t r0 = 0;
std::size_t r1 = 0;
if (range(r0, r1, str0_base_ptr_->size()))
{
const std::size_t size = (r1 - r0) + 1;
value_.assign(str0_base_ptr_->base() + r0, size);
range_.n1_c.second = value_.size() - 1;
range_.cache.second = range_.n1_c.second;
return T(1);
}
}
}
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const
{
return value_;
}
char_cptr base() const
{
return &value_[0];
}
std::size_t size() const
{
return value_.size();
}
range_t& range_ref()
{
return range_;
}
const range_t& range_ref() const
{
return range_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strccondition;
}
private:
bool initialised_;
str_base_ptr str0_base_ptr_;
irange_ptr str0_range_ptr_;
mutable range_t range_;
mutable std::string value_;
expression_ptr condition_;
expression_ptr consequent_;
};
template <typename T, typename VarArgFunction>
class str_vararg_node exprtk_final
: public expression_node <T>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef typename range_interface<T>::range_t range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit str_vararg_node(const Sequence<expression_ptr,Allocator>& arg_list)
: initialised_(false)
, str_base_ptr_ (0)
, str_range_ptr_(0)
{
construct_branch_pair(final_node_, const_cast<expression_ptr>(arg_list.back()));
if (0 == final_node_.first)
return;
else if (!is_generally_string_node(final_node_.first))
return;
str_base_ptr_ = dynamic_cast<str_base_ptr>(final_node_.first);
if (0 == str_base_ptr_)
return;
str_range_ptr_ = dynamic_cast<irange_ptr>(final_node_.first);
if (0 == str_range_ptr_)
return;
initialised_ = str_base_ptr_ && str_range_ptr_;
if (arg_list.size() > 1)
{
const std::size_t arg_list_size = arg_list.size() - 1;
arg_list_.resize(arg_list_size);
for (std::size_t i = 0; i < arg_list_size; ++i)
{
if (arg_list[i])
{
construct_branch_pair(arg_list_[i], arg_list[i]);
}
else
{
arg_list_.clear();
return;
}
}
}
}
inline T value() const exprtk_override
{
if (!arg_list_.empty())
{
VarArgFunction::process(arg_list_);
}
final_node_.first->value();
return std::numeric_limits<T>::quiet_NaN();
}
std::string str() const exprtk_override
{
return str_base_ptr_->str();
}
char_cptr base() const exprtk_override
{
return str_base_ptr_->base();
}
std::size_t size() const exprtk_override
{
return str_base_ptr_->size();
}
range_t& range_ref() exprtk_override
{
return str_range_ptr_->range_ref();
}
const range_t& range_ref() const exprtk_override
{
return str_range_ptr_->range_ref();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_stringvararg;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(final_node_ , node_delete_list);
expression_node<T>::ndb_t::collect(arg_list_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return std::max(
expression_node<T>::ndb_t::compute_node_depth(final_node_),
expression_node<T>::ndb_t::compute_node_depth(arg_list_ ));
}
private:
bool initialised_;
branch_t final_node_;
str_base_ptr str_base_ptr_;
irange_ptr str_range_ptr_;
std::vector<branch_t> arg_list_;
};
#endif
template <typename T, std::size_t N>
inline T axn(const T a, const T x)
{
// a*x^n
return a * exprtk::details::numeric::fast_exp<T,N>::result(x);
}
template <typename T, std::size_t N>
inline T axnb(const T a, const T x, const T b)
{
// a*x^n+b
return a * exprtk::details::numeric::fast_exp<T,N>::result(x) + b;
}
template <typename T>
struct sf_base
{
typedef typename details::functor_t<T>::Type Type;
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::qfunc_t quaternary_functor_t;
typedef typename functor_t::tfunc_t trinary_functor_t;
typedef typename functor_t::bfunc_t binary_functor_t;
typedef typename functor_t::ufunc_t unary_functor_t;
};
#define define_sfop3(NN, OP0, OP1) \
template <typename T> \
struct sf##NN##_op : public sf_base<T> \
{ \
typedef typename sf_base<T>::Type const Type; \
static inline T process(Type x, Type y, Type z) \
{ \
return (OP0); \
} \
static inline std::string id() \
{ \
return (OP1); \
} \
}; \
define_sfop3(00,(x + y) / z ,"(t+t)/t")
define_sfop3(01,(x + y) * z ,"(t+t)*t")
define_sfop3(02,(x + y) - z ,"(t+t)-t")
define_sfop3(03,(x + y) + z ,"(t+t)+t")
define_sfop3(04,(x - y) + z ,"(t-t)+t")
define_sfop3(05,(x - y) / z ,"(t-t)/t")
define_sfop3(06,(x - y) * z ,"(t-t)*t")
define_sfop3(07,(x * y) + z ,"(t*t)+t")
define_sfop3(08,(x * y) - z ,"(t*t)-t")
define_sfop3(09,(x * y) / z ,"(t*t)/t")
define_sfop3(10,(x * y) * z ,"(t*t)*t")
define_sfop3(11,(x / y) + z ,"(t/t)+t")
define_sfop3(12,(x / y) - z ,"(t/t)-t")
define_sfop3(13,(x / y) / z ,"(t/t)/t")
define_sfop3(14,(x / y) * z ,"(t/t)*t")
define_sfop3(15,x / (y + z) ,"t/(t+t)")
define_sfop3(16,x / (y - z) ,"t/(t-t)")
define_sfop3(17,x / (y * z) ,"t/(t*t)")
define_sfop3(18,x / (y / z) ,"t/(t/t)")
define_sfop3(19,x * (y + z) ,"t*(t+t)")
define_sfop3(20,x * (y - z) ,"t*(t-t)")
define_sfop3(21,x * (y * z) ,"t*(t*t)")
define_sfop3(22,x * (y / z) ,"t*(t/t)")
define_sfop3(23,x - (y + z) ,"t-(t+t)")
define_sfop3(24,x - (y - z) ,"t-(t-t)")
define_sfop3(25,x - (y / z) ,"t-(t/t)")
define_sfop3(26,x - (y * z) ,"t-(t*t)")
define_sfop3(27,x + (y * z) ,"t+(t*t)")
define_sfop3(28,x + (y / z) ,"t+(t/t)")
define_sfop3(29,x + (y + z) ,"t+(t+t)")
define_sfop3(30,x + (y - z) ,"t+(t-t)")
define_sfop3(31,(axnb<T,2>(x,y,z))," ")
define_sfop3(32,(axnb<T,3>(x,y,z))," ")
define_sfop3(33,(axnb<T,4>(x,y,z))," ")
define_sfop3(34,(axnb<T,5>(x,y,z))," ")
define_sfop3(35,(axnb<T,6>(x,y,z))," ")
define_sfop3(36,(axnb<T,7>(x,y,z))," ")
define_sfop3(37,(axnb<T,8>(x,y,z))," ")
define_sfop3(38,(axnb<T,9>(x,y,z))," ")
define_sfop3(39,x * numeric::log(y) + z,"")
define_sfop3(40,x * numeric::log(y) - z,"")
define_sfop3(41,x * numeric::log10(y) + z,"")
define_sfop3(42,x * numeric::log10(y) - z,"")
define_sfop3(43,x * numeric::sin(y) + z ,"")
define_sfop3(44,x * numeric::sin(y) - z ,"")
define_sfop3(45,x * numeric::cos(y) + z ,"")
define_sfop3(46,x * numeric::cos(y) - z ,"")
define_sfop3(47,details::is_true(x) ? y : z,"")
#define define_sfop4(NN, OP0, OP1) \
template <typename T> \
struct sf##NN##_op : public sf_base<T> \
{ \
typedef typename sf_base<T>::Type const Type; \
static inline T process(Type x, Type y, Type z, Type w) \
{ \
return (OP0); \
} \
static inline std::string id() \
{ \
return (OP1); \
} \
}; \
define_sfop4(48,(x + ((y + z) / w)),"t+((t+t)/t)")
define_sfop4(49,(x + ((y + z) * w)),"t+((t+t)*t)")
define_sfop4(50,(x + ((y - z) / w)),"t+((t-t)/t)")
define_sfop4(51,(x + ((y - z) * w)),"t+((t-t)*t)")
define_sfop4(52,(x + ((y * z) / w)),"t+((t*t)/t)")
define_sfop4(53,(x + ((y * z) * w)),"t+((t*t)*t)")
define_sfop4(54,(x + ((y / z) + w)),"t+((t/t)+t)")
define_sfop4(55,(x + ((y / z) / w)),"t+((t/t)/t)")
define_sfop4(56,(x + ((y / z) * w)),"t+((t/t)*t)")
define_sfop4(57,(x - ((y + z) / w)),"t-((t+t)/t)")
define_sfop4(58,(x - ((y + z) * w)),"t-((t+t)*t)")
define_sfop4(59,(x - ((y - z) / w)),"t-((t-t)/t)")
define_sfop4(60,(x - ((y - z) * w)),"t-((t-t)*t)")
define_sfop4(61,(x - ((y * z) / w)),"t-((t*t)/t)")
define_sfop4(62,(x - ((y * z) * w)),"t-((t*t)*t)")
define_sfop4(63,(x - ((y / z) / w)),"t-((t/t)/t)")
define_sfop4(64,(x - ((y / z) * w)),"t-((t/t)*t)")
define_sfop4(65,(((x + y) * z) - w),"((t+t)*t)-t")
define_sfop4(66,(((x - y) * z) - w),"((t-t)*t)-t")
define_sfop4(67,(((x * y) * z) - w),"((t*t)*t)-t")
define_sfop4(68,(((x / y) * z) - w),"((t/t)*t)-t")
define_sfop4(69,(((x + y) / z) - w),"((t+t)/t)-t")
define_sfop4(70,(((x - y) / z) - w),"((t-t)/t)-t")
define_sfop4(71,(((x * y) / z) - w),"((t*t)/t)-t")
define_sfop4(72,(((x / y) / z) - w),"((t/t)/t)-t")
define_sfop4(73,((x * y) + (z * w)),"(t*t)+(t*t)")
define_sfop4(74,((x * y) - (z * w)),"(t*t)-(t*t)")
define_sfop4(75,((x * y) + (z / w)),"(t*t)+(t/t)")
define_sfop4(76,((x * y) - (z / w)),"(t*t)-(t/t)")
define_sfop4(77,((x / y) + (z / w)),"(t/t)+(t/t)")
define_sfop4(78,((x / y) - (z / w)),"(t/t)-(t/t)")
define_sfop4(79,((x / y) - (z * w)),"(t/t)-(t*t)")
define_sfop4(80,(x / (y + (z * w))),"t/(t+(t*t))")
define_sfop4(81,(x / (y - (z * w))),"t/(t-(t*t))")
define_sfop4(82,(x * (y + (z * w))),"t*(t+(t*t))")
define_sfop4(83,(x * (y - (z * w))),"t*(t-(t*t))")
define_sfop4(84,(axn<T,2>(x,y) + axn<T,2>(z,w)),"")
define_sfop4(85,(axn<T,3>(x,y) + axn<T,3>(z,w)),"")
define_sfop4(86,(axn<T,4>(x,y) + axn<T,4>(z,w)),"")
define_sfop4(87,(axn<T,5>(x,y) + axn<T,5>(z,w)),"")
define_sfop4(88,(axn<T,6>(x,y) + axn<T,6>(z,w)),"")
define_sfop4(89,(axn<T,7>(x,y) + axn<T,7>(z,w)),"")
define_sfop4(90,(axn<T,8>(x,y) + axn<T,8>(z,w)),"")
define_sfop4(91,(axn<T,9>(x,y) + axn<T,9>(z,w)),"")
define_sfop4(92,((details::is_true(x) && details::is_true(y)) ? z : w),"")
define_sfop4(93,((details::is_true(x) || details::is_true(y)) ? z : w),"")
define_sfop4(94,((x < y) ? z : w),"")
define_sfop4(95,((x <= y) ? z : w),"")
define_sfop4(96,((x > y) ? z : w),"")
define_sfop4(97,((x >= y) ? z : w),"")
define_sfop4(98,(details::is_true(numeric::equal(x,y)) ? z : w),"")
define_sfop4(99,(x * numeric::sin(y) + z * numeric::cos(w)),"")
define_sfop4(ext00,((x + y) - (z * w)),"(t+t)-(t*t)")
define_sfop4(ext01,((x + y) - (z / w)),"(t+t)-(t/t)")
define_sfop4(ext02,((x + y) + (z * w)),"(t+t)+(t*t)")
define_sfop4(ext03,((x + y) + (z / w)),"(t+t)+(t/t)")
define_sfop4(ext04,((x - y) + (z * w)),"(t-t)+(t*t)")
define_sfop4(ext05,((x - y) + (z / w)),"(t-t)+(t/t)")
define_sfop4(ext06,((x - y) - (z * w)),"(t-t)-(t*t)")
define_sfop4(ext07,((x - y) - (z / w)),"(t-t)-(t/t)")
define_sfop4(ext08,((x + y) - (z - w)),"(t+t)-(t-t)")
define_sfop4(ext09,((x + y) + (z - w)),"(t+t)+(t-t)")
define_sfop4(ext10,((x + y) + (z + w)),"(t+t)+(t+t)")
define_sfop4(ext11,((x + y) * (z - w)),"(t+t)*(t-t)")
define_sfop4(ext12,((x + y) / (z - w)),"(t+t)/(t-t)")
define_sfop4(ext13,((x - y) - (z + w)),"(t-t)-(t+t)")
define_sfop4(ext14,((x - y) + (z + w)),"(t-t)+(t+t)")
define_sfop4(ext15,((x - y) * (z + w)),"(t-t)*(t+t)")
define_sfop4(ext16,((x - y) / (z + w)),"(t-t)/(t+t)")
define_sfop4(ext17,((x * y) - (z + w)),"(t*t)-(t+t)")
define_sfop4(ext18,((x / y) - (z + w)),"(t/t)-(t+t)")
define_sfop4(ext19,((x * y) + (z + w)),"(t*t)+(t+t)")
define_sfop4(ext20,((x / y) + (z + w)),"(t/t)+(t+t)")
define_sfop4(ext21,((x * y) + (z - w)),"(t*t)+(t-t)")
define_sfop4(ext22,((x / y) + (z - w)),"(t/t)+(t-t)")
define_sfop4(ext23,((x * y) - (z - w)),"(t*t)-(t-t)")
define_sfop4(ext24,((x / y) - (z - w)),"(t/t)-(t-t)")
define_sfop4(ext25,((x + y) * (z * w)),"(t+t)*(t*t)")
define_sfop4(ext26,((x + y) * (z / w)),"(t+t)*(t/t)")
define_sfop4(ext27,((x + y) / (z * w)),"(t+t)/(t*t)")
define_sfop4(ext28,((x + y) / (z / w)),"(t+t)/(t/t)")
define_sfop4(ext29,((x - y) / (z * w)),"(t-t)/(t*t)")
define_sfop4(ext30,((x - y) / (z / w)),"(t-t)/(t/t)")
define_sfop4(ext31,((x - y) * (z * w)),"(t-t)*(t*t)")
define_sfop4(ext32,((x - y) * (z / w)),"(t-t)*(t/t)")
define_sfop4(ext33,((x * y) * (z + w)),"(t*t)*(t+t)")
define_sfop4(ext34,((x / y) * (z + w)),"(t/t)*(t+t)")
define_sfop4(ext35,((x * y) / (z + w)),"(t*t)/(t+t)")
define_sfop4(ext36,((x / y) / (z + w)),"(t/t)/(t+t)")
define_sfop4(ext37,((x * y) / (z - w)),"(t*t)/(t-t)")
define_sfop4(ext38,((x / y) / (z - w)),"(t/t)/(t-t)")
define_sfop4(ext39,((x * y) * (z - w)),"(t*t)*(t-t)")
define_sfop4(ext40,((x * y) / (z * w)),"(t*t)/(t*t)")
define_sfop4(ext41,((x / y) * (z / w)),"(t/t)*(t/t)")
define_sfop4(ext42,((x / y) * (z - w)),"(t/t)*(t-t)")
define_sfop4(ext43,((x * y) * (z * w)),"(t*t)*(t*t)")
define_sfop4(ext44,(x + (y * (z / w))),"t+(t*(t/t))")
define_sfop4(ext45,(x - (y * (z / w))),"t-(t*(t/t))")
define_sfop4(ext46,(x + (y / (z * w))),"t+(t/(t*t))")
define_sfop4(ext47,(x - (y / (z * w))),"t-(t/(t*t))")
define_sfop4(ext48,(((x - y) - z) * w),"((t-t)-t)*t")
define_sfop4(ext49,(((x - y) - z) / w),"((t-t)-t)/t")
define_sfop4(ext50,(((x - y) + z) * w),"((t-t)+t)*t")
define_sfop4(ext51,(((x - y) + z) / w),"((t-t)+t)/t")
define_sfop4(ext52,((x + (y - z)) * w),"(t+(t-t))*t")
define_sfop4(ext53,((x + (y - z)) / w),"(t+(t-t))/t")
define_sfop4(ext54,((x + y) / (z + w)),"(t+t)/(t+t)")
define_sfop4(ext55,((x - y) / (z - w)),"(t-t)/(t-t)")
define_sfop4(ext56,((x + y) * (z + w)),"(t+t)*(t+t)")
define_sfop4(ext57,((x - y) * (z - w)),"(t-t)*(t-t)")
define_sfop4(ext58,((x - y) + (z - w)),"(t-t)+(t-t)")
define_sfop4(ext59,((x - y) - (z - w)),"(t-t)-(t-t)")
define_sfop4(ext60,((x / y) + (z * w)),"(t/t)+(t*t)")
define_sfop4(ext61,(((x * y) * z) / w),"((t*t)*t)/t")
#undef define_sfop3
#undef define_sfop4
template <typename T, typename SpecialFunction>
class sf3_node exprtk_final : public trinary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
sf3_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1,
expression_ptr branch2)
: trinary_node<T>(opr, branch0, branch1, branch2)
{}
inline T value() const exprtk_override
{
assert(trinary_node<T>::branch_[0].first);
assert(trinary_node<T>::branch_[1].first);
assert(trinary_node<T>::branch_[2].first);
const T x = trinary_node<T>::branch_[0].first->value();
const T y = trinary_node<T>::branch_[1].first->value();
const T z = trinary_node<T>::branch_[2].first->value();
return SpecialFunction::process(x, y, z);
}
};
template <typename T, typename SpecialFunction>
class sf4_node exprtk_final : public quaternary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
sf4_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1,
expression_ptr branch2,
expression_ptr branch3)
: quaternary_node<T>(opr, branch0, branch1, branch2, branch3)
{}
inline T value() const exprtk_override
{
assert(quaternary_node<T>::branch_[0].first);
assert(quaternary_node<T>::branch_[1].first);
assert(quaternary_node<T>::branch_[2].first);
assert(quaternary_node<T>::branch_[3].first);
const T x = quaternary_node<T>::branch_[0].first->value();
const T y = quaternary_node<T>::branch_[1].first->value();
const T z = quaternary_node<T>::branch_[2].first->value();
const T w = quaternary_node<T>::branch_[3].first->value();
return SpecialFunction::process(x, y, z, w);
}
};
template <typename T, typename SpecialFunction>
class sf3_var_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
sf3_var_node(const T& v0, const T& v1, const T& v2)
: v0_(v0)
, v1_(v1)
, v2_(v2)
{}
inline T value() const exprtk_override
{
return SpecialFunction::process(v0_, v1_, v2_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_trinary;
}
private:
sf3_var_node(const sf3_var_node<T,SpecialFunction>&) exprtk_delete;
sf3_var_node<T,SpecialFunction>& operator=(const sf3_var_node<T,SpecialFunction>&) exprtk_delete;
const T& v0_;
const T& v1_;
const T& v2_;
};
template <typename T, typename SpecialFunction>
class sf4_var_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
sf4_var_node(const T& v0, const T& v1, const T& v2, const T& v3)
: v0_(v0)
, v1_(v1)
, v2_(v2)
, v3_(v3)
{}
inline T value() const exprtk_override
{
return SpecialFunction::process(v0_, v1_, v2_, v3_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_trinary;
}
private:
sf4_var_node(const sf4_var_node<T,SpecialFunction>&) exprtk_delete;
sf4_var_node<T,SpecialFunction>& operator=(const sf4_var_node<T,SpecialFunction>&) exprtk_delete;
const T& v0_;
const T& v1_;
const T& v2_;
const T& v3_;
};
template <typename T, typename VarArgFunction>
class vararg_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit vararg_node(const Sequence<expression_ptr,Allocator>& arg_list)
{
arg_list_.resize(arg_list.size());
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (arg_list[i])
{
construct_branch_pair(arg_list_[i],arg_list[i]);
}
else
{
arg_list_.clear();
return;
}
}
}
inline T value() const exprtk_override
{
return VarArgFunction::process(arg_list_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vararg;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(arg_list_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(arg_list_);
}
private:
std::vector<branch_t> arg_list_;
};
template <typename T, typename VarArgFunction>
class vararg_varnode exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
template <typename Allocator,
template <typename, typename> class Sequence>
explicit vararg_varnode(const Sequence<expression_ptr,Allocator>& arg_list)
{
arg_list_.resize(arg_list.size());
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (arg_list[i] && is_variable_node(arg_list[i]))
{
variable_node<T>* var_node_ptr = static_cast<variable_node<T>*>(arg_list[i]);
arg_list_[i] = (&var_node_ptr->ref());
}
else
{
arg_list_.clear();
return;
}
}
}
inline T value() const exprtk_override
{
if (!arg_list_.empty())
return VarArgFunction::process(arg_list_);
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vararg;
}
private:
std::vector<const T*> arg_list_;
};
template <typename T, typename VecFunction>
class vectorize_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
explicit vectorize_node(const expression_ptr v)
: ivec_ptr_(0)
{
construct_branch_pair(v_, v);
if (is_ivector_node(v_.first))
{
ivec_ptr_ = dynamic_cast<vector_interface<T>*>(v_.first);
}
else
ivec_ptr_ = 0;
}
inline T value() const exprtk_override
{
if (ivec_ptr_)
{
assert(v_.first);
v_.first->value();
return VecFunction::process(ivec_ptr_);
}
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecfunc;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(v_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(v_);
}
private:
vector_interface<T>* ivec_ptr_;
branch_t v_;
};
template <typename T>
class assignment_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, var_node_ptr_(0)
{
if (is_variable_node(branch(0)))
{
var_node_ptr_ = static_cast<variable_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (var_node_ptr_)
{
assert(branch(1));
T& result = var_node_ptr_->ref();
result = branch(1)->value();
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
variable_node<T>* var_node_ptr_;
};
template <typename T>
class assignment_vec_elem_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_vec_elem_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec_node_ptr_(0)
{
if (is_vector_elem_node(branch(0)))
{
vec_node_ptr_ = static_cast<vector_elem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (vec_node_ptr_)
{
assert(branch(1));
T& result = vec_node_ptr_->ref();
result = branch(1)->value();
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
vector_elem_node<T>* vec_node_ptr_;
};
template <typename T>
class assignment_rebasevec_elem_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using expression_node<T>::branch;
assignment_rebasevec_elem_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, rbvec_node_ptr_(0)
{
if (is_rebasevector_elem_node(branch(0)))
{
rbvec_node_ptr_ = static_cast<rebasevector_elem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (rbvec_node_ptr_)
{
assert(branch(1));
T& result = rbvec_node_ptr_->ref();
result = branch(1)->value();
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
rebasevector_elem_node<T>* rbvec_node_ptr_;
};
template <typename T>
class assignment_rebasevec_celem_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_rebasevec_celem_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, rbvec_node_ptr_(0)
{
if (is_rebasevector_celem_node(branch(0)))
{
rbvec_node_ptr_ = static_cast<rebasevector_celem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (rbvec_node_ptr_)
{
assert(branch(1));
T& result = rbvec_node_ptr_->ref();
result = branch(1)->value();
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
rebasevector_celem_node<T>* rbvec_node_ptr_;
};
template <typename T>
class assignment_vec_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
assignment_vec_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec_node_ptr_(0)
{
if (is_vector_node(branch(0)))
{
vec_node_ptr_ = static_cast<vector_node<T>*>(branch(0));
vds() = vec_node_ptr_->vds();
}
}
inline T value() const exprtk_override
{
if (vec_node_ptr_)
{
assert(branch(1));
const T v = branch(1)->value();
T* vec = vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec + lud.upper_bound;
while (vec < upper_bound)
{
#define exprtk_loop(N) \
vec[N] = v; \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec += lud.batch_size;
}
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : *vec++ = v; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return vec_node_ptr_->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return vec_node_ptr_;
}
vector_node_ptr vec() exprtk_override
{
return vec_node_ptr_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvalass;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node<T>* vec_node_ptr_;
vds_t vds_;
};
template <typename T>
class assignment_vecvec_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
assignment_vecvec_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec0_node_ptr_(0)
, vec1_node_ptr_(0)
, initialised_(false)
, src_is_ivec_(false)
{
if (is_vector_node(branch(0)))
{
vec0_node_ptr_ = static_cast<vector_node<T>*>(branch(0));
vds() = vec0_node_ptr_->vds();
}
if (is_vector_node(branch(1)))
{
vec1_node_ptr_ = static_cast<vector_node<T>*>(branch(1));
vds_t::match_sizes(vds(),vec1_node_ptr_->vds());
}
else if (is_ivector_node(branch(1)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(1))))
{
vec1_node_ptr_ = vi->vec();
if (!vi->side_effect())
{
vi->vds() = vds();
src_is_ivec_ = true;
}
else
vds_t::match_sizes(vds(),vi->vds());
}
}
initialised_ = (vec0_node_ptr_ && vec1_node_ptr_);
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(1));
branch(1)->value();
if (src_is_ivec_)
return vec0_node_ptr_->value();
T* vec0 = vec0_node_ptr_->vds().data();
T* vec1 = vec1_node_ptr_->vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec0 + lud.upper_bound;
while (vec0 < upper_bound)
{
#define exprtk_loop(N) \
vec0[N] = vec1[N]; \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
}
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : *vec0++ = *vec1++; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return vec0_node_ptr_->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() exprtk_override
{
return vec0_node_ptr_;
}
vector_node_ptr vec() const exprtk_override
{
return vec0_node_ptr_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvecass;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node<T>* vec0_node_ptr_;
vector_node<T>* vec1_node_ptr_;
bool initialised_;
bool src_is_ivec_;
vds_t vds_;
};
template <typename T, typename Operation>
class assignment_op_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, var_node_ptr_(0)
{
if (is_variable_node(branch(0)))
{
var_node_ptr_ = static_cast<variable_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (var_node_ptr_)
{
assert(branch(1));
T& v = var_node_ptr_->ref();
v = Operation::process(v,branch(1)->value());
return v;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
variable_node<T>* var_node_ptr_;
};
template <typename T, typename Operation>
class assignment_vec_elem_op_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_vec_elem_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec_node_ptr_(0)
{
if (is_vector_elem_node(branch(0)))
{
vec_node_ptr_ = static_cast<vector_elem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (vec_node_ptr_)
{
assert(branch(1));
T& v = vec_node_ptr_->ref();
v = Operation::process(v,branch(1)->value());
return v;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
vector_elem_node<T>* vec_node_ptr_;
};
template <typename T, typename Operation>
class assignment_rebasevec_elem_op_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_rebasevec_elem_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, rbvec_node_ptr_(0)
{
if (is_rebasevector_elem_node(branch(0)))
{
rbvec_node_ptr_ = static_cast<rebasevector_elem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (rbvec_node_ptr_)
{
assert(branch(1));
T& v = rbvec_node_ptr_->ref();
v = Operation::process(v,branch(1)->value());
return v;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
rebasevector_elem_node<T>* rbvec_node_ptr_;
};
template <typename T, typename Operation>
class assignment_rebasevec_celem_op_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
assignment_rebasevec_celem_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, rbvec_node_ptr_(0)
{
if (is_rebasevector_celem_node(branch(0)))
{
rbvec_node_ptr_ = static_cast<rebasevector_celem_node<T>*>(branch(0));
}
}
inline T value() const exprtk_override
{
if (rbvec_node_ptr_)
{
assert(branch(1));
T& v = rbvec_node_ptr_->ref();
v = Operation::process(v,branch(1)->value());
return v;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
private:
rebasevector_celem_node<T>* rbvec_node_ptr_;
};
template <typename T, typename Operation>
class assignment_vec_op_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
assignment_vec_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec_node_ptr_(0)
{
if (is_vector_node(branch(0)))
{
vec_node_ptr_ = static_cast<vector_node<T>*>(branch(0));
vds() = vec_node_ptr_->vds();
}
}
inline T value() const exprtk_override
{
if (vec_node_ptr_)
{
assert(branch(1));
const T v = branch(1)->value();
T* vec = vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec + lud.upper_bound;
while (vec < upper_bound)
{
#define exprtk_loop(N) \
Operation::assign(vec[N],v); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec += lud.batch_size;
}
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : Operation::assign(*vec++,v); \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return vec_node_ptr_->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return vec_node_ptr_;
}
vector_node_ptr vec() exprtk_override
{
return vec_node_ptr_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecopvalass;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
bool side_effect() const exprtk_override
{
return true;
}
private:
vector_node<T>* vec_node_ptr_;
vds_t vds_;
};
template <typename T, typename Operation>
class assignment_vecvec_op_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
assignment_vecvec_op_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec0_node_ptr_(0)
, vec1_node_ptr_(0)
, initialised_(false)
{
if (is_vector_node(branch(0)))
{
vec0_node_ptr_ = static_cast<vector_node<T>*>(branch(0));
vds() = vec0_node_ptr_->vds();
}
if (is_vector_node(branch(1)))
{
vec1_node_ptr_ = static_cast<vector_node<T>*>(branch(1));
vec1_node_ptr_->vds() = vds();
}
else if (is_ivector_node(branch(1)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(1))))
{
vec1_node_ptr_ = vi->vec();
vec1_node_ptr_->vds() = vds();
}
else
vds_t::match_sizes(vds(),vec1_node_ptr_->vds());
}
initialised_ = (vec0_node_ptr_ && vec1_node_ptr_);
assert(initialised_);
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
T* vec0 = vec0_node_ptr_->vds().data();
const T* vec1 = vec1_node_ptr_->vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec0 + lud.upper_bound;
while (vec0 < upper_bound)
{
#define exprtk_loop(N) \
vec0[N] = Operation::process(vec0[N], vec1[N]); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { vec0[i] = Operation::process(vec0[i], vec1[i]); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return vec0_node_ptr_->value();
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return vec0_node_ptr_;
}
vector_node_ptr vec() exprtk_override
{
return vec0_node_ptr_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecopvecass;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
bool side_effect() const exprtk_override
{
return true;
}
private:
vector_node<T>* vec0_node_ptr_;
vector_node<T>* vec1_node_ptr_;
bool initialised_;
vds_t vds_;
};
template <typename T, typename Operation>
class vec_binop_vecvec_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vector_holder<T>* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
vec_binop_vecvec_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec0_node_ptr_(0)
, vec1_node_ptr_(0)
, temp_ (0)
, temp_vec_node_(0)
, initialised_(false)
{
bool v0_is_ivec = false;
bool v1_is_ivec = false;
if (is_vector_node(branch(0)))
{
vec0_node_ptr_ = static_cast<vector_node_ptr>(branch(0));
}
else if (is_ivector_node(branch(0)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(0))))
{
vec0_node_ptr_ = vi->vec();
v0_is_ivec = true;
}
}
if (is_vector_node(branch(1)))
{
vec1_node_ptr_ = static_cast<vector_node_ptr>(branch(1));
}
else if (is_ivector_node(branch(1)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(1))))
{
vec1_node_ptr_ = vi->vec();
v1_is_ivec = true;
}
}
if (vec0_node_ptr_ && vec1_node_ptr_)
{
vector_holder<T>& vec0 = vec0_node_ptr_->vec_holder();
vector_holder<T>& vec1 = vec1_node_ptr_->vec_holder();
if (v0_is_ivec && (vec0.size() <= vec1.size()))
vds_ = vds_t(vec0_node_ptr_->vds());
else if (v1_is_ivec && (vec1.size() <= vec0.size()))
vds_ = vds_t(vec1_node_ptr_->vds());
else
vds_ = vds_t(std::min(vec0.size(),vec1.size()));
temp_ = new vector_holder<T>(vds().data(),vds().size());
temp_vec_node_ = new vector_node <T>(vds(),temp_);
initialised_ = true;
}
assert(initialised_);
}
~vec_binop_vecvec_node()
{
delete temp_;
delete temp_vec_node_;
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
branch(1)->value();
const T* vec0 = vec0_node_ptr_->vds().data();
const T* vec1 = vec1_node_ptr_->vds().data();
T* vec2 = vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec2 + lud.upper_bound;
while (vec2 < upper_bound)
{
#define exprtk_loop(N) \
vec2[N] = Operation::process(vec0[N], vec1[N]); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
vec2 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { vec2[i] = Operation::process(vec0[i], vec1[i]); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (vds().data())[0];
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return temp_vec_node_;
}
vector_node_ptr vec() exprtk_override
{
return temp_vec_node_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvecarith;
}
std::size_t size() const exprtk_override
{
return vds_.size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node_ptr vec0_node_ptr_;
vector_node_ptr vec1_node_ptr_;
vector_holder_ptr temp_;
vector_node_ptr temp_vec_node_;
bool initialised_;
vds_t vds_;
};
template <typename T, typename Operation>
class vec_binop_vecval_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vector_holder<T>* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
vec_binop_vecval_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec0_node_ptr_(0)
, temp_ (0)
, temp_vec_node_(0)
{
bool v0_is_ivec = false;
if (is_vector_node(branch(0)))
{
vec0_node_ptr_ = static_cast<vector_node_ptr>(branch(0));
}
else if (is_ivector_node(branch(0)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(0))))
{
vec0_node_ptr_ = vi->vec();
v0_is_ivec = true;
}
}
if (vec0_node_ptr_)
{
if (v0_is_ivec)
vds() = vec0_node_ptr_->vds();
else
vds() = vds_t(vec0_node_ptr_->size());
temp_ = new vector_holder<T>(vds());
temp_vec_node_ = new vector_node <T>(vds(),temp_);
}
}
~vec_binop_vecval_node()
{
delete temp_;
delete temp_vec_node_;
}
inline T value() const exprtk_override
{
if (vec0_node_ptr_)
{
assert(branch(0));
assert(branch(1));
branch(0)->value();
const T v = branch(1)->value();
const T* vec0 = vec0_node_ptr_->vds().data();
T* vec1 = vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec0 + lud.upper_bound;
while (vec0 < upper_bound)
{
#define exprtk_loop(N) \
vec1[N] = Operation::process(vec0[N], v); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { vec1[i] = Operation::process(vec0[i], v); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (vds().data())[0];
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return temp_vec_node_;
}
vector_node_ptr vec() exprtk_override
{
return temp_vec_node_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvalarith;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node_ptr vec0_node_ptr_;
vector_holder_ptr temp_;
vector_node_ptr temp_vec_node_;
vds_t vds_;
};
template <typename T, typename Operation>
class vec_binop_valvec_node exprtk_final
: public binary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vector_holder<T>* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
using binary_node<T>::branch;
vec_binop_valvec_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, vec1_node_ptr_(0)
, temp_ (0)
, temp_vec_node_(0)
{
bool v1_is_ivec = false;
if (is_vector_node(branch(1)))
{
vec1_node_ptr_ = static_cast<vector_node_ptr>(branch(1));
}
else if (is_ivector_node(branch(1)))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch(1))))
{
vec1_node_ptr_ = vi->vec();
v1_is_ivec = true;
}
}
if (vec1_node_ptr_)
{
if (v1_is_ivec)
vds() = vec1_node_ptr_->vds();
else
vds() = vds_t(vec1_node_ptr_->size());
temp_ = new vector_holder<T>(vds());
temp_vec_node_ = new vector_node <T>(vds(),temp_);
}
}
~vec_binop_valvec_node()
{
delete temp_;
delete temp_vec_node_;
}
inline T value() const exprtk_override
{
if (vec1_node_ptr_)
{
assert(branch(0));
assert(branch(1));
const T v = branch(0)->value();
branch(1)->value();
T* vec0 = vds().data();
const T* vec1 = vec1_node_ptr_->vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec0 + lud.upper_bound;
while (vec0 < upper_bound)
{
#define exprtk_loop(N) \
vec0[N] = Operation::process(v, vec1[N]); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { vec0[i] = Operation::process(v, vec1[i]); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (vds().data())[0];
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return temp_vec_node_;
}
vector_node_ptr vec() exprtk_override
{
return temp_vec_node_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecvalarith;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node_ptr vec1_node_ptr_;
vector_holder_ptr temp_;
vector_node_ptr temp_vec_node_;
vds_t vds_;
};
template <typename T, typename Operation>
class unary_vector_node exprtk_final
: public unary_node <T>
, public vector_interface<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef vector_node<T>* vector_node_ptr;
typedef vector_holder<T>* vector_holder_ptr;
typedef vec_data_store<T> vds_t;
using expression_node<T>::branch;
unary_vector_node(const operator_type& opr, expression_ptr branch0)
: unary_node<T>(opr, branch0)
, vec0_node_ptr_(0)
, temp_ (0)
, temp_vec_node_(0)
{
bool vec0_is_ivec = false;
if (is_vector_node(branch()))
{
vec0_node_ptr_ = static_cast<vector_node_ptr>(branch());
}
else if (is_ivector_node(branch()))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 != (vi = dynamic_cast<vector_interface<T>*>(branch())))
{
vec0_node_ptr_ = vi->vec();
vec0_is_ivec = true;
}
}
if (vec0_node_ptr_)
{
if (vec0_is_ivec)
vds_ = vec0_node_ptr_->vds();
else
vds_ = vds_t(vec0_node_ptr_->size());
temp_ = new vector_holder<T>(vds());
temp_vec_node_ = new vector_node <T>(vds(),temp_);
}
}
~unary_vector_node()
{
delete temp_;
delete temp_vec_node_;
}
inline T value() const exprtk_override
{
assert(branch());
branch()->value();
if (vec0_node_ptr_)
{
const T* vec0 = vec0_node_ptr_->vds().data();
T* vec1 = vds().data();
loop_unroll::details lud(size());
const T* upper_bound = vec0 + lud.upper_bound;
while (vec0 < upper_bound)
{
#define exprtk_loop(N) \
vec1[N] = Operation::process(vec0[N]); \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec0 += lud.batch_size;
vec1 += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : { vec1[i] = Operation::process(vec0[i]); ++i; } \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (vds().data())[0];
}
else
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return temp_vec_node_;
}
vector_node_ptr vec() exprtk_override
{
return temp_vec_node_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecunaryop;
}
std::size_t size() const exprtk_override
{
return vds().size();
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
private:
vector_node_ptr vec0_node_ptr_;
vector_holder_ptr temp_;
vector_node_ptr temp_vec_node_;
vds_t vds_;
};
template <typename T>
class conditional_vector_node exprtk_final
: public expression_node <T>
, public vector_interface<T>
{
public:
typedef expression_node <T>* expression_ptr;
typedef vector_interface<T>* vec_interface_ptr;
typedef vector_node <T>* vector_node_ptr;
typedef vector_holder <T>* vector_holder_ptr;
typedef vec_data_store <T> vds_t;
typedef std::pair<expression_ptr,bool> branch_t;
conditional_vector_node(expression_ptr condition,
expression_ptr consequent,
expression_ptr alternative)
: consequent_node_ptr_ (0)
, alternative_node_ptr_(0)
, temp_vec_node_ (0)
, temp_ (0)
, vec_size_ (0)
, initialised_ (false)
{
construct_branch_pair(condition_ , condition );
construct_branch_pair(consequent_ , consequent );
construct_branch_pair(alternative_, alternative);
if (details::is_ivector_node(consequent_.first))
{
vec_interface_ptr ivec_ptr = dynamic_cast<vec_interface_ptr>(consequent_.first);
if (0 != ivec_ptr)
{
consequent_node_ptr_ = ivec_ptr->vec();
}
}
if (details::is_ivector_node(alternative_.first))
{
vec_interface_ptr ivec_ptr = dynamic_cast<vec_interface_ptr>(alternative_.first);
if (0 != ivec_ptr)
{
alternative_node_ptr_ = ivec_ptr->vec();
}
}
if (consequent_node_ptr_ && alternative_node_ptr_)
{
vec_size_ = std::min(consequent_node_ptr_ ->vds().size(),
alternative_node_ptr_->vds().size());
vds_ = vds_t(vec_size_);
temp_ = new vector_holder<T>(vds_);
temp_vec_node_ = new vector_node <T>(vds(),temp_);
initialised_ = true;
}
assert(initialised_ && (vec_size_ > 0));
}
~conditional_vector_node()
{
delete temp_;
delete temp_vec_node_;
}
inline T value() const exprtk_override
{
if (initialised_)
{
assert(condition_ .first);
assert(consequent_ .first);
assert(alternative_.first);
T result = T(0);
T* source_vector = 0;
T* result_vector = vds().data();
if (is_true(condition_))
{
result = consequent_.first->value();
source_vector = consequent_node_ptr_->vds().data();
}
else
{
result = alternative_.first->value();
source_vector = alternative_node_ptr_->vds().data();
}
for (std::size_t i = 0; i < vec_size_; ++i)
{
result_vector[i] = source_vector[i];
}
return result;
}
return std::numeric_limits<T>::quiet_NaN();
}
vector_node_ptr vec() const exprtk_override
{
return temp_vec_node_;
}
vector_node_ptr vec() exprtk_override
{
return temp_vec_node_;
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vecondition;
}
std::size_t size() const exprtk_override
{
return vec_size_;
}
vds_t& vds() exprtk_override
{
return vds_;
}
const vds_t& vds() const exprtk_override
{
return vds_;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(condition_ , node_delete_list);
expression_node<T>::ndb_t::collect(consequent_ , node_delete_list);
expression_node<T>::ndb_t::collect(alternative_ , node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth
(condition_, consequent_, alternative_);
}
private:
branch_t condition_;
branch_t consequent_;
branch_t alternative_;
vector_node_ptr consequent_node_ptr_;
vector_node_ptr alternative_node_ptr_;
vector_node_ptr temp_vec_node_;
vector_holder_ptr temp_;
vds_t vds_;
std::size_t vec_size_;
bool initialised_;
};
template <typename T>
class scand_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
scand_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
{}
inline T value() const exprtk_override
{
assert(branch(0));
assert(branch(1));
return (
std::not_equal_to<T>()
(T(0),branch(0)->value()) &&
std::not_equal_to<T>()
(T(0),branch(1)->value())
) ? T(1) : T(0);
}
};
template <typename T>
class scor_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
using binary_node<T>::branch;
scor_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
{}
inline T value() const exprtk_override
{
assert(branch(0));
assert(branch(1));
return (
std::not_equal_to<T>()
(T(0),branch(0)->value()) ||
std::not_equal_to<T>()
(T(0),branch(1)->value())
) ? T(1) : T(0);
}
};
template <typename T, typename IFunction, std::size_t N>
class function_N_node exprtk_final : public expression_node<T>
{
public:
// Function of N paramters.
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
typedef IFunction ifunction;
explicit function_N_node(ifunction* func)
: function_((N == func->param_count) ? func : reinterpret_cast<ifunction*>(0))
, parameter_count_(func->param_count)
{}
template <std::size_t NumBranches>
bool init_branches(expression_ptr (&b)[NumBranches])
{
// Needed for incompetent and broken msvc compiler versions
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
if (N != NumBranches)
return false;
else
{
for (std::size_t i = 0; i < NumBranches; ++i)
{
if (b[i])
branch_[i] = std::make_pair(b[i],branch_deletable(b[i]));
else
return false;
}
return true;
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
inline bool operator <(const function_N_node<T,IFunction,N>& fn) const
{
return this < (&fn);
}
inline T value() const exprtk_override
{
// Needed for incompetent and broken msvc compiler versions
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
if ((0 == function_) || (0 == N))
return std::numeric_limits<T>::quiet_NaN();
else
{
T v[N];
evaluate_branches<T,N>::execute(v,branch_);
return invoke<T,N>::execute(*function_,v);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_function;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::template compute_node_depth<N>(branch_);
}
template <typename T_, std::size_t BranchCount>
struct evaluate_branches
{
static inline void execute(T_ (&v)[BranchCount], const branch_t (&b)[BranchCount])
{
for (std::size_t i = 0; i < BranchCount; ++i)
{
v[i] = b[i].first->value();
}
}
};
template <typename T_>
struct evaluate_branches <T_,5>
{
static inline void execute(T_ (&v)[5], const branch_t (&b)[5])
{
v[0] = b[0].first->value();
v[1] = b[1].first->value();
v[2] = b[2].first->value();
v[3] = b[3].first->value();
v[4] = b[4].first->value();
}
};
template <typename T_>
struct evaluate_branches <T_,4>
{
static inline void execute(T_ (&v)[4], const branch_t (&b)[4])
{
v[0] = b[0].first->value();
v[1] = b[1].first->value();
v[2] = b[2].first->value();
v[3] = b[3].first->value();
}
};
template <typename T_>
struct evaluate_branches <T_,3>
{
static inline void execute(T_ (&v)[3], const branch_t (&b)[3])
{
v[0] = b[0].first->value();
v[1] = b[1].first->value();
v[2] = b[2].first->value();
}
};
template <typename T_>
struct evaluate_branches <T_,2>
{
static inline void execute(T_ (&v)[2], const branch_t (&b)[2])
{
v[0] = b[0].first->value();
v[1] = b[1].first->value();
}
};
template <typename T_>
struct evaluate_branches <T_,1>
{
static inline void execute(T_ (&v)[1], const branch_t (&b)[1])
{
v[0] = b[0].first->value();
}
};
template <typename T_, std::size_t ParamCount>
struct invoke { static inline T execute(ifunction&, branch_t (&)[ParamCount]) { return std::numeric_limits<T_>::quiet_NaN(); } };
template <typename T_>
struct invoke<T_,20>
{
static inline T_ execute(ifunction& f, T_ (&v)[20])
{ return f(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15],v[16],v[17],v[18],v[19]); }
};
template <typename T_>
struct invoke<T_,19>
{
static inline T_ execute(ifunction& f, T_ (&v)[19])
{ return f(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15],v[16],v[17],v[18]); }
};
template <typename T_>
struct invoke<T_,18>
{
static inline T_ execute(ifunction& f, T_ (&v)[18])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15], v[16], v[17]); }
};
template <typename T_>
struct invoke<T_,17>
{
static inline T_ execute(ifunction& f, T_ (&v)[17])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15], v[16]); }
};
template <typename T_>
struct invoke<T_,16>
{
static inline T_ execute(ifunction& f, T_ (&v)[16])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]); }
};
template <typename T_>
struct invoke<T_,15>
{
static inline T_ execute(ifunction& f, T_ (&v)[15])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14]); }
};
template <typename T_>
struct invoke<T_,14>
{
static inline T_ execute(ifunction& f, T_ (&v)[14])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13]); }
};
template <typename T_>
struct invoke<T_,13>
{
static inline T_ execute(ifunction& f, T_ (&v)[13])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]); }
};
template <typename T_>
struct invoke<T_,12>
{
static inline T_ execute(ifunction& f, T_ (&v)[12])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]); }
};
template <typename T_>
struct invoke<T_,11>
{
static inline T_ execute(ifunction& f, T_ (&v)[11])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]); }
};
template <typename T_>
struct invoke<T_,10>
{
static inline T_ execute(ifunction& f, T_ (&v)[10])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]); }
};
template <typename T_>
struct invoke<T_,9>
{
static inline T_ execute(ifunction& f, T_ (&v)[9])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]); }
};
template <typename T_>
struct invoke<T_,8>
{
static inline T_ execute(ifunction& f, T_ (&v)[8])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]); }
};
template <typename T_>
struct invoke<T_,7>
{
static inline T_ execute(ifunction& f, T_ (&v)[7])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5], v[6]); }
};
template <typename T_>
struct invoke<T_,6>
{
static inline T_ execute(ifunction& f, T_ (&v)[6])
{ return f(v[0], v[1], v[2], v[3], v[4], v[5]); }
};
template <typename T_>
struct invoke<T_,5>
{
static inline T_ execute(ifunction& f, T_ (&v)[5])
{ return f(v[0], v[1], v[2], v[3], v[4]); }
};
template <typename T_>
struct invoke<T_,4>
{
static inline T_ execute(ifunction& f, T_ (&v)[4])
{ return f(v[0], v[1], v[2], v[3]); }
};
template <typename T_>
struct invoke<T_,3>
{
static inline T_ execute(ifunction& f, T_ (&v)[3])
{ return f(v[0], v[1], v[2]); }
};
template <typename T_>
struct invoke<T_,2>
{
static inline T_ execute(ifunction& f, T_ (&v)[2])
{ return f(v[0], v[1]); }
};
template <typename T_>
struct invoke<T_,1>
{
static inline T_ execute(ifunction& f, T_ (&v)[1])
{ return f(v[0]); }
};
private:
ifunction* function_;
std::size_t parameter_count_;
branch_t branch_[N];
};
template <typename T, typename IFunction>
class function_N_node<T,IFunction,0> exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef IFunction ifunction;
explicit function_N_node(ifunction* func)
: function_((0 == func->param_count) ? func : reinterpret_cast<ifunction*>(0))
{}
inline bool operator <(const function_N_node<T,IFunction,0>& fn) const
{
return this < (&fn);
}
inline T value() const exprtk_override
{
if (function_)
return (*function_)();
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_function;
}
private:
ifunction* function_;
};
template <typename T, typename VarArgFunction>
class vararg_function_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
vararg_function_node(VarArgFunction* func,
const std::vector<expression_ptr>& arg_list)
: function_(func)
, arg_list_(arg_list)
{
value_list_.resize(arg_list.size(),std::numeric_limits<T>::quiet_NaN());
}
inline bool operator <(const vararg_function_node<T,VarArgFunction>& fn) const
{
return this < (&fn);
}
inline T value() const exprtk_override
{
if (function_)
{
populate_value_list();
return (*function_)(value_list_);
}
else
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_vafunction;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
for (std::size_t i = 0; i < arg_list_.size(); ++i)
{
if (arg_list_[i] && !details::is_variable_node(arg_list_[i]))
{
node_delete_list.push_back(&arg_list_[i]);
}
}
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(arg_list_);
}
private:
inline void populate_value_list() const
{
for (std::size_t i = 0; i < arg_list_.size(); ++i)
{
value_list_[i] = arg_list_[i]->value();
}
}
VarArgFunction* function_;
std::vector<expression_ptr> arg_list_;
mutable std::vector<T> value_list_;
};
template <typename T, typename GenericFunction>
class generic_function_node : public expression_node<T>
{
public:
typedef type_store<T> type_store_t;
typedef expression_node<T>* expression_ptr;
typedef variable_node<T> variable_node_t;
typedef vector_node<T> vector_node_t;
typedef variable_node_t* variable_node_ptr_t;
typedef vector_node_t* vector_node_ptr_t;
typedef range_interface<T> range_interface_t;
typedef range_data_type<T> range_data_type_t;
typedef typename range_interface<T>::range_t range_t;
typedef std::pair<expression_ptr,bool> branch_t;
typedef std::pair<void*,std::size_t> void_t;
typedef std::vector<T> tmp_vs_t;
typedef std::vector<type_store_t> typestore_list_t;
typedef std::vector<range_data_type_t> range_list_t;
explicit generic_function_node(const std::vector<expression_ptr>& arg_list,
GenericFunction* func = reinterpret_cast<GenericFunction*>(0))
: function_(func)
, arg_list_(arg_list)
{}
virtual ~generic_function_node() {}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override exprtk_final
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
virtual bool init_branches()
{
expr_as_vec1_store_.resize(arg_list_.size(),T(0) );
typestore_list_ .resize(arg_list_.size(),type_store_t() );
range_list_ .resize(arg_list_.size(),range_data_type_t());
branch_ .resize(arg_list_.size(),branch_t(reinterpret_cast<expression_ptr>(0),false));
for (std::size_t i = 0; i < arg_list_.size(); ++i)
{
type_store_t& ts = typestore_list_[i];
if (0 == arg_list_[i])
return false;
else if (is_ivector_node(arg_list_[i]))
{
vector_interface<T>* vi = reinterpret_cast<vector_interface<T>*>(0);
if (0 == (vi = dynamic_cast<vector_interface<T>*>(arg_list_[i])))
return false;
ts.size = vi->size();
ts.data = vi->vds().data();
ts.type = type_store_t::e_vector;
vi->vec()->vec_holder().set_ref(&ts.vec_data);
}
#ifndef exprtk_disable_string_capabilities
else if (is_generally_string_node(arg_list_[i]))
{
string_base_node<T>* sbn = reinterpret_cast<string_base_node<T>*>(0);
if (0 == (sbn = dynamic_cast<string_base_node<T>*>(arg_list_[i])))
return false;
ts.size = sbn->size();
ts.data = reinterpret_cast<void*>(const_cast<char_ptr>(sbn->base()));
ts.type = type_store_t::e_string;
range_list_[i].data = ts.data;
range_list_[i].size = ts.size;
range_list_[i].type_size = sizeof(char);
range_list_[i].str_node = sbn;
range_interface_t* ri = reinterpret_cast<range_interface_t*>(0);
if (0 == (ri = dynamic_cast<range_interface_t*>(arg_list_[i])))
return false;
const range_t& rp = ri->range_ref();
if (
rp.const_range() &&
is_const_string_range_node(arg_list_[i])
)
{
ts.size = rp.const_size();
ts.data = static_cast<char_ptr>(ts.data) + rp.n0_c.second;
range_list_[i].range = reinterpret_cast<range_t*>(0);
}
else
range_list_[i].range = &(ri->range_ref());
}
#endif
else if (is_variable_node(arg_list_[i]))
{
variable_node_ptr_t var = variable_node_ptr_t(0);
if (0 == (var = dynamic_cast<variable_node_ptr_t>(arg_list_[i])))
return false;
ts.size = 1;
ts.data = &var->ref();
ts.type = type_store_t::e_scalar;
}
else
{
ts.size = 1;
ts.data = reinterpret_cast<void*>(&expr_as_vec1_store_[i]);
ts.type = type_store_t::e_scalar;
}
branch_[i] = std::make_pair(arg_list_[i],branch_deletable(arg_list_[i]));
}
return true;
}
inline bool operator <(const generic_function_node<T,GenericFunction>& fn) const
{
return this < (&fn);
}
inline T value() const exprtk_override
{
if (function_)
{
if (populate_value_list())
{
typedef typename GenericFunction::parameter_list_t parameter_list_t;
return (*function_)(parameter_list_t(typestore_list_));
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_genfunction;
}
protected:
inline virtual bool populate_value_list() const
{
for (std::size_t i = 0; i < branch_.size(); ++i)
{
expr_as_vec1_store_[i] = branch_[i].first->value();
}
for (std::size_t i = 0; i < branch_.size(); ++i)
{
range_data_type_t& rdt = range_list_[i];
if (rdt.range)
{
const range_t& rp = (*rdt.range);
std::size_t r0 = 0;
std::size_t r1 = 0;
if (rp(r0, r1, rdt.size))
{
type_store_t& ts = typestore_list_[i];
ts.size = rp.cache_size();
#ifndef exprtk_disable_string_capabilities
if (ts.type == type_store_t::e_string)
ts.data = const_cast<char_ptr>(rdt.str_node->base()) + rp.cache.first;
else
#endif
ts.data = static_cast<char_ptr>(rdt.data) + (rp.cache.first * rdt.type_size);
}
else
return false;
}
}
return true;
}
GenericFunction* function_;
mutable typestore_list_t typestore_list_;
private:
std::vector<expression_ptr> arg_list_;
std::vector<branch_t> branch_;
mutable tmp_vs_t expr_as_vec1_store_;
mutable range_list_t range_list_;
};
#ifndef exprtk_disable_string_capabilities
template <typename T, typename StringFunction>
class string_function_node : public generic_function_node<T,StringFunction>,
public string_base_node<T>,
public range_interface <T>
{
public:
typedef generic_function_node<T,StringFunction> gen_function_t;
typedef typename range_interface<T>::range_t range_t;
string_function_node(StringFunction* func,
const std::vector<typename gen_function_t::expression_ptr>& arg_list)
: gen_function_t(arg_list,func)
{
range_.n0_c = std::make_pair<bool,std::size_t>(true,0);
range_.n1_c = std::make_pair<bool,std::size_t>(true,0);
range_.cache.first = range_.n0_c.second;
range_.cache.second = range_.n1_c.second;
}
inline bool operator <(const string_function_node<T,StringFunction>& fn) const
{
return this < (&fn);
}
inline T value() const exprtk_override
{
if (gen_function_t::function_)
{
if (gen_function_t::populate_value_list())
{
typedef typename StringFunction::parameter_list_t parameter_list_t;
const T result = (*gen_function_t::function_)
(
ret_string_,
parameter_list_t(gen_function_t::typestore_list_)
);
range_.n1_c.second = ret_string_.size() - 1;
range_.cache.second = range_.n1_c.second;
return result;
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strfunction;
}
std::string str() const exprtk_override
{
return ret_string_;
}
char_cptr base() const exprtk_override
{
return &ret_string_[0];
}
std::size_t size() const exprtk_override
{
return ret_string_.size();
}
range_t& range_ref() exprtk_override
{
return range_;
}
const range_t& range_ref() const exprtk_override
{
return range_;
}
protected:
mutable range_t range_;
mutable std::string ret_string_;
};
#endif
template <typename T, typename GenericFunction>
class multimode_genfunction_node : public generic_function_node<T,GenericFunction>
{
public:
typedef generic_function_node<T,GenericFunction> gen_function_t;
typedef typename gen_function_t::range_t range_t;
multimode_genfunction_node(GenericFunction* func,
const std::size_t& param_seq_index,
const std::vector<typename gen_function_t::expression_ptr>& arg_list)
: gen_function_t(arg_list,func)
, param_seq_index_(param_seq_index)
{}
inline T value() const exprtk_override
{
if (gen_function_t::function_)
{
if (gen_function_t::populate_value_list())
{
typedef typename GenericFunction::parameter_list_t parameter_list_t;
return (*gen_function_t::function_)
(
param_seq_index_,
parameter_list_t(gen_function_t::typestore_list_)
);
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override exprtk_final
{
return expression_node<T>::e_genfunction;
}
private:
std::size_t param_seq_index_;
};
#ifndef exprtk_disable_string_capabilities
template <typename T, typename StringFunction>
class multimode_strfunction_node exprtk_final : public string_function_node<T,StringFunction>
{
public:
typedef string_function_node<T,StringFunction> str_function_t;
typedef typename str_function_t::range_t range_t;
multimode_strfunction_node(StringFunction* func,
const std::size_t& param_seq_index,
const std::vector<typename str_function_t::expression_ptr>& arg_list)
: str_function_t(func,arg_list)
, param_seq_index_(param_seq_index)
{}
inline T value() const exprtk_override
{
if (str_function_t::function_)
{
if (str_function_t::populate_value_list())
{
typedef typename StringFunction::parameter_list_t parameter_list_t;
const T result = (*str_function_t::function_)
(
param_seq_index_,
str_function_t::ret_string_,
parameter_list_t(str_function_t::typestore_list_)
);
str_function_t::range_.n1_c.second = str_function_t::ret_string_.size() - 1;
str_function_t::range_.cache.second = str_function_t::range_.n1_c.second;
return result;
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_strfunction;
}
private:
const std::size_t param_seq_index_;
};
#endif
class return_exception
{};
template <typename T>
class null_igenfunc
{
public:
virtual ~null_igenfunc() {}
typedef type_store<T> generic_type;
typedef typename generic_type::parameter_list parameter_list_t;
inline virtual T operator() (parameter_list_t)
{
return std::numeric_limits<T>::quiet_NaN();
}
};
#ifndef exprtk_disable_return_statement
template <typename T>
class return_node exprtk_final : public generic_function_node<T,null_igenfunc<T> >
{
public:
typedef results_context<T> results_context_t;
typedef null_igenfunc<T> igeneric_function_t;
typedef igeneric_function_t* igeneric_function_ptr;
typedef generic_function_node<T,igeneric_function_t> gen_function_t;
return_node(const std::vector<typename gen_function_t::expression_ptr>& arg_list,
results_context_t& rc)
: gen_function_t (arg_list)
, results_context_(&rc)
{}
inline T value() const exprtk_override
{
if (
(0 != results_context_) &&
gen_function_t::populate_value_list()
)
{
typedef typename type_store<T>::parameter_list parameter_list_t;
results_context_->
assign(parameter_list_t(gen_function_t::typestore_list_));
throw return_exception();
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_return;
}
private:
results_context_t* results_context_;
};
template <typename T>
class return_envelope_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef results_context<T> results_context_t;
typedef std::pair<expression_ptr,bool> branch_t;
return_envelope_node(expression_ptr body, results_context_t& rc)
: results_context_(&rc )
, return_invoked_ (false)
{
construct_branch_pair(body_, body);
}
inline T value() const exprtk_override
{
assert(body_.first);
try
{
return_invoked_ = false;
results_context_->clear();
return body_.first->value();
}
catch(const return_exception&)
{
return_invoked_ = true;
return std::numeric_limits<T>::quiet_NaN();
}
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_retenv;
}
inline bool* retinvk_ptr()
{
return &return_invoked_;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(body_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(body_);
}
private:
results_context_t* results_context_;
mutable bool return_invoked_;
branch_t body_;
};
#endif
#define exprtk_define_unary_op(OpName) \
template <typename T> \
struct OpName##_op \
{ \
typedef typename functor_t<T>::Type Type; \
typedef typename expression_node<T>::node_type node_t; \
\
static inline T process(Type v) \
{ \
return numeric:: OpName (v); \
} \
\
static inline node_t type() \
{ \
return expression_node<T>::e_##OpName; \
} \
\
static inline details::operator_type operation() \
{ \
return details::e_##OpName; \
} \
}; \
exprtk_define_unary_op(abs )
exprtk_define_unary_op(acos )
exprtk_define_unary_op(acosh)
exprtk_define_unary_op(asin )
exprtk_define_unary_op(asinh)
exprtk_define_unary_op(atan )
exprtk_define_unary_op(atanh)
exprtk_define_unary_op(ceil )
exprtk_define_unary_op(cos )
exprtk_define_unary_op(cosh )
exprtk_define_unary_op(cot )
exprtk_define_unary_op(csc )
exprtk_define_unary_op(d2g )
exprtk_define_unary_op(d2r )
exprtk_define_unary_op(erf )
exprtk_define_unary_op(erfc )
exprtk_define_unary_op(exp )
exprtk_define_unary_op(expm1)
exprtk_define_unary_op(floor)
exprtk_define_unary_op(frac )
exprtk_define_unary_op(g2d )
exprtk_define_unary_op(log )
exprtk_define_unary_op(log10)
exprtk_define_unary_op(log2 )
exprtk_define_unary_op(log1p)
exprtk_define_unary_op(ncdf )
exprtk_define_unary_op(neg )
exprtk_define_unary_op(notl )
exprtk_define_unary_op(pos )
exprtk_define_unary_op(r2d )
exprtk_define_unary_op(round)
exprtk_define_unary_op(sec )
exprtk_define_unary_op(sgn )
exprtk_define_unary_op(sin )
exprtk_define_unary_op(sinc )
exprtk_define_unary_op(sinh )
exprtk_define_unary_op(sqrt )
exprtk_define_unary_op(tan )
exprtk_define_unary_op(tanh )
exprtk_define_unary_op(trunc)
#undef exprtk_define_unary_op
template <typename T>
struct opr_base
{
typedef typename details::functor_t<T>::Type Type;
typedef typename details::functor_t<T>::RefType RefType;
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::qfunc_t quaternary_functor_t;
typedef typename functor_t::tfunc_t trinary_functor_t;
typedef typename functor_t::bfunc_t binary_functor_t;
typedef typename functor_t::ufunc_t unary_functor_t;
};
template <typename T>
struct add_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return t1 + t2; }
static inline T process(Type t1, Type t2, Type t3) { return t1 + t2 + t3; }
static inline void assign(RefType t1, Type t2) { t1 += t2; }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_add; }
static inline details::operator_type operation() { return details::e_add; }
};
template <typename T>
struct mul_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return t1 * t2; }
static inline T process(Type t1, Type t2, Type t3) { return t1 * t2 * t3; }
static inline void assign(RefType t1, Type t2) { t1 *= t2; }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_mul; }
static inline details::operator_type operation() { return details::e_mul; }
};
template <typename T>
struct sub_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return t1 - t2; }
static inline T process(Type t1, Type t2, Type t3) { return t1 - t2 - t3; }
static inline void assign(RefType t1, Type t2) { t1 -= t2; }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_sub; }
static inline details::operator_type operation() { return details::e_sub; }
};
template <typename T>
struct div_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return t1 / t2; }
static inline T process(Type t1, Type t2, Type t3) { return t1 / t2 / t3; }
static inline void assign(RefType t1, Type t2) { t1 /= t2; }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_div; }
static inline details::operator_type operation() { return details::e_div; }
};
template <typename T>
struct mod_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return numeric::modulus<T>(t1,t2); }
static inline void assign(RefType t1, Type t2) { t1 = numeric::modulus<T>(t1,t2); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_mod; }
static inline details::operator_type operation() { return details::e_mod; }
};
template <typename T>
struct pow_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
typedef typename opr_base<T>::RefType RefType;
static inline T process(Type t1, Type t2) { return numeric::pow<T>(t1,t2); }
static inline void assign(RefType t1, Type t2) { t1 = numeric::pow<T>(t1,t2); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_pow; }
static inline details::operator_type operation() { return details::e_pow; }
};
template <typename T>
struct lt_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return ((t1 < t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 < t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_lt; }
static inline details::operator_type operation() { return details::e_lt; }
};
template <typename T>
struct lte_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return ((t1 <= t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 <= t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_lte; }
static inline details::operator_type operation() { return details::e_lte; }
};
template <typename T>
struct gt_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return ((t1 > t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 > t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_gt; }
static inline details::operator_type operation() { return details::e_gt; }
};
template <typename T>
struct gte_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return ((t1 >= t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 >= t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_gte; }
static inline details::operator_type operation() { return details::e_gte; }
};
template <typename T>
struct eq_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (std::equal_to<T>()(t1,t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 == t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_eq; }
static inline details::operator_type operation() { return details::e_eq; }
};
template <typename T>
struct equal_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return numeric::equal(t1,t2); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 == t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_eq; }
static inline details::operator_type operation() { return details::e_equal; }
};
template <typename T>
struct ne_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (std::not_equal_to<T>()(t1,t2) ? T(1) : T(0)); }
static inline T process(const std::string& t1, const std::string& t2) { return ((t1 != t2) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_ne; }
static inline details::operator_type operation() { return details::e_ne; }
};
template <typename T>
struct and_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (details::is_true(t1) && details::is_true(t2)) ? T(1) : T(0); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_and; }
static inline details::operator_type operation() { return details::e_and; }
};
template <typename T>
struct nand_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (details::is_true(t1) && details::is_true(t2)) ? T(0) : T(1); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_nand; }
static inline details::operator_type operation() { return details::e_nand; }
};
template <typename T>
struct or_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (details::is_true(t1) || details::is_true(t2)) ? T(1) : T(0); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_or; }
static inline details::operator_type operation() { return details::e_or; }
};
template <typename T>
struct nor_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return (details::is_true(t1) || details::is_true(t2)) ? T(0) : T(1); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_nor; }
static inline details::operator_type operation() { return details::e_nor; }
};
template <typename T>
struct xor_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return numeric::xor_opr<T>(t1,t2); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_nor; }
static inline details::operator_type operation() { return details::e_xor; }
};
template <typename T>
struct xnor_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(Type t1, Type t2) { return numeric::xnor_opr<T>(t1,t2); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_nor; }
static inline details::operator_type operation() { return details::e_xnor; }
};
template <typename T>
struct in_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(const T&, const T&) { return std::numeric_limits<T>::quiet_NaN(); }
static inline T process(const std::string& t1, const std::string& t2) { return ((std::string::npos != t2.find(t1)) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_in; }
static inline details::operator_type operation() { return details::e_in; }
};
template <typename T>
struct like_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(const T&, const T&) { return std::numeric_limits<T>::quiet_NaN(); }
static inline T process(const std::string& t1, const std::string& t2) { return (details::wc_match(t2,t1) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_like; }
static inline details::operator_type operation() { return details::e_like; }
};
template <typename T>
struct ilike_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(const T&, const T&) { return std::numeric_limits<T>::quiet_NaN(); }
static inline T process(const std::string& t1, const std::string& t2) { return (details::wc_imatch(t2,t1) ? T(1) : T(0)); }
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_ilike; }
static inline details::operator_type operation() { return details::e_ilike; }
};
template <typename T>
struct inrange_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
static inline T process(const T& t0, const T& t1, const T& t2) { return ((t0 <= t1) && (t1 <= t2)) ? T(1) : T(0); }
static inline T process(const std::string& t0, const std::string& t1, const std::string& t2)
{
return ((t0 <= t1) && (t1 <= t2)) ? T(1) : T(0);
}
static inline typename expression_node<T>::node_type type() { return expression_node<T>::e_inranges; }
static inline details::operator_type operation() { return details::e_inrange; }
};
template <typename T>
inline T value(details::expression_node<T>* n)
{
return n->value();
}
template <typename T>
inline T value(std::pair<details::expression_node<T>*,bool> n)
{
return n.first->value();
}
template <typename T>
inline T value(const T* t)
{
return (*t);
}
template <typename T>
inline T value(const T& t)
{
return t;
}
template <typename T>
struct vararg_add_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return T(0);
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
T result = T(0);
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
result += value(arg_list[i]);
}
return result;
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return value(arg_list[0]) + value(arg_list[1]);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return value(arg_list[0]) + value(arg_list[1]) +
value(arg_list[2]) ;
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return value(arg_list[0]) + value(arg_list[1]) +
value(arg_list[2]) + value(arg_list[3]) ;
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return value(arg_list[0]) + value(arg_list[1]) +
value(arg_list[2]) + value(arg_list[3]) +
value(arg_list[4]) ;
}
};
template <typename T>
struct vararg_mul_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return T(0);
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
T result = T(value(arg_list[0]));
for (std::size_t i = 1; i < arg_list.size(); ++i)
{
result *= value(arg_list[i]);
}
return result;
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return value(arg_list[0]) * value(arg_list[1]);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return value(arg_list[0]) * value(arg_list[1]) *
value(arg_list[2]) ;
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return value(arg_list[0]) * value(arg_list[1]) *
value(arg_list[2]) * value(arg_list[3]) ;
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return value(arg_list[0]) * value(arg_list[1]) *
value(arg_list[2]) * value(arg_list[3]) *
value(arg_list[4]) ;
}
};
template <typename T>
struct vararg_avg_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return T(0);
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default : return vararg_add_op<T>::process(arg_list) / T(arg_list.size());
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return (value(arg_list[0]) + value(arg_list[1])) / T(2);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return (value(arg_list[0]) + value(arg_list[1]) + value(arg_list[2])) / T(3);
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return (value(arg_list[0]) + value(arg_list[1]) +
value(arg_list[2]) + value(arg_list[3])) / T(4);
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return (value(arg_list[0]) + value(arg_list[1]) +
value(arg_list[2]) + value(arg_list[3]) +
value(arg_list[4])) / T(5);
}
};
template <typename T>
struct vararg_min_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return T(0);
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
T result = T(value(arg_list[0]));
for (std::size_t i = 1; i < arg_list.size(); ++i)
{
const T v = value(arg_list[i]);
if (v < result)
result = v;
}
return result;
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return std::min<T>(value(arg_list[0]),value(arg_list[1]));
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return std::min<T>(std::min<T>(value(arg_list[0]),value(arg_list[1])),value(arg_list[2]));
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return std::min<T>(
std::min<T>(value(arg_list[0]), value(arg_list[1])),
std::min<T>(value(arg_list[2]), value(arg_list[3])));
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return std::min<T>(
std::min<T>(std::min<T>(value(arg_list[0]), value(arg_list[1])),
std::min<T>(value(arg_list[2]), value(arg_list[3]))),
value(arg_list[4]));
}
};
template <typename T>
struct vararg_max_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return T(0);
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
T result = T(value(arg_list[0]));
for (std::size_t i = 1; i < arg_list.size(); ++i)
{
const T v = value(arg_list[i]);
if (v > result)
result = v;
}
return result;
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return std::max<T>(value(arg_list[0]),value(arg_list[1]));
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return std::max<T>(std::max<T>(value(arg_list[0]),value(arg_list[1])),value(arg_list[2]));
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return std::max<T>(
std::max<T>(value(arg_list[0]), value(arg_list[1])),
std::max<T>(value(arg_list[2]), value(arg_list[3])));
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return std::max<T>(
std::max<T>(std::max<T>(value(arg_list[0]), value(arg_list[1])),
std::max<T>(value(arg_list[2]), value(arg_list[3]))),
value(arg_list[4]));
}
};
template <typename T>
struct vararg_mand_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (std::equal_to<T>()(T(0), value(arg_list[i])))
return T(0);
}
return T(1);
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return std::not_equal_to<T>()
(T(0), value(arg_list[0])) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) &&
std::not_equal_to<T>()(T(0), value(arg_list[1]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) &&
std::not_equal_to<T>()(T(0), value(arg_list[1])) &&
std::not_equal_to<T>()(T(0), value(arg_list[2]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) &&
std::not_equal_to<T>()(T(0), value(arg_list[1])) &&
std::not_equal_to<T>()(T(0), value(arg_list[2])) &&
std::not_equal_to<T>()(T(0), value(arg_list[3]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) &&
std::not_equal_to<T>()(T(0), value(arg_list[1])) &&
std::not_equal_to<T>()(T(0), value(arg_list[2])) &&
std::not_equal_to<T>()(T(0), value(arg_list[3])) &&
std::not_equal_to<T>()(T(0), value(arg_list[4]))
) ? T(1) : T(0);
}
};
template <typename T>
struct vararg_mor_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
default :
{
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (std::not_equal_to<T>()(T(0), value(arg_list[i])))
return T(1);
}
return T(0);
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return std::not_equal_to<T>()
(T(0), value(arg_list[0])) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) ||
std::not_equal_to<T>()(T(0), value(arg_list[1]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) ||
std::not_equal_to<T>()(T(0), value(arg_list[1])) ||
std::not_equal_to<T>()(T(0), value(arg_list[2]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) ||
std::not_equal_to<T>()(T(0), value(arg_list[1])) ||
std::not_equal_to<T>()(T(0), value(arg_list[2])) ||
std::not_equal_to<T>()(T(0), value(arg_list[3]))
) ? T(1) : T(0);
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
return (
std::not_equal_to<T>()(T(0), value(arg_list[0])) ||
std::not_equal_to<T>()(T(0), value(arg_list[1])) ||
std::not_equal_to<T>()(T(0), value(arg_list[2])) ||
std::not_equal_to<T>()(T(0), value(arg_list[3])) ||
std::not_equal_to<T>()(T(0), value(arg_list[4]))
) ? T(1) : T(0);
}
};
template <typename T>
struct vararg_multi_op : public opr_base<T>
{
typedef typename opr_base<T>::Type Type;
template <typename Type,
typename Allocator,
template <typename, typename> class Sequence>
static inline T process(const Sequence<Type,Allocator>& arg_list)
{
switch (arg_list.size())
{
case 0 : return std::numeric_limits<T>::quiet_NaN();
case 1 : return process_1(arg_list);
case 2 : return process_2(arg_list);
case 3 : return process_3(arg_list);
case 4 : return process_4(arg_list);
case 5 : return process_5(arg_list);
case 6 : return process_6(arg_list);
case 7 : return process_7(arg_list);
case 8 : return process_8(arg_list);
default :
{
for (std::size_t i = 0; i < (arg_list.size() - 1); ++i)
{
value(arg_list[i]);
}
return value(arg_list.back());
}
}
}
template <typename Sequence>
static inline T process_1(const Sequence& arg_list)
{
return value(arg_list[0]);
}
template <typename Sequence>
static inline T process_2(const Sequence& arg_list)
{
value(arg_list[0]);
return value(arg_list[1]);
}
template <typename Sequence>
static inline T process_3(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
return value(arg_list[2]);
}
template <typename Sequence>
static inline T process_4(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
value(arg_list[2]);
return value(arg_list[3]);
}
template <typename Sequence>
static inline T process_5(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
value(arg_list[2]);
value(arg_list[3]);
return value(arg_list[4]);
}
template <typename Sequence>
static inline T process_6(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
value(arg_list[2]);
value(arg_list[3]);
value(arg_list[4]);
return value(arg_list[5]);
}
template <typename Sequence>
static inline T process_7(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
value(arg_list[2]);
value(arg_list[3]);
value(arg_list[4]);
value(arg_list[5]);
return value(arg_list[6]);
}
template <typename Sequence>
static inline T process_8(const Sequence& arg_list)
{
value(arg_list[0]);
value(arg_list[1]);
value(arg_list[2]);
value(arg_list[3]);
value(arg_list[4]);
value(arg_list[5]);
value(arg_list[6]);
return value(arg_list[7]);
}
};
template <typename T>
struct vec_add_op
{
typedef vector_interface<T>* ivector_ptr;
static inline T process(const ivector_ptr v)
{
const T* vec = v->vec()->vds().data();
const std::size_t vec_size = v->vec()->vds().size();
loop_unroll::details lud(vec_size);
if (vec_size <= static_cast<std::size_t>(lud.batch_size))
{
T result = T(0);
int i = 0;
exprtk_disable_fallthrough_begin
switch (vec_size)
{
#define case_stmt(N) \
case N : result += vec[i++]; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(16) case_stmt(15)
case_stmt(14) case_stmt(13)
case_stmt(12) case_stmt(11)
case_stmt(10) case_stmt( 9)
case_stmt( 8) case_stmt( 7)
case_stmt( 6) case_stmt( 5)
#endif
case_stmt( 4) case_stmt( 3)
case_stmt( 2) case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef case_stmt
return result;
}
T r[] = {
T(0), T(0), T(0), T(0), T(0), T(0), T(0), T(0),
T(0), T(0), T(0), T(0), T(0), T(0), T(0), T(0)
};
const T* upper_bound = vec + lud.upper_bound;
while (vec < upper_bound)
{
#define exprtk_loop(N) \
r[N] += vec[N]; \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : r[0] += vec[i++]; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (r[ 0] + r[ 1] + r[ 2] + r[ 3])
#ifndef exprtk_disable_superscalar_unroll
+ (r[ 4] + r[ 5] + r[ 6] + r[ 7])
+ (r[ 8] + r[ 9] + r[10] + r[11])
+ (r[12] + r[13] + r[14] + r[15])
#endif
;
}
};
template <typename T>
struct vec_mul_op
{
typedef vector_interface<T>* ivector_ptr;
static inline T process(const ivector_ptr v)
{
const T* vec = v->vec()->vds().data();
const std::size_t vec_size = v->vec()->vds().size();
loop_unroll::details lud(vec_size);
if (vec_size <= static_cast<std::size_t>(lud.batch_size))
{
T result = T(1);
int i = 0;
exprtk_disable_fallthrough_begin
switch (vec_size)
{
#define case_stmt(N) \
case N : result *= vec[i++]; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(16) case_stmt(15)
case_stmt(14) case_stmt(13)
case_stmt(12) case_stmt(11)
case_stmt(10) case_stmt( 9)
case_stmt( 8) case_stmt( 7)
case_stmt( 6) case_stmt( 5)
#endif
case_stmt( 4) case_stmt( 3)
case_stmt( 2) case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef case_stmt
return result;
}
T r[] = {
T(1), T(1), T(1), T(1), T(1), T(1), T(1), T(1),
T(1), T(1), T(1), T(1), T(1), T(1), T(1), T(1)
};
const T* upper_bound = vec + lud.upper_bound;
while (vec < upper_bound)
{
#define exprtk_loop(N) \
r[N] *= vec[N]; \
exprtk_loop( 0) exprtk_loop( 1)
exprtk_loop( 2) exprtk_loop( 3)
#ifndef exprtk_disable_superscalar_unroll
exprtk_loop( 4) exprtk_loop( 5)
exprtk_loop( 6) exprtk_loop( 7)
exprtk_loop( 8) exprtk_loop( 9)
exprtk_loop(10) exprtk_loop(11)
exprtk_loop(12) exprtk_loop(13)
exprtk_loop(14) exprtk_loop(15)
#endif
vec += lud.batch_size;
}
int i = 0;
exprtk_disable_fallthrough_begin
switch (lud.remainder)
{
#define case_stmt(N) \
case N : r[0] *= vec[i++]; \
#ifndef exprtk_disable_superscalar_unroll
case_stmt(15) case_stmt(14)
case_stmt(13) case_stmt(12)
case_stmt(11) case_stmt(10)
case_stmt( 9) case_stmt( 8)
case_stmt( 7) case_stmt( 6)
case_stmt( 5) case_stmt( 4)
#endif
case_stmt( 3) case_stmt( 2)
case_stmt( 1)
}
exprtk_disable_fallthrough_end
#undef exprtk_loop
#undef case_stmt
return (r[ 0] * r[ 1] * r[ 2] * r[ 3])
#ifndef exprtk_disable_superscalar_unroll
+ (r[ 4] * r[ 5] * r[ 6] * r[ 7])
+ (r[ 8] * r[ 9] * r[10] * r[11])
+ (r[12] * r[13] * r[14] * r[15])
#endif
;
}
};
template <typename T>
struct vec_avg_op
{
typedef vector_interface<T>* ivector_ptr;
static inline T process(const ivector_ptr v)
{
const T vec_size = T(v->vec()->vds().size());
return vec_add_op<T>::process(v) / vec_size;
}
};
template <typename T>
struct vec_min_op
{
typedef vector_interface<T>* ivector_ptr;
static inline T process(const ivector_ptr v)
{
const T* vec = v->vec()->vds().data();
const std::size_t vec_size = v->vec()->vds().size();
T result = vec[0];
for (std::size_t i = 1; i < vec_size; ++i)
{
const T v_i = vec[i];
if (v_i < result)
result = v_i;
}
return result;
}
};
template <typename T>
struct vec_max_op
{
typedef vector_interface<T>* ivector_ptr;
static inline T process(const ivector_ptr v)
{
const T* vec = v->vec()->vds().data();
const std::size_t vec_size = v->vec()->vds().size();
T result = vec[0];
for (std::size_t i = 1; i < vec_size; ++i)
{
const T v_i = vec[i];
if (v_i > result)
result = v_i;
}
return result;
}
};
template <typename T>
class vov_base_node : public expression_node<T>
{
public:
virtual ~vov_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T& v0() const = 0;
virtual const T& v1() const = 0;
};
template <typename T>
class cov_base_node : public expression_node<T>
{
public:
virtual ~cov_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T c() const = 0;
virtual const T& v() const = 0;
};
template <typename T>
class voc_base_node : public expression_node<T>
{
public:
virtual ~voc_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T c() const = 0;
virtual const T& v() const = 0;
};
template <typename T>
class vob_base_node : public expression_node<T>
{
public:
virtual ~vob_base_node() {}
virtual const T& v() const = 0;
};
template <typename T>
class bov_base_node : public expression_node<T>
{
public:
virtual ~bov_base_node() {}
virtual const T& v() const = 0;
};
template <typename T>
class cob_base_node : public expression_node<T>
{
public:
virtual ~cob_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T c() const = 0;
virtual void set_c(const T) = 0;
virtual expression_node<T>* move_branch(const std::size_t& index) = 0;
};
template <typename T>
class boc_base_node : public expression_node<T>
{
public:
virtual ~boc_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T c() const = 0;
virtual void set_c(const T) = 0;
virtual expression_node<T>* move_branch(const std::size_t& index) = 0;
};
template <typename T>
class uv_base_node : public expression_node<T>
{
public:
virtual ~uv_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
virtual const T& v() const = 0;
};
template <typename T>
class sos_base_node : public expression_node<T>
{
public:
virtual ~sos_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
};
template <typename T>
class sosos_base_node : public expression_node<T>
{
public:
virtual ~sosos_base_node() {}
inline virtual operator_type operation() const
{
return details::e_default;
}
};
template <typename T>
class T0oT1oT2_base_node : public expression_node<T>
{
public:
virtual ~T0oT1oT2_base_node() {}
virtual std::string type_id() const = 0;
};
template <typename T>
class T0oT1oT2oT3_base_node : public expression_node<T>
{
public:
virtual ~T0oT1oT2oT3_base_node() {}
virtual std::string type_id() const = 0;
};
template <typename T, typename Operation>
class unary_variable_node exprtk_final : public uv_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
explicit unary_variable_node(const T& var)
: v_(var)
{}
inline T value() const exprtk_override
{
return Operation::process(v_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T& v() const exprtk_override
{
return v_;
}
private:
unary_variable_node(const unary_variable_node<T,Operation>&) exprtk_delete;
unary_variable_node<T,Operation>& operator=(const unary_variable_node<T,Operation>&) exprtk_delete;
const T& v_;
};
template <typename T>
class uvouv_node exprtk_final : public expression_node<T>
{
public:
// UOpr1(v0) Op UOpr2(v1)
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
typedef typename functor_t::ufunc_t ufunc_t;
typedef expression_node<T>* expression_ptr;
explicit uvouv_node(const T& var0,const T& var1,
ufunc_t uf0, ufunc_t uf1, bfunc_t bf)
: v0_(var0)
, v1_(var1)
, u0_(uf0 )
, u1_(uf1 )
, f_ (bf )
{}
inline T value() const exprtk_override
{
return f_(u0_(v0_),u1_(v1_));
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_uvouv;
}
inline const T& v0()
{
return v0_;
}
inline const T& v1()
{
return v1_;
}
inline ufunc_t u0()
{
return u0_;
}
inline ufunc_t u1()
{
return u1_;
}
inline ufunc_t f()
{
return f_;
}
private:
uvouv_node(const uvouv_node<T>&) exprtk_delete;
uvouv_node<T>& operator=(const uvouv_node<T>&) exprtk_delete;
const T& v0_;
const T& v1_;
const ufunc_t u0_;
const ufunc_t u1_;
const bfunc_t f_;
};
template <typename T, typename Operation>
class unary_branch_node exprtk_final : public expression_node<T>
{
public:
typedef Operation operation_t;
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
explicit unary_branch_node(expression_ptr branch)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
return Operation::process(branch_.first->value());
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation()
{
return Operation::operation();
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
inline void release()
{
branch_.second = false;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
unary_branch_node(const unary_branch_node<T,Operation>&) exprtk_delete;
unary_branch_node<T,Operation>& operator=(const unary_branch_node<T,Operation>&) exprtk_delete;
branch_t branch_;
};
template <typename T> struct is_const { enum {result = 0}; };
template <typename T> struct is_const <const T> { enum {result = 1}; };
template <typename T> struct is_const_ref { enum {result = 0}; };
template <typename T> struct is_const_ref <const T&> { enum {result = 1}; };
template <typename T> struct is_ref { enum {result = 0}; };
template <typename T> struct is_ref<T&> { enum {result = 1}; };
template <typename T> struct is_ref<const T&> { enum {result = 0}; };
template <std::size_t State>
struct param_to_str { static std::string result() { static const std::string r("v"); return r; } };
template <>
struct param_to_str<0> { static std::string result() { static const std::string r("c"); return r; } };
#define exprtk_crtype(Type) \
param_to_str<is_const_ref< Type >::result>::result() \
template <typename T>
struct T0oT1oT2process
{
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
struct mode0
{
static inline T process(const T& t0, const T& t1, const T& t2, const bfunc_t bf0, const bfunc_t bf1)
{
// (T0 o0 T1) o1 T2
return bf1(bf0(t0,t1),t2);
}
template <typename T0, typename T1, typename T2>
static inline std::string id()
{
static const std::string result = "(" + exprtk_crtype(T0) + "o" +
exprtk_crtype(T1) + ")o(" +
exprtk_crtype(T2) + ")" ;
return result;
}
};
struct mode1
{
static inline T process(const T& t0, const T& t1, const T& t2, const bfunc_t bf0, const bfunc_t bf1)
{
// T0 o0 (T1 o1 T2)
return bf0(t0,bf1(t1,t2));
}
template <typename T0, typename T1, typename T2>
static inline std::string id()
{
static const std::string result = "(" + exprtk_crtype(T0) + ")o(" +
exprtk_crtype(T1) + "o" +
exprtk_crtype(T2) + ")" ;
return result;
}
};
};
template <typename T>
struct T0oT1oT20T3process
{
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
struct mode0
{
static inline T process(const T& t0, const T& t1,
const T& t2, const T& t3,
const bfunc_t bf0, const bfunc_t bf1, const bfunc_t bf2)
{
// (T0 o0 T1) o1 (T2 o2 T3)
return bf1(bf0(t0,t1),bf2(t2,t3));
}
template <typename T0, typename T1, typename T2, typename T3>
static inline std::string id()
{
static const std::string result = "(" + exprtk_crtype(T0) + "o" +
exprtk_crtype(T1) + ")o" +
"(" + exprtk_crtype(T2) + "o" +
exprtk_crtype(T3) + ")" ;
return result;
}
};
struct mode1
{
static inline T process(const T& t0, const T& t1,
const T& t2, const T& t3,
const bfunc_t bf0, const bfunc_t bf1, const bfunc_t bf2)
{
// (T0 o0 (T1 o1 (T2 o2 T3))
return bf0(t0,bf1(t1,bf2(t2,t3)));
}
template <typename T0, typename T1, typename T2, typename T3>
static inline std::string id()
{
static const std::string result = "(" + exprtk_crtype(T0) + ")o((" +
exprtk_crtype(T1) + ")o(" +
exprtk_crtype(T2) + "o" +
exprtk_crtype(T3) + "))" ;
return result;
}
};
struct mode2
{
static inline T process(const T& t0, const T& t1,
const T& t2, const T& t3,
const bfunc_t bf0, const bfunc_t bf1, const bfunc_t bf2)
{
// (T0 o0 ((T1 o1 T2) o2 T3)
return bf0(t0,bf2(bf1(t1,t2),t3));
}
template <typename T0, typename T1, typename T2, typename T3>
static inline std::string id()
{
static const std::string result = "(" + exprtk_crtype(T0) + ")o((" +
exprtk_crtype(T1) + "o" +
exprtk_crtype(T2) + ")o(" +
exprtk_crtype(T3) + "))" ;
return result;
}
};
struct mode3
{
static inline T process(const T& t0, const T& t1,
const T& t2, const T& t3,
const bfunc_t bf0, const bfunc_t bf1, const bfunc_t bf2)
{
// (((T0 o0 T1) o1 T2) o2 T3)
return bf2(bf1(bf0(t0,t1),t2),t3);
}
template <typename T0, typename T1, typename T2, typename T3>
static inline std::string id()
{
static const std::string result = "((" + exprtk_crtype(T0) + "o" +
exprtk_crtype(T1) + ")o(" +
exprtk_crtype(T2) + "))o(" +
exprtk_crtype(T3) + ")";
return result;
}
};
struct mode4
{
static inline T process(const T& t0, const T& t1,
const T& t2, const T& t3,
const bfunc_t bf0, const bfunc_t bf1, const bfunc_t bf2)
{
// ((T0 o0 (T1 o1 T2)) o2 T3
return bf2(bf0(t0,bf1(t1,t2)),t3);
}
template <typename T0, typename T1, typename T2, typename T3>
static inline std::string id()
{
static const std::string result = "((" + exprtk_crtype(T0) + ")o(" +
exprtk_crtype(T1) + "o" +
exprtk_crtype(T2) + "))o(" +
exprtk_crtype(T3) + ")" ;
return result;
}
};
};
#undef exprtk_crtype
template <typename T, typename T0, typename T1>
struct nodetype_T0oT1 { static const typename expression_node<T>::node_type result; };
template <typename T, typename T0, typename T1>
const typename expression_node<T>::node_type nodetype_T0oT1<T,T0,T1>::result = expression_node<T>::e_none;
#define synthesis_node_type_define(T0_, T1_, v_) \
template <typename T, typename T0, typename T1> \
struct nodetype_T0oT1<T,T0_,T1_> { static const typename expression_node<T>::node_type result; }; \
template <typename T, typename T0, typename T1> \
const typename expression_node<T>::node_type nodetype_T0oT1<T,T0_,T1_>::result = expression_node<T>:: v_; \
synthesis_node_type_define(const T0&, const T1&, e_vov)
synthesis_node_type_define(const T0&, const T1 , e_voc)
synthesis_node_type_define(const T0 , const T1&, e_cov)
synthesis_node_type_define( T0&, T1&, e_none)
synthesis_node_type_define(const T0 , const T1 , e_none)
synthesis_node_type_define( T0&, const T1 , e_none)
synthesis_node_type_define(const T0 , T1&, e_none)
synthesis_node_type_define(const T0&, T1&, e_none)
synthesis_node_type_define( T0&, const T1&, e_none)
#undef synthesis_node_type_define
template <typename T, typename T0, typename T1, typename T2>
struct nodetype_T0oT1oT2 { static const typename expression_node<T>::node_type result; };
template <typename T, typename T0, typename T1, typename T2>
const typename expression_node<T>::node_type nodetype_T0oT1oT2<T,T0,T1,T2>::result = expression_node<T>::e_none;
#define synthesis_node_type_define(T0_, T1_, T2_, v_) \
template <typename T, typename T0, typename T1, typename T2> \
struct nodetype_T0oT1oT2<T,T0_,T1_,T2_> { static const typename expression_node<T>::node_type result; }; \
template <typename T, typename T0, typename T1, typename T2> \
const typename expression_node<T>::node_type nodetype_T0oT1oT2<T,T0_,T1_,T2_>::result = expression_node<T>:: v_; \
synthesis_node_type_define(const T0&, const T1&, const T2&, e_vovov)
synthesis_node_type_define(const T0&, const T1&, const T2 , e_vovoc)
synthesis_node_type_define(const T0&, const T1 , const T2&, e_vocov)
synthesis_node_type_define(const T0 , const T1&, const T2&, e_covov)
synthesis_node_type_define(const T0 , const T1&, const T2 , e_covoc)
synthesis_node_type_define(const T0 , const T1 , const T2 , e_none )
synthesis_node_type_define(const T0 , const T1 , const T2&, e_none )
synthesis_node_type_define(const T0&, const T1 , const T2 , e_none )
synthesis_node_type_define( T0&, T1&, T2&, e_none )
#undef synthesis_node_type_define
template <typename T, typename T0, typename T1, typename T2, typename T3>
struct nodetype_T0oT1oT2oT3 { static const typename expression_node<T>::node_type result; };
template <typename T, typename T0, typename T1, typename T2, typename T3>
const typename expression_node<T>::node_type nodetype_T0oT1oT2oT3<T,T0,T1,T2,T3>::result = expression_node<T>::e_none;
#define synthesis_node_type_define(T0_, T1_, T2_, T3_, v_) \
template <typename T, typename T0, typename T1, typename T2, typename T3> \
struct nodetype_T0oT1oT2oT3<T,T0_,T1_,T2_,T3_> { static const typename expression_node<T>::node_type result; }; \
template <typename T, typename T0, typename T1, typename T2, typename T3> \
const typename expression_node<T>::node_type nodetype_T0oT1oT2oT3<T,T0_,T1_,T2_,T3_>::result = expression_node<T>:: v_; \
synthesis_node_type_define(const T0&, const T1&, const T2&, const T3&, e_vovovov)
synthesis_node_type_define(const T0&, const T1&, const T2&, const T3 , e_vovovoc)
synthesis_node_type_define(const T0&, const T1&, const T2 , const T3&, e_vovocov)
synthesis_node_type_define(const T0&, const T1 , const T2&, const T3&, e_vocovov)
synthesis_node_type_define(const T0 , const T1&, const T2&, const T3&, e_covovov)
synthesis_node_type_define(const T0 , const T1&, const T2 , const T3&, e_covocov)
synthesis_node_type_define(const T0&, const T1 , const T2&, const T3 , e_vocovoc)
synthesis_node_type_define(const T0 , const T1&, const T2&, const T3 , e_covovoc)
synthesis_node_type_define(const T0&, const T1 , const T2 , const T3&, e_vococov)
synthesis_node_type_define(const T0 , const T1 , const T2 , const T3 , e_none )
synthesis_node_type_define(const T0 , const T1 , const T2 , const T3&, e_none )
synthesis_node_type_define(const T0 , const T1 , const T2&, const T3 , e_none )
synthesis_node_type_define(const T0 , const T1&, const T2 , const T3 , e_none )
synthesis_node_type_define(const T0&, const T1 , const T2 , const T3 , e_none )
synthesis_node_type_define(const T0 , const T1 , const T2&, const T3&, e_none )
synthesis_node_type_define(const T0&, const T1&, const T2 , const T3 , e_none )
#undef synthesis_node_type_define
template <typename T, typename T0, typename T1>
class T0oT1 exprtk_final : public expression_node<T>
{
public:
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
typedef T value_type;
typedef T0oT1<T,T0,T1> node_type;
T0oT1(T0 p0, T1 p1, const bfunc_t p2)
: t0_(p0)
, t1_(p1)
, f_ (p2)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1<T,T0,T1>::result;
return result;
}
inline operator_type operation() const exprtk_override
{
return e_default;
}
inline T value() const exprtk_override
{
return f_(t0_,t1_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline bfunc_t f() const
{
return f_;
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator,
T0 p0, T1 p1,
bfunc_t p2)
{
return allocator
.template allocate_type<node_type, T0, T1, bfunc_t&>
(p0, p1, p2);
}
private:
T0oT1(const T0oT1<T,T0,T1>&) exprtk_delete;
T0oT1<T,T0,T1>& operator=(const T0oT1<T,T0,T1>&) { return (*this); }
T0 t0_;
T1 t1_;
const bfunc_t f_;
};
template <typename T, typename T0, typename T1, typename T2, typename ProcessMode>
class T0oT1oT2 exprtk_final : public T0oT1oT2_base_node<T>
{
public:
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
typedef T value_type;
typedef T0oT1oT2<T,T0,T1,T2,ProcessMode> node_type;
typedef ProcessMode process_mode_t;
T0oT1oT2(T0 p0, T1 p1, T2 p2, const bfunc_t p3, const bfunc_t p4)
: t0_(p0)
, t1_(p1)
, t2_(p2)
, f0_(p3)
, f1_(p4)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1oT2<T,T0,T1,T2>::result;
return result;
}
inline operator_type operation()
{
return e_default;
}
inline T value() const exprtk_override
{
return ProcessMode::process(t0_, t1_, t2_, f0_, f1_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline T2 t2() const
{
return t2_;
}
bfunc_t f0() const
{
return f0_;
}
bfunc_t f1() const
{
return f1_;
}
std::string type_id() const exprtk_override
{
return id();
}
static inline std::string id()
{
return process_mode_t::template id<T0,T1,T2>();
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator, T0 p0, T1 p1, T2 p2, bfunc_t p3, bfunc_t p4)
{
return allocator
.template allocate_type<node_type, T0, T1, T2, bfunc_t, bfunc_t>
(p0, p1, p2, p3, p4);
}
private:
T0oT1oT2(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
const bfunc_t f0_;
const bfunc_t f1_;
};
template <typename T, typename T0_, typename T1_, typename T2_, typename T3_, typename ProcessMode>
class T0oT1oT2oT3 exprtk_final : public T0oT1oT2oT3_base_node<T>
{
public:
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::bfunc_t bfunc_t;
typedef T value_type;
typedef T0_ T0;
typedef T1_ T1;
typedef T2_ T2;
typedef T3_ T3;
typedef T0oT1oT2oT3<T,T0,T1,T2,T3,ProcessMode> node_type;
typedef ProcessMode process_mode_t;
T0oT1oT2oT3(T0 p0, T1 p1, T2 p2, T3 p3, bfunc_t p4, bfunc_t p5, bfunc_t p6)
: t0_(p0)
, t1_(p1)
, t2_(p2)
, t3_(p3)
, f0_(p4)
, f1_(p5)
, f2_(p6)
{}
inline T value() const exprtk_override
{
return ProcessMode::process(t0_, t1_, t2_, t3_, f0_, f1_, f2_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline T2 t2() const
{
return t2_;
}
inline T3 t3() const
{
return t3_;
}
inline bfunc_t f0() const
{
return f0_;
}
inline bfunc_t f1() const
{
return f1_;
}
inline bfunc_t f2() const
{
return f2_;
}
inline std::string type_id() const exprtk_override
{
return id();
}
static inline std::string id()
{
return process_mode_t::template id<T0, T1, T2, T3>();
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator,
T0 p0, T1 p1, T2 p2, T3 p3,
bfunc_t p4, bfunc_t p5, bfunc_t p6)
{
return allocator
.template allocate_type<node_type, T0, T1, T2, T3, bfunc_t, bfunc_t>
(p0, p1, p2, p3, p4, p5, p6);
}
private:
T0oT1oT2oT3(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
T3 t3_;
const bfunc_t f0_;
const bfunc_t f1_;
const bfunc_t f2_;
};
template <typename T, typename T0, typename T1, typename T2>
class T0oT1oT2_sf3 exprtk_final : public T0oT1oT2_base_node<T>
{
public:
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::tfunc_t tfunc_t;
typedef T value_type;
typedef T0oT1oT2_sf3<T,T0,T1,T2> node_type;
T0oT1oT2_sf3(T0 p0, T1 p1, T2 p2, const tfunc_t p3)
: t0_(p0)
, t1_(p1)
, t2_(p2)
, f_ (p3)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1oT2<T,T0,T1,T2>::result;
return result;
}
inline operator_type operation() const exprtk_override
{
return e_default;
}
inline T value() const exprtk_override
{
return f_(t0_, t1_, t2_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline T2 t2() const
{
return t2_;
}
tfunc_t f() const
{
return f_;
}
std::string type_id() const
{
return id();
}
static inline std::string id()
{
return "sf3";
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator, T0 p0, T1 p1, T2 p2, tfunc_t p3)
{
return allocator
.template allocate_type<node_type, T0, T1, T2, tfunc_t>
(p0, p1, p2, p3);
}
private:
T0oT1oT2_sf3(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
const tfunc_t f_;
};
template <typename T, typename T0, typename T1, typename T2>
class sf3ext_type_node : public T0oT1oT2_base_node<T>
{
public:
virtual ~sf3ext_type_node() {}
virtual T0 t0() const = 0;
virtual T1 t1() const = 0;
virtual T2 t2() const = 0;
};
template <typename T, typename T0, typename T1, typename T2, typename SF3Operation>
class T0oT1oT2_sf3ext exprtk_final : public sf3ext_type_node<T,T0,T1,T2>
{
public:
typedef T value_type;
typedef T0oT1oT2_sf3ext<T, T0, T1, T2, SF3Operation> node_type;
T0oT1oT2_sf3ext(T0 p0, T1 p1, T2 p2)
: t0_(p0)
, t1_(p1)
, t2_(p2)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1oT2<T,T0,T1,T2>::result;
return result;
}
inline operator_type operation()
{
return e_default;
}
inline T value() const exprtk_override
{
return SF3Operation::process(t0_, t1_, t2_);
}
T0 t0() const exprtk_override
{
return t0_;
}
T1 t1() const exprtk_override
{
return t1_;
}
T2 t2() const exprtk_override
{
return t2_;
}
std::string type_id() const exprtk_override
{
return id();
}
static inline std::string id()
{
return SF3Operation::id();
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator, T0 p0, T1 p1, T2 p2)
{
return allocator
.template allocate_type<node_type, T0, T1, T2>
(p0, p1, p2);
}
private:
T0oT1oT2_sf3ext(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
};
template <typename T>
inline bool is_sf3ext_node(const expression_node<T>* n)
{
switch (n->type())
{
case expression_node<T>::e_vovov : return true;
case expression_node<T>::e_vovoc : return true;
case expression_node<T>::e_vocov : return true;
case expression_node<T>::e_covov : return true;
case expression_node<T>::e_covoc : return true;
default : return false;
}
}
template <typename T, typename T0, typename T1, typename T2, typename T3>
class T0oT1oT2oT3_sf4 exprtk_final : public T0oT1oT2_base_node<T>
{
public:
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::qfunc_t qfunc_t;
typedef T value_type;
typedef T0oT1oT2oT3_sf4<T, T0, T1, T2, T3> node_type;
T0oT1oT2oT3_sf4(T0 p0, T1 p1, T2 p2, T3 p3, const qfunc_t p4)
: t0_(p0)
, t1_(p1)
, t2_(p2)
, t3_(p3)
, f_ (p4)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1oT2oT3<T,T0,T1,T2,T3>::result;
return result;
}
inline operator_type operation() const exprtk_override
{
return e_default;
}
inline T value() const exprtk_override
{
return f_(t0_, t1_, t2_, t3_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline T2 t2() const
{
return t2_;
}
inline T3 t3() const
{
return t3_;
}
qfunc_t f() const
{
return f_;
}
std::string type_id() const
{
return id();
}
static inline std::string id()
{
return "sf4";
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator, T0 p0, T1 p1, T2 p2, T3 p3, qfunc_t p4)
{
return allocator
.template allocate_type<node_type, T0, T1, T2, T3, qfunc_t>
(p0, p1, p2, p3, p4);
}
private:
T0oT1oT2oT3_sf4(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
T3 t3_;
const qfunc_t f_;
};
template <typename T, typename T0, typename T1, typename T2, typename T3, typename SF4Operation>
class T0oT1oT2oT3_sf4ext exprtk_final : public T0oT1oT2oT3_base_node<T>
{
public:
typedef T value_type;
typedef T0oT1oT2oT3_sf4ext<T, T0, T1, T2, T3, SF4Operation> node_type;
T0oT1oT2oT3_sf4ext(T0 p0, T1 p1, T2 p2, T3 p3)
: t0_(p0)
, t1_(p1)
, t2_(p2)
, t3_(p3)
{}
inline typename expression_node<T>::node_type type() const exprtk_override
{
static const typename expression_node<T>::node_type result = nodetype_T0oT1oT2oT3<T,T0,T1,T2,T3>::result;
return result;
}
inline T value() const exprtk_override
{
return SF4Operation::process(t0_, t1_, t2_, t3_);
}
inline T0 t0() const
{
return t0_;
}
inline T1 t1() const
{
return t1_;
}
inline T2 t2() const
{
return t2_;
}
inline T3 t3() const
{
return t3_;
}
std::string type_id() const exprtk_override
{
return id();
}
static inline std::string id()
{
return SF4Operation::id();
}
template <typename Allocator>
static inline expression_node<T>* allocate(Allocator& allocator, T0 p0, T1 p1, T2 p2, T3 p3)
{
return allocator
.template allocate_type<node_type, T0, T1, T2, T3>
(p0, p1, p2, p3);
}
private:
T0oT1oT2oT3_sf4ext(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
T0 t0_;
T1 t1_;
T2 t2_;
T3 t3_;
};
template <typename T>
inline bool is_sf4ext_node(const expression_node<T>* n)
{
switch (n->type())
{
case expression_node<T>::e_vovovov : return true;
case expression_node<T>::e_vovovoc : return true;
case expression_node<T>::e_vovocov : return true;
case expression_node<T>::e_vocovov : return true;
case expression_node<T>::e_covovov : return true;
case expression_node<T>::e_covocov : return true;
case expression_node<T>::e_vocovoc : return true;
case expression_node<T>::e_covovoc : return true;
case expression_node<T>::e_vococov : return true;
default : return false;
}
}
template <typename T, typename T0, typename T1>
struct T0oT1_define
{
typedef details::T0oT1<T, T0, T1> type0;
};
template <typename T, typename T0, typename T1, typename T2>
struct T0oT1oT2_define
{
typedef details::T0oT1oT2<T, T0, T1, T2, typename T0oT1oT2process<T>::mode0> type0;
typedef details::T0oT1oT2<T, T0, T1, T2, typename T0oT1oT2process<T>::mode1> type1;
typedef details::T0oT1oT2_sf3<T, T0, T1, T2> sf3_type;
typedef details::sf3ext_type_node<T, T0, T1, T2> sf3_type_node;
};
template <typename T, typename T0, typename T1, typename T2, typename T3>
struct T0oT1oT2oT3_define
{
typedef details::T0oT1oT2oT3<T, T0, T1, T2, T3, typename T0oT1oT20T3process<T>::mode0> type0;
typedef details::T0oT1oT2oT3<T, T0, T1, T2, T3, typename T0oT1oT20T3process<T>::mode1> type1;
typedef details::T0oT1oT2oT3<T, T0, T1, T2, T3, typename T0oT1oT20T3process<T>::mode2> type2;
typedef details::T0oT1oT2oT3<T, T0, T1, T2, T3, typename T0oT1oT20T3process<T>::mode3> type3;
typedef details::T0oT1oT2oT3<T, T0, T1, T2, T3, typename T0oT1oT20T3process<T>::mode4> type4;
typedef details::T0oT1oT2oT3_sf4<T, T0, T1, T2, T3> sf4_type;
};
template <typename T, typename Operation>
class vov_node exprtk_final : public vov_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
// variable op variable node
explicit vov_node(const T& var0, const T& var1)
: v0_(var0)
, v1_(var1)
{}
inline T value() const exprtk_override
{
return Operation::process(v0_,v1_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T& v0() const exprtk_override
{
return v0_;
}
inline const T& v1() const exprtk_override
{
return v1_;
}
protected:
const T& v0_;
const T& v1_;
private:
vov_node(const vov_node<T,Operation>&) exprtk_delete;
vov_node<T,Operation>& operator=(const vov_node<T,Operation>&) exprtk_delete;
};
template <typename T, typename Operation>
class cov_node exprtk_final : public cov_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
// constant op variable node
explicit cov_node(const T& const_var, const T& var)
: c_(const_var)
, v_(var)
{}
inline T value() const exprtk_override
{
return Operation::process(c_,v_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T c() const exprtk_override
{
return c_;
}
inline const T& v() const exprtk_override
{
return v_;
}
protected:
const T c_;
const T& v_;
private:
cov_node(const cov_node<T,Operation>&) exprtk_delete;
cov_node<T,Operation>& operator=(const cov_node<T,Operation>&) exprtk_delete;
};
template <typename T, typename Operation>
class voc_node exprtk_final : public voc_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
// variable op constant node
explicit voc_node(const T& var, const T& const_var)
: v_(var)
, c_(const_var)
{}
inline T value() const exprtk_override
{
return Operation::process(v_,c_);
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T c() const exprtk_override
{
return c_;
}
inline const T& v() const exprtk_override
{
return v_;
}
protected:
const T& v_;
const T c_;
private:
voc_node(const voc_node<T,Operation>&) exprtk_delete;
voc_node<T,Operation>& operator=(const voc_node<T,Operation>&) exprtk_delete;
};
template <typename T, typename Operation>
class vob_node exprtk_final : public vob_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
typedef Operation operation_t;
// variable op constant node
explicit vob_node(const T& var, const expression_ptr branch)
: v_(var)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return Operation::process(v_,branch_.first->value());
}
inline const T& v() const exprtk_override
{
return v_;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
vob_node(const vob_node<T,Operation>&) exprtk_delete;
vob_node<T,Operation>& operator=(const vob_node<T,Operation>&) exprtk_delete;
const T& v_;
branch_t branch_;
};
template <typename T, typename Operation>
class bov_node exprtk_final : public bov_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
typedef Operation operation_t;
// variable op constant node
explicit bov_node(const expression_ptr branch, const T& var)
: v_(var)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return Operation::process(branch_.first->value(),v_);
}
inline const T& v() const exprtk_override
{
return v_;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
bov_node(const bov_node<T,Operation>&) exprtk_delete;
bov_node<T,Operation>& operator=(const bov_node<T,Operation>&) exprtk_delete;
const T& v_;
branch_t branch_;
};
template <typename T, typename Operation>
class cob_node exprtk_final : public cob_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
typedef Operation operation_t;
// variable op constant node
explicit cob_node(const T const_var, const expression_ptr branch)
: c_(const_var)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return Operation::process(c_,branch_.first->value());
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T c() const exprtk_override
{
return c_;
}
inline void set_c(const T new_c) exprtk_override
{
(*const_cast<T*>(&c_)) = new_c;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
inline expression_node<T>* move_branch(const std::size_t&) exprtk_override
{
branch_.second = false;
return branch_.first;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
cob_node(const cob_node<T,Operation>&) exprtk_delete;
cob_node<T,Operation>& operator=(const cob_node<T,Operation>&) exprtk_delete;
const T c_;
branch_t branch_;
};
template <typename T, typename Operation>
class boc_node exprtk_final : public boc_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr,bool> branch_t;
typedef Operation operation_t;
// variable op constant node
explicit boc_node(const expression_ptr branch, const T const_var)
: c_(const_var)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return Operation::process(branch_.first->value(),c_);
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline const T c() const exprtk_override
{
return c_;
}
inline void set_c(const T new_c) exprtk_override
{
(*const_cast<T*>(&c_)) = new_c;
}
inline expression_node<T>* branch(const std::size_t&) const exprtk_override
{
return branch_.first;
}
inline expression_node<T>* move_branch(const std::size_t&) exprtk_override
{
branch_.second = false;
return branch_.first;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
boc_node(const boc_node<T,Operation>&) exprtk_delete;
boc_node<T,Operation>& operator=(const boc_node<T,Operation>&) exprtk_delete;
const T c_;
branch_t branch_;
};
#ifndef exprtk_disable_string_capabilities
template <typename T, typename SType0, typename SType1, typename Operation>
class sos_node exprtk_final : public sos_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
// string op string node
explicit sos_node(SType0 p0, SType1 p1)
: s0_(p0)
, s1_(p1)
{}
inline T value() const exprtk_override
{
return Operation::process(s0_,s1_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline std::string& s0()
{
return s0_;
}
inline std::string& s1()
{
return s1_;
}
protected:
SType0 s0_;
SType1 s1_;
private:
sos_node(const sos_node<T,SType0,SType1,Operation>&) exprtk_delete;
sos_node<T,SType0,SType1,Operation>& operator=(const sos_node<T,SType0,SType1,Operation>&) exprtk_delete;
};
template <typename T, typename SType0, typename SType1, typename RangePack, typename Operation>
class str_xrox_node exprtk_final : public sos_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
typedef str_xrox_node<T,SType0,SType1,RangePack,Operation> node_type;
// string-range op string node
explicit str_xrox_node(SType0 p0, SType1 p1, RangePack rp0)
: s0_ (p0 )
, s1_ (p1 )
, rp0_(rp0)
{}
~str_xrox_node()
{
rp0_.free();
}
inline T value() const exprtk_override
{
std::size_t r0 = 0;
std::size_t r1 = 0;
if (rp0_(r0, r1, s0_.size()))
return Operation::process(s0_.substr(r0, (r1 - r0) + 1), s1_);
else
return T(0);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline std::string& s0()
{
return s0_;
}
inline std::string& s1()
{
return s1_;
}
protected:
SType0 s0_;
SType1 s1_;
RangePack rp0_;
private:
str_xrox_node(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
};
template <typename T, typename SType0, typename SType1, typename RangePack, typename Operation>
class str_xoxr_node exprtk_final : public sos_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
typedef str_xoxr_node<T,SType0,SType1,RangePack,Operation> node_type;
// string op string range node
explicit str_xoxr_node(SType0 p0, SType1 p1, RangePack rp1)
: s0_ (p0 )
, s1_ (p1 )
, rp1_(rp1)
{}
~str_xoxr_node()
{
rp1_.free();
}
inline T value() const exprtk_override
{
std::size_t r0 = 0;
std::size_t r1 = 0;
if (rp1_(r0, r1, s1_.size()))
return Operation::process(s0_, s1_.substr(r0, (r1 - r0) + 1));
else
return T(0);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline std::string& s0()
{
return s0_;
}
inline std::string& s1()
{
return s1_;
}
protected:
SType0 s0_;
SType1 s1_;
RangePack rp1_;
private:
str_xoxr_node(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
};
template <typename T, typename SType0, typename SType1, typename RangePack, typename Operation>
class str_xroxr_node exprtk_final : public sos_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
typedef str_xroxr_node<T,SType0,SType1,RangePack,Operation> node_type;
// string-range op string-range node
explicit str_xroxr_node(SType0 p0, SType1 p1, RangePack rp0, RangePack rp1)
: s0_ (p0 )
, s1_ (p1 )
, rp0_(rp0)
, rp1_(rp1)
{}
~str_xroxr_node()
{
rp0_.free();
rp1_.free();
}
inline T value() const exprtk_override
{
std::size_t r0_0 = 0;
std::size_t r0_1 = 0;
std::size_t r1_0 = 0;
std::size_t r1_1 = 0;
if (
rp0_(r0_0, r1_0, s0_.size()) &&
rp1_(r0_1, r1_1, s1_.size())
)
{
return Operation::process(
s0_.substr(r0_0, (r1_0 - r0_0) + 1),
s1_.substr(r0_1, (r1_1 - r0_1) + 1)
);
}
else
return T(0);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline std::string& s0()
{
return s0_;
}
inline std::string& s1()
{
return s1_;
}
protected:
SType0 s0_;
SType1 s1_;
RangePack rp0_;
RangePack rp1_;
private:
str_xroxr_node(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
};
template <typename T, typename Operation>
class str_sogens_node exprtk_final : public binary_node<T>
{
public:
typedef expression_node <T>* expression_ptr;
typedef string_base_node<T>* str_base_ptr;
typedef range_pack <T> range_t;
typedef range_t* range_ptr;
typedef range_interface <T> irange_t;
typedef irange_t* irange_ptr;
using binary_node<T>::branch;
str_sogens_node(const operator_type& opr,
expression_ptr branch0,
expression_ptr branch1)
: binary_node<T>(opr, branch0, branch1)
, str0_base_ptr_ (0)
, str1_base_ptr_ (0)
, str0_range_ptr_(0)
, str1_range_ptr_(0)
{
if (is_generally_string_node(branch(0)))
{
str0_base_ptr_ = dynamic_cast<str_base_ptr>(branch(0));
if (0 == str0_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(0));
if (0 == range)
return;
str0_range_ptr_ = &(range->range_ref());
}
if (is_generally_string_node(branch(1)))
{
str1_base_ptr_ = dynamic_cast<str_base_ptr>(branch(1));
if (0 == str1_base_ptr_)
return;
irange_ptr range = dynamic_cast<irange_ptr>(branch(1));
if (0 == range)
return;
str1_range_ptr_ = &(range->range_ref());
}
}
inline T value() const exprtk_override
{
if (
str0_base_ptr_ &&
str1_base_ptr_ &&
str0_range_ptr_ &&
str1_range_ptr_
)
{
branch(0)->value();
branch(1)->value();
std::size_t str0_r0 = 0;
std::size_t str0_r1 = 0;
std::size_t str1_r0 = 0;
std::size_t str1_r1 = 0;
const range_t& range0 = (*str0_range_ptr_);
const range_t& range1 = (*str1_range_ptr_);
if (
range0(str0_r0, str0_r1, str0_base_ptr_->size()) &&
range1(str1_r0, str1_r1, str1_base_ptr_->size())
)
{
return Operation::process(
str0_base_ptr_->str().substr(str0_r0,(str0_r1 - str0_r0) + 1),
str1_base_ptr_->str().substr(str1_r0,(str1_r1 - str1_r0) + 1)
);
}
}
return std::numeric_limits<T>::quiet_NaN();
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
private:
str_sogens_node(const str_sogens_node<T,Operation>&) exprtk_delete;
str_sogens_node<T,Operation>& operator=(const str_sogens_node<T,Operation>&) exprtk_delete;
str_base_ptr str0_base_ptr_;
str_base_ptr str1_base_ptr_;
range_ptr str0_range_ptr_;
range_ptr str1_range_ptr_;
};
template <typename T, typename SType0, typename SType1, typename SType2, typename Operation>
class sosos_node exprtk_final : public sosos_base_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef Operation operation_t;
typedef sosos_node<T, SType0, SType1, SType2, Operation> node_type;
// variable op variable node
explicit sosos_node(SType0 p0, SType1 p1, SType2 p2)
: s0_(p0)
, s1_(p1)
, s2_(p2)
{}
inline T value() const exprtk_override
{
return Operation::process(s0_, s1_, s2_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return Operation::type();
}
inline operator_type operation() const exprtk_override
{
return Operation::operation();
}
inline std::string& s0()
{
return s0_;
}
inline std::string& s1()
{
return s1_;
}
inline std::string& s2()
{
return s2_;
}
protected:
SType0 s0_;
SType1 s1_;
SType2 s2_;
private:
sosos_node(const node_type&) exprtk_delete;
node_type& operator=(const node_type&) exprtk_delete;
};
#endif
template <typename T, typename PowOp>
class ipow_node exprtk_final: public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef PowOp operation_t;
explicit ipow_node(const T& v)
: v_(v)
{}
inline T value() const exprtk_override
{
return PowOp::result(v_);
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_ipow;
}
private:
ipow_node(const ipow_node<T,PowOp>&) exprtk_delete;
ipow_node<T,PowOp>& operator=(const ipow_node<T,PowOp>&) exprtk_delete;
const T& v_;
};
template <typename T, typename PowOp>
class bipow_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr, bool> branch_t;
typedef PowOp operation_t;
explicit bipow_node(expression_ptr branch)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return PowOp::result(branch_.first->value());
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_ipow;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
bipow_node(const bipow_node<T,PowOp>&) exprtk_delete;
bipow_node<T,PowOp>& operator=(const bipow_node<T,PowOp>&) exprtk_delete;
branch_t branch_;
};
template <typename T, typename PowOp>
class ipowinv_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef PowOp operation_t;
explicit ipowinv_node(const T& v)
: v_(v)
{}
inline T value() const exprtk_override
{
return (T(1) / PowOp::result(v_));
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_ipowinv;
}
private:
ipowinv_node(const ipowinv_node<T,PowOp>&) exprtk_delete;
ipowinv_node<T,PowOp>& operator=(const ipowinv_node<T,PowOp>&) exprtk_delete;
const T& v_;
};
template <typename T, typename PowOp>
class bipowninv_node exprtk_final : public expression_node<T>
{
public:
typedef expression_node<T>* expression_ptr;
typedef std::pair<expression_ptr, bool> branch_t;
typedef PowOp operation_t;
explicit bipowninv_node(expression_ptr branch)
{
construct_branch_pair(branch_, branch);
}
inline T value() const exprtk_override
{
assert(branch_.first);
return (T(1) / PowOp::result(branch_.first->value()));
}
inline typename expression_node<T>::node_type type() const exprtk_override
{
return expression_node<T>::e_ipowinv;
}
void collect_nodes(typename expression_node<T>::noderef_list_t& node_delete_list) exprtk_override
{
expression_node<T>::ndb_t::template collect(branch_, node_delete_list);
}
std::size_t node_depth() const exprtk_override
{
return expression_node<T>::ndb_t::compute_node_depth(branch_);
}
private:
bipowninv_node(const bipowninv_node<T,PowOp>&) exprtk_delete;
bipowninv_node<T,PowOp>& operator=(const bipowninv_node<T,PowOp>&) exprtk_delete;
branch_t branch_;
};
template <typename T>
inline bool is_vov_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const vov_base_node<T>*>(node));
}
template <typename T>
inline bool is_cov_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const cov_base_node<T>*>(node));
}
template <typename T>
inline bool is_voc_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const voc_base_node<T>*>(node));
}
template <typename T>
inline bool is_cob_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const cob_base_node<T>*>(node));
}
template <typename T>
inline bool is_boc_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const boc_base_node<T>*>(node));
}
template <typename T>
inline bool is_t0ot1ot2_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const T0oT1oT2_base_node<T>*>(node));
}
template <typename T>
inline bool is_t0ot1ot2ot3_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const T0oT1oT2oT3_base_node<T>*>(node));
}
template <typename T>
inline bool is_uv_node(const expression_node<T>* node)
{
return (0 != dynamic_cast<const uv_base_node<T>*>(node));
}
template <typename T>
inline bool is_string_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_stringvar == node->type());
}
template <typename T>
inline bool is_string_range_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_stringvarrng == node->type());
}
template <typename T>
inline bool is_const_string_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_stringconst == node->type());
}
template <typename T>
inline bool is_const_string_range_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_cstringvarrng == node->type());
}
template <typename T>
inline bool is_string_assignment_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strass == node->type());
}
template <typename T>
inline bool is_string_concat_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strconcat == node->type());
}
template <typename T>
inline bool is_string_function_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strfunction == node->type());
}
template <typename T>
inline bool is_string_condition_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strcondition == node->type());
}
template <typename T>
inline bool is_string_ccondition_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strccondition == node->type());
}
template <typename T>
inline bool is_string_vararg_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_stringvararg == node->type());
}
template <typename T>
inline bool is_genricstring_range_node(const expression_node<T>* node)
{
return node && (expression_node<T>::e_strgenrange == node->type());
}
template <typename T>
inline bool is_generally_string_node(const expression_node<T>* node)
{
if (node)
{
switch (node->type())
{
case expression_node<T>::e_stringvar :
case expression_node<T>::e_stringconst :
case expression_node<T>::e_stringvarrng :
case expression_node<T>::e_cstringvarrng :
case expression_node<T>::e_strgenrange :
case expression_node<T>::e_strass :
case expression_node<T>::e_strconcat :
case expression_node<T>::e_strfunction :
case expression_node<T>::e_strcondition :
case expression_node<T>::e_strccondition :
case expression_node<T>::e_stringvararg : return true;
default : return false;
}
}
return false;
}
class node_allocator
{
public:
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[1])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0]);
result->node_depth();
return result;
}
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[2])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0], branch[1]);
result->node_depth();
return result;
}
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[3])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0], branch[1], branch[2]);
result->node_depth();
return result;
}
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[4])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0], branch[1], branch[2], branch[3]);
result->node_depth();
return result;
}
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[5])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0],branch[1], branch[2], branch[3], branch[4]);
result->node_depth();
return result;
}
template <typename ResultNode, typename OpType, typename ExprNode>
inline expression_node<typename ResultNode::value_type>* allocate(OpType& operation, ExprNode (&branch)[6])
{
expression_node<typename ResultNode::value_type>* result =
allocate<ResultNode>(operation, branch[0], branch[1], branch[2], branch[3], branch[4], branch[5]);
result->node_depth();
return result;
}
template <typename node_type>
inline expression_node<typename node_type::value_type>* allocate() const
{
return (new node_type());
}
template <typename node_type,
typename Type,
typename Allocator,
template <typename, typename> class Sequence>
inline expression_node<typename node_type::value_type>* allocate(const Sequence<Type,Allocator>& seq) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(seq));
result->node_depth();
return result;
}
template <typename node_type, typename T1>
inline expression_node<typename node_type::value_type>* allocate(T1& t1) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1));
result->node_depth();
return result;
}
template <typename node_type, typename T1>
inline expression_node<typename node_type::value_type>* allocate_c(const T1& t1) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2>
inline expression_node<typename node_type::value_type>* allocate_cr(const T1& t1, T2& t2) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2>
inline expression_node<typename node_type::value_type>* allocate_rc(T1& t1, const T2& t2) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2>
inline expression_node<typename node_type::value_type>* allocate_rr(T1& t1, T2& t2) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2>
inline expression_node<typename node_type::value_type>* allocate_tt(T1 t1, T2 t2) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3>
inline expression_node<typename node_type::value_type>* allocate_ttt(T1 t1, T2 t2, T3 t3) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3, typename T4>
inline expression_node<typename node_type::value_type>* allocate_tttt(T1 t1, T2 t2, T3 t3, T4 t4) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3>
inline expression_node<typename node_type::value_type>* allocate_rrr(T1& t1, T2& t2, T3& t3) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3, typename T4>
inline expression_node<typename node_type::value_type>* allocate_rrrr(T1& t1, T2& t2, T3& t3, T4& t4) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3, typename T4, typename T5>
inline expression_node<typename node_type::value_type>* allocate_rrrrr(T1& t1, T2& t2, T3& t3, T4& t4, T5& t5) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4, typename T5>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4, typename T5, typename T6>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5, const T6& t6) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6, typename T7>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5, const T6& t6,
const T7& t7) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6, t7));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6,
typename T7, typename T8>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5, const T6& t6,
const T7& t7, const T8& t8) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6, t7, t8));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6,
typename T7, typename T8, typename T9>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5, const T6& t6,
const T7& t7, const T8& t8,
const T9& t9) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6, t7, t8, t9));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6,
typename T7, typename T8,
typename T9, typename T10>
inline expression_node<typename node_type::value_type>* allocate(const T1& t1, const T2& t2,
const T3& t3, const T4& t4,
const T5& t5, const T6& t6,
const T7& t7, const T8& t8,
const T9& t9, const T10& t10) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2, typename T3>
inline expression_node<typename node_type::value_type>* allocate_type(T1 t1, T2 t2, T3 t3) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4>
inline expression_node<typename node_type::value_type>* allocate_type(T1 t1, T2 t2,
T3 t3, T4 t4) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5>
inline expression_node<typename node_type::value_type>* allocate_type(T1 t1, T2 t2,
T3 t3, T4 t4,
T5 t5) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6>
inline expression_node<typename node_type::value_type>* allocate_type(T1 t1, T2 t2,
T3 t3, T4 t4,
T5 t5, T6 t6) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6));
result->node_depth();
return result;
}
template <typename node_type,
typename T1, typename T2,
typename T3, typename T4,
typename T5, typename T6, typename T7>
inline expression_node<typename node_type::value_type>* allocate_type(T1 t1, T2 t2,
T3 t3, T4 t4,
T5 t5, T6 t6,
T7 t7) const
{
expression_node<typename node_type::value_type>*
result = (new node_type(t1, t2, t3, t4, t5, t6, t7));
result->node_depth();
return result;
}
template <typename T>
void inline free(expression_node<T>*& e) const
{
exprtk_debug(("node_allocator::free() - deleting expression_node "
"type: %03d addr: %p\n",
static_cast<int>(e->type()),
reinterpret_cast<void*>(e)));
delete e;
e = 0;
}
};
inline void load_operations_map(std::multimap<std::string,details::base_operation_t,details::ilesscompare>& m)
{
#define register_op(Symbol, Type, Args) \
m.insert(std::make_pair(std::string(Symbol),details::base_operation_t(Type,Args))); \
register_op("abs" , e_abs , 1)
register_op("acos" , e_acos , 1)
register_op("acosh" , e_acosh , 1)
register_op("asin" , e_asin , 1)
register_op("asinh" , e_asinh , 1)
register_op("atan" , e_atan , 1)
register_op("atanh" , e_atanh , 1)
register_op("ceil" , e_ceil , 1)
register_op("cos" , e_cos , 1)
register_op("cosh" , e_cosh , 1)
register_op("exp" , e_exp , 1)
register_op("expm1" , e_expm1 , 1)
register_op("floor" , e_floor , 1)
register_op("log" , e_log , 1)
register_op("log10" , e_log10 , 1)
register_op("log2" , e_log2 , 1)
register_op("log1p" , e_log1p , 1)
register_op("round" , e_round , 1)
register_op("sin" , e_sin , 1)
register_op("sinc" , e_sinc , 1)
register_op("sinh" , e_sinh , 1)
register_op("sec" , e_sec , 1)
register_op("csc" , e_csc , 1)
register_op("sqrt" , e_sqrt , 1)
register_op("tan" , e_tan , 1)
register_op("tanh" , e_tanh , 1)
register_op("cot" , e_cot , 1)
register_op("rad2deg" , e_r2d , 1)
register_op("deg2rad" , e_d2r , 1)
register_op("deg2grad" , e_d2g , 1)
register_op("grad2deg" , e_g2d , 1)
register_op("sgn" , e_sgn , 1)
register_op("not" , e_notl , 1)
register_op("erf" , e_erf , 1)
register_op("erfc" , e_erfc , 1)
register_op("ncdf" , e_ncdf , 1)
register_op("frac" , e_frac , 1)
register_op("trunc" , e_trunc , 1)
register_op("atan2" , e_atan2 , 2)
register_op("mod" , e_mod , 2)
register_op("logn" , e_logn , 2)
register_op("pow" , e_pow , 2)
register_op("root" , e_root , 2)
register_op("roundn" , e_roundn , 2)
register_op("equal" , e_equal , 2)
register_op("not_equal" , e_nequal , 2)
register_op("hypot" , e_hypot , 2)
register_op("shr" , e_shr , 2)
register_op("shl" , e_shl , 2)
register_op("clamp" , e_clamp , 3)
register_op("iclamp" , e_iclamp , 3)
register_op("inrange" , e_inrange , 3)
#undef register_op
}
} // namespace details
class function_traits
{
public:
function_traits()
: allow_zero_parameters_(false)
, has_side_effects_(true)
, min_num_args_(0)
, max_num_args_(std::numeric_limits<std::size_t>::max())
{}
inline bool& allow_zero_parameters()
{
return allow_zero_parameters_;
}
inline bool& has_side_effects()
{
return has_side_effects_;
}
std::size_t& min_num_args()
{
return min_num_args_;
}
std::size_t& max_num_args()
{
return max_num_args_;
}
private:
bool allow_zero_parameters_;
bool has_side_effects_;
std::size_t min_num_args_;
std::size_t max_num_args_;
};
template <typename FunctionType>
void enable_zero_parameters(FunctionType& func)
{
func.allow_zero_parameters() = true;
if (0 != func.min_num_args())
{
func.min_num_args() = 0;
}
}
template <typename FunctionType>
void disable_zero_parameters(FunctionType& func)
{
func.allow_zero_parameters() = false;
}
template <typename FunctionType>
void enable_has_side_effects(FunctionType& func)
{
func.has_side_effects() = true;
}
template <typename FunctionType>
void disable_has_side_effects(FunctionType& func)
{
func.has_side_effects() = false;
}
template <typename FunctionType>
void set_min_num_args(FunctionType& func, const std::size_t& num_args)
{
func.min_num_args() = num_args;
if ((0 != func.min_num_args()) && func.allow_zero_parameters())
func.allow_zero_parameters() = false;
}
template <typename FunctionType>
void set_max_num_args(FunctionType& func, const std::size_t& num_args)
{
func.max_num_args() = num_args;
}
template <typename T>
class ifunction : public function_traits
{
public:
explicit ifunction(const std::size_t& pc)
: param_count(pc)
{}
virtual ~ifunction() {}
#define empty_method_body(N) \
{ \
exprtk_debug(("ifunction::operator() - Operator(" #N ") has not been overridden\n")); \
return std::numeric_limits<T>::quiet_NaN(); \
} \
inline virtual T operator() ()
empty_method_body(0)
inline virtual T operator() (const T&)
empty_method_body(1)
inline virtual T operator() (const T&,const T&)
empty_method_body(2)
inline virtual T operator() (const T&, const T&, const T&)
empty_method_body(3)
inline virtual T operator() (const T&, const T&, const T&, const T&)
empty_method_body(4)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&)
empty_method_body(5)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(6)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(7)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(8)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(9)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(10)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&)
empty_method_body(11)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&)
empty_method_body(12)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&)
empty_method_body(13)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&)
empty_method_body(14)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&)
empty_method_body(15)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(16)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(17)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(18)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(19)
inline virtual T operator() (const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&,
const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&, const T&)
empty_method_body(20)
#undef empty_method_body
std::size_t param_count;
};
template <typename T>
class ivararg_function : public function_traits
{
public:
virtual ~ivararg_function() {}
inline virtual T operator() (const std::vector<T>&)
{
exprtk_debug(("ivararg_function::operator() - Operator has not been overridden\n"));
return std::numeric_limits<T>::quiet_NaN();
}
};
template <typename T>
class igeneric_function : public function_traits
{
public:
enum return_type
{
e_rtrn_scalar = 0,
e_rtrn_string = 1,
e_rtrn_overload = 2
};
typedef T type;
typedef type_store<T> generic_type;
typedef typename generic_type::parameter_list parameter_list_t;
igeneric_function(const std::string& param_seq = "", const return_type rtr_type = e_rtrn_scalar)
: parameter_sequence(param_seq)
, rtrn_type(rtr_type)
{}
virtual ~igeneric_function() {}
#define igeneric_function_empty_body(N) \
{ \
exprtk_debug(("igeneric_function::operator() - Operator(" #N ") has not been overridden\n")); \
return std::numeric_limits<T>::quiet_NaN(); \
} \
// f(i_0,i_1,....,i_N) --> Scalar
inline virtual T operator() (parameter_list_t)
igeneric_function_empty_body(1)
// f(i_0,i_1,....,i_N) --> String
inline virtual T operator() (std::string&, parameter_list_t)
igeneric_function_empty_body(2)
// f(psi,i_0,i_1,....,i_N) --> Scalar
inline virtual T operator() (const std::size_t&, parameter_list_t)
igeneric_function_empty_body(3)
// f(psi,i_0,i_1,....,i_N) --> String
inline virtual T operator() (const std::size_t&, std::string&, parameter_list_t)
igeneric_function_empty_body(4)
std::string parameter_sequence;
return_type rtrn_type;
};
#ifndef exprtk_disable_string_capabilities
template <typename T>
class stringvar_base
{
public:
typedef typename details::stringvar_node<T> stringvar_node_t;
stringvar_base(const std::string& name, stringvar_node_t* svn)
: name_(name)
, string_varnode_(svn)
{}
bool valid() const
{
return !name_.empty() && (0 != string_varnode_);
}
std::string name() const
{
assert(string_varnode_);
return name_;
}
void rebase(std::string& s)
{
assert(string_varnode_);
string_varnode_->rebase(s);
}
private:
std::string name_;
stringvar_node_t* string_varnode_;
};
#endif
template <typename T> class parser;
template <typename T> class expression_helper;
template <typename T>
class symbol_table
{
public:
enum symtab_mutability_type
{
e_unknown = 0,
e_mutable = 1,
e_immutable = 2
};
typedef T (*ff00_functor)();
typedef T (*ff01_functor)(T);
typedef T (*ff02_functor)(T, T);
typedef T (*ff03_functor)(T, T, T);
typedef T (*ff04_functor)(T, T, T, T);
typedef T (*ff05_functor)(T, T, T, T, T);
typedef T (*ff06_functor)(T, T, T, T, T, T);
typedef T (*ff07_functor)(T, T, T, T, T, T, T);
typedef T (*ff08_functor)(T, T, T, T, T, T, T, T);
typedef T (*ff09_functor)(T, T, T, T, T, T, T, T, T);
typedef T (*ff10_functor)(T, T, T, T, T, T, T, T, T, T);
typedef T (*ff11_functor)(T, T, T, T, T, T, T, T, T, T, T);
typedef T (*ff12_functor)(T, T, T, T, T, T, T, T, T, T, T, T);
typedef T (*ff13_functor)(T, T, T, T, T, T, T, T, T, T, T, T, T);
typedef T (*ff14_functor)(T, T, T, T, T, T, T, T, T, T, T, T, T, T);
typedef T (*ff15_functor)(T, T, T, T, T, T, T, T, T, T, T, T, T, T, T);
protected:
struct freefunc00 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc00(ff00_functor ff) : exprtk::ifunction<T>(0), f(ff) {}
inline T operator() () exprtk_override
{ return f(); }
ff00_functor f;
};
struct freefunc01 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc01(ff01_functor ff) : exprtk::ifunction<T>(1), f(ff) {}
inline T operator() (const T& v0) exprtk_override
{ return f(v0); }
ff01_functor f;
};
struct freefunc02 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc02(ff02_functor ff) : exprtk::ifunction<T>(2), f(ff) {}
inline T operator() (const T& v0, const T& v1) exprtk_override
{ return f(v0, v1); }
ff02_functor f;
};
struct freefunc03 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc03(ff03_functor ff) : exprtk::ifunction<T>(3), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2) exprtk_override
{ return f(v0, v1, v2); }
ff03_functor f;
};
struct freefunc04 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc04(ff04_functor ff) : exprtk::ifunction<T>(4), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3) exprtk_override
{ return f(v0, v1, v2, v3); }
ff04_functor f;
};
struct freefunc05 : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc05(ff05_functor ff) : exprtk::ifunction<T>(5), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4) exprtk_override
{ return f(v0, v1, v2, v3, v4); }
ff05_functor f;
};
struct freefunc06 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc06(ff06_functor ff) : exprtk::ifunction<T>(6), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4, const T& v5) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5); }
ff06_functor f;
};
struct freefunc07 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc07(ff07_functor ff) : exprtk::ifunction<T>(7), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4,
const T& v5, const T& v6) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5, v6); }
ff07_functor f;
};
struct freefunc08 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc08(ff08_functor ff) : exprtk::ifunction<T>(8), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4,
const T& v5, const T& v6, const T& v7) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5, v6, v7); }
ff08_functor f;
};
struct freefunc09 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc09(ff09_functor ff) : exprtk::ifunction<T>(9), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4,
const T& v5, const T& v6, const T& v7, const T& v8) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5, v6, v7, v8); }
ff09_functor f;
};
struct freefunc10 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc10(ff10_functor ff) : exprtk::ifunction<T>(10), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4,
const T& v5, const T& v6, const T& v7, const T& v8, const T& v9) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9); }
ff10_functor f;
};
struct freefunc11 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc11(ff11_functor ff) : exprtk::ifunction<T>(11), f(ff) {}
inline T operator() (const T& v0, const T& v1, const T& v2, const T& v3, const T& v4,
const T& v5, const T& v6, const T& v7, const T& v8, const T& v9, const T& v10) exprtk_override
{ return f(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); }
ff11_functor f;
};
struct freefunc12 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc12(ff12_functor ff) : exprtk::ifunction<T>(12), f(ff) {}
inline T operator() (const T& v00, const T& v01, const T& v02, const T& v03, const T& v04,
const T& v05, const T& v06, const T& v07, const T& v08, const T& v09,
const T& v10, const T& v11) exprtk_override
{ return f(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11); }
ff12_functor f;
};
struct freefunc13 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc13(ff13_functor ff) : exprtk::ifunction<T>(13), f(ff) {}
inline T operator() (const T& v00, const T& v01, const T& v02, const T& v03, const T& v04,
const T& v05, const T& v06, const T& v07, const T& v08, const T& v09,
const T& v10, const T& v11, const T& v12) exprtk_override
{ return f(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12); }
ff13_functor f;
};
struct freefunc14 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc14(ff14_functor ff) : exprtk::ifunction<T>(14), f(ff) {}
inline T operator() (const T& v00, const T& v01, const T& v02, const T& v03, const T& v04,
const T& v05, const T& v06, const T& v07, const T& v08, const T& v09,
const T& v10, const T& v11, const T& v12, const T& v13) exprtk_override
{ return f(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13); }
ff14_functor f;
};
struct freefunc15 exprtk_final : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
explicit freefunc15(ff15_functor ff) : exprtk::ifunction<T>(15), f(ff) {}
inline T operator() (const T& v00, const T& v01, const T& v02, const T& v03, const T& v04,
const T& v05, const T& v06, const T& v07, const T& v08, const T& v09,
const T& v10, const T& v11, const T& v12, const T& v13, const T& v14) exprtk_override
{ return f(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14); }
ff15_functor f;
};
template <typename Type, typename RawType>
struct type_store
{
typedef details::expression_node<T>* expression_ptr;
typedef typename details::variable_node<T> variable_node_t;
typedef ifunction<T> ifunction_t;
typedef ivararg_function<T> ivararg_function_t;
typedef igeneric_function<T> igeneric_function_t;
typedef details::vector_holder<T> vector_t;
#ifndef exprtk_disable_string_capabilities
typedef typename details::stringvar_node<T> stringvar_node_t;
#endif
typedef Type type_t;
typedef type_t* type_ptr;
typedef std::pair<bool,type_ptr> type_pair_t;
typedef std::map<std::string,type_pair_t,details::ilesscompare> type_map_t;
typedef typename type_map_t::iterator tm_itr_t;
typedef typename type_map_t::const_iterator tm_const_itr_t;
enum { lut_size = 256 };
type_map_t map;
std::size_t size;
type_store()
: size(0)
{}
struct deleter
{
#define exprtk_define_process(Type) \
static inline void process(std::pair<bool,Type*>& n) \
{ \
delete n.second; \
} \
exprtk_define_process(variable_node_t )
exprtk_define_process(vector_t )
#ifndef exprtk_disable_string_capabilities
exprtk_define_process(stringvar_node_t)
#endif
#undef exprtk_define_process
template <typename DeleteType>
static inline void process(std::pair<bool,DeleteType*>&)
{}
};
inline bool symbol_exists(const std::string& symbol_name) const
{
if (symbol_name.empty())
return false;
else if (map.end() != map.find(symbol_name))
return true;
else
return false;
}
template <typename PtrType>
inline std::string entity_name(const PtrType& ptr) const
{
if (map.empty())
return std::string();
tm_const_itr_t itr = map.begin();
while (map.end() != itr)
{
if (itr->second.second == ptr)
{
return itr->first;
}
else
++itr;
}
return std::string();
}
inline bool is_constant(const std::string& symbol_name) const
{
if (symbol_name.empty())
return false;
else
{
const tm_const_itr_t itr = map.find(symbol_name);
if (map.end() == itr)
return false;
else
return (*itr).second.first;
}
}
template <typename Tie, typename RType>
inline bool add_impl(const std::string& symbol_name, RType t, const bool is_const)
{
if (symbol_name.size() > 1)
{
for (std::size_t i = 0; i < details::reserved_symbols_size; ++i)
{
if (details::imatch(symbol_name, details::reserved_symbols[i]))
{
return false;
}
}
}
const tm_itr_t itr = map.find(symbol_name);
if (map.end() == itr)
{
map[symbol_name] = Tie::make(t,is_const);
++size;
}
return true;
}
struct tie_array
{
static inline std::pair<bool,vector_t*> make(std::pair<T*,std::size_t> v, const bool is_const = false)
{
return std::make_pair(is_const, new vector_t(v.first, v.second));
}
};
struct tie_stdvec
{
template <typename Allocator>
static inline std::pair<bool,vector_t*> make(std::vector<T,Allocator>& v, const bool is_const = false)
{
return std::make_pair(is_const, new vector_t(v));
}
};
struct tie_vecview
{
static inline std::pair<bool,vector_t*> make(exprtk::vector_view<T>& v, const bool is_const = false)
{
return std::make_pair(is_const, new vector_t(v));
}
};
struct tie_stddeq
{
template <typename Allocator>
static inline std::pair<bool,vector_t*> make(std::deque<T,Allocator>& v, const bool is_const = false)
{
return std::make_pair(is_const, new vector_t(v));
}
};
template <std::size_t v_size>
inline bool add(const std::string& symbol_name, T (&v)[v_size], const bool is_const = false)
{
return add_impl<tie_array,std::pair<T*,std::size_t> >
(symbol_name, std::make_pair(v,v_size), is_const);
}
inline bool add(const std::string& symbol_name, T* v, const std::size_t v_size, const bool is_const = false)
{
return add_impl<tie_array,std::pair<T*,std::size_t> >
(symbol_name, std::make_pair(v,v_size), is_const);
}
template <typename Allocator>
inline bool add(const std::string& symbol_name, std::vector<T,Allocator>& v, const bool is_const = false)
{
return add_impl<tie_stdvec,std::vector<T,Allocator>&>
(symbol_name, v, is_const);
}
inline bool add(const std::string& symbol_name, exprtk::vector_view<T>& v, const bool is_const = false)
{
return add_impl<tie_vecview,exprtk::vector_view<T>&>
(symbol_name, v, is_const);
}
template <typename Allocator>
inline bool add(const std::string& symbol_name, std::deque<T,Allocator>& v, const bool is_const = false)
{
return add_impl<tie_stddeq,std::deque<T,Allocator>&>
(symbol_name, v, is_const);
}
inline bool add(const std::string& symbol_name, RawType& t_, const bool is_const = false)
{
struct tie
{
static inline std::pair<bool,variable_node_t*> make(T& t, const bool is_constant = false)
{
return std::make_pair(is_constant, new variable_node_t(t));
}
#ifndef exprtk_disable_string_capabilities
static inline std::pair<bool,stringvar_node_t*> make(std::string& t, const bool is_constant = false)
{
return std::make_pair(is_constant, new stringvar_node_t(t));
}
#endif
static inline std::pair<bool,function_t*> make(function_t& t, const bool is_constant = false)
{
return std::make_pair(is_constant,&t);
}
static inline std::pair<bool,vararg_function_t*> make(vararg_function_t& t, const bool is_constant = false)
{
return std::make_pair(is_constant,&t);
}
static inline std::pair<bool,generic_function_t*> make(generic_function_t& t, const bool is_constant = false)
{
return std::make_pair(is_constant,&t);
}
};
const tm_itr_t itr = map.find(symbol_name);
if (map.end() == itr)
{
map[symbol_name] = tie::make(t_,is_const);
++size;
}
return true;
}
inline type_ptr get(const std::string& symbol_name) const
{
const tm_const_itr_t itr = map.find(symbol_name);
if (map.end() == itr)
return reinterpret_cast<type_ptr>(0);
else
return itr->second.second;
}
template <typename TType, typename TRawType, typename PtrType>
struct ptr_match
{
static inline bool test(const PtrType, const void*)
{
return false;
}
};
template <typename TType, typename TRawType>
struct ptr_match<TType,TRawType,variable_node_t*>
{
static inline bool test(const variable_node_t* p, const void* ptr)
{
exprtk_debug(("ptr_match::test() - %p <--> %p\n",(void*)(&(p->ref())),ptr));
return (&(p->ref()) == ptr);
}
};
inline type_ptr get_from_varptr(const void* ptr) const
{
tm_const_itr_t itr = map.begin();
while (map.end() != itr)
{
type_ptr ret_ptr = itr->second.second;
if (ptr_match<Type,RawType,type_ptr>::test(ret_ptr,ptr))
{
return ret_ptr;
}
++itr;
}
return type_ptr(0);
}
inline bool remove(const std::string& symbol_name, const bool delete_node = true)
{
const tm_itr_t itr = map.find(symbol_name);
if (map.end() != itr)
{
if (delete_node)
{
deleter::process((*itr).second);
}
map.erase(itr);
--size;
return true;
}
else
return false;
}
inline RawType& type_ref(const std::string& symbol_name)
{
struct init_type
{
static inline double set(double) { return (0.0); }
static inline double set(long double) { return (0.0); }
static inline float set(float) { return (0.0f); }
static inline std::string set(std::string) { return std::string(""); }
};
static RawType null_type = init_type::set(RawType());
const tm_const_itr_t itr = map.find(symbol_name);
if (map.end() == itr)
return null_type;
else
return itr->second.second->ref();
}
inline void clear(const bool delete_node = true)
{
if (!map.empty())
{
if (delete_node)
{
tm_itr_t itr = map.begin();
tm_itr_t end = map.end ();
while (end != itr)
{
deleter::process((*itr).second);
++itr;
}
}
map.clear();
}
size = 0;
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_list(Sequence<std::pair<std::string,RawType>,Allocator>& list) const
{
std::size_t count = 0;
if (!map.empty())
{
tm_const_itr_t itr = map.begin();
tm_const_itr_t end = map.end ();
while (end != itr)
{
list.push_back(std::make_pair((*itr).first,itr->second.second->ref()));
++itr;
++count;
}
}
return count;
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_list(Sequence<std::string,Allocator>& vlist) const
{
std::size_t count = 0;
if (!map.empty())
{
tm_const_itr_t itr = map.begin();
tm_const_itr_t end = map.end ();
while (end != itr)
{
vlist.push_back((*itr).first);
++itr;
++count;
}
}
return count;
}
};
typedef details::expression_node<T>* expression_ptr;
typedef typename details::variable_node<T> variable_t;
typedef typename details::vector_holder<T> vector_holder_t;
typedef variable_t* variable_ptr;
#ifndef exprtk_disable_string_capabilities
typedef typename details::stringvar_node<T> stringvar_t;
typedef stringvar_t* stringvar_ptr;
#endif
typedef ifunction <T> function_t;
typedef ivararg_function <T> vararg_function_t;
typedef igeneric_function<T> generic_function_t;
typedef function_t* function_ptr;
typedef vararg_function_t* vararg_function_ptr;
typedef generic_function_t* generic_function_ptr;
static const std::size_t lut_size = 256;
// Symbol Table Holder
struct control_block
{
struct st_data
{
type_store<variable_t , T > variable_store;
type_store<function_t , function_t > function_store;
type_store<vararg_function_t , vararg_function_t > vararg_function_store;
type_store<generic_function_t, generic_function_t> generic_function_store;
type_store<generic_function_t, generic_function_t> string_function_store;
type_store<generic_function_t, generic_function_t> overload_function_store;
type_store<vector_holder_t , vector_holder_t > vector_store;
#ifndef exprtk_disable_string_capabilities
type_store<stringvar_t , std::string > stringvar_store;
#endif
st_data()
{
for (std::size_t i = 0; i < details::reserved_words_size; ++i)
{
reserved_symbol_table_.insert(details::reserved_words[i]);
}
for (std::size_t i = 0; i < details::reserved_symbols_size; ++i)
{
reserved_symbol_table_.insert(details::reserved_symbols[i]);
}
}
~st_data()
{
for (std::size_t i = 0; i < free_function_list_.size(); ++i)
{
delete free_function_list_[i];
}
}
inline bool is_reserved_symbol(const std::string& symbol) const
{
return (reserved_symbol_table_.end() != reserved_symbol_table_.find(symbol));
}
static inline st_data* create()
{
return (new st_data);
}
static inline void destroy(st_data*& sd)
{
delete sd;
sd = reinterpret_cast<st_data*>(0);
}
std::list<T> local_symbol_list_;
std::list<std::string> local_stringvar_list_;
std::set<std::string> reserved_symbol_table_;
std::vector<ifunction<T>*> free_function_list_;
};
control_block()
: ref_count(1)
, data_(st_data::create())
, mutability_(e_mutable)
{}
explicit control_block(st_data* data)
: ref_count(1)
, data_(data)
, mutability_(e_mutable)
{}
~control_block()
{
if (data_ && (0 == ref_count))
{
st_data::destroy(data_);
}
}
static inline control_block* create()
{
return (new control_block);
}
template <typename SymTab>
static inline void destroy(control_block*& cntrl_blck, SymTab* sym_tab)
{
if (cntrl_blck)
{
if (
(0 != cntrl_blck->ref_count) &&
(0 == --cntrl_blck->ref_count)
)
{
if (sym_tab)
sym_tab->clear();
delete cntrl_blck;
}
cntrl_blck = 0;
}
}
void set_mutability(const symtab_mutability_type mutability)
{
mutability_ = mutability;
}
std::size_t ref_count;
st_data* data_;
symtab_mutability_type mutability_;
};
public:
symbol_table(const symtab_mutability_type mutability = e_mutable)
: control_block_(control_block::create())
{
control_block_->set_mutability(mutability);
clear();
}
~symbol_table()
{
exprtk::details::dump_ptr("~symbol_table", this);
control_block::destroy(control_block_, this);
}
symbol_table(const symbol_table<T>& st)
{
control_block_ = st.control_block_;
control_block_->ref_count++;
}
inline symbol_table<T>& operator=(const symbol_table<T>& st)
{
if (this != &st)
{
control_block::destroy(control_block_,reinterpret_cast<symbol_table<T>*>(0));
control_block_ = st.control_block_;
control_block_->ref_count++;
}
return (*this);
}
inline bool operator==(const symbol_table<T>& st) const
{
return (this == &st) || (control_block_ == st.control_block_);
}
inline symtab_mutability_type mutability() const
{
return valid() ? control_block_->mutability_ : e_unknown;
}
inline void clear_variables(const bool delete_node = true)
{
local_data().variable_store.clear(delete_node);
}
inline void clear_functions()
{
local_data().function_store.clear();
}
inline void clear_strings()
{
#ifndef exprtk_disable_string_capabilities
local_data().stringvar_store.clear();
#endif
}
inline void clear_vectors()
{
local_data().vector_store.clear();
}
inline void clear_local_constants()
{
local_data().local_symbol_list_.clear();
}
inline void clear()
{
if (!valid()) return;
clear_variables ();
clear_functions ();
clear_strings ();
clear_vectors ();
clear_local_constants();
}
inline std::size_t variable_count() const
{
if (valid())
return local_data().variable_store.size;
else
return 0;
}
#ifndef exprtk_disable_string_capabilities
inline std::size_t stringvar_count() const
{
if (valid())
return local_data().stringvar_store.size;
else
return 0;
}
#endif
inline std::size_t function_count() const
{
if (valid())
return local_data().function_store.size;
else
return 0;
}
inline std::size_t vector_count() const
{
if (valid())
return local_data().vector_store.size;
else
return 0;
}
inline variable_ptr get_variable(const std::string& variable_name) const
{
if (!valid())
return reinterpret_cast<variable_ptr>(0);
else if (!valid_symbol(variable_name))
return reinterpret_cast<variable_ptr>(0);
else
return local_data().variable_store.get(variable_name);
}
inline variable_ptr get_variable(const T& var_ref) const
{
if (!valid())
return reinterpret_cast<variable_ptr>(0);
else
return local_data().variable_store.get_from_varptr(
reinterpret_cast<const void*>(&var_ref));
}
#ifndef exprtk_disable_string_capabilities
inline stringvar_ptr get_stringvar(const std::string& string_name) const
{
if (!valid())
return reinterpret_cast<stringvar_ptr>(0);
else if (!valid_symbol(string_name))
return reinterpret_cast<stringvar_ptr>(0);
else
return local_data().stringvar_store.get(string_name);
}
inline stringvar_base<T> get_stringvar_base(const std::string& string_name) const
{
static stringvar_base<T> null_stringvar_base("",reinterpret_cast<stringvar_ptr>(0));
if (!valid())
return null_stringvar_base;
else if (!valid_symbol(string_name))
return null_stringvar_base;
stringvar_ptr stringvar = local_data().stringvar_store.get(string_name);
if (0 == stringvar)
{
return null_stringvar_base;
}
return stringvar_base<T>(string_name,stringvar);
}
#endif
inline function_ptr get_function(const std::string& function_name) const
{
if (!valid())
return reinterpret_cast<function_ptr>(0);
else if (!valid_symbol(function_name))
return reinterpret_cast<function_ptr>(0);
else
return local_data().function_store.get(function_name);
}
inline vararg_function_ptr get_vararg_function(const std::string& vararg_function_name) const
{
if (!valid())
return reinterpret_cast<vararg_function_ptr>(0);
else if (!valid_symbol(vararg_function_name))
return reinterpret_cast<vararg_function_ptr>(0);
else
return local_data().vararg_function_store.get(vararg_function_name);
}
inline generic_function_ptr get_generic_function(const std::string& function_name) const
{
if (!valid())
return reinterpret_cast<generic_function_ptr>(0);
else if (!valid_symbol(function_name))
return reinterpret_cast<generic_function_ptr>(0);
else
return local_data().generic_function_store.get(function_name);
}
inline generic_function_ptr get_string_function(const std::string& function_name) const
{
if (!valid())
return reinterpret_cast<generic_function_ptr>(0);
else if (!valid_symbol(function_name))
return reinterpret_cast<generic_function_ptr>(0);
else
return local_data().string_function_store.get(function_name);
}
inline generic_function_ptr get_overload_function(const std::string& function_name) const
{
if (!valid())
return reinterpret_cast<generic_function_ptr>(0);
else if (!valid_symbol(function_name))
return reinterpret_cast<generic_function_ptr>(0);
else
return local_data().overload_function_store.get(function_name);
}
typedef vector_holder_t* vector_holder_ptr;
inline vector_holder_ptr get_vector(const std::string& vector_name) const
{
if (!valid())
return reinterpret_cast<vector_holder_ptr>(0);
else if (!valid_symbol(vector_name))
return reinterpret_cast<vector_holder_ptr>(0);
else
return local_data().vector_store.get(vector_name);
}
inline T& variable_ref(const std::string& symbol_name)
{
static T null_var = T(0);
if (!valid())
return null_var;
else if (!valid_symbol(symbol_name))
return null_var;
else
return local_data().variable_store.type_ref(symbol_name);
}
#ifndef exprtk_disable_string_capabilities
inline std::string& stringvar_ref(const std::string& symbol_name)
{
static std::string null_stringvar;
if (!valid())
return null_stringvar;
else if (!valid_symbol(symbol_name))
return null_stringvar;
else
return local_data().stringvar_store.type_ref(symbol_name);
}
#endif
inline bool is_constant_node(const std::string& symbol_name) const
{
if (!valid())
return false;
else if (!valid_symbol(symbol_name))
return false;
else
return local_data().variable_store.is_constant(symbol_name);
}
#ifndef exprtk_disable_string_capabilities
inline bool is_constant_string(const std::string& symbol_name) const
{
if (!valid())
return false;
else if (!valid_symbol(symbol_name))
return false;
else if (!local_data().stringvar_store.symbol_exists(symbol_name))
return false;
else
return local_data().stringvar_store.is_constant(symbol_name);
}
#endif
inline bool create_variable(const std::string& variable_name, const T& value = T(0))
{
if (!valid())
return false;
else if (!valid_symbol(variable_name))
return false;
else if (symbol_exists(variable_name))
return false;
local_data().local_symbol_list_.push_back(value);
T& t = local_data().local_symbol_list_.back();
return add_variable(variable_name,t);
}
#ifndef exprtk_disable_string_capabilities
inline bool create_stringvar(const std::string& stringvar_name, const std::string& value = std::string(""))
{
if (!valid())
return false;
else if (!valid_symbol(stringvar_name))
return false;
else if (symbol_exists(stringvar_name))
return false;
local_data().local_stringvar_list_.push_back(value);
std::string& s = local_data().local_stringvar_list_.back();
return add_stringvar(stringvar_name,s);
}
#endif
inline bool add_variable(const std::string& variable_name, T& t, const bool is_constant = false)
{
if (!valid())
return false;
else if (!valid_symbol(variable_name))
return false;
else if (symbol_exists(variable_name))
return false;
else
return local_data().variable_store.add(variable_name, t, is_constant);
}
inline bool add_constant(const std::string& constant_name, const T& value)
{
if (!valid())
return false;
else if (!valid_symbol(constant_name))
return false;
else if (symbol_exists(constant_name))
return false;
local_data().local_symbol_list_.push_back(value);
T& t = local_data().local_symbol_list_.back();
return add_variable(constant_name, t, true);
}
#ifndef exprtk_disable_string_capabilities
inline bool add_stringvar(const std::string& stringvar_name, std::string& s, const bool is_constant = false)
{
if (!valid())
return false;
else if (!valid_symbol(stringvar_name))
return false;
else if (symbol_exists(stringvar_name))
return false;
else
return local_data().stringvar_store.add(stringvar_name, s, is_constant);
}
#endif
inline bool add_function(const std::string& function_name, function_t& function)
{
if (!valid())
return false;
else if (!valid_symbol(function_name))
return false;
else if (symbol_exists(function_name))
return false;
else
return local_data().function_store.add(function_name,function);
}
inline bool add_function(const std::string& vararg_function_name, vararg_function_t& vararg_function)
{
if (!valid())
return false;
else if (!valid_symbol(vararg_function_name))
return false;
else if (symbol_exists(vararg_function_name))
return false;
else
return local_data().vararg_function_store.add(vararg_function_name,vararg_function);
}
inline bool add_function(const std::string& function_name, generic_function_t& function)
{
if (!valid())
return false;
else if (!valid_symbol(function_name))
return false;
else if (symbol_exists(function_name))
return false;
else
{
switch (function.rtrn_type)
{
case generic_function_t::e_rtrn_scalar :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|")) ?
local_data().generic_function_store.add(function_name,function) : false;
case generic_function_t::e_rtrn_string :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|")) ?
local_data().string_function_store.add(function_name,function) : false;
case generic_function_t::e_rtrn_overload :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|:")) ?
local_data().overload_function_store.add(function_name,function) : false;
}
}
return false;
}
#define exprtk_define_freefunction(NN) \
inline bool add_function(const std::string& function_name, ff##NN##_functor function) \
{ \
if (!valid()) \
{ return false; } \
if (!valid_symbol(function_name)) \
{ return false; } \
if (symbol_exists(function_name)) \
{ return false; } \
\
exprtk::ifunction<T>* ifunc = new freefunc##NN(function); \
\
local_data().free_function_list_.push_back(ifunc); \
\
return add_function(function_name,(*local_data().free_function_list_.back())); \
} \
exprtk_define_freefunction(00) exprtk_define_freefunction(01)
exprtk_define_freefunction(02) exprtk_define_freefunction(03)
exprtk_define_freefunction(04) exprtk_define_freefunction(05)
exprtk_define_freefunction(06) exprtk_define_freefunction(07)
exprtk_define_freefunction(08) exprtk_define_freefunction(09)
exprtk_define_freefunction(10) exprtk_define_freefunction(11)
exprtk_define_freefunction(12) exprtk_define_freefunction(13)
exprtk_define_freefunction(14) exprtk_define_freefunction(15)
#undef exprtk_define_freefunction
inline bool add_reserved_function(const std::string& function_name, function_t& function)
{
if (!valid())
return false;
else if (!valid_symbol(function_name,false))
return false;
else if (symbol_exists(function_name,false))
return false;
else
return local_data().function_store.add(function_name,function);
}
inline bool add_reserved_function(const std::string& vararg_function_name, vararg_function_t& vararg_function)
{
if (!valid())
return false;
else if (!valid_symbol(vararg_function_name,false))
return false;
else if (symbol_exists(vararg_function_name,false))
return false;
else
return local_data().vararg_function_store.add(vararg_function_name,vararg_function);
}
inline bool add_reserved_function(const std::string& function_name, generic_function_t& function)
{
if (!valid())
return false;
else if (!valid_symbol(function_name,false))
return false;
else if (symbol_exists(function_name,false))
return false;
else
{
switch (function.rtrn_type)
{
case generic_function_t::e_rtrn_scalar :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|")) ?
local_data().generic_function_store.add(function_name,function) : false;
case generic_function_t::e_rtrn_string :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|")) ?
local_data().string_function_store.add(function_name,function) : false;
case generic_function_t::e_rtrn_overload :
return (std::string::npos == function.parameter_sequence.find_first_not_of("STVZ*?|:")) ?
local_data().overload_function_store.add(function_name,function) : false;
}
}
return false;
}
template <std::size_t N>
inline bool add_vector(const std::string& vector_name, T (&v)[N])
{
if (!valid())
return false;
else if (!valid_symbol(vector_name))
return false;
else if (symbol_exists(vector_name))
return false;
else
return local_data().vector_store.add(vector_name,v);
}
inline bool add_vector(const std::string& vector_name, T* v, const std::size_t& v_size)
{
if (!valid())
return false;
else if (!valid_symbol(vector_name))
return false;
else if (symbol_exists(vector_name))
return false;
else if (0 == v_size)
return false;
else
return local_data().vector_store.add(vector_name, v, v_size);
}
template <typename Allocator>
inline bool add_vector(const std::string& vector_name, std::vector<T,Allocator>& v)
{
if (!valid())
return false;
else if (!valid_symbol(vector_name))
return false;
else if (symbol_exists(vector_name))
return false;
else if (0 == v.size())
return false;
else
return local_data().vector_store.add(vector_name,v);
}
inline bool add_vector(const std::string& vector_name, exprtk::vector_view<T>& v)
{
if (!valid())
return false;
else if (!valid_symbol(vector_name))
return false;
else if (symbol_exists(vector_name))
return false;
else if (0 == v.size())
return false;
else
return local_data().vector_store.add(vector_name,v);
}
inline bool remove_variable(const std::string& variable_name, const bool delete_node = true)
{
if (!valid())
return false;
else
return local_data().variable_store.remove(variable_name, delete_node);
}
#ifndef exprtk_disable_string_capabilities
inline bool remove_stringvar(const std::string& string_name)
{
if (!valid())
return false;
else
return local_data().stringvar_store.remove(string_name);
}
#endif
inline bool remove_function(const std::string& function_name)
{
if (!valid())
return false;
else
return local_data().function_store.remove(function_name);
}
inline bool remove_vararg_function(const std::string& vararg_function_name)
{
if (!valid())
return false;
else
return local_data().vararg_function_store.remove(vararg_function_name);
}
inline bool remove_vector(const std::string& vector_name)
{
if (!valid())
return false;
else
return local_data().vector_store.remove(vector_name);
}
inline bool add_constants()
{
return add_pi () &&
add_epsilon () &&
add_infinity() ;
}
inline bool add_pi()
{
const typename details::numeric::details::number_type<T>::type num_type;
static const T local_pi = details::numeric::details::const_pi_impl<T>(num_type);
return add_constant("pi",local_pi);
}
inline bool add_epsilon()
{
static const T local_epsilon = details::numeric::details::epsilon_type<T>::value();
return add_constant("epsilon",local_epsilon);
}
inline bool add_infinity()
{
static const T local_infinity = std::numeric_limits<T>::infinity();
return add_constant("inf",local_infinity);
}
template <typename Package>
inline bool add_package(Package& package)
{
return package.register_package(*this);
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_variable_list(Sequence<std::pair<std::string,T>,Allocator>& vlist) const
{
if (!valid())
return 0;
else
return local_data().variable_store.get_list(vlist);
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_variable_list(Sequence<std::string,Allocator>& vlist) const
{
if (!valid())
return 0;
else
return local_data().variable_store.get_list(vlist);
}
#ifndef exprtk_disable_string_capabilities
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_stringvar_list(Sequence<std::pair<std::string,std::string>,Allocator>& svlist) const
{
if (!valid())
return 0;
else
return local_data().stringvar_store.get_list(svlist);
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_stringvar_list(Sequence<std::string,Allocator>& svlist) const
{
if (!valid())
return 0;
else
return local_data().stringvar_store.get_list(svlist);
}
#endif
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t get_vector_list(Sequence<std::string,Allocator>& vlist) const
{
if (!valid())
return 0;
else
return local_data().vector_store.get_list(vlist);
}
inline bool symbol_exists(const std::string& symbol_name, const bool check_reserved_symb = true) const
{
/*
Function will return true if symbol_name exists as either a
reserved symbol, variable, stringvar, vector or function name
in any of the type stores.
*/
if (!valid())
return false;
else if (local_data().variable_store.symbol_exists(symbol_name))
return true;
#ifndef exprtk_disable_string_capabilities
else if (local_data().stringvar_store.symbol_exists(symbol_name))
return true;
#endif
else if (local_data().vector_store.symbol_exists(symbol_name))
return true;
else if (local_data().function_store.symbol_exists(symbol_name))
return true;
else if (check_reserved_symb && local_data().is_reserved_symbol(symbol_name))
return true;
else
return false;
}
inline bool is_variable(const std::string& variable_name) const
{
if (!valid())
return false;
else
return local_data().variable_store.symbol_exists(variable_name);
}
#ifndef exprtk_disable_string_capabilities
inline bool is_stringvar(const std::string& stringvar_name) const
{
if (!valid())
return false;
else
return local_data().stringvar_store.symbol_exists(stringvar_name);
}
inline bool is_conststr_stringvar(const std::string& symbol_name) const
{
if (!valid())
return false;
else if (!valid_symbol(symbol_name))
return false;
else if (!local_data().stringvar_store.symbol_exists(symbol_name))
return false;
return (
local_data().stringvar_store.symbol_exists(symbol_name) ||
local_data().stringvar_store.is_constant (symbol_name)
);
}
#endif
inline bool is_function(const std::string& function_name) const
{
if (!valid())
return false;
else
return local_data().function_store.symbol_exists(function_name);
}
inline bool is_vararg_function(const std::string& vararg_function_name) const
{
if (!valid())
return false;
else
return local_data().vararg_function_store.symbol_exists(vararg_function_name);
}
inline bool is_vector(const std::string& vector_name) const
{
if (!valid())
return false;
else
return local_data().vector_store.symbol_exists(vector_name);
}
inline std::string get_variable_name(const expression_ptr& ptr) const
{
return local_data().variable_store.entity_name(ptr);
}
inline std::string get_vector_name(const vector_holder_ptr& ptr) const
{
return local_data().vector_store.entity_name(ptr);
}
#ifndef exprtk_disable_string_capabilities
inline std::string get_stringvar_name(const expression_ptr& ptr) const
{
return local_data().stringvar_store.entity_name(ptr);
}
inline std::string get_conststr_stringvar_name(const expression_ptr& ptr) const
{
return local_data().stringvar_store.entity_name(ptr);
}
#endif
inline bool valid() const
{
// Symbol table sanity check.
return control_block_ && control_block_->data_;
}
inline void load_from(const symbol_table<T>& st)
{
{
std::vector<std::string> name_list;
st.local_data().function_store.get_list(name_list);
if (!name_list.empty())
{
for (std::size_t i = 0; i < name_list.size(); ++i)
{
exprtk::ifunction<T>& ifunc = *st.get_function(name_list[i]);
add_function(name_list[i],ifunc);
}
}
}
{
std::vector<std::string> name_list;
st.local_data().vararg_function_store.get_list(name_list);
if (!name_list.empty())
{
for (std::size_t i = 0; i < name_list.size(); ++i)
{
exprtk::ivararg_function<T>& ivafunc = *st.get_vararg_function(name_list[i]);
add_function(name_list[i],ivafunc);
}
}
}
{
std::vector<std::string> name_list;
st.local_data().generic_function_store.get_list(name_list);
if (!name_list.empty())
{
for (std::size_t i = 0; i < name_list.size(); ++i)
{
exprtk::igeneric_function<T>& ifunc = *st.get_generic_function(name_list[i]);
add_function(name_list[i],ifunc);
}
}
}
{
std::vector<std::string> name_list;
st.local_data().string_function_store.get_list(name_list);
if (!name_list.empty())
{
for (std::size_t i = 0; i < name_list.size(); ++i)
{
exprtk::igeneric_function<T>& ifunc = *st.get_string_function(name_list[i]);
add_function(name_list[i],ifunc);
}
}
}
{
std::vector<std::string> name_list;
st.local_data().overload_function_store.get_list(name_list);
if (!name_list.empty())
{
for (std::size_t i = 0; i < name_list.size(); ++i)
{
exprtk::igeneric_function<T>& ifunc = *st.get_overload_function(name_list[i]);
add_function(name_list[i],ifunc);
}
}
}
}
private:
inline bool valid_symbol(const std::string& symbol, const bool check_reserved_symb = true) const
{
if (symbol.empty())
return false;
else if (!details::is_letter(symbol[0]))
return false;
else if (symbol.size() > 1)
{
for (std::size_t i = 1; i < symbol.size(); ++i)
{
if (
!details::is_letter_or_digit(symbol[i]) &&
('_' != symbol[i])
)
{
if ((i < (symbol.size() - 1)) && ('.' == symbol[i]))
continue;
else
return false;
}
}
}
return (check_reserved_symb) ? (!local_data().is_reserved_symbol(symbol)) : true;
}
inline bool valid_function(const std::string& symbol) const
{
if (symbol.empty())
return false;
else if (!details::is_letter(symbol[0]))
return false;
else if (symbol.size() > 1)
{
for (std::size_t i = 1; i < symbol.size(); ++i)
{
if (
!details::is_letter_or_digit(symbol[i]) &&
('_' != symbol[i])
)
{
if ((i < (symbol.size() - 1)) && ('.' == symbol[i]))
continue;
else
return false;
}
}
}
return true;
}
typedef typename control_block::st_data local_data_t;
inline local_data_t& local_data()
{
return *(control_block_->data_);
}
inline const local_data_t& local_data() const
{
return *(control_block_->data_);
}
control_block* control_block_;
friend class parser<T>;
}; // class symbol_table
template <typename T>
class function_compositor;
template <typename T>
class expression
{
private:
typedef details::expression_node<T>* expression_ptr;
typedef details::vector_holder<T>* vector_holder_ptr;
typedef std::vector<symbol_table<T> > symtab_list_t;
struct control_block
{
enum data_type
{
e_unknown ,
e_expr ,
e_vecholder,
e_data ,
e_vecdata ,
e_string
};
struct data_pack
{
data_pack()
: pointer(0)
, type(e_unknown)
, size(0)
{}
data_pack(void* ptr, const data_type dt, const std::size_t sz = 0)
: pointer(ptr)
, type(dt)
, size(sz)
{}
void* pointer;
data_type type;
std::size_t size;
};
typedef std::vector<data_pack> local_data_list_t;
typedef results_context<T> results_context_t;
typedef control_block* cntrl_blck_ptr_t;
control_block()
: ref_count(0)
, expr (0)
, results (0)
, retinv_null(false)
, return_invoked(&retinv_null)
{}
explicit control_block(expression_ptr e)
: ref_count(1)
, expr (e)
, results (0)
, retinv_null(false)
, return_invoked(&retinv_null)
{}
~control_block()
{
if (expr && details::branch_deletable(expr))
{
destroy_node(expr);
}
if (!local_data_list.empty())
{
for (std::size_t i = 0; i < local_data_list.size(); ++i)
{
switch (local_data_list[i].type)
{
case e_expr : delete reinterpret_cast<expression_ptr>(local_data_list[i].pointer);
break;
case e_vecholder : delete reinterpret_cast<vector_holder_ptr>(local_data_list[i].pointer);
break;
case e_data : delete reinterpret_cast<T*>(local_data_list[i].pointer);
break;
case e_vecdata : delete [] reinterpret_cast<T*>(local_data_list[i].pointer);
break;
case e_string : delete reinterpret_cast<std::string*>(local_data_list[i].pointer);
break;
default : break;
}
}
}
if (results)
{
delete results;
}
}
static inline cntrl_blck_ptr_t create(expression_ptr e)
{
return new control_block(e);
}
static inline void destroy(cntrl_blck_ptr_t& cntrl_blck)
{
if (cntrl_blck)
{
if (
(0 != cntrl_blck->ref_count) &&
(0 == --cntrl_blck->ref_count)
)
{
delete cntrl_blck;
}
cntrl_blck = 0;
}
}
std::size_t ref_count;
expression_ptr expr;
local_data_list_t local_data_list;
results_context_t* results;
bool retinv_null;
bool* return_invoked;
friend class function_compositor<T>;
};
public:
expression()
: control_block_(0)
{
set_expression(new details::null_node<T>());
}
expression(const expression<T>& e)
: control_block_ (e.control_block_ )
, symbol_table_list_(e.symbol_table_list_)
{
control_block_->ref_count++;
}
explicit expression(const symbol_table<T>& symbol_table)
: control_block_(0)
{
set_expression(new details::null_node<T>());
symbol_table_list_.push_back(symbol_table);
}
inline expression<T>& operator=(const expression<T>& e)
{
if (this != &e)
{
if (control_block_)
{
if (
(0 != control_block_->ref_count) &&
(0 == --control_block_->ref_count)
)
{
delete control_block_;
}
control_block_ = 0;
}
control_block_ = e.control_block_;
control_block_->ref_count++;
symbol_table_list_ = e.symbol_table_list_;
}
return *this;
}
inline bool operator==(const expression<T>& e) const
{
return (this == &e);
}
inline bool operator!() const
{
return (
(0 == control_block_ ) ||
(0 == control_block_->expr)
);
}
inline expression<T>& release()
{
exprtk::details::dump_ptr("expression::release", this);
control_block::destroy(control_block_);
return (*this);
}
~expression()
{
control_block::destroy(control_block_);
}
inline T value() const
{
assert(control_block_ );
assert(control_block_->expr);
return control_block_->expr->value();
}
inline T operator() () const
{
return value();
}
inline operator T() const
{
return value();
}
inline operator bool() const
{
return details::is_true(value());
}
inline void register_symbol_table(symbol_table<T>& st)
{
for (std::size_t i = 0; i < symbol_table_list_.size(); ++i)
{
if (&st == &symbol_table_list_[i])
{
return;
}
}
symbol_table_list_.push_back(st);
}
inline const symbol_table<T>& get_symbol_table(const std::size_t& index = 0) const
{
return symbol_table_list_[index];
}
inline symbol_table<T>& get_symbol_table(const std::size_t& index = 0)
{
return symbol_table_list_[index];
}
typedef results_context<T> results_context_t;
inline const results_context_t& results() const
{
if (control_block_->results)
return (*control_block_->results);
else
{
static const results_context_t null_results;
return null_results;
}
}
inline bool return_invoked() const
{
return (*control_block_->return_invoked);
}
private:
inline symtab_list_t get_symbol_table_list() const
{
return symbol_table_list_;
}
inline void set_expression(const expression_ptr expr)
{
if (expr)
{
if (control_block_)
{
if (0 == --control_block_->ref_count)
{
delete control_block_;
}
}
control_block_ = control_block::create(expr);
}
}
inline void register_local_var(expression_ptr expr)
{
if (expr)
{
if (control_block_)
{
control_block_->
local_data_list.push_back(
typename expression<T>::control_block::
data_pack(reinterpret_cast<void*>(expr),
control_block::e_expr));
}
}
}
inline void register_local_var(vector_holder_ptr vec_holder)
{
if (vec_holder)
{
if (control_block_)
{
control_block_->
local_data_list.push_back(
typename expression<T>::control_block::
data_pack(reinterpret_cast<void*>(vec_holder),
control_block::e_vecholder));
}
}
}
inline void register_local_data(void* data, const std::size_t& size = 0, const std::size_t data_mode = 0)
{
if (data)
{
if (control_block_)
{
typename control_block::data_type dt = control_block::e_data;
switch (data_mode)
{
case 0 : dt = control_block::e_data; break;
case 1 : dt = control_block::e_vecdata; break;
case 2 : dt = control_block::e_string; break;
}
control_block_->
local_data_list.push_back(
typename expression<T>::control_block::
data_pack(reinterpret_cast<void*>(data), dt, size));
}
}
}
inline const typename control_block::local_data_list_t& local_data_list()
{
if (control_block_)
{
return control_block_->local_data_list;
}
else
{
static typename control_block::local_data_list_t null_local_data_list;
return null_local_data_list;
}
}
inline void register_return_results(results_context_t* rc)
{
if (control_block_ && rc)
{
control_block_->results = rc;
}
}
inline void set_retinvk(bool* retinvk_ptr)
{
if (control_block_)
{
control_block_->return_invoked = retinvk_ptr;
}
}
control_block* control_block_;
symtab_list_t symbol_table_list_;
friend class parser<T>;
friend class expression_helper<T>;
friend class function_compositor<T>;
}; // class expression
template <typename T>
class expression_helper
{
public:
static inline bool is_constant(const expression<T>& expr)
{
return details::is_constant_node(expr.control_block_->expr);
}
static inline bool is_variable(const expression<T>& expr)
{
return details::is_variable_node(expr.control_block_->expr);
}
static inline bool is_unary(const expression<T>& expr)
{
return details::is_unary_node(expr.control_block_->expr);
}
static inline bool is_binary(const expression<T>& expr)
{
return details::is_binary_node(expr.control_block_->expr);
}
static inline bool is_function(const expression<T>& expr)
{
return details::is_function(expr.control_block_->expr);
}
static inline bool is_null(const expression<T>& expr)
{
return details::is_null_node(expr.control_block_->expr);
}
};
template <typename T>
inline bool is_valid(const expression<T>& expr)
{
return !expression_helper<T>::is_null(expr);
}
namespace parser_error
{
enum error_mode
{
e_unknown = 0,
e_syntax = 1,
e_token = 2,
e_numeric = 4,
e_symtab = 5,
e_lexer = 6,
e_helper = 7,
e_parser = 8
};
struct type
{
type()
: mode(parser_error::e_unknown)
, line_no (0)
, column_no(0)
{}
lexer::token token;
error_mode mode;
std::string diagnostic;
std::string src_location;
std::string error_line;
std::size_t line_no;
std::size_t column_no;
};
inline type make_error(const error_mode mode,
const std::string& diagnostic = "",
const std::string& src_location = "")
{
type t;
t.mode = mode;
t.token.type = lexer::token::e_error;
t.diagnostic = diagnostic;
t.src_location = src_location;
exprtk_debug(("%s\n",diagnostic .c_str()));
return t;
}
inline type make_error(const error_mode mode,
const lexer::token& tk,
const std::string& diagnostic = "",
const std::string& src_location = "")
{
type t;
t.mode = mode;
t.token = tk;
t.diagnostic = diagnostic;
t.src_location = src_location;
exprtk_debug(("%s\n",diagnostic .c_str()));
return t;
}
inline std::string to_str(error_mode mode)
{
switch (mode)
{
case e_unknown : return std::string("Unknown Error");
case e_syntax : return std::string("Syntax Error" );
case e_token : return std::string("Token Error" );
case e_numeric : return std::string("Numeric Error");
case e_symtab : return std::string("Symbol Error" );
case e_lexer : return std::string("Lexer Error" );
case e_helper : return std::string("Helper Error" );
case e_parser : return std::string("Parser Error" );
default : return std::string("Unknown Error");
}
}
inline bool update_error(type& error, const std::string& expression)
{
if (
expression.empty() ||
(error.token.position > expression.size()) ||
(std::numeric_limits<std::size_t>::max() == error.token.position)
)
{
return false;
}
std::size_t error_line_start = 0;
for (std::size_t i = error.token.position; i > 0; --i)
{
const details::char_t c = expression[i];
if (('\n' == c) || ('\r' == c))
{
error_line_start = i + 1;
break;
}
}
std::size_t next_nl_position = std::min(expression.size(),
expression.find_first_of('\n',error.token.position + 1));
error.column_no = error.token.position - error_line_start;
error.error_line = expression.substr(error_line_start,
next_nl_position - error_line_start);
error.line_no = 0;
for (std::size_t i = 0; i < next_nl_position; ++i)
{
if ('\n' == expression[i])
++error.line_no;
}
return true;
}
inline void dump_error(const type& error)
{
printf("Position: %02d Type: [%s] Msg: %s\n",
static_cast<int>(error.token.position),
exprtk::parser_error::to_str(error.mode).c_str(),
error.diagnostic.c_str());
}
}
namespace details
{
template <typename Parser>
inline void disable_type_checking(Parser& p)
{
p.state_.type_check_enabled = false;
}
}
template <typename T>
class parser : public lexer::parser_helper
{
private:
enum precedence_level
{
e_level00, e_level01, e_level02, e_level03, e_level04,
e_level05, e_level06, e_level07, e_level08, e_level09,
e_level10, e_level11, e_level12, e_level13, e_level14
};
typedef const T& cref_t;
typedef const T const_t;
typedef ifunction<T> F;
typedef ivararg_function<T> VAF;
typedef igeneric_function<T> GF;
typedef ifunction<T> ifunction_t;
typedef ivararg_function<T> ivararg_function_t;
typedef igeneric_function<T> igeneric_function_t;
typedef details::expression_node<T> expression_node_t;
typedef details::literal_node<T> literal_node_t;
typedef details::unary_node<T> unary_node_t;
typedef details::binary_node<T> binary_node_t;
typedef details::trinary_node<T> trinary_node_t;
typedef details::quaternary_node<T> quaternary_node_t;
typedef details::conditional_node<T> conditional_node_t;
typedef details::cons_conditional_node<T> cons_conditional_node_t;
typedef details::while_loop_node<T> while_loop_node_t;
typedef details::repeat_until_loop_node<T> repeat_until_loop_node_t;
typedef details::for_loop_node<T> for_loop_node_t;
typedef details::while_loop_rtc_node<T> while_loop_rtc_node_t;
typedef details::repeat_until_loop_rtc_node<T> repeat_until_loop_rtc_node_t;
typedef details::for_loop_rtc_node<T> for_loop_rtc_node_t;
#ifndef exprtk_disable_break_continue
typedef details::while_loop_bc_node<T> while_loop_bc_node_t;
typedef details::repeat_until_loop_bc_node<T> repeat_until_loop_bc_node_t;
typedef details::for_loop_bc_node<T> for_loop_bc_node_t;
typedef details::while_loop_bc_rtc_node<T> while_loop_bc_rtc_node_t;
typedef details::repeat_until_loop_bc_rtc_node<T> repeat_until_loop_bc_rtc_node_t;
typedef details::for_loop_bc_rtc_node<T> for_loop_bc_rtc_node_t;
#endif
typedef details::switch_node<T> switch_node_t;
typedef details::variable_node<T> variable_node_t;
typedef details::vector_elem_node<T> vector_elem_node_t;
typedef details::rebasevector_elem_node<T> rebasevector_elem_node_t;
typedef details::rebasevector_celem_node<T> rebasevector_celem_node_t;
typedef details::vector_node<T> vector_node_t;
typedef details::range_pack<T> range_t;
#ifndef exprtk_disable_string_capabilities
typedef details::stringvar_node<T> stringvar_node_t;
typedef details::string_literal_node<T> string_literal_node_t;
typedef details::string_range_node<T> string_range_node_t;
typedef details::const_string_range_node<T> const_string_range_node_t;
typedef details::generic_string_range_node<T> generic_string_range_node_t;
typedef details::string_concat_node<T> string_concat_node_t;
typedef details::assignment_string_node<T> assignment_string_node_t;
typedef details::assignment_string_range_node<T> assignment_string_range_node_t;
typedef details::conditional_string_node<T> conditional_string_node_t;
typedef details::cons_conditional_str_node<T> cons_conditional_str_node_t;
#endif
typedef details::assignment_node<T> assignment_node_t;
typedef details::assignment_vec_elem_node<T> assignment_vec_elem_node_t;
typedef details::assignment_rebasevec_elem_node<T> assignment_rebasevec_elem_node_t;
typedef details::assignment_rebasevec_celem_node<T> assignment_rebasevec_celem_node_t;
typedef details::assignment_vec_node<T> assignment_vec_node_t;
typedef details::assignment_vecvec_node<T> assignment_vecvec_node_t;
typedef details::conditional_vector_node<T> conditional_vector_node_t;
typedef details::scand_node<T> scand_node_t;
typedef details::scor_node<T> scor_node_t;
typedef lexer::token token_t;
typedef expression_node_t* expression_node_ptr;
typedef expression<T> expression_t;
typedef symbol_table<T> symbol_table_t;
typedef typename expression<T>::symtab_list_t symbol_table_list_t;
typedef details::vector_holder<T>* vector_holder_ptr;
typedef typename details::functor_t<T> functor_t;
typedef typename functor_t::qfunc_t quaternary_functor_t;
typedef typename functor_t::tfunc_t trinary_functor_t;
typedef typename functor_t::bfunc_t binary_functor_t;
typedef typename functor_t::ufunc_t unary_functor_t;
typedef details::operator_type operator_t;
typedef std::map<operator_t, unary_functor_t > unary_op_map_t;
typedef std::map<operator_t, binary_functor_t > binary_op_map_t;
typedef std::map<operator_t, trinary_functor_t> trinary_op_map_t;
typedef std::map<std::string,std::pair<trinary_functor_t ,operator_t> > sf3_map_t;
typedef std::map<std::string,std::pair<quaternary_functor_t,operator_t> > sf4_map_t;
typedef std::map<binary_functor_t,operator_t> inv_binary_op_map_t;
typedef std::multimap<std::string,details::base_operation_t,details::ilesscompare> base_ops_map_t;
typedef std::set<std::string,details::ilesscompare> disabled_func_set_t;
typedef details::T0oT1_define<T, cref_t , cref_t > vov_t;
typedef details::T0oT1_define<T, const_t, cref_t > cov_t;
typedef details::T0oT1_define<T, cref_t , const_t> voc_t;
typedef details::T0oT1oT2_define<T, cref_t , cref_t , cref_t > vovov_t;
typedef details::T0oT1oT2_define<T, cref_t , cref_t , const_t> vovoc_t;
typedef details::T0oT1oT2_define<T, cref_t , const_t, cref_t > vocov_t;
typedef details::T0oT1oT2_define<T, const_t, cref_t , cref_t > covov_t;
typedef details::T0oT1oT2_define<T, const_t, cref_t , const_t> covoc_t;
typedef details::T0oT1oT2_define<T, const_t, const_t, cref_t > cocov_t;
typedef details::T0oT1oT2_define<T, cref_t , const_t, const_t> vococ_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , cref_t , cref_t , cref_t > vovovov_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , cref_t , cref_t , const_t> vovovoc_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , cref_t , const_t, cref_t > vovocov_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , const_t, cref_t , cref_t > vocovov_t;
typedef details::T0oT1oT2oT3_define<T, const_t, cref_t , cref_t , cref_t > covovov_t;
typedef details::T0oT1oT2oT3_define<T, const_t, cref_t , const_t, cref_t > covocov_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , const_t, cref_t , const_t> vocovoc_t;
typedef details::T0oT1oT2oT3_define<T, const_t, cref_t , cref_t , const_t> covovoc_t;
typedef details::T0oT1oT2oT3_define<T, cref_t , const_t, const_t, cref_t > vococov_t;
typedef results_context<T> results_context_t;
typedef parser_helper prsrhlpr_t;
struct scope_element
{
enum element_type
{
e_none ,
e_variable,
e_vector ,
e_vecelem ,
e_string
};
typedef details::vector_holder<T> vector_holder_t;
typedef variable_node_t* variable_node_ptr;
typedef vector_holder_t* vector_holder_ptr;
typedef expression_node_t* expression_node_ptr;
#ifndef exprtk_disable_string_capabilities
typedef stringvar_node_t* stringvar_node_ptr;
#endif
scope_element()
: name("???")
, size (std::numeric_limits<std::size_t>::max())
, index(std::numeric_limits<std::size_t>::max())
, depth(std::numeric_limits<std::size_t>::max())
, ref_count(0)
, ip_index (0)
, type (e_none)
, active(false)
, data (0)
, var_node (0)
, vec_node (0)
#ifndef exprtk_disable_string_capabilities
, str_node(0)
#endif
{}
bool operator < (const scope_element& se) const
{
if (ip_index < se.ip_index)
return true;
else if (ip_index > se.ip_index)
return false;
else if (depth < se.depth)
return true;
else if (depth > se.depth)
return false;
else if (index < se.index)
return true;
else if (index > se.index)
return false;
else
return (name < se.name);
}
void clear()
{
name = "???";
size = std::numeric_limits<std::size_t>::max();
index = std::numeric_limits<std::size_t>::max();
depth = std::numeric_limits<std::size_t>::max();
type = e_none;
active = false;
ref_count = 0;
ip_index = 0;
data = 0;
var_node = 0;
vec_node = 0;
#ifndef exprtk_disable_string_capabilities
str_node = 0;
#endif
}
std::string name;
std::size_t size;
std::size_t index;
std::size_t depth;
std::size_t ref_count;
std::size_t ip_index;
element_type type;
bool active;
void* data;
expression_node_ptr var_node;
vector_holder_ptr vec_node;
#ifndef exprtk_disable_string_capabilities
stringvar_node_ptr str_node;
#endif
};
class scope_element_manager
{
public:
typedef expression_node_t* expression_node_ptr;
typedef variable_node_t* variable_node_ptr;
typedef parser<T> parser_t;
explicit scope_element_manager(parser<T>& p)
: parser_(p)
, input_param_cnt_(0)
{}
inline std::size_t size() const
{
return element_.size();
}
inline bool empty() const
{
return element_.empty();
}
inline scope_element& get_element(const std::size_t& index)
{
if (index < element_.size())
return element_[index];
else
return null_element_;
}
inline scope_element& get_element(const std::string& var_name,
const std::size_t index = std::numeric_limits<std::size_t>::max())
{
const std::size_t current_depth = parser_.state_.scope_depth;
for (std::size_t i = 0; i < element_.size(); ++i)
{
scope_element& se = element_[i];
if (se.depth > current_depth)
continue;
else if (
details::imatch(se.name, var_name) &&
(se.index == index)
)
return se;
}
return null_element_;
}
inline scope_element& get_active_element(const std::string& var_name,
const std::size_t index = std::numeric_limits<std::size_t>::max())
{
const std::size_t current_depth = parser_.state_.scope_depth;
for (std::size_t i = 0; i < element_.size(); ++i)
{
scope_element& se = element_[i];
if (se.depth > current_depth)
continue;
else if (
details::imatch(se.name, var_name) &&
(se.index == index) &&
(se.active)
)
return se;
}
return null_element_;
}
inline bool add_element(const scope_element& se)
{
for (std::size_t i = 0; i < element_.size(); ++i)
{
scope_element& cse = element_[i];
if (
details::imatch(cse.name, se.name) &&
(cse.depth <= se.depth) &&
(cse.index == se.index) &&
(cse.size == se.size ) &&
(cse.type == se.type ) &&
(cse.active)
)
return false;
}
element_.push_back(se);
std::sort(element_.begin(),element_.end());
return true;
}
inline void deactivate(const std::size_t& scope_depth)
{
exprtk_debug(("deactivate() - Scope depth: %d\n",
static_cast<int>(parser_.state_.scope_depth)));
for (std::size_t i = 0; i < element_.size(); ++i)
{
scope_element& se = element_[i];
if (se.active && (se.depth >= scope_depth))
{
exprtk_debug(("deactivate() - element[%02d] '%s'\n",
static_cast<int>(i),
se.name.c_str()));
se.active = false;
}
}
}
inline void free_element(scope_element& se)
{
exprtk_debug(("free_element() - se[%s]\n", se.name.c_str()));
switch (se.type)
{
case scope_element::e_variable : delete reinterpret_cast<T*>(se.data);
delete se.var_node;
break;
case scope_element::e_vector : delete[] reinterpret_cast<T*>(se.data);
delete se.vec_node;
break;
case scope_element::e_vecelem : delete se.var_node;
break;
#ifndef exprtk_disable_string_capabilities
case scope_element::e_string : delete reinterpret_cast<std::string*>(se.data);
delete se.str_node;
break;
#endif
default : return;
}
se.clear();
}
inline void cleanup()
{
for (std::size_t i = 0; i < element_.size(); ++i)
{
free_element(element_[i]);
}
element_.clear();
input_param_cnt_ = 0;
}
inline std::size_t next_ip_index()
{
return ++input_param_cnt_;
}
inline expression_node_ptr get_variable(const T& v)
{
for (std::size_t i = 0; i < element_.size(); ++i)
{
scope_element& se = element_[i];
if (
se.active &&
se.var_node &&
details::is_variable_node(se.var_node)
)
{
variable_node_ptr vn = reinterpret_cast<variable_node_ptr>(se.var_node);
if (&(vn->ref()) == (&v))
{
return se.var_node;
}
}
}
return expression_node_ptr(0);
}
private:
scope_element_manager(const scope_element_manager&) exprtk_delete;
scope_element_manager& operator=(const scope_element_manager&) exprtk_delete;
parser_t& parser_;
std::vector<scope_element> element_;
scope_element null_element_;
std::size_t input_param_cnt_;
};
class scope_handler
{
public:
typedef parser<T> parser_t;
explicit scope_handler(parser<T>& p)
: parser_(p)
{
parser_.state_.scope_depth++;
#ifdef exprtk_enable_debugging
const std::string depth(2 * parser_.state_.scope_depth,'-');
exprtk_debug(("%s> Scope Depth: %02d\n",
depth.c_str(),
static_cast<int>(parser_.state_.scope_depth)));
#endif
}
~scope_handler()
{
parser_.sem_.deactivate(parser_.state_.scope_depth);
parser_.state_.scope_depth--;
#ifdef exprtk_enable_debugging
const std::string depth(2 * parser_.state_.scope_depth,'-');
exprtk_debug(("<%s Scope Depth: %02d\n",
depth.c_str(),
static_cast<int>(parser_.state_.scope_depth)));
#endif
}
private:
scope_handler(const scope_handler&) exprtk_delete;
scope_handler& operator=(const scope_handler&) exprtk_delete;
parser_t& parser_;
};
template <typename T_>
struct halfopen_range_policy
{
static inline bool is_within(const T_& v, const T_& begin, const T_& end)
{
assert(begin <= end);
return (begin <= v) && (v < end);
}
static inline bool is_less(const T_& v, const T_& begin)
{
return (v < begin);
}
static inline bool is_greater(const T_& v, const T_& end)
{
return (end <= v);
}
static inline bool end_inclusive()
{
return false;
}
};
template <typename T_>
struct closed_range_policy
{
static inline bool is_within(const T_& v, const T_& begin, const T_& end)
{
assert(begin <= end);
return (begin <= v) && (v <= end);
}
static inline bool is_less(const T_& v, const T_& begin)
{
return (v < begin);
}
static inline bool is_greater(const T_& v, const T_& end)
{
return (end < v);
}
static inline bool end_inclusive()
{
return true;
}
};
template <typename IntervalPointType,
typename RangePolicy = halfopen_range_policy<IntervalPointType> >
class interval_container_t
{
public:
typedef IntervalPointType interval_point_t;
typedef std::pair<interval_point_t, interval_point_t> interval_t;
typedef std::map<interval_point_t, interval_t> interval_map_t;
typedef typename interval_map_t::const_iterator interval_map_citr_t;
std::size_t size() const
{
return interval_map_.size();
}
void reset()
{
interval_map_.clear();
}
bool in_interval(const interval_point_t point, interval_t& interval) const
{
interval_map_citr_t itr = RangePolicy::end_inclusive() ?
interval_map_.lower_bound(point):
interval_map_.upper_bound(point);
for (; itr != interval_map_.end(); ++itr)
{
const interval_point_t& begin = itr->second.first;
const interval_point_t& end = itr->second.second;
if (RangePolicy::is_within(point, begin, end))
{
interval = interval_t(begin,end);
return true;
}
else if (RangePolicy::is_greater(point, end))
{
break;
}
}
return false;
}
bool in_interval(const interval_point_t point) const
{
interval_t interval;
return in_interval(point,interval);
}
bool add_interval(const interval_point_t begin, const interval_point_t end)
{
if ((end <= begin) || in_interval(begin) || in_interval(end))
{
return false;
}
interval_map_[end] = std::make_pair(begin, end);
return true;
}
bool add_interval(const interval_t interval)
{
return add_interval(interval.first, interval.second);
}
private:
interval_map_t interval_map_;
};
class stack_limit_handler
{
public:
typedef parser<T> parser_t;
explicit stack_limit_handler(parser<T>& p)
: parser_(p)
, limit_exceeded_(false)
{
if (++parser_.state_.stack_depth > parser_.settings_.max_stack_depth_)
{
limit_exceeded_ = true;
parser_.set_error(
make_error(parser_error::e_parser,
"ERR000 - Current stack depth " + details::to_str(parser_.state_.stack_depth) +
" exceeds maximum allowed stack depth of " + details::to_str(parser_.settings_.max_stack_depth_),
exprtk_error_location));
}
}
~stack_limit_handler()
{
parser_.state_.stack_depth--;
}
bool operator!()
{
return limit_exceeded_;
}
private:
stack_limit_handler(const stack_limit_handler&) exprtk_delete;
stack_limit_handler& operator=(const stack_limit_handler&) exprtk_delete;
parser_t& parser_;
bool limit_exceeded_;
};
struct symtab_store
{
symbol_table_list_t symtab_list_;
typedef typename symbol_table_t::local_data_t local_data_t;
typedef typename symbol_table_t::variable_ptr variable_ptr;
typedef typename symbol_table_t::function_ptr function_ptr;
#ifndef exprtk_disable_string_capabilities
typedef typename symbol_table_t::stringvar_ptr stringvar_ptr;
#endif
typedef typename symbol_table_t::vector_holder_ptr vector_holder_ptr;
typedef typename symbol_table_t::vararg_function_ptr vararg_function_ptr;
typedef typename symbol_table_t::generic_function_ptr generic_function_ptr;
struct variable_context
{
variable_context()
: symbol_table(0)
, variable(0)
{}
const symbol_table_t* symbol_table;
variable_ptr variable;
};
struct vector_context
{
vector_context()
: symbol_table(0)
, vector_holder(0)
{}
const symbol_table_t* symbol_table;
vector_holder_ptr vector_holder;
};
#ifndef exprtk_disable_string_capabilities
struct string_context
{
string_context()
: symbol_table(0)
, str_var(0)
{}
const symbol_table_t* symbol_table;
stringvar_ptr str_var;
};
#endif
inline bool empty() const
{
return symtab_list_.empty();
}
inline void clear()
{
symtab_list_.clear();
}
inline bool valid() const
{
if (!empty())
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (symtab_list_[i].valid())
return true;
}
}
return false;
}
inline bool valid_symbol(const std::string& symbol) const
{
if (!symtab_list_.empty())
return symtab_list_[0].valid_symbol(symbol);
else
return false;
}
inline bool valid_function_name(const std::string& symbol) const
{
if (!symtab_list_.empty())
return symtab_list_[0].valid_function(symbol);
else
return false;
}
inline variable_context get_variable_context(const std::string& variable_name) const
{
variable_context result;
if (!valid_symbol(variable_name))
return result;
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
{
continue;
}
result.variable = local_data(i)
.variable_store.get(variable_name);
if (result.variable)
{
result.symbol_table = &symtab_list_[i];
break;
}
}
return result;
}
inline variable_ptr get_variable(const std::string& variable_name) const
{
if (!valid_symbol(variable_name))
return reinterpret_cast<variable_ptr>(0);
variable_ptr result = reinterpret_cast<variable_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i)
.variable_store.get(variable_name);
if (result) break;
}
return result;
}
inline variable_ptr get_variable(const T& var_ref) const
{
variable_ptr result = reinterpret_cast<variable_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i).variable_store
.get_from_varptr(reinterpret_cast<const void*>(&var_ref));
if (result) break;
}
return result;
}
#ifndef exprtk_disable_string_capabilities
inline string_context get_string_context(const std::string& string_name) const
{
string_context result;
if (!valid_symbol(string_name))
return result;
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
{
continue;
}
result.str_var = local_data(i).stringvar_store.get(string_name);
if (result.str_var)
{
result.symbol_table = &symtab_list_[i];
break;
}
}
return result;
}
inline stringvar_ptr get_stringvar(const std::string& string_name) const
{
if (!valid_symbol(string_name))
return reinterpret_cast<stringvar_ptr>(0);
stringvar_ptr result = reinterpret_cast<stringvar_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i)
.stringvar_store.get(string_name);
if (result) break;
}
return result;
}
#endif
inline function_ptr get_function(const std::string& function_name) const
{
if (!valid_function_name(function_name))
return reinterpret_cast<function_ptr>(0);
function_ptr result = reinterpret_cast<function_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i)
.function_store.get(function_name);
if (result) break;
}
return result;
}
inline vararg_function_ptr get_vararg_function(const std::string& vararg_function_name) const
{
if (!valid_function_name(vararg_function_name))
return reinterpret_cast<vararg_function_ptr>(0);
vararg_function_ptr result = reinterpret_cast<vararg_function_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i)
.vararg_function_store.get(vararg_function_name);
if (result) break;
}
return result;
}
inline generic_function_ptr get_generic_function(const std::string& function_name) const
{
if (!valid_function_name(function_name))
return reinterpret_cast<generic_function_ptr>(0);
generic_function_ptr result = reinterpret_cast<generic_function_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result = local_data(i)
.generic_function_store.get(function_name);
if (result) break;
}
return result;
}
inline generic_function_ptr get_string_function(const std::string& function_name) const
{
if (!valid_function_name(function_name))
return reinterpret_cast<generic_function_ptr>(0);
generic_function_ptr result = reinterpret_cast<generic_function_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result =
local_data(i).string_function_store.get(function_name);
if (result) break;
}
return result;
}
inline generic_function_ptr get_overload_function(const std::string& function_name) const
{
if (!valid_function_name(function_name))
return reinterpret_cast<generic_function_ptr>(0);
generic_function_ptr result = reinterpret_cast<generic_function_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result =
local_data(i).overload_function_store.get(function_name);
if (result) break;
}
return result;
}
inline vector_context get_vector_context(const std::string& vector_name) const
{
vector_context result;
if (!valid_symbol(vector_name))
return result;
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
{
continue;
}
result.vector_holder = local_data(i).vector_store.get(vector_name);
if (result.vector_holder)
{
result.symbol_table = &symtab_list_[i];
break;
}
}
return result;
}
inline vector_holder_ptr get_vector(const std::string& vector_name) const
{
if (!valid_symbol(vector_name))
return reinterpret_cast<vector_holder_ptr>(0);
vector_holder_ptr result = reinterpret_cast<vector_holder_ptr>(0);
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else
result =
local_data(i).vector_store.get(vector_name);
if (result) break;
}
return result;
}
inline bool is_constant_node(const std::string& symbol_name) const
{
if (!valid_symbol(symbol_name))
return false;
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (local_data(i).variable_store.is_constant(symbol_name))
return true;
}
return false;
}
#ifndef exprtk_disable_string_capabilities
inline bool is_constant_string(const std::string& symbol_name) const
{
if (!valid_symbol(symbol_name))
return false;
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (!local_data(i).stringvar_store.symbol_exists(symbol_name))
continue;
else if (local_data(i).stringvar_store.is_constant(symbol_name))
return true;
}
return false;
}
#endif
inline bool symbol_exists(const std::string& symbol) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (symtab_list_[i].symbol_exists(symbol))
return true;
}
return false;
}
inline bool is_variable(const std::string& variable_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
symtab_list_[i].local_data().variable_store
.symbol_exists(variable_name)
)
return true;
}
return false;
}
#ifndef exprtk_disable_string_capabilities
inline bool is_stringvar(const std::string& stringvar_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
symtab_list_[i].local_data().stringvar_store
.symbol_exists(stringvar_name)
)
return true;
}
return false;
}
inline bool is_conststr_stringvar(const std::string& symbol_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
symtab_list_[i].local_data().stringvar_store
.symbol_exists(symbol_name)
)
{
return (
local_data(i).stringvar_store.symbol_exists(symbol_name) ||
local_data(i).stringvar_store.is_constant (symbol_name)
);
}
}
return false;
}
#endif
inline bool is_function(const std::string& function_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
local_data(i).vararg_function_store
.symbol_exists(function_name)
)
return true;
}
return false;
}
inline bool is_vararg_function(const std::string& vararg_function_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
local_data(i).vararg_function_store
.symbol_exists(vararg_function_name)
)
return true;
}
return false;
}
inline bool is_vector(const std::string& vector_name) const
{
for (std::size_t i = 0; i < symtab_list_.size(); ++i)
{
if (!symtab_list_[i].valid())
continue;
else if (
local_data(i).vector_store
.symbol_exists(vector_name)
)
return true;
}
return false;
}
inline std::string get_variable_name(const expression_node_ptr& ptr) const
{
return local_data().variable_store.entity_name(ptr);
}
inline std::string get_vector_name(const vector_holder_ptr& ptr) const
{
return local_data().vector_store.entity_name(ptr);
}
#ifndef exprtk_disable_string_capabilities
inline std::string get_stringvar_name(const expression_node_ptr& ptr) const
{
return local_data().stringvar_store.entity_name(ptr);
}
inline std::string get_conststr_stringvar_name(const expression_node_ptr& ptr) const
{
return local_data().stringvar_store.entity_name(ptr);
}
#endif
inline local_data_t& local_data(const std::size_t& index = 0)
{
return symtab_list_[index].local_data();
}
inline const local_data_t& local_data(const std::size_t& index = 0) const
{
return symtab_list_[index].local_data();
}
inline symbol_table_t& get_symbol_table(const std::size_t& index = 0)
{
return symtab_list_[index];
}
};
struct parser_state
{
parser_state()
: type_check_enabled(true)
{
reset();
}
void reset()
{
parsing_return_stmt = false;
parsing_break_stmt = false;
return_stmt_present = false;
side_effect_present = false;
scope_depth = 0;
stack_depth = 0;
parsing_loop_stmt_count = 0;
}
#ifndef exprtk_enable_debugging
void activate_side_effect(const std::string&)
#else
void activate_side_effect(const std::string& source)
#endif
{
if (!side_effect_present)
{
side_effect_present = true;
exprtk_debug(("activate_side_effect() - caller: %s\n",source.c_str()));
}
}
bool parsing_return_stmt;
bool parsing_break_stmt;
bool return_stmt_present;
bool side_effect_present;
bool type_check_enabled;
std::size_t scope_depth;
std::size_t stack_depth;
std::size_t parsing_loop_stmt_count;
};
public:
struct unknown_symbol_resolver
{
enum usr_symbol_type
{
e_usr_unknown_type = 0,
e_usr_variable_type = 1,
e_usr_constant_type = 2
};
enum usr_mode
{
e_usrmode_default = 0,
e_usrmode_extended = 1
};
usr_mode mode;
unknown_symbol_resolver(const usr_mode m = e_usrmode_default)
: mode(m)
{}
virtual ~unknown_symbol_resolver() {}
virtual bool process(const std::string& /*unknown_symbol*/,
usr_symbol_type& st,
T& default_value,
std::string& error_message)
{
if (e_usrmode_default != mode)
return false;
st = e_usr_variable_type;
default_value = T(0);
error_message.clear();
return true;
}
virtual bool process(const std::string& /* unknown_symbol */,
symbol_table_t& /* symbol_table */,
std::string& /* error_message */)
{
return false;
}
};
enum collect_type
{
e_ct_none = 0,
e_ct_variables = 1,
e_ct_functions = 2,
e_ct_assignments = 4
};
enum symbol_type
{
e_st_unknown = 0,
e_st_variable = 1,
e_st_vector = 2,
e_st_vecelem = 3,
e_st_string = 4,
e_st_function = 5,
e_st_local_variable = 6,
e_st_local_vector = 7,
e_st_local_string = 8
};
class dependent_entity_collector
{
public:
typedef std::pair<std::string,symbol_type> symbol_t;
typedef std::vector<symbol_t> symbol_list_t;
dependent_entity_collector(const std::size_t options = e_ct_none)
: options_(options)
, collect_variables_ ((options_ & e_ct_variables ) == e_ct_variables )
, collect_functions_ ((options_ & e_ct_functions ) == e_ct_functions )
, collect_assignments_((options_ & e_ct_assignments) == e_ct_assignments)
, return_present_ (false)
, final_stmt_return_(false)
{}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t symbols(Sequence<symbol_t,Allocator>& symbols_list)
{
if (!collect_variables_ && !collect_functions_)
return 0;
else if (symbol_name_list_.empty())
return 0;
for (std::size_t i = 0; i < symbol_name_list_.size(); ++i)
{
details::case_normalise(symbol_name_list_[i].first);
}
std::sort(symbol_name_list_.begin(),symbol_name_list_.end());
std::unique_copy(symbol_name_list_.begin(),
symbol_name_list_.end (),
std::back_inserter(symbols_list));
return symbols_list.size();
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline std::size_t assignment_symbols(Sequence<symbol_t,Allocator>& assignment_list)
{
if (!collect_assignments_)
return 0;
else if (assignment_name_list_.empty())
return 0;
for (std::size_t i = 0; i < assignment_name_list_.size(); ++i)
{
details::case_normalise(assignment_name_list_[i].first);
}
std::sort(assignment_name_list_.begin(),assignment_name_list_.end());
std::unique_copy(assignment_name_list_.begin(),
assignment_name_list_.end (),
std::back_inserter(assignment_list));
return assignment_list.size();
}
void clear()
{
symbol_name_list_ .clear();
assignment_name_list_.clear();
retparam_list_ .clear();
return_present_ = false;
final_stmt_return_ = false;
}
bool& collect_variables()
{
return collect_variables_;
}
bool& collect_functions()
{
return collect_functions_;
}
bool& collect_assignments()
{
return collect_assignments_;
}
bool return_present() const
{
return return_present_;
}
bool final_stmt_return() const
{
return final_stmt_return_;
}
typedef std::vector<std::string> retparam_list_t;
retparam_list_t return_param_type_list() const
{
return retparam_list_;
}
private:
inline void add_symbol(const std::string& symbol, const symbol_type st)
{
switch (st)
{
case e_st_variable :
case e_st_vector :
case e_st_string :
case e_st_local_variable :
case e_st_local_vector :
case e_st_local_string : if (collect_variables_)
symbol_name_list_
.push_back(std::make_pair(symbol, st));
break;
case e_st_function : if (collect_functions_)
symbol_name_list_
.push_back(std::make_pair(symbol, st));
break;
default : return;
}
}
inline void add_assignment(const std::string& symbol, const symbol_type st)
{
switch (st)
{
case e_st_variable :
case e_st_vector :
case e_st_string : if (collect_assignments_)
assignment_name_list_
.push_back(std::make_pair(symbol, st));
break;
default : return;
}
}
std::size_t options_;
bool collect_variables_;
bool collect_functions_;
bool collect_assignments_;
bool return_present_;
bool final_stmt_return_;
symbol_list_t symbol_name_list_;
symbol_list_t assignment_name_list_;
retparam_list_t retparam_list_;
friend class parser<T>;
};
class settings_store
{
private:
typedef std::set<std::string,details::ilesscompare> disabled_entity_set_t;
typedef disabled_entity_set_t::iterator des_itr_t;
public:
enum settings_compilation_options
{
e_unknown = 0,
e_replacer = 1,
e_joiner = 2,
e_numeric_check = 4,
e_bracket_check = 8,
e_sequence_check = 16,
e_commutative_check = 32,
e_strength_reduction = 64,
e_disable_vardef = 128,
e_collect_vars = 256,
e_collect_funcs = 512,
e_collect_assings = 1024,
e_disable_usr_on_rsrvd = 2048,
e_disable_zero_return = 4096
};
enum settings_base_funcs
{
e_bf_unknown = 0,
e_bf_abs , e_bf_acos , e_bf_acosh , e_bf_asin ,
e_bf_asinh , e_bf_atan , e_bf_atan2 , e_bf_atanh ,
e_bf_avg , e_bf_ceil , e_bf_clamp , e_bf_cos ,
e_bf_cosh , e_bf_cot , e_bf_csc , e_bf_equal ,
e_bf_erf , e_bf_erfc , e_bf_exp , e_bf_expm1 ,
e_bf_floor , e_bf_frac , e_bf_hypot , e_bf_iclamp ,
e_bf_like , e_bf_log , e_bf_log10 , e_bf_log1p ,
e_bf_log2 , e_bf_logn , e_bf_mand , e_bf_max ,
e_bf_min , e_bf_mod , e_bf_mor , e_bf_mul ,
e_bf_ncdf , e_bf_pow , e_bf_root , e_bf_round ,
e_bf_roundn , e_bf_sec , e_bf_sgn , e_bf_sin ,
e_bf_sinc , e_bf_sinh , e_bf_sqrt , e_bf_sum ,
e_bf_swap , e_bf_tan , e_bf_tanh , e_bf_trunc ,
e_bf_not_equal , e_bf_inrange , e_bf_deg2grad , e_bf_deg2rad ,
e_bf_rad2deg , e_bf_grad2deg
};
enum settings_control_structs
{
e_ctrl_unknown = 0,
e_ctrl_ifelse,
e_ctrl_switch,
e_ctrl_for_loop,
e_ctrl_while_loop,
e_ctrl_repeat_loop,
e_ctrl_return
};
enum settings_logic_opr
{
e_logic_unknown = 0,
e_logic_and, e_logic_nand , e_logic_nor ,
e_logic_not, e_logic_or , e_logic_xnor,
e_logic_xor, e_logic_scand, e_logic_scor
};
enum settings_arithmetic_opr
{
e_arith_unknown = 0,
e_arith_add, e_arith_sub, e_arith_mul,
e_arith_div, e_arith_mod, e_arith_pow
};
enum settings_assignment_opr
{
e_assign_unknown = 0,
e_assign_assign, e_assign_addass, e_assign_subass,
e_assign_mulass, e_assign_divass, e_assign_modass
};
enum settings_inequality_opr
{
e_ineq_unknown = 0,
e_ineq_lt , e_ineq_lte, e_ineq_eq ,
e_ineq_equal, e_ineq_ne , e_ineq_nequal,
e_ineq_gte , e_ineq_gt
};
static const std::size_t compile_all_opts =
e_replacer +
e_joiner +
e_numeric_check +
e_bracket_check +
e_sequence_check +
e_commutative_check +
e_strength_reduction;
settings_store(const std::size_t compile_options = compile_all_opts)
: max_stack_depth_(400)
, max_node_depth_(10000)
{
load_compile_options(compile_options);
}
settings_store& enable_all_base_functions()
{
disabled_func_set_.clear();
return (*this);
}
settings_store& enable_all_control_structures()
{
disabled_ctrl_set_.clear();
return (*this);
}
settings_store& enable_all_logic_ops()
{
disabled_logic_set_.clear();
return (*this);
}
settings_store& enable_all_arithmetic_ops()
{
disabled_arithmetic_set_.clear();
return (*this);
}
settings_store& enable_all_assignment_ops()
{
disabled_assignment_set_.clear();
return (*this);
}
settings_store& enable_all_inequality_ops()
{
disabled_inequality_set_.clear();
return (*this);
}
settings_store& enable_local_vardef()
{
disable_vardef_ = false;
return (*this);
}
settings_store& disable_all_base_functions()
{
std::copy(details::base_function_list,
details::base_function_list + details::base_function_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_func_set_, disabled_func_set_.begin()));
return (*this);
}
settings_store& disable_all_control_structures()
{
std::copy(details::cntrl_struct_list,
details::cntrl_struct_list + details::cntrl_struct_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_ctrl_set_, disabled_ctrl_set_.begin()));
return (*this);
}
settings_store& disable_all_logic_ops()
{
std::copy(details::logic_ops_list,
details::logic_ops_list + details::logic_ops_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_logic_set_, disabled_logic_set_.begin()));
return (*this);
}
settings_store& disable_all_arithmetic_ops()
{
std::copy(details::arithmetic_ops_list,
details::arithmetic_ops_list + details::arithmetic_ops_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_arithmetic_set_, disabled_arithmetic_set_.begin()));
return (*this);
}
settings_store& disable_all_assignment_ops()
{
std::copy(details::assignment_ops_list,
details::assignment_ops_list + details::assignment_ops_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_assignment_set_, disabled_assignment_set_.begin()));
return (*this);
}
settings_store& disable_all_inequality_ops()
{
std::copy(details::inequality_ops_list,
details::inequality_ops_list + details::inequality_ops_list_size,
std::insert_iterator<disabled_entity_set_t>
(disabled_inequality_set_, disabled_inequality_set_.begin()));
return (*this);
}
settings_store& disable_local_vardef()
{
disable_vardef_ = true;
return (*this);
}
bool replacer_enabled () const { return enable_replacer_; }
bool commutative_check_enabled () const { return enable_commutative_check_; }
bool joiner_enabled () const { return enable_joiner_; }
bool numeric_check_enabled () const { return enable_numeric_check_; }
bool bracket_check_enabled () const { return enable_bracket_check_; }
bool sequence_check_enabled () const { return enable_sequence_check_; }
bool strength_reduction_enabled () const { return enable_strength_reduction_; }
bool collect_variables_enabled () const { return enable_collect_vars_; }
bool collect_functions_enabled () const { return enable_collect_funcs_; }
bool collect_assignments_enabled() const { return enable_collect_assings_; }
bool vardef_disabled () const { return disable_vardef_; }
bool rsrvd_sym_usr_disabled () const { return disable_rsrvd_sym_usr_; }
bool zero_return_disabled () const { return disable_zero_return_; }
bool function_enabled(const std::string& function_name) const
{
if (disabled_func_set_.empty())
return true;
else
return (disabled_func_set_.end() == disabled_func_set_.find(function_name));
}
bool control_struct_enabled(const std::string& control_struct) const
{
if (disabled_ctrl_set_.empty())
return true;
else
return (disabled_ctrl_set_.end() == disabled_ctrl_set_.find(control_struct));
}
bool logic_enabled(const std::string& logic_operation) const
{
if (disabled_logic_set_.empty())
return true;
else
return (disabled_logic_set_.end() == disabled_logic_set_.find(logic_operation));
}
bool arithmetic_enabled(const details::operator_type& arithmetic_operation) const
{
if (disabled_logic_set_.empty())
return true;
else
return disabled_arithmetic_set_.end() == disabled_arithmetic_set_
.find(arith_opr_to_string(arithmetic_operation));
}
bool assignment_enabled(const details::operator_type& assignment) const
{
if (disabled_assignment_set_.empty())
return true;
else
return disabled_assignment_set_.end() == disabled_assignment_set_
.find(assign_opr_to_string(assignment));
}
bool inequality_enabled(const details::operator_type& inequality) const
{
if (disabled_inequality_set_.empty())
return true;
else
return disabled_inequality_set_.end() == disabled_inequality_set_
.find(inequality_opr_to_string(inequality));
}
bool function_disabled(const std::string& function_name) const
{
if (disabled_func_set_.empty())
return false;
else
return (disabled_func_set_.end() != disabled_func_set_.find(function_name));
}
bool control_struct_disabled(const std::string& control_struct) const
{
if (disabled_ctrl_set_.empty())
return false;
else
return (disabled_ctrl_set_.end() != disabled_ctrl_set_.find(control_struct));
}
bool logic_disabled(const std::string& logic_operation) const
{
if (disabled_logic_set_.empty())
return false;
else
return (disabled_logic_set_.end() != disabled_logic_set_.find(logic_operation));
}
bool assignment_disabled(const details::operator_type assignment_operation) const
{
if (disabled_assignment_set_.empty())
return false;
else
return disabled_assignment_set_.end() != disabled_assignment_set_
.find(assign_opr_to_string(assignment_operation));
}
bool logic_disabled(const details::operator_type logic_operation) const
{
if (disabled_logic_set_.empty())
return false;
else
return disabled_logic_set_.end() != disabled_logic_set_
.find(logic_opr_to_string(logic_operation));
}
bool arithmetic_disabled(const details::operator_type arithmetic_operation) const
{
if (disabled_arithmetic_set_.empty())
return false;
else
return disabled_arithmetic_set_.end() != disabled_arithmetic_set_
.find(arith_opr_to_string(arithmetic_operation));
}
bool inequality_disabled(const details::operator_type& inequality) const
{
if (disabled_inequality_set_.empty())
return false;
else
return disabled_inequality_set_.end() != disabled_inequality_set_
.find(inequality_opr_to_string(inequality));
}
settings_store& disable_base_function(settings_base_funcs bf)
{
if (
(e_bf_unknown != bf) &&
(static_cast<std::size_t>(bf) < (details::base_function_list_size + 1))
)
{
disabled_func_set_.insert(details::base_function_list[bf - 1]);
}
return (*this);
}
settings_store& disable_control_structure(settings_control_structs ctrl_struct)
{
if (
(e_ctrl_unknown != ctrl_struct) &&
(static_cast<std::size_t>(ctrl_struct) < (details::cntrl_struct_list_size + 1))
)
{
disabled_ctrl_set_.insert(details::cntrl_struct_list[ctrl_struct - 1]);
}
return (*this);
}
settings_store& disable_logic_operation(settings_logic_opr logic)
{
if (
(e_logic_unknown != logic) &&
(static_cast<std::size_t>(logic) < (details::logic_ops_list_size + 1))
)
{
disabled_logic_set_.insert(details::logic_ops_list[logic - 1]);
}
return (*this);
}
settings_store& disable_arithmetic_operation(settings_arithmetic_opr arithmetic)
{
if (
(e_arith_unknown != arithmetic) &&
(static_cast<std::size_t>(arithmetic) < (details::arithmetic_ops_list_size + 1))
)
{
disabled_arithmetic_set_.insert(details::arithmetic_ops_list[arithmetic - 1]);
}
return (*this);
}
settings_store& disable_assignment_operation(settings_assignment_opr assignment)
{
if (
(e_assign_unknown != assignment) &&
(static_cast<std::size_t>(assignment) < (details::assignment_ops_list_size + 1))
)
{
disabled_assignment_set_.insert(details::assignment_ops_list[assignment - 1]);
}
return (*this);
}
settings_store& disable_inequality_operation(settings_inequality_opr inequality)
{
if (
(e_ineq_unknown != inequality) &&
(static_cast<std::size_t>(inequality) < (details::inequality_ops_list_size + 1))
)
{
disabled_inequality_set_.insert(details::inequality_ops_list[inequality - 1]);
}
return (*this);
}
settings_store& enable_base_function(settings_base_funcs bf)
{
if (
(e_bf_unknown != bf) &&
(static_cast<std::size_t>(bf) < (details::base_function_list_size + 1))
)
{
const des_itr_t itr = disabled_func_set_.find(details::base_function_list[bf - 1]);
if (disabled_func_set_.end() != itr)
{
disabled_func_set_.erase(itr);
}
}
return (*this);
}
settings_store& enable_control_structure(settings_control_structs ctrl_struct)
{
if (
(e_ctrl_unknown != ctrl_struct) &&
(static_cast<std::size_t>(ctrl_struct) < (details::cntrl_struct_list_size + 1))
)
{
const des_itr_t itr = disabled_ctrl_set_.find(details::cntrl_struct_list[ctrl_struct - 1]);
if (disabled_ctrl_set_.end() != itr)
{
disabled_ctrl_set_.erase(itr);
}
}
return (*this);
}
settings_store& enable_logic_operation(settings_logic_opr logic)
{
if (
(e_logic_unknown != logic) &&
(static_cast<std::size_t>(logic) < (details::logic_ops_list_size + 1))
)
{
const des_itr_t itr = disabled_logic_set_.find(details::logic_ops_list[logic - 1]);
if (disabled_logic_set_.end() != itr)
{
disabled_logic_set_.erase(itr);
}
}
return (*this);
}
settings_store& enable_arithmetic_operation(settings_arithmetic_opr arithmetic)
{
if (
(e_arith_unknown != arithmetic) &&
(static_cast<std::size_t>(arithmetic) < (details::arithmetic_ops_list_size + 1))
)
{
const des_itr_t itr = disabled_arithmetic_set_.find(details::arithmetic_ops_list[arithmetic - 1]);
if (disabled_arithmetic_set_.end() != itr)
{
disabled_arithmetic_set_.erase(itr);
}
}
return (*this);
}
settings_store& enable_assignment_operation(settings_assignment_opr assignment)
{
if (
(e_assign_unknown != assignment) &&
(static_cast<std::size_t>(assignment) < (details::assignment_ops_list_size + 1))
)
{
const des_itr_t itr = disabled_assignment_set_.find(details::assignment_ops_list[assignment - 1]);
if (disabled_assignment_set_.end() != itr)
{
disabled_assignment_set_.erase(itr);
}
}
return (*this);
}
settings_store& enable_inequality_operation(settings_inequality_opr inequality)
{
if (
(e_ineq_unknown != inequality) &&
(static_cast<std::size_t>(inequality) < (details::inequality_ops_list_size + 1))
)
{
const des_itr_t itr = disabled_inequality_set_.find(details::inequality_ops_list[inequality - 1]);
if (disabled_inequality_set_.end() != itr)
{
disabled_inequality_set_.erase(itr);
}
}
return (*this);
}
void set_max_stack_depth(const std::size_t max_stack_depth)
{
max_stack_depth_ = max_stack_depth;
}
void set_max_node_depth(const std::size_t max_node_depth)
{
max_node_depth_ = max_node_depth;
}
private:
void load_compile_options(const std::size_t compile_options)
{
enable_replacer_ = (compile_options & e_replacer ) == e_replacer;
enable_joiner_ = (compile_options & e_joiner ) == e_joiner;
enable_numeric_check_ = (compile_options & e_numeric_check ) == e_numeric_check;
enable_bracket_check_ = (compile_options & e_bracket_check ) == e_bracket_check;
enable_sequence_check_ = (compile_options & e_sequence_check ) == e_sequence_check;
enable_commutative_check_ = (compile_options & e_commutative_check ) == e_commutative_check;
enable_strength_reduction_ = (compile_options & e_strength_reduction ) == e_strength_reduction;
enable_collect_vars_ = (compile_options & e_collect_vars ) == e_collect_vars;
enable_collect_funcs_ = (compile_options & e_collect_funcs ) == e_collect_funcs;
enable_collect_assings_ = (compile_options & e_collect_assings ) == e_collect_assings;
disable_vardef_ = (compile_options & e_disable_vardef ) == e_disable_vardef;
disable_rsrvd_sym_usr_ = (compile_options & e_disable_usr_on_rsrvd) == e_disable_usr_on_rsrvd;
disable_zero_return_ = (compile_options & e_disable_zero_return ) == e_disable_zero_return;
}
std::string assign_opr_to_string(details::operator_type opr) const
{
switch (opr)
{
case details::e_assign : return ":=";
case details::e_addass : return "+=";
case details::e_subass : return "-=";
case details::e_mulass : return "*=";
case details::e_divass : return "/=";
case details::e_modass : return "%=";
default : return "" ;
}
}
std::string arith_opr_to_string(details::operator_type opr) const
{
switch (opr)
{
case details::e_add : return "+";
case details::e_sub : return "-";
case details::e_mul : return "*";
case details::e_div : return "/";
case details::e_mod : return "%";
default : return "" ;
}
}
std::string inequality_opr_to_string(details::operator_type opr) const
{
switch (opr)
{
case details::e_lt : return "<" ;
case details::e_lte : return "<=";
case details::e_eq : return "==";
case details::e_equal : return "=" ;
case details::e_ne : return "!=";
case details::e_nequal: return "<>";
case details::e_gte : return ">=";
case details::e_gt : return ">" ;
default : return "" ;
}
}
std::string logic_opr_to_string(details::operator_type opr) const
{
switch (opr)
{
case details::e_and : return "and" ;
case details::e_or : return "or" ;
case details::e_xor : return "xor" ;
case details::e_nand : return "nand";
case details::e_nor : return "nor" ;
case details::e_xnor : return "xnor";
case details::e_notl : return "not" ;
default : return "" ;
}
}
bool enable_replacer_;
bool enable_joiner_;
bool enable_numeric_check_;
bool enable_bracket_check_;
bool enable_sequence_check_;
bool enable_commutative_check_;
bool enable_strength_reduction_;
bool enable_collect_vars_;
bool enable_collect_funcs_;
bool enable_collect_assings_;
bool disable_vardef_;
bool disable_rsrvd_sym_usr_;
bool disable_zero_return_;
disabled_entity_set_t disabled_func_set_ ;
disabled_entity_set_t disabled_ctrl_set_ ;
disabled_entity_set_t disabled_logic_set_;
disabled_entity_set_t disabled_arithmetic_set_;
disabled_entity_set_t disabled_assignment_set_;
disabled_entity_set_t disabled_inequality_set_;
std::size_t max_stack_depth_;
std::size_t max_node_depth_;
friend class parser<T>;
};
typedef settings_store settings_t;
parser(const settings_t& settings = settings_t())
: settings_(settings)
, resolve_unknown_symbol_(false)
, results_context_(0)
, unknown_symbol_resolver_(reinterpret_cast<unknown_symbol_resolver*>(0))
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable:4355)
#endif
, sem_(*this)
#ifdef _MSC_VER
#pragma warning(pop)
#endif
, operator_joiner_2_(2)
, operator_joiner_3_(3)
, loop_runtime_check_(0)
{
init_precompilation();
load_operations_map (base_ops_map_ );
load_unary_operations_map (unary_op_map_ );
load_binary_operations_map (binary_op_map_ );
load_inv_binary_operations_map(inv_binary_op_map_);
load_sf3_map (sf3_map_ );
load_sf4_map (sf4_map_ );
expression_generator_.init_synthesize_map();
expression_generator_.set_parser(*this);
expression_generator_.set_uom(unary_op_map_);
expression_generator_.set_bom(binary_op_map_);
expression_generator_.set_ibom(inv_binary_op_map_);
expression_generator_.set_sf3m(sf3_map_);
expression_generator_.set_sf4m(sf4_map_);
expression_generator_.set_strength_reduction_state(settings_.strength_reduction_enabled());
}
~parser() {}
inline void init_precompilation()
{
dec_.collect_variables() =
settings_.collect_variables_enabled();
dec_.collect_functions() =
settings_.collect_functions_enabled();
dec_.collect_assignments() =
settings_.collect_assignments_enabled();
if (settings_.replacer_enabled())
{
symbol_replacer_.clear();
symbol_replacer_.add_replace("true" , "1", lexer::token::e_number);
symbol_replacer_.add_replace("false", "0", lexer::token::e_number);
helper_assembly_.token_modifier_list.clear();
helper_assembly_.register_modifier(&symbol_replacer_);
}
if (settings_.commutative_check_enabled())
{
for (std::size_t i = 0; i < details::reserved_words_size; ++i)
{
commutative_inserter_.ignore_symbol(details::reserved_words[i]);
}
helper_assembly_.token_inserter_list.clear();
helper_assembly_.register_inserter(&commutative_inserter_);
}
if (settings_.joiner_enabled())
{
helper_assembly_.token_joiner_list.clear();
helper_assembly_.register_joiner(&operator_joiner_2_);
helper_assembly_.register_joiner(&operator_joiner_3_);
}
if (
settings_.numeric_check_enabled () ||
settings_.bracket_check_enabled () ||
settings_.sequence_check_enabled()
)
{
helper_assembly_.token_scanner_list.clear();
if (settings_.numeric_check_enabled())
{
helper_assembly_.register_scanner(&numeric_checker_);
}
if (settings_.bracket_check_enabled())
{
helper_assembly_.register_scanner(&bracket_checker_);
}
if (settings_.sequence_check_enabled())
{
helper_assembly_.register_scanner(&sequence_validator_ );
helper_assembly_.register_scanner(&sequence_validator_3tkns_);
}
}
}
inline bool compile(const std::string& expression_string, expression<T>& expr)
{
state_ .reset();
error_list_ .clear();
brkcnt_list_ .clear();
synthesis_error_.clear();
sem_ .cleanup();
return_cleanup();
expression_generator_.set_allocator(node_allocator_);
if (expression_string.empty())
{
set_error(
make_error(parser_error::e_syntax,
"ERR001 - Empty expression!",
exprtk_error_location));
return false;
}
if (!init(expression_string))
{
process_lexer_errors();
return false;
}
if (lexer().empty())
{
set_error(
make_error(parser_error::e_syntax,
"ERR002 - Empty expression!",
exprtk_error_location));
return false;
}
if (!run_assemblies())
{
return false;
}
symtab_store_.symtab_list_ = expr.get_symbol_table_list();
dec_.clear();
lexer().begin();
next_token();
expression_node_ptr e = parse_corpus();
if ((0 != e) && (token_t::e_eof == current_token().type))
{
bool* retinvk_ptr = 0;
if (state_.return_stmt_present)
{
dec_.return_present_ = true;
e = expression_generator_
.return_envelope(e, results_context_, retinvk_ptr);
}
expr.set_expression(e);
expr.set_retinvk(retinvk_ptr);
register_local_vars(expr);
register_return_results(expr);
return !(!expr);
}
else
{
if (error_list_.empty())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR003 - Invalid expression encountered",
exprtk_error_location));
}
if ((0 != e) && branch_deletable(e))
{
destroy_node(e);
}
dec_.clear ();
sem_.cleanup ();
return_cleanup();
return false;
}
}
inline expression_t compile(const std::string& expression_string, symbol_table_t& symtab)
{
expression_t expression;
expression.register_symbol_table(symtab);
compile(expression_string,expression);
return expression;
}
void process_lexer_errors()
{
for (std::size_t i = 0; i < lexer().size(); ++i)
{
if (lexer()[i].is_error())
{
std::string diagnostic = "ERR004 - ";
switch (lexer()[i].type)
{
case lexer::token::e_error : diagnostic += "General token error";
break;
case lexer::token::e_err_symbol : diagnostic += "Symbol error";
break;
case lexer::token::e_err_number : diagnostic += "Invalid numeric token";
break;
case lexer::token::e_err_string : diagnostic += "Invalid string token";
break;
case lexer::token::e_err_sfunc : diagnostic += "Invalid special function token";
break;
default : diagnostic += "Unknown compiler error";
}
set_error(
make_error(parser_error::e_lexer,
lexer()[i],
diagnostic + ": " + lexer()[i].value,
exprtk_error_location));
}
}
}
inline bool run_assemblies()
{
if (settings_.commutative_check_enabled())
{
helper_assembly_.run_inserters(lexer());
}
if (settings_.joiner_enabled())
{
helper_assembly_.run_joiners(lexer());
}
if (settings_.replacer_enabled())
{
helper_assembly_.run_modifiers(lexer());
}
if (
settings_.numeric_check_enabled () ||
settings_.bracket_check_enabled () ||
settings_.sequence_check_enabled()
)
{
if (!helper_assembly_.run_scanners(lexer()))
{
if (helper_assembly_.error_token_scanner)
{
lexer::helper::bracket_checker* bracket_checker_ptr = 0;
lexer::helper::numeric_checker<T>* numeric_checker_ptr = 0;
lexer::helper::sequence_validator* sequence_validator_ptr = 0;
lexer::helper::sequence_validator_3tokens* sequence_validator3_ptr = 0;
if (0 != (bracket_checker_ptr = dynamic_cast<lexer::helper::bracket_checker*>(helper_assembly_.error_token_scanner)))
{
set_error(
make_error(parser_error::e_token,
bracket_checker_ptr->error_token(),
"ERR005 - Mismatched brackets: '" + bracket_checker_ptr->error_token().value + "'",
exprtk_error_location));
}
else if (0 != (numeric_checker_ptr = dynamic_cast<lexer::helper::numeric_checker<T>*>(helper_assembly_.error_token_scanner)))
{
for (std::size_t i = 0; i < numeric_checker_ptr->error_count(); ++i)
{
lexer::token error_token = lexer()[numeric_checker_ptr->error_index(i)];
set_error(
make_error(parser_error::e_token,
error_token,
"ERR006 - Invalid numeric token: '" + error_token.value + "'",
exprtk_error_location));
}
if (numeric_checker_ptr->error_count())
{
numeric_checker_ptr->clear_errors();
}
}
else if (0 != (sequence_validator_ptr = dynamic_cast<lexer::helper::sequence_validator*>(helper_assembly_.error_token_scanner)))
{
for (std::size_t i = 0; i < sequence_validator_ptr->error_count(); ++i)
{
std::pair<lexer::token,lexer::token> error_token = sequence_validator_ptr->error(i);
set_error(
make_error(parser_error::e_token,
error_token.first,
"ERR007 - Invalid token sequence: '" +
error_token.first.value + "' and '" +
error_token.second.value + "'",
exprtk_error_location));
}
if (sequence_validator_ptr->error_count())
{
sequence_validator_ptr->clear_errors();
}
}
else if (0 != (sequence_validator3_ptr = dynamic_cast<lexer::helper::sequence_validator_3tokens*>(helper_assembly_.error_token_scanner)))
{
for (std::size_t i = 0; i < sequence_validator3_ptr->error_count(); ++i)
{
std::pair<lexer::token,lexer::token> error_token = sequence_validator3_ptr->error(i);
set_error(
make_error(parser_error::e_token,
error_token.first,
"ERR008 - Invalid token sequence: '" +
error_token.first.value + "' and '" +
error_token.second.value + "'",
exprtk_error_location));
}
if (sequence_validator3_ptr->error_count())
{
sequence_validator3_ptr->clear_errors();
}
}
}
return false;
}
}
return true;
}
inline settings_store& settings()
{
return settings_;
}
inline parser_error::type get_error(const std::size_t& index) const
{
if (index < error_list_.size())
return error_list_[index];
else
throw std::invalid_argument("parser::get_error() - Invalid error index specificed");
}
inline std::string error() const
{
if (!error_list_.empty())
{
return error_list_[0].diagnostic;
}
else
return std::string("No Error");
}
inline std::size_t error_count() const
{
return error_list_.size();
}
inline dependent_entity_collector& dec()
{
return dec_;
}
inline bool replace_symbol(const std::string& old_symbol, const std::string& new_symbol)
{
if (!settings_.replacer_enabled())
return false;
else if (details::is_reserved_word(old_symbol))
return false;
else
return symbol_replacer_.add_replace(old_symbol,new_symbol,lexer::token::e_symbol);
}
inline bool remove_replace_symbol(const std::string& symbol)
{
if (!settings_.replacer_enabled())
return false;
else if (details::is_reserved_word(symbol))
return false;
else
return symbol_replacer_.remove(symbol);
}
inline void enable_unknown_symbol_resolver(unknown_symbol_resolver* usr = reinterpret_cast<unknown_symbol_resolver*>(0))
{
resolve_unknown_symbol_ = true;
if (usr)
unknown_symbol_resolver_ = usr;
else
unknown_symbol_resolver_ = &default_usr_;
}
inline void enable_unknown_symbol_resolver(unknown_symbol_resolver& usr)
{
enable_unknown_symbol_resolver(&usr);
}
inline void disable_unknown_symbol_resolver()
{
resolve_unknown_symbol_ = false;
unknown_symbol_resolver_ = &default_usr_;
}
inline void register_loop_runtime_check(loop_runtime_check& lrtchk)
{
loop_runtime_check_ = &lrtchk;
}
inline void clear_loop_runtime_check()
{
loop_runtime_check_ = loop_runtime_check_ptr(0);
}
private:
inline bool valid_base_operation(const std::string& symbol) const
{
const std::size_t length = symbol.size();
if (
(length < 3) || // Shortest base op symbol length
(length > 9) // Longest base op symbol length
)
return false;
else
return settings_.function_enabled(symbol) &&
(base_ops_map_.end() != base_ops_map_.find(symbol));
}
inline bool valid_vararg_operation(const std::string& symbol) const
{
static const std::string s_sum = "sum" ;
static const std::string s_mul = "mul" ;
static const std::string s_avg = "avg" ;
static const std::string s_min = "min" ;
static const std::string s_max = "max" ;
static const std::string s_mand = "mand";
static const std::string s_mor = "mor" ;
static const std::string s_multi = "~" ;
static const std::string s_mswitch = "[*]" ;
return
(
details::imatch(symbol,s_sum ) ||
details::imatch(symbol,s_mul ) ||
details::imatch(symbol,s_avg ) ||
details::imatch(symbol,s_min ) ||
details::imatch(symbol,s_max ) ||
details::imatch(symbol,s_mand ) ||
details::imatch(symbol,s_mor ) ||
details::imatch(symbol,s_multi ) ||
details::imatch(symbol,s_mswitch)
) &&
settings_.function_enabled(symbol);
}
bool is_invalid_logic_operation(const details::operator_type operation) const
{
return settings_.logic_disabled(operation);
}
bool is_invalid_arithmetic_operation(const details::operator_type operation) const
{
return settings_.arithmetic_disabled(operation);
}
bool is_invalid_assignment_operation(const details::operator_type operation) const
{
return settings_.assignment_disabled(operation);
}
bool is_invalid_inequality_operation(const details::operator_type operation) const
{
return settings_.inequality_disabled(operation);
}
#ifdef exprtk_enable_debugging
inline void next_token()
{
const std::string ct_str = current_token().value;
const std::size_t ct_pos = current_token().position;
parser_helper::next_token();
const std::string depth(2 * state_.scope_depth,' ');
exprtk_debug(("%s"
"prev[%s | %04d] --> curr[%s | %04d] stack_level: %3d\n",
depth.c_str(),
ct_str.c_str(),
static_cast<unsigned int>(ct_pos),
current_token().value.c_str(),
static_cast<unsigned int>(current_token().position),
static_cast<unsigned int>(state_.stack_depth)));
}
#endif
inline expression_node_ptr parse_corpus()
{
std::vector<expression_node_ptr> arg_list;
std::vector<bool> side_effect_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
lexer::token begin_token;
lexer::token end_token;
for ( ; ; )
{
state_.side_effect_present = false;
begin_token = current_token();
expression_node_ptr arg = parse_expression();
if (0 == arg)
{
if (error_list_.empty())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR009 - Invalid expression encountered",
exprtk_error_location));
}
return error_node();
}
else
{
arg_list.push_back(arg);
side_effect_list.push_back(state_.side_effect_present);
end_token = current_token();
const std::string sub_expr = construct_subexpr(begin_token, end_token);
exprtk_debug(("parse_corpus(%02d) Subexpr: %s\n",
static_cast<int>(arg_list.size() - 1),
sub_expr.c_str()));
exprtk_debug(("parse_corpus(%02d) - Side effect present: %s\n",
static_cast<int>(arg_list.size() - 1),
state_.side_effect_present ? "true" : "false"));
exprtk_debug(("-------------------------------------------------\n"));
}
if (lexer().finished())
break;
else if (token_is(token_t::e_eof,prsrhlpr_t::e_hold))
{
if (lexer().finished())
break;
else
next_token();
}
}
if (
!arg_list.empty() &&
is_return_node(arg_list.back())
)
{
dec_.final_stmt_return_ = true;
}
const expression_node_ptr result = simplify(arg_list,side_effect_list);
sdd.delete_ptr = (0 == result);
return result;
}
std::string construct_subexpr(lexer::token& begin_token, lexer::token& end_token)
{
std::string result = lexer().substr(begin_token.position,end_token.position);
for (std::size_t i = 0; i < result.size(); ++i)
{
if (details::is_whitespace(result[i])) result[i] = ' ';
}
return result;
}
static const precedence_level default_precedence = e_level00;
struct state_t
{
inline void set(const precedence_level& l,
const precedence_level& r,
const details::operator_type& o)
{
left = l;
right = r;
operation = o;
}
inline void reset()
{
left = e_level00;
right = e_level00;
operation = details::e_default;
}
precedence_level left;
precedence_level right;
details::operator_type operation;
};
inline expression_node_ptr parse_expression(precedence_level precedence = e_level00)
{
stack_limit_handler slh(*this);
if (!slh)
{
return error_node();
}
expression_node_ptr expression = parse_branch(precedence);
if (0 == expression)
{
return error_node();
}
bool break_loop = false;
state_t current_state;
for ( ; ; )
{
current_state.reset();
switch (current_token().type)
{
case token_t::e_assign : current_state.set(e_level00, e_level00, details::e_assign); break;
case token_t::e_addass : current_state.set(e_level00, e_level00, details::e_addass); break;
case token_t::e_subass : current_state.set(e_level00, e_level00, details::e_subass); break;
case token_t::e_mulass : current_state.set(e_level00, e_level00, details::e_mulass); break;
case token_t::e_divass : current_state.set(e_level00, e_level00, details::e_divass); break;
case token_t::e_modass : current_state.set(e_level00, e_level00, details::e_modass); break;
case token_t::e_swap : current_state.set(e_level00, e_level00, details::e_swap ); break;
case token_t::e_lt : current_state.set(e_level05, e_level06, details::e_lt ); break;
case token_t::e_lte : current_state.set(e_level05, e_level06, details::e_lte ); break;
case token_t::e_eq : current_state.set(e_level05, e_level06, details::e_eq ); break;
case token_t::e_ne : current_state.set(e_level05, e_level06, details::e_ne ); break;
case token_t::e_gte : current_state.set(e_level05, e_level06, details::e_gte ); break;
case token_t::e_gt : current_state.set(e_level05, e_level06, details::e_gt ); break;
case token_t::e_add : current_state.set(e_level07, e_level08, details::e_add ); break;
case token_t::e_sub : current_state.set(e_level07, e_level08, details::e_sub ); break;
case token_t::e_div : current_state.set(e_level10, e_level11, details::e_div ); break;
case token_t::e_mul : current_state.set(e_level10, e_level11, details::e_mul ); break;
case token_t::e_mod : current_state.set(e_level10, e_level11, details::e_mod ); break;
case token_t::e_pow : current_state.set(e_level12, e_level12, details::e_pow ); break;
default : if (token_t::e_symbol == current_token().type)
{
static const std::string s_and = "and" ;
static const std::string s_nand = "nand" ;
static const std::string s_or = "or" ;
static const std::string s_nor = "nor" ;
static const std::string s_xor = "xor" ;
static const std::string s_xnor = "xnor" ;
static const std::string s_in = "in" ;
static const std::string s_like = "like" ;
static const std::string s_ilike = "ilike";
static const std::string s_and1 = "&" ;
static const std::string s_or1 = "|" ;
static const std::string s_not = "not" ;
if (details::imatch(current_token().value,s_and))
{
current_state.set(e_level03, e_level04, details::e_and);
break;
}
else if (details::imatch(current_token().value,s_and1))
{
#ifndef exprtk_disable_sc_andor
current_state.set(e_level03, e_level04, details::e_scand);
#else
current_state.set(e_level03, e_level04, details::e_and);
#endif
break;
}
else if (details::imatch(current_token().value,s_nand))
{
current_state.set(e_level03, e_level04, details::e_nand);
break;
}
else if (details::imatch(current_token().value,s_or))
{
current_state.set(e_level01, e_level02, details::e_or);
break;
}
else if (details::imatch(current_token().value,s_or1))
{
#ifndef exprtk_disable_sc_andor
current_state.set(e_level01, e_level02, details::e_scor);
#else
current_state.set(e_level01, e_level02, details::e_or);
#endif
break;
}
else if (details::imatch(current_token().value,s_nor))
{
current_state.set(e_level01, e_level02, details::e_nor);
break;
}
else if (details::imatch(current_token().value,s_xor))
{
current_state.set(e_level01, e_level02, details::e_xor);
break;
}
else if (details::imatch(current_token().value,s_xnor))
{
current_state.set(e_level01, e_level02, details::e_xnor);
break;
}
else if (details::imatch(current_token().value,s_in))
{
current_state.set(e_level04, e_level04, details::e_in);
break;
}
else if (details::imatch(current_token().value,s_like))
{
current_state.set(e_level04, e_level04, details::e_like);
break;
}
else if (details::imatch(current_token().value,s_ilike))
{
current_state.set(e_level04, e_level04, details::e_ilike);
break;
}
else if (details::imatch(current_token().value,s_not))
{
break;
}
}
break_loop = true;
}
if (break_loop)
{
parse_pending_string_rangesize(expression);
break;
}
else if (current_state.left < precedence)
break;
const lexer::token prev_token = current_token();
next_token();
expression_node_ptr right_branch = error_node();
expression_node_ptr new_expression = error_node();
if (is_invalid_logic_operation(current_state.operation))
{
free_node(node_allocator_,expression);
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR010 - Invalid or disabled logic operation '" + details::to_str(current_state.operation) + "'",
exprtk_error_location));
return error_node();
}
else if (is_invalid_arithmetic_operation(current_state.operation))
{
free_node(node_allocator_,expression);
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR011 - Invalid or disabled arithmetic operation '" + details::to_str(current_state.operation) + "'",
exprtk_error_location));
return error_node();
}
else if (is_invalid_inequality_operation(current_state.operation))
{
free_node(node_allocator_,expression);
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR012 - Invalid inequality operation '" + details::to_str(current_state.operation) + "'",
exprtk_error_location));
return error_node();
}
else if (is_invalid_assignment_operation(current_state.operation))
{
free_node(node_allocator_,expression);
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR013 - Invalid or disabled assignment operation '" + details::to_str(current_state.operation) + "'",
exprtk_error_location));
return error_node();
}
if (0 != (right_branch = parse_expression(current_state.right)))
{
if (
details::is_return_node(expression ) ||
details::is_return_node(right_branch)
)
{
free_node(node_allocator_, expression );
free_node(node_allocator_, right_branch);
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR014 - Return statements cannot be part of sub-expressions",
exprtk_error_location));
return error_node();
}
new_expression = expression_generator_
(
current_state.operation,
expression,
right_branch
);
}
if (0 == new_expression)
{
if (error_list_.empty())
{
set_error(
make_error(parser_error::e_syntax,
prev_token,
!synthesis_error_.empty() ?
synthesis_error_ :
"ERR015 - General parsing error at token: '" + prev_token.value + "'",
exprtk_error_location));
}
free_node(node_allocator_, expression );
free_node(node_allocator_, right_branch);
return error_node();
}
else
{
if (
token_is(token_t::e_ternary,prsrhlpr_t::e_hold) &&
(e_level00 == precedence)
)
{
expression = parse_ternary_conditional_statement(new_expression);
}
else
expression = new_expression;
parse_pending_string_rangesize(expression);
}
}
if ((0 != expression) && (expression->node_depth() > settings_.max_node_depth_))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR016 - Expression depth of " + details::to_str(static_cast<int>(expression->node_depth())) +
" exceeds maximum allowed expression depth of " + details::to_str(static_cast<int>(settings_.max_node_depth_)),
exprtk_error_location));
free_node(node_allocator_,expression);
return error_node();
}
return expression;
}
bool simplify_unary_negation_branch(expression_node_ptr& node)
{
{
typedef details::unary_branch_node<T,details::neg_op<T> > ubn_t;
ubn_t* n = dynamic_cast<ubn_t*>(node);
if (n)
{
expression_node_ptr un_r = n->branch(0);
n->release();
free_node(node_allocator_,node);
node = un_r;
return true;
}
}
{
typedef details::unary_variable_node<T,details::neg_op<T> > uvn_t;
uvn_t* n = dynamic_cast<uvn_t*>(node);
if (n)
{
const T& v = n->v();
expression_node_ptr return_node = error_node();
if (
(0 != (return_node = symtab_store_.get_variable(v))) ||
(0 != (return_node = sem_ .get_variable(v)))
)
{
free_node(node_allocator_,node);
node = return_node;
return true;
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR017 - Failed to find variable node in symbol table",
exprtk_error_location));
free_node(node_allocator_,node);
return false;
}
}
}
return false;
}
static inline expression_node_ptr error_node()
{
return reinterpret_cast<expression_node_ptr>(0);
}
struct scoped_expression_delete
{
scoped_expression_delete(parser<T>& pr, expression_node_ptr& expression)
: delete_ptr(true)
, parser_(pr)
, expression_(expression)
{}
~scoped_expression_delete()
{
if (delete_ptr)
{
free_node(parser_.node_allocator_, expression_);
}
}
bool delete_ptr;
parser<T>& parser_;
expression_node_ptr& expression_;
private:
scoped_expression_delete(const scoped_expression_delete&) exprtk_delete;
scoped_expression_delete& operator=(const scoped_expression_delete&) exprtk_delete;
};
template <typename Type, std::size_t N>
struct scoped_delete
{
typedef Type* ptr_t;
scoped_delete(parser<T>& pr, ptr_t& p)
: delete_ptr(true)
, parser_(pr)
, p_(&p)
{}
scoped_delete(parser<T>& pr, ptr_t (&p)[N])
: delete_ptr(true)
, parser_(pr)
, p_(&p[0])
{}
~scoped_delete()
{
if (delete_ptr)
{
for (std::size_t i = 0; i < N; ++i)
{
free_node(parser_.node_allocator_, p_[i]);
}
}
}
bool delete_ptr;
parser<T>& parser_;
ptr_t* p_;
private:
scoped_delete(const scoped_delete<Type,N>&) exprtk_delete;
scoped_delete<Type,N>& operator=(const scoped_delete<Type,N>&) exprtk_delete;
};
template <typename Type>
struct scoped_deq_delete
{
typedef Type* ptr_t;
scoped_deq_delete(parser<T>& pr, std::deque<ptr_t>& deq)
: delete_ptr(true)
, parser_(pr)
, deq_(deq)
{}
~scoped_deq_delete()
{
if (delete_ptr && !deq_.empty())
{
for (std::size_t i = 0; i < deq_.size(); ++i)
{
free_node(parser_.node_allocator_,deq_[i]);
}
deq_.clear();
}
}
bool delete_ptr;
parser<T>& parser_;
std::deque<ptr_t>& deq_;
private:
scoped_deq_delete(const scoped_deq_delete<Type>&) exprtk_delete;
scoped_deq_delete<Type>& operator=(const scoped_deq_delete<Type>&) exprtk_delete;
};
template <typename Type>
struct scoped_vec_delete
{
typedef Type* ptr_t;
scoped_vec_delete(parser<T>& pr, std::vector<ptr_t>& vec)
: delete_ptr(true)
, parser_(pr)
, vec_(vec)
{}
~scoped_vec_delete()
{
if (delete_ptr && !vec_.empty())
{
for (std::size_t i = 0; i < vec_.size(); ++i)
{
free_node(parser_.node_allocator_,vec_[i]);
}
vec_.clear();
}
}
bool delete_ptr;
parser<T>& parser_;
std::vector<ptr_t>& vec_;
private:
scoped_vec_delete(const scoped_vec_delete<Type>&) exprtk_delete;
scoped_vec_delete<Type>& operator=(const scoped_vec_delete<Type>&) exprtk_delete;
};
struct scoped_bool_negator
{
explicit scoped_bool_negator(bool& bb)
: b(bb)
{ b = !b; }
~scoped_bool_negator()
{ b = !b; }
bool& b;
};
struct scoped_bool_or_restorer
{
explicit scoped_bool_or_restorer(bool& bb)
: b(bb)
, original_value_(bb)
{}
~scoped_bool_or_restorer()
{
b = b || original_value_;
}
bool& b;
bool original_value_;
};
struct scoped_inc_dec
{
explicit scoped_inc_dec(std::size_t& v)
: v_(v)
{ ++v_; }
~scoped_inc_dec()
{
assert(v_ > 0);
--v_;
}
std::size_t& v_;
};
inline expression_node_ptr parse_function_invocation(ifunction<T>* function, const std::string& function_name)
{
expression_node_ptr func_node = reinterpret_cast<expression_node_ptr>(0);
switch (function->param_count)
{
case 0 : func_node = parse_function_call_0 (function,function_name); break;
case 1 : func_node = parse_function_call< 1>(function,function_name); break;
case 2 : func_node = parse_function_call< 2>(function,function_name); break;
case 3 : func_node = parse_function_call< 3>(function,function_name); break;
case 4 : func_node = parse_function_call< 4>(function,function_name); break;
case 5 : func_node = parse_function_call< 5>(function,function_name); break;
case 6 : func_node = parse_function_call< 6>(function,function_name); break;
case 7 : func_node = parse_function_call< 7>(function,function_name); break;
case 8 : func_node = parse_function_call< 8>(function,function_name); break;
case 9 : func_node = parse_function_call< 9>(function,function_name); break;
case 10 : func_node = parse_function_call<10>(function,function_name); break;
case 11 : func_node = parse_function_call<11>(function,function_name); break;
case 12 : func_node = parse_function_call<12>(function,function_name); break;
case 13 : func_node = parse_function_call<13>(function,function_name); break;
case 14 : func_node = parse_function_call<14>(function,function_name); break;
case 15 : func_node = parse_function_call<15>(function,function_name); break;
case 16 : func_node = parse_function_call<16>(function,function_name); break;
case 17 : func_node = parse_function_call<17>(function,function_name); break;
case 18 : func_node = parse_function_call<18>(function,function_name); break;
case 19 : func_node = parse_function_call<19>(function,function_name); break;
case 20 : func_node = parse_function_call<20>(function,function_name); break;
default : {
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR018 - Invalid number of parameters for function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
}
if (func_node)
return func_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR019 - Failed to generate call to function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
}
template <std::size_t NumberofParameters>
inline expression_node_ptr parse_function_call(ifunction<T>* function, const std::string& function_name)
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
if (0 == NumberofParameters)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR020 - Expecting ifunction '" + function_name + "' to have non-zero parameter count",
exprtk_error_location));
return error_node();
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
expression_node_ptr branch[NumberofParameters];
expression_node_ptr result = error_node();
std::fill_n(branch, NumberofParameters, reinterpret_cast<expression_node_ptr>(0));
scoped_delete<expression_node_t,NumberofParameters> sd((*this),branch);
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR021 - Expecting argument list for function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
for (int i = 0; i < static_cast<int>(NumberofParameters); ++i)
{
branch[i] = parse_expression();
if (0 == branch[i])
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR022 - Failed to parse argument " + details::to_str(i) + " for function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
else if (i < static_cast<int>(NumberofParameters - 1))
{
if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR023 - Invalid number of arguments for function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
}
}
if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR024 - Invalid number of arguments for function: '" + function_name + "'",
exprtk_error_location));
return error_node();
}
else
result = expression_generator_.function(function,branch);
sd.delete_ptr = (0 == result);
return result;
}
inline expression_node_ptr parse_function_call_0(ifunction<T>* function, const std::string& function_name)
{
expression_node_ptr result = expression_generator_.function(function);
state_.side_effect_present = function->has_side_effects();
next_token();
if (
token_is(token_t::e_lbracket) &&
!token_is(token_t::e_rbracket)
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR025 - Expecting '()' to proceed call to function: '" + function_name + "'",
exprtk_error_location));
free_node(node_allocator_,result);
return error_node();
}
else
return result;
}
template <std::size_t MaxNumberofParameters>
inline std::size_t parse_base_function_call(expression_node_ptr (¶m_list)[MaxNumberofParameters], const std::string& function_name = "")
{
std::fill_n(param_list, MaxNumberofParameters, reinterpret_cast<expression_node_ptr>(0));
scoped_delete<expression_node_t,MaxNumberofParameters> sd((*this),param_list);
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR026 - Expected a '(' at start of function call to '" + function_name +
"', instead got: '" + current_token().value + "'",
exprtk_error_location));
return 0;
}
if (token_is(token_t::e_rbracket, e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR027 - Expected at least one input parameter for function call '" + function_name + "'",
exprtk_error_location));
return 0;
}
std::size_t param_index = 0;
for (; param_index < MaxNumberofParameters; ++param_index)
{
param_list[param_index] = parse_expression();
if (0 == param_list[param_index])
return 0;
else if (token_is(token_t::e_rbracket))
{
sd.delete_ptr = false;
break;
}
else if (token_is(token_t::e_comma))
continue;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR028 - Expected a ',' between function input parameters, instead got: '" + current_token().value + "'",
exprtk_error_location));
return 0;
}
}
if (sd.delete_ptr)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR029 - Invalid number of input parameters passed to function '" + function_name + "'",
exprtk_error_location));
return 0;
}
return (param_index + 1);
}
inline expression_node_ptr parse_base_operation()
{
typedef std::pair<base_ops_map_t::iterator,base_ops_map_t::iterator> map_range_t;
const std::string operation_name = current_token().value;
const token_t diagnostic_token = current_token();
map_range_t itr_range = base_ops_map_.equal_range(operation_name);
if (0 == std::distance(itr_range.first,itr_range.second))
{
set_error(
make_error(parser_error::e_syntax,
diagnostic_token,
"ERR030 - No entry found for base operation: " + operation_name,
exprtk_error_location));
return error_node();
}
static const std::size_t MaxNumberofParameters = 4;
expression_node_ptr param_list[MaxNumberofParameters] = {0};
const std::size_t parameter_count = parse_base_function_call(param_list, operation_name);
if ((parameter_count > 0) && (parameter_count <= MaxNumberofParameters))
{
for (base_ops_map_t::iterator itr = itr_range.first; itr != itr_range.second; ++itr)
{
const details::base_operation_t& operation = itr->second;
if (operation.num_params == parameter_count)
{
switch (parameter_count)
{
#define base_opr_case(N) \
case N : { \
expression_node_ptr pl##N[N] = {0}; \
std::copy(param_list, param_list + N, pl##N); \
lodge_symbol(operation_name, e_st_function); \
return expression_generator_(operation.type, pl##N); \
} \
base_opr_case(1)
base_opr_case(2)
base_opr_case(3)
base_opr_case(4)
#undef base_opr_case
}
}
}
}
for (std::size_t i = 0; i < MaxNumberofParameters; ++i)
{
free_node(node_allocator_, param_list[i]);
}
set_error(
make_error(parser_error::e_syntax,
diagnostic_token,
"ERR031 - Invalid number of input parameters for call to function: '" + operation_name + "'",
exprtk_error_location));
return error_node();
}
inline expression_node_ptr parse_conditional_statement_01(expression_node_ptr condition)
{
// Parse: [if][(][condition][,][consequent][,][alternative][)]
expression_node_ptr consequent = error_node();
expression_node_ptr alternative = error_node();
bool result = true;
if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR032 - Expected ',' between if-statement condition and consequent",
exprtk_error_location));
result = false;
}
else if (0 == (consequent = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR033 - Failed to parse consequent for if-statement",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR034 - Expected ',' between if-statement consequent and alternative",
exprtk_error_location));
result = false;
}
else if (0 == (alternative = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR035 - Failed to parse alternative for if-statement",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR036 - Expected ')' at the end of if-statement",
exprtk_error_location));
result = false;
}
#ifndef exprtk_disable_string_capabilities
if (result)
{
const bool consq_is_str = is_generally_string_node(consequent );
const bool alter_is_str = is_generally_string_node(alternative);
if (consq_is_str || alter_is_str)
{
if (consq_is_str && alter_is_str)
{
return expression_generator_
.conditional_string(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR037 - Return types of if-statement differ: string/non-string",
exprtk_error_location));
result = false;
}
}
#endif
if (result)
{
const bool consq_is_vec = is_ivector_node(consequent );
const bool alter_is_vec = is_ivector_node(alternative);
if (consq_is_vec || alter_is_vec)
{
if (consq_is_vec && alter_is_vec)
{
return expression_generator_
.conditional_vector(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR038 - Return types of if-statement differ: vector/non-vector",
exprtk_error_location));
result = false;
}
}
if (!result)
{
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent );
free_node(node_allocator_, alternative);
return error_node();
}
else
return expression_generator_
.conditional(condition, consequent, alternative);
}
inline expression_node_ptr parse_conditional_statement_02(expression_node_ptr condition)
{
expression_node_ptr consequent = error_node();
expression_node_ptr alternative = error_node();
bool result = true;
if (token_is(token_t::e_lcrlbracket,prsrhlpr_t::e_hold))
{
if (0 == (consequent = parse_multi_sequence("if-statement-01")))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR039 - Failed to parse body of consequent for if-statement",
exprtk_error_location));
result = false;
}
}
else
{
if (
settings_.commutative_check_enabled() &&
token_is(token_t::e_mul,prsrhlpr_t::e_hold)
)
{
next_token();
}
if (0 != (consequent = parse_expression()))
{
if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR040 - Expected ';' at the end of the consequent for if-statement",
exprtk_error_location));
result = false;
}
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR041 - Failed to parse body of consequent for if-statement",
exprtk_error_location));
result = false;
}
}
if (result)
{
if (details::imatch(current_token().value,"else"))
{
next_token();
if (token_is(token_t::e_lcrlbracket,prsrhlpr_t::e_hold))
{
if (0 == (alternative = parse_multi_sequence("else-statement-01")))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR042 - Failed to parse body of the 'else' for if-statement",
exprtk_error_location));
result = false;
}
}
else if (details::imatch(current_token().value,"if"))
{
if (0 == (alternative = parse_conditional_statement()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR043 - Failed to parse body of if-else statement",
exprtk_error_location));
result = false;
}
}
else if (0 != (alternative = parse_expression()))
{
if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR044 - Expected ';' at the end of the 'else-if' for the if-statement",
exprtk_error_location));
result = false;
}
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR045 - Failed to parse body of the 'else' for if-statement",
exprtk_error_location));
result = false;
}
}
}
#ifndef exprtk_disable_string_capabilities
if (result)
{
const bool consq_is_str = is_generally_string_node(consequent );
const bool alter_is_str = is_generally_string_node(alternative);
if (consq_is_str || alter_is_str)
{
if (consq_is_str && alter_is_str)
{
return expression_generator_
.conditional_string(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR046 - Return types of if-statement differ: string/non-string",
exprtk_error_location));
result = false;
}
}
#endif
if (result)
{
const bool consq_is_vec = is_ivector_node(consequent );
const bool alter_is_vec = is_ivector_node(alternative);
if (consq_is_vec || alter_is_vec)
{
if (consq_is_vec && alter_is_vec)
{
return expression_generator_
.conditional_vector(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR047 - Return types of if-statement differ: vector/non-vector",
exprtk_error_location));
result = false;
}
}
if (!result)
{
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent );
free_node(node_allocator_, alternative);
return error_node();
}
else
return expression_generator_
.conditional(condition, consequent, alternative);
}
inline expression_node_ptr parse_conditional_statement()
{
expression_node_ptr condition = error_node();
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR048 - Expected '(' at start of if-statement, instead got: '" + current_token().value + "'",
exprtk_error_location));
return error_node();
}
else if (0 == (condition = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR049 - Failed to parse condition for if-statement",
exprtk_error_location));
return error_node();
}
else if (token_is(token_t::e_comma,prsrhlpr_t::e_hold))
{
// if (x,y,z)
return parse_conditional_statement_01(condition);
}
else if (token_is(token_t::e_rbracket))
{
/*
00. if (x) y;
01. if (x) y; else z;
02. if (x) y; else {z0; ... zn;}
03. if (x) y; else if (z) w;
04. if (x) y; else if (z) w; else u;
05. if (x) y; else if (z) w; else {u0; ... un;}
06. if (x) y; else if (z) {w0; ... wn;}
07. if (x) {y0; ... yn;}
08. if (x) {y0; ... yn;} else z;
09. if (x) {y0; ... yn;} else {z0; ... zn;};
10. if (x) {y0; ... yn;} else if (z) w;
11. if (x) {y0; ... yn;} else if (z) w; else u;
12. if (x) {y0; ... nex;} else if (z) w; else {u0 ... un;}
13. if (x) {y0; ... yn;} else if (z) {w0; ... wn;}
*/
return parse_conditional_statement_02(condition);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR050 - Invalid if-statement",
exprtk_error_location));
free_node(node_allocator_,condition);
return error_node();
}
inline expression_node_ptr parse_ternary_conditional_statement(expression_node_ptr condition)
{
// Parse: [condition][?][consequent][:][alternative]
expression_node_ptr consequent = error_node();
expression_node_ptr alternative = error_node();
bool result = true;
if (0 == condition)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR051 - Encountered invalid condition branch for ternary if-statement",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_ternary))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR052 - Expected '?' after condition of ternary if-statement",
exprtk_error_location));
result = false;
}
else if (0 == (consequent = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR053 - Failed to parse consequent for ternary if-statement",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_colon))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR054 - Expected ':' between ternary if-statement consequent and alternative",
exprtk_error_location));
result = false;
}
else if (0 == (alternative = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR055 - Failed to parse alternative for ternary if-statement",
exprtk_error_location));
result = false;
}
#ifndef exprtk_disable_string_capabilities
if (result)
{
const bool consq_is_str = is_generally_string_node(consequent );
const bool alter_is_str = is_generally_string_node(alternative);
if (consq_is_str || alter_is_str)
{
if (consq_is_str && alter_is_str)
{
return expression_generator_
.conditional_string(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR056 - Return types of ternary differ: string/non-string",
exprtk_error_location));
result = false;
}
}
#endif
if (result)
{
const bool consq_is_vec = is_ivector_node(consequent );
const bool alter_is_vec = is_ivector_node(alternative);
if (consq_is_vec || alter_is_vec)
{
if (consq_is_vec && alter_is_vec)
{
return expression_generator_
.conditional_vector(condition, consequent, alternative);
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR057 - Return types of ternary differ: vector/non-vector",
exprtk_error_location));
result = false;
}
}
if (!result)
{
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent );
free_node(node_allocator_, alternative);
return error_node();
}
else
return expression_generator_
.conditional(condition, consequent, alternative);
}
inline expression_node_ptr parse_not_statement()
{
if (settings_.logic_disabled("not"))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR058 - Invalid or disabled logic operation 'not'",
exprtk_error_location));
return error_node();
}
return parse_base_operation();
}
void handle_brkcnt_scope_exit()
{
assert(!brkcnt_list_.empty());
brkcnt_list_.pop_front();
}
inline expression_node_ptr parse_while_loop()
{
// Parse: [while][(][test expr][)][{][expression][}]
expression_node_ptr condition = error_node();
expression_node_ptr branch = error_node();
expression_node_ptr result_node = error_node();
bool result = true;
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR059 - Expected '(' at start of while-loop condition statement",
exprtk_error_location));
return error_node();
}
else if (0 == (condition = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR060 - Failed to parse condition for while-loop",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR061 - Expected ')' at end of while-loop condition statement",
exprtk_error_location));
result = false;
}
brkcnt_list_.push_front(false);
if (result)
{
scoped_inc_dec sid(state_.parsing_loop_stmt_count);
if (0 == (branch = parse_multi_sequence("while-loop", true)))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR062 - Failed to parse body of while-loop"));
result = false;
}
else if (0 == (result_node = expression_generator_.while_loop(condition,
branch,
brkcnt_list_.front())))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR063 - Failed to synthesize while-loop",
exprtk_error_location));
result = false;
}
}
handle_brkcnt_scope_exit();
if (!result)
{
free_node(node_allocator_, branch );
free_node(node_allocator_, condition );
free_node(node_allocator_, result_node);
return error_node();
}
return result_node;
}
inline expression_node_ptr parse_repeat_until_loop()
{
// Parse: [repeat][{][expression][}][until][(][test expr][)]
expression_node_ptr condition = error_node();
expression_node_ptr branch = error_node();
next_token();
std::vector<expression_node_ptr> arg_list;
std::vector<bool> side_effect_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
brkcnt_list_.push_front(false);
if (details::imatch(current_token().value,"until"))
{
next_token();
branch = node_allocator_.allocate<details::null_node<T> >();
}
else
{
const token_t::token_type seperator = token_t::e_eof;
scope_handler sh(*this);
scoped_bool_or_restorer sbr(state_.side_effect_present);
scoped_inc_dec sid(state_.parsing_loop_stmt_count);
for ( ; ; )
{
state_.side_effect_present = false;
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
else
{
arg_list.push_back(arg);
side_effect_list.push_back(state_.side_effect_present);
}
if (details::imatch(current_token().value,"until"))
{
next_token();
break;
}
const bool is_next_until = peek_token_is(token_t::e_symbol) &&
peek_token_is("until");
if (!token_is(seperator) && is_next_until)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR064 - Expected '" + token_t::to_str(seperator) + "' in body of repeat until loop",
exprtk_error_location));
return error_node();
}
if (details::imatch(current_token().value,"until"))
{
next_token();
break;
}
}
branch = simplify(arg_list,side_effect_list);
sdd.delete_ptr = (0 == branch);
if (sdd.delete_ptr)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR065 - Failed to parse body of repeat until loop",
exprtk_error_location));
return error_node();
}
}
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR066 - Expected '(' before condition statement of repeat until loop",
exprtk_error_location));
free_node(node_allocator_,branch);
return error_node();
}
else if (0 == (condition = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR067 - Failed to parse condition for repeat until loop",
exprtk_error_location));
free_node(node_allocator_,branch);
return error_node();
}
else if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR068 - Expected ')' after condition of repeat until loop",
exprtk_error_location));
free_node(node_allocator_, branch );
free_node(node_allocator_, condition);
return error_node();
}
expression_node_ptr result;
result = expression_generator_
.repeat_until_loop(condition, branch, brkcnt_list_.front());
if (0 == result)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR069 - Failed to synthesize repeat until loop",
exprtk_error_location));
free_node(node_allocator_,condition);
return error_node();
}
handle_brkcnt_scope_exit();
return result;
}
inline expression_node_ptr parse_for_loop()
{
expression_node_ptr initialiser = error_node();
expression_node_ptr condition = error_node();
expression_node_ptr incrementor = error_node();
expression_node_ptr loop_body = error_node();
scope_element* se = 0;
bool result = true;
next_token();
scope_handler sh(*this);
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR070 - Expected '(' at start of for-loop",
exprtk_error_location));
return error_node();
}
if (!token_is(token_t::e_eof))
{
if (
!token_is(token_t::e_symbol,prsrhlpr_t::e_hold) &&
details::imatch(current_token().value,"var")
)
{
next_token();
if (!token_is(token_t::e_symbol,prsrhlpr_t::e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR071 - Expected a variable at the start of initialiser section of for-loop",
exprtk_error_location));
return error_node();
}
else if (!peek_token_is(token_t::e_assign))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR072 - Expected variable assignment of initialiser section of for-loop",
exprtk_error_location));
return error_node();
}
const std::string loop_counter_symbol = current_token().value;
se = &sem_.get_element(loop_counter_symbol);
if ((se->name == loop_counter_symbol) && se->active)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR073 - For-loop variable '" + loop_counter_symbol+ "' is being shadowed by a previous declaration",
exprtk_error_location));
return error_node();
}
else if (!symtab_store_.is_variable(loop_counter_symbol))
{
if (
!se->active &&
(se->name == loop_counter_symbol) &&
(se->type == scope_element::e_variable)
)
{
se->active = true;
se->ref_count++;
}
else
{
scope_element nse;
nse.name = loop_counter_symbol;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_variable;
nse.depth = state_.scope_depth;
nse.data = new T(T(0));
nse.var_node = node_allocator_.allocate<variable_node_t>(*reinterpret_cast<T*>(nse.data));
if (!sem_.add_element(nse))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR074 - Failed to add new local variable '" + loop_counter_symbol + "' to SEM",
exprtk_error_location));
sem_.free_element(nse);
result = false;
}
else
{
exprtk_debug(("parse_for_loop() - INFO - Added new local variable: %s\n",nse.name.c_str()));
state_.activate_side_effect("parse_for_loop()");
}
}
}
}
if (0 == (initialiser = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR075 - Failed to parse initialiser of for-loop",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR076 - Expected ';' after initialiser of for-loop",
exprtk_error_location));
result = false;
}
}
if (!token_is(token_t::e_eof))
{
if (0 == (condition = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR077 - Failed to parse condition of for-loop",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR078 - Expected ';' after condition section of for-loop",
exprtk_error_location));
result = false;
}
}
if (!token_is(token_t::e_rbracket))
{
if (0 == (incrementor = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR079 - Failed to parse incrementor of for-loop",
exprtk_error_location));
result = false;
}
else if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR080 - Expected ')' after incrementor section of for-loop",
exprtk_error_location));
result = false;
}
}
if (result)
{
brkcnt_list_.push_front(false);
scoped_inc_dec sid(state_.parsing_loop_stmt_count);
if (0 == (loop_body = parse_multi_sequence("for-loop", true)))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR081 - Failed to parse body of for-loop",
exprtk_error_location));
result = false;
}
}
if (!result)
{
if (se)
{
se->ref_count--;
}
free_node(node_allocator_, initialiser);
free_node(node_allocator_, condition );
free_node(node_allocator_, incrementor);
free_node(node_allocator_, loop_body );
return error_node();
}
expression_node_ptr result_node =
expression_generator_.for_loop(initialiser,
condition,
incrementor,
loop_body,
brkcnt_list_.front());
handle_brkcnt_scope_exit();
return result_node;
}
inline expression_node_ptr parse_switch_statement()
{
std::vector<expression_node_ptr> arg_list;
expression_node_ptr result = error_node();
if (!details::imatch(current_token().value,"switch"))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR082 - Expected keyword 'switch'",
exprtk_error_location));
return error_node();
}
scoped_vec_delete<expression_node_t> svd((*this),arg_list);
next_token();
if (!token_is(token_t::e_lcrlbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR083 - Expected '{' for call to switch statement",
exprtk_error_location));
return error_node();
}
expression_node_ptr default_statement = error_node();
scoped_expression_delete defstmt_delete((*this), default_statement);
for ( ; ; )
{
if (details::imatch("case",current_token().value))
{
next_token();
expression_node_ptr condition = parse_expression();
if (0 == condition)
return error_node();
else if (!token_is(token_t::e_colon))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR084 - Expected ':' for case of switch statement",
exprtk_error_location));
free_node(node_allocator_, condition);
return error_node();
}
expression_node_ptr consequent = parse_expression();
if (0 == consequent)
{
free_node(node_allocator_, condition);
return error_node();
}
else if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR085 - Expected ';' at end of case for switch statement",
exprtk_error_location));
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent);
return error_node();
}
// Can we optimise away the case statement?
if (is_constant_node(condition) && is_false(condition))
{
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent);
}
else
{
arg_list.push_back(condition );
arg_list.push_back(consequent);
}
}
else if (details::imatch("default",current_token().value))
{
if (0 != default_statement)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR086 - Multiple default cases for switch statement",
exprtk_error_location));
return error_node();
}
next_token();
if (!token_is(token_t::e_colon))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR087 - Expected ':' for default of switch statement",
exprtk_error_location));
return error_node();
}
if (token_is(token_t::e_lcrlbracket,prsrhlpr_t::e_hold))
default_statement = parse_multi_sequence("switch-default");
else
default_statement = parse_expression();
if (0 == default_statement)
return error_node();
else if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR088 - Expected ';' at end of default for switch statement",
exprtk_error_location));
return error_node();
}
}
else if (token_is(token_t::e_rcrlbracket))
break;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR089 - Expected '}' at end of switch statement",
exprtk_error_location));
return error_node();
}
}
const bool default_statement_present = (0 != default_statement);
if (default_statement_present)
{
arg_list.push_back(default_statement);
}
result = expression_generator_.switch_statement(arg_list, (0 != default_statement));
svd.delete_ptr = (0 == result);
defstmt_delete.delete_ptr = (0 == result);
return result;
}
inline expression_node_ptr parse_multi_switch_statement()
{
std::vector<expression_node_ptr> arg_list;
if (!details::imatch(current_token().value,"[*]"))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR090 - Expected token '[*]'",
exprtk_error_location));
return error_node();
}
scoped_vec_delete<expression_node_t> svd((*this),arg_list);
next_token();
if (!token_is(token_t::e_lcrlbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR091 - Expected '{' for call to [*] statement",
exprtk_error_location));
return error_node();
}
for ( ; ; )
{
if (!details::imatch("case",current_token().value))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR092 - Expected a 'case' statement for multi-switch",
exprtk_error_location));
return error_node();
}
next_token();
expression_node_ptr condition = parse_expression();
if (0 == condition)
return error_node();
if (!token_is(token_t::e_colon))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR093 - Expected ':' for case of [*] statement",
exprtk_error_location));
return error_node();
}
expression_node_ptr consequent = parse_expression();
if (0 == consequent)
return error_node();
if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR094 - Expected ';' at end of case for [*] statement",
exprtk_error_location));
return error_node();
}
// Can we optimise away the case statement?
if (is_constant_node(condition) && is_false(condition))
{
free_node(node_allocator_, condition );
free_node(node_allocator_, consequent);
}
else
{
arg_list.push_back(condition );
arg_list.push_back(consequent);
}
if (token_is(token_t::e_rcrlbracket,prsrhlpr_t::e_hold))
{
break;
}
}
if (!token_is(token_t::e_rcrlbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR095 - Expected '}' at end of [*] statement",
exprtk_error_location));
return error_node();
}
const expression_node_ptr result = expression_generator_.multi_switch_statement(arg_list);
svd.delete_ptr = (0 == result);
return result;
}
inline expression_node_ptr parse_vararg_function()
{
std::vector<expression_node_ptr> arg_list;
details::operator_type opt_type = details::e_default;
const std::string symbol = current_token().value;
if (details::imatch(symbol,"~"))
{
next_token();
return parse_multi_sequence();
}
else if (details::imatch(symbol,"[*]"))
{
return parse_multi_switch_statement();
}
else if (details::imatch(symbol, "avg" )) opt_type = details::e_avg ;
else if (details::imatch(symbol, "mand")) opt_type = details::e_mand;
else if (details::imatch(symbol, "max" )) opt_type = details::e_max ;
else if (details::imatch(symbol, "min" )) opt_type = details::e_min ;
else if (details::imatch(symbol, "mor" )) opt_type = details::e_mor ;
else if (details::imatch(symbol, "mul" )) opt_type = details::e_prod;
else if (details::imatch(symbol, "sum" )) opt_type = details::e_sum ;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR096 - Unsupported built-in vararg function: " + symbol,
exprtk_error_location));
return error_node();
}
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
lodge_symbol(symbol, e_st_function);
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR097 - Expected '(' for call to vararg function: " + symbol,
exprtk_error_location));
return error_node();
}
if (token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR098 - vararg function: " + symbol +
" requires at least one input parameter",
exprtk_error_location));
return error_node();
}
for ( ; ; )
{
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
else
arg_list.push_back(arg);
if (token_is(token_t::e_rbracket))
break;
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR099 - Expected ',' for call to vararg function: " + symbol,
exprtk_error_location));
return error_node();
}
}
const expression_node_ptr result = expression_generator_.vararg_function(opt_type,arg_list);
sdd.delete_ptr = (0 == result);
return result;
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr parse_string_range_statement(expression_node_ptr& expression)
{
if (!token_is(token_t::e_lsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR100 - Expected '[' as start of string range definition",
exprtk_error_location));
free_node(node_allocator_,expression);
return error_node();
}
else if (token_is(token_t::e_rsqrbracket))
{
return node_allocator_.allocate<details::string_size_node<T> >(expression);
}
range_t rp;
if (!parse_range(rp,true))
{
free_node(node_allocator_,expression);
return error_node();
}
expression_node_ptr result = expression_generator_(expression,rp);
if (0 == result)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR101 - Failed to generate string range node",
exprtk_error_location));
free_node(node_allocator_,expression);
rp.free();
}
rp.clear();
return result;
}
#else
inline expression_node_ptr parse_string_range_statement(expression_node_ptr&)
{
return error_node();
}
#endif
inline void parse_pending_string_rangesize(expression_node_ptr& expression)
{
// Allow no more than 100 range calls, eg: s[][][]...[][]
const std::size_t max_rangesize_parses = 100;
std::size_t i = 0;
while
(
(0 != expression) &&
(i++ < max_rangesize_parses) &&
error_list_.empty() &&
is_generally_string_node(expression) &&
token_is(token_t::e_lsqrbracket,prsrhlpr_t::e_hold)
)
{
expression = parse_string_range_statement(expression);
}
}
template <typename Allocator1,
typename Allocator2,
template <typename, typename> class Sequence>
inline expression_node_ptr simplify(Sequence<expression_node_ptr,Allocator1>& expression_list,
Sequence<bool,Allocator2>& side_effect_list,
const bool specialise_on_final_type = false)
{
if (expression_list.empty())
return error_node();
else if (1 == expression_list.size())
return expression_list[0];
Sequence<expression_node_ptr,Allocator1> tmp_expression_list;
bool return_node_present = false;
for (std::size_t i = 0; i < (expression_list.size() - 1); ++i)
{
if (is_variable_node(expression_list[i]))
continue;
else if (
is_return_node (expression_list[i]) ||
is_break_node (expression_list[i]) ||
is_continue_node(expression_list[i])
)
{
tmp_expression_list.push_back(expression_list[i]);
// Remove all subexpressions after first short-circuit
// node has been encountered.
for (std::size_t j = i + 1; j < expression_list.size(); ++j)
{
free_node(node_allocator_,expression_list[j]);
}
return_node_present = true;
break;
}
else if (
is_constant_node(expression_list[i]) ||
is_null_node (expression_list[i]) ||
!side_effect_list[i]
)
{
free_node(node_allocator_,expression_list[i]);
continue;
}
else
tmp_expression_list.push_back(expression_list[i]);
}
if (!return_node_present)
{
tmp_expression_list.push_back(expression_list.back());
}
expression_list.swap(tmp_expression_list);
if (tmp_expression_list.size() > expression_list.size())
{
exprtk_debug(("simplify() - Reduced subexpressions from %d to %d\n",
static_cast<int>(tmp_expression_list.size()),
static_cast<int>(expression_list .size())));
}
if (
return_node_present ||
side_effect_list.back() ||
(expression_list.size() > 1)
)
state_.activate_side_effect("simplify()");
if (1 == expression_list.size())
return expression_list[0];
else if (specialise_on_final_type && is_generally_string_node(expression_list.back()))
return expression_generator_.vararg_function(details::e_smulti,expression_list);
else
return expression_generator_.vararg_function(details::e_multi,expression_list);
}
inline expression_node_ptr parse_multi_sequence(const std::string& source = "",
const bool enforce_crlbrackets = false)
{
token_t::token_type open_bracket = token_t::e_lcrlbracket;
token_t::token_type close_bracket = token_t::e_rcrlbracket;
token_t::token_type seperator = token_t::e_eof;
if (!token_is(open_bracket))
{
if (!enforce_crlbrackets && token_is(token_t::e_lbracket))
{
open_bracket = token_t::e_lbracket;
close_bracket = token_t::e_rbracket;
seperator = token_t::e_comma;
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR102 - Expected '" + token_t::to_str(open_bracket) + "' for call to multi-sequence" +
((!source.empty()) ? std::string(" section of " + source): ""),
exprtk_error_location));
return error_node();
}
}
else if (token_is(close_bracket))
{
return node_allocator_.allocate<details::null_node<T> >();
}
std::vector<expression_node_ptr> arg_list;
std::vector<bool> side_effect_list;
expression_node_ptr result = error_node();
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
scope_handler sh(*this);
scoped_bool_or_restorer sbr(state_.side_effect_present);
for ( ; ; )
{
state_.side_effect_present = false;
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
else
{
arg_list.push_back(arg);
side_effect_list.push_back(state_.side_effect_present);
}
if (token_is(close_bracket))
break;
const bool is_next_close = peek_token_is(close_bracket);
if (!token_is(seperator) && is_next_close)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR103 - Expected '" + details::to_str(seperator) + "' for call to multi-sequence section of " + source,
exprtk_error_location));
return error_node();
}
if (token_is(close_bracket))
break;
}
result = simplify(arg_list, side_effect_list, source.empty());
sdd.delete_ptr = (0 == result);
return result;
}
inline bool parse_range(range_t& rp, const bool skip_lsqr = false)
{
// Examples of valid ranges:
// 1. [1:5] -> 1..5
// 2. [ :5] -> 0..5
// 3. [1: ] -> 1..end
// 4. [x:y] -> x..y where x <= y
// 5. [x+1:y/2] -> x+1..y/2 where x+1 <= y/2
// 6. [ :y] -> 0..y where 0 <= y
// 7. [x: ] -> x..end where x <= end
rp.clear();
if (!skip_lsqr && !token_is(token_t::e_lsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR104 - Expected '[' for start of range",
exprtk_error_location));
return false;
}
if (token_is(token_t::e_colon))
{
rp.n0_c.first = true;
rp.n0_c.second = 0;
rp.cache.first = 0;
}
else
{
expression_node_ptr r0 = parse_expression();
if (0 == r0)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR105 - Failed parse begin section of range",
exprtk_error_location));
return false;
}
else if (is_constant_node(r0))
{
const T r0_value = r0->value();
if (r0_value >= T(0))
{
rp.n0_c.first = true;
rp.n0_c.second = static_cast<std::size_t>(details::numeric::to_int64(r0_value));
rp.cache.first = rp.n0_c.second;
}
free_node(node_allocator_,r0);
if (r0_value < T(0))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR106 - Range lower bound less than zero! Constraint: r0 >= 0",
exprtk_error_location));
return false;
}
}
else
{
rp.n0_e.first = true;
rp.n0_e.second = r0;
}
if (!token_is(token_t::e_colon))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR107 - Expected ':' for break in range",
exprtk_error_location));
rp.free();
return false;
}
}
if (token_is(token_t::e_rsqrbracket))
{
rp.n1_c.first = true;
rp.n1_c.second = std::numeric_limits<std::size_t>::max();
}
else
{
expression_node_ptr r1 = parse_expression();
if (0 == r1)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR108 - Failed parse end section of range",
exprtk_error_location));
rp.free();
return false;
}
else if (is_constant_node(r1))
{
const T r1_value = r1->value();
if (r1_value >= T(0))
{
rp.n1_c.first = true;
rp.n1_c.second = static_cast<std::size_t>(details::numeric::to_int64(r1_value));
rp.cache.second = rp.n1_c.second;
}
free_node(node_allocator_,r1);
if (r1_value < T(0))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR109 - Range upper bound less than zero! Constraint: r1 >= 0",
exprtk_error_location));
rp.free();
return false;
}
}
else
{
rp.n1_e.first = true;
rp.n1_e.second = r1;
}
if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR110 - Expected ']' for start of range",
exprtk_error_location));
rp.free();
return false;
}
}
if (rp.const_range())
{
std::size_t r0 = 0;
std::size_t r1 = 0;
bool rp_result = false;
try
{
rp_result = rp(r0, r1);
}
catch (std::runtime_error&)
{}
if (!rp_result || (r0 > r1))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR111 - Invalid range, Constraint: r0 <= r1",
exprtk_error_location));
return false;
}
}
return true;
}
inline void lodge_symbol(const std::string& symbol,
const symbol_type st)
{
dec_.add_symbol(symbol,st);
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr parse_string()
{
const std::string symbol = current_token().value;
typedef details::stringvar_node<T>* strvar_node_t;
expression_node_ptr result = error_node();
strvar_node_t const_str_node = static_cast<strvar_node_t>(0);
scope_element& se = sem_.get_active_element(symbol);
if (scope_element::e_string == se.type)
{
se.active = true;
result = se.str_node;
lodge_symbol(symbol, e_st_local_string);
}
else
{
typedef typename symtab_store::string_context str_ctxt_t;
str_ctxt_t str_ctx = symtab_store_.get_string_context(symbol);
if ((0 == str_ctx.str_var) || !symtab_store_.is_conststr_stringvar(symbol))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR112 - Unknown string symbol",
exprtk_error_location));
return error_node();
}
assert(str_ctx.str_var != 0);
assert(str_ctx.symbol_table != 0);
result = str_ctx.str_var;
if (symtab_store_.is_constant_string(symbol))
{
const_str_node = static_cast<strvar_node_t>(result);
result = expression_generator_(const_str_node->str());
}
else if (symbol_table_t::e_immutable == str_ctx.symbol_table->mutability())
{
lodge_immutable_symbol(
current_token(),
make_memory_range(str_ctx.str_var->base(), str_ctx.str_var->size()));
}
lodge_symbol(symbol, e_st_string);
}
if (peek_token_is(token_t::e_lsqrbracket))
{
next_token();
if (peek_token_is(token_t::e_rsqrbracket))
{
next_token();
next_token();
if (const_str_node)
{
free_node(node_allocator_,result);
return expression_generator_(T(const_str_node->size()));
}
else
return node_allocator_.allocate<details::stringvar_size_node<T> >
(static_cast<details::stringvar_node<T>*>(result)->ref());
}
range_t rp;
if (!parse_range(rp))
{
free_node(node_allocator_,result);
return error_node();
}
else if (const_str_node)
{
free_node(node_allocator_,result);
result = expression_generator_(const_str_node->ref(),rp);
}
else
result = expression_generator_(static_cast<details::stringvar_node<T>*>
(result)->ref(), rp);
if (result)
rp.clear();
}
else
next_token();
return result;
}
#else
inline expression_node_ptr parse_string()
{
return error_node();
}
#endif
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr parse_const_string()
{
const std::string const_str = current_token().value;
expression_node_ptr result = expression_generator_(const_str);
if (peek_token_is(token_t::e_lsqrbracket))
{
next_token();
if (peek_token_is(token_t::e_rsqrbracket))
{
next_token();
next_token();
free_node(node_allocator_,result);
return expression_generator_(T(const_str.size()));
}
range_t rp;
if (!parse_range(rp))
{
free_node(node_allocator_,result);
rp.free();
return error_node();
}
free_node(node_allocator_,result);
if (rp.n1_c.first && (rp.n1_c.second == std::numeric_limits<std::size_t>::max()))
{
rp.n1_c.second = const_str.size() - 1;
rp.cache.second = rp.n1_c.second;
}
if (
(rp.n0_c.first && (rp.n0_c.second >= const_str.size())) ||
(rp.n1_c.first && (rp.n1_c.second >= const_str.size()))
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR113 - Overflow in range for string: '" + const_str + "'[" +
(rp.n0_c.first ? details::to_str(static_cast<int>(rp.n0_c.second)) : "?") + ":" +
(rp.n1_c.first ? details::to_str(static_cast<int>(rp.n1_c.second)) : "?") + "]",
exprtk_error_location));
rp.free();
return error_node();
}
result = expression_generator_(const_str,rp);
if (result)
rp.clear();
}
else
next_token();
return result;
}
#else
inline expression_node_ptr parse_const_string()
{
return error_node();
}
#endif
inline expression_node_ptr parse_vector()
{
const std::string symbol = current_token().value;
vector_holder_ptr vec = vector_holder_ptr(0);
const scope_element& se = sem_.get_active_element(symbol);
if (
!details::imatch(se.name, symbol) ||
(se.depth > state_.scope_depth) ||
(scope_element::e_vector != se.type)
)
{
typedef typename symtab_store::vector_context vec_ctxt_t;
vec_ctxt_t vec_ctx = symtab_store_.get_vector_context(symbol);
if (0 == vec_ctx.vector_holder)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR114 - Symbol '" + symbol+ " not a vector",
exprtk_error_location));
return error_node();
}
assert(0 != vec_ctx.vector_holder);
assert(0 != vec_ctx.symbol_table );
vec = vec_ctx.vector_holder;
if (symbol_table_t::e_immutable == vec_ctx.symbol_table->mutability())
{
lodge_immutable_symbol(
current_token(),
make_memory_range(vec->data(), vec->size()));
}
}
else
vec = se.vec_node;
assert(0 != vec);
expression_node_ptr index_expr = error_node();
next_token();
if (!token_is(token_t::e_lsqrbracket))
{
return node_allocator_.allocate<vector_node_t>(vec);
}
else if (token_is(token_t::e_rsqrbracket))
{
return expression_generator_(T(vec->size()));
}
else if (0 == (index_expr = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR115 - Failed to parse index for vector: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR116 - Expected ']' for index of vector: '" + symbol + "'",
exprtk_error_location));
free_node(node_allocator_,index_expr);
return error_node();
}
// Perform compile-time range check
if (details::is_constant_node(index_expr))
{
const std::size_t index = static_cast<std::size_t>(details::numeric::to_int32(index_expr->value()));
const std::size_t vec_size = vec->size();
if (index >= vec_size)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR117 - Index of " + details::to_str(index) + " out of range for "
"vector '" + symbol + "' of size " + details::to_str(vec_size),
exprtk_error_location));
free_node(node_allocator_,index_expr);
return error_node();
}
}
return expression_generator_.vector_element(symbol, vec, index_expr);
}
inline expression_node_ptr parse_vararg_function_call(ivararg_function<T>* vararg_function, const std::string& vararg_function_name)
{
std::vector<expression_node_ptr> arg_list;
expression_node_ptr result = error_node();
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
next_token();
if (token_is(token_t::e_lbracket))
{
if (token_is(token_t::e_rbracket))
{
if (!vararg_function->allow_zero_parameters())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR118 - Zero parameter call to vararg function: "
+ vararg_function_name + " not allowed",
exprtk_error_location));
return error_node();
}
}
else
{
for ( ; ; )
{
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
else
arg_list.push_back(arg);
if (token_is(token_t::e_rbracket))
break;
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR119 - Expected ',' for call to vararg function: "
+ vararg_function_name,
exprtk_error_location));
return error_node();
}
}
}
}
else if (!vararg_function->allow_zero_parameters())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR120 - Zero parameter call to vararg function: "
+ vararg_function_name + " not allowed",
exprtk_error_location));
return error_node();
}
if (arg_list.size() < vararg_function->min_num_args())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR121 - Invalid number of parameters to call to vararg function: "
+ vararg_function_name + ", require at least "
+ details::to_str(static_cast<int>(vararg_function->min_num_args())) + " parameters",
exprtk_error_location));
return error_node();
}
else if (arg_list.size() > vararg_function->max_num_args())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR122 - Invalid number of parameters to call to vararg function: "
+ vararg_function_name + ", require no more than "
+ details::to_str(static_cast<int>(vararg_function->max_num_args())) + " parameters",
exprtk_error_location));
return error_node();
}
result = expression_generator_.vararg_function_call(vararg_function,arg_list);
sdd.delete_ptr = (0 == result);
return result;
}
class type_checker
{
public:
enum return_type_t
{
e_overload = ' ',
e_numeric = 'T',
e_string = 'S'
};
struct function_prototype_t
{
return_type_t return_type;
std::string param_seq;
};
typedef parser<T> parser_t;
typedef std::vector<function_prototype_t> function_definition_list_t;
type_checker(parser_t& p,
const std::string& func_name,
const std::string& func_prototypes,
const return_type_t default_return_type)
: invalid_state_(true)
, parser_(p)
, function_name_(func_name)
, default_return_type_(default_return_type)
{
parse_function_prototypes(func_prototypes);
}
bool verify(const std::string& param_seq, std::size_t& pseq_index)
{
if (function_definition_list_.empty())
return true;
std::vector<std::pair<std::size_t,char> > error_list;
for (std::size_t i = 0; i < function_definition_list_.size(); ++i)
{
details::char_t diff_value = 0;
std::size_t diff_index = 0;
const bool result = details::sequence_match(function_definition_list_[i].param_seq,
param_seq,
diff_index, diff_value);
if (result)
{
pseq_index = i;
return true;
}
else
error_list.push_back(std::make_pair(diff_index, diff_value));
}
if (1 == error_list.size())
{
parser_.
set_error(
make_error(parser_error::e_syntax,
parser_.current_token(),
"ERR123 - Failed parameter type check for function '" + function_name_ + "', "
"Expected '" + function_definition_list_[0].param_seq +
"' call set: '" + param_seq + "'",
exprtk_error_location));
}
else
{
// find first with largest diff_index;
std::size_t max_diff_index = 0;
for (std::size_t i = 1; i < error_list.size(); ++i)
{
if (error_list[i].first > error_list[max_diff_index].first)
{
max_diff_index = i;
}
}
parser_.
set_error(
make_error(parser_error::e_syntax,
parser_.current_token(),
"ERR124 - Failed parameter type check for function '" + function_name_ + "', "
"Best match: '" + function_definition_list_[max_diff_index].param_seq +
"' call set: '" + param_seq + "'",
exprtk_error_location));
}
return false;
}
std::size_t paramseq_count() const
{
return function_definition_list_.size();
}
std::string paramseq(const std::size_t& index) const
{
return function_definition_list_[index].param_seq;
}
return_type_t return_type(const std::size_t& index) const
{
return function_definition_list_[index].return_type;
}
bool invalid() const
{
return !invalid_state_;
}
bool allow_zero_parameters() const
{
for (std::size_t i = 0; i < function_definition_list_.size(); ++i)
{
if (std::string::npos != function_definition_list_[i].param_seq.find("Z"))
{
return true;
}
}
return false;
}
private:
std::vector<std::string> split_param_seq(const std::string& param_seq, const details::char_t delimiter = '|') const
{
std::string::const_iterator current_begin = param_seq.begin();
std::string::const_iterator iter = param_seq.begin();
std::vector<std::string> result;
while (iter != param_seq.end())
{
if (*iter == delimiter)
{
result.push_back(std::string(current_begin, iter));
current_begin = ++iter;
}
else
++iter;
}
if (current_begin != iter)
{
result.push_back(std::string(current_begin, iter));
}
return result;
}
inline bool is_valid_token(std::string param_seq,
function_prototype_t& funcproto) const
{
// Determine return type
funcproto.return_type = default_return_type_;
if (param_seq.size() > 2)
{
if (':' == param_seq[1])
{
// Note: Only overloaded igeneric functions can have return
// type definitions.
if (type_checker::e_overload != default_return_type_)
return false;
switch (param_seq[0])
{
case 'T' : funcproto.return_type = type_checker::e_numeric;
break;
case 'S' : funcproto.return_type = type_checker::e_string;
break;
default : return false;
}
param_seq.erase(0,2);
}
}
if (
(std::string::npos != param_seq.find("?*")) ||
(std::string::npos != param_seq.find("**"))
)
{
return false;
}
else if (
(std::string::npos == param_seq.find_first_not_of("STV*?|")) ||
("Z" == param_seq)
)
{
funcproto.param_seq = param_seq;
return true;
}
return false;
}
void parse_function_prototypes(const std::string& func_prototypes)
{
if (func_prototypes.empty())
return;
std::vector<std::string> param_seq_list = split_param_seq(func_prototypes);
typedef std::map<std::string,std::size_t> param_seq_map_t;
param_seq_map_t param_seq_map;
for (std::size_t i = 0; i < param_seq_list.size(); ++i)
{
function_prototype_t func_proto;
if (!is_valid_token(param_seq_list[i], func_proto))
{
invalid_state_ = false;
parser_.
set_error(
make_error(parser_error::e_syntax,
parser_.current_token(),
"ERR125 - Invalid parameter sequence of '" + param_seq_list[i] +
"' for function: " + function_name_,
exprtk_error_location));
return;
}
param_seq_map_t::const_iterator seq_itr = param_seq_map.find(param_seq_list[i]);
if (param_seq_map.end() != seq_itr)
{
invalid_state_ = false;
parser_.
set_error(
make_error(parser_error::e_syntax,
parser_.current_token(),
"ERR126 - Function '" + function_name_ + "' has a parameter sequence conflict between " +
"pseq_idx[" + details::to_str(seq_itr->second) + "] and" +
"pseq_idx[" + details::to_str(i) + "] " +
"param seq: " + param_seq_list[i],
exprtk_error_location));
return;
}
function_definition_list_.push_back(func_proto);
}
}
type_checker(const type_checker&) exprtk_delete;
type_checker& operator=(const type_checker&) exprtk_delete;
bool invalid_state_;
parser_t& parser_;
std::string function_name_;
const return_type_t default_return_type_;
function_definition_list_t function_definition_list_;
};
inline expression_node_ptr parse_generic_function_call(igeneric_function<T>* function, const std::string& function_name)
{
std::vector<expression_node_ptr> arg_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
next_token();
std::string param_type_list;
type_checker tc(
(*this),
function_name,
function->parameter_sequence,
type_checker::e_string);
if (tc.invalid())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR127 - Type checker instantiation failure for generic function: " + function_name,
exprtk_error_location));
return error_node();
}
if (token_is(token_t::e_lbracket))
{
if (token_is(token_t::e_rbracket))
{
if (
!function->allow_zero_parameters() &&
!tc .allow_zero_parameters()
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR128 - Zero parameter call to generic function: "
+ function_name + " not allowed",
exprtk_error_location));
return error_node();
}
}
else
{
for ( ; ; )
{
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
if (is_ivector_node(arg))
param_type_list += 'V';
else if (is_generally_string_node(arg))
param_type_list += 'S';
else // Everything else is assumed to be a scalar returning expression
param_type_list += 'T';
arg_list.push_back(arg);
if (token_is(token_t::e_rbracket))
break;
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR129 - Expected ',' for call to generic function: " + function_name,
exprtk_error_location));
return error_node();
}
}
}
}
else if (
!function->parameter_sequence.empty() &&
function->allow_zero_parameters () &&
!tc .allow_zero_parameters ()
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR130 - Zero parameter call to generic function: "
+ function_name + " not allowed",
exprtk_error_location));
return error_node();
}
std::size_t param_seq_index = 0;
if (
state_.type_check_enabled &&
!tc.verify(param_type_list, param_seq_index)
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR131 - Invalid input parameter sequence for call to generic function: " + function_name,
exprtk_error_location));
return error_node();
}
expression_node_ptr result = error_node();
if (tc.paramseq_count() <= 1)
result = expression_generator_
.generic_function_call(function, arg_list);
else
result = expression_generator_
.generic_function_call(function, arg_list, param_seq_index);
sdd.delete_ptr = (0 == result);
return result;
}
inline bool parse_igeneric_function_params(std::string& param_type_list,
std::vector<expression_node_ptr>& arg_list,
const std::string& function_name,
igeneric_function<T>* function,
const type_checker& tc)
{
if (token_is(token_t::e_lbracket))
{
if (token_is(token_t::e_rbracket))
{
if (
!function->allow_zero_parameters() &&
!tc .allow_zero_parameters()
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR132 - Zero parameter call to generic function: "
+ function_name + " not allowed",
exprtk_error_location));
return false;
}
}
else
{
for ( ; ; )
{
expression_node_ptr arg = parse_expression();
if (0 == arg)
return false;
if (is_ivector_node(arg))
param_type_list += 'V';
else if (is_generally_string_node(arg))
param_type_list += 'S';
else // Everything else is a scalar returning expression
param_type_list += 'T';
arg_list.push_back(arg);
if (token_is(token_t::e_rbracket))
break;
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR133 - Expected ',' for call to string function: " + function_name,
exprtk_error_location));
return false;
}
}
}
return true;
}
else
return false;
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr parse_string_function_call(igeneric_function<T>* function, const std::string& function_name)
{
// Move pass the function name
next_token();
std::string param_type_list;
type_checker tc((*this), function_name, function->parameter_sequence, type_checker::e_string);
if (
(!function->parameter_sequence.empty()) &&
(0 == tc.paramseq_count())
)
{
return error_node();
}
std::vector<expression_node_ptr> arg_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
if (!parse_igeneric_function_params(param_type_list, arg_list, function_name, function, tc))
{
return error_node();
}
std::size_t param_seq_index = 0;
if (!tc.verify(param_type_list, param_seq_index))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR134 - Invalid input parameter sequence for call to string function: " + function_name,
exprtk_error_location));
return error_node();
}
expression_node_ptr result = error_node();
if (tc.paramseq_count() <= 1)
result = expression_generator_
.string_function_call(function, arg_list);
else
result = expression_generator_
.string_function_call(function, arg_list, param_seq_index);
sdd.delete_ptr = (0 == result);
return result;
}
inline expression_node_ptr parse_overload_function_call(igeneric_function<T>* function, const std::string& function_name)
{
// Move pass the function name
next_token();
std::string param_type_list;
type_checker tc((*this), function_name, function->parameter_sequence, type_checker::e_overload);
if (
(!function->parameter_sequence.empty()) &&
(0 == tc.paramseq_count())
)
{
return error_node();
}
std::vector<expression_node_ptr> arg_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
if (!parse_igeneric_function_params(param_type_list, arg_list, function_name, function, tc))
{
return error_node();
}
std::size_t param_seq_index = 0;
if (!tc.verify(param_type_list, param_seq_index))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR135 - Invalid input parameter sequence for call to overloaded function: " + function_name,
exprtk_error_location));
return error_node();
}
expression_node_ptr result = error_node();
if (type_checker::e_numeric == tc.return_type(param_seq_index))
{
if (tc.paramseq_count() <= 1)
result = expression_generator_
.generic_function_call(function, arg_list);
else
result = expression_generator_
.generic_function_call(function, arg_list, param_seq_index);
}
else if (type_checker::e_string == tc.return_type(param_seq_index))
{
if (tc.paramseq_count() <= 1)
result = expression_generator_
.string_function_call(function, arg_list);
else
result = expression_generator_
.string_function_call(function, arg_list, param_seq_index);
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR136 - Invalid return type for call to overloaded function: " + function_name,
exprtk_error_location));
}
sdd.delete_ptr = (0 == result);
return result;
}
#endif
template <typename Type, std::size_t NumberOfParameters>
struct parse_special_function_impl
{
static inline expression_node_ptr process(parser<Type>& p, const details::operator_type opt_type, const std::string& sf_name)
{
expression_node_ptr branch[NumberOfParameters];
expression_node_ptr result = error_node();
std::fill_n(branch, NumberOfParameters, reinterpret_cast<expression_node_ptr>(0));
scoped_delete<expression_node_t,NumberOfParameters> sd(p,branch);
p.next_token();
if (!p.token_is(token_t::e_lbracket))
{
p.set_error(
make_error(parser_error::e_syntax,
p.current_token(),
"ERR137 - Expected '(' for special function '" + sf_name + "'",
exprtk_error_location));
return error_node();
}
for (std::size_t i = 0; i < NumberOfParameters; ++i)
{
branch[i] = p.parse_expression();
if (0 == branch[i])
{
return p.error_node();
}
else if (i < (NumberOfParameters - 1))
{
if (!p.token_is(token_t::e_comma))
{
p.set_error(
make_error(parser_error::e_syntax,
p.current_token(),
"ERR138 - Expected ',' before next parameter of special function '" + sf_name + "'",
exprtk_error_location));
return p.error_node();
}
}
}
if (!p.token_is(token_t::e_rbracket))
{
p.set_error(
make_error(parser_error::e_syntax,
p.current_token(),
"ERR139 - Invalid number of parameters for special function '" + sf_name + "'",
exprtk_error_location));
return p.error_node();
}
else
result = p.expression_generator_.special_function(opt_type,branch);
sd.delete_ptr = (0 == result);
return result;
}
};
inline expression_node_ptr parse_special_function()
{
const std::string sf_name = current_token().value;
// Expect: $fDD(expr0,expr1,expr2) or $fDD(expr0,expr1,expr2,expr3)
if (
!details::is_digit(sf_name[2]) ||
!details::is_digit(sf_name[3])
)
{
set_error(
make_error(parser_error::e_token,
current_token(),
"ERR140 - Invalid special function[1]: " + sf_name,
exprtk_error_location));
return error_node();
}
const int id = (sf_name[2] - '0') * 10 +
(sf_name[3] - '0');
if (id >= details::e_sffinal)
{
set_error(
make_error(parser_error::e_token,
current_token(),
"ERR141 - Invalid special function[2]: " + sf_name,
exprtk_error_location));
return error_node();
}
const int sf_3_to_4 = details::e_sf48;
const details::operator_type opt_type = details::operator_type(id + 1000);
const std::size_t NumberOfParameters = (id < (sf_3_to_4 - 1000)) ? 3U : 4U;
switch (NumberOfParameters)
{
case 3 : return parse_special_function_impl<T,3>::process((*this), opt_type, sf_name);
case 4 : return parse_special_function_impl<T,4>::process((*this), opt_type, sf_name);
default : return error_node();
}
}
inline expression_node_ptr parse_null_statement()
{
next_token();
return node_allocator_.allocate<details::null_node<T> >();
}
#ifndef exprtk_disable_break_continue
inline expression_node_ptr parse_break_statement()
{
if (state_.parsing_break_stmt)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR142 - Invoking 'break' within a break call is not allowed",
exprtk_error_location));
return error_node();
}
else if (0 == state_.parsing_loop_stmt_count)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR143 - Invalid use of 'break', allowed only in the scope of a loop",
exprtk_error_location));
return error_node();
}
scoped_bool_negator sbn(state_.parsing_break_stmt);
if (!brkcnt_list_.empty())
{
next_token();
brkcnt_list_.front() = true;
expression_node_ptr return_expr = error_node();
if (token_is(token_t::e_lsqrbracket))
{
if (0 == (return_expr = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR144 - Failed to parse return expression for 'break' statement",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR145 - Expected ']' at the completion of break's return expression",
exprtk_error_location));
free_node(node_allocator_,return_expr);
return error_node();
}
}
state_.activate_side_effect("parse_break_statement()");
return node_allocator_.allocate<details::break_node<T> >(return_expr);
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR146 - Invalid use of 'break', allowed only in the scope of a loop",
exprtk_error_location));
}
return error_node();
}
inline expression_node_ptr parse_continue_statement()
{
if (0 == state_.parsing_loop_stmt_count)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR147 - Invalid use of 'continue', allowed only in the scope of a loop",
exprtk_error_location));
return error_node();
}
else
{
next_token();
brkcnt_list_.front() = true;
state_.activate_side_effect("parse_continue_statement()");
return node_allocator_.allocate<details::continue_node<T> >();
}
}
#endif
inline expression_node_ptr parse_define_vector_statement(const std::string& vec_name)
{
expression_node_ptr size_expr = error_node();
if (!token_is(token_t::e_lsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR148 - Expected '[' as part of vector size definition",
exprtk_error_location));
return error_node();
}
else if (0 == (size_expr = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR149 - Failed to determine size of vector '" + vec_name + "'",
exprtk_error_location));
return error_node();
}
else if (!is_constant_node(size_expr))
{
free_node(node_allocator_,size_expr);
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR150 - Expected a literal number as size of vector '" + vec_name + "'",
exprtk_error_location));
return error_node();
}
const T vector_size = size_expr->value();
free_node(node_allocator_,size_expr);
const T max_vector_size = T(2000000000.0);
if (
(vector_size <= T(0)) ||
std::not_equal_to<T>()
(T(0),vector_size - details::numeric::trunc(vector_size)) ||
(vector_size > max_vector_size)
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR151 - Invalid vector size. Must be an integer in the range [0,2e9], size: " +
details::to_str(details::numeric::to_int32(vector_size)),
exprtk_error_location));
return error_node();
}
std::vector<expression_node_ptr> vec_initilizer_list;
scoped_vec_delete<expression_node_t> svd((*this),vec_initilizer_list);
bool single_value_initialiser = false;
bool vec_to_vec_initialiser = false;
bool null_initialisation = false;
if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR152 - Expected ']' as part of vector size definition",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_eof))
{
if (!token_is(token_t::e_assign))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR153 - Expected ':=' as part of vector definition",
exprtk_error_location));
return error_node();
}
else if (token_is(token_t::e_lsqrbracket))
{
expression_node_ptr initialiser = parse_expression();
if (0 == initialiser)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR154 - Failed to parse single vector initialiser",
exprtk_error_location));
return error_node();
}
vec_initilizer_list.push_back(initialiser);
if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR155 - Expected ']' to close single value vector initialiser",
exprtk_error_location));
return error_node();
}
single_value_initialiser = true;
}
else if (!token_is(token_t::e_lcrlbracket))
{
expression_node_ptr initialiser = error_node();
// Is this a vector to vector assignment and initialisation?
if (token_t::e_symbol == current_token().type)
{
// Is it a locally defined vector?
const scope_element& se = sem_.get_active_element(current_token().value);
if (scope_element::e_vector == se.type)
{
if (0 != (initialiser = parse_expression()))
vec_initilizer_list.push_back(initialiser);
else
return error_node();
}
// Are we dealing with a user defined vector?
else if (symtab_store_.is_vector(current_token().value))
{
lodge_symbol(current_token().value, e_st_vector);
if (0 != (initialiser = parse_expression()))
vec_initilizer_list.push_back(initialiser);
else
return error_node();
}
// Are we dealing with a null initialisation vector definition?
else if (token_is(token_t::e_symbol,"null"))
null_initialisation = true;
}
if (!null_initialisation)
{
if (0 == initialiser)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR156 - Expected '{' as part of vector initialiser list",
exprtk_error_location));
return error_node();
}
else
vec_to_vec_initialiser = true;
}
}
else if (!token_is(token_t::e_rcrlbracket))
{
for ( ; ; )
{
expression_node_ptr initialiser = parse_expression();
if (0 == initialiser)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR157 - Expected '{' as part of vector initialiser list",
exprtk_error_location));
return error_node();
}
else
vec_initilizer_list.push_back(initialiser);
if (token_is(token_t::e_rcrlbracket))
break;
const bool is_next_close = peek_token_is(token_t::e_rcrlbracket);
if (!token_is(token_t::e_comma) && is_next_close)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR158 - Expected ',' between vector initialisers",
exprtk_error_location));
return error_node();
}
if (token_is(token_t::e_rcrlbracket))
break;
}
}
if (
!token_is(token_t::e_rbracket , prsrhlpr_t::e_hold) &&
!token_is(token_t::e_rcrlbracket, prsrhlpr_t::e_hold) &&
!token_is(token_t::e_rsqrbracket, prsrhlpr_t::e_hold)
)
{
if (!token_is(token_t::e_eof))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR159 - Expected ';' at end of vector definition",
exprtk_error_location));
return error_node();
}
}
if (T(vec_initilizer_list.size()) > vector_size)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR160 - Initialiser list larger than the number of elements in the vector: '" + vec_name + "'",
exprtk_error_location));
return error_node();
}
}
typename symbol_table_t::vector_holder_ptr vec_holder = typename symbol_table_t::vector_holder_ptr(0);
const std::size_t vec_size = static_cast<std::size_t>(details::numeric::to_int32(vector_size));
scope_element& se = sem_.get_element(vec_name);
if (se.name == vec_name)
{
if (se.active)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR161 - Illegal redefinition of local vector: '" + vec_name + "'",
exprtk_error_location));
return error_node();
}
else if (
(se.size == vec_size) &&
(scope_element::e_vector == se.type)
)
{
vec_holder = se.vec_node;
se.active = true;
se.depth = state_.scope_depth;
se.ref_count++;
}
}
if (0 == vec_holder)
{
scope_element nse;
nse.name = vec_name;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_vector;
nse.depth = state_.scope_depth;
nse.size = vec_size;
nse.data = new T[vec_size];
nse.vec_node = new typename scope_element::vector_holder_t(reinterpret_cast<T*>(nse.data),nse.size);
if (!sem_.add_element(nse))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR162 - Failed to add new local vector '" + vec_name + "' to SEM",
exprtk_error_location));
sem_.free_element(nse);
return error_node();
}
vec_holder = nse.vec_node;
exprtk_debug(("parse_define_vector_statement() - INFO - Added new local vector: %s[%d]\n",
nse.name.c_str(),
static_cast<int>(nse.size)));
}
state_.activate_side_effect("parse_define_vector_statement()");
lodge_symbol(vec_name, e_st_local_vector);
expression_node_ptr result = error_node();
if (null_initialisation)
result = expression_generator_(T(0.0));
else if (vec_to_vec_initialiser)
{
expression_node_ptr vec_node = node_allocator_.allocate<vector_node_t>(vec_holder);
result = expression_generator_(
details::e_assign,
vec_node,
vec_initilizer_list[0]);
}
else
result = node_allocator_
.allocate<details::vector_assignment_node<T> >(
(*vec_holder)[0],
vec_size,
vec_initilizer_list,
single_value_initialiser);
svd.delete_ptr = (0 == result);
return result;
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr parse_define_string_statement(const std::string& str_name, expression_node_ptr initialisation_expression)
{
stringvar_node_t* str_node = reinterpret_cast<stringvar_node_t*>(0);
scope_element& se = sem_.get_element(str_name);
if (se.name == str_name)
{
if (se.active)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR163 - Illegal redefinition of local variable: '" + str_name + "'",
exprtk_error_location));
free_node(node_allocator_,initialisation_expression);
return error_node();
}
else if (scope_element::e_string == se.type)
{
str_node = se.str_node;
se.active = true;
se.depth = state_.scope_depth;
se.ref_count++;
}
}
if (0 == str_node)
{
scope_element nse;
nse.name = str_name;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_string;
nse.depth = state_.scope_depth;
nse.data = new std::string;
nse.str_node = new stringvar_node_t(*reinterpret_cast<std::string*>(nse.data));
if (!sem_.add_element(nse))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR164 - Failed to add new local string variable '" + str_name + "' to SEM",
exprtk_error_location));
free_node(node_allocator_,initialisation_expression);
sem_.free_element(nse);
return error_node();
}
str_node = nse.str_node;
exprtk_debug(("parse_define_string_statement() - INFO - Added new local string variable: %s\n",nse.name.c_str()));
}
lodge_symbol(str_name, e_st_local_string);
state_.activate_side_effect("parse_define_string_statement()");
expression_node_ptr branch[2] = {0};
branch[0] = str_node;
branch[1] = initialisation_expression;
return expression_generator_(details::e_assign,branch);
}
#else
inline expression_node_ptr parse_define_string_statement(const std::string&, expression_node_ptr)
{
return error_node();
}
#endif
inline bool local_variable_is_shadowed(const std::string& symbol)
{
const scope_element& se = sem_.get_element(symbol);
return (se.name == symbol) && se.active;
}
inline expression_node_ptr parse_define_var_statement()
{
if (settings_.vardef_disabled())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR165 - Illegal variable definition",
exprtk_error_location));
return error_node();
}
else if (!details::imatch(current_token().value,"var"))
{
return error_node();
}
else
next_token();
const std::string var_name = current_token().value;
expression_node_ptr initialisation_expression = error_node();
if (!token_is(token_t::e_symbol))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR166 - Expected a symbol for variable definition",
exprtk_error_location));
return error_node();
}
else if (details::is_reserved_symbol(var_name))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR167 - Illegal redefinition of reserved keyword: '" + var_name + "'",
exprtk_error_location));
return error_node();
}
else if (symtab_store_.symbol_exists(var_name))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR168 - Illegal redefinition of variable '" + var_name + "'",
exprtk_error_location));
return error_node();
}
else if (local_variable_is_shadowed(var_name))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR169 - Illegal redefinition of local variable: '" + var_name + "'",
exprtk_error_location));
return error_node();
}
else if (token_is(token_t::e_lsqrbracket,prsrhlpr_t::e_hold))
{
return parse_define_vector_statement(var_name);
}
else if (token_is(token_t::e_lcrlbracket,prsrhlpr_t::e_hold))
{
return parse_uninitialised_var_statement(var_name);
}
else if (token_is(token_t::e_assign))
{
if (0 == (initialisation_expression = parse_expression()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR170 - Failed to parse initialisation expression",
exprtk_error_location));
return error_node();
}
}
if (
!token_is(token_t::e_rbracket , prsrhlpr_t::e_hold) &&
!token_is(token_t::e_rcrlbracket, prsrhlpr_t::e_hold) &&
!token_is(token_t::e_rsqrbracket, prsrhlpr_t::e_hold)
)
{
if (!token_is(token_t::e_eof,prsrhlpr_t::e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR171 - Expected ';' after variable definition",
exprtk_error_location));
free_node(node_allocator_,initialisation_expression);
return error_node();
}
}
if (
(0 != initialisation_expression) &&
details::is_generally_string_node(initialisation_expression)
)
{
return parse_define_string_statement(var_name,initialisation_expression);
}
expression_node_ptr var_node = reinterpret_cast<expression_node_ptr>(0);
scope_element& se = sem_.get_element(var_name);
if (se.name == var_name)
{
if (se.active)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR172 - Illegal redefinition of local variable: '" + var_name + "'",
exprtk_error_location));
free_node(node_allocator_, initialisation_expression);
return error_node();
}
else if (scope_element::e_variable == se.type)
{
var_node = se.var_node;
se.active = true;
se.depth = state_.scope_depth;
se.ref_count++;
}
}
if (0 == var_node)
{
scope_element nse;
nse.name = var_name;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_variable;
nse.depth = state_.scope_depth;
nse.data = new T(T(0));
nse.var_node = node_allocator_.allocate<variable_node_t>(*reinterpret_cast<T*>(nse.data));
if (!sem_.add_element(nse))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR173 - Failed to add new local variable '" + var_name + "' to SEM",
exprtk_error_location));
free_node(node_allocator_, initialisation_expression);
sem_.free_element(nse);
return error_node();
}
var_node = nse.var_node;
exprtk_debug(("parse_define_var_statement() - INFO - Added new local variable: %s\n",nse.name.c_str()));
}
state_.activate_side_effect("parse_define_var_statement()");
lodge_symbol(var_name, e_st_local_variable);
expression_node_ptr branch[2] = {0};
branch[0] = var_node;
branch[1] = initialisation_expression ? initialisation_expression : expression_generator_(T(0));
return expression_generator_(details::e_assign,branch);
}
inline expression_node_ptr parse_uninitialised_var_statement(const std::string& var_name)
{
if (
!token_is(token_t::e_lcrlbracket) ||
!token_is(token_t::e_rcrlbracket)
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR174 - Expected a '{}' for uninitialised var definition",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_eof,prsrhlpr_t::e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR175 - Expected ';' after uninitialised variable definition",
exprtk_error_location));
return error_node();
}
expression_node_ptr var_node = reinterpret_cast<expression_node_ptr>(0);
scope_element& se = sem_.get_element(var_name);
if (se.name == var_name)
{
if (se.active)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR176 - Illegal redefinition of local variable: '" + var_name + "'",
exprtk_error_location));
return error_node();
}
else if (scope_element::e_variable == se.type)
{
var_node = se.var_node;
se.active = true;
se.ref_count++;
}
}
if (0 == var_node)
{
scope_element nse;
nse.name = var_name;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_variable;
nse.depth = state_.scope_depth;
nse.ip_index = sem_.next_ip_index();
nse.data = new T(T(0));
nse.var_node = node_allocator_.allocate<variable_node_t>(*reinterpret_cast<T*>(nse.data));
if (!sem_.add_element(nse))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR177 - Failed to add new local variable '" + var_name + "' to SEM",
exprtk_error_location));
sem_.free_element(nse);
return error_node();
}
exprtk_debug(("parse_uninitialised_var_statement() - INFO - Added new local variable: %s\n",
nse.name.c_str()));
}
lodge_symbol(var_name, e_st_local_variable);
state_.activate_side_effect("parse_uninitialised_var_statement()");
return expression_generator_(T(0));
}
inline expression_node_ptr parse_swap_statement()
{
if (!details::imatch(current_token().value,"swap"))
{
return error_node();
}
else
next_token();
if (!token_is(token_t::e_lbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR178 - Expected '(' at start of swap statement",
exprtk_error_location));
return error_node();
}
expression_node_ptr variable0 = error_node();
expression_node_ptr variable1 = error_node();
bool variable0_generated = false;
bool variable1_generated = false;
const std::string var0_name = current_token().value;
if (!token_is(token_t::e_symbol,prsrhlpr_t::e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR179 - Expected a symbol for variable or vector element definition",
exprtk_error_location));
return error_node();
}
else if (peek_token_is(token_t::e_lsqrbracket))
{
if (0 == (variable0 = parse_vector()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR180 - First parameter to swap is an invalid vector element: '" + var0_name + "'",
exprtk_error_location));
return error_node();
}
variable0_generated = true;
}
else
{
if (symtab_store_.is_variable(var0_name))
{
variable0 = symtab_store_.get_variable(var0_name);
}
const scope_element& se = sem_.get_element(var0_name);
if (
(se.active) &&
(se.name == var0_name) &&
(scope_element::e_variable == se.type)
)
{
variable0 = se.var_node;
}
lodge_symbol(var0_name, e_st_variable);
if (0 == variable0)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR181 - First parameter to swap is an invalid variable: '" + var0_name + "'",
exprtk_error_location));
return error_node();
}
else
next_token();
}
if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR182 - Expected ',' between parameters to swap",
exprtk_error_location));
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
return error_node();
}
const std::string var1_name = current_token().value;
if (!token_is(token_t::e_symbol,prsrhlpr_t::e_hold))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR183 - Expected a symbol for variable or vector element definition",
exprtk_error_location));
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
return error_node();
}
else if (peek_token_is(token_t::e_lsqrbracket))
{
if (0 == (variable1 = parse_vector()))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR184 - Second parameter to swap is an invalid vector element: '" + var1_name + "'",
exprtk_error_location));
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
return error_node();
}
variable1_generated = true;
}
else
{
if (symtab_store_.is_variable(var1_name))
{
variable1 = symtab_store_.get_variable(var1_name);
}
const scope_element& se = sem_.get_element(var1_name);
if (
(se.active) &&
(se.name == var1_name) &&
(scope_element::e_variable == se.type)
)
{
variable1 = se.var_node;
}
lodge_symbol(var1_name, e_st_variable);
if (0 == variable1)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR185 - Second parameter to swap is an invalid variable: '" + var1_name + "'",
exprtk_error_location));
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
return error_node();
}
else
next_token();
}
if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR186 - Expected ')' at end of swap statement",
exprtk_error_location));
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
if (variable1_generated)
{
free_node(node_allocator_,variable1);
}
return error_node();
}
typedef details::variable_node<T>* variable_node_ptr;
variable_node_ptr v0 = variable_node_ptr(0);
variable_node_ptr v1 = variable_node_ptr(0);
expression_node_ptr result = error_node();
if (
(0 != (v0 = dynamic_cast<variable_node_ptr>(variable0))) &&
(0 != (v1 = dynamic_cast<variable_node_ptr>(variable1)))
)
{
result = node_allocator_.allocate<details::swap_node<T> >(v0, v1);
if (variable0_generated)
{
free_node(node_allocator_,variable0);
}
if (variable1_generated)
{
free_node(node_allocator_,variable1);
}
}
else
result = node_allocator_.allocate<details::swap_generic_node<T> >
(variable0, variable1);
state_.activate_side_effect("parse_swap_statement()");
return result;
}
#ifndef exprtk_disable_return_statement
inline expression_node_ptr parse_return_statement()
{
if (state_.parsing_return_stmt)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR187 - Return call within a return call is not allowed",
exprtk_error_location));
return error_node();
}
scoped_bool_negator sbn(state_.parsing_return_stmt);
std::vector<expression_node_ptr> arg_list;
scoped_vec_delete<expression_node_t> sdd((*this),arg_list);
if (!details::imatch(current_token().value,"return"))
{
return error_node();
}
else
next_token();
if (!token_is(token_t::e_lsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR188 - Expected '[' at start of return statement",
exprtk_error_location));
return error_node();
}
else if (!token_is(token_t::e_rsqrbracket))
{
for ( ; ; )
{
expression_node_ptr arg = parse_expression();
if (0 == arg)
return error_node();
arg_list.push_back(arg);
if (token_is(token_t::e_rsqrbracket))
break;
else if (!token_is(token_t::e_comma))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR189 - Expected ',' between values during call to return",
exprtk_error_location));
return error_node();
}
}
}
else if (settings_.zero_return_disabled())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR190 - Zero parameter return statement not allowed",
exprtk_error_location));
return error_node();
}
const lexer::token prev_token = current_token();
if (token_is(token_t::e_rsqrbracket))
{
if (!arg_list.empty())
{
set_error(
make_error(parser_error::e_syntax,
prev_token,
"ERR191 - Invalid ']' found during return call",
exprtk_error_location));
return error_node();
}
}
std::string ret_param_type_list;
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
if (0 == arg_list[i])
return error_node();
else if (is_ivector_node(arg_list[i]))
ret_param_type_list += 'V';
else if (is_generally_string_node(arg_list[i]))
ret_param_type_list += 'S';
else
ret_param_type_list += 'T';
}
dec_.retparam_list_.push_back(ret_param_type_list);
expression_node_ptr result = expression_generator_.return_call(arg_list);
sdd.delete_ptr = (0 == result);
state_.return_stmt_present = true;
state_.activate_side_effect("parse_return_statement()");
return result;
}
#else
inline expression_node_ptr parse_return_statement()
{
return error_node();
}
#endif
inline bool post_variable_process(const std::string& symbol)
{
if (
peek_token_is(token_t::e_lbracket ) ||
peek_token_is(token_t::e_lcrlbracket) ||
peek_token_is(token_t::e_lsqrbracket)
)
{
if (!settings_.commutative_check_enabled())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR192 - Invalid sequence of variable '" + symbol + "' and bracket",
exprtk_error_location));
return false;
}
lexer().insert_front(token_t::e_mul);
}
return true;
}
inline bool post_bracket_process(const typename token_t::token_type& token, expression_node_ptr& branch)
{
bool implied_mul = false;
if (details::is_generally_string_node(branch))
return true;
const lexer::parser_helper::token_advance_mode hold = prsrhlpr_t::e_hold;
switch (token)
{
case token_t::e_lcrlbracket : implied_mul = token_is(token_t::e_lbracket ,hold) ||
token_is(token_t::e_lcrlbracket,hold) ||
token_is(token_t::e_lsqrbracket,hold) ;
break;
case token_t::e_lbracket : implied_mul = token_is(token_t::e_lbracket ,hold) ||
token_is(token_t::e_lcrlbracket,hold) ||
token_is(token_t::e_lsqrbracket,hold) ;
break;
case token_t::e_lsqrbracket : implied_mul = token_is(token_t::e_lbracket ,hold) ||
token_is(token_t::e_lcrlbracket,hold) ||
token_is(token_t::e_lsqrbracket,hold) ;
break;
default : return true;
}
if (implied_mul)
{
if (!settings_.commutative_check_enabled())
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR193 - Invalid sequence of brackets",
exprtk_error_location));
return false;
}
else if (token_t::e_eof != current_token().type)
{
lexer().insert_front(current_token().type);
lexer().insert_front(token_t::e_mul);
next_token();
}
}
return true;
}
typedef typename interval_container_t<const void*>::interval_t interval_t;
typedef interval_container_t<const void*> immutable_memory_map_t;
typedef std::map<interval_t,token_t> immutable_symtok_map_t;
inline interval_t make_memory_range(const T& t)
{
const T* begin = reinterpret_cast<const T*>(&t);
const T* end = begin + 1;
return interval_t(begin, end);
}
inline interval_t make_memory_range(const T* begin, const std::size_t size)
{
return interval_t(begin, begin + size);
}
inline interval_t make_memory_range(details::char_cptr begin, const std::size_t size)
{
return interval_t(begin, begin + size);
}
void lodge_immutable_symbol(const lexer::token& token, const interval_t interval)
{
immutable_memory_map_.add_interval(interval);
immutable_symtok_map_[interval] = token;
}
inline expression_node_ptr parse_symtab_symbol()
{
const std::string symbol = current_token().value;
// Are we dealing with a variable or a special constant?
typedef typename symtab_store::variable_context var_ctxt_t;
var_ctxt_t var_ctx = symtab_store_.get_variable_context(symbol);
if (var_ctx.variable)
{
assert(var_ctx.symbol_table);
expression_node_ptr result_variable = var_ctx.variable;
if (symtab_store_.is_constant_node(symbol))
{
result_variable = expression_generator_(var_ctx.variable->value());
}
else if (symbol_table_t::e_immutable == var_ctx.symbol_table->mutability())
{
lodge_immutable_symbol(current_token(), make_memory_range(var_ctx.variable->ref()));
result_variable = var_ctx.variable;
}
if (!post_variable_process(symbol))
return error_node();
lodge_symbol(symbol, e_st_variable);
next_token();
return result_variable;
}
// Are we dealing with a locally defined variable, vector or string?
if (!sem_.empty())
{
scope_element& se = sem_.get_active_element(symbol);
if (se.active && details::imatch(se.name, symbol))
{
if (scope_element::e_variable == se.type)
{
se.active = true;
lodge_symbol(symbol, e_st_local_variable);
if (!post_variable_process(symbol))
return error_node();
next_token();
return se.var_node;
}
else if (scope_element::e_vector == se.type)
{
return parse_vector();
}
#ifndef exprtk_disable_string_capabilities
else if (scope_element::e_string == se.type)
{
return parse_string();
}
#endif
}
}
#ifndef exprtk_disable_string_capabilities
// Are we dealing with a string variable?
if (symtab_store_.is_stringvar(symbol))
{
return parse_string();
}
#endif
{
// Are we dealing with a function?
ifunction<T>* function = symtab_store_.get_function(symbol);
if (function)
{
lodge_symbol(symbol, e_st_function);
expression_node_ptr func_node =
parse_function_invocation(function,symbol);
if (func_node)
return func_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR194 - Failed to generate node for function: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
}
{
// Are we dealing with a vararg function?
ivararg_function<T>* vararg_function = symtab_store_.get_vararg_function(symbol);
if (vararg_function)
{
lodge_symbol(symbol, e_st_function);
expression_node_ptr vararg_func_node =
parse_vararg_function_call(vararg_function, symbol);
if (vararg_func_node)
return vararg_func_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR195 - Failed to generate node for vararg function: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
}
{
// Are we dealing with a vararg generic function?
igeneric_function<T>* generic_function = symtab_store_.get_generic_function(symbol);
if (generic_function)
{
lodge_symbol(symbol, e_st_function);
expression_node_ptr genericfunc_node =
parse_generic_function_call(generic_function, symbol);
if (genericfunc_node)
return genericfunc_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR196 - Failed to generate node for generic function: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
}
#ifndef exprtk_disable_string_capabilities
{
// Are we dealing with a vararg string returning function?
igeneric_function<T>* string_function = symtab_store_.get_string_function(symbol);
if (string_function)
{
lodge_symbol(symbol, e_st_function);
expression_node_ptr stringfunc_node =
parse_string_function_call(string_function, symbol);
if (stringfunc_node)
return stringfunc_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR197 - Failed to generate node for string function: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
}
{
// Are we dealing with a vararg overloaded scalar/string returning function?
igeneric_function<T>* overload_function = symtab_store_.get_overload_function(symbol);
if (overload_function)
{
lodge_symbol(symbol, e_st_function);
expression_node_ptr overloadfunc_node =
parse_overload_function_call(overload_function, symbol);
if (overloadfunc_node)
return overloadfunc_node;
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR198 - Failed to generate node for overload function: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
}
#endif
// Are we dealing with a vector?
if (symtab_store_.is_vector(symbol))
{
lodge_symbol(symbol, e_st_vector);
return parse_vector();
}
if (details::is_reserved_symbol(symbol))
{
if (
settings_.function_enabled(symbol) ||
!details::is_base_function(symbol)
)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR199 - Invalid use of reserved symbol '" + symbol + "'",
exprtk_error_location));
return error_node();
}
}
// Should we handle unknown symbols?
if (resolve_unknown_symbol_ && unknown_symbol_resolver_)
{
if (!(settings_.rsrvd_sym_usr_disabled() && details::is_reserved_symbol(symbol)))
{
symbol_table_t& symtab = symtab_store_.get_symbol_table();
std::string error_message;
if (unknown_symbol_resolver::e_usrmode_default == unknown_symbol_resolver_->mode)
{
T default_value = T(0);
typename unknown_symbol_resolver::usr_symbol_type usr_symbol_type = unknown_symbol_resolver::e_usr_unknown_type;
if (unknown_symbol_resolver_->process(symbol, usr_symbol_type, default_value, error_message))
{
bool create_result = false;
switch (usr_symbol_type)
{
case unknown_symbol_resolver::e_usr_variable_type : create_result = symtab.create_variable(symbol, default_value);
break;
case unknown_symbol_resolver::e_usr_constant_type : create_result = symtab.add_constant(symbol, default_value);
break;
default : create_result = false;
}
if (create_result)
{
expression_node_ptr var = symtab_store_.get_variable(symbol);
if (var)
{
if (symtab_store_.is_constant_node(symbol))
{
var = expression_generator_(var->value());
}
lodge_symbol(symbol, e_st_variable);
if (!post_variable_process(symbol))
return error_node();
next_token();
return var;
}
}
}
set_error(
make_error(parser_error::e_symtab,
current_token(),
"ERR200 - Failed to create variable: '" + symbol + "'" +
(error_message.empty() ? "" : " - " + error_message),
exprtk_error_location));
}
else if (unknown_symbol_resolver::e_usrmode_extended == unknown_symbol_resolver_->mode)
{
if (unknown_symbol_resolver_->process(symbol, symtab, error_message))
{
expression_node_ptr result = parse_symtab_symbol();
if (result)
{
return result;
}
}
set_error(
make_error(parser_error::e_symtab,
current_token(),
"ERR201 - Failed to resolve symbol: '" + symbol + "'" +
(error_message.empty() ? "" : " - " + error_message),
exprtk_error_location));
}
return error_node();
}
}
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR202 - Undefined symbol: '" + symbol + "'",
exprtk_error_location));
return error_node();
}
inline expression_node_ptr parse_symbol()
{
static const std::string symbol_if = "if" ;
static const std::string symbol_while = "while" ;
static const std::string symbol_repeat = "repeat" ;
static const std::string symbol_for = "for" ;
static const std::string symbol_switch = "switch" ;
static const std::string symbol_null = "null" ;
static const std::string symbol_break = "break" ;
static const std::string symbol_continue = "continue";
static const std::string symbol_var = "var" ;
static const std::string symbol_swap = "swap" ;
static const std::string symbol_return = "return" ;
static const std::string symbol_not = "not" ;
const std::string symbol = current_token().value;
if (valid_vararg_operation(symbol))
{
return parse_vararg_function();
}
else if (details::imatch(symbol, symbol_not))
{
return parse_not_statement();
}
else if (valid_base_operation(symbol))
{
return parse_base_operation();
}
else if (
details::imatch(symbol, symbol_if) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_conditional_statement();
}
else if (
details::imatch(symbol, symbol_while) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_while_loop();
}
else if (
details::imatch(symbol, symbol_repeat) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_repeat_until_loop();
}
else if (
details::imatch(symbol, symbol_for) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_for_loop();
}
else if (
details::imatch(symbol, symbol_switch) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_switch_statement();
}
else if (details::is_valid_sf_symbol(symbol))
{
return parse_special_function();
}
else if (details::imatch(symbol, symbol_null))
{
return parse_null_statement();
}
#ifndef exprtk_disable_break_continue
else if (details::imatch(symbol, symbol_break))
{
return parse_break_statement();
}
else if (details::imatch(symbol, symbol_continue))
{
return parse_continue_statement();
}
#endif
else if (details::imatch(symbol, symbol_var))
{
return parse_define_var_statement();
}
else if (details::imatch(symbol, symbol_swap))
{
return parse_swap_statement();
}
#ifndef exprtk_disable_return_statement
else if (
details::imatch(symbol, symbol_return) &&
settings_.control_struct_enabled(symbol)
)
{
return parse_return_statement();
}
#endif
else if (symtab_store_.valid() || !sem_.empty())
{
return parse_symtab_symbol();
}
else
{
set_error(
make_error(parser_error::e_symtab,
current_token(),
"ERR203 - Variable or function detected, yet symbol-table is invalid, Symbol: " + symbol,
exprtk_error_location));
return error_node();
}
}
inline expression_node_ptr parse_branch(precedence_level precedence = e_level00)
{
stack_limit_handler slh(*this);
if (!slh)
{
return error_node();
}
expression_node_ptr branch = error_node();
if (token_t::e_number == current_token().type)
{
T numeric_value = T(0);
if (details::string_to_real(current_token().value, numeric_value))
{
expression_node_ptr literal_exp = expression_generator_(numeric_value);
if (0 == literal_exp)
{
set_error(
make_error(parser_error::e_numeric,
current_token(),
"ERR204 - Failed generate node for scalar: '" + current_token().value + "'",
exprtk_error_location));
return error_node();
}
next_token();
branch = literal_exp;
}
else
{
set_error(
make_error(parser_error::e_numeric,
current_token(),
"ERR205 - Failed to convert '" + current_token().value + "' to a number",
exprtk_error_location));
return error_node();
}
}
else if (token_t::e_symbol == current_token().type)
{
branch = parse_symbol();
}
#ifndef exprtk_disable_string_capabilities
else if (token_t::e_string == current_token().type)
{
branch = parse_const_string();
}
#endif
else if (token_t::e_lbracket == current_token().type)
{
next_token();
if (0 == (branch = parse_expression()))
return error_node();
else if (!token_is(token_t::e_rbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR206 - Expected ')' instead of: '" + current_token().value + "'",
exprtk_error_location));
details::free_node(node_allocator_,branch);
return error_node();
}
else if (!post_bracket_process(token_t::e_lbracket,branch))
{
details::free_node(node_allocator_,branch);
return error_node();
}
}
else if (token_t::e_lsqrbracket == current_token().type)
{
next_token();
if (0 == (branch = parse_expression()))
return error_node();
else if (!token_is(token_t::e_rsqrbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR207 - Expected ']' instead of: '" + current_token().value + "'",
exprtk_error_location));
details::free_node(node_allocator_,branch);
return error_node();
}
else if (!post_bracket_process(token_t::e_lsqrbracket,branch))
{
details::free_node(node_allocator_,branch);
return error_node();
}
}
else if (token_t::e_lcrlbracket == current_token().type)
{
next_token();
if (0 == (branch = parse_expression()))
return error_node();
else if (!token_is(token_t::e_rcrlbracket))
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR208 - Expected '}' instead of: '" + current_token().value + "'",
exprtk_error_location));
details::free_node(node_allocator_,branch);
return error_node();
}
else if (!post_bracket_process(token_t::e_lcrlbracket,branch))
{
details::free_node(node_allocator_,branch);
return error_node();
}
}
else if (token_t::e_sub == current_token().type)
{
next_token();
branch = parse_expression(e_level11);
if (
branch &&
!(
details::is_neg_unary_node (branch) &&
simplify_unary_negation_branch(branch)
)
)
{
expression_node_ptr result = expression_generator_(details::e_neg,branch);
if (0 == result)
{
details::free_node(node_allocator_,branch);
return error_node();
}
else
branch = result;
}
}
else if (token_t::e_add == current_token().type)
{
next_token();
branch = parse_expression(e_level13);
}
else if (token_t::e_eof == current_token().type)
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR209 - Premature end of expression[1]",
exprtk_error_location));
return error_node();
}
else
{
set_error(
make_error(parser_error::e_syntax,
current_token(),
"ERR210 - Premature end of expression[2]",
exprtk_error_location));
return error_node();
}
if (
branch &&
(e_level00 == precedence) &&
token_is(token_t::e_ternary,prsrhlpr_t::e_hold)
)
{
branch = parse_ternary_conditional_statement(branch);
}
parse_pending_string_rangesize(branch);
return branch;
}
template <typename Type>
class expression_generator
{
public:
typedef details::expression_node<Type>* expression_node_ptr;
typedef expression_node_ptr (*synthesize_functor_t)(expression_generator<T>&, const details::operator_type& operation, expression_node_ptr (&branch)[2]);
typedef std::map<std::string,synthesize_functor_t> synthesize_map_t;
typedef typename exprtk::parser<Type> parser_t;
typedef const Type& vtype;
typedef const Type ctype;
inline void init_synthesize_map()
{
#ifndef exprtk_disable_enhanced_features
synthesize_map_["(v)o(v)"] = synthesize_vov_expression::process;
synthesize_map_["(c)o(v)"] = synthesize_cov_expression::process;
synthesize_map_["(v)o(c)"] = synthesize_voc_expression::process;
#define register_synthezier(S) \
synthesize_map_[S ::node_type::id()] = S ::process; \
register_synthezier(synthesize_vovov_expression0)
register_synthezier(synthesize_vovov_expression1)
register_synthezier(synthesize_vovoc_expression0)
register_synthezier(synthesize_vovoc_expression1)
register_synthezier(synthesize_vocov_expression0)
register_synthezier(synthesize_vocov_expression1)
register_synthezier(synthesize_covov_expression0)
register_synthezier(synthesize_covov_expression1)
register_synthezier(synthesize_covoc_expression0)
register_synthezier(synthesize_covoc_expression1)
register_synthezier(synthesize_cocov_expression1)
register_synthezier(synthesize_vococ_expression0)
register_synthezier(synthesize_vovovov_expression0)
register_synthezier(synthesize_vovovoc_expression0)
register_synthezier(synthesize_vovocov_expression0)
register_synthezier(synthesize_vocovov_expression0)
register_synthezier(synthesize_covovov_expression0)
register_synthezier(synthesize_covocov_expression0)
register_synthezier(synthesize_vocovoc_expression0)
register_synthezier(synthesize_covovoc_expression0)
register_synthezier(synthesize_vococov_expression0)
register_synthezier(synthesize_vovovov_expression1)
register_synthezier(synthesize_vovovoc_expression1)
register_synthezier(synthesize_vovocov_expression1)
register_synthezier(synthesize_vocovov_expression1)
register_synthezier(synthesize_covovov_expression1)
register_synthezier(synthesize_covocov_expression1)
register_synthezier(synthesize_vocovoc_expression1)
register_synthezier(synthesize_covovoc_expression1)
register_synthezier(synthesize_vococov_expression1)
register_synthezier(synthesize_vovovov_expression2)
register_synthezier(synthesize_vovovoc_expression2)
register_synthezier(synthesize_vovocov_expression2)
register_synthezier(synthesize_vocovov_expression2)
register_synthezier(synthesize_covovov_expression2)
register_synthezier(synthesize_covocov_expression2)
register_synthezier(synthesize_vocovoc_expression2)
register_synthezier(synthesize_covovoc_expression2)
register_synthezier(synthesize_vovovov_expression3)
register_synthezier(synthesize_vovovoc_expression3)
register_synthezier(synthesize_vovocov_expression3)
register_synthezier(synthesize_vocovov_expression3)
register_synthezier(synthesize_covovov_expression3)
register_synthezier(synthesize_covocov_expression3)
register_synthezier(synthesize_vocovoc_expression3)
register_synthezier(synthesize_covovoc_expression3)
register_synthezier(synthesize_vococov_expression3)
register_synthezier(synthesize_vovovov_expression4)
register_synthezier(synthesize_vovovoc_expression4)
register_synthezier(synthesize_vovocov_expression4)
register_synthezier(synthesize_vocovov_expression4)
register_synthezier(synthesize_covovov_expression4)
register_synthezier(synthesize_covocov_expression4)
register_synthezier(synthesize_vocovoc_expression4)
register_synthezier(synthesize_covovoc_expression4)
#endif
}
inline void set_parser(parser_t& p)
{
parser_ = &p;
}
inline void set_uom(unary_op_map_t& unary_op_map)
{
unary_op_map_ = &unary_op_map;
}
inline void set_bom(binary_op_map_t& binary_op_map)
{
binary_op_map_ = &binary_op_map;
}
inline void set_ibom(inv_binary_op_map_t& inv_binary_op_map)
{
inv_binary_op_map_ = &inv_binary_op_map;
}
inline void set_sf3m(sf3_map_t& sf3_map)
{
sf3_map_ = &sf3_map;
}
inline void set_sf4m(sf4_map_t& sf4_map)
{
sf4_map_ = &sf4_map;
}
inline void set_allocator(details::node_allocator& na)
{
node_allocator_ = &na;
}
inline void set_strength_reduction_state(const bool enabled)
{
strength_reduction_enabled_ = enabled;
}
inline bool strength_reduction_enabled() const
{
return strength_reduction_enabled_;
}
inline bool valid_operator(const details::operator_type& operation, binary_functor_t& bop)
{
typename binary_op_map_t::iterator bop_itr = binary_op_map_->find(operation);
if ((*binary_op_map_).end() == bop_itr)
return false;
bop = bop_itr->second;
return true;
}
inline bool valid_operator(const details::operator_type& operation, unary_functor_t& uop)
{
typename unary_op_map_t::iterator uop_itr = unary_op_map_->find(operation);
if ((*unary_op_map_).end() == uop_itr)
return false;
uop = uop_itr->second;
return true;
}
inline details::operator_type get_operator(const binary_functor_t& bop) const
{
return (*inv_binary_op_map_).find(bop)->second;
}
inline expression_node_ptr operator() (const Type& v) const
{
return node_allocator_->allocate<literal_node_t>(v);
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr operator() (const std::string& s) const
{
return node_allocator_->allocate<string_literal_node_t>(s);
}
inline expression_node_ptr operator() (std::string& s, range_t& rp) const
{
return node_allocator_->allocate_rr<string_range_node_t>(s,rp);
}
inline expression_node_ptr operator() (const std::string& s, range_t& rp) const
{
return node_allocator_->allocate_tt<const_string_range_node_t>(s,rp);
}
inline expression_node_ptr operator() (expression_node_ptr branch, range_t& rp) const
{
if (is_generally_string_node(branch))
return node_allocator_->allocate_tt<generic_string_range_node_t>(branch,rp);
else
return error_node();
}
#endif
inline bool unary_optimisable(const details::operator_type& operation) const
{
return (details::e_abs == operation) || (details::e_acos == operation) ||
(details::e_acosh == operation) || (details::e_asin == operation) ||
(details::e_asinh == operation) || (details::e_atan == operation) ||
(details::e_atanh == operation) || (details::e_ceil == operation) ||
(details::e_cos == operation) || (details::e_cosh == operation) ||
(details::e_exp == operation) || (details::e_expm1 == operation) ||
(details::e_floor == operation) || (details::e_log == operation) ||
(details::e_log10 == operation) || (details::e_log2 == operation) ||
(details::e_log1p == operation) || (details::e_neg == operation) ||
(details::e_pos == operation) || (details::e_round == operation) ||
(details::e_sin == operation) || (details::e_sinc == operation) ||
(details::e_sinh == operation) || (details::e_sqrt == operation) ||
(details::e_tan == operation) || (details::e_tanh == operation) ||
(details::e_cot == operation) || (details::e_sec == operation) ||
(details::e_csc == operation) || (details::e_r2d == operation) ||
(details::e_d2r == operation) || (details::e_d2g == operation) ||
(details::e_g2d == operation) || (details::e_notl == operation) ||
(details::e_sgn == operation) || (details::e_erf == operation) ||
(details::e_erfc == operation) || (details::e_ncdf == operation) ||
(details::e_frac == operation) || (details::e_trunc == operation) ;
}
inline bool sf3_optimisable(const std::string& sf3id, trinary_functor_t& tfunc) const
{
typename sf3_map_t::const_iterator itr = sf3_map_->find(sf3id);
if (sf3_map_->end() == itr)
return false;
else
tfunc = itr->second.first;
return true;
}
inline bool sf4_optimisable(const std::string& sf4id, quaternary_functor_t& qfunc) const
{
typename sf4_map_t::const_iterator itr = sf4_map_->find(sf4id);
if (sf4_map_->end() == itr)
return false;
else
qfunc = itr->second.first;
return true;
}
inline bool sf3_optimisable(const std::string& sf3id, details::operator_type& operation) const
{
typename sf3_map_t::const_iterator itr = sf3_map_->find(sf3id);
if (sf3_map_->end() == itr)
return false;
else
operation = itr->second.second;
return true;
}
inline bool sf4_optimisable(const std::string& sf4id, details::operator_type& operation) const
{
typename sf4_map_t::const_iterator itr = sf4_map_->find(sf4id);
if (sf4_map_->end() == itr)
return false;
else
operation = itr->second.second;
return true;
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr (&branch)[1])
{
if (0 == branch[0])
{
return error_node();
}
else if (details::is_null_node(branch[0]))
{
return branch[0];
}
else if (details::is_break_node(branch[0]))
{
return error_node();
}
else if (details::is_continue_node(branch[0]))
{
return error_node();
}
else if (details::is_constant_node(branch[0]))
{
return synthesize_expression<unary_node_t,1>(operation,branch);
}
else if (unary_optimisable(operation) && details::is_variable_node(branch[0]))
{
return synthesize_uv_expression(operation,branch);
}
else if (unary_optimisable(operation) && details::is_ivector_node(branch[0]))
{
return synthesize_uvec_expression(operation,branch);
}
else
return synthesize_unary_expression(operation,branch);
}
inline bool is_assignment_operation(const details::operator_type& operation) const
{
return (
(details::e_addass == operation) ||
(details::e_subass == operation) ||
(details::e_mulass == operation) ||
(details::e_divass == operation) ||
(details::e_modass == operation)
) &&
parser_->settings_.assignment_enabled(operation);
}
#ifndef exprtk_disable_string_capabilities
inline bool valid_string_operation(const details::operator_type& operation) const
{
return (details::e_add == operation) ||
(details::e_lt == operation) ||
(details::e_lte == operation) ||
(details::e_gt == operation) ||
(details::e_gte == operation) ||
(details::e_eq == operation) ||
(details::e_ne == operation) ||
(details::e_in == operation) ||
(details::e_like == operation) ||
(details::e_ilike == operation) ||
(details::e_assign == operation) ||
(details::e_addass == operation) ||
(details::e_swap == operation) ;
}
#else
inline bool valid_string_operation(const details::operator_type&) const
{
return false;
}
#endif
inline std::string to_str(const details::operator_type& operation) const
{
switch (operation)
{
case details::e_add : return "+" ;
case details::e_sub : return "-" ;
case details::e_mul : return "*" ;
case details::e_div : return "/" ;
case details::e_mod : return "%" ;
case details::e_pow : return "^" ;
case details::e_lt : return "<" ;
case details::e_lte : return "<=" ;
case details::e_gt : return ">" ;
case details::e_gte : return ">=" ;
case details::e_eq : return "==" ;
case details::e_ne : return "!=" ;
case details::e_and : return "and" ;
case details::e_nand : return "nand" ;
case details::e_or : return "or" ;
case details::e_nor : return "nor" ;
case details::e_xor : return "xor" ;
case details::e_xnor : return "xnor" ;
default : return "UNKNOWN";
}
}
inline bool operation_optimisable(const details::operator_type& operation) const
{
return (details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation) ||
(details::e_mod == operation) ||
(details::e_pow == operation) ||
(details::e_lt == operation) ||
(details::e_lte == operation) ||
(details::e_gt == operation) ||
(details::e_gte == operation) ||
(details::e_eq == operation) ||
(details::e_ne == operation) ||
(details::e_and == operation) ||
(details::e_nand == operation) ||
(details::e_or == operation) ||
(details::e_nor == operation) ||
(details::e_xor == operation) ||
(details::e_xnor == operation) ;
}
inline std::string branch_to_id(expression_node_ptr branch) const
{
static const std::string null_str ("(null)" );
static const std::string const_str ("(c)" );
static const std::string var_str ("(v)" );
static const std::string vov_str ("(vov)" );
static const std::string cov_str ("(cov)" );
static const std::string voc_str ("(voc)" );
static const std::string str_str ("(s)" );
static const std::string strrng_str ("(rngs)" );
static const std::string cs_str ("(cs)" );
static const std::string cstrrng_str("(crngs)");
if (details::is_null_node(branch))
return null_str;
else if (details::is_constant_node(branch))
return const_str;
else if (details::is_variable_node(branch))
return var_str;
else if (details::is_vov_node(branch))
return vov_str;
else if (details::is_cov_node(branch))
return cov_str;
else if (details::is_voc_node(branch))
return voc_str;
else if (details::is_string_node(branch))
return str_str;
else if (details::is_const_string_node(branch))
return cs_str;
else if (details::is_string_range_node(branch))
return strrng_str;
else if (details::is_const_string_range_node(branch))
return cstrrng_str;
else if (details::is_t0ot1ot2_node(branch))
return "(" + dynamic_cast<details::T0oT1oT2_base_node<T>*>(branch)->type_id() + ")";
else if (details::is_t0ot1ot2ot3_node(branch))
return "(" + dynamic_cast<details::T0oT1oT2oT3_base_node<T>*>(branch)->type_id() + ")";
else
return "ERROR";
}
inline std::string branch_to_id(expression_node_ptr (&branch)[2]) const
{
return branch_to_id(branch[0]) + std::string("o") + branch_to_id(branch[1]);
}
inline bool cov_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_constant_node(branch[0]) &&
details::is_variable_node(branch[1]) ;
}
inline bool voc_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_variable_node(branch[0]) &&
details::is_constant_node(branch[1]) ;
}
inline bool vov_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_variable_node(branch[0]) &&
details::is_variable_node(branch[1]) ;
}
inline bool cob_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_constant_node(branch[0]) &&
!details::is_constant_node(branch[1]) ;
}
inline bool boc_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return !details::is_constant_node(branch[0]) &&
details::is_constant_node(branch[1]) ;
}
inline bool cocob_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
return (details::is_constant_node(branch[0]) && details::is_cob_node(branch[1])) ||
(details::is_constant_node(branch[1]) && details::is_cob_node(branch[0])) ;
}
else
return false;
}
inline bool coboc_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
return (details::is_constant_node(branch[0]) && details::is_boc_node(branch[1])) ||
(details::is_constant_node(branch[1]) && details::is_boc_node(branch[0])) ;
}
else
return false;
}
inline bool uvouv_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_uv_node(branch[0]) &&
details::is_uv_node(branch[1]) ;
}
inline bool vob_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return details::is_variable_node(branch[0]) &&
!details::is_variable_node(branch[1]) ;
}
inline bool bov_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return !details::is_variable_node(branch[0]) &&
details::is_variable_node(branch[1]) ;
}
inline bool binext_optimisable(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!operation_optimisable(operation))
return false;
else
return !details::is_constant_node(branch[0]) ||
!details::is_constant_node(branch[1]) ;
}
inline bool is_invalid_assignment_op(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (is_assignment_operation(operation))
{
const bool b1_is_genstring = details::is_generally_string_node(branch[1]);
if (details::is_string_node(branch[0]))
return !b1_is_genstring;
else
return (
!details::is_variable_node (branch[0]) &&
!details::is_vector_elem_node (branch[0]) &&
!details::is_rebasevector_elem_node (branch[0]) &&
!details::is_rebasevector_celem_node(branch[0]) &&
!details::is_vector_node (branch[0])
)
|| b1_is_genstring;
}
else
return false;
}
inline bool is_constpow_operation(const details::operator_type& operation, expression_node_ptr(&branch)[2]) const
{
if (
!details::is_constant_node(branch[1]) ||
details::is_constant_node(branch[0]) ||
details::is_variable_node(branch[0]) ||
details::is_vector_node (branch[0]) ||
details::is_generally_string_node(branch[0])
)
return false;
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
return cardinal_pow_optimisable(operation, c);
}
inline bool is_invalid_break_continue_op(expression_node_ptr (&branch)[2]) const
{
return (
details::is_break_node (branch[0]) ||
details::is_break_node (branch[1]) ||
details::is_continue_node(branch[0]) ||
details::is_continue_node(branch[1])
);
}
inline bool is_invalid_string_op(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
const bool b0_string = is_generally_string_node(branch[0]);
const bool b1_string = is_generally_string_node(branch[1]);
bool result = false;
if (b0_string != b1_string)
result = true;
else if (!valid_string_operation(operation) && b0_string && b1_string)
result = true;
if (result)
{
parser_->set_synthesis_error("Invalid string operation");
}
return result;
}
inline bool is_invalid_string_op(const details::operator_type& operation, expression_node_ptr (&branch)[3]) const
{
const bool b0_string = is_generally_string_node(branch[0]);
const bool b1_string = is_generally_string_node(branch[1]);
const bool b2_string = is_generally_string_node(branch[2]);
bool result = false;
if ((b0_string != b1_string) || (b1_string != b2_string))
result = true;
else if ((details::e_inrange != operation) && b0_string && b1_string && b2_string)
result = true;
if (result)
{
parser_->set_synthesis_error("Invalid string operation");
}
return result;
}
inline bool is_string_operation(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
const bool b0_string = is_generally_string_node(branch[0]);
const bool b1_string = is_generally_string_node(branch[1]);
return (b0_string && b1_string && valid_string_operation(operation));
}
inline bool is_string_operation(const details::operator_type& operation, expression_node_ptr (&branch)[3]) const
{
const bool b0_string = is_generally_string_node(branch[0]);
const bool b1_string = is_generally_string_node(branch[1]);
const bool b2_string = is_generally_string_node(branch[2]);
return (b0_string && b1_string && b2_string && (details::e_inrange == operation));
}
#ifndef exprtk_disable_sc_andor
inline bool is_shortcircuit_expression(const details::operator_type& operation) const
{
return (
(details::e_scand == operation) ||
(details::e_scor == operation)
);
}
#else
inline bool is_shortcircuit_expression(const details::operator_type&) const
{
return false;
}
#endif
inline bool is_null_present(expression_node_ptr (&branch)[2]) const
{
return (
details::is_null_node(branch[0]) ||
details::is_null_node(branch[1])
);
}
inline bool is_vector_eqineq_logic_operation(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!is_ivector_node(branch[0]) && !is_ivector_node(branch[1]))
return false;
else
return (
(details::e_lt == operation) ||
(details::e_lte == operation) ||
(details::e_gt == operation) ||
(details::e_gte == operation) ||
(details::e_eq == operation) ||
(details::e_ne == operation) ||
(details::e_equal == operation) ||
(details::e_and == operation) ||
(details::e_nand == operation) ||
(details::e_or == operation) ||
(details::e_nor == operation) ||
(details::e_xor == operation) ||
(details::e_xnor == operation)
);
}
inline bool is_vector_arithmetic_operation(const details::operator_type& operation, expression_node_ptr (&branch)[2]) const
{
if (!is_ivector_node(branch[0]) && !is_ivector_node(branch[1]))
return false;
else
return (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation) ||
(details::e_pow == operation)
);
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr (&branch)[2])
{
if ((0 == branch[0]) || (0 == branch[1]))
{
return error_node();
}
else if (is_invalid_string_op(operation,branch))
{
return error_node();
}
else if (is_invalid_assignment_op(operation,branch))
{
return error_node();
}
else if (is_invalid_break_continue_op(branch))
{
return error_node();
}
else if (details::e_assign == operation)
{
return synthesize_assignment_expression(operation, branch);
}
else if (details::e_swap == operation)
{
return synthesize_swap_expression(branch);
}
else if (is_assignment_operation(operation))
{
return synthesize_assignment_operation_expression(operation, branch);
}
else if (is_vector_eqineq_logic_operation(operation, branch))
{
return synthesize_veceqineqlogic_operation_expression(operation, branch);
}
else if (is_vector_arithmetic_operation(operation, branch))
{
return synthesize_vecarithmetic_operation_expression(operation, branch);
}
else if (is_shortcircuit_expression(operation))
{
return synthesize_shortcircuit_expression(operation, branch);
}
else if (is_string_operation(operation, branch))
{
return synthesize_string_expression(operation, branch);
}
else if (is_null_present(branch))
{
return synthesize_null_expression(operation, branch);
}
#ifndef exprtk_disable_cardinal_pow_optimisation
else if (is_constpow_operation(operation, branch))
{
return cardinal_pow_optimisation(branch);
}
#endif
expression_node_ptr result = error_node();
#ifndef exprtk_disable_enhanced_features
if (synthesize_expression(operation, branch, result))
{
return result;
}
else
#endif
{
/*
Possible reductions:
1. c o cob -> cob
2. cob o c -> cob
3. c o boc -> boc
4. boc o c -> boc
*/
result = error_node();
if (cocob_optimisable(operation, branch))
{
result = synthesize_cocob_expression::process((*this), operation, branch);
}
else if (coboc_optimisable(operation, branch) && (0 == result))
{
result = synthesize_coboc_expression::process((*this), operation, branch);
}
if (result)
return result;
}
if (uvouv_optimisable(operation, branch))
{
return synthesize_uvouv_expression(operation, branch);
}
else if (vob_optimisable(operation, branch))
{
return synthesize_vob_expression::process((*this), operation, branch);
}
else if (bov_optimisable(operation, branch))
{
return synthesize_bov_expression::process((*this), operation, branch);
}
else if (cob_optimisable(operation, branch))
{
return synthesize_cob_expression::process((*this), operation, branch);
}
else if (boc_optimisable(operation, branch))
{
return synthesize_boc_expression::process((*this), operation, branch);
}
#ifndef exprtk_disable_enhanced_features
else if (cov_optimisable(operation, branch))
{
return synthesize_cov_expression::process((*this), operation, branch);
}
#endif
else if (binext_optimisable(operation, branch))
{
return synthesize_binary_ext_expression::process((*this), operation, branch);
}
else
return synthesize_expression<binary_node_t,2>(operation, branch);
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr (&branch)[3])
{
if (
(0 == branch[0]) ||
(0 == branch[1]) ||
(0 == branch[2])
)
{
details::free_all_nodes(*node_allocator_,branch);
return error_node();
}
else if (is_invalid_string_op(operation, branch))
{
return error_node();
}
else if (is_string_operation(operation, branch))
{
return synthesize_string_expression(operation, branch);
}
else
return synthesize_expression<trinary_node_t,3>(operation, branch);
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr (&branch)[4])
{
return synthesize_expression<quaternary_node_t,4>(operation,branch);
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr b0)
{
expression_node_ptr branch[1] = { b0 };
return (*this)(operation,branch);
}
inline expression_node_ptr operator() (const details::operator_type& operation, expression_node_ptr& b0, expression_node_ptr& b1)
{
expression_node_ptr result = error_node();
if ((0 != b0) && (0 != b1))
{
expression_node_ptr branch[2] = { b0, b1 };
result = expression_generator<Type>::operator()(operation, branch);
b0 = branch[0];
b1 = branch[1];
}
return result;
}
inline expression_node_ptr conditional(expression_node_ptr condition,
expression_node_ptr consequent,
expression_node_ptr alternative) const
{
if ((0 == condition) || (0 == consequent))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent );
details::free_node(*node_allocator_, alternative);
return error_node();
}
// Can the condition be immediately evaluated? if so optimise.
else if (details::is_constant_node(condition))
{
// True branch
if (details::is_true(condition))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, alternative);
return consequent;
}
// False branch
else
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent);
if (alternative)
return alternative;
else
return node_allocator_->allocate<details::null_node<T> >();
}
}
else if ((0 != consequent) && (0 != alternative))
{
return node_allocator_->
allocate<conditional_node_t>(condition, consequent, alternative);
}
else
return node_allocator_->
allocate<cons_conditional_node_t>(condition, consequent);
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr conditional_string(expression_node_ptr condition,
expression_node_ptr consequent,
expression_node_ptr alternative) const
{
if ((0 == condition) || (0 == consequent))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent );
details::free_node(*node_allocator_, alternative);
return error_node();
}
// Can the condition be immediately evaluated? if so optimise.
else if (details::is_constant_node(condition))
{
// True branch
if (details::is_true(condition))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, alternative);
return consequent;
}
// False branch
else
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent);
if (alternative)
return alternative;
else
return node_allocator_->
allocate_c<details::string_literal_node<Type> >("");
}
}
else if ((0 != consequent) && (0 != alternative))
return node_allocator_->
allocate<conditional_string_node_t>(condition, consequent, alternative);
else
return error_node();
}
#else
inline expression_node_ptr conditional_string(expression_node_ptr,
expression_node_ptr,
expression_node_ptr) const
{
return error_node();
}
#endif
inline expression_node_ptr conditional_vector(expression_node_ptr condition,
expression_node_ptr consequent,
expression_node_ptr alternative) const
{
if ((0 == condition) || (0 == consequent))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent );
details::free_node(*node_allocator_, alternative);
return error_node();
}
// Can the condition be immediately evaluated? if so optimise.
else if (details::is_constant_node(condition))
{
// True branch
if (details::is_true(condition))
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, alternative);
return consequent;
}
// False branch
else
{
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, consequent);
if (alternative)
return alternative;
else
return node_allocator_->allocate<details::null_node<T> >();
}
}
else if ((0 != consequent) && (0 != alternative))
{
return node_allocator_->
allocate<conditional_vector_node_t>(condition, consequent, alternative);
}
else
return error_node();
}
inline loop_runtime_check_ptr get_loop_runtime_check(const loop_runtime_check::loop_types loop_type) const
{
if (
parser_->loop_runtime_check_ &&
(loop_type == (parser_->loop_runtime_check_->loop_set & loop_type))
)
{
return parser_->loop_runtime_check_;
}
return loop_runtime_check_ptr(0);
}
inline expression_node_ptr while_loop(expression_node_ptr& condition,
expression_node_ptr& branch,
const bool break_continue_present = false) const
{
if (!break_continue_present && details::is_constant_node(condition))
{
expression_node_ptr result = error_node();
if (details::is_true(condition))
// Infinite loops are not allowed.
result = error_node();
else
result = node_allocator_->allocate<details::null_node<Type> >();
details::free_node(*node_allocator_, condition);
details::free_node(*node_allocator_, branch );
return result;
}
else if (details::is_null_node(condition))
{
details::free_node(*node_allocator_,condition);
return branch;
}
loop_runtime_check_ptr rtc = get_loop_runtime_check(loop_runtime_check::e_while_loop);
if (!break_continue_present)
{
if (rtc)
return node_allocator_->allocate<while_loop_rtc_node_t>
(condition, branch, rtc);
else
return node_allocator_->allocate<while_loop_node_t>
(condition, branch);
}
#ifndef exprtk_disable_break_continue
else
{
if (rtc)
return node_allocator_->allocate<while_loop_bc_rtc_node_t>
(condition, branch, rtc);
else
return node_allocator_->allocate<while_loop_bc_node_t>
(condition, branch);
}
#else
return error_node();
#endif
}
inline expression_node_ptr repeat_until_loop(expression_node_ptr& condition,
expression_node_ptr& branch,
const bool break_continue_present = false) const
{
if (!break_continue_present && details::is_constant_node(condition))
{
if (
details::is_true(condition) &&
details::is_constant_node(branch)
)
{
free_node(*node_allocator_,condition);
return branch;
}
details::free_node(*node_allocator_, condition);
details::free_node(*node_allocator_, branch );
return error_node();
}
else if (details::is_null_node(condition))
{
details::free_node(*node_allocator_,condition);
return branch;
}
loop_runtime_check_ptr rtc = get_loop_runtime_check(loop_runtime_check::e_repeat_until_loop);
if (!break_continue_present)
{
if (rtc)
return node_allocator_->allocate<repeat_until_loop_rtc_node_t>
(condition, branch, rtc);
else
return node_allocator_->allocate<repeat_until_loop_node_t>
(condition, branch);
}
#ifndef exprtk_disable_break_continue
else
{
if (rtc)
return node_allocator_->allocate<repeat_until_loop_bc_rtc_node_t>
(condition, branch, rtc);
else
return node_allocator_->allocate<repeat_until_loop_bc_node_t>
(condition, branch);
}
#else
return error_node();
#endif
}
inline expression_node_ptr for_loop(expression_node_ptr& initialiser,
expression_node_ptr& condition,
expression_node_ptr& incrementor,
expression_node_ptr& loop_body,
bool break_continue_present = false) const
{
if (!break_continue_present && details::is_constant_node(condition))
{
expression_node_ptr result = error_node();
if (details::is_true(condition))
// Infinite loops are not allowed.
result = error_node();
else
result = node_allocator_->allocate<details::null_node<Type> >();
details::free_node(*node_allocator_, initialiser);
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, incrementor);
details::free_node(*node_allocator_, loop_body );
return result;
}
else if (details::is_null_node(condition) || (0 == condition))
{
details::free_node(*node_allocator_, initialiser);
details::free_node(*node_allocator_, condition );
details::free_node(*node_allocator_, incrementor);
return loop_body;
}
loop_runtime_check_ptr rtc = get_loop_runtime_check(loop_runtime_check::e_for_loop);
if (!break_continue_present)
{
if (rtc)
return node_allocator_->allocate<for_loop_rtc_node_t>
(
initialiser,
condition,
incrementor,
loop_body,
rtc
);
else
return node_allocator_->allocate<for_loop_node_t>
(
initialiser,
condition,
incrementor,
loop_body
);
}
#ifndef exprtk_disable_break_continue
else
{
if (rtc)
return node_allocator_->allocate<for_loop_bc_rtc_node_t>
(
initialiser,
condition,
incrementor,
loop_body,
rtc
);
else
return node_allocator_->allocate<for_loop_bc_node_t>
(
initialiser,
condition,
incrementor,
loop_body
);
}
#else
return error_node();
#endif
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr const_optimise_switch(Sequence<expression_node_ptr,Allocator>& arg_list)
{
expression_node_ptr result = error_node();
for (std::size_t i = 0; i < (arg_list.size() / 2); ++i)
{
expression_node_ptr condition = arg_list[(2 * i) ];
expression_node_ptr consequent = arg_list[(2 * i) + 1];
if ((0 == result) && details::is_true(condition))
{
result = consequent;
break;
}
}
if (0 == result)
{
result = arg_list.back();
}
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
expression_node_ptr current_expr = arg_list[i];
if (current_expr && (current_expr != result))
{
free_node(*node_allocator_,current_expr);
}
}
return result;
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr const_optimise_mswitch(Sequence<expression_node_ptr,Allocator>& arg_list)
{
expression_node_ptr result = error_node();
for (std::size_t i = 0; i < (arg_list.size() / 2); ++i)
{
expression_node_ptr condition = arg_list[(2 * i) ];
expression_node_ptr consequent = arg_list[(2 * i) + 1];
if (details::is_true(condition))
{
result = consequent;
}
}
if (0 == result)
{
T zero = T(0);
result = node_allocator_->allocate<literal_node_t>(zero);
}
for (std::size_t i = 0; i < arg_list.size(); ++i)
{
expression_node_ptr& current_expr = arg_list[i];
if (current_expr && (current_expr != result))
{
details::free_node(*node_allocator_,current_expr);
}
}
return result;
}
struct switch_nodes
{
typedef std::vector<std::pair<expression_node_ptr,bool> > arg_list_t;
#define case_stmt(N) \
if (is_true(arg[(2 * N)].first)) { return arg[(2 * N) + 1].first->value(); } \
struct switch_impl_1
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0)
assert(arg.size() == ((2 * 1) + 1));
return arg.back().first->value();
}
};
struct switch_impl_2
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
assert(arg.size() == ((2 * 2) + 1));
return arg.back().first->value();
}
};
struct switch_impl_3
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
case_stmt(2)
assert(arg.size() == ((2 * 3) + 1));
return arg.back().first->value();
}
};
struct switch_impl_4
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
case_stmt(2) case_stmt(3)
assert(arg.size() == ((2 * 4) + 1));
return arg.back().first->value();
}
};
struct switch_impl_5
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
case_stmt(2) case_stmt(3)
case_stmt(4)
assert(arg.size() == ((2 * 5) + 1));
return arg.back().first->value();
}
};
struct switch_impl_6
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
case_stmt(2) case_stmt(3)
case_stmt(4) case_stmt(5)
assert(arg.size() == ((2 * 6) + 1));
return arg.back().first->value();
}
};
struct switch_impl_7
{
static inline T process(const arg_list_t& arg)
{
case_stmt(0) case_stmt(1)
case_stmt(2) case_stmt(3)
case_stmt(4) case_stmt(5)
case_stmt(6)
assert(arg.size() == ((2 * 7) + 1));
return arg.back().first->value();
}
};
#undef case_stmt
};
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr switch_statement(Sequence<expression_node_ptr,Allocator>& arg_list, const bool default_statement_present)
{
if (arg_list.empty())
return error_node();
else if (
!all_nodes_valid(arg_list) ||
(!default_statement_present && (arg_list.size() < 2))
)
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
else if (is_constant_foldable(arg_list))
return const_optimise_switch(arg_list);
switch ((arg_list.size() - 1) / 2)
{
#define case_stmt(N) \
case N : \
return node_allocator_-> \
allocate<details::switch_n_node \
<Type,typename switch_nodes::switch_impl_##N > >(arg_list); \
case_stmt(1)
case_stmt(2)
case_stmt(3)
case_stmt(4)
case_stmt(5)
case_stmt(6)
case_stmt(7)
#undef case_stmt
default : return node_allocator_->allocate<details::switch_node<Type> >(arg_list);
}
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr multi_switch_statement(Sequence<expression_node_ptr,Allocator>& arg_list)
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
else if (is_constant_foldable(arg_list))
return const_optimise_mswitch(arg_list);
else
return node_allocator_->allocate<details::multi_switch_node<Type> >(arg_list);
}
#define unary_opr_switch_statements \
case_stmt(details::e_abs , details::abs_op ) \
case_stmt(details::e_acos , details::acos_op ) \
case_stmt(details::e_acosh , details::acosh_op) \
case_stmt(details::e_asin , details::asin_op ) \
case_stmt(details::e_asinh , details::asinh_op) \
case_stmt(details::e_atan , details::atan_op ) \
case_stmt(details::e_atanh , details::atanh_op) \
case_stmt(details::e_ceil , details::ceil_op ) \
case_stmt(details::e_cos , details::cos_op ) \
case_stmt(details::e_cosh , details::cosh_op ) \
case_stmt(details::e_exp , details::exp_op ) \
case_stmt(details::e_expm1 , details::expm1_op) \
case_stmt(details::e_floor , details::floor_op) \
case_stmt(details::e_log , details::log_op ) \
case_stmt(details::e_log10 , details::log10_op) \
case_stmt(details::e_log2 , details::log2_op ) \
case_stmt(details::e_log1p , details::log1p_op) \
case_stmt(details::e_neg , details::neg_op ) \
case_stmt(details::e_pos , details::pos_op ) \
case_stmt(details::e_round , details::round_op) \
case_stmt(details::e_sin , details::sin_op ) \
case_stmt(details::e_sinc , details::sinc_op ) \
case_stmt(details::e_sinh , details::sinh_op ) \
case_stmt(details::e_sqrt , details::sqrt_op ) \
case_stmt(details::e_tan , details::tan_op ) \
case_stmt(details::e_tanh , details::tanh_op ) \
case_stmt(details::e_cot , details::cot_op ) \
case_stmt(details::e_sec , details::sec_op ) \
case_stmt(details::e_csc , details::csc_op ) \
case_stmt(details::e_r2d , details::r2d_op ) \
case_stmt(details::e_d2r , details::d2r_op ) \
case_stmt(details::e_d2g , details::d2g_op ) \
case_stmt(details::e_g2d , details::g2d_op ) \
case_stmt(details::e_notl , details::notl_op ) \
case_stmt(details::e_sgn , details::sgn_op ) \
case_stmt(details::e_erf , details::erf_op ) \
case_stmt(details::e_erfc , details::erfc_op ) \
case_stmt(details::e_ncdf , details::ncdf_op ) \
case_stmt(details::e_frac , details::frac_op ) \
case_stmt(details::e_trunc , details::trunc_op) \
inline expression_node_ptr synthesize_uv_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[1])
{
T& v = static_cast<details::variable_node<T>*>(branch[0])->ref();
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<typename details::unary_variable_node<Type,op1<Type> > >(v); \
unary_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr synthesize_uvec_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[1])
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<typename details::unary_vector_node<Type,op1<Type> > > \
(operation, branch[0]); \
unary_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr synthesize_unary_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[1])
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<typename details::unary_branch_node<Type,op1<Type> > >(branch[0]); \
unary_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr const_optimise_sf3(const details::operator_type& operation,
expression_node_ptr (&branch)[3])
{
expression_node_ptr temp_node = error_node();
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : temp_node = node_allocator_-> \
allocate<details::sf3_node<Type,details::sf##op##_op<Type> > > \
(operation, branch); \
break; \
case_stmt(00) case_stmt(01) case_stmt(02) case_stmt(03)
case_stmt(04) case_stmt(05) case_stmt(06) case_stmt(07)
case_stmt(08) case_stmt(09) case_stmt(10) case_stmt(11)
case_stmt(12) case_stmt(13) case_stmt(14) case_stmt(15)
case_stmt(16) case_stmt(17) case_stmt(18) case_stmt(19)
case_stmt(20) case_stmt(21) case_stmt(22) case_stmt(23)
case_stmt(24) case_stmt(25) case_stmt(26) case_stmt(27)
case_stmt(28) case_stmt(29) case_stmt(30) case_stmt(31)
case_stmt(32) case_stmt(33) case_stmt(34) case_stmt(35)
case_stmt(36) case_stmt(37) case_stmt(38) case_stmt(39)
case_stmt(40) case_stmt(41) case_stmt(42) case_stmt(43)
case_stmt(44) case_stmt(45) case_stmt(46) case_stmt(47)
#undef case_stmt
default : return error_node();
}
const T v = temp_node->value();
details::free_node(*node_allocator_,temp_node);
return node_allocator_->allocate<literal_node_t>(v);
}
inline expression_node_ptr varnode_optimise_sf3(const details::operator_type& operation, expression_node_ptr (&branch)[3])
{
typedef details::variable_node<Type>* variable_ptr;
const Type& v0 = static_cast<variable_ptr>(branch[0])->ref();
const Type& v1 = static_cast<variable_ptr>(branch[1])->ref();
const Type& v2 = static_cast<variable_ptr>(branch[2])->ref();
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : return node_allocator_-> \
allocate_rrr<details::sf3_var_node<Type,details::sf##op##_op<Type> > > \
(v0, v1, v2); \
case_stmt(00) case_stmt(01) case_stmt(02) case_stmt(03)
case_stmt(04) case_stmt(05) case_stmt(06) case_stmt(07)
case_stmt(08) case_stmt(09) case_stmt(10) case_stmt(11)
case_stmt(12) case_stmt(13) case_stmt(14) case_stmt(15)
case_stmt(16) case_stmt(17) case_stmt(18) case_stmt(19)
case_stmt(20) case_stmt(21) case_stmt(22) case_stmt(23)
case_stmt(24) case_stmt(25) case_stmt(26) case_stmt(27)
case_stmt(28) case_stmt(29) case_stmt(30) case_stmt(31)
case_stmt(32) case_stmt(33) case_stmt(34) case_stmt(35)
case_stmt(36) case_stmt(37) case_stmt(38) case_stmt(39)
case_stmt(40) case_stmt(41) case_stmt(42) case_stmt(43)
case_stmt(44) case_stmt(45) case_stmt(46) case_stmt(47)
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr special_function(const details::operator_type& operation, expression_node_ptr (&branch)[3])
{
if (!all_nodes_valid(branch))
return error_node();
else if (is_constant_foldable(branch))
return const_optimise_sf3(operation,branch);
else if (all_nodes_variables(branch))
return varnode_optimise_sf3(operation,branch);
else
{
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : return node_allocator_-> \
allocate<details::sf3_node<Type,details::sf##op##_op<Type> > > \
(operation, branch); \
case_stmt(00) case_stmt(01) case_stmt(02) case_stmt(03)
case_stmt(04) case_stmt(05) case_stmt(06) case_stmt(07)
case_stmt(08) case_stmt(09) case_stmt(10) case_stmt(11)
case_stmt(12) case_stmt(13) case_stmt(14) case_stmt(15)
case_stmt(16) case_stmt(17) case_stmt(18) case_stmt(19)
case_stmt(20) case_stmt(21) case_stmt(22) case_stmt(23)
case_stmt(24) case_stmt(25) case_stmt(26) case_stmt(27)
case_stmt(28) case_stmt(29) case_stmt(30) case_stmt(31)
case_stmt(32) case_stmt(33) case_stmt(34) case_stmt(35)
case_stmt(36) case_stmt(37) case_stmt(38) case_stmt(39)
case_stmt(40) case_stmt(41) case_stmt(42) case_stmt(43)
case_stmt(44) case_stmt(45) case_stmt(46) case_stmt(47)
#undef case_stmt
default : return error_node();
}
}
}
inline expression_node_ptr const_optimise_sf4(const details::operator_type& operation, expression_node_ptr (&branch)[4])
{
expression_node_ptr temp_node = error_node();
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : temp_node = node_allocator_-> \
allocate<details::sf4_node<Type,details::sf##op##_op<Type> > > \
(operation, branch); \
break; \
case_stmt(48) case_stmt(49) case_stmt(50) case_stmt(51)
case_stmt(52) case_stmt(53) case_stmt(54) case_stmt(55)
case_stmt(56) case_stmt(57) case_stmt(58) case_stmt(59)
case_stmt(60) case_stmt(61) case_stmt(62) case_stmt(63)
case_stmt(64) case_stmt(65) case_stmt(66) case_stmt(67)
case_stmt(68) case_stmt(69) case_stmt(70) case_stmt(71)
case_stmt(72) case_stmt(73) case_stmt(74) case_stmt(75)
case_stmt(76) case_stmt(77) case_stmt(78) case_stmt(79)
case_stmt(80) case_stmt(81) case_stmt(82) case_stmt(83)
case_stmt(84) case_stmt(85) case_stmt(86) case_stmt(87)
case_stmt(88) case_stmt(89) case_stmt(90) case_stmt(91)
case_stmt(92) case_stmt(93) case_stmt(94) case_stmt(95)
case_stmt(96) case_stmt(97) case_stmt(98) case_stmt(99)
#undef case_stmt
default : return error_node();
}
const T v = temp_node->value();
details::free_node(*node_allocator_,temp_node);
return node_allocator_->allocate<literal_node_t>(v);
}
inline expression_node_ptr varnode_optimise_sf4(const details::operator_type& operation, expression_node_ptr (&branch)[4])
{
typedef details::variable_node<Type>* variable_ptr;
const Type& v0 = static_cast<variable_ptr>(branch[0])->ref();
const Type& v1 = static_cast<variable_ptr>(branch[1])->ref();
const Type& v2 = static_cast<variable_ptr>(branch[2])->ref();
const Type& v3 = static_cast<variable_ptr>(branch[3])->ref();
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : return node_allocator_-> \
allocate_rrrr<details::sf4_var_node<Type,details::sf##op##_op<Type> > > \
(v0, v1, v2, v3); \
case_stmt(48) case_stmt(49) case_stmt(50) case_stmt(51)
case_stmt(52) case_stmt(53) case_stmt(54) case_stmt(55)
case_stmt(56) case_stmt(57) case_stmt(58) case_stmt(59)
case_stmt(60) case_stmt(61) case_stmt(62) case_stmt(63)
case_stmt(64) case_stmt(65) case_stmt(66) case_stmt(67)
case_stmt(68) case_stmt(69) case_stmt(70) case_stmt(71)
case_stmt(72) case_stmt(73) case_stmt(74) case_stmt(75)
case_stmt(76) case_stmt(77) case_stmt(78) case_stmt(79)
case_stmt(80) case_stmt(81) case_stmt(82) case_stmt(83)
case_stmt(84) case_stmt(85) case_stmt(86) case_stmt(87)
case_stmt(88) case_stmt(89) case_stmt(90) case_stmt(91)
case_stmt(92) case_stmt(93) case_stmt(94) case_stmt(95)
case_stmt(96) case_stmt(97) case_stmt(98) case_stmt(99)
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr special_function(const details::operator_type& operation, expression_node_ptr (&branch)[4])
{
if (!all_nodes_valid(branch))
return error_node();
else if (is_constant_foldable(branch))
return const_optimise_sf4(operation,branch);
else if (all_nodes_variables(branch))
return varnode_optimise_sf4(operation,branch);
switch (operation)
{
#define case_stmt(op) \
case details::e_sf##op : return node_allocator_-> \
allocate<details::sf4_node<Type,details::sf##op##_op<Type> > > \
(operation, branch); \
case_stmt(48) case_stmt(49) case_stmt(50) case_stmt(51)
case_stmt(52) case_stmt(53) case_stmt(54) case_stmt(55)
case_stmt(56) case_stmt(57) case_stmt(58) case_stmt(59)
case_stmt(60) case_stmt(61) case_stmt(62) case_stmt(63)
case_stmt(64) case_stmt(65) case_stmt(66) case_stmt(67)
case_stmt(68) case_stmt(69) case_stmt(70) case_stmt(71)
case_stmt(72) case_stmt(73) case_stmt(74) case_stmt(75)
case_stmt(76) case_stmt(77) case_stmt(78) case_stmt(79)
case_stmt(80) case_stmt(81) case_stmt(82) case_stmt(83)
case_stmt(84) case_stmt(85) case_stmt(86) case_stmt(87)
case_stmt(88) case_stmt(89) case_stmt(90) case_stmt(91)
case_stmt(92) case_stmt(93) case_stmt(94) case_stmt(95)
case_stmt(96) case_stmt(97) case_stmt(98) case_stmt(99)
#undef case_stmt
default : return error_node();
}
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr const_optimise_varargfunc(const details::operator_type& operation, Sequence<expression_node_ptr,Allocator>& arg_list)
{
expression_node_ptr temp_node = error_node();
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : temp_node = node_allocator_-> \
allocate<details::vararg_node<Type,op1<Type> > > \
(arg_list); \
break; \
case_stmt(details::e_sum , details::vararg_add_op )
case_stmt(details::e_prod , details::vararg_mul_op )
case_stmt(details::e_avg , details::vararg_avg_op )
case_stmt(details::e_min , details::vararg_min_op )
case_stmt(details::e_max , details::vararg_max_op )
case_stmt(details::e_mand , details::vararg_mand_op )
case_stmt(details::e_mor , details::vararg_mor_op )
case_stmt(details::e_multi , details::vararg_multi_op)
#undef case_stmt
default : return error_node();
}
const T v = temp_node->value();
details::free_node(*node_allocator_,temp_node);
return node_allocator_->allocate<literal_node_t>(v);
}
inline bool special_one_parameter_vararg(const details::operator_type& operation) const
{
return (
(details::e_sum == operation) ||
(details::e_prod == operation) ||
(details::e_avg == operation) ||
(details::e_min == operation) ||
(details::e_max == operation)
);
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr varnode_optimise_varargfunc(const details::operator_type& operation, Sequence<expression_node_ptr,Allocator>& arg_list)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<details::vararg_varnode<Type,op1<Type> > >(arg_list); \
case_stmt(details::e_sum , details::vararg_add_op )
case_stmt(details::e_prod , details::vararg_mul_op )
case_stmt(details::e_avg , details::vararg_avg_op )
case_stmt(details::e_min , details::vararg_min_op )
case_stmt(details::e_max , details::vararg_max_op )
case_stmt(details::e_mand , details::vararg_mand_op )
case_stmt(details::e_mor , details::vararg_mor_op )
case_stmt(details::e_multi , details::vararg_multi_op)
#undef case_stmt
default : return error_node();
}
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr vectorize_func(const details::operator_type& operation, Sequence<expression_node_ptr,Allocator>& arg_list)
{
if (1 == arg_list.size())
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<details::vectorize_node<Type,op1<Type> > >(arg_list[0]); \
case_stmt(details::e_sum , details::vec_add_op)
case_stmt(details::e_prod , details::vec_mul_op)
case_stmt(details::e_avg , details::vec_avg_op)
case_stmt(details::e_min , details::vec_min_op)
case_stmt(details::e_max , details::vec_max_op)
#undef case_stmt
default : return error_node();
}
}
else
return error_node();
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline expression_node_ptr vararg_function(const details::operator_type& operation, Sequence<expression_node_ptr,Allocator>& arg_list)
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
else if (is_constant_foldable(arg_list))
return const_optimise_varargfunc(operation,arg_list);
else if ((arg_list.size() == 1) && details::is_ivector_node(arg_list[0]))
return vectorize_func(operation,arg_list);
else if ((arg_list.size() == 1) && special_one_parameter_vararg(operation))
return arg_list[0];
else if (all_nodes_variables(arg_list))
return varnode_optimise_varargfunc(operation,arg_list);
#ifndef exprtk_disable_string_capabilities
if (details::e_smulti == operation)
{
return node_allocator_->
allocate<details::str_vararg_node<Type,details::vararg_multi_op<Type> > >(arg_list);
}
else
#endif
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate<details::vararg_node<Type,op1<Type> > >(arg_list); \
case_stmt(details::e_sum , details::vararg_add_op )
case_stmt(details::e_prod , details::vararg_mul_op )
case_stmt(details::e_avg , details::vararg_avg_op )
case_stmt(details::e_min , details::vararg_min_op )
case_stmt(details::e_max , details::vararg_max_op )
case_stmt(details::e_mand , details::vararg_mand_op )
case_stmt(details::e_mor , details::vararg_mor_op )
case_stmt(details::e_multi , details::vararg_multi_op)
#undef case_stmt
default : return error_node();
}
}
}
template <std::size_t N>
inline expression_node_ptr function(ifunction_t* f, expression_node_ptr (&b)[N])
{
typedef typename details::function_N_node<T,ifunction_t,N> function_N_node_t;
expression_node_ptr result = synthesize_expression<function_N_node_t,N>(f,b);
if (0 == result)
return error_node();
else
{
// Can the function call be completely optimised?
if (details::is_constant_node(result))
return result;
else if (!all_nodes_valid(b))
{
details::free_node(*node_allocator_,result);
std::fill_n(b, N, reinterpret_cast<expression_node_ptr>(0));
return error_node();
}
else if (N != f->param_count)
{
details::free_node(*node_allocator_,result);
std::fill_n(b, N, reinterpret_cast<expression_node_ptr>(0));
return error_node();
}
function_N_node_t* func_node_ptr = reinterpret_cast<function_N_node_t*>(result);
if (!func_node_ptr->init_branches(b))
{
details::free_node(*node_allocator_,result);
std::fill_n(b, N, reinterpret_cast<expression_node_ptr>(0));
return error_node();
}
return result;
}
}
inline expression_node_ptr function(ifunction_t* f)
{
typedef typename details::function_N_node<Type,ifunction_t,0> function_N_node_t;
return node_allocator_->allocate<function_N_node_t>(f);
}
inline expression_node_ptr vararg_function_call(ivararg_function_t* vaf,
std::vector<expression_node_ptr>& arg_list)
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
typedef details::vararg_function_node<Type,ivararg_function_t> alloc_type;
expression_node_ptr result = node_allocator_->allocate<alloc_type>(vaf,arg_list);
if (
!arg_list.empty() &&
!vaf->has_side_effects() &&
is_constant_foldable(arg_list)
)
{
const Type v = result->value();
details::free_node(*node_allocator_,result);
result = node_allocator_->allocate<literal_node_t>(v);
}
parser_->state_.activate_side_effect("vararg_function_call()");
return result;
}
inline expression_node_ptr generic_function_call(igeneric_function_t* gf,
std::vector<expression_node_ptr>& arg_list,
const std::size_t& param_seq_index = std::numeric_limits<std::size_t>::max())
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
typedef details::generic_function_node <Type,igeneric_function_t> alloc_type1;
typedef details::multimode_genfunction_node<Type,igeneric_function_t> alloc_type2;
const std::size_t no_psi = std::numeric_limits<std::size_t>::max();
expression_node_ptr result = error_node();
if (no_psi == param_seq_index)
result = node_allocator_->allocate<alloc_type1>(arg_list,gf);
else
result = node_allocator_->allocate<alloc_type2>(gf, param_seq_index, arg_list);
alloc_type1* genfunc_node_ptr = static_cast<alloc_type1*>(result);
if (
!arg_list.empty() &&
!gf->has_side_effects() &&
parser_->state_.type_check_enabled &&
is_constant_foldable(arg_list)
)
{
genfunc_node_ptr->init_branches();
const Type v = result->value();
details::free_node(*node_allocator_,result);
return node_allocator_->allocate<literal_node_t>(v);
}
else if (genfunc_node_ptr->init_branches())
{
parser_->state_.activate_side_effect("generic_function_call()");
return result;
}
else
{
details::free_node(*node_allocator_, result);
details::free_all_nodes(*node_allocator_, arg_list);
return error_node();
}
}
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr string_function_call(igeneric_function_t* gf,
std::vector<expression_node_ptr>& arg_list,
const std::size_t& param_seq_index = std::numeric_limits<std::size_t>::max())
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
typedef details::string_function_node <Type,igeneric_function_t> alloc_type1;
typedef details::multimode_strfunction_node<Type,igeneric_function_t> alloc_type2;
const std::size_t no_psi = std::numeric_limits<std::size_t>::max();
expression_node_ptr result = error_node();
if (no_psi == param_seq_index)
result = node_allocator_->allocate<alloc_type1>(gf,arg_list);
else
result = node_allocator_->allocate<alloc_type2>(gf, param_seq_index, arg_list);
alloc_type1* strfunc_node_ptr = static_cast<alloc_type1*>(result);
if (
!arg_list.empty() &&
!gf->has_side_effects() &&
is_constant_foldable(arg_list)
)
{
strfunc_node_ptr->init_branches();
const Type v = result->value();
details::free_node(*node_allocator_,result);
return node_allocator_->allocate<literal_node_t>(v);
}
else if (strfunc_node_ptr->init_branches())
{
parser_->state_.activate_side_effect("string_function_call()");
return result;
}
else
{
details::free_node (*node_allocator_,result );
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
}
#endif
#ifndef exprtk_disable_return_statement
inline expression_node_ptr return_call(std::vector<expression_node_ptr>& arg_list)
{
if (!all_nodes_valid(arg_list))
{
details::free_all_nodes(*node_allocator_,arg_list);
return error_node();
}
typedef details::return_node<Type> alloc_type;
expression_node_ptr result = node_allocator_->
allocate_rr<alloc_type>(arg_list,parser_->results_ctx());
alloc_type* return_node_ptr = static_cast<alloc_type*>(result);
if (return_node_ptr->init_branches())
{
parser_->state_.activate_side_effect("return_call()");
return result;
}
else
{
details::free_node (*node_allocator_, result );
details::free_all_nodes(*node_allocator_, arg_list);
return error_node();
}
}
inline expression_node_ptr return_envelope(expression_node_ptr body,
results_context_t* rc,
bool*& return_invoked)
{
typedef details::return_envelope_node<Type> alloc_type;
expression_node_ptr result = node_allocator_->
allocate_cr<alloc_type>(body,(*rc));
return_invoked = static_cast<alloc_type*>(result)->retinvk_ptr();
return result;
}
#else
inline expression_node_ptr return_call(std::vector<expression_node_ptr>&)
{
return error_node();
}
inline expression_node_ptr return_envelope(expression_node_ptr,
results_context_t*,
bool*&)
{
return error_node();
}
#endif
inline expression_node_ptr vector_element(const std::string& symbol,
vector_holder_ptr vector_base,
expression_node_ptr index)
{
expression_node_ptr result = error_node();
if (details::is_constant_node(index))
{
std::size_t i = static_cast<std::size_t>(details::numeric::to_int64(index->value()));
details::free_node(*node_allocator_,index);
if (vector_base->rebaseable())
{
return node_allocator_->allocate<rebasevector_celem_node_t>(i,vector_base);
}
const scope_element& se = parser_->sem_.get_element(symbol,i);
if (se.index == i)
{
result = se.var_node;
}
else
{
scope_element nse;
nse.name = symbol;
nse.active = true;
nse.ref_count = 1;
nse.type = scope_element::e_vecelem;
nse.index = i;
nse.depth = parser_->state_.scope_depth;
nse.data = 0;
nse.var_node = node_allocator_->allocate<variable_node_t>((*(*vector_base)[i]));
if (!parser_->sem_.add_element(nse))
{
parser_->set_synthesis_error("Failed to add new local vector element to SEM [1]");
parser_->sem_.free_element(nse);
result = error_node();
}
exprtk_debug(("vector_element() - INFO - Added new local vector element: %s\n",nse.name.c_str()));
parser_->state_.activate_side_effect("vector_element()");
result = nse.var_node;
}
}
else if (vector_base->rebaseable())
result = node_allocator_->allocate<rebasevector_elem_node_t>(index,vector_base);
else
result = node_allocator_->allocate<vector_elem_node_t>(index,vector_base);
return result;
}
private:
template <std::size_t N, typename NodePtr>
inline bool is_constant_foldable(NodePtr (&b)[N]) const
{
for (std::size_t i = 0; i < N; ++i)
{
if (0 == b[i])
return false;
else if (!details::is_constant_node(b[i]))
return false;
}
return true;
}
template <typename NodePtr,
typename Allocator,
template <typename, typename> class Sequence>
inline bool is_constant_foldable(const Sequence<NodePtr,Allocator>& b) const
{
for (std::size_t i = 0; i < b.size(); ++i)
{
if (0 == b[i])
return false;
else if (!details::is_constant_node(b[i]))
return false;
}
return true;
}
void lodge_assignment(symbol_type cst, expression_node_ptr node)
{
parser_->state_.activate_side_effect("lodge_assignment()");
if (!parser_->dec_.collect_assignments())
return;
std::string symbol_name;
switch (cst)
{
case e_st_variable : symbol_name = parser_->symtab_store_
.get_variable_name(node);
break;
#ifndef exprtk_disable_string_capabilities
case e_st_string : symbol_name = parser_->symtab_store_
.get_stringvar_name(node);
break;
#endif
case e_st_vector : {
typedef details::vector_holder<T> vector_holder_t;
vector_holder_t& vh = static_cast<vector_node_t*>(node)->vec_holder();
symbol_name = parser_->symtab_store_.get_vector_name(&vh);
}
break;
case e_st_vecelem : {
typedef details::vector_holder<T> vector_holder_t;
vector_holder_t& vh = static_cast<vector_elem_node_t*>(node)->vec_holder();
symbol_name = parser_->symtab_store_.get_vector_name(&vh);
cst = e_st_vector;
}
break;
default : return;
}
if (!symbol_name.empty())
{
parser_->dec_.add_assignment(symbol_name,cst);
}
}
const void* base_ptr(expression_node_ptr node)
{
if (node)
{
switch(node->type())
{
case details::expression_node<T>::e_variable:
return reinterpret_cast<const void*>(&static_cast<variable_node_t*>(node)->ref());
case details::expression_node<T>::e_vecelem:
return reinterpret_cast<const void*>(&static_cast<vector_elem_node_t*>(node)->ref());
case details::expression_node<T>::e_rbvecelem:
return reinterpret_cast<const void*>(&static_cast<rebasevector_elem_node_t*>(node)->ref());
case details::expression_node<T>::e_rbveccelem:
return reinterpret_cast<const void*>(&static_cast<rebasevector_celem_node_t*>(node)->ref());
case details::expression_node<T>::e_vector:
return reinterpret_cast<const void*>(static_cast<vector_node_t*>(node)->vec_holder().data());
#ifndef exprtk_disable_string_capabilities
case details::expression_node<T>::e_stringvar:
return reinterpret_cast<const void*>((static_cast<stringvar_node_t*>(node)->base()));
case details::expression_node<T>::e_stringvarrng:
return reinterpret_cast<const void*>((static_cast<string_range_node_t*>(node)->base()));
#endif
default : return reinterpret_cast<const void*>(0);
}
}
return reinterpret_cast<const void*>(0);
}
bool assign_immutable_symbol(expression_node_ptr node)
{
interval_t interval;
const void* baseptr_addr = base_ptr(node);
exprtk_debug(("assign_immutable_symbol - base ptr addr: %p\n", baseptr_addr));
if (parser_->immutable_memory_map_.in_interval(baseptr_addr,interval))
{
typename immutable_symtok_map_t::iterator itr = parser_->immutable_symtok_map_.find(interval);
if (parser_->immutable_symtok_map_.end() != itr)
{
token_t& token = itr->second;
parser_->set_error(
parser_error::make_error(parser_error::e_parser,
token,
"ERR211 - Symbol '" + token.value + "' cannot be assigned-to as it is immutable.",
exprtk_error_location));
}
else
parser_->set_synthesis_error("Unable to assign symbol is immutable.");
return true;
}
return false;
}
inline expression_node_ptr synthesize_assignment_expression(const details::operator_type& operation, expression_node_ptr (&branch)[2])
{
if (assign_immutable_symbol(branch[0]))
{
return error_node();
}
else if (details::is_variable_node(branch[0]))
{
lodge_assignment(e_st_variable,branch[0]);
return synthesize_expression<assignment_node_t,2>(operation,branch);
}
else if (details::is_vector_elem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
return synthesize_expression<assignment_vec_elem_node_t, 2>(operation, branch);
}
else if (details::is_rebasevector_elem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
return synthesize_expression<assignment_rebasevec_elem_node_t, 2>(operation, branch);
}
else if (details::is_rebasevector_celem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
return synthesize_expression<assignment_rebasevec_celem_node_t, 2>(operation, branch);
}
#ifndef exprtk_disable_string_capabilities
else if (details::is_string_node(branch[0]))
{
lodge_assignment(e_st_string,branch[0]);
return synthesize_expression<assignment_string_node_t,2>(operation, branch);
}
else if (details::is_string_range_node(branch[0]))
{
lodge_assignment(e_st_string,branch[0]);
return synthesize_expression<assignment_string_range_node_t,2>(operation, branch);
}
#endif
else if (details::is_vector_node(branch[0]))
{
lodge_assignment(e_st_vector,branch[0]);
if (details::is_ivector_node(branch[1]))
return synthesize_expression<assignment_vecvec_node_t,2>(operation, branch);
else
return synthesize_expression<assignment_vec_node_t,2>(operation, branch);
}
else
{
parser_->set_synthesis_error("Invalid assignment operation.[1]");
return error_node();
}
}
inline expression_node_ptr synthesize_assignment_operation_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
if (assign_immutable_symbol(branch[0]))
{
return error_node();
}
if (details::is_variable_node(branch[0]))
{
lodge_assignment(e_st_variable,branch[0]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
else if (details::is_vector_elem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_vec_elem_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
else if (details::is_rebasevector_elem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_rebasevec_elem_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
else if (details::is_rebasevector_celem_node(branch[0]))
{
lodge_assignment(e_st_vecelem,branch[0]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_rebasevec_celem_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
else if (details::is_vector_node(branch[0]))
{
lodge_assignment(e_st_vector,branch[0]);
if (details::is_ivector_node(branch[1]))
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_vecvec_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
else
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::assignment_vec_op_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
case_stmt(details::e_addass , details::add_op)
case_stmt(details::e_subass , details::sub_op)
case_stmt(details::e_mulass , details::mul_op)
case_stmt(details::e_divass , details::div_op)
case_stmt(details::e_modass , details::mod_op)
#undef case_stmt
default : return error_node();
}
}
}
#ifndef exprtk_disable_string_capabilities
else if (
(details::e_addass == operation) &&
details::is_string_node(branch[0])
)
{
typedef details::assignment_string_node<T,details::asn_addassignment> addass_t;
lodge_assignment(e_st_string,branch[0]);
return synthesize_expression<addass_t,2>(operation,branch);
}
#endif
else
{
parser_->set_synthesis_error("Invalid assignment operation[2]");
return error_node();
}
}
inline expression_node_ptr synthesize_veceqineqlogic_operation_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const bool is_b0_ivec = details::is_ivector_node(branch[0]);
const bool is_b1_ivec = details::is_ivector_node(branch[1]);
#define batch_eqineq_logic_case \
case_stmt(details::e_lt , details::lt_op ) \
case_stmt(details::e_lte , details::lte_op ) \
case_stmt(details::e_gt , details::gt_op ) \
case_stmt(details::e_gte , details::gte_op ) \
case_stmt(details::e_eq , details::eq_op ) \
case_stmt(details::e_ne , details::ne_op ) \
case_stmt(details::e_equal , details::equal_op) \
case_stmt(details::e_and , details::and_op ) \
case_stmt(details::e_nand , details::nand_op ) \
case_stmt(details::e_or , details::or_op ) \
case_stmt(details::e_nor , details::nor_op ) \
case_stmt(details::e_xor , details::xor_op ) \
case_stmt(details::e_xnor , details::xnor_op ) \
if (is_b0_ivec && is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_vecvec_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
batch_eqineq_logic_case
#undef case_stmt
default : return error_node();
}
}
else if (is_b0_ivec && !is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_vecval_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
batch_eqineq_logic_case
#undef case_stmt
default : return error_node();
}
}
else if (!is_b0_ivec && is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_valvec_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
batch_eqineq_logic_case
#undef case_stmt
default : return error_node();
}
}
else
return error_node();
#undef batch_eqineq_logic_case
}
inline expression_node_ptr synthesize_vecarithmetic_operation_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const bool is_b0_ivec = details::is_ivector_node(branch[0]);
const bool is_b1_ivec = details::is_ivector_node(branch[1]);
#define vector_ops \
case_stmt(details::e_add , details::add_op) \
case_stmt(details::e_sub , details::sub_op) \
case_stmt(details::e_mul , details::mul_op) \
case_stmt(details::e_div , details::div_op) \
case_stmt(details::e_mod , details::mod_op) \
if (is_b0_ivec && is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_vecvec_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
vector_ops
case_stmt(details::e_pow,details:: pow_op)
#undef case_stmt
default : return error_node();
}
}
else if (is_b0_ivec && !is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_vecval_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
vector_ops
case_stmt(details::e_pow,details:: pow_op)
#undef case_stmt
default : return error_node();
}
}
else if (!is_b0_ivec && is_b1_ivec)
{
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
template allocate_rrr<typename details::vec_binop_valvec_node<Type,op1<Type> > > \
(operation, branch[0], branch[1]); \
vector_ops
#undef case_stmt
default : return error_node();
}
}
else
return error_node();
#undef vector_ops
}
inline expression_node_ptr synthesize_swap_expression(expression_node_ptr (&branch)[2])
{
const bool v0_is_ivar = details::is_ivariable_node(branch[0]);
const bool v1_is_ivar = details::is_ivariable_node(branch[1]);
const bool v0_is_ivec = details::is_ivector_node (branch[0]);
const bool v1_is_ivec = details::is_ivector_node (branch[1]);
#ifndef exprtk_disable_string_capabilities
const bool v0_is_str = details::is_generally_string_node(branch[0]);
const bool v1_is_str = details::is_generally_string_node(branch[1]);
#endif
expression_node_ptr result = error_node();
if (v0_is_ivar && v1_is_ivar)
{
typedef details::variable_node<T>* variable_node_ptr;
variable_node_ptr v0 = variable_node_ptr(0);
variable_node_ptr v1 = variable_node_ptr(0);
if (
(0 != (v0 = dynamic_cast<variable_node_ptr>(branch[0]))) &&
(0 != (v1 = dynamic_cast<variable_node_ptr>(branch[1])))
)
{
result = node_allocator_->allocate<details::swap_node<T> >(v0,v1);
}
else
result = node_allocator_->allocate<details::swap_generic_node<T> >(branch[0],branch[1]);
}
else if (v0_is_ivec && v1_is_ivec)
{
result = node_allocator_->allocate<details::swap_vecvec_node<T> >(branch[0],branch[1]);
}
#ifndef exprtk_disable_string_capabilities
else if (v0_is_str && v1_is_str)
{
if (is_string_node(branch[0]) && is_string_node(branch[1]))
result = node_allocator_->allocate<details::swap_string_node<T> >
(branch[0], branch[1]);
else
result = node_allocator_->allocate<details::swap_genstrings_node<T> >
(branch[0], branch[1]);
}
#endif
else
{
parser_->set_synthesis_error("Only variables, strings, vectors or vector elements can be swapped");
return error_node();
}
parser_->state_.activate_side_effect("synthesize_swap_expression()");
return result;
}
#ifndef exprtk_disable_sc_andor
inline expression_node_ptr synthesize_shortcircuit_expression(const details::operator_type& operation, expression_node_ptr (&branch)[2])
{
expression_node_ptr result = error_node();
if (details::is_constant_node(branch[0]))
{
if (
(details::e_scand == operation) &&
std::equal_to<T>()(T(0),branch[0]->value())
)
result = node_allocator_->allocate_c<literal_node_t>(T(0));
else if (
(details::e_scor == operation) &&
std::not_equal_to<T>()(T(0),branch[0]->value())
)
result = node_allocator_->allocate_c<literal_node_t>(T(1));
}
if (details::is_constant_node(branch[1]) && (0 == result))
{
if (
(details::e_scand == operation) &&
std::equal_to<T>()(T(0),branch[1]->value())
)
result = node_allocator_->allocate_c<literal_node_t>(T(0));
else if (
(details::e_scor == operation) &&
std::not_equal_to<T>()(T(0),branch[1]->value())
)
result = node_allocator_->allocate_c<literal_node_t>(T(1));
}
if (result)
{
details::free_node(*node_allocator_, branch[0]);
details::free_node(*node_allocator_, branch[1]);
return result;
}
else if (details::e_scand == operation)
{
return synthesize_expression<scand_node_t,2>(operation, branch);
}
else if (details::e_scor == operation)
{
return synthesize_expression<scor_node_t,2>(operation, branch);
}
else
return error_node();
}
#else
inline expression_node_ptr synthesize_shortcircuit_expression(const details::operator_type&, expression_node_ptr (&)[2])
{
return error_node();
}
#endif
#define basic_opr_switch_statements \
case_stmt(details::e_add , details::add_op) \
case_stmt(details::e_sub , details::sub_op) \
case_stmt(details::e_mul , details::mul_op) \
case_stmt(details::e_div , details::div_op) \
case_stmt(details::e_mod , details::mod_op) \
case_stmt(details::e_pow , details::pow_op) \
#define extended_opr_switch_statements \
case_stmt(details::e_lt , details::lt_op ) \
case_stmt(details::e_lte , details::lte_op ) \
case_stmt(details::e_gt , details::gt_op ) \
case_stmt(details::e_gte , details::gte_op ) \
case_stmt(details::e_eq , details::eq_op ) \
case_stmt(details::e_ne , details::ne_op ) \
case_stmt(details::e_and , details::and_op ) \
case_stmt(details::e_nand , details::nand_op) \
case_stmt(details::e_or , details::or_op ) \
case_stmt(details::e_nor , details::nor_op ) \
case_stmt(details::e_xor , details::xor_op ) \
case_stmt(details::e_xnor , details::xnor_op) \
#ifndef exprtk_disable_cardinal_pow_optimisation
template <typename TType, template <typename, typename> class IPowNode>
inline expression_node_ptr cardinal_pow_optimisation_impl(const TType& v, const unsigned int& p)
{
switch (p)
{
#define case_stmt(cp) \
case cp : return node_allocator_-> \
allocate<IPowNode<T,details::numeric::fast_exp<T,cp> > >(v); \
case_stmt( 1) case_stmt( 2) case_stmt( 3) case_stmt( 4)
case_stmt( 5) case_stmt( 6) case_stmt( 7) case_stmt( 8)
case_stmt( 9) case_stmt(10) case_stmt(11) case_stmt(12)
case_stmt(13) case_stmt(14) case_stmt(15) case_stmt(16)
case_stmt(17) case_stmt(18) case_stmt(19) case_stmt(20)
case_stmt(21) case_stmt(22) case_stmt(23) case_stmt(24)
case_stmt(25) case_stmt(26) case_stmt(27) case_stmt(28)
case_stmt(29) case_stmt(30) case_stmt(31) case_stmt(32)
case_stmt(33) case_stmt(34) case_stmt(35) case_stmt(36)
case_stmt(37) case_stmt(38) case_stmt(39) case_stmt(40)
case_stmt(41) case_stmt(42) case_stmt(43) case_stmt(44)
case_stmt(45) case_stmt(46) case_stmt(47) case_stmt(48)
case_stmt(49) case_stmt(50) case_stmt(51) case_stmt(52)
case_stmt(53) case_stmt(54) case_stmt(55) case_stmt(56)
case_stmt(57) case_stmt(58) case_stmt(59) case_stmt(60)
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr cardinal_pow_optimisation(const T& v, const T& c)
{
const bool not_recipricol = (c >= T(0));
const unsigned int p = static_cast<unsigned int>(details::numeric::to_int32(details::numeric::abs(c)));
if (0 == p)
return node_allocator_->allocate_c<literal_node_t>(T(1));
else if (std::equal_to<T>()(T(2),c))
{
return node_allocator_->
template allocate_rr<typename details::vov_node<Type,details::mul_op<Type> > >(v,v);
}
else
{
if (not_recipricol)
return cardinal_pow_optimisation_impl<T,details::ipow_node>(v,p);
else
return cardinal_pow_optimisation_impl<T,details::ipowinv_node>(v,p);
}
}
inline bool cardinal_pow_optimisable(const details::operator_type& operation, const T& c) const
{
return (details::e_pow == operation) && (details::numeric::abs(c) <= T(60)) && details::numeric::is_integer(c);
}
inline expression_node_ptr cardinal_pow_optimisation(expression_node_ptr (&branch)[2])
{
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
const bool not_recipricol = (c >= T(0));
const unsigned int p = static_cast<unsigned int>(details::numeric::to_int32(details::numeric::abs(c)));
node_allocator_->free(branch[1]);
if (0 == p)
{
details::free_all_nodes(*node_allocator_, branch);
return node_allocator_->allocate_c<literal_node_t>(T(1));
}
else if (not_recipricol)
return cardinal_pow_optimisation_impl<expression_node_ptr,details::bipow_node>(branch[0],p);
else
return cardinal_pow_optimisation_impl<expression_node_ptr,details::bipowninv_node>(branch[0],p);
}
#else
inline expression_node_ptr cardinal_pow_optimisation(T&, const T&)
{
return error_node();
}
inline bool cardinal_pow_optimisable(const details::operator_type&, const T&)
{
return false;
}
inline expression_node_ptr cardinal_pow_optimisation(expression_node_ptr(&)[2])
{
return error_node();
}
#endif
struct synthesize_binary_ext_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const bool left_neg = is_neg_unary_node(branch[0]);
const bool right_neg = is_neg_unary_node(branch[1]);
if (left_neg && right_neg)
{
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
if (
!expr_gen.parser_->simplify_unary_negation_branch(branch[0]) ||
!expr_gen.parser_->simplify_unary_negation_branch(branch[1])
)
{
details::free_all_nodes(*expr_gen.node_allocator_,branch);
return error_node();
}
}
switch (operation)
{
// -f(x + 1) + -g(y + 1) --> -(f(x + 1) + g(y + 1))
case details::e_add : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::add_op<Type> > >
(branch[0],branch[1]));
// -f(x + 1) - -g(y + 1) --> g(y + 1) - f(x + 1)
case details::e_sub : return expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::sub_op<Type> > >
(branch[1],branch[0]);
default : break;
}
}
else if (left_neg && !right_neg)
{
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
if (!expr_gen.parser_->simplify_unary_negation_branch(branch[0]))
{
details::free_all_nodes(*expr_gen.node_allocator_,branch);
return error_node();
}
switch (operation)
{
// -f(x + 1) + g(y + 1) --> g(y + 1) - f(x + 1)
case details::e_add : return expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::sub_op<Type> > >
(branch[1], branch[0]);
// -f(x + 1) - g(y + 1) --> -(f(x + 1) + g(y + 1))
case details::e_sub : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::add_op<Type> > >
(branch[0], branch[1]));
// -f(x + 1) * g(y + 1) --> -(f(x + 1) * g(y + 1))
case details::e_mul : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::mul_op<Type> > >
(branch[0], branch[1]));
// -f(x + 1) / g(y + 1) --> -(f(x + 1) / g(y + 1))
case details::e_div : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::div_op<Type> > >
(branch[0], branch[1]));
default : return error_node();
}
}
}
else if (!left_neg && right_neg)
{
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
if (!expr_gen.parser_->simplify_unary_negation_branch(branch[1]))
{
details::free_all_nodes(*expr_gen.node_allocator_,branch);
return error_node();
}
switch (operation)
{
// f(x + 1) + -g(y + 1) --> f(x + 1) - g(y + 1)
case details::e_add : return expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::sub_op<Type> > >
(branch[0], branch[1]);
// f(x + 1) - - g(y + 1) --> f(x + 1) + g(y + 1)
case details::e_sub : return expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::add_op<Type> > >
(branch[0], branch[1]);
// f(x + 1) * -g(y + 1) --> -(f(x + 1) * g(y + 1))
case details::e_mul : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::mul_op<Type> > >
(branch[0], branch[1]));
// f(x + 1) / -g(y + 1) --> -(f(x + 1) / g(y + 1))
case details::e_div : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate<typename details::binary_ext_node<Type,details::div_op<Type> > >
(branch[0], branch[1]));
default : return error_node();
}
}
}
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate<typename details::binary_ext_node<Type,op1<Type> > > \
(branch[0], branch[1]); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_vob_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type& v = static_cast<details::variable_node<Type>*>(branch[0])->ref();
#ifndef exprtk_disable_enhanced_features
if (details::is_sf3ext_node(branch[1]))
{
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile_right<vtype>
(expr_gen, v, operation, branch[1], result);
if (synthesis_result)
{
details::free_node(*expr_gen.node_allocator_,branch[1]);
return result;
}
}
#endif
if (
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
if (details::is_uv_node(branch[1]))
{
typedef details::uv_base_node<Type>* uvbn_ptr_t;
details::operator_type o = static_cast<uvbn_ptr_t>(branch[1])->operation();
if (details::e_neg == o)
{
const Type& v1 = static_cast<uvbn_ptr_t>(branch[1])->v();
details::free_node(*expr_gen.node_allocator_,branch[1]);
switch (operation)
{
case details::e_mul : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::mul_op<Type> > >(v,v1));
case details::e_div : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::div_op<Type> > >(v,v1));
default : break;
}
}
}
}
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_rc<typename details::vob_node<Type,op1<Type> > > \
(v, branch[1]); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_bov_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type& v = static_cast<details::variable_node<Type>*>(branch[1])->ref();
#ifndef exprtk_disable_enhanced_features
if (details::is_sf3ext_node(branch[0]))
{
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile_left<vtype>
(expr_gen, v, operation, branch[0], result);
if (synthesis_result)
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
return result;
}
}
#endif
if (
(details::e_add == operation) ||
(details::e_sub == operation) ||
(details::e_mul == operation) ||
(details::e_div == operation)
)
{
if (details::is_uv_node(branch[0]))
{
typedef details::uv_base_node<Type>* uvbn_ptr_t;
details::operator_type o = static_cast<uvbn_ptr_t>(branch[0])->operation();
if (details::e_neg == o)
{
const Type& v0 = static_cast<uvbn_ptr_t>(branch[0])->v();
details::free_node(*expr_gen.node_allocator_,branch[0]);
switch (operation)
{
case details::e_add : return expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::sub_op<Type> > >(v,v0);
case details::e_sub : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::add_op<Type> > >(v0,v));
case details::e_mul : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::mul_op<Type> > >(v0,v));
case details::e_div : return expr_gen(details::e_neg,
expr_gen.node_allocator_->
template allocate_rr<typename details::
vov_node<Type,details::div_op<Type> > >(v0,v));
default : break;
}
}
}
}
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_cr<typename details::bov_node<Type,op1<Type> > > \
(branch[0], v); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_cob_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
details::free_node(*expr_gen.node_allocator_,branch[0]);
if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_,branch[1]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[1]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
return branch[1];
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
return branch[1];
if (details::is_cob_node(branch[1]))
{
// Simplify expressions of the form:
// 1. (1 * (2 * (3 * (4 * (5 * (6 * (7 * (8 * (9 + x))))))))) --> 40320 * (9 + x)
// 2. (1 + (2 + (3 + (4 + (5 + (6 + (7 + (8 + (9 + x))))))))) --> 45 + x
if (
(details::e_mul == operation) ||
(details::e_add == operation)
)
{
details::cob_base_node<Type>* cobnode = static_cast<details::cob_base_node<Type>*>(branch[1]);
if (operation == cobnode->operation())
{
switch (operation)
{
case details::e_add : cobnode->set_c(c + cobnode->c()); break;
case details::e_mul : cobnode->set_c(c * cobnode->c()); break;
default : return error_node();
}
return cobnode;
}
}
if (operation == details::e_mul)
{
details::cob_base_node<Type>* cobnode = static_cast<details::cob_base_node<Type>*>(branch[1]);
details::operator_type cob_opr = cobnode->operation();
if (
(details::e_div == cob_opr) ||
(details::e_mul == cob_opr)
)
{
switch (cob_opr)
{
case details::e_div : cobnode->set_c(c * cobnode->c()); break;
case details::e_mul : cobnode->set_c(cobnode->c() / c); break;
default : return error_node();
}
return cobnode;
}
}
else if (operation == details::e_div)
{
details::cob_base_node<Type>* cobnode = static_cast<details::cob_base_node<Type>*>(branch[1]);
details::operator_type cob_opr = cobnode->operation();
if (
(details::e_div == cob_opr) ||
(details::e_mul == cob_opr)
)
{
details::expression_node<Type>* new_cobnode = error_node();
switch (cob_opr)
{
case details::e_div : new_cobnode = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::mul_op<Type> > >
(c / cobnode->c(), cobnode->move_branch(0));
break;
case details::e_mul : new_cobnode = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::div_op<Type> > >
(c / cobnode->c(), cobnode->move_branch(0));
break;
default : return error_node();
}
details::free_node(*expr_gen.node_allocator_,branch[1]);
return new_cobnode;
}
}
}
#ifndef exprtk_disable_enhanced_features
else if (details::is_sf3ext_node(branch[1]))
{
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile_right<ctype>
(expr_gen, c, operation, branch[1], result);
if (synthesis_result)
{
details::free_node(*expr_gen.node_allocator_,branch[1]);
return result;
}
}
#endif
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_tt<typename details::cob_node<Type,op1<Type> > > \
(c, branch[1]); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_boc_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
details::free_node(*(expr_gen.node_allocator_), branch[1]);
if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
return expr_gen(std::numeric_limits<T>::quiet_NaN());
}
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
return branch[0];
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
return branch[0];
if (details::is_boc_node(branch[0]))
{
// Simplify expressions of the form:
// 1. (((((((((x + 9) * 8) * 7) * 6) * 5) * 4) * 3) * 2) * 1) --> (x + 9) * 40320
// 2. (((((((((x + 9) + 8) + 7) + 6) + 5) + 4) + 3) + 2) + 1) --> x + 45
if (
(details::e_mul == operation) ||
(details::e_add == operation)
)
{
details::boc_base_node<Type>* bocnode = static_cast<details::boc_base_node<Type>*>(branch[0]);
if (operation == bocnode->operation())
{
switch (operation)
{
case details::e_add : bocnode->set_c(c + bocnode->c()); break;
case details::e_mul : bocnode->set_c(c * bocnode->c()); break;
default : return error_node();
}
return bocnode;
}
}
else if (operation == details::e_div)
{
details::boc_base_node<Type>* bocnode = static_cast<details::boc_base_node<Type>*>(branch[0]);
details::operator_type boc_opr = bocnode->operation();
if (
(details::e_div == boc_opr) ||
(details::e_mul == boc_opr)
)
{
switch (boc_opr)
{
case details::e_div : bocnode->set_c(c * bocnode->c()); break;
case details::e_mul : bocnode->set_c(bocnode->c() / c); break;
default : return error_node();
}
return bocnode;
}
}
else if (operation == details::e_pow)
{
// (v ^ c0) ^ c1 --> v ^(c0 * c1)
details::boc_base_node<Type>* bocnode = static_cast<details::boc_base_node<Type>*>(branch[0]);
details::operator_type boc_opr = bocnode->operation();
if (details::e_pow == boc_opr)
{
bocnode->set_c(bocnode->c() * c);
return bocnode;
}
}
}
#ifndef exprtk_disable_enhanced_features
if (details::is_sf3ext_node(branch[0]))
{
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile_left<ctype>
(expr_gen, c, operation, branch[0], result);
if (synthesis_result)
{
free_node(*expr_gen.node_allocator_, branch[0]);
return result;
}
}
#endif
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_cr<typename details::boc_node<Type,op1<Type> > > \
(branch[0], c); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_cocob_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
expression_node_ptr result = error_node();
// (cob) o c --> cob
if (details::is_cob_node(branch[0]))
{
details::cob_base_node<Type>* cobnode = static_cast<details::cob_base_node<Type>*>(branch[0]);
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
details::free_node(*expr_gen.node_allocator_, branch[1]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
details::free_node(*expr_gen.node_allocator_, branch[1]);
return expr_gen(T(std::numeric_limits<T>::quiet_NaN()));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[1]);
return branch[0];
}
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[1]);
return branch[0];
}
else if (std::equal_to<T>()(T(1),c) && (details::e_div == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[1]);
return branch[0];
}
const bool op_addsub = (details::e_add == cobnode->operation()) ||
(details::e_sub == cobnode->operation()) ;
if (op_addsub)
{
switch (operation)
{
case details::e_add : cobnode->set_c(cobnode->c() + c); break;
case details::e_sub : cobnode->set_c(cobnode->c() - c); break;
default : return error_node();
}
result = cobnode;
}
else if (details::e_mul == cobnode->operation())
{
switch (operation)
{
case details::e_mul : cobnode->set_c(cobnode->c() * c); break;
case details::e_div : cobnode->set_c(cobnode->c() / c); break;
default : return error_node();
}
result = cobnode;
}
else if (details::e_div == cobnode->operation())
{
if (details::e_mul == operation)
{
cobnode->set_c(cobnode->c() * c);
result = cobnode;
}
else if (details::e_div == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::div_op<Type> > >
(cobnode->c() / c, cobnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_, branch[0]);
}
}
if (result)
{
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
// c o (cob) --> cob
else if (details::is_cob_node(branch[1]))
{
details::cob_base_node<Type>* cobnode = static_cast<details::cob_base_node<Type>*>(branch[1]);
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
details::free_node(*expr_gen.node_allocator_, branch[1]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
details::free_node(*expr_gen.node_allocator_, branch[1]);
return expr_gen(T(0));
}
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
return branch[1];
}
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
{
details::free_node(*expr_gen.node_allocator_, branch[0]);
return branch[1];
}
if (details::e_add == cobnode->operation())
{
if (details::e_add == operation)
{
cobnode->set_c(c + cobnode->c());
result = cobnode;
}
else if (details::e_sub == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::sub_op<Type> > >
(c - cobnode->c(), cobnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_sub == cobnode->operation())
{
if (details::e_add == operation)
{
cobnode->set_c(c + cobnode->c());
result = cobnode;
}
else if (details::e_sub == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::add_op<Type> > >
(c - cobnode->c(), cobnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_mul == cobnode->operation())
{
if (details::e_mul == operation)
{
cobnode->set_c(c * cobnode->c());
result = cobnode;
}
else if (details::e_div == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::div_op<Type> > >
(c / cobnode->c(), cobnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_div == cobnode->operation())
{
if (details::e_mul == operation)
{
cobnode->set_c(c * cobnode->c());
result = cobnode;
}
else if (details::e_div == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::mul_op<Type> > >
(c / cobnode->c(), cobnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
if (result)
{
details::free_node(*expr_gen.node_allocator_,branch[0]);
}
}
return result;
}
};
struct synthesize_coboc_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
expression_node_ptr result = error_node();
// (boc) o c --> boc
if (details::is_boc_node(branch[0]))
{
details::boc_base_node<Type>* bocnode = static_cast<details::boc_base_node<Type>*>(branch[0]);
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
if (details::e_add == bocnode->operation())
{
switch (operation)
{
case details::e_add : bocnode->set_c(bocnode->c() + c); break;
case details::e_sub : bocnode->set_c(bocnode->c() - c); break;
default : return error_node();
}
result = bocnode;
}
else if (details::e_mul == bocnode->operation())
{
switch (operation)
{
case details::e_mul : bocnode->set_c(bocnode->c() * c); break;
case details::e_div : bocnode->set_c(bocnode->c() / c); break;
default : return error_node();
}
result = bocnode;
}
else if (details::e_sub == bocnode->operation())
{
if (details::e_add == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::boc_node<Type,details::add_op<Type> > >
(bocnode->move_branch(0), c - bocnode->c());
details::free_node(*expr_gen.node_allocator_,branch[0]);
}
else if (details::e_sub == operation)
{
bocnode->set_c(bocnode->c() + c);
result = bocnode;
}
}
else if (details::e_div == bocnode->operation())
{
switch (operation)
{
case details::e_div : bocnode->set_c(bocnode->c() * c); break;
case details::e_mul : bocnode->set_c(bocnode->c() / c); break;
default : return error_node();
}
result = bocnode;
}
if (result)
{
details::free_node(*expr_gen.node_allocator_, branch[1]);
}
}
// c o (boc) --> boc
else if (details::is_boc_node(branch[1]))
{
details::boc_base_node<Type>* bocnode = static_cast<details::boc_base_node<Type>*>(branch[1]);
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
if (details::e_add == bocnode->operation())
{
if (details::e_add == operation)
{
bocnode->set_c(c + bocnode->c());
result = bocnode;
}
else if (details::e_sub == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::sub_op<Type> > >
(c - bocnode->c(), bocnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_sub == bocnode->operation())
{
if (details::e_add == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::boc_node<Type,details::add_op<Type> > >
(bocnode->move_branch(0), c - bocnode->c());
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
else if (details::e_sub == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::sub_op<Type> > >
(c + bocnode->c(), bocnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_mul == bocnode->operation())
{
if (details::e_mul == operation)
{
bocnode->set_c(c * bocnode->c());
result = bocnode;
}
else if (details::e_div == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::div_op<Type> > >
(c / bocnode->c(), bocnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
else if (details::e_div == bocnode->operation())
{
if (details::e_mul == operation)
{
bocnode->set_c(bocnode->c() / c);
result = bocnode;
}
else if (details::e_div == operation)
{
result = expr_gen.node_allocator_->
template allocate_tt<typename details::cob_node<Type,details::div_op<Type> > >
(c * bocnode->c(), bocnode->move_branch(0));
details::free_node(*expr_gen.node_allocator_,branch[1]);
}
}
if (result)
{
details::free_node(*expr_gen.node_allocator_,branch[0]);
}
}
return result;
}
};
#ifndef exprtk_disable_enhanced_features
inline bool synthesize_expression(const details::operator_type& operation,
expression_node_ptr (&branch)[2],
expression_node_ptr& result)
{
result = error_node();
if (!operation_optimisable(operation))
return false;
const std::string node_id = branch_to_id(branch);
const typename synthesize_map_t::iterator itr = synthesize_map_.find(node_id);
if (synthesize_map_.end() != itr)
{
result = itr->second((*this), operation, branch);
return true;
}
else
return false;
}
struct synthesize_vov_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_rr<typename details::vov_node<Type,op1<Type> > > \
(v1, v2); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_cov_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type c = static_cast<details::literal_node<Type>*> (branch[0])->value();
const Type& v = static_cast<details::variable_node<Type>*>(branch[1])->ref ();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
return expr_gen(T(0));
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
return expr_gen(T(0));
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
return static_cast<details::variable_node<Type>*>(branch[1]);
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
return static_cast<details::variable_node<Type>*>(branch[1]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_cr<typename details::cov_node<Type,op1<Type> > > \
(c, v); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_voc_expression
{
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
const Type& v = static_cast<details::variable_node<Type>*>(branch[0])->ref ();
const Type c = static_cast<details::literal_node<Type>*> (branch[1])->value();
details::free_node(*(expr_gen.node_allocator_), branch[1]);
if (expr_gen.cardinal_pow_optimisable(operation,c))
{
if (std::equal_to<T>()(T(1),c))
return branch[0];
else
return expr_gen.cardinal_pow_optimisation(v,c);
}
else if (std::equal_to<T>()(T(0),c) && (details::e_mul == operation))
return expr_gen(T(0));
else if (std::equal_to<T>()(T(0),c) && (details::e_div == operation))
return expr_gen(std::numeric_limits<T>::quiet_NaN());
else if (std::equal_to<T>()(T(0),c) && (details::e_add == operation))
return static_cast<details::variable_node<Type>*>(branch[0]);
else if (std::equal_to<T>()(T(1),c) && (details::e_mul == operation))
return static_cast<details::variable_node<Type>*>(branch[0]);
else if (std::equal_to<T>()(T(1),c) && (details::e_div == operation))
return static_cast<details::variable_node<Type>*>(branch[0]);
switch (operation)
{
#define case_stmt(op0, op1) \
case op0 : return expr_gen.node_allocator_-> \
template allocate_rc<typename details::voc_node<Type,op1<Type> > > \
(v, c); \
basic_opr_switch_statements
extended_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
};
struct synthesize_sf3ext_expression
{
template <typename T0, typename T1, typename T2>
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& sf3opr,
T0 t0, T1 t1, T2 t2)
{
switch (sf3opr)
{
#define case_stmt(op) \
case details::e_sf##op : return details::T0oT1oT2_sf3ext<T,T0,T1,T2,details::sf##op##_op<Type> >:: \
allocate(*(expr_gen.node_allocator_), t0, t1, t2); \
case_stmt(00) case_stmt(01) case_stmt(02) case_stmt(03)
case_stmt(04) case_stmt(05) case_stmt(06) case_stmt(07)
case_stmt(08) case_stmt(09) case_stmt(10) case_stmt(11)
case_stmt(12) case_stmt(13) case_stmt(14) case_stmt(15)
case_stmt(16) case_stmt(17) case_stmt(18) case_stmt(19)
case_stmt(20) case_stmt(21) case_stmt(22) case_stmt(23)
case_stmt(24) case_stmt(25) case_stmt(26) case_stmt(27)
case_stmt(28) case_stmt(29) case_stmt(30)
#undef case_stmt
default : return error_node();
}
}
template <typename T0, typename T1, typename T2>
static inline bool compile(expression_generator<Type>& expr_gen, const std::string& id,
T0 t0, T1 t1, T2 t2,
expression_node_ptr& result)
{
details::operator_type sf3opr;
if (!expr_gen.sf3_optimisable(id,sf3opr))
return false;
else
result = synthesize_sf3ext_expression::template process<T0, T1, T2>
(expr_gen, sf3opr, t0, t1, t2);
return true;
}
};
struct synthesize_sf4ext_expression
{
template <typename T0, typename T1, typename T2, typename T3>
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& sf4opr,
T0 t0, T1 t1, T2 t2, T3 t3)
{
switch (sf4opr)
{
#define case_stmt0(op) \
case details::e_sf##op : return details::T0oT1oT2oT3_sf4ext<Type,T0,T1,T2,T3,details::sf##op##_op<Type> >:: \
allocate(*(expr_gen.node_allocator_), t0, t1, t2, t3); \
#define case_stmt1(op) \
case details::e_sf4ext##op : return details::T0oT1oT2oT3_sf4ext<Type,T0,T1,T2,T3,details::sfext##op##_op<Type> >:: \
allocate(*(expr_gen.node_allocator_), t0, t1, t2, t3); \
case_stmt0(48) case_stmt0(49) case_stmt0(50) case_stmt0(51)
case_stmt0(52) case_stmt0(53) case_stmt0(54) case_stmt0(55)
case_stmt0(56) case_stmt0(57) case_stmt0(58) case_stmt0(59)
case_stmt0(60) case_stmt0(61) case_stmt0(62) case_stmt0(63)
case_stmt0(64) case_stmt0(65) case_stmt0(66) case_stmt0(67)
case_stmt0(68) case_stmt0(69) case_stmt0(70) case_stmt0(71)
case_stmt0(72) case_stmt0(73) case_stmt0(74) case_stmt0(75)
case_stmt0(76) case_stmt0(77) case_stmt0(78) case_stmt0(79)
case_stmt0(80) case_stmt0(81) case_stmt0(82) case_stmt0(83)
case_stmt1(00) case_stmt1(01) case_stmt1(02) case_stmt1(03)
case_stmt1(04) case_stmt1(05) case_stmt1(06) case_stmt1(07)
case_stmt1(08) case_stmt1(09) case_stmt1(10) case_stmt1(11)
case_stmt1(12) case_stmt1(13) case_stmt1(14) case_stmt1(15)
case_stmt1(16) case_stmt1(17) case_stmt1(18) case_stmt1(19)
case_stmt1(20) case_stmt1(21) case_stmt1(22) case_stmt1(23)
case_stmt1(24) case_stmt1(25) case_stmt1(26) case_stmt1(27)
case_stmt1(28) case_stmt1(29) case_stmt1(30) case_stmt1(31)
case_stmt1(32) case_stmt1(33) case_stmt1(34) case_stmt1(35)
case_stmt1(36) case_stmt1(37) case_stmt1(38) case_stmt1(39)
case_stmt1(40) case_stmt1(41) case_stmt1(42) case_stmt1(43)
case_stmt1(44) case_stmt1(45) case_stmt1(46) case_stmt1(47)
case_stmt1(48) case_stmt1(49) case_stmt1(50) case_stmt1(51)
case_stmt1(52) case_stmt1(53) case_stmt1(54) case_stmt1(55)
case_stmt1(56) case_stmt1(57) case_stmt1(58) case_stmt1(59)
case_stmt1(60) case_stmt1(61)
#undef case_stmt0
#undef case_stmt1
default : return error_node();
}
}
template <typename T0, typename T1, typename T2, typename T3>
static inline bool compile(expression_generator<Type>& expr_gen, const std::string& id,
T0 t0, T1 t1, T2 t2, T3 t3,
expression_node_ptr& result)
{
details::operator_type sf4opr;
if (!expr_gen.sf4_optimisable(id,sf4opr))
return false;
else
result = synthesize_sf4ext_expression::template process<T0, T1, T2, T3>
(expr_gen, sf4opr, t0, t1, t2, t3);
return true;
}
// T o (sf3ext)
template <typename ExternalType>
static inline bool compile_right(expression_generator<Type>& expr_gen,
ExternalType t,
const details::operator_type& operation,
expression_node_ptr& sf3node,
expression_node_ptr& result)
{
if (!details::is_sf3ext_node(sf3node))
return false;
typedef details::T0oT1oT2_base_node<Type>* sf3ext_base_ptr;
sf3ext_base_ptr n = static_cast<sf3ext_base_ptr>(sf3node);
const std::string id = "t" + expr_gen.to_str(operation) + "(" + n->type_id() + ")";
switch (n->type())
{
case details::expression_node<Type>::e_covoc : return compile_right_impl
<typename covoc_t::sf3_type_node,ExternalType, ctype, vtype, ctype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_covov : return compile_right_impl
<typename covov_t::sf3_type_node,ExternalType, ctype, vtype, vtype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vocov : return compile_right_impl
<typename vocov_t::sf3_type_node,ExternalType, vtype, ctype, vtype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vovoc : return compile_right_impl
<typename vovoc_t::sf3_type_node,ExternalType, vtype, vtype, ctype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vovov : return compile_right_impl
<typename vovov_t::sf3_type_node,ExternalType, vtype, vtype, vtype>
(expr_gen, id, t, sf3node, result);
default : return false;
}
}
// (sf3ext) o T
template <typename ExternalType>
static inline bool compile_left(expression_generator<Type>& expr_gen,
ExternalType t,
const details::operator_type& operation,
expression_node_ptr& sf3node,
expression_node_ptr& result)
{
if (!details::is_sf3ext_node(sf3node))
return false;
typedef details::T0oT1oT2_base_node<Type>* sf3ext_base_ptr;
sf3ext_base_ptr n = static_cast<sf3ext_base_ptr>(sf3node);
const std::string id = "(" + n->type_id() + ")" + expr_gen.to_str(operation) + "t";
switch (n->type())
{
case details::expression_node<Type>::e_covoc : return compile_left_impl
<typename covoc_t::sf3_type_node,ExternalType, ctype, vtype, ctype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_covov : return compile_left_impl
<typename covov_t::sf3_type_node,ExternalType, ctype, vtype, vtype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vocov : return compile_left_impl
<typename vocov_t::sf3_type_node,ExternalType, vtype, ctype, vtype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vovoc : return compile_left_impl
<typename vovoc_t::sf3_type_node,ExternalType, vtype, vtype, ctype>
(expr_gen, id, t, sf3node, result);
case details::expression_node<Type>::e_vovov : return compile_left_impl
<typename vovov_t::sf3_type_node,ExternalType, vtype, vtype, vtype>
(expr_gen, id, t, sf3node, result);
default : return false;
}
}
template <typename SF3TypeNode, typename ExternalType, typename T0, typename T1, typename T2>
static inline bool compile_right_impl(expression_generator<Type>& expr_gen,
const std::string& id,
ExternalType t,
expression_node_ptr& node,
expression_node_ptr& result)
{
SF3TypeNode* n = dynamic_cast<SF3TypeNode*>(node);
if (n)
{
T0 t0 = n->t0();
T1 t1 = n->t1();
T2 t2 = n->t2();
return synthesize_sf4ext_expression::template compile<ExternalType, T0, T1, T2>
(expr_gen, id, t, t0, t1, t2, result);
}
else
return false;
}
template <typename SF3TypeNode, typename ExternalType, typename T0, typename T1, typename T2>
static inline bool compile_left_impl(expression_generator<Type>& expr_gen,
const std::string& id,
ExternalType t,
expression_node_ptr& node,
expression_node_ptr& result)
{
SF3TypeNode* n = dynamic_cast<SF3TypeNode*>(node);
if (n)
{
T0 t0 = n->t0();
T1 t1 = n->t1();
T2 t2 = n->t2();
return synthesize_sf4ext_expression::template compile<T0, T1, T2, ExternalType>
(expr_gen, id, t0, t1, t2, t, result);
}
else
return false;
}
};
struct synthesize_vovov_expression0
{
typedef typename vovov_t::type0 node_type;
typedef typename vovov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 v1) o1 (v2)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[0]);
const Type& v0 = vov->v0();
const Type& v1 = vov->v1();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = vov->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / v1) / v2 --> (vovov) v0 / (v1 * v2)
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, vtype>(expr_gen, "t/(t*t)", v0, v1, v2, result);
exprtk_debug(("(v0 / v1) / v2 --> (vovov) v0 / (v1 * v2)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, vtype, vtype>
(expr_gen, id(expr_gen, o0, o1), v0, v1, v2, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_vovov_expression1
{
typedef typename vovov_t::type1 node_type;
typedef typename vovov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0) o0 (v1 o1 v2)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vov->v0();
const Type& v2 = vov->v1();
const details::operator_type o0 = operation;
const details::operator_type o1 = vov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// v0 / (v1 / v2) --> (vovov) (v0 * v2) / v1
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, vtype>(expr_gen, "(t*t)/t", v0, v2, v1, result);
exprtk_debug(("v0 / (v1 / v2) --> (vovov) (v0 * v2) / v1\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, vtype, vtype>
(expr_gen, id(expr_gen, o0, o1), v0, v1, v2, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_vovoc_expression0
{
typedef typename vovoc_t::type0 node_type;
typedef typename vovoc_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 v1) o1 (c)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[0]);
const Type& v0 = vov->v0();
const Type& v1 = vov->v1();
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = vov->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / v1) / c --> (vovoc) v0 / (v1 * c)
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, "t/(t*t)", v0, v1, c, result);
exprtk_debug(("(v0 / v1) / c --> (vovoc) v0 / (v1 * c)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, vtype, ctype>
(expr_gen, id(expr_gen, o0, o1), v0, v1, c, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_vovoc_expression1
{
typedef typename vovoc_t::type1 node_type;
typedef typename vovoc_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0) o0 (v1 o1 c)
const details::voc_base_node<Type>* voc = static_cast<const details::voc_base_node<Type>*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = voc->v();
const Type c = voc->c();
const details::operator_type o0 = operation;
const details::operator_type o1 = voc->operation();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// v0 / (v1 / c) --> (vocov) (v0 * c) / v1
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, ctype, vtype>(expr_gen, "(t*t)/t", v0, c, v1, result);
exprtk_debug(("v0 / (v1 / c) --> (vocov) (v0 * c) / v1\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, vtype, ctype>
(expr_gen, id(expr_gen, o0, o1), v0, v1, c, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_vocov_expression0
{
typedef typename vocov_t::type0 node_type;
typedef typename vocov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 c) o1 (v1)
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[0]);
const Type& v0 = voc->v();
const Type c = voc->c();
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = voc->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / c) / v1 --> (vovoc) v0 / (v1 * c)
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, "t/(t*t)", v0, v1, c, result);
exprtk_debug(("(v0 / c) / v1 --> (vovoc) v0 / (v1 * c)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, ctype, vtype>
(expr_gen, id(expr_gen, o0, o1), v0, c, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_vocov_expression1
{
typedef typename vocov_t::type1 node_type;
typedef typename vocov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0) o0 (c o1 v1)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c = cov->c();
const Type& v1 = cov->v();
const details::operator_type o0 = operation;
const details::operator_type o1 = cov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// v0 / (c / v1) --> (vovoc) (v0 * v1) / c
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, "(t*t)/t", v0, v1, c, result);
exprtk_debug(("v0 / (c / v1) --> (vovoc) (v0 * v1) / c\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, ctype, vtype>
(expr_gen, id(expr_gen, o0, o1), v0, c, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_covov_expression0
{
typedef typename covov_t::type0 node_type;
typedef typename covov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c o0 v0) o1 (v1)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[0]);
const Type c = cov->c();
const Type& v0 = cov->v();
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = cov->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c / v0) / v1 --> (covov) c / (v0 * v1)
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t/(t*t)", c, v0, v1, result);
exprtk_debug(("(c / v0) / v1 --> (covov) c / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<ctype, vtype, vtype>
(expr_gen, id(expr_gen, o0, o1), c, v0, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_covov_expression1
{
typedef typename covov_t::type1 node_type;
typedef typename covov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c) o0 (v0 o1 v1)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[1]);
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vov->v0();
const Type& v1 = vov->v1();
const details::operator_type o0 = operation;
const details::operator_type o1 = vov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// c / (v0 / v1) --> (covov) (c * v1) / v0
if ((details::e_div == o0) && (details::e_div == o1))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", c, v1, v0, result);
exprtk_debug(("c / (v0 / v1) --> (covov) (c * v1) / v0\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<ctype, vtype, vtype>
(expr_gen, id(expr_gen, o0, o1), c, v0, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_covoc_expression0
{
typedef typename covoc_t::type0 node_type;
typedef typename covoc_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c0 o0 v) o1 (c1)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[0]);
const Type c0 = cov->c();
const Type& v = cov->v();
const Type c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = cov->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c0 + v) + c1 --> (cov) (c0 + c1) + v
if ((details::e_add == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0 + v) + c1 --> (cov) (c0 + c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 + c1, v);
}
// (c0 + v) - c1 --> (cov) (c0 - c1) + v
else if ((details::e_add == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0 + v) - c1 --> (cov) (c0 - c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 - c1, v);
}
// (c0 - v) + c1 --> (cov) (c0 + c1) - v
else if ((details::e_sub == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0 - v) + c1 --> (cov) (c0 + c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 + c1, v);
}
// (c0 - v) - c1 --> (cov) (c0 - c1) - v
else if ((details::e_sub == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0 - v) - c1 --> (cov) (c0 - c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 - c1, v);
}
// (c0 * v) * c1 --> (cov) (c0 * c1) * v
else if ((details::e_mul == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0 * v) * c1 --> (cov) (c0 * c1) * v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 * c1, v);
}
// (c0 * v) / c1 --> (cov) (c0 / c1) * v
else if ((details::e_mul == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0 * v) / c1 --> (cov) (c0 / c1) * v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 / c1, v);
}
// (c0 / v) * c1 --> (cov) (c0 * c1) / v
else if ((details::e_div == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0 / v) * c1 --> (cov) (c0 * c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 * c1, v);
}
// (c0 / v) / c1 --> (cov) (c0 / c1) / v
else if ((details::e_div == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0 / v) / c1 --> (cov) (c0 / c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 / c1, v);
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<ctype, vtype, ctype>
(expr_gen, id(expr_gen, o0, o1), c0, v, c1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c0, v, c1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_covoc_expression1
{
typedef typename covoc_t::type1 node_type;
typedef typename covoc_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c0) o0 (v o1 c1)
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v = voc->v();
const Type c1 = voc->c();
const details::operator_type o0 = operation;
const details::operator_type o1 = voc->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c0) + (v + c1) --> (cov) (c0 + c1) + v
if ((details::e_add == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0) + (v + c1) --> (cov) (c0 + c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 + c1, v);
}
// (c0) + (v - c1) --> (cov) (c0 - c1) + v
else if ((details::e_add == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0) + (v - c1) --> (cov) (c0 - c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 - c1, v);
}
// (c0) - (v + c1) --> (cov) (c0 - c1) - v
else if ((details::e_sub == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0) - (v + c1) --> (cov) (c0 - c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 - c1, v);
}
// (c0) - (v - c1) --> (cov) (c0 + c1) - v
else if ((details::e_sub == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0) - (v - c1) --> (cov) (c0 + c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 + c1, v);
}
// (c0) * (v * c1) --> (voc) v * (c0 * c1)
else if ((details::e_mul == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0) * (v * c1) --> (voc) v * (c0 * c1)\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 * c1, v);
}
// (c0) * (v / c1) --> (cov) (c0 / c1) * v
else if ((details::e_mul == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0) * (v / c1) --> (cov) (c0 / c1) * v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 / c1, v);
}
// (c0) / (v * c1) --> (cov) (c0 / c1) / v
else if ((details::e_div == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0) / (v * c1) --> (cov) (c0 / c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 / c1, v);
}
// (c0) / (v / c1) --> (cov) (c0 * c1) / v
else if ((details::e_div == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0) / (v / c1) --> (cov) (c0 * c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 * c1, v);
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<ctype, vtype, ctype>
(expr_gen, id(expr_gen, o0, o1), c0, v, c1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c0, v, c1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_cocov_expression0
{
typedef typename cocov_t::type0 node_type;
static inline expression_node_ptr process(expression_generator<Type>&,
const details::operator_type&,
expression_node_ptr (&)[2])
{
// (c0 o0 c1) o1 (v) - Not possible.
return error_node();
}
};
struct synthesize_cocov_expression1
{
typedef typename cocov_t::type1 node_type;
typedef typename cocov_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c0) o0 (c1 o1 v)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type c1 = cov->c();
const Type& v = cov->v();
const details::operator_type o0 = operation;
const details::operator_type o1 = cov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c0) + (c1 + v) --> (cov) (c0 + c1) + v
if ((details::e_add == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0) + (c1 + v) --> (cov) (c0 + c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 + c1, v);
}
// (c0) + (c1 - v) --> (cov) (c0 + c1) - v
else if ((details::e_add == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0) + (c1 - v) --> (cov) (c0 + c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 + c1, v);
}
// (c0) - (c1 + v) --> (cov) (c0 - c1) - v
else if ((details::e_sub == o0) && (details::e_add == o1))
{
exprtk_debug(("(c0) - (c1 + v) --> (cov) (c0 - c1) - v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::sub_op<Type> > >(c0 - c1, v);
}
// (c0) - (c1 - v) --> (cov) (c0 - c1) + v
else if ((details::e_sub == o0) && (details::e_sub == o1))
{
exprtk_debug(("(c0) - (c1 - v) --> (cov) (c0 - c1) + v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::add_op<Type> > >(c0 - c1, v);
}
// (c0) * (c1 * v) --> (cov) (c0 * c1) * v
else if ((details::e_mul == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0) * (c1 * v) --> (cov) (c0 * c1) * v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 * c1, v);
}
// (c0) * (c1 / v) --> (cov) (c0 * c1) / v
else if ((details::e_mul == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0) * (c1 / v) --> (cov) (c0 * c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 * c1, v);
}
// (c0) / (c1 * v) --> (cov) (c0 / c1) / v
else if ((details::e_div == o0) && (details::e_mul == o1))
{
exprtk_debug(("(c0) / (c1 * v) --> (cov) (c0 / c1) / v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::div_op<Type> > >(c0 / c1, v);
}
// (c0) / (c1 / v) --> (cov) (c0 / c1) * v
else if ((details::e_div == o0) && (details::e_div == o1))
{
exprtk_debug(("(c0) / (c1 / v) --> (cov) (c0 / c1) * v\n"));
return expr_gen.node_allocator_->
template allocate_cr<typename details::cov_node<Type,details::mul_op<Type> > >(c0 / c1, v);
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<ctype, ctype, vtype>
(expr_gen, id(expr_gen, o0, o1), c0, c1, v, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c0, c1, v, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)";
}
};
struct synthesize_vococ_expression0
{
typedef typename vococ_t::type0 node_type;
typedef typename vococ_t::sf3_type sf3_type;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v o0 c0) o1 (c1)
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[0]);
const Type& v = voc->v();
const Type& c0 = voc->c();
const Type& c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = voc->operation();
const details::operator_type o1 = operation;
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v + c0) + c1 --> (voc) v + (c0 + c1)
if ((details::e_add == o0) && (details::e_add == o1))
{
exprtk_debug(("(v + c0) + c1 --> (voc) v + (c0 + c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::add_op<Type> > >(v, c0 + c1);
}
// (v + c0) - c1 --> (voc) v + (c0 - c1)
else if ((details::e_add == o0) && (details::e_sub == o1))
{
exprtk_debug(("(v + c0) - c1 --> (voc) v + (c0 - c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::add_op<Type> > >(v, c0 - c1);
}
// (v - c0) + c1 --> (voc) v - (c0 + c1)
else if ((details::e_sub == o0) && (details::e_add == o1))
{
exprtk_debug(("(v - c0) + c1 --> (voc) v - (c0 + c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::add_op<Type> > >(v, c1 - c0);
}
// (v - c0) - c1 --> (voc) v - (c0 + c1)
else if ((details::e_sub == o0) && (details::e_sub == o1))
{
exprtk_debug(("(v - c0) - c1 --> (voc) v - (c0 + c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::sub_op<Type> > >(v, c0 + c1);
}
// (v * c0) * c1 --> (voc) v * (c0 * c1)
else if ((details::e_mul == o0) && (details::e_mul == o1))
{
exprtk_debug(("(v * c0) * c1 --> (voc) v * (c0 * c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::mul_op<Type> > >(v, c0 * c1);
}
// (v * c0) / c1 --> (voc) v * (c0 / c1)
else if ((details::e_mul == o0) && (details::e_div == o1))
{
exprtk_debug(("(v * c0) / c1 --> (voc) v * (c0 / c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::mul_op<Type> > >(v, c0 / c1);
}
// (v / c0) * c1 --> (voc) v * (c1 / c0)
else if ((details::e_div == o0) && (details::e_mul == o1))
{
exprtk_debug(("(v / c0) * c1 --> (voc) v * (c1 / c0)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::mul_op<Type> > >(v, c1 / c0);
}
// (v / c0) / c1 --> (voc) v / (c0 * c1)
else if ((details::e_div == o0) && (details::e_div == o1))
{
exprtk_debug(("(v / c0) / c1 --> (voc) v / (c0 * c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::div_op<Type> > >(v, c0 * c1);
}
// (v ^ c0) ^ c1 --> (voc) v ^ (c0 * c1)
else if ((details::e_pow == o0) && (details::e_pow == o1))
{
exprtk_debug(("(v ^ c0) ^ c1 --> (voc) v ^ (c0 * c1)\n"));
return expr_gen.node_allocator_->
template allocate_rc<typename details::voc_node<Type,details::pow_op<Type> > >(v, c0 * c1);
}
}
const bool synthesis_result =
synthesize_sf3ext_expression::template compile<vtype, ctype, ctype>
(expr_gen, id(expr_gen, o0, o1), v, c0, c1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v, c0, c1, f0, f1);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t";
}
};
struct synthesize_vococ_expression1
{
typedef typename vococ_t::type0 node_type;
static inline expression_node_ptr process(expression_generator<Type>&,
const details::operator_type&,
expression_node_ptr (&)[2])
{
// (v) o0 (c0 o1 c1) - Not possible.
exprtk_debug(("(v) o0 (c0 o1 c1) - Not possible.\n"));
return error_node();
}
};
struct synthesize_vovovov_expression0
{
typedef typename vovovov_t::type0 node_type;
typedef typename vovovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 v1) o1 (v2 o2 v3)
const details::vov_base_node<Type>* vov0 = static_cast<details::vov_base_node<Type>*>(branch[0]);
const details::vov_base_node<Type>* vov1 = static_cast<details::vov_base_node<Type>*>(branch[1]);
const Type& v0 = vov0->v0();
const Type& v1 = vov0->v1();
const Type& v2 = vov1->v0();
const Type& v3 = vov1->v1();
const details::operator_type o0 = vov0->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = vov1->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / v1) * (v2 / v3) --> (vovovov) (v0 * v2) / (v1 * v3)
if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", v0, v2, v1, v3, result);
exprtk_debug(("(v0 / v1) * (v2 / v3) --> (vovovov) (v0 * v2) / (v1 * v3)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / v1) / (v2 / v3) --> (vovovov) (v0 * v3) / (v1 * v2)
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", v0, v3, v1, v2, result);
exprtk_debug(("(v0 / v1) / (v2 / v3) --> (vovovov) (v0 * v3) / (v1 * v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 + v1) / (v2 / v3) --> (vovovov) (v0 + v1) * (v3 / v2)
else if ((details::e_add == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, vtype>(expr_gen, "(t+t)*(t/t)", v0, v1, v3, v2, result);
exprtk_debug(("(v0 + v1) / (v2 / v3) --> (vovovov) (v0 + v1) * (v3 / v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 - v1) / (v2 / v3) --> (vovovov) (v0 + v1) * (v3 / v2)
else if ((details::e_sub == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, vtype>(expr_gen, "(t-t)*(t/t)", v0, v1, v3, v2, result);
exprtk_debug(("(v0 - v1) / (v2 / v3) --> (vovovov) (v0 - v1) * (v3 / v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * v1) / (v2 / v3) --> (vovovov) ((v0 * v1) * v3) / v2
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, vtype>(expr_gen, "((t*t)*t)/t", v0, v1, v3, v2, result);
exprtk_debug(("(v0 * v1) / (v2 / v3) --> (vovovov) ((v0 * v1) * v3) / v2\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, v3, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, v3, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vovovoc_expression0
{
typedef typename vovovoc_t::type0 node_type;
typedef typename vovovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 v1) o1 (v2 o2 c)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[0]);
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[1]);
const Type& v0 = vov->v0();
const Type& v1 = vov->v1();
const Type& v2 = voc->v ();
const Type c = voc->c ();
const details::operator_type o0 = vov->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = voc->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / v1) * (v2 / c) --> (vovovoc) (v0 * v2) / (v1 * c)
if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, ctype>(expr_gen, "(t*t)/(t*t)", v0, v2, v1, c, result);
exprtk_debug(("(v0 / v1) * (v2 / c) --> (vovovoc) (v0 * v2) / (v1 * c)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / v1) / (v2 / c) --> (vocovov) (v0 * c) / (v1 * v2)
if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, ctype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", v0, c, v1, v2, result);
exprtk_debug(("(v0 / v1) / (v2 / c) --> (vocovov) (v0 * c) / (v1 * v2)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, c, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, c, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vovocov_expression0
{
typedef typename vovocov_t::type0 node_type;
typedef typename vovocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 v1) o1 (c o2 v2)
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[0]);
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[1]);
const Type& v0 = vov->v0();
const Type& v1 = vov->v1();
const Type& v2 = cov->v ();
const Type c = cov->c ();
const details::operator_type o0 = vov->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = cov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / v1) * (c / v2) --> (vocovov) (v0 * c) / (v1 * v2)
if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, ctype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", v0, c, v1, v2, result);
exprtk_debug(("(v0 / v1) * (c / v2) --> (vocovov) (v0 * c) / (v1 * v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / v1) / (c / v2) --> (vovovoc) (v0 * v2) / (v1 * c)
if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, vtype, ctype>(expr_gen, "(t*t)/(t*t)", v0, v2, v1, c, result);
exprtk_debug(("(v0 / v1) / (c / v2) --> (vovovoc) (v0 * v2) / (v1 * c)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, c, v2, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vocovov_expression0
{
typedef typename vocovov_t::type0 node_type;
typedef typename vocovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 c) o1 (v1 o2 v2)
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[0]);
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[1]);
const Type c = voc->c ();
const Type& v0 = voc->v ();
const Type& v1 = vov->v0();
const Type& v2 = vov->v1();
const details::operator_type o0 = voc->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = vov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 / c) * (v1 / v2) --> (vovocov) (v0 * v1) / (c * v2)
if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, ctype, vtype>(expr_gen, "(t*t)/(t*t)", v0, v1, c, v2, result);
exprtk_debug(("(v0 / c) * (v1 / v2) --> (vovocov) (v0 * v1) / (c * v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c) / (v1 / v2) --> (vovocov) (v0 * v2) / (c * v1)
if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, vtype, ctype, vtype>(expr_gen, "(t*t)/(t*t)", v0, v2, c, v1, result);
exprtk_debug(("(v0 / c) / (v1 / v2) --> (vovocov) (v0 * v2) / (c * v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c, v1, v2, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covovov_expression0
{
typedef typename covovov_t::type0 node_type;
typedef typename covovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c o0 v0) o1 (v1 o2 v2)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[0]);
const details::vov_base_node<Type>* vov = static_cast<details::vov_base_node<Type>*>(branch[1]);
const Type c = cov->c ();
const Type& v0 = cov->v ();
const Type& v1 = vov->v0();
const Type& v2 = vov->v1();
const details::operator_type o0 = cov->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = vov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c / v0) * (v1 / v2) --> (covovov) (c * v1) / (v0 * v2)
if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<ctype, vtype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", c, v1, v0, v2, result);
exprtk_debug(("(c / v0) * (v1 / v2) --> (covovov) (c * v1) / (v0 * v2)\n"));
return (synthesis_result) ? result : error_node();
}
// (c / v0) / (v1 / v2) --> (covovov) (c * v2) / (v0 * v1)
if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<ctype, vtype, vtype, vtype>(expr_gen, "(t*t)/(t*t)", c, v2, v0, v1, result);
exprtk_debug(("(c / v0) / (v1 / v2) --> (covovov) (c * v2) / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c, v0, v1, v2, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covocov_expression0
{
typedef typename covocov_t::type0 node_type;
typedef typename covocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c0 o0 v0) o1 (c1 o2 v1)
const details::cov_base_node<Type>* cov0 = static_cast<details::cov_base_node<Type>*>(branch[0]);
const details::cov_base_node<Type>* cov1 = static_cast<details::cov_base_node<Type>*>(branch[1]);
const Type c0 = cov0->c();
const Type& v0 = cov0->v();
const Type c1 = cov1->c();
const Type& v1 = cov1->v();
const details::operator_type o0 = cov0->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = cov1->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c0 + v0) + (c1 + v1) --> (covov) (c0 + c1) + v0 + v1
if ((details::e_add == o0) && (details::e_add == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)+t", (c0 + c1), v0, v1, result);
exprtk_debug(("(c0 + v0) + (c1 + v1) --> (covov) (c0 + c1) + v0 + v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 + v0) - (c1 + v1) --> (covov) (c0 - c1) + v0 - v1
else if ((details::e_add == o0) && (details::e_sub == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)-t", (c0 - c1), v0, v1, result);
exprtk_debug(("(c0 + v0) - (c1 + v1) --> (covov) (c0 - c1) + v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 - v0) - (c1 - v1) --> (covov) (c0 - c1) - v0 + v1
else if ((details::e_sub == o0) && (details::e_sub == o1) && (details::e_sub == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t-t)+t", (c0 - c1), v0, v1, result);
exprtk_debug(("(c0 - v0) - (c1 - v1) --> (covov) (c0 - c1) - v0 + v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) * (c1 * v1) --> (covov) (c0 * c1) * v0 * v1
else if ((details::e_mul == o0) && (details::e_mul == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", (c0 * c1), v0, v1, result);
exprtk_debug(("(c0 * v0) * (c1 * v1) --> (covov) (c0 * c1) * v0 * v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) / (c1 * v1) --> (covov) (c0 / c1) * (v0 / v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 / c1), v0, v1, result);
exprtk_debug(("(c0 * v0) / (c1 * v1) --> (covov) (c0 / c1) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) * (c1 / v1) --> (covov) (c0 * c1) / (v0 * v1)
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t/(t*t)", (c0 * c1), v0, v1, result);
exprtk_debug(("(c0 / v0) * (c1 / v1) --> (covov) (c0 * c1) / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) / (c1 / v1) --> (covov) ((c0 / c1) * v1) / v0
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 / c1), v1, v0, result);
exprtk_debug(("(c0 / v0) / (c1 / v1) --> (covov) ((c0 / c1) * v1) / v0\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) / (c1 / v1) --> (covov) (c0 / c1) * (v0 * v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t*(t*t)", (c0 / c1), v0, v1, result);
exprtk_debug(("(c0 * v0) / (c1 / v1) --> (covov) (c0 / c1) * (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) / (c1 * v1) --> (covov) (c0 / c1) / (v0 * v1)
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t/(t*t)", (c0 / c1), v0, v1, result);
exprtk_debug(("(c0 / v0) / (c1 * v1) --> (covov) (c0 / c1) / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c * v0) +/- (c * v1) --> (covov) c * (v0 +/- v1)
else if (
(std::equal_to<T>()(c0,c1)) &&
(details::e_mul == o0) &&
(details::e_mul == o2) &&
(
(details::e_add == o1) ||
(details::e_sub == o1)
)
)
{
std::string specfunc;
switch (o1)
{
case details::e_add : specfunc = "t*(t+t)"; break;
case details::e_sub : specfunc = "t*(t-t)"; break;
default : return error_node();
}
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, specfunc, c0, v0, v1, result);
exprtk_debug(("(c * v0) +/- (c * v1) --> (covov) c * (v0 +/- v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, c1, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vocovoc_expression0
{
typedef typename vocovoc_t::type0 node_type;
typedef typename vocovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 c0) o1 (v1 o2 c1)
const details::voc_base_node<Type>* voc0 = static_cast<details::voc_base_node<Type>*>(branch[0]);
const details::voc_base_node<Type>* voc1 = static_cast<details::voc_base_node<Type>*>(branch[1]);
const Type c0 = voc0->c();
const Type& v0 = voc0->v();
const Type c1 = voc1->c();
const Type& v1 = voc1->v();
const details::operator_type o0 = voc0->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = voc1->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 + c0) + (v1 + c1) --> (covov) (c0 + c1) + v0 + v1
if ((details::e_add == o0) && (details::e_add == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)+t", (c0 + c1), v0, v1, result);
exprtk_debug(("(v0 + c0) + (v1 + c1) --> (covov) (c0 + c1) + v0 + v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 + c0) - (v1 + c1) --> (covov) (c0 - c1) + v0 - v1
else if ((details::e_add == o0) && (details::e_sub == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)-t", (c0 - c1), v0, v1, result);
exprtk_debug(("(v0 + c0) - (v1 + c1) --> (covov) (c0 - c1) + v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 - c0) - (v1 - c1) --> (covov) (c1 - c0) + v0 - v1
else if ((details::e_sub == o0) && (details::e_sub == o1) && (details::e_sub == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)-t", (c1 - c0), v0, v1, result);
exprtk_debug(("(v0 - c0) - (v1 - c1) --> (covov) (c1 - c0) + v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) * (v1 * c1) --> (covov) (c0 * c1) * v0 * v1
else if ((details::e_mul == o0) && (details::e_mul == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 * c0) * (v1 * c1) --> (covov) (c0 * c1) * v0 * v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) / (v1 * c1) --> (covov) (c0 / c1) * (v0 / v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 / c1), v0, v1, result);
exprtk_debug(("(v0 * c0) / (v1 * c1) --> (covov) (c0 / c1) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) * (v1 / c1) --> (covov) (1 / (c0 * c1)) * v0 * v1
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", Type(1) / (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 / c0) * (v1 / c1) --> (covov) (1 / (c0 * c1)) * v0 * v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) / (v1 / c1) --> (covov) ((c1 / c0) * v0) / v1
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c1 / c0), v0, v1, result);
exprtk_debug(("(v0 / c0) / (v1 / c1) --> (covov) ((c1 / c0) * v0) / v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) / (v1 / c1) --> (covov) (c0 * c1) * (v0 / v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t*(t/t)", (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 * c0) / (v1 / c1) --> (covov) (c0 * c1) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) / (v1 * c1) --> (covov) (1 / (c0 * c1)) * v0 / v1
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t*(t/t)", Type(1) / (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 / c0) / (v1 * c1) --> (covov) (1 / (c0 * c1)) * v0 / v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) * (v1 + c1) --> (vocovoc) (v0 * (1 / c0)) * (v1 + c1)
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, ctype, vtype, ctype>(expr_gen, "(t*t)*(t+t)", v0, T(1) / c0, v1, c1, result);
exprtk_debug(("(v0 / c0) * (v1 + c1) --> (vocovoc) (v0 * (1 / c0)) * (v1 + c1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) * (v1 - c1) --> (vocovoc) (v0 * (1 / c0)) * (v1 - c1)
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_sub == o2))
{
const bool synthesis_result =
synthesize_sf4ext_expression::
template compile<vtype, ctype, vtype, ctype>(expr_gen, "(t*t)*(t-t)", v0, T(1) / c0, v1, c1, result);
exprtk_debug(("(v0 / c0) * (v1 - c1) --> (vocovoc) (v0 * (1 / c0)) * (v1 - c1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c) +/- (v1 * c) --> (covov) c * (v0 +/- v1)
else if (
(std::equal_to<T>()(c0,c1)) &&
(details::e_mul == o0) &&
(details::e_mul == o2) &&
(
(details::e_add == o1) ||
(details::e_sub == o1)
)
)
{
std::string specfunc;
switch (o1)
{
case details::e_add : specfunc = "t*(t+t)"; break;
case details::e_sub : specfunc = "t*(t-t)"; break;
default : return error_node();
}
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, specfunc, c0, v0, v1, result);
exprtk_debug(("(v0 * c) +/- (v1 * c) --> (covov) c * (v0 +/- v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c) +/- (v1 / c) --> (vovoc) (v0 +/- v1) / c
else if (
(std::equal_to<T>()(c0,c1)) &&
(details::e_div == o0) &&
(details::e_div == o2) &&
(
(details::e_add == o1) ||
(details::e_sub == o1)
)
)
{
std::string specfunc;
switch (o1)
{
case details::e_add : specfunc = "(t+t)/t"; break;
case details::e_sub : specfunc = "(t-t)/t"; break;
default : return error_node();
}
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, specfunc, v0, v1, c0, result);
exprtk_debug(("(v0 / c) +/- (v1 / c) --> (vovoc) (v0 +/- v1) / c\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, v1, c1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covovoc_expression0
{
typedef typename covovoc_t::type0 node_type;
typedef typename covovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (c0 o0 v0) o1 (v1 o2 c1)
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[0]);
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[1]);
const Type c0 = cov->c();
const Type& v0 = cov->v();
const Type c1 = voc->c();
const Type& v1 = voc->v();
const details::operator_type o0 = cov->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = voc->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (c0 + v0) + (v1 + c1) --> (covov) (c0 + c1) + v0 + v1
if ((details::e_add == o0) && (details::e_add == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)+t", (c0 + c1), v0, v1, result);
exprtk_debug(("(c0 + v0) + (v1 + c1) --> (covov) (c0 + c1) + v0 + v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 + v0) - (v1 + c1) --> (covov) (c0 - c1) + v0 - v1
else if ((details::e_add == o0) && (details::e_sub == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)-t", (c0 - c1), v0, v1, result);
exprtk_debug(("(c0 + v0) - (v1 + c1) --> (covov) (c0 - c1) + v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 - v0) - (v1 - c1) --> (covov) (c0 + c1) - v0 - v1
else if ((details::e_sub == o0) && (details::e_sub == o1) && (details::e_sub == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t-(t+t)", (c0 + c1), v0, v1, result);
exprtk_debug(("(c0 - v0) - (v1 - c1) --> (covov) (c0 + c1) - v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) * (v1 * c1) --> (covov) (c0 * c1) * v0 * v1
else if ((details::e_mul == o0) && (details::e_mul == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", (c0 * c1), v0, v1, result);
exprtk_debug(("(c0 * v0) * (v1 * c1) --> (covov) (c0 * c1) * v0 * v1\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) / (v1 * c1) --> (covov) (c0 / c1) * (v0 / v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 / c1), v0, v1, result);
exprtk_debug(("(c0 * v0) / (v1 * c1) --> (covov) (c0 / c1) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) * (v1 / c1) --> (covov) (c0 / c1) * (v1 / v0)
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t*(t/t)", (c0 / c1), v1, v0, result);
exprtk_debug(("(c0 / v0) * (v1 / c1) --> (covov) (c0 / c1) * (v1 / v0)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) / (v1 / c1) --> (covov) (c0 * c1) / (v0 * v1)
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t/(t*t)", (c0 * c1), v0, v1, result);
exprtk_debug(("(c0 / v0) / (v1 / c1) --> (covov) (c0 * c1) / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 * v0) / (v1 / c1) --> (covov) (c0 * c1) * (v0 / v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 * c1), v0, v1, result);
exprtk_debug(("(c0 * v0) / (v1 / c1) --> (covov) (c0 * c1) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c0 / v0) / (v1 * c1) --> (covov) (c0 / c1) / (v0 * v1)
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "t/(t*t)", (c0 / c1), v0, v1, result);
exprtk_debug(("(c0 / v0) / (v1 * c1) --> (covov) (c0 / c1) / (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (c * v0) +/- (v1 * c) --> (covov) c * (v0 +/- v1)
else if (
(std::equal_to<T>()(c0,c1)) &&
(details::e_mul == o0) &&
(details::e_mul == o2) &&
(
(details::e_add == o1) ||
(details::e_sub == o1)
)
)
{
std::string specfunc;
switch (o1)
{
case details::e_add : specfunc = "t*(t+t)"; break;
case details::e_sub : specfunc = "t*(t-t)"; break;
default : return error_node();
}
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, specfunc, c0, v0, v1, result);
exprtk_debug(("(c * v0) +/- (v1 * c) --> (covov) c * (v0 +/- v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, v1, c1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vococov_expression0
{
typedef typename vococov_t::type0 node_type;
typedef typename vococov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 c0) o1 (c1 o2 v1)
const details::voc_base_node<Type>* voc = static_cast<details::voc_base_node<Type>*>(branch[0]);
const details::cov_base_node<Type>* cov = static_cast<details::cov_base_node<Type>*>(branch[1]);
const Type c0 = voc->c();
const Type& v0 = voc->v();
const Type c1 = cov->c();
const Type& v1 = cov->v();
const details::operator_type o0 = voc->operation();
const details::operator_type o1 = operation;
const details::operator_type o2 = cov->operation();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
if (expr_gen.parser_->settings_.strength_reduction_enabled())
{
// (v0 + c0) + (c1 + v1) --> (covov) (c0 + c1) + v0 + v1
if ((details::e_add == o0) && (details::e_add == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)+t", (c0 + c1), v0, v1, result);
exprtk_debug(("(v0 + c0) + (c1 + v1) --> (covov) (c0 + c1) + v0 + v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 + c0) - (c1 + v1) --> (covov) (c0 - c1) + v0 - v1
else if ((details::e_add == o0) && (details::e_sub == o1) && (details::e_add == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t+t)-t", (c0 - c1), v0, v1, result);
exprtk_debug(("(v0 + c0) - (c1 + v1) --> (covov) (c0 - c1) + v0 - v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 - c0) - (c1 - v1) --> (vovoc) v0 + v1 - (c1 + c0)
else if ((details::e_sub == o0) && (details::e_sub == o1) && (details::e_sub == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, "(t+t)-t", v0, v1, (c1 + c0), result);
exprtk_debug(("(v0 - c0) - (c1 - v1) --> (vovoc) v0 + v1 - (c1 + c0)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) * (c1 * v1) --> (covov) (c0 * c1) * v0 * v1
else if ((details::e_mul == o0) && (details::e_mul == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 * c0) * (c1 * v1) --> (covov) (c0 * c1) * v0 * v1\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) / (c1 * v1) --> (covov) (c0 / c1) * (v0 * v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c0 / c1), v0, v1, result);
exprtk_debug(("(v0 * c0) / (c1 * v1) --> (covov) (c0 / c1) * (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) * (c1 / v1) --> (covov) (c1 / c0) * (v0 / v1)
else if ((details::e_div == o0) && (details::e_mul == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", (c1 / c0), v0, v1, result);
exprtk_debug(("(v0 / c0) * (c1 / v1) --> (covov) (c1 / c0) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c0) / (c1 / v1) --> (covov) (c0 / c1) * (v0 * v1)
else if ((details::e_mul == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)*t", (c0 / c1), v0, v1, result);
exprtk_debug(("(v0 * c0) / (c1 / v1) --> (covov) (c0 / c1) * (v0 * v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) / (c1 * v1) --> (covov) (1 / (c0 * c1)) * (v0 / v1)
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_mul == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, "(t*t)/t", Type(1) / (c0 * c1), v0, v1, result);
exprtk_debug(("(v0 / c0) / (c1 * v1) --> (covov) (1 / (c0 * c1)) * (v0 / v1)\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 / c0) / (c1 / v1) --> (vovoc) (v0 * v1) * (1 / (c0 * c1))
else if ((details::e_div == o0) && (details::e_div == o1) && (details::e_div == o2))
{
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<vtype, vtype, ctype>(expr_gen, "(t*t)*t", v0, v1, Type(1) / (c0 * c1), result);
exprtk_debug(("(v0 / c0) / (c1 / v1) --> (vovoc) (v0 * v1) * (1 / (c0 * c1))\n"));
return (synthesis_result) ? result : error_node();
}
// (v0 * c) +/- (c * v1) --> (covov) c * (v0 +/- v1)
else if (
(std::equal_to<T>()(c0,c1)) &&
(details::e_mul == o0) &&
(details::e_mul == o2) &&
(
(details::e_add == o1) || (details::e_sub == o1)
)
)
{
std::string specfunc;
switch (o1)
{
case details::e_add : specfunc = "t*(t+t)"; break;
case details::e_sub : specfunc = "t*(t-t)"; break;
default : return error_node();
}
const bool synthesis_result =
synthesize_sf3ext_expression::
template compile<ctype, vtype, vtype>(expr_gen, specfunc, c0, v0, v1, result);
exprtk_debug(("(v0 * c) +/- (c * v1) --> (covov) c * (v0 +/- v1)\n"));
return (synthesis_result) ? result : error_node();
}
}
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, c1, v1, result);
if (synthesis_result)
return result;
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
if (!expr_gen.valid_operator(o0,f0))
return error_node();
else if (!expr_gen.valid_operator(o1,f1))
return error_node();
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
else
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vovovov_expression1
{
typedef typename vovovov_t::type1 node_type;
typedef typename vovovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (v1 o1 (v2 o2 v3))
typedef typename synthesize_vovov_expression1::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vovov->t0();
const Type& v2 = vovov->t1();
const Type& v3 = vovov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovov->f0());
const details::operator_type o2 = expr_gen.get_operator(vovov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovov->f0();
binary_functor_t f2 = vovov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen,id(expr_gen, o0, o1, o2), v0, v1, v2, v3, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (v1 o1 (v2 o2 v3))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, v3, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vovovoc_expression1
{
typedef typename vovovoc_t::type1 node_type;
typedef typename vovovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (v1 o1 (v2 o2 c))
typedef typename synthesize_vovoc_expression1::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vovoc->t0();
const Type& v2 = vovoc->t1();
const Type c = vovoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o2 = expr_gen.get_operator(vovoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovoc->f0();
binary_functor_t f2 = vovoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, c, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (v1 o1 (v2 o2 c))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, c, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vovocov_expression1
{
typedef typename vovocov_t::type1 node_type;
typedef typename vovocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (v1 o1 (c o2 v2))
typedef typename synthesize_vocov_expression1::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vocov->t0();
const Type c = vocov->t1();
const Type& v2 = vocov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vocov->f0());
const details::operator_type o2 = expr_gen.get_operator(vocov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vocov->f0();
binary_functor_t f2 = vocov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, c, v2, result);
if (synthesis_result)
return result;
if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (v1 o1 (c o2 v2))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vocovov_expression1
{
typedef typename vocovov_t::type1 node_type;
typedef typename vocovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (c o1 (v1 o2 v2))
typedef typename synthesize_covov_expression1::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c = covov->t0();
const Type& v1 = covov->t1();
const Type& v2 = covov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(covov->f0());
const details::operator_type o2 = expr_gen.get_operator(covov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = covov->f0();
binary_functor_t f2 = covov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (c o1 (v1 o2 v2))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_covovov_expression1
{
typedef typename covovov_t::type1 node_type;
typedef typename covovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c o0 (v0 o1 (v1 o2 v2))
typedef typename synthesize_vovov_expression1::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[1]);
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovov->f0());
const details::operator_type o2 = expr_gen.get_operator(vovov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovov->f0();
binary_functor_t f2 = vovov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c, v0, v1, v2, result);
if (synthesis_result)
return result;
if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c o0 (v0 o1 (v1 o2 v2))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_covocov_expression1
{
typedef typename covocov_t::type1 node_type;
typedef typename covocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c0 o0 (v0 o1 (c1 o2 v1))
typedef typename synthesize_vocov_expression1::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vocov->t0();
const Type c1 = vocov->t1();
const Type& v1 = vocov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vocov->f0());
const details::operator_type o2 = expr_gen.get_operator(vocov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vocov->f0();
binary_functor_t f2 = vocov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c0 o0 (v0 o1 (c1 o2 v1))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vocovoc_expression1
{
typedef typename vocovoc_t::type1 node_type;
typedef typename vocovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (c0 o1 (v1 o2 c2))
typedef typename synthesize_covoc_expression1::node_type lcl_covoc_t;
const lcl_covoc_t* covoc = static_cast<const lcl_covoc_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c0 = covoc->t0();
const Type& v1 = covoc->t1();
const Type c1 = covoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(covoc->f0());
const details::operator_type o2 = expr_gen.get_operator(covoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = covoc->f0();
binary_functor_t f2 = covoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (c0 o1 (v1 o2 c2))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_covovoc_expression1
{
typedef typename covovoc_t::type1 node_type;
typedef typename covovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c0 o0 (v0 o1 (v1 o2 c1))
typedef typename synthesize_vovoc_expression1::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vovoc->t0();
const Type& v1 = vovoc->t1();
const Type c1 = vovoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o2 = expr_gen.get_operator(vovoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovoc->f0();
binary_functor_t f2 = vovoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c0 o0 (v0 o1 (v1 o2 c1))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vococov_expression1
{
typedef typename vococov_t::type1 node_type;
typedef typename vococov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 (c0 o1 (c1 o2 v1))
typedef typename synthesize_cocov_expression1::node_type lcl_cocov_t;
const lcl_cocov_t* cocov = static_cast<const lcl_cocov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c0 = cocov->t0();
const Type c1 = cocov->t1();
const Type& v1 = cocov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(cocov->f0());
const details::operator_type o2 = expr_gen.get_operator(cocov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = cocov->f0();
binary_functor_t f2 = cocov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 (c0 o1 (c1 o2 v1))\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "(t" << expr_gen.to_str(o2)
<< "t))";
}
};
struct synthesize_vovovov_expression2
{
typedef typename vovovov_t::type2 node_type;
typedef typename vovovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 ((v1 o1 v2) o2 v3)
typedef typename synthesize_vovov_expression0::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vovov->t0();
const Type& v2 = vovov->t1();
const Type& v3 = vovov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovov->f0());
const details::operator_type o2 = expr_gen.get_operator(vovov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovov->f0();
binary_functor_t f2 = vovov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, v3, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 ((v1 o1 v2) o2 v3)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, v3, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vovovoc_expression2
{
typedef typename vovovoc_t::type2 node_type;
typedef typename vovovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 ((v1 o1 v2) o2 c)
typedef typename synthesize_vovoc_expression0::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vovoc->t0();
const Type& v2 = vovoc->t1();
const Type c = vovoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o2 = expr_gen.get_operator(vovoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovoc->f0();
binary_functor_t f2 = vovoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, c, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 ((v1 o1 v2) o2 c)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, c, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vovocov_expression2
{
typedef typename vovocov_t::type2 node_type;
typedef typename vovocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 ((v1 o1 c) o2 v2)
typedef typename synthesize_vocov_expression0::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type& v1 = vocov->t0();
const Type c = vocov->t1();
const Type& v2 = vocov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vocov->f0());
const details::operator_type o2 = expr_gen.get_operator(vocov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vocov->f0();
binary_functor_t f2 = vocov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, c, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 ((v1 o1 c) o2 v2)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vocovov_expression2
{
typedef typename vocovov_t::type2 node_type;
typedef typename vocovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 ((c o1 v1) o2 v2)
typedef typename synthesize_covov_expression0::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c = covov->t0();
const Type& v1 = covov->t1();
const Type& v2 = covov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(covov->f0());
const details::operator_type o2 = expr_gen.get_operator(covov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = covov->f0();
binary_functor_t f2 = covov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 ((c o1 v1) o2 v2)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covovov_expression2
{
typedef typename covovov_t::type2 node_type;
typedef typename covovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c o0 ((v1 o1 v2) o2 v3)
typedef typename synthesize_vovov_expression0::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[1]);
const Type c = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovov->f0());
const details::operator_type o2 = expr_gen.get_operator(vovov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovov->f0();
binary_functor_t f2 = vovov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c, v0, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c o0 ((v1 o1 v2) o2 v3)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covocov_expression2
{
typedef typename covocov_t::type2 node_type;
typedef typename covocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c0 o0 ((v0 o1 c1) o2 v1)
typedef typename synthesize_vocov_expression0::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vocov->t0();
const Type c1 = vocov->t1();
const Type& v1 = vocov->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vocov->f0());
const details::operator_type o2 = expr_gen.get_operator(vocov->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vocov->f0();
binary_functor_t f2 = vocov->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c0 o0 ((v0 o1 c1) o2 v1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vocovoc_expression2
{
typedef typename vocovoc_t::type2 node_type;
typedef typename vocovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// v0 o0 ((c0 o1 v1) o2 c1)
typedef typename synthesize_covoc_expression0::node_type lcl_covoc_t;
const lcl_covoc_t* covoc = static_cast<const lcl_covoc_t*>(branch[1]);
const Type& v0 = static_cast<details::variable_node<Type>*>(branch[0])->ref();
const Type c0 = covoc->t0();
const Type& v1 = covoc->t1();
const Type c1 = covoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(covoc->f0());
const details::operator_type o2 = expr_gen.get_operator(covoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = covoc->f0();
binary_functor_t f2 = covoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("v0 o0 ((c0 o1 v1) o2 c1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_covovoc_expression2
{
typedef typename covovoc_t::type2 node_type;
typedef typename covovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// c0 o0 ((v0 o1 v1) o2 c1)
typedef typename synthesize_vovoc_expression0::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[1]);
const Type c0 = static_cast<details::literal_node<Type>*>(branch[0])->value();
const Type& v0 = vovoc->t0();
const Type& v1 = vovoc->t1();
const Type c1 = vovoc->t2();
const details::operator_type o0 = operation;
const details::operator_type o1 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o2 = expr_gen.get_operator(vovoc->f1());
binary_functor_t f0 = reinterpret_cast<binary_functor_t>(0);
binary_functor_t f1 = vovoc->f0();
binary_functor_t f2 = vovoc->f1();
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o0,f0))
return error_node();
exprtk_debug(("c0 o0 ((v0 o1 v1) o2 c1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "t" << expr_gen.to_str(o0)
<< "((t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t)";
}
};
struct synthesize_vococov_expression2
{
typedef typename vococov_t::type2 node_type;
static inline expression_node_ptr process(expression_generator<Type>&,
const details::operator_type&,
expression_node_ptr (&)[2])
{
// v0 o0 ((c0 o1 c1) o2 v1) - Not possible
exprtk_debug(("v0 o0 ((c0 o1 c1) o2 v1) - Not possible\n"));
return error_node();
}
static inline std::string id(expression_generator<Type>&,
const details::operator_type,
const details::operator_type,
const details::operator_type)
{
return "INVALID";
}
};
struct synthesize_vovovov_expression3
{
typedef typename vovovov_t::type3 node_type;
typedef typename vovovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 v1) o1 v2) o2 v3
typedef typename synthesize_vovov_expression0::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[0]);
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const Type& v3 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vovov->f0());
const details::operator_type o1 = expr_gen.get_operator(vovov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovov->f0();
binary_functor_t f1 = vovov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, v3, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 v1) o1 v2) o2 v3\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, v3, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vovovoc_expression3
{
typedef typename vovovoc_t::type3 node_type;
typedef typename vovovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 v1) o1 v2) o2 c
typedef typename synthesize_vovov_expression0::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[0]);
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(vovov->f0());
const details::operator_type o1 = expr_gen.get_operator(vovov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovov->f0();
binary_functor_t f1 = vovov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, c, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 v1) o1 v2) o2 c\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, c, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vovocov_expression3
{
typedef typename vovocov_t::type3 node_type;
typedef typename vovocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 v1) o1 c) o2 v2
typedef typename synthesize_vovoc_expression0::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[0]);
const Type& v0 = vovoc->t0();
const Type& v1 = vovoc->t1();
const Type c = vovoc->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o1 = expr_gen.get_operator(vovoc->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovoc->f0();
binary_functor_t f1 = vovoc->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, c, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 v1) o1 c) o2 v2\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vocovov_expression3
{
typedef typename vocovov_t::type3 node_type;
typedef typename vocovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 c) o1 v1) o2 v2
typedef typename synthesize_vocov_expression0::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[0]);
const Type& v0 = vocov->t0();
const Type c = vocov->t1();
const Type& v1 = vocov->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vocov->f0());
const details::operator_type o1 = expr_gen.get_operator(vocov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vocov->f0();
binary_functor_t f1 = vocov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 c) o1 v1) o2 v2\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covovov_expression3
{
typedef typename covovov_t::type3 node_type;
typedef typename covovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c o0 v0) o1 v1) o2 v2
typedef typename synthesize_covov_expression0::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[0]);
const Type c = covov->t0();
const Type& v0 = covov->t1();
const Type& v1 = covov->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(covov->f0());
const details::operator_type o1 = expr_gen.get_operator(covov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covov->f0();
binary_functor_t f1 = covov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c, v0, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c o0 v0) o1 v1) o2 v2\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covocov_expression3
{
typedef typename covocov_t::type3 node_type;
typedef typename covocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c0 o0 v0) o1 c1) o2 v1
typedef typename synthesize_covoc_expression0::node_type lcl_covoc_t;
const lcl_covoc_t* covoc = static_cast<const lcl_covoc_t*>(branch[0]);
const Type c0 = covoc->t0();
const Type& v0 = covoc->t1();
const Type c1 = covoc->t2();
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(covoc->f0());
const details::operator_type o1 = expr_gen.get_operator(covoc->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covoc->f0();
binary_functor_t f1 = covoc->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c0 o0 v0) o1 c1) o2 v1\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vocovoc_expression3
{
typedef typename vocovoc_t::type3 node_type;
typedef typename vocovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 c0) o1 v1) o2 c1
typedef typename synthesize_vocov_expression0::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[0]);
const Type& v0 = vocov->t0();
const Type c0 = vocov->t1();
const Type& v1 = vocov->t2();
const Type c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(vocov->f0());
const details::operator_type o1 = expr_gen.get_operator(vocov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vocov->f0();
binary_functor_t f1 = vocov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 c0) o1 v1) o2 c1\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covovoc_expression3
{
typedef typename covovoc_t::type3 node_type;
typedef typename covovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c0 o0 v0) o1 v1) o2 c1
typedef typename synthesize_covov_expression0::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[0]);
const Type c0 = covov->t0();
const Type& v0 = covov->t1();
const Type& v1 = covov->t2();
const Type c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(covov->f0());
const details::operator_type o1 = expr_gen.get_operator(covov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covov->f0();
binary_functor_t f1 = covov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c0 o0 v0) o1 v1) o2 c1\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vococov_expression3
{
typedef typename vococov_t::type3 node_type;
typedef typename vococov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 c0) o1 c1) o2 v1
typedef typename synthesize_vococ_expression0::node_type lcl_vococ_t;
const lcl_vococ_t* vococ = static_cast<const lcl_vococ_t*>(branch[0]);
const Type& v0 = vococ->t0();
const Type c0 = vococ->t1();
const Type c1 = vococ->t2();
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vococ->f0());
const details::operator_type o1 = expr_gen.get_operator(vococ->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vococ->f0();
binary_functor_t f1 = vococ->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 c0) o1 c1) o2 v1\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "((t" << expr_gen.to_str(o0)
<< "t)" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vovovov_expression4
{
typedef typename vovovov_t::type4 node_type;
typedef typename vovovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// (v0 o0 (v1 o1 v2)) o2 v3
typedef typename synthesize_vovov_expression1::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[0]);
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const Type& v3 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vovov->f0());
const details::operator_type o1 = expr_gen.get_operator(vovov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovov->f0();
binary_functor_t f1 = vovov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, v3, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("(v0 o0 (v1 o1 v2)) o2 v3\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, v3, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vovovoc_expression4
{
typedef typename vovovoc_t::type4 node_type;
typedef typename vovovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 (v1 o1 v2)) o2 c)
typedef typename synthesize_vovov_expression1::node_type lcl_vovov_t;
const lcl_vovov_t* vovov = static_cast<const lcl_vovov_t*>(branch[0]);
const Type& v0 = vovov->t0();
const Type& v1 = vovov->t1();
const Type& v2 = vovov->t2();
const Type c = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(vovov->f0());
const details::operator_type o1 = expr_gen.get_operator(vovov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovov->f0();
binary_functor_t f1 = vovov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, v2, c, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 (v1 o1 v2)) o2 c)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, v2, c, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vovocov_expression4
{
typedef typename vovocov_t::type4 node_type;
typedef typename vovocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 (v1 o1 c)) o2 v1)
typedef typename synthesize_vovoc_expression1::node_type lcl_vovoc_t;
const lcl_vovoc_t* vovoc = static_cast<const lcl_vovoc_t*>(branch[0]);
const Type& v0 = vovoc->t0();
const Type& v1 = vovoc->t1();
const Type c = vovoc->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vovoc->f0());
const details::operator_type o1 = expr_gen.get_operator(vovoc->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vovoc->f0();
binary_functor_t f1 = vovoc->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, v1, c, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 (v1 o1 c)) o2 v1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, v1, c, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vocovov_expression4
{
typedef typename vocovov_t::type4 node_type;
typedef typename vocovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 (c o1 v1)) o2 v2)
typedef typename synthesize_vocov_expression1::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[0]);
const Type& v0 = vocov->t0();
const Type c = vocov->t1();
const Type& v1 = vocov->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(vocov->f0());
const details::operator_type o1 = expr_gen.get_operator(vocov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vocov->f0();
binary_functor_t f1 = vocov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 (c o1 v1)) o2 v2)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covovov_expression4
{
typedef typename covovov_t::type4 node_type;
typedef typename covovov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c o0 (v0 o1 v1)) o2 v2)
typedef typename synthesize_covov_expression1::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[0]);
const Type c = covov->t0();
const Type& v0 = covov->t1();
const Type& v1 = covov->t2();
const Type& v2 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(covov->f0());
const details::operator_type o1 = expr_gen.get_operator(covov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covov->f0();
binary_functor_t f1 = covov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c, v0, v1, v2, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c o0 (v0 o1 v1)) o2 v2)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c, v0, v1, v2, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covocov_expression4
{
typedef typename covocov_t::type4 node_type;
typedef typename covocov_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c0 o0 (v0 o1 c1)) o2 v1)
typedef typename synthesize_covoc_expression1::node_type lcl_covoc_t;
const lcl_covoc_t* covoc = static_cast<const lcl_covoc_t*>(branch[0]);
const Type c0 = covoc->t0();
const Type& v0 = covoc->t1();
const Type c1 = covoc->t2();
const Type& v1 = static_cast<details::variable_node<Type>*>(branch[1])->ref();
const details::operator_type o0 = expr_gen.get_operator(covoc->f0());
const details::operator_type o1 = expr_gen.get_operator(covoc->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covoc->f0();
binary_functor_t f1 = covoc->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, c1, v1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c0 o0 (v0 o1 c1)) o2 v1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, c1, v1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vocovoc_expression4
{
typedef typename vocovoc_t::type4 node_type;
typedef typename vocovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((v0 o0 (c0 o1 v1)) o2 c1)
typedef typename synthesize_vocov_expression1::node_type lcl_vocov_t;
const lcl_vocov_t* vocov = static_cast<const lcl_vocov_t*>(branch[0]);
const Type& v0 = vocov->t0();
const Type c0 = vocov->t1();
const Type& v1 = vocov->t2();
const Type c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(vocov->f0());
const details::operator_type o1 = expr_gen.get_operator(vocov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = vocov->f0();
binary_functor_t f1 = vocov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), v0, c0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((v0 o0 (c0 o1 v1)) o2 c1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), v0, c0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_covovoc_expression4
{
typedef typename covovoc_t::type4 node_type;
typedef typename covovoc_t::sf4_type sf4_type;
typedef typename node_type::T0 T0;
typedef typename node_type::T1 T1;
typedef typename node_type::T2 T2;
typedef typename node_type::T3 T3;
static inline expression_node_ptr process(expression_generator<Type>& expr_gen,
const details::operator_type& operation,
expression_node_ptr (&branch)[2])
{
// ((c0 o0 (v0 o1 v1)) o2 c1)
typedef typename synthesize_covov_expression1::node_type lcl_covov_t;
const lcl_covov_t* covov = static_cast<const lcl_covov_t*>(branch[0]);
const Type c0 = covov->t0();
const Type& v0 = covov->t1();
const Type& v1 = covov->t2();
const Type c1 = static_cast<details::literal_node<Type>*>(branch[1])->value();
const details::operator_type o0 = expr_gen.get_operator(covov->f0());
const details::operator_type o1 = expr_gen.get_operator(covov->f1());
const details::operator_type o2 = operation;
binary_functor_t f0 = covov->f0();
binary_functor_t f1 = covov->f1();
binary_functor_t f2 = reinterpret_cast<binary_functor_t>(0);
details::free_node(*(expr_gen.node_allocator_),branch[0]);
details::free_node(*(expr_gen.node_allocator_),branch[1]);
expression_node_ptr result = error_node();
const bool synthesis_result =
synthesize_sf4ext_expression::template compile<T0, T1, T2, T3>
(expr_gen, id(expr_gen, o0, o1, o2), c0, v0, v1, c1, result);
if (synthesis_result)
return result;
else if (!expr_gen.valid_operator(o2,f2))
return error_node();
exprtk_debug(("((c0 o0 (v0 o1 v1)) o2 c1)\n"));
return node_type::allocate(*(expr_gen.node_allocator_), c0, v0, v1, c1, f0, f1, f2);
}
static inline std::string id(expression_generator<Type>& expr_gen,
const details::operator_type o0,
const details::operator_type o1,
const details::operator_type o2)
{
return details::build_string()
<< "(t" << expr_gen.to_str(o0)
<< "(t" << expr_gen.to_str(o1)
<< "t)" << expr_gen.to_str(o2)
<< "t";
}
};
struct synthesize_vococov_expression4
{
typedef typename vococov_t::type4 node_type;
static inline expression_node_ptr process(expression_generator<Type>&,
const details::operator_type&,
expression_node_ptr (&)[2])
{
// ((v0 o0 (c0 o1 c1)) o2 v1) - Not possible
exprtk_debug(("((v0 o0 (c0 o1 c1)) o2 v1) - Not possible\n"));
return error_node();
}
static inline std::string id(expression_generator<Type>&,
const details::operator_type,
const details::operator_type,
const details::operator_type)
{
return "INVALID";
}
};
#endif
inline expression_node_ptr synthesize_uvouv_expression(const details::operator_type& operation, expression_node_ptr (&branch)[2])
{
// Definition: uv o uv
details::operator_type o0 = static_cast<details::uv_base_node<Type>*>(branch[0])->operation();
details::operator_type o1 = static_cast<details::uv_base_node<Type>*>(branch[1])->operation();
const Type& v0 = static_cast<details::uv_base_node<Type>*>(branch[0])->v();
const Type& v1 = static_cast<details::uv_base_node<Type>*>(branch[1])->v();
unary_functor_t u0 = reinterpret_cast<unary_functor_t> (0);
unary_functor_t u1 = reinterpret_cast<unary_functor_t> (0);
binary_functor_t f = reinterpret_cast<binary_functor_t>(0);
if (!valid_operator(o0,u0))
return error_node();
else if (!valid_operator(o1,u1))
return error_node();
else if (!valid_operator(operation,f))
return error_node();
expression_node_ptr result = error_node();
if (
(details::e_neg == o0) &&
(details::e_neg == o1)
)
{
switch (operation)
{
// (-v0 + -v1) --> -(v0 + v1)
case details::e_add : result = (*this)(details::e_neg,
node_allocator_->
allocate_rr<typename details::
vov_node<Type,details::add_op<Type> > >(v0, v1));
exprtk_debug(("(-v0 + -v1) --> -(v0 + v1)\n"));
break;
// (-v0 - -v1) --> (v1 - v0)
case details::e_sub : result = node_allocator_->
allocate_rr<typename details::
vov_node<Type,details::sub_op<Type> > >(v1, v0);
exprtk_debug(("(-v0 - -v1) --> (v1 - v0)\n"));
break;
// (-v0 * -v1) --> (v0 * v1)
case details::e_mul : result = node_allocator_->
allocate_rr<typename details::
vov_node<Type,details::mul_op<Type> > >(v0, v1);
exprtk_debug(("(-v0 * -v1) --> (v0 * v1)\n"));
break;
// (-v0 / -v1) --> (v0 / v1)
case details::e_div : result = node_allocator_->
allocate_rr<typename details::
vov_node<Type,details::div_op<Type> > >(v0, v1);
exprtk_debug(("(-v0 / -v1) --> (v0 / v1)\n"));
break;
default : break;
}
}
if (0 == result)
{
result = node_allocator_->
allocate_rrrrr<typename details::uvouv_node<Type> >(v0, v1, u0, u1, f);
}
details::free_all_nodes(*node_allocator_,branch);
return result;
}
#undef basic_opr_switch_statements
#undef extended_opr_switch_statements
#undef unary_opr_switch_statements
#ifndef exprtk_disable_string_capabilities
#define string_opr_switch_statements \
case_stmt(details::e_lt , details::lt_op ) \
case_stmt(details::e_lte , details::lte_op ) \
case_stmt(details::e_gt , details::gt_op ) \
case_stmt(details::e_gte , details::gte_op ) \
case_stmt(details::e_eq , details::eq_op ) \
case_stmt(details::e_ne , details::ne_op ) \
case_stmt(details::e_in , details::in_op ) \
case_stmt(details::e_like , details::like_op ) \
case_stmt(details::e_ilike , details::ilike_op) \
template <typename T0, typename T1>
inline expression_node_ptr synthesize_str_xrox_expression_impl(const details::operator_type& opr,
T0 s0, T1 s1,
range_t rp0)
{
switch (opr)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate_ttt<typename details::str_xrox_node<Type,T0,T1,range_t,op1<Type> >,T0,T1> \
(s0, s1, rp0); \
string_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
template <typename T0, typename T1>
inline expression_node_ptr synthesize_str_xoxr_expression_impl(const details::operator_type& opr,
T0 s0, T1 s1,
range_t rp1)
{
switch (opr)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate_ttt<typename details::str_xoxr_node<Type,T0,T1,range_t,op1<Type> >,T0,T1> \
(s0, s1, rp1); \
string_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
template <typename T0, typename T1>
inline expression_node_ptr synthesize_str_xroxr_expression_impl(const details::operator_type& opr,
T0 s0, T1 s1,
range_t rp0, range_t rp1)
{
switch (opr)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate_tttt<typename details::str_xroxr_node<Type,T0,T1,range_t,op1<Type> >,T0,T1> \
(s0, s1, rp0, rp1); \
string_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
template <typename T0, typename T1>
inline expression_node_ptr synthesize_sos_expression_impl(const details::operator_type& opr, T0 s0, T1 s1)
{
switch (opr)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate_tt<typename details::sos_node<Type,T0,T1,op1<Type> >,T0,T1>(s0, s1); \
string_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
inline expression_node_ptr synthesize_sos_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::stringvar_node<Type>*>(branch[0])->ref();
std::string& s1 = static_cast<details::stringvar_node<Type>*>(branch[1])->ref();
return synthesize_sos_expression_impl<std::string&,std::string&>(opr, s0, s1);
}
inline expression_node_ptr synthesize_sros_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::string_range_node<Type>*>(branch[0])->ref ();
std::string& s1 = static_cast<details::stringvar_node<Type>*> (branch[1])->ref ();
range_t rp0 = static_cast<details::string_range_node<Type>*>(branch[0])->range();
static_cast<details::string_range_node<Type>*>(branch[0])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
return synthesize_str_xrox_expression_impl<std::string&,std::string&>(opr, s0, s1, rp0);
}
inline expression_node_ptr synthesize_sosr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::stringvar_node<Type>*> (branch[0])->ref ();
std::string& s1 = static_cast<details::string_range_node<Type>*>(branch[1])->ref ();
range_t rp1 = static_cast<details::string_range_node<Type>*>(branch[1])->range();
static_cast<details::string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xoxr_expression_impl<std::string&,std::string&>(opr, s0, s1, rp1);
}
inline expression_node_ptr synthesize_socsr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::stringvar_node<Type>*> (branch[0])->ref ();
std::string s1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->str ();
range_t rp1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->range();
static_cast<details::const_string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xoxr_expression_impl<std::string&, const std::string>(opr, s0, s1, rp1);
}
inline expression_node_ptr synthesize_srosr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::string_range_node<Type>*>(branch[0])->ref ();
std::string& s1 = static_cast<details::string_range_node<Type>*>(branch[1])->ref ();
range_t rp0 = static_cast<details::string_range_node<Type>*>(branch[0])->range();
range_t rp1 = static_cast<details::string_range_node<Type>*>(branch[1])->range();
static_cast<details::string_range_node<Type>*>(branch[0])->range_ref().clear();
static_cast<details::string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xroxr_expression_impl<std::string&,std::string&>(opr, s0, s1, rp0, rp1);
}
inline expression_node_ptr synthesize_socs_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast< details::stringvar_node<Type>*>(branch[0])->ref();
std::string s1 = static_cast<details::string_literal_node<Type>*>(branch[1])->str();
details::free_node(*node_allocator_,branch[1]);
return synthesize_sos_expression_impl<std::string&, const std::string>(opr, s0, s1);
}
inline expression_node_ptr synthesize_csos_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str();
std::string& s1 = static_cast<details::stringvar_node<Type>* >(branch[1])->ref();
details::free_node(*node_allocator_,branch[0]);
return synthesize_sos_expression_impl<const std::string,std::string&>(opr, s0, s1);
}
inline expression_node_ptr synthesize_csosr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str ();
std::string& s1 = static_cast<details::string_range_node<Type>* >(branch[1])->ref ();
range_t rp1 = static_cast<details::string_range_node<Type>* >(branch[1])->range();
static_cast<details::string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xoxr_expression_impl<const std::string,std::string&>(opr, s0, s1, rp1);
}
inline expression_node_ptr synthesize_srocs_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::string_range_node<Type>* >(branch[0])->ref ();
std::string s1 = static_cast<details::string_literal_node<Type>*>(branch[1])->str ();
range_t rp0 = static_cast<details::string_range_node<Type>* >(branch[0])->range();
static_cast<details::string_range_node<Type>*>(branch[0])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xrox_expression_impl<std::string&, const std::string>(opr, s0, s1, rp0);
}
inline expression_node_ptr synthesize_srocsr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string& s0 = static_cast<details::string_range_node<Type>* >(branch[0])->ref ();
std::string s1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->str ();
range_t rp0 = static_cast<details::string_range_node<Type>* >(branch[0])->range();
range_t rp1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->range();
static_cast<details::string_range_node<Type>*> (branch[0])->range_ref().clear();
static_cast<details::const_string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xroxr_expression_impl<std::string&, const std::string>(opr, s0, s1, rp0, rp1);
}
inline expression_node_ptr synthesize_csocs_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
const std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str();
const std::string s1 = static_cast<details::string_literal_node<Type>*>(branch[1])->str();
expression_node_ptr result = error_node();
if (details::e_add == opr)
result = node_allocator_->allocate_c<details::string_literal_node<Type> >(s0 + s1);
else if (details::e_in == opr)
result = node_allocator_->allocate_c<details::literal_node<Type> >(details::in_op <Type>::process(s0,s1));
else if (details::e_like == opr)
result = node_allocator_->allocate_c<details::literal_node<Type> >(details::like_op <Type>::process(s0,s1));
else if (details::e_ilike == opr)
result = node_allocator_->allocate_c<details::literal_node<Type> >(details::ilike_op<Type>::process(s0,s1));
else
{
expression_node_ptr temp = synthesize_sos_expression_impl<const std::string, const std::string>(opr, s0, s1);
const Type v = temp->value();
details::free_node(*node_allocator_,temp);
result = node_allocator_->allocate<literal_node_t>(v);
}
details::free_all_nodes(*node_allocator_,branch);
return result;
}
inline expression_node_ptr synthesize_csocsr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
const std::string s0 = static_cast<details::string_literal_node<Type>* >(branch[0])->str ();
std::string s1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->str ();
range_t rp1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->range();
static_cast<details::const_string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xoxr_expression_impl<const std::string, const std::string>(opr, s0, s1, rp1);
}
inline expression_node_ptr synthesize_csros_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
std::string s0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->str ();
std::string& s1 = static_cast<details::stringvar_node<Type>* >(branch[1])->ref ();
range_t rp0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->range();
static_cast<details::const_string_range_node<Type>*>(branch[0])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
return synthesize_str_xrox_expression_impl<const std::string,std::string&>(opr, s0, s1, rp0);
}
inline expression_node_ptr synthesize_csrosr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
const std::string s0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->str ();
std::string& s1 = static_cast<details::string_range_node<Type>* >(branch[1])->ref ();
const range_t rp0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->range();
const range_t rp1 = static_cast<details::string_range_node<Type>* >(branch[1])->range();
static_cast<details::const_string_range_node<Type>*>(branch[0])->range_ref().clear();
static_cast<details::string_range_node<Type>*> (branch[1])->range_ref().clear();
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return synthesize_str_xroxr_expression_impl<const std::string,std::string&>(opr, s0, s1, rp0, rp1);
}
inline expression_node_ptr synthesize_csrocs_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
const std::string s0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->str ();
const std::string s1 = static_cast<details::string_literal_node<Type>* >(branch[1])->str ();
const range_t rp0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->range();
static_cast<details::const_string_range_node<Type>*>(branch[0])->range_ref().clear();
details::free_all_nodes(*node_allocator_,branch);
return synthesize_str_xrox_expression_impl<const std::string,std::string>(opr, s0, s1, rp0);
}
inline expression_node_ptr synthesize_csrocsr_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
const std::string s0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->str ();
const std::string s1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->str ();
const range_t rp0 = static_cast<details::const_string_range_node<Type>*>(branch[0])->range();
const range_t rp1 = static_cast<details::const_string_range_node<Type>*>(branch[1])->range();
static_cast<details::const_string_range_node<Type>*>(branch[0])->range_ref().clear();
static_cast<details::const_string_range_node<Type>*>(branch[1])->range_ref().clear();
details::free_all_nodes(*node_allocator_,branch);
return synthesize_str_xroxr_expression_impl<const std::string, const std::string>(opr, s0, s1, rp0, rp1);
}
inline expression_node_ptr synthesize_strogen_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
switch (opr)
{
#define case_stmt(op0, op1) \
case op0 : return node_allocator_-> \
allocate_ttt<typename details::str_sogens_node<Type,op1<Type> > > \
(opr, branch[0], branch[1]); \
string_opr_switch_statements
#undef case_stmt
default : return error_node();
}
}
#endif
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr synthesize_string_expression(const details::operator_type& opr, expression_node_ptr (&branch)[2])
{
if ((0 == branch[0]) || (0 == branch[1]))
{
details::free_all_nodes(*node_allocator_,branch);
return error_node();
}
const bool b0_is_s = details::is_string_node (branch[0]);
const bool b0_is_cs = details::is_const_string_node (branch[0]);
const bool b0_is_sr = details::is_string_range_node (branch[0]);
const bool b0_is_csr = details::is_const_string_range_node(branch[0]);
const bool b1_is_s = details::is_string_node (branch[1]);
const bool b1_is_cs = details::is_const_string_node (branch[1]);
const bool b1_is_sr = details::is_string_range_node (branch[1]);
const bool b1_is_csr = details::is_const_string_range_node(branch[1]);
const bool b0_is_gen = details::is_string_assignment_node (branch[0]) ||
details::is_genricstring_range_node(branch[0]) ||
details::is_string_concat_node (branch[0]) ||
details::is_string_function_node (branch[0]) ||
details::is_string_condition_node (branch[0]) ||
details::is_string_ccondition_node (branch[0]) ||
details::is_string_vararg_node (branch[0]) ;
const bool b1_is_gen = details::is_string_assignment_node (branch[1]) ||
details::is_genricstring_range_node(branch[1]) ||
details::is_string_concat_node (branch[1]) ||
details::is_string_function_node (branch[1]) ||
details::is_string_condition_node (branch[1]) ||
details::is_string_ccondition_node (branch[1]) ||
details::is_string_vararg_node (branch[1]) ;
if (details::e_add == opr)
{
if (!b0_is_cs || !b1_is_cs)
{
return synthesize_expression<string_concat_node_t,2>(opr,branch);
}
}
if (b0_is_gen || b1_is_gen)
{
return synthesize_strogen_expression(opr,branch);
}
else if (b0_is_s)
{
if (b1_is_s ) return synthesize_sos_expression (opr,branch);
else if (b1_is_cs ) return synthesize_socs_expression (opr,branch);
else if (b1_is_sr ) return synthesize_sosr_expression (opr,branch);
else if (b1_is_csr) return synthesize_socsr_expression (opr,branch);
}
else if (b0_is_cs)
{
if (b1_is_s ) return synthesize_csos_expression (opr,branch);
else if (b1_is_cs ) return synthesize_csocs_expression (opr,branch);
else if (b1_is_sr ) return synthesize_csosr_expression (opr,branch);
else if (b1_is_csr) return synthesize_csocsr_expression(opr,branch);
}
else if (b0_is_sr)
{
if (b1_is_s ) return synthesize_sros_expression (opr,branch);
else if (b1_is_sr ) return synthesize_srosr_expression (opr,branch);
else if (b1_is_cs ) return synthesize_srocs_expression (opr,branch);
else if (b1_is_csr) return synthesize_srocsr_expression(opr,branch);
}
else if (b0_is_csr)
{
if (b1_is_s ) return synthesize_csros_expression (opr,branch);
else if (b1_is_sr ) return synthesize_csrosr_expression (opr,branch);
else if (b1_is_cs ) return synthesize_csrocs_expression (opr,branch);
else if (b1_is_csr) return synthesize_csrocsr_expression(opr,branch);
}
return error_node();
}
#else
inline expression_node_ptr synthesize_string_expression(const details::operator_type&, expression_node_ptr (&branch)[2])
{
details::free_all_nodes(*node_allocator_,branch);
return error_node();
}
#endif
#ifndef exprtk_disable_string_capabilities
inline expression_node_ptr synthesize_string_expression(const details::operator_type& opr, expression_node_ptr (&branch)[3])
{
if (details::e_inrange != opr)
return error_node();
else if ((0 == branch[0]) || (0 == branch[1]) || (0 == branch[2]))
{
details::free_all_nodes(*node_allocator_,branch);
return error_node();
}
else if (
details::is_const_string_node(branch[0]) &&
details::is_const_string_node(branch[1]) &&
details::is_const_string_node(branch[2])
)
{
const std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str();
const std::string s1 = static_cast<details::string_literal_node<Type>*>(branch[1])->str();
const std::string s2 = static_cast<details::string_literal_node<Type>*>(branch[2])->str();
const Type v = (((s0 <= s1) && (s1 <= s2)) ? Type(1) : Type(0));
details::free_all_nodes(*node_allocator_,branch);
return node_allocator_->allocate_c<details::literal_node<Type> >(v);
}
else if (
details::is_string_node(branch[0]) &&
details::is_string_node(branch[1]) &&
details::is_string_node(branch[2])
)
{
std::string& s0 = static_cast<details::stringvar_node<Type>*>(branch[0])->ref();
std::string& s1 = static_cast<details::stringvar_node<Type>*>(branch[1])->ref();
std::string& s2 = static_cast<details::stringvar_node<Type>*>(branch[2])->ref();
typedef typename details::sosos_node<Type, std::string&, std::string&, std::string&, details::inrange_op<Type> > inrange_t;
return node_allocator_->allocate_type<inrange_t, std::string&, std::string&, std::string&>(s0, s1, s2);
}
else if (
details::is_const_string_node(branch[0]) &&
details::is_string_node(branch[1]) &&
details::is_const_string_node(branch[2])
)
{
std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str();
std::string& s1 = static_cast<details::stringvar_node<Type>* >(branch[1])->ref();
std::string s2 = static_cast<details::string_literal_node<Type>*>(branch[2])->str();
typedef typename details::sosos_node<Type, std::string, std::string&, std::string, details::inrange_op<Type> > inrange_t;
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[2]);
return node_allocator_->allocate_type<inrange_t, std::string, std::string&, std::string>(s0, s1, s2);
}
else if (
details::is_string_node(branch[0]) &&
details::is_const_string_node(branch[1]) &&
details::is_string_node(branch[2])
)
{
std::string& s0 = static_cast<details::stringvar_node<Type>* >(branch[0])->ref();
std::string s1 = static_cast<details::string_literal_node<Type>*>(branch[1])->str();
std::string& s2 = static_cast<details::stringvar_node<Type>* >(branch[2])->ref();
typedef typename details::sosos_node<Type, std::string&, std::string, std::string&, details::inrange_op<Type> > inrange_t;
details::free_node(*node_allocator_,branch[1]);
return node_allocator_->allocate_type<inrange_t, std::string&, std::string, std::string&>(s0, s1, s2);
}
else if (
details::is_string_node(branch[0]) &&
details::is_string_node(branch[1]) &&
details::is_const_string_node(branch[2])
)
{
std::string& s0 = static_cast<details::stringvar_node<Type>* >(branch[0])->ref();
std::string& s1 = static_cast<details::stringvar_node<Type>* >(branch[1])->ref();
std::string s2 = static_cast<details::string_literal_node<Type>*>(branch[2])->str();
typedef typename details::sosos_node<Type, std::string&, std::string&, std::string, details::inrange_op<Type> > inrange_t;
details::free_node(*node_allocator_,branch[2]);
return node_allocator_->allocate_type<inrange_t, std::string&, std::string&, std::string>(s0, s1, s2);
}
else if (
details::is_const_string_node(branch[0]) &&
details:: is_string_node(branch[1]) &&
details:: is_string_node(branch[2])
)
{
std::string s0 = static_cast<details::string_literal_node<Type>*>(branch[0])->str();
std::string& s1 = static_cast<details::stringvar_node<Type>* >(branch[1])->ref();
std::string& s2 = static_cast<details::stringvar_node<Type>* >(branch[2])->ref();
typedef typename details::sosos_node<Type, std::string, std::string&, std::string&, details::inrange_op<Type> > inrange_t;
details::free_node(*node_allocator_,branch[0]);
return node_allocator_->allocate_type<inrange_t, std::string, std::string&, std::string&>(s0, s1, s2);
}
else
return error_node();
}
#else
inline expression_node_ptr synthesize_string_expression(const details::operator_type&, expression_node_ptr (&branch)[3])
{
details::free_all_nodes(*node_allocator_,branch);
return error_node();
}
#endif
inline expression_node_ptr synthesize_null_expression(const details::operator_type& operation, expression_node_ptr (&branch)[2])
{
/*
Note: The following are the type promotion rules
that relate to operations that include 'null':
0. null ==/!= null --> true false
1. null operation null --> null
2. x ==/!= null --> true/false
3. null ==/!= x --> true/false
4. x operation null --> x
5. null operation x --> x
*/
typedef typename details::null_eq_node<T> nulleq_node_t;
const bool b0_null = details::is_null_node(branch[0]);
const bool b1_null = details::is_null_node(branch[1]);
if (b0_null && b1_null)
{
expression_node_ptr result = error_node();
if (details::e_eq == operation)
result = node_allocator_->allocate_c<literal_node_t>(T(1));
else if (details::e_ne == operation)
result = node_allocator_->allocate_c<literal_node_t>(T(0));
if (result)
{
details::free_node(*node_allocator_,branch[0]);
details::free_node(*node_allocator_,branch[1]);
return result;
}
details::free_node(*node_allocator_,branch[1]);
return branch[0];
}
else if (details::e_eq == operation)
{
expression_node_ptr result = node_allocator_->
allocate_rc<nulleq_node_t>(branch[b0_null ? 0 : 1],true);
details::free_node(*node_allocator_,branch[b0_null ? 1 : 0]);
return result;
}
else if (details::e_ne == operation)
{
expression_node_ptr result = node_allocator_->
allocate_rc<nulleq_node_t>(branch[b0_null ? 0 : 1],false);
details::free_node(*node_allocator_,branch[b0_null ? 1 : 0]);
return result;
}
else if (b0_null)
{
details::free_node(*node_allocator_,branch[0]);
branch[0] = branch[1];
branch[1] = error_node();
}
else if (b1_null)
{
details::free_node(*node_allocator_,branch[1]);
branch[1] = error_node();
}
if (
(details::e_add == operation) || (details::e_sub == operation) ||
(details::e_mul == operation) || (details::e_div == operation) ||
(details::e_mod == operation) || (details::e_pow == operation)
)
{
return branch[0];
}
details::free_node(*node_allocator_, branch[0]);
if (
(details::e_lt == operation) || (details::e_lte == operation) ||
(details::e_gt == operation) || (details::e_gte == operation) ||
(details::e_and == operation) || (details::e_nand == operation) ||
(details::e_or == operation) || (details::e_nor == operation) ||
(details::e_xor == operation) || (details::e_xnor == operation) ||
(details::e_in == operation) || (details::e_like == operation) ||
(details::e_ilike == operation)
)
{
return node_allocator_->allocate_c<literal_node_t>(T(0));
}
return node_allocator_->allocate<details::null_node<Type> >();
}
template <typename NodeType, std::size_t N>
inline expression_node_ptr synthesize_expression(const details::operator_type& operation, expression_node_ptr (&branch)[N])
{
if (
(details::e_in == operation) ||
(details::e_like == operation) ||
(details::e_ilike == operation)
)
{
free_all_nodes(*node_allocator_,branch);
return error_node();
}
else if (!details::all_nodes_valid<N>(branch))
{
free_all_nodes(*node_allocator_,branch);
return error_node();
}
else if ((details::e_default != operation))
{
// Attempt simple constant folding optimisation.
expression_node_ptr expression_point = node_allocator_->allocate<NodeType>(operation,branch);
if (is_constant_foldable<N>(branch))
{
const Type v = expression_point->value();
details::free_node(*node_allocator_,expression_point);
return node_allocator_->allocate<literal_node_t>(v);
}
else
return expression_point;
}
else
return error_node();
}
template <typename NodeType, std::size_t N>
inline expression_node_ptr synthesize_expression(F* f, expression_node_ptr (&branch)[N])
{
if (!details::all_nodes_valid<N>(branch))
{
free_all_nodes(*node_allocator_,branch);
return error_node();
}
typedef typename details::function_N_node<T,ifunction_t,N> function_N_node_t;
// Attempt simple constant folding optimisation.
expression_node_ptr expression_point = node_allocator_->allocate<NodeType>(f);
function_N_node_t* func_node_ptr = dynamic_cast<function_N_node_t*>(expression_point);
if (0 == func_node_ptr)
{
free_all_nodes(*node_allocator_,branch);
return error_node();
}
else
func_node_ptr->init_branches(branch);
if (is_constant_foldable<N>(branch) && !f->has_side_effects())
{
Type v = expression_point->value();
details::free_node(*node_allocator_,expression_point);
return node_allocator_->allocate<literal_node_t>(v);
}
parser_->state_.activate_side_effect("synthesize_expression(function<NT,N>)");
return expression_point;
}
bool strength_reduction_enabled_;
details::node_allocator* node_allocator_;
synthesize_map_t synthesize_map_;
unary_op_map_t* unary_op_map_;
binary_op_map_t* binary_op_map_;
inv_binary_op_map_t* inv_binary_op_map_;
sf3_map_t* sf3_map_;
sf4_map_t* sf4_map_;
parser_t* parser_;
}; // class expression_generator
inline void set_error(const parser_error::type& error_type)
{
error_list_.push_back(error_type);
}
inline void remove_last_error()
{
if (!error_list_.empty())
{
error_list_.pop_back();
}
}
inline void set_synthesis_error(const std::string& synthesis_error_message)
{
if (synthesis_error_.empty())
{
synthesis_error_ = synthesis_error_message;
}
}
inline void register_local_vars(expression<T>& e)
{
for (std::size_t i = 0; i < sem_.size(); ++i)
{
scope_element& se = sem_.get_element(i);
if (
(scope_element::e_variable == se.type) ||
(scope_element::e_vecelem == se.type)
)
{
if (se.var_node)
{
e.register_local_var(se.var_node);
}
if (se.data)
{
e.register_local_data(se.data, 1, 0);
}
}
else if (scope_element::e_vector == se.type)
{
if (se.vec_node)
{
e.register_local_var(se.vec_node);
}
if (se.data)
{
e.register_local_data(se.data, se.size, 1);
}
}
#ifndef exprtk_disable_string_capabilities
else if (scope_element::e_string == se.type)
{
if (se.str_node)
{
e.register_local_var(se.str_node);
}
if (se.data)
{
e.register_local_data(se.data, se.size, 2);
}
}
#endif
se.var_node = 0;
se.vec_node = 0;
#ifndef exprtk_disable_string_capabilities
se.str_node = 0;
#endif
se.data = 0;
se.ref_count = 0;
se.active = false;
}
}
inline void register_return_results(expression<T>& e)
{
e.register_return_results(results_context_);
results_context_ = 0;
}
inline void load_unary_operations_map(unary_op_map_t& m)
{
#define register_unary_op(Op, UnaryFunctor) \
m.insert(std::make_pair(Op,UnaryFunctor<T>::process)); \
register_unary_op(details::e_abs , details::abs_op )
register_unary_op(details::e_acos , details::acos_op )
register_unary_op(details::e_acosh , details::acosh_op)
register_unary_op(details::e_asin , details::asin_op )
register_unary_op(details::e_asinh , details::asinh_op)
register_unary_op(details::e_atanh , details::atanh_op)
register_unary_op(details::e_ceil , details::ceil_op )
register_unary_op(details::e_cos , details::cos_op )
register_unary_op(details::e_cosh , details::cosh_op )
register_unary_op(details::e_exp , details::exp_op )
register_unary_op(details::e_expm1 , details::expm1_op)
register_unary_op(details::e_floor , details::floor_op)
register_unary_op(details::e_log , details::log_op )
register_unary_op(details::e_log10 , details::log10_op)
register_unary_op(details::e_log2 , details::log2_op )
register_unary_op(details::e_log1p , details::log1p_op)
register_unary_op(details::e_neg , details::neg_op )
register_unary_op(details::e_pos , details::pos_op )
register_unary_op(details::e_round , details::round_op)
register_unary_op(details::e_sin , details::sin_op )
register_unary_op(details::e_sinc , details::sinc_op )
register_unary_op(details::e_sinh , details::sinh_op )
register_unary_op(details::e_sqrt , details::sqrt_op )
register_unary_op(details::e_tan , details::tan_op )
register_unary_op(details::e_tanh , details::tanh_op )
register_unary_op(details::e_cot , details::cot_op )
register_unary_op(details::e_sec , details::sec_op )
register_unary_op(details::e_csc , details::csc_op )
register_unary_op(details::e_r2d , details::r2d_op )
register_unary_op(details::e_d2r , details::d2r_op )
register_unary_op(details::e_d2g , details::d2g_op )
register_unary_op(details::e_g2d , details::g2d_op )
register_unary_op(details::e_notl , details::notl_op )
register_unary_op(details::e_sgn , details::sgn_op )
register_unary_op(details::e_erf , details::erf_op )
register_unary_op(details::e_erfc , details::erfc_op )
register_unary_op(details::e_ncdf , details::ncdf_op )
register_unary_op(details::e_frac , details::frac_op )
register_unary_op(details::e_trunc , details::trunc_op)
#undef register_unary_op
}
inline void load_binary_operations_map(binary_op_map_t& m)
{
typedef typename binary_op_map_t::value_type value_type;
#define register_binary_op(Op, BinaryFunctor) \
m.insert(value_type(Op,BinaryFunctor<T>::process)); \
register_binary_op(details::e_add , details::add_op )
register_binary_op(details::e_sub , details::sub_op )
register_binary_op(details::e_mul , details::mul_op )
register_binary_op(details::e_div , details::div_op )
register_binary_op(details::e_mod , details::mod_op )
register_binary_op(details::e_pow , details::pow_op )
register_binary_op(details::e_lt , details::lt_op )
register_binary_op(details::e_lte , details::lte_op )
register_binary_op(details::e_gt , details::gt_op )
register_binary_op(details::e_gte , details::gte_op )
register_binary_op(details::e_eq , details::eq_op )
register_binary_op(details::e_ne , details::ne_op )
register_binary_op(details::e_and , details::and_op )
register_binary_op(details::e_nand , details::nand_op)
register_binary_op(details::e_or , details::or_op )
register_binary_op(details::e_nor , details::nor_op )
register_binary_op(details::e_xor , details::xor_op )
register_binary_op(details::e_xnor , details::xnor_op)
#undef register_binary_op
}
inline void load_inv_binary_operations_map(inv_binary_op_map_t& m)
{
typedef typename inv_binary_op_map_t::value_type value_type;
#define register_binary_op(Op, BinaryFunctor) \
m.insert(value_type(BinaryFunctor<T>::process,Op)); \
register_binary_op(details::e_add , details::add_op )
register_binary_op(details::e_sub , details::sub_op )
register_binary_op(details::e_mul , details::mul_op )
register_binary_op(details::e_div , details::div_op )
register_binary_op(details::e_mod , details::mod_op )
register_binary_op(details::e_pow , details::pow_op )
register_binary_op(details::e_lt , details::lt_op )
register_binary_op(details::e_lte , details::lte_op )
register_binary_op(details::e_gt , details::gt_op )
register_binary_op(details::e_gte , details::gte_op )
register_binary_op(details::e_eq , details::eq_op )
register_binary_op(details::e_ne , details::ne_op )
register_binary_op(details::e_and , details::and_op )
register_binary_op(details::e_nand , details::nand_op)
register_binary_op(details::e_or , details::or_op )
register_binary_op(details::e_nor , details::nor_op )
register_binary_op(details::e_xor , details::xor_op )
register_binary_op(details::e_xnor , details::xnor_op)
#undef register_binary_op
}
inline void load_sf3_map(sf3_map_t& sf3_map)
{
typedef std::pair<trinary_functor_t,details::operator_type> pair_t;
#define register_sf3(Op) \
sf3_map[details::sf##Op##_op<T>::id()] = pair_t(details::sf##Op##_op<T>::process,details::e_sf##Op); \
register_sf3(00) register_sf3(01) register_sf3(02) register_sf3(03)
register_sf3(04) register_sf3(05) register_sf3(06) register_sf3(07)
register_sf3(08) register_sf3(09) register_sf3(10) register_sf3(11)
register_sf3(12) register_sf3(13) register_sf3(14) register_sf3(15)
register_sf3(16) register_sf3(17) register_sf3(18) register_sf3(19)
register_sf3(20) register_sf3(21) register_sf3(22) register_sf3(23)
register_sf3(24) register_sf3(25) register_sf3(26) register_sf3(27)
register_sf3(28) register_sf3(29) register_sf3(30)
#undef register_sf3
#define register_sf3_extid(Id, Op) \
sf3_map[Id] = pair_t(details::sf##Op##_op<T>::process,details::e_sf##Op); \
register_sf3_extid("(t-t)-t",23) // (t-t)-t --> t-(t+t)
#undef register_sf3_extid
}
inline void load_sf4_map(sf4_map_t& sf4_map)
{
typedef std::pair<quaternary_functor_t,details::operator_type> pair_t;
#define register_sf4(Op) \
sf4_map[details::sf##Op##_op<T>::id()] = pair_t(details::sf##Op##_op<T>::process,details::e_sf##Op); \
register_sf4(48) register_sf4(49) register_sf4(50) register_sf4(51)
register_sf4(52) register_sf4(53) register_sf4(54) register_sf4(55)
register_sf4(56) register_sf4(57) register_sf4(58) register_sf4(59)
register_sf4(60) register_sf4(61) register_sf4(62) register_sf4(63)
register_sf4(64) register_sf4(65) register_sf4(66) register_sf4(67)
register_sf4(68) register_sf4(69) register_sf4(70) register_sf4(71)
register_sf4(72) register_sf4(73) register_sf4(74) register_sf4(75)
register_sf4(76) register_sf4(77) register_sf4(78) register_sf4(79)
register_sf4(80) register_sf4(81) register_sf4(82) register_sf4(83)
#undef register_sf4
#define register_sf4ext(Op) \
sf4_map[details::sfext##Op##_op<T>::id()] = pair_t(details::sfext##Op##_op<T>::process,details::e_sf4ext##Op); \
register_sf4ext(00) register_sf4ext(01) register_sf4ext(02) register_sf4ext(03)
register_sf4ext(04) register_sf4ext(05) register_sf4ext(06) register_sf4ext(07)
register_sf4ext(08) register_sf4ext(09) register_sf4ext(10) register_sf4ext(11)
register_sf4ext(12) register_sf4ext(13) register_sf4ext(14) register_sf4ext(15)
register_sf4ext(16) register_sf4ext(17) register_sf4ext(18) register_sf4ext(19)
register_sf4ext(20) register_sf4ext(21) register_sf4ext(22) register_sf4ext(23)
register_sf4ext(24) register_sf4ext(25) register_sf4ext(26) register_sf4ext(27)
register_sf4ext(28) register_sf4ext(29) register_sf4ext(30) register_sf4ext(31)
register_sf4ext(32) register_sf4ext(33) register_sf4ext(34) register_sf4ext(35)
register_sf4ext(36) register_sf4ext(36) register_sf4ext(38) register_sf4ext(39)
register_sf4ext(40) register_sf4ext(41) register_sf4ext(42) register_sf4ext(43)
register_sf4ext(44) register_sf4ext(45) register_sf4ext(46) register_sf4ext(47)
register_sf4ext(48) register_sf4ext(49) register_sf4ext(50) register_sf4ext(51)
register_sf4ext(52) register_sf4ext(53) register_sf4ext(54) register_sf4ext(55)
register_sf4ext(56) register_sf4ext(57) register_sf4ext(58) register_sf4ext(59)
register_sf4ext(60) register_sf4ext(61)
#undef register_sf4ext
}
inline results_context_t& results_ctx()
{
if (0 == results_context_)
{
results_context_ = new results_context_t();
}
return (*results_context_);
}
inline void return_cleanup()
{
#ifndef exprtk_disable_return_statement
if (results_context_)
{
delete results_context_;
results_context_ = 0;
}
state_.return_stmt_present = false;
#endif
}
private:
parser(const parser<T>&) exprtk_delete;
parser<T>& operator=(const parser<T>&) exprtk_delete;
settings_store settings_;
expression_generator<T> expression_generator_;
details::node_allocator node_allocator_;
symtab_store symtab_store_;
dependent_entity_collector dec_;
std::deque<parser_error::type> error_list_;
std::deque<bool> brkcnt_list_;
parser_state state_;
bool resolve_unknown_symbol_;
results_context_t* results_context_;
unknown_symbol_resolver* unknown_symbol_resolver_;
unknown_symbol_resolver default_usr_;
base_ops_map_t base_ops_map_;
unary_op_map_t unary_op_map_;
binary_op_map_t binary_op_map_;
inv_binary_op_map_t inv_binary_op_map_;
sf3_map_t sf3_map_;
sf4_map_t sf4_map_;
std::string synthesis_error_;
scope_element_manager sem_;
immutable_memory_map_t immutable_memory_map_;
immutable_symtok_map_t immutable_symtok_map_;
lexer::helper::helper_assembly helper_assembly_;
lexer::helper::commutative_inserter commutative_inserter_;
lexer::helper::operator_joiner operator_joiner_2_;
lexer::helper::operator_joiner operator_joiner_3_;
lexer::helper::symbol_replacer symbol_replacer_;
lexer::helper::bracket_checker bracket_checker_;
lexer::helper::numeric_checker<T> numeric_checker_;
lexer::helper::sequence_validator sequence_validator_;
lexer::helper::sequence_validator_3tokens sequence_validator_3tkns_;
loop_runtime_check_ptr loop_runtime_check_;
template <typename ParserType>
friend void details::disable_type_checking(ParserType& p);
}; // class parser
namespace details
{
template <typename T>
struct collector_helper
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
typedef typename parser_t::dependent_entity_collector::symbol_t symbol_t;
typedef typename parser_t::unknown_symbol_resolver usr_t;
struct resolve_as_vector : public parser_t::unknown_symbol_resolver
{
typedef exprtk::parser<T> parser_t;
resolve_as_vector()
: usr_t(usr_t::e_usrmode_extended)
{}
virtual bool process(const std::string& unknown_symbol,
symbol_table_t& symbol_table,
std::string&)
{
static T v[1];
symbol_table.add_vector(unknown_symbol,v);
return true;
}
};
static inline bool collection_pass(const std::string& expression_string,
std::set<std::string>& symbol_set,
const bool collect_variables,
const bool collect_functions,
const bool vector_pass,
symbol_table_t& ext_symbol_table)
{
symbol_table_t symbol_table;
expression_t expression;
parser_t parser;
resolve_as_vector vect_resolver;
expression.register_symbol_table(symbol_table );
expression.register_symbol_table(ext_symbol_table);
if (vector_pass)
parser.enable_unknown_symbol_resolver(&vect_resolver);
else
parser.enable_unknown_symbol_resolver();
if (collect_variables)
parser.dec().collect_variables() = true;
if (collect_functions)
parser.dec().collect_functions() = true;
bool pass_result = false;
details::disable_type_checking(parser);
if (parser.compile(expression_string, expression))
{
pass_result = true;
std::deque<symbol_t> symb_list;
parser.dec().symbols(symb_list);
for (std::size_t i = 0; i < symb_list.size(); ++i)
{
symbol_set.insert(symb_list[i].first);
}
}
return pass_result;
}
};
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline bool collect_variables(const std::string& expression,
Sequence<std::string, Allocator>& symbol_list)
{
typedef double T;
typedef details::collector_helper<T> collect_t;
collect_t::symbol_table_t null_symbol_table;
std::set<std::string> symbol_set;
const bool variable_pass = collect_t::collection_pass
(expression, symbol_set, true, false, false, null_symbol_table);
const bool vector_pass = collect_t::collection_pass
(expression, symbol_set, true, false, true, null_symbol_table);
if (!variable_pass && !vector_pass)
return false;
std::set<std::string>::iterator itr = symbol_set.begin();
while (symbol_set.end() != itr)
{
symbol_list.push_back(*itr);
++itr;
}
return true;
}
template <typename T,
typename Allocator,
template <typename, typename> class Sequence>
inline bool collect_variables(const std::string& expression,
exprtk::symbol_table<T>& extrnl_symbol_table,
Sequence<std::string, Allocator>& symbol_list)
{
typedef details::collector_helper<T> collect_t;
std::set<std::string> symbol_set;
const bool variable_pass = collect_t::collection_pass
(expression, symbol_set, true, false, false, extrnl_symbol_table);
const bool vector_pass = collect_t::collection_pass
(expression, symbol_set, true, false, true, extrnl_symbol_table);
if (!variable_pass && !vector_pass)
return false;
std::set<std::string>::iterator itr = symbol_set.begin();
while (symbol_set.end() != itr)
{
symbol_list.push_back(*itr);
++itr;
}
return true;
}
template <typename Allocator,
template <typename, typename> class Sequence>
inline bool collect_functions(const std::string& expression,
Sequence<std::string, Allocator>& symbol_list)
{
typedef double T;
typedef details::collector_helper<T> collect_t;
collect_t::symbol_table_t null_symbol_table;
std::set<std::string> symbol_set;
const bool variable_pass = collect_t::collection_pass
(expression, symbol_set, false, true, false, null_symbol_table);
const bool vector_pass = collect_t::collection_pass
(expression, symbol_set, false, true, true, null_symbol_table);
if (!variable_pass && !vector_pass)
return false;
std::set<std::string>::iterator itr = symbol_set.begin();
while (symbol_set.end() != itr)
{
symbol_list.push_back(*itr);
++itr;
}
return true;
}
template <typename T,
typename Allocator,
template <typename, typename> class Sequence>
inline bool collect_functions(const std::string& expression,
exprtk::symbol_table<T>& extrnl_symbol_table,
Sequence<std::string, Allocator>& symbol_list)
{
typedef details::collector_helper<T> collect_t;
std::set<std::string> symbol_set;
const bool variable_pass = collect_t::collection_pass
(expression, symbol_set, false, true, false, extrnl_symbol_table);
const bool vector_pass = collect_t::collection_pass
(expression, symbol_set, false, true, true, extrnl_symbol_table);
if (!variable_pass && !vector_pass)
return false;
std::set<std::string>::iterator itr = symbol_set.begin();
while (symbol_set.end() != itr)
{
symbol_list.push_back(*itr);
++itr;
}
return true;
}
template <typename T>
inline T integrate(const expression<T>& e,
T& x,
const T& r0, const T& r1,
const std::size_t number_of_intervals = 1000000)
{
if (r0 > r1)
return T(0);
const T h = (r1 - r0) / (T(2) * number_of_intervals);
T total_area = T(0);
for (std::size_t i = 0; i < number_of_intervals; ++i)
{
x = r0 + T(2) * i * h;
const T y0 = e.value(); x += h;
const T y1 = e.value(); x += h;
const T y2 = e.value(); x += h;
total_area += h * (y0 + T(4) * y1 + y2) / T(3);
}
return total_area;
}
template <typename T>
inline T integrate(const expression<T>& e,
const std::string& variable_name,
const T& r0, const T& r1,
const std::size_t number_of_intervals = 1000000)
{
const symbol_table<T>& sym_table = e.get_symbol_table();
if (!sym_table.valid())
return std::numeric_limits<T>::quiet_NaN();
details::variable_node<T>* var = sym_table.get_variable(variable_name);
if (var)
{
T& x = var->ref();
const T x_original = x;
const T result = integrate(e, x, r0, r1, number_of_intervals);
x = x_original;
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
template <typename T>
inline T derivative(const expression<T>& e,
T& x,
const T& h = T(0.00000001))
{
const T x_init = x;
const T _2h = T(2) * h;
x = x_init + _2h;
const T y0 = e.value();
x = x_init + h;
const T y1 = e.value();
x = x_init - h;
const T y2 = e.value();
x = x_init - _2h;
const T y3 = e.value();
x = x_init;
return (-y0 + T(8) * (y1 - y2) + y3) / (T(12) * h);
}
template <typename T>
inline T second_derivative(const expression<T>& e,
T& x,
const T& h = T(0.00001))
{
const T x_init = x;
const T _2h = T(2) * h;
const T y = e.value();
x = x_init + _2h;
const T y0 = e.value();
x = x_init + h;
const T y1 = e.value();
x = x_init - h;
const T y2 = e.value();
x = x_init - _2h;
const T y3 = e.value();
x = x_init;
return (-y0 + T(16) * (y1 + y2) - T(30) * y - y3) / (T(12) * h * h);
}
template <typename T>
inline T third_derivative(const expression<T>& e,
T& x,
const T& h = T(0.0001))
{
const T x_init = x;
const T _2h = T(2) * h;
x = x_init + _2h;
const T y0 = e.value();
x = x_init + h;
const T y1 = e.value();
x = x_init - h;
const T y2 = e.value();
x = x_init - _2h;
const T y3 = e.value();
x = x_init;
return (y0 + T(2) * (y2 - y1) - y3) / (T(2) * h * h * h);
}
template <typename T>
inline T derivative(const expression<T>& e,
const std::string& variable_name,
const T& h = T(0.00000001))
{
const symbol_table<T>& sym_table = e.get_symbol_table();
if (!sym_table.valid())
{
return std::numeric_limits<T>::quiet_NaN();
}
details::variable_node<T>* var = sym_table.get_variable(variable_name);
if (var)
{
T& x = var->ref();
const T x_original = x;
const T result = derivative(e, x, h);
x = x_original;
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
template <typename T>
inline T second_derivative(const expression<T>& e,
const std::string& variable_name,
const T& h = T(0.00001))
{
const symbol_table<T>& sym_table = e.get_symbol_table();
if (!sym_table.valid())
{
return std::numeric_limits<T>::quiet_NaN();
}
details::variable_node<T>* var = sym_table.get_variable(variable_name);
if (var)
{
T& x = var->ref();
const T x_original = x;
const T result = second_derivative(e, x, h);
x = x_original;
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
template <typename T>
inline T third_derivative(const expression<T>& e,
const std::string& variable_name,
const T& h = T(0.0001))
{
const symbol_table<T>& sym_table = e.get_symbol_table();
if (!sym_table.valid())
{
return std::numeric_limits<T>::quiet_NaN();
}
details::variable_node<T>* var = sym_table.get_variable(variable_name);
if (var)
{
T& x = var->ref();
const T x_original = x;
const T result = third_derivative(e, x, h);
x = x_original;
return result;
}
else
return std::numeric_limits<T>::quiet_NaN();
}
/*
Note: The following 'compute' routines are simple helpers,
for quickly setting up the required pieces of code in order
to evaluate an expression. By virtue of how they operate
there will be an overhead with regards to their setup and
teardown and hence should not be used in time critical
sections of code.
Furthermore they only assume a small sub set of variables,
no string variables or user defined functions.
*/
template <typename T>
inline bool compute(const std::string& expression_string, T& result)
{
// No variables
symbol_table<T> symbol_table;
symbol_table.add_constants();
expression<T> expression;
expression.register_symbol_table(symbol_table);
parser<T> parser;
if (parser.compile(expression_string,expression))
{
result = expression.value();
return true;
}
else
return false;
}
template <typename T>
inline bool compute(const std::string& expression_string,
const T& x,
T& result)
{
// Only 'x'
static const std::string x_var("x");
symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_constant(x_var,x);
expression<T> expression;
expression.register_symbol_table(symbol_table);
parser<T> parser;
if (parser.compile(expression_string,expression))
{
result = expression.value();
return true;
}
else
return false;
}
template <typename T>
inline bool compute(const std::string& expression_string,
const T&x, const T& y,
T& result)
{
// Only 'x' and 'y'
static const std::string x_var("x");
static const std::string y_var("y");
symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_constant(x_var,x);
symbol_table.add_constant(y_var,y);
expression<T> expression;
expression.register_symbol_table(symbol_table);
parser<T> parser;
if (parser.compile(expression_string,expression))
{
result = expression.value();
return true;
}
else
return false;
}
template <typename T>
inline bool compute(const std::string& expression_string,
const T& x, const T& y, const T& z,
T& result)
{
// Only 'x', 'y' or 'z'
static const std::string x_var("x");
static const std::string y_var("y");
static const std::string z_var("z");
symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_constant(x_var,x);
symbol_table.add_constant(y_var,y);
symbol_table.add_constant(z_var,z);
expression<T> expression;
expression.register_symbol_table(symbol_table);
parser<T> parser;
if (parser.compile(expression_string,expression))
{
result = expression.value();
return true;
}
else
return false;
}
template <typename T, std::size_t N>
class polynomial : public ifunction<T>
{
private:
template <typename Type, std::size_t NumberOfCoefficients>
struct poly_impl { };
template <typename Type>
struct poly_impl <Type,12>
{
static inline T evaluate(const Type x,
const Type c12, const Type c11, const Type c10, const Type c9, const Type c8,
const Type c7, const Type c6, const Type c5, const Type c4, const Type c3,
const Type c2, const Type c1, const Type c0)
{
// p(x) = c_12x^12 + c_11x^11 + c_10x^10 + c_9x^9 + c_8x^8 + c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return ((((((((((((c12 * x + c11) * x + c10) * x + c9) * x + c8) * x + c7) * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,11>
{
static inline T evaluate(const Type x,
const Type c11, const Type c10, const Type c9, const Type c8, const Type c7,
const Type c6, const Type c5, const Type c4, const Type c3, const Type c2,
const Type c1, const Type c0)
{
// p(x) = c_11x^11 + c_10x^10 + c_9x^9 + c_8x^8 + c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return (((((((((((c11 * x + c10) * x + c9) * x + c8) * x + c7) * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,10>
{
static inline T evaluate(const Type x,
const Type c10, const Type c9, const Type c8, const Type c7, const Type c6,
const Type c5, const Type c4, const Type c3, const Type c2, const Type c1,
const Type c0)
{
// p(x) = c_10x^10 + c_9x^9 + c_8x^8 + c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return ((((((((((c10 * x + c9) * x + c8) * x + c7) * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,9>
{
static inline T evaluate(const Type x,
const Type c9, const Type c8, const Type c7, const Type c6, const Type c5,
const Type c4, const Type c3, const Type c2, const Type c1, const Type c0)
{
// p(x) = c_9x^9 + c_8x^8 + c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return (((((((((c9 * x + c8) * x + c7) * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,8>
{
static inline T evaluate(const Type x,
const Type c8, const Type c7, const Type c6, const Type c5, const Type c4,
const Type c3, const Type c2, const Type c1, const Type c0)
{
// p(x) = c_8x^8 + c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return ((((((((c8 * x + c7) * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,7>
{
static inline T evaluate(const Type x,
const Type c7, const Type c6, const Type c5, const Type c4, const Type c3,
const Type c2, const Type c1, const Type c0)
{
// p(x) = c_7x^7 + c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return (((((((c7 * x + c6) * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,6>
{
static inline T evaluate(const Type x,
const Type c6, const Type c5, const Type c4, const Type c3, const Type c2,
const Type c1, const Type c0)
{
// p(x) = c_6x^6 + c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return ((((((c6 * x + c5) * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,5>
{
static inline T evaluate(const Type x,
const Type c5, const Type c4, const Type c3, const Type c2,
const Type c1, const Type c0)
{
// p(x) = c_5x^5 + c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return (((((c5 * x + c4) * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,4>
{
static inline T evaluate(const Type x, const Type c4, const Type c3, const Type c2, const Type c1, const Type c0)
{
// p(x) = c_4x^4 + c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return ((((c4 * x + c3) * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,3>
{
static inline T evaluate(const Type x, const Type c3, const Type c2, const Type c1, const Type c0)
{
// p(x) = c_3x^3 + c_2x^2 + c_1x^1 + c_0x^0
return (((c3 * x + c2) * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,2>
{
static inline T evaluate(const Type x, const Type c2, const Type c1, const Type c0)
{
// p(x) = c_2x^2 + c_1x^1 + c_0x^0
return ((c2 * x + c1) * x + c0);
}
};
template <typename Type>
struct poly_impl <Type,1>
{
static inline T evaluate(const Type x, const Type c1, const Type c0)
{
// p(x) = c_1x^1 + c_0x^0
return (c1 * x + c0);
}
};
public:
using ifunction<T>::operator();
polynomial()
: ifunction<T>((N+2 <= 20) ? (N + 2) : std::numeric_limits<std::size_t>::max())
{
disable_has_side_effects(*this);
}
virtual ~polynomial() {}
#define poly_rtrn(NN) \
return (NN != N) ? std::numeric_limits<T>::quiet_NaN() :
inline virtual T operator() (const T& x, const T& c1, const T& c0)
{
poly_rtrn(1) (poly_impl<T,1>::evaluate(x, c1, c0));
}
inline virtual T operator() (const T& x, const T& c2, const T& c1, const T& c0)
{
poly_rtrn(2) (poly_impl<T,2>::evaluate(x, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c3, const T& c2, const T& c1, const T& c0)
{
poly_rtrn(3) (poly_impl<T,3>::evaluate(x, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c4, const T& c3, const T& c2, const T& c1,
const T& c0)
{
poly_rtrn(4) (poly_impl<T,4>::evaluate(x, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c5, const T& c4, const T& c3, const T& c2,
const T& c1, const T& c0)
{
poly_rtrn(5) (poly_impl<T,5>::evaluate(x, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c6, const T& c5, const T& c4, const T& c3,
const T& c2, const T& c1, const T& c0)
{
poly_rtrn(6) (poly_impl<T,6>::evaluate(x, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c7, const T& c6, const T& c5, const T& c4,
const T& c3, const T& c2, const T& c1, const T& c0)
{
poly_rtrn(7) (poly_impl<T,7>::evaluate(x, c7, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c8, const T& c7, const T& c6, const T& c5,
const T& c4, const T& c3, const T& c2, const T& c1, const T& c0)
{
poly_rtrn(8) (poly_impl<T,8>::evaluate(x, c8, c7, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c9, const T& c8, const T& c7, const T& c6,
const T& c5, const T& c4, const T& c3, const T& c2, const T& c1,
const T& c0)
{
poly_rtrn(9) (poly_impl<T,9>::evaluate(x, c9, c8, c7, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c10, const T& c9, const T& c8, const T& c7,
const T& c6, const T& c5, const T& c4, const T& c3, const T& c2,
const T& c1, const T& c0)
{
poly_rtrn(10) (poly_impl<T,10>::evaluate(x, c10, c9, c8, c7, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c11, const T& c10, const T& c9, const T& c8,
const T& c7, const T& c6, const T& c5, const T& c4, const T& c3,
const T& c2, const T& c1, const T& c0)
{
poly_rtrn(11) (poly_impl<T,11>::evaluate(x, c11, c10, c9, c8, c7, c6, c5, c4, c3, c2, c1, c0));
}
inline virtual T operator() (const T& x, const T& c12, const T& c11, const T& c10, const T& c9,
const T& c8, const T& c7, const T& c6, const T& c5, const T& c4,
const T& c3, const T& c2, const T& c1, const T& c0)
{
poly_rtrn(12) (poly_impl<T,12>::evaluate(x, c12, c11, c10, c9, c8, c7, c6, c5, c4, c3, c2, c1, c0));
}
#undef poly_rtrn
inline virtual T operator() ()
{
return std::numeric_limits<T>::quiet_NaN();
}
inline virtual T operator() (const T&)
{
return std::numeric_limits<T>::quiet_NaN();
}
inline virtual T operator() (const T&, const T&)
{
return std::numeric_limits<T>::quiet_NaN();
}
};
template <typename T>
class function_compositor
{
public:
typedef exprtk::expression<T> expression_t;
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::parser<T> parser_t;
typedef typename parser_t::settings_store settings_t;
struct function
{
function()
{}
function(const std::string& n)
: name_(n)
{}
function(const std::string& name,
const std::string& expression)
: name_(name)
, expression_(expression)
{}
function(const std::string& name,
const std::string& expression,
const std::string& v0)
: name_(name)
, expression_(expression)
{
v_.push_back(v0);
}
function(const std::string& name,
const std::string& expression,
const std::string& v0, const std::string& v1)
: name_(name)
, expression_(expression)
{
v_.push_back(v0); v_.push_back(v1);
}
function(const std::string& name,
const std::string& expression,
const std::string& v0, const std::string& v1,
const std::string& v2)
: name_(name)
, expression_(expression)
{
v_.push_back(v0); v_.push_back(v1);
v_.push_back(v2);
}
function(const std::string& name,
const std::string& expression,
const std::string& v0, const std::string& v1,
const std::string& v2, const std::string& v3)
: name_(name)
, expression_(expression)
{
v_.push_back(v0); v_.push_back(v1);
v_.push_back(v2); v_.push_back(v3);
}
function(const std::string& name,
const std::string& expression,
const std::string& v0, const std::string& v1,
const std::string& v2, const std::string& v3,
const std::string& v4)
: name_(name)
, expression_(expression)
{
v_.push_back(v0); v_.push_back(v1);
v_.push_back(v2); v_.push_back(v3);
v_.push_back(v4);
}
inline function& name(const std::string& n)
{
name_ = n;
return (*this);
}
inline function& expression(const std::string& e)
{
expression_ = e;
return (*this);
}
inline function& var(const std::string& v)
{
v_.push_back(v);
return (*this);
}
std::string name_;
std::string expression_;
std::deque<std::string> v_;
};
private:
struct base_func : public exprtk::ifunction<T>
{
typedef const T& type;
typedef exprtk::ifunction<T> function_t;
typedef std::vector<T*> varref_t;
typedef std::vector<T> var_t;
typedef std::pair<T*,std::size_t> lvarref_t;
typedef std::vector<lvarref_t> lvr_vec_t;
using exprtk::ifunction<T>::operator();
base_func(const std::size_t& pc = 0)
: exprtk::ifunction<T>(pc)
, local_var_stack_size(0)
, stack_depth(0)
{
v.resize(pc);
}
virtual ~base_func() {}
#define exprtk_assign(Index) \
(*v[Index]) = v##Index; \
inline void update(const T& v0)
{
exprtk_assign(0)
}
inline void update(const T& v0, const T& v1)
{
exprtk_assign(0) exprtk_assign(1)
}
inline void update(const T& v0, const T& v1, const T& v2)
{
exprtk_assign(0) exprtk_assign(1)
exprtk_assign(2)
}
inline void update(const T& v0, const T& v1, const T& v2, const T& v3)
{
exprtk_assign(0) exprtk_assign(1)
exprtk_assign(2) exprtk_assign(3)
}
inline void update(const T& v0, const T& v1, const T& v2, const T& v3, const T& v4)
{
exprtk_assign(0) exprtk_assign(1)
exprtk_assign(2) exprtk_assign(3)
exprtk_assign(4)
}
inline void update(const T& v0, const T& v1, const T& v2, const T& v3, const T& v4, const T& v5)
{
exprtk_assign(0) exprtk_assign(1)
exprtk_assign(2) exprtk_assign(3)
exprtk_assign(4) exprtk_assign(5)
}
#ifdef exprtk_assign
#undef exprtk_assign
#endif
inline function_t& setup(expression_t& expr)
{
expression = expr;
typedef typename expression_t::control_block::local_data_list_t ldl_t;
const ldl_t ldl = expr.local_data_list();
std::vector<std::size_t> index_list;
for (std::size_t i = 0; i < ldl.size(); ++i)
{
if (ldl[i].size)
{
index_list.push_back(i);
}
}
std::size_t input_param_count = 0;
for (std::size_t i = 0; i < index_list.size(); ++i)
{
const std::size_t index = index_list[i];
if (i < (index_list.size() - v.size()))
{
lv.push_back(
std::make_pair(
reinterpret_cast<T*>(ldl[index].pointer),
ldl[index].size));
local_var_stack_size += ldl[index].size;
}
else
v[input_param_count++] = reinterpret_cast<T*>(ldl[index].pointer);
}
clear_stack();
return (*this);
}
inline void pre()
{
if (stack_depth++)
{
if (!v.empty())
{
var_t var_stack(v.size(),T(0));
copy(v,var_stack);
param_stack.push_back(var_stack);
}
if (!lv.empty())
{
var_t local_var_stack(local_var_stack_size,T(0));
copy(lv,local_var_stack);
local_stack.push_back(local_var_stack);
}
}
}
inline void post()
{
if (--stack_depth)
{
if (!v.empty())
{
copy(param_stack.back(),v);
param_stack.pop_back();
}
if (!lv.empty())
{
copy(local_stack.back(),lv);
local_stack.pop_back();
}
}
}
void copy(const varref_t& src_v, var_t& dest_v)
{
for (std::size_t i = 0; i < src_v.size(); ++i)
{
dest_v[i] = (*src_v[i]);
}
}
void copy(const var_t& src_v, varref_t& dest_v)
{
for (std::size_t i = 0; i < src_v.size(); ++i)
{
(*dest_v[i]) = src_v[i];
}
}
void copy(const lvr_vec_t& src_v, var_t& dest_v)
{
typename var_t::iterator itr = dest_v.begin();
typedef typename std::iterator_traits<typename var_t::iterator>::difference_type diff_t;
for (std::size_t i = 0; i < src_v.size(); ++i)
{
lvarref_t vr = src_v[i];
if (1 == vr.second)
*itr++ = (*vr.first);
else
{
std::copy(vr.first, vr.first + vr.second, itr);
itr += static_cast<diff_t>(vr.second);
}
}
}
void copy(const var_t& src_v, lvr_vec_t& dest_v)
{
typename var_t::const_iterator itr = src_v.begin();
typedef typename std::iterator_traits<typename var_t::iterator>::difference_type diff_t;
for (std::size_t i = 0; i < src_v.size(); ++i)
{
lvarref_t vr = dest_v[i];
if (1 == vr.second)
(*vr.first) = *itr++;
else
{
std::copy(itr, itr + static_cast<diff_t>(vr.second), vr.first);
itr += static_cast<diff_t>(vr.second);
}
}
}
inline void clear_stack()
{
for (std::size_t i = 0; i < v.size(); ++i)
{
(*v[i]) = 0;
}
}
inline virtual T value(expression_t& e)
{
return e.value();
}
expression_t expression;
varref_t v;
lvr_vec_t lv;
std::size_t local_var_stack_size;
std::size_t stack_depth;
std::deque<var_t> param_stack;
std::deque<var_t> local_stack;
};
typedef std::map<std::string,base_func*> funcparam_t;
struct func_0param : public base_func
{
using exprtk::ifunction<T>::operator();
func_0param() : base_func(0) {}
inline T operator() ()
{
return this->value(base_func::expression);
}
};
typedef const T& type;
template <typename BaseFuncType>
struct scoped_bft
{
explicit scoped_bft(BaseFuncType& bft)
: bft_(bft)
{
bft_.pre ();
}
~scoped_bft()
{
bft_.post();
}
BaseFuncType& bft_;
private:
scoped_bft(const scoped_bft&) exprtk_delete;
scoped_bft& operator=(const scoped_bft&) exprtk_delete;
};
struct func_1param : public base_func
{
using exprtk::ifunction<T>::operator();
func_1param() : base_func(1) {}
inline T operator() (type v0)
{
scoped_bft<func_1param> sb(*this);
base_func::update(v0);
return this->value(base_func::expression);
}
};
struct func_2param : public base_func
{
using exprtk::ifunction<T>::operator();
func_2param() : base_func(2) {}
inline T operator() (type v0, type v1)
{
scoped_bft<func_2param> sb(*this);
base_func::update(v0, v1);
return this->value(base_func::expression);
}
};
struct func_3param : public base_func
{
using exprtk::ifunction<T>::operator();
func_3param() : base_func(3) {}
inline T operator() (type v0, type v1, type v2)
{
scoped_bft<func_3param> sb(*this);
base_func::update(v0, v1, v2);
return this->value(base_func::expression);
}
};
struct func_4param : public base_func
{
using exprtk::ifunction<T>::operator();
func_4param() : base_func(4) {}
inline T operator() (type v0, type v1, type v2, type v3)
{
scoped_bft<func_4param> sb(*this);
base_func::update(v0, v1, v2, v3);
return this->value(base_func::expression);
}
};
struct func_5param : public base_func
{
using exprtk::ifunction<T>::operator();
func_5param() : base_func(5) {}
inline T operator() (type v0, type v1, type v2, type v3, type v4)
{
scoped_bft<func_5param> sb(*this);
base_func::update(v0, v1, v2, v3, v4);
return this->value(base_func::expression);
}
};
struct func_6param : public base_func
{
using exprtk::ifunction<T>::operator();
func_6param() : base_func(6) {}
inline T operator() (type v0, type v1, type v2, type v3, type v4, type v5)
{
scoped_bft<func_6param> sb(*this);
base_func::update(v0, v1, v2, v3, v4, v5);
return this->value(base_func::expression);
}
};
static T return_value(expression_t& e)
{
typedef exprtk::results_context<T> results_context_t;
typedef typename results_context_t::type_store_t type_t;
typedef typename type_t::scalar_view scalar_t;
const T result = e.value();
if (e.return_invoked())
{
// Due to the post compilation checks, it can be safely
// assumed that there will be at least one parameter
// and that the first parameter will always be scalar.
return scalar_t(e.results()[0])();
}
return result;
}
#define def_fp_retval(N) \
struct func_##N##param_retval : public func_##N##param \
{ \
inline T value(expression_t& e) \
{ \
return return_value(e); \
} \
}; \
def_fp_retval(0)
def_fp_retval(1)
def_fp_retval(2)
def_fp_retval(3)
def_fp_retval(4)
def_fp_retval(5)
def_fp_retval(6)
template <typename Allocator,
template <typename, typename> class Sequence>
inline bool add(const std::string& name,
const std::string& expression,
const Sequence<std::string,Allocator>& var_list,
const bool override = false)
{
const typename std::map<std::string,expression_t>::iterator itr = expr_map_.find(name);
if (expr_map_.end() != itr)
{
if (!override)
{
exprtk_debug(("Compositor error(add): function '%s' already defined\n",
name.c_str()));
return false;
}
remove(name, var_list.size());
}
if (compile_expression(name, expression, var_list))
{
const std::size_t n = var_list.size();
fp_map_[n][name]->setup(expr_map_[name]);
return true;
}
else
{
exprtk_debug(("Compositor error(add): Failed to compile function '%s'\n",
name.c_str()));
return false;
}
}
public:
function_compositor()
: parser_(settings_t::compile_all_opts +
settings_t::e_disable_zero_return)
, fp_map_(7)
{}
function_compositor(const symbol_table_t& st)
: symbol_table_(st)
, parser_(settings_t::compile_all_opts +
settings_t::e_disable_zero_return)
, fp_map_(7)
{}
~function_compositor()
{
clear();
}
inline symbol_table_t& symbol_table()
{
return symbol_table_;
}
inline const symbol_table_t& symbol_table() const
{
return symbol_table_;
}
inline void add_auxiliary_symtab(symbol_table_t& symtab)
{
auxiliary_symtab_list_.push_back(&symtab);
}
void clear()
{
symbol_table_.clear();
expr_map_ .clear();
for (std::size_t i = 0; i < fp_map_.size(); ++i)
{
typename funcparam_t::iterator itr = fp_map_[i].begin();
typename funcparam_t::iterator end = fp_map_[i].end ();
while (itr != end)
{
delete itr->second;
++itr;
}
fp_map_[i].clear();
}
}
inline bool add(const function& f, const bool override = false)
{
return add(f.name_, f.expression_, f.v_,override);
}
private:
template <typename Allocator,
template <typename, typename> class Sequence>
bool compile_expression(const std::string& name,
const std::string& expression,
const Sequence<std::string,Allocator>& input_var_list,
bool return_present = false)
{
expression_t compiled_expression;
symbol_table_t local_symbol_table;
local_symbol_table.load_from(symbol_table_);
local_symbol_table.add_constants();
if (!valid(name,input_var_list.size()))
return false;
if (!forward(name,
input_var_list.size(),
local_symbol_table,
return_present))
return false;
compiled_expression.register_symbol_table(local_symbol_table);
for (std::size_t i = 0; i < auxiliary_symtab_list_.size(); ++i)
{
compiled_expression.register_symbol_table((*auxiliary_symtab_list_[i]));
}
std::string mod_expression;
for (std::size_t i = 0; i < input_var_list.size(); ++i)
{
mod_expression += " var " + input_var_list[i] + "{};\n";
}
if (
('{' == details::front(expression)) &&
('}' == details::back (expression))
)
mod_expression += "~" + expression + ";";
else
mod_expression += "~{" + expression + "};";
if (!parser_.compile(mod_expression,compiled_expression))
{
exprtk_debug(("Compositor Error: %s\n",parser_.error().c_str()));
exprtk_debug(("Compositor modified expression: \n%s\n",mod_expression.c_str()));
remove(name,input_var_list.size());
return false;
}
if (!return_present && parser_.dec().return_present())
{
remove(name,input_var_list.size());
return compile_expression(name, expression, input_var_list, true);
}
// Make sure every return point has a scalar as its first parameter
if (parser_.dec().return_present())
{
typedef std::vector<std::string> str_list_t;
str_list_t ret_param_list = parser_.dec().return_param_type_list();
for (std::size_t i = 0; i < ret_param_list.size(); ++i)
{
const std::string& params = ret_param_list[i];
if (params.empty() || ('T' != params[0]))
{
exprtk_debug(("Compositor Error: Return statement in function '%s' is invalid\n",
name.c_str()));
remove(name,input_var_list.size());
return false;
}
}
}
expr_map_[name] = compiled_expression;
exprtk::ifunction<T>& ifunc = (*(fp_map_[input_var_list.size()])[name]);
if (symbol_table_.add_function(name,ifunc))
return true;
else
{
exprtk_debug(("Compositor Error: Failed to add function '%s' to symbol table\n",
name.c_str()));
return false;
}
}
inline bool symbol_used(const std::string& symbol) const
{
return (
symbol_table_.is_variable (symbol) ||
symbol_table_.is_stringvar (symbol) ||
symbol_table_.is_function (symbol) ||
symbol_table_.is_vector (symbol) ||
symbol_table_.is_vararg_function(symbol)
);
}
inline bool valid(const std::string& name,
const std::size_t& arg_count) const
{
if (arg_count > 6)
return false;
else if (symbol_used(name))
return false;
else if (fp_map_[arg_count].end() != fp_map_[arg_count].find(name))
return false;
else
return true;
}
inline bool forward(const std::string& name,
const std::size_t& arg_count,
symbol_table_t& sym_table,
const bool ret_present = false)
{
switch (arg_count)
{
#define case_stmt(N) \
case N : (fp_map_[arg_count])[name] = \
(!ret_present) ? static_cast<base_func*> \
(new func_##N##param) : \
static_cast<base_func*> \
(new func_##N##param_retval) ; \
break; \
case_stmt(0) case_stmt(1) case_stmt(2)
case_stmt(3) case_stmt(4) case_stmt(5)
case_stmt(6)
#undef case_stmt
}
exprtk::ifunction<T>& ifunc = (*(fp_map_[arg_count])[name]);
return sym_table.add_function(name,ifunc);
}
inline void remove(const std::string& name, const std::size_t& arg_count)
{
if (arg_count > 6)
return;
const typename std::map<std::string,expression_t>::iterator em_itr = expr_map_.find(name);
if (expr_map_.end() != em_itr)
{
expr_map_.erase(em_itr);
}
const typename funcparam_t::iterator fp_itr = fp_map_[arg_count].find(name);
if (fp_map_[arg_count].end() != fp_itr)
{
delete fp_itr->second;
fp_map_[arg_count].erase(fp_itr);
}
symbol_table_.remove_function(name);
}
private:
symbol_table_t symbol_table_;
parser_t parser_;
std::map<std::string,expression_t> expr_map_;
std::vector<funcparam_t> fp_map_;
std::vector<symbol_table_t*> auxiliary_symtab_list_;
}; // class function_compositor
} // namespace exprtk
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# ifndef NOMINMAX
# define NOMINMAX
# endif
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <ctime>
#else
# include <ctime>
# include <sys/time.h>
# include <sys/types.h>
#endif
namespace exprtk
{
class timer
{
public:
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
timer()
: in_use_(false)
{
QueryPerformanceFrequency(&clock_frequency_);
}
inline void start()
{
in_use_ = true;
QueryPerformanceCounter(&start_time_);
}
inline void stop()
{
QueryPerformanceCounter(&stop_time_);
in_use_ = false;
}
inline double time() const
{
return (1.0 * (stop_time_.QuadPart - start_time_.QuadPart)) / (1.0 * clock_frequency_.QuadPart);
}
#else
timer()
: in_use_(false)
{
start_time_.tv_sec = 0;
start_time_.tv_usec = 0;
stop_time_.tv_sec = 0;
stop_time_.tv_usec = 0;
}
inline void start()
{
in_use_ = true;
gettimeofday(&start_time_,0);
}
inline void stop()
{
gettimeofday(&stop_time_, 0);
in_use_ = false;
}
inline unsigned long long int usec_time() const
{
if (!in_use_)
{
if (stop_time_.tv_sec >= start_time_.tv_sec)
{
return 1000000LLU * static_cast<details::_uint64_t>(stop_time_.tv_sec - start_time_.tv_sec ) +
static_cast<details::_uint64_t>(stop_time_.tv_usec - start_time_.tv_usec) ;
}
else
return std::numeric_limits<details::_uint64_t>::max();
}
else
return std::numeric_limits<details::_uint64_t>::max();
}
inline double time() const
{
return usec_time() * 0.000001;
}
#endif
inline bool in_use() const
{
return in_use_;
}
private:
bool in_use_;
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
LARGE_INTEGER start_time_;
LARGE_INTEGER stop_time_;
LARGE_INTEGER clock_frequency_;
#else
struct timeval start_time_;
struct timeval stop_time_;
#endif
};
template <typename T>
struct type_defs
{
typedef symbol_table<T> symbol_table_t;
typedef expression<T> expression_t;
typedef parser<T> parser_t;
typedef parser_error::type error_t;
typedef function_compositor<T> compositor_t;
typedef typename compositor_t::function function_t;
};
} // namespace exprtk
#ifndef exprtk_disable_rtl_io
namespace exprtk
{
namespace rtl { namespace io { namespace details
{
template <typename T>
inline void print_type(const std::string& fmt,
const T v,
exprtk::details::numeric::details::real_type_tag)
{
printf(fmt.c_str(),v);
}
template <typename T>
struct print_impl
{
typedef typename igeneric_function<T>::generic_type generic_type;
typedef typename igeneric_function<T>::parameter_list_t parameter_list_t;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
typedef typename generic_type::string_view string_t;
typedef typename exprtk::details::numeric::details::number_type<T>::type num_type;
static void process(const std::string& scalar_format, parameter_list_t parameters)
{
for (std::size_t i = 0; i < parameters.size(); ++i)
{
generic_type& gt = parameters[i];
switch (gt.type)
{
case generic_type::e_scalar : print(scalar_format,scalar_t(gt));
break;
case generic_type::e_vector : print(scalar_format,vector_t(gt));
break;
case generic_type::e_string : print(string_t(gt));
break;
default : continue;
}
}
}
static inline void print(const std::string& scalar_format, const scalar_t& s)
{
print_type(scalar_format,s(),num_type());
}
static inline void print(const std::string& scalar_format, const vector_t& v)
{
for (std::size_t i = 0; i < v.size(); ++i)
{
print_type(scalar_format,v[i],num_type());
if ((i + 1) < v.size())
printf(" ");
}
}
static inline void print(const string_t& s)
{
printf("%s",to_str(s).c_str());
}
};
} // namespace exprtk::rtl::io::details
template <typename T>
struct print : public exprtk::igeneric_function<T>
{
typedef typename igeneric_function<T>::parameter_list_t parameter_list_t;
using exprtk::igeneric_function<T>::operator();
print(const std::string& scalar_format = "%10.5f")
: scalar_format_(scalar_format)
{
exprtk::enable_zero_parameters(*this);
}
inline T operator() (parameter_list_t parameters)
{
details::print_impl<T>::process(scalar_format_,parameters);
return T(0);
}
std::string scalar_format_;
};
template <typename T>
struct println : public exprtk::igeneric_function<T>
{
typedef typename igeneric_function<T>::parameter_list_t parameter_list_t;
using exprtk::igeneric_function<T>::operator();
println(const std::string& scalar_format = "%10.5f")
: scalar_format_(scalar_format)
{
exprtk::enable_zero_parameters(*this);
}
inline T operator() (parameter_list_t parameters)
{
details::print_impl<T>::process(scalar_format_,parameters);
printf("\n");
return T(0);
}
std::string scalar_format_;
};
template <typename T>
struct package
{
print <T> p;
println<T> pl;
bool register_package(exprtk::symbol_table<T>& symtab)
{
#define exprtk_register_function(FunctionName, FunctionType) \
if (!symtab.add_function(FunctionName,FunctionType)) \
{ \
exprtk_debug(( \
"exprtk::rtl::io::register_package - Failed to add function: %s\n", \
FunctionName)); \
return false; \
} \
exprtk_register_function("print" , p )
exprtk_register_function("println", pl)
#undef exprtk_register_function
return true;
}
};
} // namespace exprtk::rtl::io
} // namespace exprtk::rtl
} // namespace exprtk
#endif
#ifndef exprtk_disable_rtl_io_file
#include <fstream>
namespace exprtk
{
namespace rtl { namespace io { namespace file { namespace details
{
using ::exprtk::details::char_ptr;
using ::exprtk::details::char_cptr;
enum file_mode
{
e_error = 0,
e_read = 1,
e_write = 2,
e_rdwrt = 4
};
struct file_descriptor
{
file_descriptor(const std::string& fname, const std::string& access)
: stream_ptr(0)
, mode(get_file_mode(access))
, file_name(fname)
{}
void* stream_ptr;
file_mode mode;
std::string file_name;
bool open()
{
if (e_read == mode)
{
std::ifstream* stream = new std::ifstream(file_name.c_str(),std::ios::binary);
if (!(*stream))
{
file_name.clear();
delete stream;
return false;
}
else
stream_ptr = stream;
return true;
}
else if (e_write == mode)
{
std::ofstream* stream = new std::ofstream(file_name.c_str(),std::ios::binary);
if (!(*stream))
{
file_name.clear();
delete stream;
return false;
}
else
stream_ptr = stream;
return true;
}
else if (e_rdwrt == mode)
{
std::fstream* stream = new std::fstream(file_name.c_str(),std::ios::binary);
if (!(*stream))
{
file_name.clear();
delete stream;
return false;
}
else
stream_ptr = stream;
return true;
}
else
return false;
}
template <typename Stream, typename Ptr>
void close(Ptr& p)
{
Stream* stream = reinterpret_cast<Stream*>(p);
stream->close();
delete stream;
p = reinterpret_cast<Ptr>(0);
}
bool close()
{
switch (mode)
{
case e_read : close<std::ifstream>(stream_ptr);
break;
case e_write : close<std::ofstream>(stream_ptr);
break;
case e_rdwrt : close<std::fstream> (stream_ptr);
break;
default : return false;
}
return true;
}
template <typename View>
bool write(const View& view, const std::size_t amount, const std::size_t offset = 0)
{
switch (mode)
{
case e_write : reinterpret_cast<std::ofstream*>(stream_ptr)->
write(reinterpret_cast<char_cptr>(view.begin() + offset), amount * sizeof(typename View::value_t));
break;
case e_rdwrt : reinterpret_cast<std::fstream*>(stream_ptr)->
write(reinterpret_cast<char_cptr>(view.begin() + offset) , amount * sizeof(typename View::value_t));
break;
default : return false;
}
return true;
}
template <typename View>
bool read(View& view, const std::size_t amount, const std::size_t offset = 0)
{
switch (mode)
{
case e_read : reinterpret_cast<std::ifstream*>(stream_ptr)->
read(reinterpret_cast<char_ptr>(view.begin() + offset), amount * sizeof(typename View::value_t));
break;
case e_rdwrt : reinterpret_cast<std::fstream*>(stream_ptr)->
read(reinterpret_cast<char_ptr>(view.begin() + offset) , amount * sizeof(typename View::value_t));
break;
default : return false;
}
return true;
}
bool getline(std::string& s)
{
switch (mode)
{
case e_read : return (!!std::getline(*reinterpret_cast<std::ifstream*>(stream_ptr),s));
case e_rdwrt : return (!!std::getline(*reinterpret_cast<std::fstream* >(stream_ptr),s));
default : return false;
}
}
bool eof() const
{
switch (mode)
{
case e_read : return reinterpret_cast<std::ifstream*>(stream_ptr)->eof();
case e_write : return reinterpret_cast<std::ofstream*>(stream_ptr)->eof();
case e_rdwrt : return reinterpret_cast<std::fstream* >(stream_ptr)->eof();
default : return true;
}
}
file_mode get_file_mode(const std::string& access) const
{
if (access.empty() || access.size() > 2)
return e_error;
std::size_t w_cnt = 0;
std::size_t r_cnt = 0;
for (std::size_t i = 0; i < access.size(); ++i)
{
switch (std::tolower(access[i]))
{
case 'r' : r_cnt++; break;
case 'w' : w_cnt++; break;
default : return e_error;
}
}
if ((0 == r_cnt) && (0 == w_cnt))
return e_error;
else if ((r_cnt > 1) || (w_cnt > 1))
return e_error;
else if ((1 == r_cnt) && (1 == w_cnt))
return e_rdwrt;
else if (1 == r_cnt)
return e_read;
else
return e_write;
}
};
template <typename T>
file_descriptor* make_handle(T v)
{
const std::size_t fd_size = sizeof(details::file_descriptor*);
details::file_descriptor* fd = reinterpret_cast<file_descriptor*>(0);
std::memcpy(reinterpret_cast<char_ptr >(&fd),
reinterpret_cast<char_cptr>(&v ),
fd_size);
return fd;
}
template <typename T>
void perform_check()
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4127)
#endif
if (sizeof(T) < sizeof(void*))
{
throw std::runtime_error("exprtk::rtl::io::file - Error - pointer size larger than holder.");
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
} // namespace exprtk::rtl::io::file::details
template <typename T>
class open : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::string_view string_t;
using exprtk::igeneric_function<T>::operator();
open()
: exprtk::igeneric_function<T>("S|SS")
{ details::perform_check<T>(); }
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const std::string file_name = to_str(string_t(parameters[0]));
if (file_name.empty())
return T(0);
if ((1 == ps_index) && (0 == string_t(parameters[1]).size()))
{
return T(0);
}
const std::string access =
(0 == ps_index) ? "r" : to_str(string_t(parameters[1]));
details::file_descriptor* fd = new details::file_descriptor(file_name,access);
if (fd->open())
{
T t = T(0);
const std::size_t fd_size = sizeof(details::file_descriptor*);
std::memcpy(reinterpret_cast<char*>(&t ),
reinterpret_cast<char*>(&fd),
fd_size);
return t;
}
else
{
delete fd;
return T(0);
}
}
};
template <typename T>
struct close : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
close()
: exprtk::ifunction<T>(1)
{ details::perform_check<T>(); }
inline T operator() (const T& v)
{
details::file_descriptor* fd = details::make_handle(v);
if (!fd->close())
return T(0);
delete fd;
return T(1);
}
};
template <typename T>
class write : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::string_view string_t;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
write()
: igfun_t("TS|TST|TV|TVT")
{ details::perform_check<T>(); }
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
details::file_descriptor* fd = details::make_handle(scalar_t(parameters[0])());
switch (ps_index)
{
case 0 : {
const string_t buffer(parameters[1]);
const std::size_t amount = buffer.size();
return T(fd->write(buffer, amount) ? 1 : 0);
}
case 1 : {
const string_t buffer(parameters[1]);
const std::size_t amount =
std::min(buffer.size(),
static_cast<std::size_t>(scalar_t(parameters[2])()));
return T(fd->write(buffer, amount) ? 1 : 0);
}
case 2 : {
const vector_t vec(parameters[1]);
const std::size_t amount = vec.size();
return T(fd->write(vec, amount) ? 1 : 0);
}
case 3 : {
const vector_t vec(parameters[1]);
const std::size_t amount =
std::min(vec.size(),
static_cast<std::size_t>(scalar_t(parameters[2])()));
return T(fd->write(vec, amount) ? 1 : 0);
}
}
return T(0);
}
};
template <typename T>
class read : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::string_view string_t;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
read()
: igfun_t("TS|TST|TV|TVT")
{ details::perform_check<T>(); }
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
details::file_descriptor* fd = details::make_handle(scalar_t(parameters[0])());
switch (ps_index)
{
case 0 : {
string_t buffer(parameters[1]);
const std::size_t amount = buffer.size();
return T(fd->read(buffer,amount) ? 1 : 0);
}
case 1 : {
string_t buffer(parameters[1]);
const std::size_t amount =
std::min(buffer.size(),
static_cast<std::size_t>(scalar_t(parameters[2])()));
return T(fd->read(buffer,amount) ? 1 : 0);
}
case 2 : {
vector_t vec(parameters[1]);
const std::size_t amount = vec.size();
return T(fd->read(vec,amount) ? 1 : 0);
}
case 3 : {
vector_t vec(parameters[1]);
const std::size_t amount =
std::min(vec.size(),
static_cast<std::size_t>(scalar_t(parameters[2])()));
return T(fd->read(vec,amount) ? 1 : 0);
}
}
return T(0);
}
};
template <typename T>
class getline : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::string_view string_t;
typedef typename generic_type::scalar_view scalar_t;
using exprtk::igeneric_function<T>::operator();
getline()
: igfun_t("T",igfun_t::e_rtrn_string)
{ details::perform_check<T>(); }
inline T operator() (std::string& result,
parameter_list_t parameters)
{
details::file_descriptor* fd = details::make_handle(scalar_t(parameters[0])());
return T(fd->getline(result) ? 1 : 0);
}
};
template <typename T>
struct eof : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
eof()
: exprtk::ifunction<T>(1)
{ details::perform_check<T>(); }
inline T operator() (const T& v)
{
details::file_descriptor* fd = details::make_handle(v);
return (fd->eof() ? T(1) : T(0));
}
};
template <typename T>
struct package
{
open <T> o;
close <T> c;
write <T> w;
read <T> r;
getline<T> g;
eof <T> e;
bool register_package(exprtk::symbol_table<T>& symtab)
{
#define exprtk_register_function(FunctionName, FunctionType) \
if (!symtab.add_function(FunctionName,FunctionType)) \
{ \
exprtk_debug(( \
"exprtk::rtl::io::file::register_package - Failed to add function: %s\n", \
FunctionName)); \
return false; \
} \
exprtk_register_function("open" , o)
exprtk_register_function("close" , c)
exprtk_register_function("write" , w)
exprtk_register_function("read" , r)
exprtk_register_function("getline" , g)
exprtk_register_function("eof" , e)
#undef exprtk_register_function
return true;
}
};
} // namespace exprtk::rtl::io::file
} // namespace exprtk::rtl::io
} // namespace exprtk::rtl
} // namespace exprtk
#endif
#ifndef exprtk_disable_rtl_vecops
namespace exprtk
{
namespace rtl { namespace vecops {
namespace helper
{
template <typename Vector>
inline bool invalid_range(const Vector& v, const std::size_t r0, const std::size_t r1)
{
if (r0 > (v.size() - 1))
return true;
else if (r1 > (v.size() - 1))
return true;
else if (r1 < r0)
return true;
else
return false;
}
template <typename T>
struct load_vector_range
{
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
static inline bool process(parameter_list_t& parameters,
std::size_t& r0, std::size_t& r1,
const std::size_t& r0_prmidx,
const std::size_t& r1_prmidx,
const std::size_t vec_idx = 0)
{
if (r0_prmidx >= parameters.size())
return false;
if (r1_prmidx >= parameters.size())
return false;
if (!scalar_t(parameters[r0_prmidx]).to_uint(r0))
return false;
if (!scalar_t(parameters[r1_prmidx]).to_uint(r1))
return false;
return !invalid_range(vector_t(parameters[vec_idx]), r0, r1);
}
};
}
namespace details
{
template <typename T>
inline void kahan_sum(T& sum, T& error, const T v)
{
const T x = v - error;
const T y = sum + x;
error = (y - sum) - x;
sum = y;
}
} // namespace exprtk::rtl::details
template <typename T>
class all_true : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
all_true()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0)
)
return std::numeric_limits<T>::quiet_NaN();
for (std::size_t i = r0; i <= r1; ++i)
{
if (vec[i] == T(0))
{
return T(0);
}
}
return T(1);
}
};
template <typename T>
class all_false : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
all_false()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0)
)
return std::numeric_limits<T>::quiet_NaN();
for (std::size_t i = r0; i <= r1; ++i)
{
if (vec[i] != T(0))
{
return T(0);
}
}
return T(1);
}
};
template <typename T>
class any_true : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
any_true()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0)
)
return std::numeric_limits<T>::quiet_NaN();
for (std::size_t i = r0; i <= r1; ++i)
{
if (vec[i] != T(0))
{
return T(1);
}
}
return T(0);
}
};
template <typename T>
class any_false : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
any_false()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0)
)
return std::numeric_limits<T>::quiet_NaN();
for (std::size_t i = r0; i <= r1; ++i)
{
if (vec[i] == T(0))
{
return T(1);
}
}
return T(0);
}
};
template <typename T>
class count : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
count()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0)
)
return std::numeric_limits<T>::quiet_NaN();
std::size_t cnt = 0;
for (std::size_t i = r0; i <= r1; ++i)
{
if (vec[i] != T(0)) ++cnt;
}
return T(cnt);
}
};
template <typename T>
class copy : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
copy()
: exprtk::igeneric_function<T>("VV|VTTVTT")
/*
Overloads:
0. VV - x(vector), y(vector)
1. VTTVTT - x(vector), xr0, xr1, y(vector), yr0, yr1,
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[0]);
vector_t y(parameters[(0 == ps_index) ? 1 : 3]);
std::size_t xr0 = 0;
std::size_t xr1 = x.size() - 1;
std::size_t yr0 = 0;
std::size_t yr1 = y.size() - 1;
if (1 == ps_index)
{
if (
!helper::load_vector_range<T>::process(parameters, xr0, xr1, 1, 2, 0) ||
!helper::load_vector_range<T>::process(parameters, yr0, yr1, 4, 5, 3)
)
return T(0);
}
const std::size_t n = std::min(xr1 - xr0 + 1, yr1 - yr0 + 1);
std::copy(
x.begin() + xr0,
x.begin() + xr0 + n,
y.begin() + yr0);
return T(n);
}
};
template <typename T>
class rol : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
rol()
: exprtk::igeneric_function<T>("VT|VTTT")
/*
Overloads:
0. VT - vector, N
1. VTTT - vector, N, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t n = 0;
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (!scalar_t(parameters[1]).to_uint(n))
return T(0);
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0)
)
return T(0);
const std::size_t dist = r1 - r0 + 1;
const std::size_t shift = n % dist;
std::rotate(
vec.begin() + r0,
vec.begin() + r0 + shift,
vec.begin() + r1 + 1);
return T(1);
}
};
template <typename T>
class ror : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
ror()
: exprtk::igeneric_function<T>("VT|VTTT")
/*
Overloads:
0. VT - vector, N
1. VTTT - vector, N, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t n = 0;
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (!scalar_t(parameters[1]).to_uint(n))
return T(0);
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0)
)
return T(0);
std::size_t dist = r1 - r0 + 1;
std::size_t shift = (dist - (n % dist)) % dist;
std::rotate(
vec.begin() + r0,
vec.begin() + r0 + shift,
vec.begin() + r1 + 1);
return T(1);
}
};
template <typename T>
class shift_left : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
shift_left()
: exprtk::igeneric_function<T>("VT|VTTT")
/*
Overloads:
0. VT - vector, N
1. VTTT - vector, N, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t n = 0;
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (!scalar_t(parameters[1]).to_uint(n))
return T(0);
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0)
)
return T(0);
const std::size_t dist = r1 - r0 + 1;
if (n > dist)
return T(0);
std::rotate(
vec.begin() + r0,
vec.begin() + r0 + n,
vec.begin() + r1 + 1);
for (std::size_t i = r1 - n + 1; i <= r1; ++i)
{
vec[i] = T(0);
}
return T(1);
}
};
template <typename T>
class shift_right : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
shift_right()
: exprtk::igeneric_function<T>("VT|VTTT")
/*
Overloads:
0. VT - vector, N
1. VTTT - vector, N, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t n = 0;
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (!scalar_t(parameters[1]).to_uint(n))
return T(0);
if (
(1 == ps_index) &&
!helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0)
)
return T(0);
const std::size_t dist = r1 - r0 + 1;
if (n > dist)
return T(0);
const std::size_t shift = (dist - (n % dist)) % dist;
std::rotate(
vec.begin() + r0,
vec.begin() + r0 + shift,
vec.begin() + r1 + 1);
for (std::size_t i = r0; i < r0 + n; ++i)
{
vec[i] = T(0);
}
return T(1);
}
};
template <typename T>
class sort : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::string_view string_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
sort()
: exprtk::igeneric_function<T>("V|VTT|VS|VSTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
2. VS - vector, string
3. VSTT - vector, string, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0))
return T(0);
if ((3 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0))
return T(0);
bool ascending = true;
if ((2 == ps_index) || (3 == ps_index))
{
if (exprtk::details::imatch(to_str(string_t(parameters[1])),"ascending"))
ascending = true;
else if (exprtk::details::imatch(to_str(string_t(parameters[1])),"descending"))
ascending = false;
else
return T(0);
}
if (ascending)
std::sort(
vec.begin() + r0,
vec.begin() + r1 + 1,
std::less<T>());
else
std::sort(
vec.begin() + r0,
vec.begin() + r1 + 1,
std::greater<T>());
return T(1);
}
};
template <typename T>
class nthelement : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
nthelement()
: exprtk::igeneric_function<T>("VT|VTTT")
/*
Overloads:
0. VT - vector, nth-element
1. VTTT - vector, nth-element, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
std::size_t n = 0;
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if (!scalar_t(parameters[1]).to_uint(n))
return T(0);
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0))
return std::numeric_limits<T>::quiet_NaN();
std::nth_element(
vec.begin() + r0,
vec.begin() + r0 + n ,
vec.begin() + r1 + 1);
return T(1);
}
};
template <typename T>
class iota : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
iota()
: exprtk::igeneric_function<T>("VT|VTT|VTTT|VTTTT")
/*
Overloads:
0. VT - vector, increment
1. VTT - vector, increment, base
2. VTTTT - vector, increment, r0, r1
3. VTTTT - vector, increment, base, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
vector_t vec(parameters[0]);
T increment = scalar_t(parameters[1])();
T base = ((1 == ps_index) || (3 == ps_index)) ? scalar_t(parameters[2])() : T(0);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if ((2 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0))
return std::numeric_limits<T>::quiet_NaN();
else if ((3 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 3, 4, 0))
return std::numeric_limits<T>::quiet_NaN();
else
{
long long j = 0;
for (std::size_t i = r0; i <= r1; ++i, ++j)
{
vec[i] = base + (increment * j);
}
}
return T(1);
}
};
template <typename T>
class sumk : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
sumk()
: exprtk::igeneric_function<T>("V|VTT")
/*
Overloads:
0. V - vector
1. VTT - vector, r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t vec(parameters[0]);
std::size_t r0 = 0;
std::size_t r1 = vec.size() - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 1, 2, 0))
return std::numeric_limits<T>::quiet_NaN();
T result = T(0);
T error = T(0);
for (std::size_t i = r0; i <= r1; ++i)
{
details::kahan_sum(result, error, vec[i]);
}
return result;
}
};
template <typename T>
class axpy : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
axpy()
: exprtk::igeneric_function<T>("TVV|TVVTT")
/*
y <- ax + y
Overloads:
0. TVV - a, x(vector), y(vector)
1. TVVTT - a, x(vector), y(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[1]);
vector_t y(parameters[2]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 3, 4, 1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
const T a = scalar_t(parameters[0])();
for (std::size_t i = r0; i <= r1; ++i)
{
y[i] = (a * x[i]) + y[i];
}
return T(1);
}
};
template <typename T>
class axpby : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
axpby()
: exprtk::igeneric_function<T>("TVTV|TVTVTT")
/*
y <- ax + by
Overloads:
0. TVTV - a, x(vector), b, y(vector)
1. TVTVTT - a, x(vector), b, y(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[1]);
vector_t y(parameters[3]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 4, 5, 1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
const T a = scalar_t(parameters[0])();
const T b = scalar_t(parameters[2])();
for (std::size_t i = r0; i <= r1; ++i)
{
y[i] = (a * x[i]) + (b * y[i]);
}
return T(1);
}
};
template <typename T>
class axpyz : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
axpyz()
: exprtk::igeneric_function<T>("TVVV|TVVVTT")
/*
z <- ax + y
Overloads:
0. TVVV - a, x(vector), y(vector), z(vector)
1. TVVVTT - a, x(vector), y(vector), z(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[1]);
const vector_t y(parameters[2]);
vector_t z(parameters[3]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 3, 4, 1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(z, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
const T a = scalar_t(parameters[0])();
for (std::size_t i = r0; i <= r1; ++i)
{
z[i] = (a * x[i]) + y[i];
}
return T(1);
}
};
template <typename T>
class axpbyz : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
axpbyz()
: exprtk::igeneric_function<T>("TVTVV|TVTVVTT")
/*
z <- ax + by
Overloads:
0. TVTVV - a, x(vector), b, y(vector), z(vector)
1. TVTVVTT - a, x(vector), b, y(vector), z(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[1]);
const vector_t y(parameters[3]);
vector_t z(parameters[4]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 4, 5, 1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(z, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
const T a = scalar_t(parameters[0])();
const T b = scalar_t(parameters[2])();
for (std::size_t i = r0; i <= r1; ++i)
{
z[i] = (a * x[i]) + (b * y[i]);
}
return T(1);
}
};
template <typename T>
class axpbz : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
axpbz()
: exprtk::igeneric_function<T>("TVTV|TVTVTT")
/*
z <- ax + b
Overloads:
0. TVTV - a, x(vector), b, z(vector)
1. TVTVTT - a, x(vector), b, z(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[1]);
vector_t z(parameters[3]);
std::size_t r0 = 0;
std::size_t r1 = x.size() - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 4, 5, 1))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(z, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
const T a = scalar_t(parameters[0])();
const T b = scalar_t(parameters[2])();
for (std::size_t i = r0; i <= r1; ++i)
{
z[i] = (a * x[i]) + b;
}
return T(1);
}
};
template <typename T>
class dot : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
dot()
: exprtk::igeneric_function<T>("VV|VVTT")
/*
Overloads:
0. VV - x(vector), y(vector)
1. VVTT - x(vector), y(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[0]);
const vector_t y(parameters[1]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
T result = T(0);
for (std::size_t i = r0; i <= r1; ++i)
{
result += (x[i] * y[i]);
}
return result;
}
};
template <typename T>
class dotk : public exprtk::igeneric_function<T>
{
public:
typedef typename exprtk::igeneric_function<T> igfun_t;
typedef typename igfun_t::parameter_list_t parameter_list_t;
typedef typename igfun_t::generic_type generic_type;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
using exprtk::igeneric_function<T>::operator();
dotk()
: exprtk::igeneric_function<T>("VV|VVTT")
/*
Overloads:
0. VV - x(vector), y(vector)
1. VVTT - x(vector), y(vector), r0, r1
*/
{}
inline T operator() (const std::size_t& ps_index, parameter_list_t parameters)
{
const vector_t x(parameters[0]);
const vector_t y(parameters[1]);
std::size_t r0 = 0;
std::size_t r1 = std::min(x.size(),y.size()) - 1;
if ((1 == ps_index) && !helper::load_vector_range<T>::process(parameters, r0, r1, 2, 3, 0))
return std::numeric_limits<T>::quiet_NaN();
else if (helper::invalid_range(y, r0, r1))
return std::numeric_limits<T>::quiet_NaN();
T result = T(0);
T error = T(0);
for (std::size_t i = r0; i <= r1; ++i)
{
details::kahan_sum(result, error, (x[i] * y[i]));
}
return result;
}
};
template <typename T>
struct package
{
all_true <T> at;
all_false <T> af;
any_true <T> nt;
any_false <T> nf;
count <T> c;
copy <T> cp;
rol <T> rl;
ror <T> rr;
shift_left <T> sl;
shift_right<T> sr;
sort <T> st;
nthelement <T> ne;
iota <T> ia;
sumk <T> sk;
axpy <T> b1_axpy;
axpby <T> b1_axpby;
axpyz <T> b1_axpyz;
axpbyz <T> b1_axpbyz;
axpbz <T> b1_axpbz;
dot <T> dt;
dotk <T> dtk;
bool register_package(exprtk::symbol_table<T>& symtab)
{
#define exprtk_register_function(FunctionName, FunctionType) \
if (!symtab.add_function(FunctionName,FunctionType)) \
{ \
exprtk_debug(( \
"exprtk::rtl::vecops::register_package - Failed to add function: %s\n", \
FunctionName)); \
return false; \
} \
exprtk_register_function("all_true" , at )
exprtk_register_function("all_false" , af )
exprtk_register_function("any_true" , nt )
exprtk_register_function("any_false" , nf )
exprtk_register_function("count" , c )
exprtk_register_function("copy" , cp )
exprtk_register_function("rotate_left" , rl )
exprtk_register_function("rol" , rl )
exprtk_register_function("rotate_right" , rr )
exprtk_register_function("ror" , rr )
exprtk_register_function("shftl" , sl )
exprtk_register_function("shftr" , sr )
exprtk_register_function("sort" , st )
exprtk_register_function("nth_element" , ne )
exprtk_register_function("iota" , ia )
exprtk_register_function("sumk" , sk )
exprtk_register_function("axpy" , b1_axpy )
exprtk_register_function("axpby" , b1_axpby )
exprtk_register_function("axpyz" , b1_axpyz )
exprtk_register_function("axpbyz" , b1_axpbyz)
exprtk_register_function("axpbz" , b1_axpbz )
exprtk_register_function("dot" , dt )
exprtk_register_function("dotk" , dtk )
#undef exprtk_register_function
return true;
}
};
} // namespace exprtk::rtl::vecops
} // namespace exprtk::rtl
} // namespace exprtk
#endif
namespace exprtk
{
namespace information
{
using ::exprtk::details::char_cptr;
static char_cptr library = "Mathematical Expression Toolkit";
static char_cptr version = "2.71828182845904523536028747135266"
"2497757247093699959574966967627724"
"0766303535475945713821785251664274"
"2746639193200305992181741359662904";
static char_cptr date = "20230101";
static char_cptr min_cpp = "199711L";
static inline std::string data()
{
static const std::string info_str = std::string(library) +
std::string(" v") + std::string(version) +
std::string(" (") + date + std::string(")") +
std::string(" (") + min_cpp + std::string(")");
return info_str;
}
} // namespace information
#ifdef exprtk_debug
#undef exprtk_debug
#endif
#ifdef exprtk_error_location
#undef exprtk_error_location
#endif
#ifdef exprtk_disable_fallthrough_begin
#undef exprtk_disable_fallthrough_begin
#endif
#ifdef exprtk_disable_fallthrough_end
#undef exprtk_disable_fallthrough_end
#endif
#ifdef exprtk_override
#undef exprtk_override
#endif
#ifdef exprtk_final
#undef exprtk_final
#endif
#ifdef exprtk_delete
#undef exprtk_delete
#endif
} // namespace exprtk
#endif
``` | /content/code_sandbox/libs/exprtk/include/exprtk/exprtk.hpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 317,879 |
```cmake
# This file generated automatically:
# path_to_url
# All rights reserved.
if(DEFINED LEATHERS_SOURCE_LEATHERS_SUGAR_CMAKE_)
return()
else()
set(LEATHERS_SOURCE_LEATHERS_SUGAR_CMAKE_ 1)
endif()
include(sugar_files)
sugar_files(
LEATHERS_SOURCES
###
push
pop
###
all
###
c++98-compat
c++98-compat-pedantic
assign-base-inaccessible
assign-could-not-be-generated
copy-ctor-could-not-be-generated
dflt-ctor-base-inaccessible
dflt-ctor-could-not-be-generated
user-ctor-required
automatic-inline
force-not-inlined
not-inlined
unreferenced-inline
behavior-change
bool-conversion
c++11-extensions
cast-align
catch-semantic-changed
conditional-uninitialized
constant-conditional
constant-conversion
conversion
conversion-loss
conversion-sign-extended
covered-switch-default
deprecated
deprecated-declarations
deprecated-objc-isa-usage
deprecated-register
digraphs-not-supported
disabled-macro-expansion
documentation
documentation-unknown-command
empty-body
enum-conversion
exit-time-destructors
extra-semi
format
four-char-constants
global-constructors
ill-formed-comma-expr
implicit-fallthrough
inherits-via-dominance
int-conversion
invalid-offsetof
is-defined-to-be
layout-changed
missing-braces
missing-field-initializers
missing-noreturn
missing-prototypes
name-length-exceeded
newline-eof
no-such-warning
non-virtual-dtor
object-layout-change
old-style-cast
overloaded-virtual
padded
parentheses
pedantic
pointer-sign
return-type
shadow
shift-sign-overflow
shorten-64-to-32
sign-compare
sign-conversion
signed-unsigned-compare
static-ctor-not-thread-safe
switch
switch-enum
this-used-in-init
undef
uninitialized
unknown-pragmas
unreachable-code
unreachable-code-return
unsafe-conversion
unused-but-set-variable
unused-function
unused-label
unused-parameter
unused-value
unused-variable
used-but-marked-unused
weak-vtables
arc-bridge-casts-disallowed-in-nonarc
arc-repeated-use-of-weak
deprecated-implementations
duplicate-method-match
explicit-ownership-type
implicit-atomic-properties
implicit-retain-self
objc-missing-property-synthesis
objc-root-class
protocol
receiver-is-weak
selector
strict-selector-match
undeclared-selector
)
``` | /content/code_sandbox/libs/leathers/leathers/sugar.cmake | cmake | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 646 |
```objective-c
//
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef NANOVG_GL_H
#define NANOVG_GL_H
#ifdef __cplusplus
extern "C" {
#endif
// Create flags
enum NVGcreateFlags {
// Flag indicating if geometry based anti-aliasing is used (may not be needed when using MSAA).
NVG_ANTIALIAS = 1<<0,
// Flag indicating if strokes should be drawn using stencil buffer. The rendering will be a little
// slower, but path overlaps (i.e. self-intersecting or sharp turns) will be drawn just once.
NVG_STENCIL_STROKES = 1<<1,
// Flag indicating that additional debug checks are done.
NVG_DEBUG = 1<<2,
};
#if defined NANOVG_GL2_IMPLEMENTATION
# define NANOVG_GL2 1
# define NANOVG_GL_IMPLEMENTATION 1
#elif defined NANOVG_GL3_IMPLEMENTATION
# define NANOVG_GL3 1
# define NANOVG_GL_IMPLEMENTATION 1
# define NANOVG_GL_USE_UNIFORMBUFFER 1
#elif defined NANOVG_GLES2_IMPLEMENTATION
# define NANOVG_GLES2 1
# define NANOVG_GL_IMPLEMENTATION 1
#elif defined NANOVG_GLES3_IMPLEMENTATION
# define NANOVG_GLES3 1
# define NANOVG_GL_IMPLEMENTATION 1
#endif
#define NANOVG_GL_USE_STATE_FILTER (1)
// Creates NanoVG contexts for different OpenGL (ES) versions.
// Flags should be combination of the create flags above.
#if defined NANOVG_GL2
NVGcontext* nvgCreateGL2(int flags);
void nvgDeleteGL2(NVGcontext* ctx);
int nvglCreateImageFromHandleGL2(NVGcontext* ctx, GLuint textureId, int w, int h, int flags);
GLuint nvglImageHandleGL2(NVGcontext* ctx, int image);
#endif
#if defined NANOVG_GL3
NVGcontext* nvgCreateGL3(int flags);
void nvgDeleteGL3(NVGcontext* ctx);
int nvglCreateImageFromHandleGL3(NVGcontext* ctx, GLuint textureId, int w, int h, int flags);
GLuint nvglImageHandleGL3(NVGcontext* ctx, int image);
#endif
#if defined NANOVG_GLES2
NVGcontext* nvgCreateGLES2(int flags);
void nvgDeleteGLES2(NVGcontext* ctx);
int nvglCreateImageFromHandleGLES2(NVGcontext* ctx, GLuint textureId, int w, int h, int flags);
GLuint nvglImageHandleGLES2(NVGcontext* ctx, int image);
#endif
#if defined NANOVG_GLES3
NVGcontext* nvgCreateGLES3(int flags);
void nvgDeleteGLES3(NVGcontext* ctx);
int nvglCreateImageFromHandleGLES3(NVGcontext* ctx, GLuint textureId, int w, int h, int flags);
GLuint nvglImageHandleGLES3(NVGcontext* ctx, int image);
#endif
// These are additional flags on top of NVGimageFlags.
enum NVGimageFlagsGL {
NVG_IMAGE_NODELETE = 1<<16, // Do not delete GL texture handle.
};
#ifdef __cplusplus
}
#endif
#endif /* NANOVG_GL_H */
#ifdef NANOVG_GL_IMPLEMENTATION
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "nanovg.h"
enum GLNVGuniformLoc {
GLNVG_LOC_VIEWSIZE,
GLNVG_LOC_TEX,
GLNVG_LOC_FRAG,
GLNVG_MAX_LOCS
};
enum GLNVGshaderType {
NSVG_SHADER_FILLGRAD,
NSVG_SHADER_FILLIMG,
NSVG_SHADER_SIMPLE,
NSVG_SHADER_IMG
};
#if NANOVG_GL_USE_UNIFORMBUFFER
enum GLNVGuniformBindings {
GLNVG_FRAG_BINDING = 0,
};
#endif
struct GLNVGshader {
GLuint prog;
GLuint frag;
GLuint vert;
GLint loc[GLNVG_MAX_LOCS];
};
typedef struct GLNVGshader GLNVGshader;
struct GLNVGtexture {
int id;
GLuint tex;
int width, height;
int type;
int flags;
};
typedef struct GLNVGtexture GLNVGtexture;
struct GLNVGblend
{
GLenum srcRGB;
GLenum dstRGB;
GLenum srcAlpha;
GLenum dstAlpha;
};
typedef struct GLNVGblend GLNVGblend;
enum GLNVGcallType {
GLNVG_NONE = 0,
GLNVG_FILL,
GLNVG_CONVEXFILL,
GLNVG_STROKE,
GLNVG_TRIANGLES,
};
struct GLNVGcall {
int type;
int image;
int pathOffset;
int pathCount;
int triangleOffset;
int triangleCount;
int uniformOffset;
GLNVGblend blendFunc;
};
typedef struct GLNVGcall GLNVGcall;
struct GLNVGpath {
int fillOffset;
int fillCount;
int strokeOffset;
int strokeCount;
};
typedef struct GLNVGpath GLNVGpath;
struct GLNVGfragUniforms {
#if NANOVG_GL_USE_UNIFORMBUFFER
float scissorMat[12]; // matrices are actually 3 vec4s
float paintMat[12];
struct NVGcolor innerCol;
struct NVGcolor outerCol;
float scissorExt[2];
float scissorScale[2];
float extent[2];
float radius;
float feather;
float strokeMult;
float strokeThr;
int texType;
int type;
#else
// note: after modifying layout or size of uniform array,
// don't forget to also update the fragment shader source!
#define NANOVG_GL_UNIFORMARRAY_SIZE 11
union {
struct {
float scissorMat[12]; // matrices are actually 3 vec4s
float paintMat[12];
struct NVGcolor innerCol;
struct NVGcolor outerCol;
float scissorExt[2];
float scissorScale[2];
float extent[2];
float radius;
float feather;
float strokeMult;
float strokeThr;
float texType;
float type;
};
float uniformArray[NANOVG_GL_UNIFORMARRAY_SIZE][4];
};
#endif
};
typedef struct GLNVGfragUniforms GLNVGfragUniforms;
struct GLNVGcontext {
GLNVGshader shader;
GLNVGtexture* textures;
float view[2];
int ntextures;
int ctextures;
int textureId;
GLuint vertBuf;
#if defined NANOVG_GL3
GLuint vertArr;
#endif
#if NANOVG_GL_USE_UNIFORMBUFFER
GLuint fragBuf;
#endif
int fragSize;
int flags;
// Per frame buffers
GLNVGcall* calls;
int ccalls;
int ncalls;
GLNVGpath* paths;
int cpaths;
int npaths;
struct NVGvertex* verts;
int cverts;
int nverts;
unsigned char* uniforms;
int cuniforms;
int nuniforms;
// cached state
#if NANOVG_GL_USE_STATE_FILTER
GLuint boundTexture;
GLuint stencilMask;
GLenum stencilFunc;
GLint stencilFuncRef;
GLuint stencilFuncMask;
GLNVGblend blendFunc;
#endif
int dummyTex;
};
typedef struct GLNVGcontext GLNVGcontext;
static int glnvg__maxi(int a, int b) { return a > b ? a : b; }
#ifdef NANOVG_GLES2
static unsigned int glnvg__nearestPow2(unsigned int num)
{
unsigned n = num > 0 ? num - 1 : 0;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
#endif
static void glnvg__bindTexture(GLNVGcontext* gl, GLuint tex)
{
#if NANOVG_GL_USE_STATE_FILTER
if (gl->boundTexture != tex) {
gl->boundTexture = tex;
glBindTexture(GL_TEXTURE_2D, tex);
}
#else
glBindTexture(GL_TEXTURE_2D, tex);
#endif
}
static void glnvg__stencilMask(GLNVGcontext* gl, GLuint mask)
{
#if NANOVG_GL_USE_STATE_FILTER
if (gl->stencilMask != mask) {
gl->stencilMask = mask;
glStencilMask(mask);
}
#else
glStencilMask(mask);
#endif
}
static void glnvg__stencilFunc(GLNVGcontext* gl, GLenum func, GLint ref, GLuint mask)
{
#if NANOVG_GL_USE_STATE_FILTER
if ((gl->stencilFunc != func) ||
(gl->stencilFuncRef != ref) ||
(gl->stencilFuncMask != mask)) {
gl->stencilFunc = func;
gl->stencilFuncRef = ref;
gl->stencilFuncMask = mask;
glStencilFunc(func, ref, mask);
}
#else
glStencilFunc(func, ref, mask);
#endif
}
static void glnvg__blendFuncSeparate(GLNVGcontext* gl, const GLNVGblend* blend)
{
#if NANOVG_GL_USE_STATE_FILTER
if ((gl->blendFunc.srcRGB != blend->srcRGB) ||
(gl->blendFunc.dstRGB != blend->dstRGB) ||
(gl->blendFunc.srcAlpha != blend->srcAlpha) ||
(gl->blendFunc.dstAlpha != blend->dstAlpha)) {
gl->blendFunc = *blend;
glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha,blend->dstAlpha);
}
#else
glBlendFuncSeparate(blend->srcRGB, blend->dstRGB, blend->srcAlpha,blend->dstAlpha);
#endif
}
static GLNVGtexture* glnvg__allocTexture(GLNVGcontext* gl)
{
GLNVGtexture* tex = NULL;
int i;
for (i = 0; i < gl->ntextures; i++) {
if (gl->textures[i].id == 0) {
tex = &gl->textures[i];
break;
}
}
if (tex == NULL) {
if (gl->ntextures+1 > gl->ctextures) {
GLNVGtexture* textures;
int ctextures = glnvg__maxi(gl->ntextures+1, 4) + gl->ctextures/2; // 1.5x Overallocate
textures = (GLNVGtexture*)realloc(gl->textures, sizeof(GLNVGtexture)*ctextures);
if (textures == NULL) return NULL;
gl->textures = textures;
gl->ctextures = ctextures;
}
tex = &gl->textures[gl->ntextures++];
}
memset(tex, 0, sizeof(*tex));
tex->id = ++gl->textureId;
return tex;
}
static GLNVGtexture* glnvg__findTexture(GLNVGcontext* gl, int id)
{
int i;
for (i = 0; i < gl->ntextures; i++)
if (gl->textures[i].id == id)
return &gl->textures[i];
return NULL;
}
static int glnvg__deleteTexture(GLNVGcontext* gl, int id)
{
int i;
for (i = 0; i < gl->ntextures; i++) {
if (gl->textures[i].id == id) {
if (gl->textures[i].tex != 0 && (gl->textures[i].flags & NVG_IMAGE_NODELETE) == 0)
glDeleteTextures(1, &gl->textures[i].tex);
memset(&gl->textures[i], 0, sizeof(gl->textures[i]));
return 1;
}
}
return 0;
}
static void glnvg__dumpShaderError(GLuint shader, const char* name, const char* type)
{
char str[512+1];
GLsizei len = 0;
glGetShaderInfoLog(shader, 512, &len, str);
if (len > 512) len = 512;
str[len] = '\0';
printf("Shader %s/%s error:\n%s\n", name, type, str);
}
static void glnvg__dumpProgramError(GLuint prog, const char* name)
{
char str[512+1];
GLsizei len = 0;
glGetProgramInfoLog(prog, 512, &len, str);
if (len > 512) len = 512;
str[len] = '\0';
printf("Program %s error:\n%s\n", name, str);
}
static void glnvg__checkError(GLNVGcontext* gl, const char* str)
{
GLenum err;
if ((gl->flags & NVG_DEBUG) == 0) return;
err = glGetError();
if (err != GL_NO_ERROR) {
printf("Error %08x after %s\n", err, str);
return;
}
}
static int glnvg__createShader(GLNVGshader* shader, const char* name, const char* header, const char* opts, const char* vshader, const char* fshader)
{
GLint status;
GLuint prog, vert, frag;
const char* str[3];
str[0] = header;
str[1] = opts != NULL ? opts : "";
memset(shader, 0, sizeof(*shader));
prog = glCreateProgram();
vert = glCreateShader(GL_VERTEX_SHADER);
frag = glCreateShader(GL_FRAGMENT_SHADER);
str[2] = vshader;
glShaderSource(vert, 3, str, 0);
str[2] = fshader;
glShaderSource(frag, 3, str, 0);
glCompileShader(vert);
glGetShaderiv(vert, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
glnvg__dumpShaderError(vert, name, "vert");
return 0;
}
glCompileShader(frag);
glGetShaderiv(frag, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
glnvg__dumpShaderError(frag, name, "frag");
return 0;
}
glAttachShader(prog, vert);
glAttachShader(prog, frag);
glBindAttribLocation(prog, 0, "vertex");
glBindAttribLocation(prog, 1, "tcoord");
glLinkProgram(prog);
glGetProgramiv(prog, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
glnvg__dumpProgramError(prog, name);
return 0;
}
shader->prog = prog;
shader->vert = vert;
shader->frag = frag;
return 1;
}
static void glnvg__deleteShader(GLNVGshader* shader)
{
if (shader->prog != 0)
glDeleteProgram(shader->prog);
if (shader->vert != 0)
glDeleteShader(shader->vert);
if (shader->frag != 0)
glDeleteShader(shader->frag);
}
static void glnvg__getUniforms(GLNVGshader* shader)
{
shader->loc[GLNVG_LOC_VIEWSIZE] = glGetUniformLocation(shader->prog, "viewSize");
shader->loc[GLNVG_LOC_TEX] = glGetUniformLocation(shader->prog, "tex");
#if NANOVG_GL_USE_UNIFORMBUFFER
shader->loc[GLNVG_LOC_FRAG] = glGetUniformBlockIndex(shader->prog, "frag");
#else
shader->loc[GLNVG_LOC_FRAG] = glGetUniformLocation(shader->prog, "frag");
#endif
}
static int glnvg__renderCreateTexture(void* uptr, int type, int w, int h, int imageFlags, const unsigned char* data);
static int glnvg__renderCreate(void* uptr)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
int align = 4;
// TODO: mediump float may not be enough for GLES2 in iOS.
// see the following discussion: path_to_url
static const char* shaderHeader =
#if defined NANOVG_GL2
"#define NANOVG_GL2 1\n"
#elif defined NANOVG_GL3
"#version 150 core\n"
"#define NANOVG_GL3 1\n"
#elif defined NANOVG_GLES2
"#version 100\n"
"#define NANOVG_GL2 1\n"
#elif defined NANOVG_GLES3
"#version 300 es\n"
"#define NANOVG_GL3 1\n"
#endif
#if NANOVG_GL_USE_UNIFORMBUFFER
"#define USE_UNIFORMBUFFER 1\n"
#else
"#define UNIFORMARRAY_SIZE 11\n"
#endif
"\n";
static const char* fillVertShader =
"#ifdef NANOVG_GL3\n"
" uniform vec2 viewSize;\n"
" in vec2 vertex;\n"
" in vec2 tcoord;\n"
" out vec2 ftcoord;\n"
" out vec2 fpos;\n"
"#else\n"
" uniform vec2 viewSize;\n"
" attribute vec2 vertex;\n"
" attribute vec2 tcoord;\n"
" varying vec2 ftcoord;\n"
" varying vec2 fpos;\n"
"#endif\n"
"void main(void) {\n"
" ftcoord = tcoord;\n"
" fpos = vertex;\n"
" gl_Position = vec4(2.0*vertex.x/viewSize.x - 1.0, 1.0 - 2.0*vertex.y/viewSize.y, 0, 1);\n"
"}\n";
static const char* fillFragShader =
"#ifdef GL_ES\n"
"#if defined(GL_FRAGMENT_PRECISION_HIGH) || defined(NANOVG_GL3)\n"
" precision highp float;\n"
"#else\n"
" precision mediump float;\n"
"#endif\n"
"#endif\n"
"#ifdef NANOVG_GL3\n"
"#ifdef USE_UNIFORMBUFFER\n"
" layout(std140) uniform frag {\n"
" mat3 scissorMat;\n"
" mat3 paintMat;\n"
" vec4 innerCol;\n"
" vec4 outerCol;\n"
" vec2 scissorExt;\n"
" vec2 scissorScale;\n"
" vec2 extent;\n"
" float radius;\n"
" float feather;\n"
" float strokeMult;\n"
" float strokeThr;\n"
" int texType;\n"
" int type;\n"
" };\n"
"#else\n" // NANOVG_GL3 && !USE_UNIFORMBUFFER
" uniform vec4 frag[UNIFORMARRAY_SIZE];\n"
"#endif\n"
" uniform sampler2D tex;\n"
" in vec2 ftcoord;\n"
" in vec2 fpos;\n"
" out vec4 outColor;\n"
"#else\n" // !NANOVG_GL3
" uniform vec4 frag[UNIFORMARRAY_SIZE];\n"
" uniform sampler2D tex;\n"
" varying vec2 ftcoord;\n"
" varying vec2 fpos;\n"
"#endif\n"
"#ifndef USE_UNIFORMBUFFER\n"
" #define scissorMat mat3(frag[0].xyz, frag[1].xyz, frag[2].xyz)\n"
" #define paintMat mat3(frag[3].xyz, frag[4].xyz, frag[5].xyz)\n"
" #define innerCol frag[6]\n"
" #define outerCol frag[7]\n"
" #define scissorExt frag[8].xy\n"
" #define scissorScale frag[8].zw\n"
" #define extent frag[9].xy\n"
" #define radius frag[9].z\n"
" #define feather frag[9].w\n"
" #define strokeMult frag[10].x\n"
" #define strokeThr frag[10].y\n"
" #define texType int(frag[10].z)\n"
" #define type int(frag[10].w)\n"
"#endif\n"
"\n"
"float sdroundrect(vec2 pt, vec2 ext, float rad) {\n"
" vec2 ext2 = ext - vec2(rad,rad);\n"
" vec2 d = abs(pt) - ext2;\n"
" return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rad;\n"
"}\n"
"\n"
"// Scissoring\n"
"float scissorMask(vec2 p) {\n"
" vec2 sc = (abs((scissorMat * vec3(p,1.0)).xy) - scissorExt);\n"
" sc = vec2(0.5,0.5) - sc * scissorScale;\n"
" return clamp(sc.x,0.0,1.0) * clamp(sc.y,0.0,1.0);\n"
"}\n"
"#ifdef EDGE_AA\n"
"// Stroke - from [0..1] to clipped pyramid, where the slope is 1px.\n"
"float strokeMask() {\n"
" return min(1.0, (1.0-abs(ftcoord.x*2.0-1.0))*strokeMult) * min(1.0, ftcoord.y);\n"
"}\n"
"#endif\n"
"\n"
"void main(void) {\n"
" vec4 result;\n"
" float scissor = scissorMask(fpos);\n"
"#ifdef EDGE_AA\n"
" float strokeAlpha = strokeMask();\n"
" if (strokeAlpha < strokeThr) discard;\n"
"#else\n"
" float strokeAlpha = 1.0;\n"
"#endif\n"
" if (type == 0) { // Gradient\n"
" // Calculate gradient color using box gradient\n"
" vec2 pt = (paintMat * vec3(fpos,1.0)).xy;\n"
" float d = clamp((sdroundrect(pt, extent, radius) + feather*0.5) / feather, 0.0, 1.0);\n"
" vec4 color = mix(innerCol,outerCol,d);\n"
" // Combine alpha\n"
" color *= strokeAlpha * scissor;\n"
" result = color;\n"
" } else if (type == 1) { // Image\n"
" // Calculate color fron texture\n"
" vec2 pt = (paintMat * vec3(fpos,1.0)).xy / extent;\n"
"#ifdef NANOVG_GL3\n"
" vec4 color = texture(tex, pt);\n"
"#else\n"
" vec4 color = texture2D(tex, pt);\n"
"#endif\n"
" if (texType == 1) color = vec4(color.xyz*color.w,color.w);"
" if (texType == 2) color = vec4(color.x);"
" // Apply color tint and alpha.\n"
" color *= innerCol;\n"
" // Combine alpha\n"
" color *= strokeAlpha * scissor;\n"
" result = color;\n"
" } else if (type == 2) { // Stencil fill\n"
" result = vec4(1,1,1,1);\n"
" } else if (type == 3) { // Textured tris\n"
"#ifdef NANOVG_GL3\n"
" vec4 color = texture(tex, ftcoord);\n"
"#else\n"
" vec4 color = texture2D(tex, ftcoord);\n"
"#endif\n"
" if (texType == 1) color = vec4(color.xyz*color.w,color.w);"
" if (texType == 2) color = vec4(color.x);"
" color *= scissor;\n"
" result = color * innerCol;\n"
" }\n"
"#ifdef NANOVG_GL3\n"
" outColor = result;\n"
"#else\n"
" gl_FragColor = result;\n"
"#endif\n"
"}\n";
glnvg__checkError(gl, "init");
if (gl->flags & NVG_ANTIALIAS) {
if (glnvg__createShader(&gl->shader, "shader", shaderHeader, "#define EDGE_AA 1\n", fillVertShader, fillFragShader) == 0)
return 0;
} else {
if (glnvg__createShader(&gl->shader, "shader", shaderHeader, NULL, fillVertShader, fillFragShader) == 0)
return 0;
}
glnvg__checkError(gl, "uniform locations");
glnvg__getUniforms(&gl->shader);
// Create dynamic vertex array
#if defined NANOVG_GL3
glGenVertexArrays(1, &gl->vertArr);
#endif
glGenBuffers(1, &gl->vertBuf);
#if NANOVG_GL_USE_UNIFORMBUFFER
// Create UBOs
glUniformBlockBinding(gl->shader.prog, gl->shader.loc[GLNVG_LOC_FRAG], GLNVG_FRAG_BINDING);
glGenBuffers(1, &gl->fragBuf);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &align);
#endif
gl->fragSize = sizeof(GLNVGfragUniforms) + align - sizeof(GLNVGfragUniforms) % align;
// Some platforms does not allow to have samples to unset textures.
// Create empty one which is bound when there's no texture specified.
gl->dummyTex = glnvg__renderCreateTexture(gl, NVG_TEXTURE_ALPHA, 1, 1, 0, NULL);
glnvg__checkError(gl, "create done");
glFinish();
return 1;
}
static int glnvg__renderCreateTexture(void* uptr, int type, int w, int h, int imageFlags, const unsigned char* data)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGtexture* tex = glnvg__allocTexture(gl);
if (tex == NULL) return 0;
#ifdef NANOVG_GLES2
// Check for non-power of 2.
if (glnvg__nearestPow2(w) != (unsigned int)w || glnvg__nearestPow2(h) != (unsigned int)h) {
// No repeat
if ((imageFlags & NVG_IMAGE_REPEATX) != 0 || (imageFlags & NVG_IMAGE_REPEATY) != 0) {
printf("Repeat X/Y is not supported for non power-of-two textures (%d x %d)\n", w, h);
imageFlags &= ~(NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY);
}
// No mips.
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
printf("Mip-maps is not support for non power-of-two textures (%d x %d)\n", w, h);
imageFlags &= ~NVG_IMAGE_GENERATE_MIPMAPS;
}
}
#endif
glGenTextures(1, &tex->tex);
tex->width = w;
tex->height = h;
tex->type = type;
tex->flags = imageFlags;
glnvg__bindTexture(gl, tex->tex);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
#ifndef NANOVG_GLES2
glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
#if defined (NANOVG_GL2)
// GL 1.4 and later has support for generating mipmaps using a tex parameter.
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
}
#endif
#if !defined (GL_LUMINANCE)
#define GL_LUMINANCE GL_RED
#endif
if (type == NVG_TEXTURE_RGBA)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
else
#if defined(NANOVG_GLES2) || defined (NANOVG_GL2)
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
#elif defined(NANOVG_GLES3)
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data);
#endif
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
if (imageFlags & NVG_IMAGE_NEAREST) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
} else {
if (imageFlags & NVG_IMAGE_NEAREST) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
}
if (imageFlags & NVG_IMAGE_NEAREST) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
if (imageFlags & NVG_IMAGE_REPEATX)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
else
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
if (imageFlags & NVG_IMAGE_REPEATY)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
else
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
#ifndef NANOVG_GLES2
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
// The new way to build mipmaps on GLES and GL3
#if !defined(NANOVG_GL2)
if (imageFlags & NVG_IMAGE_GENERATE_MIPMAPS) {
glGenerateMipmap(GL_TEXTURE_2D);
}
#endif
glnvg__checkError(gl, "create tex");
glnvg__bindTexture(gl, 0);
return tex->id;
}
static int glnvg__renderDeleteTexture(void* uptr, int image)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
return glnvg__deleteTexture(gl, image);
}
static int glnvg__renderUpdateTexture(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGtexture* tex = glnvg__findTexture(gl, image);
if (tex == NULL) return 0;
glnvg__bindTexture(gl, tex->tex);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
#ifndef NANOVG_GLES2
glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->width);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
#else
// No support for all of skip, need to update a whole row at a time.
if (tex->type == NVG_TEXTURE_RGBA)
data += y*tex->width*4;
else
data += y*tex->width;
x = 0;
w = tex->width;
#endif
if (tex->type == NVG_TEXTURE_RGBA)
glTexSubImage2D(GL_TEXTURE_2D, 0, x,y, w,h, GL_RGBA, GL_UNSIGNED_BYTE, data);
else
#if defined(NANOVG_GLES2) || defined(NANOVG_GL2)
glTexSubImage2D(GL_TEXTURE_2D, 0, x,y, w,h, GL_LUMINANCE, GL_UNSIGNED_BYTE, data);
#else
glTexSubImage2D(GL_TEXTURE_2D, 0, x,y, w,h, GL_RED, GL_UNSIGNED_BYTE, data);
#endif
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
#ifndef NANOVG_GLES2
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
glnvg__bindTexture(gl, 0);
return 1;
}
static int glnvg__renderGetTextureSize(void* uptr, int image, int* w, int* h)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGtexture* tex = glnvg__findTexture(gl, image);
if (tex == NULL) return 0;
*w = tex->width;
*h = tex->height;
return 1;
}
static void glnvg__xformToMat3x4(float* m3, float* t)
{
m3[0] = t[0];
m3[1] = t[1];
m3[2] = 0.0f;
m3[3] = 0.0f;
m3[4] = t[2];
m3[5] = t[3];
m3[6] = 0.0f;
m3[7] = 0.0f;
m3[8] = t[4];
m3[9] = t[5];
m3[10] = 1.0f;
m3[11] = 0.0f;
}
static NVGcolor glnvg__premulColor(NVGcolor c)
{
c.r *= c.a;
c.g *= c.a;
c.b *= c.a;
return c;
}
static int glnvg__convertPaint(GLNVGcontext* gl, GLNVGfragUniforms* frag, NVGpaint* paint,
NVGscissor* scissor, float width, float fringe, float strokeThr)
{
GLNVGtexture* tex = NULL;
float invxform[6];
memset(frag, 0, sizeof(*frag));
frag->innerCol = glnvg__premulColor(paint->innerColor);
frag->outerCol = glnvg__premulColor(paint->outerColor);
if (scissor->extent[0] < -0.5f || scissor->extent[1] < -0.5f) {
memset(frag->scissorMat, 0, sizeof(frag->scissorMat));
frag->scissorExt[0] = 1.0f;
frag->scissorExt[1] = 1.0f;
frag->scissorScale[0] = 1.0f;
frag->scissorScale[1] = 1.0f;
} else {
nvgTransformInverse(invxform, scissor->xform);
glnvg__xformToMat3x4(frag->scissorMat, invxform);
frag->scissorExt[0] = scissor->extent[0];
frag->scissorExt[1] = scissor->extent[1];
frag->scissorScale[0] = sqrtf(scissor->xform[0]*scissor->xform[0] + scissor->xform[2]*scissor->xform[2]) / fringe;
frag->scissorScale[1] = sqrtf(scissor->xform[1]*scissor->xform[1] + scissor->xform[3]*scissor->xform[3]) / fringe;
}
memcpy(frag->extent, paint->extent, sizeof(frag->extent));
frag->strokeMult = (width*0.5f + fringe*0.5f) / fringe;
frag->strokeThr = strokeThr;
if (paint->image != 0) {
tex = glnvg__findTexture(gl, paint->image);
if (tex == NULL) return 0;
if ((tex->flags & NVG_IMAGE_FLIPY) != 0) {
float m1[6], m2[6];
nvgTransformTranslate(m1, 0.0f, frag->extent[1] * 0.5f);
nvgTransformMultiply(m1, paint->xform);
nvgTransformScale(m2, 1.0f, -1.0f);
nvgTransformMultiply(m2, m1);
nvgTransformTranslate(m1, 0.0f, -frag->extent[1] * 0.5f);
nvgTransformMultiply(m1, m2);
nvgTransformInverse(invxform, m1);
} else {
nvgTransformInverse(invxform, paint->xform);
}
frag->type = NSVG_SHADER_FILLIMG;
#if NANOVG_GL_USE_UNIFORMBUFFER
if (tex->type == NVG_TEXTURE_RGBA)
frag->texType = (tex->flags & NVG_IMAGE_PREMULTIPLIED) ? 0 : 1;
else
frag->texType = 2;
#else
if (tex->type == NVG_TEXTURE_RGBA)
frag->texType = (tex->flags & NVG_IMAGE_PREMULTIPLIED) ? 0.0f : 1.0f;
else
frag->texType = 2.0f;
#endif
// printf("frag->texType = %d\n", frag->texType);
} else {
frag->type = NSVG_SHADER_FILLGRAD;
frag->radius = paint->radius;
frag->feather = paint->feather;
nvgTransformInverse(invxform, paint->xform);
}
glnvg__xformToMat3x4(frag->paintMat, invxform);
return 1;
}
static GLNVGfragUniforms* nvg__fragUniformPtr(GLNVGcontext* gl, int i);
static void glnvg__setUniforms(GLNVGcontext* gl, int uniformOffset, int image)
{
GLNVGtexture* tex = NULL;
#if NANOVG_GL_USE_UNIFORMBUFFER
glBindBufferRange(GL_UNIFORM_BUFFER, GLNVG_FRAG_BINDING, gl->fragBuf, uniformOffset, sizeof(GLNVGfragUniforms));
#else
GLNVGfragUniforms* frag = nvg__fragUniformPtr(gl, uniformOffset);
glUniform4fv(gl->shader.loc[GLNVG_LOC_FRAG], NANOVG_GL_UNIFORMARRAY_SIZE, &(frag->uniformArray[0][0]));
#endif
if (image != 0) {
tex = glnvg__findTexture(gl, image);
}
// If no image is set, use empty texture
if (tex == NULL) {
tex = glnvg__findTexture(gl, gl->dummyTex);
}
glnvg__bindTexture(gl, tex != NULL ? tex->tex : 0);
glnvg__checkError(gl, "tex paint tex");
}
static void glnvg__renderViewport(void* uptr, float width, float height, float devicePixelRatio)
{
NVG_NOTUSED(devicePixelRatio);
GLNVGcontext* gl = (GLNVGcontext*)uptr;
gl->view[0] = width;
gl->view[1] = height;
}
static void glnvg__fill(GLNVGcontext* gl, GLNVGcall* call)
{
GLNVGpath* paths = &gl->paths[call->pathOffset];
int i, npaths = call->pathCount;
// Draw shapes
glEnable(GL_STENCIL_TEST);
glnvg__stencilMask(gl, 0xff);
glnvg__stencilFunc(gl, GL_ALWAYS, 0, 0xff);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
// set bindpoint for solid loc
glnvg__setUniforms(gl, call->uniformOffset, 0);
glnvg__checkError(gl, "fill simple");
glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP);
glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP);
glDisable(GL_CULL_FACE);
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_FAN, paths[i].fillOffset, paths[i].fillCount);
glEnable(GL_CULL_FACE);
// Draw anti-aliased pixels
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glnvg__setUniforms(gl, call->uniformOffset + gl->fragSize, call->image);
glnvg__checkError(gl, "fill fill");
if (gl->flags & NVG_ANTIALIAS) {
glnvg__stencilFunc(gl, GL_EQUAL, 0x00, 0xff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// Draw fringes
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
}
// Draw fill
glnvg__stencilFunc(gl, GL_NOTEQUAL, 0x0, 0xff);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
glDrawArrays(GL_TRIANGLE_STRIP, call->triangleOffset, call->triangleCount);
glDisable(GL_STENCIL_TEST);
}
static void glnvg__convexFill(GLNVGcontext* gl, GLNVGcall* call)
{
GLNVGpath* paths = &gl->paths[call->pathOffset];
int i, npaths = call->pathCount;
glnvg__setUniforms(gl, call->uniformOffset, call->image);
glnvg__checkError(gl, "convex fill");
for (i = 0; i < npaths; i++) {
glDrawArrays(GL_TRIANGLE_FAN, paths[i].fillOffset, paths[i].fillCount);
// Draw fringes
if (paths[i].strokeCount > 0) {
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
}
}
}
static void glnvg__stroke(GLNVGcontext* gl, GLNVGcall* call)
{
GLNVGpath* paths = &gl->paths[call->pathOffset];
int npaths = call->pathCount, i;
if (gl->flags & NVG_STENCIL_STROKES) {
glEnable(GL_STENCIL_TEST);
glnvg__stencilMask(gl, 0xff);
// Fill the stroke base without overlap
glnvg__stencilFunc(gl, GL_EQUAL, 0x0, 0xff);
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
glnvg__setUniforms(gl, call->uniformOffset + gl->fragSize, call->image);
glnvg__checkError(gl, "stroke fill 0");
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
// Draw anti-aliased pixels.
glnvg__setUniforms(gl, call->uniformOffset, call->image);
glnvg__stencilFunc(gl, GL_EQUAL, 0x00, 0xff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
// Clear stencil buffer.
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glnvg__stencilFunc(gl, GL_ALWAYS, 0x0, 0xff);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
glnvg__checkError(gl, "stroke fill 1");
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDisable(GL_STENCIL_TEST);
// glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, strokeWidth, fringe, 1.0f - 0.5f/255.0f);
} else {
glnvg__setUniforms(gl, call->uniformOffset, call->image);
glnvg__checkError(gl, "stroke fill");
// Draw Strokes
for (i = 0; i < npaths; i++)
glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount);
}
}
static void glnvg__triangles(GLNVGcontext* gl, GLNVGcall* call)
{
glnvg__setUniforms(gl, call->uniformOffset, call->image);
glnvg__checkError(gl, "triangles fill");
glDrawArrays(GL_TRIANGLES, call->triangleOffset, call->triangleCount);
}
static void glnvg__renderCancel(void* uptr) {
GLNVGcontext* gl = (GLNVGcontext*)uptr;
gl->nverts = 0;
gl->npaths = 0;
gl->ncalls = 0;
gl->nuniforms = 0;
}
static GLenum glnvg_convertBlendFuncFactor(int factor)
{
if (factor == NVG_ZERO)
return GL_ZERO;
if (factor == NVG_ONE)
return GL_ONE;
if (factor == NVG_SRC_COLOR)
return GL_SRC_COLOR;
if (factor == NVG_ONE_MINUS_SRC_COLOR)
return GL_ONE_MINUS_SRC_COLOR;
if (factor == NVG_DST_COLOR)
return GL_DST_COLOR;
if (factor == NVG_ONE_MINUS_DST_COLOR)
return GL_ONE_MINUS_DST_COLOR;
if (factor == NVG_SRC_ALPHA)
return GL_SRC_ALPHA;
if (factor == NVG_ONE_MINUS_SRC_ALPHA)
return GL_ONE_MINUS_SRC_ALPHA;
if (factor == NVG_DST_ALPHA)
return GL_DST_ALPHA;
if (factor == NVG_ONE_MINUS_DST_ALPHA)
return GL_ONE_MINUS_DST_ALPHA;
if (factor == NVG_SRC_ALPHA_SATURATE)
return GL_SRC_ALPHA_SATURATE;
return GL_INVALID_ENUM;
}
static GLNVGblend glnvg__blendCompositeOperation(NVGcompositeOperationState op)
{
GLNVGblend blend;
blend.srcRGB = glnvg_convertBlendFuncFactor(op.srcRGB);
blend.dstRGB = glnvg_convertBlendFuncFactor(op.dstRGB);
blend.srcAlpha = glnvg_convertBlendFuncFactor(op.srcAlpha);
blend.dstAlpha = glnvg_convertBlendFuncFactor(op.dstAlpha);
if (blend.srcRGB == GL_INVALID_ENUM || blend.dstRGB == GL_INVALID_ENUM || blend.srcAlpha == GL_INVALID_ENUM || blend.dstAlpha == GL_INVALID_ENUM)
{
blend.srcRGB = GL_ONE;
blend.dstRGB = GL_ONE_MINUS_SRC_ALPHA;
blend.srcAlpha = GL_ONE;
blend.dstAlpha = GL_ONE_MINUS_SRC_ALPHA;
}
return blend;
}
static void glnvg__renderFlush(void* uptr)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
int i;
if (gl->ncalls > 0) {
// Setup require GL state.
glUseProgram(gl->shader.prog);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilMask(0xffffffff);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glStencilFunc(GL_ALWAYS, 0, 0xffffffff);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
#if NANOVG_GL_USE_STATE_FILTER
gl->boundTexture = 0;
gl->stencilMask = 0xffffffff;
gl->stencilFunc = GL_ALWAYS;
gl->stencilFuncRef = 0;
gl->stencilFuncMask = 0xffffffff;
gl->blendFunc.srcRGB = GL_INVALID_ENUM;
gl->blendFunc.srcAlpha = GL_INVALID_ENUM;
gl->blendFunc.dstRGB = GL_INVALID_ENUM;
gl->blendFunc.dstAlpha = GL_INVALID_ENUM;
#endif
#if NANOVG_GL_USE_UNIFORMBUFFER
// Upload ubo for frag shaders
glBindBuffer(GL_UNIFORM_BUFFER, gl->fragBuf);
glBufferData(GL_UNIFORM_BUFFER, gl->nuniforms * gl->fragSize, gl->uniforms, GL_STREAM_DRAW);
#endif
// Upload vertex data
#if defined NANOVG_GL3
glBindVertexArray(gl->vertArr);
#endif
glBindBuffer(GL_ARRAY_BUFFER, gl->vertBuf);
glBufferData(GL_ARRAY_BUFFER, gl->nverts * sizeof(NVGvertex), gl->verts, GL_STREAM_DRAW);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(NVGvertex), (const GLvoid*)(size_t)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(NVGvertex), (const GLvoid*)(0 + 2*sizeof(float)));
// Set view and texture just once per frame.
glUniform1i(gl->shader.loc[GLNVG_LOC_TEX], 0);
glUniform2fv(gl->shader.loc[GLNVG_LOC_VIEWSIZE], 1, gl->view);
#if NANOVG_GL_USE_UNIFORMBUFFER
glBindBuffer(GL_UNIFORM_BUFFER, gl->fragBuf);
#endif
for (i = 0; i < gl->ncalls; i++) {
GLNVGcall* call = &gl->calls[i];
glnvg__blendFuncSeparate(gl,&call->blendFunc);
if (call->type == GLNVG_FILL)
glnvg__fill(gl, call);
else if (call->type == GLNVG_CONVEXFILL)
glnvg__convexFill(gl, call);
else if (call->type == GLNVG_STROKE)
glnvg__stroke(gl, call);
else if (call->type == GLNVG_TRIANGLES)
glnvg__triangles(gl, call);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
#if defined NANOVG_GL3
glBindVertexArray(0);
#endif
glDisable(GL_CULL_FACE);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
glnvg__bindTexture(gl, 0);
}
// Reset calls
gl->nverts = 0;
gl->npaths = 0;
gl->ncalls = 0;
gl->nuniforms = 0;
}
static int glnvg__maxVertCount(const NVGpath* paths, int npaths)
{
int i, count = 0;
for (i = 0; i < npaths; i++) {
count += paths[i].nfill;
count += paths[i].nstroke;
}
return count;
}
static GLNVGcall* glnvg__allocCall(GLNVGcontext* gl)
{
GLNVGcall* ret = NULL;
if (gl->ncalls+1 > gl->ccalls) {
GLNVGcall* calls;
int ccalls = glnvg__maxi(gl->ncalls+1, 128) + gl->ccalls/2; // 1.5x Overallocate
calls = (GLNVGcall*)realloc(gl->calls, sizeof(GLNVGcall) * ccalls);
if (calls == NULL) return NULL;
gl->calls = calls;
gl->ccalls = ccalls;
}
ret = &gl->calls[gl->ncalls++];
memset(ret, 0, sizeof(GLNVGcall));
return ret;
}
static int glnvg__allocPaths(GLNVGcontext* gl, int n)
{
int ret = 0;
if (gl->npaths+n > gl->cpaths) {
GLNVGpath* paths;
int cpaths = glnvg__maxi(gl->npaths + n, 128) + gl->cpaths/2; // 1.5x Overallocate
paths = (GLNVGpath*)realloc(gl->paths, sizeof(GLNVGpath) * cpaths);
if (paths == NULL) return -1;
gl->paths = paths;
gl->cpaths = cpaths;
}
ret = gl->npaths;
gl->npaths += n;
return ret;
}
static int glnvg__allocVerts(GLNVGcontext* gl, int n)
{
int ret = 0;
if (gl->nverts+n > gl->cverts) {
NVGvertex* verts;
int cverts = glnvg__maxi(gl->nverts + n, 4096) + gl->cverts/2; // 1.5x Overallocate
verts = (NVGvertex*)realloc(gl->verts, sizeof(NVGvertex) * cverts);
if (verts == NULL) return -1;
gl->verts = verts;
gl->cverts = cverts;
}
ret = gl->nverts;
gl->nverts += n;
return ret;
}
static int glnvg__allocFragUniforms(GLNVGcontext* gl, int n)
{
int ret = 0, structSize = gl->fragSize;
if (gl->nuniforms+n > gl->cuniforms) {
unsigned char* uniforms;
int cuniforms = glnvg__maxi(gl->nuniforms+n, 128) + gl->cuniforms/2; // 1.5x Overallocate
uniforms = (unsigned char*)realloc(gl->uniforms, structSize * cuniforms);
if (uniforms == NULL) return -1;
gl->uniforms = uniforms;
gl->cuniforms = cuniforms;
}
ret = gl->nuniforms * structSize;
gl->nuniforms += n;
return ret;
}
static GLNVGfragUniforms* nvg__fragUniformPtr(GLNVGcontext* gl, int i)
{
return (GLNVGfragUniforms*)&gl->uniforms[i];
}
static void glnvg__vset(NVGvertex* vtx, float x, float y, float u, float v)
{
vtx->x = x;
vtx->y = y;
vtx->u = u;
vtx->v = v;
}
static void glnvg__renderFill(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe,
const float* bounds, const NVGpath* paths, int npaths)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGcall* call = glnvg__allocCall(gl);
NVGvertex* quad;
GLNVGfragUniforms* frag;
int i, maxverts, offset;
if (call == NULL) return;
call->type = GLNVG_FILL;
call->triangleCount = 4;
call->pathOffset = glnvg__allocPaths(gl, npaths);
if (call->pathOffset == -1) goto error;
call->pathCount = npaths;
call->image = paint->image;
call->blendFunc = glnvg__blendCompositeOperation(compositeOperation);
if (npaths == 1 && paths[0].convex)
{
call->type = GLNVG_CONVEXFILL;
call->triangleCount = 0; // Bounding box fill quad not needed for convex fill
}
// Allocate vertices for all the paths.
maxverts = glnvg__maxVertCount(paths, npaths) + call->triangleCount;
offset = glnvg__allocVerts(gl, maxverts);
if (offset == -1) goto error;
for (i = 0; i < npaths; i++) {
GLNVGpath* copy = &gl->paths[call->pathOffset + i];
const NVGpath* path = &paths[i];
memset(copy, 0, sizeof(GLNVGpath));
if (path->nfill > 0) {
copy->fillOffset = offset;
copy->fillCount = path->nfill;
memcpy(&gl->verts[offset], path->fill, sizeof(NVGvertex) * path->nfill);
offset += path->nfill;
}
if (path->nstroke > 0) {
copy->strokeOffset = offset;
copy->strokeCount = path->nstroke;
memcpy(&gl->verts[offset], path->stroke, sizeof(NVGvertex) * path->nstroke);
offset += path->nstroke;
}
}
// Setup uniforms for draw calls
if (call->type == GLNVG_FILL) {
// Quad
call->triangleOffset = offset;
quad = &gl->verts[call->triangleOffset];
glnvg__vset(&quad[0], bounds[2], bounds[3], 0.5f, 1.0f);
glnvg__vset(&quad[1], bounds[2], bounds[1], 0.5f, 1.0f);
glnvg__vset(&quad[2], bounds[0], bounds[3], 0.5f, 1.0f);
glnvg__vset(&quad[3], bounds[0], bounds[1], 0.5f, 1.0f);
call->uniformOffset = glnvg__allocFragUniforms(gl, 2);
if (call->uniformOffset == -1) goto error;
// Simple shader for stencil
frag = nvg__fragUniformPtr(gl, call->uniformOffset);
memset(frag, 0, sizeof(*frag));
frag->strokeThr = -1.0f;
frag->type = NSVG_SHADER_SIMPLE;
// Fill shader
glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, fringe, fringe, -1.0f);
} else {
call->uniformOffset = glnvg__allocFragUniforms(gl, 1);
if (call->uniformOffset == -1) goto error;
// Fill shader
glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, fringe, fringe, -1.0f);
}
return;
error:
// We get here if call alloc was ok, but something else is not.
// Roll back the last call to prevent drawing it.
if (gl->ncalls > 0) gl->ncalls--;
}
static void glnvg__renderStroke(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe,
float strokeWidth, const NVGpath* paths, int npaths)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGcall* call = glnvg__allocCall(gl);
int i, maxverts, offset;
if (call == NULL) return;
call->type = GLNVG_STROKE;
call->pathOffset = glnvg__allocPaths(gl, npaths);
if (call->pathOffset == -1) goto error;
call->pathCount = npaths;
call->image = paint->image;
call->blendFunc = glnvg__blendCompositeOperation(compositeOperation);
// Allocate vertices for all the paths.
maxverts = glnvg__maxVertCount(paths, npaths);
offset = glnvg__allocVerts(gl, maxverts);
if (offset == -1) goto error;
for (i = 0; i < npaths; i++) {
GLNVGpath* copy = &gl->paths[call->pathOffset + i];
const NVGpath* path = &paths[i];
memset(copy, 0, sizeof(GLNVGpath));
if (path->nstroke) {
copy->strokeOffset = offset;
copy->strokeCount = path->nstroke;
memcpy(&gl->verts[offset], path->stroke, sizeof(NVGvertex) * path->nstroke);
offset += path->nstroke;
}
}
if (gl->flags & NVG_STENCIL_STROKES) {
// Fill shader
call->uniformOffset = glnvg__allocFragUniforms(gl, 2);
if (call->uniformOffset == -1) goto error;
glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, strokeWidth, fringe, -1.0f);
glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, strokeWidth, fringe, 1.0f - 0.5f/255.0f);
} else {
// Fill shader
call->uniformOffset = glnvg__allocFragUniforms(gl, 1);
if (call->uniformOffset == -1) goto error;
glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset), paint, scissor, strokeWidth, fringe, -1.0f);
}
return;
error:
// We get here if call alloc was ok, but something else is not.
// Roll back the last call to prevent drawing it.
if (gl->ncalls > 0) gl->ncalls--;
}
static void glnvg__renderTriangles(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor,
const NVGvertex* verts, int nverts, float fringe)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
GLNVGcall* call = glnvg__allocCall(gl);
GLNVGfragUniforms* frag;
if (call == NULL) return;
call->type = GLNVG_TRIANGLES;
call->image = paint->image;
call->blendFunc = glnvg__blendCompositeOperation(compositeOperation);
// Allocate vertices for all the paths.
call->triangleOffset = glnvg__allocVerts(gl, nverts);
if (call->triangleOffset == -1) goto error;
call->triangleCount = nverts;
memcpy(&gl->verts[call->triangleOffset], verts, sizeof(NVGvertex) * nverts);
// Fill shader
call->uniformOffset = glnvg__allocFragUniforms(gl, 1);
if (call->uniformOffset == -1) goto error;
frag = nvg__fragUniformPtr(gl, call->uniformOffset);
glnvg__convertPaint(gl, frag, paint, scissor, 1.0f, fringe, -1.0f);
frag->type = NSVG_SHADER_IMG;
return;
error:
// We get here if call alloc was ok, but something else is not.
// Roll back the last call to prevent drawing it.
if (gl->ncalls > 0) gl->ncalls--;
}
static void glnvg__renderDelete(void* uptr)
{
GLNVGcontext* gl = (GLNVGcontext*)uptr;
int i;
if (gl == NULL) return;
glnvg__deleteShader(&gl->shader);
#if NANOVG_GL3
#if NANOVG_GL_USE_UNIFORMBUFFER
if (gl->fragBuf != 0)
glDeleteBuffers(1, &gl->fragBuf);
#endif
if (gl->vertArr != 0)
glDeleteVertexArrays(1, &gl->vertArr);
#endif
if (gl->vertBuf != 0)
glDeleteBuffers(1, &gl->vertBuf);
for (i = 0; i < gl->ntextures; i++) {
if (gl->textures[i].tex != 0 && (gl->textures[i].flags & NVG_IMAGE_NODELETE) == 0)
glDeleteTextures(1, &gl->textures[i].tex);
}
free(gl->textures);
free(gl->paths);
free(gl->verts);
free(gl->uniforms);
free(gl->calls);
free(gl);
}
#if defined NANOVG_GL2
inline NVGcontext* nvgCreateGL2(int flags)
#elif defined NANOVG_GL3
inline NVGcontext* nvgCreateGL3(int flags)
#elif defined NANOVG_GLES2
inline NVGcontext* nvgCreateGLES2(int flags)
#elif defined NANOVG_GLES3
inline NVGcontext* nvgCreateGLES3(int flags)
#endif
{
NVGparams params;
NVGcontext* ctx = NULL;
GLNVGcontext* gl = (GLNVGcontext*)malloc(sizeof(GLNVGcontext));
if (gl == NULL) goto error;
memset(gl, 0, sizeof(GLNVGcontext));
memset(¶ms, 0, sizeof(params));
params.renderCreate = glnvg__renderCreate;
params.renderCreateTexture = glnvg__renderCreateTexture;
params.renderDeleteTexture = glnvg__renderDeleteTexture;
params.renderUpdateTexture = glnvg__renderUpdateTexture;
params.renderGetTextureSize = glnvg__renderGetTextureSize;
params.renderViewport = glnvg__renderViewport;
params.renderCancel = glnvg__renderCancel;
params.renderFlush = glnvg__renderFlush;
params.renderFill = glnvg__renderFill;
params.renderStroke = glnvg__renderStroke;
params.renderTriangles = glnvg__renderTriangles;
params.renderDelete = glnvg__renderDelete;
params.userPtr = gl;
params.edgeAntiAlias = flags & NVG_ANTIALIAS ? 1 : 0;
gl->flags = flags;
ctx = nvgCreateInternal(¶ms);
if (ctx == NULL) goto error;
return ctx;
error:
// 'gl' is freed by nvgDeleteInternal.
if (ctx != NULL) nvgDeleteInternal(ctx);
return NULL;
}
#if defined NANOVG_GL2
inline void nvgDeleteGL2(NVGcontext* ctx)
#elif defined NANOVG_GL3
inline void nvgDeleteGL3(NVGcontext* ctx)
#elif defined NANOVG_GLES2
inline void nvgDeleteGLES2(NVGcontext* ctx)
#elif defined NANOVG_GLES3
inline void nvgDeleteGLES3(NVGcontext* ctx)
#endif
{
nvgDeleteInternal(ctx);
}
#if defined NANOVG_GL2
inline int nvglCreateImageFromHandleGL2(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags)
#elif defined NANOVG_GL3
inline int nvglCreateImageFromHandleGL3(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags)
#elif defined NANOVG_GLES2
inline int nvglCreateImageFromHandleGLES2(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags)
#elif defined NANOVG_GLES3
inline int nvglCreateImageFromHandleGLES3(NVGcontext* ctx, GLuint textureId, int w, int h, int imageFlags)
#endif
{
GLNVGcontext* gl = (GLNVGcontext*)nvgInternalParams(ctx)->userPtr;
GLNVGtexture* tex = glnvg__allocTexture(gl);
if (tex == NULL) return 0;
tex->type = NVG_TEXTURE_RGBA;
tex->tex = textureId;
tex->flags = imageFlags;
tex->width = w;
tex->height = h;
return tex->id;
}
#if defined NANOVG_GL2
inline GLuint nvglImageHandleGL2(NVGcontext* ctx, int image)
#elif defined NANOVG_GL3
inline GLuint nvglImageHandleGL3(NVGcontext* ctx, int image)
#elif defined NANOVG_GLES2
inline GLuint nvglImageHandleGLES2(NVGcontext* ctx, int image)
#elif defined NANOVG_GLES3
inline GLuint nvglImageHandleGLES3(NVGcontext* ctx, int image)
#endif
{
GLNVGcontext* gl = (GLNVGcontext*)nvgInternalParams(ctx)->userPtr;
GLNVGtexture* tex = glnvg__findTexture(gl, image);
return tex->tex;
}
#endif /* NANOVG_GL_IMPLEMENTATION */
``` | /content/code_sandbox/libs/nanovg/nanovg/nanovg_gl.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 15,554 |
```objective-c
//
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef FONS_H
#define FONS_H
#define FONS_INVALID -1
enum FONSflags {
FONS_ZERO_TOPLEFT = 1,
FONS_ZERO_BOTTOMLEFT = 2,
};
enum FONSalign {
// Horizontal align
FONS_ALIGN_LEFT = 1<<0, // Default
FONS_ALIGN_CENTER = 1<<1,
FONS_ALIGN_RIGHT = 1<<2,
// Vertical align
FONS_ALIGN_TOP = 1<<3,
FONS_ALIGN_MIDDLE = 1<<4,
FONS_ALIGN_BOTTOM = 1<<5,
FONS_ALIGN_BASELINE = 1<<6, // Default
};
enum FONSglyphBitmap {
FONS_GLYPH_BITMAP_OPTIONAL = 1,
FONS_GLYPH_BITMAP_REQUIRED = 2,
};
enum FONSerrorCode {
// Font atlas is full.
FONS_ATLAS_FULL = 1,
// Scratch memory used to render glyphs is full, requested size reported in 'val', you may need to bump up FONS_SCRATCH_BUF_SIZE.
FONS_SCRATCH_FULL = 2,
// Calls to fonsPushState has created too large stack, if you need deep state stack bump up FONS_MAX_STATES.
FONS_STATES_OVERFLOW = 3,
// Trying to pop too many states fonsPopState().
FONS_STATES_UNDERFLOW = 4,
};
struct FONSparams {
int width, height;
unsigned char flags;
void* userPtr;
int (*renderCreate)(void* uptr, int width, int height);
int (*renderResize)(void* uptr, int width, int height);
void (*renderUpdate)(void* uptr, int* rect, const unsigned char* data);
void (*renderDraw)(void* uptr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts);
void (*renderDelete)(void* uptr);
};
typedef struct FONSparams FONSparams;
struct FONSquad
{
float x0,y0,s0,t0;
float x1,y1,s1,t1;
};
typedef struct FONSquad FONSquad;
struct FONStextIter {
float x, y, nextx, nexty, scale, spacing;
unsigned int codepoint;
short isize, iblur;
struct FONSfont* font;
int prevGlyphIndex;
const char* str;
const char* next;
const char* end;
unsigned int utf8state;
int bitmapOption;
};
typedef struct FONStextIter FONStextIter;
typedef struct FONScontext FONScontext;
// Constructor and destructor.
FONScontext* fonsCreateInternal(FONSparams* params);
void fonsDeleteInternal(FONScontext* s);
void fonsSetErrorCallback(FONScontext* s, void (*callback)(void* uptr, int error, int val), void* uptr);
// Returns current atlas size.
void fonsGetAtlasSize(FONScontext* s, int* width, int* height);
// Expands the atlas size.
int fonsExpandAtlas(FONScontext* s, int width, int height);
// Resets the whole stash.
int fonsResetAtlas(FONScontext* stash, int width, int height);
// Add fonts
int fonsAddFont(FONScontext* s, const char* name, const char* path, int fontIndex);
int fonsAddFontMem(FONScontext* s, const char* name, unsigned char* data, int ndata, int freeData, int fontIndex);
int fonsGetFontByName(FONScontext* s, const char* name);
// State handling
void fonsPushState(FONScontext* s);
void fonsPopState(FONScontext* s);
void fonsClearState(FONScontext* s);
// State setting
void fonsSetSize(FONScontext* s, float size);
void fonsSetColor(FONScontext* s, unsigned int color);
void fonsSetSpacing(FONScontext* s, float spacing);
void fonsSetBlur(FONScontext* s, float blur);
void fonsSetAlign(FONScontext* s, int align);
void fonsSetFont(FONScontext* s, int font);
// Draw text
float fonsDrawText(FONScontext* s, float x, float y, const char* string, const char* end);
// Measure text
float fonsTextBounds(FONScontext* s, float x, float y, const char* string, const char* end, float* bounds);
void fonsLineBounds(FONScontext* s, float y, float* miny, float* maxy);
void fonsVertMetrics(FONScontext* s, float* ascender, float* descender, float* lineh);
// Text iterator
int fonsTextIterInit(FONScontext* stash, FONStextIter* iter, float x, float y, const char* str, const char* end, int bitmapOption);
int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, struct FONSquad* quad);
// Pull texture changes
const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height);
int fonsValidateTexture(FONScontext* s, int* dirty);
// Draws the stash texture for debugging
void fonsDrawDebug(FONScontext* s, float x, float y);
#endif // FONTSTASH_H
#ifdef FONTSTASH_IMPLEMENTATION
#define FONS_NOTUSED(v) (void)sizeof(v)
#ifdef FONS_USE_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_ADVANCES_H
#include <math.h>
struct FONSttFontImpl {
FT_Face font;
};
typedef struct FONSttFontImpl FONSttFontImpl;
#else
#define STB_TRUETYPE_IMPLEMENTATION
static void* fons__tmpalloc(size_t size, void* up);
static void fons__tmpfree(void* ptr, void* up);
#define STBTT_malloc(x,u) fons__tmpalloc(x,u)
#define STBTT_free(x,u) fons__tmpfree(x,u)
#include "stb_truetype.h"
struct FONSttFontImpl {
stbtt_fontinfo font;
};
typedef struct FONSttFontImpl FONSttFontImpl;
#endif
#ifndef FONS_SCRATCH_BUF_SIZE
# define FONS_SCRATCH_BUF_SIZE 96000
#endif
#ifndef FONS_HASH_LUT_SIZE
# define FONS_HASH_LUT_SIZE 256
#endif
#ifndef FONS_INIT_FONTS
# define FONS_INIT_FONTS 4
#endif
#ifndef FONS_INIT_GLYPHS
# define FONS_INIT_GLYPHS 256
#endif
#ifndef FONS_INIT_ATLAS_NODES
# define FONS_INIT_ATLAS_NODES 256
#endif
#ifndef FONS_VERTEX_COUNT
# define FONS_VERTEX_COUNT 1024
#endif
#ifndef FONS_MAX_STATES
# define FONS_MAX_STATES 20
#endif
#ifndef FONS_MAX_FALLBACKS
# define FONS_MAX_FALLBACKS 20
#endif
static unsigned int fons__hashint(unsigned int a)
{
a += ~(a<<15);
a ^= (a>>10);
a += (a<<3);
a ^= (a>>6);
a += ~(a<<11);
a ^= (a>>16);
return a;
}
static int fons__mini(int a, int b)
{
return a < b ? a : b;
}
static int fons__maxi(int a, int b)
{
return a > b ? a : b;
}
struct FONSglyph
{
unsigned int codepoint;
int index;
int next;
short size, blur;
short x0,y0,x1,y1;
short xadv,xoff,yoff;
};
typedef struct FONSglyph FONSglyph;
struct FONSfont
{
FONSttFontImpl font;
char name[64];
unsigned char* data;
int dataSize;
unsigned char freeData;
float ascender;
float descender;
float lineh;
FONSglyph* glyphs;
int cglyphs;
int nglyphs;
int lut[FONS_HASH_LUT_SIZE];
int fallbacks[FONS_MAX_FALLBACKS];
int nfallbacks;
};
typedef struct FONSfont FONSfont;
struct FONSstate
{
int font;
int align;
float size;
unsigned int color;
float blur;
float spacing;
};
typedef struct FONSstate FONSstate;
struct FONSatlasNode {
short x, y, width;
};
typedef struct FONSatlasNode FONSatlasNode;
struct FONSatlas
{
int width, height;
FONSatlasNode* nodes;
int nnodes;
int cnodes;
};
typedef struct FONSatlas FONSatlas;
struct FONScontext
{
FONSparams params;
float itw,ith;
unsigned char* texData;
int dirtyRect[4];
FONSfont** fonts;
FONSatlas* atlas;
int cfonts;
int nfonts;
float verts[FONS_VERTEX_COUNT*2];
float tcoords[FONS_VERTEX_COUNT*2];
unsigned int colors[FONS_VERTEX_COUNT];
int nverts;
unsigned char* scratch;
int nscratch;
FONSstate states[FONS_MAX_STATES];
int nstates;
void (*handleError)(void* uptr, int error, int val);
void* errorUptr;
#ifdef FONS_USE_FREETYPE
FT_Library ftLibrary;
#endif
};
#ifdef FONS_USE_FREETYPE
int fons__tt_init(FONScontext *context)
{
FT_Error ftError;
FONS_NOTUSED(context);
ftError = FT_Init_FreeType(&context->ftLibrary);
return ftError == 0;
}
int fons__tt_done(FONScontext *context)
{
FT_Error ftError;
FONS_NOTUSED(context);
ftError = FT_Done_FreeType(context->ftLibrary);
return ftError == 0;
}
int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize, int fontIndex)
{
FT_Error ftError;
FONS_NOTUSED(context);
ftError = FT_New_Memory_Face(context->ftLibrary, (const FT_Byte*)data, dataSize, fontIndex, &font->font);
return ftError == 0;
}
void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap)
{
*ascent = font->font->ascender;
*descent = font->font->descender;
*lineGap = font->font->height - (*ascent - *descent);
}
float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size)
{
return size / font->font->units_per_EM;
}
int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint)
{
return FT_Get_Char_Index(font->font, codepoint);
}
int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale,
int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1)
{
FT_Error ftError;
FT_GlyphSlot ftGlyph;
FT_Fixed advFixed;
FONS_NOTUSED(scale);
ftError = FT_Set_Pixel_Sizes(font->font, 0, size);
if (ftError) return 0;
ftError = FT_Load_Glyph(font->font, glyph, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT);
if (ftError) return 0;
ftError = FT_Get_Advance(font->font, glyph, FT_LOAD_NO_SCALE, &advFixed);
if (ftError) return 0;
ftGlyph = font->font->glyph;
*advance = (int)advFixed;
*lsb = (int)ftGlyph->metrics.horiBearingX;
*x0 = ftGlyph->bitmap_left;
*x1 = *x0 + ftGlyph->bitmap.width;
*y0 = -ftGlyph->bitmap_top;
*y1 = *y0 + ftGlyph->bitmap.rows;
return 1;
}
void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride,
float scaleX, float scaleY, int glyph)
{
FT_GlyphSlot ftGlyph = font->font->glyph;
int ftGlyphOffset = 0;
unsigned int x, y;
FONS_NOTUSED(outWidth);
FONS_NOTUSED(outHeight);
FONS_NOTUSED(scaleX);
FONS_NOTUSED(scaleY);
FONS_NOTUSED(glyph); // glyph has already been loaded by fons__tt_buildGlyphBitmap
for ( y = 0; y < ftGlyph->bitmap.rows; y++ ) {
for ( x = 0; x < ftGlyph->bitmap.width; x++ ) {
output[(y * outStride) + x] = ftGlyph->bitmap.buffer[ftGlyphOffset++];
}
}
}
int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2)
{
FT_Vector ftKerning;
FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning);
return (int)((ftKerning.x + 32) >> 6); // Round up and convert to integer
}
#else
int fons__tt_init(FONScontext *context)
{
FONS_NOTUSED(context);
return 1;
}
int fons__tt_done(FONScontext *context)
{
FONS_NOTUSED(context);
return 1;
}
int fons__tt_loadFont(FONScontext *context, FONSttFontImpl *font, unsigned char *data, int dataSize, int fontIndex)
{
int offset, stbError;
FONS_NOTUSED(dataSize);
font->font.userdata = context;
offset = stbtt_GetFontOffsetForIndex(data, fontIndex);
if (offset == -1) {
stbError = 0;
} else {
stbError = stbtt_InitFont(&font->font, data, offset);
}
return stbError;
}
void fons__tt_getFontVMetrics(FONSttFontImpl *font, int *ascent, int *descent, int *lineGap)
{
stbtt_GetFontVMetrics(&font->font, ascent, descent, lineGap);
}
float fons__tt_getPixelHeightScale(FONSttFontImpl *font, float size)
{
return stbtt_ScaleForMappingEmToPixels(&font->font, size);
}
int fons__tt_getGlyphIndex(FONSttFontImpl *font, int codepoint)
{
return stbtt_FindGlyphIndex(&font->font, codepoint);
}
int fons__tt_buildGlyphBitmap(FONSttFontImpl *font, int glyph, float size, float scale,
int *advance, int *lsb, int *x0, int *y0, int *x1, int *y1)
{
FONS_NOTUSED(size);
stbtt_GetGlyphHMetrics(&font->font, glyph, advance, lsb);
stbtt_GetGlyphBitmapBox(&font->font, glyph, scale, scale, x0, y0, x1, y1);
return 1;
}
void fons__tt_renderGlyphBitmap(FONSttFontImpl *font, unsigned char *output, int outWidth, int outHeight, int outStride,
float scaleX, float scaleY, int glyph)
{
stbtt_MakeGlyphBitmap(&font->font, output, outWidth, outHeight, outStride, scaleX, scaleY, glyph);
}
int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2)
{
return stbtt_GetGlyphKernAdvance(&font->font, glyph1, glyph2);
}
#endif
#ifdef STB_TRUETYPE_IMPLEMENTATION
static void* fons__tmpalloc(size_t size, void* up)
{
unsigned char* ptr;
FONScontext* stash = (FONScontext*)up;
// 16-byte align the returned pointer
size = (size + 0xf) & ~0xf;
if (stash->nscratch+(int)size > FONS_SCRATCH_BUF_SIZE) {
if (stash->handleError)
stash->handleError(stash->errorUptr, FONS_SCRATCH_FULL, stash->nscratch+(int)size);
return NULL;
}
ptr = stash->scratch + stash->nscratch;
stash->nscratch += (int)size;
return ptr;
}
static void fons__tmpfree(void* ptr, void* up)
{
(void)ptr;
(void)up;
// empty
}
#endif // STB_TRUETYPE_IMPLEMENTATION
// See path_to_url for details.
#define FONS_UTF8_ACCEPT 0
#define FONS_UTF8_REJECT 12
static unsigned int fons__decutf8(unsigned int* state, unsigned int* codep, unsigned int byte)
{
static const unsigned char utf8d[] = {
// The first part of the table maps bytes to character classes that
// to reduce the size of the transition table and create bitmasks.
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
// The second part is a transition table that maps a combination
// of a state of the automaton and a character class to a state.
0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
12,36,12,12,12,12,12,12,12,12,12,12,
};
unsigned int type = utf8d[byte];
*codep = (*state != FONS_UTF8_ACCEPT) ?
(byte & 0x3fu) | (*codep << 6) :
(0xff >> type) & (byte);
*state = utf8d[256 + *state + type];
return *state;
}
// Atlas based on Skyline Bin Packer by Jukka Jylnki
static void fons__deleteAtlas(FONSatlas* atlas)
{
if (atlas == NULL) return;
if (atlas->nodes != NULL) free(atlas->nodes);
free(atlas);
}
static FONSatlas* fons__allocAtlas(int w, int h, int nnodes)
{
FONSatlas* atlas = NULL;
// Allocate memory for the font stash.
atlas = (FONSatlas*)malloc(sizeof(FONSatlas));
if (atlas == NULL) goto error;
memset(atlas, 0, sizeof(FONSatlas));
atlas->width = w;
atlas->height = h;
// Allocate space for skyline nodes
atlas->nodes = (FONSatlasNode*)malloc(sizeof(FONSatlasNode) * nnodes);
if (atlas->nodes == NULL) goto error;
memset(atlas->nodes, 0, sizeof(FONSatlasNode) * nnodes);
atlas->nnodes = 0;
atlas->cnodes = nnodes;
// Init root node.
atlas->nodes[0].x = 0;
atlas->nodes[0].y = 0;
atlas->nodes[0].width = (short)w;
atlas->nnodes++;
return atlas;
error:
if (atlas) fons__deleteAtlas(atlas);
return NULL;
}
static int fons__atlasInsertNode(FONSatlas* atlas, int idx, int x, int y, int w)
{
int i;
// Insert node
if (atlas->nnodes+1 > atlas->cnodes) {
atlas->cnodes = atlas->cnodes == 0 ? 8 : atlas->cnodes * 2;
atlas->nodes = (FONSatlasNode*)realloc(atlas->nodes, sizeof(FONSatlasNode) * atlas->cnodes);
if (atlas->nodes == NULL)
return 0;
}
for (i = atlas->nnodes; i > idx; i--)
atlas->nodes[i] = atlas->nodes[i-1];
atlas->nodes[idx].x = (short)x;
atlas->nodes[idx].y = (short)y;
atlas->nodes[idx].width = (short)w;
atlas->nnodes++;
return 1;
}
static void fons__atlasRemoveNode(FONSatlas* atlas, int idx)
{
int i;
if (atlas->nnodes == 0) return;
for (i = idx; i < atlas->nnodes-1; i++)
atlas->nodes[i] = atlas->nodes[i+1];
atlas->nnodes--;
}
static void fons__atlasExpand(FONSatlas* atlas, int w, int h)
{
// Insert node for empty space
if (w > atlas->width)
fons__atlasInsertNode(atlas, atlas->nnodes, atlas->width, 0, w - atlas->width);
atlas->width = w;
atlas->height = h;
}
static void fons__atlasReset(FONSatlas* atlas, int w, int h)
{
atlas->width = w;
atlas->height = h;
atlas->nnodes = 0;
// Init root node.
atlas->nodes[0].x = 0;
atlas->nodes[0].y = 0;
atlas->nodes[0].width = (short)w;
atlas->nnodes++;
}
static int fons__atlasAddSkylineLevel(FONSatlas* atlas, int idx, int x, int y, int w, int h)
{
int i;
// Insert new node
if (fons__atlasInsertNode(atlas, idx, x, y+h, w) == 0)
return 0;
// Delete skyline segments that fall under the shadow of the new segment.
for (i = idx+1; i < atlas->nnodes; i++) {
if (atlas->nodes[i].x < atlas->nodes[i-1].x + atlas->nodes[i-1].width) {
int shrink = atlas->nodes[i-1].x + atlas->nodes[i-1].width - atlas->nodes[i].x;
atlas->nodes[i].x += (short)shrink;
atlas->nodes[i].width -= (short)shrink;
if (atlas->nodes[i].width <= 0) {
fons__atlasRemoveNode(atlas, i);
i--;
} else {
break;
}
} else {
break;
}
}
// Merge same height skyline segments that are next to each other.
for (i = 0; i < atlas->nnodes-1; i++) {
if (atlas->nodes[i].y == atlas->nodes[i+1].y) {
atlas->nodes[i].width += atlas->nodes[i+1].width;
fons__atlasRemoveNode(atlas, i+1);
i--;
}
}
return 1;
}
static int fons__atlasRectFits(FONSatlas* atlas, int i, int w, int h)
{
// Checks if there is enough space at the location of skyline span 'i',
// and return the max height of all skyline spans under that at that location,
// (think tetris block being dropped at that position). Or -1 if no space found.
int x = atlas->nodes[i].x;
int y = atlas->nodes[i].y;
int spaceLeft;
if (x + w > atlas->width)
return -1;
spaceLeft = w;
while (spaceLeft > 0) {
if (i == atlas->nnodes) return -1;
y = fons__maxi(y, atlas->nodes[i].y);
if (y + h > atlas->height) return -1;
spaceLeft -= atlas->nodes[i].width;
++i;
}
return y;
}
static int fons__atlasAddRect(FONSatlas* atlas, int rw, int rh, int* rx, int* ry)
{
int besth = atlas->height, bestw = atlas->width, besti = -1;
int bestx = -1, besty = -1, i;
// Bottom left fit heuristic.
for (i = 0; i < atlas->nnodes; i++) {
int y = fons__atlasRectFits(atlas, i, rw, rh);
if (y != -1) {
if (y + rh < besth || (y + rh == besth && atlas->nodes[i].width < bestw)) {
besti = i;
bestw = atlas->nodes[i].width;
besth = y + rh;
bestx = atlas->nodes[i].x;
besty = y;
}
}
}
if (besti == -1)
return 0;
// Perform the actual packing.
if (fons__atlasAddSkylineLevel(atlas, besti, bestx, besty, rw, rh) == 0)
return 0;
*rx = bestx;
*ry = besty;
return 1;
}
static void fons__addWhiteRect(FONScontext* stash, int w, int h)
{
int x, y, gx, gy;
unsigned char* dst;
if (fons__atlasAddRect(stash->atlas, w, h, &gx, &gy) == 0)
return;
// Rasterize
dst = &stash->texData[gx + gy * stash->params.width];
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++)
dst[x] = 0xff;
dst += stash->params.width;
}
stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], gx);
stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], gy);
stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], gx+w);
stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], gy+h);
}
FONScontext* fonsCreateInternal(FONSparams* params)
{
FONScontext* stash = NULL;
// Allocate memory for the font stash.
stash = (FONScontext*)malloc(sizeof(FONScontext));
if (stash == NULL) goto error;
memset(stash, 0, sizeof(FONScontext));
stash->params = *params;
// Allocate scratch buffer.
stash->scratch = (unsigned char*)malloc(FONS_SCRATCH_BUF_SIZE);
if (stash->scratch == NULL) goto error;
// Initialize implementation library
if (!fons__tt_init(stash)) goto error;
if (stash->params.renderCreate != NULL) {
if (stash->params.renderCreate(stash->params.userPtr, stash->params.width, stash->params.height) == 0)
goto error;
}
stash->atlas = fons__allocAtlas(stash->params.width, stash->params.height, FONS_INIT_ATLAS_NODES);
if (stash->atlas == NULL) goto error;
// Allocate space for fonts.
stash->fonts = (FONSfont**)malloc(sizeof(FONSfont*) * FONS_INIT_FONTS);
if (stash->fonts == NULL) goto error;
memset(stash->fonts, 0, sizeof(FONSfont*) * FONS_INIT_FONTS);
stash->cfonts = FONS_INIT_FONTS;
stash->nfonts = 0;
// Create texture for the cache.
stash->itw = 1.0f/stash->params.width;
stash->ith = 1.0f/stash->params.height;
stash->texData = (unsigned char*)malloc(stash->params.width * stash->params.height);
if (stash->texData == NULL) goto error;
memset(stash->texData, 0, stash->params.width * stash->params.height);
stash->dirtyRect[0] = stash->params.width;
stash->dirtyRect[1] = stash->params.height;
stash->dirtyRect[2] = 0;
stash->dirtyRect[3] = 0;
// Add white rect at 0,0 for debug drawing.
fons__addWhiteRect(stash, 2,2);
fonsPushState(stash);
fonsClearState(stash);
return stash;
error:
fonsDeleteInternal(stash);
return NULL;
}
static FONSstate* fons__getState(FONScontext* stash)
{
return &stash->states[stash->nstates-1];
}
int fonsAddFallbackFont(FONScontext* stash, int base, int fallback)
{
FONSfont* baseFont = stash->fonts[base];
if (baseFont->nfallbacks < FONS_MAX_FALLBACKS) {
baseFont->fallbacks[baseFont->nfallbacks++] = fallback;
return 1;
}
return 0;
}
void fonsResetFallbackFont(FONScontext* stash, int base)
{
int i;
FONSfont* baseFont = stash->fonts[base];
baseFont->nfallbacks = 0;
baseFont->nglyphs = 0;
for (i = 0; i < FONS_HASH_LUT_SIZE; i++)
baseFont->lut[i] = -1;
}
void fonsSetSize(FONScontext* stash, float size)
{
fons__getState(stash)->size = size;
}
void fonsSetColor(FONScontext* stash, unsigned int color)
{
fons__getState(stash)->color = color;
}
void fonsSetSpacing(FONScontext* stash, float spacing)
{
fons__getState(stash)->spacing = spacing;
}
void fonsSetBlur(FONScontext* stash, float blur)
{
fons__getState(stash)->blur = blur;
}
void fonsSetAlign(FONScontext* stash, int align)
{
fons__getState(stash)->align = align;
}
void fonsSetFont(FONScontext* stash, int font)
{
fons__getState(stash)->font = font;
}
void fonsPushState(FONScontext* stash)
{
if (stash->nstates >= FONS_MAX_STATES) {
if (stash->handleError)
stash->handleError(stash->errorUptr, FONS_STATES_OVERFLOW, 0);
return;
}
if (stash->nstates > 0)
memcpy(&stash->states[stash->nstates], &stash->states[stash->nstates-1], sizeof(FONSstate));
stash->nstates++;
}
void fonsPopState(FONScontext* stash)
{
if (stash->nstates <= 1) {
if (stash->handleError)
stash->handleError(stash->errorUptr, FONS_STATES_UNDERFLOW, 0);
return;
}
stash->nstates--;
}
void fonsClearState(FONScontext* stash)
{
FONSstate* state = fons__getState(stash);
state->size = 12.0f;
state->color = 0xffffffff;
state->font = 0;
state->blur = 0;
state->spacing = 0;
state->align = FONS_ALIGN_LEFT | FONS_ALIGN_BASELINE;
}
static void fons__freeFont(FONSfont* font)
{
if (font == NULL) return;
if (font->glyphs) free(font->glyphs);
if (font->freeData && font->data) free(font->data);
free(font);
}
static int fons__allocFont(FONScontext* stash)
{
FONSfont* font = NULL;
if (stash->nfonts+1 > stash->cfonts) {
stash->cfonts = stash->cfonts == 0 ? 8 : stash->cfonts * 2;
stash->fonts = (FONSfont**)realloc(stash->fonts, sizeof(FONSfont*) * stash->cfonts);
if (stash->fonts == NULL)
return -1;
}
font = (FONSfont*)malloc(sizeof(FONSfont));
if (font == NULL) goto error;
memset(font, 0, sizeof(FONSfont));
font->glyphs = (FONSglyph*)malloc(sizeof(FONSglyph) * FONS_INIT_GLYPHS);
if (font->glyphs == NULL) goto error;
font->cglyphs = FONS_INIT_GLYPHS;
font->nglyphs = 0;
stash->fonts[stash->nfonts++] = font;
return stash->nfonts-1;
error:
fons__freeFont(font);
return FONS_INVALID;
}
int fonsAddFont(FONScontext* stash, const char* name, const char* path, int fontIndex)
{
FILE* fp = 0;
int dataSize = 0;
size_t readed;
unsigned char* data = NULL;
// Read in the font data.
fp = fopen(path, "rb");
if (fp == NULL) goto error;
fseek(fp,0,SEEK_END);
dataSize = (int)ftell(fp);
fseek(fp,0,SEEK_SET);
data = (unsigned char*)malloc(dataSize);
if (data == NULL) goto error;
readed = fread(data, 1, dataSize, fp);
fclose(fp);
fp = 0;
if (readed != (size_t)dataSize) goto error;
return fonsAddFontMem(stash, name, data, dataSize, 1, fontIndex);
error:
if (data) free(data);
if (fp) fclose(fp);
return FONS_INVALID;
}
int fonsAddFontMem(FONScontext* stash, const char* name, unsigned char* data, int dataSize, int freeData, int fontIndex)
{
int i, ascent, descent, fh, lineGap;
FONSfont* font;
int idx = fons__allocFont(stash);
if (idx == FONS_INVALID)
return FONS_INVALID;
font = stash->fonts[idx];
strncpy(font->name, name, sizeof(font->name));
font->name[sizeof(font->name)-1] = '\0';
// Init hash lookup.
for (i = 0; i < FONS_HASH_LUT_SIZE; ++i)
font->lut[i] = -1;
// Read in the font data.
font->dataSize = dataSize;
font->data = data;
font->freeData = (unsigned char)freeData;
// Init font
stash->nscratch = 0;
if (!fons__tt_loadFont(stash, &font->font, data, dataSize, fontIndex)) goto error;
// Store normalized line height. The real line height is got
// by multiplying the lineh by font size.
fons__tt_getFontVMetrics( &font->font, &ascent, &descent, &lineGap);
ascent += lineGap;
fh = ascent - descent;
font->ascender = (float)ascent / (float)fh;
font->descender = (float)descent / (float)fh;
font->lineh = font->ascender - font->descender;
return idx;
error:
fons__freeFont(font);
stash->nfonts--;
return FONS_INVALID;
}
int fonsGetFontByName(FONScontext* s, const char* name)
{
int i;
for (i = 0; i < s->nfonts; i++) {
if (strcmp(s->fonts[i]->name, name) == 0)
return i;
}
return FONS_INVALID;
}
static FONSglyph* fons__allocGlyph(FONSfont* font)
{
if (font->nglyphs+1 > font->cglyphs) {
font->cglyphs = font->cglyphs == 0 ? 8 : font->cglyphs * 2;
font->glyphs = (FONSglyph*)realloc(font->glyphs, sizeof(FONSglyph) * font->cglyphs);
if (font->glyphs == NULL) return NULL;
}
font->nglyphs++;
return &font->glyphs[font->nglyphs-1];
}
// Based on Exponential blur, Jani Huhtanen, 2006
#define APREC 16
#define ZPREC 7
static void fons__blurCols(unsigned char* dst, int w, int h, int dstStride, int alpha)
{
int x, y;
for (y = 0; y < h; y++) {
int z = 0; // force zero border
for (x = 1; x < w; x++) {
z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC;
dst[x] = (unsigned char)(z >> ZPREC);
}
dst[w-1] = 0; // force zero border
z = 0;
for (x = w-2; x >= 0; x--) {
z += (alpha * (((int)(dst[x]) << ZPREC) - z)) >> APREC;
dst[x] = (unsigned char)(z >> ZPREC);
}
dst[0] = 0; // force zero border
dst += dstStride;
}
}
static void fons__blurRows(unsigned char* dst, int w, int h, int dstStride, int alpha)
{
int x, y;
for (x = 0; x < w; x++) {
int z = 0; // force zero border
for (y = dstStride; y < h*dstStride; y += dstStride) {
z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC;
dst[y] = (unsigned char)(z >> ZPREC);
}
dst[(h-1)*dstStride] = 0; // force zero border
z = 0;
for (y = (h-2)*dstStride; y >= 0; y -= dstStride) {
z += (alpha * (((int)(dst[y]) << ZPREC) - z)) >> APREC;
dst[y] = (unsigned char)(z >> ZPREC);
}
dst[0] = 0; // force zero border
dst++;
}
}
static void fons__blur(FONScontext* stash, unsigned char* dst, int w, int h, int dstStride, int blur)
{
int alpha;
float sigma;
(void)stash;
if (blur < 1)
return;
// Calculate the alpha such that 90% of the kernel is within the radius. (Kernel extends to infinity)
sigma = (float)blur * 0.57735f; // 1 / sqrt(3)
alpha = (int)((1<<APREC) * (1.0f - expf(-2.3f / (sigma+1.0f))));
fons__blurRows(dst, w, h, dstStride, alpha);
fons__blurCols(dst, w, h, dstStride, alpha);
fons__blurRows(dst, w, h, dstStride, alpha);
fons__blurCols(dst, w, h, dstStride, alpha);
// fons__blurrows(dst, w, h, dstStride, alpha);
// fons__blurcols(dst, w, h, dstStride, alpha);
}
static FONSglyph* fons__getGlyph(FONScontext* stash, FONSfont* font, unsigned int codepoint,
short isize, short iblur, int bitmapOption)
{
int i, g, advance, lsb, x0, y0, x1, y1, gw, gh, gx, gy, x, y;
float scale;
FONSglyph* glyph = NULL;
unsigned int h;
float size = isize/10.0f;
int pad, added;
unsigned char* bdst;
unsigned char* dst;
FONSfont* renderFont = font;
if (isize < 2) return NULL;
if (iblur > 20) iblur = 20;
pad = iblur+2;
// Reset allocator.
stash->nscratch = 0;
// Find code point and size.
h = fons__hashint(codepoint) & (FONS_HASH_LUT_SIZE-1);
i = font->lut[h];
while (i != -1) {
if (font->glyphs[i].codepoint == codepoint && font->glyphs[i].size == isize && font->glyphs[i].blur == iblur) {
glyph = &font->glyphs[i];
if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL || (glyph->x0 >= 0 && glyph->y0 >= 0)) {
return glyph;
}
// At this point, glyph exists but the bitmap data is not yet created.
break;
}
i = font->glyphs[i].next;
}
// Create a new glyph or rasterize bitmap data for a cached glyph.
g = fons__tt_getGlyphIndex(&font->font, codepoint);
// Try to find the glyph in fallback fonts.
if (g == 0) {
for (i = 0; i < font->nfallbacks; ++i) {
FONSfont* fallbackFont = stash->fonts[font->fallbacks[i]];
int fallbackIndex = fons__tt_getGlyphIndex(&fallbackFont->font, codepoint);
if (fallbackIndex != 0) {
g = fallbackIndex;
renderFont = fallbackFont;
break;
}
}
// It is possible that we did not find a fallback glyph.
// In that case the glyph index 'g' is 0, and we'll proceed below and cache empty glyph.
}
scale = fons__tt_getPixelHeightScale(&renderFont->font, size);
fons__tt_buildGlyphBitmap(&renderFont->font, g, size, scale, &advance, &lsb, &x0, &y0, &x1, &y1);
gw = x1-x0 + pad*2;
gh = y1-y0 + pad*2;
// Determines the spot to draw glyph in the atlas.
if (bitmapOption == FONS_GLYPH_BITMAP_REQUIRED) {
// Find free spot for the rect in the atlas
added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy);
if (added == 0 && stash->handleError != NULL) {
// Atlas is full, let the user to resize the atlas (or not), and try again.
stash->handleError(stash->errorUptr, FONS_ATLAS_FULL, 0);
added = fons__atlasAddRect(stash->atlas, gw, gh, &gx, &gy);
}
if (added == 0) return NULL;
} else {
// Negative coordinate indicates there is no bitmap data created.
gx = -1;
gy = -1;
}
// Init glyph.
if (glyph == NULL) {
glyph = fons__allocGlyph(font);
glyph->codepoint = codepoint;
glyph->size = isize;
glyph->blur = iblur;
glyph->next = 0;
// Insert char to hash lookup.
glyph->next = font->lut[h];
font->lut[h] = font->nglyphs-1;
}
glyph->index = g;
glyph->x0 = (short)gx;
glyph->y0 = (short)gy;
glyph->x1 = (short)(glyph->x0+gw);
glyph->y1 = (short)(glyph->y0+gh);
glyph->xadv = (short)(scale * advance * 10.0f);
glyph->xoff = (short)(x0 - pad);
glyph->yoff = (short)(y0 - pad);
if (bitmapOption == FONS_GLYPH_BITMAP_OPTIONAL) {
return glyph;
}
// Rasterize
dst = &stash->texData[(glyph->x0+pad) + (glyph->y0+pad) * stash->params.width];
fons__tt_renderGlyphBitmap(&renderFont->font, dst, gw-pad*2,gh-pad*2, stash->params.width, scale, scale, g);
// Make sure there is one pixel empty border.
dst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width];
for (y = 0; y < gh; y++) {
dst[y*stash->params.width] = 0;
dst[gw-1 + y*stash->params.width] = 0;
}
for (x = 0; x < gw; x++) {
dst[x] = 0;
dst[x + (gh-1)*stash->params.width] = 0;
}
// Debug code to color the glyph background
/* unsigned char* fdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width];
for (y = 0; y < gh; y++) {
for (x = 0; x < gw; x++) {
int a = (int)fdst[x+y*stash->params.width] + 20;
if (a > 255) a = 255;
fdst[x+y*stash->params.width] = a;
}
}*/
// Blur
if (iblur > 0) {
stash->nscratch = 0;
bdst = &stash->texData[glyph->x0 + glyph->y0 * stash->params.width];
fons__blur(stash, bdst, gw, gh, stash->params.width, iblur);
}
stash->dirtyRect[0] = fons__mini(stash->dirtyRect[0], glyph->x0);
stash->dirtyRect[1] = fons__mini(stash->dirtyRect[1], glyph->y0);
stash->dirtyRect[2] = fons__maxi(stash->dirtyRect[2], glyph->x1);
stash->dirtyRect[3] = fons__maxi(stash->dirtyRect[3], glyph->y1);
return glyph;
}
static void fons__getQuad(FONScontext* stash, FONSfont* font,
int prevGlyphIndex, FONSglyph* glyph,
float scale, float spacing, float* x, float* y, FONSquad* q)
{
float rx,ry,xoff,yoff,x0,y0,x1,y1;
if (prevGlyphIndex != -1) {
float adv = fons__tt_getGlyphKernAdvance(&font->font, prevGlyphIndex, glyph->index) * scale;
*x += (int)(adv + spacing + 0.5f);
}
// Each glyph has 2px border to allow good interpolation,
// one pixel to prevent leaking, and one to allow good interpolation for rendering.
// Inset the texture region by one pixel for correct interpolation.
xoff = (short)(glyph->xoff+1);
yoff = (short)(glyph->yoff+1);
x0 = (float)(glyph->x0+1);
y0 = (float)(glyph->y0+1);
x1 = (float)(glyph->x1-1);
y1 = (float)(glyph->y1-1);
if (stash->params.flags & FONS_ZERO_TOPLEFT) {
rx = floorf(*x + xoff);
ry = floorf(*y + yoff);
q->x0 = rx;
q->y0 = ry;
q->x1 = rx + x1 - x0;
q->y1 = ry + y1 - y0;
q->s0 = x0 * stash->itw;
q->t0 = y0 * stash->ith;
q->s1 = x1 * stash->itw;
q->t1 = y1 * stash->ith;
} else {
rx = floorf(*x + xoff);
ry = floorf(*y - yoff);
q->x0 = rx;
q->y0 = ry;
q->x1 = rx + x1 - x0;
q->y1 = ry - y1 + y0;
q->s0 = x0 * stash->itw;
q->t0 = y0 * stash->ith;
q->s1 = x1 * stash->itw;
q->t1 = y1 * stash->ith;
}
*x += (int)(glyph->xadv / 10.0f + 0.5f);
}
static void fons__flush(FONScontext* stash)
{
// Flush texture
if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) {
if (stash->params.renderUpdate != NULL)
stash->params.renderUpdate(stash->params.userPtr, stash->dirtyRect, stash->texData);
// Reset dirty rect
stash->dirtyRect[0] = stash->params.width;
stash->dirtyRect[1] = stash->params.height;
stash->dirtyRect[2] = 0;
stash->dirtyRect[3] = 0;
}
// Flush triangles
if (stash->nverts > 0) {
if (stash->params.renderDraw != NULL)
stash->params.renderDraw(stash->params.userPtr, stash->verts, stash->tcoords, stash->colors, stash->nverts);
stash->nverts = 0;
}
}
static __inline void fons__vertex(FONScontext* stash, float x, float y, float s, float t, unsigned int c)
{
stash->verts[stash->nverts*2+0] = x;
stash->verts[stash->nverts*2+1] = y;
stash->tcoords[stash->nverts*2+0] = s;
stash->tcoords[stash->nverts*2+1] = t;
stash->colors[stash->nverts] = c;
stash->nverts++;
}
static float fons__getVertAlign(FONScontext* stash, FONSfont* font, int align, short isize)
{
if (stash->params.flags & FONS_ZERO_TOPLEFT) {
if (align & FONS_ALIGN_TOP) {
return font->ascender * (float)isize/10.0f;
} else if (align & FONS_ALIGN_MIDDLE) {
return (font->ascender + font->descender) / 2.0f * (float)isize/10.0f;
} else if (align & FONS_ALIGN_BASELINE) {
return 0.0f;
} else if (align & FONS_ALIGN_BOTTOM) {
return font->descender * (float)isize/10.0f;
}
} else {
if (align & FONS_ALIGN_TOP) {
return -font->ascender * (float)isize/10.0f;
} else if (align & FONS_ALIGN_MIDDLE) {
return -(font->ascender + font->descender) / 2.0f * (float)isize/10.0f;
} else if (align & FONS_ALIGN_BASELINE) {
return 0.0f;
} else if (align & FONS_ALIGN_BOTTOM) {
return -font->descender * (float)isize/10.0f;
}
}
return 0.0;
}
float fonsDrawText(FONScontext* stash,
float x, float y,
const char* str, const char* end)
{
FONSstate* state = fons__getState(stash);
unsigned int codepoint;
unsigned int utf8state = 0;
FONSglyph* glyph = NULL;
FONSquad q;
int prevGlyphIndex = -1;
short isize = (short)(state->size*10.0f);
short iblur = (short)state->blur;
float scale;
FONSfont* font;
float width;
if (stash == NULL) return x;
if (state->font < 0 || state->font >= stash->nfonts) return x;
font = stash->fonts[state->font];
if (font->data == NULL) return x;
scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f);
if (end == NULL)
end = str + strlen(str);
// Align horizontally
if (state->align & FONS_ALIGN_LEFT) {
// empty
} else if (state->align & FONS_ALIGN_RIGHT) {
width = fonsTextBounds(stash, x,y, str, end, NULL);
x -= width;
} else if (state->align & FONS_ALIGN_CENTER) {
width = fonsTextBounds(stash, x,y, str, end, NULL);
x -= width * 0.5f;
}
// Align vertically.
y += fons__getVertAlign(stash, font, state->align, isize);
for (; str != end; ++str) {
if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str))
continue;
glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_REQUIRED);
if (glyph != NULL) {
fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q);
if (stash->nverts+6 > FONS_VERTEX_COUNT)
fons__flush(stash);
fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color);
fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color);
fons__vertex(stash, q.x1, q.y0, q.s1, q.t0, state->color);
fons__vertex(stash, q.x0, q.y0, q.s0, q.t0, state->color);
fons__vertex(stash, q.x0, q.y1, q.s0, q.t1, state->color);
fons__vertex(stash, q.x1, q.y1, q.s1, q.t1, state->color);
}
prevGlyphIndex = glyph != NULL ? glyph->index : -1;
}
fons__flush(stash);
return x;
}
int fonsTextIterInit(FONScontext* stash, FONStextIter* iter,
float x, float y, const char* str, const char* end, int bitmapOption)
{
FONSstate* state = fons__getState(stash);
float width;
memset(iter, 0, sizeof(*iter));
if (stash == NULL) return 0;
if (state->font < 0 || state->font >= stash->nfonts) return 0;
iter->font = stash->fonts[state->font];
if (iter->font->data == NULL) return 0;
iter->isize = (short)(state->size*10.0f);
iter->iblur = (short)state->blur;
iter->scale = fons__tt_getPixelHeightScale(&iter->font->font, (float)iter->isize/10.0f);
// Align horizontally
if (state->align & FONS_ALIGN_LEFT) {
// empty
} else if (state->align & FONS_ALIGN_RIGHT) {
width = fonsTextBounds(stash, x,y, str, end, NULL);
x -= width;
} else if (state->align & FONS_ALIGN_CENTER) {
width = fonsTextBounds(stash, x,y, str, end, NULL);
x -= width * 0.5f;
}
// Align vertically.
y += fons__getVertAlign(stash, iter->font, state->align, iter->isize);
if (end == NULL)
end = str + strlen(str);
iter->x = iter->nextx = x;
iter->y = iter->nexty = y;
iter->spacing = state->spacing;
iter->str = str;
iter->next = str;
iter->end = end;
iter->codepoint = 0;
iter->prevGlyphIndex = -1;
iter->bitmapOption = bitmapOption;
return 1;
}
int fonsTextIterNext(FONScontext* stash, FONStextIter* iter, FONSquad* quad)
{
FONSglyph* glyph = NULL;
const char* str = iter->next;
iter->str = iter->next;
if (str == iter->end)
return 0;
for (; str != iter->end; str++) {
if (fons__decutf8(&iter->utf8state, &iter->codepoint, *(const unsigned char*)str))
continue;
str++;
// Get glyph and quad
iter->x = iter->nextx;
iter->y = iter->nexty;
glyph = fons__getGlyph(stash, iter->font, iter->codepoint, iter->isize, iter->iblur, iter->bitmapOption);
// If the iterator was initialized with FONS_GLYPH_BITMAP_OPTIONAL, then the UV coordinates of the quad will be invalid.
if (glyph != NULL)
fons__getQuad(stash, iter->font, iter->prevGlyphIndex, glyph, iter->scale, iter->spacing, &iter->nextx, &iter->nexty, quad);
iter->prevGlyphIndex = glyph != NULL ? glyph->index : -1;
break;
}
iter->next = str;
return 1;
}
void fonsDrawDebug(FONScontext* stash, float x, float y)
{
int i;
int w = stash->params.width;
int h = stash->params.height;
float u = w == 0 ? 0 : (1.0f / w);
float v = h == 0 ? 0 : (1.0f / h);
if (stash->nverts+6+6 > FONS_VERTEX_COUNT)
fons__flush(stash);
// Draw background
fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff);
fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff);
fons__vertex(stash, x+w, y+0, u, v, 0x0fffffff);
fons__vertex(stash, x+0, y+0, u, v, 0x0fffffff);
fons__vertex(stash, x+0, y+h, u, v, 0x0fffffff);
fons__vertex(stash, x+w, y+h, u, v, 0x0fffffff);
// Draw texture
fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff);
fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff);
fons__vertex(stash, x+w, y+0, 1, 0, 0xffffffff);
fons__vertex(stash, x+0, y+0, 0, 0, 0xffffffff);
fons__vertex(stash, x+0, y+h, 0, 1, 0xffffffff);
fons__vertex(stash, x+w, y+h, 1, 1, 0xffffffff);
// Drawbug draw atlas
for (i = 0; i < stash->atlas->nnodes; i++) {
FONSatlasNode* n = &stash->atlas->nodes[i];
if (stash->nverts+6 > FONS_VERTEX_COUNT)
fons__flush(stash);
fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff);
fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff);
fons__vertex(stash, x+n->x+n->width, y+n->y+0, u, v, 0xc00000ff);
fons__vertex(stash, x+n->x+0, y+n->y+0, u, v, 0xc00000ff);
fons__vertex(stash, x+n->x+0, y+n->y+1, u, v, 0xc00000ff);
fons__vertex(stash, x+n->x+n->width, y+n->y+1, u, v, 0xc00000ff);
}
fons__flush(stash);
}
float fonsTextBounds(FONScontext* stash,
float x, float y,
const char* str, const char* end,
float* bounds)
{
FONSstate* state = fons__getState(stash);
unsigned int codepoint;
unsigned int utf8state = 0;
FONSquad q;
FONSglyph* glyph = NULL;
int prevGlyphIndex = -1;
short isize = (short)(state->size*10.0f);
short iblur = (short)state->blur;
float scale;
FONSfont* font;
float startx, advance;
float minx, miny, maxx, maxy;
if (stash == NULL) return 0;
if (state->font < 0 || state->font >= stash->nfonts) return 0;
font = stash->fonts[state->font];
if (font->data == NULL) return 0;
scale = fons__tt_getPixelHeightScale(&font->font, (float)isize/10.0f);
// Align vertically.
y += fons__getVertAlign(stash, font, state->align, isize);
minx = maxx = x;
miny = maxy = y;
startx = x;
if (end == NULL)
end = str + strlen(str);
for (; str != end; ++str) {
if (fons__decutf8(&utf8state, &codepoint, *(const unsigned char*)str))
continue;
glyph = fons__getGlyph(stash, font, codepoint, isize, iblur, FONS_GLYPH_BITMAP_OPTIONAL);
if (glyph != NULL) {
fons__getQuad(stash, font, prevGlyphIndex, glyph, scale, state->spacing, &x, &y, &q);
if (q.x0 < minx) minx = q.x0;
if (q.x1 > maxx) maxx = q.x1;
if (stash->params.flags & FONS_ZERO_TOPLEFT) {
if (q.y0 < miny) miny = q.y0;
if (q.y1 > maxy) maxy = q.y1;
} else {
if (q.y1 < miny) miny = q.y1;
if (q.y0 > maxy) maxy = q.y0;
}
}
prevGlyphIndex = glyph != NULL ? glyph->index : -1;
}
advance = x - startx;
// Align horizontally
if (state->align & FONS_ALIGN_LEFT) {
// empty
} else if (state->align & FONS_ALIGN_RIGHT) {
minx -= advance;
maxx -= advance;
} else if (state->align & FONS_ALIGN_CENTER) {
minx -= advance * 0.5f;
maxx -= advance * 0.5f;
}
if (bounds) {
bounds[0] = minx;
bounds[1] = miny;
bounds[2] = maxx;
bounds[3] = maxy;
}
return advance;
}
void fonsVertMetrics(FONScontext* stash,
float* ascender, float* descender, float* lineh)
{
FONSfont* font;
FONSstate* state = fons__getState(stash);
short isize;
if (stash == NULL) return;
if (state->font < 0 || state->font >= stash->nfonts) return;
font = stash->fonts[state->font];
isize = (short)(state->size*10.0f);
if (font->data == NULL) return;
if (ascender)
*ascender = font->ascender*isize/10.0f;
if (descender)
*descender = font->descender*isize/10.0f;
if (lineh)
*lineh = font->lineh*isize/10.0f;
}
void fonsLineBounds(FONScontext* stash, float y, float* miny, float* maxy)
{
FONSfont* font;
FONSstate* state = fons__getState(stash);
short isize;
if (stash == NULL) return;
if (state->font < 0 || state->font >= stash->nfonts) return;
font = stash->fonts[state->font];
isize = (short)(state->size*10.0f);
if (font->data == NULL) return;
y += fons__getVertAlign(stash, font, state->align, isize);
if (stash->params.flags & FONS_ZERO_TOPLEFT) {
*miny = y - font->ascender * (float)isize/10.0f;
*maxy = *miny + font->lineh*isize/10.0f;
} else {
*maxy = y + font->descender * (float)isize/10.0f;
*miny = *maxy - font->lineh*isize/10.0f;
}
}
const unsigned char* fonsGetTextureData(FONScontext* stash, int* width, int* height)
{
if (width != NULL)
*width = stash->params.width;
if (height != NULL)
*height = stash->params.height;
return stash->texData;
}
int fonsValidateTexture(FONScontext* stash, int* dirty)
{
if (stash->dirtyRect[0] < stash->dirtyRect[2] && stash->dirtyRect[1] < stash->dirtyRect[3]) {
dirty[0] = stash->dirtyRect[0];
dirty[1] = stash->dirtyRect[1];
dirty[2] = stash->dirtyRect[2];
dirty[3] = stash->dirtyRect[3];
// Reset dirty rect
stash->dirtyRect[0] = stash->params.width;
stash->dirtyRect[1] = stash->params.height;
stash->dirtyRect[2] = 0;
stash->dirtyRect[3] = 0;
return 1;
}
return 0;
}
void fonsDeleteInternal(FONScontext* stash)
{
int i;
if (stash == NULL) return;
if (stash->params.renderDelete)
stash->params.renderDelete(stash->params.userPtr);
for (i = 0; i < stash->nfonts; ++i)
fons__freeFont(stash->fonts[i]);
if (stash->atlas) fons__deleteAtlas(stash->atlas);
if (stash->fonts) free(stash->fonts);
if (stash->texData) free(stash->texData);
if (stash->scratch) free(stash->scratch);
fons__tt_done(stash);
free(stash);
}
void fonsSetErrorCallback(FONScontext* stash, void (*callback)(void* uptr, int error, int val), void* uptr)
{
if (stash == NULL) return;
stash->handleError = callback;
stash->errorUptr = uptr;
}
void fonsGetAtlasSize(FONScontext* stash, int* width, int* height)
{
if (stash == NULL) return;
*width = stash->params.width;
*height = stash->params.height;
}
int fonsExpandAtlas(FONScontext* stash, int width, int height)
{
int i, maxy = 0;
unsigned char* data = NULL;
if (stash == NULL) return 0;
width = fons__maxi(width, stash->params.width);
height = fons__maxi(height, stash->params.height);
if (width == stash->params.width && height == stash->params.height)
return 1;
// Flush pending glyphs.
fons__flush(stash);
// Create new texture
if (stash->params.renderResize != NULL) {
if (stash->params.renderResize(stash->params.userPtr, width, height) == 0)
return 0;
}
// Copy old texture data over.
data = (unsigned char*)malloc(width * height);
if (data == NULL)
return 0;
for (i = 0; i < stash->params.height; i++) {
unsigned char* dst = &data[i*width];
unsigned char* src = &stash->texData[i*stash->params.width];
memcpy(dst, src, stash->params.width);
if (width > stash->params.width)
memset(dst+stash->params.width, 0, width - stash->params.width);
}
if (height > stash->params.height)
memset(&data[stash->params.height * width], 0, (height - stash->params.height) * width);
free(stash->texData);
stash->texData = data;
// Increase atlas size
fons__atlasExpand(stash->atlas, width, height);
// Add existing data as dirty.
for (i = 0; i < stash->atlas->nnodes; i++)
maxy = fons__maxi(maxy, stash->atlas->nodes[i].y);
stash->dirtyRect[0] = 0;
stash->dirtyRect[1] = 0;
stash->dirtyRect[2] = stash->params.width;
stash->dirtyRect[3] = maxy;
stash->params.width = width;
stash->params.height = height;
stash->itw = 1.0f/stash->params.width;
stash->ith = 1.0f/stash->params.height;
return 1;
}
int fonsResetAtlas(FONScontext* stash, int width, int height)
{
int i, j;
if (stash == NULL) return 0;
// Flush pending glyphs.
fons__flush(stash);
// Create new texture
if (stash->params.renderResize != NULL) {
if (stash->params.renderResize(stash->params.userPtr, width, height) == 0)
return 0;
}
// Reset atlas
fons__atlasReset(stash->atlas, width, height);
// Clear texture data.
stash->texData = (unsigned char*)realloc(stash->texData, width * height);
if (stash->texData == NULL) return 0;
memset(stash->texData, 0, width * height);
// Reset dirty rect
stash->dirtyRect[0] = width;
stash->dirtyRect[1] = height;
stash->dirtyRect[2] = 0;
stash->dirtyRect[3] = 0;
// Reset cached glyphs
for (i = 0; i < stash->nfonts; i++) {
FONSfont* font = stash->fonts[i];
font->nglyphs = 0;
for (j = 0; j < FONS_HASH_LUT_SIZE; j++)
font->lut[j] = -1;
}
stash->params.width = width;
stash->params.height = height;
stash->itw = 1.0f/stash->params.width;
stash->ith = 1.0f/stash->params.height;
// Add white rect at 0,0 for debug drawing.
fons__addWhiteRect(stash, 2,2);
return 1;
}
#endif
``` | /content/code_sandbox/libs/nanovg/nanovg/fontstash.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 16,758 |
```objective-c
//
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef NANOVG_H
#define NANOVG_H
#ifdef __cplusplus
extern "C" {
#endif
#define NVG_PI 3.14159265358979323846264338327f
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union
#endif
typedef struct NVGcontext NVGcontext;
struct NVGcolor {
union {
float rgba[4];
struct {
float r,g,b,a;
};
};
};
typedef struct NVGcolor NVGcolor;
struct NVGpaint {
float xform[6];
float extent[2];
float radius;
float feather;
NVGcolor innerColor;
NVGcolor outerColor;
int image;
};
typedef struct NVGpaint NVGpaint;
enum NVGwinding {
NVG_CCW = 1, // Winding for solid shapes
NVG_CW = 2, // Winding for holes
};
enum NVGsolidity {
NVG_SOLID = 1, // CCW
NVG_HOLE = 2, // CW
};
enum NVGlineCap {
NVG_BUTT,
NVG_ROUND,
NVG_SQUARE,
NVG_BEVEL,
NVG_MITER,
};
enum NVGalign {
// Horizontal align
NVG_ALIGN_LEFT = 1<<0, // Default, align text horizontally to left.
NVG_ALIGN_CENTER = 1<<1, // Align text horizontally to center.
NVG_ALIGN_RIGHT = 1<<2, // Align text horizontally to right.
// Vertical align
NVG_ALIGN_TOP = 1<<3, // Align text vertically to top.
NVG_ALIGN_MIDDLE = 1<<4, // Align text vertically to middle.
NVG_ALIGN_BOTTOM = 1<<5, // Align text vertically to bottom.
NVG_ALIGN_BASELINE = 1<<6, // Default, align text vertically to baseline.
};
enum NVGblendFactor {
NVG_ZERO = 1<<0,
NVG_ONE = 1<<1,
NVG_SRC_COLOR = 1<<2,
NVG_ONE_MINUS_SRC_COLOR = 1<<3,
NVG_DST_COLOR = 1<<4,
NVG_ONE_MINUS_DST_COLOR = 1<<5,
NVG_SRC_ALPHA = 1<<6,
NVG_ONE_MINUS_SRC_ALPHA = 1<<7,
NVG_DST_ALPHA = 1<<8,
NVG_ONE_MINUS_DST_ALPHA = 1<<9,
NVG_SRC_ALPHA_SATURATE = 1<<10,
};
enum NVGcompositeOperation {
NVG_SOURCE_OVER,
NVG_SOURCE_IN,
NVG_SOURCE_OUT,
NVG_ATOP,
NVG_DESTINATION_OVER,
NVG_DESTINATION_IN,
NVG_DESTINATION_OUT,
NVG_DESTINATION_ATOP,
NVG_LIGHTER,
NVG_COPY,
NVG_XOR,
};
struct NVGcompositeOperationState {
int srcRGB;
int dstRGB;
int srcAlpha;
int dstAlpha;
};
typedef struct NVGcompositeOperationState NVGcompositeOperationState;
struct NVGglyphPosition {
const char* str; // Position of the glyph in the input string.
float x; // The x-coordinate of the logical glyph position.
float minx, maxx; // The bounds of the glyph shape.
};
typedef struct NVGglyphPosition NVGglyphPosition;
struct NVGtextRow {
const char* start; // Pointer to the input text where the row starts.
const char* end; // Pointer to the input text where the row ends (one past the last character).
const char* next; // Pointer to the beginning of the next row.
float width; // Logical width of the row.
float minx, maxx; // Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending.
};
typedef struct NVGtextRow NVGtextRow;
enum NVGimageFlags {
NVG_IMAGE_GENERATE_MIPMAPS = 1<<0, // Generate mipmaps during creation of the image.
NVG_IMAGE_REPEATX = 1<<1, // Repeat image in X direction.
NVG_IMAGE_REPEATY = 1<<2, // Repeat image in Y direction.
NVG_IMAGE_FLIPY = 1<<3, // Flips (inverses) image in Y direction when rendered.
NVG_IMAGE_PREMULTIPLIED = 1<<4, // Image data has premultiplied alpha.
NVG_IMAGE_NEAREST = 1<<5, // Image interpolation is Nearest instead Linear
};
// Begin drawing a new frame
// Calls to nanovg drawing API should be wrapped in nvgBeginFrame() & nvgEndFrame()
// nvgBeginFrame() defines the size of the window to render to in relation currently
// set viewport (i.e. glViewport on GL backends). Device pixel ration allows to
// control the rendering on Hi-DPI devices.
// For example, GLFW returns two dimension for an opened window: window size and
// frame buffer size. In that case you would set windowWidth/Height to the window size
// devicePixelRatio to: frameBufferWidth / windowWidth.
void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio);
// Cancels drawing the current frame.
void nvgCancelFrame(NVGcontext* ctx);
// Ends drawing flushing remaining render state.
void nvgEndFrame(NVGcontext* ctx);
//
// Composite operation
//
// The composite operations in NanoVG are modeled after HTML Canvas API, and
// the blend func is based on OpenGL (see corresponding manuals for more info).
// The colors in the blending state have premultiplied alpha.
// Sets the composite operation. The op parameter should be one of NVGcompositeOperation.
void nvgGlobalCompositeOperation(NVGcontext* ctx, int op);
// Sets the composite operation with custom pixel arithmetic. The parameters should be one of NVGblendFactor.
void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor);
// Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately. The parameters should be one of NVGblendFactor.
void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha);
//
// Color utils
//
// Colors in NanoVG are stored as unsigned ints in ABGR format.
// Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).
NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b);
// Returns a color value from red, green, blue values. Alpha will be set to 1.0f.
NVGcolor nvgRGBf(float r, float g, float b);
// Returns a color value from red, green, blue and alpha values.
NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
// Returns a color value from red, green, blue and alpha values.
NVGcolor nvgRGBAf(float r, float g, float b, float a);
// Linearly interpolates from color c0 to c1, and returns resulting color value.
NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u);
// Sets transparency of a color value.
NVGcolor nvgTransRGBA(NVGcolor c0, unsigned char a);
// Sets transparency of a color value.
NVGcolor nvgTransRGBAf(NVGcolor c0, float a);
// Returns color value specified by hue, saturation and lightness.
// HSL values are all in range [0..1], alpha will be set to 255.
NVGcolor nvgHSL(float h, float s, float l);
// Returns color value specified by hue, saturation and lightness and alpha.
// HSL values are all in range [0..1], alpha in range [0..255]
NVGcolor nvgHSLA(float h, float s, float l, unsigned char a);
//
// State Handling
//
// NanoVG contains state which represents how paths will be rendered.
// The state contains transform, fill and stroke styles, text and font styles,
// and scissor clipping.
// Pushes and saves the current render state into a state stack.
// A matching nvgRestore() must be used to restore the state.
void nvgSave(NVGcontext* ctx);
// Pops and restores current render state.
void nvgRestore(NVGcontext* ctx);
// Resets current render state to default values. Does not affect the render state stack.
void nvgReset(NVGcontext* ctx);
//
// Render styles
//
// Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern.
// Solid color is simply defined as a color value, different kinds of paints can be created
// using nvgLinearGradient(), nvgBoxGradient(), nvgRadialGradient() and nvgImagePattern().
//
// Current render style can be saved and restored using nvgSave() and nvgRestore().
// Sets whether to draw antialias for nvgStroke() and nvgFill(). It's enabled by default.
void nvgShapeAntiAlias(NVGcontext* ctx, int enabled);
// Sets current stroke style to a solid color.
void nvgStrokeColor(NVGcontext* ctx, NVGcolor color);
// Sets current stroke style to a paint, which can be a one of the gradients or a pattern.
void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint);
// Sets current fill style to a solid color.
void nvgFillColor(NVGcontext* ctx, NVGcolor color);
// Sets current fill style to a paint, which can be a one of the gradients or a pattern.
void nvgFillPaint(NVGcontext* ctx, NVGpaint paint);
// Sets the miter limit of the stroke style.
// Miter limit controls when a sharp corner is beveled.
void nvgMiterLimit(NVGcontext* ctx, float limit);
// Sets the stroke width of the stroke style.
void nvgStrokeWidth(NVGcontext* ctx, float size);
// Sets how the end of the line (cap) is drawn,
// Can be one of: NVG_BUTT (default), NVG_ROUND, NVG_SQUARE.
void nvgLineCap(NVGcontext* ctx, int cap);
// Sets how sharp path corners are drawn.
// Can be one of NVG_MITER (default), NVG_ROUND, NVG_BEVEL.
void nvgLineJoin(NVGcontext* ctx, int join);
// Sets the transparency applied to all rendered shapes.
// Already transparent paths will get proportionally more transparent as well.
void nvgGlobalAlpha(NVGcontext* ctx, float alpha);
//
// Transforms
//
// The paths, gradients, patterns and scissor region are transformed by an transformation
// matrix at the time when they are passed to the API.
// The current transformation matrix is a affine matrix:
// [sx kx tx]
// [ky sy ty]
// [ 0 0 1]
// Where: sx,sy define scaling, kx,ky skewing, and tx,ty translation.
// The last row is assumed to be 0,0,1 and is not stored.
//
// Apart from nvgResetTransform(), each transformation function first creates
// specific transformation matrix and pre-multiplies the current transformation by it.
//
// Current coordinate system (transformation) can be saved and restored using nvgSave() and nvgRestore().
// Resets current transform to a identity matrix.
void nvgResetTransform(NVGcontext* ctx);
// Premultiplies current coordinate system by specified matrix.
// The parameters are interpreted as matrix as follows:
// [a c e]
// [b d f]
// [0 0 1]
void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f);
// Translates current coordinate system.
void nvgTranslate(NVGcontext* ctx, float x, float y);
// Rotates current coordinate system. Angle is specified in radians.
void nvgRotate(NVGcontext* ctx, float angle);
// Skews the current coordinate system along X axis. Angle is specified in radians.
void nvgSkewX(NVGcontext* ctx, float angle);
// Skews the current coordinate system along Y axis. Angle is specified in radians.
void nvgSkewY(NVGcontext* ctx, float angle);
// Scales the current coordinate system.
void nvgScale(NVGcontext* ctx, float x, float y);
// Stores the top part (a-f) of the current transformation matrix in to the specified buffer.
// [a c e]
// [b d f]
// [0 0 1]
// There should be space for 6 floats in the return buffer for the values a-f.
void nvgCurrentTransform(NVGcontext* ctx, float* xform);
// The following functions can be used to make calculations on 2x3 transformation matrices.
// A 2x3 matrix is represented as float[6].
// Sets the transform to identity matrix.
void nvgTransformIdentity(float* dst);
// Sets the transform to translation matrix matrix.
void nvgTransformTranslate(float* dst, float tx, float ty);
// Sets the transform to scale matrix.
void nvgTransformScale(float* dst, float sx, float sy);
// Sets the transform to rotate matrix. Angle is specified in radians.
void nvgTransformRotate(float* dst, float a);
// Sets the transform to skew-x matrix. Angle is specified in radians.
void nvgTransformSkewX(float* dst, float a);
// Sets the transform to skew-y matrix. Angle is specified in radians.
void nvgTransformSkewY(float* dst, float a);
// Sets the transform to the result of multiplication of two transforms, of A = A*B.
void nvgTransformMultiply(float* dst, const float* src);
// Sets the transform to the result of multiplication of two transforms, of A = B*A.
void nvgTransformPremultiply(float* dst, const float* src);
// Sets the destination to inverse of specified transform.
// Returns 1 if the inverse could be calculated, else 0.
int nvgTransformInverse(float* dst, const float* src);
// Transform a point by given transform.
void nvgTransformPoint(float* dstx, float* dsty, const float* xform, float srcx, float srcy);
// Converts degrees to radians and vice versa.
float nvgDegToRad(float deg);
float nvgRadToDeg(float rad);
//
// Images
//
// NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering.
// In addition you can upload your own image. The image loading is provided by stb_image.
// The parameter imageFlags is combination of flags defined in NVGimageFlags.
// Creates image by loading it from the disk from specified file name.
// Returns handle to the image.
int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags);
// Creates image by loading it from the specified chunk of memory.
// Returns handle to the image.
int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata);
// Creates image from specified image data.
// Returns handle to the image.
int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data);
// Updates image data specified by image handle.
void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data);
// Returns the dimensions of a created image.
void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h);
// Deletes created image.
void nvgDeleteImage(NVGcontext* ctx, int image);
//
// Paints
//
// NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern.
// These can be used as paints for strokes and fills.
// Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates
// of the linear gradient, icol specifies the start color and ocol the end color.
// The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint().
NVGpaint nvgLinearGradient(NVGcontext* ctx, float sx, float sy, float ex, float ey,
NVGcolor icol, NVGcolor ocol);
// Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering
// drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle,
// (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry
// the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient.
// The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint().
NVGpaint nvgBoxGradient(NVGcontext* ctx, float x, float y, float w, float h,
float r, float f, NVGcolor icol, NVGcolor ocol);
// Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify
// the inner and outer radius of the gradient, icol specifies the start color and ocol the end color.
// The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint().
NVGpaint nvgRadialGradient(NVGcontext* ctx, float cx, float cy, float inr, float outr,
NVGcolor icol, NVGcolor ocol);
// Creates and returns an image pattern. Parameters (ox,oy) specify the left-top location of the image pattern,
// (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render.
// The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint().
NVGpaint nvgImagePattern(NVGcontext* ctx, float ox, float oy, float ex, float ey,
float angle, int image, float alpha);
//
// Scissoring
//
// Scissoring allows you to clip the rendering into a rectangle. This is useful for various
// user interface cases like rendering a text edit or a timeline.
// Sets the current scissor rectangle.
// The scissor rectangle is transformed by the current transform.
void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h);
// Intersects current scissor rectangle with the specified rectangle.
// The scissor rectangle is transformed by the current transform.
// Note: in case the rotation of previous scissor rect differs from
// the current one, the intersection will be done between the specified
// rectangle and the previous scissor rectangle transformed in the current
// transform space. The resulting shape is always rectangle.
void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h);
// Reset and disables scissoring.
void nvgResetScissor(NVGcontext* ctx);
//
// Paths
//
// Drawing a new shape starts with nvgBeginPath(), it clears all the currently defined paths.
// Then you define one or more paths and sub-paths which describe the shape. The are functions
// to draw common shapes like rectangles and circles, and lower level step-by-step functions,
// which allow to define a path curve by curve.
//
// NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise
// winding and holes should have counter clockwise order. To specify winding of a path you can
// call nvgPathWinding(). This is useful especially for the common shapes, which are drawn CCW.
//
// Finally you can fill the path using current fill style by calling nvgFill(), and stroke it
// with current stroke style by calling nvgStroke().
//
// The curve segments and sub-paths are transformed by the current transform.
// Clears the current path and sub-paths.
void nvgBeginPath(NVGcontext* ctx);
// Starts new sub-path with specified point as first point.
void nvgMoveTo(NVGcontext* ctx, float x, float y);
// Adds line segment from the last point in the path to the specified point.
void nvgLineTo(NVGcontext* ctx, float x, float y);
// Adds cubic bezier segment from last point in the path via two control points to the specified point.
void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y);
// Adds quadratic bezier segment from last point in the path via a control point to the specified point.
void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y);
// Adds an arc segment at the corner defined by the last path point, and two specified points.
void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius);
// Closes current sub-path with a line segment.
void nvgClosePath(NVGcontext* ctx);
// Sets the current sub-path winding, see NVGwinding and NVGsolidity.
void nvgPathWinding(NVGcontext* ctx, int dir);
// Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r,
// and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW, or NVG_CW).
// Angles are specified in radians.
void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir);
// Creates new rectangle shaped sub-path.
void nvgRect(NVGcontext* ctx, float x, float y, float w, float h);
// Creates new rounded rectangle shaped sub-path.
void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r);
// Creates new rounded rectangle shaped sub-path with varying radii for each corner.
void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft);
// Creates new ellipse shaped sub-path.
void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry);
// Creates new circle shaped sub-path.
void nvgCircle(NVGcontext* ctx, float cx, float cy, float r);
// Fills the current path with current fill style.
void nvgFill(NVGcontext* ctx);
// Fills the current path with current stroke style.
void nvgStroke(NVGcontext* ctx);
//
// Text
//
// NanoVG allows you to load .ttf files and use the font to render text.
//
// The appearance of the text can be defined by setting the current text style
// and by specifying the fill color. Common text and font settings such as
// font size, letter spacing and text align are supported. Font blur allows you
// to create simple text effects such as drop shadows.
//
// At render time the font face can be set based on the font handles or name.
//
// Font measure functions return values in local space, the calculations are
// carried in the same resolution as the final rendering. This is done because
// the text glyph positions are snapped to the nearest pixels sharp rendering.
//
// The local space means that values are not rotated or scale as per the current
// transformation. For example if you set font size to 12, which would mean that
// line height is 16, then regardless of the current scaling and rotation, the
// returned line height is always 16. Some measures may vary because of the scaling
// since aforementioned pixel snapping.
//
// While this may sound a little odd, the setup allows you to always render the
// same way regardless of scaling. I.e. following works regardless of scaling:
//
// const char* txt = "Text me up.";
// nvgTextBounds(vg, x,y, txt, NULL, bounds);
// nvgBeginPath(vg);
// nvgRect(vg, bounds[0],bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]);
// nvgFill(vg);
//
// Note: currently only solid color fill is supported for text.
// Creates font by loading it from the disk from specified file name.
// Returns handle to the font.
int nvgCreateFont(NVGcontext* ctx, const char* name, const char* filename);
// fontIndex specifies which font face to load from a .ttf/.ttc file.
int nvgCreateFontAtIndex(NVGcontext* ctx, const char* name, const char* filename, const int fontIndex);
// Creates font by loading it from the specified memory chunk.
// Returns handle to the font.
int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData);
// fontIndex specifies which font face to load from a .ttf/.ttc file.
int nvgCreateFontMemAtIndex(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData, const int fontIndex);
// Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.
int nvgFindFont(NVGcontext* ctx, const char* name);
// Adds a fallback font by handle.
int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont);
// Adds a fallback font by name.
int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont);
// Resets fallback fonts by handle.
void nvgResetFallbackFontsId(NVGcontext* ctx, int baseFont);
// Resets fallback fonts by name.
void nvgResetFallbackFonts(NVGcontext* ctx, const char* baseFont);
// Sets the font size of current text style.
void nvgFontSize(NVGcontext* ctx, float size);
// Sets the blur of current text style.
void nvgFontBlur(NVGcontext* ctx, float blur);
// Sets the letter spacing of current text style.
void nvgTextLetterSpacing(NVGcontext* ctx, float spacing);
// Sets the proportional line height of current text style. The line height is specified as multiple of font size.
void nvgTextLineHeight(NVGcontext* ctx, float lineHeight);
// Sets the text align of current text style, see NVGalign for options.
void nvgTextAlign(NVGcontext* ctx, int align);
// Sets the font face based on specified id of current text style.
void nvgFontFaceId(NVGcontext* ctx, int font);
// Sets the font face based on specified name of current text style.
void nvgFontFace(NVGcontext* ctx, const char* font);
// Draws text string at specified location. If end is specified only the sub-string up to the end is drawn.
float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end);
// Draws multi-line text string at specified location wrapped at the specified width. If end is specified only the sub-string up to the end is drawn.
// White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
// Words longer than the max width are slit at nearest character (i.e. no hyphenation).
void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end);
// Measures the specified text string. Parameter bounds should be a pointer to float[4],
// if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]
// Returns the horizontal advance of the measured text (i.e. where the next character should drawn).
// Measured values are returned in local coordinate space.
float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds);
// Measures the specified multi-text string. Parameter bounds should be a pointer to float[4],
// if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]
// Measured values are returned in local coordinate space.
void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds);
// Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used.
// Measured values are returned in local coordinate space.
int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions);
// Returns the vertical metrics based on the current text style.
// Measured values are returned in local coordinate space.
void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh);
// Breaks the specified text into lines. If end is specified only the sub-string will be used.
// White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.
// Words longer than the max width are slit at nearest character (i.e. no hyphenation).
int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows);
//
// Internal Render API
//
enum NVGtexture {
NVG_TEXTURE_ALPHA = 0x01,
NVG_TEXTURE_RGBA = 0x02,
};
struct NVGscissor {
float xform[6];
float extent[2];
};
typedef struct NVGscissor NVGscissor;
struct NVGvertex {
float x,y,u,v;
};
typedef struct NVGvertex NVGvertex;
struct NVGpath {
int first;
int count;
unsigned char closed;
int nbevel;
NVGvertex* fill;
int nfill;
NVGvertex* stroke;
int nstroke;
int winding;
int convex;
};
typedef struct NVGpath NVGpath;
struct NVGparams {
void* userPtr;
int edgeAntiAlias;
int (*renderCreate)(void* uptr);
int (*renderCreateTexture)(void* uptr, int type, int w, int h, int imageFlags, const unsigned char* data);
int (*renderDeleteTexture)(void* uptr, int image);
int (*renderUpdateTexture)(void* uptr, int image, int x, int y, int w, int h, const unsigned char* data);
int (*renderGetTextureSize)(void* uptr, int image, int* w, int* h);
void (*renderViewport)(void* uptr, float width, float height, float devicePixelRatio);
void (*renderCancel)(void* uptr);
void (*renderFlush)(void* uptr);
void (*renderFill)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, const float* bounds, const NVGpath* paths, int npaths);
void (*renderStroke)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, float fringe, float strokeWidth, const NVGpath* paths, int npaths);
void (*renderTriangles)(void* uptr, NVGpaint* paint, NVGcompositeOperationState compositeOperation, NVGscissor* scissor, const NVGvertex* verts, int nverts, float fringe);
void (*renderDelete)(void* uptr);
};
typedef struct NVGparams NVGparams;
// Constructor and destructor, called by the render back-end.
NVGcontext* nvgCreateInternal(NVGparams* params);
void nvgDeleteInternal(NVGcontext* ctx);
NVGparams* nvgInternalParams(NVGcontext* ctx);
// Debug function to dump cached path data.
void nvgDebugDumpPathCache(NVGcontext* ctx);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#define NVG_NOTUSED(v) for (;;) { (void)(1 ? (void)0 : ( (void)(v) ) ); break; }
#ifdef __cplusplus
}
#endif
#endif // NANOVG_H
``` | /content/code_sandbox/libs/nanovg/nanovg/nanovg.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 7,232 |
```objective-c
// stb_truetype.h - v1.26 - public domain
// authored from 2009-2021 by Sean Barrett / RAD Game Tools
//
// =======================================================================
//
// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES
//
// This library does no range checking of the offsets found in the file,
// meaning an attacker can use it to read arbitrary memory.
//
// =======================================================================
//
// This library processes TrueType files:
// parse files
// extract glyph metrics
// extract glyph shapes
// render glyphs to one-channel bitmaps with antialiasing (box filter)
// render glyphs to one-channel SDF bitmaps (signed-distance field/function)
//
// Todo:
// non-MS cmaps
// crashproof on bad data
// hinting? (no longer patented)
// cleartype-style AA?
// optimize: use simple memory allocator for intermediates
// optimize: build edge-list directly from curves
// optimize: rasterize directly from curves?
//
// ADDITIONAL CONTRIBUTORS
//
// Mikko Mononen: compound shape support, more cmap formats
// Tor Andersson: kerning, subpixel rendering
// Dougall Johnson: OpenType / Type 2 font handling
// Daniel Ribeiro Maciel: basic GPOS-based kerning
//
// Misc other:
// Ryan Gordon
// Simon Glass
// github:IntellectualKitty
// Imanol Celaya
// Daniel Ribeiro Maciel
//
// Bug/warning reports/fixes:
// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe
// Cass Everitt Martins Mozeiko github:aloucks
// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam
// Brian Hook Omar Cornut github:vassvik
// Walter van Niftrik Ryan Griege
// David Gow Peter LaValle
// David Given Sergey Popov
// Ivan-Assen Ivanov Giumo X. Clanjor
// Anthony Pesch Higor Euripedes
// Johan Duparc Thomas Fields
// Hou Qiming Derek Vinyard
// Rob Loach Cort Stratton
// Kenney Phillis Jr. Brian Costabile
// Ken Voskuil (kaesve)
//
// VERSION HISTORY
//
// 1.26 (2021-08-28) fix broken rasterizer
// 1.25 (2021-07-11) many fixes
// 1.24 (2020-02-05) fix warning
// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)
// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined
// 1.21 (2019-02-25) fix warning
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// variant PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
//
// Full history can be found at the end of this file.
//
// LICENSE
//
// See end of file for license information.
//
// USAGE
//
// Include this file in whatever places need to refer to it. In ONE C/C++
// file, write:
// #define STB_TRUETYPE_IMPLEMENTATION
// before the #include of this file. This expands out the actual
// implementation into that C/C++ file.
//
// To make the implementation private to the file that generates the implementation,
// #define STBTT_STATIC
//
// Simple 3D API (don't ship this, but it's fine for tools and quick start)
// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
// stbtt_GetBakedQuad() -- compute quad to draw for a given char
//
// Improved 3D API (more shippable):
// #include "stb_rect_pack.h" -- optional, but you really want it
// stbtt_PackBegin()
// stbtt_PackSetOversampling() -- for improved quality on small fonts
// stbtt_PackFontRanges() -- pack and renders
// stbtt_PackEnd()
// stbtt_GetPackedQuad()
//
// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
// stbtt_InitFont()
// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
//
// Render a unicode codepoint to a bitmap
// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
//
// Character advance/positioning
// stbtt_GetCodepointHMetrics()
// stbtt_GetFontVMetrics()
// stbtt_GetFontVMetricsOS2()
// stbtt_GetCodepointKernAdvance()
//
// Starting with version 1.06, the rasterizer was replaced with a new,
// faster and generally-more-precise rasterizer. The new rasterizer more
// accurately measures pixel coverage for anti-aliasing, except in the case
// where multiple shapes overlap, in which case it overestimates the AA pixel
// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
// this turns out to be a problem, you can re-enable the old rasterizer with
// #define STBTT_RASTERIZER_VERSION 1
// which will incur about a 15% speed hit.
//
// ADDITIONAL DOCUMENTATION
//
// Immediately after this block comment are a series of sample programs.
//
// After the sample programs is the "header file" section. This section
// includes documentation for each API function.
//
// Some important concepts to understand to use this library:
//
// Codepoint
// Characters are defined by unicode codepoints, e.g. 65 is
// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
// the hiragana for "ma".
//
// Glyph
// A visual character shape (every codepoint is rendered as
// some glyph)
//
// Glyph index
// A font-specific integer ID representing a glyph
//
// Baseline
// Glyph shapes are defined relative to a baseline, which is the
// bottom of uppercase characters. Characters extend both above
// and below the baseline.
//
// Current Point
// As you draw text to the screen, you keep track of a "current point"
// which is the origin of each character. The current point's vertical
// position is the baseline. Even "baked fonts" use this model.
//
// Vertical Font Metrics
// The vertical qualities of the font, used to vertically position
// and space the characters. See docs for stbtt_GetFontVMetrics.
//
// Font Size in Pixels or Points
// The preferred interface for specifying font sizes in stb_truetype
// is to specify how tall the font's vertical extent should be in pixels.
// If that sounds good enough, skip the next paragraph.
//
// Most font APIs instead use "points", which are a common typographic
// measurement for describing font size, defined as 72 points per inch.
// stb_truetype provides a point API for compatibility. However, true
// "per inch" conventions don't make much sense on computer displays
// since different monitors have different number of pixels per
// inch. For example, Windows traditionally uses a convention that
// there are 96 pixels per inch, thus making 'inch' measurements have
// nothing to do with inches, and thus effectively defining a point to
// be 1.333 pixels. Additionally, the TrueType font data provides
// an explicit scale factor to scale a given font's glyphs to points,
// but the author has observed that this scale factor is often wrong
// for non-commercial fonts, thus making fonts scaled in points
// according to the TrueType spec incoherently sized in practice.
//
// DETAILED USAGE:
//
// Scale:
// Select how high you want the font to be, in points or pixels.
// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute
// a scale factor SF that will be used by all other functions.
//
// Baseline:
// You need to select a y-coordinate that is the baseline of where
// your text will appear. Call GetFontBoundingBox to get the baseline-relative
// bounding box for all characters. SF*-y0 will be the distance in pixels
// that the worst-case character could extend above the baseline, so if
// you want the top edge of characters to appear at the top of the
// screen where y=0, then you would set the baseline to SF*-y0.
//
// Current point:
// Set the current point where the first character will appear. The
// first character could extend left of the current point; this is font
// dependent. You can either choose a current point that is the leftmost
// point and hope, or add some padding, or check the bounding box or
// left-side-bearing of the first character to be displayed and set
// the current point based on that.
//
// Displaying a character:
// Compute the bounding box of the character. It will contain signed values
// relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
// then the character should be displayed in the rectangle from
// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
//
// Advancing for the next character:
// Call GlyphHMetrics, and compute 'current_point += SF * advance'.
//
//
// ADVANCED USAGE
//
// Quality:
//
// - Use the functions with Subpixel at the end to allow your characters
// to have subpixel positioning. Since the font is anti-aliased, not
// hinted, this is very import for quality. (This is not possible with
// baked fonts.)
//
// - Kerning is now supported, and if you're supporting subpixel rendering
// then kerning is worth using to give your text a polished look.
//
// Performance:
//
// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
// if you don't do this, stb_truetype is forced to do the conversion on
// every call.
//
// - There are a lot of memory allocations. We should modify it to take
// a temp buffer and allocate from the temp buffer (without freeing),
// should help performance a lot.
//
// NOTES
//
// The system uses the raw data found in the .ttf file without changing it
// and without building auxiliary data structures. This is a bit inefficient
// on little-endian systems (the data is big-endian), but assuming you're
// caching the bitmaps or glyph shapes this shouldn't be a big deal.
//
// It appears to be very hard to programmatically determine what font a
// given file is in a general way. I provide an API for this, but I don't
// recommend it.
//
//
// PERFORMANCE MEASUREMENTS FOR 1.06:
//
// 32-bit 64-bit
// Previous release: 8.83 s 7.68 s
// Pool allocations: 7.72 s 6.34 s
// Inline sort : 6.54 s 5.65 s
// New rasterizer : 5.63 s 5.00 s
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// SAMPLE PROGRAMS
////
//
// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless.
// See "tests/truetype_demo_win32.c" for a complete version.
#if 0
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
unsigned char ttf_buffer[1<<20];
unsigned char temp_bitmap[512*512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
GLuint ftex;
void my_stbtt_initfont(void)
{
fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
// can free ttf_buffer at this point
glGenTextures(1, &ftex);
glBindTexture(GL_TEXTURE_2D, ftex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void my_stbtt_print(float x, float y, char *text)
{
// assume orthographic projection with units = screen pixels, origin at top left
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ftex);
glBegin(GL_QUADS);
while (*text) {
if (*text >= 32 && *text < 128) {
stbtt_aligned_quad q;
stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0);
glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0);
glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1);
glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1);
}
++text;
}
glEnd();
}
#endif
//
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program (this compiles): get a single bitmap, print as ASCII art
//
#if 0
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
char ttf_buffer[1<<25];
int main(int argc, char **argv)
{
stbtt_fontinfo font;
unsigned char *bitmap;
int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i)
putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
putchar('\n');
}
return 0;
}
#endif
//
// Output:
//
// .ii.
// @@@@@@.
// V@Mio@@o
// :i. V@V
// :oM@@M
// :@@@MM@M
// @@o o@M
// :@@. M@M
// @@@o@@@@
// :M@@V:@@.
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program: print "Hello World!" banner, with bugs
//
#if 0
char buffer[24<<20];
unsigned char screen[20][79];
int main(int arg, char **argv)
{
stbtt_fontinfo font;
int i,j,ascent,baseline,ch=0;
float scale, xpos=2; // leave a little padding in case the character extends left
char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, buffer, 0);
scale = stbtt_ScaleForPixelHeight(&font, 15);
stbtt_GetFontVMetrics(&font, &ascent,0,0);
baseline = (int) (ascent*scale);
while (text[ch]) {
int advance,lsb,x0,y0,x1,y1;
float x_shift = xpos - (float) floor(xpos);
stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (text[ch+1])
xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
++ch;
}
for (j=0; j < 20; ++j) {
for (i=0; i < 78; ++i)
putchar(" .:ioVM@"[screen[j][i]>>5]);
putchar('\n');
}
return 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
////
//// INTEGRATION WITH YOUR CODEBASE
////
//// The following sections allow you to supply alternate definitions
//// of C library functions used by stb_truetype, e.g. if you don't
//// link with the C runtime library.
#ifdef STB_TRUETYPE_IMPLEMENTATION
// #define your own (u)stbtt_int8/16/32 before including to override this
#ifndef stbtt_uint8
typedef unsigned char stbtt_uint8;
typedef signed char stbtt_int8;
typedef unsigned short stbtt_uint16;
typedef signed short stbtt_int16;
typedef unsigned int stbtt_uint32;
typedef signed int stbtt_int32;
#endif
typedef char stbtt__check_size32[sizeof(stbtt_int32) == 4 ? 1 : -1];
typedef char stbtt__check_size16[sizeof(stbtt_int16) == 2 ? 1 : -1];
// e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
#ifndef STBTT_ifloor
#include <math.h>
#define STBTT_ifloor(x) ((int)floor(x))
#define STBTT_iceil(x) ((int)ceil(x))
#endif
#ifndef STBTT_sqrt
#include <math.h>
#define STBTT_sqrt(x) sqrt(x)
#define STBTT_pow(x, y) pow(x, y)
#endif
#ifndef STBTT_fmod
#include <math.h>
#define STBTT_fmod(x, y) fmod(x, y)
#endif
#ifndef STBTT_cos
#include <math.h>
#define STBTT_cos(x) cos(x)
#define STBTT_acos(x) acos(x)
#endif
#ifndef STBTT_fabs
#include <math.h>
#define STBTT_fabs(x) fabs(x)
#endif
// #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
#ifndef STBTT_malloc
#include <stdlib.h>
#define STBTT_malloc(x, u) ((void)(u), malloc(x))
#define STBTT_free(x, u) ((void)(u), free(x))
#endif
#ifndef STBTT_assert
#include <assert.h>
#define STBTT_assert(x) assert(x)
#endif
#ifndef STBTT_strlen
#include <string.h>
#define STBTT_strlen(x) strlen(x)
#endif
#ifndef STBTT_memcpy
#include <string.h>
#define STBTT_memcpy memcpy
#define STBTT_memset memset
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// INTERFACE
////
////
#ifndef __STB_INCLUDE_STB_TRUETYPE_H__
#define __STB_INCLUDE_STB_TRUETYPE_H__
#ifdef STBTT_STATIC
#define STBTT_DEF static
#else
#define STBTT_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
// private structure
typedef struct
{
unsigned char* data;
int cursor;
int size;
} stbtt__buf;
//////////////////////////////////////////////////////////////////////////////
//
// TEXTURE BAKING API
//
// If you use this API, you only have to call two functions ever.
//
typedef struct
{
unsigned short x0, y0, x1, y1; // coordinates of bbox in bitmap
float xoff, yoff, xadvance;
} stbtt_bakedchar;
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char* data, int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char* pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar* chardata); // you allocate this, it's num_chars long
// if return is positive, the first unused row of the bitmap
// if return is negative, returns the negative of the number of characters that fit
// if return is 0, no characters fit and no rows were used
// This uses a very crappy packing.
typedef struct
{
float x0, y0, s0, t0; // top-left
float x1, y1, s1, t1; // bottom-right
} stbtt_aligned_quad;
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar* chardata, int pw, int ph, // same data as above
int char_index, // character to display
float* xpos, float* ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad* q, // output: quad to draw
int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
// Call GetBakedQuad with char_index = 'character - first_char', and it
// creates the quad you need to draw and advances the current position.
//
// The coordinate system used assumes y increases downwards.
//
// Characters will extend both above and below the current position;
// see discussion of "BASELINE" above.
//
// It's inefficient; you might want to c&p it and optimize it.
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char* fontdata, int index, float size, float* ascent, float* descent, float* lineGap);
// Query the font vertical metrics without having to create a font first.
//////////////////////////////////////////////////////////////////////////////
//
// NEW TEXTURE BAKING API
//
// This provides options for packing multiple fonts into one atlas, not
// perfectly but better than nothing.
typedef struct
{
unsigned short x0, y0, x1, y1; // coordinates of bbox in bitmap
float xoff, yoff, xadvance;
float xoff2, yoff2;
} stbtt_packedchar;
typedef struct stbtt_pack_context stbtt_pack_context;
typedef struct stbtt_fontinfo stbtt_fontinfo;
#ifndef STB_RECT_PACK_VERSION
typedef struct stbrp_rect stbrp_rect;
#endif
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context* spc, unsigned char* pixels, int width, int height, int stride_in_bytes, int padding, void* alloc_context);
// Initializes a packing context stored in the passed-in stbtt_pack_context.
// Future calls using this context will pack characters into the bitmap passed
// in here: a 1-channel bitmap that is width * height. stride_in_bytes is
// the distance from one row to the next (or 0 to mean they are packed tightly
// together). "padding" is the amount of padding to leave between each
// character (normally you want '1' for bitmaps you'll use as textures with
// bilinear filtering).
//
// Returns 0 on failure, 1 on success.
STBTT_DEF void stbtt_PackEnd(stbtt_pack_context* spc);
// Cleans up the packing context and frees all memory.
#define STBTT_POINT_SIZE(x) (-(x))
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context* spc, const unsigned char* fontdata, int font_index, float font_size,
int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar* chardata_for_range);
// Creates character bitmaps from the font_index'th font found in fontdata (use
// font_index=0 if you don't know what that is). It creates num_chars_in_range
// bitmaps for characters with unicode values starting at first_unicode_char_in_range
// and increasing. Data for how to render them is stored in chardata_for_range;
// pass these to stbtt_GetPackedQuad to get back renderable quads.
//
// font_size is the full height of the character from ascender to descender,
// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
// and pass that result as 'font_size':
// ..., 20 , ... // font max minus min y is 20 pixels tall
// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
typedef struct
{
float font_size;
int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
int* array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
int num_chars;
stbtt_packedchar* chardata_for_range; // output
unsigned char h_oversample, v_oversample; // don't set these, they're used internally
} stbtt_pack_range;
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context* spc, const unsigned char* fontdata, int font_index, stbtt_pack_range* ranges, int num_ranges);
// Creates character bitmaps from multiple ranges of characters stored in
// ranges. This will usually create a better-packed bitmap than multiple
// calls to stbtt_PackFontRange. Note that you can call this multiple
// times within a single PackBegin/PackEnd.
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context* spc, unsigned int h_oversample, unsigned int v_oversample);
// Oversampling a font increases the quality by allowing higher-quality subpixel
// positioning, and is especially valuable at smaller text sizes.
//
// This function sets the amount of oversampling for all following calls to
// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
// pack context. The default (no oversampling) is achieved by h_oversample=1
// and v_oversample=1. The total number of pixels required is
// h_oversample*v_oversample larger than the default; for example, 2x2
// oversampling requires 4x the storage of 1x1. For best results, render
// oversampled textures with bilinear filtering. Look at the readme in
// stb/tests/oversample for information about oversampled fonts
//
// To use with PackFontRangesGather etc., you must set it before calls
// call to PackFontRangesGatherRects.
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context* spc, int skip);
// If skip != 0, this tells stb_truetype to skip any codepoints for which
// there is no corresponding glyph. If skip=0, which is the default, then
// codepoints without a glyph recived the font's "missing character" glyph,
// typically an empty box by convention.
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar* chardata, int pw, int ph, // same data as above
int char_index, // character to display
float* xpos, float* ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad* q, // output: quad to draw
int align_to_integer);
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context* spc, const stbtt_fontinfo* info, stbtt_pack_range* ranges, int num_ranges, stbrp_rect* rects);
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context* spc, stbrp_rect* rects, int num_rects);
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context* spc, const stbtt_fontinfo* info, stbtt_pack_range* ranges, int num_ranges, stbrp_rect* rects);
// Calling these functions in sequence is roughly equivalent to calling
// stbtt_PackFontRanges(). If you more control over the packing of multiple
// fonts, or if you want to pack custom data into a font texture, take a look
// at the source to of stbtt_PackFontRanges() and create a custom version
// using these functions, e.g. call GatherRects multiple times,
// building up a single array of rects, then call PackRects once,
// then call RenderIntoRects repeatedly. This may result in a
// better packing than calling PackFontRanges multiple times
// (or it may not).
// this is an opaque structure that you shouldn't mess with which holds
// all the context needed from PackBegin to PackEnd.
struct stbtt_pack_context
{
void* user_allocator_context;
void* pack_info;
int width;
int height;
int stride_in_bytes;
int padding;
int skip_missing;
unsigned int h_oversample, v_oversample;
unsigned char* pixels;
void* nodes;
};
//////////////////////////////////////////////////////////////////////////////
//
// FONT LOADING
//
//
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char* data);
// This function will determine the number of fonts in a font file. TrueType
// collection (.ttc) files may contain multiple fonts, while TrueType font
// (.ttf) files only contain one font. The number of fonts can be used for
// indexing with the previous function where the index is between zero and one
// less than the total fonts. If an error occurs, -1 is returned.
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char* data, int index);
// Each .ttf/.ttc file may have more than one font. Each font has a sequential
// index number starting from 0. Call this function to get the font offset for
// a given index; it returns -1 if the index is out of range. A regular .ttf
// file will only define one font and it always be at offset 0, so it will
// return '0' for index 0, and -1 for all other indices.
// The following structure is defined publicly so you can declare one on
// the stack or as a global or etc, but you should treat it as opaque.
struct stbtt_fontinfo
{
void* userdata;
unsigned char* data; // pointer to .ttf file
int fontstart; // offset of start of font
int numGlyphs; // number of glyphs, needed for range checking
int loca, head, glyf, hhea, hmtx, kern, gpos, svg; // table locations as offset from start of .ttf
int index_map; // a cmap mapping for our chosen character encoding
int indexToLocFormat; // format needed to map from glyph index to glyph
stbtt__buf cff; // cff font data
stbtt__buf charstrings; // the charstring index
stbtt__buf gsubrs; // global charstring subroutines index
stbtt__buf subrs; // private charstring subroutines index
stbtt__buf fontdicts; // array of font dicts
stbtt__buf fdselect; // map from glyph to fontdict
};
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo* info, const unsigned char* data, int offset);
// Given an offset into the file that defines a font, this function builds
// the necessary cached info for the rest of the system. You must allocate
// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
// need to do anything special to free it, because the contents are pure
// value data with no additional data structures. Returns 0 on failure.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER TO GLYPH-INDEX CONVERSIOn
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo* info, int unicode_codepoint);
// If you're going to perform multiple operations on the same character
// and you want a speed-up, call this function with the character you're
// going to process, then use glyph-based functions instead of the
// codepoint-based functions.
// Returns 0 if the character codepoint is not defined in the font.
//////////////////////////////////////////////////////////////////////////////
//
// CHARACTER PROPERTIES
//
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo* info, float pixels);
// computes a scale factor to produce a font whose "height" is 'pixels' tall.
// Height is measured as the distance from the highest ascender to the lowest
// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
// and computing:
// scale = pixels / (ascent - descent)
// so if you prefer to measure height by the ascent only, use a similar calculation.
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo* info, float pixels);
// computes a scale factor to produce a font whose EM size is mapped to
// 'pixels' tall. This is probably what traditional APIs compute, but
// I'm not positive.
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo* info, int* ascent, int* descent, int* lineGap);
// ascent is the coordinate above the baseline the font extends; descent
// is the coordinate below the baseline the font extends (i.e. it is typically negative)
// lineGap is the spacing between one row's descent and the next row's ascent...
// so you should advance the vertical position by "*ascent - *descent + *lineGap"
// these are expressed in unscaled coordinates, so you must multiply by
// the scale factor for a given size
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo* info, int* typoAscent, int* typoDescent, int* typoLineGap);
// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2
// table (specific to MS/Windows TTF files).
//
// Returns 1 on success (table present), 0 on failure.
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo* info, int* x0, int* y0, int* x1, int* y1);
// the bounding box around all possible characters
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo* info, int codepoint, int* advanceWidth, int* leftSideBearing);
// leftSideBearing is the offset from the current horizontal position to the left edge of the character
// advanceWidth is the offset from the current horizontal position to the next horizontal position
// these are expressed in unscaled coordinates
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo* info, int ch1, int ch2);
// an additional amount to add to the 'advance' value between ch1 and ch2
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo* info, int codepoint, int* x0, int* y0, int* x1, int* y1);
// Gets the bounding box of the visible part of the glyph, in unscaled coordinates
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo* info, int glyph_index, int* advanceWidth, int* leftSideBearing);
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo* info, int glyph1, int glyph2);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo* info, int glyph_index, int* x0, int* y0, int* x1, int* y1);
// as above, but takes one or more glyph indices for greater efficiency
typedef struct stbtt_kerningentry
{
int glyph1; // use stbtt_FindGlyphIndex
int glyph2;
int advance;
} stbtt_kerningentry;
STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo* info);
STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo* info, stbtt_kerningentry* table, int table_length);
// Retrieves a complete list of all of the kerning pairs provided by the font
// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write.
// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1)
//////////////////////////////////////////////////////////////////////////////
//
// GLYPH SHAPES (you probably don't need these, but they have to go before
// the bitmaps for C declaration-order reasons)
//
#ifndef STBTT_vmove // you can predefine these to use different values (but why?)
enum
{
STBTT_vmove = 1,
STBTT_vline,
STBTT_vcurve,
STBTT_vcubic
};
#endif
#ifndef stbtt_vertex // you can predefine this to use different values
// (we share this with other code at RAD)
#define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
typedef struct
{
stbtt_vertex_type x, y, cx, cy, cx1, cy1;
unsigned char type, padding;
} stbtt_vertex;
#endif
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo* info, int glyph_index);
// returns non-zero if nothing is drawn for this glyph
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo* info, int unicode_codepoint, stbtt_vertex** vertices);
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo* info, int glyph_index, stbtt_vertex** vertices);
// returns # of vertices and fills *vertices with the pointer to them
// these are expressed in "unscaled" coordinates
//
// The shape is a series of contours. Each one starts with
// a STBTT_moveto, then consists of a series of mixed
// STBTT_lineto and STBTT_curveto segments. A lineto
// draws a line from previous endpoint to its x,y; a curveto
// draws a quadratic bezier from previous endpoint to
// its x,y, using cx,cy as the bezier control point.
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo* info, stbtt_vertex* vertices);
// frees the data allocated above
STBTT_DEF unsigned char* stbtt_FindSVGDoc(const stbtt_fontinfo* info, int gl);
STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo* info, int unicode_codepoint, const char** svg);
STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo* info, int gl, const char** svg);
// fills svg with the character's SVG data.
// returns data size or 0 if SVG not found.
//////////////////////////////////////////////////////////////////////////////
//
// BITMAP RENDERING
//
STBTT_DEF void stbtt_FreeBitmap(unsigned char* bitmap, void* userdata);
// frees the bitmap allocated below
STBTT_DEF unsigned char* stbtt_GetCodepointBitmap(const stbtt_fontinfo* info, float scale_x, float scale_y, int codepoint, int* width, int* height, int* xoff, int* yoff);
// allocates a large-enough single-channel 8bpp bitmap and renders the
// specified character/glyph at the specified scale into it, with
// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
// *width & *height are filled out with the width & height of the bitmap,
// which is stored left-to-right, top-to-bottom.
//
// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
STBTT_DEF unsigned char* stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo* info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int* width, int* height, int* xoff, int* yoff);
// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
// width and height and positioning info for it first.
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
// shift for the character
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float* sub_x, float* sub_y, int codepoint);
// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering
// is performed (see stbtt_PackSetOversampling)
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo* font, int codepoint, float scale_x, float scale_y, int* ix0, int* iy0, int* ix1, int* iy1);
// get the bbox of the bitmap centered around the glyph origin; so the
// bitmap width is ix1-ix0, height is iy1-iy0, and location to place
// the bitmap top left is (leftSideBearing*scale,iy0).
// (Note that the bitmap uses y-increases-down, but the shape uses
// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo* font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int* ix0, int* iy0, int* ix1, int* iy1);
// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
// shift for the character
// the following functions are equivalent to the above functions, but operate
// on glyph indices instead of Unicode codepoints (for efficiency)
STBTT_DEF unsigned char* stbtt_GetGlyphBitmap(const stbtt_fontinfo* info, float scale_x, float scale_y, int glyph, int* width, int* height, int* xoff, int* yoff);
STBTT_DEF unsigned char* stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo* info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int* width, int* height, int* xoff, int* yoff);
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float* sub_x, float* sub_y, int glyph);
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo* font, int glyph, float scale_x, float scale_y, int* ix0, int* iy0, int* ix1, int* iy1);
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo* font, int glyph, float scale_x, float scale_y, float shift_x, float shift_y, int* ix0, int* iy0, int* ix1, int* iy1);
// @TODO: don't expose this structure
typedef struct
{
int w, h, stride;
unsigned char* pixels;
} stbtt__bitmap;
// rasterize a shape with quadratic beziers into a bitmap
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap* result, // 1-channel bitmap to draw into
float flatness_in_pixels, // allowable error of curve in pixels
stbtt_vertex* vertices, // array of vertices defining shape
int num_verts, // number of vertices in above array
float scale_x, float scale_y, // scale applied to input vertices
float shift_x, float shift_y, // translation applied to input vertices
int x_off, int y_off, // another translation applied to input
int invert, // if non-zero, vertically flip shape
void* userdata); // context for to STBTT_MALLOC
//////////////////////////////////////////////////////////////////////////////
//
// Signed Distance Function (or Field) rendering
STBTT_DEF void stbtt_FreeSDF(unsigned char* bitmap, void* userdata);
// frees the SDF bitmap allocated below
STBTT_DEF unsigned char* stbtt_GetGlyphSDF(const stbtt_fontinfo* info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int* width, int* height, int* xoff, int* yoff);
STBTT_DEF unsigned char* stbtt_GetCodepointSDF(const stbtt_fontinfo* info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int* width, int* height, int* xoff, int* yoff);
// These functions compute a discretized SDF field for a single character, suitable for storing
// in a single-channel texture, sampling with bilinear filtering, and testing against
// larger than some threshold to produce scalable fonts.
// info -- the font
// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap
// glyph/codepoint -- the character to generate the SDF for
// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0),
// which allows effects like bit outlines
// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)
// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale)
// if positive, > onedge_value is inside; if negative, < onedge_value is inside
// width,height -- output height & width of the SDF bitmap (including padding)
// xoff,yoff -- output origin of the character
// return value -- a 2D array of bytes 0..255, width*height in size
//
// pixel_dist_scale & onedge_value are a scale & bias that allows you to make
// optimal use of the limited 0..255 for your application, trading off precision
// and special effects. SDF values outside the range 0..255 are clamped to 0..255.
//
// Example:
// scale = stbtt_ScaleForPixelHeight(22)
// padding = 5
// onedge_value = 180
// pixel_dist_scale = 180/5.0 = 36.0
//
// This will create an SDF bitmap in which the character is about 22 pixels
// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled
// shape, sample the SDF at each pixel and fill the pixel if the SDF value
// is greater than or equal to 180/255. (You'll actually want to antialias,
// which is beyond the scope of this example.) Additionally, you can compute
// offset outlines (e.g. to stroke the character border inside & outside,
// or only outside). For example, to fill outside the character up to 3 SDF
// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above
// choice of variables maps a range from 5 pixels outside the shape to
// 2 pixels inside the shape to 0..255; this is intended primarily for apply
// outside effects only (the interior range is needed to allow proper
// antialiasing of the font at *smaller* sizes)
//
// The function computes the SDF analytically at each SDF pixel, not by e.g.
// building a higher-res bitmap and approximating it. In theory the quality
// should be as high as possible for an SDF of this size & representation, but
// unclear if this is true in practice (perhaps building a higher-res bitmap
// and computing from that can allow drop-out prevention).
//
// The algorithm has not been optimized at all, so expect it to be slow
// if computing lots of characters or very large sizes.
//////////////////////////////////////////////////////////////////////////////
//
// Finding the right font...
//
// You should really just solve this offline, keep your own tables
// of what font is what, and don't try to get it out of the .ttf file.
// That's because getting it out of the .ttf file is really hard, because
// the names in the file can appear in many possible encodings, in many
// possible languages, and e.g. if you need a case-insensitive comparison,
// the details of that depend on the encoding & language in a complex way
// (actually underspecified in truetype, but also gigantic).
//
// But you can use the provided functions in two possible ways:
// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
// unicode-encoded names to try to find the font you want;
// you can run this before calling stbtt_InitFont()
//
// stbtt_GetFontNameString() lets you get any of the various strings
// from the file yourself and do your own comparisons on them.
// You have to have called stbtt_InitFont() first.
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char* fontdata, const char* name, int flags);
// returns the offset (not index) of the font that matches, or -1 if none
// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
// if you use any other flag, use a font name like "Arial"; this checks
// the 'macStyle' header field; i don't know if fonts set this consistently
#define STBTT_MACSTYLE_DONTCARE 0
#define STBTT_MACSTYLE_BOLD 1
#define STBTT_MACSTYLE_ITALIC 2
#define STBTT_MACSTYLE_UNDERSCORE 4
#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char* s1, int len1, const char* s2, int len2);
// returns 1/0 whether the first string interpreted as utf8 is identical to
// the second string interpreted as big-endian utf16... useful for strings from next func
STBTT_DEF const char* stbtt_GetFontNameString(const stbtt_fontinfo* font, int* length, int platformID, int encodingID, int languageID, int nameID);
// returns the string (which may be big-endian double byte, e.g. for unicode)
// and puts the length in bytes in *length.
//
// some of the values for the IDs are below; for more see the truetype spec:
// path_to_url
// path_to_url
enum
{ // platformID
STBTT_PLATFORM_ID_UNICODE = 0,
STBTT_PLATFORM_ID_MAC = 1,
STBTT_PLATFORM_ID_ISO = 2,
STBTT_PLATFORM_ID_MICROSOFT = 3
};
enum
{ // encodingID for STBTT_PLATFORM_ID_UNICODE
STBTT_UNICODE_EID_UNICODE_1_0 = 0,
STBTT_UNICODE_EID_UNICODE_1_1 = 1,
STBTT_UNICODE_EID_ISO_10646 = 2,
STBTT_UNICODE_EID_UNICODE_2_0_BMP = 3,
STBTT_UNICODE_EID_UNICODE_2_0_FULL = 4
};
enum
{ // encodingID for STBTT_PLATFORM_ID_MICROSOFT
STBTT_MS_EID_SYMBOL = 0,
STBTT_MS_EID_UNICODE_BMP = 1,
STBTT_MS_EID_SHIFTJIS = 2,
STBTT_MS_EID_UNICODE_FULL = 10
};
enum
{ // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
STBTT_MAC_EID_ROMAN = 0,
STBTT_MAC_EID_ARABIC = 4,
STBTT_MAC_EID_JAPANESE = 1,
STBTT_MAC_EID_HEBREW = 5,
STBTT_MAC_EID_CHINESE_TRAD = 2,
STBTT_MAC_EID_GREEK = 6,
STBTT_MAC_EID_KOREAN = 3,
STBTT_MAC_EID_RUSSIAN = 7
};
enum
{ // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
// problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
STBTT_MS_LANG_ENGLISH = 0x0409,
STBTT_MS_LANG_ITALIAN = 0x0410,
STBTT_MS_LANG_CHINESE = 0x0804,
STBTT_MS_LANG_JAPANESE = 0x0411,
STBTT_MS_LANG_DUTCH = 0x0413,
STBTT_MS_LANG_KOREAN = 0x0412,
STBTT_MS_LANG_FRENCH = 0x040c,
STBTT_MS_LANG_RUSSIAN = 0x0419,
STBTT_MS_LANG_GERMAN = 0x0407,
STBTT_MS_LANG_SPANISH = 0x0409,
STBTT_MS_LANG_HEBREW = 0x040d,
STBTT_MS_LANG_SWEDISH = 0x041D
};
enum
{ // languageID for STBTT_PLATFORM_ID_MAC
STBTT_MAC_LANG_ENGLISH = 0,
STBTT_MAC_LANG_JAPANESE = 11,
STBTT_MAC_LANG_ARABIC = 12,
STBTT_MAC_LANG_KOREAN = 23,
STBTT_MAC_LANG_DUTCH = 4,
STBTT_MAC_LANG_RUSSIAN = 32,
STBTT_MAC_LANG_FRENCH = 1,
STBTT_MAC_LANG_SPANISH = 6,
STBTT_MAC_LANG_GERMAN = 2,
STBTT_MAC_LANG_SWEDISH = 5,
STBTT_MAC_LANG_HEBREW = 10,
STBTT_MAC_LANG_CHINESE_SIMPLIFIED = 33,
STBTT_MAC_LANG_ITALIAN = 3,
STBTT_MAC_LANG_CHINESE_TRAD = 19
};
#ifdef __cplusplus
}
#endif
#endif // __STB_INCLUDE_STB_TRUETYPE_H__
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////
//// IMPLEMENTATION
////
////
#ifdef STB_TRUETYPE_IMPLEMENTATION
#ifndef STBTT_MAX_OVERSAMPLE
#define STBTT_MAX_OVERSAMPLE 8
#endif
#if STBTT_MAX_OVERSAMPLE > 255
#error "STBTT_MAX_OVERSAMPLE cannot be > 255"
#endif
typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE - 1)) == 0 ? 1 : -1];
#ifndef STBTT_RASTERIZER_VERSION
#define STBTT_RASTERIZER_VERSION 2
#endif
#ifdef _MSC_VER
#define STBTT__NOTUSED(v) (void)(v)
#else
#define STBTT__NOTUSED(v) (void)sizeof(v)
#endif
//////////////////////////////////////////////////////////////////////////
//
// stbtt__buf helpers to parse data from file
//
static stbtt_uint8 stbtt__buf_get8(stbtt__buf* b)
{
if (b->cursor >= b->size)
return 0;
return b->data[b->cursor++];
}
static stbtt_uint8 stbtt__buf_peek8(stbtt__buf* b)
{
if (b->cursor >= b->size)
return 0;
return b->data[b->cursor];
}
static void stbtt__buf_seek(stbtt__buf* b, int o)
{
STBTT_assert(!(o > b->size || o < 0));
b->cursor = (o > b->size || o < 0) ? b->size : o;
}
static void stbtt__buf_skip(stbtt__buf* b, int o)
{
stbtt__buf_seek(b, b->cursor + o);
}
static stbtt_uint32 stbtt__buf_get(stbtt__buf* b, int n)
{
stbtt_uint32 v = 0;
int i;
STBTT_assert(n >= 1 && n <= 4);
for (i = 0; i < n; i++)
v = (v << 8) | stbtt__buf_get8(b);
return v;
}
static stbtt__buf stbtt__new_buf(const void* p, size_t size)
{
stbtt__buf r;
STBTT_assert(size < 0x40000000);
r.data = (stbtt_uint8*)p;
r.size = (int)size;
r.cursor = 0;
return r;
}
#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
static stbtt__buf stbtt__buf_range(const stbtt__buf* b, int o, int s)
{
stbtt__buf r = stbtt__new_buf(NULL, 0);
if (o < 0 || s < 0 || o > b->size || s > b->size - o)
return r;
r.data = b->data + o;
r.size = s;
return r;
}
static stbtt__buf stbtt__cff_get_index(stbtt__buf* b)
{
int count, start, offsize;
start = b->cursor;
count = stbtt__buf_get16(b);
if (count)
{
offsize = stbtt__buf_get8(b);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(b, offsize * count);
stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
}
return stbtt__buf_range(b, start, b->cursor - start);
}
static stbtt_uint32 stbtt__cff_int(stbtt__buf* b)
{
int b0 = stbtt__buf_get8(b);
if (b0 >= 32 && b0 <= 246)
return b0 - 139;
else if (b0 >= 247 && b0 <= 250)
return (b0 - 247) * 256 + stbtt__buf_get8(b) + 108;
else if (b0 >= 251 && b0 <= 254)
return -(b0 - 251) * 256 - stbtt__buf_get8(b) - 108;
else if (b0 == 28)
return stbtt__buf_get16(b);
else if (b0 == 29)
return stbtt__buf_get32(b);
STBTT_assert(0);
return 0;
}
static void stbtt__cff_skip_operand(stbtt__buf* b)
{
int v, b0 = stbtt__buf_peek8(b);
STBTT_assert(b0 >= 28);
if (b0 == 30)
{
stbtt__buf_skip(b, 1);
while (b->cursor < b->size)
{
v = stbtt__buf_get8(b);
if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
break;
}
}
else
{
stbtt__cff_int(b);
}
}
static stbtt__buf stbtt__dict_get(stbtt__buf* b, int key)
{
stbtt__buf_seek(b, 0);
while (b->cursor < b->size)
{
int start = b->cursor, end, op;
while (stbtt__buf_peek8(b) >= 28)
stbtt__cff_skip_operand(b);
end = b->cursor;
op = stbtt__buf_get8(b);
if (op == 12)
op = stbtt__buf_get8(b) | 0x100;
if (op == key)
return stbtt__buf_range(b, start, end - start);
}
return stbtt__buf_range(b, 0, 0);
}
static void stbtt__dict_get_ints(stbtt__buf* b, int key, int outcount, stbtt_uint32* out)
{
int i;
stbtt__buf operands = stbtt__dict_get(b, key);
for (i = 0; i < outcount && operands.cursor < operands.size; i++)
out[i] = stbtt__cff_int(&operands);
}
static int stbtt__cff_index_count(stbtt__buf* b)
{
stbtt__buf_seek(b, 0);
return stbtt__buf_get16(b);
}
static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
{
int count, offsize, start, end;
stbtt__buf_seek(&b, 0);
count = stbtt__buf_get16(&b);
offsize = stbtt__buf_get8(&b);
STBTT_assert(i >= 0 && i < count);
STBTT_assert(offsize >= 1 && offsize <= 4);
stbtt__buf_skip(&b, i * offsize);
start = stbtt__buf_get(&b, offsize);
end = stbtt__buf_get(&b, offsize);
return stbtt__buf_range(&b, 2 + (count + 1) * offsize + start, end - start);
}
//////////////////////////////////////////////////////////////////////////
//
// accessors to parse data from file
//
// on platforms that don't allow misaligned reads, if we want to allow
// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
#define ttBYTE(p) (*(stbtt_uint8*)(p))
#define ttCHAR(p) (*(stbtt_int8*)(p))
#define ttFixed(p) ttLONG(p)
static stbtt_uint16 ttUSHORT(stbtt_uint8* p)
{
return p[0] * 256 + p[1];
}
static stbtt_int16 ttSHORT(stbtt_uint8* p) { return p[0] * 256 + p[1]; }
static stbtt_uint32 ttULONG(stbtt_uint8* p) { return (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3]; }
static stbtt_int32 ttLONG(stbtt_uint8* p) { return (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3]; }
#define stbtt_tag4(p, c0, c1, c2, c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
#define stbtt_tag(p, str) stbtt_tag4(p, str[0], str[1], str[2], str[3])
static int stbtt__isfont(stbtt_uint8* font)
{
// check the version number
if (stbtt_tag4(font, '1', 0, 0, 0))
return 1; // TrueType 1
if (stbtt_tag(font, "typ1"))
return 1; // TrueType with type 1 font -- we don't support this!
if (stbtt_tag(font, "OTTO"))
return 1; // OpenType with CFF
if (stbtt_tag4(font, 0, 1, 0, 0))
return 1; // OpenType 1.0
if (stbtt_tag(font, "true"))
return 1; // Apple specification for TrueType fonts
return 0;
}
// @OPTIMIZE: binary search
static stbtt_uint32 stbtt__find_table(stbtt_uint8* data, stbtt_uint32 fontstart, const char* tag)
{
stbtt_int32 num_tables = ttUSHORT(data + fontstart + 4);
stbtt_uint32 tabledir = fontstart + 12;
stbtt_int32 i;
for (i = 0; i < num_tables; ++i)
{
stbtt_uint32 loc = tabledir + 16 * i;
if (stbtt_tag(data + loc + 0, tag))
return ttULONG(data + loc + 8);
}
return 0;
}
static int stbtt_GetFontOffsetForIndex_internal(unsigned char* font_collection, int index)
{
// if it's just a font, there's only one valid index
if (stbtt__isfont(font_collection))
return index == 0 ? 0 : -1;
// check if it's a TTC
if (stbtt_tag(font_collection, "ttcf"))
{
// version 1?
if (ttULONG(font_collection + 4) == 0x00010000 || ttULONG(font_collection + 4) == 0x00020000)
{
stbtt_int32 n = ttLONG(font_collection + 8);
if (index >= n)
return -1;
return ttULONG(font_collection + 12 + index * 4);
}
}
return -1;
}
static int stbtt_GetNumberOfFonts_internal(unsigned char* font_collection)
{
// if it's just a font, there's only one valid font
if (stbtt__isfont(font_collection))
return 1;
// check if it's a TTC
if (stbtt_tag(font_collection, "ttcf"))
{
// version 1?
if (ttULONG(font_collection + 4) == 0x00010000 || ttULONG(font_collection + 4) == 0x00020000)
{
return ttLONG(font_collection + 8);
}
}
return 0;
}
static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
{
stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
stbtt__buf pdict;
stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
if (!private_loc[1] || !private_loc[0])
return stbtt__new_buf(NULL, 0);
pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
if (!subrsoff)
return stbtt__new_buf(NULL, 0);
stbtt__buf_seek(&cff, private_loc[1] + subrsoff);
return stbtt__cff_get_index(&cff);
}
// since most people won't use this, find this table the first time it's needed
static int stbtt__get_svg(stbtt_fontinfo* info)
{
stbtt_uint32 t;
if (info->svg < 0)
{
t = stbtt__find_table(info->data, info->fontstart, "SVG ");
if (t)
{
stbtt_uint32 offset = ttULONG(info->data + t + 2);
info->svg = t + offset;
}
else
{
info->svg = 0;
}
}
return info->svg;
}
static int stbtt_InitFont_internal(stbtt_fontinfo* info, unsigned char* data, int fontstart)
{
stbtt_uint32 cmap, t;
stbtt_int32 i, numTables;
info->data = data;
info->fontstart = fontstart;
info->cff = stbtt__new_buf(NULL, 0);
cmap = stbtt__find_table(data, fontstart, "cmap"); // required
info->loca = stbtt__find_table(data, fontstart, "loca"); // required
info->head = stbtt__find_table(data, fontstart, "head"); // required
info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required
if (!cmap || !info->head || !info->hhea || !info->hmtx)
return 0;
if (info->glyf)
{
// required for truetype
if (!info->loca)
return 0;
}
else
{
// initialization for CFF / Type2 fonts (OTF)
stbtt__buf b, topdict, topdictidx;
stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
stbtt_uint32 cff;
cff = stbtt__find_table(data, fontstart, "CFF ");
if (!cff)
return 0;
info->fontdicts = stbtt__new_buf(NULL, 0);
info->fdselect = stbtt__new_buf(NULL, 0);
// @TODO this should use size from table (not 512MB)
info->cff = stbtt__new_buf(data + cff, 512 * 1024 * 1024);
b = info->cff;
// read the header
stbtt__buf_skip(&b, 2);
stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
// @TODO the name INDEX could list multiple fonts,
// but we just use the first one.
stbtt__cff_get_index(&b); // name INDEX
topdictidx = stbtt__cff_get_index(&b);
topdict = stbtt__cff_index_get(topdictidx, 0);
stbtt__cff_get_index(&b); // string INDEX
info->gsubrs = stbtt__cff_get_index(&b);
stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
info->subrs = stbtt__get_subrs(b, topdict);
// we only support Type 2 charstrings
if (cstype != 2)
return 0;
if (charstrings == 0)
return 0;
if (fdarrayoff)
{
// looks like a CID font
if (!fdselectoff)
return 0;
stbtt__buf_seek(&b, fdarrayoff);
info->fontdicts = stbtt__cff_get_index(&b);
info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size - fdselectoff);
}
stbtt__buf_seek(&b, charstrings);
info->charstrings = stbtt__cff_get_index(&b);
}
t = stbtt__find_table(data, fontstart, "maxp");
if (t)
info->numGlyphs = ttUSHORT(data + t + 4);
else
info->numGlyphs = 0xffff;
info->svg = -1;
// find a cmap encoding table we understand *now* to avoid searching
// later. (todo: could make this installable)
// the same regardless of glyph.
numTables = ttUSHORT(data + cmap + 2);
info->index_map = 0;
for (i = 0; i < numTables; ++i)
{
stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
// find an encoding we understand:
switch (ttUSHORT(data + encoding_record))
{
case STBTT_PLATFORM_ID_MICROSOFT:
switch (ttUSHORT(data + encoding_record + 2))
{
case STBTT_MS_EID_UNICODE_BMP:
case STBTT_MS_EID_UNICODE_FULL:
// MS/Unicode
info->index_map = cmap + ttULONG(data + encoding_record + 4);
break;
}
break;
case STBTT_PLATFORM_ID_UNICODE:
// Mac/iOS has these
// all the encodingIDs are unicode, so we don't bother to check it
info->index_map = cmap + ttULONG(data + encoding_record + 4);
break;
}
}
if (info->index_map == 0)
return 0;
info->indexToLocFormat = ttUSHORT(data + info->head + 50);
return 1;
}
STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo* info, int unicode_codepoint)
{
stbtt_uint8* data = info->data;
stbtt_uint32 index_map = info->index_map;
stbtt_uint16 format = ttUSHORT(data + index_map + 0);
if (format == 0)
{ // apple byte encoding
stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
if (unicode_codepoint < bytes - 6)
return ttBYTE(data + index_map + 6 + unicode_codepoint);
return 0;
}
else if (format == 6)
{
stbtt_uint32 first = ttUSHORT(data + index_map + 6);
stbtt_uint32 count = ttUSHORT(data + index_map + 8);
if ((stbtt_uint32)unicode_codepoint >= first && (stbtt_uint32)unicode_codepoint < first + count)
return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first) * 2);
return 0;
}
else if (format == 2)
{
STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
return 0;
}
else if (format == 4)
{ // standard mapping for windows fonts: binary search collection of ranges
stbtt_uint16 segcount = ttUSHORT(data + index_map + 6) >> 1;
stbtt_uint16 searchRange = ttUSHORT(data + index_map + 8) >> 1;
stbtt_uint16 entrySelector = ttUSHORT(data + index_map + 10);
stbtt_uint16 rangeShift = ttUSHORT(data + index_map + 12) >> 1;
// do a binary search of the segments
stbtt_uint32 endCount = index_map + 14;
stbtt_uint32 search = endCount;
if (unicode_codepoint > 0xffff)
return 0;
// they lie from endCount .. endCount + segCount
// but searchRange is the nearest power of two, so...
if (unicode_codepoint >= ttUSHORT(data + search + rangeShift * 2))
search += rangeShift * 2;
// now decrement to bias correctly to find smallest
search -= 2;
while (entrySelector)
{
stbtt_uint16 end;
searchRange >>= 1;
end = ttUSHORT(data + search + searchRange * 2);
if (unicode_codepoint > end)
search += searchRange * 2;
--entrySelector;
}
search += 2;
{
stbtt_uint16 offset, start, last;
stbtt_uint16 item = (stbtt_uint16)((search - endCount) >> 1);
start = ttUSHORT(data + index_map + 14 + segcount * 2 + 2 + 2 * item);
last = ttUSHORT(data + endCount + 2 * item);
if (unicode_codepoint < start || unicode_codepoint > last)
return 0;
offset = ttUSHORT(data + index_map + 14 + segcount * 6 + 2 + 2 * item);
if (offset == 0)
return (stbtt_uint16)(unicode_codepoint + ttSHORT(data + index_map + 14 + segcount * 4 + 2 + 2 * item));
return ttUSHORT(data + offset + (unicode_codepoint - start) * 2 + index_map + 14 + segcount * 6 + 2 + 2 * item);
}
}
else if (format == 12 || format == 13)
{
stbtt_uint32 ngroups = ttULONG(data + index_map + 12);
stbtt_int32 low, high;
low = 0;
high = (stbtt_int32)ngroups;
// Binary search the right group.
while (low < high)
{
stbtt_int32 mid = low + ((high - low) >> 1); // rounds down, so low <= mid < high
stbtt_uint32 start_char = ttULONG(data + index_map + 16 + mid * 12);
stbtt_uint32 end_char = ttULONG(data + index_map + 16 + mid * 12 + 4);
if ((stbtt_uint32)unicode_codepoint < start_char)
high = mid;
else if ((stbtt_uint32)unicode_codepoint > end_char)
low = mid + 1;
else
{
stbtt_uint32 start_glyph = ttULONG(data + index_map + 16 + mid * 12 + 8);
if (format == 12)
return start_glyph + unicode_codepoint - start_char;
else // format == 13
return start_glyph;
}
}
return 0; // not found
}
// @TODO
STBTT_assert(0);
return 0;
}
STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo* info, int unicode_codepoint, stbtt_vertex** vertices)
{
return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
}
static void stbtt_setvertex(stbtt_vertex* v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
{
v->type = type;
v->x = (stbtt_int16)x;
v->y = (stbtt_int16)y;
v->cx = (stbtt_int16)cx;
v->cy = (stbtt_int16)cy;
}
static int stbtt__GetGlyfOffset(const stbtt_fontinfo* info, int glyph_index)
{
int g1, g2;
STBTT_assert(!info->cff.size);
if (glyph_index >= info->numGlyphs)
return -1; // glyph index out of range
if (info->indexToLocFormat >= 2)
return -1; // unknown index->glyph map format
if (info->indexToLocFormat == 0)
{
g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
}
else
{
g1 = info->glyf + ttULONG(info->data + info->loca + glyph_index * 4);
g2 = info->glyf + ttULONG(info->data + info->loca + glyph_index * 4 + 4);
}
return g1 == g2 ? -1 : g1; // if length is 0, return -1
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo* info, int glyph_index, int* x0, int* y0, int* x1, int* y1);
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo* info, int glyph_index, int* x0, int* y0, int* x1, int* y1)
{
if (info->cff.size)
{
stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
}
else
{
int g = stbtt__GetGlyfOffset(info, glyph_index);
if (g < 0)
return 0;
if (x0)
*x0 = ttSHORT(info->data + g + 2);
if (y0)
*y0 = ttSHORT(info->data + g + 4);
if (x1)
*x1 = ttSHORT(info->data + g + 6);
if (y1)
*y1 = ttSHORT(info->data + g + 8);
}
return 1;
}
STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo* info, int codepoint, int* x0, int* y0, int* x1, int* y1)
{
return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info, codepoint), x0, y0, x1, y1);
}
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo* info, int glyph_index)
{
stbtt_int16 numberOfContours;
int g;
if (info->cff.size)
return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
g = stbtt__GetGlyfOffset(info, glyph_index);
if (g < 0)
return 1;
numberOfContours = ttSHORT(info->data + g);
return numberOfContours == 0;
}
static int stbtt__close_shape(stbtt_vertex* vertices, int num_vertices, int was_off, int start_off,
stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
{
if (start_off)
{
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx + scx) >> 1, (cy + scy) >> 1, cx, cy);
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx, sy, scx, scy);
}
else
{
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx, sy, cx, cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, sx, sy, 0, 0);
}
return num_vertices;
}
static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo* info, int glyph_index, stbtt_vertex** pvertices)
{
stbtt_int16 numberOfContours;
stbtt_uint8* endPtsOfContours;
stbtt_uint8* data = info->data;
stbtt_vertex* vertices = 0;
int num_vertices = 0;
int g = stbtt__GetGlyfOffset(info, glyph_index);
*pvertices = NULL;
if (g < 0)
return 0;
numberOfContours = ttSHORT(data + g);
if (numberOfContours > 0)
{
stbtt_uint8 flags = 0, flagcount;
stbtt_int32 ins, i, j = 0, m, n, next_move, was_off = 0, off, start_off = 0;
stbtt_int32 x, y, cx, cy, sx, sy, scx, scy;
stbtt_uint8* points;
endPtsOfContours = (data + g + 10);
ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
points = data + g + 10 + numberOfContours * 2 + 2 + ins;
n = 1 + ttUSHORT(endPtsOfContours + numberOfContours * 2 - 2);
m = n + 2 * numberOfContours; // a loose bound on how many vertices we might need
vertices = (stbtt_vertex*)STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
if (vertices == 0)
return 0;
next_move = 0;
flagcount = 0;
// in first pass, we load uninterpreted data into the allocated array
// above, shifted to the end of the array so we won't overwrite it when
// we create our final data starting from the front
off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
// first load flags
for (i = 0; i < n; ++i)
{
if (flagcount == 0)
{
flags = *points++;
if (flags & 8)
flagcount = *points++;
}
else
--flagcount;
vertices[off + i].type = flags;
}
// now load x coordinates
x = 0;
for (i = 0; i < n; ++i)
{
flags = vertices[off + i].type;
if (flags & 2)
{
stbtt_int16 dx = *points++;
x += (flags & 16) ? dx : -dx; // ???
}
else
{
if (!(flags & 16))
{
x = x + (stbtt_int16)(points[0] * 256 + points[1]);
points += 2;
}
}
vertices[off + i].x = (stbtt_int16)x;
}
// now load y coordinates
y = 0;
for (i = 0; i < n; ++i)
{
flags = vertices[off + i].type;
if (flags & 4)
{
stbtt_int16 dy = *points++;
y += (flags & 32) ? dy : -dy; // ???
}
else
{
if (!(flags & 32))
{
y = y + (stbtt_int16)(points[0] * 256 + points[1]);
points += 2;
}
}
vertices[off + i].y = (stbtt_int16)y;
}
// now convert them to our format
num_vertices = 0;
sx = sy = cx = cy = scx = scy = 0;
for (i = 0; i < n; ++i)
{
flags = vertices[off + i].type;
x = (stbtt_int16)vertices[off + i].x;
y = (stbtt_int16)vertices[off + i].y;
if (next_move == i)
{
if (i != 0)
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy);
// now start the new one
start_off = !(flags & 1);
if (start_off)
{
// if we start off with an off-curve point, then when we need to find a point on the curve
// where we can start, and we need to save some state for when we wraparound.
scx = x;
scy = y;
if (!(vertices[off + i + 1].type & 1))
{
// next point is also a curve point, so interpolate an on-point curve
sx = (x + (stbtt_int32)vertices[off + i + 1].x) >> 1;
sy = (y + (stbtt_int32)vertices[off + i + 1].y) >> 1;
}
else
{
// otherwise just use the next point as our start point
sx = (stbtt_int32)vertices[off + i + 1].x;
sy = (stbtt_int32)vertices[off + i + 1].y;
++i; // we're using point i+1 as the starting point, so skip it
}
}
else
{
sx = x;
sy = y;
}
stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove, sx, sy, 0, 0);
was_off = 0;
next_move = 1 + ttUSHORT(endPtsOfContours + j * 2);
++j;
}
else
{
if (!(flags & 1))
{ // if it's a curve
if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx + x) >> 1, (cy + y) >> 1, cx, cy);
cx = x;
cy = y;
was_off = 1;
}
else
{
if (was_off)
stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x, y, cx, cy);
else
stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x, y, 0, 0);
was_off = 0;
}
}
}
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy);
}
else if (numberOfContours < 0)
{
// Compound shapes.
int more = 1;
stbtt_uint8* comp = data + g + 10;
num_vertices = 0;
vertices = 0;
while (more)
{
stbtt_uint16 flags, gidx;
int comp_num_verts = 0, i;
stbtt_vertex *comp_verts = 0, *tmp = 0;
float mtx[6] = { 1, 0, 0, 1, 0, 0 }, m, n;
flags = ttSHORT(comp);
comp += 2;
gidx = ttSHORT(comp);
comp += 2;
if (flags & 2)
{ // XY values
if (flags & 1)
{ // shorts
mtx[4] = ttSHORT(comp);
comp += 2;
mtx[5] = ttSHORT(comp);
comp += 2;
}
else
{
mtx[4] = ttCHAR(comp);
comp += 1;
mtx[5] = ttCHAR(comp);
comp += 1;
}
}
else
{
// @TODO handle matching point
STBTT_assert(0);
}
if (flags & (1 << 3))
{ // WE_HAVE_A_SCALE
mtx[0] = mtx[3] = ttSHORT(comp) / 16384.0f;
comp += 2;
mtx[1] = mtx[2] = 0;
}
else if (flags & (1 << 6))
{ // WE_HAVE_AN_X_AND_YSCALE
mtx[0] = ttSHORT(comp) / 16384.0f;
comp += 2;
mtx[1] = mtx[2] = 0;
mtx[3] = ttSHORT(comp) / 16384.0f;
comp += 2;
}
else if (flags & (1 << 7))
{ // WE_HAVE_A_TWO_BY_TWO
mtx[0] = ttSHORT(comp) / 16384.0f;
comp += 2;
mtx[1] = ttSHORT(comp) / 16384.0f;
comp += 2;
mtx[2] = ttSHORT(comp) / 16384.0f;
comp += 2;
mtx[3] = ttSHORT(comp) / 16384.0f;
comp += 2;
}
// Find transformation scales.
m = (float)STBTT_sqrt(mtx[0] * mtx[0] + mtx[1] * mtx[1]);
n = (float)STBTT_sqrt(mtx[2] * mtx[2] + mtx[3] * mtx[3]);
// Get indexed glyph.
comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
if (comp_num_verts > 0)
{
// Transform vertices.
for (i = 0; i < comp_num_verts; ++i)
{
stbtt_vertex* v = &comp_verts[i];
stbtt_vertex_type x, y;
x = v->x;
y = v->y;
v->x = (stbtt_vertex_type)(m * (mtx[0] * x + mtx[2] * y + mtx[4]));
v->y = (stbtt_vertex_type)(n * (mtx[1] * x + mtx[3] * y + mtx[5]));
x = v->cx;
y = v->cy;
v->cx = (stbtt_vertex_type)(m * (mtx[0] * x + mtx[2] * y + mtx[4]));
v->cy = (stbtt_vertex_type)(n * (mtx[1] * x + mtx[3] * y + mtx[5]));
}
// Append vertices.
tmp = (stbtt_vertex*)STBTT_malloc((num_vertices + comp_num_verts) * sizeof(stbtt_vertex), info->userdata);
if (!tmp)
{
if (vertices)
STBTT_free(vertices, info->userdata);
if (comp_verts)
STBTT_free(comp_verts, info->userdata);
return 0;
}
if (num_vertices > 0 && vertices)
STBTT_memcpy(tmp, vertices, num_vertices * sizeof(stbtt_vertex));
STBTT_memcpy(tmp + num_vertices, comp_verts, comp_num_verts * sizeof(stbtt_vertex));
if (vertices)
STBTT_free(vertices, info->userdata);
vertices = tmp;
STBTT_free(comp_verts, info->userdata);
num_vertices += comp_num_verts;
}
// More components ?
more = flags & (1 << 5);
}
}
else
{
// numberOfCounters == 0, do nothing
}
*pvertices = vertices;
return num_vertices;
}
typedef struct
{
int bounds;
int started;
float first_x, first_y;
float x, y;
stbtt_int32 min_x, max_x, min_y, max_y;
stbtt_vertex* pvertices;
int num_vertices;
} stbtt__csctx;
#define STBTT__CSCTX_INIT(bounds) \
{ \
bounds, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, 0 \
}
static void stbtt__track_vertex(stbtt__csctx* c, stbtt_int32 x, stbtt_int32 y)
{
if (x > c->max_x || !c->started)
c->max_x = x;
if (y > c->max_y || !c->started)
c->max_y = y;
if (x < c->min_x || !c->started)
c->min_x = x;
if (y < c->min_y || !c->started)
c->min_y = y;
c->started = 1;
}
static void stbtt__csctx_v(stbtt__csctx* c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
{
if (c->bounds)
{
stbtt__track_vertex(c, x, y);
if (type == STBTT_vcubic)
{
stbtt__track_vertex(c, cx, cy);
stbtt__track_vertex(c, cx1, cy1);
}
}
else
{
stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
c->pvertices[c->num_vertices].cx1 = (stbtt_int16)cx1;
c->pvertices[c->num_vertices].cy1 = (stbtt_int16)cy1;
}
c->num_vertices++;
}
static void stbtt__csctx_close_shape(stbtt__csctx* ctx)
{
if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
}
static void stbtt__csctx_rmove_to(stbtt__csctx* ctx, float dx, float dy)
{
stbtt__csctx_close_shape(ctx);
ctx->first_x = ctx->x = ctx->x + dx;
ctx->first_y = ctx->y = ctx->y + dy;
stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rline_to(stbtt__csctx* ctx, float dx, float dy)
{
ctx->x += dx;
ctx->y += dy;
stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
}
static void stbtt__csctx_rccurve_to(stbtt__csctx* ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
{
float cx1 = ctx->x + dx1;
float cy1 = ctx->y + dy1;
float cx2 = cx1 + dx2;
float cy2 = cy1 + dy2;
ctx->x = cx2 + dx3;
ctx->y = cy2 + dy3;
stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
}
static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
{
int count = stbtt__cff_index_count(&idx);
int bias = 107;
if (count >= 33900)
bias = 32768;
else if (count >= 1240)
bias = 1131;
n += bias;
if (n < 0 || n >= count)
return stbtt__new_buf(NULL, 0);
return stbtt__cff_index_get(idx, n);
}
static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo* info, int glyph_index)
{
stbtt__buf fdselect = info->fdselect;
int nranges, start, end, v, fmt, fdselector = -1, i;
stbtt__buf_seek(&fdselect, 0);
fmt = stbtt__buf_get8(&fdselect);
if (fmt == 0)
{
// untested
stbtt__buf_skip(&fdselect, glyph_index);
fdselector = stbtt__buf_get8(&fdselect);
}
else if (fmt == 3)
{
nranges = stbtt__buf_get16(&fdselect);
start = stbtt__buf_get16(&fdselect);
for (i = 0; i < nranges; i++)
{
v = stbtt__buf_get8(&fdselect);
end = stbtt__buf_get16(&fdselect);
if (glyph_index >= start && glyph_index < end)
{
fdselector = v;
break;
}
start = end;
}
}
if (fdselector == -1)
stbtt__new_buf(NULL, 0);
return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
}
static int stbtt__run_charstring(const stbtt_fontinfo* info, int glyph_index, stbtt__csctx* c)
{
int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
int has_subrs = 0, clear_stack;
float s[48];
stbtt__buf subr_stack[10], subrs = info->subrs, b;
float f;
#define STBTT__CSERR(s) (0)
// this currently ignores the initial width value, which isn't needed if we have hmtx
b = stbtt__cff_index_get(info->charstrings, glyph_index);
while (b.cursor < b.size)
{
i = 0;
clear_stack = 1;
b0 = stbtt__buf_get8(&b);
switch (b0)
{
// @TODO implement hinting
case 0x13: // hintmask
case 0x14: // cntrmask
if (in_header)
maskbits += (sp / 2); // implicit "vstem"
in_header = 0;
stbtt__buf_skip(&b, (maskbits + 7) / 8);
break;
case 0x01: // hstem
case 0x03: // vstem
case 0x12: // hstemhm
case 0x17: // vstemhm
maskbits += (sp / 2);
break;
case 0x15: // rmoveto
in_header = 0;
if (sp < 2)
return STBTT__CSERR("rmoveto stack");
stbtt__csctx_rmove_to(c, s[sp - 2], s[sp - 1]);
break;
case 0x04: // vmoveto
in_header = 0;
if (sp < 1)
return STBTT__CSERR("vmoveto stack");
stbtt__csctx_rmove_to(c, 0, s[sp - 1]);
break;
case 0x16: // hmoveto
in_header = 0;
if (sp < 1)
return STBTT__CSERR("hmoveto stack");
stbtt__csctx_rmove_to(c, s[sp - 1], 0);
break;
case 0x05: // rlineto
if (sp < 2)
return STBTT__CSERR("rlineto stack");
for (; i + 1 < sp; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
break;
// hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
// starting from a different place.
case 0x07: // vlineto
if (sp < 1)
return STBTT__CSERR("vlineto stack");
goto vlineto;
case 0x06: // hlineto
if (sp < 1)
return STBTT__CSERR("hlineto stack");
for (;;)
{
if (i >= sp)
break;
stbtt__csctx_rline_to(c, s[i], 0);
i++;
vlineto:
if (i >= sp)
break;
stbtt__csctx_rline_to(c, 0, s[i]);
i++;
}
break;
case 0x1F: // hvcurveto
if (sp < 4)
return STBTT__CSERR("hvcurveto stack");
goto hvcurveto;
case 0x1E: // vhcurveto
if (sp < 4)
return STBTT__CSERR("vhcurveto stack");
for (;;)
{
if (i + 3 >= sp)
break;
stbtt__csctx_rccurve_to(c, 0, s[i], s[i + 1], s[i + 2], s[i + 3], (sp - i == 5) ? s[i + 4] : 0.0f);
i += 4;
hvcurveto:
if (i + 3 >= sp)
break;
stbtt__csctx_rccurve_to(c, s[i], 0, s[i + 1], s[i + 2], (sp - i == 5) ? s[i + 4] : 0.0f, s[i + 3]);
i += 4;
}
break;
case 0x08: // rrcurveto
if (sp < 6)
return STBTT__CSERR("rcurveline stack");
for (; i + 5 < sp; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
break;
case 0x18: // rcurveline
if (sp < 8)
return STBTT__CSERR("rcurveline stack");
for (; i + 5 < sp - 2; i += 6)
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
if (i + 1 >= sp)
return STBTT__CSERR("rcurveline stack");
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
break;
case 0x19: // rlinecurve
if (sp < 8)
return STBTT__CSERR("rlinecurve stack");
for (; i + 1 < sp - 6; i += 2)
stbtt__csctx_rline_to(c, s[i], s[i + 1]);
if (i + 5 >= sp)
return STBTT__CSERR("rlinecurve stack");
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5]);
break;
case 0x1A: // vvcurveto
case 0x1B: // hhcurveto
if (sp < 4)
return STBTT__CSERR("(vv|hh)curveto stack");
f = 0.0;
if (sp & 1)
{
f = s[i];
i++;
}
for (; i + 3 < sp; i += 4)
{
if (b0 == 0x1B)
stbtt__csctx_rccurve_to(c, s[i], f, s[i + 1], s[i + 2], s[i + 3], 0.0);
else
stbtt__csctx_rccurve_to(c, f, s[i], s[i + 1], s[i + 2], 0.0, s[i + 3]);
f = 0.0;
}
break;
case 0x0A: // callsubr
if (!has_subrs)
{
if (info->fdselect.size)
subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
has_subrs = 1;
}
// FALLTHROUGH
case 0x1D: // callgsubr
if (sp < 1)
return STBTT__CSERR("call(g|)subr stack");
v = (int)s[--sp];
if (subr_stack_height >= 10)
return STBTT__CSERR("recursion limit");
subr_stack[subr_stack_height++] = b;
b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
if (b.size == 0)
return STBTT__CSERR("subr not found");
b.cursor = 0;
clear_stack = 0;
break;
case 0x0B: // return
if (subr_stack_height <= 0)
return STBTT__CSERR("return outside subr");
b = subr_stack[--subr_stack_height];
clear_stack = 0;
break;
case 0x0E: // endchar
stbtt__csctx_close_shape(c);
return 1;
case 0x0C:
{ // two-byte escape
float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
float dx, dy;
int b1 = stbtt__buf_get8(&b);
switch (b1)
{
// @TODO These "flex" implementations ignore the flex-depth and resolution,
// and always draw beziers.
case 0x22: // hflex
if (sp < 7)
return STBTT__CSERR("hflex stack");
dx1 = s[0];
dx2 = s[1];
dy2 = s[2];
dx3 = s[3];
dx4 = s[4];
dx5 = s[5];
dx6 = s[6];
stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
break;
case 0x23: // flex
if (sp < 13)
return STBTT__CSERR("flex stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = s[10];
dy6 = s[11];
//fd is s[12]
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
case 0x24: // hflex1
if (sp < 9)
return STBTT__CSERR("hflex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dx4 = s[5];
dx5 = s[6];
dy5 = s[7];
dx6 = s[8];
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1 + dy2 + dy5));
break;
case 0x25: // flex1
if (sp < 11)
return STBTT__CSERR("flex1 stack");
dx1 = s[0];
dy1 = s[1];
dx2 = s[2];
dy2 = s[3];
dx3 = s[4];
dy3 = s[5];
dx4 = s[6];
dy4 = s[7];
dx5 = s[8];
dy5 = s[9];
dx6 = dy6 = s[10];
dx = dx1 + dx2 + dx3 + dx4 + dx5;
dy = dy1 + dy2 + dy3 + dy4 + dy5;
if (STBTT_fabs(dx) > STBTT_fabs(dy))
dy6 = -dy;
else
dx6 = -dx;
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
break;
default:
return STBTT__CSERR("unimplemented");
}
}
break;
default:
if (b0 != 255 && b0 != 28 && b0 < 32)
return STBTT__CSERR("reserved operator");
// push immediate
if (b0 == 255)
{
f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;
}
else
{
stbtt__buf_skip(&b, -1);
f = (float)(stbtt_int16)stbtt__cff_int(&b);
}
if (sp >= 48)
return STBTT__CSERR("push stack overflow");
s[sp++] = f;
clear_stack = 0;
break;
}
if (clear_stack)
sp = 0;
}
return STBTT__CSERR("no endchar");
#undef STBTT__CSERR
}
static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo* info, int glyph_index, stbtt_vertex** pvertices)
{
// runs the charstring twice, once to count and once to output (to avoid realloc)
stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
if (stbtt__run_charstring(info, glyph_index, &count_ctx))
{
*pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices * sizeof(stbtt_vertex), info->userdata);
output_ctx.pvertices = *pvertices;
if (stbtt__run_charstring(info, glyph_index, &output_ctx))
{
STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
return output_ctx.num_vertices;
}
}
*pvertices = NULL;
return 0;
}
static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo* info, int glyph_index, int* x0, int* y0, int* x1, int* y1)
{
stbtt__csctx c = STBTT__CSCTX_INIT(1);
int r = stbtt__run_charstring(info, glyph_index, &c);
if (x0)
*x0 = r ? c.min_x : 0;
if (y0)
*y0 = r ? c.min_y : 0;
if (x1)
*x1 = r ? c.max_x : 0;
if (y1)
*y1 = r ? c.max_y : 0;
return r ? c.num_vertices : 0;
}
STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo* info, int glyph_index, stbtt_vertex** pvertices)
{
if (!info->cff.size)
return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
else
return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
}
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo* info, int glyph_index, int* advanceWidth, int* leftSideBearing)
{
stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data + info->hhea + 34);
if (glyph_index < numOfLongHorMetrics)
{
if (advanceWidth)
*advanceWidth = ttSHORT(info->data + info->hmtx + 4 * glyph_index);
if (leftSideBearing)
*leftSideBearing = ttSHORT(info->data + info->hmtx + 4 * glyph_index + 2);
}
else
{
if (advanceWidth)
*advanceWidth = ttSHORT(info->data + info->hmtx + 4 * (numOfLongHorMetrics - 1));
if (leftSideBearing)
*leftSideBearing = ttSHORT(info->data + info->hmtx + 4 * numOfLongHorMetrics + 2 * (glyph_index - numOfLongHorMetrics));
}
}
STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo* info)
{
stbtt_uint8* data = info->data + info->kern;
// we only look at the first table. it must be 'horizontal' and format 0.
if (!info->kern)
return 0;
if (ttUSHORT(data + 2) < 1) // number of tables, need at least 1
return 0;
if (ttUSHORT(data + 8) != 1) // horizontal flag must be set in format
return 0;
return ttUSHORT(data + 10);
}
STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo* info, stbtt_kerningentry* table, int table_length)
{
stbtt_uint8* data = info->data + info->kern;
int k, length;
// we only look at the first table. it must be 'horizontal' and format 0.
if (!info->kern)
return 0;
if (ttUSHORT(data + 2) < 1) // number of tables, need at least 1
return 0;
if (ttUSHORT(data + 8) != 1) // horizontal flag must be set in format
return 0;
length = ttUSHORT(data + 10);
if (table_length < length)
length = table_length;
for (k = 0; k < length; k++)
{
table[k].glyph1 = ttUSHORT(data + 18 + (k * 6));
table[k].glyph2 = ttUSHORT(data + 20 + (k * 6));
table[k].advance = ttSHORT(data + 22 + (k * 6));
}
return length;
}
static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo* info, int glyph1, int glyph2)
{
stbtt_uint8* data = info->data + info->kern;
stbtt_uint32 needle, straw;
int l, r, m;
// we only look at the first table. it must be 'horizontal' and format 0.
if (!info->kern)
return 0;
if (ttUSHORT(data + 2) < 1) // number of tables, need at least 1
return 0;
if (ttUSHORT(data + 8) != 1) // horizontal flag must be set in format
return 0;
l = 0;
r = ttUSHORT(data + 10) - 1;
needle = glyph1 << 16 | glyph2;
while (l <= r)
{
m = (l + r) >> 1;
straw = ttULONG(data + 18 + (m * 6)); // note: unaligned read
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else
return ttSHORT(data + 22 + (m * 6));
}
return 0;
}
static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8* coverageTable, int glyph)
{
stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);
switch (coverageFormat)
{
case 1:
{
stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);
// Binary search.
stbtt_int32 l = 0, r = glyphCount - 1, m;
int straw, needle = glyph;
while (l <= r)
{
stbtt_uint8* glyphArray = coverageTable + 4;
stbtt_uint16 glyphID;
m = (l + r) >> 1;
glyphID = ttUSHORT(glyphArray + 2 * m);
straw = glyphID;
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else
{
return m;
}
}
break;
}
case 2:
{
stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);
stbtt_uint8* rangeArray = coverageTable + 4;
// Binary search.
stbtt_int32 l = 0, r = rangeCount - 1, m;
int strawStart, strawEnd, needle = glyph;
while (l <= r)
{
stbtt_uint8* rangeRecord;
m = (l + r) >> 1;
rangeRecord = rangeArray + 6 * m;
strawStart = ttUSHORT(rangeRecord);
strawEnd = ttUSHORT(rangeRecord + 2);
if (needle < strawStart)
r = m - 1;
else if (needle > strawEnd)
l = m + 1;
else
{
stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);
return startCoverageIndex + glyph - strawStart;
}
}
break;
}
default: return -1; // unsupported
}
return -1;
}
static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8* classDefTable, int glyph)
{
stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);
switch (classDefFormat)
{
case 1:
{
stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);
stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);
stbtt_uint8* classDef1ValueArray = classDefTable + 6;
if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)
return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));
break;
}
case 2:
{
stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);
stbtt_uint8* classRangeRecords = classDefTable + 4;
// Binary search.
stbtt_int32 l = 0, r = classRangeCount - 1, m;
int strawStart, strawEnd, needle = glyph;
while (l <= r)
{
stbtt_uint8* classRangeRecord;
m = (l + r) >> 1;
classRangeRecord = classRangeRecords + 6 * m;
strawStart = ttUSHORT(classRangeRecord);
strawEnd = ttUSHORT(classRangeRecord + 2);
if (needle < strawStart)
r = m - 1;
else if (needle > strawEnd)
l = m + 1;
else
return (stbtt_int32)ttUSHORT(classRangeRecord + 4);
}
break;
}
default:
return -1; // Unsupported definition type, return an error.
}
// "All glyphs not assigned to a class fall into class 0". (OpenType spec)
return 0;
}
// Define to STBTT_assert(x) if you want to break on unimplemented formats.
#define STBTT_GPOS_TODO_assert(x)
static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo* info, int glyph1, int glyph2)
{
stbtt_uint16 lookupListOffset;
stbtt_uint8* lookupList;
stbtt_uint16 lookupCount;
stbtt_uint8* data;
stbtt_int32 i, sti;
if (!info->gpos)
return 0;
data = info->data + info->gpos;
if (ttUSHORT(data + 0) != 1)
return 0; // Major version 1
if (ttUSHORT(data + 2) != 0)
return 0; // Minor version 0
lookupListOffset = ttUSHORT(data + 8);
lookupList = data + lookupListOffset;
lookupCount = ttUSHORT(lookupList);
for (i = 0; i < lookupCount; ++i)
{
stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
stbtt_uint8* lookupTable = lookupList + lookupOffset;
stbtt_uint16 lookupType = ttUSHORT(lookupTable);
stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
stbtt_uint8* subTableOffsets = lookupTable + 6;
if (lookupType != 2) // Pair Adjustment Positioning Subtable
continue;
for (sti = 0; sti < subTableCount; sti++)
{
stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
stbtt_uint8* table = lookupTable + subtableOffset;
stbtt_uint16 posFormat = ttUSHORT(table);
stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
if (coverageIndex == -1)
continue;
switch (posFormat)
{
case 1:
{
stbtt_int32 l, r, m;
int straw, needle;
stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
if (valueFormat1 == 4 && valueFormat2 == 0)
{ // Support more formats?
stbtt_int32 valueRecordPairSizeInBytes = 2;
stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
stbtt_uint8* pairValueTable = table + pairPosOffset;
stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
stbtt_uint8* pairValueArray = pairValueTable + 2;
if (coverageIndex >= pairSetCount)
return 0;
needle = glyph2;
r = pairValueCount - 1;
l = 0;
// Binary search.
while (l <= r)
{
stbtt_uint16 secondGlyph;
stbtt_uint8* pairValue;
m = (l + r) >> 1;
pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;
secondGlyph = ttUSHORT(pairValue);
straw = secondGlyph;
if (needle < straw)
r = m - 1;
else if (needle > straw)
l = m + 1;
else
{
stbtt_int16 xAdvance = ttSHORT(pairValue + 2);
return xAdvance;
}
}
}
else
return 0;
break;
}
case 2:
{
stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
if (valueFormat1 == 4 && valueFormat2 == 0)
{ // Support more formats?
stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);
stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);
int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);
int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);
stbtt_uint16 class1Count = ttUSHORT(table + 12);
stbtt_uint16 class2Count = ttUSHORT(table + 14);
stbtt_uint8 *class1Records, *class2Records;
stbtt_int16 xAdvance;
if (glyph1class < 0 || glyph1class >= class1Count)
return 0; // malformed
if (glyph2class < 0 || glyph2class >= class2Count)
return 0; // malformed
class1Records = table + 16;
class2Records = class1Records + 2 * (glyph1class * class2Count);
xAdvance = ttSHORT(class2Records + 2 * glyph2class);
return xAdvance;
}
else
return 0;
break;
}
default:
return 0; // Unsupported position format
}
}
}
return 0;
}
STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo* info, int g1, int g2)
{
int xAdvance = 0;
if (info->gpos)
xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);
else if (info->kern)
xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);
return xAdvance;
}
STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo* info, int ch1, int ch2)
{
if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs
return 0;
return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info, ch1), stbtt_FindGlyphIndex(info, ch2));
}
STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo* info, int codepoint, int* advanceWidth, int* leftSideBearing)
{
stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info, codepoint), advanceWidth, leftSideBearing);
}
STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo* info, int* ascent, int* descent, int* lineGap)
{
if (ascent)
*ascent = ttSHORT(info->data + info->hhea + 4);
if (descent)
*descent = ttSHORT(info->data + info->hhea + 6);
if (lineGap)
*lineGap = ttSHORT(info->data + info->hhea + 8);
}
STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo* info, int* typoAscent, int* typoDescent, int* typoLineGap)
{
int tab = stbtt__find_table(info->data, info->fontstart, "OS/2");
if (!tab)
return 0;
if (typoAscent)
*typoAscent = ttSHORT(info->data + tab + 68);
if (typoDescent)
*typoDescent = ttSHORT(info->data + tab + 70);
if (typoLineGap)
*typoLineGap = ttSHORT(info->data + tab + 72);
return 1;
}
STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo* info, int* x0, int* y0, int* x1, int* y1)
{
*x0 = ttSHORT(info->data + info->head + 36);
*y0 = ttSHORT(info->data + info->head + 38);
*x1 = ttSHORT(info->data + info->head + 40);
*y1 = ttSHORT(info->data + info->head + 42);
}
STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo* info, float height)
{
int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
return (float)height / fheight;
}
STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo* info, float pixels)
{
int unitsPerEm = ttUSHORT(info->data + info->head + 18);
return pixels / unitsPerEm;
}
STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo* info, stbtt_vertex* v)
{
STBTT_free(v, info->userdata);
}
STBTT_DEF stbtt_uint8* stbtt_FindSVGDoc(const stbtt_fontinfo* info, int gl)
{
int i;
stbtt_uint8* data = info->data;
stbtt_uint8* svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo*)info);
int numEntries = ttUSHORT(svg_doc_list);
stbtt_uint8* svg_docs = svg_doc_list + 2;
for (i = 0; i < numEntries; i++)
{
stbtt_uint8* svg_doc = svg_docs + (12 * i);
if ((gl >= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2)))
return svg_doc;
}
return 0;
}
STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo* info, int gl, const char** svg)
{
stbtt_uint8* data = info->data;
stbtt_uint8* svg_doc;
if (info->svg == 0)
return 0;
svg_doc = stbtt_FindSVGDoc(info, gl);
if (svg_doc != NULL)
{
*svg = (char*)data + info->svg + ttULONG(svg_doc + 4);
return ttULONG(svg_doc + 8);
}
else
{
return 0;
}
}
STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo* info, int unicode_codepoint, const char** svg)
{
return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg);
}
//////////////////////////////////////////////////////////////////////////////
//
// antialiasing software rasterizer
//
STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo* font, int glyph, float scale_x, float scale_y, float shift_x, float shift_y, int* ix0, int* iy0, int* ix1, int* iy1)
{
int x0 = 0, y0 = 0, x1, y1; // =0 suppresses compiler warning
if (!stbtt_GetGlyphBox(font, glyph, &x0, &y0, &x1, &y1))
{
// e.g. space character
if (ix0)
*ix0 = 0;
if (iy0)
*iy0 = 0;
if (ix1)
*ix1 = 0;
if (iy1)
*iy1 = 0;
}
else
{
// move to integral bboxes (treating pixels as little squares, what pixels get touched)?
if (ix0)
*ix0 = STBTT_ifloor(x0 * scale_x + shift_x);
if (iy0)
*iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
if (ix1)
*ix1 = STBTT_iceil(x1 * scale_x + shift_x);
if (iy1)
*iy1 = STBTT_iceil(-y0 * scale_y + shift_y);
}
}
STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo* font, int glyph, float scale_x, float scale_y, int* ix0, int* iy0, int* ix1, int* iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0f, 0.0f, ix0, iy0, ix1, iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo* font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int* ix0, int* iy0, int* ix1, int* iy1)
{
stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font, codepoint), scale_x, scale_y, shift_x, shift_y, ix0, iy0, ix1, iy1);
}
STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo* font, int codepoint, float scale_x, float scale_y, int* ix0, int* iy0, int* ix1, int* iy1)
{
stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y, 0.0f, 0.0f, ix0, iy0, ix1, iy1);
}
//////////////////////////////////////////////////////////////////////////////
//
// Rasterizer
typedef struct stbtt__hheap_chunk
{
struct stbtt__hheap_chunk* next;
} stbtt__hheap_chunk;
typedef struct stbtt__hheap
{
struct stbtt__hheap_chunk* head;
void* first_free;
int num_remaining_in_head_chunk;
} stbtt__hheap;
static void* stbtt__hheap_alloc(stbtt__hheap* hh, size_t size, void* userdata)
{
if (hh->first_free)
{
void* p = hh->first_free;
hh->first_free = *(void**)p;
return p;
}
else
{
if (hh->num_remaining_in_head_chunk == 0)
{
int count = (size < 32 ? 2000 : size < 128 ? 800
: 100);
stbtt__hheap_chunk* c = (stbtt__hheap_chunk*)STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
if (c == NULL)
return NULL;
c->next = hh->head;
hh->head = c;
hh->num_remaining_in_head_chunk = count;
}
--hh->num_remaining_in_head_chunk;
return (char*)(hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;
}
}
static void stbtt__hheap_free(stbtt__hheap* hh, void* p)
{
*(void**)p = hh->first_free;
hh->first_free = p;
}
static void stbtt__hheap_cleanup(stbtt__hheap* hh, void* userdata)
{
stbtt__hheap_chunk* c = hh->head;
while (c)
{
stbtt__hheap_chunk* n = c->next;
STBTT_free(c, userdata);
c = n;
}
}
typedef struct stbtt__edge
{
float x0, y0, x1, y1;
int invert;
} stbtt__edge;
typedef struct stbtt__active_edge
{
struct stbtt__active_edge* next;
#if STBTT_RASTERIZER_VERSION == 1
int x, dx;
float ey;
int direction;
#elif STBTT_RASTERIZER_VERSION == 2
float fx, fdx, fdy;
float direction;
float sy;
float ey;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
} stbtt__active_edge;
#if STBTT_RASTERIZER_VERSION == 1
#define STBTT_FIXSHIFT 10
#define STBTT_FIX (1 << STBTT_FIXSHIFT)
#define STBTT_FIXMASK (STBTT_FIX - 1)
static stbtt__active_edge* stbtt__new_active(stbtt__hheap* hh, stbtt__edge* e, int off_x, float start_point, void* userdata)
{
stbtt__active_edge* z = (stbtt__active_edge*)stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
if (!z)
return z;
// round dx down to avoid overshooting
if (dxdy < 0)
z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
else
z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
z->x -= off_x * STBTT_FIX;
z->ey = e->y1;
z->next = 0;
z->direction = e->invert ? 1 : -1;
return z;
}
#elif STBTT_RASTERIZER_VERSION == 2
static stbtt__active_edge* stbtt__new_active(stbtt__hheap* hh, stbtt__edge* e, int off_x, float start_point, void* userdata)
{
stbtt__active_edge* z = (stbtt__active_edge*)stbtt__hheap_alloc(hh, sizeof(*z), userdata);
float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
STBTT_assert(z != NULL);
//STBTT_assert(e->y0 <= start_point);
if (!z)
return z;
z->fdx = dxdy;
z->fdy = dxdy != 0.0f ? (1.0f / dxdy) : 0.0f;
z->fx = e->x0 + dxdy * (start_point - e->y0);
z->fx -= off_x;
z->direction = e->invert ? 1.0f : -1.0f;
z->sy = e->y0;
z->ey = e->y1;
z->next = 0;
return z;
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#if STBTT_RASTERIZER_VERSION == 1
// note: this routine clips fills that extend off the edges... ideally this
// wouldn't happen, but it could happen if the truetype glyph bounding boxes
// are wrong, or if the user supplies a too-small bitmap
static void stbtt__fill_active_edges(unsigned char* scanline, int len, stbtt__active_edge* e, int max_weight)
{
// non-zero winding fill
int x0 = 0, w = 0;
while (e)
{
if (w == 0)
{
// if we're currently at zero, we need to record the edge start point
x0 = e->x;
w += e->direction;
}
else
{
int x1 = e->x;
w += e->direction;
// if we went to zero, we need to draw
if (w == 0)
{
int i = x0 >> STBTT_FIXSHIFT;
int j = x1 >> STBTT_FIXSHIFT;
if (i < len && j >= 0)
{
if (i == j)
{
// x0,x1 are the same pixel, so compute combined coverage
scanline[i] = scanline[i] + (stbtt_uint8)((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
}
else
{
if (i >= 0) // add antialiasing for x0
scanline[i] = scanline[i] + (stbtt_uint8)(((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
else
i = -1; // clip
if (j < len) // add antialiasing for x1
scanline[j] = scanline[j] + (stbtt_uint8)(((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
else
j = len; // clip
for (++i; i < j; ++i) // fill pixels between x0 and x1
scanline[i] = scanline[i] + (stbtt_uint8)max_weight;
}
}
}
}
e = e->next;
}
}
static void stbtt__rasterize_sorted_edges(stbtt__bitmap* result, stbtt__edge* e, int n, int vsubsample, int off_x, int off_y, void* userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge* active = NULL;
int y, j = 0;
int max_weight = (255 / vsubsample); // weight per vertical scanline
int s; // vertical subsample index
unsigned char scanline_data[512], *scanline;
if (result->w > 512)
scanline = (unsigned char*)STBTT_malloc(result->w, userdata);
else
scanline = scanline_data;
y = off_y * vsubsample;
e[n].y0 = (off_y + result->h) * (float)vsubsample + 1;
while (j < result->h)
{
STBTT_memset(scanline, 0, result->w);
for (s = 0; s < vsubsample; ++s)
{
// find center of pixel for this scanline
float scan_y = y + 0.5f;
stbtt__active_edge** step = &active;
// update all active edges;
// remove all active edges that terminate before the center of this scanline
while (*step)
{
stbtt__active_edge* z = *step;
if (z->ey <= scan_y)
{
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
}
else
{
z->x += z->dx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
}
// resort the list if needed
for (;;)
{
int changed = 0;
step = &active;
while (*step && (*step)->next)
{
if ((*step)->x > (*step)->next->x)
{
stbtt__active_edge* t = *step;
stbtt__active_edge* q = t->next;
t->next = q->next;
q->next = t;
*step = q;
changed = 1;
}
step = &(*step)->next;
}
if (!changed)
break;
}
// insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
while (e->y0 <= scan_y)
{
if (e->y1 > scan_y)
{
stbtt__active_edge* z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
if (z != NULL)
{
// find insertion point
if (active == NULL)
active = z;
else if (z->x < active->x)
{
// insert at front
z->next = active;
active = z;
}
else
{
// find thing to insert AFTER
stbtt__active_edge* p = active;
while (p->next && p->next->x < z->x)
p = p->next;
// at this point, p->next->x is NOT < z->x
z->next = p->next;
p->next = z;
}
}
}
++e;
}
// now process all active edges in XOR fashion
if (active)
stbtt__fill_active_edges(scanline, result->w, active, max_weight);
++y;
}
STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if (scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#elif STBTT_RASTERIZER_VERSION == 2
// the edge passed in here does not cross the vertical line at x or the vertical line at x+1
// (i.e. it has already been clipped to those)
static void stbtt__handle_clipped_edge(float* scanline, int x, stbtt__active_edge* e, float x0, float y0, float x1, float y1)
{
if (y0 == y1)
return;
STBTT_assert(y0 < y1);
STBTT_assert(e->sy <= e->ey);
if (y0 > e->ey)
return;
if (y1 < e->sy)
return;
if (y0 < e->sy)
{
x0 += (x1 - x0) * (e->sy - y0) / (y1 - y0);
y0 = e->sy;
}
if (y1 > e->ey)
{
x1 += (x1 - x0) * (e->ey - y1) / (y1 - y0);
y1 = e->ey;
}
if (x0 == x)
STBTT_assert(x1 <= x + 1);
else if (x0 == x + 1)
STBTT_assert(x1 >= x);
else if (x0 <= x)
STBTT_assert(x1 <= x);
else if (x0 >= x + 1)
STBTT_assert(x1 >= x + 1);
else
STBTT_assert(x1 >= x && x1 <= x + 1);
if (x0 <= x && x1 <= x)
scanline[x] += e->direction * (y1 - y0);
else if (x0 >= x + 1 && x1 >= x + 1)
;
else
{
STBTT_assert(x0 >= x && x0 <= x + 1 && x1 >= x && x1 <= x + 1);
scanline[x] += e->direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2); // coverage = 1 - average x position
}
}
static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width)
{
STBTT_assert(top_width >= 0);
STBTT_assert(bottom_width >= 0);
return (top_width + bottom_width) / 2.0f * height;
}
static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1)
{
return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0);
}
static float stbtt__sized_triangle_area(float height, float width)
{
return height * width / 2;
}
static void stbtt__fill_active_edges_new(float* scanline, float* scanline_fill, int len, stbtt__active_edge* e, float y_top)
{
float y_bottom = y_top + 1;
while (e)
{
// brute force every pixel
// compute intersection points with top & bottom
STBTT_assert(e->ey >= y_top);
if (e->fdx == 0)
{
float x0 = e->fx;
if (x0 < len)
{
if (x0 >= 0)
{
stbtt__handle_clipped_edge(scanline, (int)x0, e, x0, y_top, x0, y_bottom);
stbtt__handle_clipped_edge(scanline_fill - 1, (int)x0 + 1, e, x0, y_top, x0, y_bottom);
}
else
{
stbtt__handle_clipped_edge(scanline_fill - 1, 0, e, x0, y_top, x0, y_bottom);
}
}
}
else
{
float x0 = e->fx;
float dx = e->fdx;
float xb = x0 + dx;
float x_top, x_bottom;
float sy0, sy1;
float dy = e->fdy;
STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
// compute endpoints of line segment clipped to this scanline (if the
// line segment starts on this scanline. x0 is the intersection of the
// line with y_top, but that may be off the line segment.
if (e->sy > y_top)
{
x_top = x0 + dx * (e->sy - y_top);
sy0 = e->sy;
}
else
{
x_top = x0;
sy0 = y_top;
}
if (e->ey < y_bottom)
{
x_bottom = x0 + dx * (e->ey - y_top);
sy1 = e->ey;
}
else
{
x_bottom = xb;
sy1 = y_bottom;
}
if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len)
{
// from here on, we don't have to range check x values
if ((int)x_top == (int)x_bottom)
{
float height;
// simple case, only spans one pixel
int x = (int)x_top;
height = (sy1 - sy0) * e->direction;
STBTT_assert(x >= 0 && x < len);
scanline[x] += stbtt__position_trapezoid_area(height, x_top, x + 1.0f, x_bottom, x + 1.0f);
scanline_fill[x] += height; // everything right of this pixel is filled
}
else
{
int x, x1, x2;
float y_crossing, y_final, step, sign, area;
// covers 2+ pixels
if (x_top > x_bottom)
{
// flip scanline vertically; signed area is the same
float t;
sy0 = y_bottom - (sy0 - y_top);
sy1 = y_bottom - (sy1 - y_top);
t = sy0, sy0 = sy1, sy1 = t;
t = x_bottom, x_bottom = x_top, x_top = t;
dx = -dx;
dy = -dy;
t = x0, x0 = xb, xb = t;
}
STBTT_assert(dy >= 0);
STBTT_assert(dx >= 0);
x1 = (int)x_top;
x2 = (int)x_bottom;
// compute intersection with y axis at x1+1
y_crossing = y_top + dy * (x1 + 1 - x0);
// compute intersection with y axis at x2
y_final = y_top + dy * (x2 - x0);
// x1 x_top x2 x_bottom
// y_top +------|-----+------------+------------+--------|---+------------+
// | | | | | |
// | | | | | |
// sy0 | Txxxxx|............|............|............|............|
// y_crossing | *xxxxx.......|............|............|............|
// | | xxxxx..|............|............|............|
// | | /- xx*xxxx........|............|............|
// | | dy < | xxxxxx..|............|............|
// y_final | | \- | xx*xxx.........|............|
// sy1 | | | | xxxxxB...|............|
// | | | | | |
// | | | | | |
// y_bottom +------------+------------+------------+------------+------------+
//
// goal is to measure the area covered by '.' in each pixel
// if x2 is right at the right edge of x1, y_crossing can blow up, github #1057
// @TODO: maybe test against sy1 rather than y_bottom?
if (y_crossing > y_bottom)
y_crossing = y_bottom;
sign = e->direction;
// area of the rectangle covered from sy0..y_crossing
area = sign * (y_crossing - sy0);
// area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing)
scanline[x1] += stbtt__sized_triangle_area(area, x1 + 1 - x_top);
// check if final y_crossing is blown up; no test case for this
if (y_final > y_bottom)
{
y_final = y_bottom;
dy = (y_final - y_crossing) / (x2 - (x1 + 1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom
}
// in second pixel, area covered by line segment found in first pixel
// is always a rectangle 1 wide * the height of that line segment; this
// is exactly what the variable 'area' stores. it also gets a contribution
// from the line segment within it. the THIRD pixel will get the first
// pixel's rectangle contribution, the second pixel's rectangle contribution,
// and its own contribution. the 'own contribution' is the same in every pixel except
// the leftmost and rightmost, a trapezoid that slides down in each pixel.
// the second pixel's contribution to the third pixel will be the
// rectangle 1 wide times the height change in the second pixel, which is dy.
step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x,
// which multiplied by 1-pixel-width is how much pixel area changes for each step in x
// so the area advances by 'step' every time
for (x = x1 + 1; x < x2; ++x)
{
scanline[x] += area + step / 2; // area of trapezoid is 1*step/2
area += step;
}
STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down
STBTT_assert(sy1 > y_final - 0.01f);
// area covered in the last pixel is the rectangle from all the pixels to the left,
// plus the trapezoid filled by the line segment in this pixel all the way to the right edge
scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1 - y_final, (float)x2, x2 + 1.0f, x_bottom, x2 + 1.0f);
// the rest of the line is filled based on the total height of the line segment in this pixel
scanline_fill[x2] += sign * (sy1 - sy0);
}
}
else
{
// if edge goes outside of box we're drawing, we require
// clipping logic. since this does not match the intended use
// of this library, we use a different, very slow brute
// force implementation
// note though that this does happen some of the time because
// x_top and x_bottom can be extrapolated at the top & bottom of
// the shape and actually lie outside the bounding box
int x;
for (x = 0; x < len; ++x)
{
// cases:
//
// there can be up to two intersections with the pixel. any intersection
// with left or right edges can be handled by splitting into two (or three)
// regions. intersections with top & bottom do not necessitate case-wise logic.
//
// the old way of doing this found the intersections with the left & right edges,
// then used some simple logic to produce up to three segments in sorted order
// from top-to-bottom. however, this had a problem: if an x edge was epsilon
// across the x border, then the corresponding y position might not be distinct
// from the other y segment, and it might ignored as an empty segment. to avoid
// that, we need to explicitly produce segments based on x positions.
// rename variables to clearly-defined pairs
float y0 = y_top;
float x1 = (float)(x);
float x2 = (float)(x + 1);
float x3 = xb;
float y3 = y_bottom;
// x = e->x + e->dx * (y-y_top)
// (y-y_top) = (x - e->x) / e->dx
// y = (x - e->x) / e->dx + y_top
float y1 = (x - x0) / dx + y_top;
float y2 = (x + 1 - x0) / dx + y_top;
if (x0 < x1 && x3 > x2)
{ // three segments descending down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else if (x3 < x1 && x0 > x2)
{ // three segments descending down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if (x0 < x1 && x3 > x1)
{ // two segments across x, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if (x3 < x1 && x0 > x1)
{ // two segments across x, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1);
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3);
}
else if (x0 < x2 && x3 > x2)
{ // two segments across x+1, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else if (x3 < x2 && x0 > x2)
{ // two segments across x+1, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2);
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3);
}
else
{ // one segment
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x3, y3);
}
}
}
}
e = e->next;
}
}
// directly AA rasterize edges w/o supersampling
static void stbtt__rasterize_sorted_edges(stbtt__bitmap* result, stbtt__edge* e, int n, int vsubsample, int off_x, int off_y, void* userdata)
{
stbtt__hheap hh = { 0, 0, 0 };
stbtt__active_edge* active = NULL;
int y, j = 0, i;
float scanline_data[129], *scanline, *scanline2;
STBTT__NOTUSED(vsubsample);
if (result->w > 64)
scanline = (float*)STBTT_malloc((result->w * 2 + 1) * sizeof(float), userdata);
else
scanline = scanline_data;
scanline2 = scanline + result->w;
y = off_y;
e[n].y0 = (float)(off_y + result->h) + 1;
while (j < result->h)
{
// find center of pixel for this scanline
float scan_y_top = y + 0.0f;
float scan_y_bottom = y + 1.0f;
stbtt__active_edge** step = &active;
STBTT_memset(scanline, 0, result->w * sizeof(scanline[0]));
STBTT_memset(scanline2, 0, (result->w + 1) * sizeof(scanline[0]));
// update all active edges;
// remove all active edges that terminate before the top of this scanline
while (*step)
{
stbtt__active_edge* z = *step;
if (z->ey <= scan_y_top)
{
*step = z->next; // delete from list
STBTT_assert(z->direction);
z->direction = 0;
stbtt__hheap_free(&hh, z);
}
else
{
step = &((*step)->next); // advance through list
}
}
// insert all edges that start before the bottom of this scanline
while (e->y0 <= scan_y_bottom)
{
if (e->y0 != e->y1)
{
stbtt__active_edge* z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
if (z != NULL)
{
if (j == 0 && off_y != 0)
{
if (z->ey < scan_y_top)
{
// this can happen due to subpixel positioning and some kind of fp rounding error i think
z->ey = scan_y_top;
}
}
STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds
// insert at front
z->next = active;
active = z;
}
}
++e;
}
// now process all active edges
if (active)
stbtt__fill_active_edges_new(scanline, scanline2 + 1, result->w, active, scan_y_top);
{
float sum = 0;
for (i = 0; i < result->w; ++i)
{
float k;
int m;
sum += scanline2[i];
k = scanline[i] + sum;
k = (float)STBTT_fabs(k) * 255 + 0.5f;
m = (int)k;
if (m > 255)
m = 255;
result->pixels[j * result->stride + i] = (unsigned char)m;
}
}
// advance all the edges
step = &active;
while (*step)
{
stbtt__active_edge* z = *step;
z->fx += z->fdx; // advance to position for current scanline
step = &((*step)->next); // advance through list
}
++y;
++j;
}
stbtt__hheap_cleanup(&hh, userdata);
if (scanline != scanline_data)
STBTT_free(scanline, userdata);
}
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
#define STBTT__COMPARE(a, b) ((a)->y0 < (b)->y0)
static void stbtt__sort_edges_ins_sort(stbtt__edge* p, int n)
{
int i, j;
for (i = 1; i < n; ++i)
{
stbtt__edge t = p[i], *a = &t;
j = i;
while (j > 0)
{
stbtt__edge* b = &p[j - 1];
int c = STBTT__COMPARE(a, b);
if (!c)
break;
p[j] = p[j - 1];
--j;
}
if (i != j)
p[j] = t;
}
}
static void stbtt__sort_edges_quicksort(stbtt__edge* p, int n)
{
/* threshold for transitioning to insertion sort */
while (n > 12)
{
stbtt__edge t;
int c01, c12, c, m, i, j;
/* compute median of three */
m = n >> 1;
c01 = STBTT__COMPARE(&p[0], &p[m]);
c12 = STBTT__COMPARE(&p[m], &p[n - 1]);
/* if 0 >= mid >= end, or 0 < mid < end, then use mid */
if (c01 != c12)
{
/* otherwise, we'll need to swap something else to middle */
int z;
c = STBTT__COMPARE(&p[0], &p[n - 1]);
/* 0>mid && mid<n: 0>n => n; 0<n => 0 */
/* 0<mid && mid>n: 0>n => 0; 0<n => n */
z = (c == c12) ? 0 : n - 1;
t = p[z];
p[z] = p[m];
p[m] = t;
}
/* now p[m] is the median-of-three */
/* swap it to the beginning so it won't move around */
t = p[0];
p[0] = p[m];
p[m] = t;
/* partition loop */
i = 1;
j = n - 1;
for (;;)
{
/* handling of equality is crucial here */
/* for sentinels & efficiency with duplicates */
for (;; ++i)
{
if (!STBTT__COMPARE(&p[i], &p[0]))
break;
}
for (;; --j)
{
if (!STBTT__COMPARE(&p[0], &p[j]))
break;
}
/* make sure we haven't crossed */
if (i >= j)
break;
t = p[i];
p[i] = p[j];
p[j] = t;
++i;
--j;
}
/* recurse on smaller side, iterate on larger */
if (j < (n - i))
{
stbtt__sort_edges_quicksort(p, j);
p = p + i;
n = n - i;
}
else
{
stbtt__sort_edges_quicksort(p + i, n - i);
n = j;
}
}
}
static void stbtt__sort_edges(stbtt__edge* p, int n)
{
stbtt__sort_edges_quicksort(p, n);
stbtt__sort_edges_ins_sort(p, n);
}
typedef struct
{
float x, y;
} stbtt__point;
static void stbtt__rasterize(stbtt__bitmap* result, stbtt__point* pts, int* wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void* userdata)
{
float y_scale_inv = invert ? -scale_y : scale_y;
stbtt__edge* e;
int n, i, j, k, m;
#if STBTT_RASTERIZER_VERSION == 1
int vsubsample = result->h < 8 ? 15 : 5;
#elif STBTT_RASTERIZER_VERSION == 2
int vsubsample = 1;
#else
#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
#endif
// vsubsample should divide 255 evenly; otherwise we won't reach full opacity
// now we have to blow out the windings into explicit edge lists
n = 0;
for (i = 0; i < windings; ++i)
n += wcount[i];
e = (stbtt__edge*)STBTT_malloc(sizeof(*e) * (n + 1), userdata); // add an extra one as a sentinel
if (e == 0)
return;
n = 0;
m = 0;
for (i = 0; i < windings; ++i)
{
stbtt__point* p = pts + m;
m += wcount[i];
j = wcount[i] - 1;
for (k = 0; k < wcount[i]; j = k++)
{
int a = k, b = j;
// skip the edge if horizontal
if (p[j].y == p[k].y)
continue;
// add edge from j to k to the list
e[n].invert = 0;
if (invert ? p[j].y > p[k].y : p[j].y < p[k].y)
{
e[n].invert = 1;
a = j, b = k;
}
e[n].x0 = p[a].x * scale_x + shift_x;
e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
e[n].x1 = p[b].x * scale_x + shift_x;
e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
++n;
}
}
// now sort the edges by their highest point (should snap to integer, and then by x)
//STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
stbtt__sort_edges(e, n);
// now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
STBTT_free(e, userdata);
}
static void stbtt__add_point(stbtt__point* points, int n, float x, float y)
{
if (!points)
return; // during first pass, it's unallocated
points[n].x = x;
points[n].y = y;
}
// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching
static int stbtt__tesselate_curve(stbtt__point* points, int* num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
{
// midpoint
float mx = (x0 + 2 * x1 + x2) / 4;
float my = (y0 + 2 * y1 + y2) / 4;
// versus directly drawn line
float dx = (x0 + x2) / 2 - mx;
float dy = (y0 + y2) / 2 - my;
if (n > 16) // 65536 segments on one curve better be enough!
return 1;
if (dx * dx + dy * dy > objspace_flatness_squared)
{ // half-pixel error allowed... need to be smaller if AA
stbtt__tesselate_curve(points, num_points, x0, y0, (x0 + x1) / 2.0f, (y0 + y1) / 2.0f, mx, my, objspace_flatness_squared, n + 1);
stbtt__tesselate_curve(points, num_points, mx, my, (x1 + x2) / 2.0f, (y1 + y2) / 2.0f, x2, y2, objspace_flatness_squared, n + 1);
}
else
{
stbtt__add_point(points, *num_points, x2, y2);
*num_points = *num_points + 1;
}
return 1;
}
static void stbtt__tesselate_cubic(stbtt__point* points, int* num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
{
// @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
float dx0 = x1 - x0;
float dy0 = y1 - y0;
float dx1 = x2 - x1;
float dy1 = y2 - y1;
float dx2 = x3 - x2;
float dy2 = y3 - y2;
float dx = x3 - x0;
float dy = y3 - y0;
float longlen = (float)(STBTT_sqrt(dx0 * dx0 + dy0 * dy0) + STBTT_sqrt(dx1 * dx1 + dy1 * dy1) + STBTT_sqrt(dx2 * dx2 + dy2 * dy2));
float shortlen = (float)STBTT_sqrt(dx * dx + dy * dy);
float flatness_squared = longlen * longlen - shortlen * shortlen;
if (n > 16) // 65536 segments on one curve better be enough!
return;
if (flatness_squared > objspace_flatness_squared)
{
float x01 = (x0 + x1) / 2;
float y01 = (y0 + y1) / 2;
float x12 = (x1 + x2) / 2;
float y12 = (y1 + y2) / 2;
float x23 = (x2 + x3) / 2;
float y23 = (y2 + y3) / 2;
float xa = (x01 + x12) / 2;
float ya = (y01 + y12) / 2;
float xb = (x12 + x23) / 2;
float yb = (y12 + y23) / 2;
float mx = (xa + xb) / 2;
float my = (ya + yb) / 2;
stbtt__tesselate_cubic(points, num_points, x0, y0, x01, y01, xa, ya, mx, my, objspace_flatness_squared, n + 1);
stbtt__tesselate_cubic(points, num_points, mx, my, xb, yb, x23, y23, x3, y3, objspace_flatness_squared, n + 1);
}
else
{
stbtt__add_point(points, *num_points, x3, y3);
*num_points = *num_points + 1;
}
}
// returns number of contours
static stbtt__point* stbtt_FlattenCurves(stbtt_vertex* vertices, int num_verts, float objspace_flatness, int** contour_lengths, int* num_contours, void* userdata)
{
stbtt__point* points = 0;
int num_points = 0;
float objspace_flatness_squared = objspace_flatness * objspace_flatness;
int i, n = 0, start = 0, pass;
// count how many "moves" there are to get the contour count
for (i = 0; i < num_verts; ++i)
if (vertices[i].type == STBTT_vmove)
++n;
*num_contours = n;
if (n == 0)
return 0;
*contour_lengths = (int*)STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
if (*contour_lengths == 0)
{
*num_contours = 0;
return 0;
}
// make two passes through the points so we don't need to realloc
for (pass = 0; pass < 2; ++pass)
{
float x = 0, y = 0;
if (pass == 1)
{
points = (stbtt__point*)STBTT_malloc(num_points * sizeof(points[0]), userdata);
if (points == NULL)
goto error;
}
num_points = 0;
n = -1;
for (i = 0; i < num_verts; ++i)
{
switch (vertices[i].type)
{
case STBTT_vmove:
// start the next contour
if (n >= 0)
(*contour_lengths)[n] = num_points - start;
++n;
start = num_points;
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x, y);
break;
case STBTT_vline:
x = vertices[i].x, y = vertices[i].y;
stbtt__add_point(points, num_points++, x, y);
break;
case STBTT_vcurve:
stbtt__tesselate_curve(points, &num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
case STBTT_vcubic:
stbtt__tesselate_cubic(points, &num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].cx1, vertices[i].cy1,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
}
}
(*contour_lengths)[n] = num_points - start;
}
return points;
error:
STBTT_free(points, userdata);
STBTT_free(*contour_lengths, userdata);
*contour_lengths = 0;
*num_contours = 0;
return NULL;
}
STBTT_DEF void stbtt_Rasterize(stbtt__bitmap* result, float flatness_in_pixels, stbtt_vertex* vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void* userdata)
{
float scale = scale_x > scale_y ? scale_y : scale_x;
int winding_count = 0;
int* winding_lengths = NULL;
stbtt__point* windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
if (windings)
{
stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
STBTT_free(winding_lengths, userdata);
STBTT_free(windings, userdata);
}
}
STBTT_DEF void stbtt_FreeBitmap(unsigned char* bitmap, void* userdata)
{
STBTT_free(bitmap, userdata);
}
STBTT_DEF unsigned char* stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo* info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int* width, int* height, int* xoff, int* yoff)
{
int ix0, iy0, ix1, iy1;
stbtt__bitmap gbm;
stbtt_vertex* vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
if (scale_x == 0)
scale_x = scale_y;
if (scale_y == 0)
{
if (scale_x == 0)
{
STBTT_free(vertices, info->userdata);
return NULL;
}
scale_y = scale_x;
}
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0, &iy0, &ix1, &iy1);
// now we get the size
gbm.w = (ix1 - ix0);
gbm.h = (iy1 - iy0);
gbm.pixels = NULL; // in case we error
if (width)
*width = gbm.w;
if (height)
*height = gbm.h;
if (xoff)
*xoff = ix0;
if (yoff)
*yoff = iy0;
if (gbm.w && gbm.h)
{
gbm.pixels = (unsigned char*)STBTT_malloc(gbm.w * gbm.h, info->userdata);
if (gbm.pixels)
{
gbm.stride = gbm.w;
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
}
}
STBTT_free(vertices, info->userdata);
return gbm.pixels;
}
STBTT_DEF unsigned char* stbtt_GetGlyphBitmap(const stbtt_fontinfo* info, float scale_x, float scale_y, int glyph, int* width, int* height, int* xoff, int* yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
{
int ix0, iy0;
stbtt_vertex* vertices;
int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
stbtt__bitmap gbm;
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0, &iy0, 0, 0);
gbm.pixels = output;
gbm.w = out_w;
gbm.h = out_h;
gbm.stride = out_stride;
if (gbm.w && gbm.h)
stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
STBTT_free(vertices, info->userdata);
}
STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f, 0.0f, glyph);
}
STBTT_DEF unsigned char* stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo* info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int* width, int* height, int* xoff, int* yoff)
{
return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info, codepoint), width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float* sub_x, float* sub_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info, codepoint));
}
STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
{
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info, codepoint));
}
STBTT_DEF unsigned char* stbtt_GetCodepointBitmap(const stbtt_fontinfo* info, float scale_x, float scale_y, int codepoint, int* width, int* height, int* xoff, int* yoff)
{
return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, codepoint, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
{
stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f, 0.0f, codepoint);
}
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-CRAPPY packing to keep source code small
static int stbtt_BakeFontBitmap_internal(unsigned char* data, int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
unsigned char* pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar* chardata)
{
float scale;
int x, y, bottom_y, i;
stbtt_fontinfo f;
f.userdata = NULL;
if (!stbtt_InitFont(&f, data, offset))
return -1;
STBTT_memset(pixels, 0, pw * ph); // background of 0 around pixels
x = y = 1;
bottom_y = 1;
scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
for (i = 0; i < num_chars; ++i)
{
int advance, lsb, x0, y0, x1, y1, gw, gh;
int g = stbtt_FindGlyphIndex(&f, first_char + i);
stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
stbtt_GetGlyphBitmapBox(&f, g, scale, scale, &x0, &y0, &x1, &y1);
gw = x1 - x0;
gh = y1 - y0;
if (x + gw + 1 >= pw)
y = bottom_y, x = 1; // advance to next row
if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
return -i;
STBTT_assert(x + gw < pw);
STBTT_assert(y + gh < ph);
stbtt_MakeGlyphBitmap(&f, pixels + x + y * pw, gw, gh, pw, scale, scale, g);
chardata[i].x0 = (stbtt_int16)x;
chardata[i].y0 = (stbtt_int16)y;
chardata[i].x1 = (stbtt_int16)(x + gw);
chardata[i].y1 = (stbtt_int16)(y + gh);
chardata[i].xadvance = scale * advance;
chardata[i].xoff = (float)x0;
chardata[i].yoff = (float)y0;
x = x + gw + 1;
if (y + gh + 1 > bottom_y)
bottom_y = y + gh + 1;
}
return bottom_y;
}
STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar* chardata, int pw, int ph, int char_index, float* xpos, float* ypos, stbtt_aligned_quad* q, int opengl_fillrule)
{
float d3d_bias = opengl_fillrule ? 0 : -0.5f;
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_bakedchar* b = chardata + char_index;
int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = round_x + d3d_bias;
q->y0 = round_y + d3d_bias;
q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// rectangle packing replacement routines if you don't have stb_rect_pack.h
//
#ifndef STB_RECT_PACK_VERSION
typedef int stbrp_coord;
////////////////////////////////////////////////////////////////////////////////////
// //
// //
// COMPILER WARNING ?!?!? //
// //
// //
// if you get a compile warning due to these symbols being defined more than //
// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
// //
////////////////////////////////////////////////////////////////////////////////////
typedef struct
{
int width, height;
int x, y, bottom_y;
} stbrp_context;
typedef struct
{
unsigned char x;
} stbrp_node;
struct stbrp_rect
{
stbrp_coord x, y;
int id, w, h, was_packed;
};
static void stbrp_init_target(stbrp_context* con, int pw, int ph, stbrp_node* nodes, int num_nodes)
{
con->width = pw;
con->height = ph;
con->x = 0;
con->y = 0;
con->bottom_y = 0;
STBTT__NOTUSED(nodes);
STBTT__NOTUSED(num_nodes);
}
static void stbrp_pack_rects(stbrp_context* con, stbrp_rect* rects, int num_rects)
{
int i;
for (i = 0; i < num_rects; ++i)
{
if (con->x + rects[i].w > con->width)
{
con->x = 0;
con->y = con->bottom_y;
}
if (con->y + rects[i].h > con->height)
break;
rects[i].x = con->x;
rects[i].y = con->y;
rects[i].was_packed = 1;
con->x += rects[i].w;
if (con->y + rects[i].h > con->bottom_y)
con->bottom_y = con->y + rects[i].h;
}
for (; i < num_rects; ++i)
rects[i].was_packed = 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// bitmap baking
//
// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context* spc, unsigned char* pixels, int pw, int ph, int stride_in_bytes, int padding, void* alloc_context)
{
stbrp_context* context = (stbrp_context*)STBTT_malloc(sizeof(*context), alloc_context);
int num_nodes = pw - padding;
stbrp_node* nodes = (stbrp_node*)STBTT_malloc(sizeof(*nodes) * num_nodes, alloc_context);
if (context == NULL || nodes == NULL)
{
if (context != NULL)
STBTT_free(context, alloc_context);
if (nodes != NULL)
STBTT_free(nodes, alloc_context);
return 0;
}
spc->user_allocator_context = alloc_context;
spc->width = pw;
spc->height = ph;
spc->pixels = pixels;
spc->pack_info = context;
spc->nodes = nodes;
spc->padding = padding;
spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
spc->h_oversample = 1;
spc->v_oversample = 1;
spc->skip_missing = 0;
stbrp_init_target(context, pw - padding, ph - padding, nodes, num_nodes);
if (pixels)
STBTT_memset(pixels, 0, pw * ph); // background of 0 around pixels
return 1;
}
STBTT_DEF void stbtt_PackEnd(stbtt_pack_context* spc)
{
STBTT_free(spc->nodes, spc->user_allocator_context);
STBTT_free(spc->pack_info, spc->user_allocator_context);
}
STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context* spc, unsigned int h_oversample, unsigned int v_oversample)
{
STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
if (h_oversample <= STBTT_MAX_OVERSAMPLE)
spc->h_oversample = h_oversample;
if (v_oversample <= STBTT_MAX_OVERSAMPLE)
spc->v_oversample = v_oversample;
}
STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context* spc, int skip)
{
spc->skip_missing = skip;
}
#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE - 1)
static void stbtt__h_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_w = w - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for (j = 0; j < h; ++j)
{
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch (kernel_width)
{
case 2:
for (i = 0; i <= safe_w; ++i)
{
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 2);
}
break;
case 3:
for (i = 0; i <= safe_w; ++i)
{
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 3);
}
break;
case 4:
for (i = 0; i <= safe_w; ++i)
{
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 4);
}
break;
case 5:
for (i = 0; i <= safe_w; ++i)
{
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / 5);
}
break;
default:
for (i = 0; i <= safe_w; ++i)
{
total += pixels[i] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i];
pixels[i] = (unsigned char)(total / kernel_width);
}
break;
}
for (; i < w; ++i)
{
STBTT_assert(pixels[i] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i] = (unsigned char)(total / kernel_width);
}
pixels += stride_in_bytes;
}
}
static void stbtt__v_prefilter(unsigned char* pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
{
unsigned char buffer[STBTT_MAX_OVERSAMPLE];
int safe_h = h - kernel_width;
int j;
STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze
for (j = 0; j < w; ++j)
{
int i;
unsigned int total;
STBTT_memset(buffer, 0, kernel_width);
total = 0;
// make kernel_width a constant in common cases so compiler can optimize out the divide
switch (kernel_width)
{
case 2:
for (i = 0; i <= safe_h; ++i)
{
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 2);
}
break;
case 3:
for (i = 0; i <= safe_h; ++i)
{
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 3);
}
break;
case 4:
for (i = 0; i <= safe_h; ++i)
{
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 4);
}
break;
case 5:
for (i = 0; i <= safe_h; ++i)
{
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / 5);
}
break;
default:
for (i = 0; i <= safe_h; ++i)
{
total += pixels[i * stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
buffer[(i + kernel_width) & STBTT__OVER_MASK] = pixels[i * stride_in_bytes];
pixels[i * stride_in_bytes] = (unsigned char)(total / kernel_width);
}
break;
}
for (; i < h; ++i)
{
STBTT_assert(pixels[i * stride_in_bytes] == 0);
total -= buffer[i & STBTT__OVER_MASK];
pixels[i * stride_in_bytes] = (unsigned char)(total / kernel_width);
}
pixels += 1;
}
}
static float stbtt__oversample_shift(int oversample)
{
if (!oversample)
return 0.0f;
// The prefilter is a box filter of width "oversample",
// which shifts phase by (oversample - 1)/2 pixels in
// oversampled space. We want to shift in the opposite
// direction to counter this.
return (float)-(oversample - 1) / (2.0f * (float)oversample);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context* spc, const stbtt_fontinfo* info, stbtt_pack_range* ranges, int num_ranges, stbrp_rect* rects)
{
int i, j, k;
int missing_glyph_added = 0;
k = 0;
for (i = 0; i < num_ranges; ++i)
{
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
ranges[i].h_oversample = (unsigned char)spc->h_oversample;
ranges[i].v_oversample = (unsigned char)spc->v_oversample;
for (j = 0; j < ranges[i].num_chars; ++j)
{
int x0, y0, x1, y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
if (glyph == 0 && (spc->skip_missing || missing_glyph_added))
{
rects[k].w = rects[k].h = 0;
}
else
{
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
0, 0,
&x0, &y0, &x1, &y1);
rects[k].w = (stbrp_coord)(x1 - x0 + spc->padding + spc->h_oversample - 1);
rects[k].h = (stbrp_coord)(y1 - y0 + spc->padding + spc->v_oversample - 1);
if (glyph == 0)
missing_glyph_added = 1;
}
++k;
}
}
return k;
}
STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo* info, unsigned char* output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float* sub_x, float* sub_y, int glyph)
{
stbtt_MakeGlyphBitmapSubpixel(info,
output,
out_w - (prefilter_x - 1),
out_h - (prefilter_y - 1),
out_stride,
scale_x,
scale_y,
shift_x,
shift_y,
glyph);
if (prefilter_x > 1)
stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);
if (prefilter_y > 1)
stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);
*sub_x = stbtt__oversample_shift(prefilter_x);
*sub_y = stbtt__oversample_shift(prefilter_y);
}
// rects array must be big enough to accommodate all characters in the given ranges
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context* spc, const stbtt_fontinfo* info, stbtt_pack_range* ranges, int num_ranges, stbrp_rect* rects)
{
int i, j, k, missing_glyph = -1, return_value = 1;
// save current values
int old_h_over = spc->h_oversample;
int old_v_over = spc->v_oversample;
k = 0;
for (i = 0; i < num_ranges; ++i)
{
float fh = ranges[i].font_size;
float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
float recip_h, recip_v, sub_x, sub_y;
spc->h_oversample = ranges[i].h_oversample;
spc->v_oversample = ranges[i].v_oversample;
recip_h = 1.0f / spc->h_oversample;
recip_v = 1.0f / spc->v_oversample;
sub_x = stbtt__oversample_shift(spc->h_oversample);
sub_y = stbtt__oversample_shift(spc->v_oversample);
for (j = 0; j < ranges[i].num_chars; ++j)
{
stbrp_rect* r = &rects[k];
if (r->was_packed && r->w != 0 && r->h != 0)
{
stbtt_packedchar* bc = &ranges[i].chardata_for_range[j];
int advance, lsb, x0, y0, x1, y1;
int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
int glyph = stbtt_FindGlyphIndex(info, codepoint);
stbrp_coord pad = (stbrp_coord)spc->padding;
// pad on left and top
r->x += pad;
r->y += pad;
r->w -= pad;
r->h -= pad;
stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
stbtt_GetGlyphBitmapBox(info, glyph,
scale * spc->h_oversample,
scale * spc->v_oversample,
&x0, &y0, &x1, &y1);
stbtt_MakeGlyphBitmapSubpixel(info,
spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w - spc->h_oversample + 1,
r->h - spc->v_oversample + 1,
spc->stride_in_bytes,
scale * spc->h_oversample,
scale * spc->v_oversample,
0, 0,
glyph);
if (spc->h_oversample > 1)
stbtt__h_prefilter(spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->h_oversample);
if (spc->v_oversample > 1)
stbtt__v_prefilter(spc->pixels + r->x + r->y * spc->stride_in_bytes,
r->w, r->h, spc->stride_in_bytes,
spc->v_oversample);
bc->x0 = (stbtt_int16)r->x;
bc->y0 = (stbtt_int16)r->y;
bc->x1 = (stbtt_int16)(r->x + r->w);
bc->y1 = (stbtt_int16)(r->y + r->h);
bc->xadvance = scale * advance;
bc->xoff = (float)x0 * recip_h + sub_x;
bc->yoff = (float)y0 * recip_v + sub_y;
bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
if (glyph == 0)
missing_glyph = j;
}
else if (spc->skip_missing)
{
return_value = 0;
}
else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0)
{
ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph];
}
else
{
return_value = 0; // if any fail, report failure
}
++k;
}
}
// restore original values
spc->h_oversample = old_h_over;
spc->v_oversample = old_v_over;
return return_value;
}
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context* spc, stbrp_rect* rects, int num_rects)
{
stbrp_pack_rects((stbrp_context*)spc->pack_info, rects, num_rects);
}
STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context* spc, const unsigned char* fontdata, int font_index, stbtt_pack_range* ranges, int num_ranges)
{
stbtt_fontinfo info;
int i, j, n, return_value = 1;
//stbrp_context *context = (stbrp_context *) spc->pack_info;
stbrp_rect* rects;
// flag all characters as NOT packed
for (i = 0; i < num_ranges; ++i)
for (j = 0; j < ranges[i].num_chars; ++j)
ranges[i].chardata_for_range[j].x0 =
ranges[i].chardata_for_range[j].y0 =
ranges[i].chardata_for_range[j].x1 =
ranges[i].chardata_for_range[j].y1 = 0;
n = 0;
for (i = 0; i < num_ranges; ++i)
n += ranges[i].num_chars;
rects = (stbrp_rect*)STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
if (rects == NULL)
return 0;
info.userdata = spc->user_allocator_context;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, font_index));
n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
stbtt_PackFontRangesPackRects(spc, rects, n);
return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
STBTT_free(rects, spc->user_allocator_context);
return return_value;
}
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context* spc, const unsigned char* fontdata, int font_index, float font_size,
int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar* chardata_for_range)
{
stbtt_pack_range range;
range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
range.array_of_unicode_codepoints = NULL;
range.num_chars = num_chars_in_range;
range.chardata_for_range = chardata_for_range;
range.font_size = font_size;
return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
}
STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char* fontdata, int index, float size, float* ascent, float* descent, float* lineGap)
{
int i_ascent, i_descent, i_lineGap;
float scale;
stbtt_fontinfo info;
stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));
scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);
stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);
*ascent = (float)i_ascent * scale;
*descent = (float)i_descent * scale;
*lineGap = (float)i_lineGap * scale;
}
STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar* chardata, int pw, int ph, int char_index, float* xpos, float* ypos, stbtt_aligned_quad* q, int align_to_integer)
{
float ipw = 1.0f / pw, iph = 1.0f / ph;
const stbtt_packedchar* b = chardata + char_index;
if (align_to_integer)
{
float x = (float)STBTT_ifloor((*xpos + b->xoff) + 0.5f);
float y = (float)STBTT_ifloor((*ypos + b->yoff) + 0.5f);
q->x0 = x;
q->y0 = y;
q->x1 = x + b->xoff2 - b->xoff;
q->y1 = y + b->yoff2 - b->yoff;
}
else
{
q->x0 = *xpos + b->xoff;
q->y0 = *ypos + b->yoff;
q->x1 = *xpos + b->xoff2;
q->y1 = *ypos + b->yoff2;
}
q->s0 = b->x0 * ipw;
q->t0 = b->y0 * iph;
q->s1 = b->x1 * ipw;
q->t1 = b->y1 * iph;
*xpos += b->xadvance;
}
//////////////////////////////////////////////////////////////////////////////
//
// sdf computation
//
#define STBTT_min(a, b) ((a) < (b) ? (a) : (b))
#define STBTT_max(a, b) ((a) < (b) ? (b) : (a))
static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])
{
float q0perp = q0[1] * ray[0] - q0[0] * ray[1];
float q1perp = q1[1] * ray[0] - q1[0] * ray[1];
float q2perp = q2[1] * ray[0] - q2[0] * ray[1];
float roperp = orig[1] * ray[0] - orig[0] * ray[1];
float a = q0perp - 2 * q1perp + q2perp;
float b = q1perp - q0perp;
float c = q0perp - roperp;
float s0 = 0., s1 = 0.;
int num_s = 0;
if (a != 0.0)
{
float discr = b * b - a * c;
if (discr > 0.0)
{
float rcpna = -1 / a;
float d = (float)STBTT_sqrt(discr);
s0 = (b + d) * rcpna;
s1 = (b - d) * rcpna;
if (s0 >= 0.0 && s0 <= 1.0)
num_s = 1;
if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0)
{
if (num_s == 0)
s0 = s1;
++num_s;
}
}
}
else
{
// 2*b*s + c = 0
// s = -c / (2*b)
s0 = c / (-2 * b);
if (s0 >= 0.0 && s0 <= 1.0)
num_s = 1;
}
if (num_s == 0)
return 0;
else
{
float rcp_len2 = 1 / (ray[0] * ray[0] + ray[1] * ray[1]);
float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;
float q0d = q0[0] * rayn_x + q0[1] * rayn_y;
float q1d = q1[0] * rayn_x + q1[1] * rayn_y;
float q2d = q2[0] * rayn_x + q2[1] * rayn_y;
float rod = orig[0] * rayn_x + orig[1] * rayn_y;
float q10d = q1d - q0d;
float q20d = q2d - q0d;
float q0rd = q0d - rod;
hits[0][0] = q0rd + s0 * (2.0f - 2.0f * s0) * q10d + s0 * s0 * q20d;
hits[0][1] = a * s0 + b;
if (num_s > 1)
{
hits[1][0] = q0rd + s1 * (2.0f - 2.0f * s1) * q10d + s1 * s1 * q20d;
hits[1][1] = a * s1 + b;
return 2;
}
else
{
return 1;
}
}
}
static int equal(float* a, float* b)
{
return (a[0] == b[0] && a[1] == b[1]);
}
static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex* verts)
{
int i;
float orig[2], ray[2] = { 1, 0 };
float y_frac;
int winding = 0;
// make sure y never passes through a vertex of the shape
y_frac = (float)STBTT_fmod(y, 1.0f);
if (y_frac < 0.01f)
y += 0.01f;
else if (y_frac > 0.99f)
y -= 0.01f;
orig[0] = x;
orig[1] = y;
// test a ray from (-infinity,y) to (x,y)
for (i = 0; i < nverts; ++i)
{
if (verts[i].type == STBTT_vline)
{
int x0 = (int)verts[i - 1].x, y0 = (int)verts[i - 1].y;
int x1 = (int)verts[i].x, y1 = (int)verts[i].y;
if (y > STBTT_min(y0, y1) && y < STBTT_max(y0, y1) && x > STBTT_min(x0, x1))
{
float x_inter = (y - y0) / (y1 - y0) * (x1 - x0) + x0;
if (x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
}
if (verts[i].type == STBTT_vcurve)
{
int x0 = (int)verts[i - 1].x, y0 = (int)verts[i - 1].y;
int x1 = (int)verts[i].cx, y1 = (int)verts[i].cy;
int x2 = (int)verts[i].x, y2 = (int)verts[i].y;
int ax = STBTT_min(x0, STBTT_min(x1, x2)), ay = STBTT_min(y0, STBTT_min(y1, y2));
int by = STBTT_max(y0, STBTT_max(y1, y2));
if (y > ay && y < by && x > ax)
{
float q0[2], q1[2], q2[2];
float hits[2][2];
q0[0] = (float)x0;
q0[1] = (float)y0;
q1[0] = (float)x1;
q1[1] = (float)y1;
q2[0] = (float)x2;
q2[1] = (float)y2;
if (equal(q0, q1) || equal(q1, q2))
{
x0 = (int)verts[i - 1].x;
y0 = (int)verts[i - 1].y;
x1 = (int)verts[i].x;
y1 = (int)verts[i].y;
if (y > STBTT_min(y0, y1) && y < STBTT_max(y0, y1) && x > STBTT_min(x0, x1))
{
float x_inter = (y - y0) / (y1 - y0) * (x1 - x0) + x0;
if (x_inter < x)
winding += (y0 < y1) ? 1 : -1;
}
}
else
{
int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);
if (num_hits >= 1)
if (hits[0][0] < 0)
winding += (hits[0][1] < 0 ? -1 : 1);
if (num_hits >= 2)
if (hits[1][0] < 0)
winding += (hits[1][1] < 0 ? -1 : 1);
}
}
}
}
return winding;
}
static float stbtt__cuberoot(float x)
{
if (x < 0)
return -(float)STBTT_pow(-x, 1.0f / 3.0f);
else
return (float)STBTT_pow(x, 1.0f / 3.0f);
}
// x^3 + a*x^2 + b*x + c = 0
static int stbtt__solve_cubic(float a, float b, float c, float* r)
{
float s = -a / 3;
float p = b - a * a / 3;
float q = a * (2 * a * a - 9 * b) / 27 + c;
float p3 = p * p * p;
float d = q * q + 4 * p3 / 27;
if (d >= 0)
{
float z = (float)STBTT_sqrt(d);
float u = (-q + z) / 2;
float v = (-q - z) / 2;
u = stbtt__cuberoot(u);
v = stbtt__cuberoot(v);
r[0] = s + u + v;
return 1;
}
else
{
float u = (float)STBTT_sqrt(-p / 3);
float v = (float)STBTT_acos(-STBTT_sqrt(-27 / p3) * q / 2) / 3; // p3 must be negative, since d is negative
float m = (float)STBTT_cos(v);
float n = (float)STBTT_cos(v - 3.141592 / 2) * 1.732050808f;
r[0] = s + u * 2 * m;
r[1] = s - u * (m + n);
r[2] = s - u * (m - n);
//STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?
//STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);
//STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);
return 3;
}
}
STBTT_DEF unsigned char* stbtt_GetGlyphSDF(const stbtt_fontinfo* info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int* width, int* height, int* xoff, int* yoff)
{
float scale_x = scale, scale_y = scale;
int ix0, iy0, ix1, iy1;
int w, h;
unsigned char* data;
if (scale == 0)
return NULL;
stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f, 0.0f, &ix0, &iy0, &ix1, &iy1);
// if empty, return NULL
if (ix0 == ix1 || iy0 == iy1)
return NULL;
ix0 -= padding;
iy0 -= padding;
ix1 += padding;
iy1 += padding;
w = (ix1 - ix0);
h = (iy1 - iy0);
if (width)
*width = w;
if (height)
*height = h;
if (xoff)
*xoff = ix0;
if (yoff)
*yoff = iy0;
// invert for y-downwards bitmaps
scale_y = -scale_y;
{
int x, y, i, j;
float* precompute;
stbtt_vertex* verts;
int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);
data = (unsigned char*)STBTT_malloc(w * h, info->userdata);
precompute = (float*)STBTT_malloc(num_verts * sizeof(float), info->userdata);
for (i = 0, j = num_verts - 1; i < num_verts; j = i++)
{
if (verts[i].type == STBTT_vline)
{
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
float x1 = verts[j].x * scale_x, y1 = verts[j].y * scale_y;
float dist = (float)STBTT_sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;
}
else if (verts[i].type == STBTT_vcurve)
{
float x2 = verts[j].x * scale_x, y2 = verts[j].y * scale_y;
float x1 = verts[i].cx * scale_x, y1 = verts[i].cy * scale_y;
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
float bx = x0 - 2 * x1 + x2, by = y0 - 2 * y1 + y2;
float len2 = bx * bx + by * by;
if (len2 != 0.0f)
precompute[i] = 1.0f / (bx * bx + by * by);
else
precompute[i] = 0.0f;
}
else
precompute[i] = 0.0f;
}
for (y = iy0; y < iy1; ++y)
{
for (x = ix0; x < ix1; ++x)
{
float val;
float min_dist = 999999.0f;
float sx = (float)x + 0.5f;
float sy = (float)y + 0.5f;
float x_gspace = (sx / scale_x);
float y_gspace = (sy / scale_y);
int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path
for (i = 0; i < num_verts; ++i)
{
float x0 = verts[i].x * scale_x, y0 = verts[i].y * scale_y;
if (verts[i].type == STBTT_vline && precompute[i] != 0.0f)
{
float x1 = verts[i - 1].x * scale_x, y1 = verts[i - 1].y * scale_y;
float dist, dist2 = (x0 - sx) * (x0 - sx) + (y0 - sy) * (y0 - sy);
if (dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
// coarse culling against bbox
//if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&
// sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)
dist = (float)STBTT_fabs((x1 - x0) * (y0 - sy) - (y1 - y0) * (x0 - sx)) * precompute[i];
STBTT_assert(i != 0);
if (dist < min_dist)
{
// check position along line
// x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)
// minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)
float dx = x1 - x0, dy = y1 - y0;
float px = x0 - sx, py = y0 - sy;
// minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy
// derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve
float t = -(px * dx + py * dy) / (dx * dx + dy * dy);
if (t >= 0.0f && t <= 1.0f)
min_dist = dist;
}
}
else if (verts[i].type == STBTT_vcurve)
{
float x2 = verts[i - 1].x * scale_x, y2 = verts[i - 1].y * scale_y;
float x1 = verts[i].cx * scale_x, y1 = verts[i].cy * scale_y;
float box_x0 = STBTT_min(STBTT_min(x0, x1), x2);
float box_y0 = STBTT_min(STBTT_min(y0, y1), y2);
float box_x1 = STBTT_max(STBTT_max(x0, x1), x2);
float box_y1 = STBTT_max(STBTT_max(y0, y1), y2);
// coarse culling against bbox to avoid computing cubic unnecessarily
if (sx > box_x0 - min_dist && sx < box_x1 + min_dist && sy > box_y0 - min_dist && sy < box_y1 + min_dist)
{
int num = 0;
float ax = x1 - x0, ay = y1 - y0;
float bx = x0 - 2 * x1 + x2, by = y0 - 2 * y1 + y2;
float mx = x0 - sx, my = y0 - sy;
float res[3] = { 0.f, 0.f, 0.f };
float px, py, t, it, dist2;
float a_inv = precompute[i];
if (a_inv == 0.0)
{ // if a_inv is 0, it's 2nd degree so use quadratic formula
float a = 3 * (ax * bx + ay * by);
float b = 2 * (ax * ax + ay * ay) + (mx * bx + my * by);
float c = mx * ax + my * ay;
if (a == 0.0)
{ // if a is 0, it's linear
if (b != 0.0)
{
res[num++] = -c / b;
}
}
else
{
float discriminant = b * b - 4 * a * c;
if (discriminant < 0)
num = 0;
else
{
float root = (float)STBTT_sqrt(discriminant);
res[0] = (-b - root) / (2 * a);
res[1] = (-b + root) / (2 * a);
num = 2; // don't bother distinguishing 1-solution case, as code below will still work
}
}
}
else
{
float b = 3 * (ax * bx + ay * by) * a_inv; // could precompute this as it doesn't depend on sample point
float c = (2 * (ax * ax + ay * ay) + (mx * bx + my * by)) * a_inv;
float d = (mx * ax + my * ay) * a_inv;
num = stbtt__solve_cubic(b, c, d, res);
}
dist2 = (x0 - sx) * (x0 - sx) + (y0 - sy) * (y0 - sy);
if (dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f)
{
t = res[0], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if (dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f)
{
t = res[1], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if (dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f)
{
t = res[2], it = 1.0f - t;
px = it * it * x0 + 2 * t * it * x1 + t * t * x2;
py = it * it * y0 + 2 * t * it * y1 + t * t * y2;
dist2 = (px - sx) * (px - sx) + (py - sy) * (py - sy);
if (dist2 < min_dist * min_dist)
min_dist = (float)STBTT_sqrt(dist2);
}
}
}
}
if (winding == 0)
min_dist = -min_dist; // if outside the shape, value is negative
val = onedge_value + pixel_dist_scale * min_dist;
if (val < 0)
val = 0;
else if (val > 255)
val = 255;
data[(y - iy0) * w + (x - ix0)] = (unsigned char)val;
}
}
STBTT_free(precompute, info->userdata);
STBTT_free(verts, info->userdata);
}
return data;
}
STBTT_DEF unsigned char* stbtt_GetCodepointSDF(const stbtt_fontinfo* info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int* width, int* height, int* xoff, int* yoff)
{
return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);
}
STBTT_DEF void stbtt_FreeSDF(unsigned char* bitmap, void* userdata)
{
STBTT_free(bitmap, userdata);
}
//////////////////////////////////////////////////////////////////////////////
//
// font name matching -- recommended not to use this
//
// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8* s1, stbtt_int32 len1, stbtt_uint8* s2, stbtt_int32 len2)
{
stbtt_int32 i = 0;
// convert utf16 to utf8 and compare the results while converting
while (len2)
{
stbtt_uint16 ch = s2[0] * 256 + s2[1];
if (ch < 0x80)
{
if (i >= len1)
return -1;
if (s1[i++] != ch)
return -1;
}
else if (ch < 0x800)
{
if (i + 1 >= len1)
return -1;
if (s1[i++] != 0xc0 + (ch >> 6))
return -1;
if (s1[i++] != 0x80 + (ch & 0x3f))
return -1;
}
else if (ch >= 0xd800 && ch < 0xdc00)
{
stbtt_uint32 c;
stbtt_uint16 ch2 = s2[2] * 256 + s2[3];
if (i + 3 >= len1)
return -1;
c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
if (s1[i++] != 0xf0 + (c >> 18))
return -1;
if (s1[i++] != 0x80 + ((c >> 12) & 0x3f))
return -1;
if (s1[i++] != 0x80 + ((c >> 6) & 0x3f))
return -1;
if (s1[i++] != 0x80 + ((c)&0x3f))
return -1;
s2 += 2; // plus another 2 below
len2 -= 2;
}
else if (ch >= 0xdc00 && ch < 0xe000)
{
return -1;
}
else
{
if (i + 2 >= len1)
return -1;
if (s1[i++] != 0xe0 + (ch >> 12))
return -1;
if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f))
return -1;
if (s1[i++] != 0x80 + ((ch)&0x3f))
return -1;
}
s2 += 2;
len2 -= 2;
}
return i;
}
static int stbtt_CompareUTF8toUTF16_bigendian_internal(char* s1, int len1, char* s2, int len2)
{
return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*)s1, len1, (stbtt_uint8*)s2, len2);
}
// returns results in whatever encoding you request... but note that 2-byte encodings
// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
STBTT_DEF const char* stbtt_GetFontNameString(const stbtt_fontinfo* font, int* length, int platformID, int encodingID, int languageID, int nameID)
{
stbtt_int32 i, count, stringOffset;
stbtt_uint8* fc = font->data;
stbtt_uint32 offset = font->fontstart;
stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
if (!nm)
return NULL;
count = ttUSHORT(fc + nm + 2);
stringOffset = nm + ttUSHORT(fc + nm + 4);
for (i = 0; i < count; ++i)
{
stbtt_uint32 loc = nm + 6 + 12 * i;
if (platformID == ttUSHORT(fc + loc + 0) && encodingID == ttUSHORT(fc + loc + 2) && languageID == ttUSHORT(fc + loc + 4) && nameID == ttUSHORT(fc + loc + 6))
{
*length = ttUSHORT(fc + loc + 8);
return (const char*)(fc + stringOffset + ttUSHORT(fc + loc + 10));
}
}
return NULL;
}
static int stbtt__matchpair(stbtt_uint8* fc, stbtt_uint32 nm, stbtt_uint8* name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
{
stbtt_int32 i;
stbtt_int32 count = ttUSHORT(fc + nm + 2);
stbtt_int32 stringOffset = nm + ttUSHORT(fc + nm + 4);
for (i = 0; i < count; ++i)
{
stbtt_uint32 loc = nm + 6 + 12 * i;
stbtt_int32 id = ttUSHORT(fc + loc + 6);
if (id == target_id)
{
// find the encoding
stbtt_int32 platform = ttUSHORT(fc + loc + 0), encoding = ttUSHORT(fc + loc + 2), language = ttUSHORT(fc + loc + 4);
// is this a Unicode encoding?
if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10))
{
stbtt_int32 slen = ttUSHORT(fc + loc + 8);
stbtt_int32 off = ttUSHORT(fc + loc + 10);
// check if there's a prefix match
stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc + stringOffset + off, slen);
if (matchlen >= 0)
{
// check for target_id+1 immediately following, with same encoding & language
if (i + 1 < count && ttUSHORT(fc + loc + 12 + 6) == next_id && ttUSHORT(fc + loc + 12) == platform && ttUSHORT(fc + loc + 12 + 2) == encoding && ttUSHORT(fc + loc + 12 + 4) == language)
{
slen = ttUSHORT(fc + loc + 12 + 8);
off = ttUSHORT(fc + loc + 12 + 10);
if (slen == 0)
{
if (matchlen == nlen)
return 1;
}
else if (matchlen < nlen && name[matchlen] == ' ')
{
++matchlen;
if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*)(name + matchlen), nlen - matchlen, (char*)(fc + stringOffset + off), slen))
return 1;
}
}
else
{
// if nothing immediately following
if (matchlen == nlen)
return 1;
}
}
}
// @TODO handle other encodings
}
}
return 0;
}
static int stbtt__matches(stbtt_uint8* fc, stbtt_uint32 offset, stbtt_uint8* name, stbtt_int32 flags)
{
stbtt_int32 nlen = (stbtt_int32)STBTT_strlen((char*)name);
stbtt_uint32 nm, hd;
if (!stbtt__isfont(fc + offset))
return 0;
// check italics/bold/underline flags in macStyle...
if (flags)
{
hd = stbtt__find_table(fc, offset, "head");
if ((ttUSHORT(fc + hd + 44) & 7) != (flags & 7))
return 0;
}
nm = stbtt__find_table(fc, offset, "name");
if (!nm)
return 0;
if (flags)
{
// if we checked the macStyle flags, then just check the family and ignore the subfamily
if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))
return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 1, -1))
return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 3, -1))
return 1;
}
else
{
if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))
return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 1, 2))
return 1;
if (stbtt__matchpair(fc, nm, name, nlen, 3, -1))
return 1;
}
return 0;
}
static int stbtt_FindMatchingFont_internal(unsigned char* font_collection, char* name_utf8, stbtt_int32 flags)
{
stbtt_int32 i;
for (i = 0;; ++i)
{
stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
if (off < 0)
return off;
if (stbtt__matches((stbtt_uint8*)font_collection, off, (stbtt_uint8*)name_utf8, flags))
return off;
}
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char* data, int offset,
float pixel_height, unsigned char* pixels, int pw, int ph,
int first_char, int num_chars, stbtt_bakedchar* chardata)
{
return stbtt_BakeFontBitmap_internal((unsigned char*)data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);
}
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char* data, int index)
{
return stbtt_GetFontOffsetForIndex_internal((unsigned char*)data, index);
}
STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char* data)
{
return stbtt_GetNumberOfFonts_internal((unsigned char*)data);
}
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo* info, const unsigned char* data, int offset)
{
return stbtt_InitFont_internal(info, (unsigned char*)data, offset);
}
STBTT_DEF int stbtt_FindMatchingFont(const unsigned char* fontdata, const char* name, int flags)
{
return stbtt_FindMatchingFont_internal((unsigned char*)fontdata, (char*)name, flags);
}
STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char* s1, int len1, const char* s2, int len2)
{
return stbtt_CompareUTF8toUTF16_bigendian_internal((char*)s1, len1, (char*)s2, len2);
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#endif // STB_TRUETYPE_IMPLEMENTATION
// FULL VERSION HISTORY
//
// 1.25 (2021-07-11) many fixes
// 1.24 (2020-02-05) fix warning
// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS)
// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined
// 1.21 (2019-02-25) fix warning
// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()
// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod
// 1.18 (2018-01-29) add missing function
// 1.17 (2017-07-23) make more arguments const; doc fix
// 1.16 (2017-07-12) SDF support
// 1.15 (2017-03-03) make more arguments const
// 1.14 (2017-01-16) num-fonts-in-TTC function
// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) allow user-defined fabs() replacement
// fix memory leak if fontsize=0.0
// fix warning from duplicate typedef
// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges
// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
// allow PackFontRanges to pack and render in separate phases;
// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
// fixed an assert() bug in the new rasterizer
// replace assert() with STBTT_assert() in new rasterizer
// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
// also more precise AA rasterizer, except if shapes overlap
// remove need for STBTT_sort
// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
// 1.04 (2015-04-15) typo in example
// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
// non-oversampled; STBTT_POINT_SIZE for packed case only
// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
// 0.8b (2014-07-07) fix a warning
// 0.8 (2014-05-25) fix a few more warnings
// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
// 0.6c (2012-07-24) improve documentation
// 0.6b (2012-07-20) fix a few more warnings
// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
// 0.5 (2011-12-09) bugfixes:
// subpixel glyph renderer computed wrong bounding box
// first vertex of shape can be off-curve (FreeSans)
// 0.4b (2011-12-03) fixed an error in the font baking example
// 0.4 (2011-12-01) kerning, subpixel rendering (tor)
// bugfixes for:
// codepoint-to-glyph conversion using table fmt=12
// codepoint-to-glyph conversion using table fmt=4
// stbtt_GetBakedQuad with non-square texture (Zer)
// updated Hello World! sample to use kerning and subpixel
// fixed some warnings
// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
// userdata, malloc-from-userdata, non-zero fill (stb)
// 0.2 (2009-03-11) Fix unsigned/signed char warnings
// 0.1 (2009-03-09) First public release
//
/*
your_sha256_hash--------------
This software is available under 2 licenses -- choose whichever you prefer.
your_sha256_hash--------------
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
your_sha256_hash--------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
your_sha256_hash--------------
*/
``` | /content/code_sandbox/libs/nanovg/nanovg/stb_truetype.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 60,862 |
```objective-c
//
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef NANOVG_GL_UTILS_H
#define NANOVG_GL_UTILS_H
struct NVGLUframebuffer {
NVGcontext* ctx;
GLuint fbo;
GLuint rbo;
GLuint texture;
int image;
};
typedef struct NVGLUframebuffer NVGLUframebuffer;
// Helper function to create GL frame buffer to render to.
void nvgluBindFramebuffer(NVGLUframebuffer* fb);
NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* ctx, int w, int h, int imageFlags);
void nvgluDeleteFramebuffer(NVGLUframebuffer* fb);
#endif // NANOVG_GL_UTILS_H
#ifdef NANOVG_GL_IMPLEMENTATION
#if defined(NANOVG_GL3) || defined(NANOVG_GLES2) || defined(NANOVG_GLES3)
// FBO is core in OpenGL 3>.
# define NANOVG_FBO_VALID 1
#elif defined(NANOVG_GL2)
// On OS X including glext defines FBO on GL2 too.
# ifdef __APPLE__
# include <OpenGL/glext.h>
# define NANOVG_FBO_VALID 1
# endif
#endif
static GLint defaultFBO = -1;
NVGLUframebuffer* nvgluCreateFramebuffer(NVGcontext* ctx, int w, int h, int imageFlags)
{
#ifdef NANOVG_FBO_VALID
GLint defaultFBO;
GLint defaultRBO;
NVGLUframebuffer* fb = NULL;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
glGetIntegerv(GL_RENDERBUFFER_BINDING, &defaultRBO);
fb = (NVGLUframebuffer*)malloc(sizeof(NVGLUframebuffer));
if (fb == NULL) goto error;
memset(fb, 0, sizeof(NVGLUframebuffer));
fb->image = nvgCreateImageRGBA(ctx, w, h, imageFlags | NVG_IMAGE_FLIPY | NVG_IMAGE_PREMULTIPLIED, NULL);
#if defined NANOVG_GL2
fb->texture = nvglImageHandleGL2(ctx, fb->image);
#elif defined NANOVG_GL3
fb->texture = nvglImageHandleGL3(ctx, fb->image);
#elif defined NANOVG_GLES2
fb->texture = nvglImageHandleGLES2(ctx, fb->image);
#elif defined NANOVG_GLES3
fb->texture = nvglImageHandleGLES3(ctx, fb->image);
#endif
fb->ctx = ctx;
// frame buffer object
glGenFramebuffers(1, &fb->fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fb->fbo);
// render buffer object
glGenRenderbuffers(1, &fb->rbo);
glBindRenderbuffer(GL_RENDERBUFFER, fb->rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, w, h);
// combine all
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
#ifdef GL_DEPTH24_STENCIL8
// If GL_STENCIL_INDEX8 is not supported, try GL_DEPTH24_STENCIL8 as a fallback.
// Some graphics cards require a depth buffer along with a stencil.
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
#endif // GL_DEPTH24_STENCIL8
goto error;
}
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO);
return fb;
error:
glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
glBindRenderbuffer(GL_RENDERBUFFER, defaultRBO);
nvgluDeleteFramebuffer(fb);
return NULL;
#else
NVG_NOTUSED(ctx);
NVG_NOTUSED(w);
NVG_NOTUSED(h);
NVG_NOTUSED(imageFlags);
return NULL;
#endif
}
void nvgluBindFramebuffer(NVGLUframebuffer* fb)
{
#ifdef NANOVG_FBO_VALID
if (defaultFBO == -1) glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
glBindFramebuffer(GL_FRAMEBUFFER, fb != NULL ? fb->fbo : defaultFBO);
#else
NVG_NOTUSED(fb);
#endif
}
void nvgluDeleteFramebuffer(NVGLUframebuffer* fb)
{
#ifdef NANOVG_FBO_VALID
if (fb == NULL) return;
if (fb->fbo != 0)
glDeleteFramebuffers(1, &fb->fbo);
if (fb->rbo != 0)
glDeleteRenderbuffers(1, &fb->rbo);
if (fb->image >= 0)
nvgDeleteImage(fb->ctx, fb->image);
fb->ctx = NULL;
fb->fbo = 0;
fb->rbo = 0;
fb->texture = 0;
fb->image = -1;
free(fb);
#else
NVG_NOTUSED(fb);
#endif
}
#endif // NANOVG_GL_IMPLEMENTATION
``` | /content/code_sandbox/libs/nanovg/nanovg/nanovg_gl_utils.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,333 |
```c
//
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <memory.h>
#include "nanovg.h"
#define FONTSTASH_IMPLEMENTATION
#include "fontstash.h"
#ifndef NVG_NO_STB
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif
#ifdef _MSC_VER
#pragma warning(disable: 4100) // unreferenced formal parameter
#pragma warning(disable: 4127) // conditional expression is constant
#pragma warning(disable: 4204) // nonstandard extension used : non-constant aggregate initializer
#pragma warning(disable: 4706) // assignment within conditional expression
#endif
#define NVG_INIT_FONTIMAGE_SIZE 512
#define NVG_MAX_FONTIMAGE_SIZE 2048
#define NVG_MAX_FONTIMAGES 4
#define NVG_INIT_COMMANDS_SIZE 256
#define NVG_INIT_POINTS_SIZE 128
#define NVG_INIT_PATHS_SIZE 16
#define NVG_INIT_VERTS_SIZE 256
#ifndef NVG_MAX_STATES
#define NVG_MAX_STATES 32
#endif
#define NVG_KAPPA90 0.5522847493f // Length proportional to radius of a cubic bezier handle for 90deg arcs.
#define NVG_COUNTOF(arr) (sizeof(arr) / sizeof(0[arr]))
enum NVGcommands {
NVG_MOVETO = 0,
NVG_LINETO = 1,
NVG_BEZIERTO = 2,
NVG_CLOSE = 3,
NVG_WINDING = 4,
};
enum NVGpointFlags
{
NVG_PT_CORNER = 0x01,
NVG_PT_LEFT = 0x02,
NVG_PT_BEVEL = 0x04,
NVG_PR_INNERBEVEL = 0x08,
};
struct NVGstate {
NVGcompositeOperationState compositeOperation;
int shapeAntiAlias;
NVGpaint fill;
NVGpaint stroke;
float strokeWidth;
float miterLimit;
int lineJoin;
int lineCap;
float alpha;
float xform[6];
NVGscissor scissor;
float fontSize;
float letterSpacing;
float lineHeight;
float fontBlur;
int textAlign;
int fontId;
};
typedef struct NVGstate NVGstate;
struct NVGpoint {
float x,y;
float dx, dy;
float len;
float dmx, dmy;
unsigned char flags;
};
typedef struct NVGpoint NVGpoint;
struct NVGpathCache {
NVGpoint* points;
int npoints;
int cpoints;
NVGpath* paths;
int npaths;
int cpaths;
NVGvertex* verts;
int nverts;
int cverts;
float bounds[4];
};
typedef struct NVGpathCache NVGpathCache;
struct NVGcontext {
NVGparams params;
float* commands;
int ccommands;
int ncommands;
float commandx, commandy;
NVGstate states[NVG_MAX_STATES];
int nstates;
NVGpathCache* cache;
float tessTol;
float distTol;
float fringeWidth;
float devicePxRatio;
struct FONScontext* fs;
int fontImages[NVG_MAX_FONTIMAGES];
int fontImageIdx;
int drawCallCount;
int fillTriCount;
int strokeTriCount;
int textTriCount;
};
static float nvg__sqrtf(float a) { return sqrtf(a); }
static float nvg__modf(float a, float b) { return fmodf(a, b); }
static float nvg__sinf(float a) { return sinf(a); }
static float nvg__cosf(float a) { return cosf(a); }
static float nvg__tanf(float a) { return tanf(a); }
static float nvg__atan2f(float a,float b) { return atan2f(a, b); }
static float nvg__acosf(float a) { return acosf(a); }
static int nvg__mini(int a, int b) { return a < b ? a : b; }
static int nvg__maxi(int a, int b) { return a > b ? a : b; }
static int nvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); }
static float nvg__minf(float a, float b) { return a < b ? a : b; }
static float nvg__maxf(float a, float b) { return a > b ? a : b; }
static float nvg__absf(float a) { return a >= 0.0f ? a : -a; }
static float nvg__signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; }
static float nvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
static float nvg__cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; }
static float nvg__normalize(float *x, float* y)
{
float d = nvg__sqrtf((*x)*(*x) + (*y)*(*y));
if (d > 1e-6f) {
float id = 1.0f / d;
*x *= id;
*y *= id;
}
return d;
}
static void nvg__deletePathCache(NVGpathCache* c)
{
if (c == NULL) return;
if (c->points != NULL) free(c->points);
if (c->paths != NULL) free(c->paths);
if (c->verts != NULL) free(c->verts);
free(c);
}
static NVGpathCache* nvg__allocPathCache(void)
{
NVGpathCache* c = (NVGpathCache*)malloc(sizeof(NVGpathCache));
if (c == NULL) goto error;
memset(c, 0, sizeof(NVGpathCache));
c->points = (NVGpoint*)malloc(sizeof(NVGpoint)*NVG_INIT_POINTS_SIZE);
if (!c->points) goto error;
c->npoints = 0;
c->cpoints = NVG_INIT_POINTS_SIZE;
c->paths = (NVGpath*)malloc(sizeof(NVGpath)*NVG_INIT_PATHS_SIZE);
if (!c->paths) goto error;
c->npaths = 0;
c->cpaths = NVG_INIT_PATHS_SIZE;
c->verts = (NVGvertex*)malloc(sizeof(NVGvertex)*NVG_INIT_VERTS_SIZE);
if (!c->verts) goto error;
c->nverts = 0;
c->cverts = NVG_INIT_VERTS_SIZE;
return c;
error:
nvg__deletePathCache(c);
return NULL;
}
static void nvg__setDevicePixelRatio(NVGcontext* ctx, float ratio)
{
ctx->tessTol = 0.25f / ratio;
ctx->distTol = 0.01f / ratio;
ctx->fringeWidth = 1.0f / ratio;
ctx->devicePxRatio = ratio;
}
static NVGcompositeOperationState nvg__compositeOperationState(int op)
{
int sfactor, dfactor;
if (op == NVG_SOURCE_OVER)
{
sfactor = NVG_ONE;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_SOURCE_IN)
{
sfactor = NVG_DST_ALPHA;
dfactor = NVG_ZERO;
}
else if (op == NVG_SOURCE_OUT)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ZERO;
}
else if (op == NVG_ATOP)
{
sfactor = NVG_DST_ALPHA;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_OVER)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ONE;
}
else if (op == NVG_DESTINATION_IN)
{
sfactor = NVG_ZERO;
dfactor = NVG_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_OUT)
{
sfactor = NVG_ZERO;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_ATOP)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_SRC_ALPHA;
}
else if (op == NVG_LIGHTER)
{
sfactor = NVG_ONE;
dfactor = NVG_ONE;
}
else if (op == NVG_COPY)
{
sfactor = NVG_ONE;
dfactor = NVG_ZERO;
}
else if (op == NVG_XOR)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else
{
sfactor = NVG_ONE;
dfactor = NVG_ZERO;
}
NVGcompositeOperationState state;
state.srcRGB = sfactor;
state.dstRGB = dfactor;
state.srcAlpha = sfactor;
state.dstAlpha = dfactor;
return state;
}
static NVGstate* nvg__getState(NVGcontext* ctx)
{
return &ctx->states[ctx->nstates-1];
}
NVGcontext* nvgCreateInternal(NVGparams* params)
{
FONSparams fontParams;
NVGcontext* ctx = (NVGcontext*)malloc(sizeof(NVGcontext));
int i;
if (ctx == NULL) goto error;
memset(ctx, 0, sizeof(NVGcontext));
ctx->params = *params;
for (i = 0; i < NVG_MAX_FONTIMAGES; i++)
ctx->fontImages[i] = 0;
ctx->commands = (float*)malloc(sizeof(float)*NVG_INIT_COMMANDS_SIZE);
if (!ctx->commands) goto error;
ctx->ncommands = 0;
ctx->ccommands = NVG_INIT_COMMANDS_SIZE;
ctx->cache = nvg__allocPathCache();
if (ctx->cache == NULL) goto error;
nvgSave(ctx);
nvgReset(ctx);
nvg__setDevicePixelRatio(ctx, 1.0f);
if (ctx->params.renderCreate(ctx->params.userPtr) == 0) goto error;
// Init font rendering
memset(&fontParams, 0, sizeof(fontParams));
fontParams.width = NVG_INIT_FONTIMAGE_SIZE;
fontParams.height = NVG_INIT_FONTIMAGE_SIZE;
fontParams.flags = FONS_ZERO_TOPLEFT;
fontParams.renderCreate = NULL;
fontParams.renderUpdate = NULL;
fontParams.renderDraw = NULL;
fontParams.renderDelete = NULL;
fontParams.userPtr = NULL;
ctx->fs = fonsCreateInternal(&fontParams);
if (ctx->fs == NULL) goto error;
// Create font texture
ctx->fontImages[0] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, NULL);
if (ctx->fontImages[0] == 0) goto error;
ctx->fontImageIdx = 0;
return ctx;
error:
nvgDeleteInternal(ctx);
return 0;
}
NVGparams* nvgInternalParams(NVGcontext* ctx)
{
return &ctx->params;
}
void nvgDeleteInternal(NVGcontext* ctx)
{
int i;
if (ctx == NULL) return;
if (ctx->commands != NULL) free(ctx->commands);
if (ctx->cache != NULL) nvg__deletePathCache(ctx->cache);
if (ctx->fs)
fonsDeleteInternal(ctx->fs);
for (i = 0; i < NVG_MAX_FONTIMAGES; i++) {
if (ctx->fontImages[i] != 0) {
nvgDeleteImage(ctx, ctx->fontImages[i]);
ctx->fontImages[i] = 0;
}
}
if (ctx->params.renderDelete != NULL)
ctx->params.renderDelete(ctx->params.userPtr);
free(ctx);
}
void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio)
{
/* printf("Tris: draws:%d fill:%d stroke:%d text:%d TOT:%d\n",
ctx->drawCallCount, ctx->fillTriCount, ctx->strokeTriCount, ctx->textTriCount,
ctx->fillTriCount+ctx->strokeTriCount+ctx->textTriCount);*/
ctx->nstates = 0;
nvgSave(ctx);
nvgReset(ctx);
nvg__setDevicePixelRatio(ctx, devicePixelRatio);
ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight, devicePixelRatio);
ctx->drawCallCount = 0;
ctx->fillTriCount = 0;
ctx->strokeTriCount = 0;
ctx->textTriCount = 0;
}
void nvgCancelFrame(NVGcontext* ctx)
{
ctx->params.renderCancel(ctx->params.userPtr);
}
void nvgEndFrame(NVGcontext* ctx)
{
ctx->params.renderFlush(ctx->params.userPtr);
if (ctx->fontImageIdx != 0) {
int fontImage = ctx->fontImages[ctx->fontImageIdx];
ctx->fontImages[ctx->fontImageIdx] = 0;
int i, j, iw, ih;
// delete images that smaller than current one
if (fontImage == 0)
return;
nvgImageSize(ctx, fontImage, &iw, &ih);
for (i = j = 0; i < ctx->fontImageIdx; i++) {
if (ctx->fontImages[i] != 0) {
int nw, nh;
int image = ctx->fontImages[i];
ctx->fontImages[i] = 0;
nvgImageSize(ctx, image, &nw, &nh);
if (nw < iw || nh < ih)
nvgDeleteImage(ctx, image);
else
ctx->fontImages[j++] = image;
}
}
// make current font image to first
ctx->fontImages[j] = ctx->fontImages[0];
ctx->fontImages[0] = fontImage;
ctx->fontImageIdx = 0;
}
}
NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b)
{
return nvgRGBA(r,g,b,255);
}
NVGcolor nvgRGBf(float r, float g, float b)
{
return nvgRGBAf(r,g,b,1.0f);
}
NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
NVGcolor color;
// Use longer initialization to suppress warning.
color.r = r / 255.0f;
color.g = g / 255.0f;
color.b = b / 255.0f;
color.a = a / 255.0f;
return color;
}
NVGcolor nvgRGBAf(float r, float g, float b, float a)
{
NVGcolor color;
// Use longer initialization to suppress warning.
color.r = r;
color.g = g;
color.b = b;
color.a = a;
return color;
}
NVGcolor nvgTransRGBA(NVGcolor c, unsigned char a)
{
c.a = a / 255.0f;
return c;
}
NVGcolor nvgTransRGBAf(NVGcolor c, float a)
{
c.a = a;
return c;
}
NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u)
{
int i;
float oneminu;
NVGcolor cint = {{{0}}};
u = nvg__clampf(u, 0.0f, 1.0f);
oneminu = 1.0f - u;
for( i = 0; i <4; i++ )
{
cint.rgba[i] = c0.rgba[i] * oneminu + c1.rgba[i] * u;
}
return cint;
}
NVGcolor nvgHSL(float h, float s, float l)
{
return nvgHSLA(h,s,l,255);
}
static float nvg__hue(float h, float m1, float m2)
{
if (h < 0) h += 1;
if (h > 1) h -= 1;
if (h < 1.0f/6.0f)
return m1 + (m2 - m1) * h * 6.0f;
else if (h < 3.0f/6.0f)
return m2;
else if (h < 4.0f/6.0f)
return m1 + (m2 - m1) * (2.0f/3.0f - h) * 6.0f;
return m1;
}
NVGcolor nvgHSLA(float h, float s, float l, unsigned char a)
{
float m1, m2;
NVGcolor col;
h = nvg__modf(h, 1.0f);
if (h < 0.0f) h += 1.0f;
s = nvg__clampf(s, 0.0f, 1.0f);
l = nvg__clampf(l, 0.0f, 1.0f);
m2 = l <= 0.5f ? (l * (1 + s)) : (l + s - l * s);
m1 = 2 * l - m2;
col.r = nvg__clampf(nvg__hue(h + 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
col.g = nvg__clampf(nvg__hue(h, m1, m2), 0.0f, 1.0f);
col.b = nvg__clampf(nvg__hue(h - 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
col.a = a/255.0f;
return col;
}
void nvgTransformIdentity(float* t)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = 0.0f; t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformTranslate(float* t, float tx, float ty)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = 0.0f; t[3] = 1.0f;
t[4] = tx; t[5] = ty;
}
void nvgTransformScale(float* t, float sx, float sy)
{
t[0] = sx; t[1] = 0.0f;
t[2] = 0.0f; t[3] = sy;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformRotate(float* t, float a)
{
float cs = nvg__cosf(a), sn = nvg__sinf(a);
t[0] = cs; t[1] = sn;
t[2] = -sn; t[3] = cs;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformSkewX(float* t, float a)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = nvg__tanf(a); t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformSkewY(float* t, float a)
{
t[0] = 1.0f; t[1] = nvg__tanf(a);
t[2] = 0.0f; t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformMultiply(float* t, const float* s)
{
float t0 = t[0] * s[0] + t[1] * s[2];
float t2 = t[2] * s[0] + t[3] * s[2];
float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
t[1] = t[0] * s[1] + t[1] * s[3];
t[3] = t[2] * s[1] + t[3] * s[3];
t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
t[0] = t0;
t[2] = t2;
t[4] = t4;
}
void nvgTransformPremultiply(float* t, const float* s)
{
float s2[6];
memcpy(s2, s, sizeof(float)*6);
nvgTransformMultiply(s2, t);
memcpy(t, s2, sizeof(float)*6);
}
int nvgTransformInverse(float* inv, const float* t)
{
double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
if (det > -1e-6 && det < 1e-6) {
nvgTransformIdentity(inv);
return 0;
}
invdet = 1.0 / det;
inv[0] = (float)(t[3] * invdet);
inv[2] = (float)(-t[2] * invdet);
inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
inv[1] = (float)(-t[1] * invdet);
inv[3] = (float)(t[0] * invdet);
inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
return 1;
}
void nvgTransformPoint(float* dx, float* dy, const float* t, float sx, float sy)
{
*dx = sx*t[0] + sy*t[2] + t[4];
*dy = sx*t[1] + sy*t[3] + t[5];
}
float nvgDegToRad(float deg)
{
return deg / 180.0f * NVG_PI;
}
float nvgRadToDeg(float rad)
{
return rad / NVG_PI * 180.0f;
}
static void nvg__setPaintColor(NVGpaint* p, NVGcolor color)
{
memset(p, 0, sizeof(*p));
nvgTransformIdentity(p->xform);
p->radius = 0.0f;
p->feather = 1.0f;
p->innerColor = color;
p->outerColor = color;
}
// State handling
void nvgSave(NVGcontext* ctx)
{
if (ctx->nstates >= NVG_MAX_STATES)
return;
if (ctx->nstates > 0)
memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(NVGstate));
ctx->nstates++;
}
void nvgRestore(NVGcontext* ctx)
{
if (ctx->nstates <= 1)
return;
ctx->nstates--;
}
void nvgReset(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
memset(state, 0, sizeof(*state));
nvg__setPaintColor(&state->fill, nvgRGBA(255,255,255,255));
nvg__setPaintColor(&state->stroke, nvgRGBA(0,0,0,255));
state->compositeOperation = nvg__compositeOperationState(NVG_SOURCE_OVER);
state->shapeAntiAlias = 1;
state->strokeWidth = 1.0f;
state->miterLimit = 10.0f;
state->lineCap = NVG_BUTT;
state->lineJoin = NVG_MITER;
state->alpha = 1.0f;
nvgTransformIdentity(state->xform);
state->scissor.extent[0] = -1.0f;
state->scissor.extent[1] = -1.0f;
state->fontSize = 16.0f;
state->letterSpacing = 0.0f;
state->lineHeight = 1.0f;
state->fontBlur = 0.0f;
state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE;
state->fontId = 0;
}
// State setting
void nvgShapeAntiAlias(NVGcontext* ctx, int enabled)
{
NVGstate* state = nvg__getState(ctx);
state->shapeAntiAlias = enabled;
}
void nvgStrokeWidth(NVGcontext* ctx, float width)
{
NVGstate* state = nvg__getState(ctx);
state->strokeWidth = width;
}
void nvgMiterLimit(NVGcontext* ctx, float limit)
{
NVGstate* state = nvg__getState(ctx);
state->miterLimit = limit;
}
void nvgLineCap(NVGcontext* ctx, int cap)
{
NVGstate* state = nvg__getState(ctx);
state->lineCap = cap;
}
void nvgLineJoin(NVGcontext* ctx, int join)
{
NVGstate* state = nvg__getState(ctx);
state->lineJoin = join;
}
void nvgGlobalAlpha(NVGcontext* ctx, float alpha)
{
NVGstate* state = nvg__getState(ctx);
state->alpha = alpha;
}
void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f)
{
NVGstate* state = nvg__getState(ctx);
float t[6] = { a, b, c, d, e, f };
nvgTransformPremultiply(state->xform, t);
}
void nvgResetTransform(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
nvgTransformIdentity(state->xform);
}
void nvgTranslate(NVGcontext* ctx, float x, float y)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformTranslate(t, x,y);
nvgTransformPremultiply(state->xform, t);
}
void nvgRotate(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformRotate(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgSkewX(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformSkewX(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgSkewY(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformSkewY(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgScale(NVGcontext* ctx, float x, float y)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformScale(t, x,y);
nvgTransformPremultiply(state->xform, t);
}
void nvgCurrentTransform(NVGcontext* ctx, float* xform)
{
NVGstate* state = nvg__getState(ctx);
if (xform == NULL) return;
memcpy(xform, state->xform, sizeof(float)*6);
}
void nvgStrokeColor(NVGcontext* ctx, NVGcolor color)
{
NVGstate* state = nvg__getState(ctx);
nvg__setPaintColor(&state->stroke, color);
}
void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint)
{
NVGstate* state = nvg__getState(ctx);
state->stroke = paint;
nvgTransformMultiply(state->stroke.xform, state->xform);
}
void nvgFillColor(NVGcontext* ctx, NVGcolor color)
{
NVGstate* state = nvg__getState(ctx);
nvg__setPaintColor(&state->fill, color);
}
void nvgFillPaint(NVGcontext* ctx, NVGpaint paint)
{
NVGstate* state = nvg__getState(ctx);
state->fill = paint;
nvgTransformMultiply(state->fill.xform, state->xform);
}
#ifndef NVG_NO_STB
int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags)
{
int w, h, n, image;
unsigned char* img;
stbi_set_unpremultiply_on_load(1);
stbi_convert_iphone_png_to_rgb(1);
img = stbi_load(filename, &w, &h, &n, 4);
if (img == NULL) {
// printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
return 0;
}
image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
stbi_image_free(img);
return image;
}
int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, unsigned char* data, int ndata)
{
int w, h, n, image;
unsigned char* img = stbi_load_from_memory(data, ndata, &w, &h, &n, 4);
if (img == NULL) {
// printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
return 0;
}
image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
stbi_image_free(img);
return image;
}
#endif
int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data)
{
return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, imageFlags, data);
}
void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data)
{
int w, h;
ctx->params.renderGetTextureSize(ctx->params.userPtr, image, &w, &h);
ctx->params.renderUpdateTexture(ctx->params.userPtr, image, 0,0, w,h, data);
}
void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h)
{
ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h);
}
void nvgDeleteImage(NVGcontext* ctx, int image)
{
ctx->params.renderDeleteTexture(ctx->params.userPtr, image);
}
NVGpaint nvgLinearGradient(NVGcontext* ctx,
float sx, float sy, float ex, float ey,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
float dx, dy, d;
const float large = 1e5;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
// Calculate transform aligned to the line
dx = ex - sx;
dy = ey - sy;
d = sqrtf(dx*dx + dy*dy);
if (d > 0.0001f) {
dx /= d;
dy /= d;
} else {
dx = 0;
dy = 1;
}
p.xform[0] = dy; p.xform[1] = -dx;
p.xform[2] = dx; p.xform[3] = dy;
p.xform[4] = sx - dx*large; p.xform[5] = sy - dy*large;
p.extent[0] = large;
p.extent[1] = large + d*0.5f;
p.radius = 0.0f;
p.feather = nvg__maxf(1.0f, d);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgRadialGradient(NVGcontext* ctx,
float cx, float cy, float inr, float outr,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
float r = (inr+outr)*0.5f;
float f = (outr-inr);
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformIdentity(p.xform);
p.xform[4] = cx;
p.xform[5] = cy;
p.extent[0] = r;
p.extent[1] = r;
p.radius = r;
p.feather = nvg__maxf(1.0f, f);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgBoxGradient(NVGcontext* ctx,
float x, float y, float w, float h, float r, float f,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformIdentity(p.xform);
p.xform[4] = x+w*0.5f;
p.xform[5] = y+h*0.5f;
p.extent[0] = w*0.5f;
p.extent[1] = h*0.5f;
p.radius = r;
p.feather = nvg__maxf(1.0f, f);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgImagePattern(NVGcontext* ctx,
float cx, float cy, float w, float h, float angle,
int image, float alpha)
{
NVGpaint p;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformRotate(p.xform, angle);
p.xform[4] = cx;
p.xform[5] = cy;
p.extent[0] = w;
p.extent[1] = h;
p.image = image;
p.innerColor = p.outerColor = nvgRGBAf(1,1,1,alpha);
return p;
}
// Scissoring
void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h)
{
NVGstate* state = nvg__getState(ctx);
w = nvg__maxf(0.0f, w);
h = nvg__maxf(0.0f, h);
nvgTransformIdentity(state->scissor.xform);
state->scissor.xform[4] = x+w*0.5f;
state->scissor.xform[5] = y+h*0.5f;
nvgTransformMultiply(state->scissor.xform, state->xform);
state->scissor.extent[0] = w*0.5f;
state->scissor.extent[1] = h*0.5f;
}
static void nvg__isectRects(float* dst,
float ax, float ay, float aw, float ah,
float bx, float by, float bw, float bh)
{
float minx = nvg__maxf(ax, bx);
float miny = nvg__maxf(ay, by);
float maxx = nvg__minf(ax+aw, bx+bw);
float maxy = nvg__minf(ay+ah, by+bh);
dst[0] = minx;
dst[1] = miny;
dst[2] = nvg__maxf(0.0f, maxx - minx);
dst[3] = nvg__maxf(0.0f, maxy - miny);
}
void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h)
{
NVGstate* state = nvg__getState(ctx);
float pxform[6], invxorm[6];
float rect[4];
float ex, ey, tex, tey;
// If no previous scissor has been set, set the scissor as current scissor.
if (state->scissor.extent[0] < 0) {
nvgScissor(ctx, x, y, w, h);
return;
}
// Transform the current scissor rect into current transform space.
// If there is difference in rotation, this will be approximation.
memcpy(pxform, state->scissor.xform, sizeof(float)*6);
ex = state->scissor.extent[0];
ey = state->scissor.extent[1];
nvgTransformInverse(invxorm, state->xform);
nvgTransformMultiply(pxform, invxorm);
tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]);
tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]);
// Intersect rects.
nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, x,y,w,h);
nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]);
}
void nvgResetScissor(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
memset(state->scissor.xform, 0, sizeof(state->scissor.xform));
state->scissor.extent[0] = -1.0f;
state->scissor.extent[1] = -1.0f;
}
// Global composite operation.
void nvgGlobalCompositeOperation(NVGcontext* ctx, int op)
{
NVGstate* state = nvg__getState(ctx);
state->compositeOperation = nvg__compositeOperationState(op);
}
void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor)
{
nvgGlobalCompositeBlendFuncSeparate(ctx, sfactor, dfactor, sfactor, dfactor);
}
void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha)
{
NVGcompositeOperationState op;
op.srcRGB = srcRGB;
op.dstRGB = dstRGB;
op.srcAlpha = srcAlpha;
op.dstAlpha = dstAlpha;
NVGstate* state = nvg__getState(ctx);
state->compositeOperation = op;
}
static int nvg__ptEquals(float x1, float y1, float x2, float y2, float tol)
{
float dx = x2 - x1;
float dy = y2 - y1;
return dx*dx + dy*dy < tol*tol;
}
static float nvg__distPtSeg(float x, float y, float px, float py, float qx, float qy)
{
float pqx, pqy, dx, dy, d, t;
pqx = qx-px;
pqy = qy-py;
dx = x-px;
dy = y-py;
d = pqx*pqx + pqy*pqy;
t = pqx*dx + pqy*dy;
if (d > 0) t /= d;
if (t < 0) t = 0;
else if (t > 1) t = 1;
dx = px + t*pqx - x;
dy = py + t*pqy - y;
return dx*dx + dy*dy;
}
static void nvg__appendCommands(NVGcontext* ctx, float* vals, int nvals)
{
NVGstate* state = nvg__getState(ctx);
int i;
if (ctx->ncommands+nvals > ctx->ccommands) {
float* commands;
int ccommands = ctx->ncommands+nvals + ctx->ccommands/2;
commands = (float*)realloc(ctx->commands, sizeof(float)*ccommands);
if (commands == NULL) return;
ctx->commands = commands;
ctx->ccommands = ccommands;
}
if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) {
ctx->commandx = vals[nvals-2];
ctx->commandy = vals[nvals-1];
}
// transform commands
i = 0;
while (i < nvals) {
int cmd = (int)vals[i];
switch (cmd) {
case NVG_MOVETO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
i += 3;
break;
case NVG_LINETO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
i += 3;
break;
case NVG_BEZIERTO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
nvgTransformPoint(&vals[i+3],&vals[i+4], state->xform, vals[i+3],vals[i+4]);
nvgTransformPoint(&vals[i+5],&vals[i+6], state->xform, vals[i+5],vals[i+6]);
i += 7;
break;
case NVG_CLOSE:
i++;
break;
case NVG_WINDING:
i += 2;
break;
default:
i++;
}
}
memcpy(&ctx->commands[ctx->ncommands], vals, nvals*sizeof(float));
ctx->ncommands += nvals;
}
static void nvg__clearPathCache(NVGcontext* ctx)
{
ctx->cache->npoints = 0;
ctx->cache->npaths = 0;
}
static NVGpath* nvg__lastPath(NVGcontext* ctx)
{
if (ctx->cache->npaths > 0)
return &ctx->cache->paths[ctx->cache->npaths-1];
return NULL;
}
static void nvg__addPath(NVGcontext* ctx)
{
NVGpath* path;
if (ctx->cache->npaths+1 > ctx->cache->cpaths) {
NVGpath* paths;
int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2;
paths = (NVGpath*)realloc(ctx->cache->paths, sizeof(NVGpath)*cpaths);
if (paths == NULL) return;
ctx->cache->paths = paths;
ctx->cache->cpaths = cpaths;
}
path = &ctx->cache->paths[ctx->cache->npaths];
memset(path, 0, sizeof(*path));
path->first = ctx->cache->npoints;
path->winding = NVG_CCW;
ctx->cache->npaths++;
}
static NVGpoint* nvg__lastPoint(NVGcontext* ctx)
{
if (ctx->cache->npoints > 0)
return &ctx->cache->points[ctx->cache->npoints-1];
return NULL;
}
static void nvg__addPoint(NVGcontext* ctx, float x, float y, int flags)
{
NVGpath* path = nvg__lastPath(ctx);
NVGpoint* pt;
if (path == NULL) return;
if (path->count > 0 && ctx->cache->npoints > 0) {
pt = nvg__lastPoint(ctx);
if (nvg__ptEquals(pt->x,pt->y, x,y, ctx->distTol)) {
pt->flags |= flags;
return;
}
}
if (ctx->cache->npoints+1 > ctx->cache->cpoints) {
NVGpoint* points;
int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2;
points = (NVGpoint*)realloc(ctx->cache->points, sizeof(NVGpoint)*cpoints);
if (points == NULL) return;
ctx->cache->points = points;
ctx->cache->cpoints = cpoints;
}
pt = &ctx->cache->points[ctx->cache->npoints];
memset(pt, 0, sizeof(*pt));
pt->x = x;
pt->y = y;
pt->flags = (unsigned char)flags;
ctx->cache->npoints++;
path->count++;
}
static void nvg__closePath(NVGcontext* ctx)
{
NVGpath* path = nvg__lastPath(ctx);
if (path == NULL) return;
path->closed = 1;
}
static void nvg__pathWinding(NVGcontext* ctx, int winding)
{
NVGpath* path = nvg__lastPath(ctx);
if (path == NULL) return;
path->winding = winding;
}
static float nvg__getAverageScale(float *t)
{
float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
return (sx + sy) * 0.5f;
}
static NVGvertex* nvg__allocTempVerts(NVGcontext* ctx, int nverts)
{
if (nverts > ctx->cache->cverts) {
NVGvertex* verts;
int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly.
verts = (NVGvertex*)realloc(ctx->cache->verts, sizeof(NVGvertex)*cverts);
if (verts == NULL) return NULL;
ctx->cache->verts = verts;
ctx->cache->cverts = cverts;
}
return ctx->cache->verts;
}
static float nvg__triarea2(float ax, float ay, float bx, float by, float cx, float cy)
{
float abx = bx - ax;
float aby = by - ay;
float acx = cx - ax;
float acy = cy - ay;
return acx*aby - abx*acy;
}
static float nvg__polyArea(NVGpoint* pts, int npts)
{
int i;
float area = 0;
for (i = 2; i < npts; i++) {
NVGpoint* a = &pts[0];
NVGpoint* b = &pts[i-1];
NVGpoint* c = &pts[i];
area += nvg__triarea2(a->x,a->y, b->x,b->y, c->x,c->y);
}
return area * 0.5f;
}
static void nvg__polyReverse(NVGpoint* pts, int npts)
{
NVGpoint tmp;
int i = 0, j = npts-1;
while (i < j) {
tmp = pts[i];
pts[i] = pts[j];
pts[j] = tmp;
i++;
j--;
}
}
static void nvg__vset(NVGvertex* vtx, float x, float y, float u, float v)
{
vtx->x = x;
vtx->y = y;
vtx->u = u;
vtx->v = v;
}
static void nvg__tesselateBezier(NVGcontext* ctx,
float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4,
int level, int type)
{
float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234;
float dx,dy,d2,d3;
if (level > 10) return;
x12 = (x1+x2)*0.5f;
y12 = (y1+y2)*0.5f;
x23 = (x2+x3)*0.5f;
y23 = (y2+y3)*0.5f;
x34 = (x3+x4)*0.5f;
y34 = (y3+y4)*0.5f;
x123 = (x12+x23)*0.5f;
y123 = (y12+y23)*0.5f;
dx = x4 - x1;
dy = y4 - y1;
d2 = nvg__absf(((x2 - x4) * dy - (y2 - y4) * dx));
d3 = nvg__absf(((x3 - x4) * dy - (y3 - y4) * dx));
if ((d2 + d3)*(d2 + d3) < ctx->tessTol * (dx*dx + dy*dy)) {
nvg__addPoint(ctx, x4, y4, type);
return;
}
/* if (nvg__absf(x1+x3-x2-x2) + nvg__absf(y1+y3-y2-y2) + nvg__absf(x2+x4-x3-x3) + nvg__absf(y2+y4-y3-y3) < ctx->tessTol) {
nvg__addPoint(ctx, x4, y4, type);
return;
}*/
x234 = (x23+x34)*0.5f;
y234 = (y23+y34)*0.5f;
x1234 = (x123+x234)*0.5f;
y1234 = (y123+y234)*0.5f;
nvg__tesselateBezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0);
nvg__tesselateBezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type);
}
static void nvg__flattenPaths(NVGcontext* ctx)
{
NVGpathCache* cache = ctx->cache;
// NVGstate* state = nvg__getState(ctx);
NVGpoint* last;
NVGpoint* p0;
NVGpoint* p1;
NVGpoint* pts;
NVGpath* path;
int i, j;
float* cp1;
float* cp2;
float* p;
float area;
if (cache->npaths > 0)
return;
// Flatten
i = 0;
while (i < ctx->ncommands) {
int cmd = (int)ctx->commands[i];
switch (cmd) {
case NVG_MOVETO:
nvg__addPath(ctx);
p = &ctx->commands[i+1];
nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
i += 3;
break;
case NVG_LINETO:
p = &ctx->commands[i+1];
nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
i += 3;
break;
case NVG_BEZIERTO:
last = nvg__lastPoint(ctx);
if (last != NULL) {
cp1 = &ctx->commands[i+1];
cp2 = &ctx->commands[i+3];
p = &ctx->commands[i+5];
nvg__tesselateBezier(ctx, last->x,last->y, cp1[0],cp1[1], cp2[0],cp2[1], p[0],p[1], 0, NVG_PT_CORNER);
}
i += 7;
break;
case NVG_CLOSE:
nvg__closePath(ctx);
i++;
break;
case NVG_WINDING:
nvg__pathWinding(ctx, (int)ctx->commands[i+1]);
i += 2;
break;
default:
i++;
}
}
cache->bounds[0] = cache->bounds[1] = 1e6f;
cache->bounds[2] = cache->bounds[3] = -1e6f;
// Calculate the direction and length of line segments.
for (j = 0; j < cache->npaths; j++) {
path = &cache->paths[j];
pts = &cache->points[path->first];
// If the first and last points are the same, remove the last, mark as closed path.
p0 = &pts[path->count-1];
p1 = &pts[0];
if (nvg__ptEquals(p0->x,p0->y, p1->x,p1->y, ctx->distTol)) {
path->count--;
p0 = &pts[path->count-1];
path->closed = 1;
}
// Enforce winding.
if (path->count > 2) {
area = nvg__polyArea(pts, path->count);
if (path->winding == NVG_CCW && area < 0.0f)
nvg__polyReverse(pts, path->count);
if (path->winding == NVG_CW && area > 0.0f)
nvg__polyReverse(pts, path->count);
}
for(i = 0; i < path->count; i++) {
// Calculate segment direction and length
p0->dx = p1->x - p0->x;
p0->dy = p1->y - p0->y;
p0->len = nvg__normalize(&p0->dx, &p0->dy);
// Update bounds
cache->bounds[0] = nvg__minf(cache->bounds[0], p0->x);
cache->bounds[1] = nvg__minf(cache->bounds[1], p0->y);
cache->bounds[2] = nvg__maxf(cache->bounds[2], p0->x);
cache->bounds[3] = nvg__maxf(cache->bounds[3], p0->y);
// Advance
p0 = p1++;
}
}
}
static int nvg__curveDivs(float r, float arc, float tol)
{
float da = acosf(r / (r + tol)) * 2.0f;
return nvg__maxi(2, (int)ceilf(arc / da));
}
static void nvg__chooseBevel(int bevel, NVGpoint* p0, NVGpoint* p1, float w,
float* x0, float* y0, float* x1, float* y1)
{
if (bevel) {
*x0 = p1->x + p0->dy * w;
*y0 = p1->y - p0->dx * w;
*x1 = p1->x + p1->dy * w;
*y1 = p1->y - p1->dx * w;
} else {
*x0 = p1->x + p1->dmx * w;
*y0 = p1->y + p1->dmy * w;
*x1 = p1->x + p1->dmx * w;
*y1 = p1->y + p1->dmy * w;
}
}
static NVGvertex* nvg__roundJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
float lw, float rw, float lu, float ru, int ncap,
float fringe)
{
int i, n;
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
NVG_NOTUSED(fringe);
if (p1->flags & NVG_PT_LEFT) {
float lx0,ly0,lx1,ly1,a0,a1;
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
a0 = atan2f(-dly0, -dlx0);
a1 = atan2f(-dly1, -dlx1);
if (a1 > a0) a1 -= NVG_PI*2;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
n = nvg__clampi((int)ceilf(((a0 - a1) / NVG_PI) * ncap), 2, ncap);
for (i = 0; i < n; i++) {
float u = i/(float)(n-1);
float a = a0 + u*(a1-a0);
float rx = p1->x + cosf(a) * rw;
float ry = p1->y + sinf(a) * rw;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, rx, ry, ru,1); dst++;
}
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
float rx0,ry0,rx1,ry1,a0,a1;
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
a0 = atan2f(dly0, dlx0);
a1 = atan2f(dly1, dlx1);
if (a1 < a0) a1 += NVG_PI*2;
nvg__vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
n = nvg__clampi((int)ceilf(((a1 - a0) / NVG_PI) * ncap), 2, ncap);
for (i = 0; i < n; i++) {
float u = i/(float)(n-1);
float a = a0 + u*(a1-a0);
float lx = p1->x + cosf(a) * lw;
float ly = p1->y + sinf(a) * lw;
nvg__vset(dst, lx, ly, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
}
nvg__vset(dst, p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
}
return dst;
}
static NVGvertex* nvg__bevelJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
float lw, float rw, float lu, float ru, float fringe)
{
float rx0,ry0,rx1,ry1;
float lx0,ly0,lx1,ly1;
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
NVG_NOTUSED(fringe);
if (p1->flags & NVG_PT_LEFT) {
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
if (p1->flags & NVG_PT_BEVEL) {
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
rx0 = p1->x - p1->dmx * rw;
ry0 = p1->y - p1->dmy * rw;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
}
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
if (p1->flags & NVG_PT_BEVEL) {
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
} else {
lx0 = p1->x + p1->dmx * lw;
ly0 = p1->y + p1->dmy * lw;
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
}
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
}
return dst;
}
static NVGvertex* nvg__buttCapStart(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, float d,
float aa, float u0, float u1)
{
float px = p->x - dx*d;
float py = p->y - dy*d;
float dlx = dy;
float dly = -dx;
nvg__vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, u0,0); dst++;
nvg__vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, u1,0); dst++;
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
return dst;
}
static NVGvertex* nvg__buttCapEnd(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, float d,
float aa, float u0, float u1)
{
float px = p->x + dx*d;
float py = p->y + dy*d;
float dlx = dy;
float dly = -dx;
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
nvg__vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, u0,0); dst++;
nvg__vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, u1,0); dst++;
return dst;
}
static NVGvertex* nvg__roundCapStart(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, int ncap,
float aa, float u0, float u1)
{
int i;
float px = p->x;
float py = p->y;
float dlx = dy;
float dly = -dx;
NVG_NOTUSED(aa);
for (i = 0; i < ncap; i++) {
float a = i/(float)(ncap-1)*NVG_PI;
float ax = cosf(a) * w, ay = sinf(a) * w;
nvg__vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, u0,1); dst++;
nvg__vset(dst, px, py, 0.5f,1); dst++;
}
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
return dst;
}
static NVGvertex* nvg__roundCapEnd(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, int ncap,
float aa, float u0, float u1)
{
int i;
float px = p->x;
float py = p->y;
float dlx = dy;
float dly = -dx;
NVG_NOTUSED(aa);
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
for (i = 0; i < ncap; i++) {
float a = i/(float)(ncap-1)*NVG_PI;
float ax = cosf(a) * w, ay = sinf(a) * w;
nvg__vset(dst, px, py, 0.5f,1); dst++;
nvg__vset(dst, px - dlx*ax + dx*ay, py - dly*ax + dy*ay, u0,1); dst++;
}
return dst;
}
static void nvg__calculateJoins(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
int i, j;
float iw = 0.0f;
if (w > 0.0f) iw = 1.0f / w;
// Calculate which joins needs extra vertices to append, and gather vertex count.
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0 = &pts[path->count-1];
NVGpoint* p1 = &pts[0];
int nleft = 0;
path->nbevel = 0;
for (j = 0; j < path->count; j++) {
float dlx0, dly0, dlx1, dly1, dmr2, cross, limit;
dlx0 = p0->dy;
dly0 = -p0->dx;
dlx1 = p1->dy;
dly1 = -p1->dx;
// Calculate extrusions
p1->dmx = (dlx0 + dlx1) * 0.5f;
p1->dmy = (dly0 + dly1) * 0.5f;
dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy;
if (dmr2 > 0.000001f) {
float scale = 1.0f / dmr2;
if (scale > 600.0f) {
scale = 600.0f;
}
p1->dmx *= scale;
p1->dmy *= scale;
}
// Clear flags, but keep the corner.
p1->flags = (p1->flags & NVG_PT_CORNER) ? NVG_PT_CORNER : 0;
// Keep track of left turns.
cross = p1->dx * p0->dy - p0->dx * p1->dy;
if (cross > 0.0f) {
nleft++;
p1->flags |= NVG_PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = nvg__maxf(1.01f, nvg__minf(p0->len, p1->len) * iw);
if ((dmr2 * limit*limit) < 1.0f)
p1->flags |= NVG_PR_INNERBEVEL;
// Check to see if the corner needs to be beveled.
if (p1->flags & NVG_PT_CORNER) {
if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVG_BEVEL || lineJoin == NVG_ROUND) {
p1->flags |= NVG_PT_BEVEL;
}
}
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0)
path->nbevel++;
p0 = p1++;
}
path->convex = (nleft == path->count) ? 1 : 0;
}
}
static int nvg__expandStroke(NVGcontext* ctx, float w, float fringe, int lineCap, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
NVGvertex* verts;
NVGvertex* dst;
int cverts, i, j;
float aa = fringe;//ctx->fringeWidth;
float u0 = 0.0f, u1 = 1.0f;
int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol); // Calculate divisions per half circle.
w += aa * 0.5f;
// Disable the gradient used for antialiasing when antialiasing is not used.
if (aa == 0.0f) {
u0 = 0.5f;
u1 = 0.5f;
}
nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
// Calculate max vertex usage.
cverts = 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
int loop = (path->closed == 0) ? 0 : 1;
if (lineJoin == NVG_ROUND)
cverts += (path->count + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop
else
cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
if (loop == 0) {
// space for caps
if (lineCap == NVG_ROUND) {
cverts += (ncap*2 + 2)*2;
} else {
cverts += (3+3)*2;
}
}
}
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0;
NVGpoint* p1;
int s, e, loop;
float dx, dy;
path->fill = 0;
path->nfill = 0;
// Calculate fringe or stroke
loop = (path->closed == 0) ? 0 : 1;
dst = verts;
path->stroke = dst;
if (loop) {
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
s = 0;
e = path->count;
} else {
// Add cap
p0 = &pts[0];
p1 = &pts[1];
s = 1;
e = path->count-1;
}
if (loop == 0) {
// Add cap
dx = p1->x - p0->x;
dy = p1->y - p0->y;
nvg__normalize(&dx, &dy);
if (lineCap == NVG_BUTT)
dst = nvg__buttCapStart(dst, p0, dx, dy, w, -aa*0.5f, aa, u0, u1);
else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
dst = nvg__buttCapStart(dst, p0, dx, dy, w, w-aa, aa, u0, u1);
else if (lineCap == NVG_ROUND)
dst = nvg__roundCapStart(dst, p0, dx, dy, w, ncap, aa, u0, u1);
}
for (j = s; j < e; ++j) {
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
if (lineJoin == NVG_ROUND) {
dst = nvg__roundJoin(dst, p0, p1, w, w, u0, u1, ncap, aa);
} else {
dst = nvg__bevelJoin(dst, p0, p1, w, w, u0, u1, aa);
}
} else {
nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++;
nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++;
}
p0 = p1++;
}
if (loop) {
// Loop it
nvg__vset(dst, verts[0].x, verts[0].y, u0,1); dst++;
nvg__vset(dst, verts[1].x, verts[1].y, u1,1); dst++;
} else {
// Add cap
dx = p1->x - p0->x;
dy = p1->y - p0->y;
nvg__normalize(&dx, &dy);
if (lineCap == NVG_BUTT)
dst = nvg__buttCapEnd(dst, p1, dx, dy, w, -aa*0.5f, aa, u0, u1);
else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
dst = nvg__buttCapEnd(dst, p1, dx, dy, w, w-aa, aa, u0, u1);
else if (lineCap == NVG_ROUND)
dst = nvg__roundCapEnd(dst, p1, dx, dy, w, ncap, aa, u0, u1);
}
path->nstroke = (int)(dst - verts);
verts = dst;
}
return 1;
}
static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
NVGvertex* verts;
NVGvertex* dst;
int cverts, convex, i, j;
float aa = ctx->fringeWidth;
int fringe = w > 0.0f;
nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
// Calculate max vertex usage.
cverts = 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
cverts += path->count + path->nbevel + 1;
if (fringe)
cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
}
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return 0;
convex = cache->npaths == 1 && cache->paths[0].convex;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0;
NVGpoint* p1;
float rw, lw, woff;
float ru, lu;
// Calculate shape vertices.
woff = 0.5f*aa;
dst = verts;
path->fill = dst;
if (fringe) {
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
for (j = 0; j < path->count; ++j) {
if (p1->flags & NVG_PT_BEVEL) {
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
if (p1->flags & NVG_PT_LEFT) {
float lx = p1->x + p1->dmx * woff;
float ly = p1->y + p1->dmy * woff;
nvg__vset(dst, lx, ly, 0.5f,1); dst++;
} else {
float lx0 = p1->x + dlx0 * woff;
float ly0 = p1->y + dly0 * woff;
float lx1 = p1->x + dlx1 * woff;
float ly1 = p1->y + dly1 * woff;
nvg__vset(dst, lx0, ly0, 0.5f,1); dst++;
nvg__vset(dst, lx1, ly1, 0.5f,1); dst++;
}
} else {
nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++;
}
p0 = p1++;
}
} else {
for (j = 0; j < path->count; ++j) {
nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1);
dst++;
}
}
path->nfill = (int)(dst - verts);
verts = dst;
// Calculate fringe
if (fringe) {
lw = w + woff;
rw = w - woff;
lu = 0;
ru = 1;
dst = verts;
path->stroke = dst;
// Create only half a fringe for convex shapes so that
// the shape can be rendered without stenciling.
if (convex) {
lw = woff; // This should generate the same vertex as fill inset above.
lu = 0.5f; // Set outline fade at middle.
}
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
for (j = 0; j < path->count; ++j) {
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
dst = nvg__bevelJoin(dst, p0, p1, lw, rw, lu, ru, ctx->fringeWidth);
} else {
nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++;
nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++;
}
p0 = p1++;
}
// Loop it
nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++;
nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++;
path->nstroke = (int)(dst - verts);
verts = dst;
} else {
path->stroke = NULL;
path->nstroke = 0;
}
}
return 1;
}
// Draw
void nvgBeginPath(NVGcontext* ctx)
{
ctx->ncommands = 0;
nvg__clearPathCache(ctx);
}
void nvgMoveTo(NVGcontext* ctx, float x, float y)
{
float vals[] = { NVG_MOVETO, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgLineTo(NVGcontext* ctx, float x, float y)
{
float vals[] = { NVG_LINETO, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y)
{
float vals[] = { NVG_BEZIERTO, c1x, c1y, c2x, c2y, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y)
{
float x0 = ctx->commandx;
float y0 = ctx->commandy;
float vals[] = { NVG_BEZIERTO,
x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0),
x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y),
x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius)
{
float x0 = ctx->commandx;
float y0 = ctx->commandy;
float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1;
int dir;
if (ctx->ncommands == 0) {
return;
}
// Handle degenerate cases.
if (nvg__ptEquals(x0,y0, x1,y1, ctx->distTol) ||
nvg__ptEquals(x1,y1, x2,y2, ctx->distTol) ||
nvg__distPtSeg(x1,y1, x0,y0, x2,y2) < ctx->distTol*ctx->distTol ||
radius < ctx->distTol) {
nvgLineTo(ctx, x1,y1);
return;
}
// Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2).
dx0 = x0-x1;
dy0 = y0-y1;
dx1 = x2-x1;
dy1 = y2-y1;
nvg__normalize(&dx0,&dy0);
nvg__normalize(&dx1,&dy1);
a = nvg__acosf(dx0*dx1 + dy0*dy1);
d = radius / nvg__tanf(a/2.0f);
// printf("a=%f d=%f\n", a/NVG_PI*180.0f, d);
if (d > 10000.0f) {
nvgLineTo(ctx, x1,y1);
return;
}
if (nvg__cross(dx0,dy0, dx1,dy1) > 0.0f) {
cx = x1 + dx0*d + dy0*radius;
cy = y1 + dy0*d + -dx0*radius;
a0 = nvg__atan2f(dx0, -dy0);
a1 = nvg__atan2f(-dx1, dy1);
dir = NVG_CW;
// printf("CW c=(%f, %f) a0=%f a1=%f\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
} else {
cx = x1 + dx0*d + -dy0*radius;
cy = y1 + dy0*d + dx0*radius;
a0 = nvg__atan2f(-dx0, dy0);
a1 = nvg__atan2f(dx1, -dy1);
dir = NVG_CCW;
// printf("CCW c=(%f, %f) a0=%f a1=%f\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
}
nvgArc(ctx, cx, cy, radius, a0, a1, dir);
}
void nvgClosePath(NVGcontext* ctx)
{
float vals[] = { NVG_CLOSE };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgPathWinding(NVGcontext* ctx, int dir)
{
float vals[] = { NVG_WINDING, (float)dir };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir)
{
float a = 0, da = 0, hda = 0, kappa = 0;
float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
float px = 0, py = 0, ptanx = 0, ptany = 0;
float vals[3 + 5*7 + 100];
int i, ndivs, nvals;
int move = ctx->ncommands > 0 ? NVG_LINETO : NVG_MOVETO;
// Clamp angles
da = a1 - a0;
if (dir == NVG_CW) {
if (nvg__absf(da) >= NVG_PI*2) {
da = NVG_PI*2;
} else {
while (da < 0.0f) da += NVG_PI*2;
}
} else {
if (nvg__absf(da) >= NVG_PI*2) {
da = -NVG_PI*2;
} else {
while (da > 0.0f) da -= NVG_PI*2;
}
}
// Split arc into max 90 degree segments.
ndivs = nvg__maxi(1, nvg__mini((int)(nvg__absf(da) / (NVG_PI*0.5f) + 0.5f), 5));
hda = (da / (float)ndivs) / 2.0f;
kappa = nvg__absf(4.0f / 3.0f * (1.0f - nvg__cosf(hda)) / nvg__sinf(hda));
if (dir == NVG_CCW)
kappa = -kappa;
nvals = 0;
for (i = 0; i <= ndivs; i++) {
a = a0 + da * (i/(float)ndivs);
dx = nvg__cosf(a);
dy = nvg__sinf(a);
x = cx + dx*r;
y = cy + dy*r;
tanx = -dy*r*kappa;
tany = dx*r*kappa;
if (i == 0) {
vals[nvals++] = (float)move;
vals[nvals++] = x;
vals[nvals++] = y;
} else {
vals[nvals++] = NVG_BEZIERTO;
vals[nvals++] = px+ptanx;
vals[nvals++] = py+ptany;
vals[nvals++] = x-tanx;
vals[nvals++] = y-tany;
vals[nvals++] = x;
vals[nvals++] = y;
}
px = x;
py = y;
ptanx = tanx;
ptany = tany;
}
nvg__appendCommands(ctx, vals, nvals);
}
void nvgRect(NVGcontext* ctx, float x, float y, float w, float h)
{
float vals[] = {
NVG_MOVETO, x,y,
NVG_LINETO, x,y+h,
NVG_LINETO, x+w,y+h,
NVG_LINETO, x+w,y,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r)
{
nvgRoundedRectVarying(ctx, x, y, w, h, r, r, r, r);
}
void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft)
{
if(radTopLeft < 0.1f && radTopRight < 0.1f && radBottomRight < 0.1f && radBottomLeft < 0.1f) {
nvgRect(ctx, x, y, w, h);
return;
} else {
float halfw = nvg__absf(w)*0.5f;
float halfh = nvg__absf(h)*0.5f;
float rxBL = nvg__minf(radBottomLeft, halfw) * nvg__signf(w), ryBL = nvg__minf(radBottomLeft, halfh) * nvg__signf(h);
float rxBR = nvg__minf(radBottomRight, halfw) * nvg__signf(w), ryBR = nvg__minf(radBottomRight, halfh) * nvg__signf(h);
float rxTR = nvg__minf(radTopRight, halfw) * nvg__signf(w), ryTR = nvg__minf(radTopRight, halfh) * nvg__signf(h);
float rxTL = nvg__minf(radTopLeft, halfw) * nvg__signf(w), ryTL = nvg__minf(radTopLeft, halfh) * nvg__signf(h);
float vals[] = {
NVG_MOVETO, x, y + ryTL,
NVG_LINETO, x, y + h - ryBL,
NVG_BEZIERTO, x, y + h - ryBL*(1 - NVG_KAPPA90), x + rxBL*(1 - NVG_KAPPA90), y + h, x + rxBL, y + h,
NVG_LINETO, x + w - rxBR, y + h,
NVG_BEZIERTO, x + w - rxBR*(1 - NVG_KAPPA90), y + h, x + w, y + h - ryBR*(1 - NVG_KAPPA90), x + w, y + h - ryBR,
NVG_LINETO, x + w, y + ryTR,
NVG_BEZIERTO, x + w, y + ryTR*(1 - NVG_KAPPA90), x + w - rxTR*(1 - NVG_KAPPA90), y, x + w - rxTR, y,
NVG_LINETO, x + rxTL, y,
NVG_BEZIERTO, x + rxTL*(1 - NVG_KAPPA90), y, x, y + ryTL*(1 - NVG_KAPPA90), x, y + ryTL,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
}
void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry)
{
float vals[] = {
NVG_MOVETO, cx-rx, cy,
NVG_BEZIERTO, cx-rx, cy+ry*NVG_KAPPA90, cx-rx*NVG_KAPPA90, cy+ry, cx, cy+ry,
NVG_BEZIERTO, cx+rx*NVG_KAPPA90, cy+ry, cx+rx, cy+ry*NVG_KAPPA90, cx+rx, cy,
NVG_BEZIERTO, cx+rx, cy-ry*NVG_KAPPA90, cx+rx*NVG_KAPPA90, cy-ry, cx, cy-ry,
NVG_BEZIERTO, cx-rx*NVG_KAPPA90, cy-ry, cx-rx, cy-ry*NVG_KAPPA90, cx-rx, cy,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgCircle(NVGcontext* ctx, float cx, float cy, float r)
{
nvgEllipse(ctx, cx,cy, r,r);
}
void nvgDebugDumpPathCache(NVGcontext* ctx)
{
const NVGpath* path;
int i, j;
printf("Dumping %d cached paths\n", ctx->cache->npaths);
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
printf(" - Path %d\n", i);
if (path->nfill) {
printf(" - fill: %d\n", path->nfill);
for (j = 0; j < path->nfill; j++)
printf("%f\t%f\n", path->fill[j].x, path->fill[j].y);
}
if (path->nstroke) {
printf(" - stroke: %d\n", path->nstroke);
for (j = 0; j < path->nstroke; j++)
printf("%f\t%f\n", path->stroke[j].x, path->stroke[j].y);
}
}
}
void nvgFill(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
const NVGpath* path;
NVGpaint fillPaint = state->fill;
int i;
nvg__flattenPaths(ctx);
if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
nvg__expandFill(ctx, ctx->fringeWidth, NVG_MITER, 2.4f);
else
nvg__expandFill(ctx, 0.0f, NVG_MITER, 2.4f);
// Apply global alpha
fillPaint.innerColor.a *= state->alpha;
fillPaint.outerColor.a *= state->alpha;
ctx->params.renderFill(ctx->params.userPtr, &fillPaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
ctx->cache->bounds, ctx->cache->paths, ctx->cache->npaths);
// Count triangles
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
ctx->fillTriCount += path->nfill-2;
ctx->fillTriCount += path->nstroke-2;
ctx->drawCallCount += 2;
}
}
void nvgStroke(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getAverageScale(state->xform);
float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 200.0f);
NVGpaint strokePaint = state->stroke;
const NVGpath* path;
int i;
if (strokeWidth < ctx->fringeWidth) {
// If the stroke width is less than pixel size, use alpha to emulate coverage.
// Since coverage is area, scale by alpha*alpha.
float alpha = nvg__clampf(strokeWidth / ctx->fringeWidth, 0.0f, 1.0f);
strokePaint.innerColor.a *= alpha*alpha;
strokePaint.outerColor.a *= alpha*alpha;
strokeWidth = ctx->fringeWidth;
}
// Apply global alpha
strokePaint.innerColor.a *= state->alpha;
strokePaint.outerColor.a *= state->alpha;
nvg__flattenPaths(ctx);
if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
nvg__expandStroke(ctx, strokeWidth*0.5f, ctx->fringeWidth, state->lineCap, state->lineJoin, state->miterLimit);
else
nvg__expandStroke(ctx, strokeWidth*0.5f, 0.0f, state->lineCap, state->lineJoin, state->miterLimit);
ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
strokeWidth, ctx->cache->paths, ctx->cache->npaths);
// Count triangles
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
ctx->strokeTriCount += path->nstroke-2;
ctx->drawCallCount++;
}
}
// Add fonts
int nvgCreateFont(NVGcontext* ctx, const char* name, const char* filename)
{
return fonsAddFont(ctx->fs, name, filename, 0);
}
int nvgCreateFontAtIndex(NVGcontext* ctx, const char* name, const char* filename, const int fontIndex)
{
return fonsAddFont(ctx->fs, name, filename, fontIndex);
}
int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData)
{
return fonsAddFontMem(ctx->fs, name, data, ndata, freeData, 0);
}
int nvgCreateFontMemAtIndex(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData, const int fontIndex)
{
return fonsAddFontMem(ctx->fs, name, data, ndata, freeData, fontIndex);
}
int nvgFindFont(NVGcontext* ctx, const char* name)
{
if (name == NULL) return -1;
return fonsGetFontByName(ctx->fs, name);
}
int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont)
{
if(baseFont == -1 || fallbackFont == -1) return 0;
return fonsAddFallbackFont(ctx->fs, baseFont, fallbackFont);
}
int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont)
{
return nvgAddFallbackFontId(ctx, nvgFindFont(ctx, baseFont), nvgFindFont(ctx, fallbackFont));
}
void nvgResetFallbackFontsId(NVGcontext* ctx, int baseFont)
{
fonsResetFallbackFont(ctx->fs, baseFont);
}
void nvgResetFallbackFonts(NVGcontext* ctx, const char* baseFont)
{
nvgResetFallbackFontsId(ctx, nvgFindFont(ctx, baseFont));
}
// State setting
void nvgFontSize(NVGcontext* ctx, float size)
{
NVGstate* state = nvg__getState(ctx);
state->fontSize = size;
}
void nvgFontBlur(NVGcontext* ctx, float blur)
{
NVGstate* state = nvg__getState(ctx);
state->fontBlur = blur;
}
void nvgTextLetterSpacing(NVGcontext* ctx, float spacing)
{
NVGstate* state = nvg__getState(ctx);
state->letterSpacing = spacing;
}
void nvgTextLineHeight(NVGcontext* ctx, float lineHeight)
{
NVGstate* state = nvg__getState(ctx);
state->lineHeight = lineHeight;
}
void nvgTextAlign(NVGcontext* ctx, int align)
{
NVGstate* state = nvg__getState(ctx);
state->textAlign = align;
}
void nvgFontFaceId(NVGcontext* ctx, int font)
{
NVGstate* state = nvg__getState(ctx);
state->fontId = font;
}
void nvgFontFace(NVGcontext* ctx, const char* font)
{
NVGstate* state = nvg__getState(ctx);
state->fontId = fonsGetFontByName(ctx->fs, font);
}
static float nvg__quantize(float a, float d)
{
return ((int)(a / d + 0.5f)) * d;
}
static float nvg__getFontScale(NVGstate* state)
{
return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f);
}
static void nvg__flushTextTexture(NVGcontext* ctx)
{
int dirty[4];
if (fonsValidateTexture(ctx->fs, dirty)) {
int fontImage = ctx->fontImages[ctx->fontImageIdx];
// Update texture
if (fontImage != 0) {
int iw, ih;
const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih);
int x = dirty[0];
int y = dirty[1];
int w = dirty[2] - dirty[0];
int h = dirty[3] - dirty[1];
ctx->params.renderUpdateTexture(ctx->params.userPtr, fontImage, x,y, w,h, data);
}
}
}
static int nvg__allocTextAtlas(NVGcontext* ctx)
{
int iw, ih;
nvg__flushTextTexture(ctx);
if (ctx->fontImageIdx >= NVG_MAX_FONTIMAGES-1)
return 0;
// if next fontImage already have a texture
if (ctx->fontImages[ctx->fontImageIdx+1] != 0)
nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx+1], &iw, &ih);
else { // calculate the new font image size and create it.
nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih);
if (iw > ih)
ih *= 2;
else
iw *= 2;
if (iw > NVG_MAX_FONTIMAGE_SIZE || ih > NVG_MAX_FONTIMAGE_SIZE)
iw = ih = NVG_MAX_FONTIMAGE_SIZE;
ctx->fontImages[ctx->fontImageIdx+1] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, iw, ih, 0, NULL);
}
++ctx->fontImageIdx;
fonsResetAtlas(ctx->fs, iw, ih);
return 1;
}
static void nvg__renderText(NVGcontext* ctx, NVGvertex* verts, int nverts)
{
NVGstate* state = nvg__getState(ctx);
NVGpaint paint = state->fill;
// Render triangles.
paint.image = ctx->fontImages[ctx->fontImageIdx];
// Apply global alpha
paint.innerColor.a *= state->alpha;
paint.outerColor.a *= state->alpha;
ctx->params.renderTriangles(ctx->params.userPtr, &paint, state->compositeOperation, &state->scissor, verts, nverts, ctx->fringeWidth);
ctx->drawCallCount++;
ctx->textTriCount += nverts/3;
}
static int nvg__isTransformFlipped(const float *xform)
{
float det = xform[0] * xform[3] - xform[2] * xform[1];
return( det < 0);
}
float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end)
{
NVGstate* state = nvg__getState(ctx);
FONStextIter iter, prevIter;
FONSquad q;
NVGvertex* verts;
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
int cverts = 0;
int nverts = 0;
int isFlipped = nvg__isTransformFlipped(state->xform);
if (end == NULL)
end = string + strlen(string);
if (state->fontId == FONS_INVALID) return x;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
cverts = nvg__maxi(2, (int)(end - string)) * 6; // conservative estimate.
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return x;
fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_REQUIRED);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
float c[4*2];
if (iter.prevGlyphIndex == -1) { // can not retrieve glyph?
if (nverts != 0) {
nvg__renderText(ctx, verts, nverts);
nverts = 0;
}
if (!nvg__allocTextAtlas(ctx))
break; // no memory :(
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
if (iter.prevGlyphIndex == -1) // still can not find glyph?
break;
}
prevIter = iter;
if(isFlipped) {
float tmp;
tmp = q.y0; q.y0 = q.y1; q.y1 = tmp;
tmp = q.t0; q.t0 = q.t1; q.t1 = tmp;
}
// Transform corners.
nvgTransformPoint(&c[0],&c[1], state->xform, q.x0*invscale, q.y0*invscale);
nvgTransformPoint(&c[2],&c[3], state->xform, q.x1*invscale, q.y0*invscale);
nvgTransformPoint(&c[4],&c[5], state->xform, q.x1*invscale, q.y1*invscale);
nvgTransformPoint(&c[6],&c[7], state->xform, q.x0*invscale, q.y1*invscale);
// Create triangles
if (nverts+6 <= cverts) {
nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
nvg__vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++;
nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
nvg__vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++;
nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
}
}
// TODO: add back-end bit to do this just once per frame.
nvg__flushTextTexture(ctx);
nvg__renderText(ctx, verts, nverts);
return iter.nextx / scale;
}
void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end)
{
NVGstate* state = nvg__getState(ctx);
NVGtextRow rows[2];
int nrows = 0, i;
int oldAlign = state->textAlign;
int halign = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
float lineh = 0;
if (state->fontId == FONS_INVALID) return;
nvgTextMetrics(ctx, NULL, NULL, &lineh);
state->textAlign = NVG_ALIGN_LEFT | valign;
while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
for (i = 0; i < nrows; i++) {
NVGtextRow* row = &rows[i];
if (halign & NVG_ALIGN_LEFT)
nvgText(ctx, x, y, row->start, row->end);
else if (halign & NVG_ALIGN_CENTER)
nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end);
else if (halign & NVG_ALIGN_RIGHT)
nvgText(ctx, x + breakRowWidth - row->width, y, row->start, row->end);
y += lineh * state->lineHeight;
}
string = rows[nrows-1].next;
}
state->textAlign = oldAlign;
}
int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
FONStextIter iter, prevIter;
FONSquad q;
int npos = 0;
if (state->fontId == FONS_INVALID) return 0;
if (end == NULL)
end = string + strlen(string);
if (string == end)
return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
}
prevIter = iter;
positions[npos].str = iter.str;
positions[npos].x = iter.x * invscale;
positions[npos].minx = nvg__minf(iter.x, q.x0) * invscale;
positions[npos].maxx = nvg__maxf(iter.nextx, q.x1) * invscale;
npos++;
if (npos >= maxPositions)
break;
}
return npos;
}
enum NVGcodepointType {
NVG_SPACE,
NVG_NEWLINE,
NVG_CHAR,
NVG_CJK_CHAR,
};
int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
FONStextIter iter, prevIter;
FONSquad q;
int nrows = 0;
float rowStartX = 0;
float rowWidth = 0;
float rowMinX = 0;
float rowMaxX = 0;
const char* rowStart = NULL;
const char* rowEnd = NULL;
const char* wordStart = NULL;
float wordStartX = 0;
float wordMinX = 0;
const char* breakEnd = NULL;
float breakWidth = 0;
float breakMaxX = 0;
int type = NVG_SPACE, ptype = NVG_SPACE;
unsigned int pcodepoint = 0;
if (maxRows == 0) return 0;
if (state->fontId == FONS_INVALID) return 0;
if (end == NULL)
end = string + strlen(string);
if (string == end) return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
breakRowWidth *= scale;
fonsTextIterInit(ctx->fs, &iter, 0, 0, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
}
prevIter = iter;
switch (iter.codepoint) {
case 9: // \t
case 11: // \v
case 12: // \f
case 32: // space
case 0x00a0: // NBSP
type = NVG_SPACE;
break;
case 10: // \n
type = pcodepoint == 13 ? NVG_SPACE : NVG_NEWLINE;
break;
case 13: // \r
type = pcodepoint == 10 ? NVG_SPACE : NVG_NEWLINE;
break;
case 0x0085: // NEL
type = NVG_NEWLINE;
break;
default:
if ((iter.codepoint >= 0x4E00 && iter.codepoint <= 0x9FFF) ||
(iter.codepoint >= 0x3000 && iter.codepoint <= 0x30FF) ||
(iter.codepoint >= 0xFF00 && iter.codepoint <= 0xFFEF) ||
(iter.codepoint >= 0x1100 && iter.codepoint <= 0x11FF) ||
(iter.codepoint >= 0x3130 && iter.codepoint <= 0x318F) ||
(iter.codepoint >= 0xAC00 && iter.codepoint <= 0xD7AF))
type = NVG_CJK_CHAR;
else
type = NVG_CHAR;
break;
}
if (type == NVG_NEWLINE) {
// Always handle new lines.
rows[nrows].start = rowStart != NULL ? rowStart : iter.str;
rows[nrows].end = rowEnd != NULL ? rowEnd : iter.str;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = iter.next;
nrows++;
if (nrows >= maxRows)
return nrows;
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
// Indicate to skip the white space at the beginning of the row.
rowStart = NULL;
rowEnd = NULL;
rowWidth = 0;
rowMinX = rowMaxX = 0;
} else {
if (rowStart == NULL) {
// Skip white space until the beginning of the line
if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
// The current char is the row so far
rowStartX = iter.x;
rowStart = iter.str;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMinX = q.x0 - rowStartX;
rowMaxX = q.x1 - rowStartX;
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0 - rowStartX;
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
}
} else {
float nextWidth = iter.nextx - rowStartX;
// track last non-white space character
if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMaxX = q.x1 - rowStartX;
}
// track last end of a word
if (((ptype == NVG_CHAR || ptype == NVG_CJK_CHAR) && type == NVG_SPACE) || type == NVG_CJK_CHAR) {
breakEnd = iter.str;
breakWidth = rowWidth;
breakMaxX = rowMaxX;
}
// track last beginning of a word
if ((ptype == NVG_SPACE && (type == NVG_CHAR || type == NVG_CJK_CHAR)) || type == NVG_CJK_CHAR) {
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0;
}
// Break to new line when a character is beyond break width.
if ((type == NVG_CHAR || type == NVG_CJK_CHAR) && nextWidth > breakRowWidth) {
// The run length is too long, need to break to new line.
if (breakEnd == rowStart) {
// The current word is longer than the row length, just break it from here.
rows[nrows].start = rowStart;
rows[nrows].end = iter.str;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = iter.str;
nrows++;
if (nrows >= maxRows)
return nrows;
rowStartX = iter.x;
rowStart = iter.str;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMinX = q.x0 - rowStartX;
rowMaxX = q.x1 - rowStartX;
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0 - rowStartX;
} else {
// Break the line from the end of the last word, and start new line from the beginning of the new.
rows[nrows].start = rowStart;
rows[nrows].end = breakEnd;
rows[nrows].width = breakWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = breakMaxX * invscale;
rows[nrows].next = wordStart;
nrows++;
if (nrows >= maxRows)
return nrows;
// Update row
rowStartX = wordStartX;
rowStart = wordStart;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMinX = wordMinX - rowStartX;
rowMaxX = q.x1 - rowStartX;
}
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
}
}
}
pcodepoint = iter.codepoint;
ptype = type;
}
// Break the line from the end of the last word, and start new line from the beginning of the new.
if (rowStart != NULL) {
rows[nrows].start = rowStart;
rows[nrows].end = rowEnd;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = end;
nrows++;
}
return nrows;
}
float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
float width;
if (state->fontId == FONS_INVALID) return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds);
if (bounds != NULL) {
// Use line bounds for height.
fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]);
bounds[0] *= invscale;
bounds[1] *= invscale;
bounds[2] *= invscale;
bounds[3] *= invscale;
}
return width * invscale;
}
void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds)
{
NVGstate* state = nvg__getState(ctx);
NVGtextRow rows[2];
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
int nrows = 0, i;
int oldAlign = state->textAlign;
int halign = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
float lineh = 0, rminy = 0, rmaxy = 0;
float minx, miny, maxx, maxy;
if (state->fontId == FONS_INVALID) {
if (bounds != NULL)
bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0f;
return;
}
nvgTextMetrics(ctx, NULL, NULL, &lineh);
state->textAlign = NVG_ALIGN_LEFT | valign;
minx = maxx = x;
miny = maxy = y;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsLineBounds(ctx->fs, 0, &rminy, &rmaxy);
rminy *= invscale;
rmaxy *= invscale;
while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
for (i = 0; i < nrows; i++) {
NVGtextRow* row = &rows[i];
float rminx, rmaxx, dx = 0;
// Horizontal bounds
if (halign & NVG_ALIGN_LEFT)
dx = 0;
else if (halign & NVG_ALIGN_CENTER)
dx = breakRowWidth*0.5f - row->width*0.5f;
else if (halign & NVG_ALIGN_RIGHT)
dx = breakRowWidth - row->width;
rminx = x + row->minx + dx;
rmaxx = x + row->maxx + dx;
minx = nvg__minf(minx, rminx);
maxx = nvg__maxf(maxx, rmaxx);
// Vertical bounds.
miny = nvg__minf(miny, y + rminy);
maxy = nvg__maxf(maxy, y + rmaxy);
y += lineh * state->lineHeight;
}
string = rows[nrows-1].next;
}
state->textAlign = oldAlign;
if (bounds != NULL) {
bounds[0] = minx;
bounds[1] = miny;
bounds[2] = maxx;
bounds[3] = maxy;
}
}
void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
if (state->fontId == FONS_INVALID) return;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsVertMetrics(ctx->fs, ascender, descender, lineh);
if (ascender != NULL)
*ascender *= invscale;
if (descender != NULL)
*descender *= invscale;
if (lineh != NULL)
*lineh *= invscale;
}
// vim: ft=c nu noet ts=4
``` | /content/code_sandbox/libs/nanovg/src/nanovg.c | c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 28,814 |
```c++
// Allpass filter implementation
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#include "allpass.hpp"
allpass::allpass()
{
bufidx = 0;
}
void allpass::setbuffer(float *buf, int size)
{
buffer = buf;
bufsize = size;
}
void allpass::mute()
{
for (int i=0; i<bufsize; i++)
buffer[i]=0;
}
void allpass::setfeedback(float val)
{
feedback = val;
}
float allpass::getfeedback()
{
return feedback;
}
//ends
``` | /content/code_sandbox/libs/freeverb/src/allpass.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 143 |
```objective-c
/* stb_image - v2.29 - public domain image loader - path_to_url
no warranty implied; use at your own risk
Do this:
#define STB_IMAGE_IMPLEMENTATION
before you include this file in *one* C or C++ file to create the implementation.
// i.e. it should look like this:
#include ...
#include ...
#include ...
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
QUICK NOTES:
Primarily of interest to game developers and other people who can
avoid problematic images and only need the trivial interface
JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
PNG 1/2/4/8/16-bit-per-channel
TGA (not sure what subset, if a subset)
BMP non-1bpp, non-RLE
PSD (composited view only, no extra channels, 8/16 bit-per-channel)
GIF (*comp always reports as 4-channel)
HDR (radiance rgbE format)
PIC (Softimage PIC)
PNM (PPM and PGM binary only)
Animated GIF still needs a proper API, but here's one way to do it:
path_to_url
- decode from memory or through FILE (define STBI_NO_STDIO to remove code)
- decode from arbitrary I/O callbacks
- SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
Full documentation under "DOCUMENTATION" below.
LICENSE
See end of file for license information.
RECENT REVISION HISTORY:
2.29 (2023-05-xx) optimizations
2.28 (2023-01-29) many error fixes, security errors, just tons of stuff
2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
2.26 (2020-07-13) many minor fixes
2.25 (2020-02-02) fix warnings
2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
2.23 (2019-08-11) fix clang static analysis warning
2.22 (2019-03-04) gif fixes, fix warnings
2.21 (2019-02-25) fix typo in comment
2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
2.19 (2018-02-11) fix warning
2.18 (2018-01-30) fix warnings
2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings
2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes
2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC
2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes
2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
RGB-format JPEG; remove white matting in PSD;
allocate large structures on the stack;
correct channel count for PNG & BMP
2.10 (2016-01-22) avoid warning introduced in 2.09
2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
See end of file for full revision history.
============================ Contributors =========================
Image formats Extensions, features
Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
github:urraka (animated gif) Junggon Kim (PNM comments)
Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
socks-the-fox (16-bit PNG)
Jeremy Sawicki (handle all ImageNet JPGs)
Optimizations & bugfixes Mikhail Morozov (1-bit BMP)
Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)
Arseny Kapoulkine Simon Breuss (16-bit PNM)
John-Mark Allen
Carmelo J Fdez-Aguera
Bug & warning fixes
Marc LeBlanc David Woo Guillaume George Martins Mozeiko
Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski
Phil Jordan Dave Moore Roy Eltham
Hayaki Saito Nathan Reed Won Chun
Luke Graham Johan Duparc Nick Verigakis the Horde3D community
Thomas Ruf Ronny Chevalier github:rlyeh
Janez Zemva John Bartholomew Michal Cichon github:romigrou
Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
Eugene Golushkov Laurent Gomila Cort Stratton github:snagar
Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex
Cass Everitt Ryamond Barbiero github:grim210
Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw
Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus
Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo
Julian Raschke Gregory Mullen Christian Floisand github:darealshinji
Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007
Brad Weinberger Matvey Cherevko github:mosra
Luca Sas Alexander Veselov Zack Middleton [reserved]
Ryan C. Gordon [reserved] [reserved]
DO NOT ADD YOUR NAME HERE
Jacko Dirks
To add your name to the credits, pick a random blank space in the middle and fill it.
80% of merge conflicts on stb PRs are due to people adding their name at the end
of the credits.
*/
#ifndef STBI_INCLUDE_STB_IMAGE_H
#define STBI_INCLUDE_STB_IMAGE_H
// DOCUMENTATION
//
// Limitations:
// - no 12-bit-per-channel JPEG
// - no JPEGs with arithmetic coding
// - GIF always returns *comp=4
//
// Basic usage (see HDR discussion below for HDR usage):
// int x,y,n;
// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
// // ... process data if not NULL ...
// // ... x = width, y = height, n = # 8-bit components per pixel ...
// // ... replace '0' with '1'..'4' to force that many components per pixel
// // ... but 'n' will always be the number that it would have been if you said 0
// stbi_image_free(data);
//
// Standard parameters:
// int *x -- outputs image width in pixels
// int *y -- outputs image height in pixels
// int *channels_in_file -- outputs # of image components in image file
// int desired_channels -- if non-zero, # of image components requested in result
//
// The return value from an image loader is an 'unsigned char *' which points
// to the pixel data, or NULL on an allocation failure or if the image is
// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
// with each pixel consisting of N interleaved 8-bit components; the first
// pixel pointed to is top-left-most in the image. There is no padding between
// image scanlines or between pixels, regardless of format. The number of
// components N is 'desired_channels' if desired_channels is non-zero, or
// *channels_in_file otherwise. If desired_channels is non-zero,
// *channels_in_file has the number of components that _would_ have been
// output otherwise. E.g. if you set desired_channels to 4, you will always
// get RGBA output, but you can check *channels_in_file to see if it's trivially
// opaque because e.g. there were only 3 channels in the source image.
//
// An output image with N components has the following components interleaved
// in this order in each pixel:
//
// N=#comp components
// 1 grey
// 2 grey, alpha
// 3 red, green, blue
// 4 red, green, blue, alpha
//
// If image loading fails for any reason, the return value will be NULL,
// and *x, *y, *channels_in_file will be unchanged. The function
// stbi_failure_reason() can be queried for an extremely brief, end-user
// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
// more user-friendly ones.
//
// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
//
// To query the width, height and component count of an image without having to
// decode the full file, you can use the stbi_info family of functions:
//
// int x,y,n,ok;
// ok = stbi_info(filename, &x, &y, &n);
// // returns ok=1 and sets x, y, n if image is a supported format,
// // 0 otherwise.
//
// Note that stb_image pervasively uses ints in its public API for sizes,
// including sizes of memory buffers. This is now part of the API and thus
// hard to change without causing breakage. As a result, the various image
// loaders all have certain limits on image size; these differ somewhat
// by format but generally boil down to either just under 2GB or just under
// 1GB. When the decoded image would be larger than this, stb_image decoding
// will fail.
//
// Additionally, stb_image will reject image files that have any of their
// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
// the only way to have an image with such dimensions load correctly
// is for it to have a rather extreme aspect ratio. Either way, the
// assumption here is that such larger images are likely to be malformed
// or malicious. If you do need to load an image with individual dimensions
// larger than that, and it still fits in the overall size limit, you can
// #define STBI_MAX_DIMENSIONS on your own to be something larger.
//
// ===========================================================================
//
// UNICODE:
//
// If compiling for Windows and you wish to use Unicode filenames, compile
// with
// #define STBI_WINDOWS_UTF8
// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert
// Windows wchar_t filenames to utf8.
//
// ===========================================================================
//
// Philosophy
//
// stb libraries are designed with the following priorities:
//
// 1. easy to use
// 2. easy to maintain
// 3. good performance
//
// Sometimes I let "good performance" creep up in priority over "easy to maintain",
// and for best performance I may provide less-easy-to-use APIs that give higher
// performance, in addition to the easy-to-use ones. Nevertheless, it's important
// to keep in mind that from the standpoint of you, a client of this library,
// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.
//
// Some secondary priorities arise directly from the first two, some of which
// provide more explicit reasons why performance can't be emphasized.
//
// - Portable ("ease of use")
// - Small source code footprint ("easy to maintain")
// - No dependencies ("ease of use")
//
// ===========================================================================
//
// I/O callbacks
//
// I/O callbacks allow you to read from arbitrary sources, like packaged
// files or some other source. Data read from callbacks are processed
// through a small internal buffer (currently 128 bytes) to try to reduce
// overhead.
//
// The three functions you must define are "read" (reads some bytes of data),
// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
//
// ===========================================================================
//
// SIMD support
//
// The JPEG decoder will try to automatically use SIMD kernels on x86 when
// supported by the compiler. For ARM Neon support, you must explicitly
// request it.
//
// (The old do-it-yourself SIMD API is no longer supported in the current
// code.)
//
// On x86, SSE2 will automatically be used when available based on a run-time
// test; if not, the generic C versions are used as a fall-back. On ARM targets,
// the typical path is to have separate builds for NEON and non-NEON devices
// (at least this is true for iOS and Android). Therefore, the NEON support is
// toggled by a build flag: define STBI_NEON to get NEON loops.
//
// If for some reason you do not want to use any of SIMD code, or if
// you have issues compiling it, you can disable it entirely by
// defining STBI_NO_SIMD.
//
// ===========================================================================
//
// HDR image support (disable by defining STBI_NO_HDR)
//
// stb_image supports loading HDR images in general, and currently the Radiance
// .HDR file format specifically. You can still load any file through the existing
// interface; if you attempt to load an HDR file, it will be automatically remapped
// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
// both of these constants can be reconfigured through this interface:
//
// stbi_hdr_to_ldr_gamma(2.2f);
// stbi_hdr_to_ldr_scale(1.0f);
//
// (note, do not use _inverse_ constants; stbi_image will invert them
// appropriately).
//
// Additionally, there is a new, parallel interface for loading files as
// (linear) floats to preserve the full dynamic range:
//
// float *data = stbi_loadf(filename, &x, &y, &n, 0);
//
// If you load LDR images through this interface, those images will
// be promoted to floating point values, run through the inverse of
// constants corresponding to the above:
//
// stbi_ldr_to_hdr_scale(1.0f);
// stbi_ldr_to_hdr_gamma(2.2f);
//
// Finally, given a filename (or an open file or memory block--see header
// file for details) containing image data, you can query for the "most
// appropriate" interface to use (that is, whether the image is HDR or
// not), using:
//
// stbi_is_hdr(char *filename);
//
// ===========================================================================
//
// iPhone PNG support:
//
// We optionally support converting iPhone-formatted PNGs (which store
// premultiplied BGRA) back to RGB, even though they're internally encoded
// differently. To enable this conversion, call
// stbi_convert_iphone_png_to_rgb(1).
//
// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
// pixel to remove any premultiplied alpha *only* if the image file explicitly
// says there's premultiplied data (currently only happens in iPhone images,
// and only if iPhone convert-to-rgb processing is on).
//
// ===========================================================================
//
// ADDITIONAL CONFIGURATION
//
// - You can suppress implementation of any of the decoders to reduce
// your code footprint by #defining one or more of the following
// symbols before creating the implementation.
//
// STBI_NO_JPEG
// STBI_NO_PNG
// STBI_NO_BMP
// STBI_NO_PSD
// STBI_NO_TGA
// STBI_NO_GIF
// STBI_NO_HDR
// STBI_NO_PIC
// STBI_NO_PNM (.ppm and .pgm)
//
// - You can request *only* certain decoders and suppress all other ones
// (this will be more forward-compatible, as addition of new decoders
// doesn't require you to disable them explicitly):
//
// STBI_ONLY_JPEG
// STBI_ONLY_PNG
// STBI_ONLY_BMP
// STBI_ONLY_PSD
// STBI_ONLY_TGA
// STBI_ONLY_GIF
// STBI_ONLY_HDR
// STBI_ONLY_PIC
// STBI_ONLY_PNM (.ppm and .pgm)
//
// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
//
// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
// than that size (in either width or height) without further processing.
// This is to let programs in the wild set an upper bound to prevent
// denial-of-service attacks on untrusted data, as one could generate a
// valid image of gigantic dimensions and force stb_image to allocate a
// huge block of memory and spend disproportionate time decoding it. By
// default this is set to (1 << 24), which is 16777216, but that's still
// very big.
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif // STBI_NO_STDIO
#define STBI_VERSION 1
enum
{
STBI_default = 0, // only used for desired_channels
STBI_grey = 1,
STBI_grey_alpha = 2,
STBI_rgb = 3,
STBI_rgb_alpha = 4
};
#include <stdlib.h>
typedef unsigned char stbi_uc;
typedef unsigned short stbi_us;
#ifdef __cplusplus
extern "C" {
#endif
#ifndef STBIDEF
#ifdef STB_IMAGE_STATIC
#define STBIDEF static
#else
#define STBIDEF extern
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// PRIMARY API - works on images of any type
//
//
// load image by filename, open file, or memory buffer
//
typedef struct
{
int (*read)(void* user, char* data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read
void (*skip)(void* user, int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
int (*eof)(void* user); // returns nonzero if we are at end of file/data
} stbi_io_callbacks;
////////////////////////////////////
//
// 8-bits-per-channel interface
//
STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
// for stbi_load_from_file, file pointer is left pointing immediately after image
#endif
#ifndef STBI_NO_GIF
STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, int** delays, int* x, int* y, int* z, int* comp, int req_comp);
#endif
#ifdef STBI_WINDOWS_UTF8
STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input);
#endif
////////////////////////////////////
//
// 16-bits-per-channel interface
//
STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_us* stbi_load_from_file_16(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
#endif
////////////////////////////////////
//
// float-per-channel interface
//
#ifndef STBI_NO_LINEAR
STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
#endif
#endif
#ifndef STBI_NO_HDR
STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
STBIDEF void stbi_hdr_to_ldr_scale(float scale);
#endif // STBI_NO_HDR
#ifndef STBI_NO_LINEAR
STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
STBIDEF void stbi_ldr_to_hdr_scale(float scale);
#endif // STBI_NO_LINEAR
// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, void* user);
STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_is_hdr(char const* filename);
STBIDEF int stbi_is_hdr_from_file(FILE* f);
#endif // STBI_NO_STDIO
// get a VERY brief reason for failure
// on most compilers (and ALL modern mainstream compilers) this is threadsafe
STBIDEF const char* stbi_failure_reason(void);
// free the loaded image -- this is just free()
STBIDEF void stbi_image_free(void* retval_from_stbi_load);
// get image dimensions & components without fully decoding
STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp);
STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp);
STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len);
STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* clbk, void* user);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp);
STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp);
STBIDEF int stbi_is_16_bit(char const* filename);
STBIDEF int stbi_is_16_bit_from_file(FILE* f);
#endif
// for image formats that explicitly notate that they have premultiplied alpha,
// we just return the colors as stored in the file. set this flag to force
// unpremultiplication. results are undefined if the unpremultiply overflow.
STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
// indicate whether we should process iphone images back to canonical format,
// or just pass them through "as-is"
STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
// flip the image vertically, so the first pixel in the output array is the bottom left
STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
// as above, but only applies to images loaded on the thread that calls the function
// this function is only available if your compiler supports thread-local variables;
// calling it will fail to link if your compiler doesn't
STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
// ZLIB client - used by PNG, available for other purposes
STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, int initial_size, int* outlen);
STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, int len, int initial_size, int* outlen, int parse_header);
STBIDEF char* stbi_zlib_decode_malloc(const char* buffer, int len, int* outlen);
STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, const char* ibuffer, int ilen);
STBIDEF char* stbi_zlib_decode_noheader_malloc(const char* buffer, int len, int* outlen);
STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, const char* ibuffer, int ilen);
#ifdef __cplusplus
}
#endif
//
//
//// end header file /////////////////////////////////////////////////////
#endif // STBI_INCLUDE_STB_IMAGE_H
#ifdef STB_IMAGE_IMPLEMENTATION
#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) || defined(STBI_ONLY_ZLIB)
#ifndef STBI_ONLY_JPEG
#define STBI_NO_JPEG
#endif
#ifndef STBI_ONLY_PNG
#define STBI_NO_PNG
#endif
#ifndef STBI_ONLY_BMP
#define STBI_NO_BMP
#endif
#ifndef STBI_ONLY_PSD
#define STBI_NO_PSD
#endif
#ifndef STBI_ONLY_TGA
#define STBI_NO_TGA
#endif
#ifndef STBI_ONLY_GIF
#define STBI_NO_GIF
#endif
#ifndef STBI_ONLY_HDR
#define STBI_NO_HDR
#endif
#ifndef STBI_ONLY_PIC
#define STBI_NO_PIC
#endif
#ifndef STBI_ONLY_PNM
#define STBI_NO_PNM
#endif
#endif
#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
#define STBI_NO_ZLIB
#endif
#include <stdarg.h>
#include <stddef.h> // ptrdiff_t on osx
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
#include <math.h> // ldexp, pow
#endif
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#ifndef STBI_ASSERT
#include <assert.h>
#define STBI_ASSERT(x) assert(x)
#endif
#ifdef __cplusplus
#define STBI_EXTERN extern "C"
#else
#define STBI_EXTERN extern
#endif
#ifndef _MSC_VER
#ifdef __cplusplus
#define stbi_inline inline
#else
#define stbi_inline
#endif
#else
#define stbi_inline __forceinline
#endif
#ifndef STBI_NO_THREAD_LOCALS
#if defined(__cplusplus) && __cplusplus >= 201103L
#define STBI_THREAD_LOCAL thread_local
#elif defined(__GNUC__) && __GNUC__ < 5
#define STBI_THREAD_LOCAL __thread
#elif defined(_MSC_VER)
#define STBI_THREAD_LOCAL __declspec(thread)
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
#define STBI_THREAD_LOCAL _Thread_local
#endif
#ifndef STBI_THREAD_LOCAL
#if defined(__GNUC__)
#define STBI_THREAD_LOCAL __thread
#endif
#endif
#endif
#if defined(_MSC_VER) || defined(__SYMBIAN32__)
typedef unsigned short stbi__uint16;
typedef signed short stbi__int16;
typedef unsigned int stbi__uint32;
typedef signed int stbi__int32;
#else
#include <stdint.h>
typedef uint16_t stbi__uint16;
typedef int16_t stbi__int16;
typedef uint32_t stbi__uint32;
typedef int32_t stbi__int32;
#endif
// should produce compiler error if size is wrong
typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1];
#ifdef _MSC_VER
#define STBI_NOTUSED(v) (void)(v)
#else
#define STBI_NOTUSED(v) (void)sizeof(v)
#endif
#ifdef _MSC_VER
#define STBI_HAS_LROTL
#endif
#ifdef STBI_HAS_LROTL
#define stbi_lrot(x, y) _lrotl(x, y)
#else
#define stbi_lrot(x, y) (((x) << (y)) | ((x) >> (-(y)&31)))
#endif
#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
// ok
#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
// ok
#else
#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
#endif
#ifndef STBI_MALLOC
#define STBI_MALLOC(sz) malloc(sz)
#define STBI_REALLOC(p, newsz) realloc(p, newsz)
#define STBI_FREE(p) free(p)
#endif
#ifndef STBI_REALLOC_SIZED
#define STBI_REALLOC_SIZED(p, oldsz, newsz) STBI_REALLOC(p, newsz)
#endif
// x86/x64 detection
#if defined(__x86_64__) || defined(_M_X64)
#define STBI__X64_TARGET
#elif defined(__i386) || defined(_M_IX86)
#define STBI__X86_TARGET
#endif
#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
// gcc doesn't support sse2 intrinsics unless you compile with -msse2,
// which in turn means it gets to use SSE2 everywhere. This is unfortunate,
// but previous attempts to provide the SSE2 functions with runtime
// detection caused numerous issues. The way architecture extensions are
// exposed in GCC/Clang is, sadly, not really suited for one-file libs.
// New behavior: if compiled with -msse2, we use SSE2 without any
// detection; if not, we don't use it at all.
#define STBI_NO_SIMD
#endif
#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
//
// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
// simultaneously enabling "-mstackrealign".
//
// See path_to_url for more information.
//
// So default to no SSE2 on 32-bit MinGW. If you've read this far and added
// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
#define STBI_NO_SIMD
#endif
#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
#define STBI_SSE2
#include <emmintrin.h>
#ifdef _MSC_VER
#if _MSC_VER >= 1400 // not VC6
#include <intrin.h> // __cpuid
static int stbi__cpuid3(void)
{
int info[4];
__cpuid(info, 1);
return info[3];
}
#else
static int stbi__cpuid3(void)
{
int res;
__asm {
mov eax,1
cpuid
mov res,edx
}
return res;
}
#endif
#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
static int stbi__sse2_available(void)
{
int info3 = stbi__cpuid3();
return ((info3 >> 26) & 1) != 0;
}
#endif
#else // assume GCC-style if not VC++
#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
static int stbi__sse2_available(void)
{
// If we're even attempting to compile this on GCC/Clang, that means
// -msse2 is on, which means the compiler is allowed to use SSE2
// instructions at will, and so are we.
return 1;
}
#endif
#endif
#endif
// ARM NEON
#if defined(STBI_NO_SIMD) && defined(STBI_NEON)
#undef STBI_NEON
#endif
#ifdef STBI_NEON
#include <arm_neon.h>
#ifdef _MSC_VER
#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
#else
#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
#endif
#endif
#ifndef STBI_SIMD_ALIGN
#define STBI_SIMD_ALIGN(type, name) type name
#endif
#ifndef STBI_MAX_DIMENSIONS
#define STBI_MAX_DIMENSIONS (1 << 24)
#endif
///////////////////////////////////////////////
//
// stbi__context struct and start_xxx functions
// stbi__context structure is our basic context used by all images, so it
// contains all the IO context, plus some basic image information
typedef struct
{
stbi__uint32 img_x, img_y;
int img_n, img_out_n;
stbi_io_callbacks io;
void* io_user_data;
int read_from_callbacks;
int buflen;
stbi_uc buffer_start[128];
int callback_already_read;
stbi_uc *img_buffer, *img_buffer_end;
stbi_uc *img_buffer_original, *img_buffer_original_end;
} stbi__context;
static void stbi__refill_buffer(stbi__context* s);
// initialize a memory-decode context
static void stbi__start_mem(stbi__context* s, stbi_uc const* buffer, int len)
{
s->io.read = NULL;
s->read_from_callbacks = 0;
s->callback_already_read = 0;
s->img_buffer = s->img_buffer_original = (stbi_uc*)buffer;
s->img_buffer_end = s->img_buffer_original_end = (stbi_uc*)buffer + len;
}
// initialize a callback-based context
static void stbi__start_callbacks(stbi__context* s, stbi_io_callbacks* c, void* user)
{
s->io = *c;
s->io_user_data = user;
s->buflen = sizeof(s->buffer_start);
s->read_from_callbacks = 1;
s->callback_already_read = 0;
s->img_buffer = s->img_buffer_original = s->buffer_start;
stbi__refill_buffer(s);
s->img_buffer_original_end = s->img_buffer_end;
}
#ifndef STBI_NO_STDIO
static int stbi__stdio_read(void* user, char* data, int size)
{
return (int)fread(data, 1, size, (FILE*)user);
}
static void stbi__stdio_skip(void* user, int n)
{
int ch;
fseek((FILE*)user, n, SEEK_CUR);
ch = fgetc((FILE*)user); /* have to read a byte to reset feof()'s flag */
if (ch != EOF)
{
ungetc(ch, (FILE*)user); /* push byte back onto stream if valid. */
}
}
static int stbi__stdio_eof(void* user)
{
return feof((FILE*)user) || ferror((FILE*)user);
}
static stbi_io_callbacks stbi__stdio_callbacks = {
stbi__stdio_read,
stbi__stdio_skip,
stbi__stdio_eof,
};
static void stbi__start_file(stbi__context* s, FILE* f)
{
stbi__start_callbacks(s, &stbi__stdio_callbacks, (void*)f);
}
//static void stop_file(stbi__context *s) { }
#endif // !STBI_NO_STDIO
static void stbi__rewind(stbi__context* s)
{
// conceptually rewind SHOULD rewind to the beginning of the stream,
// but we just rewind to the beginning of the initial buffer, because
// we only use it after doing 'test', which only ever looks at at most 92 bytes
s->img_buffer = s->img_buffer_original;
s->img_buffer_end = s->img_buffer_original_end;
}
enum
{
STBI_ORDER_RGB,
STBI_ORDER_BGR
};
typedef struct
{
int bits_per_channel;
int num_channels;
int channel_order;
} stbi__result_info;
#ifndef STBI_NO_JPEG
static int stbi__jpeg_test(stbi__context* s);
static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_PNG
static int stbi__png_test(stbi__context* s);
static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp);
static int stbi__png_is16(stbi__context* s);
#endif
#ifndef STBI_NO_BMP
static int stbi__bmp_test(stbi__context* s);
static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_TGA
static int stbi__tga_test(stbi__context* s);
static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_PSD
static int stbi__psd_test(stbi__context* s);
static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc);
static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp);
static int stbi__psd_is16(stbi__context* s);
#endif
#ifndef STBI_NO_HDR
static int stbi__hdr_test(stbi__context* s);
static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_PIC
static int stbi__pic_test(stbi__context* s);
static void* stbi__pic_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_GIF
static int stbi__gif_test(stbi__context* s);
static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, int* z, int* comp, int req_comp);
static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp);
#endif
#ifndef STBI_NO_PNM
static int stbi__pnm_test(stbi__context* s);
static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri);
static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp);
static int stbi__pnm_is16(stbi__context* s);
#endif
static
#ifdef STBI_THREAD_LOCAL
STBI_THREAD_LOCAL
#endif
const char* stbi__g_failure_reason;
STBIDEF const char* stbi_failure_reason(void)
{
return stbi__g_failure_reason;
}
#ifndef STBI_NO_FAILURE_STRINGS
static int stbi__err(const char* str)
{
stbi__g_failure_reason = str;
return 0;
}
#endif
static void* stbi__malloc(size_t size)
{
return STBI_MALLOC(size);
}
// stb_image uses ints pervasively, including for offset calculations.
// therefore the largest decoded image size we can support with the
// current code, even on 64-bit targets, is INT_MAX. this is not a
// significant limitation for the intended use case.
//
// we do, however, need to make sure our size calculations don't
// overflow. hence a few helper functions for size calculations that
// multiply integers together, making sure that they're non-negative
// and no overflow occurs.
// return 1 if the sum is valid, 0 on overflow.
// negative terms are considered invalid.
static int stbi__addsizes_valid(int a, int b)
{
if (b < 0)
return 0;
// now 0 <= b <= INT_MAX, hence also
// 0 <= INT_MAX - b <= INTMAX.
// And "a + b <= INT_MAX" (which might overflow) is the
// same as a <= INT_MAX - b (no overflow)
return a <= INT_MAX - b;
}
// returns 1 if the product is valid, 0 on overflow.
// negative factors are considered invalid.
static int stbi__mul2sizes_valid(int a, int b)
{
if (a < 0 || b < 0)
return 0;
if (b == 0)
return 1; // mul-by-0 is always safe
// portable way to check for no overflows in a*b
return a <= INT_MAX / b;
}
#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow
static int stbi__mad2sizes_valid(int a, int b, int add)
{
return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a * b, add);
}
#endif
// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow
static int stbi__mad3sizes_valid(int a, int b, int c, int add)
{
return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) &&
stbi__addsizes_valid(a * b * c, add);
}
// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow
#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
{
return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) &&
stbi__mul2sizes_valid(a * b * c, d) && stbi__addsizes_valid(a * b * c * d, add);
}
#endif
#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
// mallocs with size overflow checking
static void* stbi__malloc_mad2(int a, int b, int add)
{
if (!stbi__mad2sizes_valid(a, b, add))
return NULL;
return stbi__malloc(a * b + add);
}
#endif
static void* stbi__malloc_mad3(int a, int b, int c, int add)
{
if (!stbi__mad3sizes_valid(a, b, c, add))
return NULL;
return stbi__malloc(a * b * c + add);
}
#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
static void* stbi__malloc_mad4(int a, int b, int c, int d, int add)
{
if (!stbi__mad4sizes_valid(a, b, c, d, add))
return NULL;
return stbi__malloc(a * b * c * d + add);
}
#endif
// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.
static int stbi__addints_valid(int a, int b)
{
if ((a >= 0) != (b >= 0))
return 1; // a and b have different signs, so no overflow
if (a < 0 && b < 0)
return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.
return a <= INT_MAX - b;
}
// returns 1 if the product of two ints fits in a signed short, 0 on overflow.
static int stbi__mul2shorts_valid(int a, int b)
{
if (b == 0 || b == -1)
return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow
if ((a >= 0) == (b >= 0))
return a <= SHRT_MAX / b; // product is positive, so similar to mul2sizes_valid
if (b < 0)
return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN
return a >= SHRT_MIN / b;
}
// stbi__err - error
// stbi__errpf - error returning pointer to float
// stbi__errpuc - error returning pointer to unsigned char
#ifdef STBI_NO_FAILURE_STRINGS
#define stbi__err(x, y) 0
#elif defined(STBI_FAILURE_USERMSG)
#define stbi__err(x, y) stbi__err(y)
#else
#define stbi__err(x, y) stbi__err(x)
#endif
#define stbi__errpf(x, y) ((float*)(size_t)(stbi__err(x, y) ? NULL : NULL))
#define stbi__errpuc(x, y) ((unsigned char*)(size_t)(stbi__err(x, y) ? NULL : NULL))
STBIDEF void stbi_image_free(void* retval_from_stbi_load)
{
STBI_FREE(retval_from_stbi_load);
}
#ifndef STBI_NO_LINEAR
static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp);
#endif
#ifndef STBI_NO_HDR
static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp);
#endif
static int stbi__vertically_flip_on_load_global = 0;
STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
{
stbi__vertically_flip_on_load_global = flag_true_if_should_flip;
}
#ifndef STBI_THREAD_LOCAL
#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global
#else
static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;
STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)
{
stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
stbi__vertically_flip_on_load_set = 1;
}
#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \
? stbi__vertically_flip_on_load_local \
: stbi__vertically_flip_on_load_global)
#endif // STBI_THREAD_LOCAL
static void* stbi__load_main(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc)
{
memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields
ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed
ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
ri->num_channels = 0;
// test the formats with a very explicit header first (at least a FOURCC
// or distinctive magic number first)
#ifndef STBI_NO_PNG
if (stbi__png_test(s))
return stbi__png_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_BMP
if (stbi__bmp_test(s))
return stbi__bmp_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_GIF
if (stbi__gif_test(s))
return stbi__gif_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_PSD
if (stbi__psd_test(s))
return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc);
#else
STBI_NOTUSED(bpc);
#endif
#ifndef STBI_NO_PIC
if (stbi__pic_test(s))
return stbi__pic_load(s, x, y, comp, req_comp, ri);
#endif
// then the formats that can end up attempting to load with just 1 or 2
// bytes matching expectations; these are prone to false positives, so
// try them later
#ifndef STBI_NO_JPEG
if (stbi__jpeg_test(s))
return stbi__jpeg_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_PNM
if (stbi__pnm_test(s))
return stbi__pnm_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_HDR
if (stbi__hdr_test(s))
{
float* hdr = stbi__hdr_load(s, x, y, comp, req_comp, ri);
return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
#ifndef STBI_NO_TGA
// test tga last because it's a crappy test!
if (stbi__tga_test(s))
return stbi__tga_load(s, x, y, comp, req_comp, ri);
#endif
return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
}
static stbi_uc* stbi__convert_16_to_8(stbi__uint16* orig, int w, int h, int channels)
{
int i;
int img_len = w * h * channels;
stbi_uc* reduced;
reduced = (stbi_uc*)stbi__malloc(img_len);
if (reduced == NULL)
return stbi__errpuc("outofmem", "Out of memory");
for (i = 0; i < img_len; ++i)
reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling
STBI_FREE(orig);
return reduced;
}
static stbi__uint16* stbi__convert_8_to_16(stbi_uc* orig, int w, int h, int channels)
{
int i;
int img_len = w * h * channels;
stbi__uint16* enlarged;
enlarged = (stbi__uint16*)stbi__malloc(img_len * 2);
if (enlarged == NULL)
return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory");
for (i = 0; i < img_len; ++i)
enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff
STBI_FREE(orig);
return enlarged;
}
static void stbi__vertical_flip(void* image, int w, int h, int bytes_per_pixel)
{
int row;
size_t bytes_per_row = (size_t)w * bytes_per_pixel;
stbi_uc temp[2048];
stbi_uc* bytes = (stbi_uc*)image;
for (row = 0; row < (h >> 1); row++)
{
stbi_uc* row0 = bytes + row * bytes_per_row;
stbi_uc* row1 = bytes + (h - row - 1) * bytes_per_row;
// swap row0 with row1
size_t bytes_left = bytes_per_row;
while (bytes_left)
{
size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
memcpy(temp, row0, bytes_copy);
memcpy(row0, row1, bytes_copy);
memcpy(row1, temp, bytes_copy);
row0 += bytes_copy;
row1 += bytes_copy;
bytes_left -= bytes_copy;
}
}
}
#ifndef STBI_NO_GIF
static void stbi__vertical_flip_slices(void* image, int w, int h, int z, int bytes_per_pixel)
{
int slice;
int slice_size = w * h * bytes_per_pixel;
stbi_uc* bytes = (stbi_uc*)image;
for (slice = 0; slice < z; ++slice)
{
stbi__vertical_flip(bytes, w, h, bytes_per_pixel);
bytes += slice_size;
}
}
#endif
static unsigned char* stbi__load_and_postprocess_8bit(stbi__context* s, int* x, int* y, int* comp, int req_comp)
{
stbi__result_info ri;
void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
if (result == NULL)
return NULL;
// it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
if (ri.bits_per_channel != 8)
{
result = stbi__convert_16_to_8((stbi__uint16*)result, *x, *y, req_comp == 0 ? *comp : req_comp);
ri.bits_per_channel = 8;
}
// @TODO: move stbi__convert_format to here
if (stbi__vertically_flip_on_load)
{
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
}
return (unsigned char*)result;
}
static stbi__uint16* stbi__load_and_postprocess_16bit(stbi__context* s, int* x, int* y, int* comp, int req_comp)
{
stbi__result_info ri;
void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
if (result == NULL)
return NULL;
// it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
if (ri.bits_per_channel != 16)
{
result = stbi__convert_8_to_16((stbi_uc*)result, *x, *y, req_comp == 0 ? *comp : req_comp);
ri.bits_per_channel = 16;
}
// @TODO: move stbi__convert_format16 to here
// @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision
if (stbi__vertically_flip_on_load)
{
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));
}
return (stbi__uint16*)result;
}
#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
static void stbi__float_postprocess(float* result, int* x, int* y, int* comp, int req_comp)
{
if (stbi__vertically_flip_on_load && result != NULL)
{
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
}
}
#endif
#ifndef STBI_NO_STDIO
#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char* str, int cbmb, wchar_t* widestr, int cchwide);
STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t* widestr, int cchwide, char* str, int cbmb, const char* defchar, int* used_default);
#endif
#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input)
{
return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int)bufferlen, NULL, NULL);
}
#endif
static FILE* stbi__fopen(char const* filename, char const* mode)
{
FILE* f;
#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
wchar_t wMode[64];
wchar_t wFilename[1024];
if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename) / sizeof(*wFilename)))
return 0;
if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode) / sizeof(*wMode)))
return 0;
#if defined(_MSC_VER) && _MSC_VER >= 1400
if (0 != _wfopen_s(&f, wFilename, wMode))
f = 0;
#else
f = _wfopen(wFilename, wMode);
#endif
#elif defined(_MSC_VER) && _MSC_VER >= 1400
if (0 != fopen_s(&f, filename, mode))
f = 0;
#else
f = fopen(filename, mode);
#endif
return f;
}
STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* comp, int req_comp)
{
FILE* f = stbi__fopen(filename, "rb");
unsigned char* result;
if (!f)
return stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f, x, y, comp, req_comp);
fclose(f);
return result;
}
STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* comp, int req_comp)
{
unsigned char* result;
stbi__context s;
stbi__start_file(&s, f);
result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
if (result)
{
// need to 'unget' all the characters in the IO buffer
fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR);
}
return result;
}
STBIDEF stbi__uint16* stbi_load_from_file_16(FILE* f, int* x, int* y, int* comp, int req_comp)
{
stbi__uint16* result;
stbi__context s;
stbi__start_file(&s, f);
result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp);
if (result)
{
// need to 'unget' all the characters in the IO buffer
fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR);
}
return result;
}
STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* comp, int req_comp)
{
FILE* f = stbi__fopen(filename, "rb");
stbi__uint16* result;
if (!f)
return (stbi_us*)stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file_16(f, x, y, comp, req_comp);
fclose(f);
return result;
}
#endif //!STBI_NO_STDIO
STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels)
{
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels);
}
STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user);
return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels);
}
STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp, int req_comp)
{
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp, int req_comp)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
#ifndef STBI_NO_GIF
STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, int** delays, int* x, int* y, int* z, int* comp, int req_comp)
{
unsigned char* result;
stbi__context s;
stbi__start_mem(&s, buffer, len);
result = (unsigned char*)stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
if (stbi__vertically_flip_on_load)
{
stbi__vertical_flip_slices(result, *x, *y, *z, *comp);
}
return result;
}
#endif
#ifndef STBI_NO_LINEAR
static float* stbi__loadf_main(stbi__context* s, int* x, int* y, int* comp, int req_comp)
{
unsigned char* data;
#ifndef STBI_NO_HDR
if (stbi__hdr_test(s))
{
stbi__result_info ri;
float* hdr_data = stbi__hdr_load(s, x, y, comp, req_comp, &ri);
if (hdr_data)
stbi__float_postprocess(hdr_data, x, y, comp, req_comp);
return hdr_data;
}
#endif
data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);
if (data)
return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
}
STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp, int req_comp)
{
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__loadf_main(&s, x, y, comp, req_comp);
}
STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp, int req_comp)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user);
return stbi__loadf_main(&s, x, y, comp, req_comp);
}
#ifndef STBI_NO_STDIO
STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* comp, int req_comp)
{
float* result;
FILE* f = stbi__fopen(filename, "rb");
if (!f)
return stbi__errpf("can't fopen", "Unable to open file");
result = stbi_loadf_from_file(f, x, y, comp, req_comp);
fclose(f);
return result;
}
STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* comp, int req_comp)
{
stbi__context s;
stbi__start_file(&s, f);
return stbi__loadf_main(&s, x, y, comp, req_comp);
}
#endif // !STBI_NO_STDIO
#endif // !STBI_NO_LINEAR
// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
// reports false!
STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len)
{
#ifndef STBI_NO_HDR
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__hdr_test(&s);
#else
STBI_NOTUSED(buffer);
STBI_NOTUSED(len);
return 0;
#endif
}
#ifndef STBI_NO_STDIO
STBIDEF int stbi_is_hdr(char const* filename)
{
FILE* f = stbi__fopen(filename, "rb");
int result = 0;
if (f)
{
result = stbi_is_hdr_from_file(f);
fclose(f);
}
return result;
}
STBIDEF int stbi_is_hdr_from_file(FILE* f)
{
#ifndef STBI_NO_HDR
long pos = ftell(f);
int res;
stbi__context s;
stbi__start_file(&s, f);
res = stbi__hdr_test(&s);
fseek(f, pos, SEEK_SET);
return res;
#else
STBI_NOTUSED(f);
return 0;
#endif
}
#endif // !STBI_NO_STDIO
STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, void* user)
{
#ifndef STBI_NO_HDR
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user);
return stbi__hdr_test(&s);
#else
STBI_NOTUSED(clbk);
STBI_NOTUSED(user);
return 0;
#endif
}
#ifndef STBI_NO_LINEAR
static float stbi__l2h_gamma = 2.2f, stbi__l2h_scale = 1.0f;
STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
#endif
static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f;
STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; }
STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; }
//////////////////////////////////////////////////////////////////////////////
//
// Common code used by all image loaders
//
enum
{
STBI__SCAN_load = 0,
STBI__SCAN_type,
STBI__SCAN_header
};
static void stbi__refill_buffer(stbi__context* s)
{
int n = (s->io.read)(s->io_user_data, (char*)s->buffer_start, s->buflen);
s->callback_already_read += (int)(s->img_buffer - s->img_buffer_original);
if (n == 0)
{
// at end of file, treat same as if from memory, but need to handle case
// where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
s->read_from_callbacks = 0;
s->img_buffer = s->buffer_start;
s->img_buffer_end = s->buffer_start + 1;
*s->img_buffer = 0;
}
else
{
s->img_buffer = s->buffer_start;
s->img_buffer_end = s->buffer_start + n;
}
}
stbi_inline static stbi_uc stbi__get8(stbi__context* s)
{
if (s->img_buffer < s->img_buffer_end)
return *s->img_buffer++;
if (s->read_from_callbacks)
{
stbi__refill_buffer(s);
return *s->img_buffer++;
}
return 0;
}
#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
// nothing
#else
stbi_inline static int stbi__at_eof(stbi__context* s)
{
if (s->io.read)
{
if (!(s->io.eof)(s->io_user_data))
return 0;
// if feof() is true, check if buffer = end
// special case: we've only got the special 0 character at the end
if (s->read_from_callbacks == 0)
return 1;
}
return s->img_buffer >= s->img_buffer_end;
}
#endif
#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)
// nothing
#else
static void stbi__skip(stbi__context* s, int n)
{
if (n == 0)
return; // already there!
if (n < 0)
{
s->img_buffer = s->img_buffer_end;
return;
}
if (s->io.read)
{
int blen = (int)(s->img_buffer_end - s->img_buffer);
if (blen < n)
{
s->img_buffer = s->img_buffer_end;
(s->io.skip)(s->io_user_data, n - blen);
return;
}
}
s->img_buffer += n;
}
#endif
#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)
// nothing
#else
static int stbi__getn(stbi__context* s, stbi_uc* buffer, int n)
{
if (s->io.read)
{
int blen = (int)(s->img_buffer_end - s->img_buffer);
if (blen < n)
{
int res, count;
memcpy(buffer, s->img_buffer, blen);
count = (s->io.read)(s->io_user_data, (char*)buffer + blen, n - blen);
res = (count == (n - blen));
s->img_buffer = s->img_buffer_end;
return res;
}
}
if (s->img_buffer + n <= s->img_buffer_end)
{
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
return 1;
}
else
return 0;
}
#endif
#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
// nothing
#else
static int stbi__get16be(stbi__context* s)
{
int z = stbi__get8(s);
return (z << 8) + stbi__get8(s);
}
#endif
#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
// nothing
#else
static stbi__uint32 stbi__get32be(stbi__context* s)
{
stbi__uint32 z = stbi__get16be(s);
return (z << 16) + stbi__get16be(s);
}
#endif
#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
// nothing
#else
static int stbi__get16le(stbi__context* s)
{
int z = stbi__get8(s);
return z + (stbi__get8(s) << 8);
}
#endif
#ifndef STBI_NO_BMP
static stbi__uint32 stbi__get32le(stbi__context* s)
{
stbi__uint32 z = stbi__get16le(s);
z += (stbi__uint32)stbi__get16le(s) << 16;
return z;
}
#endif
#define STBI__BYTECAST(x) ((stbi_uc)((x)&255)) // truncate int to byte without warnings
#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
// nothing
#else
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static stbi_uc stbi__compute_y(int r, int g, int b)
{
return (stbi_uc)(((r * 77) + (g * 150) + (29 * b)) >> 8);
}
#endif
#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
// nothing
#else
static unsigned char* stbi__convert_format(unsigned char* data, int img_n, int req_comp, unsigned int x, unsigned int y)
{
int i, j;
unsigned char* good;
if (req_comp == img_n)
return data;
STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
good = (unsigned char*)stbi__malloc_mad3(req_comp, x, y, 0);
if (good == NULL)
{
STBI_FREE(data);
return stbi__errpuc("outofmem", "Out of memory");
}
for (j = 0; j < (int)y; ++j)
{
unsigned char* src = data + j * x * img_n;
unsigned char* dest = good + j * x * req_comp;
#define STBI__COMBO(a, b) ((a)*8 + (b))
#define STBI__CASE(a, b) \
case STBI__COMBO(a, b): \
for (i = x - 1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch (STBI__COMBO(img_n, req_comp))
{
STBI__CASE(1, 2)
{
dest[0] = src[0];
dest[1] = 255;
}
break;
STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; }
break;
STBI__CASE(1, 4)
{
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = 255;
}
break;
STBI__CASE(2, 1) { dest[0] = src[0]; }
break;
STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; }
break;
STBI__CASE(2, 4)
{
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = src[1];
}
break;
STBI__CASE(3, 4)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest[3] = 255;
}
break;
STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); }
break;
STBI__CASE(3, 2)
{
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
dest[1] = 255;
}
break;
STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); }
break;
STBI__CASE(4, 2)
{
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
dest[1] = src[3];
}
break;
STBI__CASE(4, 3)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
break;
default:
STBI_ASSERT(0);
STBI_FREE(data);
STBI_FREE(good);
return stbi__errpuc("unsupported", "Unsupported format conversion");
}
#undef STBI__CASE
}
STBI_FREE(data);
return good;
}
#endif
#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
// nothing
#else
static stbi__uint16 stbi__compute_y_16(int r, int g, int b)
{
return (stbi__uint16)(((r * 77) + (g * 150) + (29 * b)) >> 8);
}
#endif
#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
// nothing
#else
static stbi__uint16* stbi__convert_format16(stbi__uint16* data, int img_n, int req_comp, unsigned int x, unsigned int y)
{
int i, j;
stbi__uint16* good;
if (req_comp == img_n)
return data;
STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
good = (stbi__uint16*)stbi__malloc(req_comp * x * y * 2);
if (good == NULL)
{
STBI_FREE(data);
return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory");
}
for (j = 0; j < (int)y; ++j)
{
stbi__uint16* src = data + j * x * img_n;
stbi__uint16* dest = good + j * x * req_comp;
#define STBI__COMBO(a, b) ((a)*8 + (b))
#define STBI__CASE(a, b) \
case STBI__COMBO(a, b): \
for (i = x - 1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch (STBI__COMBO(img_n, req_comp))
{
STBI__CASE(1, 2)
{
dest[0] = src[0];
dest[1] = 0xffff;
}
break;
STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; }
break;
STBI__CASE(1, 4)
{
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = 0xffff;
}
break;
STBI__CASE(2, 1) { dest[0] = src[0]; }
break;
STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; }
break;
STBI__CASE(2, 4)
{
dest[0] = dest[1] = dest[2] = src[0];
dest[3] = src[1];
}
break;
STBI__CASE(3, 4)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest[3] = 0xffff;
}
break;
STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); }
break;
STBI__CASE(3, 2)
{
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
dest[1] = 0xffff;
}
break;
STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); }
break;
STBI__CASE(4, 2)
{
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
dest[1] = src[3];
}
break;
STBI__CASE(4, 3)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
break;
default:
STBI_ASSERT(0);
STBI_FREE(data);
STBI_FREE(good);
return (stbi__uint16*)stbi__errpuc("unsupported", "Unsupported format conversion");
}
#undef STBI__CASE
}
STBI_FREE(data);
return good;
}
#endif
#ifndef STBI_NO_LINEAR
static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp)
{
int i, k, n;
float* output;
if (!data)
return NULL;
output = (float*)stbi__malloc_mad4(x, y, comp, sizeof(float), 0);
if (output == NULL)
{
STBI_FREE(data);
return stbi__errpf("outofmem", "Out of memory");
}
// compute number of non-alpha components
if (comp & 1)
n = comp;
else
n = comp - 1;
for (i = 0; i < x * y; ++i)
{
for (k = 0; k < n; ++k)
{
output[i * comp + k] = (float)(pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
}
}
if (n < comp)
{
for (i = 0; i < x * y; ++i)
{
output[i * comp + n] = data[i * comp + n] / 255.0f;
}
}
STBI_FREE(data);
return output;
}
#endif
#ifndef STBI_NO_HDR
#define stbi__float2int(x) ((int)(x))
static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp)
{
int i, k, n;
stbi_uc* output;
if (!data)
return NULL;
output = (stbi_uc*)stbi__malloc_mad3(x, y, comp, 0);
if (output == NULL)
{
STBI_FREE(data);
return stbi__errpuc("outofmem", "Out of memory");
}
// compute number of non-alpha components
if (comp & 1)
n = comp;
else
n = comp - 1;
for (i = 0; i < x * y; ++i)
{
for (k = 0; k < n; ++k)
{
float z = (float)pow(data[i * comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
if (z < 0)
z = 0;
if (z > 255)
z = 255;
output[i * comp + k] = (stbi_uc)stbi__float2int(z);
}
if (k < comp)
{
float z = data[i * comp + k] * 255 + 0.5f;
if (z < 0)
z = 0;
if (z > 255)
z = 255;
output[i * comp + k] = (stbi_uc)stbi__float2int(z);
}
}
STBI_FREE(data);
return output;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder
//
// simple implementation
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - some SIMD kernels for common paths on targets with SSE2/NEON
// - uses a lot of intermediate memory, could cache poorly
#ifndef STBI_NO_JPEG
// huffman decoding acceleration
#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct
{
stbi_uc fast[1 << FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
stbi__uint16 code[256];
stbi_uc values[256];
stbi_uc size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} stbi__huffman;
typedef struct
{
stbi__context* s;
stbi__huffman huff_dc[4];
stbi__huffman huff_ac[4];
stbi__uint16 dequant[4][64];
stbi__int16 fast_ac[4][1 << FAST_BITS];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct
{
int id;
int h, v;
int tq;
int hd, ha;
int dc_pred;
int x, y, w2, h2;
stbi_uc* data;
void *raw_data, *raw_coeff;
stbi_uc* linebuf;
short* coeff; // progressive only
int coeff_w, coeff_h; // number of 8x8 coefficient blocks
} img_comp[4];
stbi__uint32 code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int progressive;
int spec_start;
int spec_end;
int succ_high;
int succ_low;
int eob_run;
int jfif;
int app14_color_transform; // Adobe APP14 tag
int rgb;
int scan_n, order[4];
int restart_interval, todo;
// kernels
void (*idct_block_kernel)(stbi_uc* out, int out_stride, short data[64]);
void (*YCbCr_to_RGB_kernel)(stbi_uc* out, const stbi_uc* y, const stbi_uc* pcb, const stbi_uc* pcr, int count, int step);
stbi_uc* (*resample_row_hv_2_kernel)(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs);
} stbi__jpeg;
static int stbi__build_huffman(stbi__huffman* h, int* count)
{
int i, j, k = 0;
unsigned int code;
// build size list for each symbol (from JPEG spec)
for (i = 0; i < 16; ++i)
{
for (j = 0; j < count[i]; ++j)
{
h->size[k++] = (stbi_uc)(i + 1);
if (k >= 257)
return stbi__err("bad size list", "Corrupt JPEG");
}
}
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for (j = 1; j <= 16; ++j)
{
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j)
{
while (h->size[k] == j)
h->code[k++] = (stbi__uint16)(code++);
if (code - 1 >= (1u << j))
return stbi__err("bad code lengths", "Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16 - j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << FAST_BITS);
for (i = 0; i < k; ++i)
{
int s = h->size[i];
if (s <= FAST_BITS)
{
int c = h->code[i] << (FAST_BITS - s);
int m = 1 << (FAST_BITS - s);
for (j = 0; j < m; ++j)
{
h->fast[c + j] = (stbi_uc)i;
}
}
}
return 1;
}
// build a table that decodes both magnitude and value of small ACs in
// one go.
static void stbi__build_fast_ac(stbi__int16* fast_ac, stbi__huffman* h)
{
int i;
for (i = 0; i < (1 << FAST_BITS); ++i)
{
stbi_uc fast = h->fast[i];
fast_ac[i] = 0;
if (fast < 255)
{
int rs = h->values[fast];
int run = (rs >> 4) & 15;
int magbits = rs & 15;
int len = h->size[fast];
if (magbits && len + magbits <= FAST_BITS)
{
// magnitude code followed by receive_extend code
int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
int m = 1 << (magbits - 1);
if (k < m)
k += (~0U << magbits) + 1;
// if the result is small enough, we can fit it in fast_ac table
if (k >= -128 && k <= 127)
fast_ac[i] = (stbi__int16)((k * 256) + (run * 16) + (len + magbits));
}
}
}
}
static void stbi__grow_buffer_unsafe(stbi__jpeg* j)
{
do
{
unsigned int b = j->nomore ? 0 : stbi__get8(j->s);
if (b == 0xff)
{
int c = stbi__get8(j->s);
while (c == 0xff)
c = stbi__get8(j->s); // consume fill bytes
if (c != 0)
{
j->marker = (unsigned char)c;
j->nomore = 1;
return;
}
}
j->code_buffer |= b << (24 - j->code_bits);
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static const stbi__uint32 stbi__bmask[17] = { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535 };
// decode a jpeg huffman value from the bitstream
stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg* j, stbi__huffman* h)
{
unsigned int temp;
int c, k;
if (j->code_bits < 16)
stbi__grow_buffer_unsafe(j);
// look at the top FAST_BITS and determine what symbol ID it is,
// if the code is <= FAST_BITS
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
k = h->fast[c];
if (k < 255)
{
int s = h->size[k];
if (s > j->code_bits)
return -1;
j->code_buffer <<= s;
j->code_bits -= s;
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
temp = j->code_buffer >> 16;
for (k = FAST_BITS + 1;; ++k)
if (temp < h->maxcode[k])
break;
if (k == 17)
{
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits)
return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
if (c < 0 || c >= 256) // symbol id out of bounds!
return -1;
STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
j->code_buffer <<= k;
return h->values[c];
}
// bias[n] = (-1<<n) + 1
static const int stbi__jbias[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 };
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
stbi_inline static int stbi__extend_receive(stbi__jpeg* j, int n)
{
unsigned int k;
int sgn;
if (j->code_bits < n)
stbi__grow_buffer_unsafe(j);
if (j->code_bits < n)
return 0; // ran out of bits from stream, return 0s intead of continuing
sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)
k = stbi_lrot(j->code_buffer, n);
j->code_buffer = k & ~stbi__bmask[n];
k &= stbi__bmask[n];
j->code_bits -= n;
return k + (stbi__jbias[n] & (sgn - 1));
}
// get some unsigned bits
stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg* j, int n)
{
unsigned int k;
if (j->code_bits < n)
stbi__grow_buffer_unsafe(j);
if (j->code_bits < n)
return 0; // ran out of bits from stream, return 0s intead of continuing
k = stbi_lrot(j->code_buffer, n);
j->code_buffer = k & ~stbi__bmask[n];
k &= stbi__bmask[n];
j->code_bits -= n;
return k;
}
stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg* j)
{
unsigned int k;
if (j->code_bits < 1)
stbi__grow_buffer_unsafe(j);
if (j->code_bits < 1)
return 0; // ran out of bits from stream, return 0s intead of continuing
k = j->code_buffer;
j->code_buffer <<= 1;
--j->code_bits;
return k & 0x80000000;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static const stbi_uc stbi__jpeg_dezigzag[64 + 15] = {
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63
};
// decode one 64-entry block--
static int stbi__jpeg_decode_block(stbi__jpeg* j, short data[64], stbi__huffman* hdc, stbi__huffman* hac, stbi__int16* fac, int b, stbi__uint16* dequant)
{
int diff, dc, k;
int t;
if (j->code_bits < 16)
stbi__grow_buffer_unsafe(j);
t = stbi__jpeg_huff_decode(j, hdc);
if (t < 0 || t > 15)
return stbi__err("bad huffman code", "Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
memset(data, 0, 64 * sizeof(data[0]));
diff = t ? stbi__extend_receive(j, t) : 0;
if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff))
return stbi__err("bad delta", "Corrupt JPEG");
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
if (!stbi__mul2shorts_valid(dc, dequant[0]))
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
data[0] = (short)(dc * dequant[0]);
// decode AC components, see JPEG spec
k = 1;
do
{
unsigned int zig;
int c, r, s;
if (j->code_bits < 16)
stbi__grow_buffer_unsafe(j);
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
r = fac[c];
if (r)
{ // fast-AC path
k += (r >> 4) & 15; // run
s = r & 15; // combined length
if (s > j->code_bits)
return stbi__err("bad huffman code", "Combined length longer than code bits available");
j->code_buffer <<= s;
j->code_bits -= s;
// decode into unzigzag'd location
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)((r >> 8) * dequant[zig]);
}
else
{
int rs = stbi__jpeg_huff_decode(j, hac);
if (rs < 0)
return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0)
{
if (rs != 0xf0)
break; // end block
k += 16;
}
else
{
k += r;
// decode into unzigzag'd location
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]);
}
}
} while (k < 64);
return 1;
}
static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg* j, short data[64], stbi__huffman* hdc, int b)
{
int diff, dc;
int t;
if (j->spec_end != 0)
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
if (j->code_bits < 16)
stbi__grow_buffer_unsafe(j);
if (j->succ_high == 0)
{
// first scan for DC coefficient, must be first
memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now
t = stbi__jpeg_huff_decode(j, hdc);
if (t < 0 || t > 15)
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
diff = t ? stbi__extend_receive(j, t) : 0;
if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff))
return stbi__err("bad delta", "Corrupt JPEG");
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low))
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
data[0] = (short)(dc * (1 << j->succ_low));
}
else
{
// refinement scan for DC coefficient
if (stbi__jpeg_get_bit(j))
data[0] += (short)(1 << j->succ_low);
}
return 1;
}
// @OPTIMIZE: store non-zigzagged during the decode passes,
// and only de-zigzag when dequantizing
static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg* j, short data[64], stbi__huffman* hac, stbi__int16* fac)
{
int k;
if (j->spec_start == 0)
return stbi__err("can't merge dc and ac", "Corrupt JPEG");
if (j->succ_high == 0)
{
int shift = j->succ_low;
if (j->eob_run)
{
--j->eob_run;
return 1;
}
k = j->spec_start;
do
{
unsigned int zig;
int c, r, s;
if (j->code_bits < 16)
stbi__grow_buffer_unsafe(j);
c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1);
r = fac[c];
if (r)
{ // fast-AC path
k += (r >> 4) & 15; // run
s = r & 15; // combined length
if (s > j->code_bits)
return stbi__err("bad huffman code", "Combined length longer than code bits available");
j->code_buffer <<= s;
j->code_bits -= s;
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)((r >> 8) * (1 << shift));
}
else
{
int rs = stbi__jpeg_huff_decode(j, hac);
if (rs < 0)
return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0)
{
if (r < 15)
{
j->eob_run = (1 << r);
if (r)
j->eob_run += stbi__jpeg_get_bits(j, r);
--j->eob_run;
break;
}
k += 16;
}
else
{
k += r;
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short)(stbi__extend_receive(j, s) * (1 << shift));
}
}
} while (k <= j->spec_end);
}
else
{
// refinement scan for these AC coefficients
short bit = (short)(1 << j->succ_low);
if (j->eob_run)
{
--j->eob_run;
for (k = j->spec_start; k <= j->spec_end; ++k)
{
short* p = &data[stbi__jpeg_dezigzag[k]];
if (*p != 0)
if (stbi__jpeg_get_bit(j))
if ((*p & bit) == 0)
{
if (*p > 0)
*p += bit;
else
*p -= bit;
}
}
}
else
{
k = j->spec_start;
do
{
int r, s;
int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
if (rs < 0)
return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0)
{
if (r < 15)
{
j->eob_run = (1 << r) - 1;
if (r)
j->eob_run += stbi__jpeg_get_bits(j, r);
r = 64; // force end of block
}
else
{
// r=15 s=0 should write 16 0s, so we just do
// a run of 15 0s and then write s (which is 0),
// so we don't have to do anything special here
}
}
else
{
if (s != 1)
return stbi__err("bad huffman code", "Corrupt JPEG");
// sign bit
if (stbi__jpeg_get_bit(j))
s = bit;
else
s = -bit;
}
// advance by r
while (k <= j->spec_end)
{
short* p = &data[stbi__jpeg_dezigzag[k++]];
if (*p != 0)
{
if (stbi__jpeg_get_bit(j))
if ((*p & bit) == 0)
{
if (*p > 0)
*p += bit;
else
*p -= bit;
}
}
else
{
if (r == 0)
{
*p = (short)s;
break;
}
--r;
}
}
} while (k <= j->spec_end);
}
}
return 1;
}
// take a -128..127 value and stbi__clamp it and convert to 0..255
stbi_inline static stbi_uc stbi__clamp(int x)
{
// trick to use a single test to catch both cases
if ((unsigned int)x > 255)
{
if (x < 0)
return 0;
if (x > 255)
return 255;
}
return (stbi_uc)x;
}
#define stbi__f2f(x) ((int)(((x)*4096 + 0.5)))
#define stbi__fsh(x) ((x)*4096)
// derived from jidctint -- DCT_ISLOW
#define STBI__IDCT_1D(s0, s1, s2, s3, s4, s5, s6, s7) \
int t0, t1, t2, t3, p1, p2, p3, p4, p5, x0, x1, x2, x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2 + p3) * stbi__f2f(0.5411961f); \
t2 = p1 + p3 * stbi__f2f(-1.847759065f); \
t3 = p1 + p2 * stbi__f2f(0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = stbi__fsh(p2 + p3); \
t1 = stbi__fsh(p2 - p3); \
x0 = t0 + t3; \
x3 = t0 - t3; \
x1 = t1 + t2; \
x2 = t1 - t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0 + t2; \
p4 = t1 + t3; \
p1 = t0 + t3; \
p2 = t1 + t2; \
p5 = (p3 + p4) * stbi__f2f(1.175875602f); \
t0 = t0 * stbi__f2f(0.298631336f); \
t1 = t1 * stbi__f2f(2.053119869f); \
t2 = t2 * stbi__f2f(3.072711026f); \
t3 = t3 * stbi__f2f(1.501321110f); \
p1 = p5 + p1 * stbi__f2f(-0.899976223f); \
p2 = p5 + p2 * stbi__f2f(-2.562915447f); \
p3 = p3 * stbi__f2f(-1.961570560f); \
p4 = p4 * stbi__f2f(-0.390180644f); \
t3 += p1 + p4; \
t2 += p2 + p3; \
t1 += p2 + p4; \
t0 += p1 + p3;
static void stbi__idct_block(stbi_uc* out, int out_stride, short data[64])
{
int i, val[64], *v = val;
stbi_uc* o;
short* d = data;
// columns
for (i = 0; i < 8; ++i, ++d, ++v)
{
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 && d[48] == 0 && d[56] == 0)
{
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * 4;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
}
else
{
STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512;
x1 += 512;
x2 += 512;
x3 += 512;
v[0] = (x0 + t3) >> 10;
v[56] = (x0 - t3) >> 10;
v[8] = (x1 + t2) >> 10;
v[48] = (x1 - t2) >> 10;
v[16] = (x2 + t1) >> 10;
v[40] = (x2 - t1) >> 10;
v[24] = (x3 + t0) >> 10;
v[32] = (x3 - t0) >> 10;
}
}
for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride)
{
// no fast case since the first 1D IDCT spread components out
STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
// so we want to round that, which means adding 0.5 * 1<<17,
// aka 65536. Also, we'll end up with -128 to 127 that we want
// to encode as 0..255 by adding 128, so we'll add that before the shift
x0 += 65536 + (128 << 17);
x1 += 65536 + (128 << 17);
x2 += 65536 + (128 << 17);
x3 += 65536 + (128 << 17);
// tried computing the shifts into temps, or'ing the temps to see
// if any were out of range, but that was slower
o[0] = stbi__clamp((x0 + t3) >> 17);
o[7] = stbi__clamp((x0 - t3) >> 17);
o[1] = stbi__clamp((x1 + t2) >> 17);
o[6] = stbi__clamp((x1 - t2) >> 17);
o[2] = stbi__clamp((x2 + t1) >> 17);
o[5] = stbi__clamp((x2 - t1) >> 17);
o[3] = stbi__clamp((x3 + t0) >> 17);
o[4] = stbi__clamp((x3 - t0) >> 17);
}
}
#ifdef STBI_SSE2
// sse2 integer IDCT. not the fastest possible implementation but it
// produces bit-identical results to the generic C version so it's
// fully "transparent".
static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64])
{
// This is constructed to match our regular (generic) integer IDCT exactly.
__m128i row0, row1, row2, row3, row4, row5, row6, row7;
__m128i tmp;
// dot product constant: even elems=x, odd elems=y
#define dct_const(x, y) _mm_setr_epi16((x), (y), (x), (y), (x), (y), (x), (y))
// out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
// out(1) = c1[even]*x + c1[odd]*y
#define dct_rot(out0, out1, x, y, c0, c1) \
__m128i c0##lo = _mm_unpacklo_epi16((x), (y)); \
__m128i c0##hi = _mm_unpackhi_epi16((x), (y)); \
__m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
__m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
__m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
__m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
// out = in << 12 (in 16-bit, out 32-bit)
#define dct_widen(out, in) \
__m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
__m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
// wide add
#define dct_wadd(out, a, b) \
__m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
__m128i out##_h = _mm_add_epi32(a##_h, b##_h)
// wide sub
#define dct_wsub(out, a, b) \
__m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
__m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
// butterfly a/b, add bias, then shift by "s" and pack
#define dct_bfly32o(out0, out1, a, b, bias, s) \
{ \
__m128i abiased_l = _mm_add_epi32(a##_l, bias); \
__m128i abiased_h = _mm_add_epi32(a##_h, bias); \
dct_wadd(sum, abiased, b); \
dct_wsub(dif, abiased, b); \
out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
}
// 8-bit interleave step (for transposes)
#define dct_interleave8(a, b) \
tmp = a; \
a = _mm_unpacklo_epi8(a, b); \
b = _mm_unpackhi_epi8(tmp, b)
// 16-bit interleave step (for transposes)
#define dct_interleave16(a, b) \
tmp = a; \
a = _mm_unpacklo_epi16(a, b); \
b = _mm_unpackhi_epi16(tmp, b)
#define dct_pass(bias, shift) \
{ \
/* even part */ \
dct_rot(t2e, t3e, row2, row6, rot0_0, rot0_1); \
__m128i sum04 = _mm_add_epi16(row0, row4); \
__m128i dif04 = _mm_sub_epi16(row0, row4); \
dct_widen(t0e, sum04); \
dct_widen(t1e, dif04); \
dct_wadd(x0, t0e, t3e); \
dct_wsub(x3, t0e, t3e); \
dct_wadd(x1, t1e, t2e); \
dct_wsub(x2, t1e, t2e); \
/* odd part */ \
dct_rot(y0o, y2o, row7, row3, rot2_0, rot2_1); \
dct_rot(y1o, y3o, row5, row1, rot3_0, rot3_1); \
__m128i sum17 = _mm_add_epi16(row1, row7); \
__m128i sum35 = _mm_add_epi16(row3, row5); \
dct_rot(y4o, y5o, sum17, sum35, rot1_0, rot1_1); \
dct_wadd(x4, y0o, y4o); \
dct_wadd(x5, y1o, y5o); \
dct_wadd(x6, y2o, y5o); \
dct_wadd(x7, y3o, y4o); \
dct_bfly32o(row0, row7, x0, x7, bias, shift); \
dct_bfly32o(row1, row6, x1, x6, bias, shift); \
dct_bfly32o(row2, row5, x2, x5, bias, shift); \
dct_bfly32o(row3, row4, x3, x4, bias, shift); \
}
__m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
__m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f));
__m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
__m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
__m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), stbi__f2f(-1.961570560f));
__m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f));
__m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), stbi__f2f(-0.390180644f));
__m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f));
// rounding biases in column/row passes, see stbi__idct_block for explanation.
__m128i bias_0 = _mm_set1_epi32(512);
__m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17));
// load
row0 = _mm_load_si128((const __m128i*)(data + 0 * 8));
row1 = _mm_load_si128((const __m128i*)(data + 1 * 8));
row2 = _mm_load_si128((const __m128i*)(data + 2 * 8));
row3 = _mm_load_si128((const __m128i*)(data + 3 * 8));
row4 = _mm_load_si128((const __m128i*)(data + 4 * 8));
row5 = _mm_load_si128((const __m128i*)(data + 5 * 8));
row6 = _mm_load_si128((const __m128i*)(data + 6 * 8));
row7 = _mm_load_si128((const __m128i*)(data + 7 * 8));
// column pass
dct_pass(bias_0, 10);
{
// 16bit 8x8 transpose pass 1
dct_interleave16(row0, row4);
dct_interleave16(row1, row5);
dct_interleave16(row2, row6);
dct_interleave16(row3, row7);
// transpose pass 2
dct_interleave16(row0, row2);
dct_interleave16(row1, row3);
dct_interleave16(row4, row6);
dct_interleave16(row5, row7);
// transpose pass 3
dct_interleave16(row0, row1);
dct_interleave16(row2, row3);
dct_interleave16(row4, row5);
dct_interleave16(row6, row7);
}
// row pass
dct_pass(bias_1, 17);
{
// pack
__m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
__m128i p1 = _mm_packus_epi16(row2, row3);
__m128i p2 = _mm_packus_epi16(row4, row5);
__m128i p3 = _mm_packus_epi16(row6, row7);
// 8bit 8x8 transpose pass 1
dct_interleave8(p0, p2); // a0e0a1e1...
dct_interleave8(p1, p3); // c0g0c1g1...
// transpose pass 2
dct_interleave8(p0, p1); // a0c0e0g0...
dct_interleave8(p2, p3); // b0d0f0h0...
// transpose pass 3
dct_interleave8(p0, p2); // a0b0c0d0...
dct_interleave8(p1, p3); // a4b4c4d4...
// store
_mm_storel_epi64((__m128i*)out, p0);
out += out_stride;
_mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p0, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i*)out, p2);
out += out_stride;
_mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p2, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i*)out, p1);
out += out_stride;
_mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p1, 0x4e));
out += out_stride;
_mm_storel_epi64((__m128i*)out, p3);
out += out_stride;
_mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p3, 0x4e));
}
#undef dct_const
#undef dct_rot
#undef dct_widen
#undef dct_wadd
#undef dct_wsub
#undef dct_bfly32o
#undef dct_interleave8
#undef dct_interleave16
#undef dct_pass
}
#endif // STBI_SSE2
#ifdef STBI_NEON
// NEON integer IDCT. should produce bit-identical
// results to the generic C version.
static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64])
{
int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f));
int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f));
int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f));
int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f));
int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f));
int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f));
#define dct_long_mul(out, inq, coeff) \
int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
#define dct_long_mac(out, acc, inq, coeff) \
int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
#define dct_widen(out, inq) \
int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
// wide add
#define dct_wadd(out, a, b) \
int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
// wide sub
#define dct_wsub(out, a, b) \
int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
// butterfly a/b, then shift using "shiftop" by "s" and pack
#define dct_bfly32o(out0, out1, a, b, shiftop, s) \
{ \
dct_wadd(sum, a, b); \
dct_wsub(dif, a, b); \
out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
}
#define dct_pass(shiftop, shift) \
{ \
/* even part */ \
int16x8_t sum26 = vaddq_s16(row2, row6); \
dct_long_mul(p1e, sum26, rot0_0); \
dct_long_mac(t2e, p1e, row6, rot0_1); \
dct_long_mac(t3e, p1e, row2, rot0_2); \
int16x8_t sum04 = vaddq_s16(row0, row4); \
int16x8_t dif04 = vsubq_s16(row0, row4); \
dct_widen(t0e, sum04); \
dct_widen(t1e, dif04); \
dct_wadd(x0, t0e, t3e); \
dct_wsub(x3, t0e, t3e); \
dct_wadd(x1, t1e, t2e); \
dct_wsub(x2, t1e, t2e); \
/* odd part */ \
int16x8_t sum15 = vaddq_s16(row1, row5); \
int16x8_t sum17 = vaddq_s16(row1, row7); \
int16x8_t sum35 = vaddq_s16(row3, row5); \
int16x8_t sum37 = vaddq_s16(row3, row7); \
int16x8_t sumodd = vaddq_s16(sum17, sum35); \
dct_long_mul(p5o, sumodd, rot1_0); \
dct_long_mac(p1o, p5o, sum17, rot1_1); \
dct_long_mac(p2o, p5o, sum35, rot1_2); \
dct_long_mul(p3o, sum37, rot2_0); \
dct_long_mul(p4o, sum15, rot2_1); \
dct_wadd(sump13o, p1o, p3o); \
dct_wadd(sump24o, p2o, p4o); \
dct_wadd(sump23o, p2o, p3o); \
dct_wadd(sump14o, p1o, p4o); \
dct_long_mac(x4, sump13o, row7, rot3_0); \
dct_long_mac(x5, sump24o, row5, rot3_1); \
dct_long_mac(x6, sump23o, row3, rot3_2); \
dct_long_mac(x7, sump14o, row1, rot3_3); \
dct_bfly32o(row0, row7, x0, x7, shiftop, shift); \
dct_bfly32o(row1, row6, x1, x6, shiftop, shift); \
dct_bfly32o(row2, row5, x2, x5, shiftop, shift); \
dct_bfly32o(row3, row4, x3, x4, shiftop, shift); \
}
// load
row0 = vld1q_s16(data + 0 * 8);
row1 = vld1q_s16(data + 1 * 8);
row2 = vld1q_s16(data + 2 * 8);
row3 = vld1q_s16(data + 3 * 8);
row4 = vld1q_s16(data + 4 * 8);
row5 = vld1q_s16(data + 5 * 8);
row6 = vld1q_s16(data + 6 * 8);
row7 = vld1q_s16(data + 7 * 8);
// add DC bias
row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
// column pass
dct_pass(vrshrn_n_s32, 10);
// 16bit 8x8 transpose
{
// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
// whether compilers actually get this is another story, sadly.
#define dct_trn16(x, y) \
{ \
int16x8x2_t t = vtrnq_s16(x, y); \
x = t.val[0]; \
y = t.val[1]; \
}
#define dct_trn32(x, y) \
{ \
int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \
x = vreinterpretq_s16_s32(t.val[0]); \
y = vreinterpretq_s16_s32(t.val[1]); \
}
#define dct_trn64(x, y) \
{ \
int16x8_t x0 = x; \
int16x8_t y0 = y; \
x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); \
y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); \
}
// pass 1
dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
dct_trn16(row2, row3);
dct_trn16(row4, row5);
dct_trn16(row6, row7);
// pass 2
dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
dct_trn32(row1, row3);
dct_trn32(row4, row6);
dct_trn32(row5, row7);
// pass 3
dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
dct_trn64(row1, row5);
dct_trn64(row2, row6);
dct_trn64(row3, row7);
#undef dct_trn16
#undef dct_trn32
#undef dct_trn64
}
// row pass
// vrshrn_n_s32 only supports shifts up to 16, we need
// 17. so do a non-rounding shift of 16 first then follow
// up with a rounding shift by 1.
dct_pass(vshrn_n_s32, 16);
{
// pack and round
uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
// again, these can translate into one instruction, but often don't.
#define dct_trn8_8(x, y) \
{ \
uint8x8x2_t t = vtrn_u8(x, y); \
x = t.val[0]; \
y = t.val[1]; \
}
#define dct_trn8_16(x, y) \
{ \
uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \
x = vreinterpret_u8_u16(t.val[0]); \
y = vreinterpret_u8_u16(t.val[1]); \
}
#define dct_trn8_32(x, y) \
{ \
uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \
x = vreinterpret_u8_u32(t.val[0]); \
y = vreinterpret_u8_u32(t.val[1]); \
}
// sadly can't use interleaved stores here since we only write
// 8 bytes to each scan line!
// 8x8 8-bit transpose pass 1
dct_trn8_8(p0, p1);
dct_trn8_8(p2, p3);
dct_trn8_8(p4, p5);
dct_trn8_8(p6, p7);
// pass 2
dct_trn8_16(p0, p2);
dct_trn8_16(p1, p3);
dct_trn8_16(p4, p6);
dct_trn8_16(p5, p7);
// pass 3
dct_trn8_32(p0, p4);
dct_trn8_32(p1, p5);
dct_trn8_32(p2, p6);
dct_trn8_32(p3, p7);
// store
vst1_u8(out, p0);
out += out_stride;
vst1_u8(out, p1);
out += out_stride;
vst1_u8(out, p2);
out += out_stride;
vst1_u8(out, p3);
out += out_stride;
vst1_u8(out, p4);
out += out_stride;
vst1_u8(out, p5);
out += out_stride;
vst1_u8(out, p6);
out += out_stride;
vst1_u8(out, p7);
#undef dct_trn8_8
#undef dct_trn8_16
#undef dct_trn8_32
}
#undef dct_long_mul
#undef dct_long_mac
#undef dct_widen
#undef dct_wadd
#undef dct_wsub
#undef dct_bfly32o
#undef dct_pass
}
#endif // STBI_NEON
#define STBI__MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static stbi_uc stbi__get_marker(stbi__jpeg* j)
{
stbi_uc x;
if (j->marker != STBI__MARKER_none)
{
x = j->marker;
j->marker = STBI__MARKER_none;
return x;
}
x = stbi__get8(j->s);
if (x != 0xff)
return STBI__MARKER_none;
while (x == 0xff)
x = stbi__get8(j->s); // consume repeated 0xff fill bytes
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, stbi__jpeg_reset the entropy decoder and
// the dc prediction
static void stbi__jpeg_reset(stbi__jpeg* j)
{
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0;
j->marker = STBI__MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
j->eob_run = 0;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int stbi__parse_entropy_coded_data(stbi__jpeg* z)
{
stbi__jpeg_reset(z);
if (!z->progressive)
{
if (z->scan_n == 1)
{
int i, j;
STBI_SIMD_ALIGN(short, data[64]);
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j)
{
for (i = 0; i < w; ++i)
{
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq]))
return 0;
z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, z->img_comp[n].w2, data);
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0)
{
if (z->code_bits < 24)
stbi__grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!STBI__RESTART(z->marker))
return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
else
{ // interleaved
int i, j, k, x, y;
STBI_SIMD_ALIGN(short, data[64]);
for (j = 0; j < z->img_mcu_y; ++j)
{
for (i = 0; i < z->img_mcu_x; ++i)
{
// scan an interleaved mcu... process scan_n components in order
for (k = 0; k < z->scan_n; ++k)
{
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y = 0; y < z->img_comp[n].v; ++y)
{
for (x = 0; x < z->img_comp[n].h; ++x)
{
int x2 = (i * z->img_comp[n].h + x) * 8;
int y2 = (j * z->img_comp[n].v + y) * 8;
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq]))
return 0;
z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * y2 + x2, z->img_comp[n].w2, data);
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0)
{
if (z->code_bits < 24)
stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker))
return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
}
else
{
if (z->scan_n == 1)
{
int i, j;
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j)
{
for (i = 0; i < w; ++i)
{
short* data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
if (z->spec_start == 0)
{
if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
}
else
{
int ha = z->img_comp[n].ha;
if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
return 0;
}
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0)
{
if (z->code_bits < 24)
stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker))
return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
else
{ // interleaved
int i, j, k, x, y;
for (j = 0; j < z->img_mcu_y; ++j)
{
for (i = 0; i < z->img_mcu_x; ++i)
{
// scan an interleaved mcu... process scan_n components in order
for (k = 0; k < z->scan_n; ++k)
{
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y = 0; y < z->img_comp[n].v; ++y)
{
for (x = 0; x < z->img_comp[n].h; ++x)
{
int x2 = (i * z->img_comp[n].h + x);
int y2 = (j * z->img_comp[n].v + y);
short* data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0)
{
if (z->code_bits < 24)
stbi__grow_buffer_unsafe(z);
if (!STBI__RESTART(z->marker))
return 1;
stbi__jpeg_reset(z);
}
}
}
return 1;
}
}
}
static void stbi__jpeg_dequantize(short* data, stbi__uint16* dequant)
{
int i;
for (i = 0; i < 64; ++i)
data[i] *= dequant[i];
}
static void stbi__jpeg_finish(stbi__jpeg* z)
{
if (z->progressive)
{
// dequantize and idct the data
int i, j, n;
for (n = 0; n < z->s->img_n; ++n)
{
int w = (z->img_comp[n].x + 7) >> 3;
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j)
{
for (i = 0; i < w; ++i)
{
short* data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, z->img_comp[n].w2, data);
}
}
}
}
}
static int stbi__process_marker(stbi__jpeg* z, int m)
{
int L;
switch (m)
{
case STBI__MARKER_none: // no marker found
return stbi__err("expected marker", "Corrupt JPEG");
case 0xDD: // DRI - specify restart interval
if (stbi__get16be(z->s) != 4)
return stbi__err("bad DRI len", "Corrupt JPEG");
z->restart_interval = stbi__get16be(z->s);
return 1;
case 0xDB: // DQT - define quantization table
L = stbi__get16be(z->s) - 2;
while (L > 0)
{
int q = stbi__get8(z->s);
int p = q >> 4, sixteen = (p != 0);
int t = q & 15, i;
if (p != 0 && p != 1)
return stbi__err("bad DQT type", "Corrupt JPEG");
if (t > 3)
return stbi__err("bad DQT table", "Corrupt JPEG");
for (i = 0; i < 64; ++i)
z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
L -= (sixteen ? 129 : 65);
}
return L == 0;
case 0xC4: // DHT - define huffman table
L = stbi__get16be(z->s) - 2;
while (L > 0)
{
stbi_uc* v;
int sizes[16], i, n = 0;
int q = stbi__get8(z->s);
int tc = q >> 4;
int th = q & 15;
if (tc > 1 || th > 3)
return stbi__err("bad DHT header", "Corrupt JPEG");
for (i = 0; i < 16; ++i)
{
sizes[i] = stbi__get8(z->s);
n += sizes[i];
}
if (n > 256)
return stbi__err("bad DHT header", "Corrupt JPEG"); // Loop over i < n would write past end of values!
L -= 17;
if (tc == 0)
{
if (!stbi__build_huffman(z->huff_dc + th, sizes))
return 0;
v = z->huff_dc[th].values;
}
else
{
if (!stbi__build_huffman(z->huff_ac + th, sizes))
return 0;
v = z->huff_ac[th].values;
}
for (i = 0; i < n; ++i)
v[i] = stbi__get8(z->s);
if (tc != 0)
stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
L -= n;
}
return L == 0;
}
// check for comment block or APP blocks
if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE)
{
L = stbi__get16be(z->s);
if (L < 2)
{
if (m == 0xFE)
return stbi__err("bad COM len", "Corrupt JPEG");
else
return stbi__err("bad APP len", "Corrupt JPEG");
}
L -= 2;
if (m == 0xE0 && L >= 5)
{ // JFIF APP0 segment
static const unsigned char tag[5] = { 'J', 'F', 'I', 'F', '\0' };
int ok = 1;
int i;
for (i = 0; i < 5; ++i)
if (stbi__get8(z->s) != tag[i])
ok = 0;
L -= 5;
if (ok)
z->jfif = 1;
}
else if (m == 0xEE && L >= 12)
{ // Adobe APP14 segment
static const unsigned char tag[6] = { 'A', 'd', 'o', 'b', 'e', '\0' };
int ok = 1;
int i;
for (i = 0; i < 6; ++i)
if (stbi__get8(z->s) != tag[i])
ok = 0;
L -= 6;
if (ok)
{
stbi__get8(z->s); // version
stbi__get16be(z->s); // flags0
stbi__get16be(z->s); // flags1
z->app14_color_transform = stbi__get8(z->s); // color transform
L -= 6;
}
}
stbi__skip(z->s, L);
return 1;
}
return stbi__err("unknown marker", "Corrupt JPEG");
}
// after we see SOS
static int stbi__process_scan_header(stbi__jpeg* z)
{
int i;
int Ls = stbi__get16be(z->s);
z->scan_n = stbi__get8(z->s);
if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n)
return stbi__err("bad SOS component count", "Corrupt JPEG");
if (Ls != 6 + 2 * z->scan_n)
return stbi__err("bad SOS len", "Corrupt JPEG");
for (i = 0; i < z->scan_n; ++i)
{
int id = stbi__get8(z->s), which;
int q = stbi__get8(z->s);
for (which = 0; which < z->s->img_n; ++which)
if (z->img_comp[which].id == id)
break;
if (which == z->s->img_n)
return 0; // no match
z->img_comp[which].hd = q >> 4;
if (z->img_comp[which].hd > 3)
return stbi__err("bad DC huff", "Corrupt JPEG");
z->img_comp[which].ha = q & 15;
if (z->img_comp[which].ha > 3)
return stbi__err("bad AC huff", "Corrupt JPEG");
z->order[i] = which;
}
{
int aa;
z->spec_start = stbi__get8(z->s);
z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
aa = stbi__get8(z->s);
z->succ_high = (aa >> 4);
z->succ_low = (aa & 15);
if (z->progressive)
{
if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
return stbi__err("bad SOS", "Corrupt JPEG");
}
else
{
if (z->spec_start != 0)
return stbi__err("bad SOS", "Corrupt JPEG");
if (z->succ_high != 0 || z->succ_low != 0)
return stbi__err("bad SOS", "Corrupt JPEG");
z->spec_end = 63;
}
}
return 1;
}
static int stbi__free_jpeg_components(stbi__jpeg* z, int ncomp, int why)
{
int i;
for (i = 0; i < ncomp; ++i)
{
if (z->img_comp[i].raw_data)
{
STBI_FREE(z->img_comp[i].raw_data);
z->img_comp[i].raw_data = NULL;
z->img_comp[i].data = NULL;
}
if (z->img_comp[i].raw_coeff)
{
STBI_FREE(z->img_comp[i].raw_coeff);
z->img_comp[i].raw_coeff = 0;
z->img_comp[i].coeff = 0;
}
if (z->img_comp[i].linebuf)
{
STBI_FREE(z->img_comp[i].linebuf);
z->img_comp[i].linebuf = NULL;
}
}
return why;
}
static int stbi__process_frame_header(stbi__jpeg* z, int scan)
{
stbi__context* s = z->s;
int Lf, p, i, q, h_max = 1, v_max = 1, c;
Lf = stbi__get16be(s);
if (Lf < 11)
return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG
p = stbi__get8(s);
if (p != 8)
return stbi__err("only 8-bit", "JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = stbi__get16be(s);
if (s->img_y == 0)
return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
s->img_x = stbi__get16be(s);
if (s->img_x == 0)
return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires
if (s->img_y > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
c = stbi__get8(s);
if (c != 3 && c != 1 && c != 4)
return stbi__err("bad component count", "Corrupt JPEG");
s->img_n = c;
for (i = 0; i < c; ++i)
{
z->img_comp[i].data = NULL;
z->img_comp[i].linebuf = NULL;
}
if (Lf != 8 + 3 * s->img_n)
return stbi__err("bad SOF len", "Corrupt JPEG");
z->rgb = 0;
for (i = 0; i < s->img_n; ++i)
{
static const unsigned char rgb[3] = { 'R', 'G', 'B' };
z->img_comp[i].id = stbi__get8(s);
if (s->img_n == 3 && z->img_comp[i].id == rgb[i])
++z->rgb;
q = stbi__get8(s);
z->img_comp[i].h = (q >> 4);
if (!z->img_comp[i].h || z->img_comp[i].h > 4)
return stbi__err("bad H", "Corrupt JPEG");
z->img_comp[i].v = q & 15;
if (!z->img_comp[i].v || z->img_comp[i].v > 4)
return stbi__err("bad V", "Corrupt JPEG");
z->img_comp[i].tq = stbi__get8(s);
if (z->img_comp[i].tq > 3)
return stbi__err("bad TQ", "Corrupt JPEG");
}
if (scan != STBI__SCAN_load)
return 1;
if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0))
return stbi__err("too large", "Image too large to decode");
for (i = 0; i < s->img_n; ++i)
{
if (z->img_comp[i].h > h_max)
h_max = z->img_comp[i].h;
if (z->img_comp[i].v > v_max)
v_max = z->img_comp[i].v;
}
// check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
// and I've never seen a non-corrupted JPEG file actually use them
for (i = 0; i < s->img_n; ++i)
{
if (h_max % z->img_comp[i].h != 0)
return stbi__err("bad H", "Corrupt JPEG");
if (v_max % z->img_comp[i].v != 0)
return stbi__err("bad V", "Corrupt JPEG");
}
// compute interleaved mcu info
z->img_h_max = h_max;
z->img_v_max = v_max;
z->img_mcu_w = h_max * 8;
z->img_mcu_h = v_max * 8;
// these sizes can't be more than 17 bits
z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w;
z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h;
for (i = 0; i < s->img_n; ++i)
{
// number of effective pixels (e.g. for non-interleaved MCU)
z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max;
z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max;
// to simplify generation, we'll allocate enough memory to decode
// the bogus oversized data from using interleaved MCUs and their
// big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
// discard the extra data until colorspace conversion
//
// img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)
// so these muls can't overflow with 32-bit ints (which we require)
z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
z->img_comp[i].coeff = 0;
z->img_comp[i].raw_coeff = 0;
z->img_comp[i].linebuf = NULL;
z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
if (z->img_comp[i].raw_data == NULL)
return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory"));
// align blocks for idct using mmx/sse
z->img_comp[i].data = (stbi_uc*)(((size_t)z->img_comp[i].raw_data + 15) & ~15);
if (z->progressive)
{
// w2, h2 are multiples of 8 (see above)
z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
if (z->img_comp[i].raw_coeff == NULL)
return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory"));
z->img_comp[i].coeff = (short*)(((size_t)z->img_comp[i].raw_coeff + 15) & ~15);
}
}
return 1;
}
// use comparisons since in some cases we handle more than one case (e.g. SOF)
#define stbi__DNL(x) ((x) == 0xdc)
#define stbi__SOI(x) ((x) == 0xd8)
#define stbi__EOI(x) ((x) == 0xd9)
#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
#define stbi__SOS(x) ((x) == 0xda)
#define stbi__SOF_progressive(x) ((x) == 0xc2)
static int stbi__decode_jpeg_header(stbi__jpeg* z, int scan)
{
int m;
z->jfif = 0;
z->app14_color_transform = -1; // valid values are 0,1,2
z->marker = STBI__MARKER_none; // initialize cached marker to empty
m = stbi__get_marker(z);
if (!stbi__SOI(m))
return stbi__err("no SOI", "Corrupt JPEG");
if (scan == STBI__SCAN_type)
return 1;
m = stbi__get_marker(z);
while (!stbi__SOF(m))
{
if (!stbi__process_marker(z, m))
return 0;
m = stbi__get_marker(z);
while (m == STBI__MARKER_none)
{
// some files have extra padding after their blocks, so ok, we'll scan
if (stbi__at_eof(z->s))
return stbi__err("no SOF", "Corrupt JPEG");
m = stbi__get_marker(z);
}
}
z->progressive = stbi__SOF_progressive(m);
if (!stbi__process_frame_header(z, scan))
return 0;
return 1;
}
static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg* j)
{
// some JPEGs have junk at end, skip over it but if we find what looks
// like a valid marker, resume there
while (!stbi__at_eof(j->s))
{
stbi_uc x = stbi__get8(j->s);
while (x == 0xff)
{ // might be a marker
if (stbi__at_eof(j->s))
return STBI__MARKER_none;
x = stbi__get8(j->s);
if (x != 0x00 && x != 0xff)
{
// not a stuffed zero or lead-in to another marker, looks
// like an actual marker, return it
return x;
}
// stuffed zero has x=0 now which ends the loop, meaning we go
// back to regular scan loop.
// repeated 0xff keeps trying to read the next byte of the marker.
}
}
return STBI__MARKER_none;
}
// decode image to YCbCr format
static int stbi__decode_jpeg_image(stbi__jpeg* j)
{
int m;
for (m = 0; m < 4; m++)
{
j->img_comp[m].raw_data = NULL;
j->img_comp[m].raw_coeff = NULL;
}
j->restart_interval = 0;
if (!stbi__decode_jpeg_header(j, STBI__SCAN_load))
return 0;
m = stbi__get_marker(j);
while (!stbi__EOI(m))
{
if (stbi__SOS(m))
{
if (!stbi__process_scan_header(j))
return 0;
if (!stbi__parse_entropy_coded_data(j))
return 0;
if (j->marker == STBI__MARKER_none)
{
j->marker = stbi__skip_jpeg_junk_at_end(j);
// if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
}
m = stbi__get_marker(j);
if (STBI__RESTART(m))
m = stbi__get_marker(j);
}
else if (stbi__DNL(m))
{
int Ld = stbi__get16be(j->s);
stbi__uint32 NL = stbi__get16be(j->s);
if (Ld != 4)
return stbi__err("bad DNL len", "Corrupt JPEG");
if (NL != j->s->img_y)
return stbi__err("bad DNL height", "Corrupt JPEG");
m = stbi__get_marker(j);
}
else
{
if (!stbi__process_marker(j, m))
return 1;
m = stbi__get_marker(j);
}
}
if (j->progressive)
stbi__jpeg_finish(j);
return 1;
}
// static jfif-centered resampling (across block boundaries)
typedef stbi_uc* (*resample_row_func)(stbi_uc* out, stbi_uc* in0, stbi_uc* in1,
int w, int hs);
#define stbi__div4(x) ((stbi_uc)((x) >> 2))
static stbi_uc* resample_row_1(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
STBI_NOTUSED(out);
STBI_NOTUSED(in_far);
STBI_NOTUSED(w);
STBI_NOTUSED(hs);
return in_near;
}
static stbi_uc* stbi__resample_row_v_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
// need to generate two samples vertically for every one in input
int i;
STBI_NOTUSED(hs);
for (i = 0; i < w; ++i)
out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2);
return out;
}
static stbi_uc* stbi__resample_row_h_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
// need to generate two samples horizontally for every one in input
int i;
stbi_uc* input = in_near;
if (w == 1)
{
// if only one sample, can't do any interpolation
out[0] = out[1] = input[0];
return out;
}
out[0] = input[0];
out[1] = stbi__div4(input[0] * 3 + input[1] + 2);
for (i = 1; i < w - 1; ++i)
{
int n = 3 * input[i] + 2;
out[i * 2 + 0] = stbi__div4(n + input[i - 1]);
out[i * 2 + 1] = stbi__div4(n + input[i + 1]);
}
out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2);
out[i * 2 + 1] = input[w - 1];
STBI_NOTUSED(in_far);
STBI_NOTUSED(hs);
return out;
}
#define stbi__div16(x) ((stbi_uc)((x) >> 4))
static stbi_uc* stbi__resample_row_hv_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
// need to generate 2x2 samples for every one in input
int i, t0, t1;
if (w == 1)
{
out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3 * in_near[0] + in_far[0];
out[0] = stbi__div4(t1 + 2);
for (i = 1; i < w; ++i)
{
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8);
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
}
out[w * 2 - 1] = stbi__div4(t1 + 2);
STBI_NOTUSED(hs);
return out;
}
#if defined(STBI_SSE2) || defined(STBI_NEON)
static stbi_uc* stbi__resample_row_hv_2_simd(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
// need to generate 2x2 samples for every one in input
int i = 0, t0, t1;
if (w == 1)
{
out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2);
return out;
}
t1 = 3 * in_near[0] + in_far[0];
// process groups of 8 pixels for as long as we can.
// note we can't handle the last pixel in a row in this loop
// because we need to handle the filter boundary conditions.
for (; i < ((w - 1) & ~7); i += 8)
{
#if defined(STBI_SSE2)
// load and perform the vertical filtering pass
// this uses 3*x + y = 4*x + (y - x)
__m128i zero = _mm_setzero_si128();
__m128i farb = _mm_loadl_epi64((__m128i*)(in_far + i));
__m128i nearb = _mm_loadl_epi64((__m128i*)(in_near + i));
__m128i farw = _mm_unpacklo_epi8(farb, zero);
__m128i nearw = _mm_unpacklo_epi8(nearb, zero);
__m128i diff = _mm_sub_epi16(farw, nearw);
__m128i nears = _mm_slli_epi16(nearw, 2);
__m128i curr = _mm_add_epi16(nears, diff); // current row
// horizontal filter works the same based on shifted vers of current
// row. "prev" is current row shifted right by 1 pixel; we need to
// insert the previous pixel value (from t1).
// "next" is current row shifted left by 1 pixel, with first pixel
// of next block of 8 pixels added in.
__m128i prv0 = _mm_slli_si128(curr, 2);
__m128i nxt0 = _mm_srli_si128(curr, 2);
__m128i prev = _mm_insert_epi16(prv0, t1, 0);
__m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7);
// horizontal filter, polyphase implementation since it's convenient:
// even pixels = 3*cur + prev = cur*4 + (prev - cur)
// odd pixels = 3*cur + next = cur*4 + (next - cur)
// note the shared term.
__m128i bias = _mm_set1_epi16(8);
__m128i curs = _mm_slli_epi16(curr, 2);
__m128i prvd = _mm_sub_epi16(prev, curr);
__m128i nxtd = _mm_sub_epi16(next, curr);
__m128i curb = _mm_add_epi16(curs, bias);
__m128i even = _mm_add_epi16(prvd, curb);
__m128i odd = _mm_add_epi16(nxtd, curb);
// interleave even and odd pixels, then undo scaling.
__m128i int0 = _mm_unpacklo_epi16(even, odd);
__m128i int1 = _mm_unpackhi_epi16(even, odd);
__m128i de0 = _mm_srli_epi16(int0, 4);
__m128i de1 = _mm_srli_epi16(int1, 4);
// pack and write output
__m128i outv = _mm_packus_epi16(de0, de1);
_mm_storeu_si128((__m128i*)(out + i * 2), outv);
#elif defined(STBI_NEON)
// load and perform the vertical filtering pass
// this uses 3*x + y = 4*x + (y - x)
uint8x8_t farb = vld1_u8(in_far + i);
uint8x8_t nearb = vld1_u8(in_near + i);
int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
int16x8_t curr = vaddq_s16(nears, diff); // current row
// horizontal filter works the same based on shifted vers of current
// row. "prev" is current row shifted right by 1 pixel; we need to
// insert the previous pixel value (from t1).
// "next" is current row shifted left by 1 pixel, with first pixel
// of next block of 8 pixels added in.
int16x8_t prv0 = vextq_s16(curr, curr, 7);
int16x8_t nxt0 = vextq_s16(curr, curr, 1);
int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7);
// horizontal filter, polyphase implementation since it's convenient:
// even pixels = 3*cur + prev = cur*4 + (prev - cur)
// odd pixels = 3*cur + next = cur*4 + (next - cur)
// note the shared term.
int16x8_t curs = vshlq_n_s16(curr, 2);
int16x8_t prvd = vsubq_s16(prev, curr);
int16x8_t nxtd = vsubq_s16(next, curr);
int16x8_t even = vaddq_s16(curs, prvd);
int16x8_t odd = vaddq_s16(curs, nxtd);
// undo scaling and round, then store with even/odd phases interleaved
uint8x8x2_t o;
o.val[0] = vqrshrun_n_s16(even, 4);
o.val[1] = vqrshrun_n_s16(odd, 4);
vst2_u8(out + i * 2, o);
#endif
// "previous" value for next iter
t1 = 3 * in_near[i + 7] + in_far[i + 7];
}
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
for (++i; i < w; ++i)
{
t0 = t1;
t1 = 3 * in_near[i] + in_far[i];
out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8);
out[i * 2] = stbi__div16(3 * t1 + t0 + 8);
}
out[w * 2 - 1] = stbi__div4(t1 + 2);
STBI_NOTUSED(hs);
return out;
}
#endif
static stbi_uc* stbi__resample_row_generic(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs)
{
// resample with nearest-neighbor
int i, j;
STBI_NOTUSED(in_far);
for (i = 0; i < w; ++i)
for (j = 0; j < hs; ++j)
out[i * hs + j] = in_near[i];
return out;
}
// this is a reduced-precision calculation of YCbCr-to-RGB introduced
// to make sure the code produces the same results in both SIMD and scalar
#define stbi__float2fixed(x) (((int)((x)*4096.0f + 0.5f)) << 8)
static void stbi__YCbCr_to_RGB_row(stbi_uc* out, const stbi_uc* y, const stbi_uc* pcb, const stbi_uc* pcr, int count, int step)
{
int i;
for (i = 0; i < count; ++i)
{
int y_fixed = (y[i] << 20) + (1 << 19); // rounding
int r, g, b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr * stbi__float2fixed(1.40200f);
g = y_fixed + (cr * -stbi__float2fixed(0.71414f)) + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000);
b = y_fixed + cb * stbi__float2fixed(1.77200f);
r >>= 20;
g >>= 20;
b >>= 20;
if ((unsigned)r > 255)
{
if (r < 0)
r = 0;
else
r = 255;
}
if ((unsigned)g > 255)
{
if (g < 0)
g = 0;
else
g = 255;
}
if ((unsigned)b > 255)
{
if (b < 0)
b = 0;
else
b = 255;
}
out[0] = (stbi_uc)r;
out[1] = (stbi_uc)g;
out[2] = (stbi_uc)b;
out[3] = 255;
out += step;
}
}
#if defined(STBI_SSE2) || defined(STBI_NEON)
static void stbi__YCbCr_to_RGB_simd(stbi_uc* out, stbi_uc const* y, stbi_uc const* pcb, stbi_uc const* pcr, int count, int step)
{
int i = 0;
#ifdef STBI_SSE2
// step == 3 is pretty ugly on the final interleave, and i'm not convinced
// it's useful in practice (you wouldn't use it for textures, for example).
// so just accelerate step == 4 case.
if (step == 4)
{
// this is a fairly straightforward implementation and not super-optimized.
__m128i signflip = _mm_set1_epi8(-0x80);
__m128i cr_const0 = _mm_set1_epi16((short)(1.40200f * 4096.0f + 0.5f));
__m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f * 4096.0f + 0.5f));
__m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f * 4096.0f + 0.5f));
__m128i cb_const1 = _mm_set1_epi16((short)(1.77200f * 4096.0f + 0.5f));
__m128i y_bias = _mm_set1_epi8((char)(unsigned char)128);
__m128i xw = _mm_set1_epi16(255); // alpha channel
for (; i + 7 < count; i += 8)
{
// load
__m128i y_bytes = _mm_loadl_epi64((__m128i*)(y + i));
__m128i cr_bytes = _mm_loadl_epi64((__m128i*)(pcr + i));
__m128i cb_bytes = _mm_loadl_epi64((__m128i*)(pcb + i));
__m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
__m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
// unpack to short (and left-shift cr, cb by 8)
__m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
__m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
__m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
// color transform
__m128i yws = _mm_srli_epi16(yw, 4);
__m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
__m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
__m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
__m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
__m128i rws = _mm_add_epi16(cr0, yws);
__m128i gwt = _mm_add_epi16(cb0, yws);
__m128i bws = _mm_add_epi16(yws, cb1);
__m128i gws = _mm_add_epi16(gwt, cr1);
// descale
__m128i rw = _mm_srai_epi16(rws, 4);
__m128i bw = _mm_srai_epi16(bws, 4);
__m128i gw = _mm_srai_epi16(gws, 4);
// back to byte, set up for transpose
__m128i brb = _mm_packus_epi16(rw, bw);
__m128i gxb = _mm_packus_epi16(gw, xw);
// transpose to interleave channels
__m128i t0 = _mm_unpacklo_epi8(brb, gxb);
__m128i t1 = _mm_unpackhi_epi8(brb, gxb);
__m128i o0 = _mm_unpacklo_epi16(t0, t1);
__m128i o1 = _mm_unpackhi_epi16(t0, t1);
// store
_mm_storeu_si128((__m128i*)(out + 0), o0);
_mm_storeu_si128((__m128i*)(out + 16), o1);
out += 32;
}
}
#endif
#ifdef STBI_NEON
// in this version, step=3 support would be easy to add. but is there demand?
if (step == 4)
{
// this is a fairly straightforward implementation and not super-optimized.
uint8x8_t signflip = vdup_n_u8(0x80);
int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f * 4096.0f + 0.5f));
int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f * 4096.0f + 0.5f));
int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f * 4096.0f + 0.5f));
int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f * 4096.0f + 0.5f));
for (; i + 7 < count; i += 8)
{
// load
uint8x8_t y_bytes = vld1_u8(y + i);
uint8x8_t cr_bytes = vld1_u8(pcr + i);
uint8x8_t cb_bytes = vld1_u8(pcb + i);
int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
// expand to s16
int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
int16x8_t crw = vshll_n_s8(cr_biased, 7);
int16x8_t cbw = vshll_n_s8(cb_biased, 7);
// color transform
int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
int16x8_t rws = vaddq_s16(yws, cr0);
int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
int16x8_t bws = vaddq_s16(yws, cb1);
// undo scaling, round, convert to byte
uint8x8x4_t o;
o.val[0] = vqrshrun_n_s16(rws, 4);
o.val[1] = vqrshrun_n_s16(gws, 4);
o.val[2] = vqrshrun_n_s16(bws, 4);
o.val[3] = vdup_n_u8(255);
// store, interleaving r/g/b/a
vst4_u8(out, o);
out += 8 * 4;
}
}
#endif
for (; i < count; ++i)
{
int y_fixed = (y[i] << 20) + (1 << 19); // rounding
int r, g, b;
int cr = pcr[i] - 128;
int cb = pcb[i] - 128;
r = y_fixed + cr * stbi__float2fixed(1.40200f);
g = y_fixed + cr * -stbi__float2fixed(0.71414f) + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000);
b = y_fixed + cb * stbi__float2fixed(1.77200f);
r >>= 20;
g >>= 20;
b >>= 20;
if ((unsigned)r > 255)
{
if (r < 0)
r = 0;
else
r = 255;
}
if ((unsigned)g > 255)
{
if (g < 0)
g = 0;
else
g = 255;
}
if ((unsigned)b > 255)
{
if (b < 0)
b = 0;
else
b = 255;
}
out[0] = (stbi_uc)r;
out[1] = (stbi_uc)g;
out[2] = (stbi_uc)b;
out[3] = 255;
out += step;
}
}
#endif
// set up the kernels
static void stbi__setup_jpeg(stbi__jpeg* j)
{
j->idct_block_kernel = stbi__idct_block;
j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
#ifdef STBI_SSE2
if (stbi__sse2_available())
{
j->idct_block_kernel = stbi__idct_simd;
j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
}
#endif
#ifdef STBI_NEON
j->idct_block_kernel = stbi__idct_simd;
j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
#endif
}
// clean up the temporary component buffers
static void stbi__cleanup_jpeg(stbi__jpeg* j)
{
stbi__free_jpeg_components(j, j->s->img_n, 0);
}
typedef struct
{
resample_row_func resample;
stbi_uc *line0, *line1;
int hs, vs; // expansion factor in each axis
int w_lores; // horizontal pixels pre-expansion
int ystep; // how far through vertical expansion we are
int ypos; // which pre-expansion row we're on
} stbi__resample;
// fast 0..255 * 0..255 => 0..255 rounded multiplication
static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y)
{
unsigned int t = x * y + 128;
return (stbi_uc)((t + (t >> 8)) >> 8);
}
static stbi_uc* load_jpeg_image(stbi__jpeg* z, int* out_x, int* out_y, int* comp, int req_comp)
{
int n, decode_n, is_rgb;
z->s->img_n = 0; // make stbi__cleanup_jpeg safe
// validate req_comp
if (req_comp < 0 || req_comp > 4)
return stbi__errpuc("bad req_comp", "Internal error");
// load a jpeg image from whichever source, but leave in YCbCr format
if (!stbi__decode_jpeg_image(z))
{
stbi__cleanup_jpeg(z);
return NULL;
}
// determine actual number of components to generate
n = req_comp ? req_comp : z->s->img_n >= 3 ? 3
: 1;
is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
if (z->s->img_n == 3 && n < 3 && !is_rgb)
decode_n = 1;
else
decode_n = z->s->img_n;
// nothing to do if no components requested; check this now to avoid
// accessing uninitialized coutput[0] later
if (decode_n <= 0)
{
stbi__cleanup_jpeg(z);
return NULL;
}
// resample and color-convert
{
int k;
unsigned int i, j;
stbi_uc* output;
stbi_uc* coutput[4] = { NULL, NULL, NULL, NULL };
stbi__resample res_comp[4];
for (k = 0; k < decode_n; ++k)
{
stbi__resample* r = &res_comp[k];
// allocate line buffer big enough for upsampling off the edges
// with upsample factor of 4
z->img_comp[k].linebuf = (stbi_uc*)stbi__malloc(z->s->img_x + 3);
if (!z->img_comp[k].linebuf)
{
stbi__cleanup_jpeg(z);
return stbi__errpuc("outofmem", "Out of memory");
}
r->hs = z->img_h_max / z->img_comp[k].h;
r->vs = z->img_v_max / z->img_comp[k].v;
r->ystep = r->vs >> 1;
r->w_lores = (z->s->img_x + r->hs - 1) / r->hs;
r->ypos = 0;
r->line0 = r->line1 = z->img_comp[k].data;
if (r->hs == 1 && r->vs == 1)
r->resample = resample_row_1;
else if (r->hs == 1 && r->vs == 2)
r->resample = stbi__resample_row_v_2;
else if (r->hs == 2 && r->vs == 1)
r->resample = stbi__resample_row_h_2;
else if (r->hs == 2 && r->vs == 2)
r->resample = z->resample_row_hv_2_kernel;
else
r->resample = stbi__resample_row_generic;
}
// can't error after this so, this is safe
output = (stbi_uc*)stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);
if (!output)
{
stbi__cleanup_jpeg(z);
return stbi__errpuc("outofmem", "Out of memory");
}
// now go ahead and resample
for (j = 0; j < z->s->img_y; ++j)
{
stbi_uc* out = output + n * z->s->img_x * j;
for (k = 0; k < decode_n; ++k)
{
stbi__resample* r = &res_comp[k];
int y_bot = r->ystep >= (r->vs >> 1);
coutput[k] = r->resample(z->img_comp[k].linebuf,
y_bot ? r->line1 : r->line0,
y_bot ? r->line0 : r->line1,
r->w_lores, r->hs);
if (++r->ystep >= r->vs)
{
r->ystep = 0;
r->line0 = r->line1;
if (++r->ypos < z->img_comp[k].y)
r->line1 += z->img_comp[k].w2;
}
}
if (n >= 3)
{
stbi_uc* y = coutput[0];
if (z->s->img_n == 3)
{
if (is_rgb)
{
for (i = 0; i < z->s->img_x; ++i)
{
out[0] = y[i];
out[1] = coutput[1][i];
out[2] = coutput[2][i];
out[3] = 255;
out += n;
}
}
else
{
z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
}
}
else if (z->s->img_n == 4)
{
if (z->app14_color_transform == 0)
{ // CMYK
for (i = 0; i < z->s->img_x; ++i)
{
stbi_uc m = coutput[3][i];
out[0] = stbi__blinn_8x8(coutput[0][i], m);
out[1] = stbi__blinn_8x8(coutput[1][i], m);
out[2] = stbi__blinn_8x8(coutput[2][i], m);
out[3] = 255;
out += n;
}
}
else if (z->app14_color_transform == 2)
{ // YCCK
z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
for (i = 0; i < z->s->img_x; ++i)
{
stbi_uc m = coutput[3][i];
out[0] = stbi__blinn_8x8(255 - out[0], m);
out[1] = stbi__blinn_8x8(255 - out[1], m);
out[2] = stbi__blinn_8x8(255 - out[2], m);
out += n;
}
}
else
{ // YCbCr + alpha? Ignore the fourth channel for now
z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
}
}
else
for (i = 0; i < z->s->img_x; ++i)
{
out[0] = out[1] = out[2] = y[i];
out[3] = 255; // not used if n==3
out += n;
}
}
else
{
if (is_rgb)
{
if (n == 1)
for (i = 0; i < z->s->img_x; ++i)
*out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
else
{
for (i = 0; i < z->s->img_x; ++i, out += 2)
{
out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
out[1] = 255;
}
}
}
else if (z->s->img_n == 4 && z->app14_color_transform == 0)
{
for (i = 0; i < z->s->img_x; ++i)
{
stbi_uc m = coutput[3][i];
stbi_uc r = stbi__blinn_8x8(coutput[0][i], m);
stbi_uc g = stbi__blinn_8x8(coutput[1][i], m);
stbi_uc b = stbi__blinn_8x8(coutput[2][i], m);
out[0] = stbi__compute_y(r, g, b);
out[1] = 255;
out += n;
}
}
else if (z->s->img_n == 4 && z->app14_color_transform == 2)
{
for (i = 0; i < z->s->img_x; ++i)
{
out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
out[1] = 255;
out += n;
}
}
else
{
stbi_uc* y = coutput[0];
if (n == 1)
for (i = 0; i < z->s->img_x; ++i)
out[i] = y[i];
else
for (i = 0; i < z->s->img_x; ++i)
{
*out++ = y[i];
*out++ = 255;
}
}
}
}
stbi__cleanup_jpeg(z);
*out_x = z->s->img_x;
*out_y = z->s->img_y;
if (comp)
*comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output
return output;
}
}
static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
unsigned char* result;
stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
if (!j)
return stbi__errpuc("outofmem", "Out of memory");
memset(j, 0, sizeof(stbi__jpeg));
STBI_NOTUSED(ri);
j->s = s;
stbi__setup_jpeg(j);
result = load_jpeg_image(j, x, y, comp, req_comp);
STBI_FREE(j);
return result;
}
static int stbi__jpeg_test(stbi__context* s)
{
int r;
stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
if (!j)
return stbi__err("outofmem", "Out of memory");
memset(j, 0, sizeof(stbi__jpeg));
j->s = s;
stbi__setup_jpeg(j);
r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
stbi__rewind(s);
STBI_FREE(j);
return r;
}
static int stbi__jpeg_info_raw(stbi__jpeg* j, int* x, int* y, int* comp)
{
if (!stbi__decode_jpeg_header(j, STBI__SCAN_header))
{
stbi__rewind(j->s);
return 0;
}
if (x)
*x = j->s->img_x;
if (y)
*y = j->s->img_y;
if (comp)
*comp = j->s->img_n >= 3 ? 3 : 1;
return 1;
}
static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp)
{
int result;
stbi__jpeg* j = (stbi__jpeg*)(stbi__malloc(sizeof(stbi__jpeg)));
if (!j)
return stbi__err("outofmem", "Out of memory");
memset(j, 0, sizeof(stbi__jpeg));
j->s = s;
result = stbi__jpeg_info_raw(j, x, y, comp);
STBI_FREE(j);
return result;
}
#endif
// public domain zlib decode v0.2 Sean Barrett 2006-11-18
// simple implementation
// - all input must be provided in an upfront buffer
// - all output is written to a single output buffer (can malloc/realloc)
// performance
// - fast huffman
#ifndef STBI_NO_ZLIB
// fast-way is faster to check than jpeg huffman, but slow way is slower
#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet
// zlib-style huffman encoding
// (jpegs packs from left, zlib from right, so can't share code)
typedef struct
{
stbi__uint16 fast[1 << STBI__ZFAST_BITS];
stbi__uint16 firstcode[16];
int maxcode[17];
stbi__uint16 firstsymbol[16];
stbi_uc size[STBI__ZNSYMS];
stbi__uint16 value[STBI__ZNSYMS];
} stbi__zhuffman;
stbi_inline static int stbi__bitreverse16(int n)
{
n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
return n;
}
stbi_inline static int stbi__bit_reverse(int v, int bits)
{
STBI_ASSERT(bits <= 16);
// to bit reverse n bits, reverse 16 and shift
// e.g. 11 bits, bit reverse and shift away 5
return stbi__bitreverse16(v) >> (16 - bits);
}
static int stbi__zbuild_huffman(stbi__zhuffman* z, const stbi_uc* sizelist, int num)
{
int i, k = 0;
int code, next_code[16], sizes[17];
// DEFLATE spec for generating codes
memset(sizes, 0, sizeof(sizes));
memset(z->fast, 0, sizeof(z->fast));
for (i = 0; i < num; ++i)
++sizes[sizelist[i]];
sizes[0] = 0;
for (i = 1; i < 16; ++i)
if (sizes[i] > (1 << i))
return stbi__err("bad sizes", "Corrupt PNG");
code = 0;
for (i = 1; i < 16; ++i)
{
next_code[i] = code;
z->firstcode[i] = (stbi__uint16)code;
z->firstsymbol[i] = (stbi__uint16)k;
code = (code + sizes[i]);
if (sizes[i])
if (code - 1 >= (1 << i))
return stbi__err("bad codelengths", "Corrupt PNG");
z->maxcode[i] = code << (16 - i); // preshift for inner loop
code <<= 1;
k += sizes[i];
}
z->maxcode[16] = 0x10000; // sentinel
for (i = 0; i < num; ++i)
{
int s = sizelist[i];
if (s)
{
int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
stbi__uint16 fastv = (stbi__uint16)((s << 9) | i);
z->size[c] = (stbi_uc)s;
z->value[c] = (stbi__uint16)i;
if (s <= STBI__ZFAST_BITS)
{
int j = stbi__bit_reverse(next_code[s], s);
while (j < (1 << STBI__ZFAST_BITS))
{
z->fast[j] = fastv;
j += (1 << s);
}
}
++next_code[s];
}
}
return 1;
}
// zlib-from-memory implementation for PNG reading
// because PNG allows splitting the zlib stream arbitrarily,
// and it's annoying structurally to have PNG call ZLIB call PNG,
// we require PNG read all the IDATs and combine them into a single
// memory buffer
typedef struct
{
stbi_uc *zbuffer, *zbuffer_end;
int num_bits;
int hit_zeof_once;
stbi__uint32 code_buffer;
char* zout;
char* zout_start;
char* zout_end;
int z_expandable;
stbi__zhuffman z_length, z_distance;
} stbi__zbuf;
stbi_inline static int stbi__zeof(stbi__zbuf* z)
{
return (z->zbuffer >= z->zbuffer_end);
}
stbi_inline static stbi_uc stbi__zget8(stbi__zbuf* z)
{
return stbi__zeof(z) ? 0 : *z->zbuffer++;
}
static void stbi__fill_bits(stbi__zbuf* z)
{
do
{
if (z->code_buffer >= (1U << z->num_bits))
{
z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */
return;
}
z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits;
z->num_bits += 8;
} while (z->num_bits <= 24);
}
stbi_inline static unsigned int stbi__zreceive(stbi__zbuf* z, int n)
{
unsigned int k;
if (z->num_bits < n)
stbi__fill_bits(z);
k = z->code_buffer & ((1 << n) - 1);
z->code_buffer >>= n;
z->num_bits -= n;
return k;
}
static int stbi__zhuffman_decode_slowpath(stbi__zbuf* a, stbi__zhuffman* z)
{
int b, s, k;
// not resolved by fast table, so compute it the slow way
// use jpeg approach, which requires MSbits at top
k = stbi__bit_reverse(a->code_buffer, 16);
for (s = STBI__ZFAST_BITS + 1;; ++s)
if (k < z->maxcode[s])
break;
if (s >= 16)
return -1; // invalid code!
// code size is s, so:
b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s];
if (b >= STBI__ZNSYMS)
return -1; // some data was corrupt somewhere!
if (z->size[b] != s)
return -1; // was originally an assert, but report failure instead.
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
stbi_inline static int stbi__zhuffman_decode(stbi__zbuf* a, stbi__zhuffman* z)
{
int b, s;
if (a->num_bits < 16)
{
if (stbi__zeof(a))
{
if (!a->hit_zeof_once)
{
// This is the first time we hit eof, insert 16 extra padding btis
// to allow us to keep going; if we actually consume any of them
// though, that is invalid data. This is caught later.
a->hit_zeof_once = 1;
a->num_bits += 16; // add 16 implicit zero bits
}
else
{
// We already inserted our extra 16 padding bits and are again
// out, this stream is actually prematurely terminated.
return -1;
}
}
else
{
stbi__fill_bits(a);
}
}
b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
if (b)
{
s = b >> 9;
a->code_buffer >>= s;
a->num_bits -= s;
return b & 511;
}
return stbi__zhuffman_decode_slowpath(a, z);
}
static int stbi__zexpand(stbi__zbuf* z, char* zout, int n) // need to make room for n bytes
{
char* q;
unsigned int cur, limit, old_limit;
z->zout = zout;
if (!z->z_expandable)
return stbi__err("output buffer limit", "Corrupt PNG");
cur = (unsigned int)(z->zout - z->zout_start);
limit = old_limit = (unsigned)(z->zout_end - z->zout_start);
if (UINT_MAX - cur < (unsigned)n)
return stbi__err("outofmem", "Out of memory");
while (cur + n > limit)
{
if (limit > UINT_MAX / 2)
return stbi__err("outofmem", "Out of memory");
limit *= 2;
}
q = (char*)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
STBI_NOTUSED(old_limit);
if (q == NULL)
return stbi__err("outofmem", "Out of memory");
z->zout_start = q;
z->zout = q + cur;
z->zout_end = q + limit;
return 1;
}
static const int stbi__zlength_base[31] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13,
15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
static const int stbi__zlength_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 };
static const int stbi__zdist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 };
static const int stbi__zdist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
static int stbi__parse_huffman_block(stbi__zbuf* a)
{
char* zout = a->zout;
for (;;)
{
int z = stbi__zhuffman_decode(a, &a->z_length);
if (z < 256)
{
if (z < 0)
return stbi__err("bad huffman code", "Corrupt PNG"); // error in huffman codes
if (zout >= a->zout_end)
{
if (!stbi__zexpand(a, zout, 1))
return 0;
zout = a->zout;
}
*zout++ = (char)z;
}
else
{
stbi_uc* p;
int len, dist;
if (z == 256)
{
a->zout = zout;
if (a->hit_zeof_once && a->num_bits < 16)
{
// The first time we hit zeof, we inserted 16 extra zero bits into our bit
// buffer so the decoder can just do its speculative decoding. But if we
// actually consumed any of those bits (which is the case when num_bits < 16),
// the stream actually read past the end so it is malformed.
return stbi__err("unexpected end", "Corrupt PNG");
}
return 1;
}
if (z >= 286)
return stbi__err("bad huffman code", "Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data
z -= 257;
len = stbi__zlength_base[z];
if (stbi__zlength_extra[z])
len += stbi__zreceive(a, stbi__zlength_extra[z]);
z = stbi__zhuffman_decode(a, &a->z_distance);
if (z < 0 || z >= 30)
return stbi__err("bad huffman code", "Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data
dist = stbi__zdist_base[z];
if (stbi__zdist_extra[z])
dist += stbi__zreceive(a, stbi__zdist_extra[z]);
if (zout - a->zout_start < dist)
return stbi__err("bad dist", "Corrupt PNG");
if (len > a->zout_end - zout)
{
if (!stbi__zexpand(a, zout, len))
return 0;
zout = a->zout;
}
p = (stbi_uc*)(zout - dist);
if (dist == 1)
{ // run of one byte; common in images.
stbi_uc v = *p;
if (len)
{
do
*zout++ = v;
while (--len);
}
}
else
{
if (len)
{
do
*zout++ = *p++;
while (--len);
}
}
}
}
}
static int stbi__compute_huffman_codes(stbi__zbuf* a)
{
static const stbi_uc length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
stbi__zhuffman z_codelength;
stbi_uc lencodes[286 + 32 + 137]; //padding for maximum single op
stbi_uc codelength_sizes[19];
int i, n;
int hlit = stbi__zreceive(a, 5) + 257;
int hdist = stbi__zreceive(a, 5) + 1;
int hclen = stbi__zreceive(a, 4) + 4;
int ntot = hlit + hdist;
memset(codelength_sizes, 0, sizeof(codelength_sizes));
for (i = 0; i < hclen; ++i)
{
int s = stbi__zreceive(a, 3);
codelength_sizes[length_dezigzag[i]] = (stbi_uc)s;
}
if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19))
return 0;
n = 0;
while (n < ntot)
{
int c = stbi__zhuffman_decode(a, &z_codelength);
if (c < 0 || c >= 19)
return stbi__err("bad codelengths", "Corrupt PNG");
if (c < 16)
lencodes[n++] = (stbi_uc)c;
else
{
stbi_uc fill = 0;
if (c == 16)
{
c = stbi__zreceive(a, 2) + 3;
if (n == 0)
return stbi__err("bad codelengths", "Corrupt PNG");
fill = lencodes[n - 1];
}
else if (c == 17)
{
c = stbi__zreceive(a, 3) + 3;
}
else if (c == 18)
{
c = stbi__zreceive(a, 7) + 11;
}
else
{
return stbi__err("bad codelengths", "Corrupt PNG");
}
if (ntot - n < c)
return stbi__err("bad codelengths", "Corrupt PNG");
memset(lencodes + n, fill, c);
n += c;
}
}
if (n != ntot)
return stbi__err("bad codelengths", "Corrupt PNG");
if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit))
return 0;
if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist))
return 0;
return 1;
}
static int stbi__parse_uncompressed_block(stbi__zbuf* a)
{
stbi_uc header[4];
int len, nlen, k;
if (a->num_bits & 7)
stbi__zreceive(a, a->num_bits & 7); // discard
// drain the bit-packed data into header
k = 0;
while (a->num_bits > 0)
{
header[k++] = (stbi_uc)(a->code_buffer & 255); // suppress MSVC run-time check
a->code_buffer >>= 8;
a->num_bits -= 8;
}
if (a->num_bits < 0)
return stbi__err("zlib corrupt", "Corrupt PNG");
// now fill header the normal way
while (k < 4)
header[k++] = stbi__zget8(a);
len = header[1] * 256 + header[0];
nlen = header[3] * 256 + header[2];
if (nlen != (len ^ 0xffff))
return stbi__err("zlib corrupt", "Corrupt PNG");
if (a->zbuffer + len > a->zbuffer_end)
return stbi__err("read past buffer", "Corrupt PNG");
if (a->zout + len > a->zout_end)
if (!stbi__zexpand(a, a->zout, len))
return 0;
memcpy(a->zout, a->zbuffer, len);
a->zbuffer += len;
a->zout += len;
return 1;
}
static int stbi__parse_zlib_header(stbi__zbuf* a)
{
int cmf = stbi__zget8(a);
int cm = cmf & 15;
/* int cinfo = cmf >> 4; */
int flg = stbi__zget8(a);
if (stbi__zeof(a))
return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
if ((cmf * 256 + flg) % 31 != 0)
return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
if (flg & 32)
return stbi__err("no preset dict", "Corrupt PNG"); // preset dictionary not allowed in png
if (cm != 8)
return stbi__err("bad compression", "Corrupt PNG"); // DEFLATE required for png
// window = 1 << (8 + cinfo)... but who cares, we fully buffer output
return 1;
}
static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = {
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8
};
static const stbi_uc stbi__zdefault_distance[32] = {
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
};
/*
Init algorithm:
{
int i; // use <= to match clearly with spec
for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
}
*/
static int stbi__parse_zlib(stbi__zbuf* a, int parse_header)
{
int final, type;
if (parse_header)
if (!stbi__parse_zlib_header(a))
return 0;
a->num_bits = 0;
a->code_buffer = 0;
a->hit_zeof_once = 0;
do
{
final = stbi__zreceive(a, 1);
type = stbi__zreceive(a, 2);
if (type == 0)
{
if (!stbi__parse_uncompressed_block(a))
return 0;
}
else if (type == 3)
{
return 0;
}
else
{
if (type == 1)
{
// use fixed code lengths
if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, STBI__ZNSYMS))
return 0;
if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32))
return 0;
}
else
{
if (!stbi__compute_huffman_codes(a))
return 0;
}
if (!stbi__parse_huffman_block(a))
return 0;
}
} while (!final);
return 1;
}
static int stbi__do_zlib(stbi__zbuf* a, char* obuf, int olen, int exp, int parse_header)
{
a->zout_start = obuf;
a->zout = obuf;
a->zout_end = obuf + olen;
a->z_expandable = exp;
return stbi__parse_zlib(a, parse_header);
}
STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, int initial_size, int* outlen)
{
stbi__zbuf a;
char* p = (char*)stbi__malloc(initial_size);
if (p == NULL)
return NULL;
a.zbuffer = (stbi_uc*)buffer;
a.zbuffer_end = (stbi_uc*)buffer + len;
if (stbi__do_zlib(&a, p, initial_size, 1, 1))
{
if (outlen)
*outlen = (int)(a.zout - a.zout_start);
return a.zout_start;
}
else
{
STBI_FREE(a.zout_start);
return NULL;
}
}
STBIDEF char* stbi_zlib_decode_malloc(char const* buffer, int len, int* outlen)
{
return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
}
STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, int len, int initial_size, int* outlen, int parse_header)
{
stbi__zbuf a;
char* p = (char*)stbi__malloc(initial_size);
if (p == NULL)
return NULL;
a.zbuffer = (stbi_uc*)buffer;
a.zbuffer_end = (stbi_uc*)buffer + len;
if (stbi__do_zlib(&a, p, initial_size, 1, parse_header))
{
if (outlen)
*outlen = (int)(a.zout - a.zout_start);
return a.zout_start;
}
else
{
STBI_FREE(a.zout_start);
return NULL;
}
}
STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, char const* ibuffer, int ilen)
{
stbi__zbuf a;
a.zbuffer = (stbi_uc*)ibuffer;
a.zbuffer_end = (stbi_uc*)ibuffer + ilen;
if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
return (int)(a.zout - a.zout_start);
else
return -1;
}
STBIDEF char* stbi_zlib_decode_noheader_malloc(char const* buffer, int len, int* outlen)
{
stbi__zbuf a;
char* p = (char*)stbi__malloc(16384);
if (p == NULL)
return NULL;
a.zbuffer = (stbi_uc*)buffer;
a.zbuffer_end = (stbi_uc*)buffer + len;
if (stbi__do_zlib(&a, p, 16384, 1, 0))
{
if (outlen)
*outlen = (int)(a.zout - a.zout_start);
return a.zout_start;
}
else
{
STBI_FREE(a.zout_start);
return NULL;
}
}
STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, const char* ibuffer, int ilen)
{
stbi__zbuf a;
a.zbuffer = (stbi_uc*)ibuffer;
a.zbuffer_end = (stbi_uc*)ibuffer + ilen;
if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
return (int)(a.zout - a.zout_start);
else
return -1;
}
#endif
// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
// simple implementation
// - only 8-bit samples
// - no CRC checking
// - allocates lots of intermediate memory
// - avoids problem of streaming data between subsystems
// - avoids explicit window management
// performance
// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
#ifndef STBI_NO_PNG
typedef struct
{
stbi__uint32 length;
stbi__uint32 type;
} stbi__pngchunk;
static stbi__pngchunk stbi__get_chunk_header(stbi__context* s)
{
stbi__pngchunk c;
c.length = stbi__get32be(s);
c.type = stbi__get32be(s);
return c;
}
static int stbi__check_png_header(stbi__context* s)
{
static const stbi_uc png_sig[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
int i;
for (i = 0; i < 8; ++i)
if (stbi__get8(s) != png_sig[i])
return stbi__err("bad png sig", "Not a PNG");
return 1;
}
typedef struct
{
stbi__context* s;
stbi_uc *idata, *expanded, *out;
int depth;
} stbi__png;
enum
{
STBI__F_none = 0,
STBI__F_sub = 1,
STBI__F_up = 2,
STBI__F_avg = 3,
STBI__F_paeth = 4,
// synthetic filter used for first scanline to avoid needing a dummy row of 0s
STBI__F_avg_first
};
static stbi_uc first_row_filter[5] = {
STBI__F_none,
STBI__F_sub,
STBI__F_none,
STBI__F_avg_first,
STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub
};
static int stbi__paeth(int a, int b, int c)
{
// This formulation looks very different from the reference in the PNG spec, but is
// actually equivalent and has favorable data dependencies and admits straightforward
// generation of branch-free code, which helps performance significantly.
int thresh = c * 3 - (a + b);
int lo = a < b ? a : b;
int hi = a < b ? b : a;
int t0 = (hi <= thresh) ? lo : c;
int t1 = (thresh <= lo) ? hi : t0;
return t1;
}
static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01 };
// adds an extra all-255 alpha channel
// dest == src is legal
// img_n must be 1 or 3
static void stbi__create_png_alpha_expand8(stbi_uc* dest, stbi_uc* src, stbi__uint32 x, int img_n)
{
int i;
// must process data backwards since we allow dest==src
if (img_n == 1)
{
for (i = x - 1; i >= 0; --i)
{
dest[i * 2 + 1] = 255;
dest[i * 2 + 0] = src[i];
}
}
else
{
STBI_ASSERT(img_n == 3);
for (i = x - 1; i >= 0; --i)
{
dest[i * 4 + 3] = 255;
dest[i * 4 + 2] = src[i * 3 + 2];
dest[i * 4 + 1] = src[i * 3 + 1];
dest[i * 4 + 0] = src[i * 3 + 0];
}
}
}
// create the png data from post-deflated data
static int stbi__create_png_image_raw(stbi__png* a, stbi_uc* raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
{
int bytes = (depth == 16 ? 2 : 1);
stbi__context* s = a->s;
stbi__uint32 i, j, stride = x * out_n * bytes;
stbi__uint32 img_len, img_width_bytes;
stbi_uc* filter_buf;
int all_ok = 1;
int k;
int img_n = s->img_n; // copy it into a local for later
int output_bytes = out_n * bytes;
int filter_bytes = img_n * bytes;
int width = x;
STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1);
a->out = (stbi_uc*)stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into
if (!a->out)
return stbi__err("outofmem", "Out of memory");
// note: error exits here don't need to clean up a->out individually,
// stbi__do_png always does on error.
if (!stbi__mad3sizes_valid(img_n, x, depth, 7))
return stbi__err("too large", "Corrupt PNG");
img_width_bytes = (((img_n * x * depth) + 7) >> 3);
if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes))
return stbi__err("too large", "Corrupt PNG");
img_len = (img_width_bytes + 1) * y;
// we used to check for exact match between raw_len and img_len on non-interlaced PNGs,
// but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),
// so just check for raw_len < img_len always.
if (raw_len < img_len)
return stbi__err("not enough pixels", "Corrupt PNG");
// Allocate two scan lines worth of filter workspace buffer.
filter_buf = (stbi_uc*)stbi__malloc_mad2(img_width_bytes, 2, 0);
if (!filter_buf)
return stbi__err("outofmem", "Out of memory");
// Filtering for low-bit-depth images
if (depth < 8)
{
filter_bytes = 1;
width = img_width_bytes;
}
for (j = 0; j < y; ++j)
{
// cur/prior filter buffers alternate
stbi_uc* cur = filter_buf + (j & 1) * img_width_bytes;
stbi_uc* prior = filter_buf + (~j & 1) * img_width_bytes;
stbi_uc* dest = a->out + stride * j;
int nk = width * filter_bytes;
int filter = *raw++;
// check filter type
if (filter > 4)
{
all_ok = stbi__err("invalid filter", "Corrupt PNG");
break;
}
// if first row, use special filter that doesn't sample previous row
if (j == 0)
filter = first_row_filter[filter];
// perform actual filtering
switch (filter)
{
case STBI__F_none:
memcpy(cur, raw, nk);
break;
case STBI__F_sub:
memcpy(cur, raw, filter_bytes);
for (k = filter_bytes; k < nk; ++k)
cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]);
break;
case STBI__F_up:
for (k = 0; k < nk; ++k)
cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
break;
case STBI__F_avg:
for (k = 0; k < filter_bytes; ++k)
cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1));
for (k = filter_bytes; k < nk; ++k)
cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1));
break;
case STBI__F_paeth:
for (k = 0; k < filter_bytes; ++k)
cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
for (k = filter_bytes; k < nk; ++k)
cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], prior[k], prior[k - filter_bytes]));
break;
case STBI__F_avg_first:
memcpy(cur, raw, filter_bytes);
for (k = filter_bytes; k < nk; ++k)
cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1));
break;
}
raw += nk;
// expand decoded bits in cur to dest, also adding an extra alpha channel if desired
if (depth < 8)
{
stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
stbi_uc* in = cur;
stbi_uc* out = dest;
stbi_uc inb = 0;
stbi__uint32 nsmp = x * img_n;
// expand bits to bytes first
if (depth == 4)
{
for (i = 0; i < nsmp; ++i)
{
if ((i & 1) == 0)
inb = *in++;
*out++ = scale * (inb >> 4);
inb <<= 4;
}
}
else if (depth == 2)
{
for (i = 0; i < nsmp; ++i)
{
if ((i & 3) == 0)
inb = *in++;
*out++ = scale * (inb >> 6);
inb <<= 2;
}
}
else
{
STBI_ASSERT(depth == 1);
for (i = 0; i < nsmp; ++i)
{
if ((i & 7) == 0)
inb = *in++;
*out++ = scale * (inb >> 7);
inb <<= 1;
}
}
// insert alpha=255 values if desired
if (img_n != out_n)
stbi__create_png_alpha_expand8(dest, dest, x, img_n);
}
else if (depth == 8)
{
if (img_n == out_n)
memcpy(dest, cur, x * img_n);
else
stbi__create_png_alpha_expand8(dest, cur, x, img_n);
}
else if (depth == 16)
{
// convert the image data from big-endian to platform-native
stbi__uint16* dest16 = (stbi__uint16*)dest;
stbi__uint32 nsmp = x * img_n;
if (img_n == out_n)
{
for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)
*dest16 = (cur[0] << 8) | cur[1];
}
else
{
STBI_ASSERT(img_n + 1 == out_n);
if (img_n == 1)
{
for (i = 0; i < x; ++i, dest16 += 2, cur += 2)
{
dest16[0] = (cur[0] << 8) | cur[1];
dest16[1] = 0xffff;
}
}
else
{
STBI_ASSERT(img_n == 3);
for (i = 0; i < x; ++i, dest16 += 4, cur += 6)
{
dest16[0] = (cur[0] << 8) | cur[1];
dest16[1] = (cur[2] << 8) | cur[3];
dest16[2] = (cur[4] << 8) | cur[5];
dest16[3] = 0xffff;
}
}
}
}
}
STBI_FREE(filter_buf);
if (!all_ok)
return 0;
return 1;
}
static int stbi__create_png_image(stbi__png* a, stbi_uc* image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
{
int bytes = (depth == 16 ? 2 : 1);
int out_bytes = out_n * bytes;
stbi_uc* final;
int p;
if (!interlaced)
return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
// de-interlacing
final = (stbi_uc*)stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
if (!final)
return stbi__err("outofmem", "Out of memory");
for (p = 0; p < 7; ++p)
{
int xorig[] = { 0, 4, 0, 2, 0, 1, 0 };
int yorig[] = { 0, 0, 4, 0, 2, 0, 1 };
int xspc[] = { 8, 8, 4, 4, 2, 2, 1 };
int yspc[] = { 8, 8, 8, 4, 4, 2, 2 };
int i, j, x, y;
// pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p];
y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p];
if (x && y)
{
stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color))
{
STBI_FREE(final);
return 0;
}
for (j = 0; j < y; ++j)
{
for (i = 0; i < x; ++i)
{
int out_y = j * yspc[p] + yorig[p];
int out_x = i * xspc[p] + xorig[p];
memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes,
a->out + (j * x + i) * out_bytes, out_bytes);
}
}
STBI_FREE(a->out);
image_data += img_len;
image_data_len -= img_len;
}
}
a->out = final;
return 1;
}
static int stbi__compute_transparency(stbi__png* z, stbi_uc tc[3], int out_n)
{
stbi__context* s = z->s;
stbi__uint32 i, pixel_count = s->img_x * s->img_y;
stbi_uc* p = z->out;
// compute color-based transparency, assuming we've
// already got 255 as the alpha value in the output
STBI_ASSERT(out_n == 2 || out_n == 4);
if (out_n == 2)
{
for (i = 0; i < pixel_count; ++i)
{
p[1] = (p[0] == tc[0] ? 0 : 255);
p += 2;
}
}
else
{
for (i = 0; i < pixel_count; ++i)
{
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
p[3] = 0;
p += 4;
}
}
return 1;
}
static int stbi__compute_transparency16(stbi__png* z, stbi__uint16 tc[3], int out_n)
{
stbi__context* s = z->s;
stbi__uint32 i, pixel_count = s->img_x * s->img_y;
stbi__uint16* p = (stbi__uint16*)z->out;
// compute color-based transparency, assuming we've
// already got 65535 as the alpha value in the output
STBI_ASSERT(out_n == 2 || out_n == 4);
if (out_n == 2)
{
for (i = 0; i < pixel_count; ++i)
{
p[1] = (p[0] == tc[0] ? 0 : 65535);
p += 2;
}
}
else
{
for (i = 0; i < pixel_count; ++i)
{
if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
p[3] = 0;
p += 4;
}
}
return 1;
}
static int stbi__expand_png_palette(stbi__png* a, stbi_uc* palette, int len, int pal_img_n)
{
stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
stbi_uc *p, *temp_out, *orig = a->out;
p = (stbi_uc*)stbi__malloc_mad2(pixel_count, pal_img_n, 0);
if (p == NULL)
return stbi__err("outofmem", "Out of memory");
// between here and free(out) below, exitting would leak
temp_out = p;
if (pal_img_n == 3)
{
for (i = 0; i < pixel_count; ++i)
{
int n = orig[i] * 4;
p[0] = palette[n];
p[1] = palette[n + 1];
p[2] = palette[n + 2];
p += 3;
}
}
else
{
for (i = 0; i < pixel_count; ++i)
{
int n = orig[i] * 4;
p[0] = palette[n];
p[1] = palette[n + 1];
p[2] = palette[n + 2];
p[3] = palette[n + 3];
p += 4;
}
}
STBI_FREE(a->out);
a->out = temp_out;
STBI_NOTUSED(len);
return 1;
}
static int stbi__unpremultiply_on_load_global = 0;
static int stbi__de_iphone_flag_global = 0;
STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
{
stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
}
STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
{
stbi__de_iphone_flag_global = flag_true_if_should_convert;
}
#ifndef STBI_THREAD_LOCAL
#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global
#define stbi__de_iphone_flag stbi__de_iphone_flag_global
#else
static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
{
stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
stbi__unpremultiply_on_load_set = 1;
}
STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
{
stbi__de_iphone_flag_local = flag_true_if_should_convert;
stbi__de_iphone_flag_set = 1;
}
#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \
? stbi__unpremultiply_on_load_local \
: stbi__unpremultiply_on_load_global)
#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \
? stbi__de_iphone_flag_local \
: stbi__de_iphone_flag_global)
#endif // STBI_THREAD_LOCAL
static void stbi__de_iphone(stbi__png* z)
{
stbi__context* s = z->s;
stbi__uint32 i, pixel_count = s->img_x * s->img_y;
stbi_uc* p = z->out;
if (s->img_out_n == 3)
{ // convert bgr to rgb
for (i = 0; i < pixel_count; ++i)
{
stbi_uc t = p[0];
p[0] = p[2];
p[2] = t;
p += 3;
}
}
else
{
STBI_ASSERT(s->img_out_n == 4);
if (stbi__unpremultiply_on_load)
{
// convert bgr to rgb and unpremultiply
for (i = 0; i < pixel_count; ++i)
{
stbi_uc a = p[3];
stbi_uc t = p[0];
if (a)
{
stbi_uc half = a / 2;
p[0] = (p[2] * 255 + half) / a;
p[1] = (p[1] * 255 + half) / a;
p[2] = (t * 255 + half) / a;
}
else
{
p[0] = p[2];
p[2] = t;
}
p += 4;
}
}
else
{
// convert bgr to rgb
for (i = 0; i < pixel_count; ++i)
{
stbi_uc t = p[0];
p[0] = p[2];
p[2] = t;
p += 4;
}
}
}
}
#define STBI__PNG_TYPE(a, b, c, d) (((unsigned)(a) << 24) + ((unsigned)(b) << 16) + ((unsigned)(c) << 8) + (unsigned)(d))
static int stbi__parse_png_file(stbi__png* z, int scan, int req_comp)
{
stbi_uc palette[1024], pal_img_n = 0;
stbi_uc has_trans = 0, tc[3] = { 0 };
stbi__uint16 tc16[3];
stbi__uint32 ioff = 0, idata_limit = 0, i, pal_len = 0;
int first = 1, k, interlace = 0, color = 0, is_iphone = 0;
stbi__context* s = z->s;
z->expanded = NULL;
z->idata = NULL;
z->out = NULL;
if (!stbi__check_png_header(s))
return 0;
if (scan == STBI__SCAN_type)
return 1;
for (;;)
{
stbi__pngchunk c = stbi__get_chunk_header(s);
switch (c.type)
{
case STBI__PNG_TYPE('C', 'g', 'B', 'I'):
is_iphone = 1;
stbi__skip(s, c.length);
break;
case STBI__PNG_TYPE('I', 'H', 'D', 'R'):
{
int comp, filter;
if (!first)
return stbi__err("multiple IHDR", "Corrupt PNG");
first = 0;
if (c.length != 13)
return stbi__err("bad IHDR len", "Corrupt PNG");
s->img_x = stbi__get32be(s);
s->img_y = stbi__get32be(s);
if (s->img_y > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
z->depth = stbi__get8(s);
if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16)
return stbi__err("1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only");
color = stbi__get8(s);
if (color > 6)
return stbi__err("bad ctype", "Corrupt PNG");
if (color == 3 && z->depth == 16)
return stbi__err("bad ctype", "Corrupt PNG");
if (color == 3)
pal_img_n = 3;
else if (color & 1)
return stbi__err("bad ctype", "Corrupt PNG");
comp = stbi__get8(s);
if (comp)
return stbi__err("bad comp method", "Corrupt PNG");
filter = stbi__get8(s);
if (filter)
return stbi__err("bad filter method", "Corrupt PNG");
interlace = stbi__get8(s);
if (interlace > 1)
return stbi__err("bad interlace method", "Corrupt PNG");
if (!s->img_x || !s->img_y)
return stbi__err("0-pixel image", "Corrupt PNG");
if (!pal_img_n)
{
s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
if ((1 << 30) / s->img_x / s->img_n < s->img_y)
return stbi__err("too large", "Image too large to decode");
}
else
{
// if paletted, then pal_n is our final components, and
// img_n is # components to decompress/filter.
s->img_n = 1;
if ((1 << 30) / s->img_x / 4 < s->img_y)
return stbi__err("too large", "Corrupt PNG");
}
// even with SCAN_header, have to scan to see if we have a tRNS
break;
}
case STBI__PNG_TYPE('P', 'L', 'T', 'E'):
{
if (first)
return stbi__err("first not IHDR", "Corrupt PNG");
if (c.length > 256 * 3)
return stbi__err("invalid PLTE", "Corrupt PNG");
pal_len = c.length / 3;
if (pal_len * 3 != c.length)
return stbi__err("invalid PLTE", "Corrupt PNG");
for (i = 0; i < pal_len; ++i)
{
palette[i * 4 + 0] = stbi__get8(s);
palette[i * 4 + 1] = stbi__get8(s);
palette[i * 4 + 2] = stbi__get8(s);
palette[i * 4 + 3] = 255;
}
break;
}
case STBI__PNG_TYPE('t', 'R', 'N', 'S'):
{
if (first)
return stbi__err("first not IHDR", "Corrupt PNG");
if (z->idata)
return stbi__err("tRNS after IDAT", "Corrupt PNG");
if (pal_img_n)
{
if (scan == STBI__SCAN_header)
{
s->img_n = 4;
return 1;
}
if (pal_len == 0)
return stbi__err("tRNS before PLTE", "Corrupt PNG");
if (c.length > pal_len)
return stbi__err("bad tRNS len", "Corrupt PNG");
pal_img_n = 4;
for (i = 0; i < c.length; ++i)
palette[i * 4 + 3] = stbi__get8(s);
}
else
{
if (!(s->img_n & 1))
return stbi__err("tRNS with alpha", "Corrupt PNG");
if (c.length != (stbi__uint32)s->img_n * 2)
return stbi__err("bad tRNS len", "Corrupt PNG");
has_trans = 1;
// non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.
if (scan == STBI__SCAN_header)
{
++s->img_n;
return 1;
}
if (z->depth == 16)
{
for (k = 0; k < s->img_n; ++k)
tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is
}
else
{
for (k = 0; k < s->img_n; ++k)
tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger
}
}
break;
}
case STBI__PNG_TYPE('I', 'D', 'A', 'T'):
{
if (first)
return stbi__err("first not IHDR", "Corrupt PNG");
if (pal_img_n && !pal_len)
return stbi__err("no PLTE", "Corrupt PNG");
if (scan == STBI__SCAN_header)
{
// header scan definitely stops at first IDAT
if (pal_img_n)
s->img_n = pal_img_n;
return 1;
}
if (c.length > (1u << 30))
return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
if ((int)(ioff + c.length) < (int)ioff)
return 0;
if (ioff + c.length > idata_limit)
{
stbi__uint32 idata_limit_old = idata_limit;
stbi_uc* p;
if (idata_limit == 0)
idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit)
idata_limit *= 2;
STBI_NOTUSED(idata_limit_old);
p = (stbi_uc*)STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit);
if (p == NULL)
return stbi__err("outofmem", "Out of memory");
z->idata = p;
}
if (!stbi__getn(s, z->idata + ioff, c.length))
return stbi__err("outofdata", "Corrupt PNG");
ioff += c.length;
break;
}
case STBI__PNG_TYPE('I', 'E', 'N', 'D'):
{
stbi__uint32 raw_len, bpl;
if (first)
return stbi__err("first not IHDR", "Corrupt PNG");
if (scan != STBI__SCAN_load)
return 1;
if (z->idata == NULL)
return stbi__err("no IDAT", "Corrupt PNG");
// initial guess for decoded data size to avoid unnecessary reallocs
bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
z->expanded = (stbi_uc*)stbi_zlib_decode_malloc_guesssize_headerflag((char*)z->idata, ioff, raw_len, (int*)&raw_len, !is_iphone);
if (z->expanded == NULL)
return 0; // zlib should set error
STBI_FREE(z->idata);
z->idata = NULL;
if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans)
s->img_out_n = s->img_n + 1;
else
s->img_out_n = s->img_n;
if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace))
return 0;
if (has_trans)
{
if (z->depth == 16)
{
if (!stbi__compute_transparency16(z, tc16, s->img_out_n))
return 0;
}
else
{
if (!stbi__compute_transparency(z, tc, s->img_out_n))
return 0;
}
}
if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
stbi__de_iphone(z);
if (pal_img_n)
{
// pal_img_n == 3 or 4
s->img_n = pal_img_n; // record the actual colors we had
s->img_out_n = pal_img_n;
if (req_comp >= 3)
s->img_out_n = req_comp;
if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
return 0;
}
else if (has_trans)
{
// non-paletted image with tRNS -> source image has (constant) alpha
++s->img_n;
}
STBI_FREE(z->expanded);
z->expanded = NULL;
// end of PNG chunk, read and skip CRC
stbi__get32be(s);
return 1;
}
default:
// if critical, fail
if (first)
return stbi__err("first not IHDR", "Corrupt PNG");
if ((c.type & (1 << 29)) == 0)
{
#ifndef STBI_NO_FAILURE_STRINGS
// not threadsafe
static char invalid_chunk[] = "XXXX PNG chunk not known";
invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
#endif
return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
}
stbi__skip(s, c.length);
break;
}
// end of PNG chunk, read and skip CRC
stbi__get32be(s);
}
}
static void* stbi__do_png(stbi__png* p, int* x, int* y, int* n, int req_comp, stbi__result_info* ri)
{
void* result = NULL;
if (req_comp < 0 || req_comp > 4)
return stbi__errpuc("bad req_comp", "Internal error");
if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp))
{
if (p->depth <= 8)
ri->bits_per_channel = 8;
else if (p->depth == 16)
ri->bits_per_channel = 16;
else
return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
result = p->out;
p->out = NULL;
if (req_comp && req_comp != p->s->img_out_n)
{
if (ri->bits_per_channel == 8)
result = stbi__convert_format((unsigned char*)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
else
result = stbi__convert_format16((stbi__uint16*)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
p->s->img_out_n = req_comp;
if (result == NULL)
return result;
}
*x = p->s->img_x;
*y = p->s->img_y;
if (n)
*n = p->s->img_n;
}
STBI_FREE(p->out);
p->out = NULL;
STBI_FREE(p->expanded);
p->expanded = NULL;
STBI_FREE(p->idata);
p->idata = NULL;
return result;
}
static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
stbi__png p;
p.s = s;
return stbi__do_png(&p, x, y, comp, req_comp, ri);
}
static int stbi__png_test(stbi__context* s)
{
int r;
r = stbi__check_png_header(s);
stbi__rewind(s);
return r;
}
static int stbi__png_info_raw(stbi__png* p, int* x, int* y, int* comp)
{
if (!stbi__parse_png_file(p, STBI__SCAN_header, 0))
{
stbi__rewind(p->s);
return 0;
}
if (x)
*x = p->s->img_x;
if (y)
*y = p->s->img_y;
if (comp)
*comp = p->s->img_n;
return 1;
}
static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp)
{
stbi__png p;
p.s = s;
return stbi__png_info_raw(&p, x, y, comp);
}
static int stbi__png_is16(stbi__context* s)
{
stbi__png p;
p.s = s;
if (!stbi__png_info_raw(&p, NULL, NULL, NULL))
return 0;
if (p.depth != 16)
{
stbi__rewind(p.s);
return 0;
}
return 1;
}
#endif
// Microsoft/Windows BMP image
#ifndef STBI_NO_BMP
static int stbi__bmp_test_raw(stbi__context* s)
{
int r;
int sz;
if (stbi__get8(s) != 'B')
return 0;
if (stbi__get8(s) != 'M')
return 0;
stbi__get32le(s); // discard filesize
stbi__get16le(s); // discard reserved
stbi__get16le(s); // discard reserved
stbi__get32le(s); // discard data offset
sz = stbi__get32le(s);
r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
return r;
}
static int stbi__bmp_test(stbi__context* s)
{
int r = stbi__bmp_test_raw(s);
stbi__rewind(s);
return r;
}
// returns 0..31 for the highest set bit
static int stbi__high_bit(unsigned int z)
{
int n = 0;
if (z == 0)
return -1;
if (z >= 0x10000)
{
n += 16;
z >>= 16;
}
if (z >= 0x00100)
{
n += 8;
z >>= 8;
}
if (z >= 0x00010)
{
n += 4;
z >>= 4;
}
if (z >= 0x00004)
{
n += 2;
z >>= 2;
}
if (z >= 0x00002)
{
n += 1; /* >>= 1;*/
}
return n;
}
static int stbi__bitcount(unsigned int a)
{
a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
a = (a + (a >> 8)); // max 16 per 8 bits
a = (a + (a >> 16)); // max 32 per 8 bits
return a & 0xff;
}
// extract an arbitrarily-aligned N-bit value (N=bits)
// from v, and then make it 8-bits long and fractionally
// extend it to full full range.
static int stbi__shiftsigned(unsigned int v, int shift, int bits)
{
static unsigned int mul_table[9] = {
0,
0xff /*0b11111111*/,
0x55 /*0b01010101*/,
0x49 /*0b01001001*/,
0x11 /*0b00010001*/,
0x21 /*0b00100001*/,
0x41 /*0b01000001*/,
0x81 /*0b10000001*/,
0x01 /*0b00000001*/,
};
static unsigned int shift_table[9] = {
0,
0,
0,
1,
0,
2,
4,
6,
0,
};
if (shift < 0)
v <<= -shift;
else
v >>= shift;
STBI_ASSERT(v < 256);
v >>= (8 - bits);
STBI_ASSERT(bits >= 0 && bits <= 8);
return (int)((unsigned)v * mul_table[bits]) >> shift_table[bits];
}
typedef struct
{
int bpp, offset, hsz;
unsigned int mr, mg, mb, ma, all_a;
int extra_read;
} stbi__bmp_data;
static int stbi__bmp_set_mask_defaults(stbi__bmp_data* info, int compress)
{
// BI_BITFIELDS specifies masks explicitly, don't override
if (compress == 3)
return 1;
if (compress == 0)
{
if (info->bpp == 16)
{
info->mr = 31u << 10;
info->mg = 31u << 5;
info->mb = 31u << 0;
}
else if (info->bpp == 32)
{
info->mr = 0xffu << 16;
info->mg = 0xffu << 8;
info->mb = 0xffu << 0;
info->ma = 0xffu << 24;
info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
}
else
{
// otherwise, use defaults, which is all-0
info->mr = info->mg = info->mb = info->ma = 0;
}
return 1;
}
return 0; // error
}
static void* stbi__bmp_parse_header(stbi__context* s, stbi__bmp_data* info)
{
int hsz;
if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M')
return stbi__errpuc("not BMP", "Corrupt BMP");
stbi__get32le(s); // discard filesize
stbi__get16le(s); // discard reserved
stbi__get16le(s); // discard reserved
info->offset = stbi__get32le(s);
info->hsz = hsz = stbi__get32le(s);
info->mr = info->mg = info->mb = info->ma = 0;
info->extra_read = 14;
if (info->offset < 0)
return stbi__errpuc("bad BMP", "bad BMP");
if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124)
return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
if (hsz == 12)
{
s->img_x = stbi__get16le(s);
s->img_y = stbi__get16le(s);
}
else
{
s->img_x = stbi__get32le(s);
s->img_y = stbi__get32le(s);
}
if (stbi__get16le(s) != 1)
return stbi__errpuc("bad BMP", "bad BMP");
info->bpp = stbi__get16le(s);
if (hsz != 12)
{
int compress = stbi__get32le(s);
if (compress == 1 || compress == 2)
return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
if (compress >= 4)
return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes
if (compress == 3 && info->bpp != 16 && info->bpp != 32)
return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
stbi__get32le(s); // discard sizeof
stbi__get32le(s); // discard hres
stbi__get32le(s); // discard vres
stbi__get32le(s); // discard colorsused
stbi__get32le(s); // discard max important
if (hsz == 40 || hsz == 56)
{
if (hsz == 56)
{
stbi__get32le(s);
stbi__get32le(s);
stbi__get32le(s);
stbi__get32le(s);
}
if (info->bpp == 16 || info->bpp == 32)
{
if (compress == 0)
{
stbi__bmp_set_mask_defaults(info, compress);
}
else if (compress == 3)
{
info->mr = stbi__get32le(s);
info->mg = stbi__get32le(s);
info->mb = stbi__get32le(s);
info->extra_read += 12;
// not documented, but generated by photoshop and handled by mspaint
if (info->mr == info->mg && info->mg == info->mb)
{
// ?!?!?
return stbi__errpuc("bad BMP", "bad BMP");
}
}
else
return stbi__errpuc("bad BMP", "bad BMP");
}
}
else
{
// V4/V5 header
int i;
if (hsz != 108 && hsz != 124)
return stbi__errpuc("bad BMP", "bad BMP");
info->mr = stbi__get32le(s);
info->mg = stbi__get32le(s);
info->mb = stbi__get32le(s);
info->ma = stbi__get32le(s);
if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
stbi__bmp_set_mask_defaults(info, compress);
stbi__get32le(s); // discard color space
for (i = 0; i < 12; ++i)
stbi__get32le(s); // discard color space parameters
if (hsz == 124)
{
stbi__get32le(s); // discard rendering intent
stbi__get32le(s); // discard offset of profile data
stbi__get32le(s); // discard size of profile data
stbi__get32le(s); // discard reserved
}
}
}
return (void*)1;
}
static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
stbi_uc* out;
unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a;
stbi_uc pal[256][4];
int psize = 0, i, j, width;
int flip_vertically, pad, target;
stbi__bmp_data info;
STBI_NOTUSED(ri);
info.all_a = 255;
if (stbi__bmp_parse_header(s, &info) == NULL)
return NULL; // error code already set
flip_vertically = ((int)s->img_y) > 0;
s->img_y = abs((int)s->img_y);
if (s->img_y > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
mr = info.mr;
mg = info.mg;
mb = info.mb;
ma = info.ma;
all_a = info.all_a;
if (info.hsz == 12)
{
if (info.bpp < 24)
psize = (info.offset - info.extra_read - 24) / 3;
}
else
{
if (info.bpp < 16)
psize = (info.offset - info.extra_read - info.hsz) >> 2;
}
if (psize == 0)
{
// accept some number of extra bytes after the header, but if the offset points either to before
// the header ends or implies a large amount of extra data, reject the file as malformed
int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);
int header_limit = 1024; // max we actually read is below 256 bytes currently.
int extra_data_limit = 256 * 4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.
if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit)
{
return stbi__errpuc("bad header", "Corrupt BMP");
}
// we established that bytes_read_so_far is positive and sensible.
// the first half of this test rejects offsets that are either too small positives, or
// negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn
// ensures the number computed in the second half of the test can't overflow.
if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit)
{
return stbi__errpuc("bad offset", "Corrupt BMP");
}
else
{
stbi__skip(s, info.offset - bytes_read_so_far);
}
}
if (info.bpp == 24 && ma == 0xff000000)
s->img_n = 3;
else
s->img_n = ma ? 4 : 3;
if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
target = req_comp;
else
target = s->img_n; // if they want monochrome, we'll post-convert
// sanity-check size
if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))
return stbi__errpuc("too large", "Corrupt BMP");
out = (stbi_uc*)stbi__malloc_mad3(target, s->img_x, s->img_y, 0);
if (!out)
return stbi__errpuc("outofmem", "Out of memory");
if (info.bpp < 16)
{
int z = 0;
if (psize == 0 || psize > 256)
{
STBI_FREE(out);
return stbi__errpuc("invalid", "Corrupt BMP");
}
for (i = 0; i < psize; ++i)
{
pal[i][2] = stbi__get8(s);
pal[i][1] = stbi__get8(s);
pal[i][0] = stbi__get8(s);
if (info.hsz != 12)
stbi__get8(s);
pal[i][3] = 255;
}
stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4));
if (info.bpp == 1)
width = (s->img_x + 7) >> 3;
else if (info.bpp == 4)
width = (s->img_x + 1) >> 1;
else if (info.bpp == 8)
width = s->img_x;
else
{
STBI_FREE(out);
return stbi__errpuc("bad bpp", "Corrupt BMP");
}
pad = (-width) & 3;
if (info.bpp == 1)
{
for (j = 0; j < (int)s->img_y; ++j)
{
int bit_offset = 7, v = stbi__get8(s);
for (i = 0; i < (int)s->img_x; ++i)
{
int color = (v >> bit_offset) & 0x1;
out[z++] = pal[color][0];
out[z++] = pal[color][1];
out[z++] = pal[color][2];
if (target == 4)
out[z++] = 255;
if (i + 1 == (int)s->img_x)
break;
if ((--bit_offset) < 0)
{
bit_offset = 7;
v = stbi__get8(s);
}
}
stbi__skip(s, pad);
}
}
else
{
for (j = 0; j < (int)s->img_y; ++j)
{
for (i = 0; i < (int)s->img_x; i += 2)
{
int v = stbi__get8(s), v2 = 0;
if (info.bpp == 4)
{
v2 = v & 15;
v >>= 4;
}
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4)
out[z++] = 255;
if (i + 1 == (int)s->img_x)
break;
v = (info.bpp == 8) ? stbi__get8(s) : v2;
out[z++] = pal[v][0];
out[z++] = pal[v][1];
out[z++] = pal[v][2];
if (target == 4)
out[z++] = 255;
}
stbi__skip(s, pad);
}
}
}
else
{
int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0, acount = 0;
int z = 0;
int easy = 0;
stbi__skip(s, info.offset - info.extra_read - info.hsz);
if (info.bpp == 24)
width = 3 * s->img_x;
else if (info.bpp == 16)
width = 2 * s->img_x;
else /* bpp = 32 and pad = 0 */
width = 0;
pad = (-width) & 3;
if (info.bpp == 24)
{
easy = 1;
}
else if (info.bpp == 32)
{
if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
easy = 2;
}
if (!easy)
{
if (!mr || !mg || !mb)
{
STBI_FREE(out);
return stbi__errpuc("bad masks", "Corrupt BMP");
}
// right shift amt to put high bit in position #7
rshift = stbi__high_bit(mr) - 7;
rcount = stbi__bitcount(mr);
gshift = stbi__high_bit(mg) - 7;
gcount = stbi__bitcount(mg);
bshift = stbi__high_bit(mb) - 7;
bcount = stbi__bitcount(mb);
ashift = stbi__high_bit(ma) - 7;
acount = stbi__bitcount(ma);
if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8)
{
STBI_FREE(out);
return stbi__errpuc("bad masks", "Corrupt BMP");
}
}
for (j = 0; j < (int)s->img_y; ++j)
{
if (easy)
{
for (i = 0; i < (int)s->img_x; ++i)
{
unsigned char a;
out[z + 2] = stbi__get8(s);
out[z + 1] = stbi__get8(s);
out[z + 0] = stbi__get8(s);
z += 3;
a = (easy == 2 ? stbi__get8(s) : 255);
all_a |= a;
if (target == 4)
out[z++] = a;
}
}
else
{
int bpp = info.bpp;
for (i = 0; i < (int)s->img_x; ++i)
{
stbi__uint32 v = (bpp == 16 ? (stbi__uint32)stbi__get16le(s) : stbi__get32le(s));
unsigned int a;
out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
all_a |= a;
if (target == 4)
out[z++] = STBI__BYTECAST(a);
}
}
stbi__skip(s, pad);
}
}
// if alpha channel is all 0s, replace with all 255s
if (target == 4 && all_a == 0)
for (i = 4 * s->img_x * s->img_y - 1; i >= 0; i -= 4)
out[i] = 255;
if (flip_vertically)
{
stbi_uc t;
for (j = 0; j < (int)s->img_y >> 1; ++j)
{
stbi_uc* p1 = out + j * s->img_x * target;
stbi_uc* p2 = out + (s->img_y - 1 - j) * s->img_x * target;
for (i = 0; i < (int)s->img_x * target; ++i)
{
t = p1[i];
p1[i] = p2[i];
p2[i] = t;
}
}
}
if (req_comp && req_comp != target)
{
out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
if (out == NULL)
return out; // stbi__convert_format frees input on failure
}
*x = s->img_x;
*y = s->img_y;
if (comp)
*comp = s->img_n;
return out;
}
#endif
// Targa Truevision - TGA
// by Jonathan Dummer
#ifndef STBI_NO_TGA
// returns STBI_rgb or whatever, 0 on error
static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)
{
// only RGB or RGBA (incl. 16bit) or grey allowed
if (is_rgb16)
*is_rgb16 = 0;
switch (bits_per_pixel)
{
case 8: return STBI_grey;
case 16:
if (is_grey)
return STBI_grey_alpha;
// fallthrough
case 15:
if (is_rgb16)
*is_rgb16 = 1;
return STBI_rgb;
case 24: // fallthrough
case 32: return bits_per_pixel / 8;
default: return 0;
}
}
static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp)
{
int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
int sz, tga_colormap_type;
stbi__get8(s); // discard Offset
tga_colormap_type = stbi__get8(s); // colormap type
if (tga_colormap_type > 1)
{
stbi__rewind(s);
return 0; // only RGB or indexed allowed
}
tga_image_type = stbi__get8(s); // image type
if (tga_colormap_type == 1)
{ // colormapped (paletted) image
if (tga_image_type != 1 && tga_image_type != 9)
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 4); // skip index of first colormap entry and number of entries
sz = stbi__get8(s); // check bits per palette color entry
if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32))
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 4); // skip image x and y origin
tga_colormap_bpp = sz;
}
else
{ // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11))
{
stbi__rewind(s);
return 0; // only RGB or grey allowed, +/- RLE
}
stbi__skip(s, 9); // skip colormap specification and image x/y origin
tga_colormap_bpp = 0;
}
tga_w = stbi__get16le(s);
if (tga_w < 1)
{
stbi__rewind(s);
return 0; // test width
}
tga_h = stbi__get16le(s);
if (tga_h < 1)
{
stbi__rewind(s);
return 0; // test height
}
tga_bits_per_pixel = stbi__get8(s); // bits per pixel
stbi__get8(s); // ignore alpha bits
if (tga_colormap_bpp != 0)
{
if ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16))
{
// when using a colormap, tga_bits_per_pixel is the size of the indexes
// I don't think anything but 8 or 16bit indexes makes sense
stbi__rewind(s);
return 0;
}
tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
}
else
{
tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);
}
if (!tga_comp)
{
stbi__rewind(s);
return 0;
}
if (x)
*x = tga_w;
if (y)
*y = tga_h;
if (comp)
*comp = tga_comp;
return 1; // seems to have passed everything
}
static int stbi__tga_test(stbi__context* s)
{
int res = 0;
int sz, tga_color_type;
stbi__get8(s); // discard Offset
tga_color_type = stbi__get8(s); // color type
if (tga_color_type > 1)
goto errorEnd; // only RGB or indexed allowed
sz = stbi__get8(s); // image type
if (tga_color_type == 1)
{ // colormapped (paletted) image
if (sz != 1 && sz != 9)
goto errorEnd; // colortype 1 demands image type 1 or 9
stbi__skip(s, 4); // skip index of first colormap entry and number of entries
sz = stbi__get8(s); // check bits per palette color entry
if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32))
goto errorEnd;
stbi__skip(s, 4); // skip image x and y origin
}
else
{ // "normal" image w/o colormap
if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11))
goto errorEnd; // only RGB or grey allowed, +/- RLE
stbi__skip(s, 9); // skip colormap specification and image x/y origin
}
if (stbi__get16le(s) < 1)
goto errorEnd; // test width
if (stbi__get16le(s) < 1)
goto errorEnd; // test height
sz = stbi__get8(s); // bits per pixel
if ((tga_color_type == 1) && (sz != 8) && (sz != 16))
goto errorEnd; // for colormapped images, bpp is size of an index
if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32))
goto errorEnd;
res = 1; // if we got this far, everything's good and we can return 1 instead of 0
errorEnd:
stbi__rewind(s);
return res;
}
// read 16bit value and convert to 24bit RGB
static void stbi__tga_read_rgb16(stbi__context* s, stbi_uc* out)
{
stbi__uint16 px = (stbi__uint16)stbi__get16le(s);
stbi__uint16 fiveBitMask = 31;
// we have 3 channels with 5bits each
int r = (px >> 10) & fiveBitMask;
int g = (px >> 5) & fiveBitMask;
int b = px & fiveBitMask;
// Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later
out[0] = (stbi_uc)((r * 255) / 31);
out[1] = (stbi_uc)((g * 255) / 31);
out[2] = (stbi_uc)((b * 255) / 31);
// some people claim that the most significant bit might be used for alpha
// (possibly if an alpha-bit is set in the "image descriptor byte")
// but that only made 16bit test images completely translucent..
// so let's treat all 15 and 16bit TGAs as RGB with no alpha.
}
static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
// read in the TGA header stuff
int tga_offset = stbi__get8(s);
int tga_indexed = stbi__get8(s);
int tga_image_type = stbi__get8(s);
int tga_is_RLE = 0;
int tga_palette_start = stbi__get16le(s);
int tga_palette_len = stbi__get16le(s);
int tga_palette_bits = stbi__get8(s);
int tga_x_origin = stbi__get16le(s);
int tga_y_origin = stbi__get16le(s);
int tga_width = stbi__get16le(s);
int tga_height = stbi__get16le(s);
int tga_bits_per_pixel = stbi__get8(s);
int tga_comp, tga_rgb16 = 0;
int tga_inverted = stbi__get8(s);
// int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)
// image data
unsigned char* tga_data;
unsigned char* tga_palette = NULL;
int i, j;
unsigned char raw_data[4] = { 0 };
int RLE_count = 0;
int RLE_repeating = 0;
int read_next_pixel = 1;
STBI_NOTUSED(ri);
STBI_NOTUSED(tga_x_origin); // @TODO
STBI_NOTUSED(tga_y_origin); // @TODO
if (tga_height > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (tga_width > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
// do a tiny bit of precessing
if (tga_image_type >= 8)
{
tga_image_type -= 8;
tga_is_RLE = 1;
}
tga_inverted = 1 - ((tga_inverted >> 5) & 1);
// If I'm paletted, then I'll use the number of bits from the palette
if (tga_indexed)
tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
else
tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
// tga info
*x = tga_width;
*y = tga_height;
if (comp)
*comp = tga_comp;
if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))
return stbi__errpuc("too large", "Corrupt TGA");
tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);
if (!tga_data)
return stbi__errpuc("outofmem", "Out of memory");
// skip to the data's starting position (offset usually = 0)
stbi__skip(s, tga_offset);
if (!tga_indexed && !tga_is_RLE && !tga_rgb16)
{
for (i = 0; i < tga_height; ++i)
{
int row = tga_inverted ? tga_height - i - 1 : i;
stbi_uc* tga_row = tga_data + row * tga_width * tga_comp;
stbi__getn(s, tga_row, tga_width * tga_comp);
}
}
else
{
// do I need to load a palette?
if (tga_indexed)
{
if (tga_palette_len == 0)
{ /* you have to have at least one entry! */
STBI_FREE(tga_data);
return stbi__errpuc("bad palette", "Corrupt TGA");
}
// any data to skip? (offset usually = 0)
stbi__skip(s, tga_palette_start);
// load the palette
tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);
if (!tga_palette)
{
STBI_FREE(tga_data);
return stbi__errpuc("outofmem", "Out of memory");
}
if (tga_rgb16)
{
stbi_uc* pal_entry = tga_palette;
STBI_ASSERT(tga_comp == STBI_rgb);
for (i = 0; i < tga_palette_len; ++i)
{
stbi__tga_read_rgb16(s, pal_entry);
pal_entry += tga_comp;
}
}
else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp))
{
STBI_FREE(tga_data);
STBI_FREE(tga_palette);
return stbi__errpuc("bad palette", "Corrupt TGA");
}
}
// load the data
for (i = 0; i < tga_width * tga_height; ++i)
{
// if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
if (tga_is_RLE)
{
if (RLE_count == 0)
{
// yep, get the next byte as a RLE command
int RLE_cmd = stbi__get8(s);
RLE_count = 1 + (RLE_cmd & 127);
RLE_repeating = RLE_cmd >> 7;
read_next_pixel = 1;
}
else if (!RLE_repeating)
{
read_next_pixel = 1;
}
}
else
{
read_next_pixel = 1;
}
// OK, if I need to read a pixel, do it now
if (read_next_pixel)
{
// load however much data we did have
if (tga_indexed)
{
// read in index, then perform the lookup
int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
if (pal_idx >= tga_palette_len)
{
// invalid index
pal_idx = 0;
}
pal_idx *= tga_comp;
for (j = 0; j < tga_comp; ++j)
{
raw_data[j] = tga_palette[pal_idx + j];
}
}
else if (tga_rgb16)
{
STBI_ASSERT(tga_comp == STBI_rgb);
stbi__tga_read_rgb16(s, raw_data);
}
else
{
// read in the data raw
for (j = 0; j < tga_comp; ++j)
{
raw_data[j] = stbi__get8(s);
}
}
// clear the reading flag for the next pixel
read_next_pixel = 0;
} // end of reading a pixel
// copy data
for (j = 0; j < tga_comp; ++j)
tga_data[i * tga_comp + j] = raw_data[j];
// in case we're in RLE mode, keep counting down
--RLE_count;
}
// do I need to invert the image?
if (tga_inverted)
{
for (j = 0; j * 2 < tga_height; ++j)
{
int index1 = j * tga_width * tga_comp;
int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
for (i = tga_width * tga_comp; i > 0; --i)
{
unsigned char temp = tga_data[index1];
tga_data[index1] = tga_data[index2];
tga_data[index2] = temp;
++index1;
++index2;
}
}
}
// clear my palette, if I had one
if (tga_palette != NULL)
{
STBI_FREE(tga_palette);
}
}
// swap RGB - if the source data was RGB16, it already is in the right order
if (tga_comp >= 3 && !tga_rgb16)
{
unsigned char* tga_pixel = tga_data;
for (i = 0; i < tga_width * tga_height; ++i)
{
unsigned char temp = tga_pixel[0];
tga_pixel[0] = tga_pixel[2];
tga_pixel[2] = temp;
tga_pixel += tga_comp;
}
}
// convert to target component count
if (req_comp && req_comp != tga_comp)
tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
// the things I do to get rid of an error message, and yet keep
// Microsoft's C compilers happy... [8^(
tga_palette_start = tga_palette_len = tga_palette_bits =
tga_x_origin = tga_y_origin = 0;
STBI_NOTUSED(tga_palette_start);
// OK, done
return tga_data;
}
#endif
// *************************************************************************************************
// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
#ifndef STBI_NO_PSD
static int stbi__psd_test(stbi__context* s)
{
int r = (stbi__get32be(s) == 0x38425053);
stbi__rewind(s);
return r;
}
static int stbi__psd_decode_rle(stbi__context* s, stbi_uc* p, int pixelCount)
{
int count, nleft, len;
count = 0;
while ((nleft = pixelCount - count) > 0)
{
len = stbi__get8(s);
if (len == 128)
{
// No-op.
}
else if (len < 128)
{
// Copy next len+1 bytes literally.
len++;
if (len > nleft)
return 0; // corrupt data
count += len;
while (len)
{
*p = stbi__get8(s);
p += 4;
len--;
}
}
else if (len > 128)
{
stbi_uc val;
// Next -len+1 bytes in the dest are replicated from next source byte.
// (Interpret len as a negative 8-bit int.)
len = 257 - len;
if (len > nleft)
return 0; // corrupt data
val = stbi__get8(s);
count += len;
while (len)
{
*p = val;
p += 4;
len--;
}
}
}
return 1;
}
static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc)
{
int pixelCount;
int channelCount, compression;
int channel, i;
int bitdepth;
int w, h;
stbi_uc* out;
STBI_NOTUSED(ri);
// Check identifier
if (stbi__get32be(s) != 0x38425053) // "8BPS"
return stbi__errpuc("not PSD", "Corrupt PSD image");
// Check file type version.
if (stbi__get16be(s) != 1)
return stbi__errpuc("wrong version", "Unsupported version of PSD image");
// Skip 6 reserved bytes.
stbi__skip(s, 6);
// Read the number of channels (R, G, B, A, etc).
channelCount = stbi__get16be(s);
if (channelCount < 0 || channelCount > 16)
return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
// Read the rows and columns of the image.
h = stbi__get32be(s);
w = stbi__get32be(s);
if (h > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (w > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
// Make sure the depth is 8 bits.
bitdepth = stbi__get16be(s);
if (bitdepth != 8 && bitdepth != 16)
return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
// Make sure the color mode is RGB.
// Valid options are:
// 0: Bitmap
// 1: Grayscale
// 2: Indexed color
// 3: RGB color
// 4: CMYK color
// 7: Multichannel
// 8: Duotone
// 9: Lab color
if (stbi__get16be(s) != 3)
return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
// Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
stbi__skip(s, stbi__get32be(s));
// Skip the image resources. (resolution, pen tool paths, etc)
stbi__skip(s, stbi__get32be(s));
// Skip the reserved data.
stbi__skip(s, stbi__get32be(s));
// Find out if the data is compressed.
// Known values:
// 0: no compression
// 1: RLE compressed
compression = stbi__get16be(s);
if (compression > 1)
return stbi__errpuc("bad compression", "PSD has an unknown compression format");
// Check size
if (!stbi__mad3sizes_valid(4, w, h, 0))
return stbi__errpuc("too large", "Corrupt PSD");
// Create the destination image.
if (!compression && bitdepth == 16 && bpc == 16)
{
out = (stbi_uc*)stbi__malloc_mad3(8, w, h, 0);
ri->bits_per_channel = 16;
}
else
out = (stbi_uc*)stbi__malloc(4 * w * h);
if (!out)
return stbi__errpuc("outofmem", "Out of memory");
pixelCount = w * h;
// Initialize the data to zero.
//memset( out, 0, pixelCount * 4 );
// Finally, the image data.
if (compression)
{
// RLE as used by .PSD and .TIFF
// Loop until you get the number of unpacked bytes you are expecting:
// Read the next source byte into n.
// If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
// Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
// Else if n is 128, noop.
// Endloop
// The RLE-compressed data is preceded by a 2-byte data count for each row in the data,
// which we're going to just skip.
stbi__skip(s, h * channelCount * 2);
// Read the RLE data by channel.
for (channel = 0; channel < 4; channel++)
{
stbi_uc* p;
p = out + channel;
if (channel >= channelCount)
{
// Fill this channel with default data.
for (i = 0; i < pixelCount; i++, p += 4)
*p = (channel == 3 ? 255 : 0);
}
else
{
// Read the RLE data.
if (!stbi__psd_decode_rle(s, p, pixelCount))
{
STBI_FREE(out);
return stbi__errpuc("corrupt", "bad RLE data");
}
}
}
}
else
{
// We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
// where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.
// Read the data by channel.
for (channel = 0; channel < 4; channel++)
{
if (channel >= channelCount)
{
// Fill this channel with default data.
if (bitdepth == 16 && bpc == 16)
{
stbi__uint16* q = ((stbi__uint16*)out) + channel;
stbi__uint16 val = channel == 3 ? 65535 : 0;
for (i = 0; i < pixelCount; i++, q += 4)
*q = val;
}
else
{
stbi_uc* p = out + channel;
stbi_uc val = channel == 3 ? 255 : 0;
for (i = 0; i < pixelCount; i++, p += 4)
*p = val;
}
}
else
{
if (ri->bits_per_channel == 16)
{ // output bpc
stbi__uint16* q = ((stbi__uint16*)out) + channel;
for (i = 0; i < pixelCount; i++, q += 4)
*q = (stbi__uint16)stbi__get16be(s);
}
else
{
stbi_uc* p = out + channel;
if (bitdepth == 16)
{ // input bpc
for (i = 0; i < pixelCount; i++, p += 4)
*p = (stbi_uc)(stbi__get16be(s) >> 8);
}
else
{
for (i = 0; i < pixelCount; i++, p += 4)
*p = stbi__get8(s);
}
}
}
}
}
// remove weird white matte from PSD
if (channelCount >= 4)
{
if (ri->bits_per_channel == 16)
{
for (i = 0; i < w * h; ++i)
{
stbi__uint16* pixel = (stbi__uint16*)out + 4 * i;
if (pixel[3] != 0 && pixel[3] != 65535)
{
float a = pixel[3] / 65535.0f;
float ra = 1.0f / a;
float inv_a = 65535.0f * (1 - ra);
pixel[0] = (stbi__uint16)(pixel[0] * ra + inv_a);
pixel[1] = (stbi__uint16)(pixel[1] * ra + inv_a);
pixel[2] = (stbi__uint16)(pixel[2] * ra + inv_a);
}
}
}
else
{
for (i = 0; i < w * h; ++i)
{
unsigned char* pixel = out + 4 * i;
if (pixel[3] != 0 && pixel[3] != 255)
{
float a = pixel[3] / 255.0f;
float ra = 1.0f / a;
float inv_a = 255.0f * (1 - ra);
pixel[0] = (unsigned char)(pixel[0] * ra + inv_a);
pixel[1] = (unsigned char)(pixel[1] * ra + inv_a);
pixel[2] = (unsigned char)(pixel[2] * ra + inv_a);
}
}
}
}
// convert to desired output format
if (req_comp && req_comp != 4)
{
if (ri->bits_per_channel == 16)
out = (stbi_uc*)stbi__convert_format16((stbi__uint16*)out, 4, req_comp, w, h);
else
out = stbi__convert_format(out, 4, req_comp, w, h);
if (out == NULL)
return out; // stbi__convert_format frees input on failure
}
if (comp)
*comp = 4;
*y = h;
*x = w;
return out;
}
#endif
// *************************************************************************************************
// Softimage PIC loader
// by Tom Seddon
//
// See path_to_url
// See path_to_url~pbourke/dataformats/softimagepic/
#ifndef STBI_NO_PIC
static int stbi__pic_is4(stbi__context* s, const char* str)
{
int i;
for (i = 0; i < 4; ++i)
if (stbi__get8(s) != (stbi_uc)str[i])
return 0;
return 1;
}
static int stbi__pic_test_core(stbi__context* s)
{
int i;
if (!stbi__pic_is4(s, "\x53\x80\xF6\x34"))
return 0;
for (i = 0; i < 84; ++i)
stbi__get8(s);
if (!stbi__pic_is4(s, "PICT"))
return 0;
return 1;
}
typedef struct
{
stbi_uc size, type, channel;
} stbi__pic_packet;
static stbi_uc* stbi__readval(stbi__context* s, int channel, stbi_uc* dest)
{
int mask = 0x80, i;
for (i = 0; i < 4; ++i, mask >>= 1)
{
if (channel & mask)
{
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "PIC file too short");
dest[i] = stbi__get8(s);
}
}
return dest;
}
static void stbi__copyval(int channel, stbi_uc* dest, const stbi_uc* src)
{
int mask = 0x80, i;
for (i = 0; i < 4; ++i, mask >>= 1)
if (channel & mask)
dest[i] = src[i];
}
static stbi_uc* stbi__pic_load_core(stbi__context* s, int width, int height, int* comp, stbi_uc* result)
{
int act_comp = 0, num_packets = 0, y, chained;
stbi__pic_packet packets[10];
// this will (should...) cater for even some bizarre stuff like having data
// for the same channel in multiple packets.
do
{
stbi__pic_packet* packet;
if (num_packets == sizeof(packets) / sizeof(packets[0]))
return stbi__errpuc("bad format", "too many packets");
packet = &packets[num_packets++];
chained = stbi__get8(s);
packet->size = stbi__get8(s);
packet->type = stbi__get8(s);
packet->channel = stbi__get8(s);
act_comp |= packet->channel;
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "file too short (reading packets)");
if (packet->size != 8)
return stbi__errpuc("bad format", "packet isn't 8bpp");
} while (chained);
*comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
for (y = 0; y < height; ++y)
{
int packet_idx;
for (packet_idx = 0; packet_idx < num_packets; ++packet_idx)
{
stbi__pic_packet* packet = &packets[packet_idx];
stbi_uc* dest = result + y * width * 4;
switch (packet->type)
{
default:
return stbi__errpuc("bad format", "packet has bad compression type");
case 0:
{ //uncompressed
int x;
for (x = 0; x < width; ++x, dest += 4)
if (!stbi__readval(s, packet->channel, dest))
return 0;
break;
}
case 1: //Pure RLE
{
int left = width, i;
while (left > 0)
{
stbi_uc count, value[4];
count = stbi__get8(s);
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "file too short (pure read count)");
if (count > left)
count = (stbi_uc)left;
if (!stbi__readval(s, packet->channel, value))
return 0;
for (i = 0; i < count; ++i, dest += 4)
stbi__copyval(packet->channel, dest, value);
left -= count;
}
}
break;
case 2:
{ //Mixed RLE
int left = width;
while (left > 0)
{
int count = stbi__get8(s), i;
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "file too short (mixed read count)");
if (count >= 128)
{ // Repeated
stbi_uc value[4];
if (count == 128)
count = stbi__get16be(s);
else
count -= 127;
if (count > left)
return stbi__errpuc("bad file", "scanline overrun");
if (!stbi__readval(s, packet->channel, value))
return 0;
for (i = 0; i < count; ++i, dest += 4)
stbi__copyval(packet->channel, dest, value);
}
else
{ // Raw
++count;
if (count > left)
return stbi__errpuc("bad file", "scanline overrun");
for (i = 0; i < count; ++i, dest += 4)
if (!stbi__readval(s, packet->channel, dest))
return 0;
}
left -= count;
}
break;
}
}
}
}
return result;
}
static void* stbi__pic_load(stbi__context* s, int* px, int* py, int* comp, int req_comp, stbi__result_info* ri)
{
stbi_uc* result;
int i, x, y, internal_comp;
STBI_NOTUSED(ri);
if (!comp)
comp = &internal_comp;
for (i = 0; i < 92; ++i)
stbi__get8(s);
x = stbi__get16be(s);
y = stbi__get16be(s);
if (y > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (x > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "file too short (pic header)");
if (!stbi__mad3sizes_valid(x, y, 4, 0))
return stbi__errpuc("too large", "PIC image too large to decode");
stbi__get32be(s); //skip `ratio'
stbi__get16be(s); //skip `fields'
stbi__get16be(s); //skip `pad'
// intermediate buffer is RGBA
result = (stbi_uc*)stbi__malloc_mad3(x, y, 4, 0);
if (!result)
return stbi__errpuc("outofmem", "Out of memory");
memset(result, 0xff, x * y * 4);
if (!stbi__pic_load_core(s, x, y, comp, result))
{
STBI_FREE(result);
result = 0;
}
*px = x;
*py = y;
if (req_comp == 0)
req_comp = *comp;
result = stbi__convert_format(result, 4, req_comp, x, y);
return result;
}
static int stbi__pic_test(stbi__context* s)
{
int r = stbi__pic_test_core(s);
stbi__rewind(s);
return r;
}
#endif
// *************************************************************************************************
// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
#ifndef STBI_NO_GIF
typedef struct
{
stbi__int16 prefix;
stbi_uc first;
stbi_uc suffix;
} stbi__gif_lzw;
typedef struct
{
int w, h;
stbi_uc* out; // output buffer (always 4 components)
stbi_uc* background; // The current "background" as far as a gif is concerned
stbi_uc* history;
int flags, bgindex, ratio, transparent, eflags;
stbi_uc pal[256][4];
stbi_uc lpal[256][4];
stbi__gif_lzw codes[8192];
stbi_uc* color_table;
int parse, step;
int lflags;
int start_x, start_y;
int max_x, max_y;
int cur_x, cur_y;
int line_size;
int delay;
} stbi__gif;
static int stbi__gif_test_raw(stbi__context* s)
{
int sz;
if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
return 0;
sz = stbi__get8(s);
if (sz != '9' && sz != '7')
return 0;
if (stbi__get8(s) != 'a')
return 0;
return 1;
}
static int stbi__gif_test(stbi__context* s)
{
int r = stbi__gif_test_raw(s);
stbi__rewind(s);
return r;
}
static void stbi__gif_parse_colortable(stbi__context* s, stbi_uc pal[256][4], int num_entries, int transp)
{
int i;
for (i = 0; i < num_entries; ++i)
{
pal[i][2] = stbi__get8(s);
pal[i][1] = stbi__get8(s);
pal[i][0] = stbi__get8(s);
pal[i][3] = transp == i ? 0 : 255;
}
}
static int stbi__gif_header(stbi__context* s, stbi__gif* g, int* comp, int is_info)
{
stbi_uc version;
if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
return stbi__err("not GIF", "Corrupt GIF");
version = stbi__get8(s);
if (version != '7' && version != '9')
return stbi__err("not GIF", "Corrupt GIF");
if (stbi__get8(s) != 'a')
return stbi__err("not GIF", "Corrupt GIF");
stbi__g_failure_reason = "";
g->w = stbi__get16le(s);
g->h = stbi__get16le(s);
g->flags = stbi__get8(s);
g->bgindex = stbi__get8(s);
g->ratio = stbi__get8(s);
g->transparent = -1;
if (g->w > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
if (g->h > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
if (comp != 0)
*comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
if (is_info)
return 1;
if (g->flags & 0x80)
stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1);
return 1;
}
static int stbi__gif_info_raw(stbi__context* s, int* x, int* y, int* comp)
{
stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif));
if (!g)
return stbi__err("outofmem", "Out of memory");
if (!stbi__gif_header(s, g, comp, 1))
{
STBI_FREE(g);
stbi__rewind(s);
return 0;
}
if (x)
*x = g->w;
if (y)
*y = g->h;
STBI_FREE(g);
return 1;
}
static void stbi__out_gif_code(stbi__gif* g, stbi__uint16 code)
{
stbi_uc *p, *c;
int idx;
// recurse to decode the prefixes, since the linked-list is backwards,
// and working backwards through an interleaved image would be nasty
if (g->codes[code].prefix >= 0)
stbi__out_gif_code(g, g->codes[code].prefix);
if (g->cur_y >= g->max_y)
return;
idx = g->cur_x + g->cur_y;
p = &g->out[idx];
g->history[idx / 4] = 1;
c = &g->color_table[g->codes[code].suffix * 4];
if (c[3] > 128)
{ // don't render transparent pixels;
p[0] = c[2];
p[1] = c[1];
p[2] = c[0];
p[3] = c[3];
}
g->cur_x += 4;
if (g->cur_x >= g->max_x)
{
g->cur_x = g->start_x;
g->cur_y += g->step;
while (g->cur_y >= g->max_y && g->parse > 0)
{
g->step = (1 << g->parse) * g->line_size;
g->cur_y = g->start_y + (g->step >> 1);
--g->parse;
}
}
}
static stbi_uc* stbi__process_gif_raster(stbi__context* s, stbi__gif* g)
{
stbi_uc lzw_cs;
stbi__int32 len, init_code;
stbi__uint32 first;
stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
stbi__gif_lzw* p;
lzw_cs = stbi__get8(s);
if (lzw_cs > 12)
return NULL;
clear = 1 << lzw_cs;
first = 1;
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
bits = 0;
valid_bits = 0;
for (init_code = 0; init_code < clear; init_code++)
{
g->codes[init_code].prefix = -1;
g->codes[init_code].first = (stbi_uc)init_code;
g->codes[init_code].suffix = (stbi_uc)init_code;
}
// support no starting clear code
avail = clear + 2;
oldcode = -1;
len = 0;
for (;;)
{
if (valid_bits < codesize)
{
if (len == 0)
{
len = stbi__get8(s); // start new block
if (len == 0)
return g->out;
}
--len;
bits |= (stbi__int32)stbi__get8(s) << valid_bits;
valid_bits += 8;
}
else
{
stbi__int32 code = bits & codemask;
bits >>= codesize;
valid_bits -= codesize;
// @OPTIMIZE: is there some way we can accelerate the non-clear path?
if (code == clear)
{ // clear code
codesize = lzw_cs + 1;
codemask = (1 << codesize) - 1;
avail = clear + 2;
oldcode = -1;
first = 0;
}
else if (code == clear + 1)
{ // end of stream code
stbi__skip(s, len);
while ((len = stbi__get8(s)) > 0)
stbi__skip(s, len);
return g->out;
}
else if (code <= avail)
{
if (first)
{
return stbi__errpuc("no clear code", "Corrupt GIF");
}
if (oldcode >= 0)
{
p = &g->codes[avail++];
if (avail > 8192)
{
return stbi__errpuc("too many codes", "Corrupt GIF");
}
p->prefix = (stbi__int16)oldcode;
p->first = g->codes[oldcode].first;
p->suffix = (code == avail) ? p->first : g->codes[code].first;
}
else if (code == avail)
return stbi__errpuc("illegal code in raster", "Corrupt GIF");
stbi__out_gif_code(g, (stbi__uint16)code);
if ((avail & codemask) == 0 && avail <= 0x0FFF)
{
codesize++;
codemask = (1 << codesize) - 1;
}
oldcode = code;
}
else
{
return stbi__errpuc("illegal code in raster", "Corrupt GIF");
}
}
}
}
// this function is designed to support animated gifs, although stb_image doesn't support it
// two back is the image from two frames ago, used for a very specific disposal format
static stbi_uc* stbi__gif_load_next(stbi__context* s, stbi__gif* g, int* comp, int req_comp, stbi_uc* two_back)
{
int dispose;
int first_frame;
int pi;
int pcount;
STBI_NOTUSED(req_comp);
// on first frame, any non-written pixels get the background colour (non-transparent)
first_frame = 0;
if (g->out == 0)
{
if (!stbi__gif_header(s, g, comp, 0))
return 0; // stbi__g_failure_reason set by stbi__gif_header
if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))
return stbi__errpuc("too large", "GIF image is too large");
pcount = g->w * g->h;
g->out = (stbi_uc*)stbi__malloc(4 * pcount);
g->background = (stbi_uc*)stbi__malloc(4 * pcount);
g->history = (stbi_uc*)stbi__malloc(pcount);
if (!g->out || !g->background || !g->history)
return stbi__errpuc("outofmem", "Out of memory");
// image is treated as "transparent" at the start - ie, nothing overwrites the current background;
// background colour is only used for pixels that are not rendered first frame, after that "background"
// color refers to the color that was there the previous frame.
memset(g->out, 0x00, 4 * pcount);
memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent)
memset(g->history, 0x00, pcount); // pixels that were affected previous frame
first_frame = 1;
}
else
{
// second frame - how do we dispose of the previous one?
dispose = (g->eflags & 0x1C) >> 2;
pcount = g->w * g->h;
if ((dispose == 3) && (two_back == 0))
{
dispose = 2; // if I don't have an image to revert back to, default to the old background
}
if (dispose == 3)
{ // use previous graphic
for (pi = 0; pi < pcount; ++pi)
{
if (g->history[pi])
{
memcpy(&g->out[pi * 4], &two_back[pi * 4], 4);
}
}
}
else if (dispose == 2)
{
// restore what was changed last frame to background before that frame;
for (pi = 0; pi < pcount; ++pi)
{
if (g->history[pi])
{
memcpy(&g->out[pi * 4], &g->background[pi * 4], 4);
}
}
}
else
{
// This is a non-disposal case eithe way, so just
// leave the pixels as is, and they will become the new background
// 1: do not dispose
// 0: not specified.
}
// background is what out is after the undoing of the previou frame;
memcpy(g->background, g->out, 4 * g->w * g->h);
}
// clear my history;
memset(g->history, 0x00, g->w * g->h); // pixels that were affected previous frame
for (;;)
{
int tag = stbi__get8(s);
switch (tag)
{
case 0x2C: /* Image Descriptor */
{
stbi__int32 x, y, w, h;
stbi_uc* o;
x = stbi__get16le(s);
y = stbi__get16le(s);
w = stbi__get16le(s);
h = stbi__get16le(s);
if (((x + w) > (g->w)) || ((y + h) > (g->h)))
return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
g->line_size = g->w * 4;
g->start_x = x * 4;
g->start_y = y * g->line_size;
g->max_x = g->start_x + w * 4;
g->max_y = g->start_y + h * g->line_size;
g->cur_x = g->start_x;
g->cur_y = g->start_y;
// if the width of the specified rectangle is 0, that means
// we may not see *any* pixels or the image is malformed;
// to make sure this is caught, move the current y down to
// max_y (which is what out_gif_code checks).
if (w == 0)
g->cur_y = g->max_y;
g->lflags = stbi__get8(s);
if (g->lflags & 0x40)
{
g->step = 8 * g->line_size; // first interlaced spacing
g->parse = 3;
}
else
{
g->step = g->line_size;
g->parse = 0;
}
if (g->lflags & 0x80)
{
stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
g->color_table = (stbi_uc*)g->lpal;
}
else if (g->flags & 0x80)
{
g->color_table = (stbi_uc*)g->pal;
}
else
return stbi__errpuc("missing color table", "Corrupt GIF");
o = stbi__process_gif_raster(s, g);
if (!o)
return NULL;
// if this was the first frame,
pcount = g->w * g->h;
if (first_frame && (g->bgindex > 0))
{
// if first frame, any pixel not drawn to gets the background color
for (pi = 0; pi < pcount; ++pi)
{
if (g->history[pi] == 0)
{
g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be;
memcpy(&g->out[pi * 4], &g->pal[g->bgindex], 4);
}
}
}
return o;
}
case 0x21: // Comment Extension.
{
int len;
int ext = stbi__get8(s);
if (ext == 0xF9)
{ // Graphic Control Extension.
len = stbi__get8(s);
if (len == 4)
{
g->eflags = stbi__get8(s);
g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths.
// unset old transparent
if (g->transparent >= 0)
{
g->pal[g->transparent][3] = 255;
}
if (g->eflags & 0x01)
{
g->transparent = stbi__get8(s);
if (g->transparent >= 0)
{
g->pal[g->transparent][3] = 0;
}
}
else
{
// don't need transparent
stbi__skip(s, 1);
g->transparent = -1;
}
}
else
{
stbi__skip(s, len);
break;
}
}
while ((len = stbi__get8(s)) != 0)
{
stbi__skip(s, len);
}
break;
}
case 0x3B: // gif stream termination code
return (stbi_uc*)s; // using '1' causes warning on some compilers
default:
return stbi__errpuc("unknown code", "Corrupt GIF");
}
}
}
static void* stbi__load_gif_main_outofmem(stbi__gif* g, stbi_uc* out, int** delays)
{
STBI_FREE(g->out);
STBI_FREE(g->history);
STBI_FREE(g->background);
if (out)
STBI_FREE(out);
if (delays && *delays)
STBI_FREE(*delays);
return stbi__errpuc("outofmem", "Out of memory");
}
static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, int* z, int* comp, int req_comp)
{
if (stbi__gif_test(s))
{
int layers = 0;
stbi_uc* u = 0;
stbi_uc* out = 0;
stbi_uc* two_back = 0;
stbi__gif g;
int stride;
int out_size = 0;
int delays_size = 0;
STBI_NOTUSED(out_size);
STBI_NOTUSED(delays_size);
memset(&g, 0, sizeof(g));
if (delays)
{
*delays = 0;
}
do
{
u = stbi__gif_load_next(s, &g, comp, req_comp, two_back);
if (u == (stbi_uc*)s)
u = 0; // end of animated gif marker
if (u)
{
*x = g.w;
*y = g.h;
++layers;
stride = g.w * g.h * 4;
if (out)
{
void* tmp = (stbi_uc*)STBI_REALLOC_SIZED(out, out_size, layers * stride);
if (!tmp)
return stbi__load_gif_main_outofmem(&g, out, delays);
else
{
out = (stbi_uc*)tmp;
out_size = layers * stride;
}
if (delays)
{
int* new_delays = (int*)STBI_REALLOC_SIZED(*delays, delays_size, sizeof(int) * layers);
if (!new_delays)
return stbi__load_gif_main_outofmem(&g, out, delays);
*delays = new_delays;
delays_size = layers * sizeof(int);
}
}
else
{
out = (stbi_uc*)stbi__malloc(layers * stride);
if (!out)
return stbi__load_gif_main_outofmem(&g, out, delays);
out_size = layers * stride;
if (delays)
{
*delays = (int*)stbi__malloc(layers * sizeof(int));
if (!*delays)
return stbi__load_gif_main_outofmem(&g, out, delays);
delays_size = layers * sizeof(int);
}
}
memcpy(out + ((layers - 1) * stride), u, stride);
if (layers >= 2)
{
two_back = out - 2 * stride;
}
if (delays)
{
(*delays)[layers - 1U] = g.delay;
}
}
} while (u != 0);
// free temp buffer;
STBI_FREE(g.out);
STBI_FREE(g.history);
STBI_FREE(g.background);
// do the final conversion after loading everything;
if (req_comp && req_comp != 4)
out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h);
*z = layers;
return out;
}
else
{
return stbi__errpuc("not GIF", "Image was not as a gif type.");
}
}
static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
stbi_uc* u = 0;
stbi__gif g;
memset(&g, 0, sizeof(g));
STBI_NOTUSED(ri);
u = stbi__gif_load_next(s, &g, comp, req_comp, 0);
if (u == (stbi_uc*)s)
u = 0; // end of animated gif marker
if (u)
{
*x = g.w;
*y = g.h;
// moved conversion to after successful load so that the same
// can be done for multiple frames.
if (req_comp && req_comp != 4)
u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
}
else if (g.out)
{
// if there was an error and we allocated an image buffer, free it!
STBI_FREE(g.out);
}
// free buffers needed for multiple frame loading;
STBI_FREE(g.history);
STBI_FREE(g.background);
return u;
}
static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp)
{
return stbi__gif_info_raw(s, x, y, comp);
}
#endif
// *************************************************************************************************
// Radiance RGBE HDR loader
// originally by Nicolas Schulz
#ifndef STBI_NO_HDR
static int stbi__hdr_test_core(stbi__context* s, const char* signature)
{
int i;
for (i = 0; signature[i]; ++i)
if (stbi__get8(s) != signature[i])
return 0;
stbi__rewind(s);
return 1;
}
static int stbi__hdr_test(stbi__context* s)
{
int r = stbi__hdr_test_core(s, "#?RADIANCE\n");
stbi__rewind(s);
if (!r)
{
r = stbi__hdr_test_core(s, "#?RGBE\n");
stbi__rewind(s);
}
return r;
}
#define STBI__HDR_BUFLEN 1024
static char* stbi__hdr_gettoken(stbi__context* z, char* buffer)
{
int len = 0;
char c = '\0';
c = (char)stbi__get8(z);
while (!stbi__at_eof(z) && c != '\n')
{
buffer[len++] = c;
if (len == STBI__HDR_BUFLEN - 1)
{
// flush to end of line
while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
;
break;
}
c = (char)stbi__get8(z);
}
buffer[len] = 0;
return buffer;
}
static void stbi__hdr_convert(float* output, stbi_uc* input, int req_comp)
{
if (input[3] != 0)
{
float f1;
// Exponent
f1 = (float)ldexp(1.0f, input[3] - (int)(128 + 8));
if (req_comp <= 2)
output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
else
{
output[0] = input[0] * f1;
output[1] = input[1] * f1;
output[2] = input[2] * f1;
}
if (req_comp == 2)
output[1] = 1;
if (req_comp == 4)
output[3] = 1;
}
else
{
switch (req_comp)
{
case 4: output[3] = 1; /* fallthrough */
case 3:
output[0] = output[1] = output[2] = 0;
break;
case 2: output[1] = 1; /* fallthrough */
case 1:
output[0] = 0;
break;
}
}
}
static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
char buffer[STBI__HDR_BUFLEN];
char* token;
int valid = 0;
int width, height;
stbi_uc* scanline;
float* hdr_data;
int len;
unsigned char count, value;
int i, j, k, c1, c2, z;
const char* headerToken;
STBI_NOTUSED(ri);
// Check identifier
headerToken = stbi__hdr_gettoken(s, buffer);
if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)
return stbi__errpf("not HDR", "Corrupt HDR image");
// Parse header
for (;;)
{
token = stbi__hdr_gettoken(s, buffer);
if (token[0] == 0)
break;
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0)
valid = 1;
}
if (!valid)
return stbi__errpf("unsupported format", "Unsupported HDR format");
// Parse width and height
// can't use sscanf() if we're not using stdio!
token = stbi__hdr_gettoken(s, buffer);
if (strncmp(token, "-Y ", 3))
return stbi__errpf("unsupported data layout", "Unsupported HDR format");
token += 3;
height = (int)strtol(token, &token, 10);
while (*token == ' ')
++token;
if (strncmp(token, "+X ", 3))
return stbi__errpf("unsupported data layout", "Unsupported HDR format");
token += 3;
width = (int)strtol(token, NULL, 10);
if (height > STBI_MAX_DIMENSIONS)
return stbi__errpf("too large", "Very large image (corrupt?)");
if (width > STBI_MAX_DIMENSIONS)
return stbi__errpf("too large", "Very large image (corrupt?)");
*x = width;
*y = height;
if (comp)
*comp = 3;
if (req_comp == 0)
req_comp = 3;
if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))
return stbi__errpf("too large", "HDR image is too large");
// Read data
hdr_data = (float*)stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);
if (!hdr_data)
return stbi__errpf("outofmem", "Out of memory");
// Load image data
// image data is stored as some number of sca
if (width < 8 || width >= 32768)
{
// Read flat data
for (j = 0; j < height; ++j)
{
for (i = 0; i < width; ++i)
{
stbi_uc rgbe[4];
main_decode_loop:
stbi__getn(s, rgbe, 4);
stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
}
}
}
else
{
// Read RLE-encoded data
scanline = NULL;
for (j = 0; j < height; ++j)
{
c1 = stbi__get8(s);
c2 = stbi__get8(s);
len = stbi__get8(s);
if (c1 != 2 || c2 != 2 || (len & 0x80))
{
// not run-length encoded, so we have to actually use THIS data as a decoded
// pixel (note this can't be a valid pixel--one of RGB must be >= 128)
stbi_uc rgbe[4];
rgbe[0] = (stbi_uc)c1;
rgbe[1] = (stbi_uc)c2;
rgbe[2] = (stbi_uc)len;
rgbe[3] = (stbi_uc)stbi__get8(s);
stbi__hdr_convert(hdr_data, rgbe, req_comp);
i = 1;
j = 0;
STBI_FREE(scanline);
goto main_decode_loop; // yes, this makes no sense
}
len <<= 8;
len |= stbi__get8(s);
if (len != width)
{
STBI_FREE(hdr_data);
STBI_FREE(scanline);
return stbi__errpf("invalid decoded scanline length", "corrupt HDR");
}
if (scanline == NULL)
{
scanline = (stbi_uc*)stbi__malloc_mad2(width, 4, 0);
if (!scanline)
{
STBI_FREE(hdr_data);
return stbi__errpf("outofmem", "Out of memory");
}
}
for (k = 0; k < 4; ++k)
{
int nleft;
i = 0;
while ((nleft = width - i) > 0)
{
count = stbi__get8(s);
if (count > 128)
{
// Run
value = stbi__get8(s);
count -= 128;
if ((count == 0) || (count > nleft))
{
STBI_FREE(hdr_data);
STBI_FREE(scanline);
return stbi__errpf("corrupt", "bad RLE data in HDR");
}
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = value;
}
else
{
// Dump
if ((count == 0) || (count > nleft))
{
STBI_FREE(hdr_data);
STBI_FREE(scanline);
return stbi__errpf("corrupt", "bad RLE data in HDR");
}
for (z = 0; z < count; ++z)
scanline[i++ * 4 + k] = stbi__get8(s);
}
}
}
for (i = 0; i < width; ++i)
stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, scanline + i * 4, req_comp);
}
if (scanline)
STBI_FREE(scanline);
}
return hdr_data;
}
static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp)
{
char buffer[STBI__HDR_BUFLEN];
char* token;
int valid = 0;
int dummy;
if (!x)
x = &dummy;
if (!y)
y = &dummy;
if (!comp)
comp = &dummy;
if (stbi__hdr_test(s) == 0)
{
stbi__rewind(s);
return 0;
}
for (;;)
{
token = stbi__hdr_gettoken(s, buffer);
if (token[0] == 0)
break;
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0)
valid = 1;
}
if (!valid)
{
stbi__rewind(s);
return 0;
}
token = stbi__hdr_gettoken(s, buffer);
if (strncmp(token, "-Y ", 3))
{
stbi__rewind(s);
return 0;
}
token += 3;
*y = (int)strtol(token, &token, 10);
while (*token == ' ')
++token;
if (strncmp(token, "+X ", 3))
{
stbi__rewind(s);
return 0;
}
token += 3;
*x = (int)strtol(token, NULL, 10);
*comp = 3;
return 1;
}
#endif // STBI_NO_HDR
#ifndef STBI_NO_BMP
static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp)
{
void* p;
stbi__bmp_data info;
info.all_a = 255;
p = stbi__bmp_parse_header(s, &info);
if (p == NULL)
{
stbi__rewind(s);
return 0;
}
if (x)
*x = s->img_x;
if (y)
*y = s->img_y;
if (comp)
{
if (info.bpp == 24 && info.ma == 0xff000000)
*comp = 3;
else
*comp = info.ma ? 4 : 3;
}
return 1;
}
#endif
#ifndef STBI_NO_PSD
static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp)
{
int channelCount, dummy, depth;
if (!x)
x = &dummy;
if (!y)
y = &dummy;
if (!comp)
comp = &dummy;
if (stbi__get32be(s) != 0x38425053)
{
stbi__rewind(s);
return 0;
}
if (stbi__get16be(s) != 1)
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 6);
channelCount = stbi__get16be(s);
if (channelCount < 0 || channelCount > 16)
{
stbi__rewind(s);
return 0;
}
*y = stbi__get32be(s);
*x = stbi__get32be(s);
depth = stbi__get16be(s);
if (depth != 8 && depth != 16)
{
stbi__rewind(s);
return 0;
}
if (stbi__get16be(s) != 3)
{
stbi__rewind(s);
return 0;
}
*comp = 4;
return 1;
}
static int stbi__psd_is16(stbi__context* s)
{
int channelCount, depth;
if (stbi__get32be(s) != 0x38425053)
{
stbi__rewind(s);
return 0;
}
if (stbi__get16be(s) != 1)
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 6);
channelCount = stbi__get16be(s);
if (channelCount < 0 || channelCount > 16)
{
stbi__rewind(s);
return 0;
}
STBI_NOTUSED(stbi__get32be(s));
STBI_NOTUSED(stbi__get32be(s));
depth = stbi__get16be(s);
if (depth != 16)
{
stbi__rewind(s);
return 0;
}
return 1;
}
#endif
#ifndef STBI_NO_PIC
static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp)
{
int act_comp = 0, num_packets = 0, chained, dummy;
stbi__pic_packet packets[10];
if (!x)
x = &dummy;
if (!y)
y = &dummy;
if (!comp)
comp = &dummy;
if (!stbi__pic_is4(s, "\x53\x80\xF6\x34"))
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 88);
*x = stbi__get16be(s);
*y = stbi__get16be(s);
if (stbi__at_eof(s))
{
stbi__rewind(s);
return 0;
}
if ((*x) != 0 && (1 << 28) / (*x) < (*y))
{
stbi__rewind(s);
return 0;
}
stbi__skip(s, 8);
do
{
stbi__pic_packet* packet;
if (num_packets == sizeof(packets) / sizeof(packets[0]))
return 0;
packet = &packets[num_packets++];
chained = stbi__get8(s);
packet->size = stbi__get8(s);
packet->type = stbi__get8(s);
packet->channel = stbi__get8(s);
act_comp |= packet->channel;
if (stbi__at_eof(s))
{
stbi__rewind(s);
return 0;
}
if (packet->size != 8)
{
stbi__rewind(s);
return 0;
}
} while (chained);
*comp = (act_comp & 0x10 ? 4 : 3);
return 1;
}
#endif
// *************************************************************************************************
// Portable Gray Map and Portable Pixel Map loader
// by Ken Miller
//
// PGM: path_to_url
// PPM: path_to_url
//
// Known limitations:
// Does not support comments in the header section
// Does not support ASCII image data (formats P2 and P3)
#ifndef STBI_NO_PNM
static int stbi__pnm_test(stbi__context* s)
{
char p, t;
p = (char)stbi__get8(s);
t = (char)stbi__get8(s);
if (p != 'P' || (t != '5' && t != '6'))
{
stbi__rewind(s);
return 0;
}
return 1;
}
static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri)
{
stbi_uc* out;
STBI_NOTUSED(ri);
ri->bits_per_channel = stbi__pnm_info(s, (int*)&s->img_x, (int*)&s->img_y, (int*)&s->img_n);
if (ri->bits_per_channel == 0)
return 0;
if (s->img_y > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
*x = s->img_x;
*y = s->img_y;
if (comp)
*comp = s->img_n;
if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
return stbi__errpuc("too large", "PNM too large");
out = (stbi_uc*)stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);
if (!out)
return stbi__errpuc("outofmem", "Out of memory");
if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8)))
{
STBI_FREE(out);
return stbi__errpuc("bad PNM", "PNM file truncated");
}
if (req_comp && req_comp != s->img_n)
{
if (ri->bits_per_channel == 16)
{
out = (stbi_uc*)stbi__convert_format16((stbi__uint16*)out, s->img_n, req_comp, s->img_x, s->img_y);
}
else
{
out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
}
if (out == NULL)
return out; // stbi__convert_format frees input on failure
}
return out;
}
static int stbi__pnm_isspace(char c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}
static void stbi__pnm_skip_whitespace(stbi__context* s, char* c)
{
for (;;)
{
while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
*c = (char)stbi__get8(s);
if (stbi__at_eof(s) || *c != '#')
break;
while (!stbi__at_eof(s) && *c != '\n' && *c != '\r')
*c = (char)stbi__get8(s);
}
}
static int stbi__pnm_isdigit(char c)
{
return c >= '0' && c <= '9';
}
static int stbi__pnm_getinteger(stbi__context* s, char* c)
{
int value = 0;
while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c))
{
value = value * 10 + (*c - '0');
*c = (char)stbi__get8(s);
if ((value > 214748364) || (value == 214748364 && *c > '7'))
return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int");
}
return value;
}
static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp)
{
int maxv, dummy;
char c, p, t;
if (!x)
x = &dummy;
if (!y)
y = &dummy;
if (!comp)
comp = &dummy;
stbi__rewind(s);
// Get identifier
p = (char)stbi__get8(s);
t = (char)stbi__get8(s);
if (p != 'P' || (t != '5' && t != '6'))
{
stbi__rewind(s);
return 0;
}
*comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
c = (char)stbi__get8(s);
stbi__pnm_skip_whitespace(s, &c);
*x = stbi__pnm_getinteger(s, &c); // read width
if (*x == 0)
return stbi__err("invalid width", "PPM image header had zero or overflowing width");
stbi__pnm_skip_whitespace(s, &c);
*y = stbi__pnm_getinteger(s, &c); // read height
if (*y == 0)
return stbi__err("invalid width", "PPM image header had zero or overflowing width");
stbi__pnm_skip_whitespace(s, &c);
maxv = stbi__pnm_getinteger(s, &c); // read max value
if (maxv > 65535)
return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");
else if (maxv > 255)
return 16;
else
return 8;
}
static int stbi__pnm_is16(stbi__context* s)
{
if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)
return 1;
return 0;
}
#endif
static int stbi__info_main(stbi__context* s, int* x, int* y, int* comp)
{
#ifndef STBI_NO_JPEG
if (stbi__jpeg_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_PNG
if (stbi__png_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_GIF
if (stbi__gif_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_BMP
if (stbi__bmp_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_PSD
if (stbi__psd_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_PIC
if (stbi__pic_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_PNM
if (stbi__pnm_info(s, x, y, comp))
return 1;
#endif
#ifndef STBI_NO_HDR
if (stbi__hdr_info(s, x, y, comp))
return 1;
#endif
// test tga last because it's a crappy test!
#ifndef STBI_NO_TGA
if (stbi__tga_info(s, x, y, comp))
return 1;
#endif
return stbi__err("unknown image type", "Image not of any known type, or corrupt");
}
static int stbi__is_16_main(stbi__context* s)
{
#ifndef STBI_NO_PNG
if (stbi__png_is16(s))
return 1;
#endif
#ifndef STBI_NO_PSD
if (stbi__psd_is16(s))
return 1;
#endif
#ifndef STBI_NO_PNM
if (stbi__pnm_is16(s))
return 1;
#endif
return 0;
}
#ifndef STBI_NO_STDIO
STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp)
{
FILE* f = stbi__fopen(filename, "rb");
int result;
if (!f)
return stbi__err("can't fopen", "Unable to open file");
result = stbi_info_from_file(f, x, y, comp);
fclose(f);
return result;
}
STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp)
{
int r;
stbi__context s;
long pos = ftell(f);
stbi__start_file(&s, f);
r = stbi__info_main(&s, x, y, comp);
fseek(f, pos, SEEK_SET);
return r;
}
STBIDEF int stbi_is_16_bit(char const* filename)
{
FILE* f = stbi__fopen(filename, "rb");
int result;
if (!f)
return stbi__err("can't fopen", "Unable to open file");
result = stbi_is_16_bit_from_file(f);
fclose(f);
return result;
}
STBIDEF int stbi_is_16_bit_from_file(FILE* f)
{
int r;
stbi__context s;
long pos = ftell(f);
stbi__start_file(&s, f);
r = stbi__is_16_main(&s);
fseek(f, pos, SEEK_SET);
return r;
}
#endif // !STBI_NO_STDIO
STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp)
{
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__info_main(&s, x, y, comp);
}
STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* c, void* user, int* x, int* y, int* comp)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user);
return stbi__info_main(&s, x, y, comp);
}
STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len)
{
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__is_16_main(&s);
}
STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* c, void* user)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user);
return stbi__is_16_main(&s);
}
#endif // STB_IMAGE_IMPLEMENTATION
/*
revision history:
2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
2.19 (2018-02-11) fix warning
2.18 (2018-01-30) fix warnings
2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug
1-bit BMP
*_is_16_bit api
avoid warnings
2.16 (2017-07-23) all functions have 16-bit variants;
STBI_NO_STDIO works again;
compilation fixes;
fix rounding in unpremultiply;
optimize vertical flip;
disable raw_len validation;
documentation fixes
2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode;
warning fixes; disable run-time SSE detection on gcc;
uniform handling of optional "return" values;
thread-safe initialization of zlib tables
2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
2.13 (2016-11-29) add 16-bit API, only supported for PNG right now
2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
2.11 (2016-04-02) allocate large structures on the stack
remove white matting for transparent PSD
fix reported channel count for PNG & BMP
re-enable SSE2 in non-gcc 64-bit
support RGB-formatted JPEG
read 16-bit PNGs (only as 8-bit)
2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED
2.09 (2016-01-16) allow comments in PNM files
16-bit-per-pixel TGA (not bit-per-component)
info() for TGA could break due to .hdr handling
info() for BMP to shares code instead of sloppy parse
can use STBI_REALLOC_SIZED if allocator doesn't support realloc
code cleanup
2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
2.07 (2015-09-13) fix compiler warnings
partial animated GIF support
limited 16-bpc PSD support
#ifdef unused functions
bug with < 92 byte PIC,PNM,HDR,TGA
2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
2.03 (2015-04-12) extra corruption checking (mmozeiko)
stbi_set_flip_vertically_on_load (nguillemot)
fix NEON support; fix mingw support
2.02 (2015-01-19) fix incorrect assert, fix warning
2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
progressive JPEG (stb)
PGM/PPM support (Ken Miller)
STBI_MALLOC,STBI_REALLOC,STBI_FREE
GIF bugfix -- seemingly never worked
STBI_NO_*, STBI_ONLY_*
1.48 (2014-12-14) fix incorrectly-named assert()
1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
optimize PNG (ryg)
fix bug in interlaced PNG with user-specified channel count (stb)
1.46 (2014-08-26)
fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
1.45 (2014-08-16)
fix MSVC-ARM internal compiler error by wrapping malloc
1.44 (2014-08-07)
various warning fixes from Ronny Chevalier
1.43 (2014-07-15)
fix MSVC-only compiler problem in code changed in 1.42
1.42 (2014-07-09)
don't define _CRT_SECURE_NO_WARNINGS (affects user code)
fixes to stbi__cleanup_jpeg path
added STBI_ASSERT to avoid requiring assert.h
1.41 (2014-06-25)
fix search&replace from 1.36 that messed up comments/error messages
1.40 (2014-06-22)
fix gcc struct-initialization warning
1.39 (2014-06-15)
fix to TGA optimization when req_comp != number of components in TGA;
fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
add support for BMP version 5 (more ignored fields)
1.38 (2014-06-06)
suppress MSVC warnings on integer casts truncating values
fix accidental rename of 'skip' field of I/O
1.37 (2014-06-04)
remove duplicate typedef
1.36 (2014-06-03)
convert to header file single-file library
if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
1.35 (2014-05-27)
various warnings
fix broken STBI_SIMD path
fix bug where stbi_load_from_file no longer left file pointer in correct place
fix broken non-easy path for 32-bit BMP (possibly never used)
TGA optimization by Arseny Kapoulkine
1.34 (unknown)
use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
1.33 (2011-07-14)
make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
1.32 (2011-07-13)
support for "info" function for all supported filetypes (SpartanJ)
1.31 (2011-06-20)
a few more leak fixes, bug in PNG handling (SpartanJ)
1.30 (2011-06-11)
added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
removed deprecated format-specific test/load functions
removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
fix inefficiency in decoding 32-bit BMP (David Woo)
1.29 (2010-08-16)
various warning fixes from Aurelien Pocheville
1.28 (2010-08-01)
fix bug in GIF palette transparency (SpartanJ)
1.27 (2010-08-01)
cast-to-stbi_uc to fix warnings
1.26 (2010-07-24)
fix bug in file buffering for PNG reported by SpartanJ
1.25 (2010-07-17)
refix trans_data warning (Won Chun)
1.24 (2010-07-12)
perf improvements reading from files on platforms with lock-heavy fgetc()
minor perf improvements for jpeg
deprecated type-specific functions so we'll get feedback if they're needed
attempt to fix trans_data warning (Won Chun)
1.23 fixed bug in iPhone support
1.22 (2010-07-10)
removed image *writing* support
stbi_info support from Jetro Lauha
GIF support from Jean-Marc Lienher
iPhone PNG-extensions from James Brown
warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
1.21 fix use of 'stbi_uc' in header (reported by jon blow)
1.20 added support for Softimage PIC, by Tom Seddon
1.19 bug in interlaced PNG corruption check (found by ryg)
1.18 (2008-08-02)
fix a threading bug (local mutable static)
1.17 support interlaced PNG
1.16 major bugfix - stbi__convert_format converted one too many pixels
1.15 initialize some fields for thread safety
1.14 fix threadsafe conversion bug
header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
1.13 threadsafe
1.12 const qualifiers in the API
1.11 Support installable IDCT, colorspace conversion routines
1.10 Fixes for 64-bit (don't use "unsigned long")
optimized upsampling by Fabian "ryg" Giesen
1.09 Fix format-conversion for PSD code (bad global variables!)
1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
1.07 attempt to fix C++ warning/errors again
1.06 attempt to fix C++ warning/errors again
1.05 fix TGA loading to return correct *comp and use good luminance calc
1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
1.02 support for (subset of) HDR files, float interface for preferred access to them
1.01 fix bug: possible bug in handling right-side up bmps... not sure
fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
1.00 interface to zlib that skips zlib header
0.99 correct handling of alpha in palette
0.98 TGA loader by lonesock; dynamically add loaders (untested)
0.97 jpeg errors on too large a file; also catch another malloc failure
0.96 fix detection of invalid v value - particleman@mollyrocket forum
0.95 during header scan, seek to markers in case of padding
0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
0.93 handle jpegtran output; verbose errors
0.92 read 4,8,16,24,32-bit BMP files of several formats
0.91 output 24-bit Windows 3.0 BMP files
0.90 fix a few more warnings; bump version number to approach 1.0
0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
0.60 fix compiling as c++
0.59 fix warnings: merge Dave Moore's -Wall fixes
0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
0.56 fix bug: zlib uncompressed mode len vs. nlen
0.55 fix bug: restart_interval not initialized to 0
0.54 allow NULL for 'int *comp'
0.53 fix bug in png 3->4; speedup png decoding
0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
0.51 obey req_comp requests, 1-component jpegs return as 1-component,
on 'test' only check type, not whether we support this variant
0.50 (2006-11-19)
first released version
*/
/*
your_sha256_hash--------------
This software is available under 2 licenses -- choose whichever you prefer.
your_sha256_hash--------------
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
your_sha256_hash--------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
your_sha256_hash--------------
*/
``` | /content/code_sandbox/libs/nanovg/nanovg/stb_image.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 93,391 |
```c++
// Reverb model implementation
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#include "revmodel.hpp"
revmodel::revmodel()
{
// Tie the components to their buffers
combL[0].setbuffer(bufcombL1,combtuningL1);
combR[0].setbuffer(bufcombR1,combtuningR1);
combL[1].setbuffer(bufcombL2,combtuningL2);
combR[1].setbuffer(bufcombR2,combtuningR2);
combL[2].setbuffer(bufcombL3,combtuningL3);
combR[2].setbuffer(bufcombR3,combtuningR3);
combL[3].setbuffer(bufcombL4,combtuningL4);
combR[3].setbuffer(bufcombR4,combtuningR4);
combL[4].setbuffer(bufcombL5,combtuningL5);
combR[4].setbuffer(bufcombR5,combtuningR5);
combL[5].setbuffer(bufcombL6,combtuningL6);
combR[5].setbuffer(bufcombR6,combtuningR6);
combL[6].setbuffer(bufcombL7,combtuningL7);
combR[6].setbuffer(bufcombR7,combtuningR7);
combL[7].setbuffer(bufcombL8,combtuningL8);
combR[7].setbuffer(bufcombR8,combtuningR8);
allpassL[0].setbuffer(bufallpassL1,allpasstuningL1);
allpassR[0].setbuffer(bufallpassR1,allpasstuningR1);
allpassL[1].setbuffer(bufallpassL2,allpasstuningL2);
allpassR[1].setbuffer(bufallpassR2,allpasstuningR2);
allpassL[2].setbuffer(bufallpassL3,allpasstuningL3);
allpassR[2].setbuffer(bufallpassR3,allpasstuningR3);
allpassL[3].setbuffer(bufallpassL4,allpasstuningL4);
allpassR[3].setbuffer(bufallpassR4,allpasstuningR4);
// Set default values
allpassL[0].setfeedback(0.5f);
allpassR[0].setfeedback(0.5f);
allpassL[1].setfeedback(0.5f);
allpassR[1].setfeedback(0.5f);
allpassL[2].setfeedback(0.5f);
allpassR[2].setfeedback(0.5f);
allpassL[3].setfeedback(0.5f);
allpassR[3].setfeedback(0.5f);
setwet(initialwet);
setroomsize(initialroom);
setdry(initialdry);
setdamp(initialdamp);
setwidth(initialwidth);
setmode(initialmode);
// Buffer will be full of rubbish - so we MUST mute them
mute();
}
void revmodel::mute()
{
if (getmode() >= freezemode)
return;
int i;
for (i=0;i<numcombs;i++)
{
combL[i].mute();
combR[i].mute();
}
for (i=0;i<numallpasses;i++)
{
allpassL[i].mute();
allpassR[i].mute();
}
}
void revmodel::processreplace(float *inputL, float *inputR, float *outputL, float *outputR, long numsamples, int skip)
{
float outL,outR,input;
while(numsamples-- > 0)
{
outL = outR = 0;
input = (*inputL + *inputR) * gain;
// Accumulate comb filters in parallel
int i;
for(i=0; i<numcombs; i++)
{
outL += combL[i].process(input);
outR += combR[i].process(input);
}
// Feed through allpasses in series
for(i=0; i<numallpasses; i++)
{
outL = allpassL[i].process(outL);
outR = allpassR[i].process(outR);
}
// Calculate output REPLACING anything already there
*outputL = outL*wet1 + outR*wet2 + *inputL*dry;
*outputR = outR*wet1 + outL*wet2 + *inputR*dry;
// Increment sample pointers, allowing for interleave (if any)
inputL += skip;
inputR += skip;
outputL += skip;
outputR += skip;
}
}
void revmodel::processmix(float *inputL, float *inputR, float *outputL, float *outputR, long numsamples, int skip)
{
float outL,outR,input;
while(numsamples-- > 0)
{
outL = outR = 0;
input = (*inputL + *inputR) * gain;
int i;
// Accumulate comb filters in parallel
for(i=0; i<numcombs; i++)
{
outL += combL[i].process(input);
outR += combR[i].process(input);
}
// Feed through allpasses in series
for(i=0; i<numallpasses; i++)
{
outL = allpassL[i].process(outL);
outR = allpassR[i].process(outR);
}
// Calculate output MIXING with anything already there
*outputL += outL*wet1 + outR*wet2 + *inputL*dry;
*outputR += outR*wet1 + outL*wet2 + *inputR*dry;
// Increment sample pointers, allowing for interleave (if any)
inputL += skip;
inputR += skip;
outputL += skip;
outputR += skip;
}
}
void revmodel::update()
{
// Recalculate internal values after parameter change
int i;
wet1 = wet*(width/2 + 0.5f);
wet2 = wet*((1-width)/2);
if (mode >= freezemode)
{
roomsize1 = 1;
damp1 = 0;
gain = muted;
}
else
{
roomsize1 = roomsize;
damp1 = damp;
gain = fixedgain;
}
for(i=0; i<numcombs; i++)
{
combL[i].setfeedback(roomsize1);
combR[i].setfeedback(roomsize1);
}
for(i=0; i<numcombs; i++)
{
combL[i].setdamp(damp1);
combR[i].setdamp(damp1);
}
}
// The following get/set functions are not inlined, because
// speed is never an issue when calling them, and also
// because as you develop the reverb model, you may
// wish to take dynamic action when they are called.
void revmodel::setroomsize(float value)
{
roomsize = value;
}
float revmodel::getroomsize()
{
return roomsize;
}
void revmodel::setdamp(float value)
{
damp = (value*0.01f)*scaledamp;
}
float revmodel::getdamp()
{
return (damp*100.0f)/scaledamp;
}
void revmodel::setwet(float value)
{
wet = value;
// if (value <= wetmin)
// wet = 0.0f;
// else
// wet = (value / 20.0f);
}
float revmodel::getwet()
{
return wet;
// if (wet <= 0.0f)
// return wetmin;
// else
// return 20.0f * log10f(wet);
}
void revmodel::setdry(float value)
{
dry = value;
// if (value <= drymin)
// dry = 0.0f;
// else
// dry = (value / 20.0f);
}
float revmodel::getdry()
{
return dry;
// if (dry <= 0.0f)
// return drymin;
// else
// return 20.0f * log10f(dry);
}
void revmodel::setwidth(float value)
{
width = (value*0.01f);
}
float revmodel::getwidth()
{
return (width*100.0f);
}
void revmodel::setmode(float value)
{
mode = value;
}
float revmodel::getmode()
{
if (mode >= freezemode)
return 1;
else
return 0;
}
//ends
``` | /content/code_sandbox/libs/freeverb/src/revmodel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,971 |
```c++
// Comb filter implementation
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#include "comb.hpp"
comb::comb()
{
filterstore = 0;
bufidx = 0;
}
void comb::setbuffer(float *buf, int size)
{
buffer = buf;
bufsize = size;
}
void comb::mute()
{
for (int i=0; i<bufsize; i++)
buffer[i]=0;
}
void comb::setdamp(float val)
{
damp1 = val;
damp2 = 1-val;
}
float comb::getdamp()
{
return damp1;
}
void comb::setfeedback(float val)
{
feedback = val;
}
float comb::getfeedback()
{
return feedback;
}
// ends
``` | /content/code_sandbox/libs/freeverb/src/comb.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 183 |
```objective-c
// Macro for killing denormalled numbers
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// Based on IS_DENORMAL macro by Jon Watte
// This code is public domain
#ifndef _denormals_
#define _denormals_
#define undenormalise(sample) if(((*(unsigned int*)&sample)&0x7f800000)==0) sample=0.0f
#endif//_denormals_
//ends
``` | /content/code_sandbox/libs/freeverb/freeverb/denormals.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 104 |
```c++
// Comb filter class declaration
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#ifndef _comb_
#define _comb_
#include "denormals.h"
class comb
{
public:
comb();
void setbuffer(float *buf, int size);
inline float process(float inp);
void mute();
void setdamp(float val);
float getdamp();
void setfeedback(float val);
float getfeedback();
private:
float feedback;
float filterstore;
float damp1;
float damp2;
float *buffer;
int bufsize;
int bufidx;
};
// Big to inline - but crucial for speed
inline float comb::process(float input)
{
float output;
output = buffer[bufidx];
undenormalise(output);
filterstore = (output*damp2) + (filterstore*damp1);
undenormalise(filterstore);
buffer[bufidx] = input + (filterstore*feedback);
if(++bufidx>=bufsize) bufidx = 0;
return output;
}
#endif //_comb_
//ends
``` | /content/code_sandbox/libs/freeverb/freeverb/comb.hpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 245 |
```objective-c
// Reverb model tuning values
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#ifndef _tuning_
#define _tuning_
const int numcombs = 8;
const int numallpasses = 4;
const float muted = 0.0f;
const float fixedgain = 0.015f;
const float scalewet = 3.0f;
const float scaledry = 2.0f;
const float scaledamp = 0.4f;
const float scaleroom = 0.28f;
const float offsetroom = 0.7f;
const float initialroom = 0.5f;
const float initialdamp = 0.5f;
const float initialwet = 1.0f;
const float initialdry = 0.0f;
const float initialwidth = 1.0f;
const float initialmode = 0.0f;
const float freezemode = 1.0f;
const int stereospread = 23;
// These values assume 44.1KHz sample rate
// they will probably be OK for 48KHz sample rate
// but would need scaling for 96KHz (or other) sample rates.
// The values were obtained by listening tests.
const int combtuningL1 = 1116;
const int combtuningR1 = 1116+stereospread;
const int combtuningL2 = 1188;
const int combtuningR2 = 1188+stereospread;
const int combtuningL3 = 1277;
const int combtuningR3 = 1277+stereospread;
const int combtuningL4 = 1356;
const int combtuningR4 = 1356+stereospread;
const int combtuningL5 = 1422;
const int combtuningR5 = 1422+stereospread;
const int combtuningL6 = 1491;
const int combtuningR6 = 1491+stereospread;
const int combtuningL7 = 1557;
const int combtuningR7 = 1557+stereospread;
const int combtuningL8 = 1617;
const int combtuningR8 = 1617+stereospread;
const int allpasstuningL1 = 556;
const int allpasstuningR1 = 556+stereospread;
const int allpasstuningL2 = 441;
const int allpasstuningR2 = 441+stereospread;
const int allpasstuningL3 = 341;
const int allpasstuningR3 = 341+stereospread;
const int allpasstuningL4 = 225;
const int allpasstuningR4 = 225+stereospread;
#endif//_tuning_
//ends
``` | /content/code_sandbox/libs/freeverb/freeverb/tuning.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 716 |
```c++
// Allpass filter declaration
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#ifndef _allpass_
#define _allpass_
#include "denormals.h"
class allpass
{
public:
allpass();
void setbuffer(float *buf, int size);
inline float process(float inp);
void mute();
void setfeedback(float val);
float getfeedback();
// private:
float feedback;
float *buffer;
int bufsize;
int bufidx;
};
// Big to inline - but crucial for speed
inline float allpass::process(float input)
{
float output;
float bufout;
bufout = buffer[bufidx];
undenormalise(bufout);
output = -input + bufout;
buffer[bufidx] = input + (bufout*feedback);
if(++bufidx>=bufsize) bufidx = 0;
return output;
}
#endif//_allpass
//ends
``` | /content/code_sandbox/libs/freeverb/freeverb/allpass.hpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 215 |
```c++
// Reverb model declaration
//
// Written by Jezar at Dreampoint, June 2000
// path_to_url
// This code is public domain
#ifndef _revmodel_
#define _revmodel_
#include "comb.hpp"
#include "allpass.hpp"
#include "tuning.h"
class revmodel
{
public:
revmodel();
void mute();
void processmix(float *inputL, float *inputR, float *outputL, float *outputR, long numsamples, int skip);
void processreplace(float *inputL, float *inputR, float *outputL, float *outputR, long numsamples, int skip);
void setroomsize(float value);
float getroomsize();
void setdamp(float value);
float getdamp();
void setwet(float value);
float getwet();
void setdry(float value);
float getdry();
void setwidth(float value);
float getwidth();
void setmode(float value);
float getmode();
void update();
private:
float gain;
float roomsize,roomsize1;
float damp,damp1;
float wet,wet1,wet2;
float dry;
float width;
float mode;
// The following are all declared inline
// to remove the need for dynamic allocation
// with its subsequent error-checking messiness
// Comb filters
comb combL[numcombs];
comb combR[numcombs];
// Allpass filters
allpass allpassL[numallpasses];
allpass allpassR[numallpasses];
// Buffers for the combs
float bufcombL1[combtuningL1];
float bufcombR1[combtuningR1];
float bufcombL2[combtuningL2];
float bufcombR2[combtuningR2];
float bufcombL3[combtuningL3];
float bufcombR3[combtuningR3];
float bufcombL4[combtuningL4];
float bufcombR4[combtuningR4];
float bufcombL5[combtuningL5];
float bufcombR5[combtuningR5];
float bufcombL6[combtuningL6];
float bufcombR6[combtuningR6];
float bufcombL7[combtuningL7];
float bufcombR7[combtuningR7];
float bufcombL8[combtuningL8];
float bufcombR8[combtuningR8];
// Buffers for the allpasses
float bufallpassL1[allpasstuningL1];
float bufallpassR1[allpasstuningR1];
float bufallpassL2[allpasstuningL2];
float bufallpassR2[allpasstuningR2];
float bufallpassL3[allpasstuningL3];
float bufallpassR3[allpasstuningR3];
float bufallpassL4[allpasstuningL4];
float bufallpassR4[allpasstuningR4];
};
#endif//_revmodel_
//ends
``` | /content/code_sandbox/libs/freeverb/freeverb/revmodel.hpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 674 |
```c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "lut.h"
/* The number of bits to form the hash, which governs the overall size
* of the hash lookup table, and hence the amount of chaining */
#define HASH_BITS 16
#define HASH(timecode) ((timecode) & ((1 << HASH_BITS) - 1))
#define NO_SLOT ((unsigned)-1)
/* Initialise an empty hash lookup table to store the given number
* of timecode -> position lookups */
int lut_init(struct lut *lut, int nslots)
{
int n, hashes;
size_t bytes;
hashes = 1 << HASH_BITS;
bytes = sizeof(struct slot) * nslots + sizeof(slot_no_t) * hashes;
fprintf(stderr, "Lookup table has %d hashes to %d slots"
" (%d slots per hash, %zuKb)\n",
hashes, nslots, nslots / hashes, bytes / 1024);
lut->slot = malloc(sizeof(struct slot) * nslots);
if (lut->slot == NULL) {
perror("malloc");
return -1;
}
lut->table = malloc(sizeof(slot_no_t) * hashes);
if (lut->table == NULL) {
perror("malloc");
return -1;
}
for (n = 0; n < hashes; n++)
lut->table[n] = NO_SLOT;
lut->avail = 0;
return 0;
}
void lut_clear(struct lut *lut)
{
free(lut->table);
free(lut->slot);
}
void lut_push(struct lut *lut, unsigned int timecode)
{
unsigned int hash;
slot_no_t slot_no;
struct slot *slot;
slot_no = lut->avail++; /* take the next available slot */
slot = &lut->slot[slot_no];
slot->timecode = timecode;
hash = HASH(timecode);
slot->next = lut->table[hash];
lut->table[hash] = slot_no;
}
unsigned int lut_lookup(struct lut *lut, unsigned int timecode)
{
unsigned int hash;
slot_no_t slot_no;
struct slot *slot;
hash = HASH(timecode);
slot_no = lut->table[hash];
while (slot_no != NO_SLOT) {
slot = &lut->slot[slot_no];
if (slot->timecode == timecode)
return slot_no;
slot_no = slot->next;
}
return (unsigned)-1;
}
``` | /content/code_sandbox/libs/xwax/src/lut.c | c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 638 |
```c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef BESPOKE_WINDOWS
#include <unistd.h>
#endif
#include "debug.h"
#include "timecoder.h"
#define ZERO_THRESHOLD (128 << 16)
#define ZERO_RC 0.001 /* time constant for zero/rumble filter */
#define REF_PEAKS_AVG 48 /* in wave cycles */
/* The number of correct bits which come in before the timecode is
* declared valid. Set this too low, and risk the record skipping
* around (often to blank areas of track) during scratching */
#define VALID_BITS 24
#define MONITOR_DECAY_EVERY 512 /* in samples */
#define SQ(x) ((x)*(x))
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*x))
/* Timecode definitions */
#define SWITCH_PHASE 0x1 /* tone phase difference of 270 (not 90) degrees */
#define SWITCH_PRIMARY 0x2 /* use left channel (not right) as primary */
#define SWITCH_POLARITY 0x4 /* read bit values in negative (not positive) */
static struct timecode_def timecodes[] = {
{
.name = "serato_2a",
.desc = "Serato 2nd Ed., side A",
.resolution = 1000,
.bits = 20,
.seed = 0x59017,
.taps = 0x361e4,
.length = 712000,
.safe = 707000,
},
{
.name = "serato_2b",
.desc = "Serato 2nd Ed., side B",
.resolution = 1000,
.bits = 20,
.seed = 0x8f3c6,
.taps = 0x4f0d8, /* reverse of side A */
.length = 922000,
.safe = 917000,
},
{
.name = "serato_cd",
.desc = "Serato CD",
.resolution = 1000,
.bits = 20,
.seed = 0xd8b40,
.taps = 0x34d54,
.length = 950000,
.safe = 940000,
},
{
.name = "traktor_a",
.desc = "Traktor Scratch, side A",
.resolution = 2000,
.flags = SWITCH_PRIMARY | SWITCH_POLARITY | SWITCH_PHASE,
.bits = 23,
.seed = 0x134503,
.taps = 0x041040,
.length = 1500000,
.safe = 1480000,
},
{
.name = "traktor_b",
.desc = "Traktor Scratch, side B",
.resolution = 2000,
.flags = SWITCH_PRIMARY | SWITCH_POLARITY | SWITCH_PHASE,
.bits = 23,
.seed = 0x32066c,
.taps = 0x041040, /* same as side A */
.length = 2110000,
.safe = 2090000,
},
{
.name = "mixvibes_v2",
.desc = "MixVibes V2",
.resolution = 1300,
.flags = SWITCH_PHASE,
.bits = 20,
.seed = 0x22c90,
.taps = 0x00008,
.length = 950000,
.safe = 923000,
},
{
.name = "mixvibes_7inch",
.desc = "MixVibes 7\"",
.resolution = 1300,
.flags = SWITCH_PHASE,
.bits = 20,
.seed = 0x22c90,
.taps = 0x00008,
.length = 312000,
.safe = 310000,
},
{
.name = "pioneer_a",
.desc = "Pioneer RekordBox DVS Control Vinyl, side A",
.resolution = 1000,
.flags = SWITCH_POLARITY,
.bits = 20,
.seed = 0x78370,
.taps = 0x7933a,
.length = 635000,
.safe = 614000,
},
{
.name = "pioneer_b",
.desc = "Pioneer RekordBox DVS Control Vinyl, side B",
.resolution = 1000,
.flags = SWITCH_POLARITY,
.bits = 20,
.seed = 0xf7012,
.taps = 0x2ef1c,
.length = 918500,
.safe = 913000,
},
};
/*
* Calculate LFSR bit
*/
static inline bits_t lfsr(bits_t code, bits_t taps)
{
bits_t taken;
int xrs;
taken = code & taps;
xrs = 0;
while (taken != 0x0) {
xrs += taken & 0x1;
taken >>= 1;
}
return xrs & 0x1;
}
/*
* Linear Feedback Shift Register in the forward direction. New values
* are generated at the least-significant bit.
*/
static inline bits_t fwd(bits_t current, struct timecode_def *def)
{
bits_t l;
/* New bits are added at the MSB; shift right by one */
l = lfsr(current, def->taps | 0x1);
return (current >> 1) | (l << (def->bits - 1));
}
/*
* Linear Feedback Shift Register in the reverse direction
*/
static inline bits_t rev(bits_t current, struct timecode_def *def)
{
bits_t l, mask;
/* New bits are added at the LSB; shift left one and mask */
mask = (1 << def->bits) - 1;
l = lfsr(current, (def->taps >> 1) | (0x1 << (def->bits - 1)));
return ((current << 1) & mask) | l;
}
/*
* Where necessary, build the lookup table required for this timecode
*
* Return: -1 if not enough memory could be allocated, otherwise 0
*/
static int build_lookup(struct timecode_def *def)
{
unsigned int n;
bits_t current;
if (def->lookup)
return 0;
fprintf(stderr, "Building LUT for %d bit %dHz timecode (%s)\n",
def->bits, def->resolution, def->desc);
if (lut_init(&def->lut, def->length) == -1)
return -1;
current = def->seed;
for (n = 0; n < def->length; n++) {
bits_t next;
/* timecode must not wrap */
assert(lut_lookup(&def->lut, current) == (unsigned)-1);
lut_push(&def->lut, current);
/* check symmetry of the lfsr functions */
next = fwd(current, def);
assert(rev(next, def) == current);
current = next;
}
def->lookup = true;
return 0;
}
/*
* Find a timecode definition by name
*
* Return: pointer to timecode definition, or NULL if not available
*/
struct timecode_def* timecoder_find_definition(const char *name)
{
unsigned int n;
for (n = 0; n < ARRAY_SIZE(timecodes); n++) {
struct timecode_def *def = &timecodes[n];
if (strcmp(def->name, name) != 0)
continue;
if (build_lookup(def) == -1)
return NULL; /* error */
return def;
}
return NULL; /* not found */
}
/*
* Free the timecoder lookup tables when they are no longer needed
*/
void timecoder_free_lookup(void) {
unsigned int n;
for (n = 0; n < ARRAY_SIZE(timecodes); n++) {
struct timecode_def *def = &timecodes[n];
if (def->lookup)
lut_clear(&def->lut);
}
}
/*
* Initialise filter values for one channel
*/
static void init_channel(struct timecoder_channel *ch)
{
ch->positive = false;
ch->zero = 0;
}
/*
* Initialise a timecode decoder at the given reference speed
*
* Return: -1 if the timecoder could not be initialised, otherwise 0
*/
void timecoder_init(struct timecoder *tc, struct timecode_def *def,
double speed, unsigned int sample_rate, bool phono)
{
assert(def != NULL);
/* A definition contains a lookup table which can be shared
* across multiple timecoders */
assert(def->lookup);
tc->def = def;
tc->speed = speed;
tc->dt = 1.0 / sample_rate;
tc->zero_alpha = tc->dt / (ZERO_RC + tc->dt);
tc->threshold = ZERO_THRESHOLD;
if (phono)
tc->threshold >>= 5; /* approx -36dB */
tc->forwards = 1;
init_channel(&tc->primary);
init_channel(&tc->secondary);
pitch_init(&tc->pitch, tc->dt);
tc->ref_level = INT_MAX;
tc->bitstream = 0;
tc->timecode = 0;
tc->valid_counter = 0;
tc->timecode_ticker = 0;
tc->mon = NULL;
}
/*
* Clear resources associated with a timecode decoder
*/
void timecoder_clear(struct timecoder *tc)
{
assert(tc->mon == NULL);
}
/*
* Initialise a raster display of the incoming audio
*
* The monitor (otherwise known as 'scope' in the interface) is an x-y
* display of the post-calibrated incoming audio.
*
* Return: -1 if not enough memory could be allocated, otherwise 0
*/
int timecoder_monitor_init(struct timecoder *tc, int size)
{
assert(tc->mon == NULL);
tc->mon_size = size;
tc->mon = malloc(SQ(tc->mon_size));
if (tc->mon == NULL) {
perror("malloc");
return -1;
}
memset(tc->mon, 0, SQ(tc->mon_size));
tc->mon_counter = 0;
return 0;
}
/*
* Clear the monitor on the given timecoder
*/
void timecoder_monitor_clear(struct timecoder *tc)
{
assert(tc->mon != NULL);
free(tc->mon);
tc->mon = NULL;
}
/*
* Update channel information with axis-crossings
*/
static void detect_zero_crossing(struct timecoder_channel *ch,
signed int v, double alpha,
signed int threshold)
{
ch->crossing_ticker++;
ch->swapped = false;
if (v > ch->zero + threshold && !ch->positive) {
ch->swapped = true;
ch->positive = true;
ch->crossing_ticker = 0;
} else if (v < ch->zero - threshold && ch->positive) {
ch->swapped = true;
ch->positive = false;
ch->crossing_ticker = 0;
}
ch->zero += alpha * (v - ch->zero);
}
/*
* Plot the given sample value in the x-y monitor
*/
static void update_monitor(struct timecoder *tc, signed int x, signed int y)
{
int px, py, size, ref;
if (!tc->mon)
return;
size = tc->mon_size;
ref = tc->ref_level;
/* Decay the pixels already in the montior */
if (++tc->mon_counter % MONITOR_DECAY_EVERY == 0) {
int p;
for (p = 0; p < SQ(size); p++) {
if (tc->mon[p])
tc->mon[p] = tc->mon[p] * 7 / 8;
}
}
assert(ref > 0);
/* ref_level is half the precision of signal level */
px = size / 2 + (long long)x * size / ref / 8;
py = size / 2 + (long long)y * size / ref / 8;
if (px < 0 || px >= size || py < 0 || py >= size)
return;
tc->mon[py * size + px] = 0xff; /* white */
}
/*
* Extract the bitstream from the sample value
*/
static void process_bitstream(struct timecoder *tc, signed int m)
{
bits_t b;
b = m > tc->ref_level;
/* Add it to the bitstream, and work out what we were expecting
* (timecode). */
/* tc->bitstream is always in the order it is physically placed on
* the vinyl, regardless of the direction. */
if (tc->forwards) {
tc->timecode = fwd(tc->timecode, tc->def);
tc->bitstream = (tc->bitstream >> 1)
+ (b << (tc->def->bits - 1));
} else {
bits_t mask;
mask = ((1 << tc->def->bits) - 1);
tc->timecode = rev(tc->timecode, tc->def);
tc->bitstream = ((tc->bitstream << 1) & mask) + b;
}
if (tc->timecode == tc->bitstream)
tc->valid_counter++;
else {
tc->timecode = tc->bitstream;
tc->valid_counter = 0;
}
/* Take note of the last time we read a valid timecode */
tc->timecode_ticker = 0;
/* Adjust the reference level based on this new peak */
tc->ref_level -= tc->ref_level / REF_PEAKS_AVG;
tc->ref_level += m / REF_PEAKS_AVG;
debug("%+6d zero, %+6d (ref %+6d)\t= %d%c (%5d)",
tc->primary.zero,
m, tc->ref_level,
b, tc->valid_counter == 0 ? 'x' : ' ',
tc->valid_counter);
}
/*
* Process a single sample from the incoming audio
*
* The two input signals (primary and secondary) are in the full range
* of a signed int; ie. 32-bit signed.
*/
static void process_sample(struct timecoder *tc,
signed int primary, signed int secondary)
{
detect_zero_crossing(&tc->primary, primary, tc->zero_alpha, tc->threshold);
detect_zero_crossing(&tc->secondary, secondary, tc->zero_alpha, tc->threshold);
/* If an axis has been crossed, use the direction of the crossing
* to work out the direction of the vinyl */
if (tc->primary.swapped || tc->secondary.swapped) {
bool forwards;
if (tc->primary.swapped) {
forwards = (tc->primary.positive != tc->secondary.positive);
} else {
forwards = (tc->primary.positive == tc->secondary.positive);
}
if (tc->def->flags & SWITCH_PHASE)
forwards = !forwards;
if (forwards != tc->forwards) { /* direction has changed */
tc->forwards = forwards;
tc->valid_counter = 0;
}
}
/* If any axis has been crossed, register movement using the pitch
* counters */
if (!tc->primary.swapped && !tc->secondary.swapped)
pitch_dt_observation(&tc->pitch, 0.0);
else {
double dx;
dx = 1.0 / tc->def->resolution / 4;
if (!tc->forwards)
dx = -dx;
pitch_dt_observation(&tc->pitch, dx);
}
/* If we have crossed the primary channel in the right polarity,
* it's time to read off a timecode 0 or 1 value */
if (tc->secondary.swapped &&
tc->primary.positive == ((tc->def->flags & SWITCH_POLARITY) == 0))
{
signed int m;
/* scale to avoid clipping */
m = abs(primary / 2 - tc->primary.zero / 2);
process_bitstream(tc, m);
}
tc->timecode_ticker++;
}
/*
* Cycle to the next timecode definition which has a valid lookup
*
* Return: pointer to timecode definition
*/
static struct timecode_def* next_definition(struct timecode_def *def)
{
assert(def != NULL);
do {
def++;
if (def >= timecodes + ARRAY_SIZE(timecodes))
def = timecodes;
} while (!def->lookup);
return def;
}
/*
* Change the timecode definition to the next available
*/
void timecoder_cycle_definition(struct timecoder *tc)
{
tc->def = next_definition(tc->def);
tc->valid_counter = 0;
tc->timecode_ticker = 0;
}
/*
* Submit and decode a block of PCM audio data to the timecode decoder
*
* PCM data is in the full range of signed short; ie. 16-bit signed.
*/
void timecoder_submit(struct timecoder *tc, signed short *pcm, size_t npcm)
{
while (npcm--) {
signed int left, right, primary, secondary;
left = pcm[0] << 16;
right = pcm[1] << 16;
if (tc->def->flags & SWITCH_PRIMARY) {
primary = left;
secondary = right;
} else {
primary = right;
secondary = left;
}
process_sample(tc, primary, secondary);
update_monitor(tc, left, right);
pcm += TIMECODER_CHANNELS;
}
}
/*
* Get the last-known position of the timecode
*
* If now data is available or if too few bits have been error
* checked, then this counts as invalid. The last known position is
* given along with the time elapsed since the position stamp was
* read.
*
* Return: the known position of the timecode, or -1 if not known
* Post: if when != NULL, *when is the elapsed time in seconds
*/
signed int timecoder_get_position(struct timecoder *tc, double *when)
{
signed int r;
if (tc->valid_counter <= VALID_BITS)
return -1;
r = lut_lookup(&tc->def->lut, tc->bitstream);
if (r == -1)
return -1;
if (when)
*when = tc->timecode_ticker * tc->dt;
return r;
}
``` | /content/code_sandbox/libs/xwax/src/timecoder.c | c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,218 |
```objective-c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
/*
* Enable a specific debug message by prefixing with an underscore,
* otherwise -DDEBUG to enable all within that particular compile.
*/
#define _debug(...) { \
fprintf(stderr, "%s:%d: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
fputc('\n', stderr); \
}
#ifdef DEBUG
#define debug(...) _debug(__VA_ARGS__)
#else
#define debug(...)
#endif
#define not_implemented() abort()
#endif
``` | /content/code_sandbox/libs/xwax/xwax/debug.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 216 |
```objective-c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#ifndef TIMECODER_H
#define TIMECODER_H
#include <stdbool.h>
#include "lut.h"
#include "pitch.h"
#define TIMECODER_CHANNELS 2
typedef unsigned int bits_t;
struct timecode_def {
char *name, *desc;
int bits, /* number of bits in string */
resolution, /* wave cycles per second */
flags;
bits_t seed, /* LFSR value at timecode zero */
taps; /* central LFSR taps, excluding end taps */
unsigned int length, /* in cycles */
safe; /* last 'safe' timecode number (for auto disconnect) */
bool lookup; /* true if lut has been generated */
struct lut lut;
};
struct timecoder_channel {
bool positive, /* wave is in positive part of cycle */
swapped; /* wave recently swapped polarity */
signed int zero;
unsigned int crossing_ticker; /* samples since we last crossed zero */
};
struct timecoder {
struct timecode_def *def;
double speed;
/* Precomputed values */
double dt, zero_alpha;
signed int threshold;
/* Pitch information */
bool forwards;
struct timecoder_channel primary, secondary;
struct pitch pitch;
/* Numerical timecode */
signed int ref_level;
bits_t bitstream, /* actual bits from the record */
timecode; /* corrected timecode */
unsigned int valid_counter, /* number of successful error checks */
timecode_ticker; /* samples since valid timecode was read */
/* Feedback */
unsigned char *mon; /* x-y array */
int mon_size, mon_counter;
};
struct timecode_def* timecoder_find_definition(const char *name);
void timecoder_free_lookup(void);
void timecoder_init(struct timecoder *tc, struct timecode_def *def,
double speed, unsigned int sample_rate, bool phono);
void timecoder_clear(struct timecoder *tc);
int timecoder_monitor_init(struct timecoder *tc, int size);
void timecoder_monitor_clear(struct timecoder *tc);
void timecoder_cycle_definition(struct timecoder *tc);
void timecoder_submit(struct timecoder *tc, signed short *pcm, size_t npcm);
signed int timecoder_get_position(struct timecoder *tc, double *when);
/*
* The timecode definition currently in use by this decoder
*/
static inline struct timecode_def* timecoder_get_definition(struct timecoder *tc)
{
return tc->def;
}
/*
* Return the pitch relative to reference playback speed
*/
static inline double timecoder_get_pitch(struct timecoder *tc)
{
return pitch_current(&tc->pitch) / tc->speed;
}
/*
* The last 'safe' timecode value on the record. Beyond this value, we
* probably want to ignore the timecode values, as we will hit the
* label of the record.
*/
static inline unsigned int timecoder_get_safe(struct timecoder *tc)
{
return tc->def->safe;
}
/*
* The resolution of the timecode. This is the number of bits per
* second at reference playback speed
*/
static inline double timecoder_get_resolution(struct timecoder *tc)
{
return tc->def->resolution * tc->speed;
}
/*
* The number of revolutions per second of the timecode vinyl,
* used only for visual display
*/
static inline double timecoder_revs_per_sec(struct timecoder *tc)
{
return (33.0 + 1.0 / 3) * tc->speed / 60;
}
#endif
``` | /content/code_sandbox/libs/xwax/xwax/timecoder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 843 |
```objective-c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#ifndef PITCH_H
#define PITCH_H
/* Values for the filter concluded experimentally */
#define ALPHA (1.0/512)
#define BETA (ALPHA/256)
/* State of the pitch calculation filter */
struct pitch {
double dt, x, v;
};
/* Prepare the filter for observations every dt seconds */
static inline void pitch_init(struct pitch *p, double dt)
{
p->dt = dt;
p->x = 0.0;
p->v = 0.0;
}
/* Input an observation to the filter; in the last dt seconds the
* position has moved by dx.
*
* Because the vinyl uses timestamps, the values for dx are discrete
* rather than smooth. */
static inline void pitch_dt_observation(struct pitch *p, double dx)
{
double predicted_x, predicted_v, residual_x;
predicted_x = p->x + p->v * p->dt;
predicted_v = p->v;
residual_x = dx - predicted_x;
p->x = predicted_x + residual_x * ALPHA;
p->v = predicted_v + residual_x * BETA / p->dt;
p->x -= dx; /* relative to previous */
}
/* Get the pitch after filtering */
static inline double pitch_current(struct pitch *p)
{
return p->v;
}
#endif
``` | /content/code_sandbox/libs/xwax/xwax/pitch.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 388 |
```objective-c
/*
*
* This file is part of "xwax".
*
* "xwax" is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation.
*
* "xwax" 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
*
* along with this program; if not, see <path_to_url
*
*/
#ifndef LUT_H
#define LUT_H
typedef unsigned int slot_no_t;
struct slot {
unsigned int timecode;
slot_no_t next; /* next slot with the same hash */
};
struct lut {
struct slot *slot;
slot_no_t *table, /* hash -> slot lookup */
avail; /* next available slot */
};
int lut_init(struct lut *lut, int nslots);
void lut_clear(struct lut *lut);
void lut_push(struct lut *lut, unsigned int timecode);
unsigned int lut_lookup(struct lut *lut, unsigned int timecode);
#endif
``` | /content/code_sandbox/libs/xwax/xwax/lut.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 226 |
```shell
xcrun stapler staple Bespoke-Mac.dmg
``` | /content/code_sandbox/scripts/installer_macOS/post_notarization_staple.sh | shell | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 13 |
```shell
#!/bin/sh
# requires appdmg, which can be installed via: npm install -g appdmg
rm Bespoke-Mac.dmg
rm -rf BespokeSynth.app
ditto ../../ignore/build/Source/BespokeSynth_artefacts/Release/BespokeSynth.app BespokeSynth.app
#codesign --force --options runtime --timestamp --verbose=4 --entitlements entitlements.plist --sign "Developer ID Application: Ryan Challinor (J5RJ562GN5)" BespokeSynth.app/Contents/MacOS/BespokeSynth
#codesign --force --options runtime --timestamp --verbose=4 --entitlements entitlements.plist --sign "Developer ID Application: Ryan Challinor (J5RJ562GN5)" BespokeSynth.app/Contents/Frameworks/Python.framework/Versions/3.9/Python
#codesign --force --options runtime --timestamp --verbose=4 --entitlements entitlements.plist --sign "Developer ID Application: Ryan Challinor (J5RJ562GN5)" BespokeSynth.app/Contents/Frameworks/Python.framework/Versions/3.9/bin/python3.9
#codesign --force --options runtime --timestamp --verbose=4 --entitlements entitlements.plist --sign "Developer ID Application: Ryan Challinor (J5RJ562GN5)" BespokeSynth.app/Contents/Frameworks/Python.framework/Versions/3.9/Resources/Python.app/Contents/MacOS/Python
appdmg bespoke_dmg.json Bespoke-Mac.dmg
codesign -s "Developer ID Application: Ryan Challinor (J5RJ562GN5)" --timestamp Bespoke-Mac.dmg
``` | /content/code_sandbox/scripts/installer_macOS/build_dmg.sh | shell | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 370 |
```shell
xcrun notarytool --notarize-app --primary-bundle-id "com.ryanchallinor.bespokesynth" --apple-id "awwbees@gmail.com" --password "@keychain:Bespoke app-specific password" -t osx -f Bespoke-Mac.dmg
``` | /content/code_sandbox/scripts/installer_macOS/notarize.sh | shell | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 65 |
```shell
#!/bin/bash
#this is pulled from surge and adapted: path_to_url
# Documentation for pkgbuild and productbuild: path_to_url
# preflight check
INDIR=$1
SOURCEDIR=$2
TARGET_DIR=$3
VERSION=$4
echo "MAKE from $INDIR $SOURCEDIR into $TARGET_DIR with $VERSION"
if [ "$VERSION" == "" ]; then
echo "You must specify the version you are packaging!"
echo "eg: ./make_installer.sh 1.0.6b4"
exit 1
fi
OUTPUT_BASE_FILENAME="BespokeSynth-Mac-$VERSION"
mkdir -p "${TARGET_DIR}"
echo "{ \"title\": \"Bespoke\", \"background\": \"${SOURCEDIR}/background.png\", \"icon-size\": 80," > dmg_manifest.json
echo "\"contents\": [ { \"x\": 192, \"y\": 338, \"type\": \"file\", \"path\": \"${INDIR}/BespokeSynth.app\"}, " >> dmg_manifest.json
echo "{ \"x\": 448, \"y\": 338, \"type\": \"link\", \"path\": \"/Applications\" }]}" >> dmg_manifest.json
appdmg "dmg_manifest.json" "${TARGET_DIR}/$OUTPUT_BASE_FILENAME.dmg"
echo "dmg created at ${TARGET_DIR}/$OUTPUT_BASE_FILENAME.dmg"
if [[ ! -z $MAC_SIGNING_CERT ]]; then
echo "running codesign with cert $MAC_SIGNING_CERT"
codesign --force -s "$MAC_SIGNING_CERT" --timestamp "${TARGET_DIR}/$OUTPUT_BASE_FILENAME.dmg"
echo "checking codesign"
codesign -vvv "${TARGET_DIR}/$OUTPUT_BASE_FILENAME.dmg"
echo "running notarytool"
xcrun notarytool submit "${TARGET_DIR}/$OUTPUT_BASE_FILENAME.dmg" \
--apple-id ${MAC_SIGNING_ID} \
--team-id ${MAC_SIGNING_TEAM} \
--password ${MAC_SIGNING_1UPW} \
--wait
echo "running stapler"
xcrun stapler staple "${TARGET_DIR}/${OUTPUT_BASE_FILENAME}.dmg"
fi
# clean up
``` | /content/code_sandbox/scripts/installer_macOS/make_installer.sh | shell | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 473 |
```desktop
[Desktop Entry]
Name=BespokeSynth
GenericName=Software modular synth
Comment=Software modular synth with controllers support, scripting and VST
Exec=BespokeSynth
Icon=bespoke_icon
Categories=AudioVideo;Audio;Music;Midi
Terminal=false
Type=Application
Keywords=MIDI;Synth;VST
``` | /content/code_sandbox/scripts/installer_linux/BespokeSynth.desktop | desktop | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 75 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
AudioToCV.cpp
Created: 18 Nov 2017 10:46:05pm
Author: Ryan Challinor
==============================================================================
*/
#include "AudioToCV.h"
#include "Profiler.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
AudioToCV::AudioToCV()
: IAudioProcessor(gBufferSize)
{
mModulationBuffer = new float[gBufferSize];
}
void AudioToCV::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGainSlider = new FloatSlider(this, "gain", 3, 2, 100, 15, &mGain, 1, 10);
mMinSlider = new FloatSlider(this, "min", mGainSlider, kAnchor_Below, 100, 15, &mDummyMin, 0, 1);
mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1);
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
AudioToCV::~AudioToCV()
{
delete[] mModulationBuffer;
}
void AudioToCV::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mGainSlider->Draw();
mMinSlider->Draw();
mMaxSlider->Draw();
ofPushStyle();
ofSetColor(0, 255, 0, gModuleDrawAlpha);
ofBeginShape();
float x, y;
float w, h;
mGainSlider->GetPosition(x, y, K(local));
mGainSlider->GetDimensions(w, h);
for (int i = 0; i < gBufferSize; ++i)
{
ofVertex(ofMap(mModulationBuffer[i], -1, 1, x, x + w, K(clamp)), ofMap(i, 0, gBufferSize, y, y + h), K(clamp));
}
ofEndShape();
ofPopStyle();
}
void AudioToCV::Process(double time)
{
PROFILER(AudioToCV);
if (!mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
assert(GetBuffer()->BufferSize());
Clear(gWorkBuffer, gBufferSize);
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
Add(gWorkBuffer, GetBuffer()->GetChannel(ch), gBufferSize);
BufferCopy(mModulationBuffer, gWorkBuffer, gBufferSize);
Mult(mModulationBuffer, mGain, gBufferSize);
GetBuffer()->Reset();
}
void AudioToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
}
float AudioToCV::Value(int samplesIn)
{
return ofMap(mModulationBuffer[samplesIn] / 2 + .5f, 0, 1, GetMin(), GetMax(), K(clamp));
}
void AudioToCV::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void AudioToCV::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void AudioToCV::SetUpFromSaveData()
{
}
void AudioToCV::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
}
void AudioToCV::LoadState(FileStreamIn& in, int rev)
{
if (rev < 1)
{
// Temporary additional cable source
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
IDrawableModule::LoadState(in, rev);
if (rev < 1)
{
const auto target = GetPatchCableSource(1)->GetTarget();
if (target != nullptr)
GetPatchCableSource()->SetTarget(target);
RemovePatchCableSource(GetPatchCableSource(1));
mTargetCable = GetPatchCableSource();
}
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
}
``` | /content/code_sandbox/Source/AudioToCV.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,063 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// ClipLauncher.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/17/15.
//
//
#include "ClipLauncher.h"
#include "IAudioReceiver.h"
#include "Sample.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "Looper.h"
#include "FillSaveDropdown.h"
ClipLauncher::ClipLauncher()
{
}
void ClipLauncher::Init()
{
IDrawableModule::Init();
TheTransport->AddListener(this, kInterval_1n, OffsetInfo(0, true), false);
}
void ClipLauncher::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolumeSlider = new FloatSlider(this, "volume", 5, 2, 110, 15, &mVolume, 0, 2);
}
ClipLauncher::~ClipLauncher()
{
TheTransport->RemoveListener(this);
}
void ClipLauncher::Process(double time)
{
PROFILER(ClipLauncher);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
int sampleToPlay = -1;
for (int i = 0; i < mSamples.size(); ++i)
{
if (mSamples[i].mPlay)
sampleToPlay = i;
}
Sample* sample = nullptr;
float volSq = 1;
if (sampleToPlay != -1)
{
mSampleMutex.lock();
sample = mSamples[sampleToPlay].mSample;
volSq = mVolume * mSamples[sampleToPlay].mVolume;
volSq *= volSq;
float speed = sample->LengthInSamples() * gInvSampleRateMs / TheTransport->MsPerBar() / mSamples[sampleToPlay].mNumBars;
RecalcPos(time, sampleToPlay);
sample->SetRate(speed);
}
if (sample)
{
gWorkChannelBuffer.SetNumActiveChannels(1);
sample->ConsumeData(time, &gWorkChannelBuffer, bufferSize, true);
}
for (int i = 0; i < bufferSize; ++i)
{
float samp = 0;
if (sample)
samp = gWorkChannelBuffer.GetChannel(0)[i] * volSq;
samp = mJumpBlender.Process(samp, i);
out[i] += samp;
GetVizBuffer()->Write(samp, 0);
}
if (sampleToPlay != -1)
mSampleMutex.unlock();
}
void ClipLauncher::DropdownClicked(DropdownList* list)
{
}
void ClipLauncher::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void ClipLauncher::OnTimeEvent(double time)
{
}
void ClipLauncher::DrawModule()
{
DrawConnection(mLooper);
if (Minimized() || IsVisible() == false)
return;
mVolumeSlider->Draw();
for (int i = 0; i < mSamples.size(); ++i)
{
mSamples[i].Draw();
}
}
int ClipLauncher::GetRowY(int idx)
{
return 20 + idx * 40;
}
void ClipLauncher::ButtonClicked(ClickButton* button, double time)
{
}
void ClipLauncher::CheckboxUpdated(Checkbox* checkbox, double time)
{
for (int i = 0; i < mSamples.size(); ++i)
{
if (checkbox == mSamples[i].mPlayCheckbox)
{
int currentlyPlaying = -1;
for (int j = 0; j < mSamples.size(); ++j)
{
if (j != i && mSamples[j].mPlay)
currentlyPlaying = j;
}
for (int j = 0; j < mSamples.size(); ++j)
{
if (j != i)
mSamples[j].mPlay = false;
}
int newPlaying = -1;
for (int j = 0; j < mSamples.size(); ++j)
{
if (mSamples[j].mPlay)
newPlaying = j;
}
if (currentlyPlaying != newPlaying)
{
mSampleMutex.lock();
float data[JUMP_BLEND_SAMPLES];
ChannelBuffer temp(data, JUMP_BLEND_SAMPLES);
if (currentlyPlaying != -1)
mSamples[currentlyPlaying].mSample->ConsumeData(time, &temp, JUMP_BLEND_SAMPLES, true);
mJumpBlender.CaptureForJump(0, data, JUMP_BLEND_SAMPLES, gBufferSize);
mSampleMutex.unlock();
}
}
if (checkbox == mSamples[i].mGrabCheckbox)
{
if (mSamples[i].mHasSample)
{
if (mSamples[i].mPlay)
mSampleMutex.lock();
int bufferSize;
mSamples[i].mSample->Create(mLooper->GetLoopBuffer(bufferSize));
mSamples[i].mNumBars = mLooper->GetNumBars();
mLooper->Clear();
if (mSamples[i].mPlay)
mSampleMutex.unlock();
for (int j = 0; j < mSamples.size(); ++j)
mSamples[j].mPlay = (j == i);
}
else
{
mSamples[i].mPlay = false;
mSamples[i].mSample->Create(1);
}
}
}
}
void ClipLauncher::GetModuleDimensions(float& width, float& height)
{
width = 180;
height = 180;
}
void ClipLauncher::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void ClipLauncher::RecalcPos(double time, int idx)
{
int numBars = mSamples[idx].mNumBars;
Sample* sample = mSamples[idx].mSample;
if (sample)
{
float measurePos = TheTransport->GetMeasure(time) % numBars + TheTransport->GetMeasurePos(time);
int pos = ofMap(measurePos / numBars, 0, 1, 0, sample->LengthInSamples(), true);
sample->SetPlayPosition(pos);
}
}
void ClipLauncher::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void ClipLauncher::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadString("looper", moduleInfo, "", FillDropdown<Looper*>);
mModuleSaveData.LoadInt("numclips", moduleInfo, 4, 1, 16);
SetUpFromSaveData();
}
void ClipLauncher::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
mLooper = dynamic_cast<Looper*>(TheSynth->FindModule(mModuleSaveData.GetString("looper"), false));
mSamples.resize(mModuleSaveData.GetInt("numclips"));
for (int i = 0; i < mSamples.size(); ++i)
{
mSamples[i].Init(this, i);
}
}
ClipLauncher::SampleData::~SampleData()
{
delete mSample;
}
void ClipLauncher::SampleData::Init(ClipLauncher* launcher, int index)
{
mClipLauncher = launcher;
mIndex = index;
delete mSample;
if (mGrabCheckbox)
{
launcher->RemoveUIControl(mGrabCheckbox);
mGrabCheckbox->Delete();
}
if (mPlayCheckbox)
{
launcher->RemoveUIControl(mPlayCheckbox);
mPlayCheckbox->Delete();
}
std::string indexStr = ofToString(index + 1);
mSample = new Sample();
mSample->SetLooping(true);
int y = launcher->GetRowY(index);
mGrabCheckbox = new Checkbox(launcher, ("grab" + indexStr).c_str(), 110, y, &mHasSample);
mPlayCheckbox = new Checkbox(launcher, ("play" + indexStr).c_str(), 110, y + 20, &mPlay);
}
void ClipLauncher::SampleData::Draw()
{
ofPushMatrix();
ofTranslate(5, mClipLauncher->GetRowY(mIndex));
DrawAudioBuffer(100, 36, mSample->Data(), 0, mSample->LengthInSamples(), mPlay ? mSample->GetPlayPosition() : -1);
ofPopMatrix();
mGrabCheckbox->Draw();
mPlayCheckbox->Draw();
}
``` | /content/code_sandbox/Source/ClipLauncher.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,962 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// NoteVibrato.h
// Bespoke
//
// Created by Ryan Challinor on 12/27/15.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "DropdownList.h"
#include "Transport.h"
class NoteVibrato : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IDropdownListener, public IAudioPoller
{
public:
NoteVibrato();
virtual ~NoteVibrato();
static IDrawableModule* Create() { return new NoteVibrato(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void OnTransportAdvanced(float amount) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 138;
height = 22;
}
NoteInterval mVibratoInterval{ NoteInterval::kInterval_16n };
DropdownList* mIntervalSelector{ nullptr };
float mVibratoAmount{ 0 };
FloatSlider* mVibratoSlider{ nullptr };
Modulations mModulation{ true };
};
``` | /content/code_sandbox/Source/NoteVibrato.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 548 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// FloatSliderLFOControl.h
// modularSynth
//
// Created by Ryan Challinor on 2/22/13.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Transport.h"
#include "LFO.h"
#include "RadioButton.h"
#include "Slider.h"
#include "ClickButton.h"
#include "PatchCableSource.h"
#include "DropdownList.h"
#include "IModulator.h"
struct LFOSettings
{
NoteInterval mInterval{ kInterval_1n };
OscillatorType mOscType{ kOsc_Sin };
float mLFOOffset{ 0 };
float mBias{ 0 };
float mSpread{ 0 };
float mSoften{ 0 };
float mShuffle{ 0 };
float mFreeRate{ 1 };
float mLength{ 1 };
bool mLowResMode{ false };
void SaveState(FileStreamOut& out) const;
void LoadState(FileStreamIn& in);
};
class FloatSliderLFOControl : public IDrawableModule, public IRadioButtonListener, public IFloatSliderListener, public IButtonListener, public IDropdownListener, public IModulator
{
public:
FloatSliderLFOControl();
static IDrawableModule* Create() { return new FloatSliderLFOControl(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void Delete() { delete this; }
void DrawModule() override;
const LFOSettings& GetSettings() { return mLFOSettings; }
void Load(LFOSettings settings);
LFOSettings* GetLFOSettings() { return &mLFOSettings; }
void SetEnabled(bool enabled) override {} //don't use this one
void SetLFOEnabled(bool enabled);
bool IsEnabled() const override { return mEnabled; }
void SetRate(NoteInterval rate);
void UpdateFromSettings();
void SetOwner(FloatSlider* owner);
FloatSlider* GetOwner() { return mTargets[0].mSliderTarget; }
bool HasTitleBar() const override { return mPinned; }
bool IsSaveable() override { return mPinned; }
void CreateUIControls() override;
bool IsPinned() const { return mPinned; }
void RandomizeSettings();
bool InLowResMode() const { return mLFOSettings.mLowResMode; }
bool HasSpecialDelete() const override { return true; }
void DoSpecialDelete() override;
bool DrawToPush2Screen() override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
bool InitializeWithZeroRange() const override { return true; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
protected:
virtual ~FloatSliderLFOControl();
private:
void UpdateVisibleControls();
float GetLFOValue(int samplesIn = 0, float forcePhase = -1);
float GetTargetMin() const;
float GetTargetMax() const;
LFOSettings mLFOSettings;
LFO mLFO;
DropdownList* mIntervalSelector{ nullptr };
DropdownList* mOscSelector{ nullptr };
FloatSlider* mOffsetSlider{ nullptr };
FloatSlider* mBiasSlider{ nullptr };
FloatSlider* mSpreadSlider{ nullptr };
FloatSlider* mSoftenSlider{ nullptr };
FloatSlider* mShuffleSlider{ nullptr };
FloatSlider* mFreeRateSlider{ nullptr };
FloatSlider* mLengthSlider{ nullptr };
ClickButton* mPinButton{ nullptr };
Checkbox* mEnableLFOCheckbox{ nullptr };
Checkbox* mLowResModeCheckbox{ nullptr };
float mWidth{ 100 };
float mHeight{ 20 };
bool mPinned{ false };
};
class LFOPool
{
public:
static void Init();
static void Shutdown();
static FloatSliderLFOControl* GetLFO(FloatSlider* owner);
private:
#define LFO_POOL_SIZE 256
static FloatSliderLFOControl* sLFOPool[LFO_POOL_SIZE];
static int sNextLFOIndex;
static bool sInitialized;
};
``` | /content/code_sandbox/Source/FloatSliderLFOControl.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,196 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Rewriter.h
// modularSynth
//
// Created by Ryan Challinor on 3/16/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "RollingBuffer.h"
#include "MidiDevice.h"
#include "Checkbox.h"
class Looper;
class Rewriter : public IAudioProcessor, public IDrawableModule, public IButtonListener
{
public:
Rewriter();
virtual ~Rewriter();
static IDrawableModule* Create() { return new Rewriter(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Go(double time);
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IAudioSource
void Process(double time) override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = mWidth;
h = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
double mStartRecordTime{ -1 };
ClickButton* mRewriteButton{ nullptr };
ClickButton* mStartRecordTimeButton{ nullptr };
RollingBuffer mRecordBuffer;
Looper* mConnectedLooper{ nullptr };
PatchCableSource* mLooperCable{ nullptr };
};
``` | /content/code_sandbox/Source/Rewriter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 526 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Splitter.h
Created: 10 Oct 2017 9:50:00pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "RollingBuffer.h"
#include "Ramp.h"
#include "PatchCableSource.h"
class Splitter : public IAudioProcessor, public IDrawableModule
{
public:
Splitter();
virtual ~Splitter();
static IDrawableModule* Create() { return new Splitter(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
int GetNumTargets() override { return 2; }
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 80;
h = 10;
}
RollingBuffer mVizBuffer2;
PatchCableSource* mPatchCableSource2{ nullptr };
};
``` | /content/code_sandbox/Source/Splitter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 391 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Producer.h
// modularSynth
//
// Created by Ryan Challinor on 11/13/13.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "BiquadFilterEffect.h"
#define PRODUCER_NUM_BIQUADS 5
class Sample;
class Producer : public IAudioSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public INoteReceiver
{
public:
Producer();
~Producer();
static IDrawableModule* Create() { return new Producer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IFloatSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IDropdownListener
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
void UpdateSample();
void DoWrite();
void UpdateZoomExtents();
int GetMeasureSample(int measure);
float GetBufferPos(int sample);
int GetMeasureForSample(int sample);
int GetSamplesPerMeasure();
bool IsSkipMeasure(int measure);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
Sample* mSample{ nullptr };
float mVolume{ .6 };
FloatSlider* mVolumeSlider{ nullptr };
float* mWriteBuffer{ nullptr };
bool mPlay{ false };
Checkbox* mPlayCheckbox{ nullptr };
bool mLoop{ false };
Checkbox* mLoopCheckbox{ nullptr };
float mClipStart{ 0 };
FloatSlider* mClipStartSlider{ nullptr };
float mClipEnd{ 1 };
FloatSlider* mClipEndSlider{ nullptr };
float mZoomStart{ 0 };
FloatSlider* mZoomStartSlider{ nullptr };
float mZoomEnd{ 1 };
FloatSlider* mZoomEndSlider{ nullptr };
float mOffset{ 0 };
FloatSlider* mOffsetSlider{ nullptr };
int mNumBars{ 1 };
IntSlider* mNumBarsSlider{ nullptr };
ClickButton* mWriteButton{ nullptr };
int mPlayhead{ 0 };
float mTempo{ 120 };
FloatSlider* mTempoSlider{ nullptr };
int mStartOffset{ 0 };
ClickButton* mCalcTempoButton{ nullptr };
IntSlider* mStartOffsetSlider{ nullptr };
ClickButton* mDoubleLengthButton{ nullptr };
ClickButton* mHalveLengthButton{ nullptr };
BiquadFilterEffect mBiquad[PRODUCER_NUM_BIQUADS];
std::list<int> mSkipMeasures;
ClickButton* mRestartButton{ nullptr };
};
``` | /content/code_sandbox/Source/Producer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,015 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// FMSynth.h
// modularSynth
//
// Created by Ryan Challinor on 1/6/13.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "PolyphonyMgr.h"
#include "FMVoice.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ADSRDisplay.h"
class FMSynth : public IAudioSource, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener
{
public:
FMSynth();
~FMSynth();
static IDrawableModule* Create() { return new FMSynth(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool HasDebugDraw() const override { return true; }
bool IsEnabled() const override { return mEnabled; }
private:
void UpdateHarmonicRatio();
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 180;
height = 203;
}
PolyphonyMgr mPolyMgr;
NoteInputBuffer mNoteInputBuffer;
FMVoiceParams mVoiceParams;
FloatSlider* mVolSlider{ nullptr };
ADSRDisplay* mAdsrDisplayVol{ nullptr };
FloatSlider* mPhaseOffsetSlider0{ nullptr };
FloatSlider* mHarmSlider{ nullptr };
ADSRDisplay* mAdsrDisplayHarm{ nullptr };
FloatSlider* mModSlider{ nullptr };
ADSRDisplay* mAdsrDisplayMod{ nullptr };
int mHarmRatioBase{ 1 }; //negative means 1/val
float mHarmRatioTweak{ 1 };
DropdownList* mHarmRatioBaseDropdown{ nullptr };
FloatSlider* mPhaseOffsetSlider1{ nullptr };
FloatSlider* mHarmSlider2{ nullptr };
ADSRDisplay* mAdsrDisplayHarm2{ nullptr };
FloatSlider* mModSlider2{ nullptr };
ADSRDisplay* mAdsrDisplayMod2{ nullptr };
int mHarmRatioBase2{ 1 }; //negative means 1/val
float mHarmRatioTweak2{ 1 };
DropdownList* mHarmRatioBaseDropdown2{ nullptr };
FloatSlider* mPhaseOffsetSlider2{ nullptr };
ChannelBuffer mWriteBuffer;
};
``` | /content/code_sandbox/Source/FMSynth.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 826 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// NoteFilter.h
// Bespoke
//
// Created by Ryan Challinor on 11/28/15.
//
//
#pragma once
#include <stdio.h>
#include "NoteEffectBase.h"
class NoteFilter : public NoteEffectBase, public IDrawableModule
{
public:
NoteFilter();
virtual ~NoteFilter();
static IDrawableModule* Create() { return new NoteFilter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
std::array<bool, 128> mGate;
std::array<float, 128> mLastPlayTime;
std::vector<Checkbox*> mGateCheckboxes;
int mMinPitch{ 0 };
int mMaxPitch{ 7 };
};
``` | /content/code_sandbox/Source/NoteFilter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 406 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// SingleOscillator.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/4/13.
//
//
#include "SingleOscillator.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "ofxJSONElement.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "UIControlMacros.h"
SingleOscillator::SingleOscillator()
: mPolyMgr(this)
, mNoteInputBuffer(this)
, mWriteBuffer(gBufferSize)
{
mVoiceParams.mAdsr.Set(10, 0, 1, 10);
mVoiceParams.mVol = .25f;
mVoiceParams.mPulseWidth = .5f;
mVoiceParams.mSyncMode = Oscillator::SyncMode::None;
mVoiceParams.mSyncFreq = 200;
mVoiceParams.mSyncRatio = 1;
mVoiceParams.mMult = 1;
mVoiceParams.mOscType = kOsc_Square;
mVoiceParams.mDetune = 0;
mVoiceParams.mFilterAdsr.Set(1, 0, 1, 1000);
mVoiceParams.mFilterCutoffMax = SINGLEOSCILLATOR_NO_CUTOFF;
mVoiceParams.mFilterCutoffMin = 10;
mVoiceParams.mFilterQ = sqrt(2) / 2;
mVoiceParams.mShuffle = 0;
mVoiceParams.mPhaseOffset = 0;
mVoiceParams.mUnison = 1;
mVoiceParams.mUnisonWidth = 0;
mVoiceParams.mVelToVolume = .5f;
mVoiceParams.mVelToEnvelope = 0;
mVoiceParams.mSoften = 0;
mVoiceParams.mLiteCPUMode = false;
mPolyMgr.Init(kVoiceType_SingleOscillator, &mVoiceParams);
}
namespace
{
const float kColumnWidth = 90;
const float kGap = 5;
}
void SingleOscillator::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float width, height;
UIBLOCK(3 + kGap + kColumnWidth, 3, kColumnWidth);
UICONTROL_CUSTOM(mADSRDisplay, new ADSRDisplay(UICONTROL_BASICS("env"), kColumnWidth, 36, &mVoiceParams.mAdsr));
FLOATSLIDER(mVolSlider, "vol", &mVoiceParams.mVol, 0, 1);
FLOATSLIDER_DIGITS(mDetuneSlider, "detune", &mVoiceParams.mDetune, -.05f, .05f, 3);
INTSLIDER(mUnisonSlider, "unison", &mVoiceParams.mUnison, 1, SingleOscillatorVoice::kMaxUnison);
FLOATSLIDER(mUnisonWidthSlider, "width", &mVoiceParams.mUnisonWidth, 0, 1);
CHECKBOX(mLiteCPUModeCheckbox, "lite cpu", &mVoiceParams.mLiteCPUMode);
ENDUIBLOCK(width, height);
mWidth = MAX(width, mWidth);
mHeight = MAX(height, mHeight);
UIBLOCK(3, 42, kColumnWidth);
DROPDOWN(mOscSelector, "osc", (int*)(&mVoiceParams.mOscType), kColumnWidth / 2);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mMultSelector, "mult", &mMult, kColumnWidth / 2 - 3);
UIBLOCK_NEWLINE();
FLOATSLIDER_DIGITS(mPulseWidthSlider, "pw", &mVoiceParams.mPulseWidth, 0.01f, .99f, 2);
FLOATSLIDER(mShuffleSlider, "shuffle", &mVoiceParams.mShuffle, 0, 1);
FLOATSLIDER(mSoftenSlider, "soften", &mVoiceParams.mSoften, 0, 1);
FLOATSLIDER(mPhaseOffsetSlider, "phase", &mVoiceParams.mPhaseOffset, 0, TWO_PI);
DROPDOWN(mSyncModeSelector, "syncmode", (int*)(&mVoiceParams.mSyncMode), 60);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_PUSHSLIDERWIDTH(47);
FLOATSLIDER(mSyncFreqSlider, "syncf", &mVoiceParams.mSyncFreq, 10, 999.9f);
UIBLOCK_SHIFTLEFT();
FLOATSLIDER(mSyncRatioSlider, "syncratio", &mVoiceParams.mSyncRatio, .1f, 10.0f);
UIBLOCK_NEWLINE();
UIBLOCK_POPSLIDERWIDTH();
ENDUIBLOCK(width, height);
mWidth = MAX(width, mWidth);
mHeight = MAX(height, mHeight);
UIBLOCK(3 + (kGap + kColumnWidth) * 2, 3, kColumnWidth);
UICONTROL_CUSTOM(mFilterADSRDisplay, new ADSRDisplay(UICONTROL_BASICS("envfilter"), kColumnWidth, 36, &mVoiceParams.mFilterAdsr));
FLOATSLIDER(mFilterCutoffMaxSlider, "fmax", &mVoiceParams.mFilterCutoffMax, 10, SINGLEOSCILLATOR_NO_CUTOFF);
FLOATSLIDER(mFilterCutoffMinSlider, "fmin", &mVoiceParams.mFilterCutoffMin, 10, SINGLEOSCILLATOR_NO_CUTOFF);
FLOATSLIDER_DIGITS(mFilterQSlider, "q", &mVoiceParams.mFilterQ, .1, 20, 3);
FLOATSLIDER(mVelToVolumeSlider, "vel2vol", &mVoiceParams.mVelToVolume, 0, 1);
FLOATSLIDER(mVelToEnvelopeSlider, "vel2env", &mVoiceParams.mVelToEnvelope, -1, 1);
ENDUIBLOCK(width, height);
mWidth = MAX(width, mWidth);
mHeight = MAX(height, mHeight);
mOscSelector->AddLabel("sin", kOsc_Sin);
mOscSelector->AddLabel("squ", kOsc_Square);
mOscSelector->AddLabel("tri", kOsc_Tri);
mOscSelector->AddLabel("saw", kOsc_Saw);
mOscSelector->AddLabel("-saw", kOsc_NegSaw);
mOscSelector->AddLabel("noise", kOsc_Random);
mSyncModeSelector->AddLabel("no sync", (int)Oscillator::SyncMode::None);
mSyncModeSelector->AddLabel("ratio", (int)Oscillator::SyncMode::Ratio);
mSyncModeSelector->AddLabel("freq", (int)Oscillator::SyncMode::Frequency);
mSyncFreqSlider->SetShowName(false);
mSyncRatioSlider->SetShowName(false);
mSyncRatioSlider->SetMode(FloatSlider::kSquare);
mFilterCutoffMaxSlider->SetMaxValueDisplay("none");
mMultSelector->AddLabel("1/8", -8);
mMultSelector->AddLabel("1/7", -7);
mMultSelector->AddLabel("1/6", -6);
mMultSelector->AddLabel("1/5", -5);
mMultSelector->AddLabel("1/4", -4);
mMultSelector->AddLabel("1/3", -3);
mMultSelector->AddLabel("1/2", -2);
mMultSelector->AddLabel("1", 1);
mMultSelector->AddLabel("1.5", -1);
mMultSelector->AddLabel("2", 2);
mMultSelector->AddLabel("3", 3);
mMultSelector->AddLabel("4", 4);
mMultSelector->AddLabel("5", 5);
mMultSelector->AddLabel("6", 6);
mMultSelector->AddLabel("7", 7);
mMultSelector->AddLabel("8", 8);
mFilterCutoffMaxSlider->SetMode(FloatSlider::kSquare);
mFilterCutoffMinSlider->SetMode(FloatSlider::kSquare);
mFilterQSlider->SetMode(FloatSlider::kSquare);
}
SingleOscillator::~SingleOscillator()
{
}
void SingleOscillator::Process(double time)
{
PROFILER(SingleOscillator);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
mNoteInputBuffer.Process(time);
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
assert(bufferSize == gBufferSize);
mWriteBuffer.Clear();
mPolyMgr.Process(time, &mWriteBuffer, bufferSize);
SyncOutputBuffer(mWriteBuffer.NumActiveChannels());
for (int ch = 0; ch < mWriteBuffer.NumActiveChannels(); ++ch)
{
GetVizBuffer()->WriteChunk(mWriteBuffer.GetChannel(ch), mWriteBuffer.BufferSize(), ch);
Add(target->GetBuffer()->GetChannel(ch), mWriteBuffer.GetChannel(ch), gBufferSize);
}
}
void SingleOscillator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
return;
if (!NoteInputBuffer::IsTimeWithinFrame(time) && GetTarget())
{
mNoteInputBuffer.QueueNote(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (velocity > 0)
{
mPolyMgr.Start(time, pitch, velocity / 127.0f, voiceIdx, modulation);
float adsrScale = SingleOscillatorVoice::GetADSRScale(velocity / 127.0f, mVoiceParams.mVelToEnvelope);
mVoiceParams.mAdsr.Start(time, 1, adsrScale); //for visualization
mVoiceParams.mFilterAdsr.Start(time, 1, adsrScale); //for visualization
}
else
{
mPolyMgr.Stop(time, pitch, voiceIdx);
mVoiceParams.mAdsr.Stop(time, false); //for visualization
mVoiceParams.mFilterAdsr.Stop(time, false); //for visualization
}
if (mDrawDebug)
{
mDebugLines[mDebugLinesPos].text = "PlayNote(" + ofToString(time / 1000) + ", " + ofToString(pitch) + ", " + ofToString(velocity) + ", " + ofToString(voiceIdx) + ")";
if (velocity > 0)
mDebugLines[mDebugLinesPos].color = ofColor::lime;
else
mDebugLines[mDebugLinesPos].color = ofColor::red;
ofLog() << mDebugLines[mDebugLinesPos].text;
mDebugLinesPos = (mDebugLinesPos + 1) % (int)mDebugLines.size();
}
}
void SingleOscillator::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void SingleOscillator::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mSyncFreqSlider->SetShowing(mVoiceParams.mSyncMode == Oscillator::SyncMode::Frequency);
mSyncRatioSlider->SetShowing(mVoiceParams.mSyncMode == Oscillator::SyncMode::Ratio);
mVolSlider->Draw();
mPhaseOffsetSlider->Draw();
mPulseWidthSlider->Draw();
mSyncModeSelector->Draw();
mSyncFreqSlider->Draw();
mSyncRatioSlider->Draw();
mOscSelector->Draw();
mDetuneSlider->Draw();
mUnisonSlider->Draw();
mUnisonWidthSlider->Draw();
mShuffleSlider->Draw();
mVelToVolumeSlider->Draw();
mVelToEnvelopeSlider->Draw();
mFilterADSRDisplay->Draw();
mFilterCutoffMaxSlider->Draw();
mFilterCutoffMinSlider->Draw();
mFilterQSlider->Draw();
if (mVoiceParams.mFilterCutoffMax == SINGLEOSCILLATOR_NO_CUTOFF)
{
ofPushStyle();
ofSetColor(0, 0, 0, 100);
ofFill();
ofRect(mFilterADSRDisplay->GetRect(true).grow(1));
ofRect(mFilterCutoffMinSlider->GetRect(true));
ofRect(mFilterQSlider->GetRect(true));
ofPopStyle();
}
mADSRDisplay->Draw();
mMultSelector->Draw();
mSoftenSlider->Draw();
mLiteCPUModeCheckbox->Draw();
{
ofPushStyle();
int x = 3;
int y = 3;
int height = 36;
int width = kColumnWidth;
ofSetColor(100, 100, .8f * gModuleDrawAlpha);
ofSetLineWidth(.5f);
ofRect(x, y, width, height, 0);
ofSetColor(245, 58, 0, gModuleDrawAlpha);
ofSetLineWidth(1);
ofBeginShape();
for (float i = 0; i < width; i += (.25f / gDrawScale))
{
float phase = i / width * FTWO_PI;
phase += gTime * .005f;
if (mVoiceParams.mSyncMode != Oscillator::SyncMode::None)
{
phase = FloatWrap(phase, FTWO_PI);
if (mVoiceParams.mSyncMode == Oscillator::SyncMode::Frequency)
phase *= mVoiceParams.mSyncFreq / 200;
if (mVoiceParams.mSyncMode == Oscillator::SyncMode::Ratio)
phase *= mVoiceParams.mSyncRatio;
}
if (mDrawOsc.GetShuffle() > 0)
phase *= 2;
mDrawOsc.SetSoften(mVoiceParams.mSoften);
float value = mDrawOsc.Value(phase);
ofVertex(i + x, ofMap(value, -1, 1, 0, height) + y);
}
ofEndShape(false);
ofPopStyle();
}
DrawTextRightJustify("wave", kGap + kColumnWidth - 11, 15);
DrawTextRightJustify("volume", (kGap + kColumnWidth) * 2 - 11, 15);
ofPushStyle();
if (mVoiceParams.mFilterCutoffMax == SINGLEOSCILLATOR_NO_CUTOFF)
ofSetColor(100, 100, 100);
DrawTextRightJustify("filter", (kGap + kColumnWidth) * 3 - 11, 15);
ofPopStyle();
}
void SingleOscillator::DrawModuleUnclipped()
{
if (mDrawDebug)
{
mPolyMgr.DrawDebug(mWidth + 3, 0);
float y = mHeight + 15;
for (size_t i = 0; i < mDebugLines.size(); ++i)
{
const DebugLine& line = mDebugLines[(mDebugLinesPos + i) % mDebugLines.size()];
ofSetColor(line.color);
DrawTextNormal(line.text, 0, y);
y += 15;
}
}
}
void SingleOscillator::UpdateOldControlName(std::string& oldName)
{
IDrawableModule::UpdateOldControlName(oldName);
if (oldName == "f")
oldName = "fmax";
}
void SingleOscillator::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("voicelimit", moduleInfo, -1, -1, kNumVoices);
mModuleSaveData.LoadBool("mono", moduleInfo, false);
SetUpFromSaveData();
}
void SingleOscillator::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
int voiceLimit = mModuleSaveData.GetInt("voicelimit");
if (voiceLimit > 0)
mPolyMgr.SetVoiceLimit(voiceLimit);
else
mPolyMgr.SetVoiceLimit(kNumVoices);
bool mono = mModuleSaveData.GetBool("mono");
mWriteBuffer.SetNumActiveChannels(mono ? 1 : 2);
}
void SingleOscillator::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mMultSelector)
{
if (mMult > 0)
mVoiceParams.mMult = mMult;
else if (mMult == -1) //-1 is special case for 1.5
mVoiceParams.mMult = 1.5f;
else //other negative numbers mean 1/-x
mVoiceParams.mMult = -1.0f / mMult;
}
if (list == mOscSelector)
mDrawOsc.SetType(mVoiceParams.mOscType);
}
void SingleOscillator::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
}
void SingleOscillator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mShuffleSlider)
mDrawOsc.SetShuffle(mVoiceParams.mShuffle);
if (slider == mPulseWidthSlider)
mDrawOsc.SetPulseWidth(mVoiceParams.mPulseWidth);
}
void SingleOscillator::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void SingleOscillator::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mPolyMgr.KillAll();
}
void SingleOscillator::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
}
void SingleOscillator::LoadState(FileStreamIn& in, int rev)
{
mLoadRev = rev;
IDrawableModule::LoadState(in, rev);
}
bool SingleOscillator::LoadOldControl(FileStreamIn& in, std::string& oldName)
{
if (mLoadRev < 1)
{
if (oldName == "sync")
{
//load checkbox
int checkboxRev;
in >> checkboxRev;
float checkboxVal;
in >> checkboxVal;
if (checkboxVal > 0)
mVoiceParams.mSyncMode = Oscillator::SyncMode::Frequency;
else
mVoiceParams.mSyncMode = Oscillator::SyncMode::None;
return true;
}
}
return false;
}
``` | /content/code_sandbox/Source/SingleOscillator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,167 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// LinkwitzRileyFilter.h
// Bespoke
//
// Created by Ryan Challinor on 4/30/14.
//
//
#pragma once
#include <iostream>
#include "SynthGlobals.h"
class CLinkwitzRiley_4thOrder
{
public:
CLinkwitzRiley_4thOrder(const double crossoverFreq = 1000.0)
: mCrossoverFreq(crossoverFreq)
{
CalculateCoefficients();
}
void SetCrossoverFreq(const double newCrossoverFreq)
{
mCrossoverFreq = newCrossoverFreq;
CalculateCoefficients();
}
void ProcessSample(const float& sample, float& lowOut, float& highOut)
{
static double smp; // done in case sample is coming in as a reused var in the outs
smp = sample;
lowOut = mL_A0 * smp + mL_A1 * mXm1 + mL_A2 * mXm2 + mL_A3 * mXm3 + mL_A4 * mXm4 - mB1 * mLYm1 - mB2 * mLYm2 - mB3 * mLYm3 - mB4 * mLYm4;
highOut = mH_A0 * smp + mH_A1 * mXm1 + mH_A2 * mXm2 + mH_A3 * mXm3 + mH_A4 * mXm4 - mB1 * mHYm1 - mB2 * mHYm2 - mB3 * mHYm3 - mB4 * mHYm4;
// Shuffle history
mXm4 = mXm3;
mXm3 = mXm2;
mXm2 = mXm1;
mXm1 = smp;
mLYm4 = mLYm3;
mLYm3 = mLYm2;
mLYm2 = mLYm1;
mLYm1 = lowOut; // low
mHYm4 = mHYm3;
mHYm3 = mHYm2;
mHYm2 = mHYm1;
mHYm1 = highOut; // high
}
private:
void CalculateCoefficients()
{
// shared for both lp, hp; optimizations here
double wc = 2.0 * M_PI * mCrossoverFreq;
double wc2 = wc * wc;
double wc3 = wc2 * wc;
double wc4 = wc2 * wc2;
double k = wc / tan(M_PI * mCrossoverFreq / gSampleRate);
double k2 = k * k;
double k3 = k2 * k;
double k4 = k2 * k2;
double sqrt2 = sqrt(2.0);
double sq_tmp1 = sqrt2 * wc3 * k;
double sq_tmp2 = sqrt2 * wc * k3;
double a_tmp = 4.0 * wc2 * k2 + 2.0 * sq_tmp1 + k4 + 2.0 * sq_tmp2 + wc4;
// Shared coeff
mB1 = (4.0 * (wc4 + sq_tmp1 - k4 - sq_tmp2)) / a_tmp;
mB2 = (6.0 * wc4 - 8.0 * wc2 * k2 + 6.0 * k4) / a_tmp;
mB3 = (4.0 * (wc4 - sq_tmp1 + sq_tmp2 - k4)) / a_tmp;
mB4 = (k4 - 2.0 * sq_tmp1 + wc4 - 2.0 * sq_tmp2 + 4.0 * wc2 * k2) / a_tmp;
// low-pass coeff
mL_A0 = wc4 / a_tmp;
mL_A1 = 4.0 * wc4 / a_tmp;
mL_A2 = 6.0 * wc4 / a_tmp;
mL_A3 = mL_A1;
mL_A4 = mL_A0;
// high-pass coeff
mH_A0 = k4 / a_tmp;
mH_A1 = -4.0 * k4 / a_tmp;
mH_A2 = 6.0 * k4 / a_tmp;
mH_A3 = mH_A1;
mH_A4 = mH_A0;
}
double mCrossoverFreq;
double mB1, mB2, mB3, mB4; // shared with lp & hp
double mL_A0, mL_A1, mL_A2, mL_A3, mL_A4; // lp coefficients
double mH_A0, mH_A1, mH_A2, mH_A3, mH_A4; // hp coefficients
double mXm1{ 0 }, mXm2{ 0 }, mXm3{ 0 }, mXm4{ 0 }; // incoming sample history
double mLYm1{ 0 }, mLYm2{ 0 }, mLYm3{ 0 }, mLYm4{ 0 }; // low output history
double mHYm1{ 0 }, mHYm2{ 0 }, mHYm3{ 0 }, mHYm4{ 0 }; // high output history
};
/*As for how to use it, pretty easy:
// I just allocate two of them with the desired crossover points
mLow = new CLinkwitzRiley_4thOrder(44000.0, 400.0);
mHigh = new CLinkwitzRiley_4thOrder(44000.0, 4000.0);
// Then take your sample, pass it into the low, then take the high from that and pass it through the high crossover
double low, mid, high;
mLow->ProcessSample(sampleIn, low, high);
mHigh->ProcessSample(high, mid, high);
When I sum the low mid and high back together, I cant discern any signal loss once I bypass the splitter
The only bad thing Ive noticed is that changing the low freq real time is unstable. There are probably ways around this
Good luck!*/
``` | /content/code_sandbox/Source/LinkwitzRileyFilter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,464 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// CurveLooper.h
// Bespoke
//
// Created by Ryan Challinor on 3/5/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "Checkbox.h"
#include "Transport.h"
#include "DropdownList.h"
#include "EnvelopeEditor.h"
class PatchCableSource;
class CurveLooper : public IDrawableModule, public IDropdownListener, public IButtonListener, public IAudioPoller
{
public:
CurveLooper();
~CurveLooper();
static IDrawableModule* Create() { return new CurveLooper(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void OnTransportAdvanced(float amount) override;
//IDrawableModule
void Init() override;
void Poll() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
bool IsEnabled() const override { return mEnabled; }
private:
float GetPlaybackPosition();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
std::array<IUIControl*, 16> mUIControls{ nullptr };
int mLength{ 1 };
DropdownList* mLengthSelector{ nullptr };
PatchCableSource* mControlCable{ nullptr };
float mWidth{ 200 };
float mHeight{ 120 };
EnvelopeControl mEnvelopeControl{ ofVec2f(5, 25), ofVec2f(mWidth - 10, mHeight - 30) };
::ADSR mAdsr;
ClickButton* mRandomizeButton{ nullptr };
};
``` | /content/code_sandbox/Source/CurveLooper.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 696 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// SustainPedal.h
// Bespoke
//
// Created by Ryan Challinor on 5/7/14.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
class SustainPedal : public NoteEffectBase, public IDrawableModule
{
public:
SustainPedal();
static IDrawableModule* Create() { return new SustainPedal(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 90;
height = 21;
}
std::array<bool, 128> mIsNoteBeingSustained{ false };
bool mSustain{ false };
Checkbox* mSustainCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/SustainPedal.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 418 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// NoteCanvas.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/30/14.
//
//
#include "NoteCanvas.h"
#include "SynthGlobals.h"
#include "DrumPlayer.h"
#include "ModularSynth.h"
#include "CanvasControls.h"
#include "Scale.h"
#include "CanvasElement.h"
#include "Profiler.h"
#include "CanvasTimeline.h"
#include "CanvasScrollbar.h"
#include "juce_gui_basics/juce_gui_basics.h"
NoteCanvas::NoteCanvas()
{
mVoiceModulations.resize(kNumVoices + 1);
}
void NoteCanvas::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
void NoteCanvas::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mQuantizeButton = new ClickButton(this, "quantize", 160, 5);
mSaveMidiButton = new ClickButton(this, "save midi", 228, 5);
mLoadMidiButton = new ClickButton(this, "load midi", 290, 5);
mLoadMidiTrackEntry = new TextEntry(this, "loadtrack", 350, 5, 3, &mLoadMidiTrack, 0, 127);
//mClipButton = new ClickButton(this,"clip",220,5);
mPlayCheckbox = new Checkbox(this, "play", 5, 5, &mPlay);
mRecordCheckbox = new Checkbox(this, "rec", 50, 5, &mRecord);
mFreeRecordCheckbox = new Checkbox(this, "free rec", 90, 5, &mFreeRecord);
mNumMeasuresSlider = new IntSlider(this, "measures", 5, 25, 100, 15, &mNumMeasures, 1, 16);
mShowIntervalsCheckbox = new Checkbox(this, "show chord intervals", 160, 25, &mShowIntervals);
mIntervalSelector = new DropdownList(this, "interval", 110, 25, (int*)(&mInterval));
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mIntervalSelector->AddLabel("64n", kInterval_64n);
mCanvas = new Canvas(this, 5, 55, 390, 200, L(length, 1), L(rows, 128), L(cols, 16), &(NoteCanvasElement::Create));
AddUIControl(mCanvas);
mCanvas->SetNumVisibleRows(16);
mCanvas->SetRowOffset(60);
mCanvasControls = new CanvasControls();
mCanvasControls->SetCanvas(mCanvas);
mCanvasControls->CreateUIControls();
AddChild(mCanvasControls);
UpdateNumColumns();
mCanvas->SetListener(this);
mCanvasTimeline = new CanvasTimeline(mCanvas, "timeline");
AddUIControl(mCanvasTimeline);
mCanvasScrollbarHorizontal = new CanvasScrollbar(mCanvas, "scrollh", CanvasScrollbar::Style::kHorizontal);
AddUIControl(mCanvasScrollbarHorizontal);
mCanvasScrollbarVertical = new CanvasScrollbar(mCanvas, "scrollv", CanvasScrollbar::Style::kVertical);
AddUIControl(mCanvasScrollbarVertical);
}
NoteCanvas::~NoteCanvas()
{
mCanvas->SetListener(nullptr);
TheTransport->RemoveAudioPoller(this);
}
void NoteCanvas::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
mNoteOutput.PlayNote(time, pitch, velocity, voiceIdx, modulation);
if (!mEnabled || !mRecord)
return;
if (mInputNotes[pitch]) //handle note-offs or retriggers
{
double endPos = GetCurPos(time);
if (mInputNotes[pitch]->GetStart() > endPos)
endPos += 1; //wrap
mInputNotes[pitch]->SetEnd(endPos);
mInputNotes[pitch] = nullptr;
}
if (velocity > 0)
{
if (mFreeRecord && mFreeRecordStartMeasure == -1)
mFreeRecordStartMeasure = TheTransport->GetMeasure(time);
double measurePos = GetCurPos(time) * mNumMeasures;
NoteCanvasElement* element = AddNote(measurePos, pitch, velocity, 1 / mCanvas->GetNumCols(), voiceIdx, modulation);
mInputNotes[pitch] = element;
mCanvas->SetRowOffset(element->mRow - mCanvas->GetNumVisibleRows() / 2);
}
}
void NoteCanvas::KeyPressed(int key, bool isRepeat)
{
IDrawableModule::KeyPressed(key, isRepeat);
}
bool NoteCanvas::FreeRecordParityMatched()
{
int currentMeasureParity = (TheTransport->GetMeasure(gTime) % (mNumMeasures * 2)) / mNumMeasures;
int recordStartMeasureParity = (mFreeRecordStartMeasure % (mNumMeasures * 2)) / mNumMeasures;
return currentMeasureParity == recordStartMeasureParity;
}
void NoteCanvas::OnTransportAdvanced(float amount)
{
PROFILER(NoteCanvas);
if (mFreeRecord && mFreeRecordStartMeasure != -1)
{
if (TheTransport->GetMeasurePos(gTime) < amount &&
!FreeRecordParityMatched())
{
int oldNumMeasures = mNumMeasures;
while (!FreeRecordParityMatched())
mNumMeasures *= 2;
int shift = mFreeRecordStartMeasure % mNumMeasures - mFreeRecordStartMeasure % oldNumMeasures;
SetNumMeasures(mNumMeasures);
for (auto* element : mCanvas->GetElements())
element->SetStart(element->GetStart() + float(shift) / mNumMeasures, true);
}
}
if (mStopQueued)
{
mNoteOutput.Flush(NextBufferTime(false));
for (int i = 0; i < mCurrentNotes.size(); ++i)
mCurrentNotes[i] = nullptr;
mStopQueued = false;
}
if (!mEnabled || !mPlay)
{
mCanvas->SetCursorPos(-1);
return;
}
double cursorPlayTime = gTime;
//if (Transport::sDoEventLookahead)??? should we?
// cursorPlayTime += Transport::sEventEarlyMs;
//else
cursorPlayTime += amount * TheTransport->MsPerBar();
double curPos = GetCurPos(cursorPlayTime);
mCanvas->FillElementsAt(curPos, mNoteChecker);
for (int i = 0; i < 128; ++i)
{
int pitch = 128 - i - 1;
bool wasOn = mCurrentNotes[pitch] != nullptr || mInputNotes[pitch];
bool nowOn = mNoteChecker[i] != nullptr || mInputNotes[pitch];
bool hasChanged = (nowOn || wasOn) && mCurrentNotes[pitch] != static_cast<NoteCanvasElement*>(mNoteChecker[i]);
if (wasOn && mInputNotes[pitch] == nullptr && hasChanged)
{
//note off
if (mCurrentNotes[pitch])
{
double cursorAdvanceSinceEvent = curPos - mCurrentNotes[pitch]->GetEnd();
if (cursorAdvanceSinceEvent < 0)
cursorAdvanceSinceEvent += 1;
double time = cursorPlayTime - cursorAdvanceSinceEvent * TheTransport->MsPerBar() * mNumMeasures;
if (time < gTime)
time = gTime;
mNoteOutput.PlayNote(time, pitch, 0, mCurrentNotes[pitch]->GetVoiceIdx());
mCurrentNotes[pitch] = nullptr;
}
}
if (nowOn && mInputNotes[pitch] == nullptr && hasChanged)
{
//note on
NoteCanvasElement* note = static_cast<NoteCanvasElement*>(mNoteChecker[i]);
assert(note);
double cursorAdvanceSinceEvent = curPos - note->GetStart();
if (cursorAdvanceSinceEvent < 0)
cursorAdvanceSinceEvent += 1;
double time = cursorPlayTime - cursorAdvanceSinceEvent * TheTransport->MsPerBar() * mNumMeasures;
if (time > gTime)
{
mCurrentNotes[pitch] = note;
mNoteOutput.PlayNote(time, pitch, note->GetVelocity() * 127, note->GetVoiceIdx(), ModulationParameters(note->GetPitchBend(), note->GetModWheel(), note->GetPressure(), note->GetPan()));
}
}
mNoteChecker[i] = nullptr;
}
for (int pitch = 0; pitch < 128; ++pitch)
{
if (mInputNotes[pitch])
{
float endPos = curPos;
if (mInputNotes[pitch]->GetStart() > endPos)
endPos += 1; //wrap
mInputNotes[pitch]->SetEnd(endPos);
int modIdx = mInputNotes[pitch]->GetVoiceIdx();
if (modIdx == -1)
modIdx = kNumVoices;
float bend = ModulationParameters::kDefaultPitchBend;
float mod = ModulationParameters::kDefaultModWheel;
float pressure = ModulationParameters::kDefaultPressure;
if (mVoiceModulations[modIdx].pitchBend)
bend = mVoiceModulations[modIdx].pitchBend->GetValue(0);
if (mVoiceModulations[modIdx].modWheel)
mod = mVoiceModulations[modIdx].modWheel->GetValue(0);
if (mVoiceModulations[modIdx].pressure)
pressure = mVoiceModulations[modIdx].pressure->GetValue(0);
mInputNotes[pitch]->WriteModulation(curPos, bend, mod, pressure, mVoiceModulations[modIdx].pan);
}
else if (mCurrentNotes[pitch])
{
mCurrentNotes[pitch]->UpdateModulation(curPos);
}
}
}
double NoteCanvas::GetCurPos(double time) const
{
int loopMeasures = MAX(1, int(mCanvas->mLoopEnd - mCanvas->mLoopStart));
return (((TheTransport->GetMeasure(time) % loopMeasures) + TheTransport->GetMeasurePos(time)) + mCanvas->mLoopStart) / mCanvas->GetLength();
}
void NoteCanvas::UpdateNumColumns()
{
mCanvas->RescaleNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures);
if (mInterval < kInterval_8n)
mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval));
else
mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval) / 4);
}
void NoteCanvas::Clear(double time)
{
bool wasPlaying = mPlay;
mPlay = false;
for (int pitch = 0; pitch < 128; ++pitch)
{
mInputNotes[pitch] = nullptr;
mCurrentNotes[pitch] = nullptr;
}
mNoteOutput.Flush(time);
mCanvas->Clear();
mPlay = wasPlaying;
}
NoteCanvasElement* NoteCanvas::AddNote(double measurePos, int pitch, int velocity, double length, int voiceIdx /*=-1*/, ModulationParameters modulation /* = ModulationParameters()*/)
{
double canvasPos = measurePos / mNumMeasures * mCanvas->GetNumCols();
int col = int(canvasPos + .5f); //round off
int row = mCanvas->GetNumRows() - pitch - 1;
NoteCanvasElement* element = static_cast<NoteCanvasElement*>(mCanvas->CreateElement(col, row));
element->mOffset = canvasPos - element->mCol; //the rounded off part
element->mLength = length / mNumMeasures * mCanvas->GetNumCols();
element->SetVelocity(velocity / 127.0f);
element->SetVoiceIdx(voiceIdx);
int modIdx = voiceIdx;
if (modIdx == -1)
modIdx = kNumVoices;
mVoiceModulations[modIdx] = modulation;
mCanvas->AddElement(element);
return element;
}
void NoteCanvas::FitNotes()
{
float latest = 0.0;
for (auto* element : mCanvas->GetElements())
{
if (element->GetEnd() > latest)
latest = element->GetEnd();
}
SetNumMeasures(static_cast<int>(std::ceil(latest)));
}
void NoteCanvas::CanvasUpdated(Canvas* canvas)
{
if (canvas == mCanvas)
{
}
}
void NoteCanvas::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofPushStyle();
ofFill();
for (int i = 0; i < 128; ++i)
{
int pitch = 127 - i;
if (pitch % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot() % TheScale->GetPitchesPerOctave())
mCanvas->SetRowColor(i, ofColor(0, 255, 0, 80));
else if (pitch % TheScale->GetPitchesPerOctave() == (TheScale->ScaleRoot() + 7) % TheScale->GetPitchesPerOctave())
mCanvas->SetRowColor(i, ofColor(200, 150, 0, 80));
else if (TheScale->IsInScale(pitch))
mCanvas->SetRowColor(i, ofColor(100, 75, 0, 80));
else
mCanvas->SetRowColor(i, ofColor(100, 100, 100, 30));
}
ofPopStyle();
mCanvas->SetCursorPos(GetCurPos(gTime));
mCanvas->Draw();
mCanvasTimeline->Draw();
mCanvasScrollbarHorizontal->Draw();
mCanvasScrollbarVertical->Draw();
ofPushStyle();
ofSetColor(128, 128, 128, gModuleDrawAlpha * .8f);
for (int i = 0; i < mCanvas->GetNumVisibleRows(); ++i)
{
int pitch = 127 - mCanvas->GetRowOffset() - i;
float boxHeight = (float(mCanvas->GetHeight()) / mCanvas->GetNumVisibleRows());
float y = mCanvas->GetPosition(true).y + i * boxHeight;
float scale = MIN(boxHeight - 2, 18);
DrawTextNormal(NoteName(pitch, false, true) + "(" + ofToString(pitch) + ")", mCanvas->GetPosition(true).x + 2, y - (scale / 8) + boxHeight, scale);
}
ofPopStyle();
if (mShowIntervals)
{
ofPushMatrix();
ofTranslate(mCanvas->GetPosition(true).x, mCanvas->GetPosition(true).y);
ofPushStyle();
ofSetLineWidth(3);
auto elements = mCanvas->GetElements();
for (auto e1 : elements)
{
for (auto e2 : elements)
{
if (e1 != e2)
{
if (abs(e1->GetStart() - e2->GetStart()) < (1.0 / 32) / mNumMeasures)
{
int interval = abs(e1->mRow - e2->mRow);
if (interval >= 3 && interval <= 7)
{
auto rect1 = e1->GetRect(true, false);
auto rect2 = e2->GetRect(true, false);
float offset = 0;
if (interval == 3)
{
ofSetColor(255, 0, 0, 50);
}
if (interval == 4)
{
ofSetColor(0, 255, 0, 50);
}
if (interval == 5)
{
ofSetColor(0, 0, 255, 50);
offset = -1;
}
if (interval == 6)
{
ofSetColor(255, 0, 255, 50);
offset = 3;
}
if (interval == 7)
{
ofSetColor(0, 0, 0, 50);
offset = -3;
}
ofLine(rect1.x + offset, rect1.getCenter().y, rect2.x + offset, rect2.getCenter().y);
ofLine(rect1.x + offset, rect1.getCenter().y, rect1.x + 5 + offset, rect1.getCenter().y);
ofLine(rect2.x + offset, rect2.getCenter().y, rect2.x + 5 + offset, rect2.getCenter().y);
}
}
}
}
}
ofPopStyle();
ofPopMatrix();
}
mCanvasControls->Draw();
mQuantizeButton->Draw();
mSaveMidiButton->Draw();
mLoadMidiButton->Draw();
mLoadMidiTrackEntry->Draw();
//mClipButton->Draw();
mPlayCheckbox->Draw();
mRecordCheckbox->Draw();
mFreeRecordCheckbox->Draw();
mNumMeasuresSlider->Draw();
mIntervalSelector->Draw();
mShowIntervalsCheckbox->Draw();
if (mRecord)
{
ofPushStyle();
ofSetColor(205 + 50 * (cosf(TheTransport->GetMeasurePos(gTime) * 4 * FTWO_PI)), 0, 0);
ofSetLineWidth(4);
ofRect(mCanvas->GetPosition(true).x, mCanvas->GetPosition(true).y, mCanvas->GetWidth(), mCanvas->GetHeight());
ofPopStyle();
}
}
namespace
{
const float extraW = 20;
const float extraH = 163;
}
void NoteCanvas::Resize(float w, float h)
{
w = MAX(w - extraW, 390);
h = MAX(h - extraH, 40);
mCanvas->SetDimensions(w, h);
}
void NoteCanvas::GetModuleDimensions(float& width, float& height)
{
width = mCanvas->GetWidth() + extraW;
height = mCanvas->GetHeight() + extraH;
}
void NoteCanvas::SetNumMeasures(int numMeasures)
{
mNumMeasures = numMeasures;
mCanvas->SetLength(mNumMeasures);
mCanvas->SetNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures);
if (mInterval < kInterval_8n)
mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval));
else
mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval) / 4);
mCanvas->mViewStart = 0;
mCanvas->mViewEnd = mNumMeasures;
mCanvas->mLoopStart = 0;
mCanvas->mLoopEnd = mNumMeasures;
}
void NoteCanvas::SetRecording(bool rec)
{
mRecord = rec;
if (mRecord)
mPlay = true;
for (int pitch = 0; pitch < 128; ++pitch)
mInputNotes[pitch] = nullptr;
}
void NoteCanvas::ClipNotes()
{
bool anyHighlighted = false;
float earliest = FLT_MAX;
float latest = 0;
std::vector<CanvasElement*> toDelete;
for (auto* element : mCanvas->GetElements())
{
if (element->GetHighlighted())
{
anyHighlighted = true;
if (element->GetStart() < earliest)
earliest = element->GetStart();
if (element->GetEnd() > latest)
latest = element->GetEnd();
}
else
{
toDelete.push_back(element);
}
}
if (anyHighlighted)
{
for (auto* remove : toDelete)
mCanvas->RemoveElement(remove);
int earliestMeasure = int(earliest * mNumMeasures);
int latestMeasure = int(latest * mNumMeasures) + 1;
int clipStart = 0;
int clipEnd = mNumMeasures;
while (earliestMeasure - clipStart >= (clipEnd - clipStart) / 2 ||
clipEnd - latestMeasure >= (clipEnd - clipStart) / 2)
{
if (earliestMeasure - clipStart >= (clipEnd - clipStart) / 2)
clipStart += (clipEnd - clipStart) / 2;
if (clipEnd - latestMeasure >= (clipEnd - clipStart) / 2)
clipEnd -= (clipEnd - clipStart) / 2;
}
SetNumMeasures(clipEnd - clipStart);
ofLog() << earliest << " " << latest << " " << clipStart << " " << clipEnd;
int shift = -clipStart;
for (auto* element : mCanvas->GetElements())
element->SetStart(element->GetStart() + float(shift) / mNumMeasures, true);
}
}
void NoteCanvas::QuantizeNotes()
{
bool anyHighlighted = false;
for (auto* element : mCanvas->GetElements())
{
if (element->GetHighlighted())
{
anyHighlighted = true;
break;
}
}
for (auto* element : mCanvas->GetElements())
{
if (anyHighlighted == false || element->GetHighlighted())
{
element->mCol = int(element->mCol + element->mOffset + .5f) % mCanvas->GetNumCols();
element->mOffset = 0;
}
}
}
void NoteCanvas::LoadMidi()
{
using namespace juce;
String file_pattern = "*.mid;*.midi";
if (File::areFileNamesCaseSensitive())
file_pattern += ";" + file_pattern.toUpperCase();
FileChooser chooser("Load midi", File(ofToDataPath("")), file_pattern, true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToOpen())
{
bool wasPlaying = mPlay;
mPlay = false;
Clear(NextBufferTime(false));
SetNumMeasures(1);
File file = chooser.getResult();
FileInputStream inputStream(file);
MidiFile midifile;
if (midifile.readFrom(inputStream))
{
midifile.convertTimestampTicksToSeconds();
int ticksPerQuarterNote = midifile.getTimeFormat();
int trackToGet = 0;
if (midifile.getNumTracks() > 1)
trackToGet = mLoadMidiTrack;
const MidiMessageSequence* trackSequence = midifile.getTrack(trackToGet);
for (int eventIndex = 0; eventIndex < trackSequence->getNumEvents(); eventIndex++)
{
MidiMessageSequence::MidiEventHolder* noteEvent = trackSequence->getEventPointer(eventIndex);
if (noteEvent->noteOffObject)
{
int note = noteEvent->message.getNoteNumber();
int veloc = noteEvent->message.getVelocity() * 1.27;
double start = noteEvent->message.getTimeStamp() / ticksPerQuarterNote / TheTransport->CountInStandardMeasure(kInterval_4n);
double end = noteEvent->noteOffObject->message.getTimeStamp() / ticksPerQuarterNote / TheTransport->CountInStandardMeasure(kInterval_4n);
double length = end - start;
AddNote(start, note, veloc, length, -1, ModulationParameters());
}
}
float latest = 0.0;
for (auto* element : mCanvas->GetElements())
{
if (element->GetEnd() > latest)
latest = element->GetEnd();
}
mNumMeasuresSlider->SetExtents(0, static_cast<int>(std::ceil(latest)));
FitNotes();
}
mPlay = wasPlaying;
}
}
void NoteCanvas::SaveMidi()
{
using namespace juce;
constexpr static int ticksPerQuarterNote = 960;
FileChooser chooser("Save midi", File(ofToDataPath("midi")), "*.mid", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToSave(true))
{
MidiFile midifile;
midifile.setTicksPerQuarterNote(ticksPerQuarterNote);
MidiMessageSequence track1;
MidiMessage trackTimeSig = MidiMessage::timeSignatureMetaEvent(TheTransport->GetTimeSigTop(), TheTransport->GetTimeSigBottom());
track1.addEvent(trackTimeSig);
for (auto* element : mCanvas->GetElements())
{
NoteCanvasElement* noteOnElement = static_cast<NoteCanvasElement*>(element);
int noteNumber = mCanvas->GetNumRows() - noteOnElement->mRow - 1;
float noteStart = (element->mCol + element->mOffset) * ticksPerQuarterNote *
+TheTransport->GetMeasureFraction(mInterval) / TheTransport->GetMeasureFraction(kInterval_4n);
float velocity = noteOnElement->GetVelocity();
MidiMessage messageOn = MidiMessage::noteOn(1, noteNumber, velocity);
messageOn.setTimeStamp(noteStart);
track1.addEvent(messageOn);
float noteEnd = (element->mCol + element->mOffset + element->mLength) * ticksPerQuarterNote *
+TheTransport->GetMeasureFraction(mInterval) / TheTransport->GetMeasureFraction(kInterval_4n);
MidiMessage messageOff = MidiMessage::noteOff(1, noteNumber, velocity);
messageOff.setTimeStamp(noteEnd);
track1.addEvent(messageOff);
}
midifile.addTrack(track1);
std::string savePath = chooser.getResult().getFullPathName().toStdString();
File f(savePath);
FileOutputStream out(f);
midifile.writeTo(out);
}
}
void NoteCanvas::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int pitch = 0; pitch < 128; ++pitch)
mInputNotes[pitch] = nullptr;
mNoteOutput.Flush(time);
}
if (checkbox == mPlayCheckbox)
{
if (!mPlay)
{
mRecord = false;
mStopQueued = true;
}
}
if (checkbox == mRecordCheckbox)
{
SetRecording(mRecord);
}
if (checkbox == mFreeRecordCheckbox)
{
if (mFreeRecord)
{
SetRecording(true);
mFreeRecordStartMeasure = -1;
}
}
}
void NoteCanvas::ButtonClicked(ClickButton* button, double time)
{
if (button == mQuantizeButton)
QuantizeNotes();
if (button == mClipButton)
ClipNotes();
if (button == mLoadMidiButton)
LoadMidi();
if (button == mSaveMidiButton)
SaveMidi();
}
void NoteCanvas::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void NoteCanvas::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mNumMeasuresSlider)
{
SetNumMeasures(mNumMeasures);
}
}
void NoteCanvas::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
{
UpdateNumColumns();
}
}
void NoteCanvas::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("canvaswidth", moduleInfo, 390, 390, 99999, K(isTextField));
mModuleSaveData.LoadFloat("canvasheight", moduleInfo, 200, 40, 99999, K(isTextField));
SetUpFromSaveData();
}
void NoteCanvas::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mCanvas->SetDimensions(mModuleSaveData.GetFloat("canvaswidth"), mModuleSaveData.GetFloat("canvasheight"));
}
void NoteCanvas::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["canvaswidth"] = mCanvas->GetWidth();
moduleInfo["canvasheight"] = mCanvas->GetHeight();
}
void NoteCanvas::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mCanvas->SaveState(out);
}
void NoteCanvas::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
mCanvas->LoadState(in);
}
``` | /content/code_sandbox/Source/NoteCanvas.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,443 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// IUIControl.cpp
// modularSynth
//
// Created by Ryan Challinor on 6/13/13.
//
//
#include "IUIControl.h"
#include "Snapshots.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "PatchCable.h"
#include "Push2Control.h"
//static
IUIControl* IUIControl::sLastHoveredUIControl = nullptr;
//static
bool IUIControl::sLastUIHoverWasSetManually = false;
IUIControl::~IUIControl()
{
if (gHoveredUIControl == this)
gHoveredUIControl = nullptr;
if (gBindToUIControl == this)
gBindToUIControl = nullptr;
}
bool IUIControl::IsPreset()
{
return VectorContains(this, Snapshots::sSnapshotHighlightControls);
}
bool IUIControl::TestHover(int x, int y)
{
if (mNoHover)
return false;
if (!mShowing)
return false;
float w, h;
GetDimensions(w, h);
if (x >= 0 && x < w && y >= 0 && y < h) //make sure we're hovered over the control
{
IDrawableModule* moduleParent = GetModuleParent();
float thisX, thisY;
GetPosition(thisX, thisY);
x += thisX;
y += thisY;
if (moduleParent->GetOwningContainer()->GetModuleAt(x, y) == moduleParent)
{
float localX, localY;
GetPosition(localX, localY, K(localOnly));
float parentW, parentH;
GetParent()->GetDimensions(parentW, parentH);
if (localX < parentW && localY < parentH)
return true;
}
}
return false;
}
void IUIControl::CheckHover(int x, int y)
{
static long sLastHoveredUIControlFrame = 0;
if (TheSynth->GetFrameCount() != sLastHoveredUIControlFrame &&
!TheSynth->IsGroupSelecting() && PatchCable::sActivePatchCable == nullptr &&
TestHover(x, y) &&
(gHoveredUIControl == nullptr || !gHoveredUIControl->IsMouseDown()) &&
GetModuleParent() == TheSynth->GetModuleAtCursor())
{
gHoveredUIControl = this;
sLastHoveredUIControl = this;
sLastUIHoverWasSetManually = false;
sLastHoveredUIControlFrame = TheSynth->GetFrameCount();
}
}
void IUIControl::DrawHover(float x, float y, float w, float h)
{
if (Push2Control::sDrawingPush2Display)
return;
if (gHoveredUIControl == this && IKeyboardFocusListener::GetActiveKeyboardFocus() == nullptr && TheSynth->GetGroupSelectedModules().empty())
{
ofPushStyle();
ofNoFill();
ofSetColor(0, 255, 255, 255);
ofRect(x, y, w, h, 4);
ofPopStyle();
}
if (mRemoteControlCount > 0 && TheSynth->InMidiMapMode())
{
ofPushStyle();
ofFill();
ofSetColor(255, 0, 255, 100);
ofRect(x, y, w, h);
ofPopStyle();
}
if (gBindToUIControl == this)
{
ofPushStyle();
ofNoFill();
ofSetLineWidth(5);
ofSetColor(255, 0, 255, 200);
ofRect(x, y, w, h);
ofPopStyle();
}
DrawPatchCableHover();
}
void IUIControl::DrawPatchCableHover()
{
if (PatchCable::sActivePatchCable &&
(PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_Pulse ||
PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_Modulator ||
PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_ValueSetter ||
PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_UIControl ||
PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_Grid) &&
PatchCable::sActivePatchCable->IsValidTarget(this))
{
float w, h;
GetDimensions(w, h);
ofPushStyle();
ofNoFill();
ofSetLineWidth(1.5f);
ofSetColor(255, 0, 255, 200);
ofRect(mX, mY, w, h);
ofPopStyle();
}
}
bool IUIControl::CanBeTargetedBy(PatchCableSource* source) const
{
if (!mCableTargetable)
return false;
if (GetNoHover())
return false;
return source->GetConnectionType() == kConnectionType_Modulator || source->GetConnectionType() == kConnectionType_ValueSetter || source->GetConnectionType() == kConnectionType_UIControl;
}
void IUIControl::StartBeacon()
{
IClickable::StartBeacon();
IClickable* moduleParent = GetModuleParent();
if (moduleParent)
moduleParent->StartBeacon();
}
void IUIControl::PositionTo(IUIControl* anchor, AnchorDirection direction)
{
ofRectangle rect = anchor->GetRect(true);
if (direction == kAnchor_Below)
{
mX = rect.x;
mY = rect.y + rect.height + 2;
}
else if (direction == kAnchor_Right)
{
mX = rect.x + rect.width + 3;
mY = rect.y;
}
else if (direction == kAnchor_Right_Padded)
{
mX = rect.x + rect.width + 10;
mY = rect.y;
}
}
void IUIControl::GetColors(ofColor& color, ofColor& textColor)
{
IDrawableModule* module = dynamic_cast<IDrawableModule*>(GetParent());
if (module)
color = IDrawableModule::GetColor(module->GetModuleCategory());
else
color = ofColor::white;
float h, s, b;
color.getHsb(h, s, b);
color.setHsb(h, s * .4f, ofLerp(b, 0, .6f));
if (IsPreset())
{
color.getHsb(h, s, b);
color.setHsb(85, s, b);
textColor.set(0, 255, 0, gModuleDrawAlpha);
}
else
{
textColor.set(255, 255, 255, gModuleDrawAlpha);
}
}
void IUIControl::RemoveFromOwner()
{
IDrawableModule* owner = dynamic_cast<IDrawableModule*>(GetParent());
assert(owner);
if (owner)
owner->RemoveUIControl(this);
}
//static
void IUIControl::SetNewManualHoverViaTab(int direction)
{
if (gHoveredUIControl == nullptr)
{
gHoveredUIControl = sLastHoveredUIControl;
sLastUIHoverWasSetManually = true;
}
else
{
IDrawableModule* uiControlModule = gHoveredUIControl->GetModuleParent();
if (uiControlModule != nullptr)
{
const auto& controls = uiControlModule->GetUIControls();
int controlIndex = 0;
for (int i = 0; i < (int)controls.size(); ++i)
{
if (controls[i] == gHoveredUIControl)
{
controlIndex = i;
break;
}
}
for (int i = 1; i < (int)controls.size(); ++i)
{
int newControlIndex = (controlIndex + i * direction + (int)controls.size()) % (int)controls.size();
if (controls[newControlIndex]->IsShowing() && !controls[newControlIndex]->GetNoHover())
{
gHoveredUIControl = controls[newControlIndex];
sLastHoveredUIControl = gHoveredUIControl;
sLastUIHoverWasSetManually = true;
break;
}
}
}
}
}
namespace
{
//only supports cardinal directions
float GetDistanceScore(ofVec2f direction, ofRectangle rectA, ofRectangle rectB)
{
float score = 0;
ofVec2f edgeA = rectA.getCenter() + ofVec2f(rectA.width * .5f * direction.x, rectA.height * .5f * direction.y);
ofVec2f edgeB = rectB.getCenter() + ofVec2f(rectB.width * -.5f * direction.x, rectB.height * -.5f * direction.y);
ofVec2f toRect = edgeB - edgeA;
float dot = direction.dot(toRect);
if (dot > 0)
{
ofVec2f perpendicularDirection(direction.y, direction.x);
float minExtentA = fabsf(rectA.getMinX() * perpendicularDirection.x + rectA.getMinY() * perpendicularDirection.y);
float maxExtentA = fabsf(rectA.getMaxX() * perpendicularDirection.x + rectA.getMaxY() * perpendicularDirection.y);
float minExtentB = fabsf(rectB.getMinX() * perpendicularDirection.x + rectB.getMinY() * perpendicularDirection.y);
float maxExtentB = fabsf(rectB.getMaxX() * perpendicularDirection.x + rectB.getMaxY() * perpendicularDirection.y);
if (minExtentA <= maxExtentB && maxExtentA >= minExtentB) //overlap, score based upon closest in the specified direction
score = 1 / direction.dot(toRect) + 1000; //bonus points so that overlapping ones win
else //no overlap,but still in the requested direction. score based upon overall distance
score = 1 / toRect.distanceSquared();
}
return score;
}
}
//static
void IUIControl::SetNewManualHoverViaArrow(ofVec2f direction)
{
if (gHoveredUIControl == nullptr)
{
gHoveredUIControl = sLastHoveredUIControl;
sLastUIHoverWasSetManually = true;
}
else
{
IDrawableModule* uiControlModule = gHoveredUIControl->GetModuleParent();
if (uiControlModule != nullptr)
{
const auto& controls = uiControlModule->GetUIControls();
ofRectangle currentControlRect = gHoveredUIControl->GetRect();
float bestScore = 0;
int bestScoreIndex = -1;
for (int i = 0; i < (int)controls.size(); ++i)
{
if (controls[i]->IsShowing() && !controls[i]->GetNoHover() && controls[i] != gHoveredUIControl)
{
float score = GetDistanceScore(direction, currentControlRect, controls[i]->GetRect());
if (score > bestScore)
{
bestScore = score;
bestScoreIndex = i;
}
}
}
if (bestScoreIndex != -1)
{
gHoveredUIControl = controls[bestScoreIndex];
sLastHoveredUIControl = gHoveredUIControl;
sLastUIHoverWasSetManually = true;
}
}
}
}
//static
void IUIControl::DestroyCablesTargetingControls(std::vector<IUIControl*> controls)
{
std::vector<IDrawableModule*> modules;
TheSynth->GetAllModules(modules);
std::vector<PatchCable*> cablesToDestroy;
for (const auto module_iter : modules)
{
for (const auto source : module_iter->GetPatchCableSources())
{
for (const auto cable : source->GetPatchCables())
{
for (const auto control : controls)
{
if (cable->GetTarget() == control)
{
cablesToDestroy.push_back(cable);
break;
}
}
}
}
}
for (const auto cable : cablesToDestroy)
cable->Destroy(false);
}
``` | /content/code_sandbox/Source/IUIControl.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,779 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// PolyphonyMgr.h
// additiveSynth
//
// Created by Ryan Challinor on 11/20/12.
//
//
#pragma once
#include "SynthGlobals.h"
#include "ChannelBuffer.h"
const int kVoiceFadeSamples = 50;
extern ChannelBuffer gMidiVoiceWorkChannelBuffer;
class IMidiVoice;
class IVoiceParams;
class IDrawableModule;
struct ModulationParameters;
enum VoiceType
{
kVoiceType_Karplus,
kVoiceType_FM,
kVoiceType_SingleOscillator,
kVoiceType_Sampler
};
struct VoiceInfo
{
float mPitch{ -1 };
IMidiVoice* mVoice{ nullptr };
double mTime{ 0 };
bool mNoteOn{ false };
float mActivity{ 0 };
};
class PolyphonyMgr
{
public:
PolyphonyMgr(IDrawableModule* owner);
~PolyphonyMgr();
void Init(VoiceType type,
IVoiceParams* mVoiceParams);
void Start(double time, int pitch, float amount, int voiceIdx, ModulationParameters modulation);
void Stop(double time, int pitch, int voiceIdx);
void Process(double time, ChannelBuffer* out, int bufferSize);
void DrawDebug(float x, float y);
void SetVoiceLimit(int limit) { mVoiceLimit = limit; }
void KillAll();
void SetOversampling(int oversampling) { mOversampling = oversampling; }
private:
VoiceInfo mVoices[kNumVoices];
bool mAllowStealing{ true };
int mLastVoice{ -1 };
ChannelBuffer mFadeOutBuffer{ kVoiceFadeSamples };
ChannelBuffer mFadeOutWorkBuffer{ kVoiceFadeSamples };
float mWorkBuffer[2048]{};
int mFadeOutBufferPos{ 0 };
IDrawableModule* mOwner;
int mVoiceLimit{ kNumVoices };
int mOversampling{ 1 };
};
``` | /content/code_sandbox/Source/PolyphonyMgr.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 520 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
SampleBrowser.cpp
Created: 19 Jun 2021 6:46:39pm
Author: Ryan Challinor
==============================================================================
*/
#include "SampleBrowser.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
#include "IAudioReceiver.h"
#include "Profiler.h"
#include "juce_audio_formats/juce_audio_formats.h"
using namespace juce;
SampleBrowser::SampleBrowser()
{
mCurrentDirectory = ofToDataPath("samples");
}
SampleBrowser::~SampleBrowser()
{
}
void SampleBrowser::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(3, 20);
for (int i = 0; i < (int)mButtons.size(); ++i)
{
BUTTON(mButtons[i], ("button" + ofToString(i)).c_str());
UIBLOCK_SHIFTX(270);
BUTTON(mPlayButtons[i], ("play" + ofToString(i)).c_str());
mPlayButtons[i]->SetDisplayStyle(ButtonDisplayStyle::kPlay);
mPlayButtons[i]->SetDimensions(20, 15);
UIBLOCK_NEWLINE();
}
BUTTON(mBackButton, " < ");
UIBLOCK_SHIFTX(80);
BUTTON(mForwardButton, " > ");
ENDUIBLOCK0();
SetDirectory(mCurrentDirectory);
}
void SampleBrowser::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
float fontSize = 13;
float stringWidth = gFont.GetStringWidth(mCurrentDirectory.toStdString(), fontSize);
float moduleWidth, moduleHeight;
GetModuleDimensions(moduleWidth, moduleHeight);
float textX = 3;
if (stringWidth > moduleWidth)
textX = moduleWidth - 3 - stringWidth;
gFont.DrawString(mCurrentDirectory.toStdString(), fontSize, textX, 15);
for (size_t i = 0; i < mButtons.size(); ++i)
mButtons[i]->Draw();
for (size_t i = 0; i < mPlayButtons.size(); ++i)
mPlayButtons[i]->Draw();
mBackButton->Draw();
mForwardButton->Draw();
int numPages = GetNumPages();
if (numPages > 1)
DrawTextNormal(ofToString(mCurrentPage + 1) + "/" + ofToString(numPages), 40, mBackButton->GetPosition(true).y + 12);
}
void SampleBrowser::ButtonClicked(ClickButton* button, double time)
{
if (button == mBackButton)
ShowPage(mCurrentPage - 1);
if (button == mForwardButton)
ShowPage(mCurrentPage + 1);
for (int i = 0; i < (int)mButtons.size(); ++i)
{
if (button == mButtons[i] || button == mPlayButtons[i])
{
int offset = mCurrentPage * (int)mButtons.size();
int entryIndex = offset + i;
if (entryIndex < (int)mDirectoryListing.size())
{
String clicked = mDirectoryListing[entryIndex];
if (button == mButtons[i])
{
if (clicked == "..")
{
File dir(mCurrentDirectory);
if (dir.getParentDirectory().getFullPathName() != dir.getFullPathName())
SetDirectory(File(mCurrentDirectory).getParentDirectory().getFullPathName());
else
SetDirectory("");
}
else if (File(clicked).isDirectory())
{
SetDirectory(clicked);
}
else
{
TheSynth->GrabSample(clicked.toStdString());
}
}
if (button == mPlayButtons[i])
{
if (File(clicked).existsAsFile())
{
mSampleMutex.lock();
mPlayingSample.Read(clicked.toStdString().c_str());
mPlayingSample.Play(NextBufferTime(false), 1, 0);
mSampleMutex.unlock();
}
}
}
}
}
}
void SampleBrowser::Process(double time)
{
PROFILER(SampleBrowser);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
int bufferSize = target->GetBuffer()->BufferSize();
assert(bufferSize == gBufferSize);
gWorkChannelBuffer.Clear();
mSampleMutex.lock();
if (mPlayingSample.IsPlaying())
mPlayingSample.ConsumeData(time, &gWorkChannelBuffer, bufferSize, true);
mSampleMutex.unlock();
const int kNumChannels = 2;
SyncOutputBuffer(kNumChannels);
for (int ch = 0; ch < kNumChannels; ++ch)
{
GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), bufferSize, ch);
Add(target->GetBuffer()->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), bufferSize);
}
}
namespace
{
int CompareDirectoryListing(const String& text, const String& other)
{
if (text == other)
return 0;
bool isDir = text == ".." || File(text).isDirectory();
bool isOtherDir = other == ".." || File(other).isDirectory();
if (isDir && !isOtherDir)
return -1;
if (!isDir && isOtherDir)
return 1;
return text.compareIgnoreCase(other);
}
void SortDirectoryListing(StringArray& listing)
{
std::sort(listing.begin(), listing.end(), [](const String& a, const String& b)
{
return CompareDirectoryListing(a, b) < 0;
});
}
}
void SampleBrowser::SetDirectory(String dirPath)
{
mCurrentDirectory = dirPath;
mDirectoryListing.clear();
if (dirPath != "")
{
String matcher = TheSynth->GetAudioFormatManager().getWildcardForAllFormats();
StringArray wildcards;
wildcards.addTokens(matcher, ";,", "\"'");
wildcards.trim();
wildcards.removeEmptyStrings();
mDirectoryListing.add("..");
File dir(ofToDataPath(dirPath.toStdString()));
for (auto file : dir.findChildFiles(File::findFilesAndDirectories | File::ignoreHiddenFiles, false))
{
bool include = false;
if (file.isDirectory())
{
include = true;
}
else
{
for (auto& w : wildcards)
{
if (file.getFileName().matchesWildcard(w, true))
{
include = true;
break;
}
}
}
if (include)
mDirectoryListing.add(file.getFullPathName());
}
}
else
{
Array<File> roots;
File::findFileSystemRoots(roots);
for (auto root : roots)
mDirectoryListing.add(root.getFullPathName());
}
SortDirectoryListing(mDirectoryListing);
ShowPage(0);
}
void SampleBrowser::ShowPage(int page)
{
page = ofClamp(page, 0, GetNumPages() - 1);
mCurrentPage = page;
int offset = page * (int)mButtons.size();
for (int i = 0; i < (int)mButtons.size(); ++i)
{
if (i + offset < (int)mDirectoryListing.size())
{
mButtons[i]->SetShowing(true);
if (mDirectoryListing[i + offset] == ".." || File(mDirectoryListing[i + offset]).isDirectory())
{
mButtons[i]->SetDisplayStyle(ButtonDisplayStyle::kFolderIcon);
mPlayButtons[i]->SetShowing(false);
}
else
{
mButtons[i]->SetDisplayStyle(ButtonDisplayStyle::kSampleIcon);
mPlayButtons[i]->SetShowing(true);
}
if (mDirectoryListing[i + offset] == "..")
mButtons[i]->SetLabel("..");
else
mButtons[i]->SetLabel(File(mDirectoryListing[i + offset]).getFileName().toStdString().c_str());
}
else
{
mButtons[i]->SetShowing(false);
mPlayButtons[i]->SetShowing(false);
}
}
mBackButton->SetShowing(GetNumPages() > 1 && mCurrentPage > 0);
mForwardButton->SetShowing(GetNumPages() > 1 && mCurrentPage < GetNumPages() - 1);
}
int SampleBrowser::GetNumPages() const
{
return MAX((int)ceil((float)mDirectoryListing.size() / mButtons.size()), 1);
}
void SampleBrowser::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void SampleBrowser::SetUpFromSaveData()
{
}
void SampleBrowser::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mCurrentDirectory.toStdString();
}
void SampleBrowser::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
std::string currentDirectory;
in >> currentDirectory;
SetDirectory(currentDirectory);
}
``` | /content/code_sandbox/Source/SampleBrowser.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,065 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
TransposeFrom.cpp
Created: 14 Jul 2021 7:47:51pm
Author: Ryan Challinor
==============================================================================
*/
#include "TransposeFrom.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
TransposeFrom::TransposeFrom()
{
TheScale->AddListener(this);
}
TransposeFrom::~TransposeFrom()
{
TheScale->RemoveListener(this);
}
void TransposeFrom::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
DROPDOWN(mRootSelector, "root", &mRoot, 50);
CHECKBOX(mRetriggerCheckbox, "retrigger", &mRetrigger);
ENDUIBLOCK(mWidth, mHeight);
mRootSelector->AddLabel("A", 9);
mRootSelector->AddLabel("A#/Bb", 10);
mRootSelector->AddLabel("B", 11);
mRootSelector->AddLabel("C", 0);
mRootSelector->AddLabel("C#/Db", 1);
mRootSelector->AddLabel("D", 2);
mRootSelector->AddLabel("D#/Eb", 3);
mRootSelector->AddLabel("E", 4);
mRootSelector->AddLabel("F", 5);
mRootSelector->AddLabel("F#/Gb", 6);
mRootSelector->AddLabel("G", 7);
mRootSelector->AddLabel("G#/Ab", 8);
}
void TransposeFrom::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mRootSelector->Draw();
mRetriggerCheckbox->Draw();
}
void TransposeFrom::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
int TransposeFrom::GetTransposeAmount() const
{
return TheScale->ScaleRoot() - mRoot;
}
void TransposeFrom::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (pitch >= 0 && pitch < 128)
{
if (velocity > 0)
{
mInputNotes[pitch].mOn = true;
mInputNotes[pitch].mVelocity = velocity;
mInputNotes[pitch].mVoiceIdx = voiceIdx;
mInputNotes[pitch].mOutputPitch = pitch + GetTransposeAmount();
}
else
{
mInputNotes[pitch].mOn = false;
}
PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, velocity, mInputNotes[pitch].mVoiceIdx, modulation);
}
}
void TransposeFrom::OnScaleChanged()
{
OnRootChanged(gTime);
}
void TransposeFrom::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mRootSelector && mEnabled && mRetrigger)
OnRootChanged(time);
}
void TransposeFrom::OnRootChanged(double time)
{
for (int pitch = 0; pitch < 128; ++pitch)
{
if (mInputNotes[pitch].mOn)
{
PlayNoteOutput(time + .01, mInputNotes[pitch].mOutputPitch, 0, mInputNotes[pitch].mVoiceIdx, ModulationParameters());
mInputNotes[pitch].mOutputPitch = pitch + GetTransposeAmount();
PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, mInputNotes[pitch].mVelocity, mInputNotes[pitch].mVoiceIdx, ModulationParameters());
}
}
}
void TransposeFrom::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void TransposeFrom::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/TransposeFrom.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 996 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
GainStage.cpp
Created: 24 Apr 2021 3:47:25pm
Author: Ryan Challinor
==============================================================================
*/
#include "GainStageEffect.h"
#include "SynthGlobals.h"
#include "Profiler.h"
GainStageEffect::GainStageEffect()
{
}
void GainStageEffect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGainSlider = new FloatSlider(this, "gain", 5, 2, 110, 15, &mGain, 0, 4);
}
void GainStageEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(GainStageEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
buffer->GetChannel(ch)[i] *= mGain;
}
}
void GainStageEffect::DrawModule()
{
mGainSlider->Draw();
}
void GainStageEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void GainStageEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
``` | /content/code_sandbox/Source/GainStageEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 377 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// EnvOscillator.cpp
// additiveSynth
//
// Created by Ryan Challinor on 11/20/12.
//
//
#include "EnvOscillator.h"
float EnvOscillator::Audio(double time, float phase)
{
return mOsc.Value(phase) * mAdsr.Value(time);
}
``` | /content/code_sandbox/Source/EnvOscillator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 166 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// FileStream.cpp
// Bespoke
//
// Created by Ryan Challinor on 4/26/15.
//
//
#include "FileStream.h"
#include "ModularSynth.h"
//static
bool FileStreamIn::s32BitMode = false;
static std::unique_ptr<juce::FileOutputStream> MakeFileOutStream(const std::string& path)
{
auto stream = std::make_unique<juce::FileOutputStream>(juce::File{ path });
stream->setPosition(0);
stream->truncate();
return stream;
}
FileStreamOut::FileStreamOut(const std::string& file)
: mStream(MakeFileOutStream(file))
{
}
FileStreamOut::FileStreamOut(juce::MemoryBlock& block, bool appendToExistingBlockContent)
: mStream(std::make_unique<juce::MemoryOutputStream>(block, appendToExistingBlockContent))
{
}
FileStreamOut::~FileStreamOut()
{
mStream->flush();
}
FileStreamIn::FileStreamIn(const std::string& file)
: mStream(std::make_unique<juce::FileInputStream>(juce::File{ file }))
{
}
FileStreamIn::FileStreamIn(const juce::MemoryBlock& block)
: mStream(std::make_unique<juce::MemoryInputStream>(block, false))
{
}
FileStreamIn::~FileStreamIn() = default;
FileStreamOut& FileStreamOut::operator<<(const int& var)
{
mStream->write(&var, sizeof(int));
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const uint32_t& var)
{
mStream->write(&var, sizeof(uint32_t));
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const bool& var)
{
mStream->write(&var, sizeof(bool));
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const float& var)
{
mStream->write(&var, sizeof(float));
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const double& var)
{
mStream->write(&var, sizeof(double));
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const std::string& var)
{
const uint64_t len = var.length();
mStream->write(&len, sizeof(len));
mStream->write(var.data(), len);
return *this;
}
FileStreamOut& FileStreamOut::operator<<(const char& var)
{
mStream->write(&var, sizeof(char));
return *this;
}
void FileStreamOut::Write(const float* buffer, int size)
{
mStream->write(buffer, sizeof(float) * size);
}
void FileStreamOut::WriteGeneric(const void* buffer, int size)
{
mStream->write(buffer, size);
}
juce::int64 FileStreamOut::GetSize() const
{
return mStream->getPosition();
}
FileStreamIn& FileStreamIn::operator>>(int& var)
{
mStream->read(&var, sizeof(int));
return *this;
}
FileStreamIn& FileStreamIn::operator>>(uint32_t& var)
{
mStream->read(&var, sizeof(uint32_t));
return *this;
}
FileStreamIn& FileStreamIn::operator>>(bool& var)
{
mStream->read(&var, sizeof(bool));
return *this;
}
FileStreamIn& FileStreamIn::operator>>(float& var)
{
mStream->read(&var, sizeof(float));
return *this;
}
FileStreamIn& FileStreamIn::operator>>(double& var)
{
mStream->read(&var, sizeof(double));
return *this;
}
FileStreamIn& FileStreamIn::operator>>(std::string& var)
{
uint64_t len64;
if (s32BitMode)
{
uint32_t len32;
mStream->read(&len32, sizeof(len32));
len64 = len32;
}
else
{
mStream->read(&len64, sizeof(len64));
}
if (TheSynth->IsLoadingModule())
LoadStateValidate(len64 < sMaxStringLength); //probably garbage beyond this point
else
assert(len64 < sMaxStringLength); //probably garbage beyond this point
size_t len = len64;
var.resize(len);
mStream->read(var.data(), len);
return *this;
}
FileStreamIn& FileStreamIn::operator>>(char& var)
{
mStream->read(&var, sizeof(char));
return *this;
}
void FileStreamIn::Read(float* buffer, int size)
{
mStream->read(buffer, sizeof(float) * size);
}
void FileStreamIn::ReadGeneric(void* buffer, int size)
{
mStream->read(buffer, size);
}
void FileStreamIn::Peek(void* buffer, int size)
{
auto pos = mStream->getPosition();
mStream->read(buffer, size);
mStream->setPosition(pos);
}
bool FileStreamIn::Eof() const
{
return mStream->isExhausted();
}
int FileStreamIn::GetFilePosition() const
{
return int(mStream->getPosition());
}
bool FileStreamIn::OpenedOk() const
{
if (auto* file = dynamic_cast<juce::FileInputStream*>(mStream.get()))
return file->openedOk();
return true;
}
``` | /content/code_sandbox/Source/FileStream.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,207 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PulseButton.h
Created: 20 Jun 2020 2:46:02pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "IPulseReceiver.h"
#include "ClickButton.h"
class PulseButton : public IDrawableModule, public IPulseSource, public IButtonListener
{
public:
PulseButton();
virtual ~PulseButton();
static IDrawableModule* Create() { return new PulseButton(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void ButtonClicked(ClickButton* button, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
ClickButton* mButton{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
bool mForceImmediate{ false };
};
``` | /content/code_sandbox/Source/PulseButton.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 385 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Compressor.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#include "Compressor.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "Profiler.h"
#include "UIControlMacros.h"
namespace
{
static double lin2dB(double lin)
{
static const double LOG_2_DB = 8.6858896380650365530225783783321; // 20 / ln( 10 )
return log(lin) * LOG_2_DB;
}
static double dB2lin(double dB)
{
static const double DB_2_LOG = 0.11512925464970228420089957273422; // ln( 10 ) / 20
return exp(dB * DB_2_LOG);
}
const float kMaxLookaheadMs = 50;
}
Compressor::Compressor()
: mDelayBuffer(kMaxLookaheadMs * gSampleRateMs)
{
}
void Compressor::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mMixSlider, "mix", &mMix, 0, 1);
FLOATSLIDER(mDriveSlider, "drive", &mDrive, .01f, 2);
FLOATSLIDER(mThresholdSlider, "threshold", &mThreshold, -70, 0);
FLOATSLIDER(mRatioSlider, "ratio", &mRatio, 1, 40);
UIBLOCK_NEWCOLUMN();
FLOATSLIDER(mAttackSlider, "attack", &mAttack, .1f, kMaxLookaheadMs);
FLOATSLIDER(mReleaseSlider, "release", &mRelease, .1f, 500);
FLOATSLIDER(mLookaheadSlider, "lookahead", &mLookahead, 0, kMaxLookaheadMs);
FLOATSLIDER(mOutputAdjustSlider, "output", &mOutputAdjust, 0, 2);
ENDUIBLOCK(mWidth, mHeight);
mRatioSlider->SetMode(FloatSlider::kSquare);
mAttackSlider->SetMode(FloatSlider::kSquare);
mReleaseSlider->SetMode(FloatSlider::kSquare);
mLookaheadSlider->SetMode(FloatSlider::kSquare);
mOutputAdjustSlider->SetMode(FloatSlider::kSquare);
mEnv.setAttack(mAttack);
mEnv.setRelease(mRelease);
}
void Compressor::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(Compressor);
if (!mEnabled)
return;
int bufferSize = buffer->BufferSize();
mDelayBuffer.SetNumChannels(buffer->NumActiveChannels());
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
// create sidechain
float input = 0;
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
input = MAX(input, fabsf(buffer->GetChannel(ch)[i]));
input *= mDrive;
/* if desired, one could use another EnvelopeDetector to smooth
* the rectified signal.
*/
// convert key to dB
input += DC_OFFSET; // add DC offset to avoid log( 0 )
mCurrentInputDb = lin2dB(input); // convert linear -> dB
// threshold
double overdB = mCurrentInputDb - mThreshold; // delta over threshold
if (overdB < 0.0)
overdB = 0.0;
// attack/release
overdB += DC_OFFSET; // add DC offset to avoid denormal
mEnv.run(overdB, envdB_); // run attack/release envelope
overdB = envdB_ - DC_OFFSET; // subtract DC offset
/* REGARDING THE DC OFFSET: In this case, since the offset is added before
* the attack/release processes, the envelope will never fall below the offset,
* thereby avoiding denormals. However, to prevent the offset from causing
* constant gain reduction, we must subtract it from the envelope, yielding
* a minimum value of 0dB.
*/
double invRatio = 1 / mRatio;
// transfer function
double reduction = overdB * (invRatio - 1.0); // gain reduction (dB)
double makeup = (-mThreshold * .5) * (1.0 - invRatio);
mOutputGain = ofLerp(1, dB2lin(reduction + makeup) * mDrive * mOutputAdjust, mMix);
// output gain
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
{
mDelayBuffer.Write(buffer->GetChannel(ch)[i], ch);
buffer->GetChannel(ch)[i] = mDelayBuffer.GetSample(ofClamp(int(mLookahead * gSampleRateMs) + 1, 1, mDelayBuffer.Size() - 1), ch) * mOutputGain; // apply gain reduction to input
}
}
}
void Compressor::DrawModule()
{
mMixSlider->Draw();
mDriveSlider->Draw();
mThresholdSlider->Draw();
mRatioSlider->Draw();
mAttackSlider->Draw();
mReleaseSlider->Draw();
mLookaheadSlider->Draw();
mOutputAdjustSlider->Draw();
ofPushStyle();
ofSetColor(0, 255, 0, gModuleDrawAlpha);
float x, y, w, h;
mThresholdSlider->GetPosition(x, y, K(local));
mThresholdSlider->GetDimensions(w, h);
float currentInputX = ofMap(mCurrentInputDb, mThresholdSlider->GetMin(), mThresholdSlider->GetMax(), x, x + w, K(clamp));
ofLine(currentInputX, y, currentInputX, y + h);
mRatioSlider->GetPosition(x, y, K(local));
mRatioSlider->GetDimensions(w, h);
float outputNormalized = ofClamp(mOutputGain / 10, 0, 1);
float currentOutputX = ofLerp(x, x + w, sqrtf(outputNormalized));
ofLine(currentOutputX, y, currentOutputX, y + h);
ofPopStyle();
}
void Compressor::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
envdB_ = DC_OFFSET; //reset state
}
void Compressor::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mAttackSlider)
mEnv.setAttack(MAX(.1f, mAttack));
if (slider == mReleaseSlider)
mEnv.setRelease(MAX(.1f, mRelease));
}
//-------------------------------------------------------------
// envelope detector
//-------------------------------------------------------------
EnvelopeDetector::EnvelopeDetector(double ms)
{
assert(ms > 0.0);
ms_ = ms;
setCoef();
}
//-------------------------------------------------------------
void EnvelopeDetector::setTc(double ms)
{
assert(ms > 0.0);
ms_ = ms;
setCoef();
}
//-------------------------------------------------------------
void EnvelopeDetector::setCoef()
{
coef_ = exp(-1000.0 / (ms_ * gSampleRate));
}
//-------------------------------------------------------------
// attack/release envelope
//-------------------------------------------------------------
AttRelEnvelope::AttRelEnvelope(double att_ms, double rel_ms)
: att_(att_ms)
, rel_(rel_ms)
{
}
//-------------------------------------------------------------
void AttRelEnvelope::setAttack(double ms)
{
att_.setTc(ms);
}
//-------------------------------------------------------------
void AttRelEnvelope::setRelease(double ms)
{
rel_.setTc(ms);
}
``` | /content/code_sandbox/Source/Compressor.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,738 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ControlRecorder.h
Created: 7 Apr 2024
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "Checkbox.h"
#include "Transport.h"
#include "DropdownList.h"
#include "Curve.h"
#include "IModulator.h"
#include "Slider.h"
class PatchCableSource;
class ControlRecorder : public IDrawableModule, public IDropdownListener, public IButtonListener, public IFloatSliderListener, public IModulator
{
public:
ControlRecorder();
~ControlRecorder();
static IDrawableModule* Create() { return new ControlRecorder(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetRecording(bool on);
float GetLength() const { return mLength; }
//IDrawableModule
void Init() override;
void Poll() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return IsEnabled() && mHasRecorded && !mRecord; }
bool CanAdjustRange() const override { return false; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return mEnabled; }
private:
float GetPlaybackTime(double time);
void RecordPoint();
void Clear();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
Curve mCurve{ 0 };
bool mHasRecorded{ false };
float mLength{ 0 };
bool mQuantizeLength{ true };
Checkbox* mQuantizeLengthCheckbox{ nullptr };
NoteInterval mQuantizeInterval{ NoteInterval::kInterval_1n };
DropdownList* mQuantizeLengthSelector{ nullptr };
float mSpeed{ 1 };
FloatSlider* mSpeedSlider{ nullptr };
ClickButton* mClearButton{ nullptr };
float mDisplayStartY{ 0 };
float mWidth{ 220 };
float mHeight{ 100 };
double mRecordStartOffset{ 0 };
Checkbox* mRecordCheckbox{ nullptr };
bool mRecord{ false };
IUIControl* mConnectedControl{ nullptr };
};
``` | /content/code_sandbox/Source/ControlRecorder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 819 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// RingModulator.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/7/13.
//
//
#include "RingModulator.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "Scale.h"
RingModulator::RingModulator()
: IAudioProcessor(gBufferSize)
, mDryBuffer(gBufferSize)
{
mModOsc.Start(gTime, 1);
mFreqRamp.Start(gTime, 220, gTime + mGlideTime);
}
void RingModulator::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mFreqSlider = new FloatSlider(this, "freq", 5, 4, 120, 15, &mFreq, 20, 2000);
mDryWetSlider = new FloatSlider(this, "dry/wet", 5, 20, 120, 15, &mDryWet, 0, 1);
mVolumeSlider = new FloatSlider(this, "volume", 5, 36, 120, 15, &mVolume, 0, 2);
mGlideSlider = new FloatSlider(this, "glide", 5, 52, 120, 15, &mGlideTime, 0, 1000);
mFreqSlider->SetMode(FloatSlider::kLogarithmic);
}
RingModulator::~RingModulator()
{
}
void RingModulator::Process(double time)
{
PROFILER(RingModulator);
IAudioReceiver* target = GetTarget();
if (target == nullptr)
return;
SyncBuffers();
mDryBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels());
int bufferSize = target->GetBuffer()->BufferSize();
if (mEnabled)
{
mDryBuffer.CopyFrom(GetBuffer());
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
GetBuffer()->GetChannel(ch)[i] *= mModOsc.Audio(time, mPhase);
float phaseInc = GetPhaseInc(mFreqRamp.Value(time));
mPhase += phaseInc;
while (mPhase > FTWO_PI)
{
mPhase -= FTWO_PI;
}
time += gInvSampleRateMs;
}
}
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
if (mEnabled)
{
Mult(mDryBuffer.GetChannel(ch), (1 - mDryWet) * mVolume * mVolume, GetBuffer()->BufferSize());
Mult(GetBuffer()->GetChannel(ch), mDryWet * mVolume * mVolume, GetBuffer()->BufferSize());
Add(GetBuffer()->GetChannel(ch), mDryBuffer.GetChannel(ch), GetBuffer()->BufferSize());
}
Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
GetBuffer()->Reset();
}
void RingModulator::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mFreqSlider->Draw();
mVolumeSlider->Draw();
mDryWetSlider->Draw();
mGlideSlider->Draw();
}
void RingModulator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0)
{
float freq = TheScale->PitchToFreq(pitch);
mFreqRamp.Start(time, freq, time + mGlideTime);
mFreq = freq;
}
}
void RingModulator::ButtonClicked(ClickButton* button, double time)
{
}
void RingModulator::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void RingModulator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mFreqSlider)
{
mFreqRamp.SetValue(mFreq);
}
}
void RingModulator::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void RingModulator::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/RingModulator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,061 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteCounter.h
Created: 24 Apr 2021 3:47:48pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Transport.h"
#include "Slider.h"
#include "DropdownList.h"
#include "IPulseReceiver.h"
#include "IDrivableSequencer.h"
#include "ClickButton.h"
#include "TextEntry.h"
class NoteCounter : public IDrawableModule, public INoteSource, public ITimeListener, public IIntSliderListener, public IDropdownListener, public IPulseReceiver, public IDrivableSequencer, public ITextEntryListener, public IButtonListener
{
public:
NoteCounter();
~NoteCounter();
static IDrawableModule* Create() { return new NoteCounter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//ITimeListener
void OnTimeEvent(double time) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
//IDrivableSequencer
bool HasExternalPulseSource() const override { return mHasExternalPulseSource; }
void ResetExternalPulseSource() override { mHasExternalPulseSource = false; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override {}
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 2; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void Step(double time, float velocity, int pulseFlags);
void Reseed();
std::uint64_t GetRandom(double time, int seedOffset) const;
float mWidth{ 200 };
float mHeight{ 20 };
NoteInterval mInterval{ NoteInterval::kInterval_16n };
DropdownList* mIntervalSelector{ nullptr };
int mStart{ 0 };
IntSlider* mStartSlider{ nullptr };
int mLength{ 16 };
IntSlider* mLengthSlider{ nullptr };
int mStep{ 0 };
Checkbox* mSyncCheckbox{ nullptr };
bool mSync{ true };
int mCustomDivisor{ 8 };
IntSlider* mCustomDivisorSlider{ nullptr };
bool mRandom{ false };
Checkbox* mRandomCheckbox{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
bool mHasExternalPulseSource{ false };
bool mDeterministic{ false };
int mDeterministicLength{ 4 };
IntSlider* mDeterministicLengthSlider{ nullptr };
int mSeed{ 0 };
TextEntry* mSeedEntry{ nullptr };
ClickButton* mReseedButton{ nullptr };
ClickButton* mPrevSeedButton{ nullptr };
ClickButton* mNextSeedButton{ nullptr };
};
``` | /content/code_sandbox/Source/NoteCounter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 905 |
```c++
/*
* ofxJSONFile.cpp
* asift
*
* Created by Jeffrey Crouse on 12/17/10.
*
*/
#include "ofxJSONElement.h"
#include "SynthGlobals.h"
#include <json/reader.h>
#include <json/writer.h>
#include "juce_core/juce_core.h"
using namespace Json;
//--------------------------------------------------------------
ofxJSONElement::ofxJSONElement(const Json::Value& v)
: Value(v)
{
}
//--------------------------------------------------------------
ofxJSONElement::ofxJSONElement(std::string jsonString)
{
parse(jsonString);
}
//--------------------------------------------------------------
bool ofxJSONElement::parse(std::string jsonString)
{
CharReaderBuilder rb;
auto reader = std::unique_ptr<Json::CharReader>(rb.newCharReader());
Json::String errors;
if (!reader->parse(jsonString.c_str(),
jsonString.c_str() + jsonString.size(),
this, &errors))
{
ofLog() << "Unable to parse string: " << errors;
return false;
}
return true;
}
//--------------------------------------------------------------
bool ofxJSONElement::open(std::string filename)
{
juce::File file(filename);
if (file.exists())
{
juce::String str = file.loadFileAsString();
CharReaderBuilder builder;
auto reader = std::unique_ptr<CharReader>(builder.newCharReader());
auto mS = str.toStdString();
if (!reader->parse(mS.c_str(), mS.c_str() + mS.size(), this, nullptr))
{
ofLog() << "Unable to parse " + filename;
return false;
}
}
else
{
ofLog() << "Could not load file " + filename;
return false;
}
return true;
}
//--------------------------------------------------------------
bool ofxJSONElement::save(std::string filename, bool pretty)
{
filename = ofToDataPath(filename);
juce::File file(filename);
file.create();
if (!file.exists())
{
ofLog() << "Unable to create " + filename;
return false;
}
Json::StreamWriterBuilder builder;
if (pretty)
{
builder["indentation"] = " ";
}
const std::string json_file = Json::writeString(builder, *this);
file.replaceWithText(json_file);
ofLog() << "JSON saved to " + filename;
return true;
}
//--------------------------------------------------------------
std::string ofxJSONElement::getRawString(bool pretty)
{
std::string raw;
Json::StreamWriterBuilder builder;
if (pretty)
{
builder["indentation"] = " ";
}
raw = Json::writeString(builder, *this);
return raw;
}
``` | /content/code_sandbox/Source/ofxJSONElement.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 572 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ScriptStatus.h
Created: 25 Apr 2020 10:51:14pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "ClickButton.h"
class ScriptStatus : public IDrawableModule, public IButtonListener
{
public:
ScriptStatus();
virtual ~ScriptStatus();
static IDrawableModule* Create() { return new ScriptStatus(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void Poll() override;
void CreateUIControls() override;
void ButtonClicked(ClickButton* button, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void OnClicked(float x, float y, bool right) override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override
{
mWidth = w;
mHeight = h;
}
ClickButton* mResetAll{ nullptr };
std::string mStatus;
double mNextUpdateTime{ 0 };
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/ScriptStatus.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 509 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// BeatBloks.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/9/13.
//
//
#include "BeatBloks.h"
#include "IAudioReceiver.h"
#include "Sample.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif
const float mBufferX = 5;
const float mBufferY = 80;
const float mBufferW = 900;
const float mBufferH = 200;
const float mRemixBufferY = mBufferY + mBufferH + 60;
BeatBloks::BeatBloks()
: mRemixZoomEnd(gSampleRate * 25)
{
mWriteBuffer = new float[gBufferSize];
Clear(mWriteBuffer, gBufferSize);
mSample = new Sample();
/*vector<string> fake;
fake.push_back(ofToDataPath("01 - Reflektor.mp3",true));
FilesDropped(fake, 0, 0);*/
}
void BeatBloks::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolumeSlider = new FloatSlider(this, "volume", 5, 20, 110, 15, &mVolume, 0, 2);
mPlayCheckbox = new Checkbox(this, "play", 5, mBufferY - 20, &mPlay);
mLoopCheckbox = new Checkbox(this, "loop", 60, mBufferY - 20, &mLoop);
mClipStartSlider = new FloatSlider(this, "start", mBufferX, mBufferY + mBufferH - 30, 900, 15, &mClipStart, 0, gSampleRate * 200);
mClipEndSlider = new FloatSlider(this, "end", mBufferX, mBufferY + mBufferH - 15, 900, 15, &mClipEnd, 0, gSampleRate * 200);
mZoomStartSlider = new FloatSlider(this, "zoomstart", mBufferX, mBufferY + mBufferH + 5, 900, 15, &mZoomStart, 0, gSampleRate * 200);
mZoomEndSlider = new FloatSlider(this, "zoomend", mBufferX, mBufferY + mBufferH + 20, 900, 15, &mZoomEnd, 0, gSampleRate * 200);
mNumBarsSlider = new IntSlider(this, "num bars", 215, 3, 220, 15, &mNumBars, 1, 16);
mOffsetSlider = new FloatSlider(this, "offset", 215, 20, 300, 15, &mOffset, -gSampleRate * 2, gSampleRate * 2);
mWriteButton = new ClickButton(this, "[test]", 600, 50);
mDoubleLengthButton = new ClickButton(this, "double", 600, 10);
mHalveLengthButton = new ClickButton(this, "halve", 600, 28);
mDrawBlokTypeDropdown = new DropdownList(this, "draw type", 215, 40, (int*)&mDrawBlokType);
mPlayRemixCheckbox = new Checkbox(this, "play remix", 15, mRemixBufferY - 20, &mPlayRemix);
mClearRemixButton = new ClickButton(this, "clear remix", 100, mRemixBufferY - 20);
mDrawSourcesCheckbox = new Checkbox(this, "draw sources", 300, mRemixBufferY - 20, &mDrawSources);
mRemixZoomStartSlider = new FloatSlider(this, "r zoomstart", mBufferX, mRemixBufferY + mBufferH + 5, 900, 15, &mRemixZoomStart, 0, gSampleRate * 200);
mRemixZoomEndSlider = new FloatSlider(this, "r zoomend", mBufferX, mRemixBufferY + mBufferH + 20, 900, 15, &mRemixZoomEnd, 0, gSampleRate * 200);
mGetLuckyButton = new ClickButton(this, "gl", 700, 10);
mLoseYourselfButton = new ClickButton(this, "ly", 700, 28);
mDrawBlokTypeDropdown->AddLabel("tatums", kBlok_Tatum);
mDrawBlokTypeDropdown->AddLabel("beats", kBlok_Beat);
mDrawBlokTypeDropdown->AddLabel("segments", kBlok_Segment);
mDrawBlokTypeDropdown->AddLabel("bars", kBlok_Bar);
mDrawBlokTypeDropdown->AddLabel("sections", kBlok_Section);
}
BeatBloks::~BeatBloks()
{
delete[] mWriteBuffer;
delete mSample;
}
void BeatBloks::Poll()
{
if (mBlockMultiPlaceEngaged && !IsKeyHeld('z'))
{
mHeldBlok = nullptr;
}
}
void BeatBloks::Process(double time)
{
PROFILER(BeatBloks);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr || mSample == nullptr || mLoading)
return;
ComputeSliders(0);
if (mWantWrite)
{
DoWrite();
mWantWrite = false;
}
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
float volSq = mVolume * mVolume;
float clipStart = mClipStart;
float clipEnd = mClipEnd;
if (mPlay && (clipStart < clipEnd))
{
float speed = float(clipEnd - clipStart) * gInvSampleRateMs / TheTransport->MsPerBar() / mNumBars;
const float* data = mSample->Data()->GetChannel(0);
int numSamples = mSample->LengthInSamples();
float sampleRateRatio = mSample->GetSampleRateRatio();
mPlayheadRemainder = TheTransport->GetMeasurePos(time) + (TheTransport->GetMeasure(time) % mNumBars);
mPlayheadRemainder /= mNumBars;
mPlayheadRemainder *= clipEnd - clipStart;
mPlayheadWhole = int(mPlayheadRemainder);
mPlayheadRemainder -= mPlayheadWhole;
mPlayheadWhole += int(clipStart);
mPlayheadRemainder += clipStart - int(clipStart);
mPlayheadWhole = MAX(0, mPlayheadWhole);
mPlayheadRemainder = MAX(0.0f, mPlayheadRemainder);
for (int i = 0; i < bufferSize; ++i)
{
if (mPlayheadWhole >= clipEnd)
mPlayheadWhole -= (clipEnd - clipStart);
if (mPlayheadWhole < clipStart)
mPlayheadWhole += (clipEnd - clipStart);
out[i] = GetInterpolatedSample(mPlayheadRemainder + 1, data + mPlayheadWhole - 1, numSamples) * volSq;
mPlayheadRemainder += speed * sampleRateRatio;
}
}
Blok* heldBlok = mHeldBlok; //hold onto it in case it gets nulled in the main thread
if (mPlayBlokPreview && heldBlok)
{
float speed = 1;
const float* data = mSample->Data()->GetChannel(0);
int numSamples = mSample->LengthInSamples();
float sampleRateRatio = mSample->GetSampleRateRatio();
double previewTime = time;
for (int i = 0; i < bufferSize; ++i)
{
if (mBlokPreviewPlayhead == 0)
{
mBlokPreviewRamp.Start(previewTime, 1, previewTime + 1);
}
if (mBlokPreviewPlayhead > heldBlok->mDuration * numSamples)
{
if (mBlokPreviewRamp.Target(previewTime) != 0)
mBlokPreviewRamp.Start(previewTime, 0, previewTime + 1);
if (mBlokPreviewRamp.Value(previewTime) == 0)
{
mPlayBlokPreview = false;
}
}
float lookupPlayhead = StartTime(*heldBlok) * numSamples + mBlokPreviewPlayhead;
out[i] = GetInterpolatedSample(lookupPlayhead, data, numSamples);
out[i] *= mBlokPreviewRamp.Value(previewTime);
out[i] *= volSq;
mBlokPreviewPlayhead += speed * sampleRateRatio;
previewTime += gInvSampleRateMs;
}
}
if (mPlayRemix)
{
float speed = 1;
const float* data = mSample->Data()->GetChannel(0);
int numSamples = mSample->LengthInSamples();
float sampleRateRatio = mSample->GetSampleRateRatio();
for (int i = 0; i < bufferSize; ++i)
{
float remixPlayheadLeft = mRemixPlayhead;
Blok* currentBlok = nullptr;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter)
{
if (remixPlayheadLeft < (*iter)->mDuration * numSamples)
{
currentBlok = (*iter);
break;
}
remixPlayheadLeft -= (*iter)->mDuration * numSamples;
}
if (currentBlok == nullptr)
{
out[i] = 0;
mPlayRemix = false;
continue;
}
if (currentBlok != mLastPlayedRemixBlok && mLastPlayedRemixBlok)
{
mRemixJumpBlender.CaptureForJump(mLastLookupPlayhead, data, numSamples, i);
}
float lookupPlayhead = StartTime(*currentBlok) * numSamples + remixPlayheadLeft;
mLastLookupPlayhead = lookupPlayhead;
out[i] = GetInterpolatedSample(lookupPlayhead, data, numSamples);
out[i] = mRemixJumpBlender.Process(out[i], i);
out[i] *= volSq;
mRemixPlayhead += speed * sampleRateRatio;
mPlayheadWhole = int(lookupPlayhead); //for visualizing it jump around
mLastPlayedRemixBlok = currentBlok;
}
}
GetVizBuffer()->WriteChunk(out, bufferSize, 0);
}
void BeatBloks::FilesDropped(std::vector<std::string> files, int x, int y)
{
mLoading = true;
mSample->Reset();
mSample->Read(files[0].c_str());
ResetRead();
std::vector<std::string> tokens = ofSplitString(files[0].c_str(), GetPathSeparator());
std::string cachedFilename = tokens[tokens.size() - 1].c_str();
tokens = ofSplitString(cachedFilename, ".");
cachedFilename = tokens[0] + ".cached";
bool hasCached = juce::File(ofToDataPath(cachedFilename)).existsAsFile();
ofLog() << cachedFilename << " exists: " << (hasCached ? "true" : "false");
FILE* output;
FILE* cachedFile;
if (!hasCached) //have to look it up with echonest
{
char command[2048];
snprintf(command, sizeof(command), "export ECHO_NEST_API_KEY=SUZ3W7PAIVQQXZCAW; export PATH=/usr/local/bin:$PATH; python \"%s\" \"%s\"", ofToDataPath("get_echonest_remix_data.py").c_str(), files[0].c_str());
output = popen(command, "r");
cachedFile = fopen(ofToDataPath(cachedFilename).c_str(), "w");
}
else
{
output = fopen(ofToDataPath(cachedFilename).c_str(), "r");
}
char c;
char line[512]{};
int linepos = 0;
do
{
c = fgetc(output);
if (!hasCached)
fputc(c, cachedFile);
//printf("%c",c);
if (c == '\n' || c == EOF)
{
ReadEchonestLine(line);
linepos = 0;
std::memset(line, 0, sizeof(line));
}
else
{
line[linepos++] = c;
}
} while (c != EOF);
if (hasCached)
{
fclose(output);
}
else
{
pclose(output);
fclose(cachedFile);
}
mClipStart = 0;
mClipEnd = mSample->LengthInSamples();
mZoomStart = 0;
mZoomEnd = MIN(1400000, mClipEnd);
mNumBars = (int)mBars.size();
mZoomStartSlider->SetExtents(0, mSample->LengthInSamples());
mZoomEndSlider->SetExtents(0, mSample->LengthInSamples());
UpdateZoomExtents();
mRemixBloks.clear();
mOffset = 0;
TheTransport->SetTempo(76);
mLoading = false;
}
void BeatBloks::ResetRead()
{
mReadState = kReadState_Start;
mBars.clear();
mBeats.clear();
mTatums.clear();
mSections.clear();
mSegments.clear();
}
void BeatBloks::ReadEchonestLine(const char* line)
{
std::vector<std::string> tokens = ofSplitString(line, " ");
if (tokens.size() == 1)
{
if (tokens[0] == "bars")
mReadState = kReadState_Bars;
if (tokens[0] == "beats")
mReadState = kReadState_Beats;
if (tokens[0] == "tatums")
mReadState = kReadState_Tatums;
if (tokens[0] == "sections")
mReadState = kReadState_Sections;
if (tokens[0] == "segments")
mReadState = kReadState_Segments;
}
else
{
float lengthInSeconds = mSample->LengthInSamples() / gSampleRate;
if (mReadState == kReadState_Bars || mReadState == kReadState_Beats || mReadState == kReadState_Tatums)
assert(tokens.size() == 3);
if (mReadState == kReadState_Sections || mReadState == kReadState_Segments)
assert(tokens.size() == 2);
float adjustSeconds = -.062f;
float start = (ofToFloat(tokens[0]) + adjustSeconds) / lengthInSeconds;
float duration = ofToFloat(tokens[1]) / lengthInSeconds;
float confidence = tokens.size() == 3 ? ofToFloat(tokens[2]) : 1;
Blok blok(start, duration, confidence);
if (mReadState == kReadState_Bars)
{
blok.mType = kBlok_Bar;
mBars.push_back(blok);
}
if (mReadState == kReadState_Beats)
{
blok.mType = kBlok_Beat;
mBeats.push_back(blok);
}
if (mReadState == kReadState_Tatums)
{
blok.mType = kBlok_Tatum;
mTatums.push_back(blok);
}
if (mReadState == kReadState_Sections)
{
blok.mType = kBlok_Section;
mSections.push_back(blok);
}
if (mReadState == kReadState_Segments)
{
blok.mType = kBlok_Segment;
mSegments.push_back(blok);
}
}
}
void BeatBloks::DropdownClicked(DropdownList* list)
{
}
void BeatBloks::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void BeatBloks::UpdateSample()
{
}
void BeatBloks::ButtonClicked(ClickButton* button, double time)
{
if (button == mWriteButton)
{
//mWantWrite = true;
mClipStart = StartTime(mBars[10]) * mSample->LengthInSamples();
mClipEnd = StartTime(mBars[14]) * mSample->LengthInSamples();
mZoomStart = mClipStart - 40000;
mZoomEnd = mClipEnd + 40000;
mNumBars = 4;
UpdateZoomExtents();
}
if (button == mDoubleLengthButton)
{
float newEnd = (mClipEnd - mClipStart) * 2 + mClipStart;
if (newEnd < mSample->LengthInSamples())
{
mClipEnd = newEnd;
mNumBars *= 2;
}
}
if (button == mHalveLengthButton)
{
if (mNumBars % 2 == 0)
{
float newEnd = (mClipEnd - mClipStart) / 2 + mClipStart;
mClipEnd = newEnd;
mNumBars /= 2;
}
}
if (button == mClearRemixButton)
{
mRemixBloks.clear();
}
if (button == mGetLuckyButton)
{
std::vector<std::string> fake;
fake.push_back(ofToDataPath("Daft Punk - Get Lucky.mp3"));
FilesDropped(fake, 0, 0);
mOffset = -53275;
}
if (button == mLoseYourselfButton)
{
std::vector<std::string> fake;
fake.push_back(ofToDataPath("Daft Punk - Lose Yourself To Dance.mp3"));
FilesDropped(fake, 0, 0);
}
}
void BeatBloks::DoWrite()
{
if (mSample)
{
mSample->ClipTo(mClipStart, mClipEnd);
int shift = (mClipEnd - mClipStart);
if (shift < 0)
shift += mClipEnd - mClipStart;
mSample->ShiftWrap(shift);
mSample->Write(ofGetTimestampString("BeatBloks_%Y-%m-%d_%H-%M.wav").c_str());
mClipStart = 0;
mClipEnd = mSample->LengthInSamples();
mZoomStart = 0;
mZoomEnd = mClipEnd;
mZoomStartSlider->SetExtents(0, mClipEnd);
mZoomEndSlider->SetExtents(0, mClipEnd);
UpdateZoomExtents();
}
}
void BeatBloks::UpdateZoomExtents()
{
mClipStartSlider->SetExtents(mZoomStart, mZoomEnd);
mClipEndSlider->SetExtents(mZoomStart, mZoomEnd);
}
void BeatBloks::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
int sampleLength = mSample->LengthInSamples();
if (x >= mBufferX && y >= mBufferY && x <= mBufferX + mBufferW && y <= mBufferY + mBufferH - 28) //clicked waveform
{
x -= mBufferX;
y -= mBufferY;
if (y < MEASURE_ZONE_HEIGHT) //clicked measure
{
float zoomPos = x / mBufferW;
float pos = ofMap(zoomPos, 0, 1, mZoomStart / sampleLength, mZoomEnd / sampleLength);
for (int i = 0; i < mBars.size(); ++i)
{
if (StartTime(mBars[i]) < pos && pos < StartTime(mBars[i]) + mBars[i].mDuration)
mHeldBlok = &mBars[i];
}
}
else if (y > mBufferH - BEAT_ZONE_HEIGHT) //clicked beat
{
float zoomPos = x / mBufferW;
float pos = ofMap(zoomPos, 0, 1, mZoomStart / sampleLength, mZoomEnd / sampleLength);
for (int i = 0; i < mBeats.size(); ++i)
{
if (StartTime(mBeats[i]) < pos && pos < StartTime(mBeats[i]) + mBeats[i].mDuration)
mHeldBlok = &mBeats[i];
}
}
else //clicked tatum
{
float zoomPos = x / mBufferW;
float pos = ofMap(zoomPos, 0, 1, mZoomStart / sampleLength, mZoomEnd / sampleLength);
for (int i = 0; i < mTatums.size(); ++i)
{
if (StartTime(mTatums[i]) < pos && pos < StartTime(mTatums[i]) + mTatums[i].mDuration)
mHeldBlok = &mTatums[i];
}
}
if (mHeldBlok)
{
if (IsKeyHeld('s'))
{
mRemixBloks.push_back(mHeldBlok);
mHeldBlok = nullptr;
}
else
{
float pos = ofMap(StartTime(*mHeldBlok), mZoomStart / sampleLength, mZoomEnd / sampleLength, 0, 1);
mGrabOffsetX = x - mBufferW * pos;
mGrabOffsetY = y;
mBlokPreviewPlayhead = 0;
mPlayBlokPreview = true;
mBlockMultiPlaceEngaged = false;
}
mLastRemovedRemixBlokIdx = -1;
}
}
else if (y > mRemixBufferY && y < mRemixBufferY + mBufferH)
{
if (mHeldBlok)
{
PlaceHeldBlok();
if (!IsKeyHeld('z'))
mHeldBlok = nullptr;
}
else if (IsKeyHeld('a'))
{
mHeldBlok = RemoveBlokAt(x);
mBlokPreviewPlayhead = 0;
mPlayBlokPreview = true;
mBlockMultiPlaceEngaged = false;
mGrabOffsetX = 0;
mGrabOffsetY = 0;
}
else if (IsKeyHeld('x'))
{
RemoveBlokAt(x);
}
else
{
mRemixPlayhead = ofMap(x, mBufferX, mBufferX + mBufferW, mRemixZoomStart, mRemixZoomEnd, true);
mPlayRemix = true;
}
}
else
{
mHeldBlok = nullptr;
}
}
void BeatBloks::PlaceHeldBlok()
{
assert(mHeldBlok);
int insertIndex;
GetInsertPosition(insertIndex);
if (insertIndex == -1)
{
mRemixBloks.push_back(mHeldBlok);
}
else
{
int i = 0;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter, ++i)
{
if (i == insertIndex)
{
mRemixBloks.insert(iter, mHeldBlok);
break;
}
}
}
}
void BeatBloks::MouseReleased()
{
IDrawableModule::MouseReleased();
if (!mBlockMultiPlaceEngaged && mMouseY > mRemixBufferY && mMouseY < mRemixBufferY + mBufferH)
{
if (mHeldBlok)
PlaceHeldBlok();
}
if (IsKeyHeld('z'))
mBlockMultiPlaceEngaged = true;
else
mHeldBlok = nullptr;
}
bool BeatBloks::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mMouseX = x;
mMouseY = y;
return false;
}
void BeatBloks::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVolumeSlider->Draw();
mPlayCheckbox->Draw();
mLoopCheckbox->Draw();
mDrawBlokTypeDropdown->Draw();
mPlayRemixCheckbox->Draw();
mClearRemixButton->Draw();
mDrawSourcesCheckbox->Draw();
mRemixZoomStartSlider->Draw();
mRemixZoomEndSlider->Draw();
mGetLuckyButton->Draw();
mLoseYourselfButton->Draw();
if (mSample)
{
ofPushMatrix();
ofTranslate(mBufferX, mBufferY);
ofPushStyle();
mSample->LockDataMutex(true);
DrawAudioBuffer(mBufferW, mBufferH, mSample->Data(), mZoomStart, mZoomEnd, (int)mPlayheadWhole);
mSample->LockDataMutex(false);
int sampleLength = MAX(1, mSample->LengthInSamples());
if (mBars.size() != 0)
{
ofSetColor(0, 255, 255, 60);
std::vector<Blok>& drawBloks = mNothing;
switch (mDrawBlokType)
{
case kBlok_Bar:
drawBloks = mBars;
break;
case kBlok_Beat:
drawBloks = mBeats;
break;
case kBlok_Tatum:
drawBloks = mTatums;
break;
case kBlok_Section:
drawBloks = mSections;
break;
case kBlok_Segment:
drawBloks = mSegments;
break;
}
for (int i = 0; i < drawBloks.size(); ++i)
{
float pos = ofMap(StartTime(drawBloks[i]), mZoomStart / sampleLength, mZoomEnd / sampleLength, 0, 1);
if (pos >= 0 && pos <= 1)
ofLine(mBufferW * pos, 0, mBufferW * pos, mBufferH);
}
ofFill();
for (int i = 0; i < mBars.size(); ++i)
{
ofSetColor(255, 0, (i % 2) * 255, 60);
float pos = ofMap(StartTime(mBars[i]), mZoomStart / sampleLength, mZoomEnd / sampleLength, 0, 1);
float dur = ofMap(mBars[i].mDuration, 0, (mZoomEnd - mZoomStart) / sampleLength, 0, 1);
float end = pos + dur;
if ((pos >= 0 && pos <= 1) || (end >= 0 && end <= 1))
{
pos = ofClamp(pos, 0, 1);
end = ofClamp(end, 0, 1);
ofRect(mBufferW * pos, 0, mBufferW * (end - pos), MEASURE_ZONE_HEIGHT);
}
}
for (int i = 0; i < mBeats.size(); ++i)
{
ofSetColor(255, 255, (i % 2) * 255, 60);
float pos = ofMap(StartTime(mBeats[i]), mZoomStart / sampleLength, mZoomEnd / sampleLength, 0, 1);
float dur = ofMap(mBeats[i].mDuration, 0, (mZoomEnd - mZoomStart) / sampleLength, 0, 1);
float end = pos + dur;
if ((pos >= 0 && pos <= 1) || (end >= 0 && end <= 1))
{
pos = ofClamp(pos, 0, 1);
end = ofClamp(end, 0, 1);
ofRect(mBufferW * pos, mBufferH - BEAT_ZONE_HEIGHT, mBufferW * (end - pos), BEAT_ZONE_HEIGHT);
}
}
for (int i = 0; i < mTatums.size(); ++i)
{
ofSetColor(0, 255, 255, ((i + 1) % 2) * 20);
float pos = ofMap(StartTime(mTatums[i]), mZoomStart / sampleLength, mZoomEnd / sampleLength, 0, 1);
float dur = ofMap(mTatums[i].mDuration, 0, (mZoomEnd - mZoomStart) / sampleLength, 0, 1);
float end = pos + dur;
if ((pos >= 0 && pos <= 1) || (end >= 0 && end <= 1))
{
pos = ofClamp(pos, 0, 1);
end = ofClamp(end, 0, 1);
ofRect(mBufferW * pos, MEASURE_ZONE_HEIGHT, mBufferW * (end - pos), mBufferH - MEASURE_ZONE_HEIGHT - BEAT_ZONE_HEIGHT);
}
}
}
ofPopStyle();
ofPopMatrix();
mClipStartSlider->Draw();
mClipEndSlider->Draw();
mZoomStartSlider->Draw();
mZoomEndSlider->Draw();
mNumBarsSlider->Draw();
mOffsetSlider->Draw();
mWriteButton->Draw();
mDoubleLengthButton->Draw();
mHalveLengthButton->Draw();
if (mSample)
DrawTextNormal(ofToString(mSample->GetPlayPosition()), 335, 50);
}
ofPushMatrix();
ofPushStyle();
ofFill();
ofTranslate(mBufferX, mRemixBufferY);
int sourceSampleLength = 1;
if (mSample != nullptr)
sourceSampleLength = MAX(1, mSample->LengthInSamples());
ofPushMatrix();
int count = 0;
int i = 0;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter, ++i)
{
float dur = ofMap((*iter)->mDuration * sourceSampleLength, mRemixZoomStart, mRemixZoomEnd, 0, 1);
float width = MAX(0.0f, mBufferW * dur);
DrawAudioBuffer(width, mBufferH, mSample->Data(), StartTime(*(*iter)) * sourceSampleLength, (StartTime(*(*iter)) + (*iter)->mDuration) * sourceSampleLength, -1);
if ((*iter)->mType == kBlok_Bar)
{
ofSetColor(255, 0, (i % 2) * 255, 60);
ofRect(0, 0, width, MEASURE_ZONE_HEIGHT);
}
if ((*iter)->mType == kBlok_Beat)
{
ofSetColor(255, 255, (i % 2) * 255, 60);
ofRect(0, mBufferH - BEAT_ZONE_HEIGHT, width, BEAT_ZONE_HEIGHT);
}
if ((*iter)->mType == kBlok_Tatum)
{
ofSetColor(0, 255, 255, ((i + 1) % 2) * 20);
ofRect(0, MEASURE_ZONE_HEIGHT, width, mBufferH - MEASURE_ZONE_HEIGHT - BEAT_ZONE_HEIGHT);
}
//ofSetColor(255,0,((count/8)%2)*255,255);
//ofRect(0,mBufferH-30,width,30);
if ((*iter)->mType == kBlok_Bar)
count = (count / 8 + 1) * 8;
if ((*iter)->mType == kBlok_Beat)
count += 2;
if ((*iter)->mType == kBlok_Tatum)
count += 1;
ofTranslate(width, 0);
if (mHeldBlok && mLastRemovedRemixBlokIdx != -1 && mLastRemovedRemixBlokIdx - 1 == i)
{
ofPushStyle();
ofSetLineWidth(5);
ofSetColor(0, 255, 255, 200);
ofLine(0, 0, 0, mBufferH);
ofPopStyle();
}
}
ofPopMatrix();
if (mPlayRemix)
{
ofSetColor(0, 255, 0);
float pos = mBufferW * ofMap(mRemixPlayhead, mRemixZoomStart, mRemixZoomEnd, 0, 1);
ofLine(pos, 0, pos, mBufferH);
}
ofPopStyle();
ofPopMatrix();
if (mDrawSources)
{
ofPushStyle();
ofSetColor(255, 200, 0, 200);
float posRemix = 0;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter)
{
float dur = ofMap((*iter)->mDuration * sourceSampleLength, mRemixZoomStart, mRemixZoomEnd, 0, 1);
posRemix += dur / 2;
float posSrc = ofMap(StartTime(*(*iter)), mZoomStart / sourceSampleLength, mZoomEnd / sourceSampleLength, 0, 1);
float durSrc = ofMap((*iter)->mDuration, 0, (mZoomEnd - mZoomStart) / sourceSampleLength, 0, 1);
posSrc += durSrc / 2;
posSrc = ofClamp(posSrc, 0, 1);
ofLine(mBufferX + mBufferW * posRemix, mRemixBufferY, mBufferX + mBufferW * posSrc, mBufferY + mBufferH);
posRemix += dur / 2;
}
ofPopStyle();
}
if (mHeldBlok && mSample != nullptr)
{
ofPushMatrix();
ofTranslate(mMouseX - mGrabOffsetX, mMouseY - mGrabOffsetY);
int sampleLength = MAX(1, mSample->LengthInSamples());
float dur = ofMap(mHeldBlok->mDuration, 0, (mZoomEnd - mZoomStart) / sampleLength, 0, 1);
float width = mBufferW * dur;
DrawAudioBuffer(width, mBufferH, mSample->Data(), StartTime(*mHeldBlok) * sampleLength, (StartTime(*mHeldBlok) + mHeldBlok->mDuration) * sampleLength, -1);
ofPopMatrix();
if (mMouseY > mRemixBufferY && mMouseY < mRemixBufferY + mBufferH)
{
ofPushStyle();
ofSetColor(255, 255, 0);
int insertIndex;
float insertPos = GetInsertPosition(insertIndex);
ofLine(insertPos, mRemixBufferY, insertPos, mRemixBufferY + mBufferH);
ofPopStyle();
}
}
}
float BeatBloks::StartTime(const BeatBloks::Blok& blok)
{
float numSamples = mSample ? mSample->LengthInSamples() : 1;
return blok.mStartTime + mOffset / numSamples;
}
float BeatBloks::GetInsertPosition(int& insertIndex)
{
float insertPos = mBufferX;
int sourceSampleLength = mSample->LengthInSamples();
int i = 0;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter, ++i)
{
float dur = ofMap((*iter)->mDuration * sourceSampleLength, mRemixZoomStart, mRemixZoomEnd, 0, 1);
float width = MAX(0.0f, mBufferW * dur);
if (mMouseX < insertPos + width / 2)
{
insertIndex = i;
return insertPos;
}
insertPos += width;
}
insertIndex = -1;
return insertPos;
}
BeatBloks::Blok* BeatBloks::RemoveBlokAt(int x)
{
int sourceSampleLength = mSample->LengthInSamples();
float pos = mBufferX;
int i = 0;
for (auto iter = mRemixBloks.begin(); iter != mRemixBloks.end(); ++iter, ++i)
{
float dur = ofMap((*iter)->mDuration * sourceSampleLength, mRemixZoomStart, mRemixZoomEnd, 0, 1);
float width = MAX(0.0f, mBufferW * dur);
if (mMouseX < pos + width)
{
Blok* blok = (*iter);
mRemixBloks.erase(iter);
mLastRemovedRemixBlokIdx = i;
return blok;
}
pos += width;
}
return nullptr;
}
void BeatBloks::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mPlayCheckbox)
{
if (mSample)
mSample->Reset();
TheTransport->SetMeasureTime(0);
}
if (checkbox == mPlayRemixCheckbox)
{
mRemixPlayhead = 0;
}
}
void BeatBloks::GetModuleDimensions(float& width, float& height)
{
width = 910;
height = mRemixBufferY + mBufferH + 45;
}
void BeatBloks::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mClipStartSlider)
{
if (mSample && mClipStart > mSample->LengthInSamples())
mClipStart = mSample->LengthInSamples();
}
if (slider == mClipEndSlider)
{
if (mSample && mClipEnd > mSample->LengthInSamples())
mClipEnd = mSample->LengthInSamples();
}
if (slider == mZoomStartSlider)
{
if (mSample && mZoomStart > mSample->LengthInSamples())
mZoomStart = mSample->LengthInSamples();
UpdateZoomExtents();
}
if (slider == mZoomEndSlider)
{
if (mSample && mZoomEnd > mSample->LengthInSamples())
mZoomEnd = mSample->LengthInSamples();
UpdateZoomExtents();
}
if (slider == mRemixZoomStartSlider)
{
mRemixZoomStart = 0;
}
}
void BeatBloks::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void BeatBloks::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mSample)
{
mPlay = false;
if (pitch == 16)
{
mSample->Reset();
}
else if (pitch >= 0 && pitch < 16 && velocity > 0)
{
int slice = (pitch / 8) * 8 + 7 - (pitch % 8);
int barLength = (mClipEnd - mClipStart) / mNumBars;
int position = (barLength / 4) * slice + mClipStart;
mSample->Play(time, 1, position);
}
}
}
void BeatBloks::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void BeatBloks::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/BeatBloks.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 8,866 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// KeyboardDisplay.cpp
// Bespoke
//
// Created by Ryan Challinor on 5/12/16.
// Tweaked by ArkyonVeil on April/2024
//
#include "KeyboardDisplay.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "ModuleContainer.h"
#include "FileStream.h"
#include "QwertyToPitchMapping.h"
#include "ModularSynth.h"
namespace
{
const float kKeyboardYOffset = 0;
}
KeyboardDisplay::KeyboardDisplay()
{
for (int i = 0; i < 128; ++i)
{
mLastOnTime[i] = 0;
mLastOffTime[i] = 0;
}
}
void KeyboardDisplay::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void KeyboardDisplay::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
DrawKeyboard(0, kKeyboardYOffset, mWidth, mHeight - kKeyboardYOffset);
}
void KeyboardDisplay::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (pitch >= 0 && pitch < 128)
{
if (velocity > 0)
{
mLastOnTime[pitch] = time;
mLastOffTime[pitch] = 0;
}
else
{
mLastOffTime[pitch] = time;
}
}
}
void KeyboardDisplay::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (IsHoveringOverResizeHandle() || !IsEnabled())
return;
double time = NextBufferTime(false);
for (int pass = 0; pass < 2; ++pass)
{
for (int i = 0; i < NumKeys(); ++i)
{
bool isBlackKey;
if (GetKeyboardKeyRect(i + RootKey(), mWidth, mHeight - kKeyboardYOffset, isBlackKey).contains(x, y - kKeyboardYOffset))
{
if ((pass == 0 && isBlackKey) || (pass == 1 && !isBlackKey))
{
int pitch = i + RootKey();
float minVelocityY;
float maxVelocityY;
if (isBlackKey)
{
minVelocityY = 0;
maxVelocityY = (mHeight / 2) * .9f;
}
else
{
minVelocityY = mHeight / 2;
maxVelocityY = mHeight * .9f;
}
int noteVelocity = 127;
if (mGetVelocityFromClickHeight)
noteVelocity = (int)ofMap(y, minVelocityY, maxVelocityY, 20, 127, K(clamp));
if (mPlayingMousePitch == -1 || !mLatch)
{
PlayNote(time, pitch, noteVelocity);
mPlayingMousePitch = pitch;
}
else
{
bool newNote = (mPlayingMousePitch != pitch);
if (newNote)
PlayNote(time, pitch, noteVelocity);
PlayNote(time, mPlayingMousePitch, 0);
mPlayingMousePitch = newNote ? pitch : -1;
}
return;
}
}
}
}
}
void KeyboardDisplay::MouseReleased()
{
IDrawableModule::MouseReleased();
if (mPlayingMousePitch != -1 && !mLatch)
{
double time = NextBufferTime(false);
PlayNote(time, mPlayingMousePitch, 0);
mPlayingMousePitch = -1;
}
}
int KeyboardDisplay::RootKey() const
{
return TheScale->GetPitchesPerOctave() * mRootOctave;
}
int KeyboardDisplay::NumKeys() const
{
return TheScale->GetPitchesPerOctave() * mNumOctaves + 1;
}
void KeyboardDisplay::SetPitchColor(int pitch)
{
if (mShowScale)
{
if (TheScale->IsRoot(pitch))
ofSetColor(0, 200, 0);
else if (TheScale->IsInPentatonic(pitch))
ofSetColor(255, 128, 0);
else if (TheScale->IsInScale(pitch))
ofSetColor(180, 80, 0);
else
ofSetColor(50, 50, 50);
}
else
{
int enableOffset = 0;
if (!IsEnabled())
enableOffset = 80;
pitch %= 12;
ofColor color;
if (pitch == 0 || pitch == 2 || pitch == 4 || pitch == 5 || pitch == 7 || pitch == 9 || pitch == 11)
color.setHsb(240, 145, 200 - enableOffset);
else
color.setHsb(240, 145, 120 - enableOffset);
ofSetColor(color);
}
}
void KeyboardDisplay::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
RefreshOctaveCount();
}
void KeyboardDisplay::RefreshOctaveCount()
{
if (mForceNumOctaves == 0)
{
float ratio = mWidth / mHeight;
constexpr float baseRatioForOneElement = 250.0f / 180.0f;
int elements = static_cast<int>(ratio / baseRatioForOneElement);
elements = std::clamp(elements, 1, 10);
if (mRootOctave + elements > 9) //Ensure that we can't go into octaves where it begins to break...
mRootOctave = 10 - mNumOctaves;
mNumOctaves = elements;
}
else
{
mNumOctaves = mForceNumOctaves;
mRootOctave = 10 - mNumOctaves;
}
}
void KeyboardDisplay::DrawKeyboard(int x, int y, int w, int h)
{
ofPushStyle();
ofPushMatrix();
ofTranslate(x, y);
for (int pass = 0; pass < 2; ++pass)
{
for (int i = 0; i < NumKeys(); ++i)
{
bool isBlackKey;
ofRectangle key = GetKeyboardKeyRect(i + RootKey(), w, h, isBlackKey);
if ((pass == 0 && !isBlackKey) || (pass == 1 && isBlackKey))
{
SetPitchColor(i);
ofFill();
ofRect(key);
ofSetColor(0, 0, 0);
ofNoFill();
ofRect(key);
}
}
}
float keySpace = (float)w / ((float)NumKeys() - mNumOctaves * 5);
int oct = mRootOctave;
if (keySpace > 16 && h > 34 && !mHideLabels)
{
for (int i = 0; i < NumKeys(); i += 7)
{
ofSetColor(108, 37, 62, 255);
DrawTextNormal("C" + std::to_string(oct), keySpace * 0.5f - 6.5f + i * keySpace, h - 8, 12);
oct++;
}
}
ofPushStyle();
ofFill();
ofSetLineWidth(2);
for (int pitch = RootKey(); pitch < RootKey() + NumKeys(); ++pitch)
{
if (gTime >= mLastOnTime[pitch] && (gTime <= mLastOffTime[pitch] || mLastOffTime[pitch] < mLastOnTime[pitch]))
{
bool isBlackKey;
ofRectangle key = GetKeyboardKeyRect(pitch, w, h, isBlackKey);
key.height /= 3;
key.y += key.height * 2;
ofSetColor(255, 255, 255, ofLerp(255, 150, ofClamp((gTime - mLastOnTime[pitch]) / 150.0f, 0, 1)));
ofRect(key);
}
}
ofPopStyle();
ofPopMatrix();
ofPopStyle();
}
ofRectangle KeyboardDisplay::GetKeyboardKeyRect(int pitch, int w, int h, bool& isBlackKey) const
{
float extraKeyWidth = w / (mNumOctaves * 7 + 1);
float octaveWidth = (w - extraKeyWidth) / mNumOctaves;
pitch -= RootKey();
float offset = pitch / TheScale->GetPitchesPerOctave() * (octaveWidth);
pitch %= 12;
if ((pitch <= 4 && pitch % 2 == 0) || (pitch >= 5 && pitch % 2 == 1)) //white key
{
int whiteKey = (pitch + 1) / 2;
isBlackKey = false;
return ofRectangle(offset + whiteKey * octaveWidth / 7, 0, octaveWidth / 7, h);
}
else //black key
{
int blackKey = pitch / 2;
isBlackKey = true;
return ofRectangle(offset + blackKey * octaveWidth / 7 + octaveWidth / 16 + octaveWidth / 7 * .1f, 0, octaveWidth / 7 * .8f, h / 2);
}
}
bool KeyboardDisplay::ShouldConsumeKey(int key)
{
if (mEnabled && mAllowHoverTypingInput)
{
key = KeyToLower(key);
QwertyToPitchResponse res = QwertyToPitchMapping::GetPitchForComputerKey(key);
if (res.mOctaveShift != 0)
return true;
if (res.mPitch != -1)
return true;
}
return false;
}
void KeyboardDisplay::OnKeyPressed(int key, bool isRepeat)
{
if (mEnabled && !isRepeat && mAllowHoverTypingInput)
{
key = KeyToLower(key);
QwertyToPitchResponse res = QwertyToPitchMapping::GetPitchForComputerKey(key);
if (res.mOctaveShift != 0)
{
int newRootOctave = mRootOctave + res.mOctaveShift;
if (newRootOctave > 0 && newRootOctave + mNumOctaves <= 12)
mRootOctave = newRootOctave;
}
if (res.mPitch != -1)
{
int pitch = res.mPitch + mRootOctave * 12;
mKeyPressRegister[key] = pitch;
PlayNote(NextBufferTime(false), pitch, 127);
}
}
}
void KeyboardDisplay::KeyReleased(int key)
{
IDrawableModule::KeyReleased(key);
key = KeyToLower(key);
auto it = mKeyPressRegister.find(key);
if (it != mKeyPressRegister.end())
{
int pitch = it->second;
mKeyPressRegister.erase(key);
if (pitch != -1)
PlayNote(NextBufferTime(false), pitch, 0);
}
}
void KeyboardDisplay::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
if (!mEnabled)
{
mNoteOutput.Flush(NextBufferTime(false));
mKeyPressRegister.clear();
for (int i = 0; i < 128; ++i)
{
mLastOnTime[i] = 0;
mLastOffTime[i] = 0;
}
}
}
}
void KeyboardDisplay::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("force_num_octaves", moduleInfo, 0, 0, 10, K(isTextField));
mModuleSaveData.LoadBool("latch", moduleInfo, false);
mModuleSaveData.LoadBool("show_scale", moduleInfo, false);
mModuleSaveData.LoadBool("hide_labels", moduleInfo, false);
mModuleSaveData.LoadBool("get_velocity_from_click_height", moduleInfo, true);
mModuleSaveData.LoadBool("allow_hover_typing_input", moduleInfo, true);
SetUpFromSaveData();
}
void KeyboardDisplay::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mForceNumOctaves = mModuleSaveData.GetInt("force_num_octaves");
mLatch = mModuleSaveData.GetBool("latch");
mShowScale = mModuleSaveData.GetBool("show_scale");
mHideLabels = mModuleSaveData.GetBool("hide_labels");
mGetVelocityFromClickHeight = mModuleSaveData.GetBool("get_velocity_from_click_height");
mAllowHoverTypingInput = mModuleSaveData.GetBool("allow_hover_typing_input");
if (mForceNumOctaves)
RefreshOctaveCount();
}
void KeyboardDisplay::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mWidth;
out << mHeight;
out << mNumOctaves;
out << mRootOctave;
}
void KeyboardDisplay::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (!ModuleContainer::DoesModuleHaveMoreSaveData(in))
return; //this was saved before we added versioning, bail out
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
in >> mWidth;
in >> mHeight;
if (rev >= 2)
{
in >> mNumOctaves;
in >> mRootOctave;
}
}
``` | /content/code_sandbox/Source/KeyboardDisplay.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,140 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModulatorAddCentered.h
Created: 22 Nov 2017 9:50:16am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
class PatchCableSource;
class ModulatorAddCentered : public IDrawableModule, public IFloatSliderListener, public IModulator
{
public:
ModulatorAddCentered();
virtual ~ModulatorAddCentered();
static IDrawableModule* Create() { return new ModulatorAddCentered(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
bool CanAdjustRange() const override { return false; }
FloatSlider* GetTarget() { return GetSliderTarget(); }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 106;
h = 17 * 3 + 4;
}
float mValue1{ 0 };
float mValue2{ 0 };
float mValue2Range{ 1 };
FloatSlider* mValue1Slider{ nullptr };
FloatSlider* mValue2Slider{ nullptr };
FloatSlider* mValue2RangeSlider{ nullptr };
};
``` | /content/code_sandbox/Source/ModulatorAddCentered.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 559 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// WindowCloseListener.h
// Bespoke
//
// Created by Ryan Challinor on 10/17/21.
//
//
#pragma once
class WindowCloseListener
{
public:
virtual void OnWindowClosed() = 0;
};
``` | /content/code_sandbox/Source/WindowCloseListener.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 149 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// SingleOscillatorVoice.h
// modularSynth
//
// Created by Ryan Challinor on 12/4/13.
//
//
#pragma once
#include "OpenFrameworksPort.h"
#include "IMidiVoice.h"
#include "IVoiceParams.h"
#include "ADSR.h"
#include "EnvOscillator.h"
#include "LFO.h"
#include "BiquadFilter.h"
#define SINGLEOSCILLATOR_NO_CUTOFF 10000
class OscillatorVoiceParams : public IVoiceParams
{
public:
::ADSR mAdsr{ 10, 0, 1, 10 };
float mVol{ .25 };
float mPulseWidth{ .5 };
Oscillator::SyncMode mSyncMode{ Oscillator::SyncMode::None };
float mSyncFreq{ 200 };
float mSyncRatio{ 1 };
float mMult{ 1 };
OscillatorType mOscType{ OscillatorType::kOsc_Square };
float mDetune{ 0 };
float mShuffle{ 0 };
float mPhaseOffset{ 0 };
int mUnison{ 1 };
float mUnisonWidth{ 0 };
float mSoften{ 0 };
float mFilterCutoffMax{ SINGLEOSCILLATOR_NO_CUTOFF };
float mFilterCutoffMin{ 10 };
float mFilterQ{ float(sqrt(2) / 2) };
::ADSR mFilterAdsr{ 1, 0, 1, 1000 };
float mVelToVolume{ .5 };
float mVelToEnvelope{ 0 };
bool mLiteCPUMode{ false };
};
class SingleOscillatorVoice : public IMidiVoice
{
public:
SingleOscillatorVoice(IDrawableModule* owner = nullptr);
~SingleOscillatorVoice();
// IMidiVoice
void Start(double time, float amount) override;
void Stop(double time) override;
void ClearVoice() override;
bool Process(double time, ChannelBuffer* out, int oversampling) override;
void SetVoiceParams(IVoiceParams* params) override;
bool IsDone(double time) override;
static float GetADSRScale(float velocity, float velToEnvelope);
static const int kMaxUnison = 8;
private:
void DoParameterUpdate(int samplesIn,
float& pitch,
float& freq,
float& vol,
float& syncPhaseInc);
struct OscData
{
float mPhase{ 0 };
float mSyncPhase{ 0 };
Oscillator mOsc{ kOsc_Square };
float mDetuneFactor{ 0 };
float mCurrentPhaseInc{ 0 };
};
OscData mOscData[kMaxUnison];
::ADSR mAdsr;
OscillatorVoiceParams* mVoiceParams{ nullptr };
::ADSR mFilterAdsr;
BiquadFilter mFilterLeft;
BiquadFilter mFilterRight;
bool mUseFilter{ false };
IDrawableModule* mOwner;
};
``` | /content/code_sandbox/Source/SingleOscillatorVoice.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 766 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// OutputChannel.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/17/12.
//
//
#include "OutputChannel.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
OutputChannel::OutputChannel()
: IAudioProcessor(gBufferSize)
{
for (size_t i = 0; i < mLevelMeters.size(); ++i)
{
mLevelMeters[i].mPeakTrackerSlow.SetDecayTime(3);
mLevelMeters[i].mPeakTrackerSlow.SetLimit(1);
}
}
OutputChannel::~OutputChannel()
{
}
void OutputChannel::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mChannelSelector = new DropdownList(this, "ch", 3, 3, &mChannelSelectionIndex);
for (int i = 0; i < TheSynth->GetNumOutputChannels(); ++i)
mChannelSelector->AddLabel(ofToString(i + 1), i);
mStereoSelectionOffset = mChannelSelector->GetNumValues(); //after this, the stereo pairs
for (int i = 0; i < TheSynth->GetNumOutputChannels() - 1; ++i)
mChannelSelector->AddLabel(ofToString(i + 1) + "&" + ofToString(i + 2), mChannelSelector->GetNumValues());
mChannelSelector->DrawLabel(true);
mChannelSelector->SetWidth(43);
GetPatchCableSource()->SetEnabled(false);
}
void OutputChannel::Process(double time)
{
int numChannels = GetNumChannels();
SyncBuffers(numChannels);
int channelSelectionIndex = mChannelSelectionIndex;
if (numChannels == 1)
{
int channel = channelSelectionIndex;
auto getBufferGetChannel0 = GetBuffer()->GetChannel(0);
if (channel >= 0 && channel < TheSynth->GetNumOutputChannels())
{
if (mLimit > std::numeric_limits<float>::epsilon())
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel)[i] += std::clamp(getBufferGetChannel0[i], -mLimit, mLimit);
}
else
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel)[i] += getBufferGetChannel0[i];
}
}
GetVizBuffer()->WriteChunk(getBufferGetChannel0, gBufferSize, 0);
mLevelMeters[0].mPeakTracker.Process(TheSynth->GetOutputBuffer(channel), gBufferSize);
mLevelMeters[0].mPeakTrackerSlow.Process(TheSynth->GetOutputBuffer(channel), gBufferSize);
}
else //stereo
{
int channel1 = channelSelectionIndex - mStereoSelectionOffset;
if (channel1 >= 0 && channel1 < TheSynth->GetNumOutputChannels())
{
auto getBufferGetChannel0 = GetBuffer()->GetChannel(0);
if (mLimit > std::numeric_limits<float>::epsilon())
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel1)[i] += CLAMP(getBufferGetChannel0[i], -mLimit, mLimit);
}
else
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel1)[i] += getBufferGetChannel0[i];
}
GetVizBuffer()->WriteChunk(getBufferGetChannel0, gBufferSize, 0);
}
int channel2 = channel1 + 1;
int inputChannel2 = (GetBuffer()->NumActiveChannels() >= 2) ? 1 : 0;
if (channel2 >= 0 && channel2 < TheSynth->GetNumOutputChannels())
{
auto getBufferGetChannel2 = GetBuffer()->GetChannel(inputChannel2);
if (mLimit > std::numeric_limits<float>::epsilon())
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel2)[i] += CLAMP(getBufferGetChannel2[i], -mLimit, mLimit);
}
else
{
for (int i = 0; i < gBufferSize; ++i)
TheSynth->GetOutputBuffer(channel2)[i] += getBufferGetChannel2[i];
}
GetVizBuffer()->WriteChunk(getBufferGetChannel2, gBufferSize, 1);
}
mLevelMeters[0].mPeakTracker.Process(TheSynth->GetOutputBuffer(channel1), gBufferSize);
mLevelMeters[0].mPeakTrackerSlow.Process(TheSynth->GetOutputBuffer(channel1), gBufferSize);
mLevelMeters[1].mPeakTracker.Process(TheSynth->GetOutputBuffer(channel2), gBufferSize);
mLevelMeters[1].mPeakTrackerSlow.Process(TheSynth->GetOutputBuffer(channel2), gBufferSize);
}
GetBuffer()->Reset();
}
void OutputChannel::DrawModule()
{
mChannelSelector->Draw();
if (GetNumChannels() == 1)
mHeight = 30;
else
mHeight = 40;
for (int i = 0; i < GetNumChannels(); ++i)
{
const int kNumSegments = 20;
const int kPaddingOutside = 3;
const int kPaddingBetween = 1;
const int kBarHeight = 8;
const float kSegmentWidth = (mWidth - kPaddingOutside * 2) / kNumSegments;
for (int j = 0; j < kNumSegments; ++j)
{
ofPushStyle();
ofFill();
float level = mLevelMeters[i].mPeakTracker.GetPeak() / (mLimit > 0 ? mLimit : 1);
float slowLevel = mLevelMeters[i].mPeakTrackerSlow.GetPeak() / (mLimit > 0 ? mLimit : 1);
ofColor color(0, 255, 0);
if (j > kNumSegments - 3)
color.set(255, 0, 0);
else if (j > kNumSegments - 6)
color.set(255, 255, 0);
if (slowLevel > 0 && ofClamp(int(slowLevel * kNumSegments), 0, kNumSegments - 1) == j)
ofSetColor(color);
else if (level > 0 && level >= j / (float)kNumSegments)
ofSetColor(color * .9f);
else
ofSetColor(color * .5f);
ofRect(kPaddingOutside + kSegmentWidth * j, 20 + i * (kBarHeight + 2), kSegmentWidth - kPaddingBetween, kBarHeight, 0);
ofPopStyle();
}
if (mLevelMeters[i].mPeakTrackerSlow.GetLastHitLimitTime() > gTime - 1000)
{
ofPushStyle();
ofSetColor(ofColor::red);
DrawTextBold("clipped", kPaddingOutside + 10, 20 + i * (kBarHeight + 2) + 8, 10.0f);
ofPopStyle();
}
}
}
void OutputChannel::LoadLayout(const ofxJSONElement& moduleInfo)
{
if (!moduleInfo["channel"].isNull())
mModuleSaveData.LoadInt("channel", moduleInfo, 0, 0, TheSynth->GetNumOutputChannels() - 1);
mModuleSaveData.LoadEnum<int>("channels", moduleInfo, 0, mChannelSelector);
mModuleSaveData.LoadFloat("limit", moduleInfo, 1, 0, 1000, K(isTextField));
SetUpFromSaveData();
}
void OutputChannel::SetUpFromSaveData()
{
if (mModuleSaveData.HasProperty("channel")) //old version
mChannelSelectionIndex = mModuleSaveData.GetInt("channel") - 1;
else
mChannelSelectionIndex = mModuleSaveData.GetEnum<int>("channels");
mLimit = mModuleSaveData.GetFloat("limit");
for (size_t i = 0; i < mLevelMeters.size(); ++i)
mLevelMeters[i].mPeakTrackerSlow.SetLimit(mLimit);
}
``` | /content/code_sandbox/Source/OutputChannel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,944 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// FileStream.h
// Bespoke
//
// Created by Ryan Challinor on 4/26/15.
//
//
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include "juce_core/juce_core.h"
namespace juce
{
class InputStream;
class OutputStream;
}
class FileStreamOut
{
public:
explicit FileStreamOut(std::unique_ptr<juce::OutputStream> stream)
: mStream(std::move(stream))
{}
explicit FileStreamOut(const std::string& file);
explicit FileStreamOut(juce::MemoryBlock& block, bool appendToExistingBlockContent = true);
FileStreamOut(const char*) = delete; // Hint: UTF-8 encoded std::string required
~FileStreamOut();
FileStreamOut& operator<<(const int& var);
FileStreamOut& operator<<(const std::uint32_t& var);
FileStreamOut& operator<<(const bool& var);
FileStreamOut& operator<<(const float& var);
FileStreamOut& operator<<(const double& var);
FileStreamOut& operator<<(const std::string& var);
FileStreamOut& operator<<(const char& var);
void Write(const float* buffer, int size);
void WriteGeneric(const void* buffer, int size);
juce::int64 GetSize() const;
private:
std::unique_ptr<juce::OutputStream> mStream;
};
class FileStreamIn
{
public:
explicit FileStreamIn(std::unique_ptr<juce::InputStream> stream)
: mStream(std::move(stream))
{}
explicit FileStreamIn(const std::string& file);
explicit FileStreamIn(const juce::MemoryBlock& block);
FileStreamIn(const char*) = delete; // Hint: UTF-8 encoded std::string required
~FileStreamIn();
FileStreamIn& operator>>(int& var);
FileStreamIn& operator>>(std::uint32_t& var);
FileStreamIn& operator>>(bool& var);
FileStreamIn& operator>>(float& var);
FileStreamIn& operator>>(double& var);
FileStreamIn& operator>>(std::string& var);
FileStreamIn& operator>>(char& var);
void Read(float* buffer, int size);
void ReadGeneric(void* buffer, int size);
void Peek(void* buffer, int size);
int GetFilePosition() const;
bool OpenedOk() const;
bool Eof() const;
static bool s32BitMode;
static const int sMaxStringLength = 999999; //the primary thing that might hit this limit is the json layout file (one user has had a file that exceeded a length of 100000)
private:
std::unique_ptr<juce::InputStream> mStream;
};
``` | /content/code_sandbox/Source/FileStream.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 670 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// LooperRecorder.h
// modularSynth
//
// Created by Ryan Challinor on 12/9/12.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "RollingBuffer.h"
#include "RadioButton.h"
#include "ClickButton.h"
#include "Checkbox.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "Looper.h"
#include "Ramp.h"
#include "DropdownList.h"
#include "Push2Control.h"
class Stutter;
class PatchCableSource;
class LooperRecorder : public IAudioProcessor, public IDrawableModule, public IButtonListener, public IFloatSliderListener, public IRadioButtonListener, public IIntSliderListener, public IDropdownListener, public IPush2GridController
{
public:
LooperRecorder();
~LooperRecorder();
static IDrawableModule* Create() { return new LooperRecorder(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetNumBars(int numBars) { mNumBars = numBars; }
int GetNumBars() const { return mNumBars; }
void Commit(Looper* looper);
void RequestMerge(Looper* looper);
void RequestSwap(Looper* looper);
void RequestCopy(Looper* looper);
Looper* GetMergeSource() { return mMergeSource; }
Looper* GetSwapSource() { return mSwapSource; }
Looper* GetCopySource() { return mCopySource; }
int IncreaseCommitCount() { return ++mCommitCount; }
void RemoveLooper(Looper* looper);
void ResetSpeed();
RollingBuffer* GetRecordBuffer() { return &mRecordBuffer; }
Looper* GetNextCommitTarget() { return (mNextCommitTargetIndex < (int)mLoopers.size()) ? mLoopers[mNextCommitTargetIndex] : nullptr; }
void StartFreeRecord(double time);
void EndFreeRecord(double time);
void CancelFreeRecord();
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void Poll() override;
void PreRepatch(PatchCableSource* cableSource) override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IPush2GridController
bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override;
void UpdatePush2Leds(Push2Control* push2) override;
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
bool HasDebugDraw() const override { return true; }
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return mEnabled; }
private:
void SyncLoopLengths();
void UpdateSpeed();
float AdjustedRootForSpeed();
void SnapToClosestPitch();
void Resample(bool setKey);
void DrawCircleHash(ofVec2f center, float progress, float width, float innerRadius, float outerRadius);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
static constexpr int kMaxLoopers = 8;
float mWidth{ 235 };
float mHeight{ 126 };
RollingBuffer mRecordBuffer;
std::array<Looper*, kMaxLoopers> mLoopers{ nullptr };
int mNumLoopers{ 4 };
int mNumBars{ 1 };
DropdownList* mNumBarsSelector{ nullptr };
float mSpeed{ 1 };
float mBaseTempo{ 120 };
ClickButton* mResampleButton{ nullptr };
ClickButton* mResampAndSetButton{ nullptr };
Looper* mMergeSource{ nullptr };
Looper* mSwapSource{ nullptr };
Looper* mCopySource{ nullptr };
int mCommitCount{ 0 };
ClickButton* mDoubleTempoButton{ nullptr };
ClickButton* mHalfTempoButton{ nullptr };
ClickButton* mShiftMeasureButton{ nullptr };
ClickButton* mHalfShiftButton{ nullptr };
ClickButton* mClearOverdubButton{ nullptr };
Ramp mQuietInputRamp;
double mUnquietInputTime{ -1 };
ClickButton* mShiftDownbeatButton{ nullptr };
ClickButton* mOrigSpeedButton{ nullptr };
ClickButton* mSnapPitchButton{ nullptr };
float mCommitDelay{ 0 };
FloatSlider* mCommitDelaySlider{ nullptr };
ChannelBuffer mWriteBuffer;
Looper* mCommitToLooper{ nullptr };
std::array<PatchCableSource*, kMaxLoopers> mLooperPatchCables{ nullptr };
ClickButton* mCommit1BarButton{ nullptr };
ClickButton* mCommit2BarsButton{ nullptr };
ClickButton* mCommit4BarsButton{ nullptr };
ClickButton* mCommit8BarsButton{ nullptr };
IntSlider* mNextCommitTargetSlider{ nullptr };
int mNextCommitTargetIndex{ 0 };
Checkbox* mAutoAdvanceThroughLoopersCheckbox{ nullptr };
bool mAutoAdvanceThroughLoopers{ false };
bool mTemporarilySilenceAfterCommit{ false };
std::array<Checkbox*, kMaxLoopers> mWriteForLooperCheckbox{ nullptr };
std::array<bool, kMaxLoopers> mWriteForLooper{ false };
std::array<double, kMaxLoopers> mStartRecordMeasureTime{ 0 };
float mLatencyFixMs{ 0 };
FloatSlider* mLatencyFixMsSlider{ nullptr };
bool mFreeRecording{ false };
Checkbox* mFreeRecordingCheckbox{ nullptr };
double mStartFreeRecordTime{ 0 };
ClickButton* mCancelFreeRecordButton{ nullptr };
enum RecorderMode
{
kRecorderMode_Record,
kRecorderMode_Overdub,
kRecorderMode_Loop
};
RecorderMode mRecorderMode{ RecorderMode::kRecorderMode_Record };
DropdownList* mModeSelector{ nullptr };
};
``` | /content/code_sandbox/Source/LooperRecorder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,607 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteRatchet.cpp
Created: 2 Aug 2021 10:32:23pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteRatchet.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
NoteRatchet::NoteRatchet()
{
}
void NoteRatchet::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
DROPDOWN(mRatchetDurationSelector, "duration", (int*)&mRatchetDuration, 50);
DROPDOWN(mRatchetSubdivisionSelector, "subdivision", (int*)&mRatchetSubdivision, 50);
CHECKBOX(mSkipFirstCheckbox, "skip first", &mSkipFirst);
ENDUIBLOCK(mWidth, mHeight);
mRatchetDurationSelector->AddLabel("1n", kInterval_1n);
mRatchetDurationSelector->AddLabel("2n", kInterval_2n);
mRatchetDurationSelector->AddLabel("4n", kInterval_4n);
mRatchetDurationSelector->AddLabel("4nt", kInterval_4nt);
mRatchetDurationSelector->AddLabel("8n", kInterval_8n);
mRatchetDurationSelector->AddLabel("8nt", kInterval_8nt);
mRatchetDurationSelector->AddLabel("16n", kInterval_16n);
mRatchetDurationSelector->AddLabel("16nt", kInterval_16nt);
mRatchetDurationSelector->AddLabel("32n", kInterval_32n);
mRatchetDurationSelector->AddLabel("32nt", kInterval_32nt);
mRatchetDurationSelector->AddLabel("64n", kInterval_64n);
mRatchetSubdivisionSelector->AddLabel("1n", kInterval_1n);
mRatchetSubdivisionSelector->AddLabel("2n", kInterval_2n);
mRatchetSubdivisionSelector->AddLabel("4n", kInterval_4n);
mRatchetSubdivisionSelector->AddLabel("4nt", kInterval_4nt);
mRatchetSubdivisionSelector->AddLabel("8n", kInterval_8n);
mRatchetSubdivisionSelector->AddLabel("8nt", kInterval_8nt);
mRatchetSubdivisionSelector->AddLabel("16n", kInterval_16n);
mRatchetSubdivisionSelector->AddLabel("16nt", kInterval_16nt);
mRatchetSubdivisionSelector->AddLabel("32n", kInterval_32n);
mRatchetSubdivisionSelector->AddLabel("32nt", kInterval_32nt);
mRatchetSubdivisionSelector->AddLabel("64n", kInterval_64n);
mRatchetDurationSelector->DrawLabel(true);
mRatchetSubdivisionSelector->DrawLabel(true);
mWidth = mRatchetSubdivisionSelector->GetRect().width + 6;
}
void NoteRatchet::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mRatchetDurationSelector->Draw();
mRatchetSubdivisionSelector->Draw();
mSkipFirstCheckbox->Draw();
}
void NoteRatchet::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void NoteRatchet::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (velocity > 0)
{
double subdivisionMs = TheTransport->GetDuration(mRatchetSubdivision);
int repetitions = TheTransport->CountInStandardMeasure(mRatchetSubdivision) / TheTransport->CountInStandardMeasure(mRatchetDuration);
int startIndex = 0;
if (mSkipFirst)
startIndex = 1;
for (int i = startIndex; i < repetitions; ++i)
{
PlayNoteOutput(time + subdivisionMs * i, pitch, velocity, voiceIdx, modulation);
PlayNoteOutput(time + subdivisionMs * (i + 1), pitch, 0, voiceIdx, modulation);
}
}
}
void NoteRatchet::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void NoteRatchet::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteRatchet::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteRatchet.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,105 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// IDrivableSequencer.h
// modularSynth
//
// Created by Ryan Challinor 10/30/21
//
//
#pragma once
class IDrivableSequencer
{
public:
virtual bool HasExternalPulseSource() const = 0;
virtual void ResetExternalPulseSource() = 0;
};
``` | /content/code_sandbox/Source/IDrivableSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 171 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// MidiClockOut.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/1/22.
//
//
#include "MidiClockOut.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
MidiClockOut::MidiClockOut()
{
}
MidiClockOut::~MidiClockOut()
{
TheTransport->RemoveAudioPoller(this);
}
void MidiClockOut::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
DROPDOWN(mDeviceList, "device", &mDeviceIndex, 120);
BUTTON(mStartButton, "send start");
DROPDOWN(mMultiplierSelector, "multiplier", ((int*)&mMultiplier), 70);
ENDUIBLOCK(mWidth, mHeight);
mMultiplierSelector->AddLabel("quarter", (int)ClockMultiplier::Quarter);
mMultiplierSelector->AddLabel("half", (int)ClockMultiplier::Half);
mMultiplierSelector->AddLabel("one", (int)ClockMultiplier::One);
mMultiplierSelector->AddLabel("two", (int)ClockMultiplier::Two);
mMultiplierSelector->AddLabel("four", (int)ClockMultiplier::Four);
}
void MidiClockOut::Init()
{
IDrawableModule::Init();
InitDevice();
TheTransport->AddAudioPoller(this);
}
void MidiClockOut::InitDevice()
{
BuildDeviceList();
const std::vector<std::string>& devices = mDevice.GetPortList(false);
for (int i = 0; i < devices.size(); ++i)
{
if (strcmp(devices[i].c_str(), mDevice.Name()) == 0)
mDeviceIndex = i;
}
}
void MidiClockOut::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mDeviceList->Draw();
mStartButton->Draw();
mMultiplierSelector->Draw();
}
void MidiClockOut::BuildDeviceList()
{
mDeviceList->Clear();
const std::vector<std::string>& devices = mDevice.GetPortList(false);
for (int i = 0; i < devices.size(); ++i)
mDeviceList->AddLabel(devices[i].c_str(), i);
}
void MidiClockOut::OnTransportAdvanced(float amount)
{
if (mEnabled)
{
int pulsesPerBeat = 24;
switch (mMultiplier)
{
case ClockMultiplier::Quarter: pulsesPerBeat /= 4; break;
case ClockMultiplier::Half: pulsesPerBeat /= 2; break;
case ClockMultiplier::One: break;
case ClockMultiplier::Two: pulsesPerBeat *= 2; break;
case ClockMultiplier::Four: pulsesPerBeat *= 4; break;
}
int pulsesPerMeasure = TheTransport->GetTimeSigTop() * pulsesPerBeat;
double oldPulse = TheTransport->GetMeasureTime(gTime) * pulsesPerMeasure;
double newPulse = TheTransport->GetMeasureTime(NextBufferTime(false)) * pulsesPerMeasure;
int pulses = int(floor(newPulse) - floor(oldPulse));
double distToFirstPulse = 1 - fmod(oldPulse, 1);
double pulseMs = TheTransport->GetDuration(kInterval_4n) / pulsesPerBeat;
for (int i = 0; i < pulses; ++i)
{
if (mClockStartQueued && (int(oldPulse) + i) % pulsesPerMeasure == 0)
{
mDevice.SendMessage(gTime + (distToFirstPulse + i) * pulseMs, juce::MidiMessage::midiStart());
mClockStartQueued = false;
}
else
{
mDevice.SendMessage(gTime + (distToFirstPulse + i) * pulseMs, juce::MidiMessage::midiClock());
}
}
}
}
void MidiClockOut::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mDeviceList)
{
mDevice.ConnectOutput(mDeviceIndex);
}
}
void MidiClockOut::ButtonClicked(ClickButton* button, double time)
{
if (button == mStartButton)
mClockStartQueued = true;
}
void MidiClockOut::DropdownClicked(DropdownList* list)
{
BuildDeviceList();
}
void MidiClockOut::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void MidiClockOut::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/MidiClockOut.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,088 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Canvas.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/29/14.
//
//
#include "Canvas.h"
#include "CanvasControls.h"
#include "CanvasElement.h"
#include "FileStream.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "Snapshots.h"
Canvas::Canvas(IDrawableModule* parent, int x, int y, int w, int h, float length, int rows, int cols, CreateCanvasElementFn elementCreator)
: mWidth(w)
, mHeight(h)
, mLength(length)
, mNumRows(rows)
, mNumCols(cols)
, mViewEnd(length)
, mLoopEnd(length)
, mElementCreator(elementCreator)
, mNumVisibleRows(rows)
{
SetName("canvas");
SetPosition(x, y);
SetParent(parent);
for (size_t i = 0; i < mRowColors.size(); ++i)
mRowColors[i] = ofColor(200, 200, 200, 70);
}
Canvas::~Canvas()
{
for (int i = 0; i < mElements.size(); ++i)
delete mElements[i];
}
void Canvas::Render()
{
ofPushMatrix();
ofTranslate(mX, mY);
ofPushStyle();
ofSetLineWidth(.5f);
float w, h;
GetDimensions(w, h);
ofNoFill();
ofRect(0, 0, mWidth, mHeight, 0);
ofRect(0, 0, GetWidth(), GetHeight(), 0);
ofPushStyle();
ofFill();
const float rowHeight = GetHeight() / GetNumVisibleRows();
for (int i = 0; i < GetNumVisibleRows(); ++i)
{
int row = mRowOffset + i;
if (row >= 0 && row < mRowColors.size())
ofSetColorGradient(mRowColors[row], ofColor::lerp(mRowColors[row], ofColor::clear, .1f), ofVec2f(0, i * rowHeight + rowHeight * 0.0f), ofVec2f(0, i * rowHeight + rowHeight));
ofRect(0, i * rowHeight, GetWidth(), rowHeight, 0);
}
ofPopStyle();
for (int i = 0; i < GetNumCols(); ++i)
{
float pos = ofMap(float(i) / GetNumCols(), mViewStart / mLength, mViewEnd / mLength, 0, 1) * GetWidth();
if (pos >= 0 && pos < GetWidth())
{
ofPushStyle();
if (mMajorColumnInterval != -1 && i % mMajorColumnInterval == 0)
ofSetColor(255, 255, 255);
ofLine(pos, 0, pos, GetHeight());
ofPopStyle();
}
}
for (int i = 0; i < mElements.size(); ++i)
{
//ofMap(GetStart() + offset,mCanvas->mStart/mCanvas->GetLength(),mCanvas->mEnd/mCanvas->GetLength(),0,1,clamp)
bool visibleOnCanvas = mElements[i]->mRow >= mRowOffset && mElements[i]->mRow < mRowOffset + GetNumVisibleRows() &&
mElements[i]->GetStart() <= mViewEnd / GetLength() && mElements[i]->GetEnd() >= mViewStart / GetLength();
if (visibleOnCanvas)
{
ofVec2f offset(0, 0);
if (mClick && mClickedElement != nullptr && mElements[i]->GetHighlighted() && mDragEnd == kHighlightEnd_None)
offset = (ofVec2f(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()) - mClickedElementStartMousePos) / gDrawScale;
mElements[i]->Draw(offset);
}
if (!visibleOnCanvas)
mElements[i]->DrawOffscreen();
}
if (mDragSelecting)
{
ofPushStyle();
ofSetColor(255, 255, 255);
ofRect(mDragSelectRect);
ofPopStyle();
}
float pos = ofMap(mCursorPos, mViewStart / mLength, mViewEnd / mLength, 0, 1) * GetWidth();
if (pos >= 0 && pos < GetWidth())
{
ofPushStyle();
ofSetColor(0, 255, 0);
ofLine(pos, 0, pos, GetHeight());
ofPopStyle();
}
ofPopStyle();
ofPopMatrix();
}
void Canvas::AddElement(CanvasElement* element)
{
mElements.push_back(element);
}
void Canvas::RemoveElement(CanvasElement* element)
{
if (mListener)
mListener->ElementRemoved(element);
RemoveFromVector(element, mElements, !K(fail));
//delete element; TODO(Ryan) figure out how to delete without messing up stuff accessing data from other thread
}
void Canvas::SelectElement(CanvasElement* element)
{
bool commandHeld = GetKeyModifiers() & kModifier_Command;
if (!commandHeld)
{
mClickedElement = element;
if (mControls)
mControls->SetElement(element);
if (element && element->GetHighlighted())
return;
}
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i] == element)
{
if (commandHeld)
mElements[i]->SetHighlight(!mElements[i]->GetHighlighted());
else
mElements[i]->SetHighlight(true);
}
else
{
if (!commandHeld)
mElements[i]->SetHighlight(false);
}
}
}
void Canvas::SelectElements(std::vector<CanvasElement*> elements)
{
bool commandHeld = GetKeyModifiers() & kModifier_Command;
if (mControls)
mControls->SetElement(elements.empty() ? nullptr : elements[0]);
for (int i = 0; i < mElements.size(); ++i)
{
if (VectorContains(mElements[i], elements))
{
if (commandHeld)
mElements[i]->SetHighlight(!mElements[i]->GetHighlighted());
else
mElements[i]->SetHighlight(true);
}
else
{
if (!commandHeld)
mElements[i]->SetHighlight(false);
}
}
}
ofVec2f Canvas::RescaleForZoom(float x, float y) const
{
return ofVec2f(ofMap(x / mWidth, 0, 1, mViewStart, mViewEnd) * mWidth, y);
}
bool Canvas::IsOnElement(CanvasElement* element, float x, float y) const
{
return element->GetRect(true, false).contains(x, y) || (mWrap && element->GetRect(true, true).contains(x, y));
}
bool Canvas::IsRowVisible(int row) const
{
return row >= mRowOffset && row < mRowOffset + GetNumVisibleRows();
}
void Canvas::OnClicked(float x, float y, bool right)
{
mClick = true;
mHasDuplicatedThisDrag = false;
if (mHighlightEnd != kHighlightEnd_None)
{
mDragEnd = mHighlightEnd;
mClickedElement = mHighlightEndElement;
}
else
{
bool clickedElement = false;
for (int i = (int)mElements.size() - 1; i >= 0; --i)
{
if (IsOnElement(mElements[i], x, y))
{
SelectElement(mElements[i]);
clickedElement = true;
if (mClickedElement)
mClickedElementStartMousePos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY());
break;
}
}
if (clickedElement == false)
{
SelectElement(nullptr);
if (GetKeyModifiers() & kModifier_Shift)
{
CanvasCoord coord = GetCoordAt(x, y);
CanvasElement* element = CreateElement(coord.col, coord.row);
AddElement(element);
SelectElement(element);
mHasDuplicatedThisDrag = true; //to prevent a duplicate from being made
mClickedElementStartMousePos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY());
}
else if (GetKeyModifiers() & kModifier_Alt)
{
mDragCanvasMoving = true;
mDragCanvasStartMousePos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY());
mDragCanvasStartCanvasPos.set(mViewStart, mRowOffset);
}
else if (GetKeyModifiers() & kModifier_Command)
{
mDragCanvasZooming = true;
mDragCanvasStartMousePos.set(x, y);
mDragCanvasStartCanvasPos.set(ofMap(x, 0, mWidth, mViewStart, mViewEnd), ofMap(y, 0, mHeight, mRowOffset, mRowOffset + mNumVisibleRows));
mDragZoomStartDimensions.set(mViewEnd - mViewStart, mNumVisibleRows);
}
else
{
mDragSelecting = true;
mDragSelectRect.set(x, y, 1, 1);
}
}
}
if (mListener)
mListener->CanvasUpdated(this);
}
float Canvas::QuantizeToGrid(float input) const
{
float col = int(input * GetNumCols() + .5f);
return col / GetNumCols();
}
bool Canvas::CanBeTargetedBy(PatchCableSource* source) const
{
return source->GetConnectionType() == kConnectionType_UIControl && dynamic_cast<Snapshots*>(source->GetOwner()) != nullptr;
}
bool Canvas::MouseMoved(float x, float y)
{
CheckHover(x, y);
bool quantize = GetKeyModifiers() & kModifier_Command;
if (mDragEnd != kHighlightEnd_None)
{
ofVec2f scaled = RescaleForZoom(x, y);
if (mDragEnd == kHighlightEnd_Start)
{
float oldStart = mClickedElement->GetStart();
float newStart = scaled.x / GetWidth() / mLength;
float startDelta = newStart - oldStart;
for (auto* element : mElements)
{
if (element->GetHighlighted())
{
float start = element->GetStart() + startDelta;
if (quantize)
start = QuantizeToGrid(start);
element->SetStart(start, false);
}
}
}
if (mDragEnd == kHighlightEnd_End)
{
float oldEnd = mClickedElement->GetEnd();
float newEnd = scaled.x / GetWidth() / mLength;
float endDelta = newEnd - oldEnd;
for (auto* element : mElements)
{
if (element->GetHighlighted())
{
float end = element->GetEnd() + endDelta;
if (quantize)
end = QuantizeToGrid(end);
element->SetEnd(end);
}
}
}
return true;
}
if (x >= 0 && x < mWidth && y >= 0 && y < mHeight)
{
if (mClick)
{
if (mClickedElement != nullptr)
{
ofVec2f dragOffset = (ofVec2f(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()) - mClickedElementStartMousePos) / gDrawScale;
if (GetKeyModifiers() & kModifier_Shift && !mHasDuplicatedThisDrag && dragOffset.distanceSquared() > 9)
{
mHasDuplicatedThisDrag = true;
std::vector<CanvasElement*> newElements;
for (auto element : mElements)
{
if (element->GetHighlighted())
newElements.push_back(element->CreateDuplicate());
}
for (auto newElement : newElements)
mElements.push_back(newElement);
}
}
}
mHighlightEnd = kHighlightEnd_None;
mHighlightEndElement = nullptr;
for (auto* element : mElements)
{
if (element->GetHighlighted())
{
ofRectangle rect = element->GetRect(!K(clamp), !K(wrapped));
float startX = rect.x;
if (element->GetEnd() > 1 && mWrap)
rect = element->GetRect(!K(clamp), K(wrapped));
float endX = rect.x + rect.width;
if (y >= rect.y && y < rect.y + rect.height)
{
if (fabsf(startX - x) < 3 / gDrawScale && element->IsResizable())
{
mHighlightEnd = kHighlightEnd_Start;
mHighlightEndElement = element;
}
if (fabsf(endX - x) < 3 / gDrawScale && element->IsResizable())
{
mHighlightEnd = kHighlightEnd_End;
mHighlightEndElement = element;
}
}
}
}
}
else
{
}
if (mDragSelecting)
{
mDragSelectRect.width = x - mDragSelectRect.x;
mDragSelectRect.height = y - mDragSelectRect.y;
}
if (mDragCanvasMoving && (GetKeyModifiers() & kModifier_Alt))
{
ofVec2f mousePos(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY());
ofVec2f delta = (mousePos - mDragCanvasStartMousePos) / gDrawScale;
float viewLength = mViewEnd - mViewStart;
float moveX = -delta.x / mWidth * viewLength;
mViewStart = ofClamp(mDragCanvasStartCanvasPos.x + moveX, 0, mLength - viewLength);
mViewEnd = mViewStart + viewLength;
float moveY = -delta.y / mHeight * GetNumVisibleRows();
mRowOffset = ofClamp(int(mDragCanvasStartCanvasPos.y + moveY + .5f), 0, GetNumRows() - GetNumVisibleRows());
}
else
{
mDragCanvasMoving = false;
}
if (mDragCanvasZooming && (GetKeyModifiers() & kModifier_Command))
{
ofVec2f mousePos(x, y);
ofVec2f delta = (mousePos - mDragCanvasStartMousePos) / gDrawScale;
{
float originalViewLength = mDragZoomStartDimensions.x;
float originalViewCenterX = mDragCanvasStartCanvasPos.x;
float newViewLength = MAX((1 - delta.x / mWidth) * originalViewLength, .01f);
mViewStart = ofClamp(originalViewCenterX - newViewLength * (mDragCanvasStartMousePos.x / mWidth), 0, mLength);
mViewEnd = ofClamp(originalViewCenterX + newViewLength * (1 - mDragCanvasStartMousePos.x / mWidth), 0, mLength);
}
{
float originalViewHeight = mDragZoomStartDimensions.y;
float originalViewCenterY = mDragCanvasStartCanvasPos.y;
float newViewHeight = MAX((1 + delta.y / mHeight) * originalViewHeight, .01f);
mRowOffset = int(ofClamp(originalViewCenterY - newViewHeight * (mDragCanvasStartMousePos.y / mHeight), 0, mNumRows - 1) + .5f);
mNumVisibleRows = int(ofClamp(originalViewCenterY + newViewHeight * (1 - mDragCanvasStartMousePos.y / mHeight), mRowOffset + 1, mNumRows) + .5f) - mRowOffset;
}
}
else
{
mDragCanvasZooming = false;
}
return false;
}
void Canvas::MouseReleased()
{
if (mClick && mClickedElement != nullptr && mDragEnd == kHighlightEnd_None)
{
for (auto* element : mElements)
{
if (element->GetHighlighted())
element->MoveElementByDrag((ofVec2f(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()) - mClickedElementStartMousePos) / gDrawScale);
}
if (mListener)
mListener->CanvasUpdated(this);
}
mClick = false;
mClickedElement = nullptr;
mDragEnd = kHighlightEnd_None;
if (mDragSelecting)
{
std::vector<CanvasElement*> selectedElements;
for (int i = (int)mElements.size() - 1; i >= 0; --i)
{
if (mElements[i]->GetRect(true, false).intersects(mDragSelectRect) ||
(mWrap && mElements[i]->GetRect(true, true).intersects(mDragSelectRect)))
{
selectedElements.push_back(mElements[i]);
}
}
SelectElements(selectedElements);
mDragSelecting = false;
}
mDragCanvasMoving = false;
mDragCanvasZooming = false;
}
bool Canvas::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
if (GetKeyModifiers() & kModifier_Alt)
{
scrollX = scrollY;
scrollY = 0;
}
if (GetKeyModifiers() & kModifier_Shift)
{
float canvasX, canvasY;
GetPosition(canvasX, canvasY, false);
ofVec2f canvasPos = ofVec2f(ofMap(x, canvasX, canvasX + GetWidth(), 0, 1),
ofMap(y, canvasY, canvasY + GetHeight(), 0, 1));
if (IsInUnitBox(canvasPos))
{
float zoomCenter = ofLerp(mViewStart, mViewEnd, canvasPos.x);
float distFromStart = zoomCenter - mViewStart;
float distFromEnd = zoomCenter - mViewEnd;
distFromStart *= 1 - scrollY / 50;
distFromEnd *= 1 - scrollY / 50;
mViewStart = ofClamp(zoomCenter - distFromStart, 0, mLength);
mViewEnd = ofClamp(zoomCenter - distFromEnd, 0, mLength);
//ofLog() << mStart << " " << mEnd;
return true;
}
}
else
{
if (x >= GetPosition(false).x && y >= GetPosition(false).y &&
x < GetPosition(false).x + GetWidth() && y < GetPosition(false).y + GetHeight())
{
mScrollVerticalPartial -= scrollY;
int scrollWhole = int(mScrollVerticalPartial);
mScrollVerticalPartial -= scrollWhole;
SetRowOffset(GetRowOffset() + scrollWhole);
}
float slideX = (mViewEnd - mViewStart) * -scrollX / 50;
if (slideX > 0)
slideX = MIN(slideX, mLength - mViewEnd);
if (slideX < 0)
slideX = MAX(slideX, -mViewStart);
mViewStart += slideX;
mViewEnd += slideX;
return true;
}
return false;
}
void Canvas::KeyPressed(int key, bool isRepeat)
{
if (TheSynth->GetLastClickedModule() == GetParent() && gHoveredUIControl == this)
{
if (key == juce::KeyPress::backspaceKey || key == juce::KeyPress::deleteKey)
{
if (mControls)
mControls->SetElement(nullptr);
std::vector<CanvasElement*> toRemove;
for (auto element : mElements)
{
if (element->GetHighlighted())
toRemove.push_back(element);
}
for (auto element : toRemove)
{
RemoveElement(element);
}
}
if (key == 'a' && GetKeyModifiers() & kModifier_Command)
{
for (auto* element : mElements)
element->SetHighlight(true);
}
if (key == OF_KEY_LEFT || key == OF_KEY_RIGHT)
{
int direction = (key == OF_KEY_LEFT) ? -1 : 1;
for (auto* element : mElements)
{
if (element->GetHighlighted())
element->mCol += direction;
}
}
if (key == OF_KEY_UP || key == OF_KEY_DOWN)
{
int direction = (key == OF_KEY_UP) ? -1 : 1;
if (GetKeyModifiers() == kModifier_Shift)
direction *= 12; //octave
for (auto* element : mElements)
{
if (element->GetHighlighted())
element->mRow += direction;
}
}
}
}
void Canvas::RescaleNumCols(int cols)
{
float ratio = (float)cols / mNumCols;
for (auto* element : mElements)
{
element->SetStart(element->GetStart() * ratio, true);
element->mLength *= ratio;
}
mNumCols = cols;
}
void Canvas::SetRowColor(int row, ofColor color)
{
if (row >= 0 && row <= mRowColors.size())
mRowColors[row] = color;
}
juce::MouseCursor Canvas::GetMouseCursorType()
{
using juce::MouseCursor;
if (GetKeyModifiers() & kModifier_Shift)
return MouseCursor::CopyingCursor;
if (GetKeyModifiers() & kModifier_Alt)
return MouseCursor::DraggingHandCursor;
if (GetKeyModifiers() & kModifier_Command)
return MouseCursor::IBeamCursor;
if (mHighlightEnd == kHighlightEnd_Start)
return MouseCursor::RightEdgeResizeCursor;
if (mHighlightEnd == kHighlightEnd_End)
return MouseCursor::LeftEdgeResizeCursor;
return MouseCursor::NormalCursor;
}
CanvasElement* Canvas::GetElementAt(float pos, int row)
{
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i]->mRow == row && pos >= mElements[i]->GetStart() && pos < mElements[i]->GetEnd())
return mElements[i];
else if (mWrap && pos >= mElements[i]->GetStart() - mLength && pos < mElements[i]->GetEnd() - mLength)
return mElements[i];
}
return nullptr;
}
void Canvas::FillElementsAt(float pos, std::vector<CanvasElement*>& elementsAt) const
{
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i]->mRow == -1 || mElements[i]->mCol == -1 || mElements[i]->mRow >= elementsAt.size())
continue;
bool on = false;
if (pos >= mElements[i]->GetStart() && pos < mElements[i]->GetEnd())
on = true;
if (mWrap && pos >= mElements[i]->GetStart() - mLength && pos < mElements[i]->GetEnd() - mLength)
on = true;
if (on)
elementsAt[mElements[i]->mRow] = mElements[i];
}
}
void Canvas::EraseElementsAt(float pos)
{
std::vector<CanvasElement*> toErase;
for (int i = 0; i < mElements.size(); ++i)
{
if (mElements[i]->mRow == -1 || mElements[i]->mCol == -1)
continue;
bool on = false;
if (pos >= mElements[i]->GetStart() && pos < mElements[i]->GetEnd())
on = true;
if (mWrap && pos >= mElements[i]->GetStart() - mLength && pos < mElements[i]->GetEnd() - mLength)
on = true;
if (on)
toErase.push_back(mElements[i]);
}
for (auto* elem : toErase)
RemoveElement(elem);
}
CanvasCoord Canvas::GetCoordAt(int x, int y)
{
if (x >= 0 && x < GetWidth() && y >= 0 && y < GetHeight())
{
int col = int(ofMap(x / mWidth, 0, mLength, mViewStart, mViewEnd) * mNumCols);
int row = (y / GetHeight()) * GetNumVisibleRows() + mRowOffset;
return CanvasCoord(col, row);
}
return CanvasCoord(-1, -1);
}
void Canvas::Clear()
{
mElements.clear();
}
namespace
{
const int kSaveStateRev = 3;
}
void Canvas::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
out << mNumCols;
out << mNumRows;
out << mNumVisibleRows;
out << mRowOffset;
out << mLoopStart;
out << mLoopEnd;
out << (int)mElements.size();
for (int i = 0; i < mElements.size(); ++i)
{
out << mElements[i]->mCol;
out << mElements[i]->mRow;
mElements[i]->SaveState(out);
}
}
void Canvas::LoadState(FileStreamIn& in, bool shouldSetValue)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
in >> mNumCols;
in >> mNumRows;
in >> mNumVisibleRows;
in >> mRowOffset;
if (rev >= 3)
{
in >> mLoopStart;
in >> mLoopEnd;
}
mElements.clear();
int size;
in >> size;
for (int i = 0; i < size; ++i)
{
int col = 0, row = 0;
if (rev >= 2)
{
in >> col;
in >> row;
}
CanvasElement* element = mElementCreator(this, col, row);
element->LoadState(in);
mElements.push_back(element);
}
}
``` | /content/code_sandbox/Source/Canvas.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,804 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Splitter.cpp
Created: 10 Oct 2017 9:50:02pm
Author: Ryan Challinor
==============================================================================
*/
#include "Splitter.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "PatchCableSource.h"
Splitter::Splitter()
: IAudioProcessor(gBufferSize)
, mVizBuffer2(VIZ_BUFFER_SECONDS * gSampleRate)
{
}
void Splitter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float w, h;
GetDimensions(w, h);
GetPatchCableSource()->SetManualPosition(w / 2 - 15, h + 3);
GetPatchCableSource()->SetManualSide(PatchCableSource::Side::kBottom);
mPatchCableSource2 = new PatchCableSource(this, kConnectionType_Audio);
mPatchCableSource2->SetManualPosition(w / 2 + 15, h + 3);
mPatchCableSource2->SetOverrideVizBuffer(&mVizBuffer2);
mPatchCableSource2->SetManualSide(PatchCableSource::Side::kBottom);
AddPatchCableSource(mPatchCableSource2);
}
Splitter::~Splitter()
{
}
void Splitter::Process(double time)
{
PROFILER(Splitter);
IAudioReceiver* target0 = GetTarget(0);
if (target0)
{
ChannelBuffer* out = target0->GetBuffer();
Add(out->GetChannel(0), GetBuffer()->GetChannel(0), GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), GetBuffer()->BufferSize(), 0);
}
int secondChannel = 1;
if (GetBuffer()->NumActiveChannels() == 1)
secondChannel = 0;
IAudioReceiver* target1 = GetTarget(1);
if (target1)
{
ChannelBuffer* out2 = target1->GetBuffer();
Add(out2->GetChannel(0), GetBuffer()->GetChannel(secondChannel), GetBuffer()->BufferSize());
mVizBuffer2.WriteChunk(GetBuffer()->GetChannel(secondChannel), GetBuffer()->BufferSize(), 0);
}
GetBuffer()->Reset();
}
void Splitter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void Splitter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadString("target2", moduleInfo);
SetUpFromSaveData();
}
void Splitter::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
IClickable* target2 = TheSynth->FindModule(mModuleSaveData.GetString("target2"));
if (target2)
mPatchCableSource2->AddPatchCable(target2);
}
``` | /content/code_sandbox/Source/Splitter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 738 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// PressureToModwheel.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#include "PressureToModwheel.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
PressureToModwheel::PressureToModwheel()
{
}
PressureToModwheel::~PressureToModwheel()
{
}
void PressureToModwheel::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void PressureToModwheel::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
modulation.modWheel = modulation.pressure;
modulation.pressure = nullptr;
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void PressureToModwheel::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PressureToModwheel::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PressureToModwheel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 334 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Capo.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/5/14.
//
//
#include "Capo.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
Capo::Capo()
{
}
void Capo::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
INTSLIDER(mCapoSlider, "capo", &mCapo, -12, 12);
CHECKBOX(mRetriggerCheckbox, "retrigger", &mRetrigger);
CHECKBOX(mDiatonicCheckbox, "diatonic", &mDiatonic);
ENDUIBLOCK(mWidth, mHeight);
}
void Capo::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mCapoSlider->Draw();
mRetriggerCheckbox->Draw();
mDiatonicCheckbox->Draw();
}
void Capo::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void Capo::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (pitch >= 0 && pitch < 128)
{
if (velocity > 0)
{
mInputNotes[pitch].mOn = true;
mInputNotes[pitch].mVelocity = velocity;
mInputNotes[pitch].mVoiceIdx = voiceIdx;
mInputNotes[pitch].mOutputPitch = TransformPitch(pitch);
}
else
{
mInputNotes[pitch].mOn = false;
}
PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, velocity, mInputNotes[pitch].mVoiceIdx, modulation);
}
}
int Capo::TransformPitch(int pitch)
{
if (mDiatonic)
{
pitch += mCapo;
while (!TheScale->IsInScale(pitch))
{
++pitch;
}
return pitch;
}
else
{
return pitch + mCapo;
}
}
void Capo::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mCapoSlider && mEnabled && mRetrigger)
{
for (int pitch = 0; pitch < 128; ++pitch)
{
if (mInputNotes[pitch].mOn)
{
PlayNoteOutput(time + .01, mInputNotes[pitch].mOutputPitch, 0, mInputNotes[pitch].mVoiceIdx, ModulationParameters());
mInputNotes[pitch].mOutputPitch = pitch + mCapo;
PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, mInputNotes[pitch].mVelocity, mInputNotes[pitch].mVoiceIdx, ModulationParameters());
}
}
}
}
void Capo::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Capo::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/Capo.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 837 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Kicker.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/7/13.
//
//
#include "Kicker.h"
#include "OpenFrameworksPort.h"
#include "DrumPlayer.h"
#include "ModularSynth.h"
#include "FillSaveDropdown.h"
Kicker::Kicker()
{
}
void Kicker::DrawModule()
{
DrawConnection(mDrumPlayer);
if (Minimized() || IsVisible() == false)
return;
}
void Kicker::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void Kicker::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (mEnabled && mDrumPlayer)
{
mDrumPlayer->PlayNote(time, 3, velocity);
}
}
void Kicker::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadString("drumplayer", moduleInfo, "", FillDropdown<DrumPlayer*>);
SetUpFromSaveData();
}
void Kicker::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
SetDrumPlayer(dynamic_cast<DrumPlayer*>(TheSynth->FindModule(mModuleSaveData.GetString("drumplayer"), false)));
}
``` | /content/code_sandbox/Source/Kicker.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 420 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// PitchBender.cpp
// Bespoke
//
// Created by Ryan Challinor on 9/7/14.
//
//
#include "PitchBender.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
PitchBender::PitchBender()
: mBend(0)
, mBendSlider(nullptr)
, mRange(2)
//, mBendingCheckbox(this,"bending",HIDDEN_UICONTROL,HIDDEN_UICONTROL,mBendSlider->mTouching)
, mModulation(true)
{
//mBendSlider->SetRelative(true);
}
void PitchBender::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
PitchBender::~PitchBender()
{
TheTransport->RemoveAudioPoller(this);
}
void PitchBender::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mBendSlider = new FloatSlider(this, "bend", 5, 2, 110, 15, &mBend, -mRange, mRange);
}
void PitchBender::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mBendSlider->Draw();
}
void PitchBender::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
mModulation.GetPitchBend(voiceIdx)->AppendTo(modulation.pitchBend);
modulation.pitchBend = mModulation.GetPitchBend(voiceIdx);
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void PitchBender::OnTransportAdvanced(float amount)
{
ComputeSliders(0);
}
void PitchBender::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mBendSlider)
mModulation.GetPitchBend(-1)->SetValue(mBend);
}
void PitchBender::CheckboxUpdated(Checkbox* checkbox, double time)
{
/*if (checkbox == &mBendingCheckbox)
{
mBendSlider->UpdateTouching();
}*/
}
void PitchBender::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("range", moduleInfo, 2, 0, 48, true);
SetUpFromSaveData();
}
void PitchBender::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mRange = mModuleSaveData.GetFloat("range");
mBendSlider->SetExtents(-mRange, mRange);
}
``` | /content/code_sandbox/Source/PitchBender.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 684 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
UnstableModWheel.h
Created: 2 Mar 2021 7:48:49pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "Transport.h"
#include "UnstablePitch.h"
class UnstableModWheel : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
UnstableModWheel();
virtual ~UnstableModWheel();
static IDrawableModule* Create() { return new UnstableModWheel(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void FillModulationBuffer(double time, int voiceIdx);
UnstablePerlinModulation mPerlin{ .2, .1, 0 };
FloatSlider* mAmountSlider{ nullptr };
FloatSlider* mWarbleSlider{ nullptr };
FloatSlider* mNoiseSlider{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
std::array<bool, kNumVoices> mIsVoiceUsed{ false };
std::array<int, 128> mPitchToVoice{};
int mVoiceRoundRobin{ 0 };
Modulations mModulation{ false };
};
``` | /content/code_sandbox/Source/UnstableModWheel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 612 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
SampleBrowser.h
Created: 19 Jun 2021 6:46:36pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "Sample.h"
#include "ClickButton.h"
#include "IAudioSource.h"
class SampleBrowser : public IDrawableModule, public IButtonListener, public IAudioSource
{
public:
SampleBrowser();
~SampleBrowser();
static IDrawableModule* Create() { return new SampleBrowser(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 300;
height = 38 + (int)mButtons.size() * 17;
}
void SetDirectory(juce::String dirPath);
int GetNumPages() const;
void ShowPage(int page);
juce::String mCurrentDirectory;
juce::StringArray mDirectoryListing;
std::array<ClickButton*, 30> mButtons{ nullptr };
std::array<ClickButton*, 30> mPlayButtons{ nullptr };
ClickButton* mBackButton{ nullptr };
ClickButton* mForwardButton{ nullptr };
int mCurrentPage{ 0 };
Sample mPlayingSample;
ofMutex mSampleMutex;
};
``` | /content/code_sandbox/Source/SampleBrowser.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 546 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
SpectralDisplay.h
Created: 14 Nov 2019 10:39:24am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "FFT.h"
#include "RollingBuffer.h"
class SpectralDisplay : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
SpectralDisplay();
virtual ~SpectralDisplay();
static IDrawableModule* Create() { return new SpectralDisplay(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = mWidth;
h = mHeight;
}
float mWidth{ 400 };
float mHeight{ 100 };
float* mWindower{ nullptr };
float* mSmoother{ nullptr };
::FFT mFFT;
FFTData mFFTData;
RollingBuffer mRollingInputBuffer;
};
``` | /content/code_sandbox/Source/SpectralDisplay.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 503 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// PanicButton.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/31/14.
//
//
#include "PanicButton.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
PanicButton::PanicButton()
{
}
PanicButton::~PanicButton()
{
}
void PanicButton::OnClicked(float x, float y, bool right)
{
TheSynth->LoadLayout(ofToDataPath("daftpunk.json"));
}
void PanicButton::DrawModule()
{
gFont.DrawString("If anything goes horribly awry, click this\nand the party will be restored", 13, 5, 12);
ofPushStyle();
ofFill();
ofSetColor(70, 0, 0);
ofRect(10, 40, 270, 80);
ofSetColor(255, 0, 0);
gFont.DrawString("PANIC", 106, 15, 115);
ofPopStyle();
}
``` | /content/code_sandbox/Source/PanicButton.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 312 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteToPulse.cpp
Created: 20 Sep 2018 9:43:01pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteToPulse.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "ModulationChain.h"
NoteToPulse::NoteToPulse()
{
}
NoteToPulse::~NoteToPulse()
{
}
void NoteToPulse::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void NoteToPulse::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void NoteToPulse::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && velocity > 0)
DispatchPulse(GetPatchCableSource(), time, velocity / 127.0f, 0);
}
void NoteToPulse::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void NoteToPulse::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteToPulse::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteToPulse.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 388 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// VSTWindow.h
// Bespoke
//
// Created by Ryan Challinor on 1/23/16.
//
//
#pragma once
#include "juce_audio_processors/juce_audio_processors.h"
#include "juce_gui_basics/juce_gui_basics.h"
class VSTPlugin;
namespace juce
{
class NSViewComponent;
}
//==============================================================================
class VSTWindow : public juce::DocumentWindow
{
public:
enum WindowFormatType
{
Normal = 0,
Generic,
Programs,
Parameters,
NumTypes
};
VSTWindow(VSTPlugin* vst, Component* pluginEditor, WindowFormatType);
~VSTWindow();
void ShowWindow();
static VSTWindow* CreateVSTWindow(VSTPlugin* vst, WindowFormatType);
void moved() override;
void closeButtonPressed() override;
#ifdef JUCE_MAC
juce::NSViewComponent* GetNSViewComponent()
{
return mNSViewComponent;
}
#endif
private:
WindowFormatType mType{ WindowFormatType::Normal };
VSTPlugin* mOwner{ nullptr };
#ifdef JUCE_MAC
juce::NSViewComponent* mNSViewComponent{ nullptr };
#endif
float getDesktopScaleFactor() const override
{
return 1.0f;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(VSTWindow)
};
inline juce::String toString(VSTWindow::WindowFormatType type)
{
switch (type)
{
case VSTWindow::Normal: return "Normal";
case VSTWindow::Generic: return "Generic";
case VSTWindow::Programs: return "Programs";
case VSTWindow::Parameters: return "Parameters";
default: return juce::String();
}
}
inline juce::String getLastXProp(VSTWindow::WindowFormatType type) { return "uiLastX_" + toString(type); }
inline juce::String getLastYProp(VSTWindow::WindowFormatType type) { return "uiLastY_" + toString(type); }
inline juce::String getOpenProp(VSTWindow::WindowFormatType type) { return "uiopen_" + toString(type); }
class ProcessorProgramPropertyComp : public juce::PropertyComponent,
private juce::AudioProcessorListener
{
public:
ProcessorProgramPropertyComp(const juce::String& name, juce::AudioProcessor& p, int index_)
: PropertyComponent(name)
, owner(p)
, index(index_)
{
owner.addListener(this);
}
~ProcessorProgramPropertyComp()
{
owner.removeListener(this);
}
void refresh() {}
void audioProcessorChanged(juce::AudioProcessor*, const juce::AudioProcessorListener::ChangeDetails&) {}
void audioProcessorParameterChanged(juce::AudioProcessor*, int, float) {}
private:
juce::AudioProcessor& owner;
const int index;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ProcessorProgramPropertyComp)
};
class ProgramAudioProcessorEditor : public juce::AudioProcessorEditor
{
public:
ProgramAudioProcessorEditor(juce::AudioProcessor* const p)
: juce::AudioProcessorEditor(p)
{
jassert(p != nullptr);
setOpaque(true);
addAndMakeVisible(panel);
juce::Array<juce::PropertyComponent*> programs;
const int numPrograms = p->getNumPrograms();
int totalHeight = 0;
for (int i = 0; i < numPrograms; ++i)
{
juce::String name(p->getProgramName(i).trim());
if (name.isEmpty())
name = "Unnamed";
ProcessorProgramPropertyComp* const pc = new ProcessorProgramPropertyComp(name, *p, i);
programs.add(pc);
totalHeight += pc->getPreferredHeight();
}
panel.addProperties(programs);
setSize(400, juce::jlimit(25, 400, totalHeight));
}
void paint(juce::Graphics& g)
{
g.fillAll(juce::Colours::grey);
}
void resized()
{
panel.setBounds(getLocalBounds());
}
private:
juce::PropertyPanel panel;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ProgramAudioProcessorEditor)
};
``` | /content/code_sandbox/Source/VSTWindow.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,023 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NotePanRandom.h
Created: 22 Feb 2020 10:39:25pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
class NotePanRandom : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
NotePanRandom();
static IDrawableModule* Create() { return new NotePanRandom(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mSpread{ 1 };
FloatSlider* mSpreadSlider{ nullptr };
float mCenter{ 0 };
FloatSlider* mCenterSlider{ nullptr };
static const int kPanHistoryDisplaySize = 10;
struct PanHistoryDisplayItem
{
float time{ -9999 };
float pan{ 0 };
};
PanHistoryDisplayItem mPanHistoryDisplay[kPanHistoryDisplaySize];
int mPanHistoryDisplayIndex{ 0 };
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/NotePanRandom.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 532 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
MathUtils.h
Created: 12 Nov 2017 8:24:59pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "OpenFrameworksPort.h"
#define CUBE(x) ((x) * (x) * (x))
#define SQUARE(x) ((x) * (x))
namespace MathUtils
{
float Bezier(float t, float p0, float p1, float p2, float p3);
ofVec2f Bezier(float t, ofVec2f p0, ofVec2f p1, ofVec2f p2, ofVec2f p3);
float BezierDerivative(float t, float p0, float p1, float p2, float p3);
ofVec2f BezierPerpendicular(float t, ofVec2f p0, ofVec2f p1, ofVec2f p2, ofVec2f p3);
ofVec2f ScaleVec(ofVec2f a, ofVec2f b);
ofVec2f Normal(ofVec2f v);
float Curve(float t, float curve);
int HighestPow2(int n);
};
``` | /content/code_sandbox/Source/MathUtils.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 351 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteSorter.h
Created: 2 Aug 2021 10:32:36pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "TextEntry.h"
class NoteSorter : public INoteReceiver, public INoteSource, public IDrawableModule, public ITextEntryListener
{
public:
NoteSorter();
static IDrawableModule* Create() { return new NoteSorter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override;
void SendCC(int control, int value, int voiceIdx = -1) override;
void TextEntryComplete(TextEntry* entry) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
std::array<int, 128> mPitch;
std::vector<TextEntry*> mPitchEntry;
std::vector<AdditionalNoteCable*> mDestinationCables;
};
``` | /content/code_sandbox/Source/NoteSorter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 438 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// SamplerGrid.h
// Bespoke
//
// Created by Ryan Challinor on 6/12/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "MidiDevice.h"
#include "Ramp.h"
#include "GridController.h"
#include "UIGrid.h"
class ofxJSONElement;
#define MAX_SAMPLER_GRID_LENGTH 5 * 44100 //just 5-ish seconds of audio. don't need to adjust for actual sample rate.
#define SAMPLE_RAMP_MS 3
class SamplerGrid : public IAudioProcessor, public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener, public IGridControllerListener, public UIGridListener, public INoteReceiver
{
public:
SamplerGrid();
~SamplerGrid();
static IDrawableModule* Create() { return new SamplerGrid(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void Poll() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override;
//IAudioProcessor
InputMode GetInputMode() override { return kInputMode_Mono; }
//IGridControllerListener
void OnControllerPageSelected() override;
void OnGridButton(int x, int y, float velocity, IGridController* grid) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//UIGridListener
void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override;
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void SampleDropped(int x, int y, Sample* sample) override;
bool CanDropSample() const override { return true; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
void MouseReleased() override;
void InitGrid();
void UpdateLights();
int GridToIdx(int x, int y) { return x + y * mCols; }
Checkbox* mClearCheckbox{ nullptr };
bool mClear{ false };
struct GridSample
{
float mSampleData[MAX_SAMPLER_GRID_LENGTH]{};
int mPlayhead{ 0 };
bool mHasSample{ false };
bool mRecordingArmed{ false };
int mSampleLength{ 0 };
Ramp mRamp;
int mSampleStart{ 0 };
int mSampleEnd{ 0 };
};
void SetEditSample(GridSample* sample);
GridSample* mGridSamples{ nullptr };
int mRecordingSample{ -1 };
bool mPassthrough{ true };
Checkbox* mPassthroughCheckbox{ nullptr };
float mVolume{ 1 };
FloatSlider* mVolumeSlider{ nullptr };
bool mEditMode{ false };
Checkbox* mEditCheckbox{ nullptr };
bool mDuplicate{ false };
Checkbox* mDuplicateCheckbox{ nullptr };
GridControlTarget* mGridControlTarget{ nullptr };
int mCols{ 8 };
int mRows{ 8 };
bool mLastColumnIsGroup{ true }; //@TODO(Noxy): Not used?
int mEditSampleX{ 2 };
int mEditSampleY{ 95 };
float mEditSampleWidth{ 395 };
float mEditSampleHeight{ 200 };
GridSample* mEditSample{ nullptr };
IntSlider* mEditStartSlider{ nullptr };
IntSlider* mEditEndSlider{ nullptr };
int mDummyInt{ 0 };
UIGrid* mGrid{ nullptr };
};
``` | /content/code_sandbox/Source/SamplerGrid.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,166 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModuleContainer.h
Created: 16 Oct 2016 3:47:41pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "OpenFrameworksPort.h"
#include "IDrawableModule.h"
#include "ofxJSONElement.h"
class ModuleContainer
{
public:
ModuleContainer();
const std::vector<IDrawableModule*>& GetModules() const { return mModules; }
void SetOwner(IDrawableModule* owner) { mOwner = owner; }
IDrawableModule* GetOwner() const { return mOwner; }
void DrawContents();
void DrawModules();
void DrawPatchCables(bool parentMinimized, bool inFront);
void DrawUnclipped();
void PostRender();
void Poll();
void Clear();
void Exit();
ofVec2f GetOwnerPosition() const;
ofVec2f GetDrawOffset();
ofVec2f& GetDrawOffsetRef() { return mDrawOffset; }
void SetDrawOffset(ofVec2f offset) { mDrawOffset = offset; }
float GetDrawScale() const;
void SetDrawScale(float scale) { mDrawScale = scale; }
void KeyPressed(int key, bool isRepeat);
void KeyReleased(int key);
void MouseMoved(float x, float y);
void MouseReleased();
IDrawableModule* GetModuleAt(float x, float y);
void GetModulesWithinRect(ofRectangle rect, std::vector<IDrawableModule*>& output);
void MoveToFront(IDrawableModule* module);
void AddModule(IDrawableModule* module);
void TakeModule(IDrawableModule* module);
void DeleteModule(IDrawableModule* module, bool fail = true);
static void DeleteCablesForControl(const IUIControl* control);
IDrawableModule* FindModule(std::string name, bool fail = true);
IUIControl* FindUIControl(std::string path);
bool IsHigherThan(IDrawableModule* checkFor, IDrawableModule* checkAgainst) const;
void GetAllModules(std::vector<IDrawableModule*>& out);
template <class T>
std::vector<std::string> GetModuleNames()
{
std::vector<std::string> ret;
for (int i = 0; i < mModules.size(); ++i)
{
if (dynamic_cast<T>(mModules[i]))
ret.push_back(mModules[i]->Name());
}
return ret;
}
void LoadModules(const ofxJSONElement& modules);
ofxJSONElement WriteModules();
void SaveState(FileStreamOut& out);
void LoadState(FileStreamIn& in);
static constexpr int GetModuleSeparatorLength() { return 13; }
static const char* GetModuleSeparator() { return "ryanchallinor"; }
static bool DoesModuleHaveMoreSaveData(FileStreamIn& in);
private:
std::vector<IDrawableModule*> mModules;
IDrawableModule* mOwner{ nullptr };
ofVec2f mDrawOffset;
float mDrawScale{ 1 };
};
``` | /content/code_sandbox/Source/ModuleContainer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 767 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Pressure.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#include "Pressure.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
Pressure::Pressure()
{
}
void Pressure::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
Pressure::~Pressure()
{
TheTransport->RemoveAudioPoller(this);
}
void Pressure::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mPressureSlider = new FloatSlider(this, "pressure", 5, 2, 110, 15, &mPressure, 0, 1);
}
void Pressure::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mPressureSlider->Draw();
}
void Pressure::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
mModulation.GetPressure(voiceIdx)->AppendTo(modulation.pressure);
modulation.pressure = mModulation.GetPressure(voiceIdx);
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void Pressure::OnTransportAdvanced(float amount)
{
ComputeSliders(0);
}
void Pressure::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mPressureSlider)
mModulation.GetPressure(-1)->SetValue(mPressure);
}
void Pressure::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void Pressure::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Pressure::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/Pressure.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 491 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Stutter.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/24/12.
//
//
#include "Stutter.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
bool Stutter::sQuantize = true;
int Stutter::sStutterSubdivide = 1;
Stutter::Stutter()
: mRecordBuffer(STUTTER_BUFFER_SIZE)
, mStutterBuffer(STUTTER_BUFFER_SIZE)
{
mBlendRamp.SetValue(0);
}
void Stutter::Init()
{
TheTransport->AddListener(this, kInterval_16n, OffsetInfo(0, true), false);
}
Stutter::~Stutter()
{
TheTransport->RemoveListener(this);
}
void Stutter::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(Stutter);
float bufferSize = buffer->BufferSize();
mRecordBuffer.SetNumChannels(buffer->NumActiveChannels());
mStutterBuffer.SetNumActiveChannels(buffer->NumActiveChannels());
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
mRecordBuffer.WriteChunk(buffer->GetChannel(ch), bufferSize, ch);
if (mBlendRamp.Target(time) > 0 || mBlendRamp.Value(time) > 0)
{
if (mCurrentStutter.interval == kInterval_None)
{
mStutterLengthRamp.Start(time, mFreeStutterLength * gSampleRate, time + 20);
mStutterSpeed.Start(time, mFreeStutterSpeed, time + 20);
}
for (int i = 0; i < bufferSize; ++i)
{
if (mCurrentStutter.interval != kInterval_None)
mStutterLength = int(TheTransport->GetDuration(mCurrentStutter.interval) / 1000 * gSampleRate);
else
mStutterLength = int(mStutterLengthRamp.Value(time));
float offset = mStutterPos;
if (offset > mStutterLength)
offset -= mStutterLength;
int pos = int(offset);
int posNext = int(offset + 1) % mStutterLength;
float a = offset - pos;
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
{
float sample = GetStutterSampleWithWraparoundBlend(pos, ch);
float nextSample = GetStutterSampleWithWraparoundBlend(posNext, ch);
float stutterOut = (1 - a) * sample + a * nextSample; //interpolate
float fade = 1;
if (mFadeStutter)
fade -= (offset / mStutterLength) * (offset / mStutterLength);
float blend = mBlendRamp.Value(time);
buffer->GetChannel(ch)[i] = stutterOut * blend * fade + buffer->GetChannel(ch)[i] * (1 - blend);
buffer->GetChannel(ch)[i] = mJumpBlender[ch].Process(buffer->GetChannel(ch)[i], i);
}
//TODO(Ryan) what was this for?
//if (blend == 0 && mBlendRamp.Target() == 0)
// break;
mStutterPos += mStutterSpeed.Value(time);
if (mStutterPos > mStutterLength)
mStutterPos -= mStutterLength;
if (mStutterPos < 0)
mStutterPos += mStutterLength;
time += gInvSampleRateMs;
}
}
}
float Stutter::GetStutterSampleWithWraparoundBlend(int pos, int ch)
{
if (pos > mStutterLength - STUTTER_BLEND_WRAPAROUND_SAMPLES)
{
float a = float(mStutterLength - pos) / STUTTER_BLEND_WRAPAROUND_SAMPLES;
int blendPos = pos - mStutterLength;
pos = GetBufferReadPos(pos);
blendPos = GetBufferReadPos(blendPos);
pos = ofClamp(pos, 0, mCaptureLength);
blendPos = ofClamp(blendPos, 0, mCaptureLength);
return mStutterBuffer.GetChannel(ch)[pos] * a + mStutterBuffer.GetChannel(ch)[blendPos] * (1 - a);
}
else
{
pos = GetBufferReadPos(pos);
pos = ofClamp(pos, 0, mCaptureLength);
return mStutterBuffer.GetChannel(ch)[pos];
}
}
float Stutter::GetBufferReadPos(float stutterPos)
{
return stutterPos; // + mCaptureLength - mStutterLength;
}
//TODO(Ryan) figure out how to blend out when we hit the rewrite button
void Stutter::StartStutter(double time, StutterParams stutter)
{
if (mAutoStutter || !mEnabled)
return;
mMutex.lock();
mStutterStack.push_front(stutter);
mMutex.unlock();
bool quantize = sQuantize;
if (stutter.interval == kInterval_None)
quantize = false; //"free stutter" shouldn't be quantized
if (!quantize)
DoStutter(time, stutter);
}
void Stutter::EndStutter(double time, StutterParams stutter)
{
if (mAutoStutter || !mEnabled)
return;
mMutex.lock();
bool hasNewStutter = false;
if (mStutterStack.size() > 1 && *(mStutterStack.begin()) == stutter)
{ //if we're removing the current stutter and there are held stutters
mStutterStack.remove(stutter); //remove all matching stutters
if (mStutterStack.size() > 0) //if there's anything left
{
stutter = *(mStutterStack.begin()); //use previously held as stutter
hasNewStutter = true;
}
}
else
{
mStutterStack.remove(stutter);
}
mMutex.unlock();
bool quantize = sQuantize;
if (stutter.interval == kInterval_None && mStutterStack.empty())
quantize = false; //"free stutter" shouldn't be quantized if we're releasing the only stutter
if (!quantize)
{
if (mStutterStack.empty())
StopStutter(time);
else if (hasNewStutter)
DoStutter(time, stutter);
}
}
void Stutter::StopStutter(double time)
{
if (mStuttering)
{
mBlendRamp.Start(time, 0, time + STUTTER_START_BLEND_MS);
mStuttering = false;
}
}
void Stutter::DoStutter(double time, StutterParams stutter)
{
if (mStuttering && stutter == mCurrentStutter)
return;
mCurrentStutter = stutter;
if (!mStuttering ||
int(TheTransport->GetDuration(mCurrentStutter.interval) / 1000 * gSampleRate) > mCaptureLength)
{
DoCapture();
}
else
{
//blend from the prior stutter to this new one
for (int ch = 0; ch < mStutterBuffer.NumActiveChannels(); ++ch)
{
float jumpBlend[JUMP_BLEND_SAMPLES];
for (int i = 0; i < JUMP_BLEND_SAMPLES; ++i)
jumpBlend[i] = GetStutterSampleWithWraparoundBlend(int(mStutterPos) % mStutterLength + i, ch);
mJumpBlender[ch].CaptureForJump(0, jumpBlend, JUMP_BLEND_SAMPLES, 0);
}
}
mStutterPos = 0;
mStuttering = true;
mBlendRamp.Start(time, 1, time + STUTTER_START_BLEND_MS);
if (stutter.interval != kInterval_None)
mStutterLength = int(TheTransport->GetDuration(stutter.interval) / 1000 * gSampleRate);
else
mStutterLength = mFreeStutterLength;
if (stutter.speedBlendTime == 0)
mStutterSpeed.SetValue(stutter.speedStart);
else
mStutterSpeed.Start(time, stutter.speedStart, stutter.speedEnd, time + stutter.speedBlendTime);
mStutterLength /= sStutterSubdivide;
mStutterLength = MAX(1, mStutterLength); //don't allow it to be zero
mStutterLengthRamp.SetValue(mStutterLength);
}
void Stutter::DrawStutterBuffer(float x, float y, float width, float height)
{
ofPushMatrix();
ofTranslate(x, y);
if (mStuttering)
DrawAudioBuffer(width, height, &mStutterBuffer, 0, mCaptureLength, GetBufferReadPos(mStutterPos));
ofPopMatrix();
}
void Stutter::DoCapture()
{
mCaptureLength = int(TheTransport->GetDuration(mCurrentStutter.interval) / 1000 * gSampleRate);
mCaptureLength = ofClamp(mCaptureLength, 0, STUTTER_BUFFER_SIZE - 1);
mCaptureLength /= sStutterSubdivide;
for (int ch = 0; ch < mStutterBuffer.NumActiveChannels(); ++ch)
mRecordBuffer.ReadChunk(mStutterBuffer.GetChannel(ch), mCaptureLength, 0, ch);
}
void Stutter::OnTimeEvent(double time)
{
if (mEnabled)
{
if (mAutoStutter && TheTransport->GetMeasurePos(time) > .001f) //don't auto-stutter downbeat
{
if (gRandom() % 4 == 0)
{
const StutterParams randomStutters[] = { StutterParams(kInterval_2n, 1),
StutterParams(kInterval_4n, 1),
StutterParams(kInterval_8n, 1),
StutterParams(kInterval_16n, 1),
StutterParams(kInterval_32n, 1),
StutterParams(kInterval_64n, 1),
StutterParams(kInterval_2n, -1),
StutterParams(kInterval_8n, .5f),
StutterParams(kInterval_8n, 2) };
DoStutter(time, randomStutters[gRandom() % 9]);
}
else
{
StopStutter(time);
}
}
if (sQuantize && !mAutoStutter)
{
mMutex.lock();
if (mStutterStack.empty())
StopStutter(time);
else
DoStutter(time, *mStutterStack.begin());
mMutex.unlock();
}
}
}
void Stutter::SetEnabled(double time, bool enabled)
{
if (enabled != mEnabled)
{
mEnabled = enabled;
if (!mEnabled)
{
mMutex.lock();
mStutterStack.clear();
mMutex.unlock();
StopStutter(time);
}
}
}
``` | /content/code_sandbox/Source/Stutter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,484 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteQuantizer.cpp
Created: 6 Dec 2020 7:36:30pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteQuantizer.h"
#include "SynthGlobals.h"
NoteQuantizer::NoteQuantizer()
{
}
void NoteQuantizer::Init()
{
IDrawableModule::Init();
TheTransport->AddListener(this, mQuantizeInterval, OffsetInfo(0, true), false);
}
NoteQuantizer::~NoteQuantizer()
{
TheTransport->RemoveListener(this);
}
void NoteQuantizer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mQuantizeIntervalSelector = new DropdownList(this, "quantize", 3, 4, (int*)(&mQuantizeInterval));
mNoteRepeatCheckbox = new Checkbox(this, "repeat", 3, 22, &mNoteRepeat);
mQuantizeIntervalSelector->AddLabel("none", kInterval_None);
mQuantizeIntervalSelector->AddLabel("4n", kInterval_4n);
mQuantizeIntervalSelector->AddLabel("4nt", kInterval_4nt);
mQuantizeIntervalSelector->AddLabel("8n", kInterval_8n);
mQuantizeIntervalSelector->AddLabel("8nt", kInterval_8nt);
mQuantizeIntervalSelector->AddLabel("16n", kInterval_16n);
mQuantizeIntervalSelector->AddLabel("16nt", kInterval_16nt);
mQuantizeIntervalSelector->AddLabel("32n", kInterval_32n);
mQuantizeIntervalSelector->AddLabel("64n", kInterval_64n);
}
void NoteQuantizer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mQuantizeIntervalSelector->SetShowing(!mHasReceivedPulse);
mQuantizeIntervalSelector->Draw();
mNoteRepeatCheckbox->Draw();
}
void NoteQuantizer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (mQuantizeInterval == kInterval_None)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
else
{
if (pitch < mInputInfos.size())
{
if (velocity > 0)
{
if ((mScheduledOffs[pitch] || mPreScheduledOffs[pitch] || mInputInfos[pitch].held) && mInputInfos[pitch].voiceIdx != voiceIdx)
{
PlayNoteOutput(time, pitch, 0, mInputInfos[pitch].voiceIdx, mInputInfos[pitch].modulation);
mScheduledOffs[pitch] = false;
mPreScheduledOffs[pitch] = false;
}
mInputInfos[pitch].velocity = velocity;
mInputInfos[pitch].voiceIdx = voiceIdx;
mInputInfos[pitch].modulation = modulation;
mInputInfos[pitch].held = true;
mInputInfos[pitch].hasPlayedYet = false;
}
else
{
if (mInputInfos[pitch].hasPlayedYet)
mScheduledOffs[pitch] = true;
else
mPreScheduledOffs[pitch] = true;
if (mNoteRepeat)
mInputInfos[pitch].velocity = 0;
mInputInfos[pitch].held = false;
}
}
}
}
void NoteQuantizer::OnEvent(double time, float strength)
{
for (int i = 0; i < (int)mInputInfos.size(); ++i)
{
if (mScheduledOffs[i])
{
PlayNoteOutput(time, i, 0, mInputInfos[i].voiceIdx, mInputInfos[i].modulation);
mScheduledOffs[i] = false;
}
if (mInputInfos[i].velocity > 0)
{
PlayNoteOutput(time, i, mInputInfos[i].velocity * strength, mInputInfos[i].voiceIdx, mInputInfos[i].modulation);
mInputInfos[i].hasPlayedYet = true;
if (!mNoteRepeat)
mInputInfos[i].velocity = 0;
else
mScheduledOffs[i] = true;
if (mPreScheduledOffs[i])
{
mPreScheduledOffs[i] = false;
mScheduledOffs[i] = true;
}
}
}
}
void NoteQuantizer::OnTimeEvent(double time)
{
if (!mHasReceivedPulse)
OnEvent(time, 1);
}
void NoteQuantizer::OnPulse(double time, float velocity, int flags)
{
mHasReceivedPulse = true;
OnEvent(time, velocity);
}
void NoteQuantizer::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mQuantizeIntervalSelector)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mQuantizeInterval;
}
}
void NoteQuantizer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteQuantizer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteQuantizer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,292 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// MidiReader.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/29/14.
//
//
#include "MidiReader.h"
MidiReader::MidiReader()
//: mSequencer(nullptr)
{
}
MidiReader::~MidiReader()
{
//delete mSequencer;
}
void MidiReader::Read(const char* midiFileName)
{
/*MIDITimedBigMessage event;
int eventTrack = 0;
string filePath = ofToDataPath(midiFileName, true);
MIDIFileReadStreamFile rs ( filePath.c_str() );
if ( !rs.IsValid() )
{
ofLogError( "ERROR OPENING FILE AT: ", filePath);
}
MIDIFileReadMultiTrack track_loader ( &mTracks );
MIDIFileRead reader ( &rs, &track_loader );
int numMidiTracks = reader.ReadNumTracks();
int midiFormat = reader.GetFormat();
mTracks.ClearAndResize( numMidiTracks );
cout << "numMidiTracks: " << numMidiTracks << endl;
cout << "midiFormat: " << midiFormat << endl;
if ( reader.Parse() )
{
cout << "reader parsed!" << endl;
}
delete mSequencer;
mSequencer = new MIDISequencer(&mTracks);*/
}
float MidiReader::GetTempo(double ms)
{
/*if (mSequencer)
{
mSequencer->GoToTimeMs(ms);
return mSequencer->GetCurrentTempo();
}*/
return 120;
}
int MidiReader::GetBeat(double ms)
{
/*if (mSequencer)
{
mSequencer->GoToTimeMs(ms);
return mSequencer->GetCurrentBeat();
}*/
return 0;
}
void MidiReader::GetMeasurePos(double ms, int& measure, float& measurePos)
{
/*if (mSequencer)
{
mSequencer->GoToTimeMs(ms);
int beat = (mSequencer->GetCurrentBeat() + mBeatOffset + 16) % 4;
measure = mSequencer->GetCurrentMeasure() + ((mSequencer->GetCurrentBeat() + mBeatOffset + 16) / 4 - 4);
double msIn = ms-mSequencer->GetCurrentTimeInMs();
double bpm = mSequencer->GetCurrentTempo();
double bpms = bpm / 60 / 1000;
double beatProgress = bpms * msIn;
measurePos = float((beat + beatProgress) / 4.0f);
}
else
{
measure = 0;
measurePos = 0;
}*/
}
``` | /content/code_sandbox/Source/MidiReader.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 698 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// NoteSustain.h
// Bespoke
//
// Created by Ryan Challinor on 6/19/15.
//
//
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
#include "Slider.h"
#include "Transport.h"
class NoteSustain : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
NoteSustain();
~NoteSustain();
static IDrawableModule* Create() { return new NoteSustain(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override
{
mEnabled = enabled;
mNoteOutput.Flush(NextBufferTime(false));
}
void OnTransportAdvanced(float amount) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 110;
height = 22;
}
struct QueuedNoteOff
{
QueuedNoteOff(double time, double pitch, double voiceIdx)
: mTime(time)
, mPitch(pitch)
, mVoiceIdx(voiceIdx)
{}
double mTime{ 0 };
int mPitch{ 0 };
int mVoiceIdx{ -1 };
};
float mSustain{ .25 };
FloatSlider* mSustainSlider{ nullptr };
std::list<QueuedNoteOff> mNoteOffs;
};
``` | /content/code_sandbox/Source/NoteSustain.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 555 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Slider.h
// modularSynth
//
// Created by Ryan Challinor on 12/4/12.
//
//
#pragma once
#include <iostream>
#include <limits>
#include "TextEntry.h"
#include "Ramp.h"
#include "IAudioPoller.h"
class FloatSlider;
class FloatSliderLFOControl;
class IModulator;
class IFloatSliderListener
{
public:
virtual ~IFloatSliderListener() {}
virtual void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) = 0;
};
class FloatSlider : public IUIControl, public ITextEntryListener, public IAudioPoller
{
public:
FloatSlider(IFloatSliderListener* owner, const char* label, int x, int y, int w, int h, float* var, float min, float max, int digits = -1);
FloatSlider(IFloatSliderListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDir, int w, int h, float* var, float min, float max, int digits = -1);
void SetVar(float* var) { mVar = var; }
void Render() override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
bool IsMouseDown() const override { return mMouseDown; }
void SetExtents(float min, float max)
{
mMin = min;
mMax = max;
}
void Compute(int samplesIn = 0)
{
mComputeHasBeenCalledOnce = true; //mark this slider as one whose owner calls compute on it
if (mIsSmoothing || mModulator != nullptr)
DoCompute(samplesIn);
}
void DisplayLFOControl();
void DisableLFO();
FloatSliderLFOControl* GetLFO() { return mLFOControl; }
FloatSliderLFOControl* AcquireLFO();
void MatchExtents(FloatSlider* slider);
void SetRelative(bool relative) { mRelative = relative; }
void SetClamped(bool clamped) { mClamped = clamped; }
float GetMin() const { return mMin; }
float GetMax() const { return mMax; }
void SetMaxValueDisplay(std::string display) { mMaxValueDisplay = display; }
void SetMinValueDisplay(std::string display) { mMinValueDisplay = display; }
void SetLFO(FloatSliderLFOControl* lfo);
void SetShowName(bool show) { mShowName = show; }
void SetDimensions(int w, int h)
{
mWidth = w;
mHeight = h;
}
void SetBezierControl(float control) { mBezierControl = control; }
void SetModulator(IModulator* modulator);
IModulator* GetModulator() { return mModulator; }
float& GetModulatorMin() { return mModulatorMin; }
float& GetModulatorMax() { return mModulatorMax; }
bool ModulatorUsesLiteralValue() const override { return true; }
float GetModulationRangeMin() const override { return mMin; }
float GetModulationRangeMax() const override { return mMax; }
void OnTransportAdvanced(float amount) override;
void Init() override;
enum Mode
{
kNormal,
kLogarithmic,
kSquare,
kBezier
};
void SetMode(Mode mode) { mMode = mode; }
Mode GetMode() const { return mMode; }
bool CheckNeedsDraw() override;
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override;
std::string GetDisplayValue(float val) const override;
float GetMidiValue() const override;
void GetRange(float& min, float& max) override
{
min = mMin;
max = mMax;
}
void Double() override;
void Halve() override;
void ResetToOriginal() override;
void Poll() override;
void Increment(float amount) override;
float PosToVal(float pos, bool ignoreSmooth) const;
float ValToPos(float val, bool ignoreSmooth) const;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
bool AttemptTextInput() override;
void TextEntryComplete(TextEntry* entry) override;
void TextEntryCancelled(TextEntry* entry) override;
void UpdateTouching();
bool mTouching{ false }; //to be controlled with external checkbox for "relative" sliders
protected:
~FloatSlider(); //protected so that it can't be created on the stack
private:
void OnClicked(float x, float y, bool right) override;
void SetValueForMouse(float x, float y);
float* GetModifyValue();
bool AdjustSmooth() const;
void SmoothUpdated();
void DoCompute(int samplesIn);
int mWidth;
int mHeight;
float* mVar;
float mMin;
float mMax;
float mModulatorMin;
float mModulatorMax;
bool mMouseDown{ false };
int mFineRefX{ -999 };
int mRefY{ -999 };
int mShowDigits;
IFloatSliderListener* mOwner{ nullptr };
FloatSliderLFOControl* mLFOControl{ nullptr };
IModulator* mModulator{ nullptr };
bool mRelative{ false };
float mRelativeOffset{ -999 };
bool mClamped{ true };
Mode mMode{ Mode::kNormal };
float mOriginalValue{ 0 };
std::string mMinValueDisplay{ "" };
std::string mMaxValueDisplay{ "" };
bool mShowName{ true };
float mBezierControl{ 1 };
float mSmooth{ 0 };
float mSmoothTarget{ 0 };
Ramp mRamp;
bool mIsSmoothing{ false };
bool mComputeHasBeenCalledOnce{ false };
double mLastComputeTime{ 0 };
int mLastComputeSamplesIn{ 0 };
double* mLastComputeCacheTime;
float* mLastComputeCacheValue;
float mLastDisplayedValue{ std::numeric_limits<float>::max() };
TextEntry* mFloatEntry{ nullptr };
char mEntryString[MAX_TEXTENTRY_LENGTH]{};
bool mAllowMinMaxAdjustment{ true };
TextEntry* mMinEntry{ nullptr };
TextEntry* mMaxEntry{ nullptr };
};
class IntSlider;
class IIntSliderListener
{
public:
virtual ~IIntSliderListener() {}
virtual void IntSliderUpdated(IntSlider* slider, int oldVal, double time) = 0;
};
class IntSlider : public IUIControl, public ITextEntryListener
{
public:
IntSlider(IIntSliderListener* owner, const char* label, int x, int y, int w, int h, int* var, int min, int max);
IntSlider(IIntSliderListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDir, int w, int h, int* var, int min, int max);
void SetVar(int* var) { mVar = var; }
void Render() override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override { mMouseDown = false; }
bool IsMouseDown() const override { return mMouseDown; }
int GetMin() const { return mMin; }
int GetMax() const { return mMax; }
void SetExtents(int min, int max)
{
mMin = min;
mMax = max;
CalcSliderVal();
}
void SetShowName(bool show) { mShowName = show; }
void SetDimensions(int w, int h)
{
mWidth = w;
mHeight = h;
}
void Init() override;
bool CheckNeedsDraw() override;
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override;
float GetMidiValue() const override;
void GetRange(float& min, float& max) override
{
min = mMin;
max = mMax;
}
int GetNumValues() override { return mMax - mMin + 1; }
bool ModulatorUsesLiteralValue() const override { return true; }
float GetModulationRangeMin() const override { return mMin; }
float GetModulationRangeMax() const override { return mMax; }
std::string GetDisplayValue(float val) const override;
void GetRange(int& min, int& max)
{
min = mMin;
max = mMax;
}
void Double() override;
void Halve() override;
void Increment(float amount) override;
void ResetToOriginal() override;
void Poll() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
bool AttemptTextInput() override;
void TextEntryComplete(TextEntry* entry) override;
void TextEntryCancelled(TextEntry* entry) override;
protected:
~IntSlider(); //protected so that it can't be created on the stack
private:
void OnClicked(float x, float y, bool right) override;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SetValueForMouse(float x, float y);
void CalcSliderVal();
int mWidth;
int mHeight;
int* mVar;
int mMin;
int mMax;
bool mMouseDown;
int mOriginalValue;
IIntSliderListener* mOwner;
int mLastDisplayedValue;
int mLastSetValue;
float mSliderVal;
bool mShowName;
TextEntry* mIntEntry;
char mEntryString[MAX_TEXTENTRY_LENGTH];
bool mAllowMinMaxAdjustment;
TextEntry* mMinEntry;
TextEntry* mMaxEntry;
};
``` | /content/code_sandbox/Source/Slider.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,398 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// QwertyController.h
// Bespoke
//
// Created by Ryan Challinor on 4/15/24.
//
//
#include "QwertyController.h"
#include "SynthGlobals.h"
QwertyController::QwertyController(MidiDeviceListener* listener)
: mListener(listener)
{
}
QwertyController::~QwertyController()
{
}
std::string QwertyController::GetControlTooltip(MidiMessageType type, int control)
{
if (type == kMidiMessage_Note)
return std::string(1, char(control));
return "[unmapped]";
}
void QwertyController::OnKeyPressed(int key)
{
if (key >= 0 && key < (int)mPressedKeys.size())
{
mPressedKeys[key] = true;
MidiNote note;
note.mPitch = key;
note.mVelocity = 127.0f;
note.mChannel = 0;
note.mDeviceName = "keyboard";
mListener->OnMidiNote(note);
}
}
void QwertyController::OnKeyReleased(int key)
{
if (key >= 0 && key < (int)mPressedKeys.size() && mPressedKeys[key])
{
mPressedKeys[key] = false;
MidiNote note;
note.mPitch = key;
note.mVelocity = 0.0f;
note.mChannel = 0;
note.mDeviceName = "keyboard";
mListener->OnMidiNote(note);
}
}
namespace
{
const int kSaveStateRev = 1;
}
void QwertyController::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
}
void QwertyController::LoadState(FileStreamIn& in)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
}
``` | /content/code_sandbox/Source/QwertyController.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 493 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// VoiceSetter.h
// Bespoke
//
// Created by Ryan Challinor on 6/17/15.
//
//
#pragma once
#include "NoteEffectBase.h"
class VoiceSetter : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
VoiceSetter() = default;
static IDrawableModule* Create() { return new VoiceSetter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 90 };
float mHeight{ 20 };
int mVoiceIdx{ 0 };
IntSlider* mVoiceSlider{ nullptr };
};
``` | /content/code_sandbox/Source/VoiceSetter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 402 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteHumanizer.cpp
Created: 2 Nov 2016 7:56:21pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteHumanizer.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
NoteHumanizer::NoteHumanizer()
{
}
NoteHumanizer::~NoteHumanizer()
{
}
void NoteHumanizer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTimeSlider = new FloatSlider(this, "time", 4, 4, 100, 15, &mTime, 0, 500);
mVelocitySlider = new FloatSlider(this, "velocity", mTimeSlider, kAnchor_Below, 100, 15, &mVelocity, 0, 1);
mTimeSlider->SetMode(FloatSlider::kSquare);
}
void NoteHumanizer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mTimeSlider->Draw();
mVelocitySlider->Draw();
}
void NoteHumanizer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void NoteHumanizer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
return;
}
float delayMs;
int outputVelocity;
if (velocity > 0)
{
delayMs = ofRandom(0, mTime);
outputVelocity = ofClamp((velocity / 127.0f * ofRandom(1 - mVelocity, 1 + mVelocity)) * 127, 1, 127);
mLastDelayMs[pitch] = delayMs;
}
else
{
delayMs = mLastDelayMs[pitch];
outputVelocity = 0;
}
PlayNoteOutput(time + delayMs, pitch, outputVelocity, voiceIdx, modulation);
}
void NoteHumanizer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void NoteHumanizer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteHumanizer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteHumanizer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 632 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// FollowingSong.h
// Bespoke
//
// Created by Ryan Challinor on 10/15/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "ClickButton.h"
#include "RadioButton.h"
#include "Slider.h"
#include "IAudioSource.h"
#include "MidiReader.h"
#include "Sample.h"
#include "ofxJSONElement.h"
class FollowingSong : public IDrawableModule, public IDropdownListener, public IButtonListener, public IRadioButtonListener, public IIntSliderListener, public IAudioSource, public IFloatSliderListener
{
public:
FollowingSong();
~FollowingSong();
static IDrawableModule* Create() { return new FollowingSong(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void LoadSample(const char* file);
void SetPlaybackInfo(bool play, int position, float speed, float volume);
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 560;
height = 130;
}
ofMutex mLoadSongMutex;
bool mLoadingSong{ true };
Sample mSample;
float mVolume{ 1 };
bool mPlay{ false };
bool mMute{ false };
Checkbox* mMuteCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/FollowingSong.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 608 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// Autotalent.h
// modularSynth
//
// Created by Ryan Challinor on 1/27/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "Slider.h"
#include "Checkbox.h"
#include "IDrawableModule.h"
#include "RadioButton.h"
#include "ClickButton.h"
#include "INoteReceiver.h"
class FFT;
class Autotalent : public IAudioProcessor, public IIntSliderListener, public IFloatSliderListener, public IDrawableModule, public IRadioButtonListener, public IButtonListener, public INoteReceiver
{
public:
Autotalent();
~Autotalent();
static IDrawableModule* Create() { return new Autotalent(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioReceiver
InputMode GetInputMode() override { return kInputMode_Mono; }
//IAudioSource
void Process(double time) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void CheckboxUpdated(Checkbox* checkbox, double time) override {}
//IIntSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {}
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
//IRadioButtonListener
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override {}
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
void UpdateShiftSlider();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 260;
height = 360;
}
float* mWorkingBuffer;
RadioButton* mASelector{ nullptr };
RadioButton* mBbSelector{ nullptr };
RadioButton* mBSelector{ nullptr };
RadioButton* mCSelector{ nullptr };
RadioButton* mDbSelector{ nullptr };
RadioButton* mDSelector{ nullptr };
RadioButton* mEbSelector{ nullptr };
RadioButton* mESelector{ nullptr };
RadioButton* mFSelector{ nullptr };
RadioButton* mGbSelector{ nullptr };
RadioButton* mGSelector{ nullptr };
RadioButton* mAbSelector{ nullptr };
FloatSlider* mAmountSlider{ nullptr };
FloatSlider* mSmoothSlider{ nullptr };
IntSlider* mShiftSlider{ nullptr };
IntSlider* mScwarpSlider{ nullptr };
FloatSlider* mLfoampSlider{ nullptr };
FloatSlider* mLforateSlider{ nullptr };
IntSlider* mLfoshapeSlider{ nullptr };
FloatSlider* mLfosymmSlider{ nullptr };
Checkbox* mLfoquantCheckbox{ nullptr };
Checkbox* mFcorrCheckbox{ nullptr };
FloatSlider* mFwarpSlider{ nullptr };
FloatSlider* mMixSlider{ nullptr };
ClickButton* mSetFromScaleButton{ nullptr };
////////////////////////////////////////
//ported
float mTune{ 440 };
float mFixed{ 0 };
float mPull{ 0 };
int mA{ 0 };
int mBb{ 0 };
int mB{ 0 };
int mC{ 0 };
int mDb{ 0 };
int mD{ 0 };
int mEb{ 0 };
int mE{ 0 };
int mF{ 0 };
int mGb{ 0 };
int mG{ 0 };
int mAb{ 0 };
float mAmount{ 1 };
float mSmooth{ 0 };
int mShift{ 0 };
int mScwarp{ 0 };
float mLfoamp{ 0 };
float mLforate{ 0 };
int mLfoshape{ 0 };
float mLfosymm{ 0 };
bool mLfoquant{ false };
bool mFcorr{ false };
float mFwarp{ 0 };
float mMix{ 1 };
float mPitch{ 0 };
float mConfidence{ 0 };
float mLatency{ 0 };
::FFT* mFFT;
unsigned long mfs; // Sample rate
unsigned long mcbsize; // size of circular buffer
unsigned long mcorrsize; // cbsize/2 + 1
unsigned long mcbiwr;
unsigned long mcbord;
float* mcbi; // circular input buffer
float* mcbf; // circular formant correction buffer
float* mcbo; // circular output buffer
float* mcbwindow; // hann of length N/2, zeros for the rest
float* macwinv; // inverse of autocorrelation of window
float* mhannwindow; // length-N hann
int mnoverlap;
float* mffttime;
float* mfftfreqre;
float* mfftfreqim;
// VARIABLES FOR LOW-RATE SECTION
float maref{ 440 }; // A tuning reference (Hz)
float minpitch{ 0 }; // Input pitch (semitones)
float mconf{ 0 }; // Confidence of pitch period estimate (between 0 and 1)
float moutpitch{ 0 }; // Output pitch (semitones)
float mvthresh; // Voiced speech threshold
float mpmax; // Maximum allowable pitch period (seconds)
float mpmin; // Minimum allowable pitch period (seconds)
unsigned long mnmax; // Maximum period index for pitch prd est
unsigned long mnmin; // Minimum period index for pitch prd est
float mlrshift; // Shift prescribed by low-rate section
int mptarget; // Pitch target, between 0 and 11
float msptarget; // Smoothed pitch target
float mlfophase;
// VARIABLES FOR PITCH SHIFTER
float mphprdd; // default (unvoiced) phase period
double minphinc; // input phase increment
double moutphinc{ 0 }; // input phase increment
double mphincfact; // factor determining output phase increment
double mphasein;
double mphaseout;
float* mfrag; // windowed fragment of speech
unsigned long mfragsize; // size of fragment in samples
// VARIABLES FOR FORMANT CORRECTOR
int mford;
float mfalph;
float mflamb;
float* mfk;
float* mfb;
float* mfc;
float* mfrb;
float* mfrc;
float* mfsig;
float* mfsmooth;
float mfhp;
float mflp;
float mflpa;
float** mfbuff;
float* mftvec;
float mfmute;
float mfmutealph;
};
``` | /content/code_sandbox/Source/Autotalent.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,722 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Inverter.h
Created: 13 Nov 2019 10:16:14pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
class Inverter : public IAudioProcessor, public IDrawableModule
{
public:
Inverter();
virtual ~Inverter();
static IDrawableModule* Create() { return new Inverter(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 120;
h = 12;
}
};
``` | /content/code_sandbox/Source/Inverter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 361 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(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
along with this program. If not, see <path_to_url
**/
//
// LocationZoomer.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/6/14.
//
//
#include "LocationZoomer.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UserPrefs.h"
#include "juce_core/juce_core.h"
LocationZoomer::LocationZoomer()
{
}
void LocationZoomer::Init()
{
mHome.mZoomLevel = UserPrefs.zoom.Get();
mHome.mOffset.set(0, 0);
mStart = mHome;
mDestination = mHome;
mCurrentProgress = 1;
gDrawScale = mHome.mZoomLevel;
}
void LocationZoomer::Update()
{
if (mCurrentProgress < 1)
{
mCurrentProgress = ofClamp(mCurrentProgress + ofGetLastFrameTime() * mSpeed, 0, 1);
float ease;
if (mInVanityPanningMode) //ease in/out
ease = mCurrentProgress < 0.5 ? 2 * mCurrentProgress * mCurrentProgress : 1 - pow(-2 * mCurrentProgress + 2, 2) / 2;
else //ease out
ease = -1 * mCurrentProgress * (mCurrentProgress - 2);
gDrawScale = ofLerp(mStart.mZoomLevel, mDestination.mZoomLevel, ease);
ofVec2f offset;
offset.x = ofLerp(mStart.mOffset.x, mDestination.mOffset.x, ease);
offset.y = ofLerp(mStart.mOffset.y, mDestination.mOffset.y, ease);
TheSynth->SetDrawOffset(offset);
if (mInVanityPanningMode && mCurrentProgress >= 1)
PickNewVanityPanningDestination();
}
}
void LocationZoomer::OnKeyPressed(char key)
{
if (key < CHAR_MAX && juce::CharacterFunctions::isDigit(key) && key != '0') // 0 is reserved
{
if (GetKeyModifiers() == kModifier_Command)
WriteCurrentLocation(key);
else if (GetKeyModifiers() == kModifier_Shift)
MoveToLocation(key);
}
}
void LocationZoomer::WriteCurrentLocation(char key)
{
mLocations[key].mZoomLevel = gDrawScale;
mLocations[key].mOffset = TheSynth->GetDrawOffset();
}
bool LocationZoomer::HasLocation(char key)
{
return mLocations.find(key) != mLocations.end();
}
void LocationZoomer::MoveToLocation(char key)
{
if (mLocations.count(key) > 0)
{
mStart.mZoomLevel = gDrawScale;
mStart.mOffset = TheSynth->GetDrawOffset();
mDestination = mLocations[key];
mCurrentProgress = 0;
mSpeed = 2;
}
}
void LocationZoomer::GoHome()
{
mStart.mZoomLevel = gDrawScale;
mStart.mOffset = TheSynth->GetDrawOffset();
mDestination = mHome;
mCurrentProgress = 0;
mSpeed = 2;
}
void LocationZoomer::EnterVanityPanningMode()
{
mInVanityPanningMode = true;
PickNewVanityPanningDestination();
}
void LocationZoomer::ExitVanityPanningMode()
{
mInVanityPanningMode = false;
mCurrentProgress = 1;
}
void LocationZoomer::PickNewVanityPanningDestination()
{
std::vector<IDrawableModule*> modules;
TheSynth->GetAllModules(modules);
ofVec2f allModulesCenter;
for (int i = 0; i < (int)modules.size(); ++i)
{
if (modules[i]->IsShowing() && !modules[i]->Minimized())
{
ofVec2f modulePos = modules[i]->GetRect().getCenter();
allModulesCenter += modulePos / (int)modules.size();
}
}
const int kRandomChoices = 3;
ofVec2f randomModulesCenter;
int attempts = 0;
for (int i = 0; i < kRandomChoices; ++i)
{
int choice = gRandom() % ((int)modules.size());
if (modules[choice]->IsShowing() && !modules[choice]->Minimized())
{
ofVec2f modulePos = modules[choice]->GetRect().getCenter();
randomModulesCenter += modulePos / kRandomChoices;
}
else
{
--i; //try again
}
++attempts;
if (attempts > 100) //avoid infinite loop if all modules are hidden/minimized
break;
}
ofVec2f center = allModulesCenter * .5f + randomModulesCenter * .5f;
float newScale = ofRandom(1, 1.5f) * UserPrefs.zoom.Get();
mStart.mZoomLevel = gDrawScale;
mStart.mOffset = TheSynth->GetDrawOffset();
mDestination.mZoomLevel = newScale;
mDestination.mOffset = (center * -1) + ofVec2f(ofGetWidth(), ofGetHeight()) / newScale * .5f;
mCurrentProgress = 0;
mSpeed = ofRandom(.03f, .1f);
}
ofxJSONElement LocationZoomer::GetSaveData()
{
ofxJSONElement save;
save.resize((unsigned int)mLocations.size());
int i = 0;
for (auto iter = mLocations.begin(); iter != mLocations.end(); ++iter)
{
const Location& loc = iter->second;
save[i]["shortcut"] = iter->first;
save[i]["zoomlevel"] = loc.mZoomLevel;
save[i]["offset_x"] = loc.mOffset.x;
save[i]["offset_y"] = loc.mOffset.y;
++i;
}
return save;
}
void LocationZoomer::LoadFromSaveData(const ofxJSONElement& saveData)
{
mLocations.clear();
for (int i = 0; i < saveData.size(); ++i)
{
try
{
int shortcut = saveData[i]["shortcut"].asInt();
mLocations[shortcut].mZoomLevel = saveData[i]["zoomlevel"].asDouble();
mLocations[shortcut].mOffset.set(saveData[i]["offset_x"].asDouble(),
saveData[i]["offset_y"].asDouble());
}
catch (Json::LogicError& e)
{
TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error);
}
}
MoveToLocation(-1);
mCurrentProgress = .999f;
}
``` | /content/code_sandbox/Source/LocationZoomer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.