diff options
author | Damien Zammit <damien@zamaudio.com> | 2015-06-14 01:49:35 +1000 |
---|---|---|
committer | Damien Zammit <damien@zamaudio.com> | 2015-06-14 01:49:35 +1000 |
commit | 2e2cd2404c5f4f86fb76dedb971051951148a6d7 (patch) | |
tree | 78b96c034bc80f0bc99e24ee8a059a83c9ecc416 | |
parent | 001a7db3a6df7d5c1d5c3ba1b2215d2212af4eee (diff) | |
parent | 9038ee0032e29a69993de1f9baaac11ace73207d (diff) |
Merge pull request #30 from falkTX/master
Update to new DPF and convert to submodule
201 files changed, 1393 insertions, 43517 deletions
@@ -1,4 +1,5 @@ *.a +*.d *.o *.exe diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..608b657 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "dpf"] + path = dpf + url = git://github.com/DISTRHO/DPF @@ -8,23 +8,31 @@ VERSION = $(shell cat .version) PLUGINS=ZamComp ZamCompX2 ZaMultiComp ZamTube ZamEQ2 ZamAutoSat ZamGEQ31 ZamGEQ31X2 ZaMultiCompX2 ZamGate ZamGateX2 #ZamPiano ZamSFZ ZamChild670 +include Makefile.mk + +# -------------------------------------------------------------- + all: libs $(PLUGINS) gen -libs: FORCE - $(MAKE) -C libs/dgl +libs: +ifeq ($(HAVE_DGL),true) + $(MAKE) -C dpf/dgl +endif -gen: plugins libs/lv2_ttl_generator - @./libs/generate-ttl.sh +gen: $(PLUGINS) dpf/utils/lv2_ttl_generator + @$(CURDIR)/dpf/utils/generate-ttl.sh ifeq ($(MACOS),true) - @./libs/generate-vst-bundles.sh + @$(CURDIR)/dpf/utils/generate-vst-bundles.sh endif -libs/lv2_ttl_generator: - $(MAKE) -C libs/lv2-ttl-generator +dpf/utils/lv2_ttl_generator: + $(MAKE) -C dpf/utils/lv2-ttl-generator $(PLUGINS): libs $(MAKE) -C plugins/$@ +# -------------------------------------------------------------- + install: all install -d $(DESTDIR)$(PREFIX)/$(LIBDIR)/ladspa \ $(DESTDIR)$(PREFIX)/$(LIBDIR)/lv2 \ @@ -47,16 +55,18 @@ uninstall: rm -f $(DESTDIR)$(PREFIX)/$(BINDIR)/"$$plugin" ; \ done +# -------------------------------------------------------------- -plugins: FORCE - - -clean: FORCE +clean: for plugin in $(PLUGINS); do \ - $(MAKE) PREFIX="$(PREFIX)" LIBDIR="$(LIBDIR)" -C plugins/"$$plugin" clean; \ + $(MAKE) -C plugins/"$$plugin" clean; \ done - $(MAKE) clean -C libs/dgl - $(MAKE) clean -C libs/lv2-ttl-generator +ifeq ($(HAVE_DGL),true) + $(MAKE) clean -C dpf/dgl +endif + $(MAKE) clean -C dpf/utils/lv2-ttl-generator + +# -------------------------------------------------------------- .version: FORCE if test -d .git; then \ diff --git a/Makefile.mk b/Makefile.mk index 30e6703..7588326 100644 --- a/Makefile.mk +++ b/Makefile.mk @@ -4,6 +4,7 @@ # Created by falkTX # +AR ?= ar CC ?= gcc CXX ?= g++ @@ -19,38 +20,41 @@ endif endif # -------------------------------------------------------------- -# Common build and link flags +# Set build and link flags -BASE_FLAGS = -Wall -Wextra -pipe -Wno-switch -Wno-reorder -BASE_OPTS = -O2 -ffast-math -fdata-sections -ffunction-sections -ifneq ($(NOOPT),true) -BASE_OPTS += -mtune=generic -msse -msse2 -mfpmath=sse +BASE_FLAGS = -Wall -Wextra -pipe +BASE_OPTS = -O2 -ffast-math -mtune=generic -msse -msse2 -fdata-sections -ffunction-sections + +ifneq ($(MACOS),true) +# MacOS doesn't support this +BASE_OPTS += -mfpmath=sse endif -LINK_OPTS = -fdata-sections -ffunction-sections -Wl,-O1 -Wl,--as-needed -Wl,--gc-sections -Wl,--strip-all ifeq ($(MACOS),true) # MacOS linker flags LINK_OPTS = -fdata-sections -ffunction-sections -Wl,-dead_strip -Wl,-dead_strip_dylibs +else +# Common linker flags +LINK_OPTS = -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,-O1 -Wl,--as-needed -Wl,--strip-all endif ifeq ($(RASPPI),true) -# Raspberry-Pi flags -BASE_OPTS = -O2 -ffast-math -ifneq ($(NOOPT),true) -BASE_OPTS += -march=armv6 -mfpu=vfp -mfloat-abi=hard -endif +# Raspberry-Pi optimization flags +BASE_OPTS = -O2 -ffast-math -march=armv6 -mfpu=vfp -mfloat-abi=hard LINK_OPTS = -Wl,-O1 -Wl,--as-needed -Wl,--strip-all endif ifeq ($(PANDORA),true) -# OpenPandora flags -BASE_OPTS = -O2 -ffast-math -ifneq ($(NOOPT),true) -BASE_OPTS += -march=armv7-a -mcpu=cortex-a8 -mtune=cortex-a8 -mfpu=neon -mfloat-abi=softfp -endif +# OpenPandora optimization flags +BASE_OPTS = -O2 -ffast-math -march=armv7-a -mcpu=cortex-a8 -mtune=cortex-a8 -mfpu=neon -mfloat-abi=softfp LINK_OPTS = -Wl,-O1 -Wl,--as-needed -Wl,--strip-all endif +ifeq ($(NOOPT),true) +# No optimization flags +BASE_OPTS = -O2 -ffast-math -fdata-sections -ffunction-sections +endif + ifneq ($(WIN32),true) # not needed for Windows BASE_FLAGS += -fPIC -DPIC @@ -75,27 +79,27 @@ LINK_FLAGS = $(LINK_OPTS) $(LDFLAGS) endif # -------------------------------------------------------------- -# Check for required libs +# Check for optional libs ifeq ($(LINUX),true) -ifneq ($(shell pkg-config --exists jack && echo true),true) -$(error JACK missing, cannot continue) -endif -ifneq ($(shell pkg-config --exists gl && echo true),true) -$(error OpenGL missing, cannot continue) -endif -ifneq ($(shell pkg-config --exists x11 && echo true),true) -$(error X11 missing, cannot continue) +HAVE_DGL = $(shell pkg-config --exists gl x11 && echo true) +HAVE_JACK = $(shell pkg-config --exists jack && echo true) +HAVE_LIBLO = $(shell pkg-config --exists liblo && echo true) endif + +ifeq ($(MACOS),true) +HAVE_DGL = true endif -ifneq ($(shell pkg-config --exists liblo && echo true),true) -$(error liblo missing, cannot continue) +ifeq ($(WIN32),true) +HAVE_DGL = true endif # -------------------------------------------------------------- # Set libs stuff +ifeq ($(HAVE_DGL),true) + ifeq ($(LINUX),true) DGL_FLAGS = $(shell pkg-config --cflags gl x11) DGL_LIBS = $(shell pkg-config --libs gl x11) @@ -109,17 +113,26 @@ ifeq ($(WIN32),true) DGL_LIBS = -lopengl32 -lgdi32 endif +endif # HAVE_DGL + +# -------------------------------------------------------------- +# Set app extension + +ifeq ($(WIN32),true) +APP_EXT = .exe +endif + # -------------------------------------------------------------- -# Set extension +# Set shared lib extension -EXT = so +LIB_EXT = .so ifeq ($(MACOS),true) -EXT = dylib +LIB_EXT = .dylib endif ifeq ($(WIN32),true) -EXT = dll +LIB_EXT = .dll endif # -------------------------------------------------------------- diff --git a/dpf b/dpf new file mode 160000 +Subproject 2f3950d633cbce20f0fd588c8c745c90d9b82b8 diff --git a/libs/dgl/App.hpp b/libs/dgl/App.hpp deleted file mode 100644 index 4babf1f..0000000 --- a/libs/dgl/App.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_APP_HPP_INCLUDED -#define DGL_APP_HPP_INCLUDED - -#include "Base.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Forward class names - -class Window; - -// ----------------------------------------------------------------------- - -/** - Base DGL Application class. - - One application instance is required for creating a window. - There's no single/global application instance in DGL, and multiple - windows can share the same app instance. - - In standalone mode an application will automatically quit its - event-loop when all its windows are closed. - */ -class App -{ -public: - /** - Constructor. - */ - App(); - - /** - Destructor. - */ - ~App(); - - /** - Idle function. - This runs the application event-loop once. - */ - void idle(); - - /** - Run the application event-loop until all Windows are closed. - idle() is called at regular intervals. - @note: This function is meant for standalones only, *never* call this from plugins. - */ - void exec(); - - /** - Quit the application. - This stops the event-loop and closes all Windows. - */ - void quit(); - - /** - Check if the application is about to quit. - Returning true means there's no event-loop running at the moment (or it's just about to stop). - */ - bool isQuiting() const noexcept; - -private: - struct PrivateData; - PrivateData* const pData; - friend class Window; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(App) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_APP_HPP_INCLUDED diff --git a/libs/dgl/Base.hpp b/libs/dgl/Base.hpp deleted file mode 100644 index edefbcf..0000000 --- a/libs/dgl/Base.hpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_BASE_HPP_INCLUDED -#define DGL_BASE_HPP_INCLUDED - -#include "../distrho/extra/d_leakdetector.hpp" -#include "../distrho/extra/d_scopedpointer.hpp" - -// ----------------------------------------------------------------------- -// Define namespace - -#ifndef DGL_NAMESPACE -# define DGL_NAMESPACE DGL -#endif - -#define START_NAMESPACE_DGL namespace DGL_NAMESPACE { -#define END_NAMESPACE_DGL } -#define USE_NAMESPACE_DGL using namespace DGL_NAMESPACE; - -#ifdef DISTRHO_OS_WINDOWS -// ----------------------------------------------------------------------- -// Fix OpenGL includes for Windows, based on glfw code - -#ifndef APIENTRY -# define APIENTRY __stdcall -#endif // APIENTRY - -/* We need WINGDIAPI defined */ -#ifndef WINGDIAPI -# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__) -# define WINGDIAPI __declspec(dllimport) -# elif defined(__LCC__) -# define WINGDIAPI __stdcall -# else -# define WINGDIAPI extern -# endif -# define DGL_WINGDIAPI_DEFINED -#endif // WINGDIAPI - -/* Some <GL/glu.h> files also need CALLBACK defined */ -#ifndef CALLBACK -# if defined(_MSC_VER) -# if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) -# define CALLBACK __stdcall -# else -# define CALLBACK -# endif -# else -# define CALLBACK __stdcall -# endif -# define DGL_CALLBACK_DEFINED -#endif // CALLBACK - -/* Most GL/glu.h variants on Windows need wchar_t */ -#include <cstddef> - -#endif // DISTRHO_OS_WINDOWS - -// ----------------------------------------------------------------------- -// OpenGL includes - -#ifdef DISTRHO_OS_MAC -# include "OpenGL/gl.h" -#else -# define GL_GLEXT_PROTOTYPES -# include "GL/gl.h" -# include "GL/glext.h" -#endif - -// ----------------------------------------------------------------------- -// Missing OpenGL defines - -#if defined(GL_BGR_EXT) && ! defined(GL_BGR) -# define GL_BGR GL_BGR_EXT -#endif - -#if defined(GL_BGRA_EXT) && ! defined(GL_BGRA) -# define GL_BGRA GL_BGRA_EXT -#endif - -#ifndef GL_CLAMP_TO_BORDER -# define GL_CLAMP_TO_BORDER 0x812D -#endif - -#ifdef DISTRHO_OS_WINDOWS -// ----------------------------------------------------------------------- -// Fix OpenGL includes for Windows, based on glfw code - -#ifdef DGL_WINGDIAPI_DEFINED -# undef WINGDIAPI -# undef DGL_WINGDIAPI_DEFINED -#endif - -#ifdef DGL_CALLBACK_DEFINED -# undef CALLBACK -# undef DGL_CALLBACK_DEFINED -#endif - -#endif // DISTRHO_OS_WINDOWS - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Base DGL enums - -/** - Convenience symbols for ASCII control characters. - */ -enum Char { - CHAR_BACKSPACE = 0x08, - CHAR_ESCAPE = 0x1B, - CHAR_DELETE = 0x7F -}; - -/** - Keyboard modifier flags. - */ -enum Modifier { - MODIFIER_SHIFT = 1 << 0, /**< Shift key */ - MODIFIER_CTRL = 1 << 1, /**< Control key */ - MODIFIER_ALT = 1 << 2, /**< Alt/Option key */ - MODIFIER_SUPER = 1 << 3 /**< Mod4/Command/Windows key */ -}; - -/** - Special (non-Unicode) keyboard keys. - */ -enum Key { - KEY_F1 = 1, - KEY_F2, - KEY_F3, - KEY_F4, - KEY_F5, - KEY_F6, - KEY_F7, - KEY_F8, - KEY_F9, - KEY_F10, - KEY_F11, - KEY_F12, - KEY_LEFT, - KEY_UP, - KEY_RIGHT, - KEY_DOWN, - KEY_PAGE_UP, - KEY_PAGE_DOWN, - KEY_HOME, - KEY_END, - KEY_INSERT, - KEY_SHIFT, - KEY_CTRL, - KEY_ALT, - KEY_SUPER -}; - -// ----------------------------------------------------------------------- -// Base DGL classes - -/** - Idle callback. - */ -class IdleCallback -{ -public: - virtual ~IdleCallback() {} - virtual void idleCallback() = 0; -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_BASE_HPP_INCLUDED diff --git a/libs/dgl/Color.hpp b/libs/dgl/Color.hpp deleted file mode 100644 index d47f354..0000000 --- a/libs/dgl/Color.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_COLOR_HPP_INCLUDED -#define DGL_COLOR_HPP_INCLUDED - -#include "Base.hpp" - -struct NVGcolor; - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -// TODO: create color from "#333" and "#112233" like strings - -/** - A color made from red, green, blue and alpha floating-point values in [0..1] range. -*/ -struct Color { - /** - Direct access to the color values. - */ - union { - float rgba[4]; - struct { float red, green, blue, alpha; }; - }; - - /** - Create black color. - */ - Color() noexcept; - - /** - Create a color from red, green, blue and alpha numeric values. - Values must be in [0..255] range. - */ - Color(int red, int green, int blue, int alpha = 255) noexcept; - - /** - Create a color from red, green, blue and alpha floating-point values. - Values must in [0..1] range. - */ - Color(float red, float green, float blue, float alpha = 1.0f) noexcept; - - /** - Create a color by copying another color. - */ - Color(const Color& color) noexcept; - Color& operator=(const Color& color) noexcept; - - /** - Create a color by linearly interpolating two other colors. - */ - Color(const Color& color1, const Color& color2, float u) noexcept; - - /** - Create a color specified by hue, saturation and lightness. - Values must in [0..1] range. - */ - static Color fromHSL(float hue, float saturation, float lightness, float alpha = 1.0f); - - /** - Create a color from a HTML string like "#333" or "#112233". - */ - static Color fromHTML(const char* rgb, float alpha = 1.0f); - - /** - Linearly interpolate this color against another. - */ - void interpolate(const Color& other, float u) noexcept; - - /** - Check if this color matches another. - @note: Comparison is forced within 8-bit color values. - */ - bool isEqual(const Color& color, bool withAlpha = true) noexcept; - bool isNotEqual(const Color& color, bool withAlpha = true) noexcept; - bool operator==(const Color& color) noexcept; - bool operator!=(const Color& color) noexcept; - - /** - Fix color bounds if needed. - */ - void fixBounds() noexcept; - - /** - @internal - Needed for NanoVG compatibility. - */ - Color(const NVGcolor&) noexcept; - operator NVGcolor() const noexcept; -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_COLOR_HPP_INCLUDED diff --git a/libs/dgl/Geometry.hpp b/libs/dgl/Geometry.hpp deleted file mode 100644 index 725a15e..0000000 --- a/libs/dgl/Geometry.hpp +++ /dev/null @@ -1,750 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_GEOMETRY_HPP_INCLUDED -#define DGL_GEOMETRY_HPP_INCLUDED - -#include "Base.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Forward class names - -template<typename> class Line; -template<typename> class Circle; -template<typename> class Triangle; -template<typename> class Rectangle; - -// ----------------------------------------------------------------------- - -/** - DGL Point class. - - This class describes a single point in space, defined by an X and Y value. - */ -template<typename T> -class Point -{ -public: - /** - Constructor for (0, 0) point. - */ - Point() noexcept; - - /** - Constructor using custom X and Y values. - */ - Point(const T& x, const T& y) noexcept; - - /** - Constructor using another Point class values. - */ - Point(const Point<T>& pos) noexcept; - - /** - Get X value. - */ - const T& getX() const noexcept; - - /** - Get Y value. - */ - const T& getY() const noexcept; - - /** - Set X value to @a x. - */ - void setX(const T& x) noexcept; - - /** - Set Y value to @a y. - */ - void setY(const T& y) noexcept; - - /** - Set X and Y values to @a x and @a y respectively. - */ - void setPos(const T& x, const T& y) noexcept; - - /** - Set X and Y values according to @a pos. - */ - void setPos(const Point<T>& pos) noexcept; - - /** - Move this point by @a x and @a y values. - */ - void moveBy(const T& x, const T& y) noexcept; - - /** - Move this point by @a pos. - */ - void moveBy(const Point<T>& pos) noexcept; - - /** - Return true if point is (0, 0). - */ - bool isZero() const noexcept; - - /** - Return true if point is not (0, 0). - */ - bool isNotZero() const noexcept; - - Point<T> operator+(const Point<T>& pos) noexcept; - Point<T> operator-(const Point<T>& pos) noexcept; - Point<T>& operator=(const Point<T>& pos) noexcept; - Point<T>& operator+=(const Point<T>& pos) noexcept; - Point<T>& operator-=(const Point<T>& pos) noexcept; - bool operator==(const Point<T>& pos) const noexcept; - bool operator!=(const Point<T>& pos) const noexcept; - -private: - T fX, fY; - template<typename> friend class Line; - template<typename> friend class Circle; - template<typename> friend class Triangle; - template<typename> friend class Rectangle; -}; - -// ----------------------------------------------------------------------- - -/** - DGL Size class. - - This class describes a size, defined by a width and height value. - */ -template<typename T> -class Size -{ -public: - /** - Constructor for null size (0x0). - */ - Size() noexcept; - - /** - Constructor using custom width and height values. - */ - Size(const T& width, const T& height) noexcept; - - /** - Constructor using another Size class values. - */ - Size(const Size<T>& size) noexcept; - - /** - Get width. - */ - const T& getWidth() const noexcept; - - /** - Get height. - */ - const T& getHeight() const noexcept; - - /** - Set width. - */ - void setWidth(const T& width) noexcept; - - /** - Set height. - */ - void setHeight(const T& height) noexcept; - - /** - Set size to @a width and @a height. - */ - void setSize(const T& width, const T& height) noexcept; - - /** - Set size. - */ - void setSize(const Size<T>& size) noexcept; - - /** - Grow size by @a multiplier. - */ - void growBy(double multiplier) noexcept; - - /** - Shrink size by @a divider. - */ - void shrinkBy(double divider) noexcept; - - /** - Return true if size is null (0x0). - An null size is also invalid. - */ - bool isNull() const noexcept; - - /** - Return true if size is not null (0x0). - A non-null size is still invalid if its width or height is negative. - */ - bool isNotNull() const noexcept; - - /** - Return true if size is valid (width and height are higher than zero). - */ - bool isValid() const noexcept; - - /** - Return true if size is invalid (width or height are lower or equal to zero). - An invalid size might not be null under some circumstances. - */ - bool isInvalid() const noexcept; - - Size<T> operator+(const Size<T>& size) noexcept; - Size<T> operator-(const Size<T>& size) noexcept; - Size<T>& operator=(const Size<T>& size) noexcept; - Size<T>& operator+=(const Size<T>& size) noexcept; - Size<T>& operator-=(const Size<T>& size) noexcept; - Size<T>& operator*=(double m) noexcept; - Size<T>& operator/=(double d) noexcept; - bool operator==(const Size<T>& size) const noexcept; - bool operator!=(const Size<T>& size) const noexcept; - -private: - T fWidth, fHeight; - template<typename> friend class Rectangle; -}; - -// ----------------------------------------------------------------------- - -/** - DGL Line class. - - This class describes a line, defined by two points. - */ -template<typename T> -class Line -{ -public: - /** - Constructor for a null line ([0,0] to [0,0]). - */ - Line() noexcept; - - /** - Constructor using custom start X, start Y, end X and end Y values. - */ - Line(const T& startX, const T& startY, const T& endX, const T& endY) noexcept; - - /** - Constructor using custom start X, start Y and end pos values. - */ - Line(const T& startX, const T& startY, const Point<T>& endPos) noexcept; - - /** - Constructor using custom start pos, end X and end Y values. - */ - Line(const Point<T>& startPos, const T& endX, const T& endY) noexcept; - - /** - Constructor using custom start and end pos values. - */ - Line(const Point<T>& startPos, const Point<T>& endPos) noexcept; - - /** - Constructor using another Line class values. - */ - Line(const Line<T>& line) noexcept; - - /** - Get start X value. - */ - const T& getStartX() const noexcept; - - /** - Get start Y value. - */ - const T& getStartY() const noexcept; - - /** - Get end X value. - */ - const T& getEndX() const noexcept; - - /** - Get end Y value. - */ - const T& getEndY() const noexcept; - - /** - Get start position. - */ - const Point<T>& getStartPos() const noexcept; - - /** - Get end position. - */ - const Point<T>& getEndPos() const noexcept; - - /** - Set start X value to @a x. - */ - void setStartX(const T& x) noexcept; - - /** - Set start Y value to @a y. - */ - void setStartY(const T& y) noexcept; - - /** - Set start X and Y values to @a x and @a y respectively. - */ - void setStartPos(const T& x, const T& y) noexcept; - - /** - Set start X and Y values according to @a pos. - */ - void setStartPos(const Point<T>& pos) noexcept; - - /** - Set end X value to @a x. - */ - void setEndX(const T& x) noexcept; - - /** - Set end Y value to @a y. - */ - void setEndY(const T& y) noexcept; - - /** - Set end X and Y values to @a x and @a y respectively. - */ - void setEndPos(const T& x, const T& y) noexcept; - - /** - Set end X and Y values according to @a pos. - */ - void setEndPos(const Point<T>& pos) noexcept; - - /** - Move this line by @a x and @a y values. - */ - void moveBy(const T& x, const T& y) noexcept; - - /** - Move this line by @a pos. - */ - void moveBy(const Point<T>& pos) noexcept; - - /** - Draw this line using the current OpenGL state. - */ - void draw(); - - /** - Return true if line is null (start and end pos are equal). - */ - bool isNull() const noexcept; - - /** - Return true if line is not null (start and end pos are different). - */ - bool isNotNull() const noexcept; - - Line<T>& operator=(const Line<T>& line) noexcept; - bool operator==(const Line<T>& line) const noexcept; - bool operator!=(const Line<T>& line) const noexcept; - -private: - Point<T> fPosStart, fPosEnd; -}; - -// ----------------------------------------------------------------------- - -/** - DGL Circle class. - - This class describes a circle, defined by position, size and a minimum of 3 segments. - - TODO: report if circle starts at top-left, bottom-right or center. - and size grows from which point? - */ -template<typename T> -class Circle -{ -public: - /** - Constructor for a null circle. - */ - Circle() noexcept; - - /** - Constructor using custom X, Y and size values. - */ - Circle(const T& x, const T& y, const float size, const uint numSegments = 300); - - /** - Constructor using custom position and size values. - */ - Circle(const Point<T>& pos, const float size, const uint numSegments = 300); - - /** - Constructor using another Circle class values. - */ - Circle(const Circle<T>& cir) noexcept; - - /** - Get X value. - */ - const T& getX() const noexcept; - - /** - Get Y value. - */ - const T& getY() const noexcept; - - /** - Get position. - */ - const Point<T>& getPos() const noexcept; - - /** - Set X value to @a x. - */ - void setX(const T& x) noexcept; - - /** - Set Y value to @a y. - */ - void setY(const T& y) noexcept; - - /** - Set X and Y values to @a x and @a y respectively. - */ - void setPos(const T& x, const T& y) noexcept; - - /** - Set X and Y values according to @a pos. - */ - void setPos(const Point<T>& pos) noexcept; - - /** - Get size. - */ - float getSize() const noexcept; - - /** - Set size. - @note Must always be > 0 - */ - void setSize(const float size) noexcept; - - /** - Get the current number of line segments that make this circle. - */ - uint getNumSegments() const noexcept; - - /** - Set the number of line segments that will make this circle. - @note Must always be >= 3 - */ - void setNumSegments(const uint num); - - /** - Draw this circle using the current OpenGL state. - */ - void draw(); - - /** - Draw lines (outline of this circle) using the current OpenGL state. - */ - void drawOutline(); - - Circle<T>& operator=(const Circle<T>& cir) noexcept; - bool operator==(const Circle<T>& cir) const noexcept; - bool operator!=(const Circle<T>& cir) const noexcept; - -private: - Point<T> fPos; - float fSize; - uint fNumSegments; - - // cached values - float fTheta, fCos, fSin; - - void _draw(const bool outline); -}; - -// ----------------------------------------------------------------------- - -/** - DGL Triangle class. - - This class describes a triangle, defined by 3 points. - */ -template<typename T> -class Triangle -{ -public: - /** - Constructor for a null triangle. - */ - Triangle() noexcept; - - /** - Constructor using custom X and Y values. - */ - Triangle(const T& x1, const T& y1, const T& x2, const T& y2, const T& x3, const T& y3) noexcept; - - /** - Constructor using custom position values. - */ - Triangle(const Point<T>& pos1, const Point<T>& pos2, const Point<T>& pos3) noexcept; - - /** - Constructor using another Triangle class values. - */ - Triangle(const Triangle<T>& tri) noexcept; - - /** - Draw this triangle using the current OpenGL state. - */ - void draw(); - - /** - Draw lines (outline of this triangle) using the current OpenGL state. - */ - void drawOutline(); - - /** - Return true if triangle is null (all its points are equal). - An null triangle is also invalid. - */ - bool isNull() const noexcept; - - /** - Return true if triangle is not null (one its points is different from the others). - A non-null triangle is still invalid if two of its points are equal. - */ - bool isNotNull() const noexcept; - - /** - Return true if triangle is valid (all its points are different). - */ - bool isValid() const noexcept; - - /** - Return true if triangle is invalid (one or two of its points are equal). - An invalid triangle might not be null under some circumstances. - */ - bool isInvalid() const noexcept; - - Triangle<T>& operator=(const Triangle<T>& tri) noexcept; - bool operator==(const Triangle<T>& tri) const noexcept; - bool operator!=(const Triangle<T>& tri) const noexcept; - -private: - Point<T> fPos1, fPos2, fPos3; - - void _draw(const bool outline); -}; - -// ----------------------------------------------------------------------- - -/** - DGL Rectangle class. - - This class describes a rectangle, defined by a starting point and a size. - */ -template<typename T> -class Rectangle -{ -public: - /** - Constructor for a null rectangle. - */ - Rectangle() noexcept; - - /** - Constructor using custom X, Y, width and height values. - */ - Rectangle(const T& x, const T& y, const T& width, const T& height) noexcept; - - /** - Constructor using custom X, Y and size values. - */ - Rectangle(const T& x, const T& y, const Size<T>& size) noexcept; - - /** - Constructor using custom pos, width and height values. - */ - Rectangle(const Point<T>& pos, const T& width, const T& height) noexcept; - - /** - Constructor using custom position and size. - */ - Rectangle(const Point<T>& pos, const Size<T>& size) noexcept; - - /** - Constructor using another Rectangle class values. - */ - Rectangle(const Rectangle<T>& rect) noexcept; - - /** - Get X value. - */ - const T& getX() const noexcept; - - /** - Get Y value. - */ - const T& getY() const noexcept; - - /** - Get width. - */ - const T& getWidth() const noexcept; - - /** - Get height. - */ - const T& getHeight() const noexcept; - - /** - Get position. - */ - const Point<T>& getPos() const noexcept; - - /** - Get size. - */ - const Size<T>& getSize() const noexcept; - - /** - Set X value as @a x. - */ - void setX(const T& x) noexcept; - - /** - Set Y value as @a y. - */ - void setY(const T& y) noexcept; - - /** - Set X and Y values as @a x and @a y respectively. - */ - void setPos(const T& x, const T& y) noexcept; - - /** - Set X and Y values according to @a pos. - */ - void setPos(const Point<T>& pos) noexcept; - - /** - Move this rectangle by @a x and @a y values. - */ - void moveBy(const T& x, const T& y) noexcept; - - /** - Move this rectangle by @a pos. - */ - void moveBy(const Point<T>& pos) noexcept; - - /** - Set width. - */ - void setWidth(const T& width) noexcept; - - /** - Set height. - */ - void setHeight(const T& height) noexcept; - - /** - Set size using @a width and @a height. - */ - void setSize(const T& width, const T& height) noexcept; - - /** - Set size. - */ - void setSize(const Size<T>& size) noexcept; - - /** - Grow size by @a multiplier. - */ - void growBy(double multiplier) noexcept; - - /** - Shrink size by @a divider. - */ - void shrinkBy(double divider) noexcept; - - /** - Set rectangle using @a pos and @a size. - */ - void setRectangle(const Point<T>& pos, const Size<T>& size) noexcept; - - /** - Set rectangle. - */ - void setRectangle(const Rectangle<T>& rect) noexcept; - - /** - Check if this rectangle contains the point defined by @a X and @a Y. - */ - bool contains(const T& x, const T& y) const noexcept; - - /** - Check if this rectangle contains the point @a pos. - */ - bool contains(const Point<T>& pos) const noexcept; - - /** - Check if this rectangle contains X. - */ - bool containsX(const T& x) const noexcept; - - /** - Check if this rectangle contains Y. - */ - bool containsY(const T& y) const noexcept; - - /** - Draw this rectangle using the current OpenGL state. - */ - void draw(); - - /** - Draw lines (outline of this rectangle) using the current OpenGL state. - */ - void drawOutline(); - - Rectangle<T>& operator=(const Rectangle<T>& rect) noexcept; - Rectangle<T>& operator*=(double m) noexcept; - Rectangle<T>& operator/=(double d) noexcept; - bool operator==(const Rectangle<T>& size) const noexcept; - bool operator!=(const Rectangle<T>& size) const noexcept; - -private: - Point<T> fPos; - Size<T> fSize; - - void _draw(const bool outline); -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_GEOMETRY_HPP_INCLUDED diff --git a/libs/dgl/Image.hpp b/libs/dgl/Image.hpp deleted file mode 100644 index ab0e648..0000000 --- a/libs/dgl/Image.hpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_HPP_INCLUDED -#define DGL_IMAGE_HPP_INCLUDED - -#include "Geometry.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -/** - Base DGL Image class. - - This is an Image class that handles raw image data in pixels. - You can init the image data on the contructor or later on by calling loadFromMemory(). - - To generate raw data useful for this class see the utils/png2rgba.py script. - Be careful when using a PNG without alpha channel, for those the format is 'GL_BGR' - instead of the default 'GL_BGRA'. - - Images are drawn on screen via 2D textures. - */ -class Image -{ -public: - /** - Constructor for a null Image. - */ - Image(); - - /** - Constructor using raw image data. - @note: @a rawData must remain valid for the lifetime of this Image. - */ - Image(const char* const rawData, const uint width, const uint height, const GLenum format = GL_BGRA, const GLenum type = GL_UNSIGNED_BYTE); - - /** - Constructor using raw image data. - @note: @a rawData must remain valid for the lifetime of this Image. - */ - Image(const char* const rawData, const Size<uint>& size, const GLenum format = GL_BGRA, const GLenum type = GL_UNSIGNED_BYTE); - - /** - Constructor using another image data. - */ - Image(const Image& image); - - /** - Destructor. - */ - ~Image(); - - /** - Load image data from memory. - @note: @a rawData must remain valid for the lifetime of this Image. - */ - void loadFromMemory(const char* const rawData, const uint width, const uint height, const GLenum format = GL_BGRA, const GLenum type = GL_UNSIGNED_BYTE) noexcept; - - /** - Load image data from memory. - @note: @a rawData must remain valid for the lifetime of this Image. - */ - void loadFromMemory(const char* const rawData, const Size<uint>& size, const GLenum format = GL_BGRA, const GLenum type = GL_UNSIGNED_BYTE) noexcept; - - /** - Check if this image is valid. - */ - bool isValid() const noexcept; - - /** - Get width. - */ - uint getWidth() const noexcept; - - /** - Get height. - */ - uint getHeight() const noexcept; - - /** - Get size. - */ - const Size<uint>& getSize() const noexcept; - - /** - Get the raw image data. - */ - const char* getRawData() const noexcept; - - /** - Get the image format. - */ - GLenum getFormat() const noexcept; - - /** - Get the image type. - */ - GLenum getType() const noexcept; - - /** - Draw this image at (0, 0) point. - */ - void draw(); - - /** - Draw this image at (x, y) point. - */ - void drawAt(const int x, const int y); - - /** - Draw this image at position @a pos. - */ - void drawAt(const Point<int>& pos); - - Image& operator=(const Image& image) noexcept; - bool operator==(const Image& image) const noexcept; - bool operator!=(const Image& image) const noexcept; - -private: - const char* fRawData; - Size<uint> fSize; - GLenum fFormat; - GLenum fType; - GLuint fTextureId; - bool fIsReady; -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_HPP_INCLUDED diff --git a/libs/dgl/ImageAboutWindow.hpp b/libs/dgl/ImageAboutWindow.hpp deleted file mode 100644 index 2ffc0de..0000000 --- a/libs/dgl/ImageAboutWindow.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_ABOUT_WINDOW_HPP_INCLUDED -#define DGL_IMAGE_ABOUT_WINDOW_HPP_INCLUDED - -#include "Image.hpp" -#include "Widget.hpp" -#include "Window.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class ImageAboutWindow : public Window, - public Widget -{ -public: - explicit ImageAboutWindow(Window& parent, const Image& image = Image()); - explicit ImageAboutWindow(Widget* widget, const Image& image = Image()); - - void setImage(const Image& image); - -protected: - void onDisplay() override; - bool onKeyboard(const KeyboardEvent&) override; - bool onMouse(const MouseEvent&) override; - void onReshape(uint width, uint height) override; - -private: - Image fImgBackground; - - DISTRHO_DECLARE_NON_COPY_CLASS(ImageAboutWindow) - //DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ImageAboutWindow) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_ABOUT_WINDOW_HPP_INCLUDED diff --git a/libs/dgl/ImageButton.hpp b/libs/dgl/ImageButton.hpp deleted file mode 100644 index a400961..0000000 --- a/libs/dgl/ImageButton.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_BUTTON_HPP_INCLUDED -#define DGL_IMAGE_BUTTON_HPP_INCLUDED - -#include "Image.hpp" -#include "Widget.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class ImageButton : public Widget -{ -public: - class Callback - { - public: - virtual ~Callback() {} - virtual void imageButtonClicked(ImageButton* imageButton, int button) = 0; - }; - - explicit ImageButton(Window& parent, const Image& image) noexcept; - explicit ImageButton(Window& parent, const Image& imageNormal, const Image& imageHover, const Image& imageDown) noexcept; - explicit ImageButton(Widget* widget, const Image& image) noexcept; - explicit ImageButton(Widget* widget, const Image& imageNormal, const Image& imageHover, const Image& imageDown) noexcept; - explicit ImageButton(const ImageButton& imageButton) noexcept; - ImageButton& operator=(const ImageButton& imageButton) noexcept; - - void setCallback(Callback* callback) noexcept; - -protected: - void onDisplay() override; - bool onMouse(const MouseEvent&) override; - bool onMotion(const MotionEvent&) override; - -private: - Image fImageNormal; - Image fImageHover; - Image fImageDown; - Image* fCurImage; - int fCurButton; - - Callback* fCallback; - - DISTRHO_LEAK_DETECTOR(ImageButton) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_BUTTON_HPP_INCLUDED diff --git a/libs/dgl/ImageKnob.hpp b/libs/dgl/ImageKnob.hpp deleted file mode 100644 index 2dd2669..0000000 --- a/libs/dgl/ImageKnob.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_KNOB_HPP_INCLUDED -#define DGL_IMAGE_KNOB_HPP_INCLUDED - -#include "Image.hpp" -#include "Widget.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class ImageKnob : public Widget -{ -public: - enum Orientation { - Horizontal, - Vertical - }; - - class Callback - { - public: - virtual ~Callback() {} - virtual void imageKnobDragStarted(ImageKnob* imageKnob) = 0; - virtual void imageKnobDragFinished(ImageKnob* imageKnob) = 0; - virtual void imageKnobValueChanged(ImageKnob* imageKnob, float value) = 0; - }; - - explicit ImageKnob(Window& parent, const Image& image, Orientation orientation = Vertical) noexcept; - explicit ImageKnob(Widget* widget, const Image& image, Orientation orientation = Vertical) noexcept; - explicit ImageKnob(const ImageKnob& imageKnob); - ImageKnob& operator=(const ImageKnob& imageKnob); - ~ImageKnob() override; - - float getValue() const noexcept; - - void setDefault(float def) noexcept; - void setRange(float min, float max) noexcept; - void setStep(float step) noexcept; - void setValue(float value, bool sendCallback = false) noexcept; - void setUsingLogScale(bool yesNo) noexcept; - - void setCallback(Callback* callback) noexcept; - void setOrientation(Orientation orientation) noexcept; - void setRotationAngle(int angle); - -protected: - void onDisplay() override; - bool onMouse(const MouseEvent&) override; - bool onMotion(const MotionEvent&) override; - bool onScroll(const ScrollEvent&) override; - -private: - Image fImage; - float fMinimum; - float fMaximum; - float fStep; - float fValue; - float fValueDef; - float fValueTmp; - bool fUsingDefault; - bool fUsingLog; - Orientation fOrientation; - - int fRotationAngle; - bool fDragging; - int fLastX; - int fLastY; - - Callback* fCallback; - - bool fIsImgVertical; - uint fImgLayerSize; - uint fImgLayerCount; - bool fIsReady; - GLuint fTextureId; - - float _logscale(float value) const; - float _invlogscale(float value) const; - - DISTRHO_LEAK_DETECTOR(ImageKnob) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_KNOB_HPP_INCLUDED diff --git a/libs/dgl/ImageSlider.hpp b/libs/dgl/ImageSlider.hpp deleted file mode 100644 index e6f2716..0000000 --- a/libs/dgl/ImageSlider.hpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_SLIDER_HPP_INCLUDED -#define DGL_IMAGE_SLIDER_HPP_INCLUDED - -#include "Image.hpp" -#include "Widget.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class ImageSlider : public Widget -{ -public: - class Callback - { - public: - virtual ~Callback() {} - virtual void imageSliderDragStarted(ImageSlider* imageSlider) = 0; - virtual void imageSliderDragFinished(ImageSlider* imageSlider) = 0; - virtual void imageSliderValueChanged(ImageSlider* imageSlider, float value) = 0; - }; - - explicit ImageSlider(Window& parent, const Image& image) noexcept; - explicit ImageSlider(Widget* widget, const Image& image) noexcept; - explicit ImageSlider(const ImageSlider& imageSlider) noexcept; - ImageSlider& operator=(const ImageSlider& imageSlider) noexcept; - - float getValue() const noexcept; - - void setStartPos(const Point<int>& startPos) noexcept; - void setStartPos(int x, int y) noexcept; - void setEndPos(const Point<int>& endPos) noexcept; - void setEndPos(int x, int y) noexcept; - - void setInverted(bool inverted) noexcept; - void setRange(float min, float max) noexcept; - void setStep(float step) noexcept; - void setValue(float value, bool sendCallback = false) noexcept; - - void setCallback(Callback* callback) noexcept; - -protected: - void onDisplay() override; - bool onMouse(const MouseEvent&) override; - bool onMotion(const MotionEvent&) override; - -private: - Image fImage; - float fMinimum; - float fMaximum; - float fStep; - float fValue; - float fValueTmp; - - bool fDragging; - bool fInverted; - int fStartedX; - int fStartedY; - - Callback* fCallback; - - Point<int> fStartPos; - Point<int> fEndPos; - Rectangle<int> fSliderArea; - - void _recheckArea() noexcept; - - // these should not be used - void setAbsoluteX(int) const noexcept {} - void setAbsoluteY(int) const noexcept {} - void setAbsolutePos(int, int) const noexcept {} - void setAbsolutePos(const Point<int>&) const noexcept {} - void setNeedsFullViewport(bool) const noexcept {} - - DISTRHO_LEAK_DETECTOR(ImageSlider) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_SLIDER_HPP_INCLUDED diff --git a/libs/dgl/ImageSwitch.hpp b/libs/dgl/ImageSwitch.hpp deleted file mode 100644 index 172d61c..0000000 --- a/libs/dgl/ImageSwitch.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_IMAGE_SWITCH_HPP_INCLUDED -#define DGL_IMAGE_SWITCH_HPP_INCLUDED - -#include "Image.hpp" -#include "Widget.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class ImageSwitch : public Widget -{ -public: - class Callback - { - public: - virtual ~Callback() {} - virtual void imageSwitchClicked(ImageSwitch* imageButton, bool down) = 0; - }; - - explicit ImageSwitch(Window& parent, const Image& imageNormal, const Image& imageDown) noexcept; - explicit ImageSwitch(Widget* widget, const Image& imageNormal, const Image& imageDown) noexcept; - explicit ImageSwitch(const ImageSwitch& imageSwitch) noexcept; - ImageSwitch& operator=(const ImageSwitch& imageSwitch) noexcept; - - bool isDown() const noexcept; - void setDown(bool down) noexcept; - - void setCallback(Callback* callback) noexcept; - -protected: - void onDisplay() override; - bool onMouse(const MouseEvent&) override; - -private: - Image fImageNormal; - Image fImageDown; - bool fIsDown; - - Callback* fCallback; - - DISTRHO_LEAK_DETECTOR(ImageSwitch) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_IMAGE_SWITCH_HPP_INCLUDED diff --git a/libs/dgl/Makefile b/libs/dgl/Makefile deleted file mode 100644 index 856af9a..0000000 --- a/libs/dgl/Makefile +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/make -f -# Makefile for dgl # -# ---------------- # -# Created by falkTX -# - -include ../../Makefile.mk - -# -------------------------------------------------------------- - -BUILD_C_FLAGS += $(DGL_FLAGS) -I. -BUILD_CXX_FLAGS += $(DGL_FLAGS) -I. -LINK_FLAGS += $(DGL_LIBS) - -# -------------------------------------------------------------- - -OBJS = \ - src/App.cpp.o \ - src/Geometry.cpp.o \ - src/Image.cpp.o \ - src/ImageAboutWindow.cpp.o \ - src/ImageButton.cpp.o \ - src/ImageKnob.cpp.o \ - src/ImageSlider.cpp.o \ - src/ImageSwitch.cpp.o \ - src/NanoVG.cpp.o \ - src/Widget.cpp.o - -ifeq ($(MACOS),true) -OBJS += src/Window.mm.o -else -OBJS += src/Window.cpp.o -endif - -TARGET = ../libdgl.a - -# -------------------------------------------------------------- - -all: $(TARGET) - -# -------------------------------------------------------------- - -../libdgl.a: $(OBJS) - rm -f $@ - $(AR) crs $@ $^ - -../libdgl.dll: $(OBJS) - # -Wl,--output-def,$@.def,--out-implib,$@.a - $(CXX) $^ -shared $(LINK_FLAGS) -o $@ - -../libdgl.dylib: $(OBJS) - $(CXX) $^ -dynamiclib $(LINK_FLAGS) -o $@ - -../libdgl.so: $(OBJS) - $(CXX) $^ -shared $(LINK_FLAGS) -o $@ - -# -------------------------------------------------------------- - -%.c.o: %.c - $(CC) $< $(BUILD_C_FLAGS) -c -o $@ - -%.cpp.o: %.cpp - $(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ - -%.mm.o: %.cpp - $(CXX) $< $(BUILD_CXX_FLAGS) -ObjC++ -c -o $@ - -# -------------------------------------------------------------- - -clean: - rm -f src/*.o src/pugl/*.o src/freetype-gl/*.o ../libdgl.* - -debug: - $(MAKE) DEBUG=true - -# -------------------------------------------------------------- diff --git a/libs/dgl/NanoVG.hpp b/libs/dgl/NanoVG.hpp deleted file mode 100644 index 1135f55..0000000 --- a/libs/dgl/NanoVG.hpp +++ /dev/null @@ -1,799 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_NANO_WIDGET_HPP_INCLUDED -#define DGL_NANO_WIDGET_HPP_INCLUDED - -#include "Color.hpp" -#include "Widget.hpp" - -struct NVGcontext; -struct NVGpaint; - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// NanoImage - -/** - NanoVG Image class. - - This implements NanoVG images as a C++ class where deletion is handled automatically. - Images need to be created within a NanoVG or NanoWidget class. - */ -class NanoImage -{ -public: - /** - Destructor. - */ - ~NanoImage(); - - /** - Get size. - */ - Size<uint> getSize() const noexcept; - - /** - Update image data. - */ - void updateImage(const uchar* const data); - -protected: - /** - Constructors are protected. - NanoImages must be created within a NanoVG or NanoWidget class. - */ - NanoImage(NVGcontext* const context, const int imageId) noexcept; - -private: - NVGcontext* fContext; - int fImageId; - Size<uint> fSize; - friend class NanoVG; - - void _updateSize(); - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoImage) -}; - -// ----------------------------------------------------------------------- -// NanoVG - -/** - NanoVG class. - - This class exposes the NanoVG drawing API. - All calls should be wrapped in beginFrame() and endFrame(). - - @section 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. - - @section 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 linearGradient(), boxGradient(), radialGradient() and imagePattern(). - - Current render style can be saved and restored using save() and restore(). - - @section 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 resetTransform(), 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 save() and restore(). - - @section 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. - - @section 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. - - @section Scissoring - Scissoring allows you to clip the rendering into a rectangle. This is useful for varius - user interface cases like rendering a text edit or a timeline. - - @section Paths - Drawing a new shape starts with beginPath(), 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 pathWinding(). This is useful especially for the common shapes, which are drawn CCW. - - Finally you can fill the path using current fill style by calling fill(), and stroke it - with current stroke style by calling stroke(). - - The curve segments and sub-paths are transformed by the current transform. - - @section 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: - - @code - const char* txt = "Text me up."; - textBounds(vg, x,y, txt, NULL, bounds); - beginPath(vg); - roundedRect(vg, bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]); - fill(vg); - @endcode - - Note: currently only solid color fill is supported for text. - */ -class NanoVG -{ -public: - enum Align { - // Horizontal align - ALIGN_LEFT = 1 << 0, // Align horizontally to left (default). - ALIGN_CENTER = 1 << 1, // Align horizontally to center. - ALIGN_RIGHT = 1 << 2, // Align horizontally to right. - // Vertical align - ALIGN_TOP = 1 << 3, // Align vertically to top. - ALIGN_MIDDLE = 1 << 4, // Align vertically to middle. - ALIGN_BOTTOM = 1 << 5, // Align vertically to bottom. - ALIGN_BASELINE = 1 << 6 // Align vertically to baseline (default). - }; - - enum Alpha { - STRAIGHT_ALPHA, - PREMULTIPLIED_ALPHA - }; - - enum LineCap { - BUTT, - ROUND, - SQUARE, - BEVEL, - MITER - }; - - enum PatternRepeat { - REPEAT_NONE = 0x0, // No repeat - REPEAT_X = 0x1, // Repeat in X direction - REPEAT_Y = 0x2 // Repeat in Y direction - }; - - enum Solidity { - SOLID = 1, // CCW - HOLE = 2 // CW - }; - - enum Winding { - CCW = 1, // Winding for solid shapes - CW = 2 // Winding for holes - }; - - struct Paint { - float xform[6]; - float extent[2]; - float radius; - float feather; - Color innerColor; - Color outerColor; - int imageId; - PatternRepeat repeat; - - Paint() noexcept; - - /** - @internal - */ - Paint(const NVGpaint&) noexcept; - operator NVGpaint() const noexcept; - }; - - struct GlyphPosition { - 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. - }; - - struct TextRow { - 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 int FontId; - - /** - Constructor. - Uses 512x512 as default atlas size. - */ - NanoVG(); - - /** - Constructor using custom text atlas size. - */ - NanoVG(const int textAtlasWidth, const int textAtlasHeight); - - /** - Destructor. - */ - virtual ~NanoVG(); - - /** - Get the NanoVG context. - You should not need this under normal circumstances. - */ - NVGcontext* getContext() const noexcept - { - return fContext; - } - - /** - Begin drawing a new frame. - @param withAlha Controls if drawing the shapes to the render target should be done using straight or pre-multiplied alpha. - */ - void beginFrame(const uint width, const uint height, const float scaleFactor = 1.0f, const Alpha alpha = PREMULTIPLIED_ALPHA); - - /** - Begin drawing a new frame inside a widget. - */ - void beginFrame(Widget* const widget); - - /** - Ends drawing flushing remaining render state. - */ - void endFrame(); - - /* -------------------------------------------------------------------- - * State Handling */ - - /** - Pushes and saves the current render state into a state stack. - A matching restore() must be used to restore the state. - */ - void save(); - - /** - Pops and restores current render state. - */ - void restore(); - - /** - Resets current render state to default values. Does not affect the render state stack. - */ - void reset(); - - /* -------------------------------------------------------------------- - * Render styles */ - - /** - Sets current stroke style to a solid color. - */ - void strokeColor(const Color& color); - - /** - Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values. - Values must be in [0..255] range. - */ - void strokeColor(const int red, const int green, const int blue, const int alpha = 255); - - /** - Sets current stroke style to a solid color, made from red, green, blue and alpha numeric values. - Values must in [0..1] range. - */ - void strokeColor(const float red, const float green, const float blue, const float alpha = 1.0f); - - /** - Sets current stroke style to a paint, which can be a one of the gradients or a pattern. - */ - void strokePaint(const Paint& paint); - - /** - Sets current fill style to a solid color. - */ - void fillColor(const Color& color); - - /** - Sets current fill style to a solid color, made from red, green, blue and alpha numeric values. - Values must be in [0..255] range. - */ - void fillColor(const int red, const int green, const int blue, const int alpha = 255); - - /** - Sets current fill style to a solid color, made from red, green, blue and alpha numeric values. - Values must in [0..1] range. - */ - void fillColor(const float red, const float green, const float blue, const float alpha = 1.0f); - - /** - Sets current fill style to a paint, which can be a one of the gradients or a pattern. - */ - void fillPaint(const Paint& paint); - - /** - Sets the miter limit of the stroke style. - Miter limit controls when a sharp corner is beveled. - */ - void miterLimit(float limit); - - /** - Sets the stroke width of the stroke style. - */ - void strokeWidth(float size); - - /** - Sets how the end of the line (cap) is drawn, - Can be one of: BUTT, ROUND, SQUARE. - */ - void lineCap(LineCap cap = BUTT); - - /** - Sets how sharp path corners are drawn. - Can be one of MITER, ROUND, BEVEL. - */ - void lineJoin(LineCap join = MITER); - - /* -------------------------------------------------------------------- - * Transforms */ - - /** - Resets current transform to a identity matrix. - */ - void resetTransform(); - - /** - Pre-multiplies current coordinate system by specified matrix. - The parameters are interpreted as matrix as follows: - [a c e] - [b d f] - [0 0 1] - */ - void transform(float a, float b, float c, float d, float e, float f); - - /** - Translates current coordinate system. - */ - void translate(float x, float y); - - /** - Rotates current coordinate system. Angle is specified in radians. - */ - void rotate(float angle); - - /** - Skews the current coordinate system along X axis. Angle is specified in radians. - */ - void skewX(float angle); - - /** - Skews the current coordinate system along Y axis. Angle is specified in radians. - */ - void skewY(float angle); - - /** - Scales the current coordinate system. - */ - void scale(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] - */ - void currentTransform(float xform[6]); - - /** - 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. - */ - static void transformIdentity(float dst[6]); - - /** - Sets the transform to translation matrix - */ - static void transformTranslate(float dst[6], float tx, float ty); - - /** - Sets the transform to scale matrix. - */ - static void transformScale(float dst[6], float sx, float sy); - - /** - Sets the transform to rotate matrix. Angle is specified in radians. - */ - static void transformRotate(float dst[6], float a); - - /** - Sets the transform to skew-x matrix. Angle is specified in radians. - */ - static void transformSkewX(float dst[6], float a); - - /** - Sets the transform to skew-y matrix. Angle is specified in radians. - */ - static void transformSkewY(float dst[6], float a); - - /** - Sets the transform to the result of multiplication of two transforms, of A = A*B. - */ - static void transformMultiply(float dst[6], const float src[6]); - - /** - Sets the transform to the result of multiplication of two transforms, of A = B*A. - */ - static void transformPremultiply(float dst[6], const float src[6]); - - /** - Sets the destination to inverse of specified transform. - Returns 1 if the inverse could be calculated, else 0. - */ - static int transformInverse(float dst[6], const float src[6]); - - /** - Transform a point by given transform. - */ - static void transformPoint(float& dstx, float& dsty, const float xform[6], float srcx, float srcy); - - /** - Convert degrees to radians. - */ - static float degToRad(float deg); - - /** - Convert radians to degrees. - */ - static float radToDeg(float rad); - - /* -------------------------------------------------------------------- - * Images */ - - /** - Creates image by loading it from the disk from specified file name. - */ - NanoImage* createImage(const char* filename); - - /** - Creates image by loading it from the specified chunk of memory. - */ - NanoImage* createImageMem(uchar* data, int ndata); - - /** - Creates image from specified image data. - */ - NanoImage* createImageRGBA(uint w, uint h, const uchar* data); - - /* -------------------------------------------------------------------- - * Paints */ - - /** - 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 fillPaint() or strokePaint(). - */ - Paint linearGradient(float sx, float sy, float ex, float ey, const Color& icol, const Color& 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 fillPaint() or strokePaint(). - */ - Paint boxGradient(float x, float y, float w, float h, float r, float f, const Color& icol, const Color& 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 fillPaint() or strokePaint(). - */ - Paint radialGradient(float cx, float cy, float inr, float outr, const Color& icol, const Color& 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, - and repeat tells if the image should be repeated across x or y. - The gradient is transformed by the current transform when it is passed to fillPaint() or strokePaint(). - */ - Paint imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage* image, PatternRepeat repeat); - - /* -------------------------------------------------------------------- - * Scissoring */ - - /** - Sets the current - The scissor rectangle is transformed by the current transform. - */ - void scissor(float x, float y, float w, float h); - - /** - Reset and disables scissoring. - */ - void resetScissor(); - - /* -------------------------------------------------------------------- - * Paths */ - - /** - Clears the current path and sub-paths. - */ - void beginPath(); - - /** - Starts new sub-path with specified point as first point. - */ - void moveTo(float x, float y); - - /** - Adds line segment from the last point in the path to the specified point. - */ - void lineTo(float x, float y); - - /** - Adds bezier segment from last point in the path via two control points to the specified point. - */ - void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y); - - /** - Adds an arc segment at the corner defined by the last path point, and two specified points. - */ - void arcTo(float x1, float y1, float x2, float y2, float radius); - - /** - Closes current sub-path with a line segment. - */ - void closePath(); - - /** - Sets the current sub-path winding. - */ - void pathWinding(Winding dir); - - /** - Creates new arc shaped sub-path. - */ - void arc(float cx, float cy, float r, float a0, float a1, Winding dir); - - /** - Creates new rectangle shaped sub-path. - */ - void rect(float x, float y, float w, float h); - - /** - Creates new rounded rectangle shaped sub-path. - */ - void roundedRect(float x, float y, float w, float h, float r); - - /** - Creates new ellipse shaped sub-path. - */ - void ellipse(float cx, float cy, float rx, float ry); - - /** - Creates new circle shaped sub-path. - */ - void circle(float cx, float cy, float r); - - /** - Fills the current path with current fill style. - */ - void fill(); - - /** - Fills the current path with current stroke style. - */ - void stroke(); - - /* -------------------------------------------------------------------- - * Text */ - - /** - Creates font by loading it from the disk from specified file name. - Returns handle to the font. - */ - FontId createFont(const char* name, const char* filename); - - /** - Creates font by loading it from the specified memory chunk. - Returns handle to the font. - */ - FontId createFontMem(const char* name, const uchar* data, int ndata, bool freeData); - - /** - Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found. - */ - FontId findFont(const char* name); - - /** - Sets the font size of current text style. - */ - void fontSize(float size); - - /** - Sets the blur of current text style. - */ - void fontBlur(float blur); - - /** - Sets the letter spacing of current text style. - */ - void textLetterSpacing(float spacing); - - /** - Sets the proportional line height of current text style. The line height is specified as multiple of font size. - */ - void textLineHeight(float lineHeight); - - /** - Sets the text align of current text style. - */ - void textAlign(Align align); - - /** - Sets the text align of current text style. - Overloaded function for convenience. - @see Align - */ - void textAlign(int align); - - /** - Sets the font face based on specified id of current text style. - */ - void fontFaceId(FontId font); - - /** - Sets the font face based on specified name of current text style. - */ - void fontFace(const char* font); - - /** - Draws text string at specified location. If end is specified only the sub-string up to the end is drawn. - */ - float text(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 textBox(float x, float y, float breakRowWidth, const char* string, const char* end); - - /** - Measures the specified text string. 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 textBounds(float x, float y, const char* string, const char* end, Rectangle<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 textBoxBounds(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 textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition* positions, int maxPositions); - - /** - Returns the vertical metrics based on the current text style. - Measured values are returned in local coordinate space. - */ - void textMetrics(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 textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows, int maxRows); - -private: - NVGcontext* const fContext; - bool fInFrame; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoVG) -}; - -// ----------------------------------------------------------------------- -// NanoWidget - -/** - NanoVG Widget class. - - This class implements the NanoVG drawing API inside a DGL Widget. - The drawing function onDisplay() is implemented internally but a - new onNanoDisplay() needs to be overridden instead. - */ -class NanoWidget : public Widget, - public NanoVG -{ -public: - /** - Constructor. - */ - NanoWidget(Window& parent) - : Widget(parent), - NanoVG(), - leakDetector_NanoWidget() - { - setNeedsScaling(true); - } - -protected: - /** - New virtual onDisplay function. - @see onDisplay - */ - virtual void onNanoDisplay() = 0; - -private: - /** - Widget display function. - Implemented internally to wrap begin/endFrame() automatically. - */ - void onDisplay() override - { - //glPushAttrib(GL_PIXEL_MODE_BIT|GL_STENCIL_BUFFER_BIT|GL_ENABLE_BIT); - beginFrame(getWidth(), getHeight()); - onNanoDisplay(); - endFrame(); - //glPopAttrib(); - glDisable(GL_CULL_FACE); - } - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NanoWidget) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_NANO_WIDGET_HPP_INCLUDED diff --git a/libs/dgl/StandaloneWindow.hpp b/libs/dgl/StandaloneWindow.hpp deleted file mode 100644 index b4087f9..0000000 --- a/libs/dgl/StandaloneWindow.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_STANDALONE_WINDOW_HPP_INCLUDED -#define DGL_STANDALONE_WINDOW_HPP_INCLUDED - -#include "App.hpp" -#include "Widget.hpp" -#include "Window.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class StandaloneWindow : public App, - public Window -{ -public: - StandaloneWindow() - : App(), - Window((App&)*this), - fWidget(nullptr) {} - - void exec() - { - Window::show(); - App::exec(); - } - -protected: - void onReshape(uint width, uint height) override - { - if (fWidget != nullptr) - fWidget->setSize(width, height); - Window::onReshape(width, height); - } - -private: - Widget* fWidget; - - void _addWidget(Widget* widget) override - { - if (fWidget == nullptr) - { - fWidget = widget; - fWidget->setNeedsFullViewport(true); - } - Window::_addWidget(widget); - } - - void _removeWidget(Widget* widget) override - { - if (fWidget == widget) - { - fWidget->setNeedsFullViewport(false); - fWidget = nullptr; - } - Window::_removeWidget(widget); - } - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(StandaloneWindow) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_STANDALONE_WINDOW_HPP_INCLUDED diff --git a/libs/dgl/Widget.hpp b/libs/dgl/Widget.hpp deleted file mode 100644 index faed6b5..0000000 --- a/libs/dgl/Widget.hpp +++ /dev/null @@ -1,387 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_WIDGET_HPP_INCLUDED -#define DGL_WIDGET_HPP_INCLUDED - -#include "Geometry.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Forward class names - -class App; -class Window; -class StandaloneWindow; - -// ----------------------------------------------------------------------- - -/** - Base DGL Widget class. - - This is the base Widget class, from which all widgets are built. - - All widgets have a parent Window where they'll be drawn. - This parent is never changed during the widget lifetime. - - Widgets receive events in relative coordinates. - (0, 0) means its top-left position. - - Windows paint widgets in the order they are constructed. - Early widgets are drawn first, at the bottom, then newer ones on top. - Events are sent in the inverse order so that the top-most widget gets - a chance to catch the event and stop its propagation. - - All widget event callbacks do nothing by default. - */ -class Widget -{ -public: - /** - Base event data. - @a mod The currently active keyboard modifiers, @see Modifier. - @a time The timestamp (if any). - */ - struct BaseEvent { - uint mod; - uint32_t time; - - /** Constuctor */ - BaseEvent() noexcept : mod(0x0), time(0) {} - /** Destuctor */ - virtual ~BaseEvent() noexcept {} - }; - - /** - Keyboard event. - @a press True if the key was pressed, false if released. - @a key Unicode point of the key pressed. - @see onKeyboard - */ - struct KeyboardEvent : BaseEvent { - bool press; - uint key; - - /** Constuctor */ - KeyboardEvent() noexcept - : BaseEvent(), - press(false), - key(0) {} - }; - - /** - Special keyboard event. - @a press True if the key was pressed, false if released. - @a key The key pressed. - @see onSpecial - */ - struct SpecialEvent : BaseEvent { - bool press; - Key key; - - /** Constuctor */ - SpecialEvent() noexcept - : BaseEvent(), - press(false), - key(Key(0)) {} - }; - - /** - Mouse event. - @a button The button number (1 = left, 2 = middle, 3 = right). - @a press True if the key was pressed, false if released. - @a pos The widget-relative coordinates of the pointer. - @see onMouse - */ - struct MouseEvent : BaseEvent { - int button; - bool press; - Point<int> pos; - - /** Constuctor */ - MouseEvent() noexcept - : BaseEvent(), - button(0), - press(false), - pos(0, 0) {} - }; - - /** - Mouse motion event. - @a pos The widget-relative coordinates of the pointer. - @see onMotion - */ - struct MotionEvent : BaseEvent { - Point<int> pos; - - /** Constuctor */ - MotionEvent() noexcept - : BaseEvent(), - pos(0, 0) {} - }; - - /** - Mouse scroll event. - @a pos The widget-relative coordinates of the pointer. - @a delta The scroll distance. - @see onScroll - */ - struct ScrollEvent : BaseEvent { - Point<int> pos; - Point<float> delta; - - /** Constuctor */ - ScrollEvent() noexcept - : BaseEvent(), - pos(0, 0), - delta(0.0f, 0.0f) {} - }; - - /** - Resize event. - @a size The new widget size. - @a oldSize The previous size, may be null. - @see onResize - */ - struct ResizeEvent { - Size<uint> size; - Size<uint> oldSize; - - /** Constuctor */ - ResizeEvent() noexcept - : size(0, 0), - oldSize(0, 0) {} - }; - - /** - Constructor. - */ - explicit Widget(Window& parent); - - /** - Destructor. - */ - virtual ~Widget(); - - /** - Check if this widget is visible within its parent window. - Invisible widgets do not receive events except resize. - */ - bool isVisible() const noexcept; - - /** - Set widget visible (or not) according to @a yesNo. - */ - void setVisible(bool yesNo); - - /** - Show widget. - This is the same as calling setVisible(true). - */ - void show(); - - /** - Hide widget. - This is the same as calling setVisible(false). - */ - void hide(); - - /** - Get width. - */ - uint getWidth() const noexcept; - - /** - Get height. - */ - uint getHeight() const noexcept; - - /** - Get size. - */ - const Size<uint>& getSize() const noexcept; - - /** - Set width. - */ - void setWidth(uint width) noexcept; - - /** - Set height. - */ - void setHeight(uint height) noexcept; - - /** - Set size using @a width and @a height values. - */ - void setSize(uint width, uint height) noexcept; - - /** - Set size. - */ - void setSize(const Size<uint>& size) noexcept; - - /** - Get absolute X. - */ - int getAbsoluteX() const noexcept; - - /** - Get absolute Y. - */ - int getAbsoluteY() const noexcept; - - /** - Get absolute position. - */ - const Point<int>& getAbsolutePos() const noexcept; - - /** - Set absolute X. - */ - void setAbsoluteX(int x) noexcept; - - /** - Set absolute Y. - */ - void setAbsoluteY(int y) noexcept; - - /** - Set absolute position using @a x and @a y values. - */ - void setAbsolutePos(int x, int y) noexcept; - - /** - Set absolute position. - */ - void setAbsolutePos(const Point<int>& pos) noexcept; - - /** - Get this widget's window application. - Same as calling getParentWindow().getApp(). - */ - App& getParentApp() const noexcept; - - /** - Get parent window, as passed in the constructor. - */ - Window& getParentWindow() const noexcept; - - /** - Check if this widget contains the point defined by @a x and @a y. - */ - bool contains(int x, int y) const noexcept; - - /** - Check if this widget contains the point @a pos. - */ - bool contains(const Point<int>& pos) const noexcept; - - /** - Tell this widget's window to repaint itself. - */ - void repaint() noexcept; - - /** - Get the Id associated with this widget. - @see setId - */ - uint getId() const noexcept; - - /** - Set an Id to be associated with this widget. - @see getId - */ - void setId(uint id) noexcept; - -protected: - /** - A function called to draw the view contents with OpenGL. - */ - virtual void onDisplay() = 0; - - /** - A function called when a key is pressed or released. - @return True to stop event propagation, false otherwise. - */ - virtual bool onKeyboard(const KeyboardEvent&); - - /** - A function called when a special key is pressed or released. - @return True to stop event propagation, false otherwise. - */ - virtual bool onSpecial(const SpecialEvent&); - - /** - A function called when a mouse button is pressed or released. - @return True to stop event propagation, false otherwise. - */ - virtual bool onMouse(const MouseEvent&); - - /** - A function called when the pointer moves. - @return True to stop event propagation, false otherwise. - */ - virtual bool onMotion(const MotionEvent&); - - /** - A function called on scrolling (e.g. mouse wheel or track pad). - @return True to stop event propagation, false otherwise. - */ - virtual bool onScroll(const ScrollEvent&); - - /** - A function called when the widget is resized. - */ - virtual void onResize(const ResizeEvent&); - - /** - Tell the parent window this widget needs the full viewport. - When enabled, the local widget coordinates are ignored. - @note: This is an internal function; - You do not need it under normal circumstances. - */ - void setNeedsFullViewport(bool yesNo) noexcept; - - /** - Tell the parent window this widget needs scaling. - When enabled, the widget viewport is scaled to match width and height. - @note: This is an internal function; - You do not need it under normal circumstances. - */ - void setNeedsScaling(bool yesNo) noexcept; - -private: - Window& fParent; - bool fNeedsFullViewport; - bool fNeedsScaling; - bool fVisible; - uint fId; - Point<int> fAbsolutePos; - Size<uint> fSize; - - friend class Window; - friend class StandaloneWindow; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Widget) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_WIDGET_HPP_INCLUDED diff --git a/libs/dgl/Window.hpp b/libs/dgl/Window.hpp deleted file mode 100644 index 37ae278..0000000 --- a/libs/dgl/Window.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_WINDOW_HPP_INCLUDED -#define DGL_WINDOW_HPP_INCLUDED - -#include "Geometry.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -class App; -class Widget; -class StandaloneWindow; - -class Window -{ -public: - /** - File browser options. - */ - struct FileBrowserOptions { - const char* startDir; - const char* title; - uint width; - uint height; - - /** - File browser buttons. - - 0 means hidden. - 1 means visible and unchecked. - 2 means visible and checked. - */ - struct Buttons { - uint listAllFiles; - uint showHidden; - uint showPlaces; - - /** Constuctor for default values */ - Buttons() - : listAllFiles(2), - showHidden(1), - showPlaces(1) {} - } buttons; - - /** Constuctor for default values */ - FileBrowserOptions() - : startDir(nullptr), - title(nullptr), - width(0), - height(0), - buttons() {} - }; - - explicit Window(App& app); - explicit Window(App& app, Window& parent); - explicit Window(App& app, intptr_t parentId); - virtual ~Window(); - - void show(); - void hide(); - void close(); - void exec(bool lockWait = false); - - void focus(); - void repaint() noexcept; - - bool openFileBrowser(const FileBrowserOptions& options); - - bool isVisible() const noexcept; - void setVisible(bool yesNo); - - bool isResizable() const noexcept; - void setResizable(bool yesNo); - - uint getWidth() const noexcept; - uint getHeight() const noexcept; - Size<uint> getSize() const noexcept; - void setSize(uint width, uint height); - void setSize(Size<uint> size); - - const char* getTitle() const noexcept; - void setTitle(const char* title); - - void setTransientWinId(uintptr_t winId); - - App& getApp() const noexcept; - intptr_t getWindowId() const noexcept; - - void addIdleCallback(IdleCallback* const callback); - void removeIdleCallback(IdleCallback* const callback); - -protected: - virtual void onDisplayBefore(); - virtual void onDisplayAfter(); - virtual void onReshape(uint width, uint height); - virtual void onClose(); - - virtual void fileBrowserSelected(const char* filename); - -private: - struct PrivateData; - PrivateData* const pData; - friend class App; - friend class Widget; - friend class StandaloneWindow; - - virtual void _addWidget(Widget* const widget); - virtual void _removeWidget(Widget* const widget); - void _idle(); - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Window) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_WINDOW_HPP_INCLUDED diff --git a/libs/dgl/src/App.cpp b/libs/dgl/src/App.cpp deleted file mode 100644 index b0467ca..0000000 --- a/libs/dgl/src/App.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "AppPrivateData.hpp" -#include "../Window.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -App::App() - : pData(new PrivateData()), - leakDetector_App() {} - -App::~App() -{ - delete pData; -} - -void App::idle() -{ - for (std::list<Window*>::iterator it = pData->windows.begin(), ite = pData->windows.end(); it != ite; ++it) - { - Window* const window(*it); - window->_idle(); - } - - for (std::list<IdleCallback*>::iterator it = pData->idleCallbacks.begin(), ite = pData->idleCallbacks.end(); it != ite; ++it) - { - IdleCallback* const idleCallback(*it); - idleCallback->idleCallback(); - } -} - -void App::exec() -{ - for (; pData->doLoop;) - { - idle(); - d_msleep(10); - } -} - -void App::quit() -{ - pData->doLoop = false; - - for (std::list<Window*>::reverse_iterator rit = pData->windows.rbegin(), rite = pData->windows.rend(); rit != rite; ++rit) - { - Window* const window(*rit); - window->close(); - } -} - -bool App::isQuiting() const noexcept -{ - return !pData->doLoop; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/AppPrivateData.hpp b/libs/dgl/src/AppPrivateData.hpp deleted file mode 100644 index c668968..0000000 --- a/libs/dgl/src/AppPrivateData.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DGL_APP_PRIVATE_DATA_HPP_INCLUDED -#define DGL_APP_PRIVATE_DATA_HPP_INCLUDED - -#include "../App.hpp" -#include "../../distrho/extra/d_sleep.hpp" - -#include <list> - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -struct App::PrivateData { - bool doLoop; - uint visibleWindows; - std::list<Window*> windows; - std::list<IdleCallback*> idleCallbacks; - - PrivateData() - : doLoop(true), - visibleWindows(0), - windows(), - idleCallbacks() {} - - ~PrivateData() - { - DISTRHO_SAFE_ASSERT(! doLoop); - DISTRHO_SAFE_ASSERT(visibleWindows == 0); - - windows.clear(); - idleCallbacks.clear(); - } - - void oneShown() noexcept - { - if (++visibleWindows == 1) - doLoop = true; - } - - void oneHidden() noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(visibleWindows > 0,); - - if (--visibleWindows == 0) - doLoop = false; - } - - DISTRHO_DECLARE_NON_COPY_STRUCT(PrivateData) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#endif // DGL_APP_PRIVATE_DATA_HPP_INCLUDED diff --git a/libs/dgl/src/Color.cpp b/libs/dgl/src/Color.cpp deleted file mode 100644 index 57b8c07..0000000 --- a/libs/dgl/src/Color.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../Color.hpp" - -#include "nanovg/nanovg.h" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -static void fixRange(float& value) -{ - /**/ if (value < 0.0f) - value = 0.0f; - else if (value > 1.0f) - value = 1.0f; -} - -static float getFixedRange(const float& value) -{ - if (value <= 0.0f) - return 0.0f; - if (value >= 1.0f) - return 1.0f; - return value; -} - -static uchar getFixedRange2(const float& value) -{ - const float value2(getFixedRange(value)*255.0f); - if (value2 <= 0.0f) - return 0; - if (value2 >= 255.0f) - return 255; - return static_cast<uchar>(value2); -} - -// ----------------------------------------------------------------------- - -Color::Color() noexcept - : red(1.0f), - green(1.0f), - blue(1.0f), - alpha(1.0f) {} - -Color::Color(int r, int g, int b, int a) noexcept - : red(static_cast<float>(r)/255.0f), - green(static_cast<float>(g)/255.0f), - blue(static_cast<float>(b)/255.0f), - alpha(static_cast<float>(a)/255.0f) -{ - fixBounds(); -} - -Color::Color(float r, float g, float b, float a) noexcept - : red(r), - green(g), - blue(b), - alpha(a) -{ - fixBounds(); -} - -Color::Color(const Color& color) noexcept - : red(color.red), - green(color.green), - blue(color.blue), - alpha(color.alpha) -{ - fixBounds(); -} - -Color& Color::operator=(const Color& color) noexcept -{ - red = color.red; - green = color.green; - blue = color.blue; - alpha = color.alpha; - fixBounds(); - return *this; -} - -Color::Color(const Color& color1, const Color& color2, float u) noexcept - : red(color1.red), - green(color1.green), - blue(color1.blue), - alpha(color1.alpha) -{ - interpolate(color2, u); -} - -Color Color::fromHSL(float hue, float saturation, float lightness, float alpha) -{ - return nvgHSLA(hue, saturation, lightness, static_cast<uchar>(getFixedRange(alpha)*255.0f)); -} - -Color Color::fromHTML(const char* rgb, float alpha) -{ - Color fallback; - DISTRHO_SAFE_ASSERT_RETURN(rgb != nullptr && rgb[0] != '\0', fallback); - - if (rgb[0] == '#') ++rgb; - DISTRHO_SAFE_ASSERT_RETURN(rgb[0] != '\0', fallback); - - std::size_t rgblen(std::strlen(rgb)); - DISTRHO_SAFE_ASSERT_RETURN(rgblen == 3 || rgblen == 6, fallback); - - char rgbtmp[3] = { '\0', '\0', '\0' }; - int r, g, b; - - if (rgblen == 3) - { - rgbtmp[0] = rgb[0]; - r = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - - rgbtmp[0] = rgb[1]; - g = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - - rgbtmp[0] = rgb[2]; - b = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - } - else - { - rgbtmp[0] = rgb[0]; - rgbtmp[1] = rgb[1]; - r = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - - rgbtmp[0] = rgb[2]; - rgbtmp[1] = rgb[3]; - g = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - - rgbtmp[0] = rgb[4]; - rgbtmp[1] = rgb[5]; - b = static_cast<int>(std::strtol(rgbtmp, nullptr, 16)); - } - - return Color(r, g, b, static_cast<int>(getFixedRange(alpha)*255.0f)); -} - -void Color::interpolate(const Color& other, float u) noexcept -{ - fixRange(u); - const float oneMinusU(1.0f - u); - - red = red * oneMinusU + other.red * u; - green = green * oneMinusU + other.green * u; - blue = blue * oneMinusU + other.blue * u; - alpha = alpha * oneMinusU + other.alpha * u; - - fixBounds(); -} - -// ----------------------------------------------------------------------- - -bool Color::isEqual(const Color& color, bool withAlpha) noexcept -{ - const uchar r1 = getFixedRange2(rgba[0]); - const uchar g1 = getFixedRange2(rgba[1]); - const uchar b1 = getFixedRange2(rgba[2]); - const uchar a1 = getFixedRange2(rgba[3]); - - const uchar r2 = getFixedRange2(color.rgba[0]); - const uchar g2 = getFixedRange2(color.rgba[1]); - const uchar b2 = getFixedRange2(color.rgba[2]); - const uchar a2 = getFixedRange2(color.rgba[3]); - - if (withAlpha) - return (r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2); - else - return (r1 == r2 && g1 == g2 && b1 == b2); -} - -bool Color::isNotEqual(const Color& color, bool withAlpha) noexcept -{ - const uchar r1 = getFixedRange2(rgba[0]); - const uchar g1 = getFixedRange2(rgba[1]); - const uchar b1 = getFixedRange2(rgba[2]); - const uchar a1 = getFixedRange2(rgba[3]); - - const uchar r2 = getFixedRange2(color.rgba[0]); - const uchar g2 = getFixedRange2(color.rgba[1]); - const uchar b2 = getFixedRange2(color.rgba[2]); - const uchar a2 = getFixedRange2(color.rgba[3]); - - if (withAlpha) - return (r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2); - else - return (r1 != r2 || g1 != g2 || b1 != b2); -} - -bool Color::operator==(const Color& color) noexcept -{ - return isEqual(color, true); -} - -bool Color::operator!=(const Color& color) noexcept -{ - return isNotEqual(color, true); -} - -// ----------------------------------------------------------------------- - -void Color::fixBounds() noexcept -{ - fixRange(red); - fixRange(green); - fixRange(blue); - fixRange(alpha); -} - -// ----------------------------------------------------------------------- - -Color::Color(const NVGcolor& c) noexcept - : red(c.r), green(c.g), blue(c.b), alpha(c.a) -{ - fixBounds(); -} - -Color::operator NVGcolor() const noexcept -{ - NVGcolor nc; - nc.r = red; - nc.g = green; - nc.b = blue; - nc.a = alpha; - return nc; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/Geometry.cpp b/libs/dgl/src/Geometry.cpp deleted file mode 100644 index 6964816..0000000 --- a/libs/dgl/src/Geometry.cpp +++ /dev/null @@ -1,1072 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../Geometry.hpp" - -#include <cmath> - -START_NAMESPACE_DGL - -static const float M_2PIf = 3.14159265358979323846f*2.0f; - -// ----------------------------------------------------------------------- -// Point - -template<typename T> -Point<T>::Point() noexcept - : fX(0), - fY(0) {} - -template<typename T> -Point<T>::Point(const T& x, const T& y) noexcept - : fX(x), - fY(y) {} - -template<typename T> -Point<T>::Point(const Point<T>& pos) noexcept - : fX(pos.fX), - fY(pos.fY) {} - -template<typename T> -const T& Point<T>::getX() const noexcept -{ - return fX; -} - -template<typename T> -const T& Point<T>::getY() const noexcept -{ - return fY; -} - -template<typename T> -void Point<T>::setX(const T& x) noexcept -{ - fX = x; -} - -template<typename T> -void Point<T>::setY(const T& y) noexcept -{ - fY = y; -} - -template<typename T> -void Point<T>::setPos(const T& x, const T& y) noexcept -{ - fX = x; - fY = y; -} - -template<typename T> -void Point<T>::setPos(const Point<T>& pos) noexcept -{ - fX = pos.fX; - fY = pos.fY; -} - -template<typename T> -void Point<T>::moveBy(const T& x, const T& y) noexcept -{ - fX = static_cast<T>(fX+x); - fY = static_cast<T>(fY+y); -} - -template<typename T> -void Point<T>::moveBy(const Point<T>& pos) noexcept -{ - fX = static_cast<T>(fX+pos.fX); - fY = static_cast<T>(fY+pos.fY); -} - -template<typename T> -bool Point<T>::isZero() const noexcept -{ - return fX == 0 && fY == 0; -} - -template<typename T> -bool Point<T>::isNotZero() const noexcept -{ - return fX != 0 || fY != 0; -} - -template<typename T> -Point<T> Point<T>::operator+(const Point<T>& pos) noexcept -{ - return Point<T>(fX+pos.fX, fY+pos.fY); -} - -template<typename T> -Point<T> Point<T>::operator-(const Point<T>& pos) noexcept -{ - return Point<T>(fX-pos.fX, fY-pos.fY); -} - -template<typename T> -Point<T>& Point<T>::operator=(const Point<T>& pos) noexcept -{ - fX = pos.fX; - fY = pos.fY; - return *this; -} - -template<typename T> -Point<T>& Point<T>::operator+=(const Point<T>& pos) noexcept -{ - fX = static_cast<T>(fX+pos.fX); - fY = static_cast<T>(fY+pos.fY); - return *this; -} - -template<typename T> -Point<T>& Point<T>::operator-=(const Point<T>& pos) noexcept -{ - fX = static_cast<T>(fX-pos.fX); - fY = static_cast<T>(fY-pos.fY); - return *this; -} - -template<typename T> -bool Point<T>::operator==(const Point<T>& pos) const noexcept -{ - return (fX == pos.fX && fY == pos.fY); -} - -template<typename T> -bool Point<T>::operator!=(const Point<T>& pos) const noexcept -{ - return (fX != pos.fX || fY != pos.fY); -} - -// ----------------------------------------------------------------------- -// Size - -template<typename T> -Size<T>::Size() noexcept - : fWidth(0), - fHeight(0) {} - -template<typename T> -Size<T>::Size(const T& width, const T& height) noexcept - : fWidth(width), - fHeight(height) {} - -template<typename T> -Size<T>::Size(const Size<T>& size) noexcept - : fWidth(size.fWidth), - fHeight(size.fHeight) {} - -template<typename T> -const T& Size<T>::getWidth() const noexcept -{ - return fWidth; -} - -template<typename T> -const T& Size<T>::getHeight() const noexcept -{ - return fHeight; -} - -template<typename T> -void Size<T>::setWidth(const T& width) noexcept -{ - fWidth = width; -} - -template<typename T> -void Size<T>::setHeight(const T& height) noexcept -{ - fHeight = height; -} - -template<typename T> -void Size<T>::setSize(const T& width, const T& height) noexcept -{ - fWidth = width; - fHeight = height; -} - -template<typename T> -void Size<T>::setSize(const Size<T>& size) noexcept -{ - fWidth = size.fWidth; - fHeight = size.fHeight; -} - -template<typename T> -void Size<T>::growBy(double multiplier) noexcept -{ - fWidth = static_cast<T>(static_cast<double>(fWidth)*multiplier); - fHeight = static_cast<T>(static_cast<double>(fHeight)*multiplier); -} - -template<typename T> -void Size<T>::shrinkBy(double divider) noexcept -{ - fWidth = static_cast<T>(static_cast<double>(fWidth)/divider); - fHeight = static_cast<T>(static_cast<double>(fHeight)/divider); -} - -template<typename T> -bool Size<T>::isNull() const noexcept -{ - return fWidth == 0 && fHeight == 0; -} - -template<typename T> -bool Size<T>::isNotNull() const noexcept -{ - return fWidth != 0 || fHeight != 0; -} - -template<typename T> -bool Size<T>::isValid() const noexcept -{ - return fWidth > 1 && fHeight > 1; -} - -template<typename T> -bool Size<T>::isInvalid() const noexcept -{ - return fWidth <= 0 || fHeight <= 0; -} - -template<typename T> -Size<T> Size<T>::operator+(const Size<T>& size) noexcept -{ - return Size<T>(fWidth+size.fWidth, fHeight+size.fHeight); -} - -template<typename T> -Size<T> Size<T>::operator-(const Size<T>& size) noexcept -{ - return Size<T>(fWidth-size.fWidth, fHeight-size.fHeight); -} - -template<typename T> -Size<T>& Size<T>::operator=(const Size<T>& size) noexcept -{ - fWidth = size.fWidth; - fHeight = size.fHeight; - return *this; -} - -template<typename T> -Size<T>& Size<T>::operator+=(const Size<T>& size) noexcept -{ - fWidth = static_cast<T>(fWidth+size.fWidth); - fHeight = static_cast<T>(fHeight+size.fHeight); - return *this; -} - -template<typename T> -Size<T>& Size<T>::operator-=(const Size<T>& size) noexcept -{ - fWidth = static_cast<T>(fWidth-size.fWidth); - fHeight = static_cast<T>(fHeight-size.fHeight); - return *this; -} - -template<typename T> -Size<T>& Size<T>::operator*=(double m) noexcept -{ - fWidth = static_cast<T>(static_cast<double>(fWidth)*m); - fHeight = static_cast<T>(static_cast<double>(fHeight)*m); - return *this; -} - -template<typename T> -Size<T>& Size<T>::operator/=(double d) noexcept -{ - fWidth = static_cast<T>(static_cast<double>(fWidth)/d); - fHeight = static_cast<T>(static_cast<double>(fHeight)/d); - return *this; -} - -template<typename T> -bool Size<T>::operator==(const Size<T>& size) const noexcept -{ - return (fWidth == size.fWidth && fHeight == size.fHeight); -} - -template<typename T> -bool Size<T>::operator!=(const Size<T>& size) const noexcept -{ - return (fWidth != size.fWidth || fHeight != size.fHeight); -} - -// ----------------------------------------------------------------------- -// Line - -template<typename T> -Line<T>::Line() noexcept - : fPosStart(0, 0), - fPosEnd(0, 0) {} - -template<typename T> -Line<T>::Line(const T& startX, const T& startY, const T& endX, const T& endY) noexcept - : fPosStart(startX, startY), - fPosEnd(endX, endY) {} - -template<typename T> -Line<T>::Line(const T& startX, const T& startY, const Point<T>& endPos) noexcept - : fPosStart(startX, startY), - fPosEnd(endPos) {} - -template<typename T> -Line<T>::Line(const Point<T>& startPos, const T& endX, const T& endY) noexcept - : fPosStart(startPos), - fPosEnd(endX, endY) {} - -template<typename T> -Line<T>::Line(const Point<T>& startPos, const Point<T>& endPos) noexcept - : fPosStart(startPos), - fPosEnd(endPos) {} - -template<typename T> -Line<T>::Line(const Line<T>& line) noexcept - : fPosStart(line.fPosStart), - fPosEnd(line.fPosEnd) {} - -template<typename T> -const T& Line<T>::getStartX() const noexcept -{ - return fPosStart.fX; -} - -template<typename T> -const T& Line<T>::getStartY() const noexcept -{ - return fPosStart.fY; -} - -template<typename T> -const T& Line<T>::getEndX() const noexcept -{ - return fPosEnd.fX; -} - -template<typename T> -const T& Line<T>::getEndY() const noexcept -{ - return fPosEnd.fY; -} - -template<typename T> -const Point<T>& Line<T>::getStartPos() const noexcept -{ - return fPosStart; -} - -template<typename T> -const Point<T>& Line<T>::getEndPos() const noexcept -{ - return fPosEnd; -} - -template<typename T> -void Line<T>::setStartX(const T& x) noexcept -{ - fPosStart.fX = x; -} - -template<typename T> -void Line<T>::setStartY(const T& y) noexcept -{ - fPosStart.fY = y; -} - -template<typename T> -void Line<T>::setStartPos(const T& x, const T& y) noexcept -{ - fPosStart = Point<T>(x, y); -} - -template<typename T> -void Line<T>::setStartPos(const Point<T>& pos) noexcept -{ - fPosStart = pos; -} - -template<typename T> -void Line<T>::setEndX(const T& x) noexcept -{ - fPosEnd.fX = x; -} - -template<typename T> -void Line<T>::setEndY(const T& y) noexcept -{ - fPosEnd.fY = y; -} - -template<typename T> -void Line<T>::setEndPos(const T& x, const T& y) noexcept -{ - fPosEnd = Point<T>(x, y); -} - -template<typename T> -void Line<T>::setEndPos(const Point<T>& pos) noexcept -{ - fPosEnd = pos; -} - -template<typename T> -void Line<T>::moveBy(const T& x, const T& y) noexcept -{ - fPosStart.moveBy(x, y); - fPosEnd.moveBy(x, y); -} - -template<typename T> -void Line<T>::moveBy(const Point<T>& pos) noexcept -{ - fPosStart.moveBy(pos); - fPosEnd.moveBy(pos); -} - -template<typename T> -void Line<T>::draw() -{ - DISTRHO_SAFE_ASSERT_RETURN(fPosStart != fPosEnd,); - - glBegin(GL_LINES); - - { - glVertex2d(fPosStart.fX, fPosStart.fY); - glVertex2d(fPosEnd.fX, fPosEnd.fY); - } - - glEnd(); -} - -template<typename T> -bool Line<T>::isNull() const noexcept -{ - return fPosStart == fPosEnd; -} - -template<typename T> -bool Line<T>::isNotNull() const noexcept -{ - return fPosStart != fPosEnd; -} - -template<typename T> -Line<T>& Line<T>::operator=(const Line<T>& line) noexcept -{ - fPosStart = line.fPosStart; - fPosEnd = line.fPosEnd; - return *this; -} - -template<typename T> -bool Line<T>::operator==(const Line<T>& line) const noexcept -{ - return (fPosStart == line.fPosStart && fPosEnd == line.fPosEnd); -} - -template<typename T> -bool Line<T>::operator!=(const Line<T>& line) const noexcept -{ - return (fPosStart != line.fPosStart || fPosEnd != line.fPosEnd); -} - -// ----------------------------------------------------------------------- -// Circle - -template<typename T> -Circle<T>::Circle() noexcept - : fPos(0, 0), - fSize(0.0f), - fNumSegments(0), - fTheta(0.0f), - fCos(0.0f), - fSin(0.0f) {} - -template<typename T> -Circle<T>::Circle(const T& x, const T& y, const float size, const uint numSegments) - : fPos(x, y), - fSize(size), - fNumSegments(numSegments >= 3 ? numSegments : 3), - fTheta(M_2PIf / static_cast<float>(fNumSegments)), - fCos(std::cos(fTheta)), - fSin(std::sin(fTheta)) -{ - DISTRHO_SAFE_ASSERT(fSize > 0.0f); -} - -template<typename T> -Circle<T>::Circle(const Point<T>& pos, const float size, const uint numSegments) - : fPos(pos), - fSize(size), - fNumSegments(numSegments >= 3 ? numSegments : 3), - fTheta(M_2PIf / static_cast<float>(fNumSegments)), - fCos(std::cos(fTheta)), - fSin(std::sin(fTheta)) -{ - DISTRHO_SAFE_ASSERT(fSize > 0.0f); -} - -template<typename T> -Circle<T>::Circle(const Circle<T>& cir) noexcept - : fPos(cir.fPos), - fSize(cir.fSize), - fNumSegments(cir.fNumSegments), - fTheta(cir.fTheta), - fCos(cir.fCos), - fSin(cir.fSin) -{ - DISTRHO_SAFE_ASSERT(fSize > 0.0f); -} - -template<typename T> -const T& Circle<T>::getX() const noexcept -{ - return fPos.fX; -} - -template<typename T> -const T& Circle<T>::getY() const noexcept -{ - return fPos.fX; -} - -template<typename T> -const Point<T>& Circle<T>::getPos() const noexcept -{ - return fPos; -} - -template<typename T> -void Circle<T>::setX(const T& x) noexcept -{ - fPos.fX = x; -} - -template<typename T> -void Circle<T>::setY(const T& y) noexcept -{ - fPos.fY = y; -} - -template<typename T> -void Circle<T>::setPos(const T& x, const T& y) noexcept -{ - fPos.fX = x; - fPos.fY = y; -} - -template<typename T> -void Circle<T>::setPos(const Point<T>& pos) noexcept -{ - fPos = pos; -} - -template<typename T> -float Circle<T>::getSize() const noexcept -{ - return fSize; -} - -template<typename T> -void Circle<T>::setSize(const float size) noexcept -{ - DISTRHO_SAFE_ASSERT_RETURN(size > 0.0f,); - - fSize = size; -} - -template<typename T> -uint Circle<T>::getNumSegments() const noexcept -{ - return fNumSegments; -} - -template<typename T> -void Circle<T>::setNumSegments(const uint num) -{ - DISTRHO_SAFE_ASSERT_RETURN(num >= 3,); - - if (fNumSegments == num) - return; - - fNumSegments = num; - - fTheta = M_2PIf / static_cast<float>(fNumSegments); - fCos = std::cos(fTheta); - fSin = std::sin(fTheta); -} - -template<typename T> -void Circle<T>::draw() -{ - _draw(false); -} - -template<typename T> -void Circle<T>::drawOutline() -{ - _draw(true); -} - -template<typename T> -Circle<T>& Circle<T>::operator=(const Circle<T>& cir) noexcept -{ - fPos = cir.fPos; - fSize = cir.fSize; - fTheta = cir.fTheta; - fCos = cir.fCos; - fSin = cir.fSin; - fNumSegments = cir.fNumSegments; - return *this; -} - -template<typename T> -bool Circle<T>::operator==(const Circle<T>& cir) const noexcept -{ - return (fPos == cir.fPos && d_isEqual(fSize, cir.fSize) && fNumSegments == cir.fNumSegments); -} - -template<typename T> -bool Circle<T>::operator!=(const Circle<T>& cir) const noexcept -{ - return (fPos != cir.fPos || d_isNotEqual(fSize, cir.fSize) || fNumSegments != cir.fNumSegments); -} - -template<typename T> -void Circle<T>::_draw(const bool outline) -{ - DISTRHO_SAFE_ASSERT_RETURN(fNumSegments >= 3 && fSize > 0.0f,); - - float t, x = fSize, y = 0.0f; - - glBegin(outline ? GL_LINE_LOOP : GL_POLYGON); - - for (uint i=0; i<fNumSegments; ++i) - { - glVertex2f(x + fPos.fX, y + fPos.fY); - - t = x; - x = fCos * x - fSin * y; - y = fSin * t + fCos * y; - } - - glEnd(); -} - -// ----------------------------------------------------------------------- -// Triangle - -template<typename T> -Triangle<T>::Triangle() noexcept - : fPos1(0, 0), - fPos2(0, 0), - fPos3(0, 0) {} - -template<typename T> -Triangle<T>::Triangle(const T& x1, const T& y1, const T& x2, const T& y2, const T& x3, const T& y3) noexcept - : fPos1(x1, y1), - fPos2(x2, y2), - fPos3(x3, y3) {} - -template<typename T> -Triangle<T>::Triangle(const Point<T>& pos1, const Point<T>& pos2, const Point<T>& pos3) noexcept - : fPos1(pos1), - fPos2(pos2), - fPos3(pos3) {} - -template<typename T> -Triangle<T>::Triangle(const Triangle<T>& tri) noexcept - : fPos1(tri.fPos1), - fPos2(tri.fPos2), - fPos3(tri.fPos3) {} - -template<typename T> -void Triangle<T>::draw() -{ - _draw(false); -} - -template<typename T> -void Triangle<T>::drawOutline() -{ - _draw(true); -} - -template<typename T> -bool Triangle<T>::isNull() const noexcept -{ - return fPos1 == fPos2 && fPos1 == fPos3; -} - -template<typename T> -bool Triangle<T>::isNotNull() const noexcept -{ - return fPos1 != fPos2 || fPos1 != fPos3; -} - -template<typename T> -bool Triangle<T>::isValid() const noexcept -{ - return fPos1 != fPos2 && fPos1 != fPos3; -} - -template<typename T> -bool Triangle<T>::isInvalid() const noexcept -{ - return fPos1 == fPos2 || fPos1 == fPos3; -} - -template<typename T> -Triangle<T>& Triangle<T>::operator=(const Triangle<T>& tri) noexcept -{ - fPos1 = tri.fPos1; - fPos2 = tri.fPos2; - fPos3 = tri.fPos3; - return *this; -} - -template<typename T> -bool Triangle<T>::operator==(const Triangle<T>& tri) const noexcept -{ - return (fPos1 == tri.fPos1 && fPos2 == tri.fPos2 && fPos3 == tri.fPos3); -} - -template<typename T> -bool Triangle<T>::operator!=(const Triangle<T>& tri) const noexcept -{ - return (fPos1 != tri.fPos1 || fPos2 != tri.fPos2 || fPos3 != tri.fPos3); -} - -template<typename T> -void Triangle<T>::_draw(const bool outline) -{ - DISTRHO_SAFE_ASSERT_RETURN(fPos1 != fPos2 && fPos1 != fPos3,); - - glBegin(outline ? GL_LINE_LOOP : GL_TRIANGLES); - - { - glVertex2d(fPos1.fX, fPos1.fY); - glVertex2d(fPos2.fX, fPos2.fY); - glVertex2d(fPos3.fX, fPos3.fY); - } - - glEnd(); -} - -// ----------------------------------------------------------------------- -// Rectangle - -template<typename T> -Rectangle<T>::Rectangle() noexcept - : fPos(0, 0), - fSize(0, 0) {} - -template<typename T> -Rectangle<T>::Rectangle(const T& x, const T& y, const T& width, const T& height) noexcept - : fPos(x, y), - fSize(width, height) {} - -template<typename T> -Rectangle<T>::Rectangle(const T& x, const T& y, const Size<T>& size) noexcept - : fPos(x, y), - fSize(size) {} - -template<typename T> -Rectangle<T>::Rectangle(const Point<T>& pos, const T& width, const T& height) noexcept - : fPos(pos), - fSize(width, height) {} - -template<typename T> -Rectangle<T>::Rectangle(const Point<T>& pos, const Size<T>& size) noexcept - : fPos(pos), - fSize(size) {} - -template<typename T> -Rectangle<T>::Rectangle(const Rectangle<T>& rect) noexcept - : fPos(rect.fPos), - fSize(rect.fSize) {} - -template<typename T> -const T& Rectangle<T>::getX() const noexcept -{ - return fPos.fX; -} - -template<typename T> -const T& Rectangle<T>::getY() const noexcept -{ - return fPos.fY; -} - -template<typename T> -const T& Rectangle<T>::getWidth() const noexcept -{ - return fSize.fWidth; -} - -template<typename T> -const T& Rectangle<T>::getHeight() const noexcept -{ - return fSize.fHeight; -} - -template<typename T> -const Point<T>& Rectangle<T>::getPos() const noexcept -{ - return fPos; -} - -template<typename T> -const Size<T>& Rectangle<T>::getSize() const noexcept -{ - return fSize; -} - -template<typename T> -void Rectangle<T>::setX(const T& x) noexcept -{ - fPos.fX = x; -} - -template<typename T> -void Rectangle<T>::setY(const T& y) noexcept -{ - fPos.fY = y; -} - -template<typename T> -void Rectangle<T>::setPos(const T& x, const T& y) noexcept -{ - fPos.fX = x; - fPos.fY = y; -} - -template<typename T> -void Rectangle<T>::setPos(const Point<T>& pos) noexcept -{ - fPos = pos; -} - -template<typename T> -void Rectangle<T>::moveBy(const T& x, const T& y) noexcept -{ - fPos.moveBy(x, y); -} - -template<typename T> -void Rectangle<T>::moveBy(const Point<T>& pos) noexcept -{ - fPos.moveBy(pos); -} - -template<typename T> -void Rectangle<T>::setWidth(const T& width) noexcept -{ - fSize.fWidth = width; -} - -template<typename T> -void Rectangle<T>::setHeight(const T& height) noexcept -{ - fSize.fHeight = height; -} - -template<typename T> -void Rectangle<T>::setSize(const T& width, const T& height) noexcept -{ - fSize.fWidth = width; - fSize.fHeight = height; -} - -template<typename T> -void Rectangle<T>::setSize(const Size<T>& size) noexcept -{ - fSize = size; -} - -template<typename T> -void Rectangle<T>::growBy(double multiplier) noexcept -{ - fSize.growBy(multiplier); -} - -template<typename T> -void Rectangle<T>::shrinkBy(double divider) noexcept -{ - fSize.shrinkBy(divider); -} - -template<typename T> -void Rectangle<T>::setRectangle(const Point<T>& pos, const Size<T>& size) noexcept -{ - fPos = pos; - fSize = size; -} - -template<typename T> -void Rectangle<T>::setRectangle(const Rectangle<T>& rect) noexcept -{ - fPos = rect.fPos; - fSize = rect.fSize; -} - -template<typename T> -bool Rectangle<T>::contains(const T& x, const T& y) const noexcept -{ - return (x >= fPos.fX && y >= fPos.fY && x <= fPos.fX+fSize.fWidth && y <= fPos.fY+fSize.fHeight); -} - -template<typename T> -bool Rectangle<T>::contains(const Point<T>& pos) const noexcept -{ - return contains(pos.fX, pos.fY); -} - -template<typename T> -bool Rectangle<T>::containsX(const T& x) const noexcept -{ - return (x >= fPos.fX && x <= fPos.fX + fSize.fWidth); -} - -template<typename T> -bool Rectangle<T>::containsY(const T& y) const noexcept -{ - return (y >= fPos.fY && y <= fPos.fY + fSize.fHeight); -} - -template<typename T> -void Rectangle<T>::draw() -{ - _draw(false); -} - -template<typename T> -void Rectangle<T>::drawOutline() -{ - _draw(true); -} - -template<typename T> -Rectangle<T>& Rectangle<T>::operator=(const Rectangle<T>& rect) noexcept -{ - fPos = rect.fPos; - fSize = rect.fSize; - return *this; -} - -template<typename T> -Rectangle<T>& Rectangle<T>::operator*=(double m) noexcept -{ - fSize *= m; - return *this; -} - -template<typename T> -Rectangle<T>& Rectangle<T>::operator/=(double d) noexcept -{ - fSize /= d; - return *this; -} - -template<typename T> -bool Rectangle<T>::operator==(const Rectangle<T>& rect) const noexcept -{ - return (fPos == rect.fPos && fSize == rect.fSize); -} - -template<typename T> -bool Rectangle<T>::operator!=(const Rectangle<T>& rect) const noexcept -{ - return (fPos != rect.fPos || fSize != rect.fSize); -} - -template<typename T> -void Rectangle<T>::_draw(const bool outline) -{ - DISTRHO_SAFE_ASSERT_RETURN(fSize.isValid(),); - - glBegin(outline ? GL_LINE_LOOP : GL_QUADS); - - { - glTexCoord2f(0.0f, 0.0f); - glVertex2d(fPos.fX, fPos.fY); - - glTexCoord2f(1.0f, 0.0f); - glVertex2d(fPos.fX+fSize.fWidth, fPos.fY); - - glTexCoord2f(1.0f, 1.0f); - glVertex2d(fPos.fX+fSize.fWidth, fPos.fY+fSize.fHeight); - - glTexCoord2f(0.0f, 1.0f); - glVertex2d(fPos.fX, fPos.fY+fSize.fHeight); - } - - glEnd(); -} - -// ----------------------------------------------------------------------- -// Possible template data types - -template class Point<double>; -template class Point<float>; -template class Point<int>; -template class Point<uint>; -template class Point<short>; -template class Point<ushort>; - -template class Size<double>; -template class Size<float>; -template class Size<int>; -template class Size<uint>; -template class Size<short>; -template class Size<ushort>; - -template class Line<double>; -template class Line<float>; -template class Line<int>; -template class Line<uint>; -template class Line<short>; -template class Line<ushort>; - -template class Circle<double>; -template class Circle<float>; -template class Circle<int>; -template class Circle<uint>; -template class Circle<short>; -template class Circle<ushort>; - -template class Triangle<double>; -template class Triangle<float>; -template class Triangle<int>; -template class Triangle<uint>; -template class Triangle<short>; -template class Triangle<ushort>; - -template class Rectangle<double>; -template class Rectangle<float>; -template class Rectangle<int>; -template class Rectangle<uint>; -template class Rectangle<short>; -template class Rectangle<ushort>; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/Image.cpp b/libs/dgl/src/Image.cpp deleted file mode 100644 index 74dceed..0000000 --- a/libs/dgl/src/Image.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../Image.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -Image::Image() - : fRawData(nullptr), - fSize(0, 0), - fFormat(0), - fType(0), - fTextureId(0), - fIsReady(false) -{ - glGenTextures(1, &fTextureId); -} - -Image::Image(const char* const rawData, const uint width, const uint height, const GLenum format, const GLenum type) - : fRawData(rawData), - fSize(width, height), - fFormat(format), - fType(type), - fTextureId(0), - fIsReady(false) -{ - glGenTextures(1, &fTextureId); -} - -Image::Image(const char* const rawData, const Size<uint>& size, const GLenum format, const GLenum type) - : fRawData(rawData), - fSize(size), - fFormat(format), - fType(type), - fTextureId(0), - fIsReady(false) -{ - glGenTextures(1, &fTextureId); -} - -Image::Image(const Image& image) - : fRawData(image.fRawData), - fSize(image.fSize), - fFormat(image.fFormat), - fType(image.fType), - fTextureId(0), - fIsReady(false) -{ - glGenTextures(1, &fTextureId); -} - -Image::~Image() -{ - if (fTextureId != 0) - { - glDeleteTextures(1, &fTextureId); - fTextureId = 0; - } -} - -void Image::loadFromMemory(const char* const rawData, const uint width, const uint height, const GLenum format, const GLenum type) noexcept -{ - loadFromMemory(rawData, Size<uint>(width, height), format, type); -} - -void Image::loadFromMemory(const char* const rawData, const Size<uint>& size, const GLenum format, const GLenum type) noexcept -{ - fRawData = rawData; - fSize = size; - fFormat = format; - fType = type; - fIsReady = false; -} - -bool Image::isValid() const noexcept -{ - return (fRawData != nullptr && fSize.getWidth() > 0 && fSize.getHeight() > 0); -} - -uint Image::getWidth() const noexcept -{ - return fSize.getWidth(); -} - -uint Image::getHeight() const noexcept -{ - return fSize.getHeight(); -} - -const Size<uint>& Image::getSize() const noexcept -{ - return fSize; -} - -const char* Image::getRawData() const noexcept -{ - return fRawData; -} - -GLenum Image::getFormat() const noexcept -{ - return fFormat; -} - -GLenum Image::getType() const noexcept -{ - return fType; -} - -void Image::draw() -{ - drawAt(0, 0); -} - -void Image::drawAt(const int x, const int y) -{ - drawAt(Point<int>(x, y)); -} - -void Image::drawAt(const Point<int>& pos) -{ - if (fTextureId == 0 || ! isValid()) - return; - - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, fTextureId); - - if (! fIsReady) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - - static const float trans[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, trans); - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, - static_cast<GLsizei>(fSize.getWidth()), static_cast<GLsizei>(fSize.getHeight()), 0, - fFormat, fType, fRawData); - - fIsReady = true; - } - - Rectangle<int>(pos, static_cast<int>(fSize.getWidth()), static_cast<int>(fSize.getHeight())).draw(); - - glBindTexture(GL_TEXTURE_2D, 0); - glDisable(GL_TEXTURE_2D); -} - -// ----------------------------------------------------------------------- - -Image& Image::operator=(const Image& image) noexcept -{ - fRawData = image.fRawData; - fSize = image.fSize; - fFormat = image.fFormat; - fType = image.fType; - fIsReady = false; - return *this; -} - -bool Image::operator==(const Image& image) const noexcept -{ - return (fRawData == image.fRawData && fSize == image.fSize); -} - -bool Image::operator!=(const Image& image) const noexcept -{ - return !operator==(image); -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/ImageAboutWindow.cpp b/libs/dgl/src/ImageAboutWindow.cpp deleted file mode 100644 index 9e90f29..0000000 --- a/libs/dgl/src/ImageAboutWindow.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../ImageAboutWindow.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -ImageAboutWindow::ImageAboutWindow(Window& parent, const Image& image) - : Window(parent.getApp(), parent), - Widget((Window&)*this), - fImgBackground(image)/*, - leakDetector_ImageAboutWindow()*/ -{ - Window::setResizable(false); - Window::setSize(static_cast<uint>(image.getWidth()), static_cast<uint>(image.getHeight())); - Window::setTitle("About"); -} - -ImageAboutWindow::ImageAboutWindow(Widget* widget, const Image& image) - : Window(widget->getParentApp(), widget->getParentWindow()), - Widget((Window&)*this), - fImgBackground(image)/*, - leakDetector_ImageAboutWindow()*/ -{ - Window::setResizable(false); - Window::setSize(static_cast<uint>(image.getWidth()), static_cast<uint>(image.getHeight())); - Window::setTitle("About"); -} - -void ImageAboutWindow::setImage(const Image& image) -{ - if (fImgBackground == image) - return; - - fImgBackground = image; - Window::setSize(static_cast<uint>(image.getWidth()), static_cast<uint>(image.getHeight())); -} - -void ImageAboutWindow::onDisplay() -{ - fImgBackground.draw(); -} - -bool ImageAboutWindow::onKeyboard(const KeyboardEvent& ev) -{ - if (ev.press && ev.key == CHAR_ESCAPE) - { - Window::close(); - return true; - } - - return false; -} - -bool ImageAboutWindow::onMouse(const MouseEvent& ev) -{ - if (ev.press) - { - Window::close(); - return true; - } - - return false; -} - -void ImageAboutWindow::onReshape(uint width, uint height) -{ - Widget::setSize(width, height); - Window::onReshape(width, height); -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/ImageButton.cpp b/libs/dgl/src/ImageButton.cpp deleted file mode 100644 index 3502170..0000000 --- a/libs/dgl/src/ImageButton.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../ImageButton.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -ImageButton::ImageButton(Window& parent, const Image& image) noexcept - : Widget(parent), - fImageNormal(image), - fImageHover(image), - fImageDown(image), - fCurImage(&fImageNormal), - fCurButton(-1), - fCallback(nullptr), - leakDetector_ImageButton() {} - -ImageButton::ImageButton(Window& parent, const Image& imageNormal, const Image& imageHover, const Image& imageDown) noexcept - : Widget(parent), - fImageNormal(imageNormal), - fImageHover(imageHover), - fImageDown(imageDown), - fCurImage(&fImageNormal), - fCurButton(-1), - fCallback(nullptr), - leakDetector_ImageButton() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageHover.getSize() && fImageHover.getSize() == fImageDown.getSize()); - - setSize(fCurImage->getSize()); -} - -ImageButton::ImageButton(Widget* widget, const Image& image) noexcept - : Widget(widget->getParentWindow()), - fImageNormal(image), - fImageHover(image), - fImageDown(image), - fCurImage(&fImageNormal), - fCurButton(-1), - fCallback(nullptr), - leakDetector_ImageButton() {} - -ImageButton::ImageButton(Widget* widget, const Image& imageNormal, const Image& imageHover, const Image& imageDown) noexcept - : Widget(widget->getParentWindow()), - fImageNormal(imageNormal), - fImageHover(imageHover), - fImageDown(imageDown), - fCurImage(&fImageNormal), - fCurButton(-1), - fCallback(nullptr), - leakDetector_ImageButton() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageHover.getSize() && fImageHover.getSize() == fImageDown.getSize()); - - setSize(fCurImage->getSize()); -} - -ImageButton::ImageButton(const ImageButton& imageButton) noexcept - : Widget(imageButton.getParentWindow()), - fImageNormal(imageButton.fImageNormal), - fImageHover(imageButton.fImageHover), - fImageDown(imageButton.fImageDown), - fCurImage(&fImageNormal), - fCurButton(-1), - fCallback(imageButton.fCallback), - leakDetector_ImageButton() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageHover.getSize() && fImageHover.getSize() == fImageDown.getSize()); - - setSize(fCurImage->getSize()); -} - -ImageButton& ImageButton::operator=(const ImageButton& imageButton) noexcept -{ - fImageNormal = imageButton.fImageNormal; - fImageHover = imageButton.fImageHover; - fImageDown = imageButton.fImageDown; - fCurImage = &fImageNormal; - fCurButton = -1; - fCallback = imageButton.fCallback; - - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageHover.getSize() && fImageHover.getSize() == fImageDown.getSize()); - - setSize(fCurImage->getSize()); - - return *this; -} - -void ImageButton::setCallback(Callback* callback) noexcept -{ - fCallback = callback; -} - -void ImageButton::onDisplay() -{ - fCurImage->draw(); -} - -bool ImageButton::onMouse(const MouseEvent& ev) -{ - if (fCurButton != -1 && ! ev.press) - { - if (fCurImage != &fImageNormal) - { - fCurImage = &fImageNormal; - repaint(); - } - - if (! contains(ev.pos)) - { - fCurButton = -1; - return false; - } - - if (fCallback != nullptr) - fCallback->imageButtonClicked(this, fCurButton); - -#if 0 - if (contains(ev.pos)) - { - fCurImage = &fImageHover; - repaint(); - } -#endif - - fCurButton = -1; - - return true; - } - - if (ev.press && contains(ev.pos)) - { - if (fCurImage != &fImageDown) - { - fCurImage = &fImageDown; - repaint(); - } - - fCurButton = ev.button; - return true; - } - - return false; -} - -bool ImageButton::onMotion(const MotionEvent& ev) -{ - if (fCurButton != -1) - return true; - - if (contains(ev.pos)) - { - if (fCurImage != &fImageHover) - { - fCurImage = &fImageHover; - repaint(); - } - - return true; - } - else - { - if (fCurImage != &fImageNormal) - { - fCurImage = &fImageNormal; - repaint(); - } - - return false; - } -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/ImageKnob.cpp b/libs/dgl/src/ImageKnob.cpp deleted file mode 100644 index 57dae6a..0000000 --- a/libs/dgl/src/ImageKnob.cpp +++ /dev/null @@ -1,459 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../ImageKnob.hpp" - -#include <cmath> - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -ImageKnob::ImageKnob(Window& parent, const Image& image, Orientation orientation) noexcept - : Widget(parent), - fImage(image), - fMinimum(0.0f), - fMaximum(1.0f), - fStep(0.0f), - fValue(0.5f), - fValueDef(fValue), - fValueTmp(fValue), - fUsingDefault(false), - fUsingLog(false), - fOrientation(orientation), - fRotationAngle(0), - fDragging(false), - fLastX(0), - fLastY(0), - fCallback(nullptr), - fIsImgVertical(image.getHeight() > image.getWidth()), - fImgLayerSize(fIsImgVertical ? image.getWidth() : image.getHeight()), - fImgLayerCount(fIsImgVertical ? image.getHeight()/fImgLayerSize : image.getWidth()/fImgLayerSize), - fIsReady(false), - fTextureId(0), - leakDetector_ImageKnob() -{ - glGenTextures(1, &fTextureId); - setSize(fImgLayerSize, fImgLayerSize); -} - -ImageKnob::ImageKnob(Widget* widget, const Image& image, Orientation orientation) noexcept - : Widget(widget->getParentWindow()), - fImage(image), - fMinimum(0.0f), - fMaximum(1.0f), - fStep(0.0f), - fValue(0.5f), - fValueDef(fValue), - fValueTmp(fValue), - fUsingDefault(false), - fUsingLog(false), - fOrientation(orientation), - fRotationAngle(0), - fDragging(false), - fLastX(0), - fLastY(0), - fCallback(nullptr), - fIsImgVertical(image.getHeight() > image.getWidth()), - fImgLayerSize(fIsImgVertical ? image.getWidth() : image.getHeight()), - fImgLayerCount(fIsImgVertical ? image.getHeight()/fImgLayerSize : image.getWidth()/fImgLayerSize), - fIsReady(false), - fTextureId(0), - leakDetector_ImageKnob() -{ - glGenTextures(1, &fTextureId); - setSize(fImgLayerSize, fImgLayerSize); -} - -ImageKnob::ImageKnob(const ImageKnob& imageKnob) - : Widget(imageKnob.getParentWindow()), - fImage(imageKnob.fImage), - fMinimum(imageKnob.fMinimum), - fMaximum(imageKnob.fMaximum), - fStep(imageKnob.fStep), - fValue(imageKnob.fValue), - fValueDef(imageKnob.fValueDef), - fValueTmp(fValue), - fUsingDefault(imageKnob.fUsingDefault), - fUsingLog(imageKnob.fUsingLog), - fOrientation(imageKnob.fOrientation), - fRotationAngle(imageKnob.fRotationAngle), - fDragging(false), - fLastX(0), - fLastY(0), - fCallback(imageKnob.fCallback), - fIsImgVertical(imageKnob.fIsImgVertical), - fImgLayerSize(imageKnob.fImgLayerSize), - fImgLayerCount(imageKnob.fImgLayerCount), - fIsReady(false), - fTextureId(0), - leakDetector_ImageKnob() -{ - glGenTextures(1, &fTextureId); - setSize(fImgLayerSize, fImgLayerSize); -} - -ImageKnob& ImageKnob::operator=(const ImageKnob& imageKnob) -{ - fImage = imageKnob.fImage; - fMinimum = imageKnob.fMinimum; - fMaximum = imageKnob.fMaximum; - fStep = imageKnob.fStep; - fValue = imageKnob.fValue; - fValueDef = imageKnob.fValueDef; - fValueTmp = fValue; - fUsingDefault = imageKnob.fUsingDefault; - fUsingLog = imageKnob.fUsingLog; - fOrientation = imageKnob.fOrientation; - fRotationAngle = imageKnob.fRotationAngle; - fDragging = false; - fLastX = 0; - fLastY = 0; - fCallback = imageKnob.fCallback; - fIsImgVertical = imageKnob.fIsImgVertical; - fImgLayerSize = imageKnob.fImgLayerSize; - fImgLayerCount = imageKnob.fImgLayerCount; - fIsReady = false; - - if (fTextureId != 0) - { - glDeleteTextures(1, &fTextureId); - fTextureId = 0; - } - - glGenTextures(1, &fTextureId); - setSize(fImgLayerSize, fImgLayerSize); - - return *this; -} - -ImageKnob::~ImageKnob() -{ - if (fTextureId != 0) - { - glDeleteTextures(1, &fTextureId); - fTextureId = 0; - } -} - -float ImageKnob::getValue() const noexcept -{ - return fValue; -} - -// NOTE: value is assumed to be scaled if using log -void ImageKnob::setDefault(float value) noexcept -{ - fValueDef = value; - fUsingDefault = true; -} - -void ImageKnob::setRange(float min, float max) noexcept -{ - DISTRHO_SAFE_ASSERT_RETURN(max > min,); - - if (fValue < min) - { - fValue = min; - repaint(); - - if (fCallback != nullptr) - { - try { - fCallback->imageKnobValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageKnob::setRange < min"); - } - } - else if (fValue > max) - { - fValue = max; - repaint(); - - if (fCallback != nullptr) - { - try { - fCallback->imageKnobValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageKnob::setRange > max"); - } - } - - fMinimum = min; - fMaximum = max; -} - -void ImageKnob::setStep(float step) noexcept -{ - fStep = step; -} - -// NOTE: value is assumed to be scaled if using log -void ImageKnob::setValue(float value, bool sendCallback) noexcept -{ - if (d_isEqual(fValue, value)) - return; - - fValue = value; - - if (d_isZero(fStep)) - fValueTmp = value; - - if (fRotationAngle == 0) - fIsReady = false; - - repaint(); - - if (sendCallback && fCallback != nullptr) - { - try { - fCallback->imageKnobValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageKnob::setValue"); - } -} - -void ImageKnob::setUsingLogScale(bool yesNo) noexcept -{ - fUsingLog = yesNo; -} - -void ImageKnob::setCallback(Callback* callback) noexcept -{ - fCallback = callback; -} - -void ImageKnob::setOrientation(Orientation orientation) noexcept -{ - if (fOrientation == orientation) - return; - - fOrientation = orientation; -} - -void ImageKnob::setRotationAngle(int angle) -{ - if (fRotationAngle == angle) - return; - - fRotationAngle = angle; - fIsReady = false; -} - -void ImageKnob::onDisplay() -{ - const float normValue = ((fUsingLog ? _invlogscale(fValue) : fValue) - fMinimum) / (fMaximum - fMinimum); - - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, fTextureId); - - if (! fIsReady) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - - static const float trans[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, trans); - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - uint imageDataOffset = 0; - - if (fRotationAngle == 0) - { - DISTRHO_SAFE_ASSERT_RETURN(fImgLayerCount > 0,); - DISTRHO_SAFE_ASSERT_RETURN(normValue >= 0.0f,); - - const uint layerDataSize = fImgLayerSize * fImgLayerSize * ((fImage.getFormat() == GL_BGRA || fImage.getFormat() == GL_RGBA) ? 4 : 3); - /* */ imageDataOffset = layerDataSize * uint(normValue * float(fImgLayerCount-1)); - } - - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, - static_cast<GLsizei>(getWidth()), static_cast<GLsizei>(getHeight()), 0, - fImage.getFormat(), fImage.getType(), fImage.getRawData() + imageDataOffset); - - fIsReady = true; - } - - const int w = static_cast<int>(getWidth()); - const int h = static_cast<int>(getHeight()); - - if (fRotationAngle != 0) - { - glPushMatrix(); - - const int w2 = w/2; - const int h2 = h/2; - - glTranslatef(static_cast<float>(w2), static_cast<float>(h2), 0.0f); - glRotatef(normValue*static_cast<float>(fRotationAngle), 0.0f, 0.0f, 1.0f); - - Rectangle<int>(-w2, -h2, w, h).draw(); - - glPopMatrix(); - } - else - { - Rectangle<int>(0, 0, w, h).draw(); - } - - glBindTexture(GL_TEXTURE_2D, 0); - glDisable(GL_TEXTURE_2D); -} - -bool ImageKnob::onMouse(const MouseEvent& ev) -{ - if (ev.button != 1) - return false; - - if (ev.press) - { - if (! contains(ev.pos)) - return false; - - if ((ev.mod & MODIFIER_SHIFT) != 0 && fUsingDefault) - { - setValue(fValueDef, true); - fValueTmp = fValue; - return true; - } - - fDragging = true; - fLastX = ev.pos.getX(); - fLastY = ev.pos.getY(); - - if (fCallback != nullptr) - fCallback->imageKnobDragStarted(this); - - return true; - } - else if (fDragging) - { - if (fCallback != nullptr) - fCallback->imageKnobDragFinished(this); - - fDragging = false; - return true; - } - - return false; -} - -bool ImageKnob::onMotion(const MotionEvent& ev) -{ - if (! fDragging) - return false; - - bool doVal = false; - float d, value = 0.0f; - - if (fOrientation == ImageKnob::Horizontal) - { - if (const int movX = ev.pos.getX() - fLastX) - { - d = (ev.mod & MODIFIER_CTRL) ? 2000.0f : 200.0f; - value = (fUsingLog ? _invlogscale(fValueTmp) : fValueTmp) + (float(fMaximum - fMinimum) / d * float(movX)); - doVal = true; - } - } - else if (fOrientation == ImageKnob::Vertical) - { - if (const int movY = fLastY - ev.pos.getY()) - { - d = (ev.mod & MODIFIER_CTRL) ? 2000.0f : 200.0f; - value = (fUsingLog ? _invlogscale(fValueTmp) : fValueTmp) + (float(fMaximum - fMinimum) / d * float(movY)); - doVal = true; - } - } - - if (! doVal) - return false; - - if (fUsingLog) - value = _logscale(value); - - if (value < fMinimum) - { - fValueTmp = value = fMinimum; - } - else if (value > fMaximum) - { - fValueTmp = value = fMaximum; - } - else if (d_isNotZero(fStep)) - { - fValueTmp = value; - const float rest = std::fmod(value, fStep); - value = value - rest + (rest > fStep/2.0f ? fStep : 0.0f); - } - - setValue(value, true); - - fLastX = ev.pos.getX(); - fLastY = ev.pos.getY(); - - return true; -} - -bool ImageKnob::onScroll(const ScrollEvent& ev) -{ - if (! contains(ev.pos)) - return false; - - const float d = (ev.mod & MODIFIER_CTRL) ? 2000.0f : 200.0f; - float value = (fUsingLog ? _invlogscale(fValueTmp) : fValueTmp) + (float(fMaximum - fMinimum) / d * 10.f * ev.delta.getY()); - - if (fUsingLog) - value = _logscale(value); - - if (value < fMinimum) - { - fValueTmp = value = fMinimum; - } - else if (value > fMaximum) - { - fValueTmp = value = fMaximum; - } - else if (d_isNotZero(fStep)) - { - fValueTmp = value; - const float rest = std::fmod(value, fStep); - value = value - rest + (rest > fStep/2.0f ? fStep : 0.0f); - } - - setValue(value, true); - return true; -} - -// ----------------------------------------------------------------------- - -float ImageKnob::_logscale(float value) const -{ - const float b = std::log(fMaximum/fMinimum)/(fMaximum-fMinimum); - const float a = fMaximum/std::exp(fMaximum*b); - return a * std::exp(b*value); -} - -float ImageKnob::_invlogscale(float value) const -{ - const float b = std::log(fMaximum/fMinimum)/(fMaximum-fMinimum); - const float a = fMaximum/std::exp(fMaximum*b); - return std::log(value/a)/b; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/ImageSlider.cpp b/libs/dgl/src/ImageSlider.cpp deleted file mode 100644 index 12f7b37..0000000 --- a/libs/dgl/src/ImageSlider.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../ImageSlider.hpp" - -#include <cmath> - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -ImageSlider::ImageSlider(Window& parent, const Image& image) noexcept - : Widget(parent), - fImage(image), - fMinimum(0.0f), - fMaximum(1.0f), - fStep(0.0f), - fValue(0.5f), - fValueTmp(fValue), - fDragging(false), - fInverted(false), - fStartedX(0), - fStartedY(0), - fCallback(nullptr), - fStartPos(), - fEndPos(), - fSliderArea(), - leakDetector_ImageSlider() -{ - Widget::setNeedsFullViewport(true); -} - -ImageSlider::ImageSlider(Widget* widget, const Image& image) noexcept - : Widget(widget->getParentWindow()), - fImage(image), - fMinimum(0.0f), - fMaximum(1.0f), - fStep(0.0f), - fValue(0.5f), - fValueTmp(fValue), - fDragging(false), - fInverted(false), - fStartedX(0), - fStartedY(0), - fCallback(nullptr), - fStartPos(), - fEndPos(), - fSliderArea(), - leakDetector_ImageSlider() -{ - Widget::setNeedsFullViewport(true); -} - -ImageSlider::ImageSlider(const ImageSlider& imageSlider) noexcept - : Widget(imageSlider.getParentWindow()), - fImage(imageSlider.fImage), - fMinimum(imageSlider.fMinimum), - fMaximum(imageSlider.fMaximum), - fStep(imageSlider.fStep), - fValue(imageSlider.fValue), - fValueTmp(fValue), - fDragging(false), - fInverted(imageSlider.fInverted), - fStartedX(0), - fStartedY(0), - fCallback(imageSlider.fCallback), - fStartPos(imageSlider.fStartPos), - fEndPos(imageSlider.fEndPos), - fSliderArea(imageSlider.fSliderArea), - leakDetector_ImageSlider() -{ - Widget::setNeedsFullViewport(true); -} - -ImageSlider& ImageSlider::operator=(const ImageSlider& imageSlider) noexcept -{ - fImage = imageSlider.fImage; - fMinimum = imageSlider.fMinimum; - fMaximum = imageSlider.fMaximum; - fStep = imageSlider.fStep; - fValue = imageSlider.fValue; - fValueTmp = fValue; - fDragging = false; - fInverted = imageSlider.fInverted; - fStartedX = 0; - fStartedY = 0; - fCallback = imageSlider.fCallback; - fStartPos = imageSlider.fStartPos; - fEndPos = imageSlider.fEndPos; - fSliderArea = imageSlider.fSliderArea; - - return *this; -} - -float ImageSlider::getValue() const noexcept -{ - return fValue; -} - -void ImageSlider::setStartPos(const Point<int>& startPos) noexcept -{ - fStartPos = startPos; - _recheckArea(); -} - -void ImageSlider::setStartPos(int x, int y) noexcept -{ - setStartPos(Point<int>(x, y)); -} - -void ImageSlider::setEndPos(const Point<int>& endPos) noexcept -{ - fEndPos = endPos; - _recheckArea(); -} - -void ImageSlider::setEndPos(int x, int y) noexcept -{ - setEndPos(Point<int>(x, y)); -} - -void ImageSlider::setInverted(bool inverted) noexcept -{ - if (fInverted == inverted) - return; - - fInverted = inverted; - repaint(); -} - -void ImageSlider::setRange(float min, float max) noexcept -{ - if (fValue < min) - { - fValue = min; - repaint(); - - if (fCallback != nullptr) - { - try { - fCallback->imageSliderValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageSlider::setRange < min"); - } - } - else if (fValue > max) - { - fValue = max; - repaint(); - - if (fCallback != nullptr) - { - try { - fCallback->imageSliderValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageSlider::setRange > max"); - } - } - - fMinimum = min; - fMaximum = max; -} - -void ImageSlider::setStep(float step) noexcept -{ - fStep = step; -} - -void ImageSlider::setValue(float value, bool sendCallback) noexcept -{ - if (d_isEqual(fValue, value)) - return; - - fValue = value; - - if (d_isZero(fStep)) - fValueTmp = value; - - repaint(); - - if (sendCallback && fCallback != nullptr) - { - try { - fCallback->imageSliderValueChanged(this, fValue); - } DISTRHO_SAFE_EXCEPTION("ImageSlider::setValue"); - } -} - -void ImageSlider::setCallback(Callback* callback) noexcept -{ - fCallback = callback; -} - -void ImageSlider::onDisplay() -{ -#if 0 // DEBUG, paints slider area - glColor3f(0.4f, 0.5f, 0.1f); - glRecti(fSliderArea.getX(), fSliderArea.getY(), fSliderArea.getX()+fSliderArea.getWidth(), fSliderArea.getY()+fSliderArea.getHeight()); - glColor4f(1.0f, 1.0f, 1.0f, 1.0f); -#endif - - const float normValue = (fValue - fMinimum) / (fMaximum - fMinimum); - - int x, y; - - if (fStartPos.getY() == fEndPos.getY()) - { - // horizontal - if (fInverted) - x = fEndPos.getX() - static_cast<int>(normValue*static_cast<float>(fEndPos.getX()-fStartPos.getX())); - else - x = fStartPos.getX() + static_cast<int>(normValue*static_cast<float>(fEndPos.getX()-fStartPos.getX())); - - y = fStartPos.getY(); - } - else - { - // vertical - x = fStartPos.getX(); - - if (fInverted) - y = fEndPos.getY() - static_cast<int>(normValue*static_cast<float>(fEndPos.getY()-fStartPos.getY())); - else - y = fStartPos.getY() + static_cast<int>(normValue*static_cast<float>(fEndPos.getY()-fStartPos.getY())); - } - - fImage.drawAt(x, y); -} - -bool ImageSlider::onMouse(const MouseEvent& ev) -{ - if (ev.button != 1) - return false; - - if (ev.press) - { - if (! fSliderArea.contains(ev.pos)) - return false; - - float vper; - const int x = ev.pos.getX(); - const int y = ev.pos.getY(); - - if (fStartPos.getY() == fEndPos.getY()) - { - // horizontal - vper = float(x - fSliderArea.getX()) / float(fSliderArea.getWidth()); - } - else - { - // vertical - vper = float(y - fSliderArea.getY()) / float(fSliderArea.getHeight()); - } - - float value; - - if (fInverted) - value = fMaximum - vper * (fMaximum - fMinimum); - else - value = fMinimum + vper * (fMaximum - fMinimum); - - if (value < fMinimum) - { - fValueTmp = value = fMinimum; - } - else if (value > fMaximum) - { - fValueTmp = value = fMaximum; - } - else if (d_isNotZero(fStep)) - { - fValueTmp = value; - const float rest = std::fmod(value, fStep); - value = value - rest + (rest > fStep/2.0f ? fStep : 0.0f); - } - - fDragging = true; - fStartedX = x; - fStartedY = y; - - if (fCallback != nullptr) - fCallback->imageSliderDragStarted(this); - - setValue(value, true); - - return true; - } - else if (fDragging) - { - if (fCallback != nullptr) - fCallback->imageSliderDragFinished(this); - - fDragging = false; - return true; - } - - return false; -} - -bool ImageSlider::onMotion(const MotionEvent& ev) -{ - if (! fDragging) - return false; - - const bool horizontal = fStartPos.getY() == fEndPos.getY(); - const int x = ev.pos.getX(); - const int y = ev.pos.getY(); - - if ((horizontal && fSliderArea.containsX(x)) || (fSliderArea.containsY(y) && ! horizontal)) - { - float vper; - - if (horizontal) - { - // horizontal - vper = float(x - fSliderArea.getX()) / float(fSliderArea.getWidth()); - } - else - { - // vertical - vper = float(y - fSliderArea.getY()) / float(fSliderArea.getHeight()); - } - - float value; - - if (fInverted) - value = fMaximum - vper * (fMaximum - fMinimum); - else - value = fMinimum + vper * (fMaximum - fMinimum); - - if (value < fMinimum) - { - fValueTmp = value = fMinimum; - } - else if (value > fMaximum) - { - fValueTmp = value = fMaximum; - } - else if (d_isNotZero(fStep)) - { - fValueTmp = value; - const float rest = std::fmod(value, fStep); - value = value - rest + (rest > fStep/2.0f ? fStep : 0.0f); - } - - setValue(value, true); - } - else if (horizontal) - { - if (x < fSliderArea.getX()) - setValue(fInverted ? fMaximum : fMinimum, true); - else - setValue(fInverted ? fMinimum : fMaximum, true); - } - else - { - if (y < fSliderArea.getY()) - setValue(fInverted ? fMaximum : fMinimum, true); - else - setValue(fInverted ? fMinimum : fMaximum, true); - } - - return true; -} - -void ImageSlider::_recheckArea() noexcept -{ - if (fStartPos.getY() == fEndPos.getY()) - { - // horizontal - fSliderArea = Rectangle<int>(fStartPos.getX(), - fStartPos.getY(), - fEndPos.getX() + static_cast<int>(fImage.getWidth()) - fStartPos.getX(), - static_cast<int>(fImage.getHeight())); - } - else - { - // vertical - fSliderArea = Rectangle<int>(fStartPos.getX(), - fStartPos.getY(), - static_cast<int>(fImage.getWidth()), - fEndPos.getY() + static_cast<int>(fImage.getHeight()) - fStartPos.getY()); - } -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/ImageSwitch.cpp b/libs/dgl/src/ImageSwitch.cpp deleted file mode 100644 index 37b3e56..0000000 --- a/libs/dgl/src/ImageSwitch.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../ImageSwitch.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- - -ImageSwitch::ImageSwitch(Window& parent, const Image& imageNormal, const Image& imageDown) noexcept - : Widget(parent), - fImageNormal(imageNormal), - fImageDown(imageDown), - fIsDown(false), - fCallback(nullptr), - leakDetector_ImageSwitch() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageDown.getSize()); - - setSize(fImageNormal.getSize()); -} - -ImageSwitch::ImageSwitch(Widget* widget, const Image& imageNormal, const Image& imageDown) noexcept - : Widget(widget->getParentWindow()), - fImageNormal(imageNormal), - fImageDown(imageDown), - fIsDown(false), - fCallback(nullptr), - leakDetector_ImageSwitch() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageDown.getSize()); - - setSize(fImageNormal.getSize()); -} - -ImageSwitch::ImageSwitch(const ImageSwitch& imageSwitch) noexcept - : Widget(imageSwitch.getParentWindow()), - fImageNormal(imageSwitch.fImageNormal), - fImageDown(imageSwitch.fImageDown), - fIsDown(imageSwitch.fIsDown), - fCallback(imageSwitch.fCallback), - leakDetector_ImageSwitch() -{ - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageDown.getSize()); - - setSize(fImageNormal.getSize()); -} - -ImageSwitch& ImageSwitch::operator=(const ImageSwitch& imageSwitch) noexcept -{ - fImageNormal = imageSwitch.fImageNormal; - fImageDown = imageSwitch.fImageDown; - fIsDown = imageSwitch.fIsDown; - fCallback = imageSwitch.fCallback; - - DISTRHO_SAFE_ASSERT(fImageNormal.getSize() == fImageDown.getSize()); - - setSize(fImageNormal.getSize()); - - return *this; -} - -bool ImageSwitch::isDown() const noexcept -{ - return fIsDown; -} - -void ImageSwitch::setDown(bool down) noexcept -{ - if (fIsDown == down) - return; - - fIsDown = down; - repaint(); -} - -void ImageSwitch::setCallback(Callback* callback) noexcept -{ - fCallback = callback; -} - -void ImageSwitch::onDisplay() -{ - if (fIsDown) - fImageNormal.draw(); - else - fImageDown.draw(); -} - -bool ImageSwitch::onMouse(const MouseEvent& ev) -{ - if (ev.press && contains(ev.pos)) - { - fIsDown = !fIsDown; - - repaint(); - - if (fCallback != nullptr) - fCallback->imageSwitchClicked(this, fIsDown); - - return true; - } - - return false; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/NanoVG.cpp b/libs/dgl/src/NanoVG.cpp deleted file mode 100644 index a4c357b..0000000 --- a/libs/dgl/src/NanoVG.cpp +++ /dev/null @@ -1,780 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../NanoVG.hpp" -#include "../Window.hpp" - -// ----------------------------------------------------------------------- -// Ignore some warnings if debugging - -#if 0 //def DEBUG -# define NANOVG_GL3 0 -# define NANOVG_GLES2 0 -# define NANOVG_GLES3 0 -# define NANOVG_GL_USE_UNIFORMBUFFER 0 -# if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Weverything" -# elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wall" -# pragma GCC diagnostic ignored "-Wextra" -# pragma GCC diagnostic ignored "-Wconversion" -# pragma GCC diagnostic ignored "-Weffc++" -# pragma GCC diagnostic ignored "-Wsign-conversion" -# pragma GCC diagnostic ignored "-Wundef" -# pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" -# endif -#endif - -// ----------------------------------------------------------------------- -// Include NanoVG OpenGL implementation - -#define NANOVG_GL2_IMPLEMENTATION 1 -#include "nanovg/nanovg_gl.h" - -#if defined(NANOVG_GL2) -# define nvgCreateGL nvgCreateGL2 -# define nvgDeleteGL nvgDeleteGL2 -#elif defined(NANOVG_GL3) -# define nvgCreateGL nvgCreateGL3 -# define nvgDeleteGL nvgDeleteGL3 -#elif defined(NANOVG_GLES2) -# define nvgCreateGL nvgCreateGLES2 -# define nvgDeleteGL nvgDeleteGLES2 -#elif defined(NANOVG_GLES3) -# define nvgCreateGL nvgCreateGLES3 -# define nvgDeleteGL nvgDeleteGLES3 -#endif - -// ----------------------------------------------------------------------- -// Restore normal state if debugging - -#if 0//def DEBUG -# if defined(__clang__) -# pragma clang diagnostic pop -# elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -# endif -#endif - -// ----------------------------------------------------------------------- - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Paint - -NanoVG::Paint::Paint() noexcept - : radius(0.0f), feather(0.0f), innerColor(), outerColor(), imageId(0), repeat(REPEAT_NONE) -{ - std::memset(xform, 0, sizeof(float)*6); - std::memset(extent, 0, sizeof(float)*2); -} - -NanoVG::Paint::Paint(const NVGpaint& p) noexcept - : radius(p.radius), feather(p.feather), innerColor(p.innerColor), outerColor(p.outerColor), imageId(p.image), repeat(static_cast<PatternRepeat>(p.repeat)) -{ - std::memcpy(xform, p.xform, sizeof(float)*6); - std::memcpy(extent, p.extent, sizeof(float)*2); -} - -NanoVG::Paint::operator NVGpaint() const noexcept -{ - NVGpaint p; - p.radius = radius; - p.feather = feather; - p.innerColor = innerColor; - p.outerColor = outerColor; - p.image = imageId; - p.repeat = repeat; - std::memcpy(p.xform, xform, sizeof(float)*6); - std::memcpy(p.extent, extent, sizeof(float)*2); - return p; -} - -// ----------------------------------------------------------------------- -// NanoImage - -NanoImage::NanoImage(NVGcontext* const context, const int imageId) noexcept - : fContext(context), - fImageId(imageId), - fSize(), - leakDetector_NanoImage() -{ - _updateSize(); -} - -NanoImage::~NanoImage() -{ - if (fContext != nullptr && fImageId != 0) - nvgDeleteImage(fContext, fImageId); -} - -Size<uint> NanoImage::getSize() const noexcept -{ - return fSize; -} - -void NanoImage::updateImage(const uchar* const data) -{ - DISTRHO_SAFE_ASSERT_RETURN(data != nullptr,); - - if (fContext != nullptr && fImageId != 0) - { - nvgUpdateImage(fContext, fImageId, data); - _updateSize(); - } -} - -void NanoImage::_updateSize() -{ - int w=0, h=0; - - if (fContext != nullptr && fImageId != 0) - { - nvgImageSize(fContext, fImageId, &w, &h); - - if (w < 0) w = 0; - if (h < 0) h = 0; - } - - fSize.setSize(static_cast<uint>(w), static_cast<uint>(h)); -} - -// ----------------------------------------------------------------------- -// NanoVG - -NanoVG::NanoVG() - : fContext(nvgCreateGL(512, 512, NVG_ANTIALIAS)), - fInFrame(false), - leakDetector_NanoVG() -{ - DISTRHO_SAFE_ASSERT_RETURN(fContext != nullptr,); -} - -NanoVG::NanoVG(const int textAtlasWidth, const int textAtlasHeight) - : fContext(nvgCreateGL(textAtlasWidth, textAtlasHeight, NVG_ANTIALIAS)), - fInFrame(false), - leakDetector_NanoVG() -{ - DISTRHO_SAFE_ASSERT_RETURN(fContext != nullptr,); -} - -NanoVG::~NanoVG() -{ - DISTRHO_SAFE_ASSERT(! fInFrame); - - if (fContext != nullptr) - nvgDeleteGL(fContext); -} - -// ----------------------------------------------------------------------- - -void NanoVG::beginFrame(const uint width, const uint height, const float scaleFactor, const Alpha alpha) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(scaleFactor > 0.0f,); - DISTRHO_SAFE_ASSERT_RETURN(! fInFrame,); - - fInFrame = true; - nvgBeginFrame(fContext, static_cast<int>(width), static_cast<int>(height), scaleFactor, static_cast<NVGalpha>(alpha)); -} - -void NanoVG::beginFrame(Widget* const widget) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(widget != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(! fInFrame,); - - Window& window(widget->getParentWindow()); - - fInFrame = true; - nvgBeginFrame(fContext, static_cast<int>(window.getWidth()), static_cast<int>(window.getHeight()), 1.0f, NVG_PREMULTIPLIED_ALPHA); -} - -void NanoVG::endFrame() -{ - DISTRHO_SAFE_ASSERT_RETURN(fInFrame,); - - if (fContext != nullptr) - nvgEndFrame(fContext); - - fInFrame = false; -} - -// ----------------------------------------------------------------------- -// State Handling - -void NanoVG::save() -{ - if (fContext != nullptr) - nvgSave(fContext); -} - -void NanoVG::restore() -{ - if (fContext != nullptr) - nvgRestore(fContext); -} - -void NanoVG::reset() -{ - if (fContext != nullptr) - nvgReset(fContext); -} - -// ----------------------------------------------------------------------- -// Render styles - -void NanoVG::strokeColor(const Color& color) -{ - if (fContext != nullptr) - nvgStrokeColor(fContext, color); -} - -void NanoVG::strokeColor(const int red, const int green, const int blue, const int alpha) -{ - if (fContext != nullptr) - { - DISTRHO_SAFE_ASSERT_RETURN(red >= 0 && red <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(green >= 0 && green <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(blue >= 0 && blue <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(alpha >= 0 && alpha <= 255,); - - nvgStrokeColor(fContext, nvgRGBA(static_cast<uchar>(red), - static_cast<uchar>(green), - static_cast<uchar>(blue), - static_cast<uchar>(alpha))); - } -} - -void NanoVG::strokeColor(const float red, const float green, const float blue, const float alpha) -{ - if (fContext != nullptr) - nvgStrokeColor(fContext, nvgRGBAf(red, green, blue, alpha)); -} - -void NanoVG::strokePaint(const Paint& paint) -{ - if (fContext != nullptr) - nvgStrokePaint(fContext, paint); -} - -void NanoVG::fillColor(const Color& color) -{ - if (fContext != nullptr) - nvgFillColor(fContext, color); -} - -void NanoVG::fillColor(const int red, const int green, const int blue, const int alpha) -{ - if (fContext != nullptr) - { - DISTRHO_SAFE_ASSERT_RETURN(red >= 0 && red <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(green >= 0 && green <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(blue >= 0 && blue <= 255,); - DISTRHO_SAFE_ASSERT_RETURN(alpha >= 0 && alpha <= 255,); - - nvgFillColor(fContext, nvgRGBA(static_cast<uchar>(red), - static_cast<uchar>(green), - static_cast<uchar>(blue), - static_cast<uchar>(alpha))); - } -} - -void NanoVG::fillColor(const float red, const float green, const float blue, const float alpha) -{ - if (fContext != nullptr) - nvgFillColor(fContext, nvgRGBAf(red, green, blue, alpha)); -} - -void NanoVG::fillPaint(const Paint& paint) -{ - if (fContext != nullptr) - nvgFillPaint(fContext, paint); -} - -void NanoVG::miterLimit(float limit) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(limit > 0.0f,); - - nvgMiterLimit(fContext, limit); -} - -void NanoVG::strokeWidth(float size) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(size > 0.0f,); - - nvgStrokeWidth(fContext, size); -} - -void NanoVG::lineCap(NanoVG::LineCap cap) -{ - if (fContext != nullptr) - nvgLineCap(fContext, cap); -} - -void NanoVG::lineJoin(NanoVG::LineCap join) -{ - if (fContext != nullptr) - nvgLineJoin(fContext, join); -} - -// ----------------------------------------------------------------------- -// Transforms - -void NanoVG::resetTransform() -{ - if (fContext != nullptr) - nvgResetTransform(fContext); -} - -void NanoVG::transform(float a, float b, float c, float d, float e, float f) -{ - if (fContext != nullptr) - nvgTransform(fContext, a, b, c, d, e, f); -} - -void NanoVG::translate(float x, float y) -{ - if (fContext != nullptr) - nvgTranslate(fContext, x, y); -} - -void NanoVG::rotate(float angle) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(angle > 0.0f,); - - nvgRotate(fContext, angle); -} - -void NanoVG::skewX(float angle) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(angle > 0.0f,); - - nvgSkewX(fContext, angle); -} - -void NanoVG::skewY(float angle) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(angle > 0.0f,); - - nvgSkewY(fContext, angle); -} - -void NanoVG::scale(float x, float y) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(x > 0.0f,); - DISTRHO_SAFE_ASSERT_RETURN(y > 0.0f,); - - nvgScale(fContext, x, y); -} - -void NanoVG::currentTransform(float xform[6]) -{ - if (fContext != nullptr) - nvgCurrentTransform(fContext, xform); -} - -void NanoVG::transformIdentity(float dst[6]) -{ - nvgTransformIdentity(dst); -} - -void NanoVG::transformTranslate(float dst[6], float tx, float ty) -{ - nvgTransformTranslate(dst, tx, ty); -} - -void NanoVG::transformScale(float dst[6], float sx, float sy) -{ - nvgTransformScale(dst, sx, sy); -} - -void NanoVG::transformRotate(float dst[6], float a) -{ - nvgTransformRotate(dst, a); -} - -void NanoVG::transformSkewX(float dst[6], float a) -{ - nvgTransformSkewX(dst, a); -} - -void NanoVG::transformSkewY(float dst[6], float a) -{ - nvgTransformSkewY(dst, a); -} - -void NanoVG::transformMultiply(float dst[6], const float src[6]) -{ - nvgTransformMultiply(dst, src); -} - -void NanoVG::transformPremultiply(float dst[6], const float src[6]) -{ - nvgTransformPremultiply(dst, src); -} - -int NanoVG::transformInverse(float dst[6], const float src[6]) -{ - return nvgTransformInverse(dst, src); -} - -void NanoVG::transformPoint(float& dstx, float& dsty, const float xform[6], float srcx, float srcy) -{ - nvgTransformPoint(&dstx, &dsty, xform, srcx, srcy); -} - -float NanoVG::degToRad(float deg) -{ - return nvgDegToRad(deg); -} - -float NanoVG::radToDeg(float rad) -{ - return nvgRadToDeg(rad); -} - -// ----------------------------------------------------------------------- -// Images - -NanoImage* NanoVG::createImage(const char* filename) -{ - if (fContext == nullptr) return nullptr; - DISTRHO_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', nullptr); - - if (const int imageId = nvgCreateImage(fContext, filename)) - return new NanoImage(fContext, imageId); - - return nullptr; -} - -NanoImage* NanoVG::createImageMem(uchar* data, int ndata) -{ - if (fContext == nullptr) return nullptr; - DISTRHO_SAFE_ASSERT_RETURN(data != nullptr, nullptr); - DISTRHO_SAFE_ASSERT_RETURN(ndata > 0, nullptr); - - if (const int imageId = nvgCreateImageMem(fContext, data, ndata)) - return new NanoImage(fContext, imageId); - - return nullptr; -} - -NanoImage* NanoVG::createImageRGBA(uint w, uint h, const uchar* data) -{ - if (fContext == nullptr) return nullptr; - DISTRHO_SAFE_ASSERT_RETURN(data != nullptr, nullptr); - - if (const int imageId = nvgCreateImageRGBA(fContext, static_cast<int>(w), static_cast<int>(h), data)) - return new NanoImage(fContext, imageId); - - return nullptr; -} - -// ----------------------------------------------------------------------- -// Paints - -NanoVG::Paint NanoVG::linearGradient(float sx, float sy, float ex, float ey, const Color& icol, const Color& ocol) -{ - if (fContext == nullptr) return Paint(); - return nvgLinearGradient(fContext, sx, sy, ex, ey, icol, ocol); -} - -NanoVG::Paint NanoVG::boxGradient(float x, float y, float w, float h, float r, float f, const Color& icol, const Color& ocol) -{ - if (fContext == nullptr) return Paint(); - return nvgBoxGradient(fContext, x, y, w, h, r, f, icol, ocol); -} - -NanoVG::Paint NanoVG::radialGradient(float cx, float cy, float inr, float outr, const Color& icol, const Color& ocol) -{ - if (fContext == nullptr) return Paint(); - return nvgRadialGradient(fContext, cx, cy, inr, outr, icol, ocol); -} - -NanoVG::Paint NanoVG::imagePattern(float ox, float oy, float ex, float ey, float angle, const NanoImage* image, NanoVG::PatternRepeat repeat) -{ - if (fContext == nullptr) return Paint(); - DISTRHO_SAFE_ASSERT_RETURN(image != nullptr, Paint()); - - return nvgImagePattern(fContext, ox, oy, ex, ey, angle, image->fImageId, repeat); -} - -// ----------------------------------------------------------------------- -// Scissoring - -void NanoVG::scissor(float x, float y, float w, float h) -{ - if (fContext != nullptr) - nvgScissor(fContext, x, y, w, h); -} - -void NanoVG::resetScissor() -{ - if (fContext != nullptr) - nvgResetScissor(fContext); -} - -// ----------------------------------------------------------------------- -// Paths - -void NanoVG::beginPath() -{ - if (fContext != nullptr) - nvgBeginPath(fContext); -} - -void NanoVG::moveTo(float x, float y) -{ - if (fContext != nullptr) - nvgMoveTo(fContext, x, y); -} - -void NanoVG::lineTo(float x, float y) -{ - if (fContext != nullptr) - nvgLineTo(fContext, x, y); -} - -void NanoVG::bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y) -{ - if (fContext != nullptr) - nvgBezierTo(fContext, c1x, c1y, c2x, c2y, x, y); -} - -void NanoVG::arcTo(float x1, float y1, float x2, float y2, float radius) -{ - if (fContext != nullptr) - nvgArcTo(fContext, x1, y1, x2, y2, radius); -} - -void NanoVG::closePath() -{ - if (fContext != nullptr) - nvgClosePath(fContext); -} - -void NanoVG::pathWinding(NanoVG::Winding dir) -{ - if (fContext != nullptr) - nvgPathWinding(fContext, dir); -} - -void NanoVG::arc(float cx, float cy, float r, float a0, float a1, NanoVG::Winding dir) -{ - if (fContext != nullptr) - nvgArc(fContext, cx, cy, r, a0, a1, dir); -} - -void NanoVG::rect(float x, float y, float w, float h) -{ - if (fContext != nullptr) - nvgRect(fContext, x, y, w, h); -} - -void NanoVG::roundedRect(float x, float y, float w, float h, float r) -{ - if (fContext != nullptr) - nvgRoundedRect(fContext, x, y, w, h, r); -} - -void NanoVG::ellipse(float cx, float cy, float rx, float ry) -{ - if (fContext != nullptr) - nvgEllipse(fContext, cx, cy, rx, ry); -} - -void NanoVG::circle(float cx, float cy, float r) -{ - if (fContext != nullptr) - nvgCircle(fContext, cx, cy, r); -} - -void NanoVG::fill() -{ - if (fContext != nullptr) - nvgFill(fContext); -} - -void NanoVG::stroke() -{ - if (fContext != nullptr) - nvgStroke(fContext); -} - -// ----------------------------------------------------------------------- -// Text - -NanoVG::FontId NanoVG::createFont(const char* name, const char* filename) -{ - if (fContext == nullptr) return -1; - DISTRHO_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', -1); - DISTRHO_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', -1); - - return nvgCreateFont(fContext, name, filename); -} - -NanoVG::FontId NanoVG::createFontMem(const char* name, const uchar* data, int ndata, bool freeData) -{ - if (fContext == nullptr) return -1; - DISTRHO_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', -1); - DISTRHO_SAFE_ASSERT_RETURN(data != nullptr, -1); - - return nvgCreateFontMem(fContext, name, const_cast<uchar*>(data), ndata, freeData); -} - -NanoVG::FontId NanoVG::findFont(const char* name) -{ - if (fContext == nullptr) return -1; - DISTRHO_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0', -1); - - return nvgFindFont(fContext, name); -} - -void NanoVG::fontSize(float size) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(size > 0.0f,); - - nvgFontSize(fContext, size); -} - -void NanoVG::fontBlur(float blur) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(blur >= 0.0f,); - - nvgFontBlur(fContext, blur); -} - -void NanoVG::textLetterSpacing(float spacing) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(spacing >= 0.0f,); - - nvgTextLetterSpacing(fContext, spacing); -} - -void NanoVG::textLineHeight(float lineHeight) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(lineHeight > 0.0f,); - - nvgTextLineHeight(fContext, lineHeight); -} - -void NanoVG::textAlign(NanoVG::Align align) -{ - if (fContext != nullptr) - nvgTextAlign(fContext, align); -} - -void NanoVG::textAlign(int align) -{ - if (fContext != nullptr) - nvgTextAlign(fContext, align); -} - -void NanoVG::fontFaceId(FontId font) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(font >= 0,); - - nvgFontFaceId(fContext, font); -} - -void NanoVG::fontFace(const char* font) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(font != nullptr && font[0] != '\0',); - - nvgFontFace(fContext, font); -} - -float NanoVG::text(float x, float y, const char* string, const char* end) -{ - if (fContext == nullptr) return 0.0f; - DISTRHO_SAFE_ASSERT_RETURN(string != nullptr && string[0] != '\0', 0.0f); - - return nvgText(fContext, x, y, string, end); -} - -void NanoVG::textBox(float x, float y, float breakRowWidth, const char* string, const char* end) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(string != nullptr && string[0] != '\0',); - - nvgTextBox(fContext, x, y, breakRowWidth, string, end); -} - -float NanoVG::textBounds(float x, float y, const char* string, const char* end, Rectangle<float>& bounds) -{ - if (fContext == nullptr) return 0.0f; - DISTRHO_SAFE_ASSERT_RETURN(string != nullptr && string[0] != '\0', 0.0f); - - float b[4]; - const float ret = nvgTextBounds(fContext, x, y, string, end, b); - bounds = Rectangle<float>(b[0], b[1], b[2], b[3]); - return ret; -} - -void NanoVG::textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) -{ - if (fContext == nullptr) return; - DISTRHO_SAFE_ASSERT_RETURN(string != nullptr && string[0] != '\0',); - - nvgTextBoxBounds(fContext, x, y, breakRowWidth, string, end, bounds); -} - -int NanoVG::textGlyphPositions(float x, float y, const char* string, const char* end, NanoVG::GlyphPosition* positions, int maxPositions) -{ - if (fContext == nullptr) return 0; - DISTRHO_SAFE_ASSERT_RETURN(string != nullptr && string[0] != '\0', 0); - - return nvgTextGlyphPositions(fContext, x, y, string, end, (NVGglyphPosition*)positions, maxPositions); -} - -void NanoVG::textMetrics(float* ascender, float* descender, float* lineh) -{ - if (fContext != nullptr) - nvgTextMetrics(fContext, ascender, descender, lineh); -} - -int NanoVG::textBreakLines(const char* string, const char* end, float breakRowWidth, NanoVG::TextRow* rows, int maxRows) -{ - if (fContext != nullptr) - return nvgTextBreakLines(fContext, string, end, breakRowWidth, (NVGtextRow*)rows, maxRows); - return 0; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -extern "C" { -#include "nanovg/nanovg.c" -} - -// ----------------------------------------------------------------------- diff --git a/libs/dgl/src/Widget.cpp b/libs/dgl/src/Widget.cpp deleted file mode 100644 index d2898b3..0000000 --- a/libs/dgl/src/Widget.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "../Widget.hpp" -#include "../Window.hpp" - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Widget - -Widget::Widget(Window& parent) - : fParent(parent), - fNeedsFullViewport(false), - fNeedsScaling(false), - fVisible(true), - fId(0), - fAbsolutePos(0, 0), - fSize(0, 0), - leakDetector_Widget() -{ - fParent._addWidget(this); -} - -Widget::~Widget() -{ - fParent._removeWidget(this); -} - -bool Widget::isVisible() const noexcept -{ - return fVisible; -} - -void Widget::setVisible(bool yesNo) -{ - if (fVisible == yesNo) - return; - - fVisible = yesNo; - fParent.repaint(); -} - -void Widget::show() -{ - setVisible(true); -} - -void Widget::hide() -{ - setVisible(false); -} - -uint Widget::getWidth() const noexcept -{ - return fSize.getWidth(); -} - -uint Widget::getHeight() const noexcept -{ - return fSize.getHeight(); -} - -const Size<uint>& Widget::getSize() const noexcept -{ - return fSize; -} - -void Widget::setWidth(uint width) noexcept -{ - if (fSize.getWidth() == width) - return; - - ResizeEvent ev; - ev.oldSize = fSize; - ev.size = Size<uint>(width, fSize.getHeight()); - - fSize.setWidth(width); - onResize(ev); - - fParent.repaint(); -} - -void Widget::setHeight(uint height) noexcept -{ - if (fSize.getHeight() == height) - return; - - ResizeEvent ev; - ev.oldSize = fSize; - ev.size = Size<uint>(fSize.getWidth(), height); - - fSize.setHeight(height); - onResize(ev); - - fParent.repaint(); -} - -void Widget::setSize(uint width, uint height) noexcept -{ - setSize(Size<uint>(width, height)); -} - -void Widget::setSize(const Size<uint>& size) noexcept -{ - if (fSize == size) - return; - - ResizeEvent ev; - ev.oldSize = fSize; - ev.size = size; - - fSize = size; - onResize(ev); - - fParent.repaint(); -} - -int Widget::getAbsoluteX() const noexcept -{ - return fAbsolutePos.getX(); -} - -int Widget::getAbsoluteY() const noexcept -{ - return fAbsolutePos.getY(); -} - -const Point<int>& Widget::getAbsolutePos() const noexcept -{ - return fAbsolutePos; -} - -void Widget::setAbsoluteX(int x) noexcept -{ - if (fAbsolutePos.getX() == x) - return; - - fAbsolutePos.setX(x); - fParent.repaint(); -} - -void Widget::setAbsoluteY(int y) noexcept -{ - if (fAbsolutePos.getY() == y) - return; - - fAbsolutePos.setY(y); - fParent.repaint(); -} - -void Widget::setAbsolutePos(int x, int y) noexcept -{ - setAbsolutePos(Point<int>(x, y)); -} - -void Widget::setAbsolutePos(const Point<int>& pos) noexcept -{ - if (fAbsolutePos == pos) - return; - - fAbsolutePos = pos; - fParent.repaint(); -} - -App& Widget::getParentApp() const noexcept -{ - return fParent.getApp(); -} - -Window& Widget::getParentWindow() const noexcept -{ - return fParent; -} - -bool Widget::contains(int x, int y) const noexcept -{ - return (x >= 0 && y >= 0 && static_cast<uint>(x) < fSize.getWidth() && static_cast<uint>(y) < fSize.getHeight()); -} - -bool Widget::contains(const Point<int>& pos) const noexcept -{ - return contains(pos.getX(), pos.getY()); -} - -void Widget::repaint() noexcept -{ - fParent.repaint(); -} - -uint Widget::getId() const noexcept -{ - return fId; -} - -void Widget::setId(uint id) noexcept -{ - fId = id; -} - -bool Widget::onKeyboard(const KeyboardEvent&) -{ - return false; -} - -bool Widget::onSpecial(const SpecialEvent&) -{ - return false; -} - -bool Widget::onMouse(const MouseEvent&) -{ - return false; -} - -bool Widget::onMotion(const MotionEvent&) -{ - return false; -} - -bool Widget::onScroll(const ScrollEvent&) -{ - return false; -} - -void Widget::onResize(const ResizeEvent&) -{ -} - -void Widget::setNeedsFullViewport(bool yesNo) noexcept -{ - fNeedsFullViewport = yesNo; -} - -void Widget::setNeedsScaling(bool yesNo) noexcept -{ - fNeedsScaling = yesNo; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL diff --git a/libs/dgl/src/Window.cpp b/libs/dgl/src/Window.cpp deleted file mode 100644 index f18aff5..0000000 --- a/libs/dgl/src/Window.cpp +++ /dev/null @@ -1,1213 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -// we need this for now -//#define PUGL_GRAB_FOCUS 1 - -#include "AppPrivateData.hpp" -#include "../Widget.hpp" -#include "../Window.hpp" -#include "../../distrho/extra/d_string.hpp" - -#include "pugl/pugl.h" - -#if defined(DISTRHO_OS_WINDOWS) -# include "pugl/pugl_win.cpp" -#elif defined(DISTRHO_OS_MAC) -# include "pugl/pugl_osx.m" -#elif defined(DISTRHO_OS_LINUX) -# include <sys/types.h> -# include <unistd.h> -extern "C" { -# include "pugl/pugl_x11.c" -} -#else -# error Unsupported platform -#endif - -#define FOR_EACH_WIDGET(it) \ - for (std::list<Widget*>::iterator it = fWidgets.begin(); it != fWidgets.end(); ++it) - -#define FOR_EACH_WIDGET_INV(rit) \ - for (std::list<Widget*>::reverse_iterator rit = fWidgets.rbegin(); rit != fWidgets.rend(); ++rit) - -#ifdef DEBUG -# define DBG(msg) std::fprintf(stderr, "%s", msg); -# define DBGp(...) std::fprintf(stderr, __VA_ARGS__); -# define DBGF std::fflush(stderr); -#else -# define DBG(msg) -# define DBGp(...) -# define DBGF -#endif - -START_NAMESPACE_DGL - -// ----------------------------------------------------------------------- -// Window Private - -struct Window::PrivateData { - PrivateData(App& app, Window* const self) - : fApp(app), - fSelf(self), - fView(puglInit()), - fFirstInit(true), - fVisible(false), - fResizable(true), - fUsingEmbed(false), - fWidth(1), - fHeight(1), - fTitle(nullptr), - fWidgets(), - fModal(), -#if defined(DISTRHO_OS_WINDOWS) - hwnd(0), -#elif defined(DISTRHO_OS_LINUX) - xDisplay(nullptr), - xWindow(0), -#elif defined(DISTRHO_OS_MAC) - fNeedsIdle(true), - mView(nullptr), - mWindow(nullptr), -#endif - leakDetector_PrivateData() - { - DBG("Creating window without parent..."); DBGF; - init(); - } - - PrivateData(App& app, Window* const self, Window& parent) - : fApp(app), - fSelf(self), - fView(puglInit()), - fFirstInit(true), - fVisible(false), - fResizable(true), - fUsingEmbed(false), - fWidth(1), - fHeight(1), - fTitle(nullptr), - fWidgets(), - fModal(parent.pData), -#if defined(DISTRHO_OS_WINDOWS) - hwnd(0), -#elif defined(DISTRHO_OS_LINUX) - xDisplay(nullptr), - xWindow(0), -#elif defined(DISTRHO_OS_MAC) - fNeedsIdle(false), - mView(nullptr), - mWindow(nullptr), -#endif - leakDetector_PrivateData() - { - DBG("Creating window with parent..."); DBGF; - init(); - - const PuglInternals* const parentImpl(parent.pData->fView->impl); -#if defined(DISTRHO_OS_LINUX) - XSetTransientForHint(xDisplay, xWindow, parentImpl->win); -//#elif defined(DISTRHO_OS_MAC) -// [parentImpl->window orderWindow:NSWindowBelow relativeTo:[[mView window] windowNumber]]; -#else - // unused - return; (void)parentImpl; -#endif - } - - PrivateData(App& app, Window* const self, const intptr_t parentId) - : fApp(app), - fSelf(self), - fView(puglInit()), - fFirstInit(true), - fVisible(parentId != 0), - fResizable(parentId == 0), - fUsingEmbed(parentId != 0), - fWidth(1), - fHeight(1), - fTitle(nullptr), - fWidgets(), - fModal(), -#if defined(DISTRHO_OS_WINDOWS) - hwnd(0), -#elif defined(DISTRHO_OS_LINUX) - xDisplay(nullptr), - xWindow(0), -#elif defined(DISTRHO_OS_MAC) - fNeedsIdle(parentId == 0), - mView(nullptr), - mWindow(nullptr), -#endif - leakDetector_PrivateData() - { - if (fUsingEmbed) - { - DBG("Creating embedded window..."); DBGF; - puglInitWindowParent(fView, parentId); - } - else - { - DBG("Creating window without parent..."); DBGF; - } - - init(); - - if (fUsingEmbed) - { - DBG("NOTE: Embed window is always visible and non-resizable\n"); - puglShowWindow(fView); - fApp.pData->oneShown(); - fFirstInit = false; - } - } - - void init() - { - if (fSelf == nullptr || fView == nullptr) - { - DBG("Failed!\n"); - return; - } - - puglInitResizable(fView, fResizable); - puglInitWindowSize(fView, static_cast<int>(fWidth), static_cast<int>(fHeight)); - - puglSetHandle(fView, this); - puglSetDisplayFunc(fView, onDisplayCallback); - puglSetKeyboardFunc(fView, onKeyboardCallback); - puglSetMotionFunc(fView, onMotionCallback); - puglSetMouseFunc(fView, onMouseCallback); - puglSetScrollFunc(fView, onScrollCallback); - puglSetSpecialFunc(fView, onSpecialCallback); - puglSetReshapeFunc(fView, onReshapeCallback); - puglSetCloseFunc(fView, onCloseCallback); - puglSetFileSelectedFunc(fView, fileBrowserSelectedCallback); - - puglCreateWindow(fView, nullptr); - - PuglInternals* impl = fView->impl; -#if defined(DISTRHO_OS_WINDOWS) - hwnd = impl->hwnd; - DISTRHO_SAFE_ASSERT(hwnd != 0); -#elif defined(DISTRHO_OS_MAC) - mView = impl->glview; - mWindow = impl->window; - DISTRHO_SAFE_ASSERT(mView != nullptr); - if (fUsingEmbed) { - DISTRHO_SAFE_ASSERT(mWindow == nullptr); - } else { - DISTRHO_SAFE_ASSERT(mWindow != nullptr); - } -#elif defined(DISTRHO_OS_LINUX) - xDisplay = impl->display; - xWindow = impl->win; - DISTRHO_SAFE_ASSERT(xWindow != 0); - - if (! fUsingEmbed) - { - pid_t pid = getpid(); - Atom _nwp = XInternAtom(xDisplay, "_NET_WM_PID", True); - XChangeProperty(xDisplay, xWindow, _nwp, XA_CARDINAL, 32, PropModeReplace, (const uchar*)&pid, 1); - } -#endif - - fApp.pData->windows.push_back(fSelf); - - DBG("Success!\n"); - } - - ~PrivateData() - { - DBG("Destroying window..."); DBGF; - - if (fModal.enabled) - { - exec_fini(); - close(); - } - - fWidgets.clear(); - - if (fUsingEmbed) - { - puglHideWindow(fView); - fApp.pData->oneHidden(); - } - - if (fSelf != nullptr) - { - fApp.pData->windows.remove(fSelf); - fSelf = nullptr; - } - - if (fView != nullptr) - { - puglDestroy(fView); - fView = nullptr; - } - -#if defined(DISTRHO_OS_WINDOWS) - hwnd = 0; -#elif defined(DISTRHO_OS_MAC) - mView = nullptr; - mWindow = nullptr; -#elif defined(DISTRHO_OS_LINUX) - xDisplay = nullptr; - xWindow = 0; -#endif - - DBG("Success!\n"); - } - - // ------------------------------------------------------------------- - - void close() - { - DBG("Window close\n"); - - if (fUsingEmbed) - return; - - setVisible(false); - - if (! fFirstInit) - { - fApp.pData->oneHidden(); - fFirstInit = true; - } - } - - void exec(const bool lockWait) - { - DBG("Window exec\n"); - exec_init(); - - if (lockWait) - { - for (; fVisible && fModal.enabled;) - { - idle(); - d_msleep(10); - } - - exec_fini(); - } - else - { - idle(); - } - } - - // ------------------------------------------------------------------- - - void exec_init() - { - DBG("Window modal loop starting..."); DBGF; - DISTRHO_SAFE_ASSERT_RETURN(fModal.parent != nullptr, setVisible(true)); - - fModal.enabled = true; - fModal.parent->fModal.childFocus = this; - -#ifdef DISTRHO_OS_WINDOWS - // Center this window - PuglInternals* const parentImpl = fModal.parent->fView->impl; - - RECT curRect; - RECT parentRect; - GetWindowRect(hwnd, &curRect); - GetWindowRect(parentImpl->hwnd, &parentRect); - - int x = parentRect.left+(parentRect.right-curRect.right)/2; - int y = parentRect.top +(parentRect.bottom-curRect.bottom)/2; - - SetWindowPos(hwnd, 0, x, y, 0, 0, SWP_NOACTIVATE|SWP_NOOWNERZORDER|SWP_NOSIZE|SWP_NOZORDER); - UpdateWindow(hwnd); -#endif - - fModal.parent->setVisible(true); - setVisible(true); - - DBG("Ok\n"); - } - - void exec_fini() - { - DBG("Window modal loop stopping..."); DBGF; - fModal.enabled = false; - - if (fModal.parent != nullptr) - fModal.parent->fModal.childFocus = nullptr; - - DBG("Ok\n"); - } - - // ------------------------------------------------------------------- - - void focus() - { - DBG("Window focus\n"); -#if defined(DISTRHO_OS_WINDOWS) - SetForegroundWindow(hwnd); - SetActiveWindow(hwnd); - SetFocus(hwnd); -#elif defined(DISTRHO_OS_MAC) - if (mWindow != nullptr) - { - // TODO - //[NSApp activateIgnoringOtherApps:YES]; - //[mWindow makeKeyAndOrderFront:mWindow]; - } -#elif defined(DISTRHO_OS_LINUX) - XRaiseWindow(xDisplay, xWindow); - XSetInputFocus(xDisplay, xWindow, RevertToPointerRoot, CurrentTime); - XFlush(xDisplay); -#endif - } - - // ------------------------------------------------------------------- - - void setVisible(const bool yesNo) - { - if (fVisible == yesNo) - { - DBG("Window setVisible matches current state, ignoring request\n"); - return; - } - if (fUsingEmbed) - { - DBG("Window setVisible cannot be called when embedded\n"); - return; - } - - DBG("Window setVisible called\n"); - - fVisible = yesNo; - - if (yesNo && fFirstInit) - setSize(fWidth, fHeight, true); - -#if defined(DISTRHO_OS_WINDOWS) - if (yesNo) - ShowWindow(hwnd, fFirstInit ? SW_SHOWNORMAL : SW_RESTORE); - else - ShowWindow(hwnd, SW_HIDE); - - UpdateWindow(hwnd); -#elif defined(DISTRHO_OS_MAC) - if (yesNo) - { - if (mWindow != nullptr) - [mWindow setIsVisible:YES]; - else - [mView setHidden:NO]; - } - else - { - if (mWindow != nullptr) - [mWindow setIsVisible:NO]; - else - [mView setHidden:YES]; - } -#elif defined(DISTRHO_OS_LINUX) - if (yesNo) - XMapRaised(xDisplay, xWindow); - else - XUnmapWindow(xDisplay, xWindow); - - XFlush(xDisplay); -#endif - - if (yesNo) - { - if (fFirstInit) - { - fApp.pData->oneShown(); - fFirstInit = false; - } - } - else if (fModal.enabled) - exec_fini(); - } - - // ------------------------------------------------------------------- - - void setResizable(const bool yesNo) - { - if (fResizable == yesNo) - { - DBG("Window setResizable matches current state, ignoring request\n"); - return; - } - if (fUsingEmbed) - { - DBG("Window setResizable cannot be called when embedded\n"); - return; - } - - DBG("Window setResizable called\n"); - - fResizable = yesNo; - -#if defined(DISTRHO_OS_WINDOWS) - const int winFlags = fResizable ? GetWindowLong(hwnd, GWL_STYLE) | WS_SIZEBOX - : GetWindowLong(hwnd, GWL_STYLE) & ~WS_SIZEBOX; - SetWindowLong(hwnd, GWL_STYLE, winFlags); -#elif defined(DISTRHO_OS_MAC) - // FIXME? - const uint flags(yesNo ? (NSViewWidthSizable|NSViewHeightSizable) : 0x0); - [mView setAutoresizingMask:flags]; -#endif - - setSize(fWidth, fHeight, true); - } - - // ------------------------------------------------------------------- - - void setSize(uint width, uint height, const bool forced = false) - { - if (width <= 1 || height <= 1) - { - DBGp("Window setSize called with invalid value(s) %i %i, ignoring request\n", width, height); - return; - } - - if (fWidth == width && fHeight == height && ! forced) - { - DBGp("Window setSize matches current size, ignoring request (%i %i)\n", width, height); - return; - } - - fWidth = width; - fHeight = height; - - DBGp("Window setSize called %s, size %i %i, resizable %s\n", forced ? "(forced)" : "(not forced)", width, height, fResizable?"true":"false"); - -#if defined(DISTRHO_OS_WINDOWS) - const int winFlags = WS_POPUPWINDOW | WS_CAPTION | (fResizable ? WS_SIZEBOX : 0x0); - RECT wr = { 0, 0, static_cast<long>(width), static_cast<long>(height) }; - AdjustWindowRectEx(&wr, fUsingEmbed ? WS_CHILD : winFlags, FALSE, WS_EX_TOPMOST); - - SetWindowPos(hwnd, 0, 0, 0, wr.right-wr.left, wr.bottom-wr.top, - SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOOWNERZORDER|SWP_NOZORDER); - - if (! forced) - UpdateWindow(hwnd); -#elif defined(DISTRHO_OS_MAC) - [mView setFrame:NSMakeRect(0, 0, width, height)]; - - if (mWindow != nullptr) - { - [mWindow setContentSize:NSMakeSize(width, height)]; - } -#elif defined(DISTRHO_OS_LINUX) - XResizeWindow(xDisplay, xWindow, width, height); - - if (! fResizable) - { - XSizeHints sizeHints; - memset(&sizeHints, 0, sizeof(sizeHints)); - - sizeHints.flags = PSize|PMinSize|PMaxSize; - sizeHints.width = static_cast<int>(width); - sizeHints.height = static_cast<int>(height); - sizeHints.min_width = static_cast<int>(width); - sizeHints.min_height = static_cast<int>(height); - sizeHints.max_width = static_cast<int>(width); - sizeHints.max_height = static_cast<int>(height); - - XSetNormalHints(xDisplay, xWindow, &sizeHints); - } - - if (! forced) - XFlush(xDisplay); -#endif - - puglPostRedisplay(fView); - } - - // ------------------------------------------------------------------- - - const char* getTitle() const noexcept - { - static const char* const kFallback = ""; - - return fTitle != nullptr ? fTitle : kFallback; - } - - void setTitle(const char* const title) - { - DBGp("Window setTitle \"%s\"\n", title); - - if (fTitle != nullptr) - std::free(fTitle); - - fTitle = strdup(title); - -#if defined(DISTRHO_OS_WINDOWS) - SetWindowTextA(hwnd, title); -#elif defined(DISTRHO_OS_MAC) - if (mWindow != nullptr) - { - NSString* titleString = [[NSString alloc] - initWithBytes:title - length:strlen(title) - encoding:NSUTF8StringEncoding]; - - [mWindow setTitle:titleString]; - } -#elif defined(DISTRHO_OS_LINUX) - XStoreName(xDisplay, xWindow, title); -#endif - } - - void setTransientWinId(const uintptr_t winId) - { -#if defined(DISTRHO_OS_LINUX) - XSetTransientForHint(xDisplay, xWindow, static_cast< ::Window>(winId)); -#else - return; - // unused - (void)winId; -#endif - } - - // ------------------------------------------------------------------- - - void addWidget(Widget* const widget) - { - fWidgets.push_back(widget); - } - - void removeWidget(Widget* const widget) - { - fWidgets.remove(widget); - } - - void idle() - { - puglProcessEvents(fView); - -#ifdef DISTRHO_OS_MAC - if (fNeedsIdle) - { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSEvent* event; - - for (;;) - { - event = [NSApp - nextEventMatchingMask:NSAnyEventMask - untilDate:[NSDate distantPast] - inMode:NSDefaultRunLoopMode - dequeue:YES]; - - if (event == nil) - break; - - [NSApp sendEvent: event]; - } - - [pool release]; - } -#endif - - if (fModal.enabled && fModal.parent != nullptr) - fModal.parent->idle(); - } - - // ------------------------------------------------------------------- - - void onPuglDisplay() - { - fSelf->onDisplayBefore(); - - bool needsDisableScissor = false; - - FOR_EACH_WIDGET(it) - { - Widget* const widget(*it); - - if (widget->isVisible()) - { - // reset color - glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - - if (widget->fNeedsFullViewport || (widget->fAbsolutePos.isZero() && widget->fSize == Size<uint>(fWidth, fHeight))) - { - // full viewport size - glViewport(0, - 0, - static_cast<GLsizei>(fWidth), - static_cast<GLsizei>(fHeight)); - } - else if (! widget->fNeedsScaling) - { - // only set viewport pos - glViewport(widget->getAbsoluteX(), - /*fView->height - static_cast<int>(widget->getHeight())*/ - widget->getAbsoluteY(), - static_cast<GLsizei>(fWidth), - static_cast<GLsizei>(fHeight)); - - // then cut the outer bounds - glScissor(widget->getAbsoluteX(), - fView->height - static_cast<int>(widget->getHeight()) - widget->getAbsoluteY(), - static_cast<GLsizei>(widget->getWidth()), - static_cast<GLsizei>(widget->getHeight())); - - glEnable(GL_SCISSOR_TEST); - needsDisableScissor = true; - } - else - { - // limit viewport to widget bounds - glViewport(widget->getAbsoluteX(), - fView->height - static_cast<int>(widget->getHeight()) - widget->getAbsoluteY(), - static_cast<GLsizei>(widget->getWidth()), - static_cast<GLsizei>(widget->getHeight())); - } - - // display widget - widget->onDisplay(); - - if (needsDisableScissor) - { - glDisable(GL_SCISSOR_TEST); - needsDisableScissor = false; - } - } - } - - fSelf->onDisplayAfter(); - } - - void onPuglKeyboard(const bool press, const uint key) - { - DBGp("PUGL: onKeyboard : %i %i\n", press, key); - - if (fModal.childFocus != nullptr) - return fModal.childFocus->focus(); - - Widget::KeyboardEvent ev; - ev.press = press; - ev.key = key; - ev.mod = static_cast<Modifier>(puglGetModifiers(fView)); - ev.time = puglGetEventTimestamp(fView); - - FOR_EACH_WIDGET_INV(rit) - { - Widget* const widget(*rit); - - if (widget->isVisible() && widget->onKeyboard(ev)) - break; - } - } - - void onPuglSpecial(const bool press, const Key key) - { - DBGp("PUGL: onSpecial : %i %i\n", press, key); - - if (fModal.childFocus != nullptr) - return fModal.childFocus->focus(); - - Widget::SpecialEvent ev; - ev.press = press; - ev.key = key; - ev.mod = static_cast<Modifier>(puglGetModifiers(fView)); - ev.time = puglGetEventTimestamp(fView); - - FOR_EACH_WIDGET_INV(rit) - { - Widget* const widget(*rit); - - if (widget->isVisible() && widget->onSpecial(ev)) - break; - } - } - - void onPuglMouse(const int button, const bool press, const int x, const int y) - { - DBGp("PUGL: onMouse : %i %i %i %i\n", button, press, x, y); - - // FIXME - pugl sends 2 of these for each window on init, don't ask me why. we'll ignore it - if (press && button == 0 && x == 0 && y == 0) return; - - if (fModal.childFocus != nullptr) - return fModal.childFocus->focus(); - - Widget::MouseEvent ev; - ev.button = button; - ev.press = press; - ev.mod = static_cast<Modifier>(puglGetModifiers(fView)); - ev.time = puglGetEventTimestamp(fView); - - FOR_EACH_WIDGET_INV(rit) - { - Widget* const widget(*rit); - - ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY()); - - if (widget->isVisible() && widget->onMouse(ev)) - break; - } - } - - void onPuglMotion(const int x, const int y) - { - DBGp("PUGL: onMotion : %i %i\n", x, y); - - if (fModal.childFocus != nullptr) - return; - - Widget::MotionEvent ev; - ev.mod = static_cast<Modifier>(puglGetModifiers(fView)); - ev.time = puglGetEventTimestamp(fView); - - FOR_EACH_WIDGET_INV(rit) - { - Widget* const widget(*rit); - - ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY()); - - if (widget->isVisible() && widget->onMotion(ev)) - break; - } - } - - void onPuglScroll(const int x, const int y, const float dx, const float dy) - { - DBGp("PUGL: onScroll : %i %i %f %f\n", x, y, dx, dy); - - if (fModal.childFocus != nullptr) - return; - - Widget::ScrollEvent ev; - ev.delta = Point<float>(dx, dy); - ev.mod = static_cast<Modifier>(puglGetModifiers(fView)); - ev.time = puglGetEventTimestamp(fView); - - FOR_EACH_WIDGET_INV(rit) - { - Widget* const widget(*rit); - - ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY()); - - if (widget->isVisible() && widget->onScroll(ev)) - break; - } - } - - void onPuglReshape(const int width, const int height) - { - DBGp("PUGL: onReshape : %i %i\n", width, height); - - if (width <= 1 && height <= 1) - return; - - fWidth = static_cast<uint>(width); - fHeight = static_cast<uint>(height); - - fSelf->onReshape(fWidth, fHeight); - - FOR_EACH_WIDGET(it) - { - Widget* const widget(*it); - - if (widget->fNeedsFullViewport) - widget->setSize(fWidth, fHeight); - } - } - - void onPuglClose() - { - DBG("PUGL: onClose\n"); - - if (fModal.enabled) - exec_fini(); - - fSelf->onClose(); - - if (fModal.childFocus != nullptr) - fModal.childFocus->fSelf->onClose(); - - close(); - } - - // ------------------------------------------------------------------- - - App& fApp; - Window* fSelf; - PuglView* fView; - - bool fFirstInit; - bool fVisible; - bool fResizable; - bool fUsingEmbed; - uint fWidth; - uint fHeight; - char* fTitle; - std::list<Widget*> fWidgets; - - struct Modal { - bool enabled; - PrivateData* parent; - PrivateData* childFocus; - - Modal() - : enabled(false), - parent(nullptr), - childFocus(nullptr) {} - - Modal(PrivateData* const p) - : enabled(false), - parent(p), - childFocus(nullptr) {} - - ~Modal() - { - DISTRHO_SAFE_ASSERT(! enabled); - DISTRHO_SAFE_ASSERT(childFocus == nullptr); - } - - DISTRHO_DECLARE_NON_COPY_STRUCT(Modal) - } fModal; - -#if defined(DISTRHO_OS_WINDOWS) - HWND hwnd; -#elif defined(DISTRHO_OS_LINUX) - Display* xDisplay; - ::Window xWindow; -#elif defined(DISTRHO_OS_MAC) - bool fNeedsIdle; - PuglOpenGLView* mView; - id mWindow; -#endif - - // ------------------------------------------------------------------- - // Callbacks - - #define handlePtr ((PrivateData*)puglGetHandle(view)) - - static void onDisplayCallback(PuglView* view) - { - handlePtr->onPuglDisplay(); - } - - static void onKeyboardCallback(PuglView* view, bool press, uint32_t key) - { - handlePtr->onPuglKeyboard(press, key); - } - - static void onSpecialCallback(PuglView* view, bool press, PuglKey key) - { - handlePtr->onPuglSpecial(press, static_cast<Key>(key)); - } - - static void onMouseCallback(PuglView* view, int button, bool press, int x, int y) - { - handlePtr->onPuglMouse(button, press, x, y); - } - - static void onMotionCallback(PuglView* view, int x, int y) - { - handlePtr->onPuglMotion(x, y); - } - - static void onScrollCallback(PuglView* view, int x, int y, float dx, float dy) - { - handlePtr->onPuglScroll(x, y, dx, dy); - } - - static void onReshapeCallback(PuglView* view, int width, int height) - { - handlePtr->onPuglReshape(width, height); - } - - static void onCloseCallback(PuglView* view) - { - handlePtr->onPuglClose(); - } - - static void fileBrowserSelectedCallback(PuglView* view, const char* filename) - { - handlePtr->fSelf->fileBrowserSelected(filename); - } - - #undef handlePtr - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PrivateData) -}; - -// ----------------------------------------------------------------------- -// Window - -Window::Window(App& app) - : pData(new PrivateData(app, this)), - leakDetector_Window() {} - -Window::Window(App& app, Window& parent) - : pData(new PrivateData(app, this, parent)), - leakDetector_Window() {} - -Window::Window(App& app, intptr_t parentId) - : pData(new PrivateData(app, this, parentId)), - leakDetector_Window() {} - -Window::~Window() -{ - delete pData; -} - -void Window::show() -{ - pData->setVisible(true); -} - -void Window::hide() -{ - pData->setVisible(false); -} - -void Window::close() -{ - pData->close(); -} - -void Window::exec(bool lockWait) -{ - pData->exec(lockWait); -} - -void Window::focus() -{ - pData->focus(); -} - -void Window::repaint() noexcept -{ - puglPostRedisplay(pData->fView); -} - -// static int fib_filter_filename_filter(const char* const name) -// { -// return 1; -// (void)name; -// } - -bool Window::openFileBrowser(const FileBrowserOptions& options) -{ -#ifdef SOFD_HAVE_X11 - using DISTRHO_NAMESPACE::d_string; - - // -------------------------------------------------------------------------- - // configure start dir - - // TODO: get abspath if needed - // TODO: cross-platform - - d_string startDir(options.startDir); - - if (startDir.isEmpty()) - { - if (char* const dir_name = get_current_dir_name()) - { - startDir = dir_name; - std::free(dir_name); - } - } - - DISTRHO_SAFE_ASSERT_RETURN(startDir.isNotEmpty(), false); - - if (! startDir.endsWith('/')) - startDir += "/"; - - DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, false); - - // -------------------------------------------------------------------------- - // configure title - - d_string title(options.title); - - if (title.isEmpty()) - { - title = pData->getTitle(); - - if (title.isEmpty()) - title = "FileBrowser"; - } - - DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, title) == 0, false); - - // -------------------------------------------------------------------------- - // configure filters - - x_fib_cfg_filter_callback(nullptr); //fib_filter_filename_filter); - - // -------------------------------------------------------------------------- - // configure buttons - - x_fib_cfg_buttons(3, options.buttons.listAllFiles-1); - x_fib_cfg_buttons(1, options.buttons.showHidden-1); - x_fib_cfg_buttons(2, options.buttons.showPlaces-1); - - // -------------------------------------------------------------------------- - // show - - return (x_fib_show(pData->xDisplay, pData->xWindow, /*options.width*/0, /*options.height*/0) == 0); -#else - // not implemented - return false; -#endif -} - -bool Window::isVisible() const noexcept -{ - return pData->fVisible; -} - -void Window::setVisible(bool yesNo) -{ - pData->setVisible(yesNo); -} - -bool Window::isResizable() const noexcept -{ - return pData->fResizable; -} - -void Window::setResizable(bool yesNo) -{ - pData->setResizable(yesNo); -} - -uint Window::getWidth() const noexcept -{ - return pData->fWidth; -} - -uint Window::getHeight() const noexcept -{ - return pData->fHeight; -} - -Size<uint> Window::getSize() const noexcept -{ - return Size<uint>(pData->fWidth, pData->fHeight); -} - -void Window::setSize(uint width, uint height) -{ - pData->setSize(width, height); -} - -void Window::setSize(Size<uint> size) -{ - pData->setSize(size.getWidth(), size.getHeight()); -} - -const char* Window::getTitle() const noexcept -{ - return pData->getTitle(); -} - -void Window::setTitle(const char* title) -{ - pData->setTitle(title); -} - -void Window::setTransientWinId(uintptr_t winId) -{ - pData->setTransientWinId(winId); -} - -App& Window::getApp() const noexcept -{ - return pData->fApp; -} - -intptr_t Window::getWindowId() const noexcept -{ - return puglGetNativeWindow(pData->fView); -} - -void Window::_addWidget(Widget* const widget) -{ - pData->addWidget(widget); -} - -void Window::_removeWidget(Widget* const widget) -{ - pData->removeWidget(widget); -} - -void Window::_idle() -{ - pData->idle(); -} - -// ----------------------------------------------------------------------- - -void Window::addIdleCallback(IdleCallback* const callback) -{ - DISTRHO_SAFE_ASSERT_RETURN(callback != nullptr,) - - pData->fApp.pData->idleCallbacks.push_back(callback); -} - -void Window::removeIdleCallback(IdleCallback* const callback) -{ - DISTRHO_SAFE_ASSERT_RETURN(callback != nullptr,) - - pData->fApp.pData->idleCallbacks.remove(callback); -} - -// ----------------------------------------------------------------------- - -void Window::onDisplayBefore() -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glLoadIdentity(); -} - -void Window::onDisplayAfter() -{ -} - -void Window::onReshape(uint width, uint height) -{ - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0.0, static_cast<GLdouble>(width), static_cast<GLdouble>(height), 0.0, 0.0, 1.0); - glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); -} - -void Window::onClose() -{ -} - -void Window::fileBrowserSelected(const char*) -{ -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DGL - -#undef DBG -#undef DBGF diff --git a/libs/dgl/src/nanovg/LICENSE.txt b/libs/dgl/src/nanovg/LICENSE.txt deleted file mode 100644 index 2a03a1a..0000000 --- a/libs/dgl/src/nanovg/LICENSE.txt +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013 Mikko Mononen memon@inside.org
-
-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.
-
diff --git a/libs/dgl/src/nanovg/fontstash.h b/libs/dgl/src/nanovg/fontstash.h deleted file mode 100644 index a97ce53..0000000 --- a/libs/dgl/src/nanovg/fontstash.h +++ /dev/null @@ -1,1673 +0,0 @@ -// -// Copyright (c) 2009-2013 Mikko Mononen memon@inside.org -// -// 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 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 craeted 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); -}; - -struct FONSquad -{ - float x0,y0,s0,t0; - float x1,y1,s1,t1; -}; - -struct FONStextIter { - float x, y, nextx, nexty, scale, spacing; - unsigned int codepoint; - short isize, iblur; - struct FONSfont* font; - struct FONSglyph* prevGlyph; - const char* str; - const char* next; - const char* end; - unsigned int utf8state; -}; - -// Contructor and destructor. -struct FONScontext* fonsCreateInternal(struct FONSparams* params); -void fonsDeleteInternal(struct FONScontext* s); - -void fonsSetErrorCallback(struct FONScontext* s, void (*callback)(void* uptr, int error, int val), void* uptr); -// Returns current atlas size. -void fonsGetAtlasSize(struct FONScontext* s, int* width, int* height); -// Expands the atlas size. -int fonsExpandAtlas(struct FONScontext* s, int width, int height); -// Reseta the whole stash. -int fonsResetAtlas(struct FONScontext* stash, int width, int height); - -// Add fonts -int fonsAddFont(struct FONScontext* s, const char* name, const char* path); -int fonsAddFontMem(struct FONScontext* s, const char* name, unsigned char* data, int ndata, int freeData); -int fonsGetFontByName(struct FONScontext* s, const char* name); - -// State handling -void fonsPushState(struct FONScontext* s); -void fonsPopState(struct FONScontext* s); -void fonsClearState(struct FONScontext* s); - -// State setting -void fonsSetSize(struct FONScontext* s, float size); -void fonsSetColor(struct FONScontext* s, unsigned int color); -void fonsSetSpacing(struct FONScontext* s, float spacing); -void fonsSetBlur(struct FONScontext* s, float blur); -void fonsSetAlign(struct FONScontext* s, int align); -void fonsSetFont(struct FONScontext* s, int font); - -// Draw text -float fonsDrawText(struct FONScontext* s, float x, float y, const char* string, const char* end); - -// Measure text -float fonsTextBounds(struct FONScontext* s, float x, float y, const char* string, const char* end, float* bounds); -void fonsLineBounds(struct FONScontext* s, float y, float* miny, float* maxy); -void fonsVertMetrics(struct FONScontext* s, float* ascender, float* descender, float* lineh); - -// Text iterator -int fonsTextIterInit(struct FONScontext* stash, struct FONStextIter* iter, float x, float y, const char* str, const char* end); -int fonsTextIterNext(struct FONScontext* stash, struct FONStextIter* iter, struct FONSquad* quad); - -// Pull texture changes -const unsigned char* fonsGetTextureData(struct FONScontext* stash, int* width, int* height); -int fonsValidateTexture(struct FONScontext* s, int* dirty); - -// Draws the stash texture for debugging -void fonsDrawDebug(struct FONScontext* s, float x, float y); - -#endif // FONS_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; -}; - -static FT_Library ftLibrary; - -int fons__tt_init() -{ - FT_Error ftError; - ftError = FT_Init_FreeType(&ftLibrary); - return ftError == 0; -} - -int fons__tt_loadFont(struct FONScontext *context, struct FONSttFontImpl *font, unsigned char *data, int dataSize) -{ - FT_Error ftError; - FONS_NOTUSED(context); - - //font->font.userdata = stash; - ftError = FT_New_Memory_Face(ftLibrary, (const FT_Byte*)data, dataSize, 0, &font->font); - return ftError == 0; -} - -void fons__tt_getFontVMetrics(struct 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(struct FONSttFontImpl *font, float size) -{ - return size / (font->font->ascender - font->font->descender); -} - -int fons__tt_getGlyphIndex(struct FONSttFontImpl *font, int codepoint) -{ - return FT_Get_Char_Index(font->font, codepoint); -} - -int fons__tt_buildGlyphBitmap(struct 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; - FONS_NOTUSED(scale); - - ftError = FT_Set_Pixel_Sizes(font->font, 0, (FT_UInt)(size * (float)font->font->units_per_EM / (float)(font->font->ascender - font->font->descender))); - if (ftError) return 0; - ftError = FT_Load_Glyph(font->font, glyph, FT_LOAD_RENDER); - if (ftError) return 0; - ftError = FT_Get_Advance(font->font, glyph, FT_LOAD_NO_SCALE, (FT_Fixed*)advance); - if (ftError) return 0; - ftGlyph = font->font->glyph; - *lsb = 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(struct 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; - 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(struct FONSttFontImpl *font, int glyph1, int glyph2) -{ - FT_Vector ftKerning; - FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning); - return ftKerning.x; -} - -#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; -}; - -int fons__tt_init(struct FONScontext *context) -{ - FONS_NOTUSED(context); - return 1; -} - -int fons__tt_loadFont(struct FONScontext *context, struct FONSttFontImpl *font, unsigned char *data, int dataSize) -{ - int stbError; - FONS_NOTUSED(dataSize); - - font->font.userdata = context; - stbError = stbtt_InitFont(&font->font, data, 0); - return stbError; -} - -void fons__tt_getFontVMetrics(struct FONSttFontImpl *font, int *ascent, int *descent, int *lineGap) -{ - stbtt_GetFontVMetrics(&font->font, ascent, descent, lineGap); -} - -float fons__tt_getPixelHeightScale(struct FONSttFontImpl *font, float size) -{ - return stbtt_ScaleForPixelHeight(&font->font, size); -} - -int fons__tt_getGlyphIndex(struct FONSttFontImpl *font, int codepoint) -{ - return stbtt_FindGlyphIndex(&font->font, codepoint); -} - -int fons__tt_buildGlyphBitmap(struct 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(struct 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(struct FONSttFontImpl *font, int glyph1, int glyph2) -{ - return stbtt_GetGlyphKernAdvance(&font->font, glyph1, glyph2); -} - -#endif - -#ifndef FONS_SCRATCH_BUF_SIZE -# define FONS_SCRATCH_BUF_SIZE 16000 -#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 - -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; -}; - -struct FONSfont -{ - struct FONSttFontImpl font; - char name[64]; - unsigned char* data; - int dataSize; - unsigned char freeData; - float ascender; - float descender; - float lineh; - struct FONSglyph* glyphs; - int cglyphs; - int nglyphs; - int lut[FONS_HASH_LUT_SIZE]; -}; - -struct FONSstate -{ - int font; - int align; - float size; - unsigned int color; - float blur; - float spacing; -}; - -struct FONSatlasNode { - short x, y, width; -}; - -struct FONSatlas -{ - int width, height; - struct FONSatlasNode* nodes; - int nnodes; - int cnodes; -}; - -struct FONScontext -{ - struct FONSparams params; - float itw,ith; - unsigned char* texData; - int dirtyRect[4]; - struct FONSfont** fonts; - struct 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; - struct FONSstate states[FONS_MAX_STATES]; - int nstates; - void (*handleError)(void* uptr, int error, int val); - void* errorUptr; -}; - -static void* fons__tmpalloc(size_t size, void* up) -{ - unsigned char* ptr; - struct FONScontext* stash = (struct 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 -} - -// Copyright (c) 2008-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de> -// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ 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 Jylänki - -static void fons__deleteAtlas(struct FONSatlas* atlas) -{ - if (atlas == NULL) return; - if (atlas->nodes != NULL) free(atlas->nodes); - free(atlas); -} - -static struct FONSatlas* fons__allocAtlas(int w, int h, int nnodes) -{ - struct FONSatlas* atlas = NULL; - - // Allocate memory for the font stash. - atlas = (struct FONSatlas*)malloc(sizeof(struct FONSatlas)); - if (atlas == NULL) goto error; - memset(atlas, 0, sizeof(struct FONSatlas)); - - atlas->width = w; - atlas->height = h; - - // Allocate space for skyline nodes - atlas->nodes = (struct FONSatlasNode*)malloc(sizeof(struct FONSatlasNode) * nnodes); - if (atlas->nodes == NULL) goto error; - memset(atlas->nodes, 0, sizeof(struct 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(struct 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 = (struct FONSatlasNode*)realloc(atlas->nodes, sizeof(struct 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(struct 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(struct 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(struct 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(struct 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 shaodw 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(struct 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(struct 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(struct 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); -} - -struct FONScontext* fonsCreateInternal(struct FONSparams* params) -{ - struct FONScontext* stash = NULL; - - // Allocate memory for the font stash. - stash = (struct FONScontext*)malloc(sizeof(struct FONScontext)); - if (stash == NULL) goto error; - memset(stash, 0, sizeof(struct 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 = (struct FONSfont**)malloc(sizeof(struct FONSfont*) * FONS_INIT_FONTS); - if (stash->fonts == NULL) goto error; - memset(stash->fonts, 0, sizeof(struct 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 struct FONSstate* fons__getState(struct FONScontext* stash) -{ - return &stash->states[stash->nstates-1]; -} - -void fonsSetSize(struct FONScontext* stash, float size) -{ - fons__getState(stash)->size = size; -} - -void fonsSetColor(struct FONScontext* stash, unsigned int color) -{ - fons__getState(stash)->color = color; -} - -void fonsSetSpacing(struct FONScontext* stash, float spacing) -{ - fons__getState(stash)->spacing = spacing; -} - -void fonsSetBlur(struct FONScontext* stash, float blur) -{ - fons__getState(stash)->blur = blur; -} - -void fonsSetAlign(struct FONScontext* stash, int align) -{ - fons__getState(stash)->align = align; -} - -void fonsSetFont(struct FONScontext* stash, int font) -{ - fons__getState(stash)->font = font; -} - -void fonsPushState(struct 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(struct FONSstate)); - stash->nstates++; -} - -void fonsPopState(struct FONScontext* stash) -{ - if (stash->nstates <= 1) { - if (stash->handleError) - stash->handleError(stash->errorUptr, FONS_STATES_UNDERFLOW, 0); - return; - } - stash->nstates--; -} - -void fonsClearState(struct FONScontext* stash) -{ - struct 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(struct 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(struct FONScontext* stash) -{ - struct FONSfont* font = NULL; - if (stash->nfonts+1 > stash->cfonts) { - stash->cfonts = stash->cfonts == 0 ? 8 : stash->cfonts * 2; - stash->fonts = (struct FONSfont**)realloc(stash->fonts, sizeof(struct FONSfont*) * stash->cfonts); - if (stash->fonts == NULL) - return -1; - } - font = (struct FONSfont*)malloc(sizeof(struct FONSfont)); - if (font == NULL) goto error; - memset(font, 0, sizeof(struct FONSfont)); - - font->glyphs = (struct FONSglyph*)malloc(sizeof(struct 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(struct FONScontext* stash, const char* name, const char* path) -{ - FILE* fp = 0; - int dataSize = 0; - unsigned char* data = NULL; - size_t r; - - // Read in the font data. - fp = fopen(path, "rb"); - if (!fp) 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; - r = fread(data, 1, dataSize, fp); - fclose(fp); - fp = 0; - - return fonsAddFontMem(stash, name, data, dataSize, 1); - - NVG_NOTUSED(r); - -error: - if (data) free(data); - if (fp) fclose(fp); - return FONS_INVALID; -} - -int fonsAddFontMem(struct FONScontext* stash, const char* name, unsigned char* data, int dataSize, int freeData) -{ - int i, ascent, descent, fh, lineGap; - struct 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)) 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); - fh = ascent - descent; - font->ascender = (float)ascent / (float)fh; - font->descender = (float)descent / (float)fh; - font->lineh = (float)(fh + lineGap) / (float)fh; - - return idx; - -error: - fons__freeFont(font); - stash->nfonts--; - return FONS_INVALID; -} - -int fonsGetFontByName(struct 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 struct FONSglyph* fons__allocGlyph(struct FONSfont* font) -{ - if (font->nglyphs+1 > font->cglyphs) { - font->cglyphs = font->cglyphs == 0 ? 8 : font->cglyphs * 2; - font->glyphs = (struct FONSglyph*)realloc(font->glyphs, sizeof(struct 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(struct 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 struct FONSglyph* fons__getGlyph(struct FONScontext* stash, struct FONSfont* font, unsigned int codepoint, - short isize, short iblur) -{ - int i, g, advance, lsb, x0, y0, x1, y1, gw, gh, gx, gy, x, y; - float scale; - struct FONSglyph* glyph = NULL; - unsigned int h; - float size = isize/10.0f; - int pad, added; - unsigned char* bdst; - unsigned char* dst; - - 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) - return &font->glyphs[i]; - i = font->glyphs[i].next; - } - - // Could not find glyph, create it. - scale = fons__tt_getPixelHeightScale(&font->font, size); - g = fons__tt_getGlyphIndex(&font->font, codepoint); - fons__tt_buildGlyphBitmap(&font->font, g, size, scale, &advance, &lsb, &x0, &y0, &x1, &y1); - gw = x1-x0 + pad*2; - gh = y1-y0 + pad*2; - - // 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; - - // Init glyph. - glyph = fons__allocGlyph(font); - glyph->codepoint = codepoint; - glyph->size = isize; - glyph->blur = iblur; - 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); - glyph->next = 0; - - // Insert char to hash lookup. - glyph->next = font->lut[h]; - font->lut[h] = font->nglyphs-1; - - // Rasterize - dst = &stash->texData[(glyph->x0+pad) + (glyph->y0+pad) * stash->params.width]; - fons__tt_renderGlyphBitmap(&font->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(struct FONScontext* stash, struct FONSfont* font, - struct FONSglyph* prevGlyph, struct FONSglyph* glyph, - float scale, float spacing, float* x, float* y, struct FONSquad* q) -{ - float rx,ry,xoff,yoff,x0,y0,x1,y1; - - if (prevGlyph) { - float adv = fons__tt_getGlyphKernAdvance(&font->font, prevGlyph->index, 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 corret 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 = (float)(int)(*x + xoff); - ry = (float)(int)(*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 = (float)(int)(*x + xoff); - ry = (float)(int)(*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(struct 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(struct 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(struct FONScontext* stash, struct 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(struct FONScontext* stash, - float x, float y, - const char* str, const char* end) -{ - struct FONSstate* state = fons__getState(stash); - unsigned int codepoint; - unsigned int utf8state = 0; - struct FONSglyph* glyph = NULL; - struct FONSglyph* prevGlyph = NULL; - struct FONSquad q; - short isize = (short)(state->size*10.0f); - short iblur = (short)state->blur; - float scale; - struct 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) 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); - if (glyph) { - fons__getQuad(stash, font, prevGlyph, 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); - } - prevGlyph = glyph; - } - fons__flush(stash); - - return x; -} - -int fonsTextIterInit(struct FONScontext* stash, struct FONStextIter* iter, - float x, float y, const char* str, const char* end) -{ - struct 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) 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; - - return 1; -} - -int fonsTextIterNext(struct FONScontext* stash, struct FONStextIter* iter, struct FONSquad* quad) -{ - struct 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); - if (glyph != NULL) - fons__getQuad(stash, iter->font, iter->prevGlyph, glyph, iter->scale, iter->spacing, &iter->nextx, &iter->nexty, quad); - iter->prevGlyph = glyph; - break; - } - iter->next = str; - - return 1; -} - -void fonsDrawDebug(struct 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++) { - struct 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(struct FONScontext* stash, - float x, float y, - const char* str, const char* end, - float* bounds) -{ - struct FONSstate* state = fons__getState(stash); - unsigned int codepoint; - unsigned int utf8state = 0; - struct FONSquad q; - struct FONSglyph* glyph = NULL; - struct FONSglyph* prevGlyph = NULL; - short isize = (short)(state->size*10.0f); - short iblur = (short)state->blur; - float scale; - struct 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) 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); - if (glyph) { - fons__getQuad(stash, font, prevGlyph, 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; - } - } - prevGlyph = glyph; - } - - 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(struct FONScontext* stash, - float* ascender, float* descender, float* lineh) -{ - struct FONSfont* font; - struct 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) 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(struct FONScontext* stash, float y, float* miny, float* maxy) -{ - struct FONSfont* font; - struct 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) 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(struct 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(struct 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(struct 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); - free(stash); -} - -void fonsSetErrorCallback(struct FONScontext* stash, void (*callback)(void* uptr, int error, int val), void* uptr) -{ - if (stash == NULL) return; - stash->handleError = callback; - stash->errorUptr = uptr; -} - -void fonsGetAtlasSize(struct FONScontext* stash, int* width, int* height) -{ - if (stash == NULL) return; - *width = stash->params.width; - *height = stash->params.height; -} - -int fonsExpandAtlas(struct 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 axisting 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(struct 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++) { - struct 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 diff --git a/libs/dgl/src/nanovg/nanovg.c b/libs/dgl/src/nanovg/nanovg.c deleted file mode 100644 index 0697c9b..0000000 --- a/libs/dgl/src/nanovg/nanovg.c +++ /dev/null @@ -1,2475 +0,0 @@ -// -// Copyright (c) 2013 Mikko Mononen memon@inside.org -// -// 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 <stdio.h> -#include <math.h> -#include "nanovg.h" -#define FONTSTASH_IMPLEMENTATION -#include "fontstash.h" -#include "stb_image.c" - - -#define NVG_INIT_COMMANDS_SIZE 256 -#define NVG_INIT_POINTS_SIZE 128 -#define NVG_INIT_PATHS_SIZE 16 -#define NVG_INIT_VERTS_SIZE 256 -#define NVG_MAX_STATES 32 - -#define NVG_KAPPA90 0.5522847493f // Lenght 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, -}; - -enum NVGexpandFeatures { - NVG_FILL = 0x01, - NVG_STROKE = 0x02, - NVG_CAPS = 0x04, -}; - -struct NVGstate { - struct NVGpaint fill; - struct NVGpaint stroke; - float strokeWidth; - float miterLimit; - int lineJoin; - int lineCap; - float xform[6]; - struct NVGscissor scissor; - float fontSize; - float letterSpacing; - float lineHeight; - float fontBlur; - int textAlign; - int fontId; -}; - -struct NVGpoint { - float x,y; - float dx, dy; - float len; - float dmx, dmy; - unsigned char flags; -}; - -struct NVGpathCache { - struct NVGpoint* points; - int npoints; - int cpoints; - struct NVGpath* paths; - int npaths; - int cpaths; - struct NVGvertex* verts; - int nverts; - int cverts; - float bounds[4]; -}; - -struct NVGcontext { - struct NVGparams params; - float* commands; - int ccommands; - int ncommands; - float commandx, commandy; - struct NVGstate states[NVG_MAX_STATES]; - int nstates; - struct NVGpathCache* cache; - float tessTol; - float distTol; - float fringeWidth; - float devicePxRatio; - struct FONScontext* fs; - int fontImage; - int alphaBlend; - 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__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(struct 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 struct NVGpathCache* nvg__allocPathCache() -{ - struct NVGpathCache* c = (struct NVGpathCache*)malloc(sizeof(struct NVGpathCache)); - if (c == NULL) goto error; - memset(c, 0, sizeof(struct NVGpathCache)); - - c->points = (struct NVGpoint*)malloc(sizeof(struct NVGpoint)*NVG_INIT_POINTS_SIZE); - if (!c->points) goto error; - c->npoints = 0; - c->cpoints = NVG_INIT_POINTS_SIZE; - - c->paths = (struct NVGpath*)malloc(sizeof(struct NVGpath)*NVG_INIT_PATHS_SIZE); - if (!c->paths) goto error; - c->npaths = 0; - c->cpaths = NVG_INIT_PATHS_SIZE; - - c->verts = (struct NVGvertex*)malloc(sizeof(struct 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(struct NVGcontext* ctx, float ratio) -{ - ctx->tessTol = 1.0f / ratio; - ctx->distTol = 0.01f / ratio; - ctx->fringeWidth = 1.0f / ratio; - ctx->devicePxRatio = ratio; -} - -struct NVGcontext* nvgCreateInternal(struct NVGparams* params) -{ - struct FONSparams fontParams; - struct NVGcontext* ctx = (struct NVGcontext*)malloc(sizeof(struct NVGcontext)); - if (ctx == NULL) goto error; - memset(ctx, 0, sizeof(struct NVGcontext)); - - ctx->params = *params; - - 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->alphaBlend = NVG_STRAIGHT_ALPHA; - - 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 = params->atlasWidth; - fontParams.height = params->atlasHeight; - 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->fontImage = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, NULL); - if (ctx->fontImage == 0) goto error; - - return ctx; - -error: - nvgDeleteInternal(ctx); - return 0; -} - -void nvgDeleteInternal(struct NVGcontext* ctx) -{ - 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); - - if (ctx->params.renderDelete != NULL) - ctx->params.renderDelete(ctx->params.userPtr); - - free(ctx); -} - -void nvgBeginFrame(struct NVGcontext* ctx, int windowWidth, int windowHeight, float devicePixelRatio, int alphaBlend) -{ -/* 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->alphaBlend = alphaBlend; - - ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight, ctx->alphaBlend); - - ctx->drawCallCount = 0; - ctx->fillTriCount = 0; - ctx->strokeTriCount = 0; - ctx->textTriCount = 0; -} - -void nvgEndFrame(struct NVGcontext* ctx) -{ - ctx->params.renderFlush(ctx->params.userPtr, ctx->alphaBlend); -} - -struct NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b) -{ - return nvgRGBA(r,g,b,255); -} - -struct NVGcolor nvgRGBf(float r, float g, float b) -{ - return nvgRGBAf(r,g,b,1.0f); -} - -struct NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - struct 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; -} - -struct NVGcolor nvgRGBAf(float r, float g, float b, float a) -{ - struct NVGcolor color; - // Use longer initialization to suppress warning. - color.r = r; - color.g = g; - color.b = b; - color.a = a; - return color; -} - -struct NVGcolor nvgTransRGBA(struct NVGcolor c, unsigned char a) -{ - c.a = a / 255.0f; - return c; -} - -struct NVGcolor nvgTransRGBAf(struct NVGcolor c, float a) -{ - c.a = a; - return c; -} - -struct NVGcolor nvgLerpRGBA(struct NVGcolor c0, struct NVGcolor c1, float u) -{ - int i; - float oneminu; - struct NVGcolor cint; - - 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; -} - -struct 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; -} - -struct NVGcolor nvgHSLA(float h, float s, float l, unsigned char a) -{ - float m1, m2; - struct 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; -} - - -static struct NVGstate* nvg__getState(struct NVGcontext* ctx) -{ - return &ctx->states[ctx->nstates-1]; -} - -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(struct NVGpaint* p, struct 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(struct NVGcontext* ctx) -{ - if (ctx->nstates >= NVG_MAX_STATES) - return; - if (ctx->nstates > 0) - memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(struct NVGstate)); - ctx->nstates++; -} - -void nvgRestore(struct NVGcontext* ctx) -{ - if (ctx->nstates <= 1) - return; - ctx->nstates--; -} - -void nvgReset(struct NVGcontext* ctx) -{ - struct 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->strokeWidth = 1.0f; - state->miterLimit = 10.0f; - state->lineCap = NVG_BUTT; - state->lineJoin = NVG_MITER; - nvgTransformIdentity(state->xform); - - state->scissor.extent[0] = 0.0f; - state->scissor.extent[1] = 0.0f; - - state->fontSize = 16.0f; - state->letterSpacing = 0.0f; - state->lineHeight = 0.0f; - state->fontBlur = 0.0f; - state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE; - state->fontId = 0; -} - -// State setting -void nvgStrokeWidth(struct NVGcontext* ctx, float width) -{ - struct NVGstate* state = nvg__getState(ctx); - state->strokeWidth = width; -} - -void nvgMiterLimit(struct NVGcontext* ctx, float limit) -{ - struct NVGstate* state = nvg__getState(ctx); - state->miterLimit = limit; -} - -void nvgLineCap(struct NVGcontext* ctx, int cap) -{ - struct NVGstate* state = nvg__getState(ctx); - state->lineCap = cap; -} - -void nvgLineJoin(struct NVGcontext* ctx, int join) -{ - struct NVGstate* state = nvg__getState(ctx); - state->lineJoin = join; -} - - -void nvgTransform(struct NVGcontext* ctx, float a, float b, float c, float d, float e, float f) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6] = { a, b, c, d, e, f }; - nvgTransformPremultiply(state->xform, t); -} - -void nvgResetTransform(struct NVGcontext* ctx) -{ - struct NVGstate* state = nvg__getState(ctx); - nvgTransformIdentity(state->xform); -} - -void nvgTranslate(struct NVGcontext* ctx, float x, float y) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6]; - nvgTransformTranslate(t, x,y); - nvgTransformPremultiply(state->xform, t); -} - -void nvgRotate(struct NVGcontext* ctx, float angle) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6]; - nvgTransformRotate(t, angle); - nvgTransformPremultiply(state->xform, t); -} - -void nvgSkewX(struct NVGcontext* ctx, float angle) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6]; - nvgTransformSkewX(t, angle); - nvgTransformPremultiply(state->xform, t); -} - -void nvgSkewY(struct NVGcontext* ctx, float angle) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6]; - nvgTransformSkewY(t, angle); - nvgTransformPremultiply(state->xform, t); -} - -void nvgScale(struct NVGcontext* ctx, float x, float y) -{ - struct NVGstate* state = nvg__getState(ctx); - float t[6]; - nvgTransformScale(t, x,y); - nvgTransformPremultiply(state->xform, t); -} - -void nvgCurrentTransform(struct NVGcontext* ctx, float* xform) -{ - struct NVGstate* state = nvg__getState(ctx); - if (xform == NULL) return; - memcpy(xform, state->xform, sizeof(float)*6); -} - -void nvgStrokeColor(struct NVGcontext* ctx, struct NVGcolor color) -{ - struct NVGstate* state = nvg__getState(ctx); - nvg__setPaintColor(&state->stroke, color); -} - -void nvgStrokePaint(struct NVGcontext* ctx, struct NVGpaint paint) -{ - struct NVGstate* state = nvg__getState(ctx); - state->stroke = paint; - nvgTransformMultiply(state->stroke.xform, state->xform); -} - -void nvgFillColor(struct NVGcontext* ctx, struct NVGcolor color) -{ - struct NVGstate* state = nvg__getState(ctx); - nvg__setPaintColor(&state->fill, color); -} - -void nvgFillPaint(struct NVGcontext* ctx, struct NVGpaint paint) -{ - struct NVGstate* state = nvg__getState(ctx); - state->fill = paint; - nvgTransformMultiply(state->fill.xform, state->xform); -} - -int nvgCreateImage(struct NVGcontext* ctx, const char* filename) -{ - int w, h, n, image; - unsigned char* 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, img); - stbi_image_free(img); - return image; -} - -int nvgCreateImageMem(struct NVGcontext* ctx, 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, img); - stbi_image_free(img); - return image; -} - -int nvgCreateImageRGBA(struct NVGcontext* ctx, int w, int h, const unsigned char* data) -{ - return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, data); -} - -void nvgUpdateImage(struct 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(struct NVGcontext* ctx, int image, int* w, int* h) -{ - ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h); -} - -void nvgDeleteImage(struct NVGcontext* ctx, int image) -{ - ctx->params.renderDeleteTexture(ctx->params.userPtr, image); -} - -struct NVGpaint nvgLinearGradient(struct NVGcontext* ctx, - float sx, float sy, float ex, float ey, - struct NVGcolor icol, struct NVGcolor ocol) -{ - struct 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; -} - -struct NVGpaint nvgRadialGradient(struct NVGcontext* ctx, - float cx, float cy, float inr, float outr, - struct NVGcolor icol, struct NVGcolor ocol) -{ - struct 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; -} - -struct NVGpaint nvgBoxGradient(struct NVGcontext* ctx, - float x, float y, float w, float h, float r, float f, - struct NVGcolor icol, struct NVGcolor ocol) -{ - struct 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; -} - - -struct NVGpaint nvgImagePattern(struct NVGcontext* ctx, - float cx, float cy, float w, float h, float angle, - int image, int repeat) -{ - struct 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.repeat = repeat; - - return p; -} - -// Scissoring -void nvgScissor(struct NVGcontext* ctx, float x, float y, float w, float h) -{ - struct NVGstate* state = nvg__getState(ctx); - - 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; -} - -void nvgResetScissor(struct NVGcontext* ctx) -{ - struct NVGstate* state = nvg__getState(ctx); - memset(state->scissor.xform, 0, sizeof(state->scissor.xform)); - state->scissor.extent[0] = 0; - state->scissor.extent[1] = 0; -} - -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(struct NVGcontext* ctx, float* vals, int nvals) -{ - struct 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; - } - - // 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; - - if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) { - ctx->commandx = vals[nvals-2]; - ctx->commandy = vals[nvals-1]; - } -} - - -static void nvg__clearPathCache(struct NVGcontext* ctx) -{ - ctx->cache->npoints = 0; - ctx->cache->npaths = 0; -} - -static struct NVGpath* nvg__lastPath(struct NVGcontext* ctx) -{ - if (ctx->cache->npaths > 0) - return &ctx->cache->paths[ctx->cache->npaths-1]; - return NULL; -} - -static void nvg__addPath(struct NVGcontext* ctx) -{ - struct NVGpath* path; - if (ctx->cache->npaths+1 > ctx->cache->cpaths) { - struct NVGpath* paths; - int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2; - paths = (struct NVGpath*)realloc(ctx->cache->paths, sizeof(struct 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 struct NVGpoint* nvg__lastPoint(struct NVGcontext* ctx) -{ - if (ctx->cache->npoints > 0) - return &ctx->cache->points[ctx->cache->npoints-1]; - return NULL; -} - -static void nvg__addPoint(struct NVGcontext* ctx, float x, float y, int flags) -{ - struct NVGpath* path = nvg__lastPath(ctx); - struct NVGpoint* pt; - if (path == NULL) return; - - if (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) { - struct NVGpoint* points; - int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2; - points = (struct NVGpoint*)realloc(ctx->cache->points, sizeof(struct 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 = flags; - - ctx->cache->npoints++; - path->count++; -} - -static void nvg__closePath(struct NVGcontext* ctx) -{ - struct NVGpath* path = nvg__lastPath(ctx); - if (path == NULL) return; - path->closed = 1; -} - -static void nvg__pathWinding(struct NVGcontext* ctx, int winding) -{ - struct 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 struct NVGvertex* nvg__allocTempVerts(struct NVGcontext* ctx, int nverts) -{ - if (nverts > ctx->cache->cverts) { - struct NVGvertex* verts; - int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly. - verts = (struct NVGvertex*)realloc(ctx->cache->verts, sizeof(struct 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(struct NVGpoint* pts, int npts) -{ - int i; - float area = 0; - for (i = 2; i < npts; i++) { - struct NVGpoint* a = &pts[0]; - struct NVGpoint* b = &pts[i-1]; - struct 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(struct NVGpoint* pts, int npts) -{ - struct 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(struct 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(struct 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 = x3 - x1; - dy = y3 - 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(struct NVGcontext* ctx) -{ - struct NVGpathCache* cache = ctx->cache; -// struct NVGstate* state = nvg__getState(ctx); - struct NVGpoint* last; - struct NVGpoint* p0; - struct NVGpoint* p1; - struct NVGpoint* pts; - struct 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, struct NVGpoint* p0, struct 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 struct NVGvertex* nvg__roundJoin(struct NVGvertex* dst, struct NVGpoint* p0, struct 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 struct NVGvertex* nvg__bevelJoin(struct NVGvertex* dst, struct NVGpoint* p0, struct NVGpoint* p1, - float lw, float rw, float lu, float ru, float fringe) -{ - float rx0,ry0,rx1,ry1; - float lx0,ly0,lx1,ly1; - float mx,my,len,mu; - 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) { - // TODO: this needs more work. - mx = (dlx0 + dlx1) * 0.5f; - my = (dly0 + dly1) * 0.5f; - len = sqrtf(mx*mx + my*my); - mu = ru + len*(lu-ru)*0.5f; - - 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) { - // TODO: this needs more work. - mx = (dlx0 + dlx1) * 0.5f; - my = (dly0 + dly1) * 0.5f; - len = sqrtf(mx*mx + my*my); - mu = lu + len*(ru-lu)*0.5f; - - 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; - - NVG_NOTUSED(mu); -} - -static int nvg__expandStrokeAndFill(struct NVGcontext* ctx, int feats, float w, int lineCap, int lineJoin, float miterLimit) -{ - struct NVGpathCache* cache = ctx->cache; - struct NVGpath* path; - struct NVGpoint* pts; - struct NVGvertex* verts; - struct NVGvertex* dst; - struct NVGpoint* p0; - struct NVGpoint* p1; - int cverts, convex, i, j, s, e; - float wo = 0, iw = 0, aa = ctx->fringeWidth; - int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol / 4.0f); - int nleft = 0; - - 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++) { - path = &cache->paths[i]; - pts = &cache->points[path->first]; - path->nbevel = 0; - nleft = 0; - - p0 = &pts[path->count-1]; - p1 = &pts[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; - } - - // Calculate max vertex usage. - cverts = 0; - for (i = 0; i < cache->npaths; i++) { - path = &cache->paths[i]; - if (feats & NVG_FILL) - cverts += path->count + path->nbevel + 1; - if (feats & NVG_STROKE) { - int loop = ((feats & NVG_CAPS) && path->closed == 0) ? 0 : 1; - if (lineCap == 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; - - if ((feats & NVG_FILL) && cache->npaths == 1 && cache->paths[0].convex) - convex = 1; - else - convex = 0; - - for (i = 0; i < cache->npaths; i++) { - path = &cache->paths[i]; - pts = &cache->points[path->first]; - - // Calculate shape vertices. - if (feats & NVG_FILL) { - wo = 0.5f*aa; - dst = verts; - path->fill = dst; - - if (w == 0.0f) { - for (j = 0; j < path->count; ++j) { - nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1); - dst++; - } - } else { - // 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 * wo; - float ly = p1->y + p1->dmy * wo; - nvg__vset(dst, lx, ly, 0.5f,1); dst++; - } else { - float lx0 = p1->x + dlx0 * wo; - float ly0 = p1->y + dly0 * wo; - float lx1 = p1->x + dlx1 * wo; - float ly1 = p1->y + dly1 * wo; - 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 * wo), p1->y + (p1->dmy * wo), 0.5f,1); dst++; - } - p0 = p1++; - } - } - - path->nfill = (int)(dst - verts); - verts = dst; - } else { - wo = 0.0f; - path->fill = 0; - path->nfill = 0; - } - - // Calculate fringe or stroke - if (feats & NVG_STROKE) { - float lw = w + wo, rw = w - wo; - float lu = 0, ru = 1; - int loop = ((feats & NVG_CAPS) && path->closed == 0) ? 0 : 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 = wo; // This should generate the same vertex as fill inset above. - lu = 0.5f; // Set outline fade at middle. - } - - 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 - float dx, dy, dlx, dly, px, py; - dx = p1->x - p0->x; - dy = p1->y - p0->y; - nvg__normalize(&dx, &dy); - dlx = dy; - dly = -dx; - if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE) { - if (lineCap == NVG_BUTT) { - px = p0->x + dx*ctx->fringeWidth*0.5f; - py = p0->y + dy*ctx->fringeWidth*0.5f; - } else /*if (lineCap == NVG_SQUARE)*/ { - px = p0->x - dx*(w - ctx->fringeWidth); - py = p0->y - dy*(w - ctx->fringeWidth); - } - nvg__vset(dst, px + dlx*lw - dx*aa, py + dly*lw - dy*aa, lu,0); dst++; - nvg__vset(dst, px - dlx*rw - dx*aa, py - dly*rw - dy*aa, ru,0); dst++; - nvg__vset(dst, px + dlx*lw, py + dly * lw, lu,1); dst++; - nvg__vset(dst, px - dlx*rw, py - dly * rw, ru,1); dst++; - } else if (lineCap == NVG_ROUND) { - px = p0->x; - py = p0->y; - for (j = 0; j < ncap; j++) { - float a = j/(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, lu,1); dst++; - nvg__vset(dst, px, py, 0.5f,1); dst++; - } - nvg__vset(dst, px + dlx*lw, py + dly * lw, lu,1); dst++; - nvg__vset(dst, px - dlx*rw, py - dly * rw, ru,1); dst++; - } - } - - 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, lw, rw, lu, ru, ncap, ctx->fringeWidth); - } else { - 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++; - } - - if (loop) { - // 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++; - } else { - // Add cap - float dx, dy, dlx, dly, px, py; - dx = p1->x - p0->x; - dy = p1->y - p0->y; - nvg__normalize(&dx, &dy); - dlx = dy; - dly = -dx; - if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE) { - if (lineCap == NVG_BUTT) { - px = p1->x - dx*ctx->fringeWidth*0.5f; - py = p1->y - dy*ctx->fringeWidth*0.5f; - } else /*if (lineCap == NVG_SQUARE)*/ { - px = p1->x + dx*(w - ctx->fringeWidth); - py = p1->y + dy*(w - ctx->fringeWidth); - } - nvg__vset(dst, px + dlx*lw, py + dly * lw, lu,1); dst++; - nvg__vset(dst, px - dlx*rw, py - dly * rw, ru,1); dst++; - nvg__vset(dst, px + dlx*lw + dx*aa, py + dly*lw + dy*aa, lu,0); dst++; - nvg__vset(dst, px - dlx*rw + dx*aa, py - dly*rw + dy*aa, ru,0); dst++; - } else if (lineCap == NVG_ROUND) { - px = p1->x; - py = p1->y; - nvg__vset(dst, px + dlx*lw, py + dly * lw, lu,1); dst++; - nvg__vset(dst, px - dlx*rw, py - dly * rw, ru,1); dst++; - for (j = 0; j < ncap; j++) { - float a = j/(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, lu,1); dst++; - } - } - } - - path->nstroke = (int)(dst - verts); - - verts = dst; - } else { - path->stroke = 0; - path->nstroke = 0; - } - } - - return 1; -} - - -// Draw -void nvgBeginPath(struct NVGcontext* ctx) -{ - ctx->ncommands = 0; - nvg__clearPathCache(ctx); -} - -void nvgMoveTo(struct NVGcontext* ctx, float x, float y) -{ - float vals[] = { NVG_MOVETO, x, y }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); -} - -void nvgLineTo(struct NVGcontext* ctx, float x, float y) -{ - float vals[] = { NVG_LINETO, x, y }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); -} - -void nvgBezierTo(struct 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 nvgArcTo(struct 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(struct NVGcontext* ctx) -{ - float vals[] = { NVG_CLOSE }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); -} - -void nvgPathWinding(struct NVGcontext* ctx, int dir) -{ - float vals[] = { NVG_WINDING, (float)dir }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); -} - -void nvgArc(struct 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(struct NVGcontext* ctx, float x, float y, float w, float h) -{ - float vals[] = { - NVG_MOVETO, x,y, - NVG_LINETO, x+w,y, - NVG_LINETO, x+w,y+h, - NVG_LINETO, x,y+h, - NVG_CLOSE - }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); -} - -void nvgRoundedRect(struct NVGcontext* ctx, float x, float y, float w, float h, float r) -{ - if (r < 0.1f) { - nvgRect(ctx, x,y,w,h); - return; - } - else { - float vals[] = { - NVG_MOVETO, x+r, y, - NVG_LINETO, x+w-r, y, - NVG_BEZIERTO, x+w-r*(1-NVG_KAPPA90), y, x+w, y+r*(1-NVG_KAPPA90), x+w, y+r, - NVG_LINETO, x+w, y+h-r, - NVG_BEZIERTO, x+w, y+h-r*(1-NVG_KAPPA90), x+w-r*(1-NVG_KAPPA90), y+h, x+w-r, y+h, - NVG_LINETO, x+r, y+h, - NVG_BEZIERTO, x+r*(1-NVG_KAPPA90), y+h, x, y+h-r*(1-NVG_KAPPA90), x, y+h-r, - NVG_LINETO, x, y+r, - NVG_BEZIERTO, x, y+r*(1-NVG_KAPPA90), x+r*(1-NVG_KAPPA90), y, x+r, y, - NVG_CLOSE - }; - nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals)); - } -} - -void nvgEllipse(struct 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(struct NVGcontext* ctx, float cx, float cy, float r) -{ - nvgEllipse(ctx, cx,cy, r,r); -} - -void nvgDebugDumpPathCache(struct NVGcontext* ctx) -{ - const struct 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(struct NVGcontext* ctx) -{ - struct NVGstate* state = nvg__getState(ctx); - const struct NVGpath* path; - int i; - - nvg__flattenPaths(ctx); - if (ctx->params.edgeAntiAlias) - nvg__expandStrokeAndFill(ctx, NVG_FILL|NVG_STROKE, ctx->fringeWidth, NVG_BUTT, NVG_MITER, 3.6f); - else - nvg__expandStrokeAndFill(ctx, NVG_FILL, 0.0f, NVG_BUTT, NVG_MITER, 1.2f); - - ctx->params.renderFill(ctx->params.userPtr, &state->fill, &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(struct NVGcontext* ctx) -{ - struct NVGstate* state = nvg__getState(ctx); - float scale = nvg__getAverageScale(state->xform); - float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 20.0f); - struct NVGpaint strokePaint = state->stroke; - const struct NVGpath* path; - int i; - - if (strokeWidth < ctx->fringeWidth) { - // If the stroke width is less than pixel size, use alpha to emulate coverate. - // 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; - } - - nvg__flattenPaths(ctx); - if (ctx->params.edgeAntiAlias) - nvg__expandStrokeAndFill(ctx, NVG_STROKE|NVG_CAPS, strokeWidth*0.5f + ctx->fringeWidth*0.5f, state->lineCap, state->lineJoin, state->miterLimit); - else - nvg__expandStrokeAndFill(ctx, NVG_STROKE|NVG_CAPS, strokeWidth*0.5f, state->lineCap, state->lineJoin, state->miterLimit); - - ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, &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(struct NVGcontext* ctx, const char* name, const char* path) -{ - return fonsAddFont(ctx->fs, name, path); -} - -int nvgCreateFontMem(struct NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData) -{ - return fonsAddFontMem(ctx->fs, name, data, ndata, freeData); -} - -int nvgFindFont(struct NVGcontext* ctx, const char* name) -{ - if (name == NULL) return -1; - return fonsGetFontByName(ctx->fs, name); -} - -// State setting -void nvgFontSize(struct NVGcontext* ctx, float size) -{ - struct NVGstate* state = nvg__getState(ctx); - state->fontSize = size; -} - -void nvgFontBlur(struct NVGcontext* ctx, float blur) -{ - struct NVGstate* state = nvg__getState(ctx); - state->fontBlur = blur; -} - -void nvgTextLetterSpacing(struct NVGcontext* ctx, float spacing) -{ - struct NVGstate* state = nvg__getState(ctx); - state->letterSpacing = spacing; -} - -void nvgTextLineHeight(struct NVGcontext* ctx, float lineHeight) -{ - struct NVGstate* state = nvg__getState(ctx); - state->lineHeight = lineHeight; -} - -void nvgTextAlign(struct NVGcontext* ctx, int align) -{ - struct NVGstate* state = nvg__getState(ctx); - state->textAlign = align; -} - -void nvgFontFaceId(struct NVGcontext* ctx, int font) -{ - struct NVGstate* state = nvg__getState(ctx); - state->fontId = font; -} - -void nvgFontFace(struct NVGcontext* ctx, const char* font) -{ - struct 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(struct NVGstate* state) -{ - return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f); -} - -float nvgText(struct NVGcontext* ctx, float x, float y, const char* string, const char* end) -{ - struct NVGstate* state = nvg__getState(ctx); - struct NVGpaint paint; - struct FONStextIter iter; - struct FONSquad q; - struct NVGvertex* verts; - float scale = nvg__getFontScale(state) * ctx->devicePxRatio; - float invscale = 1.0f / scale; - int dirty[4]; - int cverts = 0; - int nverts = 0; - - 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); - while (fonsTextIterNext(ctx->fs, &iter, &q)) { - // Trasnform corners. - float c[4*2]; - 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. - if (fonsValidateTexture(ctx->fs, dirty)) { - // Update texture - if (ctx->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, ctx->fontImage, x,y, w,h, data); - } - } - - // Render triangles. - paint = state->fill; - paint.image = ctx->fontImage; - ctx->params.renderTriangles(ctx->params.userPtr, &paint, &state->scissor, verts, nverts); - - ctx->drawCallCount++; - ctx->textTriCount += nverts/3; - - return iter.x; -} - -void nvgTextBox(struct NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end) -{ - struct NVGstate* state = nvg__getState(ctx); - struct NVGtextRow rows[2]; - int nrows = 0, i; - int oldAlign = state->textAlign; - int haling = 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++) { - struct NVGtextRow* row = &rows[i]; - if (haling & NVG_ALIGN_LEFT) - nvgText(ctx, x, y, row->start, row->end); - else if (haling & NVG_ALIGN_CENTER) - nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end); - else if (haling & 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(struct NVGcontext* ctx, float x, float y, const char* string, const char* end, struct NVGglyphPosition* positions, int maxPositions) -{ - struct NVGstate* state = nvg__getState(ctx); - float scale = nvg__getFontScale(state) * ctx->devicePxRatio; - float invscale = 1.0f / scale; - struct FONStextIter iter; - struct 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); - while (fonsTextIterNext(ctx->fs, &iter, &q)) { - positions[npos].str = iter.str; - positions[npos].x = iter.x * invscale; - positions[npos].minx = q.x0 * invscale; - positions[npos].maxx = q.x1 * invscale; - npos++; - if (npos >= maxPositions) - break; - } - - return npos; -} - -enum NVGcodepointType { - NVG_SPACE, - NVG_NEWLINE, - NVG_CHAR, -}; - -int nvgTextBreakLines(struct NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, struct NVGtextRow* rows, int maxRows) -{ - struct NVGstate* state = nvg__getState(ctx); - float scale = nvg__getFontScale(state) * ctx->devicePxRatio; - float invscale = 1.0f / scale; - struct FONStextIter iter; - struct 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); - while (fonsTextIterNext(ctx->fs, &iter, &q)) { - 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: - 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) { - // The current char is the row so far - rowStartX = iter.x; - rowStart = iter.str; - rowEnd = iter.next; - rowWidth = iter.nextx - rowStartX; // q.x1 - 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; //q.x1 - rowStartX; - - if (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 begining 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; - rowStartX = wordStartX; - rowStart = wordStart; - rowEnd = iter.next; - rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX; - rowMinX = wordMinX; - rowMaxX = q.x1 - rowStartX; - // No change to the word start - } - // Set null break point - breakEnd = rowStart; - breakWidth = 0.0; - breakMaxX = 0.0; - } - - // track last non-white space character - if (type == NVG_CHAR) { - rowEnd = iter.next; - rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX; - rowMaxX = q.x1 - rowStartX; - } - // track last end of a word - if (ptype == NVG_CHAR && (type == NVG_SPACE || type == NVG_SPACE)) { - breakEnd = iter.str; - breakWidth = rowWidth; - breakMaxX = rowMaxX; - } - // track last beginning of a word - if ((ptype == NVG_SPACE || ptype == NVG_SPACE) && type == NVG_CHAR) { - wordStart = iter.str; - wordStartX = iter.x; - wordMinX = q.x0 - rowStartX; - } - } - } - - pcodepoint = iter.codepoint; - ptype = type; - } - - // Break the line from the end of the last word, and start new line from the begining 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(struct NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds) -{ - struct 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, y, string, end, bounds); - if (bounds != NULL) { - bounds[0] *= invscale; - bounds[1] *= invscale; - bounds[2] *= invscale; - bounds[3] *= invscale; - } - return width * invscale; -} - -void nvgTextBoxBounds(struct NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) -{ - struct NVGstate* state = nvg__getState(ctx); - struct NVGtextRow rows[2]; - float scale = nvg__getFontScale(state) * ctx->devicePxRatio; - float invscale = 1.0f / scale; - int nrows = 0, i; - int oldAlign = state->textAlign; - int haling = 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); - - 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++) { - struct NVGtextRow* row = &rows[i]; - float rminx, rmaxx, dx = 0; - // Horizontal bounds - if (haling & NVG_ALIGN_LEFT) - dx = 0; - else if (haling & NVG_ALIGN_CENTER) - dx = breakRowWidth*0.5f - row->width*0.5f; - else if (haling & 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(struct NVGcontext* ctx, float* ascender, float* descender, float* lineh) -{ - struct 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; -} diff --git a/libs/dgl/src/nanovg/nanovg.h b/libs/dgl/src/nanovg/nanovg.h deleted file mode 100644 index 247a9ee..0000000 --- a/libs/dgl/src/nanovg/nanovg.h +++ /dev/null @@ -1,590 +0,0 @@ -// -// Copyright (c) 2013 Mikko Mononen memon@inside.org -// -// 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 - -struct NVGcontext; - -struct NVGcolor { - union { - float rgba[4]; - struct { - float r,g,b,a; - }; - }; -}; - -struct NVGpaint { - float xform[6]; - float extent[2]; - float radius; - float feather; - struct NVGcolor innerColor; - struct NVGcolor outerColor; - int image; - int repeat; -}; - -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 NVGpatternRepeat { - NVG_REPEATX = 0x01, // Repeat image pattern in X direction - NVG_REPEATY = 0x02, // Repeat image pattern in Y direction -}; - -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 NVGalpha { - NVG_STRAIGHT_ALPHA, - NVG_PREMULTIPLIED_ALPHA, -}; - -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. -}; - -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. -}; - - -// 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. -// AlphaBlend controls if drawing the shapes to the render target should be done using straight or -// premultiplied alpha. If rendering directly to framebuffer you probably want to use NVG_STRAIGHT_ALPHA, -// if rendering to texture which should contain transparent regions NVG_PREMULTIPLIED_ALPHA is the -// right choice. -void nvgBeginFrame(struct NVGcontext* ctx, int windowWidth, int windowHeight, float devicePixelRatio, int alphaBlend); - -// Ends drawing flushing remaining render state. -void nvgEndFrame(struct NVGcontext* ctx); - -// -// 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). -struct 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. -struct NVGcolor nvgRGBf(float r, float g, float b); - - -// Returns a color value from red, green, blue and alpha values. -struct 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. -struct NVGcolor nvgRGBAf(float r, float g, float b, float a); - - -// Linearly interpoaltes from color c0 to c1, and returns resulting color value. -struct NVGcolor nvgLerpRGBA(struct NVGcolor c0, struct NVGcolor c1, float u); - -// Sets transparency of a color value. -struct NVGcolor nvgTransRGBA(struct NVGcolor c0, unsigned char a); - -// Sets transparency of a color value. -struct NVGcolor nvgTransRGBAf(struct 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. -struct 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] -struct 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(struct NVGcontext* ctx); - -// Pops and restores current render state. -void nvgRestore(struct NVGcontext* ctx); - -// Resets current render state to default values. Does not affect the render state stack. -void nvgReset(struct 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 current stroke style to a solid color. -void nvgStrokeColor(struct NVGcontext* ctx, struct NVGcolor color); - -// Sets current stroke style to a paint, which can be a one of the gradients or a pattern. -void nvgStrokePaint(struct NVGcontext* ctx, struct NVGpaint paint); - -// Sets current fill cstyle to a solid color. -void nvgFillColor(struct NVGcontext* ctx, struct NVGcolor color); - -// Sets current fill style to a paint, which can be a one of the gradients or a pattern. -void nvgFillPaint(struct NVGcontext* ctx, struct NVGpaint paint); - -// Sets the miter limit of the stroke style. -// Miter limit controls when a sharp corner is beveled. -void nvgMiterLimit(struct NVGcontext* ctx, float limit); - -// Sets the stroke witdth of the stroke style. -void nvgStrokeWidth(struct 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(struct NVGcontext* ctx, int cap); - -// Sets how sharp path corners are drawn. -// Can be one of NVG_MITER (default), NVG_ROUND, NVG_BEVEL. -void nvgLineJoin(struct NVGcontext* ctx, int join); - -// -// 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(struct 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(struct NVGcontext* ctx, float a, float b, float c, float d, float e, float f); - -// Translates current coordinate system. -void nvgTranslate(struct NVGcontext* ctx, float x, float y); - -// Rotates current coordinate system. Angle is specifid in radians. -void nvgRotate(struct NVGcontext* ctx, float angle); - -// Skews the current coordinate system along X axis. Angle is specifid in radians. -void nvgSkewX(struct NVGcontext* ctx, float angle); - -// Skews the current coordinate system along Y axis. Angle is specifid in radians. -void nvgSkewY(struct NVGcontext* ctx, float angle); - -// Scales the current coordinat system. -void nvgScale(struct 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(struct NVGcontext* ctx, float* xform); - - -// The following functions can be used to make calculations on 2x3 transformation matrices. -// A 2x3 matrix is representated 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 specifid in radians. -void nvgTransformRotate(float* dst, float a); - -// Sets the transform to skew-x matrix. Angle is specifid in radians. -void nvgTransformSkewX(float* dst, float a); - -// Sets the transform to skew-y matrix. Angle is specifid 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 degress 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. - -// Creates image by loading it from the disk from specified file name. -// Returns handle to the image. -int nvgCreateImage(struct NVGcontext* ctx, const char* filename); - -// Creates image by loading it from the specified chunk of memory. -// Returns handle to the image. -int nvgCreateImageMem(struct NVGcontext* ctx, unsigned char* data, int ndata); - -// Creates image from specified image data. -// Returns handle to the image. -int nvgCreateImageRGBA(struct NVGcontext* ctx, int w, int h, const unsigned char* data); - -// Updates image data specified by image handle. -void nvgUpdateImage(struct NVGcontext* ctx, int image, const unsigned char* data); - -// Returns the domensions of a created image. -void nvgImageSize(struct NVGcontext* ctx, int image, int* w, int* h); - -// Deletes created image. -void nvgDeleteImage(struct 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(). -struct NVGpaint nvgLinearGradient(struct NVGcontext* ctx, float sx, float sy, float ex, float ey, - struct NVGcolor icol, struct NVGcolor ocol); - -// Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering -// drop shadows or hilights 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(). -struct NVGpaint nvgBoxGradient(struct NVGcontext* ctx, float x, float y, float w, float h, - float r, float f, struct NVGcolor icol, struct 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(). -struct NVGpaint nvgRadialGradient(struct NVGcontext* ctx, float cx, float cy, float inr, float outr, - struct NVGcolor icol, struct NVGcolor ocol); - -// Creates and returns an image patter. 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, -// and repeat is combination of NVG_REPEATX and NVG_REPEATY which tells if the image should be repeated across x or y. -// The gradient is transformed by the current transform when it is passed to nvgFillPaint() or nvgStrokePaint(). -struct NVGpaint nvgImagePattern(struct NVGcontext* ctx, float ox, float oy, float ex, float ey, - float angle, int image, int repeat); - -// -// Scissoring -// -// Scissoring allows you to clip the rendering into a rectangle. This is useful for varius -// user interface cases like rendering a text edit or a timeline. - -// Sets the current -// The scissor rectangle is transformed by the current transform. -void nvgScissor(struct NVGcontext* ctx, float x, float y, float w, float h); - -// Reset and disables scissoring. -void nvgResetScissor(struct 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(struct NVGcontext* ctx); - -// Starts new sub-path with specified point as first point. -void nvgMoveTo(struct NVGcontext* ctx, float x, float y); - -// Adds line segment from the last point in the path to the specified point. -void nvgLineTo(struct NVGcontext* ctx, float x, float y); - -// Adds bezier segment from last point in the path via two control points to the specified point. -void nvgBezierTo(struct NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y); - -// Adds an arc segment at the corner defined by the last path point, and two specified points. -void nvgArcTo(struct NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius); - -// Closes current sub-path with a line segment. -void nvgClosePath(struct NVGcontext* ctx); - -// Sets the current sub-path winding, see NVGwinding and NVGsolidity. -void nvgPathWinding(struct NVGcontext* ctx, int dir); - -// Creates new arc shaped sub-path. -void nvgArc(struct NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir); - -// Creates new rectangle shaped sub-path. -void nvgRect(struct NVGcontext* ctx, float x, float y, float w, float h); - -// Creates new rounded rectangle shaped sub-path. -void nvgRoundedRect(struct NVGcontext* ctx, float x, float y, float w, float h, float r); - -// Creates new ellipse shaped sub-path. -void nvgEllipse(struct NVGcontext* ctx, float cx, float cy, float rx, float ry); - -// Creates new circle shaped sub-path. -void nvgCircle(struct NVGcontext* ctx, float cx, float cy, float r); - -// Fills the current path with current fill style. -void nvgFill(struct NVGcontext* ctx); - -// Fills the current path with current stroke style. -void nvgStroke(struct 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); -// nvgRoundedRect(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(struct NVGcontext* ctx, const char* name, const char* filename); - -// Creates image by loading it from the specified memory chunk. -// Returns handle to the font. -int nvgCreateFontMem(struct NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData); - -// Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found. -int nvgFindFont(struct NVGcontext* ctx, const char* name); - -// Sets the font size of current text style. -void nvgFontSize(struct NVGcontext* ctx, float size); - -// Sets the blur of current text style. -void nvgFontBlur(struct NVGcontext* ctx, float blur); - -// Sets the letter spacing of current text style. -void nvgTextLetterSpacing(struct 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(struct NVGcontext* ctx, float lineHeight); - -// Sets the text align of current text style, see NVGaling for options. -void nvgTextAlign(struct NVGcontext* ctx, int align); - -// Sets the font face based on specified id of current text style. -void nvgFontFaceId(struct NVGcontext* ctx, int font); - -// Sets the font face based on specified name of current text style. -void nvgFontFace(struct 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(struct 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(struct 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(struct 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(struct 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(struct NVGcontext* ctx, float x, float y, const char* string, const char* end, struct NVGglyphPosition* positions, int maxPositions); - -// Returns the vertical metrics based on the current text style. -// Measured values are returned in local coordinate space. -void nvgTextMetrics(struct 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(struct NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, struct 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]; -}; - -struct NVGvertex { - float x,y,u,v; -}; - -struct NVGpath { - int first; - int count; - unsigned char closed; - int nbevel; - struct NVGvertex* fill; - int nfill; - struct NVGvertex* stroke; - int nstroke; - int winding; - int convex; -}; - -struct NVGparams { - void* userPtr; - int atlasWidth, atlasHeight; - int edgeAntiAlias; - int (*renderCreate)(void* uptr); - int (*renderCreateTexture)(void* uptr, int type, int w, int h, 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, int width, int height, int alphaBlend); - void (*renderFlush)(void* uptr, int alphaBlend); - void (*renderFill)(void* uptr, struct NVGpaint* paint, struct NVGscissor* scissor, float fringe, const float* bounds, const struct NVGpath* paths, int npaths); - void (*renderStroke)(void* uptr, struct NVGpaint* paint, struct NVGscissor* scissor, float fringe, float strokeWidth, const struct NVGpath* paths, int npaths); - void (*renderTriangles)(void* uptr, struct NVGpaint* paint, struct NVGscissor* scissor, const struct NVGvertex* verts, int nverts); - void (*renderDelete)(void* uptr); -}; - -// Contructor and destructor, called by the render back-end. -struct NVGcontext* nvgCreateInternal(struct NVGparams* params); -void nvgDeleteInternal(struct NVGcontext* ctx); - -// Debug function to dump cached path data. -void nvgDebugDumpPathCache(struct NVGcontext* ctx); - -#define NVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) - -#ifdef __cplusplus -} -#endif - -#endif // NANOVG_H diff --git a/libs/dgl/src/nanovg/nanovg_gl.h b/libs/dgl/src/nanovg/nanovg_gl.h deleted file mode 100644 index c3c80cf..0000000 --- a/libs/dgl/src/nanovg/nanovg_gl.h +++ /dev/null @@ -1,1293 +0,0 @@ -// -// Copyright (c) 2009-2013 Mikko Mononen memon@inside.org -// -// 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_GL3_H -#define NANOVG_GL3_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define NVG_ANTIALIAS 1 - -#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 - - -#if defined NANOVG_GL2 - -struct NVGcontext* nvgCreateGL2(int atlasw, int atlash, int edgeaa); -void nvgDeleteGL2(struct NVGcontext* ctx); - -#elif defined NANOVG_GL3 - -struct NVGcontext* nvgCreateGL3(int atlasw, int atlash, int edgeaa); -void nvgDeleteGL3(struct NVGcontext* ctx); - -#elif defined NANOVG_GLES2 - -struct NVGcontext* nvgCreateGLES2(int atlasw, int atlash, int edgeaa); -void nvgDeleteGLES2(struct NVGcontext* ctx); - -#elif defined NANOVG_GLES3 - -struct NVGcontext* nvgCreateGLES3(int atlasw, int atlash, int edgeaa); -void nvgDeleteGLES3(struct NVGcontext* ctx); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif - -#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, -#if NANOVG_GL_USE_UNIFORMBUFFER - GLNVG_LOC_FRAG, -#else - GLNVG_LOC_SCISSORMAT, - GLNVG_LOC_SCISSOREXT, - GLNVG_LOC_SCISSORSCALE, - GLNVG_LOC_PAINTMAT, - GLNVG_LOC_EXTENT, - GLNVG_LOC_RADIUS, - GLNVG_LOC_FEATHER, - GLNVG_LOC_INNERCOL, - GLNVG_LOC_OUTERCOL, - GLNVG_LOC_STROKEMULT, - GLNVG_LOC_TEXTYPE, - GLNVG_LOC_TYPE, -#endif - 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]; -}; - -struct GLNVGtexture { - int id; - GLuint tex; - int width, height; - int type; -}; - -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; -}; - -struct GLNVGpath { - int fillOffset; - int fillCount; - int strokeOffset; - int strokeCount; -}; - -struct GLNVGfragUniforms { - 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; - int texType; - int type; -}; - -struct GLNVGcontext { - struct GLNVGshader shader; - struct 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 edgeAntiAlias; - - // Per frame buffers - struct GLNVGcall* calls; - int ccalls; - int ncalls; - struct GLNVGpath* paths; - int cpaths; - int npaths; - struct NVGvertex* verts; - int cverts; - int nverts; - unsigned char* uniforms; - int cuniforms; - int nuniforms; -}; - -static int glnvg__maxi(int a, int b) { return a > b ? a : b; } - -static struct GLNVGtexture* glnvg__allocTexture(struct GLNVGcontext* gl) -{ - struct 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) { - struct GLNVGtexture* textures; - int ctextures = glnvg__maxi(gl->ntextures+1, 4) + gl->ctextures/2; // 1.5x Overallocate - textures = (struct GLNVGtexture*)realloc(gl->textures, sizeof(struct 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 struct GLNVGtexture* glnvg__findTexture(struct 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(struct 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) - 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]; - int 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]; - int 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 int glnvg__checkError(const char* str) -{ - GLenum err = glGetError(); - if (err != GL_NO_ERROR) { - printf("Error %08x after %s\n", err, str); - return 1; - } - return 0; -} - -static int glnvg__createShader(struct 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(struct 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(struct 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_SCISSORMAT] = glGetUniformLocation(shader->prog, "scissorMat"); - shader->loc[GLNVG_LOC_SCISSOREXT] = glGetUniformLocation(shader->prog, "scissorExt"); - shader->loc[GLNVG_LOC_SCISSORSCALE] = glGetUniformLocation(shader->prog, "scissorScale"); - shader->loc[GLNVG_LOC_PAINTMAT] = glGetUniformLocation(shader->prog, "paintMat"); - shader->loc[GLNVG_LOC_EXTENT] = glGetUniformLocation(shader->prog, "extent"); - shader->loc[GLNVG_LOC_RADIUS] = glGetUniformLocation(shader->prog, "radius"); - shader->loc[GLNVG_LOC_FEATHER] = glGetUniformLocation(shader->prog, "feather"); - shader->loc[GLNVG_LOC_INNERCOL] = glGetUniformLocation(shader->prog, "innerCol"); - shader->loc[GLNVG_LOC_OUTERCOL] = glGetUniformLocation(shader->prog, "outerCol"); - shader->loc[GLNVG_LOC_STROKEMULT] = glGetUniformLocation(shader->prog, "strokeMult"); - shader->loc[GLNVG_LOC_TEXTYPE] = glGetUniformLocation(shader->prog, "texType"); - shader->loc[GLNVG_LOC_TYPE] = glGetUniformLocation(shader->prog, "type"); -#endif -} - -static int glnvg__renderCreate(void* uptr) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - int align = 4; - - // TODO: mediump float may not be enough for GLES2 in iOS. - // see the following discussion: https://github.com/memononen/nanovg/issues/46 - static const char* shaderHeader = -#if defined NANOVG_GL2 - "#define NANOVG_GL2 1\n"; -#elif defined NANOVG_GL3 - "#version 150 core\n" -#if NANOVG_GL_USE_UNIFORMBUFFER - "#define USE_UNIFORMBUFFER 1\n" -#endif - "#define NANOVG_GL3 1\n"; -#elif defined NANOVG_GLES2 - "#version 100\n" - "precision mediump float;\n" - "#define NANOVG_GL2 1\n"; -#elif defined NANOVG_GLES3 - "#version 300 es\n" - "precision mediump float;\n" - "#define NANOVG_GL3 1\n"; -#endif - - 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 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" - " int texType;\n" - " int type;\n" - " };\n" - "#else\n" - " uniform mat3 scissorMat;\n" - " uniform mat3 paintMat;\n" - " uniform vec4 innerCol;\n" - " uniform vec4 outerCol;\n" - " uniform vec2 scissorExt;\n" - " uniform vec2 scissorScale;\n" - " uniform vec2 extent;\n" - " uniform float radius;\n" - " uniform float feather;\n" - " uniform float strokeMult;\n" - " uniform int texType;\n" - " uniform int type;\n" - "#endif\n" - " uniform sampler2D tex;\n" - " in vec2 ftcoord;\n" - " in vec2 fpos;\n" - " out vec4 outColor;\n" - "#else\n" - " uniform mat3 scissorMat;\n" - " uniform mat3 paintMat;\n" - " uniform vec4 innerCol;\n" - " uniform vec4 outerCol;\n" - " uniform vec2 scissorExt;\n" - " uniform vec2 scissorScale;\n" - " uniform vec2 extent;\n" - " uniform float radius;\n" - " uniform float feather;\n" - " uniform float strokeMult;\n" - " uniform int texType;\n" - " uniform int type;\n" - " uniform sampler2D tex;\n" - " varying vec2 ftcoord;\n" - " varying vec2 fpos;\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" - "#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.w *= 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" - " color = texType == 0 ? color : vec4(1,1,1,color.x);\n" - " // Combine alpha\n" - " color.w *= 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" - " color = texType == 0 ? color : vec4(1,1,1,color.x);\n" - " color.w *= 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("init"); - - if (gl->edgeAntiAlias) { - 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("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(struct GLNVGfragUniforms) + align - sizeof(struct GLNVGfragUniforms) % align; - - glnvg__checkError("create done"); - - glFinish(); - - return 1; -} - -static int glnvg__renderCreateTexture(void* uptr, int type, int w, int h, const unsigned char* data) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct GLNVGtexture* tex = glnvg__allocTexture(gl); - - if (tex == NULL) return 0; - - glGenTextures(1, &tex->tex); - tex->width = w; - tex->height = h; - tex->type = type; - glBindTexture(GL_TEXTURE_2D, 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 (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) - 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 - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - 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 - - if (glnvg__checkError("create tex")) - return 0; - - glBindTexture(GL_TEXTURE_2D, 0); - - return tex->id; -} - - -static int glnvg__renderDeleteTexture(void* uptr, int image) -{ - struct GLNVGcontext* gl = (struct 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) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct GLNVGtexture* tex = glnvg__findTexture(gl, image); - - if (tex == NULL) return 0; - glBindTexture(GL_TEXTURE_2D, 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 -#ifdef NANOVG_GLES2 - 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 - - glBindTexture(GL_TEXTURE_2D, 0); - - return 1; -} - -static int glnvg__renderGetTextureSize(void* uptr, int image, int* w, int* h) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct 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 int glnvg__convertPaint(struct GLNVGcontext* gl, struct GLNVGfragUniforms* frag, struct NVGpaint* paint, - struct NVGscissor* scissor, float width, float fringe) -{ - struct GLNVGtexture* tex = NULL; - float invxform[6]; - - memset(frag, 0, sizeof(*frag)); - - frag->innerCol = paint->innerColor; - frag->outerCol = paint->outerColor; - - nvgTransformInverse(invxform, paint->xform); - glnvg__xformToMat3x4(frag->paintMat, invxform); - - 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; - - if (paint->image != 0) { - tex = glnvg__findTexture(gl, paint->image); - if (tex == NULL) return 0; - frag->type = NSVG_SHADER_FILLIMG; - frag->texType = tex->type == NVG_TEXTURE_RGBA ? 0 : 1; - } else { - frag->type = NSVG_SHADER_FILLGRAD; - frag->radius = paint->radius; - frag->feather = paint->feather; - } - return 1; -} - -static struct GLNVGfragUniforms* nvg__fragUniformPtr(struct GLNVGcontext* gl, int i); - -#if !NANOVG_GL_USE_UNIFORMBUFFER -static void glnvg__mat3(float* dst, float* src) -{ - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - - dst[3] = src[4]; - dst[4] = src[5]; - dst[5] = src[6]; - - dst[6] = src[8]; - dst[7] = src[9]; - dst[8] = src[10]; -} -#endif - -static void glnvg__setUniforms(struct GLNVGcontext* gl, int uniformOffset, int image) -{ -#if NANOVG_GL_USE_UNIFORMBUFFER - glBindBufferRange(GL_UNIFORM_BUFFER, GLNVG_FRAG_BINDING, gl->fragBuf, uniformOffset, sizeof(struct GLNVGfragUniforms)); -#else - struct GLNVGfragUniforms* frag = nvg__fragUniformPtr(gl, uniformOffset); - float tmp[9]; // Maybe there's a way to get rid of this... - glnvg__mat3(tmp, frag->scissorMat); - glUniformMatrix3fv(gl->shader.loc[GLNVG_LOC_SCISSORMAT], 1, GL_FALSE, tmp); - glnvg__mat3(tmp, frag->paintMat); - glUniformMatrix3fv(gl->shader.loc[GLNVG_LOC_PAINTMAT], 1, GL_FALSE, tmp); - glUniform4fv(gl->shader.loc[GLNVG_LOC_INNERCOL], 1, frag->innerCol.rgba); - glUniform4fv(gl->shader.loc[GLNVG_LOC_OUTERCOL], 1, frag->outerCol.rgba); - glUniform2fv(gl->shader.loc[GLNVG_LOC_SCISSOREXT], 1, frag->scissorExt); - glUniform2fv(gl->shader.loc[GLNVG_LOC_SCISSORSCALE], 1, frag->scissorScale); - glUniform2fv(gl->shader.loc[GLNVG_LOC_EXTENT], 1, frag->extent); - glUniform1f(gl->shader.loc[GLNVG_LOC_RADIUS], frag->radius); - glUniform1f(gl->shader.loc[GLNVG_LOC_FEATHER], frag->feather); - glUniform1f(gl->shader.loc[GLNVG_LOC_STROKEMULT], frag->strokeMult); - glUniform1i(gl->shader.loc[GLNVG_LOC_TEXTYPE], frag->texType); - glUniform1i(gl->shader.loc[GLNVG_LOC_TYPE], frag->type); -#endif - - if (image != 0) { - struct GLNVGtexture* tex = glnvg__findTexture(gl, image); - glBindTexture(GL_TEXTURE_2D, tex != NULL ? tex->tex : 0); - glnvg__checkError("tex paint tex"); - } else { - glBindTexture(GL_TEXTURE_2D, 0); - } -} - -static void glnvg__renderViewport(void* uptr, int width, int height, int alphaBlend) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - NVG_NOTUSED(alphaBlend); - gl->view[0] = (float)width; - gl->view[1] = (float)height; -} - -static void glnvg__fill(struct GLNVGcontext* gl, struct GLNVGcall* call) -{ - struct GLNVGpath* paths = &gl->paths[call->pathOffset]; - int i, npaths = call->pathCount; - - // Draw shapes - glEnable(GL_STENCIL_TEST); - glStencilMask(0xff); - glStencilFunc(GL_ALWAYS, 0, ~0L); - glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - - // set bindpoint for solid loc - glnvg__setUniforms(gl, call->uniformOffset, 0); - glnvg__checkError("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 aliased off-pixels - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - - glnvg__setUniforms(gl, call->uniformOffset + gl->fragSize, call->image); - glnvg__checkError("fill fill"); - - if (gl->edgeAntiAlias) { - glStencilFunc(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 - glStencilFunc(GL_NOTEQUAL, 0x0, 0xff); - glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); - glDrawArrays(GL_TRIANGLES, call->triangleOffset, call->triangleCount); - - glDisable(GL_STENCIL_TEST); -} - -static void glnvg__convexFill(struct GLNVGcontext* gl, struct GLNVGcall* call) -{ - struct GLNVGpath* paths = &gl->paths[call->pathOffset]; - int i, npaths = call->pathCount; - - glnvg__setUniforms(gl, call->uniformOffset, call->image); - glnvg__checkError("convex fill"); - - for (i = 0; i < npaths; i++) - glDrawArrays(GL_TRIANGLE_FAN, paths[i].fillOffset, paths[i].fillCount); - if (gl->edgeAntiAlias) { - // Draw fringes - for (i = 0; i < npaths; i++) - glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); - } -} - -static void glnvg__stroke(struct GLNVGcontext* gl, struct GLNVGcall* call) -{ - struct GLNVGpath* paths = &gl->paths[call->pathOffset]; - int npaths = call->pathCount, i; - - glnvg__setUniforms(gl, call->uniformOffset, call->image); - glnvg__checkError("stroke fill"); - - // Draw Strokes - for (i = 0; i < npaths; i++) - glDrawArrays(GL_TRIANGLE_STRIP, paths[i].strokeOffset, paths[i].strokeCount); -} - -static void glnvg__triangles(struct GLNVGcontext* gl, struct GLNVGcall* call) -{ - glnvg__setUniforms(gl, call->uniformOffset, call->image); - glnvg__checkError("triangles fill"); - - glDrawArrays(GL_TRIANGLES, call->triangleOffset, call->triangleCount); -} - -static void glnvg__renderFlush(void* uptr, int alphaBlend) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - int i; - - if (gl->ncalls > 0) { - - // Setup require GL state. - glUseProgram(gl->shader.prog); - - if (alphaBlend == NVG_PREMULTIPLIED_ALPHA) - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - else - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - 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); - -#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(struct NVGvertex), gl->verts, GL_STREAM_DRAW); - glEnableVertexAttribArray(0); - glEnableVertexAttribArray(1); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(struct NVGvertex), (const GLvoid*)(size_t)0); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(struct 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++) { - struct GLNVGcall* call = &gl->calls[i]; - 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 - glUseProgram(0); - glBindTexture(GL_TEXTURE_2D, 0); - } - - // Reset calls - gl->nverts = 0; - gl->npaths = 0; - gl->ncalls = 0; - gl->nuniforms = 0; -} - -static int glnvg__maxVertCount(const struct 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 struct GLNVGcall* glnvg__allocCall(struct GLNVGcontext* gl) -{ - struct GLNVGcall* ret = NULL; - if (gl->ncalls+1 > gl->ccalls) { - struct GLNVGcall* calls; - int ccalls = glnvg__maxi(gl->ncalls+1, 128) + gl->ccalls; // 1.5x Overallocate - calls = (struct GLNVGcall*)realloc(gl->calls, sizeof(struct GLNVGcall) * ccalls); - if (calls == NULL) return NULL; - gl->calls = calls; - gl->ccalls = ccalls; - } - ret = &gl->calls[gl->ncalls++]; - memset(ret, 0, sizeof(struct GLNVGcall)); - return ret; -} - -static int glnvg__allocPaths(struct GLNVGcontext* gl, int n) -{ - int ret = 0; - if (gl->npaths+n > gl->cpaths) { - struct GLNVGpath* paths; - int cpaths = glnvg__maxi(gl->npaths + n, 128) + gl->cpaths; // 1.5x Overallocate - paths = (struct GLNVGpath*)realloc(gl->paths, sizeof(struct 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(struct GLNVGcontext* gl, int n) -{ - int ret = 0; - if (gl->nverts+n > gl->cverts) { - struct NVGvertex* verts; - int cverts = glnvg__maxi(gl->nverts + n, 4096) + gl->cverts/2; // 1.5x Overallocate - verts = (struct NVGvertex*)realloc(gl->verts, sizeof(struct 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(struct 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 struct GLNVGfragUniforms* nvg__fragUniformPtr(struct GLNVGcontext* gl, int i) -{ - return (struct GLNVGfragUniforms*)&gl->uniforms[i]; -} - -static void glnvg__vset(struct 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, struct NVGpaint* paint, struct NVGscissor* scissor, float fringe, - const float* bounds, const struct NVGpath* paths, int npaths) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct GLNVGcall* call = glnvg__allocCall(gl); - struct NVGvertex* quad; - struct GLNVGfragUniforms* frag; - int i, maxverts, offset; - - if (call == NULL) return; - - call->type = GLNVG_FILL; - call->pathOffset = glnvg__allocPaths(gl, npaths); - if (call->pathOffset == -1) goto error; - call->pathCount = npaths; - call->image = paint->image; - - if (npaths == 1 && paths[0].convex) - call->type = GLNVG_CONVEXFILL; - - // Allocate vertices for all the paths. - maxverts = glnvg__maxVertCount(paths, npaths) + 6; - offset = glnvg__allocVerts(gl, maxverts); - if (offset == -1) goto error; - - for (i = 0; i < npaths; i++) { - struct GLNVGpath* copy = &gl->paths[call->pathOffset + i]; - const struct NVGpath* path = &paths[i]; - memset(copy, 0, sizeof(struct GLNVGpath)); - if (path->nfill > 0) { - copy->fillOffset = offset; - copy->fillCount = path->nfill; - memcpy(&gl->verts[offset], path->fill, sizeof(struct NVGvertex) * path->nfill); - offset += path->nfill; - } - if (path->nstroke > 0) { - copy->strokeOffset = offset; - copy->strokeCount = path->nstroke; - memcpy(&gl->verts[offset], path->stroke, sizeof(struct NVGvertex) * path->nstroke); - offset += path->nstroke; - } - } - - // Quad - call->triangleOffset = offset; - call->triangleCount = 6; - quad = &gl->verts[call->triangleOffset]; - glnvg__vset(&quad[0], bounds[0], bounds[3], 0.5f, 1.0f); - glnvg__vset(&quad[1], bounds[2], bounds[3], 0.5f, 1.0f); - glnvg__vset(&quad[2], bounds[2], bounds[1], 0.5f, 1.0f); - - glnvg__vset(&quad[3], bounds[0], bounds[3], 0.5f, 1.0f); - glnvg__vset(&quad[4], bounds[2], bounds[1], 0.5f, 1.0f); - glnvg__vset(&quad[5], bounds[0], bounds[1], 0.5f, 1.0f); - - // Setup uniforms for draw calls - if (call->type == GLNVG_FILL) { - 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->type = NSVG_SHADER_SIMPLE; - // Fill shader - glnvg__convertPaint(gl, nvg__fragUniformPtr(gl, call->uniformOffset + gl->fragSize), paint, scissor, fringe, fringe); - } 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); - } - - 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, struct NVGpaint* paint, struct NVGscissor* scissor, float fringe, - float strokeWidth, const struct NVGpath* paths, int npaths) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct 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; - - // 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++) { - struct GLNVGpath* copy = &gl->paths[call->pathOffset + i]; - const struct NVGpath* path = &paths[i]; - memset(copy, 0, sizeof(struct GLNVGpath)); - if (path->nstroke) { - copy->strokeOffset = offset; - copy->strokeCount = path->nstroke; - memcpy(&gl->verts[offset], path->stroke, sizeof(struct NVGvertex) * path->nstroke); - offset += path->nstroke; - } - } - - // 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); - - 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, struct NVGpaint* paint, struct NVGscissor* scissor, - const struct NVGvertex* verts, int nverts) -{ - struct GLNVGcontext* gl = (struct GLNVGcontext*)uptr; - struct GLNVGcall* call = glnvg__allocCall(gl); - struct GLNVGfragUniforms* frag; - - if (call == NULL) return; - - call->type = GLNVG_TRIANGLES; - call->image = paint->image; - - // 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(struct 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, 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) -{ - struct GLNVGcontext* gl = (struct 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) - glDeleteTextures(1, &gl->textures[i].tex); - } - free(gl->textures); - - free(gl); -} - - -#if defined NANOVG_GL2 -struct NVGcontext* nvgCreateGL2(int atlasw, int atlash, int edgeaa) -#elif defined NANOVG_GL3 -struct NVGcontext* nvgCreateGL3(int atlasw, int atlash, int edgeaa) -#elif defined NANOVG_GLES2 -struct NVGcontext* nvgCreateGLES2(int atlasw, int atlash, int edgeaa) -#elif defined NANOVG_GLES3 -struct NVGcontext* nvgCreateGLES3(int atlasw, int atlash, int edgeaa) -#endif -{ - struct NVGparams params; - struct NVGcontext* ctx = NULL; - struct GLNVGcontext* gl = (struct GLNVGcontext*)malloc(sizeof(struct GLNVGcontext)); - if (gl == NULL) goto error; - memset(gl, 0, sizeof(struct 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.renderFlush = glnvg__renderFlush; - params.renderFill = glnvg__renderFill; - params.renderStroke = glnvg__renderStroke; - params.renderTriangles = glnvg__renderTriangles; - params.renderDelete = glnvg__renderDelete; - params.userPtr = gl; - params.atlasWidth = atlasw; - params.atlasHeight = atlash; - params.edgeAntiAlias = edgeaa; - - gl->edgeAntiAlias = edgeaa; - - ctx = nvgCreateInternal(¶ms); - if (ctx == NULL) goto error; - - return ctx; - -error: - // 'gl' is freed by nvgDeleteInternal. - if (ctx != NULL) nvgDeleteInternal(ctx); - return NULL; -} - -#if NANOVG_GL2 -void nvgDeleteGL2(struct NVGcontext* ctx) -#elif NANOVG_GL3 -void nvgDeleteGL3(struct NVGcontext* ctx) -#elif NANOVG_GLES2 -void nvgDeleteGLES2(struct NVGcontext* ctx) -#elif NANOVG_GLES3 -void nvgDeleteGLES3(struct NVGcontext* ctx) -#endif -{ - nvgDeleteInternal(ctx); -} - -#endif diff --git a/libs/dgl/src/nanovg/stb_image.c b/libs/dgl/src/nanovg/stb_image.c deleted file mode 100644 index d72ee6a..0000000 --- a/libs/dgl/src/nanovg/stb_image.c +++ /dev/null @@ -1,4676 +0,0 @@ -/* stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
- when you control the images you're loading
- no warranty implied; use at your own risk
-
- QUICK NOTES:
- Primarily of interest to game developers and other people who can
- avoid problematic images and only need the trivial interface
-
- JPEG baseline (no JPEG progressive)
- PNG 8-bit-per-channel only
-
- TGA (not sure what subset, if a subset)
- BMP non-1bpp, non-RLE
- PSD (composited view only, no extra channels)
-
- GIF (*comp always reports as 4-channel)
- HDR (radiance rgbE format)
- PIC (Softimage PIC)
-
- - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
- - decode from arbitrary I/O callbacks
- - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
-
- Latest revisions:
- 1.33 (2011-07-14) minor fixes suggested by Dave Moore
- 1.32 (2011-07-13) info support for all filetypes (SpartanJ)
- 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)
- 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)
- 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-uint8 to fix warnings (Laurent Gomila)
- allow trailing 0s at end of image data (Laurent Gomila)
- 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ
-
- See end of file for full revision history.
-
- TODO:
- stbi_info support for BMP,PSD,HDR,PIC
-
-
- ============================ Contributors =========================
-
- Image formats Optimizations & bugfixes
- Sean Barrett (jpeg, png, bmp) Fabian "ryg" Giesen
- Nicolas Schulz (hdr, psd)
- Jonathan Dummer (tga) Bug fixes & warning fixes
- Jean-Marc Lienher (gif) Marc LeBlanc
- Tom Seddon (pic) Christpher Lloyd
- Thatcher Ulrich (psd) Dave Moore
- Won Chun
- the Horde3D community
- Extensions, features Janez Zemva
- Jetro Lauha (stbi_info) Jonathan Blow
- James "moose2000" Brown (iPhone PNG) Laurent Gomila
- Ben "Disch" Wenger (io callbacks) Aruelien Pocheville
- Martin "SpartanJ" Golini Ryamond Barbiero
- David Woo
-
-
- If your name should be here but isn't, let Sean know.
-
-*/
-
-#ifndef STBI_INCLUDE_STB_IMAGE_H
-#define STBI_INCLUDE_STB_IMAGE_H
-
-// To get a header file for this, either cut and paste the header,
-// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and
-// then include stb_image.c from it.
-
-//// begin header file ////////////////////////////////////////////////////
-//
-// Limitations:
-// - no jpeg progressive support
-// - non-HDR formats support 8-bit samples only (jpeg, png)
-// - no delayed line count (jpeg) -- IJG doesn't support either
-// - no 1-bit BMP
-// - GIF always returns *comp=4
-//
-// Basic usage (see HDR discussion below):
-// 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 *comp -- outputs # of image components in image file
-// int req_comp -- 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. 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 'req_comp' if req_comp is non-zero, or *comp otherwise.
-// If req_comp is non-zero, *comp has the number of components that _would_
-// have been output otherwise. E.g. if you set req_comp to 4, you will always
-// get RGBA output, but you can check *comp to easily see if it's opaque.
-//
-// 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, *comp 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.
-//
-// ===========================================================================
-//
-// iPhone PNG support:
-//
-// By default we convert iphone-formatted PNGs back to RGB; nominally they
-// would silently load as BGR, except the existing code should have just
-// failed on such iPhone PNGs. But you can disable this conversion by
-// by calling stbi_convert_iphone_png_to_rgb(0), in which case
-// you will always just get the native iphone "format" through.
-//
-// 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).
-//
-// ===========================================================================
-//
-// HDR image support (disable by defining STBI_NO_HDR)
-//
-// stb_image now supports loading HDR images in general, and currently
-// the Radiance .HDR file format, although the support is provided
-// generically. 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);
-//
-// ===========================================================================
-//
-// 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).
-
-
-#ifndef STBI_NO_STDIO
-
-#if defined(_MSC_VER) && _MSC_VER >= 0x1400
-#define _CRT_SECURE_NO_WARNINGS // suppress bogus warnings about fopen()
-#endif
-
-#include <stdio.h>
-#endif
-
-#define STBI_VERSION 1
-
-enum
-{
- STBI_default = 0, // only used for req_comp
-
- STBI_grey = 1,
- STBI_grey_alpha = 2,
- STBI_rgb = 3,
- STBI_rgb_alpha = 4
-};
-
-typedef unsigned char stbi_uc;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// PRIMARY API - works on images of any type
-//
-
-//
-// load image by filename, open file, or memory buffer
-//
-
-extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
-
-#ifndef STBI_NO_STDIO
-extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
-extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
-// for stbi_load_from_file, file pointer is left pointing immediately after image
-#endif
-
-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,unsigned n); // skip the next 'n' bytes
- int (*eof) (void *user); // returns nonzero if we are at end of file/data
-} stbi_io_callbacks;
-
-extern stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
-
-#ifndef STBI_NO_HDR
- extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
-
- #ifndef STBI_NO_STDIO
- extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
- extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
- #endif
-
- extern float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
-
- extern void stbi_hdr_to_ldr_gamma(float gamma);
- extern void stbi_hdr_to_ldr_scale(float scale);
-
- extern void stbi_ldr_to_hdr_gamma(float gamma);
- extern void stbi_ldr_to_hdr_scale(float scale);
-#endif // STBI_NO_HDR
-
-// stbi_is_hdr is always defined
-extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
-extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
-#ifndef STBI_NO_STDIO
-extern int stbi_is_hdr (char const *filename);
-extern int stbi_is_hdr_from_file(FILE *f);
-#endif // STBI_NO_STDIO
-
-
-// get a VERY brief reason for failure
-// NOT THREADSAFE
-extern const char *stbi_failure_reason (void);
-
-// free the loaded image -- this is just free()
-extern void stbi_image_free (void *retval_from_stbi_load);
-
-// get image dimensions & components without fully decoding
-extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
-extern int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
-
-#ifndef STBI_NO_STDIO
-extern int stbi_info (char const *filename, int *x, int *y, int *comp);
-extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
-
-#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.
-extern 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"
-extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
-
-
-// ZLIB client - used by PNG, available for other purposes
-
-extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
-extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
-extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
-
-extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
-extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
-
-
-// define faster low-level operations (typically SIMD support)
-#ifdef STBI_SIMD
-typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
-// compute an integer IDCT on "input"
-// input[x] = data[x] * dequantize[x]
-// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
-// CLAMP results to 0..255
-typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);
-// compute a conversion from YCbCr to RGB
-// 'count' pixels
-// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
-// y: Y input channel
-// cb: Cb input channel; scale/biased to be 0..255
-// cr: Cr input channel; scale/biased to be 0..255
-
-extern void stbi_install_idct(stbi_idct_8x8 func);
-extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
-#endif // STBI_SIMD
-
-
-#ifdef __cplusplus
-}
-#endif
-
-//
-//
-//// end header file /////////////////////////////////////////////////////
-#endif // STBI_INCLUDE_STB_IMAGE_H
-
-#ifndef STBI_HEADER_FILE_ONLY
-
-#ifndef STBI_NO_HDR
-#include <math.h> // ldexp
-#include <string.h> // strcmp, strtok
-#endif
-
-#ifndef STBI_NO_STDIO
-#include <stdio.h>
-#endif
-#include <stdlib.h>
-#include <memory.h>
-#include <assert.h>
-#include <stdarg.h>
-
-#ifndef _MSC_VER
- #ifdef __cplusplus
- #define stbi_inline inline
- #else
- #define stbi_inline
- #endif
-#else
- #define stbi_inline __forceinline
-#endif
-
-
-// implementation:
-typedef unsigned char uint8;
-typedef unsigned short uint16;
-typedef signed short int16;
-typedef unsigned int uint32;
-typedef signed int int32;
-typedef unsigned int uint;
-
-// should produce compiler error if size is wrong
-typedef unsigned char validate_uint32[sizeof(uint32)==4 ? 1 : -1];
-
-#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
-#define STBI_NO_WRITE
-#endif
-
-#define STBI_NOTUSED(v) (void)sizeof(v)
-
-#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) >> (32 - (y))))
-#endif
-
-///////////////////////////////////////////////
-//
-// stbi struct and start_xxx functions
-
-// stbi structure is our basic context used by all images, so it
-// contains all the IO context, plus some basic image information
-typedef struct
-{
- 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;
- uint8 buffer_start[128];
-
- uint8 *img_buffer, *img_buffer_end;
- uint8 *img_buffer_original;
-} stbi;
-
-
-static void refill_buffer(stbi *s);
-
-// initialize a memory-decode context
-static void start_mem(stbi *s, uint8 const *buffer, int len)
-{
- s->io.read = NULL;
- s->read_from_callbacks = 0;
- s->img_buffer = s->img_buffer_original = (uint8 *) buffer;
- s->img_buffer_end = (uint8 *) buffer+len;
-}
-
-// initialize a callback-based context
-static void start_callbacks(stbi *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->img_buffer_original = s->buffer_start;
- refill_buffer(s);
-}
-
-#ifndef STBI_NO_STDIO
-
-static int stdio_read(void *user, char *data, int size)
-{
- return (int) fread(data,1,size,(FILE*) user);
-}
-
-static void stdio_skip(void *user, unsigned n)
-{
- fseek((FILE*) user, n, SEEK_CUR);
-}
-
-static int stdio_eof(void *user)
-{
- return feof((FILE*) user);
-}
-
-static stbi_io_callbacks stbi_stdio_callbacks =
-{
- stdio_read,
- stdio_skip,
- stdio_eof,
-};
-
-static void start_file(stbi *s, FILE *f)
-{
- start_callbacks(s, &stbi_stdio_callbacks, (void *) f);
-}
-
-//static void stop_file(stbi *s) { }
-
-#endif // !STBI_NO_STDIO
-
-static void stbi_rewind(stbi *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;
-}
-
-static int stbi_jpeg_test(stbi *s);
-static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);
-static int stbi_png_test(stbi *s);
-static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_png_info(stbi *s, int *x, int *y, int *comp);
-static int stbi_bmp_test(stbi *s);
-static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_tga_test(stbi *s);
-static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_tga_info(stbi *s, int *x, int *y, int *comp);
-static int stbi_psd_test(stbi *s);
-static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_hdr_test(stbi *s);
-static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_pic_test(stbi *s);
-static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_gif_test(stbi *s);
-static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
-static int stbi_gif_info(stbi *s, int *x, int *y, int *comp);
-
-
-// this is not threadsafe
-static const char *failure_reason;
-
-const char *stbi_failure_reason(void)
-{
- return failure_reason;
-}
-
-static int e(const char *str)
-{
- failure_reason = str;
- return 0;
-}
-
-// e - error
-// epf - error returning pointer to float
-// epuc - error returning pointer to unsigned char
-
-#ifdef STBI_NO_FAILURE_STRINGS
- #define e(x,y) 0
-#elif defined(STBI_FAILURE_USERMSG)
- #define e(x,y) e(y)
-#else
- #define e(x,y) e(x)
-#endif
-
-#define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
-#define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
-
-void stbi_image_free(void *retval_from_stbi_load)
-{
- free(retval_from_stbi_load);
-}
-
-#ifndef STBI_NO_HDR
-static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
-static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
-#endif
-
-static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);
- if (stbi_png_test(s)) return stbi_png_load(s,x,y,comp,req_comp);
- if (stbi_bmp_test(s)) return stbi_bmp_load(s,x,y,comp,req_comp);
- if (stbi_gif_test(s)) return stbi_gif_load(s,x,y,comp,req_comp);
- if (stbi_psd_test(s)) return stbi_psd_load(s,x,y,comp,req_comp);
- if (stbi_pic_test(s)) return stbi_pic_load(s,x,y,comp,req_comp);
-
- #ifndef STBI_NO_HDR
- if (stbi_hdr_test(s)) {
- float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);
- return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
- }
- #endif
-
- // test tga last because it's a crappy test!
- if (stbi_tga_test(s))
- return stbi_tga_load(s,x,y,comp,req_comp);
- return epuc("unknown image type", "Image not of any known type, or corrupt");
-}
-
-#ifndef STBI_NO_STDIO
-unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
-{
- FILE *f = fopen(filename, "rb");
- unsigned char *result;
- if (!f) return epuc("can't fopen", "Unable to open file");
- result = stbi_load_from_file(f,x,y,comp,req_comp);
- fclose(f);
- return result;
-}
-
-unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_file(&s,f);
- return stbi_load_main(&s,x,y,comp,req_comp);
-}
-#endif //!STBI_NO_STDIO
-
-unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_mem(&s,buffer,len);
- return stbi_load_main(&s,x,y,comp,req_comp);
-}
-
-unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
- return stbi_load_main(&s,x,y,comp,req_comp);
-}
-
-#ifndef STBI_NO_HDR
-
-float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- unsigned char *data;
- #ifndef STBI_NO_HDR
- if (stbi_hdr_test(s))
- return stbi_hdr_load(s,x,y,comp,req_comp);
- #endif
- data = stbi_load_main(s, x, y, comp, req_comp);
- if (data)
- return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
- return epf("unknown image type", "Image not of any known type, or corrupt");
-}
-
-float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_mem(&s,buffer,len);
- return stbi_loadf_main(&s,x,y,comp,req_comp);
-}
-
-float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
- return stbi_loadf_main(&s,x,y,comp,req_comp);
-}
-
-#ifndef STBI_NO_STDIO
-float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
-{
- FILE *f = fopen(filename, "rb");
- float *result;
- if (!f) return epf("can't fopen", "Unable to open file");
- result = stbi_loadf_from_file(f,x,y,comp,req_comp);
- fclose(f);
- return result;
-}
-
-float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
-{
- stbi s;
- start_file(&s,f);
- return stbi_loadf_main(&s,x,y,comp,req_comp);
-}
-#endif // !STBI_NO_STDIO
-
-#endif // !STBI_NO_HDR
-
-// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
-// defined, for API simplicity; if STBI_NO_HDR is defined, it always
-// reports false!
-
-int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
-{
- #ifndef STBI_NO_HDR
- stbi s;
- start_mem(&s,buffer,len);
- return stbi_hdr_test(&s);
- #else
- STBI_NOTUSED(buffer);
- STBI_NOTUSED(len);
- return 0;
- #endif
-}
-
-#ifndef STBI_NO_STDIO
-extern int stbi_is_hdr (char const *filename)
-{
- FILE *f = fopen(filename, "rb");
- int result=0;
- if (f) {
- result = stbi_is_hdr_from_file(f);
- fclose(f);
- }
- return result;
-}
-
-extern int stbi_is_hdr_from_file(FILE *f)
-{
- #ifndef STBI_NO_HDR
- stbi s;
- start_file(&s,f);
- return stbi_hdr_test(&s);
- #else
- return 0;
- #endif
-}
-#endif // !STBI_NO_STDIO
-
-extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
-{
- #ifndef STBI_NO_HDR
- stbi s;
- start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
- return stbi_hdr_test(&s);
- #else
- return 0;
- #endif
-}
-
-#ifndef STBI_NO_HDR
-static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
-static float l2h_gamma=2.2f, l2h_scale=1.0f;
-
-void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
-void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
-
-void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
-void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
-#endif
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// Common code used by all image loaders
-//
-
-enum
-{
- SCAN_load=0,
- SCAN_type,
- SCAN_header
-};
-
-static void refill_buffer(stbi *s)
-{
- int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
- if (n == 0) {
- // at end of file, treat same as if from memory
- s->read_from_callbacks = 0;
- s->img_buffer = s->img_buffer_end-1;
- *s->img_buffer = 0;
- } else {
- s->img_buffer = s->buffer_start;
- s->img_buffer_end = s->buffer_start + n;
- }
-}
-
-stbi_inline static int get8(stbi *s)
-{
- if (s->img_buffer < s->img_buffer_end)
- return *s->img_buffer++;
- if (s->read_from_callbacks) {
- refill_buffer(s);
- return *s->img_buffer++;
- }
- return 0;
-}
-
-stbi_inline static int at_eof(stbi *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;
-}
-
-stbi_inline static uint8 get8u(stbi *s)
-{
- return (uint8) get8(s);
-}
-
-static void skip(stbi *s, int n)
-{
- if (s->io.read) {
- int blen = 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;
-}
-
-static int getn(stbi *s, stbi_uc *buffer, int n)
-{
- if (s->io.read) {
- int blen = 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;
-}
-
-static int get16(stbi *s)
-{
- int z = get8(s);
- return (z << 8) + get8(s);
-}
-
-static uint32 get32(stbi *s)
-{
- uint32 z = get16(s);
- return (z << 16) + get16(s);
-}
-
-static int get16le(stbi *s)
-{
- int z = get8(s);
- return z + (get8(s) << 8);
-}
-
-static uint32 get32le(stbi *s)
-{
- uint32 z = get16le(s);
- return z + (get16le(s) << 16);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// 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 uint8 compute_y(int r, int g, int b)
-{
- return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
-}
-
-static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
-{
- int i,j;
- unsigned char *good;
-
- if (req_comp == img_n) return data;
- assert(req_comp >= 1 && req_comp <= 4);
-
- good = (unsigned char *) malloc(req_comp * x * y);
- if (good == NULL) {
- free(data);
- return epuc("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 COMBO(a,b) ((a)*8+(b))
- #define CASE(a,b) case 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 (COMBO(img_n, req_comp)) {
- CASE(1,2) dest[0]=src[0], dest[1]=255; break;
- CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
- CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
- CASE(2,1) dest[0]=src[0]; break;
- CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
- CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
- CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
- CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
- CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
- CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
- CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
- CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
- default: assert(0);
- }
- #undef CASE
- }
-
- free(data);
- return good;
-}
-
-#ifndef STBI_NO_HDR
-static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
-{
- int i,k,n;
- float *output = (float *) malloc(x * y * comp * sizeof(float));
- if (output == NULL) { free(data); return epf("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, l2h_gamma) * l2h_scale;
- }
- if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
- }
- free(data);
- return output;
-}
-
-#define float2int(x) ((int) (x))
-static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
-{
- int i,k,n;
- stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
- if (output == NULL) { free(data); return epuc("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]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
- if (z < 0) z = 0;
- if (z > 255) z = 255;
- output[i*comp + k] = (uint8) 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] = (uint8) float2int(z);
- }
- }
- free(data);
- return output;
-}
-#endif
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
-//
-// simple implementation
-// - channel subsampling of at most 2 in each dimension
-// - 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
-// - uses a lot of intermediate memory, could cache poorly
-// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
-// stb_jpeg: 1.34 seconds (MSVC6, default release build)
-// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
-// IJL11.dll: 1.08 seconds (compiled by intel)
-// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
-// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
-
-// huffman decoding acceleration
-#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
-
-typedef struct
-{
- uint8 fast[1 << FAST_BITS];
- // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
- uint16 code[256];
- uint8 values[256];
- uint8 size[257];
- unsigned int maxcode[18];
- int delta[17]; // old 'firstsymbol' - old 'firstcode'
-} huffman;
-
-typedef struct
-{
- #ifdef STBI_SIMD
- unsigned short dequant2[4][64];
- #endif
- stbi *s;
- huffman huff_dc[4];
- huffman huff_ac[4];
- uint8 dequant[4][64];
-
-// 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;
- uint8 *data;
- void *raw_data;
- uint8 *linebuf;
- } img_comp[4];
-
- 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 scan_n, order[4];
- int restart_interval, todo;
-} jpeg;
-
-static int build_huffman(huffman *h, int *count)
-{
- int i,j,k=0,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++] = (uint8) (i+1);
- 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++] = (uint16) (code++);
- if (code-1 >= (1 << j)) return e("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] = (uint8) i;
- }
- }
- }
- return 1;
-}
-
-static void grow_buffer_unsafe(jpeg *j)
-{
- do {
- int b = j->nomore ? 0 : get8(j->s);
- if (b == 0xff) {
- int c = get8(j->s);
- 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 uint32 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 decode(jpeg *j, huffman *h)
-{
- unsigned int temp;
- int c,k;
-
- if (j->code_bits < 16) 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)) & bmask[k]) + h->delta[k];
- assert((((j->code_buffer) >> (32 - h->size[c])) & 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];
-}
-
-// combined JPEG 'receive' and JPEG 'extend', since baseline
-// always extends everything it receives.
-stbi_inline static int extend_receive(jpeg *j, int n)
-{
- unsigned int m = 1 << (n-1);
- unsigned int k;
- if (j->code_bits < n) grow_buffer_unsafe(j);
-
- #if 1
- k = stbi_lrot(j->code_buffer, n);
- j->code_buffer = k & ~bmask[n];
- k &= bmask[n];
- j->code_bits -= n;
- #else
- k = (j->code_buffer >> (32 - n)) & bmask[n];
- j->code_bits -= n;
- j->code_buffer <<= n;
- #endif
- // the following test is probably a random branch that won't
- // predict well. I tried to table accelerate it but failed.
- // maybe it's compiling as a conditional move?
- if (k < m)
- return (-1 << n) + k + 1;
- else
- return k;
-}
-
-// 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 uint8 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 decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
-{
- int diff,dc,k;
- int t = decode(j, hdc);
- if (t < 0) return e("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 ? extend_receive(j, t) : 0;
- dc = j->img_comp[b].dc_pred + diff;
- j->img_comp[b].dc_pred = dc;
- data[0] = (short) dc;
-
- // decode AC components, see JPEG spec
- k = 1;
- do {
- int r,s;
- int rs = decode(j, hac);
- if (rs < 0) return e("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
- data[dezigzag[k++]] = (short) extend_receive(j,s);
- }
- } while (k < 64);
- return 1;
-}
-
-// take a -128..127 value and clamp it and convert to 0..255
-stbi_inline static uint8 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 (uint8) x;
-}
-
-#define f2f(x) (int) (((x) * 4096 + 0.5))
-#define fsh(x) ((x) << 12)
-
-// derived from jidctint -- DCT_ISLOW
-#define 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) * f2f(0.5411961f); \
- t2 = p1 + p3*f2f(-1.847759065f); \
- t3 = p1 + p2*f2f( 0.765366865f); \
- p2 = s0; \
- p3 = s4; \
- t0 = fsh(p2+p3); \
- t1 = 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)*f2f( 1.175875602f); \
- t0 = t0*f2f( 0.298631336f); \
- t1 = t1*f2f( 2.053119869f); \
- t2 = t2*f2f( 3.072711026f); \
- t3 = t3*f2f( 1.501321110f); \
- p1 = p5 + p1*f2f(-0.899976223f); \
- p2 = p5 + p2*f2f(-2.562915447f); \
- p3 = p3*f2f(-1.961570560f); \
- p4 = p4*f2f(-0.390180644f); \
- t3 += p1+p4; \
- t2 += p2+p3; \
- t1 += p2+p4; \
- t0 += p1+p3;
-
-#ifdef STBI_SIMD
-typedef unsigned short stbi_dequantize_t;
-#else
-typedef uint8 stbi_dequantize_t;
-#endif
-
-// .344 seconds on 3*anemones.jpg
-static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
-{
- int i,val[64],*v=val;
- stbi_dequantize_t *dq = dequantize;
- uint8 *o;
- short *d = data;
-
- // columns
- for (i=0; i < 8; ++i,++d,++dq, ++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] * dq[0] << 2;
- v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
- } else {
- IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
- d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[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
- 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] = clamp((x0+t3) >> 17);
- o[7] = clamp((x0-t3) >> 17);
- o[1] = clamp((x1+t2) >> 17);
- o[6] = clamp((x1-t2) >> 17);
- o[2] = clamp((x2+t1) >> 17);
- o[5] = clamp((x2-t1) >> 17);
- o[3] = clamp((x3+t0) >> 17);
- o[4] = clamp((x3-t0) >> 17);
- }
-}
-
-#ifdef STBI_SIMD
-static stbi_idct_8x8 stbi_idct_installed = idct_block;
-
-void stbi_install_idct(stbi_idct_8x8 func)
-{
- stbi_idct_installed = func;
-}
-#endif
-
-#define 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 uint8 get_marker(jpeg *j)
-{
- uint8 x;
- if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
- x = get8u(j->s);
- if (x != 0xff) return MARKER_none;
- while (x == 0xff)
- x = get8u(j->s);
- return x;
-}
-
-// in each scan, we'll have scan_n components, and the order
-// of the components is specified by order[]
-#define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
-
-// after a restart interval, reset the entropy decoder and
-// the dc prediction
-static void reset(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 = 0;
- j->marker = MARKER_none;
- j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
- // 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 parse_entropy_coded_data(jpeg *z)
-{
- reset(z);
- if (z->scan_n == 1) {
- int i,j;
- #ifdef STBI_SIMD
- __declspec(align(16))
- #endif
- 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) {
- if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
- #ifdef STBI_SIMD
- stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
- #else
- idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
- #endif
- // every data block is an MCU, so countdown the restart interval
- if (--z->todo <= 0) {
- if (z->code_bits < 24) grow_buffer_unsafe(z);
- // if it's NOT a restart, then just bail, so we get corrupt data
- // rather than no data
- if (!RESTART(z->marker)) return 1;
- reset(z);
- }
- }
- }
- } else { // interleaved!
- int i,j,k,x,y;
- 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;
- if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
- #ifdef STBI_SIMD
- stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
- #else
- idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
- #endif
- }
- }
- }
- // 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) grow_buffer_unsafe(z);
- // if it's NOT a restart, then just bail, so we get corrupt data
- // rather than no data
- if (!RESTART(z->marker)) return 1;
- reset(z);
- }
- }
- }
- }
- return 1;
-}
-
-static int process_marker(jpeg *z, int m)
-{
- int L;
- switch (m) {
- case MARKER_none: // no marker found
- return e("expected marker","Corrupt JPEG");
-
- case 0xC2: // SOF - progressive
- return e("progressive jpeg","JPEG format not supported (progressive)");
-
- case 0xDD: // DRI - specify restart interval
- if (get16(z->s) != 4) return e("bad DRI len","Corrupt JPEG");
- z->restart_interval = get16(z->s);
- return 1;
-
- case 0xDB: // DQT - define quantization table
- L = get16(z->s)-2;
- while (L > 0) {
- int q = get8(z->s);
- int p = q >> 4;
- int t = q & 15,i;
- if (p != 0) return e("bad DQT type","Corrupt JPEG");
- if (t > 3) return e("bad DQT table","Corrupt JPEG");
- for (i=0; i < 64; ++i)
- z->dequant[t][dezigzag[i]] = get8u(z->s);
- #ifdef STBI_SIMD
- for (i=0; i < 64; ++i)
- z->dequant2[t][i] = z->dequant[t][i];
- #endif
- L -= 65;
- }
- return L==0;
-
- case 0xC4: // DHT - define huffman table
- L = get16(z->s)-2;
- while (L > 0) {
- uint8 *v;
- int sizes[16],i,m=0;
- int q = get8(z->s);
- int tc = q >> 4;
- int th = q & 15;
- if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
- for (i=0; i < 16; ++i) {
- sizes[i] = get8(z->s);
- m += sizes[i];
- }
- L -= 17;
- if (tc == 0) {
- if (!build_huffman(z->huff_dc+th, sizes)) return 0;
- v = z->huff_dc[th].values;
- } else {
- if (!build_huffman(z->huff_ac+th, sizes)) return 0;
- v = z->huff_ac[th].values;
- }
- for (i=0; i < m; ++i)
- v[i] = get8u(z->s);
- L -= m;
- }
- return L==0;
- }
- // check for comment block or APP blocks
- if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
- skip(z->s, get16(z->s)-2);
- return 1;
- }
- return 0;
-}
-
-// after we see SOS
-static int process_scan_header(jpeg *z)
-{
- int i;
- int Ls = get16(z->s);
- z->scan_n = get8(z->s);
- if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return e("bad SOS component count","Corrupt JPEG");
- if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");
- for (i=0; i < z->scan_n; ++i) {
- int id = get8(z->s), which;
- int q = 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;
- z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
- z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
- z->order[i] = which;
- }
- if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
- get8(z->s); // should be 63, but might be 0
- if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
-
- return 1;
-}
-
-static int process_frame_header(jpeg *z, int scan)
-{
- stbi *s = z->s;
- int Lf,p,i,q, h_max=1,v_max=1,c;
- Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
- p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
- s->img_y = get16(s); if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
- s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
- c = get8(s);
- if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires
- 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 e("bad SOF len","Corrupt JPEG");
-
- for (i=0; i < s->img_n; ++i) {
- z->img_comp[i].id = get8(s);
- if (z->img_comp[i].id != i+1) // JFIF requires
- if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
- return e("bad component ID","Corrupt JPEG");
- q = get8(s);
- z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");
- z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");
- z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
- }
-
- if (scan != SCAN_load) return 1;
-
- if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("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;
- }
-
- // 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;
- 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
- 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].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
- if (z->img_comp[i].raw_data == NULL) {
- for(--i; i >= 0; --i) {
- free(z->img_comp[i].raw_data);
- z->img_comp[i].data = NULL;
- }
- return e("outofmem", "Out of memory");
- }
- // align blocks for installable-idct using mmx/sse
- z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
- z->img_comp[i].linebuf = NULL;
- }
-
- return 1;
-}
-
-// use comparisons since in some cases we handle more than one case (e.g. SOF)
-#define DNL(x) ((x) == 0xdc)
-#define SOI(x) ((x) == 0xd8)
-#define EOI(x) ((x) == 0xd9)
-#define SOF(x) ((x) == 0xc0 || (x) == 0xc1)
-#define SOS(x) ((x) == 0xda)
-
-static int decode_jpeg_header(jpeg *z, int scan)
-{
- int m;
- z->marker = MARKER_none; // initialize cached marker to empty
- m = get_marker(z);
- if (!SOI(m)) return e("no SOI","Corrupt JPEG");
- if (scan == SCAN_type) return 1;
- m = get_marker(z);
- while (!SOF(m)) {
- if (!process_marker(z,m)) return 0;
- m = get_marker(z);
- while (m == MARKER_none) {
- // some files have extra padding after their blocks, so ok, we'll scan
- if (at_eof(z->s)) return e("no SOF", "Corrupt JPEG");
- m = get_marker(z);
- }
- }
- if (!process_frame_header(z, scan)) return 0;
- return 1;
-}
-
-static int decode_jpeg_image(jpeg *j)
-{
- int m;
- j->restart_interval = 0;
- if (!decode_jpeg_header(j, SCAN_load)) return 0;
- m = get_marker(j);
- while (!EOI(m)) {
- if (SOS(m)) {
- if (!process_scan_header(j)) return 0;
- if (!parse_entropy_coded_data(j)) return 0;
- if (j->marker == MARKER_none ) {
- // handle 0s at the end of image data from IP Kamera 9060
- while (!at_eof(j->s)) {
- int x = get8(j->s);
- if (x == 255) {
- j->marker = get8u(j->s);
- break;
- } else if (x != 0) {
- return 0;
- }
- }
- // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0
- }
- } else {
- if (!process_marker(j, m)) return 0;
- }
- m = get_marker(j);
- }
- return 1;
-}
-
-// static jfif-centered resampling (across block boundaries)
-
-typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
- int w, int hs);
-
-#define div4(x) ((uint8) ((x) >> 2))
-
-static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
-{
- STBI_NOTUSED(out);
- STBI_NOTUSED(in_far);
- STBI_NOTUSED(w);
- STBI_NOTUSED(hs);
- return in_near;
-}
-
-static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *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] = div4(3*in_near[i] + in_far[i] + 2);
- return out;
-}
-
-static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
-{
- // need to generate two samples horizontally for every one in input
- int i;
- uint8 *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] = div4(input[0]*3 + input[1] + 2);
- for (i=1; i < w-1; ++i) {
- int n = 3*input[i]+2;
- out[i*2+0] = div4(n+input[i-1]);
- out[i*2+1] = div4(n+input[i+1]);
- }
- out[i*2+0] = 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 div16(x) ((uint8) ((x) >> 4))
-
-static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *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] = div4(3*in_near[0] + in_far[0] + 2);
- return out;
- }
-
- t1 = 3*in_near[0] + in_far[0];
- out[0] = div4(t1+2);
- for (i=1; i < w; ++i) {
- t0 = t1;
- t1 = 3*in_near[i]+in_far[i];
- out[i*2-1] = div16(3*t0 + t1 + 8);
- out[i*2 ] = div16(3*t1 + t0 + 8);
- }
- out[w*2-1] = div4(t1+2);
-
- STBI_NOTUSED(hs);
-
- return out;
-}
-
-static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *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;
-}
-
-#define float2fixed(x) ((int) ((x) * 65536 + 0.5))
-
-// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
-// VC6 without processor=Pro is generating multiple LEAs per multiply!
-static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
-{
- int i;
- for (i=0; i < count; ++i) {
- int y_fixed = (y[i] << 16) + 32768; // rounding
- int r,g,b;
- int cr = pcr[i] - 128;
- int cb = pcb[i] - 128;
- r = y_fixed + cr*float2fixed(1.40200f);
- g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
- b = y_fixed + cb*float2fixed(1.77200f);
- r >>= 16;
- g >>= 16;
- b >>= 16;
- 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] = (uint8)r;
- out[1] = (uint8)g;
- out[2] = (uint8)b;
- out[3] = 255;
- out += step;
- }
-}
-
-#ifdef STBI_SIMD
-static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
-
-void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
-{
- stbi_YCbCr_installed = func;
-}
-#endif
-
-
-// clean up the temporary component buffers
-static void cleanup_jpeg(jpeg *j)
-{
- int i;
- for (i=0; i < j->s->img_n; ++i) {
- if (j->img_comp[i].data) {
- free(j->img_comp[i].raw_data);
- j->img_comp[i].data = NULL;
- }
- if (j->img_comp[i].linebuf) {
- free(j->img_comp[i].linebuf);
- j->img_comp[i].linebuf = NULL;
- }
- }
-}
-
-typedef struct
-{
- resample_row_func resample;
- uint8 *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;
-
-static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
-{
- int n, decode_n;
- // validate req_comp
- if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
- z->s->img_n = 0;
-
- // load a jpeg image from whichever source
- if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
-
- // determine actual number of components to generate
- n = req_comp ? req_comp : z->s->img_n;
-
- if (z->s->img_n == 3 && n < 3)
- decode_n = 1;
- else
- decode_n = z->s->img_n;
-
- // resample and color-convert
- {
- int k;
- uint i,j;
- uint8 *output;
- uint8 *coutput[4];
-
- 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 = (uint8 *) malloc(z->s->img_x + 3);
- if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("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 = resample_row_v_2;
- else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
- else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
- else r->resample = resample_row_generic;
- }
-
- // can't error after this so, this is safe
- output = (uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);
- if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
-
- // now go ahead and resample
- for (j=0; j < z->s->img_y; ++j) {
- uint8 *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) {
- uint8 *y = coutput[0];
- if (z->s->img_n == 3) {
- #ifdef STBI_SIMD
- stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
- #else
- YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
- #endif
- } 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 {
- uint8 *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;
- }
- }
- cleanup_jpeg(z);
- *out_x = z->s->img_x;
- *out_y = z->s->img_y;
- if (comp) *comp = z->s->img_n; // report original components, not output
- return output;
- }
-}
-
-static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- jpeg j;
- j.s = s;
- return load_jpeg_image(&j, x,y,comp,req_comp);
-}
-
-static int stbi_jpeg_test(stbi *s)
-{
- int r;
- jpeg j;
- j.s = s;
- r = decode_jpeg_header(&j, SCAN_type);
- stbi_rewind(s);
- return r;
-}
-
-static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)
-{
- if (!decode_jpeg_header(j, 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;
- return 1;
-}
-
-static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)
-{
- jpeg j;
- j.s = s;
- return stbi_jpeg_info_raw(&j, x, y, comp);
-}
-
-// 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
-
-// fast-way is faster to check than jpeg huffman, but slow way is slower
-#define ZFAST_BITS 9 // accelerate all cases in default tables
-#define ZFAST_MASK ((1 << ZFAST_BITS) - 1)
-
-// zlib-style huffman encoding
-// (jpegs packs from left, zlib from right, so can't share code)
-typedef struct
-{
- uint16 fast[1 << ZFAST_BITS];
- uint16 firstcode[16];
- int maxcode[17];
- uint16 firstsymbol[16];
- uint8 size[288];
- uint16 value[288];
-} zhuffman;
-
-stbi_inline static int 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 bit_reverse(int v, int bits)
-{
- assert(bits <= 16);
- // to bit reverse n bits, reverse 16 and shift
- // e.g. 11 bits, bit reverse and shift away 5
- return bitreverse16(v) >> (16-bits);
-}
-
-static int zbuild_huffman(zhuffman *z, uint8 *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, 255, sizeof(z->fast));
- for (i=0; i < num; ++i)
- ++sizes[sizelist[i]];
- sizes[0] = 0;
- for (i=1; i < 16; ++i)
- assert(sizes[i] <= (1 << i));
- code = 0;
- for (i=1; i < 16; ++i) {
- next_code[i] = code;
- z->firstcode[i] = (uint16) code;
- z->firstsymbol[i] = (uint16) k;
- code = (code + sizes[i]);
- if (sizes[i])
- if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
- 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];
- z->size[c] = (uint8)s;
- z->value[c] = (uint16)i;
- if (s <= ZFAST_BITS) {
- int k = bit_reverse(next_code[s],s);
- while (k < (1 << ZFAST_BITS)) {
- z->fast[k] = (uint16) c;
- k += (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
-{
- uint8 *zbuffer, *zbuffer_end;
- int num_bits;
- uint32 code_buffer;
-
- char *zout;
- char *zout_start;
- char *zout_end;
- int z_expandable;
-
- zhuffman z_length, z_distance;
-} zbuf;
-
-stbi_inline static int zget8(zbuf *z)
-{
- if (z->zbuffer >= z->zbuffer_end) return 0;
- return *z->zbuffer++;
-}
-
-static void fill_bits(zbuf *z)
-{
- do {
- assert(z->code_buffer < (1U << z->num_bits));
- z->code_buffer |= zget8(z) << z->num_bits;
- z->num_bits += 8;
- } while (z->num_bits <= 24);
-}
-
-stbi_inline static unsigned int zreceive(zbuf *z, int n)
-{
- unsigned int k;
- if (z->num_bits < n) fill_bits(z);
- k = z->code_buffer & ((1 << n) - 1);
- z->code_buffer >>= n;
- z->num_bits -= n;
- return k;
-}
-
-stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)
-{
- int b,s,k;
- if (a->num_bits < 16) fill_bits(a);
- b = z->fast[a->code_buffer & ZFAST_MASK];
- if (b < 0xffff) {
- s = z->size[b];
- a->code_buffer >>= s;
- a->num_bits -= s;
- return z->value[b];
- }
-
- // not resolved by fast table, so compute it the slow way
- // use jpeg approach, which requires MSbits at top
- k = bit_reverse(a->code_buffer, 16);
- for (s=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];
- assert(z->size[b] == s);
- a->code_buffer >>= s;
- a->num_bits -= s;
- return z->value[b];
-}
-
-static int expand(zbuf *z, int n) // need to make room for n bytes
-{
- char *q;
- int cur, limit;
- if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");
- cur = (int) (z->zout - z->zout_start);
- limit = (int) (z->zout_end - z->zout_start);
- while (cur + n > limit)
- limit *= 2;
- q = (char *) realloc(z->zout_start, limit);
- if (q == NULL) return e("outofmem", "Out of memory");
- z->zout_start = q;
- z->zout = q + cur;
- z->zout_end = q + limit;
- return 1;
-}
-
-static int length_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 int length_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 int dist_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 int dist_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 parse_huffman_block(zbuf *a)
-{
- for(;;) {
- int z = zhuffman_decode(a, &a->z_length);
- if (z < 256) {
- if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
- if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
- *a->zout++ = (char) z;
- } else {
- uint8 *p;
- int len,dist;
- if (z == 256) return 1;
- z -= 257;
- len = length_base[z];
- if (length_extra[z]) len += zreceive(a, length_extra[z]);
- z = zhuffman_decode(a, &a->z_distance);
- if (z < 0) return e("bad huffman code","Corrupt PNG");
- dist = dist_base[z];
- if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
- if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");
- if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
- p = (uint8 *) (a->zout - dist);
- while (len--)
- *a->zout++ = *p++;
- }
- }
-}
-
-static int compute_huffman_codes(zbuf *a)
-{
- static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
- zhuffman z_codelength;
- uint8 lencodes[286+32+137];//padding for maximum single op
- uint8 codelength_sizes[19];
- int i,n;
-
- int hlit = zreceive(a,5) + 257;
- int hdist = zreceive(a,5) + 1;
- int hclen = zreceive(a,4) + 4;
-
- memset(codelength_sizes, 0, sizeof(codelength_sizes));
- for (i=0; i < hclen; ++i) {
- int s = zreceive(a,3);
- codelength_sizes[length_dezigzag[i]] = (uint8) s;
- }
- if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
-
- n = 0;
- while (n < hlit + hdist) {
- int c = zhuffman_decode(a, &z_codelength);
- assert(c >= 0 && c < 19);
- if (c < 16)
- lencodes[n++] = (uint8) c;
- else if (c == 16) {
- c = zreceive(a,2)+3;
- memset(lencodes+n, lencodes[n-1], c);
- n += c;
- } else if (c == 17) {
- c = zreceive(a,3)+3;
- memset(lencodes+n, 0, c);
- n += c;
- } else {
- assert(c == 18);
- c = zreceive(a,7)+11;
- memset(lencodes+n, 0, c);
- n += c;
- }
- }
- if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
- if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
- if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
- return 1;
-}
-
-static int parse_uncompressed_block(zbuf *a)
-{
- uint8 header[4];
- int len,nlen,k;
- if (a->num_bits & 7)
- zreceive(a, a->num_bits & 7); // discard
- // drain the bit-packed data into header
- k = 0;
- while (a->num_bits > 0) {
- header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
- a->code_buffer >>= 8;
- a->num_bits -= 8;
- }
- assert(a->num_bits == 0);
- // now fill header the normal way
- while (k < 4)
- header[k++] = (uint8) zget8(a);
- len = header[1] * 256 + header[0];
- nlen = header[3] * 256 + header[2];
- if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
- if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");
- if (a->zout + len > a->zout_end)
- if (!expand(a, len)) return 0;
- memcpy(a->zout, a->zbuffer, len);
- a->zbuffer += len;
- a->zout += len;
- return 1;
-}
-
-static int parse_zlib_header(zbuf *a)
-{
- int cmf = zget8(a);
- int cm = cmf & 15;
- /* int cinfo = cmf >> 4; */
- int flg = zget8(a);
- if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
- if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
- if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
- // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
- return 1;
-}
-
-// @TODO: should statically initialize these for optimal thread safety
-static uint8 default_length[288], default_distance[32];
-static void init_defaults(void)
-{
- int i; // use <= to match clearly with spec
- for (i=0; i <= 143; ++i) default_length[i] = 8;
- for ( ; i <= 255; ++i) default_length[i] = 9;
- for ( ; i <= 279; ++i) default_length[i] = 7;
- for ( ; i <= 287; ++i) default_length[i] = 8;
-
- for (i=0; i <= 31; ++i) default_distance[i] = 5;
-}
-
-int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
-static int parse_zlib(zbuf *a, int parse_header)
-{
- int final_, type;
- if (parse_header)
- if (!parse_zlib_header(a)) return 0;
- a->num_bits = 0;
- a->code_buffer = 0;
- do {
- final_ = zreceive(a,1);
- type = zreceive(a,2);
- if (type == 0) {
- if (!parse_uncompressed_block(a)) return 0;
- } else if (type == 3) {
- return 0;
- } else {
- if (type == 1) {
- // use fixed code lengths
- if (!default_distance[31]) init_defaults();
- if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;
- if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;
- } else {
- if (!compute_huffman_codes(a)) return 0;
- }
- if (!parse_huffman_block(a)) return 0;
- }
- if (stbi_png_partial && a->zout - a->zout_start > 65536)
- break;
- } while (!final_);
- return 1;
-}
-
-static int do_zlib(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 parse_zlib(a, parse_header);
-}
-
-char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
-{
- zbuf a;
- char *p = (char *) malloc(initial_size);
- if (p == NULL) return NULL;
- a.zbuffer = (uint8 *) buffer;
- a.zbuffer_end = (uint8 *) buffer + len;
- if (do_zlib(&a, p, initial_size, 1, 1)) {
- if (outlen) *outlen = (int) (a.zout - a.zout_start);
- return a.zout_start;
- } else {
- free(a.zout_start);
- return NULL;
- }
-}
-
-char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
-{
- return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
-}
-
-char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
-{
- zbuf a;
- char *p = (char *) malloc(initial_size);
- if (p == NULL) return NULL;
- a.zbuffer = (uint8 *) buffer;
- a.zbuffer_end = (uint8 *) buffer + len;
- if (do_zlib(&a, p, initial_size, 1, parse_header)) {
- if (outlen) *outlen = (int) (a.zout - a.zout_start);
- return a.zout_start;
- } else {
- free(a.zout_start);
- return NULL;
- }
-}
-
-int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
-{
- zbuf a;
- a.zbuffer = (uint8 *) ibuffer;
- a.zbuffer_end = (uint8 *) ibuffer + ilen;
- if (do_zlib(&a, obuffer, olen, 0, 1))
- return (int) (a.zout - a.zout_start);
- else
- return -1;
-}
-
-char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
-{
- zbuf a;
- char *p = (char *) malloc(16384);
- if (p == NULL) return NULL;
- a.zbuffer = (uint8 *) buffer;
- a.zbuffer_end = (uint8 *) buffer+len;
- if (do_zlib(&a, p, 16384, 1, 0)) {
- if (outlen) *outlen = (int) (a.zout - a.zout_start);
- return a.zout_start;
- } else {
- free(a.zout_start);
- return NULL;
- }
-}
-
-int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
-{
- zbuf a;
- a.zbuffer = (uint8 *) ibuffer;
- a.zbuffer_end = (uint8 *) ibuffer + ilen;
- if (do_zlib(&a, obuffer, olen, 0, 0))
- return (int) (a.zout - a.zout_start);
- else
- return -1;
-}
-
-// 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
-
-
-typedef struct
-{
- uint32 length;
- uint32 type;
-} chunk;
-
-#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
-
-static chunk get_chunk_header(stbi *s)
-{
- chunk c;
- c.length = get32(s);
- c.type = get32(s);
- return c;
-}
-
-static int check_png_header(stbi *s)
-{
- static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
- int i;
- for (i=0; i < 8; ++i)
- if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG");
- return 1;
-}
-
-typedef struct
-{
- stbi *s;
- uint8 *idata, *expanded, *out;
-} png;
-
-
-enum {
- F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
- F_avg_first, F_paeth_first
-};
-
-static uint8 first_row_filter[5] =
-{
- F_none, F_sub, F_none, F_avg_first, F_paeth_first
-};
-
-static int paeth(int a, int b, int c)
-{
- int p = a + b - c;
- int pa = abs(p-a);
- int pb = abs(p-b);
- int pc = abs(p-c);
- if (pa <= pb && pa <= pc) return a;
- if (pb <= pc) return b;
- return c;
-}
-
-// create the png data from post-deflated data
-static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
-{
- stbi *s = a->s;
- uint32 i,j,stride = x*out_n;
- int k;
- int img_n = s->img_n; // copy it into a local for later
- assert(out_n == s->img_n || out_n == s->img_n+1);
- if (stbi_png_partial) y = 1;
- a->out = (uint8 *) malloc(x * y * out_n);
- if (!a->out) return e("outofmem", "Out of memory");
- if (!stbi_png_partial) {
- if (s->img_x == x && s->img_y == y) {
- if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
- } else { // interlaced:
- if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
- }
- }
- for (j=0; j < y; ++j) {
- uint8 *cur = a->out + stride*j;
- uint8 *prior = cur - stride;
- int filter = *raw++;
- if (filter > 4) return e("invalid filter","Corrupt PNG");
- // if first row, use special filter that doesn't sample previous row
- if (j == 0) filter = first_row_filter[filter];
- // handle first pixel explicitly
- for (k=0; k < img_n; ++k) {
- switch (filter) {
- case F_none : cur[k] = raw[k]; break;
- case F_sub : cur[k] = raw[k]; break;
- case F_up : cur[k] = raw[k] + prior[k]; break;
- case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
- case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
- case F_avg_first : cur[k] = raw[k]; break;
- case F_paeth_first: cur[k] = raw[k]; break;
- }
- }
- if (img_n != out_n) cur[img_n] = 255;
- raw += img_n;
- cur += out_n;
- prior += out_n;
- // this is a little gross, so that we don't switch per-pixel or per-component
- if (img_n == out_n) {
- #define CASE(f) \
- case f: \
- for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
- for (k=0; k < img_n; ++k)
- switch (filter) {
- CASE(F_none) cur[k] = raw[k]; break;
- CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
- CASE(F_up) cur[k] = raw[k] + prior[k]; break;
- CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
- CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
- CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
- CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
- }
- #undef CASE
- } else {
- assert(img_n+1 == out_n);
- #define CASE(f) \
- case f: \
- for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
- for (k=0; k < img_n; ++k)
- switch (filter) {
- CASE(F_none) cur[k] = raw[k]; break;
- CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
- CASE(F_up) cur[k] = raw[k] + prior[k]; break;
- CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
- CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
- CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
- CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
- }
- #undef CASE
- }
- }
- return 1;
-}
-
-static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
-{
- uint8 *final_;
- int p;
- int save;
- if (!interlaced)
- return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);
- save = stbi_png_partial;
- stbi_png_partial = 0;
-
- // de-interlacing
- final_ = (uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);
- 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) {
- if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
- free(final_);
- return 0;
- }
- for (j=0; j < y; ++j)
- for (i=0; i < x; ++i)
- memcpy(final_ + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
- a->out + (j*x+i)*out_n, out_n);
- free(a->out);
- raw += (x*out_n+1)*y;
- raw_len -= (x*out_n+1)*y;
- }
- }
- a->out = final_;
-
- stbi_png_partial = save;
- return 1;
-}
-
-static int compute_transparency(png *z, uint8 tc[3], int out_n)
-{
- stbi *s = z->s;
- uint32 i, pixel_count = s->img_x * s->img_y;
- uint8 *p = z->out;
-
- // compute color-based transparency, assuming we've
- // already got 255 as the alpha value in the output
- 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 expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
-{
- uint32 i, pixel_count = a->s->img_x * a->s->img_y;
- uint8 *p, *temp_out, *orig = a->out;
-
- p = (uint8 *) malloc(pixel_count * pal_img_n);
- if (p == NULL) return e("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;
- }
- }
- free(a->out);
- a->out = temp_out;
-
- STBI_NOTUSED(len);
-
- return 1;
-}
-
-static int stbi_unpremultiply_on_load = 0;
-static int stbi_de_iphone_flag = 0;
-
-void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
-{
- stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;
-}
-void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
-{
- stbi_de_iphone_flag = flag_true_if_should_convert;
-}
-
-static void stbi_de_iphone(png *z)
-{
- stbi *s = z->s;
- uint32 i, pixel_count = s->img_x * s->img_y;
- uint8 *p = z->out;
-
- if (s->img_out_n == 3) { // convert bgr to rgb
- for (i=0; i < pixel_count; ++i) {
- uint8 t = p[0];
- p[0] = p[2];
- p[2] = t;
- p += 3;
- }
- } else {
- assert(s->img_out_n == 4);
- if (stbi_unpremultiply_on_load) {
- // convert bgr to rgb and unpremultiply
- for (i=0; i < pixel_count; ++i) {
- uint8 a = p[3];
- uint8 t = p[0];
- if (a) {
- p[0] = p[2] * 255 / a;
- p[1] = p[1] * 255 / a;
- p[2] = t * 255 / a;
- } else {
- p[0] = p[2];
- p[2] = t;
- }
- p += 4;
- }
- } else {
- // convert bgr to rgb
- for (i=0; i < pixel_count; ++i) {
- uint8 t = p[0];
- p[0] = p[2];
- p[2] = t;
- p += 4;
- }
- }
- }
-}
-
-static int parse_png_file(png *z, int scan, int req_comp)
-{
- uint8 palette[1024], pal_img_n=0;
- uint8 has_trans=0, tc[3];
- uint32 ioff=0, idata_limit=0, i, pal_len=0;
- int first=1,k,interlace=0, iphone=0;
- stbi *s = z->s;
-
- z->expanded = NULL;
- z->idata = NULL;
- z->out = NULL;
-
- if (!check_png_header(s)) return 0;
-
- if (scan == SCAN_type) return 1;
-
- for (;;) {
- chunk c = get_chunk_header(s);
- switch (c.type) {
- case PNG_TYPE('C','g','B','I'):
- iphone = stbi_de_iphone_flag;
- skip(s, c.length);
- break;
- case PNG_TYPE('I','H','D','R'): {
- int depth,color,comp,filter;
- if (!first) return e("multiple IHDR","Corrupt PNG");
- first = 0;
- if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
- s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
- s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
- depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");
- color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");
- if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
- comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");
- filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");
- interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");
- if (!s->img_x || !s->img_y) return e("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 e("too large", "Image too large to decode");
- if (scan == SCAN_header) return 1;
- } 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 e("too large","Corrupt PNG");
- // if SCAN_header, have to scan to see if we have a tRNS
- }
- break;
- }
-
- case PNG_TYPE('P','L','T','E'): {
- if (first) return e("first not IHDR", "Corrupt PNG");
- if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
- pal_len = c.length / 3;
- if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
- for (i=0; i < pal_len; ++i) {
- palette[i*4+0] = get8u(s);
- palette[i*4+1] = get8u(s);
- palette[i*4+2] = get8u(s);
- palette[i*4+3] = 255;
- }
- break;
- }
-
- case PNG_TYPE('t','R','N','S'): {
- if (first) return e("first not IHDR", "Corrupt PNG");
- if (z->idata) return e("tRNS after IDAT","Corrupt PNG");
- if (pal_img_n) {
- if (scan == SCAN_header) { s->img_n = 4; return 1; }
- if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
- if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
- pal_img_n = 4;
- for (i=0; i < c.length; ++i)
- palette[i*4+3] = get8u(s);
- } else {
- if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
- if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");
- has_trans = 1;
- for (k=0; k < s->img_n; ++k)
- tc[k] = (uint8) get16(s); // non 8-bit images will be larger
- }
- break;
- }
-
- case PNG_TYPE('I','D','A','T'): {
- if (first) return e("first not IHDR", "Corrupt PNG");
- if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
- if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
- if (ioff + c.length > idata_limit) {
- uint8 *p;
- if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
- while (ioff + c.length > idata_limit)
- idata_limit *= 2;
- p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
- z->idata = p;
- }
- if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");
- ioff += c.length;
- break;
- }
-
- case PNG_TYPE('I','E','N','D'): {
- uint32 raw_len;
- if (first) return e("first not IHDR", "Corrupt PNG");
- if (scan != SCAN_load) return 1;
- if (z->idata == NULL) return e("no IDAT","Corrupt PNG");
- z->expanded = (uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);
- if (z->expanded == NULL) return 0; // zlib should set error
- 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 (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
- if (has_trans)
- if (!compute_transparency(z, tc, s->img_out_n)) return 0;
- if (iphone && 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 (!expand_palette(z, palette, pal_len, s->img_out_n))
- return 0;
- }
- free(z->expanded); z->expanded = NULL;
- return 1;
- }
-
- default:
- // if critical, fail
- if (first) return e("first not IHDR", "Corrupt PNG");
- if ((c.type & (1 << 29)) == 0) {
- #ifndef STBI_NO_FAILURE_STRINGS
- // not threadsafe
- static char invalid_chunk[] = "XXXX chunk not known";
- invalid_chunk[0] = (uint8) (c.type >> 24);
- invalid_chunk[1] = (uint8) (c.type >> 16);
- invalid_chunk[2] = (uint8) (c.type >> 8);
- invalid_chunk[3] = (uint8) (c.type >> 0);
- #endif
- return e(invalid_chunk, "PNG not supported: unknown chunk type");
- }
- skip(s, c.length);
- break;
- }
- // end of chunk, read and skip CRC
- get32(s);
- }
-}
-
-static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
-{
- unsigned char *result=NULL;
- if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
- if (parse_png_file(p, SCAN_load, req_comp)) {
- result = p->out;
- p->out = NULL;
- if (req_comp && req_comp != p->s->img_out_n) {
- result = convert_format(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;
- }
- free(p->out); p->out = NULL;
- free(p->expanded); p->expanded = NULL;
- free(p->idata); p->idata = NULL;
-
- return result;
-}
-
-static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- png p;
- p.s = s;
- return do_png(&p, x,y,comp,req_comp);
-}
-
-static int stbi_png_test(stbi *s)
-{
- int r;
- r = check_png_header(s);
- stbi_rewind(s);
- return r;
-}
-
-static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)
-{
- if (!parse_png_file(p, 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 *s, int *x, int *y, int *comp)
-{
- png p;
- p.s = s;
- return stbi_png_info_raw(&p, x, y, comp);
-}
-
-// Microsoft/Windows BMP image
-
-static int bmp_test(stbi *s)
-{
- int sz;
- if (get8(s) != 'B') return 0;
- if (get8(s) != 'M') return 0;
- get32le(s); // discard filesize
- get16le(s); // discard reserved
- get16le(s); // discard reserved
- get32le(s); // discard data offset
- sz = get32le(s);
- if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
- return 0;
-}
-
-static int stbi_bmp_test(stbi *s)
-{
- int r = bmp_test(s);
- stbi_rewind(s);
- return r;
-}
-
-
-// returns 0..31 for the highest set bit
-static int 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, z >>= 1;
- return n;
-}
-
-static int 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;
-}
-
-static int shiftsigned(int v, int shift, int bits)
-{
- int result;
- int z=0;
-
- if (shift < 0) v <<= -shift;
- else v >>= shift;
- result = v;
-
- z = bits;
- while (z < 8) {
- result += v >> z;
- z += bits;
- }
- return result;
-}
-
-static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- uint8 *out;
- unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
- stbi_uc pal[256][4];
- int psize=0,i,j,compress=0,width;
- int bpp, flip_vertically, pad, target, offset, hsz;
- if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");
- get32le(s); // discard filesize
- get16le(s); // discard reserved
- get16le(s); // discard reserved
- offset = get32le(s);
- hsz = get32le(s);
- if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
- if (hsz == 12) {
- s->img_x = get16le(s);
- s->img_y = get16le(s);
- } else {
- s->img_x = get32le(s);
- s->img_y = get32le(s);
- }
- if (get16le(s) != 1) return epuc("bad BMP", "bad BMP");
- bpp = get16le(s);
- if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
- flip_vertically = ((int) s->img_y) > 0;
- s->img_y = abs((int) s->img_y);
- if (hsz == 12) {
- if (bpp < 24)
- psize = (offset - 14 - 24) / 3;
- } else {
- compress = get32le(s);
- if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
- get32le(s); // discard sizeof
- get32le(s); // discard hres
- get32le(s); // discard vres
- get32le(s); // discard colorsused
- get32le(s); // discard max important
- if (hsz == 40 || hsz == 56) {
- if (hsz == 56) {
- get32le(s);
- get32le(s);
- get32le(s);
- get32le(s);
- }
- if (bpp == 16 || bpp == 32) {
- mr = mg = mb = 0;
- if (compress == 0) {
- if (bpp == 32) {
- mr = 0xffu << 16;
- mg = 0xffu << 8;
- mb = 0xffu << 0;
- ma = 0xffu << 24;
- fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
- } else {
- mr = 31u << 10;
- mg = 31u << 5;
- mb = 31u << 0;
- }
- } else if (compress == 3) {
- mr = get32le(s);
- mg = get32le(s);
- mb = get32le(s);
- // not documented, but generated by photoshop and handled by mspaint
- if (mr == mg && mg == mb) {
- // ?!?!?
- return epuc("bad BMP", "bad BMP");
- }
- } else
- return epuc("bad BMP", "bad BMP");
- }
- } else {
- assert(hsz == 108);
- mr = get32le(s);
- mg = get32le(s);
- mb = get32le(s);
- ma = get32le(s);
- get32le(s); // discard color space
- for (i=0; i < 12; ++i)
- get32le(s); // discard color space parameters
- }
- if (bpp < 16)
- psize = (offset - 14 - hsz) >> 2;
- }
- 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
- out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
- if (!out) return epuc("outofmem", "Out of memory");
- if (bpp < 16) {
- int z=0;
- if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }
- for (i=0; i < psize; ++i) {
- pal[i][2] = get8u(s);
- pal[i][1] = get8u(s);
- pal[i][0] = get8u(s);
- if (hsz != 12) get8(s);
- pal[i][3] = 255;
- }
- skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
- if (bpp == 4) width = (s->img_x + 1) >> 1;
- else if (bpp == 8) width = s->img_x;
- else { free(out); return epuc("bad bpp", "Corrupt BMP"); }
- pad = (-width)&3;
- for (j=0; j < (int) s->img_y; ++j) {
- for (i=0; i < (int) s->img_x; i += 2) {
- int v=get8(s),v2=0;
- if (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 = (bpp == 8) ? get8(s) : v2;
- out[z++] = pal[v][0];
- out[z++] = pal[v][1];
- out[z++] = pal[v][2];
- if (target == 4) out[z++] = 255;
- }
- 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;
- skip(s, offset - 14 - hsz);
- if (bpp == 24) width = 3 * s->img_x;
- else if (bpp == 16) width = 2*s->img_x;
- else /* bpp = 32 and pad = 0 */ width=0;
- pad = (-width) & 3;
- if (bpp == 24) {
- easy = 1;
- } else if (bpp == 32) {
- if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
- easy = 2;
- }
- if (!easy) {
- if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); }
- // right shift amt to put high bit in position #7
- rshift = high_bit(mr)-7; rcount = bitcount(mr);
- gshift = high_bit(mg)-7; gcount = bitcount(mr);
- bshift = high_bit(mb)-7; bcount = bitcount(mr);
- ashift = high_bit(ma)-7; acount = bitcount(mr);
- }
- for (j=0; j < (int) s->img_y; ++j) {
- if (easy) {
- for (i=0; i < (int) s->img_x; ++i) {
- int a;
- out[z+2] = get8u(s);
- out[z+1] = get8u(s);
- out[z+0] = get8u(s);
- z += 3;
- a = (easy == 2 ? get8(s) : 255);
- if (target == 4) out[z++] = (uint8) a;
- }
- } else {
- for (i=0; i < (int) s->img_x; ++i) {
- uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
- int a;
- out[z++] = (uint8) shiftsigned(v & mr, rshift, rcount);
- out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount);
- out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount);
- a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
- if (target == 4) out[z++] = (uint8) a;
- }
- }
- skip(s, pad);
- }
- }
- 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 = convert_format(out, target, req_comp, s->img_x, s->img_y);
- if (out == NULL) return out; // convert_format frees input on failure
- }
-
- *x = s->img_x;
- *y = s->img_y;
- if (comp) *comp = s->img_n;
- return out;
-
- NVG_NOTUSED(fake_a);
-}
-
-static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)
-{
- return bmp_load(s, x,y,comp,req_comp);
-}
-
-
-// Targa Truevision - TGA
-// by Jonathan Dummer
-
-static int tga_info(stbi *s, int *x, int *y, int *comp)
-{
- int tga_w, tga_h, tga_comp;
- int sz;
- get8u(s); // discard Offset
- sz = get8u(s); // color type
- if( sz > 1 ) {
- stbi_rewind(s);
- return 0; // only RGB or indexed allowed
- }
- sz = get8u(s); // image type
- // only RGB or grey allowed, +/- RLE
- if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
- skip(s,9);
- tga_w = get16le(s);
- if( tga_w < 1 ) {
- stbi_rewind(s);
- return 0; // test width
- }
- tga_h = get16le(s);
- if( tga_h < 1 ) {
- stbi_rewind(s);
- return 0; // test height
- }
- sz = get8(s); // bits per pixel
- // only RGB or RGBA or grey allowed
- if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
- stbi_rewind(s);
- return 0;
- }
- tga_comp = sz;
- if (x) *x = tga_w;
- if (y) *y = tga_h;
- if (comp) *comp = tga_comp / 8;
- return 1; // seems to have passed everything
-}
-
-int stbi_tga_info(stbi *s, int *x, int *y, int *comp)
-{
- return tga_info(s, x, y, comp);
-}
-
-static int tga_test(stbi *s)
-{
- int sz;
- get8u(s); // discard Offset
- sz = get8u(s); // color type
- if ( sz > 1 ) return 0; // only RGB or indexed allowed
- sz = get8u(s); // image type
- if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
- get16(s); // discard palette start
- get16(s); // discard palette length
- get8(s); // discard bits per palette color entry
- get16(s); // discard x origin
- get16(s); // discard y origin
- if ( get16(s) < 1 ) return 0; // test width
- if ( get16(s) < 1 ) return 0; // test height
- sz = get8(s); // bits per pixel
- if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed
- return 1; // seems to have passed everything
-}
-
-static int stbi_tga_test(stbi *s)
-{
- int res = tga_test(s);
- stbi_rewind(s);
- return res;
-}
-
-static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- // read in the TGA header stuff
- int tga_offset = get8u(s);
- int tga_indexed = get8u(s);
- int tga_image_type = get8u(s);
- int tga_is_RLE = 0;
- int tga_palette_start = get16le(s);
- int tga_palette_len = get16le(s);
- int tga_palette_bits = get8u(s);
- int tga_x_origin = get16le(s);
- int tga_y_origin = get16le(s);
- int tga_width = get16le(s);
- int tga_height = get16le(s);
- int tga_bits_per_pixel = get8u(s);
- int tga_inverted = get8u(s);
- // image data
- unsigned char *tga_data;
- unsigned char *tga_palette = NULL;
- int i, j;
- unsigned char raw_data[4];
- unsigned char trans_data[4];
- int RLE_count = 0;
- int RLE_repeating = 0;
- int read_next_pixel = 1;
-
- // do a tiny bit of precessing
- if ( tga_image_type >= 8 )
- {
- tga_image_type -= 8;
- tga_is_RLE = 1;
- }
- /* int tga_alpha_bits = tga_inverted & 15; */
- tga_inverted = 1 - ((tga_inverted >> 5) & 1);
-
- // error check
- if ( //(tga_indexed) ||
- (tga_width < 1) || (tga_height < 1) ||
- (tga_image_type < 1) || (tga_image_type > 3) ||
- ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
- (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
- )
- {
- return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
- }
-
- // If I'm paletted, then I'll use the number of bits from the palette
- if ( tga_indexed )
- {
- tga_bits_per_pixel = tga_palette_bits;
- }
-
- // tga info
- *x = tga_width;
- *y = tga_height;
- if ( (req_comp < 1) || (req_comp > 4) )
- {
- // just use whatever the file was
- req_comp = tga_bits_per_pixel / 8;
- *comp = req_comp;
- } else
- {
- // force a new number of components
- *comp = tga_bits_per_pixel/8;
- }
- tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
- if (!tga_data) return epuc("outofmem", "Out of memory");
-
- // skip to the data's starting position (offset usually = 0)
- skip(s, tga_offset );
- // do I need to load a palette?
- if ( tga_indexed )
- {
- // any data to skip? (offset usually = 0)
- skip(s, tga_palette_start );
- // load the palette
- tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
- if (!tga_palette) return epuc("outofmem", "Out of memory");
- if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
- free(tga_data);
- free(tga_palette);
- return epuc("bad palette", "Corrupt TGA");
- }
- }
- // load the data
- trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0;
- for (i=0; i < tga_width * tga_height; ++i)
- {
- // if I'm in RLE mode, do I need to get a RLE chunk?
- if ( tga_is_RLE )
- {
- if ( RLE_count == 0 )
- {
- // yep, get the next byte as a RLE command
- int RLE_cmd = get8u(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 1 byte, then perform the lookup
- int pal_idx = get8u(s);
- if ( pal_idx >= tga_palette_len )
- {
- // invalid index
- pal_idx = 0;
- }
- pal_idx *= tga_bits_per_pixel / 8;
- for (j = 0; j*8 < tga_bits_per_pixel; ++j)
- {
- raw_data[j] = tga_palette[pal_idx+j];
- }
- } else
- {
- // read in the data raw
- for (j = 0; j*8 < tga_bits_per_pixel; ++j)
- {
- raw_data[j] = get8u(s);
- }
- }
- // convert raw to the intermediate format
- switch (tga_bits_per_pixel)
- {
- case 8:
- // Luminous => RGBA
- trans_data[0] = raw_data[0];
- trans_data[1] = raw_data[0];
- trans_data[2] = raw_data[0];
- trans_data[3] = 255;
- break;
- case 16:
- // Luminous,Alpha => RGBA
- trans_data[0] = raw_data[0];
- trans_data[1] = raw_data[0];
- trans_data[2] = raw_data[0];
- trans_data[3] = raw_data[1];
- break;
- case 24:
- // BGR => RGBA
- trans_data[0] = raw_data[2];
- trans_data[1] = raw_data[1];
- trans_data[2] = raw_data[0];
- trans_data[3] = 255;
- break;
- case 32:
- // BGRA => RGBA
- trans_data[0] = raw_data[2];
- trans_data[1] = raw_data[1];
- trans_data[2] = raw_data[0];
- trans_data[3] = raw_data[3];
- break;
- }
- // clear the reading flag for the next pixel
- read_next_pixel = 0;
- } // end of reading a pixel
- // convert to final format
- switch (req_comp)
- {
- case 1:
- // RGBA => Luminance
- tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
- break;
- case 2:
- // RGBA => Luminance,Alpha
- tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
- tga_data[i*req_comp+1] = trans_data[3];
- break;
- case 3:
- // RGBA => RGB
- tga_data[i*req_comp+0] = trans_data[0];
- tga_data[i*req_comp+1] = trans_data[1];
- tga_data[i*req_comp+2] = trans_data[2];
- break;
- case 4:
- // RGBA => RGBA
- tga_data[i*req_comp+0] = trans_data[0];
- tga_data[i*req_comp+1] = trans_data[1];
- tga_data[i*req_comp+2] = trans_data[2];
- tga_data[i*req_comp+3] = trans_data[3];
- break;
- }
- // 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 * req_comp;
- int index2 = (tga_height - 1 - j) * tga_width * req_comp;
- for (i = tga_width * req_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 )
- {
- free( tga_palette );
- }
- // 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;
- // OK, done
- return tga_data;
-}
-
-static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- return tga_load(s,x,y,comp,req_comp);
-}
-
-
-// *************************************************************************************************
-// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
-
-static int psd_test(stbi *s)
-{
- if (get32(s) != 0x38425053) return 0; // "8BPS"
- else return 1;
-}
-
-static int stbi_psd_test(stbi *s)
-{
- int r = psd_test(s);
- stbi_rewind(s);
- return r;
-}
-
-static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- int pixelCount;
- int channelCount, compression;
- int channel, i, count, len;
- int w,h;
- uint8 *out;
-
- // Check identifier
- if (get32(s) != 0x38425053) // "8BPS"
- return epuc("not PSD", "Corrupt PSD image");
-
- // Check file type version.
- if (get16(s) != 1)
- return epuc("wrong version", "Unsupported version of PSD image");
-
- // Skip 6 reserved bytes.
- skip(s, 6 );
-
- // Read the number of channels (R, G, B, A, etc).
- channelCount = get16(s);
- if (channelCount < 0 || channelCount > 16)
- return epuc("wrong channel count", "Unsupported number of channels in PSD image");
-
- // Read the rows and columns of the image.
- h = get32(s);
- w = get32(s);
-
- // Make sure the depth is 8 bits.
- if (get16(s) != 8)
- return epuc("unsupported bit depth", "PSD bit depth is not 8 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 (get16(s) != 3)
- return epuc("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.)
- skip(s,get32(s) );
-
- // Skip the image resources. (resolution, pen tool paths, etc)
- skip(s, get32(s) );
-
- // Skip the reserved data.
- skip(s, get32(s) );
-
- // Find out if the data is compressed.
- // Known values:
- // 0: no compression
- // 1: RLE compressed
- compression = get16(s);
- if (compression > 1)
- return epuc("bad compression", "PSD has an unknown compression format");
-
- // Create the destination image.
- out = (stbi_uc *) malloc(4 * w*h);
- if (!out) return epuc("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 preceeded by a 2-byte data count for each row in the data,
- // which we're going to just skip.
- skip(s, h * channelCount * 2 );
-
- // Read the RLE data by channel.
- for (channel = 0; channel < 4; channel++) {
- uint8 *p;
-
- p = out+channel;
- if (channel >= channelCount) {
- // Fill this channel with default data.
- for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
- } else {
- // Read the RLE data.
- count = 0;
- while (count < pixelCount) {
- len = get8(s);
- if (len == 128) {
- // No-op.
- } else if (len < 128) {
- // Copy next len+1 bytes literally.
- len++;
- count += len;
- while (len) {
- *p = get8u(s);
- p += 4;
- len--;
- }
- } else if (len > 128) {
- uint8 val;
- // Next -len+1 bytes in the dest are replicated from next source byte.
- // (Interpret len as a negative 8-bit int.)
- len ^= 0x0FF;
- len += 2;
- val = get8u(s);
- count += len;
- while (len) {
- *p = val;
- p += 4;
- len--;
- }
- }
- }
- }
- }
-
- } 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 value for each pixel in the image.
-
- // Read the data by channel.
- for (channel = 0; channel < 4; channel++) {
- uint8 *p;
-
- p = out + channel;
- if (channel > channelCount) {
- // Fill this channel with default data.
- for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
- } else {
- // Read the data.
- for (i = 0; i < pixelCount; i++)
- *p = get8u(s), p += 4;
- }
- }
- }
-
- if (req_comp && req_comp != 4) {
- out = convert_format(out, 4, req_comp, w, h);
- if (out == NULL) return out; // convert_format frees input on failure
- }
-
- if (comp) *comp = channelCount;
- *y = h;
- *x = w;
-
- return out;
-}
-
-static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- return psd_load(s,x,y,comp,req_comp);
-}
-
-// *************************************************************************************************
-// Softimage PIC loader
-// by Tom Seddon
-//
-// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
-// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
-
-static int pic_is4(stbi *s,const char *str)
-{
- int i;
- for (i=0; i<4; ++i)
- if (get8(s) != (stbi_uc)str[i])
- return 0;
-
- return 1;
-}
-
-static int pic_test(stbi *s)
-{
- int i;
-
- if (!pic_is4(s,"\x53\x80\xF6\x34"))
- return 0;
-
- for(i=0;i<84;++i)
- get8(s);
-
- if (!pic_is4(s,"PICT"))
- return 0;
-
- return 1;
-}
-
-typedef struct
-{
- stbi_uc size,type,channel;
-} pic_packet_t;
-
-static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)
-{
- int mask=0x80, i;
-
- for (i=0; i<4; ++i, mask>>=1) {
- if (channel & mask) {
- if (at_eof(s)) return epuc("bad file","PIC file too short");
- dest[i]=get8u(s);
- }
- }
-
- return dest;
-}
-
-static void pic_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 *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)
-{
- int act_comp=0,num_packets=0,y,chained;
- pic_packet_t packets[10];
-
- // this will (should...) cater for even some bizarre stuff like having data
- // for the same channel in multiple packets.
- do {
- pic_packet_t *packet;
-
- if (num_packets==sizeof(packets)/sizeof(packets[0]))
- return epuc("bad format","too many packets");
-
- packet = &packets[num_packets++];
-
- chained = get8(s);
- packet->size = get8u(s);
- packet->type = get8u(s);
- packet->channel = get8u(s);
-
- act_comp |= packet->channel;
-
- if (at_eof(s)) return epuc("bad file","file too short (reading packets)");
- if (packet->size != 8) return epuc("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) {
- pic_packet_t *packet = &packets[packet_idx];
- stbi_uc *dest = result+y*width*4;
-
- switch (packet->type) {
- default:
- return epuc("bad format","packet has bad compression type");
-
- case 0: {//uncompressed
- int x;
-
- for(x=0;x<width;++x, dest+=4)
- if (!pic_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=get8u(s);
- if (at_eof(s)) return epuc("bad file","file too short (pure read count)");
-
- if (count > left)
- count = (uint8) left;
-
- if (!pic_readval(s,packet->channel,value)) return 0;
-
- for(i=0; i<count; ++i,dest+=4)
- pic_copyval(packet->channel,dest,value);
- left -= count;
- }
- }
- break;
-
- case 2: {//Mixed RLE
- int left=width;
- while (left>0) {
- int count = get8(s), i;
- if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");
-
- if (count >= 128) { // Repeated
- stbi_uc value[4];
- int i;
-
- if (count==128)
- count = get16(s);
- else
- count -= 127;
- if (count > left)
- return epuc("bad file","scanline overrun");
-
- if (!pic_readval(s,packet->channel,value))
- return 0;
-
- for(i=0;i<count;++i, dest += 4)
- pic_copyval(packet->channel,dest,value);
- } else { // Raw
- ++count;
- if (count>left) return epuc("bad file","scanline overrun");
-
- for(i=0;i<count;++i, dest+=4)
- if (!pic_readval(s,packet->channel,dest))
- return 0;
- }
- left-=count;
- }
- break;
- }
- }
- }
- }
-
- return result;
-}
-
-static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)
-{
- stbi_uc *result;
- int i, x,y;
-
- for (i=0; i<92; ++i)
- get8(s);
-
- x = get16(s);
- y = get16(s);
- if (at_eof(s)) return epuc("bad file","file too short (pic header)");
- if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");
-
- get32(s); //skip `ratio'
- get16(s); //skip `fields'
- get16(s); //skip `pad'
-
- // intermediate buffer is RGBA
- result = (stbi_uc *) malloc(x*y*4);
- memset(result, 0xff, x*y*4);
-
- if (!pic_load2(s,x,y,comp, result)) {
- free(result);
- result=0;
- }
- *px = x;
- *py = y;
- if (req_comp == 0) req_comp = *comp;
- result=convert_format(result,4,req_comp,x,y);
-
- return result;
-}
-
-static int stbi_pic_test(stbi *s)
-{
- int r = pic_test(s);
- stbi_rewind(s);
- return r;
-}
-
-static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- return pic_load(s,x,y,comp,req_comp);
-}
-
-// *************************************************************************************************
-// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
-typedef struct stbi_gif_lzw_struct {
- int16 prefix;
- uint8 first;
- uint8 suffix;
-} stbi_gif_lzw;
-
-typedef struct stbi_gif_struct
-{
- int w,h;
- stbi_uc *out; // output buffer (always 4 components)
- int flags, bgindex, ratio, transparent, eflags;
- uint8 pal[256][4];
- uint8 lpal[256][4];
- stbi_gif_lzw codes[4096];
- uint8 *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;
-} stbi_gif;
-
-static int gif_test(stbi *s)
-{
- int sz;
- if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;
- sz = get8(s);
- if (sz != '9' && sz != '7') return 0;
- if (get8(s) != 'a') return 0;
- return 1;
-}
-
-static int stbi_gif_test(stbi *s)
-{
- int r = gif_test(s);
- stbi_rewind(s);
- return r;
-}
-
-static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp)
-{
- int i;
- for (i=0; i < num_entries; ++i) {
- pal[i][2] = get8u(s);
- pal[i][1] = get8u(s);
- pal[i][0] = get8u(s);
- pal[i][3] = transp ? 0 : 255;
- }
-}
-
-static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)
-{
- uint8 version;
- if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')
- return e("not GIF", "Corrupt GIF");
-
- version = get8u(s);
- if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");
- if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");
-
- failure_reason = "";
- g->w = get16le(s);
- g->h = get16le(s);
- g->flags = get8(s);
- g->bgindex = get8(s);
- g->ratio = get8(s);
- g->transparent = -1;
-
- 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 *s, int *x, int *y, int *comp)
-{
- stbi_gif g;
- if (!stbi_gif_header(s, &g, comp, 1)) {
- stbi_rewind( s );
- return 0;
- }
- if (x) *x = g.w;
- if (y) *y = g.h;
- return 1;
-}
-
-static void stbi_out_gif_code(stbi_gif *g, uint16 code)
-{
- uint8 *p, *c;
-
- // 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;
-
- p = &g->out[g->cur_x + g->cur_y];
- c = &g->color_table[g->codes[code].suffix * 4];
-
- if (c[3] >= 128) {
- 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 uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)
-{
- uint8 lzw_cs;
- int32 len, code;
- uint32 first;
- int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
- stbi_gif_lzw *p;
-
- lzw_cs = get8u(s);
- clear = 1 << lzw_cs;
- first = 1;
- codesize = lzw_cs + 1;
- codemask = (1 << codesize) - 1;
- bits = 0;
- valid_bits = 0;
- for (code = 0; code < clear; code++) {
- g->codes[code].prefix = -1;
- g->codes[code].first = (uint8) code;
- g->codes[code].suffix = (uint8) code;
- }
-
- // support no starting clear code
- avail = clear+2;
- oldcode = -1;
-
- len = 0;
- for(;;) {
- if (valid_bits < codesize) {
- if (len == 0) {
- len = get8(s); // start new block
- if (len == 0)
- return g->out;
- }
- --len;
- bits |= (int32) get8(s) << valid_bits;
- valid_bits += 8;
- } else {
- 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
- skip(s, len);
- while ((len = get8(s)) > 0)
- skip(s,len);
- return g->out;
- } else if (code <= avail) {
- if (first) return epuc("no clear code", "Corrupt GIF");
-
- if (oldcode >= 0) {
- p = &g->codes[avail++];
- if (avail > 4096) return epuc("too many codes", "Corrupt GIF");
- p->prefix = (int16) oldcode;
- p->first = g->codes[oldcode].first;
- p->suffix = (code == avail) ? p->first : g->codes[code].first;
- } else if (code == avail)
- return epuc("illegal code in raster", "Corrupt GIF");
-
- stbi_out_gif_code(g, (uint16) code);
-
- if ((avail & codemask) == 0 && avail <= 0x0FFF) {
- codesize++;
- codemask = (1 << codesize) - 1;
- }
-
- oldcode = code;
- } else {
- return epuc("illegal code in raster", "Corrupt GIF");
- }
- }
- }
-}
-
-static void stbi_fill_gif_background(stbi_gif *g)
-{
- int i;
- uint8 *c = g->pal[g->bgindex];
- // @OPTIMIZE: write a dword at a time
- for (i = 0; i < g->w * g->h * 4; i += 4) {
- uint8 *p = &g->out[i];
- p[0] = c[2];
- p[1] = c[1];
- p[2] = c[0];
- p[3] = c[3];
- }
-}
-
-// this function is designed to support animated gifs, although stb_image doesn't support it
-static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)
-{
- int i;
- uint8 *old_out = 0;
-
- if (g->out == 0) {
- if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header
- g->out = (uint8 *) malloc(4 * g->w * g->h);
- if (g->out == 0) return epuc("outofmem", "Out of memory");
- stbi_fill_gif_background(g);
- } else {
- // animated-gif-only path
- if (((g->eflags & 0x1C) >> 2) == 3) {
- old_out = g->out;
- g->out = (uint8 *) malloc(4 * g->w * g->h);
- if (g->out == 0) return epuc("outofmem", "Out of memory");
- memcpy(g->out, old_out, g->w*g->h*4);
- }
- }
-
- for (;;) {
- switch (get8(s)) {
- case 0x2C: /* Image Descriptor */
- {
- int32 x, y, w, h;
- uint8 *o;
-
- x = get16le(s);
- y = get16le(s);
- w = get16le(s);
- h = get16le(s);
- if (((x + w) > (g->w)) || ((y + h) > (g->h)))
- return epuc("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;
-
- g->lflags = 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 = (uint8 *) g->lpal;
- } else if (g->flags & 0x80) {
- for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent
- g->pal[i][3] = 255;
- if (g->transparent >= 0 && (g->eflags & 0x01))
- g->pal[g->transparent][3] = 0;
- g->color_table = (uint8 *) g->pal;
- } else
- return epuc("missing color table", "Corrupt GIF");
-
- o = stbi_process_gif_raster(s, g);
- if (o == NULL) return NULL;
-
- if (req_comp && req_comp != 4)
- o = convert_format(o, 4, req_comp, g->w, g->h);
- return o;
- }
-
- case 0x21: // Comment Extension.
- {
- int len;
- if (get8(s) == 0xF9) { // Graphic Control Extension.
- len = get8(s);
- if (len == 4) {
- g->eflags = get8(s);
- get16le(s); // delay
- g->transparent = get8(s);
- } else {
- skip(s, len);
- break;
- }
- }
- while ((len = get8(s)) != 0)
- skip(s, len);
- break;
- }
-
- case 0x3B: // gif stream termination code
- return (uint8 *) 1;
-
- default:
- return epuc("unknown code", "Corrupt GIF");
- }
- }
-}
-
-static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- uint8 *u = 0;
- stbi_gif g;
- memset(&g, 0, sizeof(stbi_gif));
-
- u = stbi_gif_load_next(s, &g, comp, req_comp);
- if (u == (void *) 1) u = 0; // end of animated gif marker
- if (u) {
- *x = g.w;
- *y = g.h;
- }
-
- return u;
-}
-
-static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)
-{
- return stbi_gif_info_raw(s,x,y,comp);
-}
-
-
-// *************************************************************************************************
-// Radiance RGBE HDR loader
-// originally by Nicolas Schulz
-#ifndef STBI_NO_HDR
-static int hdr_test(stbi *s)
-{
- const char *signature = "#?RADIANCE\n";
- int i;
- for (i=0; signature[i]; ++i)
- if (get8(s) != signature[i])
- return 0;
- return 1;
-}
-
-static int stbi_hdr_test(stbi* s)
-{
- int r = hdr_test(s);
- stbi_rewind(s);
- return r;
-}
-
-#define HDR_BUFLEN 1024
-static char *hdr_gettoken(stbi *z, char *buffer)
-{
- int len=0;
- char c = '\0';
-
- c = (char) get8(z);
-
- while (!at_eof(z) && c != '\n') {
- buffer[len++] = c;
- if (len == HDR_BUFLEN-1) {
- // flush to end of line
- while (!at_eof(z) && get8(z) != '\n')
- ;
- break;
- }
- c = (char) get8(z);
- }
-
- buffer[len] = 0;
- return buffer;
-}
-
-static void 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 *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- char buffer[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;
-
-
- // Check identifier
- if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
- return epf("not HDR", "Corrupt HDR image");
-
- // Parse header
- for(;;) {
- token = hdr_gettoken(s,buffer);
- if (token[0] == 0) break;
- if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
- }
-
- if (!valid) return epf("unsupported format", "Unsupported HDR format");
-
- // Parse width and height
- // can't use sscanf() if we're not using stdio!
- token = hdr_gettoken(s,buffer);
- if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
- token += 3;
- height = strtol(token, &token, 10);
- while (*token == ' ') ++token;
- if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
- token += 3;
- width = strtol(token, NULL, 10);
-
- *x = width;
- *y = height;
-
- *comp = 3;
- if (req_comp == 0) req_comp = 3;
-
- // Read data
- hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
-
- // 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:
- getn(s, rgbe, 4);
- 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 = get8(s);
- c2 = get8(s);
- len = 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)
- uint8 rgbe[4];
- rgbe[0] = (uint8) c1;
- rgbe[1] = (uint8) c2;
- rgbe[2] = (uint8) len;
- rgbe[3] = (uint8) get8u(s);
- hdr_convert(hdr_data, rgbe, req_comp);
- i = 1;
- j = 0;
- free(scanline);
- goto main_decode_loop; // yes, this makes no sense
- }
- len <<= 8;
- len |= get8(s);
- if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }
- if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
-
- for (k = 0; k < 4; ++k) {
- i = 0;
- while (i < width) {
- count = get8u(s);
- if (count > 128) {
- // Run
- value = get8u(s);
- count -= 128;
- for (z = 0; z < count; ++z)
- scanline[i++ * 4 + k] = value;
- } else {
- // Dump
- for (z = 0; z < count; ++z)
- scanline[i++ * 4 + k] = get8u(s);
- }
- }
- }
- for (i=0; i < width; ++i)
- hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
- }
- free(scanline);
- }
-
- return hdr_data;
-}
-
-static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
-{
- return hdr_load(s,x,y,comp,req_comp);
-}
-
-static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)
-{
- char buffer[HDR_BUFLEN];
- char *token;
- int valid = 0;
-
- if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
- stbi_rewind( s );
- return 0;
- }
-
- for(;;) {
- token = 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 = hdr_gettoken(s,buffer);
- if (strncmp(token, "-Y ", 3)) {
- stbi_rewind( s );
- return 0;
- }
- token += 3;
- *y = strtol(token, &token, 10);
- while (*token == ' ') ++token;
- if (strncmp(token, "+X ", 3)) {
- stbi_rewind( s );
- return 0;
- }
- token += 3;
- *x = strtol(token, NULL, 10);
- *comp = 3;
- return 1;
-}
-#endif // STBI_NO_HDR
-
-static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)
-{
- int hsz;
- if (get8(s) != 'B' || get8(s) != 'M') {
- stbi_rewind( s );
- return 0;
- }
- skip(s,12);
- hsz = get32le(s);
- if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {
- stbi_rewind( s );
- return 0;
- }
- if (hsz == 12) {
- *x = get16le(s);
- *y = get16le(s);
- } else {
- *x = get32le(s);
- *y = get32le(s);
- }
- if (get16le(s) != 1) {
- stbi_rewind( s );
- return 0;
- }
- *comp = get16le(s) / 8;
- return 1;
-}
-
-static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)
-{
- int channelCount;
- if (get32(s) != 0x38425053) {
- stbi_rewind( s );
- return 0;
- }
- if (get16(s) != 1) {
- stbi_rewind( s );
- return 0;
- }
- skip(s, 6);
- channelCount = get16(s);
- if (channelCount < 0 || channelCount > 16) {
- stbi_rewind( s );
- return 0;
- }
- *y = get32(s);
- *x = get32(s);
- if (get16(s) != 8) {
- stbi_rewind( s );
- return 0;
- }
- if (get16(s) != 3) {
- stbi_rewind( s );
- return 0;
- }
- *comp = 4;
- return 1;
-}
-
-static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)
-{
- int act_comp=0,num_packets=0,chained;
- pic_packet_t packets[10];
-
- skip(s, 92);
-
- *x = get16(s);
- *y = get16(s);
- if (at_eof(s)) return 0;
- if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
- stbi_rewind( s );
- return 0;
- }
-
- skip(s, 8);
-
- do {
- pic_packet_t *packet;
-
- if (num_packets==sizeof(packets)/sizeof(packets[0]))
- return 0;
-
- packet = &packets[num_packets++];
- chained = get8(s);
- packet->size = get8u(s);
- packet->type = get8u(s);
- packet->channel = get8u(s);
- act_comp |= packet->channel;
-
- if (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;
-}
-
-static int stbi_info_main(stbi *s, int *x, int *y, int *comp)
-{
- if (stbi_jpeg_info(s, x, y, comp))
- return 1;
- if (stbi_png_info(s, x, y, comp))
- return 1;
- if (stbi_gif_info(s, x, y, comp))
- return 1;
- if (stbi_bmp_info(s, x, y, comp))
- return 1;
- if (stbi_psd_info(s, x, y, comp))
- return 1;
- if (stbi_pic_info(s, x, y, comp))
- return 1;
- #ifndef STBI_NO_HDR
- if (stbi_hdr_info(s, x, y, comp))
- return 1;
- #endif
- // test tga last because it's a crappy test!
- if (stbi_tga_info(s, x, y, comp))
- return 1;
- return e("unknown image type", "Image not of any known type, or corrupt");
-}
-
-#ifndef STBI_NO_STDIO
-int stbi_info(char const *filename, int *x, int *y, int *comp)
-{
- FILE *f = fopen(filename, "rb");
- int result;
- if (!f) return e("can't fopen", "Unable to open file");
- result = stbi_info_from_file(f, x, y, comp);
- fclose(f);
- return result;
-}
-
-int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
-{
- int r;
- stbi s;
- long pos = ftell(f);
- start_file(&s, f);
- r = stbi_info_main(&s,x,y,comp);
- fseek(f,pos,SEEK_SET);
- return r;
-}
-#endif // !STBI_NO_STDIO
-
-int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
-{
- stbi s;
- start_mem(&s,buffer,len);
- return stbi_info_main(&s,x,y,comp);
-}
-
-int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
-{
- stbi s;
- start_callbacks(&s, (stbi_io_callbacks *) c, user);
- return stbi_info_main(&s,x,y,comp);
-}
-
-#endif // STBI_HEADER_FILE_ONLY
-
-/*
- revision history:
- 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-uint8 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.e. Janez (U+017D)emva)
- 1.21 fix use of 'uint8' 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 - 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 first released version
-*/
diff --git a/libs/dgl/src/nanovg/stb_truetype.h b/libs/dgl/src/nanovg/stb_truetype.h deleted file mode 100644 index 9290789..0000000 --- a/libs/dgl/src/nanovg/stb_truetype.h +++ /dev/null @@ -1,2064 +0,0 @@ -// stb_truetype.h - v0.6c - public domain
-// authored from 2009-2012 by Sean Barrett / RAD Game Tools
-//
-// This library processes TrueType files:
-// parse files
-// extract glyph metrics
-// extract glyph shapes
-// render glyphs to one-channel bitmaps with antialiasing (box filter)
-//
-// 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
-//
-// Bug/warning reports:
-// "Zer" on mollyrocket (with fix)
-// Cass Everitt
-// stoiko (Haemimont Games)
-// Brian Hook
-// Walter van Niftrik
-//
-// VERSION HISTORY
-//
-// 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
-//
-// LICENSE
-//
-// This software is in the public domain. Where that dedication is not
-// recognized, you are granted a perpetual, irrevokable license to copy
-// and modify this file as you see fit.
-//
-// USAGE
-//
-// Include this file in whatever places neeed 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.
-//
-// Simple 3D API (don't ship this, but it's fine for tools and quick start,
-// and you can cut and paste from it to move to more advanced)
-// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
-// stbtt_GetBakedQuad() -- compute quad to draw for a given char
-//
-// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
-// stbtt_InitFont()
-// stbtt_GetFontOffsetForIndex() -- use 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_GetCodepointKernAdvance()
-//
-// 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 they 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.
-//
-// 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.
-//
-//
-// SOURCE STATISTICS (based on v0.6c, 2050 LOC)
-//
-// Documentation & header file 520 LOC \___ 660 LOC documentation
-// Sample code 140 LOC /
-// Truetype parsing 620 LOC ---- 620 LOC TrueType
-// Software rasterization 240 LOC \ .
-// Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
-// Bitmap management 100 LOC /
-// Baked bitmap interface 70 LOC /
-// Font name matching & access 150 LOC ---- 150
-// C runtime library abstraction 60 LOC ---- 60
-
-
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-////
-//// SAMPLE PROGRAMS
-////
-//
-// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
-//
-#if 0
-#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
-#include "stb_truetype.h"
-
-char ttf_buffer[1<<20];
-unsigned char temp_bitmap[512*512];
-
-stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
-GLstbtt_uint ftex;
-
-void my_stbtt_initfont(void)
-{
- fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
- stbtt_BakeFontBitmap(data,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
- 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,0=old d3d
- glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
- glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
- glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
- glTexCoord2f(q.s0,q.t0); 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=0;
- char *text = "Heljo World!";
-
- 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.
-
-#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];
-
- // #define your own STBTT_sort() to override this to avoid qsort
- #ifndef STBTT_sort
- #include <stdlib.h>
- #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func)
- #endif
-
- // #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
-
- // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
- #ifndef STBTT_malloc
- #include <malloc.h>
- #define STBTT_malloc(x,u) malloc(x)
- #define STBTT_free(x,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 <memory.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 __cplusplus
-extern "C" {
-#endif
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// 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;
-
-extern 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;
-
-extern void stbtt_GetBakedQuad(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.
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// FONT LOADING
-//
-//
-
-extern 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. You can just skip
-// this step if you know it's that kind of font.
-
-
-// The following structure is defined publically so you can declare one on
-// the stack or as a global or etc, but you should treat it as opaque.
-typedef 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; // 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_fontinfo;
-
-extern 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
-
-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.
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// CHARACTER PROPERTIES
-//
-
-extern 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.
-
-extern 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.
-
-extern 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
-
-extern void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
-// the bounding box around all possible characters
-
-extern 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
-
-extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
-// an additional amount to add to the 'advance' value between ch1 and ch2
-// @TODO; for now always returns 0!
-
-extern 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
-
-extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
-extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
-extern 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
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// 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
- };
-#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;
- unsigned char type,padding;
- } stbtt_vertex;
-#endif
-
-extern int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
-// returns non-zero if nothing is drawn for this glyph
-
-extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
-extern 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
-
-extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
-// frees the data allocated above
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// BITMAP RENDERING
-//
-
-extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
-// frees the bitmap allocated below
-
-extern 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
-
-extern 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
-
-extern 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.
-
-extern 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
-
-extern 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.)
-
-extern 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)
-extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
-extern 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);
-extern 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);
-extern 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);
-extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
-extern 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;
-
-extern 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);
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// 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.
-
-
-extern 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
-
-extern 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
-
-extern 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:
-// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
-// http://www.microsoft.com/typography/otspec/name.htm
-
-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
-
-//////////////////////////////////////////////////////////////////////////
-//
-// 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)
-
-#if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
-
- #define ttUSHORT(p) (* (stbtt_uint16 *) (p))
- #define ttSHORT(p) (* (stbtt_int16 *) (p))
- #define ttULONG(p) (* (stbtt_uint32 *) (p))
- #define ttLONG(p) (* (stbtt_int32 *) (p))
-
-#else
-
- stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
- stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
- stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
- stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
-
-#endif
-
-#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(const 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
- 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;
-}
-
-int stbtt_GetFontOffsetForIndex(const 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*14);
- }
- }
- return -1;
-}
-
-int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
-{
- stbtt_uint8 *data = (stbtt_uint8 *) data2;
- stbtt_uint32 cmap, t;
- stbtt_int32 i,numTables;
-
- info->data = data;
- info->fontstart = fontstart;
-
- 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
- if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
- return 0;
-
- t = stbtt__find_table(data, fontstart, "maxp");
- if (t)
- info->numGlyphs = ttUSHORT(data+t+4);
- else
- info->numGlyphs = 0xffff;
-
- // 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;
- }
- }
- if (info->index_map == 0)
- return 0;
-
- info->indexToLocFormat = ttUSHORT(data+info->head + 50);
- return 1;
-}
-
-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;
- stbtt_uint16 item, offset, start, end;
-
- // 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) {
- searchRange >>= 1;
- start = ttUSHORT(data + search + 2 + segcount*2 + 2);
- end = ttUSHORT(data + search + 2);
- start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);
- end = ttUSHORT(data + search + searchRange*2);
- if (unicode_codepoint > end)
- search += searchRange*2;
- --entrySelector;
- }
- search += 2;
-
- item = (stbtt_uint16) ((search - endCount) >> 1);
-
- STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
- start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
- end = ttUSHORT(data + index_map + 14 + 2 + 2*item);
- if (unicode_codepoint < start)
- 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;
-}
-
-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;
-
- 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
-}
-
-int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
-{
- 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;
-}
-
-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);
-}
-
-int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
-{
- stbtt_int16 numberOfContours;
- int 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;
-}
-
-int stbtt_GetGlyphShape(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 == -1) {
- // 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) sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
- n = (float) 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) memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
- 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 if (numberOfContours < 0) {
- // @TODO other compound variations?
- STBTT_assert(0);
- } else {
- // numberOfCounters == 0, do nothing
- }
-
- *pvertices = vertices;
- return num_vertices;
-}
-
-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));
- }
-}
-
-int stbtt_GetGlyphKernAdvance(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;
-}
-
-int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
-{
- if (!info->kern) // 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));
-}
-
-void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
-{
- stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
-}
-
-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);
-}
-
-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);
-}
-
-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;
-}
-
-float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
-{
- int unitsPerEm = ttUSHORT(info->data + info->head + 18);
- return pixels / unitsPerEm;
-}
-
-void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
-{
- STBTT_free(v, info->userdata);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// antialiasing software rasterizer
-//
-
-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,y0,x1,y1;
- if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1))
- x0=y0=x1=y1=0; // e.g. space character
- // now 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_iceil (y1 * scale_y + shift_y);
- if (ix1) *ix1 = STBTT_iceil (x1 * scale_x + shift_x);
- if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y + shift_y);
-}
-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);
-}
-
-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);
-}
-
-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);
-}
-
-typedef struct stbtt__edge {
- float x0,y0, x1,y1;
- int invert;
-} stbtt__edge;
-
-typedef struct stbtt__active_edge
-{
- int x,dx;
- float ey;
- struct stbtt__active_edge *next;
- int valid;
-} stbtt__active_edge;
-
-#define FIXSHIFT 10
-#define FIX (1 << FIXSHIFT)
-#define FIXMASK (FIX-1)
-
-static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)
-{
- stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!
- float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
- STBTT_assert(e->y0 <= start_point);
- if (!z) return z;
- // round dx down to avoid going too far
- if (dxdy < 0)
- z->dx = -STBTT_ifloor(FIX * -dxdy);
- else
- z->dx = STBTT_ifloor(FIX * dxdy);
- z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));
- z->x -= off_x * FIX;
- z->ey = e->y1;
- z->next = 0;
- z->valid = e->invert ? 1 : -1;
- return z;
-}
-
-// 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->valid;
- } else {
- int x1 = e->x; w += e->valid;
- // if we went to zero, we need to draw
- if (w == 0) {
- int i = x0 >> FIXSHIFT;
- int j = x1 >> 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 >> FIXSHIFT);
- } else {
- if (i >= 0) // add antialiasing for x0
- scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);
- else
- i = -1; // clip
-
- if (j < len) // add antialiasing for x1
- scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> 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__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->valid);
- z->valid = 0;
- STBTT_free(z, userdata);
- } 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 = new_active(e, off_x, scan_y, userdata);
- // 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;
- }
-
- while (active) {
- stbtt__active_edge *z = active;
- active = active->next;
- STBTT_free(z, userdata);
- }
-
- if (scanline != scanline_data)
- STBTT_free(scanline, userdata);
-}
-
-static int stbtt__edge_compare(const void *p, const void *q)
-{
- stbtt__edge *a = (stbtt__edge *) p;
- stbtt__edge *b = (stbtt__edge *) q;
-
- if (a->y0 < b->y0) return -1;
- if (a->y0 > b->y0) return 1;
- return 0;
-}
-
-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;
- int vsubsample = result->h < 8 ? 15 : 5;
- // 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 * vsubsample + shift_y;
- e[n].x1 = p[b].x * scale_x + shift_x;
- e[n].y1 = p[b].y * y_scale_inv * vsubsample + shift_y;
- ++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);
-
- // 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;
-}
-
-// tesselate until threshhold 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;
-}
-
-// returns number of contours
-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;
- }
- }
- (*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;
-}
-
-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, *winding_lengths;
- 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);
- }
-}
-
-void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
-{
- STBTT_free(bitmap, userdata);
-}
-
-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) return NULL;
- scale_y = scale_x;
- }
-
- stbtt_GetGlyphBitmapBox(info, glyph, scale_x, scale_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;
-}
-
-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);
-}
-
-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);
-}
-
-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);
-}
-
-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);
-}
-
-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));
-}
-
-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);
-}
-
-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
-
-extern 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)
-{
- float scale;
- int x,y,bottom_y, i;
- stbtt_fontinfo f;
- stbtt_InitFont(&f, data, offset);
- 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 + 2;
- if (y+gh+2 > bottom_y)
- bottom_y = y+gh+2;
- }
- return bottom_y;
-}
-
-void stbtt_GetBakedQuad(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;
- stbtt_bakedchar *b = chardata + char_index;
- int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);
- int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);
-
- 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;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// 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(const stbtt_uint8 *s1, stbtt_int32 len1, const 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;
-}
-
-int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
-{
- return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const 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
-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), 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) {
- stbtt_int32 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((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;
-}
-
-int stbtt_FindMatchingFont(const unsigned char *font_collection, const 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;
- }
-}
-
-#endif // STB_TRUETYPE_IMPLEMENTATION
diff --git a/libs/dgl/src/pugl/pugl.h b/libs/dgl/src/pugl/pugl.h deleted file mode 100644 index 7cd8b84..0000000 --- a/libs/dgl/src/pugl/pugl.h +++ /dev/null @@ -1,404 +0,0 @@ -/* - Copyright 2012-2014 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file pugl.h API for Pugl, a minimal portable API for OpenGL. -*/ - -#ifndef PUGL_H_INCLUDED -#define PUGL_H_INCLUDED - -#include <stdint.h> - -/* - This API is pure portable C and contains no platform specific elements, or - even a GL dependency. However, unfortunately GL includes vary across - platforms so they are included here to allow for pure portable programs. -*/ -#ifdef __APPLE__ -# include "OpenGL/gl.h" -#else -# ifdef _WIN32 -# include <windows.h> /* Broken Windows GL headers require this */ -# endif -# include "GL/gl.h" -#endif - -#ifdef PUGL_SHARED -# ifdef _WIN32 -# define PUGL_LIB_IMPORT __declspec(dllimport) -# define PUGL_LIB_EXPORT __declspec(dllexport) -# else -# define PUGL_LIB_IMPORT __attribute__((visibility("default"))) -# define PUGL_LIB_EXPORT __attribute__((visibility("default"))) -# endif -# ifdef PUGL_INTERNAL -# define PUGL_API PUGL_LIB_EXPORT -# else -# define PUGL_API PUGL_LIB_IMPORT -# endif -#else -# ifdef _WIN32 -# define PUGL_API -# else -# define PUGL_API __attribute__((visibility("hidden"))) -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** - @defgroup pugl Pugl - A minimal portable API for OpenGL. - @{ -*/ - -/** - An OpenGL view. -*/ -typedef struct PuglViewImpl PuglView; - -/** - A native window handle. - - On X11, this is a Window. - On OSX, this is an NSView*. - On Windows, this is a HWND. -*/ -typedef intptr_t PuglNativeWindow; - -/** - Return status code. -*/ -typedef enum { - PUGL_SUCCESS = 0 -} PuglStatus; - -/** - Convenience symbols for ASCII control characters. -*/ -typedef enum { - PUGL_CHAR_BACKSPACE = 0x08, - PUGL_CHAR_ESCAPE = 0x1B, - PUGL_CHAR_DELETE = 0x7F -} PuglChar; - -/** - Special (non-Unicode) keyboard keys. -*/ -typedef enum { - PUGL_KEY_F1 = 1, - PUGL_KEY_F2, - PUGL_KEY_F3, - PUGL_KEY_F4, - PUGL_KEY_F5, - PUGL_KEY_F6, - PUGL_KEY_F7, - PUGL_KEY_F8, - PUGL_KEY_F9, - PUGL_KEY_F10, - PUGL_KEY_F11, - PUGL_KEY_F12, - PUGL_KEY_LEFT, - PUGL_KEY_UP, - PUGL_KEY_RIGHT, - PUGL_KEY_DOWN, - PUGL_KEY_PAGE_UP, - PUGL_KEY_PAGE_DOWN, - PUGL_KEY_HOME, - PUGL_KEY_END, - PUGL_KEY_INSERT, - PUGL_KEY_SHIFT, - PUGL_KEY_CTRL, - PUGL_KEY_ALT, - PUGL_KEY_SUPER -} PuglKey; - -/** - Keyboard modifier flags. -*/ -typedef enum { - PUGL_MOD_SHIFT = 1, /**< Shift key */ - PUGL_MOD_CTRL = 1 << 1, /**< Control key */ - PUGL_MOD_ALT = 1 << 2, /**< Alt/Option key */ - PUGL_MOD_SUPER = 1 << 3 /**< Mod4/Command/Windows key */ -} PuglMod; - -/** - Handle for opaque user data. -*/ -typedef void* PuglHandle; - -/** - A function called when the window is closed. -*/ -typedef void (*PuglCloseFunc)(PuglView* view); - -/** - A function called to draw the view contents with OpenGL. -*/ -typedef void (*PuglDisplayFunc)(PuglView* view); - -/** - A function called when a key is pressed or released. - @param view The view the event occured in. - @param press True if the key was pressed, false if released. - @param key Unicode point of the key pressed. -*/ -typedef void (*PuglKeyboardFunc)(PuglView* view, bool press, uint32_t key); - -/** - A function called when the pointer moves. - @param view The view the event occured in. - @param x The window-relative x coordinate of the pointer. - @param y The window-relative y coordinate of the pointer. -*/ -typedef void (*PuglMotionFunc)(PuglView* view, int x, int y); - -/** - A function called when a mouse button is pressed or released. - @param view The view the event occured in. - @param button The button number (1 = left, 2 = middle, 3 = right). - @param press True if the key was pressed, false if released. - @param x The window-relative x coordinate of the pointer. - @param y The window-relative y coordinate of the pointer. -*/ -typedef void (*PuglMouseFunc)( - PuglView* view, int button, bool press, int x, int y); - -/** - A function called when the view is resized. - @param view The view being resized. - @param width The new view width. - @param height The new view height. -*/ -typedef void (*PuglReshapeFunc)(PuglView* view, int width, int height); - -/** - A function called on scrolling (e.g. mouse wheel or track pad). - - The distances used here are in "lines", a single tick of a clicking mouse - wheel. For example, @p dy = 1.0 scrolls 1 line up. Some systems and - devices support finer resolution and/or higher values for fast scrolls, - so programs should handle any value gracefully. - - @param view The view being scrolled. - @param x The window-relative x coordinate of the pointer. - @param y The window-relative y coordinate of the pointer. - @param dx The scroll x distance. - @param dx The scroll y distance. -*/ -typedef void (*PuglScrollFunc)(PuglView* view, int x, int y, float dx, float dy); - -/** - A function called when a special key is pressed or released. - - This callback allows the use of keys that do not have unicode points. - Note that some are non-printable keys. - - @param view The view the event occured in. - @param press True if the key was pressed, false if released. - @param key The key pressed. -*/ -typedef void (*PuglSpecialFunc)(PuglView* view, bool press, PuglKey key); - -/** - A function called when a filename is selected via file-browser. - - @param view The view the event occured in. - @param filename The selected file name or NULL if the dialog was canceled. -*/ -typedef void (*PuglFileSelectedFunc)(PuglView* view, const char* filename); - -/** - Create a Pugl context. - - To create a window, call the various puglInit* functions as necessary, then - call puglCreateWindow(). -*/ -PUGL_API PuglView* -puglInit(void); - -/** - Set the parent window before creating a window (for embedding). -*/ -PUGL_API void -puglInitWindowParent(PuglView* view, PuglNativeWindow parent); - -/** - Set the window size before creating a window. -*/ -PUGL_API void -puglInitWindowSize(PuglView* view, int width, int height); - -/** - Enable or disable resizing before creating a window. -*/ -PUGL_API void -puglInitUserResizable(PuglView* view, bool resizable); - -/** - Create a window with the settings given by the various puglInit functions. - - @return 1 (pugl does not currently support multiple windows). -*/ -PUGL_API int -puglCreateWindow(PuglView* view, const char* title); - -/** - Show the current window. -*/ -PUGL_API void -puglShowWindow(PuglView* view); - -/** - Hide the current window. -*/ -PUGL_API void -puglHideWindow(PuglView* view); - -/** - Set the handle to be passed to all callbacks. - - This is generally a pointer to a struct which contains all necessary state. - Everything needed in callbacks should be here, not in static variables. - - Note the lack of this facility makes GLUT unsuitable for plugins or - non-trivial programs; this mistake is largely why Pugl exists. -*/ -PUGL_API void -puglSetHandle(PuglView* view, PuglHandle handle); - -/** - Get the handle to be passed to all callbacks. -*/ -PUGL_API PuglHandle -puglGetHandle(PuglView* view); - -/** - Return the timestamp (if any) of the currently-processing event. -*/ -PUGL_API uint32_t -puglGetEventTimestamp(PuglView* view); - -/** - Get the currently active modifiers (PuglMod flags). - - This should only be called from an event handler. -*/ -PUGL_API int -puglGetModifiers(PuglView* view); - -/** - Ignore synthetic repeated key events. -*/ -PUGL_API void -puglIgnoreKeyRepeat(PuglView* view, bool ignore); - -/** - Set the function to call when the window is closed. -*/ -PUGL_API void -puglSetCloseFunc(PuglView* view, PuglCloseFunc closeFunc); - -/** - Set the display function which should draw the UI using GL. -*/ -PUGL_API void -puglSetDisplayFunc(PuglView* view, PuglDisplayFunc displayFunc); - -/** - Set the function to call on keyboard events. -*/ -PUGL_API void -puglSetKeyboardFunc(PuglView* view, PuglKeyboardFunc keyboardFunc); - -/** - Set the function to call on mouse motion. -*/ -PUGL_API void -puglSetMotionFunc(PuglView* view, PuglMotionFunc motionFunc); - -/** - Set the function to call on mouse button events. -*/ -PUGL_API void -puglSetMouseFunc(PuglView* view, PuglMouseFunc mouseFunc); - -/** - Set the function to call on scroll events. -*/ -PUGL_API void -puglSetScrollFunc(PuglView* view, PuglScrollFunc scrollFunc); - -/** - Set the function to call on special events. -*/ -PUGL_API void -puglSetSpecialFunc(PuglView* view, PuglSpecialFunc specialFunc); - -/** - Set the function to call when the window size changes. -*/ -PUGL_API void -puglSetReshapeFunc(PuglView* view, PuglReshapeFunc reshapeFunc); - -/** - Set the function to call on file-browser selections. -*/ -PUGL_API void -puglSetFileSelectedFunc(PuglView* view, PuglFileSelectedFunc fileSelectedFunc); - -/** - Return the native window handle. -*/ -PUGL_API PuglNativeWindow -puglGetNativeWindow(PuglView* view); - -/** - Process all pending window events. - - This handles input events as well as rendering, so it should be called - regularly and rapidly enough to keep the UI responsive. -*/ -PUGL_API PuglStatus -puglProcessEvents(PuglView* view); - -/** - Request a redisplay on the next call to puglProcessEvents(). -*/ -PUGL_API void -puglPostRedisplay(PuglView* view); - -/** - Destroy a GL window. -*/ -PUGL_API void -puglDestroy(PuglView* view); - -/** - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* PUGL_H_INCLUDED */ diff --git a/libs/dgl/src/pugl/pugl_internal.h b/libs/dgl/src/pugl/pugl_internal.h deleted file mode 100644 index 7301091..0000000 --- a/libs/dgl/src/pugl/pugl_internal.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file pugl_internal.h Private platform-independent definitions. - - Note this file contains function definitions, so it must be compiled into - the final binary exactly once. Each platform specific implementation file - including it once should achieve this. - - If you are copying the pugl code into your source tree, the following - symbols can be defined to tweak pugl behaviour: - - PUGL_GRAB_FOCUS: Work around reparent keyboard issues by grabbing focus. - PUGL_VERBOSE: Print GL information to console. -*/ - -#include "pugl.h" - -#ifdef PUGL_VERBOSE -# include <stdio.h> -# define PUGL_LOG(str) fprintf(stderr, "pugl: " str) -# define PUGL_LOGF(fmt, ...) fprintf(stderr, "pugl: " fmt, __VA_ARGS__) -#else -# define PUGL_LOG(str) -# define PUGL_LOGF(fmt, ...) -#endif - -typedef struct PuglInternalsImpl PuglInternals; - -struct PuglViewImpl { - PuglHandle handle; - PuglCloseFunc closeFunc; - PuglDisplayFunc displayFunc; - PuglKeyboardFunc keyboardFunc; - PuglMotionFunc motionFunc; - PuglMouseFunc mouseFunc; - PuglReshapeFunc reshapeFunc; - PuglScrollFunc scrollFunc; - PuglSpecialFunc specialFunc; - PuglFileSelectedFunc fileSelectedFunc; - - PuglInternals* impl; - PuglNativeWindow parent; - - int width; - int height; - int mods; - bool mouse_in_view; - bool ignoreKeyRepeat; - bool redisplay; - bool resizable; - uint32_t event_timestamp_ms; -}; - -PuglInternals* puglInitInternals(void); - -PuglView* -puglInit(void) -{ - PuglView* view = (PuglView*)calloc(1, sizeof(PuglView)); - if (!view) { - return NULL; - } - - PuglInternals* impl = puglInitInternals(); - if (!impl) { - free(view); - return NULL; - } - - view->impl = impl; - view->width = 640; - view->height = 480; - - return view; -} - -void -puglInitWindowSize(PuglView* view, int width, int height) -{ - view->width = width; - view->height = height; -} - -void -puglInitWindowParent(PuglView* view, PuglNativeWindow parent) -{ - view->parent = parent; -} - -void -puglInitResizable(PuglView* view, bool resizable) -{ - view->resizable = resizable; -} - -void -puglSetHandle(PuglView* view, PuglHandle handle) -{ - view->handle = handle; -} - -PuglHandle -puglGetHandle(PuglView* view) -{ - return view->handle; -} - -uint32_t -puglGetEventTimestamp(PuglView* view) -{ - return view->event_timestamp_ms; -} - -int -puglGetModifiers(PuglView* view) -{ - return view->mods; -} - -static void -puglDefaultReshape(PuglView* view, int width, int height) -{ - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, width, height, 0, 0, 1); - glViewport(0, 0, width, height); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - return; - - // unused - (void)view; -} - -void -puglIgnoreKeyRepeat(PuglView* view, bool ignore) -{ - view->ignoreKeyRepeat = ignore; -} - -void -puglSetCloseFunc(PuglView* view, PuglCloseFunc closeFunc) -{ - view->closeFunc = closeFunc; -} - -void -puglSetDisplayFunc(PuglView* view, PuglDisplayFunc displayFunc) -{ - view->displayFunc = displayFunc; -} - -void -puglSetKeyboardFunc(PuglView* view, PuglKeyboardFunc keyboardFunc) -{ - view->keyboardFunc = keyboardFunc; -} - -void -puglSetMotionFunc(PuglView* view, PuglMotionFunc motionFunc) -{ - view->motionFunc = motionFunc; -} - -void -puglSetMouseFunc(PuglView* view, PuglMouseFunc mouseFunc) -{ - view->mouseFunc = mouseFunc; -} - -void -puglSetReshapeFunc(PuglView* view, PuglReshapeFunc reshapeFunc) -{ - view->reshapeFunc = reshapeFunc; -} - -void -puglSetScrollFunc(PuglView* view, PuglScrollFunc scrollFunc) -{ - view->scrollFunc = scrollFunc; -} - -void -puglSetSpecialFunc(PuglView* view, PuglSpecialFunc specialFunc) -{ - view->specialFunc = specialFunc; -} - -void -puglSetFileSelectedFunc(PuglView* view, PuglFileSelectedFunc fileSelectedFunc) -{ - view->fileSelectedFunc = fileSelectedFunc; -} diff --git a/libs/dgl/src/pugl/pugl_osx.m b/libs/dgl/src/pugl/pugl_osx.m deleted file mode 100644 index a99d8d0..0000000 --- a/libs/dgl/src/pugl/pugl_osx.m +++ /dev/null @@ -1,546 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file pugl_osx.m OSX/Cocoa Pugl Implementation. -*/ - -#include <stdlib.h> - -#import <Cocoa/Cocoa.h> - -#include "pugl_internal.h" - -@interface PuglWindow : NSWindow -{ -@public - PuglView* puglview; -} - -- (id) initWithContentRect:(NSRect)contentRect - styleMask:(unsigned int)aStyle - backing:(NSBackingStoreType)bufferingType - defer:(BOOL)flag; -- (void) setPuglview:(PuglView*)view; -- (BOOL) canBecomeKeyWindow; -- (BOOL) windowShouldClose:(id)sender; -@end - -@implementation PuglWindow - -- (id)initWithContentRect:(NSRect)contentRect - styleMask:(unsigned int)aStyle - backing:(NSBackingStoreType)bufferingType - defer:(BOOL)flag -{ - NSWindow* result = [super initWithContentRect:contentRect - styleMask:(NSClosableWindowMask | - NSTitledWindowMask | - NSResizableWindowMask) - backing:NSBackingStoreBuffered defer:NO]; - - [result setAcceptsMouseMovedEvents:YES]; - [result setLevel: CGShieldingWindowLevel() + 1]; - - return (PuglWindow*)result; - - // unused - (void)aStyle; (void)bufferingType; (void)flag; -} - -- (void)setPuglview:(PuglView*)view -{ - puglview = view; - [self setContentSize:NSMakeSize(view->width, view->height)]; -} - -- (BOOL)canBecomeKeyWindow -{ - return YES; -} - -- (BOOL)windowShouldClose:(id)sender -{ - if (puglview->closeFunc) - puglview->closeFunc(puglview); - return YES; - - // unused - (void)sender; -} - -@end - -static void -puglDisplay(PuglView* view) -{ - view->redisplay = false; - if (view->displayFunc) { - view->displayFunc(view); - } -} - -@interface PuglOpenGLView : NSOpenGLView -{ -@public - PuglView* puglview; - NSTrackingArea* trackingArea; - bool doubleBuffered; -} - -- (BOOL) acceptsFirstMouse:(NSEvent*)e; -- (BOOL) acceptsFirstResponder; -- (BOOL) isFlipped; -- (BOOL) isOpaque; -- (BOOL) preservesContentInLiveResize; -- (id) initWithFrame:(NSRect)frame; -- (void) reshape; -- (void) drawRect:(NSRect)r; -- (void) cursorUpdate:(NSEvent*)e; -- (void) updateTrackingAreas; -- (void) viewWillMoveToWindow:(NSWindow*)newWindow; -- (void) mouseMoved:(NSEvent*)event; -- (void) mouseDragged:(NSEvent*)event; -- (void) rightMouseDragged:(NSEvent*)event; -- (void) otherMouseDragged:(NSEvent*)event; -- (void) mouseDown:(NSEvent*)event; -- (void) rightMouseDown:(NSEvent*)event; -- (void) otherMouseDown:(NSEvent*)event; -- (void) mouseUp:(NSEvent*)event; -- (void) rightMouseUp:(NSEvent*)event; -- (void) otherMouseUp:(NSEvent*)event; -- (void) scrollWheel:(NSEvent*)event; -- (void) keyDown:(NSEvent*)event; -- (void) keyUp:(NSEvent*)event; -- (void) flagsChanged:(NSEvent*)event; - -@end - -@implementation PuglOpenGLView - -- (BOOL) acceptsFirstMouse:(NSEvent*)e -{ - return YES; - - // unused - (void)e; -} - -- (BOOL) acceptsFirstResponder -{ - return YES; -} - -- (BOOL) isFlipped -{ - return YES; -} - -- (BOOL) isOpaque -{ - return YES; -} - -- (BOOL) preservesContentInLiveResize -{ - return NO; -} - -- (id) initWithFrame:(NSRect)frame -{ - puglview = nil; - trackingArea = nil; - doubleBuffered = true; - - NSOpenGLPixelFormatAttribute pixelAttribs[] = { - NSOpenGLPFAColorSize, 24, - NSOpenGLPFAAlphaSize, 8, - NSOpenGLPFADepthSize, 16, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFAAccelerated, - 0 - }; - - NSOpenGLPixelFormat* pixelFormat = [[NSOpenGLPixelFormat alloc] - initWithAttributes:pixelAttribs]; - - if (pixelFormat) { - self = [super initWithFrame:frame pixelFormat:pixelFormat]; - [pixelFormat release]; - printf("Is doubleBuffered? TRUE\n"); - } else { - self = [super initWithFrame:frame]; - doubleBuffered = false; - printf("Is doubleBuffered? FALSE\n"); - } - - if (self) { - NSOpenGLContext* context = [self openGLContext]; - [context makeCurrentContext]; - - GLint swapInterval = 1; - [context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; - - [self reshape]; - } - - return self; -} - -- (void) reshape -{ - [[self openGLContext] update]; - - if (!puglview) { - /* NOTE: Apparently reshape gets called when the GC gets around to - deleting the view (?), so we must have reset puglview to NULL when - this comes around. - */ - return; - } - - NSRect bounds = [self bounds]; - int width = bounds.size.width; - int height = bounds.size.height; - - if (puglview->reshapeFunc) { - puglview->reshapeFunc(puglview, width, height); - } else { - puglDefaultReshape(puglview, width, height); - } - - puglview->width = width; - puglview->height = height; -} - -- (void) drawRect:(NSRect)r -{ - puglDisplay(puglview); - - if (doubleBuffered) { - [[self openGLContext] flushBuffer]; - } else { - glFlush(); - //glSwapAPPLE(); - } - - // unused - return; (void)r; -} - -- (void) cursorUpdate:(NSEvent*)e -{ - [[NSCursor arrowCursor] set]; - - // unused - return; (void)e; -} - -- (void) updateTrackingAreas -{ - static const int opts = NSTrackingMouseEnteredAndExited - | NSTrackingMouseMoved - | NSTrackingEnabledDuringMouseDrag - | NSTrackingInVisibleRect - | NSTrackingActiveAlways - | NSTrackingCursorUpdate; - - if (trackingArea != nil) { - [self removeTrackingArea:trackingArea]; - [trackingArea release]; - } - - trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] - options:opts - owner:self - userInfo:nil]; - [self addTrackingArea:trackingArea]; - [super updateTrackingAreas]; -} - -- (void) viewWillMoveToWindow:(NSWindow*)newWindow -{ - if (newWindow != nil) { - [newWindow setAcceptsMouseMovedEvents:YES]; - [newWindow makeFirstResponder:self]; - } - - [super viewWillMoveToWindow:newWindow]; -} - -static unsigned -getModifiers(PuglView* view, NSEvent* ev) -{ - const unsigned modifierFlags = [ev modifierFlags]; - - view->event_timestamp_ms = fmod([ev timestamp] * 1000.0, UINT32_MAX); - - unsigned mods = 0; - mods |= (modifierFlags & NSShiftKeyMask) ? PUGL_MOD_SHIFT : 0; - mods |= (modifierFlags & NSControlKeyMask) ? PUGL_MOD_CTRL : 0; - mods |= (modifierFlags & NSAlternateKeyMask) ? PUGL_MOD_ALT : 0; - mods |= (modifierFlags & NSCommandKeyMask) ? PUGL_MOD_SUPER : 0; - return mods; -} - -static int -getFixedAppKitButton(NSInteger button) -{ - switch (button) { - case 0: return 1; - case 1: return 3; - case 2: return 2; - default: return button; - } -} - -- (void) mouseMoved:(NSEvent*)event -{ - if (puglview->motionFunc) { - NSPoint loc = [self convertPoint:[event locationInWindow] fromView:nil]; - puglview->mods = getModifiers(puglview, event); - puglview->motionFunc(puglview, loc.x, loc.y); - } -} - -- (void) mouseDragged:(NSEvent*)event -{ - [self mouseMoved:event]; -} - -- (void) rightMouseDragged:(NSEvent*)event -{ - [self mouseDragged:event]; -} - -- (void) otherMouseDragged:(NSEvent*)event -{ - [self mouseDragged:event]; -} - -- (void) mouseDown:(NSEvent*)event -{ - if (puglview->mouseFunc) { - NSPoint loc = [self convertPoint:[event locationInWindow] fromView:nil]; - puglview->mods = getModifiers(puglview, event); - puglview->mouseFunc(puglview, getFixedAppKitButton([event buttonNumber]), true, loc.x, loc.y); - } -} - -- (void) rightMouseDown:(NSEvent*)event -{ - [self mouseDown:event]; -} - -- (void) otherMouseDown:(NSEvent*)event -{ - [self mouseDown:event]; -} - -- (void) mouseUp:(NSEvent*)event -{ - if (puglview->mouseFunc) { - NSPoint loc = [self convertPoint:[event locationInWindow] fromView:nil]; - puglview->mods = getModifiers(puglview, event); - puglview->mouseFunc(puglview, getFixedAppKitButton([event buttonNumber]), false, loc.x, loc.y); - } -} - -- (void) rightMouseUp:(NSEvent*)event -{ - [self mouseUp:event]; -} - -- (void) otherMouseUp:(NSEvent*)event -{ - [self mouseUp:event]; -} - -- (void) scrollWheel:(NSEvent*)event -{ - if (puglview->scrollFunc) { - NSPoint loc = [self convertPoint:[event locationInWindow] fromView:nil]; - puglview->mods = getModifiers(puglview, event); - puglview->scrollFunc(puglview, - loc.x, loc.y, - [event deltaX], [event deltaY]); - } -} - -- (void) keyDown:(NSEvent*)event -{ - if (puglview->keyboardFunc && !(puglview->ignoreKeyRepeat && [event isARepeat])) { - NSString* chars = [event characters]; - puglview->mods = getModifiers(puglview, event); - puglview->keyboardFunc(puglview, true, [chars characterAtIndex:0]); - } -} - -- (void) keyUp:(NSEvent*)event -{ - if (puglview->keyboardFunc) { - NSString* chars = [event characters]; - puglview->mods = getModifiers(puglview, event); - puglview->keyboardFunc(puglview, false, [chars characterAtIndex:0]); - } -} - -- (void) flagsChanged:(NSEvent*)event -{ - if (puglview->specialFunc) { - const unsigned mods = getModifiers(puglview, event); - if ((mods & PUGL_MOD_SHIFT) != (puglview->mods & PUGL_MOD_SHIFT)) { - puglview->specialFunc(puglview, mods & PUGL_MOD_SHIFT, PUGL_KEY_SHIFT); - } else if ((mods & PUGL_MOD_CTRL) != (puglview->mods & PUGL_MOD_CTRL)) { - puglview->specialFunc(puglview, mods & PUGL_MOD_CTRL, PUGL_KEY_CTRL); - } else if ((mods & PUGL_MOD_ALT) != (puglview->mods & PUGL_MOD_ALT)) { - puglview->specialFunc(puglview, mods & PUGL_MOD_ALT, PUGL_KEY_ALT); - } else if ((mods & PUGL_MOD_SUPER) != (puglview->mods & PUGL_MOD_SUPER)) { - puglview->specialFunc(puglview, mods & PUGL_MOD_SUPER, PUGL_KEY_SUPER); - } - puglview->mods = mods; - } -} - -@end - -struct PuglInternalsImpl { - PuglOpenGLView* glview; - id window; -}; - -PuglInternals* -puglInitInternals() -{ - return (PuglInternals*)calloc(1, sizeof(PuglInternals)); -} - -int -puglCreateWindow(PuglView* view, const char* title) -{ - PuglInternals* impl = view->impl; - - [NSAutoreleasePool new]; - [NSApplication sharedApplication]; - - impl->glview = [PuglOpenGLView new]; - - if (!impl->glview) { - return 1; - } - - impl->glview->puglview = view; - - if (view->resizable) { - [impl->glview setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable]; - } - - if (view->parent) { - [impl->glview retain]; - NSView* pview = (NSView*)view->parent; - [pview addSubview:impl->glview]; - return 0; - } - - id window = [[PuglWindow new]retain]; - - if (title) { - NSString* titleString = [[NSString alloc] - initWithBytes:title - length:strlen(title) - encoding:NSUTF8StringEncoding]; - - [window setTitle:titleString]; - } - - [window setPuglview:view]; - [window setContentView:impl->glview]; - [window makeFirstResponder:impl->glview]; - [window makeKeyAndOrderFront:window]; - - // wait for first puglShowWindow - [window setIsVisible:NO]; - - [NSApp activateIgnoringOtherApps:YES]; - [window center]; - - impl->window = window; - - return 0; -} - -void -puglShowWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - if (impl->window) { - [impl->window setIsVisible:YES]; - } else { - [view->impl->glview setHidden:NO]; - } -} - -void -puglHideWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - if (impl->window) { - [impl->window setIsVisible:NO]; - } else { - [impl->glview setHidden:YES]; - } -} - -void -puglDestroy(PuglView* view) -{ - view->impl->glview->puglview = NULL; - - if (view->impl->window) { - [view->impl->window close]; - [view->impl->glview release]; - [view->impl->window release]; - } else { - [view->impl->glview release]; - } - - free(view->impl); - free(view); -} - -PuglStatus -puglProcessEvents(PuglView* view) -{ - return PUGL_SUCCESS; - - // unused - (void)view; -} - -void -puglPostRedisplay(PuglView* view) -{ - view->redisplay = true; - [view->impl->glview setNeedsDisplay:YES]; -} - -PuglNativeWindow -puglGetNativeWindow(PuglView* view) -{ - return (PuglNativeWindow)view->impl->glview; -} diff --git a/libs/dgl/src/pugl/pugl_win.cpp b/libs/dgl/src/pugl/pugl_win.cpp deleted file mode 100644 index 0837ac1..0000000 --- a/libs/dgl/src/pugl/pugl_win.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file pugl_win.cpp Windows/WGL Pugl Implementation. -*/ - -#include <windows.h> -#include <windowsx.h> -#include <GL/gl.h> - -#include <ctime> -#include <stdio.h> -#include <stdlib.h> - -#include "pugl_internal.h" - -#ifndef WM_MOUSEWHEEL -# define WM_MOUSEWHEEL 0x020A -#endif -#ifndef WM_MOUSEHWHEEL -# define WM_MOUSEHWHEEL 0x020E -#endif -#ifndef WHEEL_DELTA -# define WHEEL_DELTA 120 -#endif - -const int LOCAL_CLOSE_MSG = WM_USER + 50; - -HINSTANCE hInstance = NULL; - -struct PuglInternalsImpl { - HWND hwnd; - HDC hdc; - HGLRC hglrc; - WNDCLASS wc; -}; - -LRESULT CALLBACK -wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); - -#if 0 -extern "C" { -BOOL WINAPI -DllMain(HINSTANCE hInst, DWORD, LPVOID) -{ - hInstance = hInst; - return 1; -} -} // extern "C" -#endif - -PuglInternals* -puglInitInternals() -{ - return (PuglInternals*)calloc(1, sizeof(PuglInternals)); -} - -int -puglCreateWindow(PuglView* view, const char* title) -{ - PuglInternals* impl = view->impl; - - if (!title) { - title = "Window"; - } - - // FIXME: This is nasty, and pugl should not have static anything. - // Should class be a parameter? Does this make sense on other platforms? - static int wc_count = 0; - char classNameBuf[256]; - std::srand((std::time(NULL))); - _snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d-%d", title, std::rand(), ++wc_count); - classNameBuf[sizeof(classNameBuf)-1] = '\0'; - - impl->wc.style = CS_OWNDC; - impl->wc.lpfnWndProc = wndProc; - impl->wc.cbClsExtra = 0; - impl->wc.cbWndExtra = 0; - impl->wc.hInstance = hInstance; - impl->wc.hIcon = LoadIcon(hInstance, IDI_APPLICATION); - impl->wc.hCursor = LoadCursor(hInstance, IDC_ARROW); - impl->wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); - impl->wc.lpszMenuName = NULL; - impl->wc.lpszClassName = strdup(classNameBuf); - - if (!RegisterClass(&impl->wc)) { - free((void*)impl->wc.lpszClassName); - free(impl); - free(view); - return 1; - } - - // Adjust the overall window size to accomodate our requested client size - const int winFlags = WS_POPUPWINDOW | WS_CAPTION | (view->resizable ? WS_SIZEBOX : 0x0); - RECT wr = { 0, 0, view->width, view->height }; - AdjustWindowRectEx(&wr, view->parent ? WS_CHILD : winFlags, FALSE, WS_EX_TOPMOST); - - impl->hwnd = CreateWindowEx( - WS_EX_TOPMOST, - classNameBuf, title, - view->parent ? (WS_CHILD | WS_VISIBLE) : winFlags, - CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top, - (HWND)view->parent, NULL, hInstance, NULL); - - if (!impl->hwnd) { - UnregisterClass(impl->wc.lpszClassName, NULL); - free((void*)impl->wc.lpszClassName); - free(impl); - free(view); - return 1; - } - - SetWindowLongPtr(impl->hwnd, GWLP_USERDATA, (LONG_PTR)view); - - impl->hdc = GetDC(impl->hwnd); - - PIXELFORMATDESCRIPTOR pfd; - ZeroMemory(&pfd, sizeof(pfd)); - pfd.nSize = sizeof(pfd); - pfd.nVersion = 1; - pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; - pfd.iPixelType = PFD_TYPE_RGBA; - pfd.cColorBits = 24; - pfd.cDepthBits = 16; - pfd.iLayerType = PFD_MAIN_PLANE; - - int format = ChoosePixelFormat(impl->hdc, &pfd); - SetPixelFormat(impl->hdc, format, &pfd); - - impl->hglrc = wglCreateContext(impl->hdc); - if (!impl->hglrc) { - ReleaseDC (impl->hwnd, impl->hdc); - DestroyWindow (impl->hwnd); - UnregisterClass (impl->wc.lpszClassName, NULL); - free((void*)impl->wc.lpszClassName); - free(impl); - free(view); - return 1; - } - - wglMakeCurrent(impl->hdc, impl->hglrc); - - return 0; -} - -void -puglShowWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - ShowWindow(impl->hwnd, SW_SHOWNORMAL); -} - -void -puglHideWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - ShowWindow(impl->hwnd, SW_HIDE); -} - -void -puglDestroy(PuglView* view) -{ - wglMakeCurrent(NULL, NULL); - wglDeleteContext(view->impl->hglrc); - ReleaseDC(view->impl->hwnd, view->impl->hdc); - DestroyWindow(view->impl->hwnd); - UnregisterClass(view->impl->wc.lpszClassName, NULL); - free((void*)view->impl->wc.lpszClassName); - free(view->impl); - free(view); -} - -static void -puglReshape(PuglView* view, int width, int height) -{ - wglMakeCurrent(view->impl->hdc, view->impl->hglrc); - - if (view->reshapeFunc) { - view->reshapeFunc(view, width, height); - } else { - puglDefaultReshape(view, width, height); - } - - view->width = width; - view->height = height; -} - -static void -puglDisplay(PuglView* view) -{ - wglMakeCurrent(view->impl->hdc, view->impl->hglrc); - - view->redisplay = false; - if (view->displayFunc) { - view->displayFunc(view); - } - - glFlush(); - SwapBuffers(view->impl->hdc); -} - -static PuglKey -keySymToSpecial(int sym) -{ - switch (sym) { - case VK_F1: return PUGL_KEY_F1; - case VK_F2: return PUGL_KEY_F2; - case VK_F3: return PUGL_KEY_F3; - case VK_F4: return PUGL_KEY_F4; - case VK_F5: return PUGL_KEY_F5; - case VK_F6: return PUGL_KEY_F6; - case VK_F7: return PUGL_KEY_F7; - case VK_F8: return PUGL_KEY_F8; - case VK_F9: return PUGL_KEY_F9; - case VK_F10: return PUGL_KEY_F10; - case VK_F11: return PUGL_KEY_F11; - case VK_F12: return PUGL_KEY_F12; - case VK_LEFT: return PUGL_KEY_LEFT; - case VK_UP: return PUGL_KEY_UP; - case VK_RIGHT: return PUGL_KEY_RIGHT; - case VK_DOWN: return PUGL_KEY_DOWN; - case VK_PRIOR: return PUGL_KEY_PAGE_UP; - case VK_NEXT: return PUGL_KEY_PAGE_DOWN; - case VK_HOME: return PUGL_KEY_HOME; - case VK_END: return PUGL_KEY_END; - case VK_INSERT: return PUGL_KEY_INSERT; - case VK_SHIFT: return PUGL_KEY_SHIFT; - case VK_CONTROL: return PUGL_KEY_CTRL; - case VK_MENU: return PUGL_KEY_ALT; - case VK_LWIN: return PUGL_KEY_SUPER; - case VK_RWIN: return PUGL_KEY_SUPER; - } - return (PuglKey)0; -} - -static void -processMouseEvent(PuglView* view, int button, bool press, LPARAM lParam) -{ - view->event_timestamp_ms = GetMessageTime(); - if (press) { - SetCapture(view->impl->hwnd); - } else { - ReleaseCapture(); - } - - if (view->mouseFunc) { - view->mouseFunc(view, button, press, - GET_X_LPARAM(lParam), - GET_Y_LPARAM(lParam)); - } -} - -static void -setModifiers(PuglView* view) -{ - view->mods = 0; - view->mods |= (GetKeyState(VK_SHIFT) < 0) ? PUGL_MOD_SHIFT : 0; - view->mods |= (GetKeyState(VK_CONTROL) < 0) ? PUGL_MOD_CTRL : 0; - view->mods |= (GetKeyState(VK_MENU) < 0) ? PUGL_MOD_ALT : 0; - view->mods |= (GetKeyState(VK_LWIN) < 0) ? PUGL_MOD_SUPER : 0; - view->mods |= (GetKeyState(VK_RWIN) < 0) ? PUGL_MOD_SUPER : 0; -} - -static LRESULT -handleMessage(PuglView* view, UINT message, WPARAM wParam, LPARAM lParam) -{ - PAINTSTRUCT ps; - PuglKey key; - - setModifiers(view); - switch (message) { - case WM_CREATE: - case WM_SHOWWINDOW: - case WM_SIZE: - RECT rect; - GetClientRect(view->impl->hwnd, &rect); - puglReshape(view, rect.right, rect.bottom); - view->width = rect.right; - view->height = rect.bottom; - break; - case WM_PAINT: - BeginPaint(view->impl->hwnd, &ps); - puglDisplay(view); - EndPaint(view->impl->hwnd, &ps); - break; - case WM_MOUSEMOVE: - if (view->motionFunc) { - view->motionFunc(view, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - } - break; - case WM_LBUTTONDOWN: - processMouseEvent(view, 1, true, lParam); - break; - case WM_MBUTTONDOWN: - processMouseEvent(view, 2, true, lParam); - break; - case WM_RBUTTONDOWN: - processMouseEvent(view, 3, true, lParam); - break; - case WM_LBUTTONUP: - processMouseEvent(view, 1, false, lParam); - break; - case WM_MBUTTONUP: - processMouseEvent(view, 2, false, lParam); - break; - case WM_RBUTTONUP: - processMouseEvent(view, 3, false, lParam); - break; - case WM_MOUSEWHEEL: - if (view->scrollFunc) { - view->event_timestamp_ms = GetMessageTime(); - POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; - ScreenToClient(view->impl->hwnd, &pt); - view->scrollFunc( - view, pt.x, pt.y, - 0, GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); - } - break; - case WM_MOUSEHWHEEL: - if (view->scrollFunc) { - view->event_timestamp_ms = GetMessageTime(); - POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; - ScreenToClient(view->impl->hwnd, &pt); - view->scrollFunc( - view, pt.x, pt.y, - GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0); - } - break; - case WM_KEYDOWN: - if (view->ignoreKeyRepeat && (lParam & (1 << 30))) { - break; - } // else nobreak - case WM_KEYUP: - view->event_timestamp_ms = GetMessageTime(); - if ((key = keySymToSpecial(wParam))) { - if (view->specialFunc) { - view->specialFunc(view, message == WM_KEYDOWN, key); - } - } else if (view->keyboardFunc) { - static BYTE kbs[256]; - if (GetKeyboardState(kbs) != FALSE) { - char lb[2]; - UINT scanCode = (lParam >> 8) & 0xFFFFFF00; - if ( 1 == ToAscii(wParam, scanCode, kbs, (LPWORD)lb, 0)) { - view->keyboardFunc(view, message == WM_KEYDOWN, (char)lb[0]); - } - } - } - break; - case WM_QUIT: - case LOCAL_CLOSE_MSG: - if (view->closeFunc) { - view->closeFunc(view); - } - break; - default: - return DefWindowProc( - view->impl->hwnd, message, wParam, lParam); - } - - return 0; -} - -PuglStatus -puglProcessEvents(PuglView* view) -{ - MSG msg; - while (PeekMessage(&msg, view->impl->hwnd, 0, 0, PM_REMOVE)) { - handleMessage(view, msg.message, msg.wParam, msg.lParam); - } - - if (view->redisplay) { - InvalidateRect(view->impl->hwnd, NULL, FALSE); - } - - return PUGL_SUCCESS; -} - -LRESULT CALLBACK -wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - PuglView* view = (PuglView*)GetWindowLongPtr(hwnd, GWLP_USERDATA); - - switch (message) { - case WM_CREATE: - PostMessage(hwnd, WM_SHOWWINDOW, TRUE, 0); - return 0; - case WM_CLOSE: - PostMessage(hwnd, LOCAL_CLOSE_MSG, wParam, lParam); - return 0; - case WM_DESTROY: - return 0; - default: - if (view && hwnd == view->impl->hwnd) { - return handleMessage(view, message, wParam, lParam); - } else { - return DefWindowProc(hwnd, message, wParam, lParam); - } - } -} - -void -puglPostRedisplay(PuglView* view) -{ - view->redisplay = true; -} - -PuglNativeWindow -puglGetNativeWindow(PuglView* view) -{ - return (PuglNativeWindow)view->impl->hwnd; -} diff --git a/libs/dgl/src/pugl/pugl_x11.c b/libs/dgl/src/pugl/pugl_x11.c deleted file mode 100644 index d1f68ea..0000000 --- a/libs/dgl/src/pugl/pugl_x11.c +++ /dev/null @@ -1,464 +0,0 @@ -/* - Copyright 2012-2014 David Robillard <http://drobilla.net> - Copyright 2011-2012 Ben Loftis, Harrison Consoles - Copyright 2013 Robin Gareus <robin@gareus.org> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file pugl_x11.c X11 Pugl Implementation. -*/ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <GL/gl.h> -#include <GL/glx.h> -#include <X11/Xatom.h> -#include <X11/Xlib.h> -#include <X11/keysym.h> - -#include "pugl_internal.h" - -#define SOFD_HAVE_X11 -#include "../sofd/libsofd.h" -#include "../sofd/libsofd.c" - -struct PuglInternalsImpl { - Display* display; - int screen; - Window win; - GLXContext ctx; - Bool doubleBuffered; -}; - -/** - Attributes for single-buffered RGBA with at least - 4 bits per color and a 16 bit depth buffer. -*/ -static int attrListSgl[] = { - GLX_RGBA, - GLX_RED_SIZE, 4, - GLX_GREEN_SIZE, 4, - GLX_BLUE_SIZE, 4, - GLX_DEPTH_SIZE, 16, - GLX_ARB_multisample, 1, - None -}; - -/** - Attributes for double-buffered RGBA with at least - 4 bits per color and a 16 bit depth buffer. -*/ -static int attrListDbl[] = { - GLX_RGBA, GLX_DOUBLEBUFFER, - GLX_RED_SIZE, 4, - GLX_GREEN_SIZE, 4, - GLX_BLUE_SIZE, 4, - GLX_DEPTH_SIZE, 16, - GLX_ARB_multisample, 1, - None -}; - -/** - Attributes for double-buffered RGBA with multi-sampling - (antialiasing) -*/ -static int attrListDblMS[] = { - GLX_RGBA, - GLX_DOUBLEBUFFER , True, - GLX_RED_SIZE , 4, - GLX_GREEN_SIZE , 4, - GLX_BLUE_SIZE , 4, - GLX_ALPHA_SIZE , 4, - GLX_DEPTH_SIZE , 16, - GLX_SAMPLE_BUFFERS , 1, - GLX_SAMPLES , 4, - None -}; - -PuglInternals* -puglInitInternals(void) -{ - return (PuglInternals*)calloc(1, sizeof(PuglInternals)); -} - -int -puglCreateWindow(PuglView* view, const char* title) -{ - PuglInternals* impl = view->impl; - - impl->display = XOpenDisplay(NULL); - impl->screen = DefaultScreen(impl->display); - impl->doubleBuffered = True; - - XVisualInfo* vi = glXChooseVisual(impl->display, impl->screen, attrListDblMS); - - if (!vi) { - vi = glXChooseVisual(impl->display, impl->screen, attrListDbl); - PUGL_LOG("multisampling (antialiasing) is not available\n"); - } - - if (!vi) { - vi = glXChooseVisual(impl->display, impl->screen, attrListSgl); - impl->doubleBuffered = False; - PUGL_LOG("singlebuffered rendering will be used, no doublebuffering available\n"); - } - - int glxMajor, glxMinor; - glXQueryVersion(impl->display, &glxMajor, &glxMinor); - PUGL_LOGF("GLX Version %d.%d\n", glxMajor, glxMinor); - - impl->ctx = glXCreateContext(impl->display, vi, 0, GL_TRUE); - - Window xParent = view->parent - ? (Window)view->parent - : RootWindow(impl->display, impl->screen); - - Colormap cmap = XCreateColormap( - impl->display, xParent, vi->visual, AllocNone); - - XSetWindowAttributes attr; - memset(&attr, 0, sizeof(XSetWindowAttributes)); - attr.colormap = cmap; - attr.border_pixel = 0; - - attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask - | ButtonPressMask | ButtonReleaseMask -#ifdef PUGL_GRAB_FOCUS - | EnterWindowMask -#endif - | PointerMotionMask | StructureNotifyMask; - - impl->win = XCreateWindow( - impl->display, xParent, - 0, 0, view->width, view->height, 0, vi->depth, InputOutput, vi->visual, - CWBorderPixel | CWColormap | CWEventMask, &attr); - - XSizeHints sizeHints; - memset(&sizeHints, 0, sizeof(sizeHints)); - if (!view->resizable) { - sizeHints.flags = PMinSize|PMaxSize; - sizeHints.min_width = view->width; - sizeHints.min_height = view->height; - sizeHints.max_width = view->width; - sizeHints.max_height = view->height; - XSetNormalHints(impl->display, impl->win, &sizeHints); - } - - if (title) { - XStoreName(impl->display, impl->win, title); - } - - if (!view->parent) { - Atom wmDelete = XInternAtom(impl->display, "WM_DELETE_WINDOW", True); - XSetWMProtocols(impl->display, impl->win, &wmDelete, 1); - } - - if (glXIsDirect(impl->display, impl->ctx)) { - PUGL_LOG("DRI enabled (to disable, set LIBGL_ALWAYS_INDIRECT=1\n"); - } else { - PUGL_LOG("No DRI available\n"); - } - - XFree(vi); - - glXMakeCurrent(view->impl->display, view->impl->win, view->impl->ctx); - - return 0; -} - -void -puglShowWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - XMapRaised(impl->display, impl->win); -} - -void -puglHideWindow(PuglView* view) -{ - PuglInternals* impl = view->impl; - - XUnmapWindow(impl->display, impl->win); -} - -void -puglDestroy(PuglView* view) -{ - if (!view) { - return; - } - - x_fib_close(view->impl->display); - - glXDestroyContext(view->impl->display, view->impl->ctx); - XDestroyWindow(view->impl->display, view->impl->win); - XCloseDisplay(view->impl->display); - free(view->impl); - free(view); -} - -static void -puglReshape(PuglView* view, int width, int height) -{ - glXMakeCurrent(view->impl->display, view->impl->win, view->impl->ctx); - - if (view->reshapeFunc) { - view->reshapeFunc(view, width, height); - } else { - puglDefaultReshape(view, width, height); - } - - view->width = width; - view->height = height; -} - -static void -puglDisplay(PuglView* view) -{ - glXMakeCurrent(view->impl->display, view->impl->win, view->impl->ctx); - - view->redisplay = false; - - if (view->displayFunc) { - view->displayFunc(view); - } - - glFlush(); - - if (view->impl->doubleBuffered) { - glXSwapBuffers(view->impl->display, view->impl->win); - } -} - -static PuglKey -keySymToSpecial(KeySym sym) -{ - switch (sym) { - case XK_F1: return PUGL_KEY_F1; - case XK_F2: return PUGL_KEY_F2; - case XK_F3: return PUGL_KEY_F3; - case XK_F4: return PUGL_KEY_F4; - case XK_F5: return PUGL_KEY_F5; - case XK_F6: return PUGL_KEY_F6; - case XK_F7: return PUGL_KEY_F7; - case XK_F8: return PUGL_KEY_F8; - case XK_F9: return PUGL_KEY_F9; - case XK_F10: return PUGL_KEY_F10; - case XK_F11: return PUGL_KEY_F11; - case XK_F12: return PUGL_KEY_F12; - case XK_Left: return PUGL_KEY_LEFT; - case XK_Up: return PUGL_KEY_UP; - case XK_Right: return PUGL_KEY_RIGHT; - case XK_Down: return PUGL_KEY_DOWN; - case XK_Page_Up: return PUGL_KEY_PAGE_UP; - case XK_Page_Down: return PUGL_KEY_PAGE_DOWN; - case XK_Home: return PUGL_KEY_HOME; - case XK_End: return PUGL_KEY_END; - case XK_Insert: return PUGL_KEY_INSERT; - case XK_Shift_L: return PUGL_KEY_SHIFT; - case XK_Shift_R: return PUGL_KEY_SHIFT; - case XK_Control_L: return PUGL_KEY_CTRL; - case XK_Control_R: return PUGL_KEY_CTRL; - case XK_Alt_L: return PUGL_KEY_ALT; - case XK_Alt_R: return PUGL_KEY_ALT; - case XK_Super_L: return PUGL_KEY_SUPER; - case XK_Super_R: return PUGL_KEY_SUPER; - } - return (PuglKey)0; -} - -static void -setModifiers(PuglView* view, unsigned xstate, unsigned xtime) -{ - view->event_timestamp_ms = xtime; - - view->mods = 0; - view->mods |= (xstate & ShiftMask) ? PUGL_MOD_SHIFT : 0; - view->mods |= (xstate & ControlMask) ? PUGL_MOD_CTRL : 0; - view->mods |= (xstate & Mod1Mask) ? PUGL_MOD_ALT : 0; - view->mods |= (xstate & Mod4Mask) ? PUGL_MOD_SUPER : 0; -} - -static void -dispatchKey(PuglView* view, XEvent* event, bool press) -{ - KeySym sym; - char str[5]; - const int n = XLookupString(&event->xkey, str, 4, &sym, NULL); - - if (sym == XK_Escape && view->closeFunc && !press && !view->parent) { - view->closeFunc(view); - view->redisplay = false; - return; - } - if (n == 0) { - return; - } - if (n > 1) { - fprintf(stderr, "warning: Unsupported multi-byte key %X\n", (int)sym); - return; - } - - const PuglKey special = keySymToSpecial(sym); - if (special && view->specialFunc) { - view->specialFunc(view, press, special); - } else if (!special && view->keyboardFunc) { - view->keyboardFunc(view, press, str[0]); - } -} - -PuglStatus -puglProcessEvents(PuglView* view) -{ - XEvent event; - while (XPending(view->impl->display) > 0) { - XNextEvent(view->impl->display, &event); - - if (x_fib_handle_events(view->impl->display, &event)) { - const int status = x_fib_status(); - - if (status > 0) { - char* const filename = x_fib_filename(); - x_fib_close(view->impl->display); - if (view->fileSelectedFunc) { - view->fileSelectedFunc(view, filename); - } - free(filename); - } else if (status < 0) { - x_fib_close(view->impl->display); - if (view->fileSelectedFunc) { - view->fileSelectedFunc(view, NULL); - } - } - break; - } - - if (event.xany.window != view->impl->win) { - continue; - } - - switch (event.type) { - case MapNotify: - puglReshape(view, view->width, view->height); - break; - case ConfigureNotify: - if ((event.xconfigure.width != view->width) || - (event.xconfigure.height != view->height)) { - puglReshape(view, - event.xconfigure.width, - event.xconfigure.height); - } - break; - case Expose: - if (event.xexpose.count != 0) { - break; - } - puglDisplay(view); - break; - case MotionNotify: - setModifiers(view, event.xmotion.state, event.xmotion.time); - if (view->motionFunc) { - view->motionFunc(view, event.xmotion.x, event.xmotion.y); - } - break; - case ButtonPress: - setModifiers(view, event.xbutton.state, event.xbutton.time); - if (event.xbutton.button >= 4 && event.xbutton.button <= 7) { - if (view->scrollFunc) { - float dx = 0, dy = 0; - switch (event.xbutton.button) { - case 4: dy = 1.0f; break; - case 5: dy = -1.0f; break; - case 6: dx = -1.0f; break; - case 7: dx = 1.0f; break; - } - view->scrollFunc(view, event.xbutton.x, event.xbutton.y, dx, dy); - } - break; - } - // nobreak - case ButtonRelease: - setModifiers(view, event.xbutton.state, event.xbutton.time); - if (view->mouseFunc && - (event.xbutton.button < 4 || event.xbutton.button > 7)) { - view->mouseFunc(view, - event.xbutton.button, event.type == ButtonPress, - event.xbutton.x, event.xbutton.y); - } - break; - case KeyPress: - setModifiers(view, event.xkey.state, event.xkey.time); - dispatchKey(view, &event, true); - break; - case KeyRelease: { - setModifiers(view, event.xkey.state, event.xkey.time); - bool repeated = false; - if (view->ignoreKeyRepeat && - XEventsQueued(view->impl->display, QueuedAfterReading)) { - XEvent next; - XPeekEvent(view->impl->display, &next); - if (next.type == KeyPress && - next.xkey.time == event.xkey.time && - next.xkey.keycode == event.xkey.keycode) { - XNextEvent(view->impl->display, &event); - repeated = true; - } - } - if (!repeated) { - dispatchKey(view, &event, false); - } - } break; - case ClientMessage: { - char* type = XGetAtomName(view->impl->display, - event.xclient.message_type); - if (!strcmp(type, "WM_PROTOCOLS")) { - if (view->closeFunc) { - view->closeFunc(view); - view->redisplay = false; - } - } - XFree(type); - } break; -#ifdef PUGL_GRAB_FOCUS - case EnterNotify: - XSetInputFocus(view->impl->display, view->impl->win, RevertToPointerRoot, CurrentTime); - break; -#endif - default: - break; - } - } - - if (view->redisplay) { - puglDisplay(view); - } - - return PUGL_SUCCESS; -} - -void -puglPostRedisplay(PuglView* view) -{ - view->redisplay = true; -} - -PuglNativeWindow -puglGetNativeWindow(PuglView* view) -{ - return view->impl->win; -} diff --git a/libs/dgl/src/sofd/libsofd.c b/libs/dgl/src/sofd/libsofd.c deleted file mode 100644 index bcca9f7..0000000 --- a/libs/dgl/src/sofd/libsofd.c +++ /dev/null @@ -1,2431 +0,0 @@ -/* libSOFD - Simple Open File Dialog [for X11 without toolkit] - * - * Copyright (C) 2014 Robin Gareus <robin@gareus.org> - * - * 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. - */ - -/* Test and example: - * gcc -Wall -D SOFD_TEST -g -o sofd libsofd.c -lX11 - * - * public API documentation and example code at the bottom of this file - * - * This small lib may one day include openGL rendering and - * wayland window support, but not today. Today we celebrate - * 30 years of X11. - */ - -#ifdef SOFD_TEST -#define SOFD_HAVE_X11 -#include "libsofd.h" -#endif - -#include <stdio.h> -#include <stdint.h> -#include <string.h> -#include <stdlib.h> -#include <unistd.h> -#include <libgen.h> -#include <time.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <assert.h> - -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wnarrowing" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wnarrowing" -#endif - -// shared 'recently used' implementation -// sadly, xbel does not qualify as simple. -// hence we use a simple format alike the -// gtk-bookmark list (one file per line) - -#define MAX_RECENT_ENTRIES 24 -#define MAX_RECENT_AGE (15552000) // 180 days (in sec) - -typedef struct { - char path[1024]; - time_t atime; -} FibRecentFile; - -static FibRecentFile *_recentlist = NULL; -static unsigned int _recentcnt = 0; -static uint8_t _recentlock = 0; - -static int fib_isxdigit (const char x) { - if ( - (x >= '0' && x <= '9') - || - (x >= 'a' && x <= 'f') - || - (x >= 'A' && x <= 'F') - ) return 1; - return 0; -} - -static void decode_3986 (char *str) { - int len = strlen (str); - int idx = 0; - while (idx + 2 < len) { - char *in = &str[idx]; - if (('%' == *in) && fib_isxdigit (in[1]) && fib_isxdigit (in[2])) { - char hexstr[3]; - hexstr[0] = in[1]; - hexstr[1] = in[2]; - hexstr[2] = 0; - long hex = strtol (hexstr, NULL, 16); - *in = hex; - memmove (&str[idx+1], &str[idx + 3], len - idx - 2); - len -= 2; - } - ++idx; - } -} - -static char *encode_3986 (const char *str) { - size_t alloc, newlen; - char *ns = NULL; - unsigned char in; - size_t i = 0; - size_t length; - - if (!str) return strdup (""); - - alloc = strlen (str) + 1; - newlen = alloc; - - ns = (char*) malloc (alloc); - - length = alloc; - while (--length) { - in = *str; - - switch (in) { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case 'a': case 'b': case 'c': case 'd': case 'e': - case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': - case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': - case 'A': case 'B': case 'C': case 'D': case 'E': - case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': - case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': - case '_': case '~': case '.': case '-': - case '/': case ',': // XXX not in RFC3986 - ns[i++] = in; - break; - default: - newlen += 2; /* this'll become a %XX */ - if (newlen > alloc) { - alloc *= 2; - ns = (char*) realloc (ns, alloc); - } - snprintf (&ns[i], 4, "%%%02X", in); - i += 3; - break; - } - ++str; - } - ns[i] = 0; - return ns; -} - -void x_fib_free_recent () { - free (_recentlist); - _recentlist = NULL; - _recentcnt = 0; -} - -static int cmp_recent (const void *p1, const void *p2) { - FibRecentFile *a = (FibRecentFile*) p1; - FibRecentFile *b = (FibRecentFile*) p2; - if (a->atime == b->atime) return 0; - return a->atime < b->atime; -} - -int x_fib_add_recent (const char *path, time_t atime) { - unsigned int i; - struct stat fs; - if (_recentlock) { return -1; } - if (access (path, R_OK)) { - return -1; - } - if (stat (path, &fs)) { - return -1; - } - if (!S_ISREG (fs.st_mode)) { - return -1; - } - if (atime == 0) atime = time (NULL); - if (MAX_RECENT_AGE > 0 && atime + MAX_RECENT_AGE < time (NULL)) { - return -1; - } - - for (i = 0; i < _recentcnt; ++i) { - if (!strcmp (_recentlist[i].path, path)) { - if (_recentlist[i].atime < atime) { - _recentlist[i].atime = atime; - } - qsort (_recentlist, _recentcnt, sizeof(FibRecentFile), cmp_recent); - return _recentcnt; - } - } - _recentlist = (FibRecentFile*)realloc (_recentlist, (_recentcnt + 1) * sizeof(FibRecentFile)); - _recentlist[_recentcnt].atime = atime; - strcpy (_recentlist[_recentcnt].path, path); - qsort (_recentlist, _recentcnt + 1, sizeof(FibRecentFile), cmp_recent); - - if (_recentcnt >= MAX_RECENT_ENTRIES) { - return (_recentcnt); - } - return (++_recentcnt); -} - -#ifdef PATHSEP -#undef PATHSEP -#endif - -#ifdef PLATFORM_WINDOWS -#define DIRSEP '\\' -#else -#define DIRSEP '/' -#endif - -static void mkpath(const char *dir) { - char tmp[1024]; - char *p; - size_t len; - - snprintf (tmp, sizeof(tmp), "%s", dir); - len = strlen(tmp); - if (tmp[len - 1] == '/') - tmp[len - 1] = 0; - for (p = tmp + 1; *p; ++p) - if(*p == DIRSEP) { - *p = 0; -#ifdef PLATFORM_WINDOWS - mkdir(tmp); -#else - mkdir(tmp, 0755); -#endif - *p = DIRSEP; - } -#ifdef PLATFORM_WINDOWS - mkdir(tmp); -#else - mkdir(tmp, 0755); -#endif -} - -int x_fib_save_recent (const char *fn) { - if (_recentlock) { return -1; } - if (!fn) { return -1; } - if (_recentcnt < 1 || !_recentlist) { return -1; } - unsigned int i; - char *dn = strdup (fn); - mkpath (dirname (dn)); - free (dn); - - FILE *rf = fopen (fn, "w"); - if (!rf) return -1; - - qsort (_recentlist, _recentcnt, sizeof(FibRecentFile), cmp_recent); - for (i = 0; i < _recentcnt; ++i) { - char *n = encode_3986 (_recentlist[i].path); - fprintf (rf, "%s %lu\n", n, _recentlist[i].atime); - free (n); - } - fclose (rf); - return 0; -} - -int x_fib_load_recent (const char *fn) { - char tmp[1024]; - if (_recentlock) { return -1; } - if (!fn) { return -1; } - x_fib_free_recent (); - if (access (fn, R_OK)) { - return -1; - } - FILE *rf = fopen (fn, "r"); - if (!rf) return -1; - while (fgets (tmp, sizeof(tmp), rf) - && strlen (tmp) > 1 - && strlen (tmp) < sizeof(tmp)) - { - char *s; - tmp[strlen (tmp) - 1] = '\0'; // strip newline - if (!(s = strchr (tmp, ' '))) { // find name <> atime sep - continue; - } - *s = '\0'; - time_t t = atol (++s); - decode_3986 (tmp); - x_fib_add_recent (tmp, t); - } - fclose (rf); - return 0; -} - -unsigned int x_fib_recent_count () { - return _recentcnt; -} - -const char *x_fib_recent_at (unsigned int i) { - if (i >= _recentcnt) - return NULL; - return _recentlist[i].path; -} - -#ifdef PLATFORM_WINDOWS -#define PATHSEP "\\" -#else -#define PATHSEP "/" -#endif - -const char *x_fib_recent_file(const char *appname) { - static char recent_file[1024]; - assert(!strchr(appname, '/')); - const char *xdg = getenv("XDG_DATA_HOME"); - if (xdg && (strlen(xdg) + strlen(appname) + 10) < sizeof(recent_file)) { - sprintf(recent_file, "%s" PATHSEP "%s" PATHSEP "recent", xdg, appname); - return recent_file; - } -#ifdef PLATFORM_WINDOWS - const char * homedrive = getenv("HOMEDRIVE"); - const char * homepath = getenv("HOMEPATH"); - if (homedrive && homepath && (strlen(homedrive) + strlen(homepath) + strlen(appname) + 29) < PATH_MAX) { - sprintf(recent_file, "%s%s" PATHSEP "Application Data" PATHSEP "%s" PATHSEP "recent.txt", homedrive, homepath, appname); - return recent_file; - } -#elif defined PLATFORM_OSX - const char *home = getenv("HOME"); - if (home && (strlen(home) + strlen(appname) + 29) < sizeof(recent_file)) { - sprintf(recent_file, "%s/Library/Preferences/%s/recent", home, appname); - return recent_file; - } -#else - const char *home = getenv("HOME"); - if (home && (strlen(home) + strlen(appname) + 22) < sizeof(recent_file)) { - sprintf(recent_file, "%s/.local/share/%s/recent", home, appname); - return recent_file; - } -#endif - return NULL; -} - -#ifdef SOFD_HAVE_X11 -#include <mntent.h> -#include <dirent.h> - -#include <X11/Xlib.h> -#include <X11/Xatom.h> -#include <X11/Xutil.h> -#include <X11/keysym.h> -#include <X11/Xos.h> - -#ifndef MIN -#define MIN(A,B) ( (A) < (B) ? (A) : (B) ) -#endif - -#ifndef MAX -#define MAX(A,B) ( (A) < (B) ? (B) : (A) ) -#endif - -static Window _fib_win = 0; -static GC _fib_gc = 0; -static XColor _c_gray0, _c_gray1, _c_gray2, _c_gray3, _c_gray4, _c_gray5, _c_gray6; -static Font _fibfont = 0; -static Pixmap _pixbuffer = None; - -static int _fib_width = 100; -static int _fib_height = 100; -static int _btn_w = 0; -static int _btn_span = 0; - -static int _fib_font_height = 0; -static int _fib_dir_indent = 0; -static int _fib_spc_norm = 0; -static int _fib_font_ascent = 0; -static int _fib_font_vsep = 0; -static int _fib_font_size_width = 0; -static int _fib_font_time_width = 0; -static int _fib_place_width = 0; - -static int _scrl_f = 0; -static int _scrl_y0 = -1; -static int _scrl_y1 = -1; -static int _scrl_my = -1; -static int _scrl_mf = -1; -static int _view_p = -1; - -static int _fsel = -1; -static int _hov_b = -1; -static int _hov_f = -1; -static int _hov_p = -1; -static int _hov_h = -1; -static int _hov_l = -1; -static int _hov_s = -1; -static int _sort = 0; -static int _columns = 0; -static int _fib_filter_fn = 1; -static int _fib_hidden_fn = 0; -static int _fib_show_places = 0; - -static uint8_t _fib_mapped = 0; -static uint8_t _fib_resized = 0; -static unsigned long _dblclk = 0; - -static int _status = -2; -static char _rv_open[1024] = ""; - -static char _fib_cfg_custom_places[1024] = ""; -static char _fib_cfg_custom_font[256] = ""; -static char _fib_cfg_title[128] = "xjadeo - Open Video File"; - -typedef struct { - char name[256]; - int x0; - int xw; -} FibPathButton; - -typedef struct { - char name[256]; - char strtime[32]; - char strsize[32]; - int ssizew; - off_t size; - time_t mtime; - uint8_t flags; // 2: selected, 4: isdir 8: recent-entry - FibRecentFile *rfp; -} FibFileEntry; - -typedef struct { - char text[24]; - uint8_t flags; // 2: selected, 4: toggle, 8 disable - int x0; - int tw; - int xw; - void (*callback)(Display*); -} FibButton; - -typedef struct { - char name[256]; - char path[1024]; - uint8_t flags; // 1: hover, 2: selected, 4:add sep -} FibPlace; - -static char _cur_path[1024] = ""; -static FibFileEntry *_dirlist = NULL; -static FibPathButton *_pathbtn = NULL; -static FibPlace *_placelist = NULL; -static int _dircount = 0; -static int _pathparts = 0; -static int _placecnt = 0; - -static FibButton _btn_ok; -static FibButton _btn_cancel; -static FibButton _btn_filter; -static FibButton _btn_places; -static FibButton _btn_hidden; -static FibButton *_btns[] = {&_btn_places, &_btn_filter, &_btn_hidden, &_btn_cancel, &_btn_ok}; - -static int (*_fib_filter_function)(const char *filename); - -/* hardcoded layout */ -#define DSEP 6 // px; horiz space beween elements, also l+r margin for file-list -#define PSEP 4 // px; horiz space beween paths -#define FILECOLUMN (17 * _fib_dir_indent) //px; min width of file-column -#define LISTTOP 2.7 //em; top of the file-browser list -#define LISTBOT 4.75 //em; bottom of the file-browers list -#define BTNBTMMARGIN 0.75 //em; height/margin of the button row -#define BTNPADDING 2 // px - only used for open/cancel buttons -#define SCROLLBARW (3 + (_fib_spc_norm&~1)) //px; - should be SCROLLBARW = (N * 2 + 3) -#define SCROLLBOXH 10 //px; arrow box top+bottom -#define PLACESW _fib_place_width //px; -#define PLACESWMAX (15 *_fib_spc_norm) //px; -#define PATHBTNTOP _fib_font_vsep //px; offset by (_fib_font_ascent); -#define FAREAMRGB 3 //px; base L+R margin -#define FAREAMRGR (FAREAMRGB + 1) //px; right margin of file-area + 1 (line width) -#define FAREAMRGL (_fib_show_places ? PLACESW + FAREAMRGB : FAREAMRGB) //px; left margin of file-area -#define TEXTSEP 4 //px; -#define FAREATEXTL (FAREAMRGL + TEXTSEP) //px; filename text-left FAREAMRGL + TEXTSEP -#define SORTBTNOFF -10 //px; - -#define DBLCLKTME 400 //msec; double click time -#define DRAW_OUTLINE -#define DOUBLE_BUFFER - -static int query_font_geometry (Display *dpy, GC gc, const char *txt, int *w, int *h, int *a, int *d) { - XCharStruct text_structure; - int font_direction, font_ascent, font_descent; - XFontStruct *fontinfo = XQueryFont (dpy, XGContextFromGC (gc)); - - if (!fontinfo) { return -1; } - XTextExtents (fontinfo, txt, strlen (txt), &font_direction, &font_ascent, &font_descent, &text_structure); - if (w) *w = XTextWidth (fontinfo, txt, strlen (txt)); - if (h) *h = text_structure.ascent + text_structure.descent; - if (a) *a = text_structure.ascent; - if (d) *d = text_structure.descent; - XFreeFontInfo (NULL, fontinfo, 1); - return 0; -} - -static void VDrawRectangle (Display *dpy, Drawable d, GC gc, int x, int y, unsigned int w, unsigned int h) { - const unsigned long blackColor = BlackPixel (dpy, DefaultScreen (dpy)); -#ifdef DRAW_OUTLINE - XSetForeground (dpy, gc, _c_gray5.pixel); - XDrawLine (dpy, d, gc, x + 1, y + h, x + w, y + h); - XDrawLine (dpy, d, gc, x + w, y + 1, x + w, y + h); - - XSetForeground (dpy, gc, blackColor); - XDrawLine (dpy, d, gc, x + 1, y, x + w, y); - XDrawLine (dpy, d, gc, x, y + 1, x, y + h); -#else - XSetForeground (dpy, _fib_gc, blackColor); - XDrawRectangle (dpy, d, gc, x, y, w, h); -#endif -} - -static void fib_expose (Display *dpy, Window realwin) { - int i; - XID win; - const unsigned long whiteColor = WhitePixel (dpy, DefaultScreen (dpy)); - const unsigned long blackColor = BlackPixel (dpy, DefaultScreen (dpy)); - if (!_fib_mapped) return; - - if (_fib_resized -#ifdef DOUBLE_BUFFER - || !_pixbuffer -#endif - ) - { -#ifdef DOUBLE_BUFFER - unsigned int w = 0, h = 0; - if (_pixbuffer != None) { - Window ignored_w; - int ignored_i; - unsigned int ignored_u; - XGetGeometry(dpy, _pixbuffer, &ignored_w, &ignored_i, &ignored_i, &w, &h, &ignored_u, &ignored_u); - if (_fib_width != (int)w || _fib_height != (int)h) { - XFreePixmap (dpy, _pixbuffer); - _pixbuffer = None; - } - } - if (_pixbuffer == None) { - XWindowAttributes wa; - XGetWindowAttributes (dpy, realwin, &wa); - _pixbuffer = XCreatePixmap (dpy, realwin, _fib_width, _fib_height, wa.depth); - } -#endif - if (_pixbuffer != None) { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - XFillRectangle (dpy, _pixbuffer, _fib_gc, 0, 0, _fib_width, _fib_height); - } else { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - XFillRectangle (dpy, realwin, _fib_gc, 0, 0, _fib_width, _fib_height); - } - _fib_resized = 0; - } - - if (_pixbuffer == None) { - win = realwin; - } else { - win = _pixbuffer; - } - - // Top Row: dirs and up navigation - - int ppw = 0; - int ppx = FAREAMRGB; - - for (i = _pathparts - 1; i >= 0; --i) { - ppw += _pathbtn[i].xw + PSEP; - if (ppw >= _fib_width - PSEP - _pathbtn[0].xw - FAREAMRGB) break; // XXX, first change is from "/" to "<", NOOP - } - ++i; - // border-less "<" parent/up, IFF space is limited - if (i > 0) { - if (0 == _hov_p || (_hov_p > 0 && _hov_p < _pathparts - 1)) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - } else { - XSetForeground (dpy, _fib_gc, blackColor); - } - XDrawString (dpy, win, _fib_gc, ppx, PATHBTNTOP, "<", 1); - ppx += _pathbtn[0].xw + PSEP; - if (i == _pathparts) --i; - } - - _view_p = i; - - while (i < _pathparts) { - if (i == _hov_p) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray2.pixel); - } - XFillRectangle (dpy, win, _fib_gc, - ppx + 1, PATHBTNTOP - _fib_font_ascent, - _pathbtn[i].xw - 1, _fib_font_height); - VDrawRectangle (dpy, win, _fib_gc, - ppx, PATHBTNTOP - _fib_font_ascent, - _pathbtn[i].xw, _fib_font_height); - XDrawString (dpy, win, _fib_gc, ppx + 1 + BTNPADDING, PATHBTNTOP, - _pathbtn[i].name, strlen (_pathbtn[i].name)); - _pathbtn[i].x0 = ppx; // current position - ppx += _pathbtn[i].xw + PSEP; - ++i; - } - - // middle, scroll list of file names - const int ltop = LISTTOP * _fib_font_vsep; - const int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - const int fsel_height = 4 + llen * _fib_font_vsep; - const int fsel_width = _fib_width - FAREAMRGL - FAREAMRGR - (llen < _dircount ? SCROLLBARW : 0); - const int t_x = FAREATEXTL; - int t_s = FAREATEXTL + fsel_width; - int t_t = FAREATEXTL + fsel_width; - - // check which colums can be visible - // depending on available width of window. - _columns = 0; - if (fsel_width > FILECOLUMN + _fib_font_size_width + _fib_font_time_width) { - _columns |= 2; - t_s = FAREAMRGL + fsel_width - _fib_font_time_width - TEXTSEP; - } - if (fsel_width > FILECOLUMN + _fib_font_size_width) { - _columns |= 1; - t_t = t_s - _fib_font_size_width - TEXTSEP; - } - - int fstop = _scrl_f; // first entry in scroll position - const int ttop = ltop - _fib_font_height + _fib_font_ascent; - - if (fstop > 0 && fstop + llen > _dircount) { - fstop = MAX (0, _dircount - llen); - _scrl_f = fstop; - } - - // list header - XSetForeground (dpy, _fib_gc, _c_gray3.pixel); - XFillRectangle (dpy, win, _fib_gc, FAREAMRGL, ltop - _fib_font_vsep, fsel_width, _fib_font_vsep); - - // draw background of file list - XSetForeground (dpy, _fib_gc, _c_gray2.pixel); - XFillRectangle (dpy, win, _fib_gc, FAREAMRGL, ltop, fsel_width, fsel_height); - -#ifdef DRAW_OUTLINE - VDrawRectangle (dpy, win, _fib_gc, FAREAMRGL, ltop - _fib_font_vsep -1, _fib_width - FAREAMRGL - FAREAMRGR, fsel_height + _fib_font_vsep + 1); -#endif - - switch (_hov_h) { - case 1: - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - XFillRectangle (dpy, win, _fib_gc, t_x + _fib_dir_indent - TEXTSEP + 1, ltop - _fib_font_vsep, t_t - t_x - _fib_dir_indent - 1, _fib_font_vsep); - break; - case 2: - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - XFillRectangle (dpy, win, _fib_gc, t_t - TEXTSEP + 1, ltop - _fib_font_vsep, _fib_font_size_width + TEXTSEP - 1, _fib_font_vsep); - break; - case 3: - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - XFillRectangle (dpy, win, _fib_gc, t_s - TEXTSEP + 1, ltop - _fib_font_vsep, TEXTSEP + TEXTSEP + _fib_font_time_width - 1, _fib_font_vsep); - break; - default: - break; - } - - // column headings and sort order - int arp = MAX (2, _fib_font_height / 5); // arrow scale - const int trioff = _fib_font_height - _fib_font_ascent - arp + 1; - XPoint ptri[4] = { {0, ttop - trioff }, {arp, -arp - arp - 1}, {-arp - arp, 0}, {arp, arp + arp + 1}}; - if (_sort & 1) { - ptri[0].y = ttop -arp - arp - 1; - ptri[1].y *= -1; - ptri[3].y *= -1; - } - switch (_sort) { - case 0: - case 1: - ptri[0].x = t_t + SORTBTNOFF + 2 - arp; - XSetForeground (dpy, _fib_gc, _c_gray6.pixel); - XFillPolygon (dpy, win, _fib_gc, ptri, 3, Convex, CoordModePrevious); - XDrawLines (dpy, win, _fib_gc, ptri, 4, CoordModePrevious); - break; - case 2: - case 3: - if (_columns & 1) { - ptri[0].x = t_s + SORTBTNOFF + 2 - arp; - XSetForeground (dpy, _fib_gc, _c_gray6.pixel); - XFillPolygon (dpy, win, _fib_gc, ptri, 3, Convex, CoordModePrevious); - XDrawLines (dpy, win, _fib_gc, ptri, 4, CoordModePrevious); - } - break; - case 4: - case 5: - if (_columns & 2) { - ptri[0].x = FAREATEXTL + fsel_width + SORTBTNOFF + 2 - arp; - XSetForeground (dpy, _fib_gc, _c_gray6.pixel); - XFillPolygon (dpy, win, _fib_gc, ptri, 3, Convex, CoordModePrevious); - XDrawLines (dpy, win, _fib_gc, ptri, 4, CoordModePrevious); - } - break; - } - -#if 0 // bottom header bottom border - XSetForeground (dpy, _fib_gc, _c_gray5.pixel); - XSetLineAttributes (dpy, _fib_gc, 1, LineOnOffDash, CapButt, JoinMiter); - XDrawLine (dpy, win, _fib_gc, - FAREAMRGL + 1, ltop, - FAREAMRGL + fsel_width, ltop); - XSetLineAttributes (dpy, _fib_gc, 1, LineSolid, CapButt, JoinMiter); -#endif - - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - XDrawLine (dpy, win, _fib_gc, - t_x + _fib_dir_indent - TEXTSEP, ltop - _fib_font_vsep + 3, - t_x + _fib_dir_indent - TEXTSEP, ltop - 3); - - XSetForeground (dpy, _fib_gc, blackColor); - XDrawString (dpy, win, _fib_gc, t_x + _fib_dir_indent, ttop, "Name", 4); - - if (_columns & 1) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - XDrawLine (dpy, win, _fib_gc, - t_t - TEXTSEP, ltop - _fib_font_vsep + 3, - t_t - TEXTSEP, ltop - 3); - XSetForeground (dpy, _fib_gc, blackColor); - XDrawString (dpy, win, _fib_gc, t_t, ttop, "Size", 4); - } - - if (_columns & 2) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - XDrawLine (dpy, win, _fib_gc, - t_s - TEXTSEP, ltop - _fib_font_vsep + 3, - t_s - TEXTSEP, ltop - 3); - XSetForeground (dpy, _fib_gc, blackColor); - if (_pathparts > 0) - XDrawString (dpy, win, _fib_gc, t_s, ttop, "Last Modified", 13); - else - XDrawString (dpy, win, _fib_gc, t_s, ttop, "Last Used", 9); - } - - // scrollbar sep - if (llen < _dircount) { - const int sx0 = _fib_width - SCROLLBARW - FAREAMRGR; - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - XDrawLine (dpy, win, _fib_gc, - sx0 - 1, ltop - _fib_font_vsep, -#ifdef DRAW_OUTLINE - sx0 - 1, ltop + fsel_height -#else - sx0 - 1, ltop - 1 -#endif - ); - } - - // clip area for file-name - XRectangle clp = {FAREAMRGL + 1, ltop, t_t - FAREAMRGL - TEXTSEP - TEXTSEP - 1, fsel_height}; - - // list files in view - for (i = 0; i < llen; ++i) { - const int j = i + fstop; - if (j >= _dircount) break; - - const int t_y = ltop + (i+1) * _fib_font_vsep - 4; - - XSetForeground (dpy, _fib_gc, blackColor); - if (_dirlist[j].flags & 2) { - XSetForeground (dpy, _fib_gc, blackColor); - XFillRectangle (dpy, win, _fib_gc, - FAREAMRGL, t_y - _fib_font_ascent, fsel_width, _fib_font_height); - XSetForeground (dpy, _fib_gc, whiteColor); - } - if (_hov_f == j && !(_dirlist[j].flags & 2)) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - } - if (_dirlist[j].flags & 4) { - XDrawString (dpy, win, _fib_gc, t_x, t_y, "D", 1); - } - XSetClipRectangles (dpy, _fib_gc, 0, 0, &clp, 1, Unsorted); - XDrawString (dpy, win, _fib_gc, - t_x + _fib_dir_indent, t_y, - _dirlist[j].name, strlen (_dirlist[j].name)); - XSetClipMask (dpy, _fib_gc, None); - - if (_columns & 1) // right-aligned 'size' - XDrawString (dpy, win, _fib_gc, - t_s - TEXTSEP - 2 - _dirlist[j].ssizew, t_y, - _dirlist[j].strsize, strlen (_dirlist[j].strsize)); - if (_columns & 2) - XDrawString (dpy, win, _fib_gc, - t_s, t_y, - _dirlist[j].strtime, strlen (_dirlist[j].strtime)); - } - - // scrollbar - if (llen < _dircount) { - float sl = (fsel_height + _fib_font_vsep - (SCROLLBOXH + SCROLLBOXH)) / (float) _dircount; - sl = MAX ((8. / llen), sl); // 8px min height of scroller - const int sy1 = llen * sl; - const float mx = (fsel_height + _fib_font_vsep - (SCROLLBOXH + SCROLLBOXH) - sy1) / (float)(_dircount - llen); - const int sy0 = fstop * mx; - const int sx0 = _fib_width - SCROLLBARW - FAREAMRGR; - const int stop = ltop - _fib_font_vsep; - - _scrl_y0 = stop + SCROLLBOXH + sy0; - _scrl_y1 = _scrl_y0 + sy1; - - assert (fstop + llen <= _dircount); - // scroll-bar background - XSetForeground (dpy, _fib_gc, _c_gray3.pixel); - XFillRectangle (dpy, win, _fib_gc, sx0, stop, SCROLLBARW, fsel_height + _fib_font_vsep); - - // scroller - if (_hov_s == 0) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - } - XFillRectangle (dpy, win, _fib_gc, sx0 + 1, stop + SCROLLBOXH + sy0, SCROLLBARW - 2, sy1); - - int scrw = (SCROLLBARW -3) / 2; - // arrows top and bottom - if (_hov_s == 1) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - } - XPoint ptst[4] = { {sx0 + 1, stop + 8}, {scrw, -7}, {scrw, 7}, {-2 * scrw, 0}}; - XFillPolygon (dpy, win, _fib_gc, ptst, 3, Convex, CoordModePrevious); - XDrawLines (dpy, win, _fib_gc, ptst, 4, CoordModePrevious); - - if (_hov_s == 2) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - } - XPoint ptsb[4] = { {sx0 + 1, ltop + fsel_height - 9}, {2*scrw, 0}, {-scrw, 7}, {-scrw, -7}}; - XFillPolygon (dpy, win, _fib_gc, ptsb, 3, Convex, CoordModePrevious); - XDrawLines (dpy, win, _fib_gc, ptsb, 4, CoordModePrevious); - } else { - _scrl_y0 = _scrl_y1 = -1; - } - - if (_fib_show_places) { - assert (_placecnt > 0); - - // heading - XSetForeground (dpy, _fib_gc, _c_gray3.pixel); - XFillRectangle (dpy, win, _fib_gc, FAREAMRGB, ltop - _fib_font_vsep, PLACESW - TEXTSEP, _fib_font_vsep); - - // body - XSetForeground (dpy, _fib_gc, _c_gray2.pixel); - XFillRectangle (dpy, win, _fib_gc, FAREAMRGB, ltop, PLACESW - TEXTSEP, fsel_height); - -#ifdef DRAW_OUTLINE - VDrawRectangle (dpy, win, _fib_gc, FAREAMRGB, ltop - _fib_font_vsep -1, PLACESW - TEXTSEP, fsel_height + _fib_font_vsep + 1); -#endif - - XSetForeground (dpy, _fib_gc, blackColor); - XDrawString (dpy, win, _fib_gc, FAREAMRGB + TEXTSEP, ttop, "Places", 6); - - XRectangle pclip = {FAREAMRGB + 1, ltop, PLACESW - TEXTSEP -1, fsel_height}; - XSetClipRectangles (dpy, _fib_gc, 0, 0, &pclip, 1, Unsorted); - const int plx = FAREAMRGB + TEXTSEP; - for (i = 0; i < llen && i < _placecnt; ++i) { - const int ply = ltop + (i+1) * _fib_font_vsep - 4; - if (i == _hov_l) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - } else { - XSetForeground (dpy, _fib_gc, blackColor); - } - XDrawString (dpy, win, _fib_gc, - plx, ply, - _placelist[i].name, strlen (_placelist[i].name)); - if (_placelist[i].flags & 4) { - XSetForeground (dpy, _fib_gc, _c_gray3.pixel); - const int plly = ply - _fib_font_ascent + _fib_font_height; - const int pllx0 = FAREAMRGB; - const int pllx1 = FAREAMRGB + (PLACESW - TEXTSEP); - XDrawLine (dpy, win, _fib_gc, pllx0, plly, pllx1, plly); - } - } - XSetClipMask (dpy, _fib_gc, None); - - if (_placecnt > llen) { - const int plly = ltop + fsel_height - _fib_font_height + _fib_font_ascent; - const int pllx0 = FAREAMRGB + (PLACESW - TEXTSEP) * .75; - const int pllx1 = FAREAMRGB + (PLACESW - TEXTSEP - TEXTSEP); - - XSetForeground (dpy, _fib_gc, blackColor); - XSetLineAttributes (dpy, _fib_gc, 1, LineOnOffDash, CapButt, JoinMiter); - XDrawLine (dpy, win, _fib_gc, pllx0, plly, pllx1, plly); - XSetLineAttributes (dpy, _fib_gc, 1, LineSolid, CapButt, JoinMiter); - } - } - - // Bottom Buttons - const int numb = sizeof(_btns) / sizeof(FibButton*); - int xtra = _fib_width - _btn_span; - const int cbox = _fib_font_ascent - 2; - const int bbase = _fib_height - BTNBTMMARGIN * _fib_font_vsep - BTNPADDING; - const int cblw = cbox > 20 ? 5 : ( cbox > 9 ? 3 : 1); - - int bx = FAREAMRGB; - for (i = 0; i < numb; ++i) { - if (_btns[i]->flags & 8) { continue; } - if (_btns[i]->flags & 4) { - // checkbutton - const int cby0 = bbase - cbox + 1 + BTNPADDING; - if (i == _hov_b) { - XSetForeground (dpy, _fib_gc, _c_gray4.pixel); - } else { - XSetForeground (dpy, _fib_gc, blackColor); - } - XDrawRectangle (dpy, win, _fib_gc, - bx, cby0 - 1, cbox + 1, cbox + 1); - - if (i == _hov_b) { - XSetForeground (dpy, _fib_gc, _c_gray5.pixel); - } else { - XSetForeground (dpy, _fib_gc, blackColor); - } - XDrawString (dpy, win, _fib_gc, BTNPADDING + bx + _fib_font_ascent, 1 + bbase + BTNPADDING, - _btns[i]->text, strlen (_btns[i]->text)); - - if (i == _hov_b) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - if (_btns[i]->flags & 2) { - XSetForeground (dpy, _fib_gc, _c_gray1.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray2.pixel); - } - } - XFillRectangle (dpy, win, _fib_gc, - bx+1, cby0, cbox, cbox); - - if (_btns[i]->flags & 2) { - XSetLineAttributes (dpy, _fib_gc, cblw, LineSolid, CapRound, JoinMiter); - XSetForeground (dpy, _fib_gc, _c_gray6.pixel); - XDrawLine (dpy, win, _fib_gc, - bx + 2, cby0 + 1, - bx + cbox - 1, cby0 + cbox - 2); - XDrawLine (dpy, win, _fib_gc, - bx + cbox - 1, cby0 + 1, - bx + 2, cby0 + cbox - 2); - XSetLineAttributes (dpy, _fib_gc, 1, LineSolid, CapButt, JoinMiter); - } - } else { - if (xtra > 0) { - bx += xtra; - xtra = 0; - } - // pushbutton - - uint8_t can_hover = 1; // special case - if (_btns[i] == &_btn_ok) { - if (_fsel < 0 || _fsel >= _dircount) { - can_hover = 0; - } - } - - if (can_hover && i == _hov_b) { - XSetForeground (dpy, _fib_gc, _c_gray0.pixel); - } else { - XSetForeground (dpy, _fib_gc, _c_gray2.pixel); - } - XFillRectangle (dpy, win, _fib_gc, - bx + 1, bbase - _fib_font_ascent, - _btn_w - 1, _fib_font_height + BTNPADDING + BTNPADDING); - VDrawRectangle (dpy, win, _fib_gc, - bx, bbase - _fib_font_ascent, - _btn_w, _fib_font_height + BTNPADDING + BTNPADDING); - XDrawString (dpy, win, _fib_gc, bx + (_btn_w - _btns[i]->tw) * .5, 1 + bbase + BTNPADDING, - _btns[i]->text, strlen (_btns[i]->text)); - } - _btns[i]->x0 = bx; - bx += _btns[i]->xw + DSEP; - } - - if (_pixbuffer != None) { - XCopyArea(dpy, _pixbuffer, realwin, _fib_gc, 0, 0, _fib_width, _fib_height, 0, 0); - } - XFlush (dpy); -} - -static void fib_reset () { - _hov_p = _hov_f = _hov_h = _hov_l = -1; - _scrl_f = 0; - _fib_resized = 1; -} - -static int cmp_n_up (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - return strcmp (a->name, b->name); -} - -static int cmp_n_down (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - return strcmp (b->name, a->name); -} - -static int cmp_t_up (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - if (a->mtime == b->mtime) return 0; - return a->mtime > b->mtime ? -1 : 1; -} - -static int cmp_t_down (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - if (a->mtime == b->mtime) return 0; - return a->mtime > b->mtime ? 1 : -1; -} - -static int cmp_s_up (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && (b->flags & 4)) return 0; // dir, no size, retain order - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - if (a->size == b->size) return 0; - return a->size > b->size ? -1 : 1; -} - -static int cmp_s_down (const void *p1, const void *p2) { - FibFileEntry *a = (FibFileEntry*) p1; - FibFileEntry *b = (FibFileEntry*) p2; - if ((a->flags & 4) && (b->flags & 4)) return 0; // dir, no size, retain order - if ((a->flags & 4) && !(b->flags & 4)) return -1; - if (!(a->flags & 4) && (b->flags & 4)) return 1; - if (a->size == b->size) return 0; - return a->size > b->size ? 1 : -1; -} - -static void fmt_size (Display *dpy, FibFileEntry *f) { - if (f->size > 10995116277760) { - sprintf (f->strsize, "%.0f TB", f->size / 1099511627776.f); - } - if (f->size > 1099511627776) { - sprintf (f->strsize, "%.1f TB", f->size / 1099511627776.f); - } - else if (f->size > 10737418240) { - sprintf (f->strsize, "%.0f GB", f->size / 1073741824.f); - } - else if (f->size > 1073741824) { - sprintf (f->strsize, "%.1f GB", f->size / 1073741824.f); - } - else if (f->size > 10485760) { - sprintf (f->strsize, "%.0f MB", f->size / 1048576.f); - } - else if (f->size > 1048576) { - sprintf (f->strsize, "%.1f MB", f->size / 1048576.f); - } - else if (f->size > 10240) { - sprintf (f->strsize, "%.0f KB", f->size / 1024.f); - } - else if (f->size >= 1000) { - sprintf (f->strsize, "%.1f KB", f->size / 1024.f); - } - else { - sprintf (f->strsize, "%.0f B", f->size / 1.f); - } - int sw = 0; - query_font_geometry (dpy, _fib_gc, f->strsize, &sw, NULL, NULL, NULL); - if (sw > _fib_font_size_width) { - _fib_font_size_width = sw; - } - f->ssizew = sw; -} - -static void fmt_time (Display *dpy, FibFileEntry *f) { - struct tm *tmp; - tmp = localtime (&f->mtime); - if (!tmp) { - return; - } - strftime (f->strtime, sizeof(f->strtime), "%F %H:%M", tmp); - - int tw = 0; - query_font_geometry (dpy, _fib_gc, f->strtime, &tw, NULL, NULL, NULL); - if (tw > _fib_font_time_width) { - _fib_font_time_width = tw; - } -} - -static void fib_resort (const char * sel) { - if (_dircount < 1) { return; } - int (*sortfn)(const void *p1, const void *p2); - switch (_sort) { - case 1: sortfn = &cmp_n_down; break; - case 2: sortfn = &cmp_s_down; break; - case 3: sortfn = &cmp_s_up; break; - case 4: sortfn = &cmp_t_down; break; - case 5: sortfn = &cmp_t_up; break; - default: - sortfn = &cmp_n_up; - break; - } - qsort (_dirlist, _dircount, sizeof(_dirlist[0]), sortfn); - int i; - for (i = 0; i < _dircount && sel; ++i) { - if (!strcmp (_dirlist[i].name, sel)) { - _fsel = i; - break; - } - } -} - -static void fib_select (Display *dpy, int item) { - if (_fsel >= 0) { - _dirlist[_fsel].flags &= ~2; - } - _fsel = item; - if (_fsel >= 0 && _fsel < _dircount) { - _dirlist[_fsel].flags |= 2; - const int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - if (_fsel < _scrl_f) { - _scrl_f = _fsel; - } - else if (_fsel >= _scrl_f + llen) { - _scrl_f = 1 + _fsel - llen; - } - } else { - _fsel = -1; - } - - fib_expose (dpy, _fib_win); -} - -static inline int fib_filter (const char *name) { - if (_fib_filter_function) { - return _fib_filter_function (name); - } else { - return 1; - } -} - -static void fib_pre_opendir (Display *dpy) { - if (_dirlist) free (_dirlist); - if (_pathbtn) free (_pathbtn); - _dirlist = NULL; - _pathbtn = NULL; - _dircount = 0; - _pathparts = 0; - query_font_geometry (dpy, _fib_gc, "Size ", &_fib_font_size_width, NULL, NULL, NULL); - fib_reset (); - _fsel = -1; -} - -static void fib_post_opendir (Display *dpy, const char *sel) { - if (_dircount > 0) - _fsel = 0; // select first - else - _fsel = -1; - fib_resort (sel); - - if (_dircount > 0 && _fsel >= 0) { - fib_select (dpy, _fsel); - } else { - fib_expose (dpy, _fib_win); - } -} - -static int fib_dirlistadd (Display *dpy, const int i, const char* path, const char *name, time_t mtime) { - char tp[1024]; - struct stat fs; - if (!_fib_hidden_fn && name[0] == '.') return -1; - if (!strcmp (name, ".")) return -1; - if (!strcmp (name, "..")) return -1; - strcpy (tp, path); - strcat (tp, name); - if (access (tp, R_OK)) { - return -1; - } - if (stat (tp, &fs)) { - return -1; - } - assert (i < _dircount); // could happen if dir changes while we're reading. - if (i >= _dircount) return -1; - if (S_ISDIR (fs.st_mode)) { - _dirlist[i].flags |= 4; - } - else if (S_ISREG (fs.st_mode)) { - if (!fib_filter (name)) return -1; - } -#if 0 // only needed with lstat() - else if (S_ISLNK (fs.st_mode)) { - if (!fib_filter (name)) return -1; - } -#endif - else { - return -1; - } - strcpy (_dirlist[i].name, name); - _dirlist[i].mtime = mtime > 0 ? mtime : fs.st_mtime; - _dirlist[i].size = fs.st_size; - if (!(_dirlist[i].flags & 4)) - fmt_size (dpy, &_dirlist[i]); - fmt_time (dpy, &_dirlist[i]); - return 0; -} - -static int fib_openrecent (Display *dpy, const char *sel) { - int i; - unsigned int j; - assert (_recentcnt > 0); - fib_pre_opendir (dpy); - query_font_geometry (dpy, _fib_gc, "Last Used", &_fib_font_time_width, NULL, NULL, NULL); - _dirlist = (FibFileEntry*) calloc (_recentcnt, sizeof(FibFileEntry)); - _dircount = _recentcnt; - for (j = 0, i = 0; j < _recentcnt; ++j) { - char base[1024]; - char *s = strrchr (_recentlist[j].path, '/'); - if (!s || !*++s) continue; - size_t len = (s - _recentlist[j].path); - strncpy (base, _recentlist[j].path, len); - base[len] = '\0'; - if (!fib_dirlistadd (dpy, i, base, s, _recentlist[j].atime)) { - _dirlist[i].rfp = &_recentlist[j]; - _dirlist[i].flags |= 8; - ++i; - } - } - _dircount = i; - fib_post_opendir (dpy, sel); - return _dircount; -} - -static int fib_opendir (Display *dpy, const char* path, const char *sel) { - char *t0, *t1; - int i; - - assert (path); - - if (strlen (path) == 0 && _recentcnt > 0) { // XXX we should use a better indication for this - strcpy (_cur_path, ""); - return fib_openrecent (dpy, sel); - } - - assert (strlen (path) < sizeof(_cur_path) -1); - assert (strlen (path) > 0); - assert (strstr (path, "//") == NULL); - assert (path[0] == '/'); - - fib_pre_opendir (dpy); - - query_font_geometry (dpy, _fib_gc, "Last Modified", &_fib_font_time_width, NULL, NULL, NULL); - DIR *dir = opendir (path); - if (!dir) { - strcpy (_cur_path, "/"); - } else { - int i; - struct dirent *de; - strcpy (_cur_path, path); - - if (_cur_path[strlen (_cur_path) -1] != '/') - strcat (_cur_path, "/"); - - while ((de = readdir (dir))) { - if (!_fib_hidden_fn && de->d_name[0] == '.') continue; - ++_dircount; - } - - if (_dircount > 0) - _dirlist = (FibFileEntry*) calloc (_dircount, sizeof(FibFileEntry)); - - rewinddir (dir); - - i = 0; - while ((de = readdir (dir))) { - if (!fib_dirlistadd (dpy, i, _cur_path, de->d_name, 0)) - ++i; - } - _dircount = i; - closedir (dir); - } - - t0 = _cur_path; - while (*t0 && (t0 = strchr (t0, '/'))) { - ++_pathparts; - ++t0; - } - assert (_pathparts > 0); - _pathbtn = (FibPathButton*) calloc (_pathparts + 1, sizeof(FibPathButton)); - - t1 = _cur_path; - i = 0; - while (*t1 && (t0 = strchr (t1, '/'))) { - if (i == 0) { - strcpy (_pathbtn[i].name, "/"); - } else { - *t0 = 0; - strcpy (_pathbtn[i].name, t1); - } - query_font_geometry (dpy, _fib_gc, _pathbtn[i].name, &_pathbtn[i].xw, NULL, NULL, NULL); - _pathbtn[i].xw += BTNPADDING + BTNPADDING; - *t0 = '/'; - t1 = t0 + 1; - ++i; - } - fib_post_opendir (dpy, sel); - return _dircount; -} - -static int fib_open (Display *dpy, int item) { - char tp[1024]; - if (_dirlist[item].flags & 8) { - assert (_dirlist[item].rfp); - strcpy (_rv_open, _dirlist[item].rfp->path); - _status = 1; - return 0; - } - strcpy (tp, _cur_path); - strcat (tp, _dirlist[item].name); - if (_dirlist[item].flags & 4) { - fib_opendir (dpy, tp, NULL); - return 0; - } else { - _status = 1; - strcpy (_rv_open, tp); - } - return 0; -} - -static void cb_cancel (Display *dpy) { - _status = -1; - - // unused - return; (void)dpy; -} - -static void cb_open (Display *dpy) { - if (_fsel >= 0 && _fsel < _dircount) { - fib_open (dpy, _fsel); - } -} - -static void sync_button_states () { - if (_fib_show_places) - _btn_places.flags |= 2; - else - _btn_places.flags &= ~2; - if (_fib_filter_fn) // inverse -> show all - _btn_filter.flags &= ~2; - else - _btn_filter.flags |= 2; - if (_fib_hidden_fn) - _btn_hidden.flags |= 2; - else - _btn_hidden.flags &= ~2; -} - -static void cb_places (Display *dpy) { - _fib_show_places = ! _fib_show_places; - if (_placecnt < 1) - _fib_show_places = 0; - sync_button_states (); - _fib_resized = 1; - fib_expose (dpy, _fib_win); -} - -static void cb_filter (Display *dpy) { - _fib_filter_fn = ! _fib_filter_fn; - sync_button_states (); - char *sel = _fsel >= 0 ? strdup (_dirlist[_fsel].name) : NULL; - fib_opendir (dpy, _cur_path, sel); - free (sel); -} - -static void cb_hidden (Display *dpy) { - _fib_hidden_fn = ! _fib_hidden_fn; - sync_button_states (); - char *sel = _fsel >= 0 ? strdup (_dirlist[_fsel].name) : NULL; - fib_opendir (dpy, _cur_path, sel); - free (sel); -} - -static int fib_widget_at_pos (Display *dpy, int x, int y, int *it) { - const int btop = _fib_height - BTNBTMMARGIN * _fib_font_vsep - _fib_font_ascent - BTNPADDING; - const int bbot = btop + _fib_font_height + BTNPADDING + BTNPADDING; - const int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - const int ltop = LISTTOP * _fib_font_vsep; - const int fbot = ltop + 4 + llen * _fib_font_vsep; - const int ptop = PATHBTNTOP - _fib_font_ascent; - assert (it); - - // paths at top - if (y > ptop && y < ptop + _fib_font_height && _view_p >= 0 && _pathparts > 0) { - int i = _view_p; - *it = -1; - if (i > 0) { // special case '<' - if (x > FAREAMRGB && x <= FAREAMRGB + _pathbtn[0].xw) { - *it = _view_p - 1; - i = _pathparts; - } - } - while (i < _pathparts) { - if (x >= _pathbtn[i].x0 && x <= _pathbtn[i].x0 + _pathbtn[i].xw) { - *it = i; - break; - } - ++i; - } - assert (*it < _pathparts); - if (*it >= 0) return 1; - else return 0; - } - - // buttons at bottom - if (y > btop && y < bbot) { - size_t i; - *it = -1; - for (i = 0; i < sizeof(_btns) / sizeof(FibButton*); ++i) { - const int bx = _btns[i]->x0; - if (_btns[i]->flags & 8) { continue; } - if (x > bx && x < bx + _btns[i]->xw) { - *it = i; - } - } - if (*it >= 0) return 3; - else return 0; - } - - // main file area - if (y >= ltop - _fib_font_vsep && y < fbot && x > FAREAMRGL && x < _fib_width - FAREAMRGR) { - // scrollbar - if (_scrl_y0 > 0 && x >= _fib_width - (FAREAMRGR + SCROLLBARW) && x <= _fib_width - FAREAMRGR) { - if (y >= _scrl_y0 && y < _scrl_y1) { - *it = 0; - } else if (y >= _scrl_y1) { - *it = 2; - } else { - *it = 1; - } - return 4; - } - // file-list - else if (y >= ltop) { - const int item = (y - ltop) / _fib_font_vsep + _scrl_f; - *it = -1; - if (item >= 0 && item < _dircount) { - *it = item; - } - if (*it >= 0) return 2; - else return 0; - } - else { - *it = -1; - const int fsel_width = _fib_width - FAREAMRGL - FAREAMRGR - (llen < _dircount ? SCROLLBARW : 0); - const int t_s = FAREAMRGL + fsel_width - _fib_font_time_width - TEXTSEP - TEXTSEP; - const int t_t = FAREAMRGL + fsel_width - TEXTSEP - _fib_font_size_width - ((_columns & 2) ? ( _fib_font_time_width + TEXTSEP + TEXTSEP) : 0); - if (x >= fsel_width + FAREAMRGL) ; - else if ((_columns & 2) && x >= t_s) *it = 3; - else if ((_columns & 1) && x >= t_t) *it = 2; - else if (x >= FAREATEXTL + _fib_dir_indent - TEXTSEP) *it = 1; - if (*it >= 0) return 5; - else return 0; - } - } - - // places list - if (_fib_show_places && y >= ltop && y < fbot && x > FAREAMRGB && x < FAREAMRGL - FAREAMRGB) { - const int item = (y - ltop) / _fib_font_vsep; - *it = -1; - if (item >= 0 && item < _placecnt) { - *it = item; - } - if (*it >= 0) return 6; - else return 0; - } - - return 0; - - // unused - (void)dpy; -} - -static void fib_update_hover (Display *dpy, int need_expose, const int type, const int item) { - int hov_p = -1; - int hov_b = -1; - int hov_h = -1; - int hov_s = -1; -#ifdef LIST_ENTRY_HOVER - int hov_f = -1; - int hov_l = -1; -#endif - - switch (type) { - case 1: hov_p = item; break; - case 3: hov_b = item; break; - case 4: hov_s = item; break; - case 5: hov_h = item; break; -#ifdef LIST_ENTRY_HOVER - case 6: hov_l = item; break; - case 2: hov_f = item; break; -#endif - default: break; - } -#ifdef LIST_ENTRY_HOVER - if (hov_f != _hov_f) { _hov_f = hov_f; need_expose = 1; } - if (hov_l != _hov_l) { _hov_l = hov_l; need_expose = 1; } -#endif - if (hov_b != _hov_b) { _hov_b = hov_b; need_expose = 1; } - if (hov_p != _hov_p) { _hov_p = hov_p; need_expose = 1; } - if (hov_h != _hov_h) { _hov_h = hov_h; need_expose = 1; } - if (hov_s != _hov_s) { _hov_s = hov_s; need_expose = 1; } - - if (need_expose) { - fib_expose (dpy, _fib_win); - } -} - -static void fib_motion (Display *dpy, int x, int y) { - int it = -1; - - if (_scrl_my >= 0) { - const int sdiff = y - _scrl_my; - const int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - const int fsel_height = 4 + llen * _fib_font_vsep; - const float sl = (fsel_height + _fib_font_vsep - (SCROLLBOXH + SCROLLBOXH)) / (float) _dircount; - - int news = _scrl_mf + sdiff / sl; - if (news < 0) news = 0; - if (news >= (_dircount - llen)) news = _dircount - llen; - if (news != _scrl_f) { - _scrl_f = news; - fib_expose (dpy, _fib_win); - } - return; - } - - const int type = fib_widget_at_pos (dpy, x, y, &it); - fib_update_hover (dpy, 0, type, it); -} - -static void fib_mousedown (Display *dpy, int x, int y, int btn, unsigned long time) { - int it; - switch (fib_widget_at_pos (dpy, x, y, &it)) { - case 4: // scrollbar - if (btn == 1) { - _dblclk = 0; - if (it == 0) { - _scrl_my = y; - _scrl_mf = _scrl_f; - } else { - int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - if (llen < 2) llen = 2; - int news = _scrl_f; - if (it == 1) { - news -= llen - 1; - } else { - news += llen - 1; - } - if (news < 0) news = 0; - if (news >= (_dircount - llen)) news = _dircount - llen; - if (news != _scrl_f && _scrl_y0 >= 0) { - assert (news >=0); - _scrl_f = news; - fib_update_hover (dpy, 1, 4, it); - } - } - } - break; - case 2: // file-list - if (btn == 4 || btn == 5) { - const int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - int news = _scrl_f + ((btn == 4) ? - 1 : 1); - if (news < 0) news = 0; - if (news >= (_dircount - llen)) news = _dircount - llen; - if (news != _scrl_f && _scrl_y0 >= 0) { - assert (news >=0); - _scrl_f = news; - fib_update_hover (dpy, 1, 0, 0); - } - _dblclk = 0; - } - else if (btn == 1 && it >= 0 && it < _dircount) { - if (_fsel == it) { - if (time - _dblclk < DBLCLKTME) { - fib_open (dpy, it); - _dblclk = 0; - } - _dblclk = time; - } else { - fib_select (dpy, it); - _dblclk = time; - } - /*if (_fsel >= 0) { - if (!(_dirlist[_fsel].flags & 4)); - }*/ - } - break; - case 1: // paths - assert (_fsel < _dircount); - assert (it >= 0 && it < _pathparts); - { - int i = 0; - char path[1024] = "/"; - while (++i <= it) { - strcat (path, _pathbtn[i].name); - strcat (path, "/"); - } - char *sel = NULL; - if (i < _pathparts) - sel = strdup (_pathbtn[i].name); - else if (i == _pathparts && _fsel >= 0) - sel = strdup (_dirlist[_fsel].name); - fib_opendir (dpy, path, sel); - free (sel); - } - break; - case 3: // btn - if (btn == 1 && _btns[it]->callback) { - _btns[it]->callback (dpy); - } - break; - case 5: // sort - if (btn == 1) { - switch (it) { - case 1: if (_sort == 0) _sort = 1; else _sort = 0; break; - case 2: if (_sort == 2) _sort = 3; else _sort = 2; break; - case 3: if (_sort == 4) _sort = 5; else _sort = 4; break; - } - if (_fsel >= 0) { - assert (_dirlist && _dircount >= _fsel); - _dirlist[_fsel].flags &= ~2; - char *sel = strdup (_dirlist[_fsel].name); - fib_resort (sel); - free (sel); - } else { - fib_resort (NULL); - _fsel = -1; - } - fib_reset (); - _hov_h = it; - fib_select (dpy, _fsel); - } - break; - case 6: - if (btn == 1 && it >= 0 && it < _placecnt) { - fib_opendir (dpy, _placelist[it].path, NULL); - } - break; - default: - break; - } -} - -static void fib_mouseup (Display *dpy, int x, int y, int btn, unsigned long time) { - _scrl_my = -1; - - // unused - return; (void)dpy; (void)x; (void)y; (void)btn; (void)time; -} - -static void add_place_raw (Display *dpy, const char *name, const char *path) { - _placelist = (FibPlace*) realloc (_placelist, (_placecnt + 1) * sizeof(FibPlace)); - strcpy (_placelist[_placecnt].path, path); - strcpy (_placelist[_placecnt].name, name); - _placelist[_placecnt].flags = 0; - - int sw; - query_font_geometry (dpy, _fib_gc, name, &sw, NULL, NULL, NULL); - if (sw > _fib_place_width) { - _fib_place_width = sw; - } - ++_placecnt; -} - -static int add_place_places (Display *dpy, const char *name, const char *url) { - char const * path; - struct stat fs; - int i; - if (!url || strlen (url) < 1) return -1; - if (!name || strlen (name) < 1) return -1; - if (url[0] == '/') { - path = url; - } - else if (!strncmp (url, "file:///", 8)) { - path = &url[7]; - } - else { - return -1; - } - - if (access (path, R_OK)) { - return -1; - } - if (stat (path, &fs)) { - return -1; - } - if (!S_ISDIR (fs.st_mode)) { - return -1; - } - - for (i = 0; i < _placecnt; ++i) { - if (!strcmp (path, _placelist[i].path)) { - return -1; - } - } - add_place_raw (dpy, name, path); - return 0; -} - -static int parse_gtk_bookmarks (Display *dpy, const char *fn) { - char tmp[1024]; - if (access (fn, R_OK)) { - return -1; - } - FILE *bm = fopen (fn, "r"); - if (!bm) return -1; - int found = 0; - while (fgets (tmp, sizeof(tmp), bm) - && strlen (tmp) > 1 - && strlen (tmp) < sizeof(tmp)) - { - char *s, *n; - tmp[strlen (tmp) - 1] = '\0'; // strip newline - if ((s = strchr (tmp, ' '))) { - *s = '\0'; - n = strdup (++s); - decode_3986 (tmp); - if (!add_place_places (dpy, n, tmp)) { - ++found; - } - free (n); - } else if ((s = strrchr (tmp, '/'))) { - n = strdup (++s); - decode_3986 (tmp); - if (!add_place_places (dpy, n, tmp)) { - ++found; - } - free (n); - } - } - fclose (bm); - return found; -} - -static const char *ignore_mountpoints[] = { - "/bin", "/boot", "/dev", "/etc", - "/lib", "/live", "/mnt", "/opt", - "/root", "/sbin", "/srv", "/tmp", - "/usr", "/var", "/proc", "/sbin", - "/net", "/sys" -}; - -static const char *ignore_fs[] = { - "auto", "autofs", - "debugfs", "devfs", - "devpts", "ecryptfs", - "fusectl", "kernfs", - "linprocfs", "proc", - "ptyfs", "rootfs", - "selinuxfs", "sysfs", - "tmpfs", "usbfs", - "nfsd", "rpc_pipefs", -}; - -static const char *ignore_devices[] = { - "binfmt_", "devpts", - "gvfs", "none", - "nfsd", "sunrpc", - "/dev/loop", "/dev/vn" -}; - -static int check_mount (const char *mountpoint, const char *fs, const char *device) { - size_t i; - if (!mountpoint || !fs || !device) return -1; - //printf("%s %s %s\n", mountpoint, fs, device); - for (i = 0 ; i < sizeof(ignore_mountpoints) / sizeof(char*); ++i) { - if (!strncmp (mountpoint, ignore_mountpoints[i], strlen (ignore_mountpoints[i]))) { - return 1; - } - } - if (!strncmp (mountpoint, "/home", 5)) { - return 1; - } - for (i = 0 ; i < sizeof(ignore_fs) / sizeof(char*); ++i) { - if (!strncmp (fs, ignore_fs[i], strlen (ignore_fs[i]))) { - return 1; - } - } - for (i = 0 ; i < sizeof(ignore_devices) / sizeof(char*); ++i) { - if (!strncmp (device, ignore_devices[i], strlen (ignore_devices[i]))) { - return 1; - } - } - return 0; -} - -static int read_mtab (Display *dpy, const char *mtab) { - FILE *mt = fopen (mtab, "r"); - if (!mt) return -1; - int found = 0; - struct mntent *mntent; - while ((mntent = getmntent (mt)) != NULL) { - char *s; - if (check_mount (mntent->mnt_dir, mntent->mnt_type, mntent->mnt_fsname)) - continue; - - if ((s = strrchr (mntent->mnt_dir, '/'))) { - ++s; - } else { - s = mntent->mnt_dir; - } - if (!add_place_places (dpy, s, mntent->mnt_dir)) { - ++found; - } - } - fclose (mt); - return found; -} - -static void populate_places (Display *dpy) { - char tmp[1024]; - int spacer = -1; - if (_placecnt > 0) return; - _fib_place_width = 0; - - if (_recentcnt > 0) { - add_place_raw (dpy, "Recently Used", ""); - _placelist[0].flags |= 4; - } - - add_place_places (dpy, "Home", getenv ("HOME")); - - if (getenv ("HOME")) { - strcpy (tmp, getenv ("HOME")); - strcat (tmp, "/Desktop"); - add_place_places (dpy, "Desktop", tmp); - } - - add_place_places (dpy, "Filesystem", "/"); - - if (_placecnt > 0) spacer = _placecnt -1; - - if (strlen (_fib_cfg_custom_places) > 0) { - parse_gtk_bookmarks (dpy, _fib_cfg_custom_places); - } - - if (read_mtab (dpy, "/proc/mounts") < 1) { - read_mtab (dpy, "/etc/mtab"); - } - - int parsed_bookmarks = 0; - if (!parsed_bookmarks && getenv ("HOME")) { - strcpy (tmp, getenv ("HOME")); - strcat (tmp, "/.gtk-bookmarks"); - if (parse_gtk_bookmarks (dpy, tmp) > 0) { - parsed_bookmarks = 1; - } - } - if (!parsed_bookmarks && getenv ("XDG_CONFIG_HOME")) { - strcpy (tmp, getenv ("XDG_CONFIG_HOME")); - strcat (tmp, "/gtk-3.0/bookmarks"); - if (parse_gtk_bookmarks (dpy, tmp) > 0) { - parsed_bookmarks = 1; - } - } - if (!parsed_bookmarks && getenv ("HOME")) { - strcpy (tmp, getenv ("HOME")); - strcat (tmp, "/.config/gtk-3.0/bookmarks"); - if (parse_gtk_bookmarks (dpy, tmp) > 0) { - parsed_bookmarks = 1; - } - } - if (_fib_place_width > 0) { - _fib_place_width = MIN (_fib_place_width + TEXTSEP + _fib_dir_indent /*extra*/ , PLACESWMAX); - } - if (spacer > 0 && spacer < _placecnt -1) { - _placelist[ spacer ].flags |= 4; - } -} - -static uint8_t font_err = 0; -static int x_error_handler (Display *d, XErrorEvent *e) { - font_err = 1; - return 0; - - // unused - (void)d; (void)e; -} - -int x_fib_show (Display *dpy, Window parent, int x, int y) { - if (_fib_win) { - XSetInputFocus (dpy, _fib_win, RevertToParent, CurrentTime); - return -1; - } - - _status = 0; - _rv_open[0] = '\0'; - - Colormap colormap = DefaultColormap (dpy, DefaultScreen (dpy)); - _c_gray1.flags= DoRed | DoGreen | DoBlue; - _c_gray0.red = _c_gray0.green = _c_gray0.blue = 61710; // 95% hover prelight - _c_gray1.red = _c_gray1.green = _c_gray1.blue = 60416; // 93% window bg, scrollbar-fg - _c_gray2.red = _c_gray2.green = _c_gray2.blue = 54016; // 83% button & list bg - _c_gray3.red = _c_gray3.green = _c_gray3.blue = 48640; // 75% heading + scrollbar-bg - _c_gray4.red = _c_gray4.green = _c_gray4.blue = 26112; // 40% prelight text, sep lines - _c_gray5.red = _c_gray5.green = _c_gray5.blue = 12800; // 20% 3D border - _c_gray6.red = _c_gray6.green = _c_gray6.blue = 6400; // 10% checkbox cross, sort triangles - - if (!XAllocColor (dpy, colormap, &_c_gray0)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray1)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray2)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray3)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray4)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray5)) return -1; - if (!XAllocColor (dpy, colormap, &_c_gray6)) return -1; - - XSetWindowAttributes attr; - memset (&attr, 0, sizeof(XSetWindowAttributes)); - attr.border_pixel = _c_gray2.pixel; - - attr.event_mask = ExposureMask | KeyPressMask - | ButtonPressMask | ButtonReleaseMask - | ConfigureNotify | StructureNotifyMask - | PointerMotionMask | LeaveWindowMask; - - _fib_win = XCreateWindow ( - dpy, DefaultRootWindow (dpy), - x, y, _fib_width, _fib_height, - 1, CopyFromParent, InputOutput, CopyFromParent, - CWEventMask | CWBorderPixel, &attr); - - if (!_fib_win) { return 1; } - - if (parent) - XSetTransientForHint (dpy, _fib_win, parent); - - XStoreName (dpy, _fib_win, "Select File"); - - Atom wmDelete = XInternAtom (dpy, "WM_DELETE_WINDOW", True); - XSetWMProtocols (dpy, _fib_win, &wmDelete, 1); - - _fib_gc = XCreateGC (dpy, _fib_win, 0, NULL); - XSetLineAttributes (dpy, _fib_gc, 1, LineSolid, CapButt, JoinMiter); - const char dl[1] = {1}; - XSetDashes (dpy, _fib_gc, 0, dl, 1); - - int (*handler)(Display *, XErrorEvent *) = XSetErrorHandler (&x_error_handler); - -#define _XTESTFONT(FN) \ - { \ - font_err = 0; \ - _fibfont = XLoadFont (dpy, FN); \ - XSetFont (dpy, _fib_gc, _fibfont); \ - XSync (dpy, False); \ - } - - font_err = 1; - if (getenv ("XJFONT")) _XTESTFONT (getenv ("XJFONT")); - if (font_err && strlen (_fib_cfg_custom_font) > 0) _XTESTFONT (_fib_cfg_custom_font); - if (font_err) _XTESTFONT ("-*-helvetica-medium-r-normal-*-12-*-*-*-*-*-*-*"); - if (font_err) _XTESTFONT ("-*-verdana-medium-r-normal-*-12-*-*-*-*-*-*-*"); - if (font_err) _XTESTFONT ("-misc-fixed-medium-r-normal-*-13-*-*-*-*-*-*-*"); - if (font_err) _XTESTFONT ("-misc-fixed-medium-r-normal-*-12-*-*-*-*-*-*-*"); - if (font_err) _fibfont = None; - XSync (dpy, False); - XSetErrorHandler (handler); - - if (_fib_font_height == 0) { // 1st time only - query_font_geometry (dpy, _fib_gc, "D ", &_fib_dir_indent, NULL, NULL, NULL); - query_font_geometry (dpy, _fib_gc, "_", &_fib_spc_norm, NULL, NULL, NULL); - if (query_font_geometry (dpy, _fib_gc, "|0Yy", NULL, &_fib_font_height, &_fib_font_ascent, NULL)) { - XFreeGC (dpy, _fib_gc); - XDestroyWindow (dpy, _fib_win); - _fib_win = 0; - return -1; - } - _fib_font_height += 3; - _fib_font_ascent += 2; - _fib_font_vsep = _fib_font_height + 2; - } - - populate_places (dpy); - - strcpy (_btn_ok.text, "Open"); - strcpy (_btn_cancel.text, "Cancel"); - strcpy (_btn_filter.text, "List All Files"); - strcpy (_btn_places.text, "Show Places"); - strcpy (_btn_hidden.text, "Show Hidden"); - - _btn_ok.callback = &cb_open; - _btn_cancel.callback = &cb_cancel; - _btn_filter.callback = &cb_filter; - _btn_places.callback = &cb_places; - _btn_hidden.callback = &cb_hidden; - _btn_filter.flags |= 4; - _btn_places.flags |= 4; - _btn_hidden.flags |= 4; - - if (!_fib_filter_function) { - _btn_filter.flags |= 8; - } - - size_t i; - int btncnt = 0; - _btn_w = 0; - _btn_span = 0; - for (i = 0; i < sizeof(_btns) / sizeof(FibButton*); ++i) { - if (_btns[i]->flags & 8) { continue; } - query_font_geometry (dpy, _fib_gc, _btns[i]->text, &_btns[i]->tw, NULL, NULL, NULL); - if (_btns[i]->flags & 4) { - _btn_span += _btns[i]->tw + _fib_font_ascent + TEXTSEP; - } else { - ++btncnt; - if (_btns[i]->tw > _btn_w) - _btn_w = _btns[i]->tw; - } - } - - _btn_w += BTNPADDING + BTNPADDING + TEXTSEP + TEXTSEP + TEXTSEP; - _btn_span += _btn_w * btncnt + DSEP * (i - 1) + FAREAMRGR + FAREAMRGB; - - for (i = 0; i < sizeof(_btns) / sizeof(FibButton*); ++i) { - if (_btns[i]->flags & 8) { continue; } - if (_btns[i]->flags & 4) { - _btns[i]->xw = _btns[i]->tw + _fib_font_ascent + TEXTSEP; - } else { - _btns[i]->xw = _btn_w; - } - } - - sync_button_states () ; - - _fib_height = _fib_font_vsep * (15.8); - _fib_width = MAX (_btn_span, 440); - - XResizeWindow (dpy, _fib_win, _fib_width, _fib_height); - - XTextProperty x_wname, x_iname; - XSizeHints hints; - XWMHints wmhints; - - hints.flags = PSize | PMinSize; - hints.min_width = _btn_span; - hints.min_height = 8 * _fib_font_vsep; - - char *w_name = & _fib_cfg_title[0]; - - wmhints.input = True; - wmhints.flags = InputHint; - if (XStringListToTextProperty (&w_name, 1, &x_wname) && - XStringListToTextProperty (&w_name, 1, &x_iname)) - { - XSetWMProperties (dpy, _fib_win, &x_wname, &x_iname, NULL, 0, &hints, &wmhints, NULL); - XFree (x_wname.value); - XFree (x_iname.value); - } - - XSetWindowBackground (dpy, _fib_win, _c_gray1.pixel); - - _fib_mapped = 0; - XMapRaised (dpy, _fib_win); - - if (!strlen (_cur_path) || !fib_opendir (dpy, _cur_path, NULL)) { - fib_opendir (dpy, getenv ("HOME") ? getenv ("HOME") : "/", NULL); - } - -#if 0 - XGrabPointer (dpy, _fib_win, True, - ButtonReleaseMask | ButtonPressMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask | StructureNotifyMask, - GrabModeAsync, GrabModeAsync, None, None, CurrentTime); - XGrabKeyboard (dpy, _fib_win, True, GrabModeAsync, GrabModeAsync, CurrentTime); - //XSetInputFocus (dpy, parent, RevertToNone, CurrentTime); -#endif - _recentlock = 1; - return 0; -} - -void x_fib_close (Display *dpy) { - if (!_fib_win) return; - XFreeGC (dpy, _fib_gc); - XDestroyWindow (dpy, _fib_win); - _fib_win = 0; - free (_dirlist); - _dirlist = NULL; - free (_pathbtn); - _pathbtn = NULL; - if (_fibfont != None) XUnloadFont (dpy, _fibfont); - _fibfont = None; - free (_placelist); - _placelist = NULL; - _dircount = 0; - _pathparts = 0; - _placecnt = 0; - if (_pixbuffer != None) XFreePixmap (dpy, _pixbuffer); - _pixbuffer = None; - Colormap colormap = DefaultColormap (dpy, DefaultScreen (dpy)); - XFreeColors (dpy, colormap, &_c_gray0.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray1.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray2.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray3.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray4.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray5.pixel, 1, 0); - XFreeColors (dpy, colormap, &_c_gray6.pixel, 1, 0); - _recentlock = 0; -} - -int x_fib_handle_events (Display *dpy, XEvent *event) { - if (!_fib_win) return 0; - if (_status) return 0; - if (event->xany.window != _fib_win) { - return 0; - } - - switch (event->type) { - case MapNotify: - _fib_mapped = 1; - break; - case UnmapNotify: - _fib_mapped = 0; - break; - case LeaveNotify: - fib_update_hover (dpy, 1, 0, 0); - break; - case ClientMessage: - if (!strcmp (XGetAtomName (dpy, event->xclient.message_type), "WM_PROTOCOLS")) { - _status = -1; - } - case ConfigureNotify: - if ( - (event->xconfigure.width > 1 && event->xconfigure.height > 1) - && - (event->xconfigure.width != _fib_width || event->xconfigure.height != _fib_height) - ) - { - _fib_width = event->xconfigure.width; - _fib_height = event->xconfigure.height; - _fib_resized = 1; - } - break; - case Expose: - if (event->xexpose.count == 0) { - fib_expose (dpy, event->xany.window); - } - break; - case MotionNotify: - fib_motion (dpy, event->xmotion.x, event->xmotion.y); - if (event->xmotion.is_hint == NotifyHint) { - XGetMotionEvents (dpy, event->xany.window, CurrentTime, CurrentTime, NULL); - } - break; - case ButtonPress: - fib_mousedown (dpy, event->xbutton.x, event->xbutton.y, event->xbutton.button, event->xbutton.time); - break; - case ButtonRelease: - fib_mouseup (dpy, event->xbutton.x, event->xbutton.y, event->xbutton.button, event->xbutton.time); - break; - case KeyRelease: - break; - case KeyPress: - { - KeySym key; - char buf[100]; - static XComposeStatus stat; - XLookupString (&event->xkey, buf, sizeof(buf), &key, &stat); - switch (key) { - case XK_Escape: - _status = -1; - break; - case XK_Up: - if (_fsel > 0) { - fib_select (dpy, _fsel - 1); - } - break; - case XK_Down: - if (_fsel < _dircount -1) { - fib_select ( dpy, _fsel + 1); - } - break; - case XK_Page_Up: - if (_fsel > 0) { - int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - if (llen < 1) llen = 1; else --llen; - int fs = MAX (0, _fsel - llen); - fib_select ( dpy, fs); - } - break; - case XK_Page_Down: - if (_fsel < _dircount) { - int llen = (_fib_height - LISTBOT * _fib_font_vsep) / _fib_font_vsep; - if (llen < 1) llen = 1; else --llen; - int fs = MIN (_dircount - 1, _fsel + llen); - fib_select ( dpy, fs); - } - break; - case XK_Left: - if (_pathparts > 1) { - int i = 0; - char path[1024] = "/"; - while (++i < _pathparts - 1) { - strcat (path, _pathbtn[i].name); - strcat (path, "/"); - } - char *sel = strdup (_pathbtn[_pathparts-1].name); - fib_opendir (dpy, path, sel); - free (sel); - } - break; - case XK_Right: - if (_fsel >= 0 && _fsel < _dircount) { - if (_dirlist[_fsel].flags & 4) { - cb_open (dpy); - } - } - break; - case XK_Return: - cb_open (dpy); - break; - default: - if ((key >= XK_a && key <= XK_z) || (key >= XK_0 && key <= XK_9)) { - int i; - for (i = 0; i < _dircount; ++i) { - int j = (_fsel + i + 1) % _dircount; - char kcmp = _dirlist[j].name[0]; - if (kcmp > 0x40 && kcmp <= 0x5A) kcmp |= 0x20; - if (kcmp == (char)key) { - fib_select ( dpy, j); - break; - } - } - } - break; - } - } - break; - } - - if (_status) { - x_fib_close (dpy); - } - return _status; -} - -int x_fib_status () { - return _status; -} - -int x_fib_configure (int k, const char *v) { - if (_fib_win) { return -1; } - switch (k) { - case 0: - if (strlen (v) >= sizeof(_cur_path) -1) return -2; - if (strlen (v) < 1) return -2; - if (v[0] != '/') return -2; - if (strstr (v, "//")) return -2; - strncpy (_cur_path, v, sizeof(_cur_path)); - break; - case 1: - if (strlen (v) >= sizeof(_fib_cfg_title) -1) return -2; - strncpy (_fib_cfg_title, v, sizeof(_fib_cfg_title)); - break; - case 2: - if (strlen (v) >= sizeof(_fib_cfg_custom_font) -1) return -2; - strncpy (_fib_cfg_custom_font, v, sizeof(_fib_cfg_custom_font)); - break; - case 3: - if (strlen (v) >= sizeof(_fib_cfg_custom_places) -1) return -2; - strncpy (_fib_cfg_custom_places, v, sizeof(_fib_cfg_custom_places)); - break; - default: - return -2; - } - return 0; -} - -int x_fib_cfg_buttons (int k, int v) { - if (_fib_win) { return -1; } - switch (k) { - case 1: - if (v < 0) { - _btn_hidden.flags |= 8; - } else { - _btn_hidden.flags &= ~8; - } - if (v == 1) { - _btn_hidden.flags |= 2; - _fib_hidden_fn = 1; - } else if (v == 0) { - _btn_hidden.flags &= 2; - _fib_hidden_fn = 0; - } - break; - case 2: - if (v < 0) { - _btn_places.flags |= 8; - } else { - _btn_places.flags &= ~8; - } - if (v == 1) { - _btn_places.flags |= 2; - _fib_show_places = 1; - } else if (v == 0) { - _btn_places.flags &= ~2; - _fib_show_places = 0; - } - break; - case 3: - // NB. filter button is automatically hidden - // IFF the filter-function is NULL. - if (v < 0) { - _btn_filter.flags |= 8; - } else { - _btn_filter.flags &= ~8; - } - if (v == 1) { - _btn_filter.flags &= ~2; // inverse - 'show all' = !filter - _fib_filter_fn = 1; - } else if (v == 0) { - _btn_filter.flags |= 2; - _fib_filter_fn = 0; - } - default: - return -2; - } - return 0; -} - -int x_fib_cfg_filter_callback (int (*cb)(const char*)) { - if (_fib_win) { return -1; } - _fib_filter_function = cb; - return 0; -} - -char *x_fib_filename () { - if (_status > 0 && !_fib_win) - return strdup (_rv_open); - else - return NULL; -} -#endif // SOFD_HAVE_X11 - -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif - -/* example usage */ -#ifdef SOFD_TEST - -static int fib_filter_movie_filename (const char *name) { - if (!_fib_filter_fn) return 1; - const int l3 = strlen (name) - 3; - const int l4 = l3 - 1; - const int l5 = l4 - 1; - const int l6 = l5 - 1; - const int l9 = l6 - 3; - if ( - (l4 > 0 && ( - !strcasecmp (&name[l4], ".avi") - || !strcasecmp (&name[l4], ".mov") - || !strcasecmp (&name[l4], ".ogg") - || !strcasecmp (&name[l4], ".ogv") - || !strcasecmp (&name[l4], ".mpg") - || !strcasecmp (&name[l4], ".mov") - || !strcasecmp (&name[l4], ".mp4") - || !strcasecmp (&name[l4], ".mkv") - || !strcasecmp (&name[l4], ".vob") - || !strcasecmp (&name[l4], ".asf") - || !strcasecmp (&name[l4], ".avs") - || !strcasecmp (&name[l4], ".dts") - || !strcasecmp (&name[l4], ".flv") - || !strcasecmp (&name[l4], ".m4v") - )) || - (l5 > 0 && ( - !strcasecmp (&name[l5], ".h264") - || !strcasecmp (&name[l5], ".webm") - )) || - (l6 > 0 && ( - !strcasecmp (&name[l6], ".dirac") - )) || - (l9 > 0 && ( - !strcasecmp (&name[l9], ".matroska") - )) || - (l3 > 0 && ( - !strcasecmp (&name[l3], ".dv") - || !strcasecmp (&name[l3], ".ts") - )) - ) - { - return 1; - } - return 0; -} - -int main (int argc, char **argv) { - Display* dpy = XOpenDisplay (0); - if (!dpy) return -1; - - x_fib_cfg_filter_callback (fib_filter_movie_filename); - x_fib_configure (1, "Open Movie File"); - x_fib_load_recent ("/tmp/sofd.recent"); - x_fib_show (dpy, 0, 300, 300); - - while (1) { - XEvent event; - while (XPending (dpy) > 0) { - XNextEvent (dpy, &event); - if (x_fib_handle_events (dpy, &event)) { - if (x_fib_status () > 0) { - char *fn = x_fib_filename (); - printf ("OPEN '%s'\n", fn); - x_fib_add_recent (fn, time (NULL)); - free (fn); - } - } - } - if (x_fib_status ()) { - break; - } - usleep (80000); - } - x_fib_close (dpy); - - x_fib_save_recent ("/tmp/sofd.recent"); - - x_fib_free_recent (); - XCloseDisplay (dpy); - return 0; -} -#endif diff --git a/libs/dgl/src/sofd/libsofd.h b/libs/dgl/src/sofd/libsofd.h deleted file mode 100644 index 412db85..0000000 --- a/libs/dgl/src/sofd/libsofd.h +++ /dev/null @@ -1,175 +0,0 @@ -/* libSOFD - Simple Open File Dialog [for X11 without toolkit] - * - * Copyright (C) 2014 Robin Gareus <robin@gareus.org> - * - * 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. - */ - -#ifdef SOFD_HAVE_X11 -#include <X11/Xlib.h> - -/////////////////////////////////////////////////////////////////////////////// -/* public API */ - -typedef struct FibInternalsImpl FibInternals; - -/** open a file select dialog - * @param dpy X Display connection - * @param parent (optional) if not NULL, become transient for given window - * @param x if >0 set explict initial width of the window - * @param y if >0 set explict initial height of the window - * @return 0 on success - */ -int x_fib_show (Display *dpy, Window parent, int x, int y); - -/** force close the dialog. - * This is normally not needed, the dialog closes itself - * when a file is selected or the user cancels selection. - * @param dpy X Display connection - */ -void x_fib_close (Display *dpy); - -/** non-blocking X11 event handler. - * It is safe to run this function even if the dialog is - * closed or was not initialized. - * - * @param dpy X Display connection - * @param event the XEvent to process - * @return status - * 0: the event was not for this window, or file-dialog still - * active, or the dialog window is not displayed. - * >0: file was selected, dialog closed - * <0: file selection was cancelled. - */ -int x_fib_handle_events (Display *dpy, XEvent *event); - -/** last status of the dialog - * @return >0: file was selected, <0: canceled or inactive. 0: active - */ -int x_fib_status (); - -/** query the selected filename - * @return NULL if none set, or allocated string to be free()ed by the called - */ -char *x_fib_filename (); - -/** customize/configure the dialog before calling \ref x_fib_show - * changes only have any effect if the dialog is not visible. - * @param k key to change - * 0: set current dir to display (must end with slash) - * 1: set title of dialog window - * 2: specify a custom X11 font to use - * 3: specify a custom 'places' file to include - * (following gtk-bookmark convention) - * @param v value - * @return 0 on success. - */ -int x_fib_configure (int k, const char *v); - -/** customize/configure the dialog before calling \ref x_fib_show - * changes only have any effect if the dialog is not visible. - * - * @param k button to change: - * 1: show hidden files - * 2: show places - * 3: show filter/list all (automatically hidden if there is no - * filter function) - * @param v <0 to hide the button >=0 show button, - * 0: set button-state to not-checked - * 1: set button-state to checked - * >1: retain current state - * @return 0 on success. - */ -int x_fib_cfg_buttons (int k, int v); - -/** set custom callback to filter file-names. - * NULL will disable the filter and hide the 'show all' button. - * changes only have any effect if the dialog is not visible. - * - * @param cb callback function to check file - * the callback function is called with the file name (basename only) - * and is expected to return 1 if the file passes the filter - * and 0 if the file should not be listed by default. - * @return 0 on success. - */ -int x_fib_cfg_filter_callback (int (*cb)(const char*)); - -#endif /* END X11 specific functions */ - -/* 'recently used' API. x-platform - * NOTE: all functions use a static cache and are not reentrant. - * It is expected that none of these functions are called in - * parallel from different threads. - */ - -/** release static resources of 'recently used files' - */ -void x_fib_free_recent (); - -/** add an entry to the recently used list - * - * The dialog does not add files automatically on open, - * if the application succeeds to open a selected file, - * this function should be called. - * - * @param path complete path to file - * @param atime time of last use, 0: NOW - * @return -1 on error, number of current entries otherwise - */ -int x_fib_add_recent (const char *path, time_t atime); - -/** get a platform specific path to a good location for - * saving the recently used file list. - * (follows XDG_DATA_HOME on Unix, and CSIDL_LOCAL_APPDATA spec) - * - * @param application-name to use to include in file - * @return pointer to static path or NULL - */ -const char *x_fib_recent_file(const char *appname); - -/** save the current list of recently used files to the given filename - * (the format is one file per line, filename URL encoded and space separated - * with last-used timestamp) - * - * This function tries to creates the containing directory if it does - * not exist. - * - * @param fn file to save the list to - * @return 0: on success - */ -int x_fib_save_recent (const char *fn); - -/** load a recently used file list. - * - * @param fn file to load the list from - * @return 0: on success - */ -int x_fib_load_recent (const char *fn); - -/** get number of entries in the current list - * @return number of entries in the recently used list - */ -unsigned int x_fib_recent_count (); - -/** get recently used entry at given position - * - * @param i entry to query - * @return pointer to static string - */ -const char *x_fib_recent_at (unsigned int i); diff --git a/libs/distrho/DistrhoPlugin.hpp b/libs/distrho/DistrhoPlugin.hpp deleted file mode 100644 index 817c266..0000000 --- a/libs/distrho/DistrhoPlugin.hpp +++ /dev/null @@ -1,636 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_PLUGIN_HPP_INCLUDED -#define DISTRHO_PLUGIN_HPP_INCLUDED - -#include "extra/d_string.hpp" -#include "src/DistrhoPluginChecks.h" - -#include <cmath> - -#ifdef DISTRHO_PROPER_CPP11_SUPPORT -# include <cstdint> -#else -# include <stdint.h> -#endif - -#ifndef M_PI -# define M_PI 3.14159265358979323846 -#endif - -START_NAMESPACE_DISTRHO - -/* ------------------------------------------------------------------------------------------------------------ - * Parameter Hints */ - -/** - @defgroup ParameterHints Parameter Hints - - Various parameter hints. - @see Parameter::hints - @{ - */ - -/** - Parameter is automable (real-time safe). - @see Plugin::d_setParameterValue() - */ -static const uint32_t kParameterIsAutomable = 0x01; - -/** - Parameter value is boolean. - It's always at either minimum or maximum value. - */ -static const uint32_t kParameterIsBoolean = 0x02; - -/** - Parameter value is integer. - */ -static const uint32_t kParameterIsInteger = 0x04; - -/** - Parameter value is logarithmic. - */ -static const uint32_t kParameterIsLogarithmic = 0x08; - -/** - Parameter is of output type. - When unset, parameter is assumed to be of input type. - - Parameter inputs are changed by the host and must not be changed by the plugin. - The only exception being when changing programs, see Plugin::d_setProgram(). - Outputs are changed by the plugin and never modified by the host. - */ -static const uint32_t kParameterIsOutput = 0x10; - -/** @} */ - -/* ------------------------------------------------------------------------------------------------------------ - * DPF Base structs */ - -/** - Parameter ranges. - This is used to set the default, minimum and maximum values of a parameter. - - By default a parameter has 0.0 as minimum, 1.0 as maximum and 0.0 as default. - When changing this struct values you must ensure maximum > minimum and default is within range. - */ -struct ParameterRanges { - /** - Default value. - */ - float def; - - /** - Minimum value. - */ - float min; - - /** - Maximum value. - */ - float max; - - /** - Default constructor. - */ - ParameterRanges() noexcept - : def(0.0f), - min(0.0f), - max(1.0f) {} - - /** - Constructor using custom values. - */ - ParameterRanges(const float df, const float mn, const float mx) noexcept - : def(df), - min(mn), - max(mx) {} - - /** - Fix the default value within range. - */ - void fixDefault() noexcept - { - fixValue(def); - } - - /** - Fix a value within range. - */ - void fixValue(float& value) const noexcept - { - if (value < min) - value = min; - else if (value > max) - value = max; - } - - /** - Get a fixed value within range. - */ - const float& getFixedValue(const float& value) const noexcept - { - if (value <= min) - return min; - if (value >= max) - return max; - return value; - } - - /** - Get a value normalized to 0.0<->1.0. - */ - float getNormalizedValue(const float& value) const noexcept - { - const float normValue((value - min) / (max - min)); - - if (normValue <= 0.0f) - return 0.0f; - if (normValue >= 1.0f) - return 1.0f; - return normValue; - } - - /** - Get a value normalized to 0.0<->1.0, fixed within range. - */ - float getFixedAndNormalizedValue(const float& value) const noexcept - { - if (value <= min) - return 0.0f; - if (value >= max) - return 1.0f; - - const float normValue((value - min) / (max - min)); - - if (normValue <= 0.0f) - return 0.0f; - if (normValue >= 1.0f) - return 1.0f; - - return normValue; - } - - /** - Get a proper value previously normalized to 0.0<->1.0. - */ - float getUnnormalizedValue(const float& value) const noexcept - { - if (value <= 0.0f) - return min; - if (value >= 1.0f) - return max; - - return value * (max - min) + min; - } -}; - -/** - Parameter. - */ -struct Parameter { - /** - Hints describing this parameter. - @see ParameterHints - */ - uint32_t hints; - - /** - The name of this parameter. - A parameter name can contain any character, but hosts might have a hard time with non-ascii ones. - The name doesn't have to be unique within a plugin instance, but it's recommended. - */ - d_string name; - - /** - The symbol of this parameter. - A parameter symbol is a short restricted name used as a machine and human readable identifier. - The first character must be one of _, a-z or A-Z and subsequent characters can be from _, a-z, A-Z and 0-9. - @note: Parameter symbols MUST be unique within a plugin instance. - */ - d_string symbol; - - /** - The unit of this parameter. - This means something like "dB", "kHz" and "ms". - Can be left blank if units do not apply to this parameter. - */ - d_string unit; - - /** - Ranges of this parameter. - The ranges describe the default, minimum and maximum values. - */ - ParameterRanges ranges; - - /** - Default constructor for a null parameter. - */ - Parameter() noexcept - : hints(0x0), - name(), - symbol(), - unit(), - ranges() {} -}; - -/** - MIDI event. - */ -struct MidiEvent { - /** - Size of internal data. - */ - static const uint32_t kDataSize = 4; - - /** - Time offset in frames. - */ - uint32_t frame; - - /** - Number of bytes used. - */ - uint32_t size; - - /** - MIDI data. - If size > kDataSize, dataExt is used (otherwise null). - */ - uint8_t data[kDataSize]; - const uint8_t* dataExt; -}; - -/** - Time position. - The @a playing and @a frame values are always valid. - BBT values are only valid when @a bbt.valid is true. - - This struct is inspired by the JACK Transport API. - */ -struct TimePosition { - /** - Wherever the host transport is playing/rolling. - */ - bool playing; - - /** - Current host transport position in frames. - */ - uint64_t frame; - - /** - Bar-Beat-Tick time position. - */ - struct BarBeatTick { - /** - Wherever the host transport is using BBT. - If false you must not read from this struct. - */ - bool valid; - - /** - Current bar. - Should always be > 0. - The first bar is bar '1'. - */ - int32_t bar; - - /** - Current beat within bar. - Should always be > 0 and <= @a beatsPerBar. - The first beat is beat '1'. - */ - int32_t beat; - - /** - Current tick within beat. - Should always be > 0 and <= @a ticksPerBeat. - The first tick is tick '0'. - */ - int32_t tick; - - /** - Number of ticks that have elapsed between frame 0 and the first beat of the current measure. - */ - double barStartTick; - - /** - Time signature "numerator". - */ - float beatsPerBar; - - /** - Time signature "denominator". - */ - float beatType; - - /** - Number of ticks within a bar. - Usually a moderately large integer with many denominators, such as 1920.0. - */ - double ticksPerBeat; - - /** - Number of beats per minute. - */ - double beatsPerMinute; - - /** - Default constructor for a null BBT time position. - */ - BarBeatTick() noexcept - : valid(false), - bar(0), - beat(0), - tick(0), - barStartTick(0.0), - beatsPerBar(0.0f), - beatType(0.0f), - ticksPerBeat(0.0), - beatsPerMinute(0.0) {} - } bbt; - - /** - Default constructor for a time position. - */ - TimePosition() noexcept - : playing(false), - frame(0), - bbt() {} -}; - -/* ------------------------------------------------------------------------------------------------------------ - * DPF Plugin */ - -/** - DPF Plugin class from where plugin instances are created. - - The public methods (Host state) are called from the plugin to get or set host information. - They can be called from a plugin instance at anytime unless stated otherwise. - All other methods are to be implemented by the plugin and will be called by the host. - - Shortly after a plugin instance is created, the various d_init* functions will be called by the host. - Host will call d_activate() before d_run(), and d_deactivate() before the plugin instance is destroyed. - The host may call deactivate right after activate and vice-versa, but never activate/deactivate consecutively. - There is no limit on how many times d_run() is called, only that activate/deactivate will be called in between. - - The buffer size and sample rate values will remain constant between activate and deactivate. - Buffer size is only a hint though, the host might call d_run() with a higher or lower number of frames. - - Some of this class functions are only available according to some macros. - - DISTRHO_PLUGIN_WANT_PROGRAMS activates program related features. - When enabled you need to implement d_initProgramName() and d_setProgram(). - - DISTRHO_PLUGIN_WANT_STATE activates internal state features. - When enabled you need to implement d_initStateKey() and d_setState(). - - The process function d_run() changes wherever DISTRHO_PLUGIN_HAS_MIDI_INPUT is enabled or not. - When enabled it provides midi input events. - */ -class Plugin -{ -public: - /** - Plugin class constructor. - You must set all parameter values to their defaults, matching ParameterRanges::def. - If you're using states you must also set them to their defaults by calling d_setState(). - */ - Plugin(const uint32_t parameterCount, const uint32_t programCount, const uint32_t stateCount); - - /** - Destructor. - */ - virtual ~Plugin(); - - /* -------------------------------------------------------------------------------------------------------- - * Host state */ - - /** - Get the current buffer size that will probably be used during processing, in frames. - This value will remain constant between activate and deactivate. - @note: This value is only a hint! - Hosts might call d_run() with a higher or lower number of frames. - @see d_bufferSizeChanged(uint32_t) - */ - uint32_t d_getBufferSize() const noexcept; - - /** - Get the current sample rate that will be used during processing. - This value will remain constant between activate and deactivate. - @see d_sampleRateChanged(double) - */ - double d_getSampleRate() const noexcept; - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - /** - Get the current host transport time position. - This function should only be called during d_run(). - You can call this during other times, but the returned position is not guaranteed to be in sync. - @note: TimePos is not supported in LADSPA and DSSI plugin formats. - */ - const TimePosition& d_getTimePosition() const noexcept; -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - /** - Change the plugin audio output latency to @a frames. - This function should only be called in the constructor, d_activate() and d_run(). - */ - void d_setLatency(const uint32_t frames) noexcept; -#endif - -#if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT - /** - Write a MIDI output event. - This function must only be called during d_run(). - Returns false when the host buffer is full, in which case do not call this again until the next d_run(). - */ - bool d_writeMidiEvent(const MidiEvent& midiEvent) noexcept; -#endif - -protected: - /* -------------------------------------------------------------------------------------------------------- - * Information */ - - /** - Get the plugin name. - Returns DISTRHO_PLUGIN_NAME by default. - */ - virtual const char* d_getName() const { return DISTRHO_PLUGIN_NAME; } - - /** - Get the plugin label. - A plugin label follows the same rules as Parameter::symbol, with the exception that it can start with numbers. - */ - virtual const char* d_getLabel() const = 0; - - /** - Get the plugin author/maker. - */ - virtual const char* d_getMaker() const = 0; - - /** - Get the plugin license name (a single line of text). - */ - virtual const char* d_getLicense() const = 0; - - /** - Get the plugin version, in hexadecimal. - TODO format to be defined - */ - virtual uint32_t d_getVersion() const = 0; - - /** - Get the plugin unique Id. - This value is used by LADSPA, DSSI and VST plugin formats. - */ - virtual int64_t d_getUniqueId() const = 0; - - /* -------------------------------------------------------------------------------------------------------- - * Init */ - - /** - Initialize the parameter @a index. - This function will be called once, shortly after the plugin is created. - */ - virtual void d_initParameter(uint32_t index, Parameter& parameter) = 0; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - /** - Set the name of the program @a index. - This function will be called once, shortly after the plugin is created. - Must be implemented by your plugin class only if DISTRHO_PLUGIN_WANT_PROGRAMS is enabled. - */ - virtual void d_initProgramName(uint32_t index, d_string& programName) = 0; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - /** - Set the state key and default value of @a index. - This function will be called once, shortly after the plugin is created. - Must be implemented by your plugin class only if DISTRHO_PLUGIN_WANT_STATE is enabled. - */ - virtual void d_initState(uint32_t index, d_string& stateKey, d_string& defaultStateValue) = 0; -#endif - - /* -------------------------------------------------------------------------------------------------------- - * Internal data */ - - /** - Get the current value of a parameter. - The host may call this function from any context, including realtime processing. - */ - virtual float d_getParameterValue(uint32_t index) const = 0; - - /** - Change a parameter value. - The host may call this function from any context, including realtime processing. - When a parameter is marked as automable, you must ensure no non-realtime operations are called. - @note This function will only be called for parameter inputs. - */ - virtual void d_setParameterValue(uint32_t index, float value) = 0; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - /** - Change the currently used program to @a index. - The host may call this function from any context, including realtime processing. - Must be implemented by your plugin class only if DISTRHO_PLUGIN_WANT_PROGRAMS is enabled. - */ - virtual void d_setProgram(uint32_t index) = 0; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - /** - Change an internal state @a key to @a value. - Must be implemented by your plugin class only if DISTRHO_PLUGIN_WANT_STATE is enabled. - */ - virtual void d_setState(const char* key, const char* value) = 0; -#endif - - /* -------------------------------------------------------------------------------------------------------- - * Process */ - - /** - Activate this plugin. - */ - virtual void d_activate() {} - - /** - Deactivate this plugin. - */ - virtual void d_deactivate() {} - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - /** - Run/process function for plugins with MIDI input. - @note: Some parameters might be null if there are no audio inputs/outputs or MIDI events. - */ - virtual void d_run(const float** inputs, float** outputs, uint32_t frames, - const MidiEvent* midiEvents, uint32_t midiEventCount) = 0; -#else - /** - Run/process function for plugins without MIDI input. - @note: Some parameters might be null if there are no audio inputs or outputs. - */ - virtual void d_run(const float** inputs, float** outputs, uint32_t frames) = 0; -#endif - - /* -------------------------------------------------------------------------------------------------------- - * Callbacks (optional) */ - - /** - Optional callback to inform the plugin about a buffer size change. - This function will only be called when the plugin is deactivated. - @note: This value is only a hint! - Hosts might call d_run() with a higher or lower number of frames. - @see d_getBufferSize() - */ - virtual void d_bufferSizeChanged(uint32_t newBufferSize); - - /** - Optional callback to inform the plugin about a sample rate change. - This function will only be called when the plugin is deactivated. - @see d_getSampleRate() - */ - virtual void d_sampleRateChanged(double newSampleRate); - - // ------------------------------------------------------------------------------------------------------- - -private: - struct PrivateData; - PrivateData* const pData; - friend class PluginExporter; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Plugin) -}; - -/* ------------------------------------------------------------------------------------------------------------ - * Create plugin, entry point */ - -/** - TODO. - */ -extern Plugin* createPlugin(); - -// ----------------------------------------------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_PLUGIN_HPP_INCLUDED diff --git a/libs/distrho/DistrhoPluginMain.cpp b/libs/distrho/DistrhoPluginMain.cpp deleted file mode 100644 index 8fce7db..0000000 --- a/libs/distrho/DistrhoPluginMain.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "src/DistrhoPlugin.cpp" - -#if defined(DISTRHO_PLUGIN_TARGET_CARLA) -# include "src/DistrhoPluginCarla.cpp" -#elif defined(DISTRHO_PLUGIN_TARGET_JACK) -# include "src/DistrhoPluginJack.cpp" -#elif (defined(DISTRHO_PLUGIN_TARGET_LADSPA) || defined(DISTRHO_PLUGIN_TARGET_DSSI)) -# include "src/DistrhoPluginLADSPA+DSSI.cpp" -#elif defined(DISTRHO_PLUGIN_TARGET_LV2) -# include "src/DistrhoPluginLV2.cpp" -# include "src/DistrhoPluginLV2export.cpp" -#elif defined(DISTRHO_PLUGIN_TARGET_VST) -# include "src/DistrhoPluginVST.cpp" -#endif diff --git a/libs/distrho/DistrhoUI.hpp b/libs/distrho/DistrhoUI.hpp deleted file mode 100644 index 2832db0..0000000 --- a/libs/distrho/DistrhoUI.hpp +++ /dev/null @@ -1,196 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_UI_HPP_INCLUDED -#define DISTRHO_UI_HPP_INCLUDED - -#include "extra/d_leakdetector.hpp" -#include "src/DistrhoPluginChecks.h" - -#if DISTRHO_UI_USE_NANOVG -# include "../dgl/NanoVG.hpp" -typedef DGL::NanoWidget UIWidget; -#else -# include "../dgl/Widget.hpp" -typedef DGL::Widget UIWidget; -#endif - -START_NAMESPACE_DISTRHO - -/* ------------------------------------------------------------------------------------------------------------ - * DPF UI */ - -/** - DPF UI class from where UI instances are created. - - TODO. - - must call setSize during construction, - */ -class UI : public UIWidget -{ -public: - /** - UI class constructor. - The UI should be initialized to a default state that matches the plugin side. - */ - UI(); - - /** - Destructor. - */ - virtual ~UI(); - - /* -------------------------------------------------------------------------------------------------------- - * Host state */ - - /** - Get the current sample rate used in plugin processing. - @see d_sampleRateChanged(double) - */ - double d_getSampleRate() const noexcept; - - /** - TODO: Document this. - */ - void d_editParameter(const uint32_t index, const bool started); - - /** - TODO: Document this. - */ - void d_setParameterValue(const uint32_t index, const float value); - -#if DISTRHO_PLUGIN_WANT_STATE - /** - TODO: Document this. - */ - void d_setState(const char* const key, const char* const value); -#endif - -#if DISTRHO_PLUGIN_IS_SYNTH - /** - TODO: Document this. - */ - void d_sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity); -#endif - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - /* -------------------------------------------------------------------------------------------------------- - * Direct DSP access - DO NOT USE THIS UNLESS STRICTLY NECESSARY!! */ - - /** - TODO: Document this. - */ - void* d_getPluginInstancePointer() const noexcept; -#endif - -protected: - /* -------------------------------------------------------------------------------------------------------- - * DSP/Plugin Callbacks */ - - /** - A parameter has changed on the plugin side. - This is called by the host to inform the UI about parameter changes. - */ - virtual void d_parameterChanged(uint32_t index, float value) = 0; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - /** - The current program has changed on the plugin side. - This is called by the host to inform the UI about program changes. - */ - virtual void d_programChanged(uint32_t index) = 0; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - /** - A state has changed on the plugin side. - This is called by the host to inform the UI about state changes. - */ - virtual void d_stateChanged(const char* key, const char* value) = 0; -#endif - - /* -------------------------------------------------------------------------------------------------------- - * DSP/Plugin Callbacks (optional) */ - - /** - Optional callback to inform the UI about a sample rate change on the plugin side. - @see d_getSampleRate() - */ - virtual void d_sampleRateChanged(double newSampleRate); - - /* -------------------------------------------------------------------------------------------------------- - * UI Callbacks (optional) */ - - /** - TODO: Document this. - */ - virtual void d_uiIdle() {} - - /** - File browser selected function. - @see Window::fileBrowserSelected(const char*) - */ - virtual void d_uiFileBrowserSelected(const char* filename); - - /** - OpenGL window reshape function, called when parent window is resized. - You can reimplement this function for a custom OpenGL state. - @see Window::onReshape(uint,uint) - */ - virtual void d_uiReshape(uint width, uint height); - - /* -------------------------------------------------------------------------------------------------------- - * UI Resize Handling, internal */ - - /** - OpenGL widget resize function, called when the widget is resized. - This is overriden here so the host knows when the UI is resized by you. - @see Widget::onResize(const ResizeEvent&) - */ - void onResize(const ResizeEvent& ev) override; - - // ------------------------------------------------------------------------------------------------------- - -private: - struct PrivateData; - PrivateData* const pData; - friend class UIExporter; - friend class UIExporterWindow; - - // these should not be used - void setAbsoluteX(int) const noexcept {} - void setAbsoluteY(int) const noexcept {} - void setAbsolutePos(int, int) const noexcept {} - void setAbsolutePos(const DGL::Point<int>&) const noexcept {} - void setNeedsFullViewport(bool) const noexcept {} - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UI) -}; - -/* ------------------------------------------------------------------------------------------------------------ - * Create UI, entry point */ - -/** - TODO. - */ -extern UI* createUI(); - -// ----------------------------------------------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_UI_HPP_INCLUDED diff --git a/libs/distrho/DistrhoUIMain.cpp b/libs/distrho/DistrhoUIMain.cpp deleted file mode 100644 index cb1cb6e..0000000 --- a/libs/distrho/DistrhoUIMain.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "src/DistrhoUI.cpp" - -#if defined(DISTRHO_PLUGIN_TARGET_CARLA) -// nothing -#elif defined(DISTRHO_PLUGIN_TARGET_JACK) -// nothing -#elif defined(DISTRHO_PLUGIN_TARGET_DSSI) -# include "src/DistrhoUIDSSI.cpp" -#elif defined(DISTRHO_PLUGIN_TARGET_LV2) -# include "src/DistrhoUILV2.cpp" -#elif defined(DISTRHO_PLUGIN_TARGET_VST) -// nothing -#endif diff --git a/libs/distrho/DistrhoUtils.hpp b/libs/distrho/DistrhoUtils.hpp deleted file mode 100644 index b1391ef..0000000 --- a/libs/distrho/DistrhoUtils.hpp +++ /dev/null @@ -1,202 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_UTILS_HPP_INCLUDED -#define DISTRHO_UTILS_HPP_INCLUDED - -#include "src/DistrhoDefines.h" - -#include <cstdarg> -#include <cstdio> -#include <cstdlib> -#include <cstring> - -#include <cmath> -#include <limits> - -#ifdef DISTRHO_PROPER_CPP11_SUPPORT -# include <cstdint> -#else -# include <stdint.h> -#endif - -#if defined(DISTRHO_OS_MAC) && ! defined(CARLA_OS_MAC) -namespace std { -inline float fmin(float __x, float __y) - { return __builtin_fminf(__x, __y); } -inline float fmax(float __x, float __y) - { return __builtin_fmaxf(__x, __y); } -inline float rint(float __x) - { return __builtin_rintf(__x); } -inline float round(float __x) - { return __builtin_roundf(__x); } -} -#endif - -// ----------------------------------------------------------------------- -// misc functions - -/* - * Return a 64-bit number from 4 8-bit numbers. - */ -static inline -int64_t d_cconst(const uint8_t a, const uint8_t b, const uint8_t c, const uint8_t d) noexcept -{ - return (a << 24) | (b << 16) | (c << 8) | (d << 0); -} - -/* - * Dummy function. - */ -static inline -void d_pass() noexcept {} - -// ----------------------------------------------------------------------- -// string print functions - -/* - * Print a string to stdout with newline (gray color). - * Does nothing if DEBUG is not defined. - */ -#ifndef DEBUG -# define d_debug(...) -#else -static inline -void d_debug(const char* const fmt, ...) noexcept -{ - try { - ::va_list args; - ::va_start(args, fmt); - std::fprintf(stdout, "\x1b[30;1m"); - std::vfprintf(stdout, fmt, args); - std::fprintf(stdout, "\x1b[0m\n"); - ::va_end(args); - } catch (...) {} -} -#endif - -/* - * Print a string to stdout with newline. - */ -static inline -void d_stdout(const char* const fmt, ...) noexcept -{ - try { - ::va_list args; - ::va_start(args, fmt); - std::vfprintf(stdout, fmt, args); - std::fprintf(stdout, "\n"); - ::va_end(args); - } catch (...) {} -} - -/* - * Print a string to stderr with newline. - */ -static inline -void d_stderr(const char* const fmt, ...) noexcept -{ - try { - ::va_list args; - ::va_start(args, fmt); - std::vfprintf(stderr, fmt, args); - std::fprintf(stderr, "\n"); - ::va_end(args); - } catch (...) {} -} - -/* - * Print a string to stderr with newline (red color). - */ -static inline -void d_stderr2(const char* const fmt, ...) noexcept -{ - try { - ::va_list args; - ::va_start(args, fmt); - std::fprintf(stderr, "\x1b[31m"); - std::vfprintf(stderr, fmt, args); - std::fprintf(stderr, "\x1b[0m\n"); - ::va_end(args); - } catch (...) {} -} - -/* - * Print a safe assertion error message. - */ -static inline -void d_safe_assert(const char* const assertion, const char* const file, const int line) noexcept -{ - d_stderr2("assertion failure: \"%s\" in file %s, line %i", assertion, file, line); -} - -/* - * Print a safe exception error message. - */ -static inline -void d_safe_exception(const char* const exception, const char* const file, const int line) noexcept -{ - d_stderr2("exception caught: \"%s\" in file %s, line %i", exception, file, line); -} - -// ----------------------------------------------------------------------- -// math functions - -/* - * Safely compare two floating point numbers. - * Returns true if they match. - */ -template<typename T> -static inline -bool d_isEqual(const T& v1, const T& v2) -{ - return std::abs(v1-v2) < std::numeric_limits<T>::epsilon(); -} - -/* - * Safely compare two floating point numbers. - * Returns true if they don't match. - */ -template<typename T> -static inline -bool d_isNotEqual(const T& v1, const T& v2) -{ - return std::abs(v1-v2) >= std::numeric_limits<T>::epsilon(); -} - -/* - * Safely check if a floating point number is zero. - */ -template<typename T> -static inline -bool d_isZero(const T& value) -{ - return std::abs(value) < std::numeric_limits<T>::epsilon(); -} - -/* - * Safely check if a floating point number is not zero. - */ -template<typename T> -static inline -bool d_isNotZero(const T& value) -{ - return std::abs(value) >= std::numeric_limits<T>::epsilon(); -} - -// ----------------------------------------------------------------------- - -#endif // DISTRHO_UTILS_HPP_INCLUDED diff --git a/libs/distrho/extra/d_leakdetector.hpp b/libs/distrho/extra/d_leakdetector.hpp deleted file mode 100644 index 2840c2d..0000000 --- a/libs/distrho/extra/d_leakdetector.hpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_LEAK_DETECTOR_HPP_INCLUDED -#define DISTRHO_LEAK_DETECTOR_HPP_INCLUDED - -#include "../DistrhoUtils.hpp" - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// The following code was based from juce-core LeakDetector class -// Copyright (C) 2013 Raw Material Software Ltd. - -/** A good old-fashioned C macro concatenation helper. - This combines two items (which may themselves be macros) into a single string, - avoiding the pitfalls of the ## macro operator. -*/ -#define DISTRHO_JOIN_MACRO_HELPER(a, b) a ## b -#define DISTRHO_JOIN_MACRO(item1, item2) DISTRHO_JOIN_MACRO_HELPER(item1, item2) - -/** This macro lets you embed a leak-detecting object inside a class.\n - To use it, simply declare a DISTRHO_LEAK_DETECTOR(YourClassName) inside a private section - of the class declaration. E.g. - \code - class MyClass - { - public: - MyClass(); - void blahBlah(); - - private: - DISTRHO_LEAK_DETECTOR(MyClass) - }; - \endcode -*/ -#define DISTRHO_LEAK_DETECTOR(ClassName) \ - friend class DISTRHO_NAMESPACE::LeakedObjectDetector<ClassName>; \ - static const char* getLeakedObjectClassName() noexcept { return #ClassName; } \ - DISTRHO_NAMESPACE::LeakedObjectDetector<ClassName> DISTRHO_JOIN_MACRO(leakDetector_, ClassName); - -#define DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \ - DISTRHO_DECLARE_NON_COPY_CLASS(ClassName) \ - DISTRHO_LEAK_DETECTOR(ClassName) - -//============================================================================== -/** - Embedding an instance of this class inside another class can be used as a low-overhead - way of detecting leaked instances. - - This class keeps an internal static count of the number of instances that are - active, so that when the app is shutdown and the static destructors are called, - it can check whether there are any left-over instances that may have been leaked. - - To use it, use the DISTRHO_LEAK_DETECTOR macro as a simple way to put one in your - class declaration. -*/ -template<class OwnerClass> -class LeakedObjectDetector -{ -public: - //============================================================================== - LeakedObjectDetector() noexcept { ++(getCounter().numObjects); } - LeakedObjectDetector(const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); } - - ~LeakedObjectDetector() noexcept - { - if (--(getCounter().numObjects) < 0) - { - /** If you hit this, then you've managed to delete more instances of this class than you've - created.. That indicates that you're deleting some dangling pointers. - - Note that although this assertion will have been triggered during a destructor, it might - not be this particular deletion that's at fault - the incorrect one may have happened - at an earlier point in the program, and simply not been detected until now. - - Most errors like this are caused by using old-fashioned, non-RAII techniques for - your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays, - ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs! - */ - d_stderr2("*** Dangling pointer deletion! Class: '%s', Count: %i", getLeakedObjectClassName(), getCounter().numObjects); - } - } - -private: - //============================================================================== - class LeakCounter - { - public: - LeakCounter() noexcept - : numObjects(0) {} - - ~LeakCounter() noexcept - { - if (numObjects > 0) - { - /** If you hit this, then you've leaked one or more objects of the type specified by - the 'OwnerClass' template parameter - the name should have been printed by the line above. - - If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for - your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays, - ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs! - */ - d_stderr2("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects, getLeakedObjectClassName()); - } - } - - // this should be an atomic... - volatile int numObjects; - }; - - static const char* getLeakedObjectClassName() noexcept - { - return OwnerClass::getLeakedObjectClassName(); - } - - static LeakCounter& getCounter() noexcept - { - static LeakCounter counter; - return counter; - } -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_LEAK_DETECTOR_HPP_INCLUDED diff --git a/libs/distrho/extra/d_mutex.hpp b/libs/distrho/extra/d_mutex.hpp deleted file mode 100644 index df704e0..0000000 --- a/libs/distrho/extra/d_mutex.hpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_MUTEX_HPP_INCLUDED -#define DISTRHO_MUTEX_HPP_INCLUDED - -#include "../DistrhoUtils.hpp" - -#ifdef DISTRHO_OS_WINDOWS -# include <winsock2.h> -# include <windows.h> -#endif - -#include <pthread.h> - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// Mutex class - -class Mutex -{ -public: - /* - * Constructor. - */ - Mutex() noexcept - { - pthread_mutex_init(&fMutex, nullptr); - } - - /* - * Destructor. - */ - ~Mutex() noexcept - { - pthread_mutex_destroy(&fMutex); - } - - /* - * Lock the mutex. - */ - void lock() const noexcept - { - pthread_mutex_lock(&fMutex); - } - - /* - * Try to lock the mutex. - * Returns true if successful. - */ - bool tryLock() const noexcept - { - return (pthread_mutex_trylock(&fMutex) == 0); - } - - /* - * Unlock the mutex. - */ - void unlock() const noexcept - { - pthread_mutex_unlock(&fMutex); - } - -private: - mutable pthread_mutex_t fMutex; - - DISTRHO_PREVENT_HEAP_ALLOCATION - DISTRHO_DECLARE_NON_COPY_CLASS(Mutex) -}; - -// ----------------------------------------------------------------------- -// RecursiveMutex class - -class RecursiveMutex -{ -public: - /* - * Constructor. - */ - RecursiveMutex() noexcept - { -#ifdef DISTRHO_OS_WINDOWS - InitializeCriticalSection(&fSection); -#else - pthread_mutexattr_t atts; - pthread_mutexattr_init(&atts); - pthread_mutexattr_settype(&atts, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&fMutex, &atts); - pthread_mutexattr_destroy(&atts); -#endif - } - - /* - * Destructor. - */ - ~RecursiveMutex() noexcept - { -#ifdef DISTRHO_OS_WINDOWS - DeleteCriticalSection(&fSection); -#else - pthread_mutex_destroy(&fMutex); -#endif - } - - /* - * Lock the mutex. - */ - void lock() const noexcept - { -#ifdef DISTRHO_OS_WINDOWS - EnterCriticalSection(&fSection); -#else - pthread_mutex_lock(&fMutex); -#endif - } - - /* - * Try to lock the mutex. - * Returns true if successful. - */ - bool tryLock() const noexcept - { -#ifdef DISTRHO_OS_WINDOWS - return (TryEnterCriticalSection(&fSection) != FALSE); -#else - return (pthread_mutex_trylock(&fMutex) == 0); -#endif - } - - /* - * Unlock the mutex. - */ - void unlock() const noexcept - { -#ifdef DISTRHO_OS_WINDOWS - LeaveCriticalSection(&fSection); -#else - pthread_mutex_unlock(&fMutex); -#endif - } - -private: -#ifdef DISTRHO_OS_WINDOWS - mutable CRITICAL_SECTION fSection; -#else - mutable pthread_mutex_t fMutex; -#endif - - DISTRHO_PREVENT_HEAP_ALLOCATION - DISTRHO_DECLARE_NON_COPY_CLASS(RecursiveMutex) -}; - -// ----------------------------------------------------------------------- -// Helper class to lock&unlock a mutex during a function scope. - -template <class Mutex> -class ScopedLocker -{ -public: - ScopedLocker(const Mutex& mutex) noexcept - : fMutex(mutex) - { - fMutex.lock(); - } - - ~ScopedLocker() noexcept - { - fMutex.unlock(); - } - -private: - const Mutex& fMutex; - - DISTRHO_PREVENT_HEAP_ALLOCATION - DISTRHO_DECLARE_NON_COPY_CLASS(ScopedLocker) -}; - -// ----------------------------------------------------------------------- -// Helper class to unlock&lock a mutex during a function scope. - -template <class Mutex> -class ScopedUnlocker -{ -public: - ScopedUnlocker(const Mutex& mutex) noexcept - : fMutex(mutex) - { - fMutex.unlock(); - } - - ~ScopedUnlocker() noexcept - { - fMutex.lock(); - } - -private: - const Mutex& fMutex; - - DISTRHO_PREVENT_HEAP_ALLOCATION - DISTRHO_DECLARE_NON_COPY_CLASS(ScopedUnlocker) -}; - -// ----------------------------------------------------------------------- -// Define types - -typedef ScopedLocker<Mutex> MutexLocker; -typedef ScopedLocker<RecursiveMutex> RecursiveMutexLocker; - -typedef ScopedUnlocker<Mutex> MutexUnlocker; -typedef ScopedUnlocker<RecursiveMutex> RecursiveMutexUnlocker; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_MUTEX_HPP_INCLUDED diff --git a/libs/distrho/extra/d_scopedpointer.hpp b/libs/distrho/extra/d_scopedpointer.hpp deleted file mode 100644 index bde4e7b..0000000 --- a/libs/distrho/extra/d_scopedpointer.hpp +++ /dev/null @@ -1,247 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_SCOPED_POINTER_HPP_INCLUDED -#define DISTRHO_SCOPED_POINTER_HPP_INCLUDED - -#include "../DistrhoUtils.hpp" - -#include <algorithm> - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// The following code was based from juce-core ScopedPointer class -// Copyright (C) 2013 Raw Material Software Ltd. - -/** - Used by container classes as an indirect way to delete an object of a - particular type. - - The generic implementation of this class simply calls 'delete', but you can - create a specialised version of it for a particular class if you need to - delete that type of object in a more appropriate way. -*/ -template<typename ObjectType> -struct ContainerDeletePolicy -{ - static void destroy(ObjectType* const object) - { - delete object; - } -}; - -//============================================================================== -/** - This class holds a pointer which is automatically deleted when this object goes - out of scope. - - Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer - gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or - as member variables is a good way to use RAII to avoid accidentally leaking dynamically - created objects. - - A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer - to an object. If you use the assignment operator to assign a different object to a - ScopedPointer, the old one will be automatically deleted. - - A const ScopedPointer is guaranteed not to lose ownership of its object or change the - object to which it points during its lifetime. This means that making a copy of a const - ScopedPointer is impossible, as that would involve the new copy taking ownership from the - old one. - - If you need to get a pointer out of a ScopedPointer without it being deleted, you - can use the release() method. - - Something to note is the main difference between this class and the std::auto_ptr class, - which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr - requires that you always call get() to retrieve the pointer. The advantages of providing - the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much - exactly the same way as a raw pointer. The disadvantage is that the compiler is free to - use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult - to return a ScopedPointer as the result of a function. To avoid this causing errors, - ScopedPointer contains an overloaded constructor that should cause a syntax error in these - circumstances, but it does mean that instead of returning a ScopedPointer from a function, - you'd need to return a raw pointer (or use a std::auto_ptr instead). -*/ -template<class ObjectType> -class ScopedPointer -{ -public: - //============================================================================== - /** Creates a ScopedPointer containing a null pointer. */ - ScopedPointer() noexcept - : object(nullptr) {} - - /** Creates a ScopedPointer that owns the specified object. */ - ScopedPointer(ObjectType* const objectToTakePossessionOf) noexcept - : object(objectToTakePossessionOf) {} - - /** Creates a ScopedPointer that takes its pointer from another ScopedPointer. - - Because a pointer can only belong to one ScopedPointer, this transfers - the pointer from the other object to this one, and the other object is reset to - be a null pointer. - */ - ScopedPointer(ScopedPointer& objectToTransferFrom) noexcept - : object(objectToTransferFrom.object) - { - objectToTransferFrom.object = nullptr; - } - - /** Destructor. - This will delete the object that this ScopedPointer currently refers to. - */ - ~ScopedPointer() - { - ContainerDeletePolicy<ObjectType>::destroy(object); - } - - /** Changes this ScopedPointer to point to a new object. - - Because a pointer can only belong to one ScopedPointer, this transfers - the pointer from the other object to this one, and the other object is reset to - be a null pointer. - - If this ScopedPointer already points to an object, that object - will first be deleted. - */ - ScopedPointer& operator=(ScopedPointer& objectToTransferFrom) - { - if (this != objectToTransferFrom.getAddress()) - { - // Two ScopedPointers should never be able to refer to the same object - if - // this happens, you must have done something dodgy! - DISTRHO_SAFE_ASSERT_RETURN(object == nullptr || object != objectToTransferFrom.object, *this); - - ObjectType* const oldObject = object; - object = objectToTransferFrom.object; - objectToTransferFrom.object = nullptr; - ContainerDeletePolicy<ObjectType>::destroy(oldObject); - } - - return *this; - } - - /** Changes this ScopedPointer to point to a new object. - - If this ScopedPointer already points to an object, that object - will first be deleted. - - The pointer that you pass in may be a nullptr. - */ - ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf) - { - if (object != newObjectToTakePossessionOf) - { - ObjectType* const oldObject = object; - object = newObjectToTakePossessionOf; - ContainerDeletePolicy<ObjectType>::destroy(oldObject); - } - - return *this; - } - - //============================================================================== - /** Returns the object that this ScopedPointer refers to. */ - operator ObjectType*() const noexcept { return object; } - - /** Returns the object that this ScopedPointer refers to. */ - ObjectType* get() const noexcept { return object; } - - /** Returns the object that this ScopedPointer refers to. */ - ObjectType& operator*() const noexcept { return *object; } - - /** Lets you access methods and properties of the object that this ScopedPointer refers to. */ - ObjectType* operator->() const noexcept { return object; } - - //============================================================================== - /** Removes the current object from this ScopedPointer without deleting it. - This will return the current object, and set the ScopedPointer to a null pointer. - */ - ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; } - - //============================================================================== - /** Swaps this object with that of another ScopedPointer. - The two objects simply exchange their pointers. - */ - void swapWith(ScopedPointer<ObjectType>& other) noexcept - { - // Two ScopedPointers should never be able to refer to the same object - if - // this happens, you must have done something dodgy! - DISTRHO_SAFE_ASSERT_RETURN(object != other.object || this == other.getAddress() || object == nullptr,); - - std::swap(object, other.object); - } - -private: - //============================================================================== - ObjectType* object; - - // (Required as an alternative to the overloaded & operator). - const ScopedPointer* getAddress() const noexcept { return this; } - -#ifndef _MSC_VER // (MSVC can't deal with multiple copy constructors) - /* The copy constructors are private to stop people accidentally copying a const ScopedPointer - (the compiler would let you do so by implicitly casting the source to its raw object pointer). - - A side effect of this is that in a compiler that doesn't support C++11, you may hit an - error when you write something like this: - - ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private. - - Even though the compiler would normally ignore the assignment here, it can't do so when the - copy constructor is private. It's very easy to fix though - just write it like this: - - ScopedPointer<MyClass> m (new MyClass()); // Compiles OK - - It's probably best to use the latter form when writing your object declarations anyway, as - this is a better representation of the code that you actually want the compiler to produce. - */ -# ifdef DISTRHO_PROPER_CPP11_SUPPORT - ScopedPointer(const ScopedPointer&) = delete; - ScopedPointer& operator=(const ScopedPointer&) = delete; -# else - ScopedPointer(const ScopedPointer&); - ScopedPointer& operator=(const ScopedPointer&); -# endif -#endif -}; - -//============================================================================== -/** Compares a ScopedPointer with another pointer. - This can be handy for checking whether this is a null pointer. -*/ -template<class ObjectType> -bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept -{ - return static_cast<ObjectType*>(pointer1) == pointer2; -} - -/** Compares a ScopedPointer with another pointer. - This can be handy for checking whether this is a null pointer. -*/ -template<class ObjectType> -bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept -{ - return static_cast<ObjectType*>(pointer1) != pointer2; -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_SCOPED_POINTER_HPP_INCLUDED diff --git a/libs/distrho/extra/d_sleep.hpp b/libs/distrho/extra/d_sleep.hpp deleted file mode 100644 index c9c2c59..0000000 --- a/libs/distrho/extra/d_sleep.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_SLEEP_HPP_INCLUDED -#define DISTRHO_SLEEP_HPP_INCLUDED - -#include "../DistrhoUtils.hpp" - -#ifdef DISTRHO_OS_WINDOWS -# include <winsock2.h> -# include <windows.h> -#else -# include <unistd.h> -#endif - -// ----------------------------------------------------------------------- -// d_*sleep - -static inline -void d_sleep(const uint secs) noexcept -{ - DISTRHO_SAFE_ASSERT_RETURN(secs > 0,); - - try { -#ifdef DISTRHO_OS_WINDOWS - ::Sleep(secs * 1000); -#else - ::sleep(secs); -#endif - } DISTRHO_SAFE_EXCEPTION("d_sleep"); -} - -static inline -void d_msleep(const uint msecs) noexcept -{ - DISTRHO_SAFE_ASSERT_RETURN(msecs > 0,); - - try { -#ifdef DISTRHO_OS_WINDOWS - ::Sleep(msecs); -#else - ::usleep(msecs * 1000); -#endif - } DISTRHO_SAFE_EXCEPTION("d_msleep"); -} - -// ----------------------------------------------------------------------- - -#endif // DISTRHO_SLEEP_HPP_INCLUDED diff --git a/libs/distrho/extra/d_string.hpp b/libs/distrho/extra/d_string.hpp deleted file mode 100644 index 0420c42..0000000 --- a/libs/distrho/extra/d_string.hpp +++ /dev/null @@ -1,750 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_STRING_HPP_INCLUDED -#define DISTRHO_STRING_HPP_INCLUDED - -#include "d_leakdetector.hpp" - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// d_string class - -class d_string -{ -public: - // ------------------------------------------------------------------- - // constructors (no explicit conversions allowed) - - /* - * Empty string. - */ - explicit d_string() noexcept - { - _init(); - } - - /* - * Simple character. - */ - explicit d_string(const char c) noexcept - { - char ch[2]; - ch[0] = c; - ch[1] = '\0'; - - _init(); - _dup(ch); - } - - /* - * Simple char string. - */ - explicit d_string(char* const strBuf) noexcept - { - _init(); - _dup(strBuf); - } - - /* - * Simple const char string. - */ - explicit d_string(const char* const strBuf) noexcept - { - _init(); - _dup(strBuf); - } - - /* - * Integer. - */ - explicit d_string(const int value) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, "%d", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Unsigned integer, possibly in hexadecimal. - */ - explicit d_string(const unsigned int value, const bool hexadecimal = false) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, hexadecimal ? "0x%x" : "%u", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Long integer. - */ - explicit d_string(const long value) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, "%ld", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Long unsigned integer, possibly hexadecimal. - */ - explicit d_string(const unsigned long value, const bool hexadecimal = false) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, hexadecimal ? "0x%lx" : "%lu", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Long long integer. - */ - explicit d_string(const long long value) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, "%lld", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Long long unsigned integer, possibly hexadecimal. - */ - explicit d_string(const unsigned long long value, const bool hexadecimal = false) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, hexadecimal ? "0x%llx" : "%llu", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Single-precision floating point number. - */ - explicit d_string(const float value) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, "%f", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - /* - * Double-precision floating point number. - */ - explicit d_string(const double value) noexcept - { - char strBuf[0xff+1]; - std::snprintf(strBuf, 0xff, "%g", value); - strBuf[0xff] = '\0'; - - _init(); - _dup(strBuf); - } - - // ------------------------------------------------------------------- - // non-explicit constructor - - /* - * Create string from another string. - */ - d_string(const d_string& str) noexcept - { - _init(); - _dup(str.fBuffer); - } - - // ------------------------------------------------------------------- - // destructor - - /* - * Destructor. - */ - ~d_string() noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fBuffer != nullptr,); - - if (fBuffer == _null()) - return; - - std::free(fBuffer); - - fBuffer = nullptr; - fBufferLen = 0; - } - - // ------------------------------------------------------------------- - // public methods - - /* - * Get length of the string. - */ - size_t length() const noexcept - { - return fBufferLen; - } - - /* - * Check if the string is empty. - */ - bool isEmpty() const noexcept - { - return (fBufferLen == 0); - } - - /* - * Check if the string is not empty. - */ - bool isNotEmpty() const noexcept - { - return (fBufferLen != 0); - } - - /* - * Check if the string contains another string, optionally ignoring case. - */ - bool contains(const char* const strBuf, const bool ignoreCase = false) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(strBuf != nullptr, false); - - if (ignoreCase) - { -#ifdef __USE_GNU - return (strcasestr(fBuffer, strBuf) != nullptr); -#else - d_string tmp1(fBuffer), tmp2(strBuf); - - // memory allocation failed or empty string(s) - if (tmp1.fBuffer == _null() || tmp2.fBuffer == _null()) - return false; - - tmp1.toLower(); - tmp2.toLower(); - return (std::strstr(tmp1, tmp2) != nullptr); -#endif - } - - return (std::strstr(fBuffer, strBuf) != nullptr); - } - - /* - * Check if character at 'pos' is a digit. - */ - bool isDigit(const size_t pos) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(pos < fBufferLen, false); - - return (fBuffer[pos] >= '0' && fBuffer[pos] <= '9'); - } - - /* - * Check if the string starts with the character 'c'. - */ - bool startsWith(const char c) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(c != '\0', false); - - return (fBufferLen > 0 && fBuffer[0] == c); - } - - /* - * Check if the string starts with the string 'prefix'. - */ - bool startsWith(const char* const prefix) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(prefix != nullptr, false); - - const size_t prefixLen(std::strlen(prefix)); - - if (fBufferLen < prefixLen) - return false; - - return (std::strncmp(fBuffer, prefix, prefixLen) == 0); - } - - /* - * Check if the string ends with the character 'c'. - */ - bool endsWith(const char c) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(c != '\0', false); - - return (fBufferLen > 0 && fBuffer[fBufferLen-1] == c); - } - - /* - * Check if the string ends with the string 'suffix'. - */ - bool endsWith(const char* const suffix) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(suffix != nullptr, false); - - const size_t suffixLen(std::strlen(suffix)); - - if (fBufferLen < suffixLen) - return false; - - return (std::strncmp(fBuffer + (fBufferLen-suffixLen), suffix, suffixLen) == 0); - } - - /* - * Find the first occurrence of character 'c' in the string. - * Returns "length()" if the character is not found. - */ - size_t find(const char c, bool* const found = nullptr) const noexcept - { - if (fBufferLen == 0 || c == '\0') - { - if (found != nullptr) - *found = false; - return fBufferLen; - } - - for (size_t i=0; i < fBufferLen; ++i) - { - if (fBuffer[i] == c) - { - if (found != nullptr) - *found = true; - return i; - } - } - - if (found != nullptr) - *found = false; - return fBufferLen; - } - - /* - * Find the first occurrence of string 'strBuf' in the string. - * Returns "length()" if the string is not found. - */ - size_t find(const char* const strBuf, bool* const found = nullptr) const noexcept - { - if (fBufferLen == 0 || strBuf == nullptr || strBuf[0] == '\0') - { - if (found != nullptr) - *found = false; - return fBufferLen; - } - - if (char* const subStrBuf = std::strstr(fBuffer, strBuf)) - { - const ssize_t ret(subStrBuf - fBuffer); - - if (ret < 0) - { - // should never happen! - d_safe_assert("ret >= 0", __FILE__, __LINE__); - - if (found != nullptr) - *found = false; - return fBufferLen; - } - - if (found != nullptr) - *found = true; - return static_cast<size_t>(ret); - } - - if (found != nullptr) - *found = false; - return fBufferLen; - } - - /* - * Find the last occurrence of character 'c' in the string. - * Returns "length()" if the character is not found. - */ - size_t rfind(const char c, bool* const found = nullptr) const noexcept - { - if (fBufferLen == 0 || c == '\0') - { - if (found != nullptr) - *found = false; - return fBufferLen; - } - - for (size_t i=fBufferLen; i > 0; --i) - { - if (fBuffer[i-1] == c) - { - if (found != nullptr) - *found = true; - return i-1; - } - } - - if (found != nullptr) - *found = false; - return fBufferLen; - } - - /* - * Find the last occurrence of string 'strBuf' in the string. - * Returns "length()" if the string is not found. - */ - size_t rfind(const char* const strBuf, bool* const found = nullptr) const noexcept - { - if (found != nullptr) - *found = false; - - if (fBufferLen == 0 || strBuf == nullptr || strBuf[0] == '\0') - return fBufferLen; - - const size_t strBufLen(std::strlen(strBuf)); - - size_t ret = fBufferLen; - const char* tmpBuf = fBuffer; - - for (size_t i=0; i < fBufferLen; ++i) - { - if (std::strstr(tmpBuf+1, strBuf) == nullptr && std::strncmp(tmpBuf, strBuf, strBufLen) == 0) - { - if (found != nullptr) - *found = true; - break; - } - - --ret; - ++tmpBuf; - } - - return fBufferLen-ret; - } - - /* - * Clear the string. - */ - void clear() noexcept - { - truncate(0); - } - - /* - * Replace all occurrences of character 'before' with character 'after'. - */ - void replace(const char before, const char after) noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(before != '\0' && after != '\0',); - - for (size_t i=0; i < fBufferLen; ++i) - { - if (fBuffer[i] == before) - fBuffer[i] = after; - } - } - - /* - * Truncate the string to size 'n'. - */ - void truncate(const size_t n) noexcept - { - if (n >= fBufferLen) - return; - - for (size_t i=n; i < fBufferLen; ++i) - fBuffer[i] = '\0'; - - fBufferLen = n; - } - - /* - * Convert all non-basic characters to '_'. - */ - void toBasic() noexcept - { - for (size_t i=0; i < fBufferLen; ++i) - { - if (fBuffer[i] >= '0' && fBuffer[i] <= '9') - continue; - if (fBuffer[i] >= 'A' && fBuffer[i] <= 'Z') - continue; - if (fBuffer[i] >= 'a' && fBuffer[i] <= 'z') - continue; - if (fBuffer[i] == '_') - continue; - - fBuffer[i] = '_'; - } - } - - /* - * Convert to all ascii characters to lowercase. - */ - void toLower() noexcept - { - static const char kCharDiff('a' - 'A'); - - for (size_t i=0; i < fBufferLen; ++i) - { - if (fBuffer[i] >= 'A' && fBuffer[i] <= 'Z') - fBuffer[i] = static_cast<char>(fBuffer[i] + kCharDiff); - } - } - - /* - * Convert to all ascii characters to uppercase. - */ - void toUpper() noexcept - { - static const char kCharDiff('a' - 'A'); - - for (size_t i=0; i < fBufferLen; ++i) - { - if (fBuffer[i] >= 'a' && fBuffer[i] <= 'z') - fBuffer[i] = static_cast<char>(fBuffer[i] - kCharDiff); - } - } - - /* - * Direct access to the string buffer (read-only). - */ - const char* buffer() const noexcept - { - return fBuffer; - } - - // ------------------------------------------------------------------- - // public operators - - operator const char*() const noexcept - { - return fBuffer; - } - - char operator[](const size_t pos) const noexcept - { - if (pos < fBufferLen) - return fBuffer[pos]; - - d_safe_assert("pos < fBufferLen", __FILE__, __LINE__); - - static char fallback; - fallback = '\0'; - return fallback; - } - - char& operator[](const size_t pos) noexcept - { - if (pos < fBufferLen) - return fBuffer[pos]; - - d_safe_assert("pos < fBufferLen", __FILE__, __LINE__); - - static char fallback; - fallback = '\0'; - return fallback; - } - - bool operator==(const char* const strBuf) const noexcept - { - return (strBuf != nullptr && std::strcmp(fBuffer, strBuf) == 0); - } - - bool operator==(const d_string& str) const noexcept - { - return operator==(str.fBuffer); - } - - bool operator!=(const char* const strBuf) const noexcept - { - return !operator==(strBuf); - } - - bool operator!=(const d_string& str) const noexcept - { - return !operator==(str.fBuffer); - } - - d_string& operator=(const char* const strBuf) noexcept - { - _dup(strBuf); - - return *this; - } - - d_string& operator=(const d_string& str) noexcept - { - _dup(str.fBuffer); - - return *this; - } - - d_string& operator+=(const char* const strBuf) noexcept - { - if (strBuf == nullptr) - return *this; - - const size_t newBufSize = fBufferLen + std::strlen(strBuf) + 1; - char newBuf[newBufSize]; - - std::strcpy(newBuf, fBuffer); - std::strcat(newBuf, strBuf); - - _dup(newBuf, newBufSize-1); - - return *this; - } - - d_string& operator+=(const d_string& str) noexcept - { - return operator+=(str.fBuffer); - } - - d_string operator+(const char* const strBuf) noexcept - { - const size_t newBufSize = fBufferLen + ((strBuf != nullptr) ? std::strlen(strBuf) : 0) + 1; - char newBuf[newBufSize]; - - std::strcpy(newBuf, fBuffer); - - if (strBuf != nullptr) - std::strcat(newBuf, strBuf); - - return d_string(newBuf); - } - - d_string operator+(const d_string& str) noexcept - { - return operator+(str.fBuffer); - } - - // ------------------------------------------------------------------- - -private: - char* fBuffer; // the actual string buffer - size_t fBufferLen; // string length - - /* - * Static null string. - * Prevents allocation for new and/or empty strings. - */ - static char* _null() noexcept - { - static char sNull = '\0'; - return &sNull; - } - - /* - * Shared init function. - * Called on all constructors. - */ - void _init() noexcept - { - fBuffer = _null(); - fBufferLen = 0; - } - - /* - * Helper function. - * Called whenever the string needs to be allocated. - * - * Notes: - * - Allocates string only if 'strBuf' is not null and new string contents are different - * - If 'strBuf' is null, 'size' must be 0 - */ - void _dup(const char* const strBuf, const size_t size = 0) noexcept - { - if (strBuf != nullptr) - { - // don't recreate string if contents match - if (std::strcmp(fBuffer, strBuf) == 0) - return; - - if (fBuffer != _null()) - std::free(fBuffer); - - fBufferLen = (size > 0) ? size : std::strlen(strBuf); - fBuffer = (char*)std::malloc(fBufferLen+1); - - if (fBuffer == nullptr) - return _init(); - - std::strcpy(fBuffer, strBuf); - - fBuffer[fBufferLen] = '\0'; - } - else - { - DISTRHO_SAFE_ASSERT(size == 0); - - // don't recreate null string - if (fBuffer == _null()) - return; - - DISTRHO_SAFE_ASSERT(fBuffer != nullptr); - std::free(fBuffer); - - _init(); - } - } - - DISTRHO_LEAK_DETECTOR(d_string) - DISTRHO_PREVENT_HEAP_ALLOCATION -}; - -// ----------------------------------------------------------------------- - -static inline -d_string operator+(const d_string& strBefore, const char* const strBufAfter) noexcept -{ - const char* const strBufBefore = strBefore.buffer(); - const size_t newBufSize = strBefore.length() + ((strBufAfter != nullptr) ? std::strlen(strBufAfter) : 0) + 1; - char newBuf[newBufSize]; - - std::strcpy(newBuf, strBufBefore); - std::strcat(newBuf, strBufAfter); - - return d_string(newBuf); -} - -static inline -d_string operator+(const char* const strBufBefore, const d_string& strAfter) noexcept -{ - const char* const strBufAfter = strAfter.buffer(); - const size_t newBufSize = ((strBufBefore != nullptr) ? std::strlen(strBufBefore) : 0) + strAfter.length() + 1; - char newBuf[newBufSize]; - - std::strcpy(newBuf, strBufBefore); - std::strcat(newBuf, strBufAfter); - - return d_string(newBuf); -} - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_STRING_HPP_INCLUDED diff --git a/libs/distrho/extra/d_thread.hpp b/libs/distrho/extra/d_thread.hpp deleted file mode 100644 index 9a7b2a9..0000000 --- a/libs/distrho/extra/d_thread.hpp +++ /dev/null @@ -1,291 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_THREAD_HPP_INCLUDED -#define DISTRHO_THREAD_HPP_INCLUDED - -#include "d_mutex.hpp" -#include "d_sleep.hpp" -#include "d_string.hpp" - -#if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 -// has pthread_setname_np -#elif defined(DISTRHO_OS_LINUX) -# include <sys/prctl.h> -#endif - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// Thread class - -class Thread -{ -protected: - /* - * Constructor. - */ - Thread(const char* const threadName = nullptr) noexcept - : fLock(), - fName(threadName), -#ifdef PTW32_DLLPORT - fHandle({nullptr, 0}), -#else - fHandle(0), -#endif - fShouldExit(false) {} - - /* - * Destructor. - */ - virtual ~Thread() /*noexcept*/ - { - DISTRHO_SAFE_ASSERT(! isThreadRunning()); - - stopThread(-1); - } - - /* - * Virtual function to be implemented by the subclass. - */ - virtual void run() = 0; - - // ------------------------------------------------------------------- - -public: - /* - * Check if the thread is running. - */ - bool isThreadRunning() const noexcept - { -#ifdef PTW32_DLLPORT - return (fHandle.p != nullptr); -#else - return (fHandle != 0); -#endif - } - - /* - * Check if the thread should exit. - */ - bool shouldThreadExit() const noexcept - { - return fShouldExit; - } - - /* - * Start the thread. - */ - bool startThread() noexcept - { - // check if already running - DISTRHO_SAFE_ASSERT_RETURN(! isThreadRunning(), true); - - const MutexLocker cml(fLock); - - fShouldExit = false; - - pthread_t handle; - - if (pthread_create(&handle, nullptr, _entryPoint, this) == 0) - { -#ifdef PTW32_DLLPORT - DISTRHO_SAFE_ASSERT_RETURN(handle.p != nullptr, false); -#else - DISTRHO_SAFE_ASSERT_RETURN(handle != 0, false); -#endif - pthread_detach(handle); - _copyFrom(handle); - - // wait for thread to start - fLock.lock(); - - return true; - } - - return false; - } - - /* - * Stop the thread. - * In the 'timeOutMilliseconds': - * = 0 -> no wait - * > 0 -> wait timeout value - * < 0 -> wait forever - */ - bool stopThread(const int timeOutMilliseconds) noexcept - { - const MutexLocker cml(fLock); - - if (isThreadRunning()) - { - signalThreadShouldExit(); - - if (timeOutMilliseconds != 0) - { - // Wait for the thread to stop - int timeOutCheck = (timeOutMilliseconds == 1 || timeOutMilliseconds == -1) ? timeOutMilliseconds : timeOutMilliseconds/2; - - for (; isThreadRunning();) - { - d_msleep(2); - - if (timeOutCheck < 0) - continue; - - if (timeOutCheck > 0) - timeOutCheck -= 1; - else - break; - } - } - - if (isThreadRunning()) - { - // should never happen! - d_stderr2("Carla assertion failure: \"! isThreadRunning()\" in file %s, line %i", __FILE__, __LINE__); - - // copy thread id so we can clear our one - pthread_t threadId; - _copyTo(threadId); - _init(); - - try { - pthread_cancel(threadId); - } DISTRHO_SAFE_EXCEPTION("pthread_cancel"); - - return false; - } - } - - return true; - } - - /* - * Tell the thread to stop as soon as possible. - */ - void signalThreadShouldExit() noexcept - { - fShouldExit = true; - } - - // ------------------------------------------------------------------- - - /* - * Returns the name of the thread. - * This is the name that gets set in the constructor. - */ - const d_string& getThreadName() const noexcept - { - return fName; - } - - /* - * Changes the name of the caller thread. - */ - static void setCurrentThreadName(const char* const name) noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(name != nullptr && name[0] != '\0',); - -#if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012 - pthread_setname_np(pthread_self(), name); -#elif defined(DISTRHO_OS_LINUX) - prctl(PR_SET_NAME, name, 0, 0, 0); -#endif - } - - // ------------------------------------------------------------------- - -private: - Mutex fLock; // Thread lock - const d_string fName; // Thread name - volatile pthread_t fHandle; // Handle for this thread - volatile bool fShouldExit; // true if thread should exit - - /* - * Init pthread type. - */ - void _init() noexcept - { -#ifdef PTW32_DLLPORT - fHandle.p = nullptr; - fHandle.x = 0; -#else - fHandle = 0; -#endif - } - - /* - * Copy our pthread type from another var. - */ - void _copyFrom(const pthread_t& handle) noexcept - { -#ifdef PTW32_DLLPORT - fHandle.p = handle.p; - fHandle.x = handle.x; -#else - fHandle = handle; -#endif - } - - /* - * Copy our pthread type to another var. - */ - void _copyTo(volatile pthread_t& handle) const noexcept - { -#ifdef PTW32_DLLPORT - handle.p = fHandle.p; - handle.x = fHandle.x; -#else - handle = fHandle; -#endif - } - - /* - * Thread entry point. - */ - void _runEntryPoint() noexcept - { - // report ready - fLock.unlock(); - - setCurrentThreadName(fName); - - try { - run(); - } catch(...) {} - - // done - _init(); - } - - /* - * Thread entry point. - */ - static void* _entryPoint(void* userData) noexcept - { - static_cast<Thread*>(userData)->_runEntryPoint(); - return nullptr; - } - - DISTRHO_DECLARE_NON_COPY_CLASS(Thread) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_THREAD_HPP_INCLUDED diff --git a/libs/distrho/src/DistrhoDefines.h b/libs/distrho/src/DistrhoDefines.h deleted file mode 100644 index 59e4c34..0000000 --- a/libs/distrho/src/DistrhoDefines.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_DEFINES_H_INCLUDED -#define DISTRHO_DEFINES_H_INCLUDED - -/* Compatibility with non-clang compilers */ -#ifndef __has_feature -# define __has_feature(x) 0 -#endif -#ifndef __has_extension -# define __has_extension __has_feature -#endif - -/* Check OS */ -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) -# define DISTRHO_PLUGIN_EXPORT extern "C" __declspec (dllexport) -# define DISTRHO_OS_WINDOWS 1 -# define DISTRHO_DLL_EXTENSION "dll" -#else -# define DISTRHO_PLUGIN_EXPORT extern "C" __attribute__ ((visibility("default"))) -# if defined(__APPLE__) -# define DISTRHO_OS_MAC 1 -# define DISTRHO_DLL_EXTENSION "dylib" -# elif defined(__HAIKU__) -# define DISTRHO_OS_HAIKU 1 -# elif defined(__linux__) -# define DISTRHO_OS_LINUX 1 -# endif -#endif - -#ifndef DISTRHO_DLL_EXTENSION -# define DISTRHO_DLL_EXTENSION "so" -#endif - -/* Check for C++11 support */ -#if defined(HAVE_CPP11_SUPPORT) -# define DISTRHO_PROPER_CPP11_SUPPORT -#elif __cplusplus >= 201103L || (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 405) || __has_extension(cxx_noexcept) -# define DISTRHO_PROPER_CPP11_SUPPORT -# if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) < 407 && ! defined(__clang__)) || (defined(__clang__) && ! __has_extension(cxx_override_control)) -# define override // gcc4.7+ only -# define final // gcc4.7+ only -# endif -#endif - -#ifndef DISTRHO_PROPER_CPP11_SUPPORT -# define noexcept throw() -# define override -# define final -# define nullptr NULL -#endif - -/* Define DISTRHO_SAFE_ASSERT* */ -#define DISTRHO_SAFE_ASSERT(cond) if (! (cond)) d_safe_assert(#cond, __FILE__, __LINE__); -#define DISTRHO_SAFE_ASSERT_BREAK(cond) if (! (cond)) { d_safe_assert(#cond, __FILE__, __LINE__); break; } -#define DISTRHO_SAFE_ASSERT_CONTINUE(cond) if (! (cond)) { d_safe_assert(#cond, __FILE__, __LINE__); continue; } -#define DISTRHO_SAFE_ASSERT_RETURN(cond, ret) if (! (cond)) { d_safe_assert(#cond, __FILE__, __LINE__); return ret; } - -/* Define DISTRHO_SAFE_EXCEPTION */ -#define DISTRHO_SAFE_EXCEPTION(msg) catch(...) { d_safe_exception(msg, __FILE__, __LINE__); } -#define DISTRHO_SAFE_EXCEPTION_BREAK(msg) catch(...) { d_safe_exception(msg, __FILE__, __LINE__); break; } -#define DISTRHO_SAFE_EXCEPTION_CONTINUE(msg) catch(...) { d_safe_exception(msg, __FILE__, __LINE__); continue; } -#define DISTRHO_SAFE_EXCEPTION_RETURN(msg, ret) catch(...) { d_safe_exception(msg, __FILE__, __LINE__); return ret; } - -/* Define DISTRHO_DECLARE_NON_COPY_CLASS */ -#ifdef DISTRHO_PROPER_CPP11_SUPPORT -# define DISTRHO_DECLARE_NON_COPY_CLASS(ClassName) \ -private: \ - ClassName(ClassName&) = delete; \ - ClassName(const ClassName&) = delete; \ - ClassName& operator=(ClassName&) = delete ; \ - ClassName& operator=(const ClassName&) = delete; -#else -# define DISTRHO_DECLARE_NON_COPY_CLASS(ClassName) \ -private: \ - ClassName(ClassName&); \ - ClassName(const ClassName&); \ - ClassName& operator=(ClassName&); \ - ClassName& operator=(const ClassName&); -#endif - -/* Define DISTRHO_DECLARE_NON_COPY_STRUCT */ -#ifdef DISTRHO_PROPER_CPP11_SUPPORT -# define DISTRHO_DECLARE_NON_COPY_STRUCT(StructName) \ - StructName(StructName&) = delete; \ - StructName(const StructName&) = delete; \ - StructName& operator=(StructName&) = delete; \ - StructName& operator=(const StructName&) = delete; -#else -# define DISTRHO_DECLARE_NON_COPY_STRUCT(StructName) -#endif - -/* Define DISTRHO_PREVENT_HEAP_ALLOCATION */ -#ifdef DISTRHO_PROPER_CPP11_SUPPORT -# define DISTRHO_PREVENT_HEAP_ALLOCATION \ -private: \ - static void* operator new(size_t) = delete; \ - static void operator delete(void*) = delete; -#else -# define DISTRHO_PREVENT_HEAP_ALLOCATION \ -private: \ - static void* operator new(size_t); \ - static void operator delete(void*); -#endif - -/* Define namespace */ -#ifndef DISTRHO_NAMESPACE -# define DISTRHO_NAMESPACE DISTRHO -#endif -#define START_NAMESPACE_DISTRHO namespace DISTRHO_NAMESPACE { -#define END_NAMESPACE_DISTRHO } -#define USE_NAMESPACE_DISTRHO using namespace DISTRHO_NAMESPACE; - -/* Useful typedefs */ -typedef unsigned char uchar; -typedef unsigned short int ushort; -typedef unsigned int uint; -typedef unsigned long int ulong; - -#endif // DISTRHO_DEFINES_H_INCLUDED diff --git a/libs/distrho/src/DistrhoPlugin.cpp b/libs/distrho/src/DistrhoPlugin.cpp deleted file mode 100644 index 9b301be..0000000 --- a/libs/distrho/src/DistrhoPlugin.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoPluginInternal.hpp" - -START_NAMESPACE_DISTRHO - -/* ------------------------------------------------------------------------------------------------------------ - * Static data, see DistrhoPluginInternal.hpp */ - -uint32_t d_lastBufferSize = 0; -double d_lastSampleRate = 0.0; - -/* ------------------------------------------------------------------------------------------------------------ - * Static fallback data, see DistrhoPluginInternal.hpp */ - -const d_string PluginExporter::sFallbackString; -const ParameterRanges PluginExporter::sFallbackRanges; - -/* ------------------------------------------------------------------------------------------------------------ - * Plugin */ - -Plugin::Plugin(const uint32_t parameterCount, const uint32_t programCount, const uint32_t stateCount) - : pData(new PrivateData()) -{ - if (parameterCount > 0) - { - pData->parameterCount = parameterCount; - pData->parameters = new Parameter[parameterCount]; - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - if (programCount > 0) - { - pData->programCount = programCount; - pData->programNames = new d_string[programCount]; - } -#else - DISTRHO_SAFE_ASSERT(programCount == 0); -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - if (stateCount > 0) - { - pData->stateCount = stateCount; - pData->stateKeys = new d_string[stateCount]; - pData->stateDefValues = new d_string[stateCount]; - } -#else - DISTRHO_SAFE_ASSERT(stateCount == 0); -#endif -} - -Plugin::~Plugin() -{ - delete pData; -} - -/* ------------------------------------------------------------------------------------------------------------ - * Host state */ - -uint32_t Plugin::d_getBufferSize() const noexcept -{ - return pData->bufferSize; -} - -double Plugin::d_getSampleRate() const noexcept -{ - return pData->sampleRate; -} - -#if DISTRHO_PLUGIN_WANT_TIMEPOS -const TimePosition& Plugin::d_getTimePosition() const noexcept -{ - return pData->timePosition; -} -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY -void Plugin::d_setLatency(const uint32_t frames) noexcept -{ - pData->latency = frames; -} -#endif - -#if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT -bool Plugin::d_writeMidiEvent(const MidiEvent& /*midiEvent*/) noexcept -{ - // TODO - return false; -} -#endif - -/* ------------------------------------------------------------------------------------------------------------ - * Callbacks (optional) */ - -void Plugin::d_bufferSizeChanged(uint32_t) {} -void Plugin::d_sampleRateChanged(double) {} - -// ----------------------------------------------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO diff --git a/libs/distrho/src/DistrhoPluginCarla.cpp b/libs/distrho/src/DistrhoPluginCarla.cpp deleted file mode 100644 index 1f0a75e..0000000 --- a/libs/distrho/src/DistrhoPluginCarla.cpp +++ /dev/null @@ -1,480 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * For a full copy of the license see the LGPL.txt file - */ - -#include "DistrhoPluginInternal.hpp" - -#if DISTRHO_PLUGIN_HAS_UI -# include "DistrhoUIInternal.hpp" -#endif - -#include "CarlaNative.hpp" - -// ----------------------------------------------------------------------- - -START_NAMESPACE_DISTRHO - -#if DISTRHO_PLUGIN_HAS_UI -// ----------------------------------------------------------------------- -// Carla UI - -#if ! DISTRHO_PLUGIN_WANT_STATE -static const setStateFunc setStateCallback = nullptr; -#endif -#if ! DISTRHO_PLUGIN_IS_SYNTH -static const sendNoteFunc sendNoteCallback = nullptr; -#endif - -class UICarla -{ -public: - UICarla(const NativeHostDescriptor* const host, PluginExporter* const plugin) - : fHost(host), - fPlugin(plugin), - fUI(this, 0, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer()) - { - fUI.setWindowTitle(host->uiName); - - if (host->uiParentId != 0) - fUI.setWindowTransientWinId(host->uiParentId); - } - - ~UICarla() - { - fUI.quit(); - } - - // --------------------------------------------- - - void carla_show(const bool yesNo) - { - fUI.setWindowVisible(yesNo); - } - - bool carla_idle() - { - return fUI.idle(); - } - - void carla_setParameterValue(const uint32_t index, const float value) - { - fUI.parameterChanged(index, value); - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - void carla_setMidiProgram(const uint32_t realProgram) - { - fUI.programChanged(realProgram); - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - void carla_setCustomData(const char* const key, const char* const value) - { - fUI.stateChanged(key, value); - } -#endif - - void carla_setUiTitle(const char* const uiTitle) - { - fUI.setWindowTitle(uiTitle); - } - - // --------------------------------------------- - -protected: - void handleEditParameter(const uint32_t, const bool) - { - // TODO - } - - void handleSetParameterValue(const uint32_t rindex, const float value) - { - fHost->ui_parameter_changed(fHost->handle, rindex, value); - } - - void handleSetState(const char* const key, const char* const value) - { - fHost->ui_custom_data_changed(fHost->handle, key, value); - } - - void handleSendNote(const uint8_t, const uint8_t, const uint8_t) - { - // TODO - } - - void handleSetSize(const uint width, const uint height) - { - fUI.setWindowSize(width, height); - } - - // --------------------------------------------- - -private: - // Plugin stuff - const NativeHostDescriptor* const fHost; - PluginExporter* const fPlugin; - - // UI - UIExporter fUI; - - // --------------------------------------------- - // Callbacks - - #define handlePtr ((UICarla*)ptr) - - static void editParameterCallback(void* ptr, uint32_t index, bool started) - { - handlePtr->handleEditParameter(index, started); - } - - static void setParameterCallback(void* ptr, uint32_t rindex, float value) - { - handlePtr->handleSetParameterValue(rindex, value); - } - -#if DISTRHO_PLUGIN_WANT_STATE - static void setStateCallback(void* ptr, const char* key, const char* value) - { - handlePtr->handleSetState(key, value); - } -#endif - -#if DISTRHO_PLUGIN_IS_SYNTH - static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) - { - handlePtr->handleSendNote(channel, note, velocity); - } -#endif - - static void setSizeCallback(void* ptr, uint width, uint height) - { - handlePtr->handleSetSize(width, height); - } - - #undef handlePtr - - CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UICarla) -}; -#endif // DISTRHO_PLUGIN_HAS_UI - -// ----------------------------------------------------------------------- -// Carla Plugin - -class PluginCarla : public NativePluginClass -{ -public: - PluginCarla(const NativeHostDescriptor* const host) - : NativePluginClass(host) - { -#if DISTRHO_PLUGIN_HAS_UI - fUiPtr = nullptr; -#endif - } - - ~PluginCarla() override - { -#if DISTRHO_PLUGIN_HAS_UI - if (fUiPtr != nullptr) - { - delete fUiPtr; - fUiPtr = nullptr; - } -#endif - } - -protected: - // ------------------------------------------------------------------- - // Plugin parameter calls - - uint32_t getParameterCount() const override - { - return fPlugin.getParameterCount(); - } - - const NativeParameter* getParameterInfo(const uint32_t index) const override - { - CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), nullptr); - - static NativeParameter param; - - param.scalePointCount = 0; - param.scalePoints = nullptr; - - { - int nativeParamHints = ::NATIVE_PARAMETER_IS_ENABLED; - const uint32_t paramHints = fPlugin.getParameterHints(index); - - if (paramHints & kParameterIsAutomable) - nativeParamHints |= ::NATIVE_PARAMETER_IS_AUTOMABLE; - if (paramHints & kParameterIsBoolean) - nativeParamHints |= ::NATIVE_PARAMETER_IS_BOOLEAN; - if (paramHints & kParameterIsInteger) - nativeParamHints |= ::NATIVE_PARAMETER_IS_INTEGER; - if (paramHints & kParameterIsLogarithmic) - nativeParamHints |= ::NATIVE_PARAMETER_IS_LOGARITHMIC; - if (paramHints & kParameterIsOutput) - nativeParamHints |= ::NATIVE_PARAMETER_IS_OUTPUT; - - param.hints = static_cast<NativeParameterHints>(nativeParamHints); - } - - param.name = fPlugin.getParameterName(index); - param.unit = fPlugin.getParameterUnit(index); - - { - const ParameterRanges& ranges(fPlugin.getParameterRanges(index)); - - param.ranges.def = ranges.def; - param.ranges.min = ranges.min; - param.ranges.max = ranges.max; - } - - return ¶m; - } - - float getParameterValue(const uint32_t index) const override - { - CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), 0.0f); - - return fPlugin.getParameterValue(index); - } - - // ------------------------------------------------------------------- - // Plugin midi-program calls - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - uint32_t getMidiProgramCount() const override - { - return fPlugin.getProgramCount(); - } - - const NativeMidiProgram* getMidiProgramInfo(const uint32_t index) const override - { - CARLA_SAFE_ASSERT_RETURN(index < getMidiProgramCount(), nullptr); - - static NativeMidiProgram midiProgram; - - midiProgram.bank = index / 128; - midiProgram.program = index % 128; - midiProgram.name = fPlugin.getProgramName(index); - - return &midiProgram; - } -#endif - - // ------------------------------------------------------------------- - // Plugin state calls - - void setParameterValue(const uint32_t index, const float value) override - { - CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); - - fPlugin.setParameterValue(index, value); - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - void setMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override - { - const uint32_t realProgram(bank * 128 + program); - - CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); - - fPlugin.setProgram(realProgram); - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - void setCustomData(const char* const key, const char* const value) override - { - CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); - CARLA_SAFE_ASSERT_RETURN(value != nullptr,); - - fPlugin.setState(key, value); - } -#endif - - // ------------------------------------------------------------------- - // Plugin process calls - - void activate() override - { - fPlugin.activate(); - } - - void deactivate() override - { - fPlugin.deactivate(); - } - -#if DISTRHO_PLUGIN_IS_SYNTH - void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const midiEvents, const uint32_t midiEventCount) override - { - MidiEvent realMidiEvents[midiEventCount]; - - for (uint32_t i=0; i < midiEventCount; ++i) - { - const NativeMidiEvent& midiEvent(midiEvents[i]); - MidiEvent& realMidiEvent(realMidiEvents[i]); - - realMidiEvent.frame = midiEvent.time; - realMidiEvent.size = midiEvent.size; - - uint8_t j=0; - for (; j<midiEvent.size; ++j) - realMidiEvent.data[j] = midiEvent.data[j]; - for (; j<midiEvent.size; ++j) - realMidiEvent.data[j] = midiEvent.data[j]; - - realMidiEvent.dataExt = nullptr; - } - - fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames, realMidiEvents, midiEventCount); - } -#else - void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const, const uint32_t) override - { - fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames); - } -#endif - - // ------------------------------------------------------------------- - // Plugin UI calls - -#if DISTRHO_PLUGIN_HAS_UI - void uiShow(const bool show) override - { - if (show) - { - createUiIfNeeded(); - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - - fUiPtr->carla_show(show); - } - else if (fUiPtr != nullptr) - { - delete fUiPtr; - fUiPtr = nullptr; - } - } - - void uiIdle() override - { - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - - if (! fUiPtr->carla_idle()) - { - uiClosed(); - - delete fUiPtr; - fUiPtr = nullptr; - } - } - - void uiSetParameterValue(const uint32_t index, const float value) override - { - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); - - fUiPtr->carla_setParameterValue(index, value); - } - -# if DISTRHO_PLUGIN_WANT_PROGRAMS - void uiSetMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override - { - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - - const uint32_t realProgram(bank * 128 + program); - - CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); - - fUiPtr->carla_setMidiProgram(realProgram); - } -# endif - -# if DISTRHO_PLUGIN_WANT_STATE - void uiSetCustomData(const char* const key, const char* const value) override - { - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); - CARLA_SAFE_ASSERT_RETURN(value != nullptr,); - - fUiPtr->carla_setCustomData(key, value); - } -# endif -#endif - - // ------------------------------------------------------------------- - // Plugin dispatcher calls - - void bufferSizeChanged(const uint32_t bufferSize) override - { - fPlugin.setBufferSize(bufferSize, true); - } - - void sampleRateChanged(const double sampleRate) override - { - fPlugin.setSampleRate(sampleRate, true); - } - -#if DISTRHO_PLUGIN_HAS_UI - void uiNameChanged(const char* const uiName) override - { - CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); - - fUiPtr->carla_setUiTitle(uiName); - } -#endif - - // ------------------------------------------------------------------- - -private: - PluginExporter fPlugin; - -#if DISTRHO_PLUGIN_HAS_UI - // UI - UICarla* fUiPtr; - - void createUiIfNeeded() - { - if (fUiPtr == nullptr) - { - d_lastUiSampleRate = getSampleRate(); - fUiPtr = new UICarla(getHostHandle(), &fPlugin); - } - } -#endif - - CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginCarla) - - // ------------------------------------------------------------------- - -public: - static NativePluginHandle _instantiate(const NativeHostDescriptor* host) - { - d_lastBufferSize = host->get_buffer_size(host->handle); - d_lastSampleRate = host->get_sample_rate(host->handle); - return new PluginCarla(host); - } - - static void _cleanup(NativePluginHandle handle) - { - delete (PluginCarla*)handle; - } -}; - -END_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/DistrhoPluginChecks.h b/libs/distrho/src/DistrhoPluginChecks.h deleted file mode 100644 index 16d6b43..0000000 --- a/libs/distrho/src/DistrhoPluginChecks.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_PLUGIN_CHECKS_H_INCLUDED -#define DISTRHO_PLUGIN_CHECKS_H_INCLUDED - -#include "DistrhoPluginInfo.h" - -// ----------------------------------------------------------------------- -// Check if all required macros are defined - -#ifndef DISTRHO_PLUGIN_NAME -# error DISTRHO_PLUGIN_NAME undefined! -#endif - -#ifndef DISTRHO_PLUGIN_HAS_UI -# error DISTRHO_PLUGIN_HAS_UI undefined! -#endif - -#ifndef DISTRHO_PLUGIN_IS_SYNTH -# error DISTRHO_PLUGIN_IS_SYNTH undefined! -#endif - -#ifndef DISTRHO_PLUGIN_NUM_INPUTS -# error DISTRHO_PLUGIN_NUM_INPUTS undefined! -#endif - -#ifndef DISTRHO_PLUGIN_NUM_OUTPUTS -# error DISTRHO_PLUGIN_NUM_OUTPUTS undefined! -#endif - -#ifndef DISTRHO_PLUGIN_WANT_LATENCY -# error DISTRHO_PLUGIN_WANT_LATENCY undefined! -#endif - -#ifndef DISTRHO_PLUGIN_WANT_PROGRAMS -# error DISTRHO_PLUGIN_WANT_PROGRAMS undefined! -#endif - -#ifndef DISTRHO_PLUGIN_WANT_STATE -# error DISTRHO_PLUGIN_WANT_STATE undefined! -#endif - -#ifndef DISTRHO_PLUGIN_WANT_TIMEPOS -# error DISTRHO_PLUGIN_WANT_TIMEPOS undefined! -#endif - -// ----------------------------------------------------------------------- -// Test if synth has audio outputs - -#if DISTRHO_PLUGIN_IS_SYNTH && DISTRHO_PLUGIN_NUM_OUTPUTS == 0 -# error Synths need audio output to work! -#endif - -// ----------------------------------------------------------------------- -// Enable MIDI input if synth, test if midi-input disabled when synth - -#ifndef DISTRHO_PLUGIN_HAS_MIDI_INPUT -# define DISTRHO_PLUGIN_HAS_MIDI_INPUT DISTRHO_PLUGIN_IS_SYNTH -#elif DISTRHO_PLUGIN_IS_SYNTH && ! DISTRHO_PLUGIN_HAS_MIDI_INPUT -# error Synths need MIDI input to work! -#endif - -// ----------------------------------------------------------------------- -// Define optional macros if not done yet - -#ifndef DISTRHO_PLUGIN_HAS_MIDI_OUTPUT -# define DISTRHO_PLUGIN_HAS_MIDI_OUTPUT 0 -#endif - -#ifndef DISTRHO_PLUGIN_IS_RT_SAFE -# define DISTRHO_PLUGIN_IS_RT_SAFE 0 -#endif - -#ifndef DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -# define DISTRHO_PLUGIN_WANT_DIRECT_ACCESS 0 -#endif - -#ifndef DISTRHO_UI_USE_NANOVG -# define DISTRHO_UI_USE_NANOVG 0 -#endif - -// ----------------------------------------------------------------------- -// Define DISTRHO_UI_URI if needed - -#ifndef DISTRHO_UI_URI -# define DISTRHO_UI_URI DISTRHO_PLUGIN_URI "#UI" -#endif - -// ----------------------------------------------------------------------- - -#endif // DISTRHO_PLUGIN_CHECKS_H_INCLUDED diff --git a/libs/distrho/src/DistrhoPluginInternal.hpp b/libs/distrho/src/DistrhoPluginInternal.hpp deleted file mode 100644 index e9e2e23..0000000 --- a/libs/distrho/src/DistrhoPluginInternal.hpp +++ /dev/null @@ -1,471 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_PLUGIN_INTERNAL_HPP_INCLUDED -#define DISTRHO_PLUGIN_INTERNAL_HPP_INCLUDED - -#include "../DistrhoPlugin.hpp" - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// Maxmimum values - -static const uint32_t kMaxMidiEvents = 512; - -// ----------------------------------------------------------------------- -// Static data, see DistrhoPlugin.cpp - -extern uint32_t d_lastBufferSize; -extern double d_lastSampleRate; - -// ----------------------------------------------------------------------- -// Plugin private data - -struct Plugin::PrivateData { - bool isProcessing; - - uint32_t parameterCount; - Parameter* parameters; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - uint32_t programCount; - d_string* programNames; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - uint32_t stateCount; - d_string* stateKeys; - d_string* stateDefValues; -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - uint32_t latency; -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - TimePosition timePosition; -#endif - - uint32_t bufferSize; - double sampleRate; - - PrivateData() noexcept - : isProcessing(false), - parameterCount(0), - parameters(nullptr), -#if DISTRHO_PLUGIN_WANT_PROGRAMS - programCount(0), - programNames(nullptr), -#endif -#if DISTRHO_PLUGIN_WANT_STATE - stateCount(0), - stateKeys(nullptr), - stateDefValues(nullptr), -#endif -#if DISTRHO_PLUGIN_WANT_LATENCY - latency(0), -#endif - bufferSize(d_lastBufferSize), - sampleRate(d_lastSampleRate) - { - DISTRHO_SAFE_ASSERT(bufferSize != 0); - DISTRHO_SAFE_ASSERT(d_isNotZero(sampleRate)); - } - - ~PrivateData() noexcept - { - if (parameters != nullptr) - { - delete[] parameters; - parameters = nullptr; - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - if (programNames != nullptr) - { - delete[] programNames; - programNames = nullptr; - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - if (stateKeys != nullptr) - { - delete[] stateKeys; - stateKeys = nullptr; - } - - if (stateDefValues != nullptr) - { - delete[] stateDefValues; - stateDefValues = nullptr; - } -#endif - } -}; - -// ----------------------------------------------------------------------- -// Plugin exporter class - -class PluginExporter -{ -public: - PluginExporter() - : fPlugin(createPlugin()), - fData((fPlugin != nullptr) ? fPlugin->pData : nullptr), - fIsActive(false) - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - - for (uint32_t i=0, count=fData->parameterCount; i < count; ++i) - fPlugin->d_initParameter(i, fData->parameters[i]); - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - for (uint32_t i=0, count=fData->programCount; i < count; ++i) - fPlugin->d_initProgramName(i, fData->programNames[i]); -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - for (uint32_t i=0, count=fData->stateCount; i < count; ++i) - fPlugin->d_initState(i, fData->stateKeys[i], fData->stateDefValues[i]); -#endif - } - - ~PluginExporter() - { - delete fPlugin; - } - - // ------------------------------------------------------------------- - - const char* getName() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, ""); - - return fPlugin->d_getName(); - } - - const char* getLabel() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, ""); - - return fPlugin->d_getLabel(); - } - - const char* getMaker() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, ""); - - return fPlugin->d_getMaker(); - } - - const char* getLicense() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, ""); - - return fPlugin->d_getLicense(); - } - - uint32_t getVersion() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, 0); - - return fPlugin->d_getVersion(); - } - - long getUniqueId() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, 0); - - return fPlugin->d_getUniqueId(); - } - - void* getInstancePointer() const noexcept - { - return fPlugin; - } - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_LATENCY - uint32_t getLatency() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - - return fData->latency; - } -#endif - - uint32_t getParameterCount() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - - return fData->parameterCount; - } - - uint32_t getParameterHints(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, 0x0); - - return fData->parameters[index].hints; - } - - bool isParameterOutput(const uint32_t index) const noexcept - { - return (getParameterHints(index) & kParameterIsOutput); - } - - const d_string& getParameterName(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, sFallbackString); - - return fData->parameters[index].name; - } - - const d_string& getParameterSymbol(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, sFallbackString); - - return fData->parameters[index].symbol; - } - - const d_string& getParameterUnit(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, sFallbackString); - - return fData->parameters[index].unit; - } - - const ParameterRanges& getParameterRanges(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, sFallbackRanges); - - return fData->parameters[index].ranges; - } - - float getParameterValue(const uint32_t index) const - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr, 0.0f); - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount, 0.0f); - - return fPlugin->d_getParameterValue(index); - } - - void setParameterValue(const uint32_t index, const float value) - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->parameterCount,); - - fPlugin->d_setParameterValue(index, value); - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - uint32_t getProgramCount() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - - return fData->programCount; - } - - const d_string& getProgramName(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->programCount, sFallbackString); - - return fData->programNames[index]; - } - - void setProgram(const uint32_t index) - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->programCount,); - - fPlugin->d_setProgram(index); - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - uint32_t getStateCount() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - - return fData->stateCount; - } - - const d_string& getStateKey(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->stateCount, sFallbackString); - - return fData->stateKeys[index]; - } - - const d_string& getStateDefaultValue(const uint32_t index) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr && index < fData->stateCount, sFallbackString); - - return fData->stateDefValues[index]; - } - - void setState(const char* const key, const char* const value) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); - DISTRHO_SAFE_ASSERT_RETURN(value != nullptr,); - - fPlugin->d_setState(key, value); - } - - bool wantStateKey(const char* const key) const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, false); - DISTRHO_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0', false); - - for (uint32_t i=0; i < fData->stateCount; ++i) - { - if (fData->stateKeys[i] == key) - return true; - } - - return false; - } -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - void setTimePosition(const TimePosition& timePosition) noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - - std::memcpy(&fData->timePosition, &timePosition, sizeof(TimePosition)); - } -#endif - - // ------------------------------------------------------------------- - - void activate() - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - - fIsActive = true; - fPlugin->d_activate(); - } - - void deactivate() - { - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - - fIsActive = false; - fPlugin->d_deactivate(); - } - -#if DISTRHO_PLUGIN_IS_SYNTH - void run(const float** const inputs, float** const outputs, const uint32_t frames, - const MidiEvent* const midiEvents, const uint32_t midiEventCount) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - - fData->isProcessing = true; - fPlugin->d_run(inputs, outputs, frames, midiEvents, midiEventCount); - fData->isProcessing = false; - } -#else - void run(const float** const inputs, float** const outputs, const uint32_t frames) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - - fData->isProcessing = true; - fPlugin->d_run(inputs, outputs, frames); - fData->isProcessing = false; - } -#endif - - // ------------------------------------------------------------------- - - uint32_t getBufferSize() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - return fData->bufferSize; - } - - double getSampleRate() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0.0); - return fData->sampleRate; - } - - void setBufferSize(const uint32_t bufferSize, const bool doCallback = false) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - DISTRHO_SAFE_ASSERT(bufferSize >= 2); - - if (fData->bufferSize == bufferSize) - return; - - fData->bufferSize = bufferSize; - - if (doCallback) - { - if (fIsActive) fPlugin->d_deactivate(); - fPlugin->d_bufferSizeChanged(bufferSize); - if (fIsActive) fPlugin->d_activate(); - } - } - - void setSampleRate(const double sampleRate, const bool doCallback = false) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fPlugin != nullptr,); - DISTRHO_SAFE_ASSERT(sampleRate > 0.0); - - if (d_isEqual(fData->sampleRate, sampleRate)) - return; - - fData->sampleRate = sampleRate; - - if (doCallback) - { - if (fIsActive) fPlugin->d_deactivate(); - fPlugin->d_sampleRateChanged(sampleRate); - if (fIsActive) fPlugin->d_activate(); - } - } - -private: - // ------------------------------------------------------------------- - // Plugin and DistrhoPlugin data - - Plugin* const fPlugin; - Plugin::PrivateData* const fData; - bool fIsActive; - - // ------------------------------------------------------------------- - // Static fallback data, see DistrhoPlugin.cpp - - static const d_string sFallbackString; - static const ParameterRanges sFallbackRanges; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginExporter) - DISTRHO_PREVENT_HEAP_ALLOCATION -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_PLUGIN_INTERNAL_HPP_INCLUDED diff --git a/libs/distrho/src/DistrhoPluginJack.cpp b/libs/distrho/src/DistrhoPluginJack.cpp deleted file mode 100644 index 2de1165..0000000 --- a/libs/distrho/src/DistrhoPluginJack.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * For a full copy of the license see the LGPL.txt file - */ - -#include "DistrhoPluginInternal.hpp" - -#if ! DISTRHO_PLUGIN_HAS_UI -# error JACK export requires an UI -#endif - -#include "DistrhoUIInternal.hpp" - -#include "jack/jack.h" -#include "jack/midiport.h" -#include "jack/transport.h" - -// ----------------------------------------------------------------------- - -START_NAMESPACE_DISTRHO - -#if ! DISTRHO_PLUGIN_WANT_STATE -static const setStateFunc setStateCallback = nullptr; -#endif - -// ----------------------------------------------------------------------- - -class PluginJack : public IdleCallback -{ -public: - PluginJack(jack_client_t* const client) - : fPlugin(), - fUI(this, 0, nullptr, setParameterValueCallback, setStateCallback, nullptr, setSizeCallback, fPlugin.getInstancePointer()), - fClient(client) - { - char strBuf[0xff+1]; - strBuf[0xff] = '\0'; - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - { - std::snprintf(strBuf, 0xff, "in%i", i+1); - fPortAudioIns[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); - } -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - { - std::snprintf(strBuf, 0xff, "out%i", i+1); - fPortAudioOuts[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); - } -#endif - -#if DISTRHO_PLUGIN_IS_SYNTH - fPortMidiIn = jack_port_register(fClient, "midi-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0); -#endif - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - if (fPlugin.getProgramCount() > 0) - { - fPlugin.setProgram(0); - fUI.programChanged(0); - } -#endif - - if (const uint32_t count = fPlugin.getParameterCount()) - { - fLastOutputValues = new float[count]; - - for (uint32_t i=0; i < count; ++i) - { - if (fPlugin.isParameterOutput(i)) - { - fLastOutputValues[i] = fPlugin.getParameterValue(i); - } - else - { - fLastOutputValues[i] = 0.0f; - fUI.parameterChanged(i, fPlugin.getParameterValue(i)); - } - } - } - else - { - fLastOutputValues = nullptr; - } - - jack_set_buffer_size_callback(fClient, jackBufferSizeCallback, this); - jack_set_sample_rate_callback(fClient, jackSampleRateCallback, this); - jack_set_process_callback(fClient, jackProcessCallback, this); - jack_on_shutdown(fClient, jackShutdownCallback, this); - - jack_activate(fClient); - - if (const char* const name = jack_get_client_name(fClient)) - fUI.setWindowTitle(name); - else - fUI.setWindowTitle(fPlugin.getName()); - - fUI.exec(this); - } - - ~PluginJack() - { - if (fClient == nullptr) - return; - - jack_deactivate(fClient); - -#if DISTRHO_PLUGIN_IS_SYNTH - jack_port_unregister(fClient, fPortMidiIn); - fPortMidiIn = nullptr; -#endif - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - { - jack_port_unregister(fClient, fPortAudioIns[i]); - fPortAudioIns[i] = nullptr; - } -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - { - jack_port_unregister(fClient, fPortAudioOuts[i]); - fPortAudioOuts[i] = nullptr; - } -#endif - - jack_client_close(fClient); - } - - // ------------------------------------------------------------------- - -protected: - void idleCallback() override - { - float value; - - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (! fPlugin.isParameterOutput(i)) - continue; - - value = fPlugin.getParameterValue(i); - - if (fLastOutputValues[i] == value) - continue; - - fLastOutputValues[i] = value; - fUI.parameterChanged(i, value); - } - - fUI.exec_idle(); - } - - void jackBufferSize(const jack_nframes_t nframes) - { - fPlugin.setBufferSize(nframes, true); - } - - void jackSampleRate(const jack_nframes_t nframes) - { - fPlugin.setSampleRate(nframes, true); - } - - void jackProcess(const jack_nframes_t nframes) - { -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - const float* audioIns[DISTRHO_PLUGIN_NUM_INPUTS]; - - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - audioIns[i] = (const float*)jack_port_get_buffer(fPortAudioIns[i], nframes); -#else - static const float** audioIns = nullptr; -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - float* audioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; - - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - audioOuts[i] = (float*)jack_port_get_buffer(fPortAudioOuts[i], nframes); -#else - static float** audioOuts = nullptr; -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - jack_position_t pos; - fTimePosition.playing = (jack_transport_query(fClient, &pos) == JackTransportRolling); - - if (pos.unique_1 == pos.unique_2) - { - fTimePosition.frame = pos.frame; - - if (pos.valid & JackTransportBBT) - { - fTimePosition.bbt.valid = true; - - fTimePosition.bbt.bar = pos.bar; - fTimePosition.bbt.beat = pos.beat; - fTimePosition.bbt.tick = pos.tick; - fTimePosition.bbt.barStartTick = pos.bar_start_tick; - - fTimePosition.bbt.beatsPerBar = pos.beats_per_bar; - fTimePosition.bbt.beatType = pos.beat_type; - - fTimePosition.bbt.ticksPerBeat = pos.ticks_per_beat; - fTimePosition.bbt.beatsPerMinute = pos.beats_per_minute; - } - else - fTimePosition.bbt.valid = false; - } - else - { - fTimePosition.bbt.valid = false; - fTimePosition.frame = 0; - } - - fPlugin.setTimePosition(fTimePosition); -#endif - -#if DISTRHO_PLUGIN_IS_SYNTH - void* const midiBuf = jack_port_get_buffer(fPortMidiIn, nframes); - - if (const uint32_t eventCount = jack_midi_get_event_count(midiBuf)) - { - uint32_t midiEventCount = 0; - MidiEvent midiEvents[eventCount]; - - jack_midi_event_t jevent; - - for (uint32_t i=0; i < eventCount; ++i) - { - if (jack_midi_event_get(&jevent, midiBuf, i) != 0) - break; - - MidiEvent& midiEvent(midiEvents[midiEventCount++]); - - midiEvent.frame = jevent.time; - midiEvent.size = jevent.size; - - if (midiEvent.size > MidiEvent::kDataSize) - midiEvent.dataExt = jevent.buffer; - else - std::memcpy(midiEvent.data, jevent.buffer, midiEvent.size); - } - - fPlugin.run(audioIns, audioOuts, nframes, midiEvents, midiEventCount); - } - else - { - fPlugin.run(audioIns, audioOuts, nframes, nullptr, 0); - } -#else - fPlugin.run(audioIns, audioOuts, nframes); -#endif - } - - void jackShutdown() - { - d_stderr("jack has shutdown, quitting now..."); - fClient = nullptr; - fUI.quit(); - } - - // ------------------------------------------------------------------- - - void setParameterValue(const uint32_t index, const float value) - { - fPlugin.setParameterValue(index, value); - } - -#if DISTRHO_PLUGIN_WANT_STATE - void setState(const char* const key, const char* const value) - { - fPlugin.setState(key, value); - } -#endif - - void setSize(const uint width, const uint height) - { - fUI.setWindowSize(width, height); - } - - // ------------------------------------------------------------------- - -private: - PluginExporter fPlugin; - UIExporter fUI; - - jack_client_t* fClient; - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - jack_port_t* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS]; -#endif -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - jack_port_t* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; -#endif -#if DISTRHO_PLUGIN_IS_SYNTH - jack_port_t* fPortMidiIn; -#endif -#if DISTRHO_PLUGIN_WANT_TIMEPOS - TimePosition fTimePosition; -#endif - - // Temporary data - float* fLastOutputValues; - - // ------------------------------------------------------------------- - // Callbacks - - #define uiPtr ((PluginJack*)ptr) - - static int jackBufferSizeCallback(jack_nframes_t nframes, void* ptr) - { - uiPtr->jackBufferSize(nframes); - return 0; - } - - static int jackSampleRateCallback(jack_nframes_t nframes, void* ptr) - { - uiPtr->jackSampleRate(nframes); - return 0; - } - - static int jackProcessCallback(jack_nframes_t nframes, void* ptr) - { - uiPtr->jackProcess(nframes); - return 0; - } - - static void jackShutdownCallback(void* ptr) - { - uiPtr->jackShutdown(); - } - - static void setParameterValueCallback(void* ptr, uint32_t index, float value) - { - uiPtr->setParameterValue(index, value); - } - -#if DISTRHO_PLUGIN_WANT_STATE - static void setStateCallback(void* ptr, const char* key, const char* value) - { - uiPtr->setState(key, value); - } -#endif - - static void setSizeCallback(void* ptr, uint width, uint height) - { - uiPtr->setSize(width, height); - } - - #undef uiPtr -}; - -END_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- - -int main() -{ - USE_NAMESPACE_DISTRHO; - - jack_status_t status = jack_status_t(0x0); - jack_client_t* client = jack_client_open(DISTRHO_PLUGIN_NAME, JackNoStartServer, &status); - - if (client == nullptr) - { - d_string errorString; - - if (status & JackFailure) - errorString += "Overall operation failed;\n"; - if (status & JackInvalidOption) - errorString += "The operation contained an invalid or unsupported option;\n"; - if (status & JackNameNotUnique) - errorString += "The desired client name was not unique;\n"; - if (status & JackServerStarted) - errorString += "The JACK server was started as a result of this operation;\n"; - if (status & JackServerFailed) - errorString += "Unable to connect to the JACK server;\n"; - if (status & JackServerError) - errorString += "Communication error with the JACK server;\n"; - if (status & JackNoSuchClient) - errorString += "Requested client does not exist;\n"; - if (status & JackLoadFailure) - errorString += "Unable to load internal client;\n"; - if (status & JackInitFailure) - errorString += "Unable to initialize client;\n"; - if (status & JackShmFailure) - errorString += "Unable to access shared memory;\n"; - if (status & JackVersionError) - errorString += "Client's protocol version does not match;\n"; - if (status & JackBackendError) - errorString += "Backend Error;\n"; - if (status & JackClientZombie) - errorString += "Client is being shutdown against its will;\n"; - - if (errorString.isNotEmpty()) - { - errorString[errorString.length()-2] = '.'; - d_stderr("Failed to create jack client, reason was:\n%s", errorString.buffer()); - } - else - d_stderr("Failed to create jack client, cannot continue!"); - - return 1; - } - - USE_NAMESPACE_DISTRHO; - - d_lastBufferSize = jack_get_buffer_size(client); - d_lastSampleRate = jack_get_sample_rate(client); - d_lastUiSampleRate = d_lastSampleRate; - - const PluginJack p(client); - - return 0; -} - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/DistrhoPluginLADSPA+DSSI.cpp b/libs/distrho/src/DistrhoPluginLADSPA+DSSI.cpp deleted file mode 100644 index cfa9c9b..0000000 --- a/libs/distrho/src/DistrhoPluginLADSPA+DSSI.cpp +++ /dev/null @@ -1,713 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoPluginInternal.hpp" - -#if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT -# error Cannot use MIDI Output with LADSPA or DSSI -#endif - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI -# include "dssi/dssi.h" -#else -# include <ladspa.h> -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT -# error Cannot use MIDI with LADSPA -# endif -# if DISTRHO_PLUGIN_WANT_STATE -# warning LADSPA cannot handle states -# endif -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS -# warning LADSPA/DSSI does not support TimePos -#endif - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- - -class PluginLadspaDssi -{ -public: - PluginLadspaDssi() - : fPortControls(nullptr), - fLastControlValues(nullptr) - { -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - fPortAudioIns[i] = nullptr; -#else - fPortAudioIns = nullptr; -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - fPortAudioOuts[i] = nullptr; -#else - fPortAudioOuts = nullptr; -#endif - - if (const uint32_t count = fPlugin.getParameterCount()) - { - fPortControls = new LADSPA_Data*[count]; - fLastControlValues = new LADSPA_Data[count]; - - for (uint32_t i=0; i < count; ++i) - { - fPortControls[i] = nullptr; - fLastControlValues[i] = fPlugin.getParameterValue(i); - } - } - else - { - fPortControls = nullptr; - fLastControlValues = nullptr; - } - -#if DISTRHO_PLUGIN_WANT_LATENCY - fPortLatency = nullptr; -#endif - } - - ~PluginLadspaDssi() noexcept - { - if (fPortControls != nullptr) - { - delete[] fPortControls; - fPortControls = nullptr; - } - - if (fLastControlValues != nullptr) - { - delete[] fLastControlValues; - fLastControlValues = nullptr; - } - } - - // ------------------------------------------------------------------- - - void ladspa_activate() - { - fPlugin.activate(); - } - - void ladspa_deactivate() - { - fPlugin.deactivate(); - } - - // ------------------------------------------------------------------- - - void ladspa_connect_port(const ulong port, LADSPA_Data* const dataLocation) noexcept - { - ulong index = 0; - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (ulong i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - { - if (port == index++) - { - fPortAudioIns[i] = dataLocation; - return; - } - } -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (ulong i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - { - if (port == index++) - { - fPortAudioOuts[i] = dataLocation; - return; - } - } -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - if (port == index++) - { - fPortLatency = dataLocation; - return; - } -#endif - - for (ulong i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (port == index++) - { - fPortControls[i] = dataLocation; - return; - } - } - } - - // ------------------------------------------------------------------- - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI - void ladspa_run(const ulong sampleCount) - { - dssi_run_synth(sampleCount, nullptr, 0); - } - - void dssi_run_synth(const ulong sampleCount, snd_seq_event_t* const events, const ulong eventCount) -#else - void ladspa_run(const ulong sampleCount) -#endif - { - // pre-roll - if (sampleCount == 0) - return updateParameterOutputs(); - - // Check for updated parameters - float curValue; - - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (fPortControls[i] == nullptr) - continue; - - curValue = *fPortControls[i]; - - if (fLastControlValues[i] != curValue && ! fPlugin.isParameterOutput(i)) - { - fLastControlValues[i] = curValue; - fPlugin.setParameterValue(i, curValue); - } - } - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - // Get MIDI Events - uint32_t midiEventCount = 0; - MidiEvent midiEvents[eventCount]; - - for (uint32_t i=0, j; i < eventCount; ++i) - { - const snd_seq_event_t& seqEvent(events[i]); - - // FIXME - if (seqEvent.data.note.channel > 0xF || seqEvent.data.control.channel > 0xF) - continue; - - switch (seqEvent.type) - { - case SND_SEQ_EVENT_NOTEOFF: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 3; - midiEvents[j].data[0] = 0x80 + seqEvent.data.note.channel; - midiEvents[j].data[1] = seqEvent.data.note.note; - midiEvents[j].data[2] = 0; - midiEvents[j].data[3] = 0; - break; - case SND_SEQ_EVENT_NOTEON: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 3; - midiEvents[j].data[0] = 0x90 + seqEvent.data.note.channel; - midiEvents[j].data[1] = seqEvent.data.note.note; - midiEvents[j].data[2] = seqEvent.data.note.velocity; - midiEvents[j].data[3] = 0; - break; - case SND_SEQ_EVENT_KEYPRESS: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 3; - midiEvents[j].data[0] = 0xA0 + seqEvent.data.note.channel; - midiEvents[j].data[1] = seqEvent.data.note.note; - midiEvents[j].data[2] = seqEvent.data.note.velocity; - midiEvents[j].data[3] = 0; - break; - case SND_SEQ_EVENT_CONTROLLER: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 3; - midiEvents[j].data[0] = 0xB0 + seqEvent.data.control.channel; - midiEvents[j].data[1] = seqEvent.data.control.param; - midiEvents[j].data[2] = seqEvent.data.control.value; - midiEvents[j].data[3] = 0; - break; - case SND_SEQ_EVENT_CHANPRESS: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 2; - midiEvents[j].data[0] = 0xD0 + seqEvent.data.control.channel; - midiEvents[j].data[1] = seqEvent.data.control.value; - midiEvents[j].data[2] = 0; - midiEvents[j].data[3] = 0; - break; -#if 0 // TODO - case SND_SEQ_EVENT_PITCHBEND: - j = midiEventCount++; - midiEvents[j].frame = seqEvent.time.tick; - midiEvents[j].size = 3; - midiEvents[j].data[0] = 0xE0 + seqEvent.data.control.channel; - midiEvents[j].data[1] = 0; - midiEvents[j].data[2] = 0; - midiEvents[j].data[3] = 0; - break; -#endif - } - } - - fPlugin.run(fPortAudioIns, fPortAudioOuts, sampleCount, midiEvents, midiEventCount); -#else - fPlugin.run(fPortAudioIns, fPortAudioOuts, sampleCount); -#endif - - updateParameterOutputs(); - -#if defined(DISTRHO_PLUGIN_TARGET_DSSI) && ! DISTRHO_PLUGIN_HAS_MIDI_INPUT - return; // unused - (void)events; (void)eventCount; -#endif - } - - // ------------------------------------------------------------------- - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI -# if DISTRHO_PLUGIN_WANT_STATE - char* dssi_configure(const char* const key, const char* const value) - { - if (std::strncmp(key, DSSI_RESERVED_CONFIGURE_PREFIX, std::strlen(DSSI_RESERVED_CONFIGURE_PREFIX) == 0)) - return nullptr; - if (std::strncmp(key, DSSI_GLOBAL_CONFIGURE_PREFIX, std::strlen(DSSI_GLOBAL_CONFIGURE_PREFIX) == 0)) - return nullptr; - - fPlugin.setState(key, value); - return nullptr; - } -# endif - -# if DISTRHO_PLUGIN_WANT_PROGRAMS - const DSSI_Program_Descriptor* dssi_get_program(const ulong index) - { - if (index >= fPlugin.getProgramCount()) - return nullptr; - - static DSSI_Program_Descriptor desc; - - desc.Bank = index / 128; - desc.Program = index % 128; - desc.Name = fPlugin.getProgramName(index); - - return &desc; - } - - void dssi_select_program(const ulong bank, const ulong program) - { - const ulong realProgram(bank * 128 + program); - - DISTRHO_SAFE_ASSERT_RETURN(realProgram < fPlugin.getProgramCount(),); - - fPlugin.setProgram(realProgram); - - // Update control inputs - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (fPlugin.isParameterOutput(i)) - continue; - - fLastControlValues[i] = fPlugin.getParameterValue(i); - - if (fPortControls[i] != nullptr) - *fPortControls[i] = fLastControlValues[i]; - } - } -# endif -#endif - - // ------------------------------------------------------------------- - -private: - PluginExporter fPlugin; - - // LADSPA ports -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - const LADSPA_Data* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS]; -#else - const LADSPA_Data** fPortAudioIns; -#endif -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - LADSPA_Data* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; -#else - LADSPA_Data** fPortAudioOuts; -#endif - LADSPA_Data** fPortControls; -#if DISTRHO_PLUGIN_WANT_LATENCY - LADSPA_Data* fPortLatency; -#endif - - // Temporary data - LADSPA_Data* fLastControlValues; - - // ------------------------------------------------------------------- - - void updateParameterOutputs() - { - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (! fPlugin.isParameterOutput(i)) - continue; - - fLastControlValues[i] = fPlugin.getParameterValue(i); - - if (fPortControls[i] != nullptr) - *fPortControls[i] = fLastControlValues[i]; - } - -#if DISTRHO_PLUGIN_WANT_LATENCY - if (fPortLatency != nullptr) - *fPortLatency = fPlugin.getLatency(); -#endif - } -}; - -// ----------------------------------------------------------------------- - -static LADSPA_Handle ladspa_instantiate(const LADSPA_Descriptor*, ulong sampleRate) -{ - if (d_lastBufferSize == 0) - d_lastBufferSize = 2048; - d_lastSampleRate = sampleRate; - - return new PluginLadspaDssi(); -} - -#define instancePtr ((PluginLadspaDssi*)instance) - -static void ladspa_connect_port(LADSPA_Handle instance, ulong port, LADSPA_Data* dataLocation) -{ - instancePtr->ladspa_connect_port(port, dataLocation); -} - -static void ladspa_activate(LADSPA_Handle instance) -{ - instancePtr->ladspa_activate(); -} - -static void ladspa_run(LADSPA_Handle instance, ulong sampleCount) -{ - instancePtr->ladspa_run(sampleCount); -} - -static void ladspa_deactivate(LADSPA_Handle instance) -{ - instancePtr->ladspa_deactivate(); -} - -static void ladspa_cleanup(LADSPA_Handle instance) -{ - delete instancePtr; -} - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI -# if DISTRHO_PLUGIN_WANT_STATE -static char* dssi_configure(LADSPA_Handle instance, const char* key, const char* value) -{ - return instancePtr->dssi_configure(key, value); -} -# endif - -# if DISTRHO_PLUGIN_WANT_PROGRAMS -static const DSSI_Program_Descriptor* dssi_get_program(LADSPA_Handle instance, ulong index) -{ - return instancePtr->dssi_get_program(index); -} - -static void dssi_select_program(LADSPA_Handle instance, ulong bank, ulong program) -{ - instancePtr->dssi_select_program(bank, program); -} -# endif - -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT -static void dssi_run_synth(LADSPA_Handle instance, ulong sampleCount, snd_seq_event_t* events, ulong eventCount) -{ - instancePtr->dssi_run_synth(sampleCount, events, eventCount); -} -# endif -#endif - -#undef instancePtr - -// ----------------------------------------------------------------------- - -static LADSPA_Descriptor sLadspaDescriptor = { - /* UniqueID */ 0, - /* Label */ nullptr, -#if DISTRHO_PLUGIN_IS_RT_SAFE - /* Properties */ LADSPA_PROPERTY_HARD_RT_CAPABLE, -#else - /* Properties */ 0x0, -#endif - /* Name */ nullptr, - /* Maker */ nullptr, - /* Copyright */ nullptr, - /* PortCount */ 0, - /* PortDescriptors */ nullptr, - /* PortNames */ nullptr, - /* PortRangeHints */ nullptr, - /* ImplementationData */ nullptr, - ladspa_instantiate, - ladspa_connect_port, - ladspa_activate, - ladspa_run, - /* run_adding */ nullptr, - /* set_run_adding_gain */ nullptr, - ladspa_deactivate, - ladspa_cleanup -}; - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI -static DSSI_Descriptor sDssiDescriptor = { - 1, - &sLadspaDescriptor, -# if DISTRHO_PLUGIN_WANT_STATE - dssi_configure, -# else - /* configure */ nullptr, -# endif -# if DISTRHO_PLUGIN_WANT_PROGRAMS - dssi_get_program, - dssi_select_program, -# else - /* get_program */ nullptr, - /* select_program */ nullptr, -# endif - /* get_midi_controller_for_port */ nullptr, -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT - dssi_run_synth, -# else - /* run_synth */ nullptr, -# endif - /* run_synth_adding */ nullptr, - /* run_multiple_synths */ nullptr, - /* run_multiple_synths_adding */ nullptr, - nullptr, nullptr -}; -#endif - -// ----------------------------------------------------------------------- - -class DescriptorInitializer -{ -public: - DescriptorInitializer() - { - // Create dummy plugin to get data from - d_lastBufferSize = 512; - d_lastSampleRate = 44100.0; - PluginExporter plugin; - d_lastBufferSize = 0; - d_lastSampleRate = 0.0; - - // Get port count, init - ulong port = 0; - ulong portCount = DISTRHO_PLUGIN_NUM_INPUTS + DISTRHO_PLUGIN_NUM_OUTPUTS + plugin.getParameterCount(); -#if DISTRHO_PLUGIN_WANT_LATENCY - portCount += 1; -#endif - const char** const portNames = new const char*[portCount]; - LADSPA_PortDescriptor* portDescriptors = new LADSPA_PortDescriptor[portCount]; - LADSPA_PortRangeHint* portRangeHints = new LADSPA_PortRangeHint [portCount]; - - // Set ports -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (ulong i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i, ++port) - { - char portName[24] = { '\0' }; - std::sprintf(portName, "Audio Input %lu", i+1); - - portNames[port] = strdup(portName); - portDescriptors[port] = LADSPA_PORT_AUDIO | LADSPA_PORT_INPUT; - - portRangeHints[port].HintDescriptor = 0x0; - portRangeHints[port].LowerBound = 0.0f; - portRangeHints[port].UpperBound = 1.0f; - } -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (ulong i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i, ++port) - { - char portName[24] = { '\0' }; - std::sprintf(portName, "Audio Output %lu", i+1); - - portNames[port] = strdup(portName); - portDescriptors[port] = LADSPA_PORT_AUDIO | LADSPA_PORT_OUTPUT; - - portRangeHints[port].HintDescriptor = 0x0; - portRangeHints[port].LowerBound = 0.0f; - portRangeHints[port].UpperBound = 1.0f; - } -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - // Set latency port - portNames[port] = strdup("_latency"); - portDescriptors[port] = LADSPA_PORT_CONTROL | LADSPA_PORT_OUTPUT; - portRangeHints[port].HintDescriptor = LADSPA_HINT_SAMPLE_RATE|LADSPA_HINT_INTEGER; - portRangeHints[port].LowerBound = 0.0f; - portRangeHints[port].UpperBound = 1.0f; - ++port; -#endif - - for (ulong i=0, count=plugin.getParameterCount(); i < count; ++i, ++port) - { - portNames[port] = strdup((const char*)plugin.getParameterName(i)); - portDescriptors[port] = LADSPA_PORT_CONTROL; - - if (plugin.isParameterOutput(i)) - portDescriptors[port] |= LADSPA_PORT_OUTPUT; - else - portDescriptors[port] |= LADSPA_PORT_INPUT; - - { - const ParameterRanges& ranges(plugin.getParameterRanges(i)); - const float defValue(ranges.def); - - portRangeHints[port].HintDescriptor = LADSPA_HINT_BOUNDED_BELOW | LADSPA_HINT_BOUNDED_ABOVE; - portRangeHints[port].LowerBound = ranges.min; - portRangeHints[port].UpperBound = ranges.max; - - if (defValue == 0.0f) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_0; - else if (defValue == 1.0f) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_1; - else if (defValue == 100.0f) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_100; - else if (defValue == 440.0f) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_440; - else if (ranges.min == defValue) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_MINIMUM; - else if (ranges.max == defValue) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_MAXIMUM; - else - { - const float middleValue = ranges.min/2.0f + ranges.max/2.0f; - const float middleLow = (ranges.min/2.0f + middleValue/2.0f)/2.0f + middleValue/2.0f; - const float middleHigh = (ranges.max/2.0f + middleValue/2.0f)/2.0f + middleValue/2.0f; - - if (defValue < middleLow) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_LOW; - else if (defValue > middleHigh) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_HIGH; - else - portRangeHints[port].HintDescriptor |= LADSPA_HINT_DEFAULT_MIDDLE; - } - } - - { - const uint32_t hints(plugin.getParameterHints(i)); - - if (hints & kParameterIsBoolean) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_TOGGLED; - if (hints & kParameterIsInteger) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_INTEGER; - if (hints & kParameterIsLogarithmic) - portRangeHints[port].HintDescriptor |= LADSPA_HINT_LOGARITHMIC; - } - } - - // Set data - sLadspaDescriptor.UniqueID = plugin.getUniqueId(); - sLadspaDescriptor.Label = strdup(plugin.getLabel()); - sLadspaDescriptor.Name = strdup(plugin.getName()); - sLadspaDescriptor.Maker = strdup(plugin.getMaker()); - sLadspaDescriptor.Copyright = strdup(plugin.getLicense()); - sLadspaDescriptor.PortCount = portCount; - sLadspaDescriptor.PortNames = portNames; - sLadspaDescriptor.PortDescriptors = portDescriptors; - sLadspaDescriptor.PortRangeHints = portRangeHints; - } - - ~DescriptorInitializer() - { - if (sLadspaDescriptor.Label != nullptr) - { - std::free((void*)sLadspaDescriptor.Label); - sLadspaDescriptor.Label = nullptr; - } - - if (sLadspaDescriptor.Name != nullptr) - { - std::free((void*)sLadspaDescriptor.Name); - sLadspaDescriptor.Name = nullptr; - } - - if (sLadspaDescriptor.Maker != nullptr) - { - std::free((void*)sLadspaDescriptor.Maker); - sLadspaDescriptor.Maker = nullptr; - } - - if (sLadspaDescriptor.Copyright != nullptr) - { - std::free((void*)sLadspaDescriptor.Copyright); - sLadspaDescriptor.Copyright = nullptr; - } - - if (sLadspaDescriptor.PortDescriptors != nullptr) - { - delete[] sLadspaDescriptor.PortDescriptors; - sLadspaDescriptor.PortDescriptors = nullptr; - } - - if (sLadspaDescriptor.PortRangeHints != nullptr) - { - delete[] sLadspaDescriptor.PortRangeHints; - sLadspaDescriptor.PortRangeHints = nullptr; - } - - if (sLadspaDescriptor.PortNames != nullptr) - { - for (ulong i=0; i < sLadspaDescriptor.PortCount; ++i) - { - if (sLadspaDescriptor.PortNames[i] != nullptr) - std::free((void*)sLadspaDescriptor.PortNames[i]); - } - - delete[] sLadspaDescriptor.PortNames; - sLadspaDescriptor.PortNames = nullptr; - } - } -}; - -static DescriptorInitializer sDescInit; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -DISTRHO_PLUGIN_EXPORT -const LADSPA_Descriptor* ladspa_descriptor(ulong index) -{ - USE_NAMESPACE_DISTRHO - return (index == 0) ? &sLadspaDescriptor : nullptr; -} - -#ifdef DISTRHO_PLUGIN_TARGET_DSSI -DISTRHO_PLUGIN_EXPORT -const DSSI_Descriptor* dssi_descriptor(ulong index) -{ - USE_NAMESPACE_DISTRHO - return (index == 0) ? &sDssiDescriptor : nullptr; -} -#endif - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/DistrhoPluginLV2.cpp b/libs/distrho/src/DistrhoPluginLV2.cpp deleted file mode 100644 index 2739338..0000000 --- a/libs/distrho/src/DistrhoPluginLV2.cpp +++ /dev/null @@ -1,1107 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoPluginInternal.hpp" - -#include "lv2/atom.h" -#include "lv2/atom-util.h" -#include "lv2/buf-size.h" -#include "lv2/data-access.h" -#include "lv2/instance-access.h" -#include "lv2/midi.h" -#include "lv2/options.h" -#include "lv2/state.h" -#include "lv2/time.h" -#include "lv2/urid.h" -#include "lv2/worker.h" -#include "lv2/lv2_kxstudio_properties.h" -#include "lv2/lv2_programs.h" - -#ifdef noexcept -# undef noexcept -#endif - -#include <map> - -#ifndef DISTRHO_PLUGIN_URI -# error DISTRHO_PLUGIN_URI undefined! -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS -# warning LV2 TimePos still TODO -#endif - -#define DISTRHO_LV2_USE_EVENTS_IN (DISTRHO_PLUGIN_HAS_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)) -#define DISTRHO_LV2_USE_EVENTS_OUT (DISTRHO_PLUGIN_HAS_MIDI_OUTPUT || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)) - -START_NAMESPACE_DISTRHO - -typedef std::map<const d_string,d_string> StringMap; - -// ----------------------------------------------------------------------- - -class PluginLv2 -{ -public: - PluginLv2(const double sampleRate, const LV2_URID_Map* const uridMap, const LV2_Worker_Schedule* const worker) - : fPortControls(nullptr), - fLastControlValues(nullptr), - fSampleRate(sampleRate), -#if DISTRHO_LV2_USE_EVENTS_IN || DISTRHO_LV2_USE_EVENTS_OUT -# if DISTRHO_PLUGIN_WANT_TIMEPOS - fLastTimeSpeed(0.0), -# endif - fURIDs(uridMap), -#endif - fUridMap(uridMap), - fWorker(worker) - { -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - fPortAudioIns[i] = nullptr; -#else - fPortAudioIns = nullptr; -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - fPortAudioOuts[i] = nullptr; -#else - fPortAudioOuts = nullptr; -#endif - - if (const uint32_t count = fPlugin.getParameterCount()) - { - fPortControls = new float*[count]; - fLastControlValues = new float[count]; - - for (uint32_t i=0; i < count; ++i) - { - fPortControls[i] = nullptr; - fLastControlValues[i] = fPlugin.getParameterValue(i); - } - } - else - { - fPortControls = nullptr; - fLastControlValues = nullptr; - } - -#if DISTRHO_LV2_USE_EVENTS_IN - fPortEventsIn = nullptr; -#endif -#if DISTRHO_LV2_USE_EVENTS_OUT - fPortEventsOut = nullptr; -#endif -#if DISTRHO_PLUGIN_WANT_LATENCY - fPortLatency = nullptr; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - if (const uint32_t count = fPlugin.getStateCount()) - { - fNeededUiSends = new bool[count]; - - for (uint32_t i=0; i < count; ++i) - { - fNeededUiSends[i] = false; - - const d_string& d_key(fPlugin.getStateKey(i)); - fStateMap[d_key] = fPlugin.getStateDefaultValue(i); - } - } - else - { - fNeededUiSends = nullptr; - } -#else - // unused - (void)fWorker; -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - // hosts may not send all values, resulting on some invalid ones - fTimePosition.bbt.valid = false; - fTimePosition.bbt.bar = 1; - fTimePosition.bbt.beat = 1; - fTimePosition.bbt.tick = 0; - fTimePosition.bbt.barStartTick = 0; - fTimePosition.bbt.beatsPerBar = 4; - fTimePosition.bbt.beatType = 4; - fTimePosition.bbt.ticksPerBeat = 960.0; - fTimePosition.bbt.beatsPerMinute = 120.0; -#endif - } - - ~PluginLv2() - { - if (fPortControls != nullptr) - { - delete[] fPortControls; - fPortControls = nullptr; - } - - if (fLastControlValues) - { - delete[] fLastControlValues; - fLastControlValues = nullptr; - } - -#if DISTRHO_PLUGIN_WANT_STATE - if (fNeededUiSends != nullptr) - { - delete[] fNeededUiSends; - fNeededUiSends = nullptr; - } - - fStateMap.clear(); -#endif - } - - // ------------------------------------------------------------------- - - void lv2_activate() - { - fPlugin.activate(); - } - - void lv2_deactivate() - { - fPlugin.deactivate(); - } - - // ------------------------------------------------------------------- - - void lv2_connect_port(const uint32_t port, void* const dataLocation) - { - uint32_t index = 0; - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i) - { - if (port == index++) - { - fPortAudioIns[i] = (const float*)dataLocation; - return; - } - } -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i) - { - if (port == index++) - { - fPortAudioOuts[i] = (float*)dataLocation; - return; - } - } -#endif - -#if DISTRHO_LV2_USE_EVENTS_IN - if (port == index++) - { - fPortEventsIn = (LV2_Atom_Sequence*)dataLocation; - return; - } -#endif - -#if DISTRHO_LV2_USE_EVENTS_OUT - if (port == index++) - { - fPortEventsOut = (LV2_Atom_Sequence*)dataLocation; - return; - } -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - if (port == index++) - { - fPortLatency = (float*)dataLocation; - return; - } -#endif - - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (port == index++) - { - fPortControls[i] = (float*)dataLocation; - return; - } - } - } - - // ------------------------------------------------------------------- - - void lv2_run(const uint32_t sampleCount) - { - // pre-roll - if (sampleCount == 0) - return updateParameterOutputs(); - - // Check for updated parameters - float curValue; - - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (fPortControls[i] == nullptr) - continue; - - curValue = *fPortControls[i]; - - if (fLastControlValues[i] != curValue && ! fPlugin.isParameterOutput(i)) - { - fLastControlValues[i] = curValue; - fPlugin.setParameterValue(i, curValue); - } - } - -#if DISTRHO_LV2_USE_EVENTS_IN -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT - uint32_t midiEventCount = 0; -# endif - LV2_ATOM_SEQUENCE_FOREACH(fPortEventsIn, event) - { - if (event == nullptr) - break; - -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT - if (event->body.type == fURIDs.midiEvent) - { - if (midiEventCount >= kMaxMidiEvents) - continue; - - const uint8_t* const data((const uint8_t*)(event + 1)); - - MidiEvent& midiEvent(fMidiEvents[midiEventCount]); - - midiEvent.frame = event->time.frames; - midiEvent.size = event->body.size; - - if (midiEvent.size > MidiEvent::kDataSize) - midiEvent.dataExt = data; - else - std::memcpy(midiEvent.data, data, midiEvent.size); - - ++midiEventCount; - continue; - } -# endif -# if DISTRHO_PLUGIN_WANT_TIMEPOS - if (event->body.type == fURIDs.atomBlank || event->body.type == fURIDs.atomObject) - { - const LV2_Atom_Object* const obj((const LV2_Atom_Object*)&event->body); - - if (obj->body.otype != fURIDs.timePosition) - continue; - - LV2_Atom* bar = nullptr; - LV2_Atom* barBeat = nullptr; - LV2_Atom* beat = nullptr; - LV2_Atom* beatUnit = nullptr; - LV2_Atom* beatsPerBar = nullptr; - LV2_Atom* beatsPerMinute = nullptr; - LV2_Atom* ticksPerBeat = nullptr; - LV2_Atom* frame = nullptr; - LV2_Atom* speed = nullptr; - - lv2_atom_object_get(obj, - fURIDs.timeBar, &bar, - fURIDs.timeBarBeat, &barBeat, - fURIDs.timeBeat, &beat, - fURIDs.timeBeatUnit, &beatUnit, - fURIDs.timeBeatsPerBar, &beatsPerBar, - fURIDs.timeBeatsPerMinute, &beatsPerMinute, - fURIDs.timeTicksPerBeat, &ticksPerBeat, - fURIDs.timeFrame, &frame, - fURIDs.timeSpeed, &speed, - nullptr); - - if (bar != nullptr) - { - /**/ if (bar->type == fURIDs.atomDouble) - fTimePosition.bbt.bar = ((LV2_Atom_Double*)bar)->body + 1.0; - else if (bar->type == fURIDs.atomFloat) - fTimePosition.bbt.bar = ((LV2_Atom_Float*)bar)->body + 1.0f; - else if (bar->type == fURIDs.atomInt) - fTimePosition.bbt.bar = ((LV2_Atom_Int*)bar)->body + 1; - else if (bar->type == fURIDs.atomLong) - fTimePosition.bbt.bar = ((LV2_Atom_Long*)bar)->body + 1; - else - d_stderr("Unknown lv2 bar value type"); - } - - if (ticksPerBeat != nullptr) - { - /**/ if (ticksPerBeat->type == fURIDs.atomDouble) - fTimePosition.bbt.ticksPerBeat = ((LV2_Atom_Double*)ticksPerBeat)->body; - else if (ticksPerBeat->type == fURIDs.atomFloat) - fTimePosition.bbt.ticksPerBeat = ((LV2_Atom_Float*)ticksPerBeat)->body; - else if (ticksPerBeat->type == fURIDs.atomInt) - fTimePosition.bbt.ticksPerBeat = ((LV2_Atom_Int*)ticksPerBeat)->body; - else if (ticksPerBeat->type == fURIDs.atomLong) - fTimePosition.bbt.ticksPerBeat = ((LV2_Atom_Long*)ticksPerBeat)->body; - else - d_stderr("Unknown lv2 ticksPerBeat value type"); - } - - if (barBeat != nullptr) - { - double barBeatValue = 0.0; - - /**/ if (barBeat->type == fURIDs.atomDouble) - barBeatValue = ((LV2_Atom_Double*)barBeat)->body; - else if (barBeat->type == fURIDs.atomFloat) - barBeatValue = ((LV2_Atom_Float*)barBeat)->body; - else if (barBeat->type == fURIDs.atomInt) - barBeatValue = ((LV2_Atom_Int*)barBeat)->body; - else if (barBeat->type == fURIDs.atomLong) - barBeatValue = ((LV2_Atom_Long*)barBeat)->body; - else - d_stderr("Unknown lv2 barBeat value type"); - - const double rest = std::fmod(barBeatValue, 1.0); - fTimePosition.bbt.beat = barBeatValue-rest+1.0; - fTimePosition.bbt.tick = rest*fTimePosition.bbt.ticksPerBeat+0.5; - } - // barBeat includes beat - else if (beat != nullptr) - { - /**/ if (beat->type == fURIDs.atomDouble) - fTimePosition.bbt.beat = ((LV2_Atom_Double*)beat)->body + 1.0; - else if (beat->type == fURIDs.atomFloat) - fTimePosition.bbt.beat = ((LV2_Atom_Float*)beat)->body + 1.0f; - else if (beat->type == fURIDs.atomInt) - fTimePosition.bbt.beat = ((LV2_Atom_Int*)beat)->body + 1; - else if (beat->type == fURIDs.atomLong) - fTimePosition.bbt.beat = ((LV2_Atom_Long*)beat)->body + 1; - else - d_stderr("Unknown lv2 beat value type"); - } - - if (beatUnit != nullptr) - { - /**/ if (beatUnit->type == fURIDs.atomDouble) - fTimePosition.bbt.beatType = ((LV2_Atom_Double*)beatUnit)->body; - else if (beatUnit->type == fURIDs.atomFloat) - fTimePosition.bbt.beatType = ((LV2_Atom_Float*)beatUnit)->body; - else if (beatUnit->type == fURIDs.atomInt) - fTimePosition.bbt.beatType = ((LV2_Atom_Int*)beatUnit)->body; - else if (beatUnit->type == fURIDs.atomLong) - fTimePosition.bbt.beatType = ((LV2_Atom_Long*)beatUnit)->body; - else - d_stderr("Unknown lv2 beatUnit value type"); - } - - if (beatsPerBar != nullptr) - { - /**/ if (beatsPerBar->type == fURIDs.atomDouble) - fTimePosition.bbt.beatsPerBar = ((LV2_Atom_Double*)beatsPerBar)->body; - else if (beatsPerBar->type == fURIDs.atomFloat) - fTimePosition.bbt.beatsPerBar = ((LV2_Atom_Float*)beatsPerBar)->body; - else if (beatsPerBar->type == fURIDs.atomInt) - fTimePosition.bbt.beatsPerBar = ((LV2_Atom_Int*)beatsPerBar)->body; - else if (beatsPerBar->type == fURIDs.atomLong) - fTimePosition.bbt.beatsPerBar = ((LV2_Atom_Long*)beatsPerBar)->body; - else - d_stderr("Unknown lv2 beatsPerBar value type"); - } - - if (beatsPerMinute != nullptr) - { - /**/ if (beatsPerMinute->type == fURIDs.atomDouble) - fTimePosition.bbt.beatsPerMinute = ((LV2_Atom_Double*)beatsPerMinute)->body; - else if (beatsPerMinute->type == fURIDs.atomFloat) - fTimePosition.bbt.beatsPerMinute = ((LV2_Atom_Float*)beatsPerMinute)->body; - else if (beatsPerMinute->type == fURIDs.atomInt) - fTimePosition.bbt.beatsPerMinute = ((LV2_Atom_Int*)beatsPerMinute)->body; - else if (beatsPerMinute->type == fURIDs.atomLong) - fTimePosition.bbt.beatsPerMinute = ((LV2_Atom_Long*)beatsPerMinute)->body; - else - d_stderr("Unknown lv2 beatsPerMinute value type"); - } - - fTimePosition.bbt.barStartTick = fTimePosition.bbt.ticksPerBeat*fTimePosition.bbt.beatsPerBar*(fTimePosition.bbt.bar-1); - - if (frame != nullptr && frame->type == fURIDs.atomLong) - fTimePosition.frame = ((LV2_Atom_Long*)frame)->body; - - if (speed != nullptr && speed->type == fURIDs.atomFloat) - { - fLastTimeSpeed = ((LV2_Atom_Float*)speed)->body; - fTimePosition.playing = (fLastTimeSpeed == 1.0); - } - - fTimePosition.bbt.valid = (beatsPerMinute != nullptr && beatsPerBar != nullptr && beatUnit != nullptr); - continue; - } -# endif -# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI) - if (event->body.type == fURIDs.distrhoState && fWorker != nullptr) - { - const void* const data((const void*)(event + 1)); - - // check if this is our special message - if (std::strcmp((const char*)data, "__dpf_ui_data__") == 0) - { - for (uint32_t i=0, count=fPlugin.getStateCount(); i < count; ++i) - fNeededUiSends[i] = true; - } - else - // no, send to DSP as usual - { - fWorker->schedule_work(fWorker->handle, event->body.size, data); - } - - continue; - } -# endif - } -#endif - -# if DISTRHO_PLUGIN_WANT_TIMEPOS - fPlugin.setTimePosition(fTimePosition); -# endif - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - fPlugin.run(fPortAudioIns, fPortAudioOuts, sampleCount, fMidiEvents, midiEventCount); -#else - fPlugin.run(fPortAudioIns, fPortAudioOuts, sampleCount); -#endif - -# if DISTRHO_PLUGIN_WANT_TIMEPOS - // update timePos for next callback - if (fLastTimeSpeed != 0.0) - { - const double newFrames = fLastTimeSpeed*sampleCount; - - fTimePosition.frame += newFrames; - - if (fTimePosition.bbt.valid) - { - const double samplesPerBeat = 60.0 / fTimePosition.bbt.beatsPerMinute * fSampleRate; - const double ticksPerSample = fTimePosition.bbt.ticksPerBeat / samplesPerBeat; - - double newTickPos = double(fTimePosition.bbt.tick) + ticksPerSample*newFrames; - double newBeatPos = double(fTimePosition.bbt.beat)-1.0; - double newBarPos = double(fTimePosition.bbt.bar)-1.0; - - for (; newTickPos >= fTimePosition.bbt.ticksPerBeat;) - { - ++newBeatPos; - newTickPos -= fTimePosition.bbt.ticksPerBeat; - } - - for (; newBeatPos >= fTimePosition.bbt.beatsPerBar;) - { - ++newBarPos; - newBeatPos -= fTimePosition.bbt.beatsPerBar; - } - - fTimePosition.bbt.bar = newBarPos+1.0; - fTimePosition.bbt.beat = newBeatPos+1.0; - fTimePosition.bbt.tick = newTickPos; - fTimePosition.bbt.barStartTick = fTimePosition.bbt.ticksPerBeat*fTimePosition.bbt.beatsPerBar*(fTimePosition.bbt.bar-1); - } - } -# endif - - updateParameterOutputs(); - -#if DISTRHO_LV2_USE_EVENTS_OUT - const uint32_t capacity = fPortEventsOut->atom.size; - - bool needsInit = true; - uint32_t size, offset = 0; - LV2_Atom_Event* aev; - -# if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT - // TODO -# endif -# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI) - for (uint32_t i=0, count=fPlugin.getStateCount(); i < count; ++i) - { - if (! fNeededUiSends[i]) - continue; - - const d_string& key = fPlugin.getStateKey(i); - - for (StringMap::const_iterator cit=fStateMap.begin(), cite=fStateMap.end(); cit != cite; ++cit) - { - const d_string& curKey = cit->first; - - if (curKey != key) - continue; - - const d_string& value = cit->second; - - // set msg size (key + value + separator + 2x null terminator) - const size_t msgSize(key.length()+value.length()+3); - - if (sizeof(LV2_Atom_Event) + msgSize > capacity - offset) - break; - - if (needsInit) - { - fPortEventsOut->atom.size = 0; - fPortEventsOut->atom.type = fURIDs.atomSequence; - fPortEventsOut->body.unit = 0; - fPortEventsOut->body.pad = 0; - needsInit = false; - } - - // reserve msg space - char msgBuf[msgSize]; - std::memset(msgBuf, 0, msgSize); - - // write key and value in atom bufer - std::memcpy(msgBuf, key.buffer(), key.length()); - std::memcpy(msgBuf+(key.length()+1), value.buffer(), value.length()); - - // put data - aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, fPortEventsOut) + offset); - aev->time.frames = 0; - aev->body.type = fURIDs.distrhoState; - aev->body.size = msgSize; - std::memcpy(LV2_ATOM_BODY(&aev->body), msgBuf, msgSize-1); - - size = lv2_atom_pad_size(sizeof(LV2_Atom_Event) + msgSize); - offset += size; - fPortEventsOut->atom.size += size; - - fNeededUiSends[i] = false; - break; - } - } -# endif -#endif - } - - // ------------------------------------------------------------------- - - uint32_t lv2_get_options(LV2_Options_Option* const /*options*/) - { - // currently unused - return LV2_OPTIONS_ERR_UNKNOWN; - } - - uint32_t lv2_set_options(const LV2_Options_Option* const options) - { - for (int i=0; options[i].key != 0; ++i) - { - if (options[i].key == fUridMap->map(fUridMap->handle, LV2_BUF_SIZE__maxBlockLength)) - { - if (options[i].type == fUridMap->map(fUridMap->handle, LV2_ATOM__Int)) - { - const int bufferSize(*(const int*)options[i].value); - fPlugin.setBufferSize(bufferSize); - continue; - } - else - { - d_stderr("Host changed maxBlockLength but with wrong value type"); - continue; - } - } - else if (options[i].key == fUridMap->map(fUridMap->handle, LV2_CORE__sampleRate)) - { - if (options[i].type == fUridMap->map(fUridMap->handle, LV2_ATOM__Double)) - { - const double sampleRate(*(const double*)options[i].value); - fSampleRate = sampleRate; - fPlugin.setSampleRate(sampleRate); - continue; - } - else - { - d_stderr("Host changed sampleRate but with wrong value type"); - continue; - } - } - } - - return LV2_OPTIONS_SUCCESS; - } - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - const LV2_Program_Descriptor* lv2_get_program(const uint32_t index) - { - if (index >= fPlugin.getProgramCount()) - return nullptr; - - static LV2_Program_Descriptor desc; - - desc.bank = index / 128; - desc.program = index % 128; - desc.name = fPlugin.getProgramName(index); - - return &desc; - } - - void lv2_select_program(const uint32_t bank, const uint32_t program) - { - const uint32_t realProgram(bank * 128 + program); - - if (realProgram >= fPlugin.getProgramCount()) - return; - - fPlugin.setProgram(realProgram); - - // Update control inputs - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (fPlugin.isParameterOutput(i)) - continue; - - fLastControlValues[i] = fPlugin.getParameterValue(i); - - if (fPortControls[i] != nullptr) - *fPortControls[i] = fLastControlValues[i]; - } - } -#endif - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_STATE - LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle) - { - for (StringMap::const_iterator cit=fStateMap.begin(), cite=fStateMap.end(); cit != cite; ++cit) - { - const d_string& key = cit->first; - const d_string& value = cit->second; - - const d_string urnKey("urn:distrho:" + key); - - // some hosts need +1 for the null terminator, even though the type is string - store(handle, fUridMap->map(fUridMap->handle, urnKey.buffer()), value.buffer(), value.length()+1, fURIDs.atomString, LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE); - } - - return LV2_STATE_SUCCESS; - } - - LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve, const LV2_State_Handle handle) - { - size_t size; - uint32_t type, flags; - - for (uint32_t i=0, count=fPlugin.getStateCount(); i < count; ++i) - { - const d_string& key(fPlugin.getStateKey(i)); - const d_string urnKey("urn:distrho:" + key); - - size = 0; - type = 0; - flags = LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE; - const void* data = retrieve(handle, fUridMap->map(fUridMap->handle, urnKey.buffer()), &size, &type, &flags); - - if (data == nullptr || size == 0) - continue; - - DISTRHO_SAFE_ASSERT_CONTINUE(type == fURIDs.atomString); - - const char* const value((const char*)data); - const std::size_t length(std::strlen(value)); - DISTRHO_SAFE_ASSERT_CONTINUE(length == size || length+1 == size); - - setState(key, value); - -#if DISTRHO_LV2_USE_EVENTS_OUT - // signal msg needed for UI - fNeededUiSends[i] = true; -#endif - } - - return LV2_STATE_SUCCESS; - } - - // ------------------------------------------------------------------- - - LV2_Worker_Status lv2_work(const void* const data) - { - const char* const key((const char*)data); - const char* const value(key+std::strlen(key)+1); - - setState(key, value); - - return LV2_WORKER_SUCCESS; - } -#endif - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - void* lv2_get_instance_pointer() - { - return fPlugin.getInstancePointer(); - } -#endif - - // ------------------------------------------------------------------- - -private: - PluginExporter fPlugin; - - // LV2 ports -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - const float* fPortAudioIns[DISTRHO_PLUGIN_NUM_INPUTS]; -#else - const float** fPortAudioIns; -#endif -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - float* fPortAudioOuts[DISTRHO_PLUGIN_NUM_OUTPUTS]; -#else - float** fPortAudioOuts; -#endif - float** fPortControls; -#if DISTRHO_LV2_USE_EVENTS_IN - LV2_Atom_Sequence* fPortEventsIn; -#endif -#if DISTRHO_LV2_USE_EVENTS_OUT - LV2_Atom_Sequence* fPortEventsOut; -#endif -#if DISTRHO_PLUGIN_WANT_LATENCY - float* fPortLatency; -#endif - - // Temporary data - float* fLastControlValues; - double fSampleRate; -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - MidiEvent fMidiEvents[kMaxMidiEvents]; -#endif -#if DISTRHO_PLUGIN_WANT_TIMEPOS - TimePosition fTimePosition; - double fLastTimeSpeed; -#endif - - // LV2 URIDs -#if DISTRHO_LV2_USE_EVENTS_IN || DISTRHO_LV2_USE_EVENTS_OUT - struct URIDs { - LV2_URID atomBlank; - LV2_URID atomObject; - LV2_URID atomDouble; - LV2_URID atomFloat; - LV2_URID atomInt; - LV2_URID atomLong; - LV2_URID atomSequence; - LV2_URID atomString; - LV2_URID distrhoState; - LV2_URID midiEvent; - LV2_URID timePosition; - LV2_URID timeBar; - LV2_URID timeBarBeat; - LV2_URID timeBeat; - LV2_URID timeBeatUnit; - LV2_URID timeBeatsPerBar; - LV2_URID timeBeatsPerMinute; - LV2_URID timeTicksPerBeat; - LV2_URID timeFrame; - LV2_URID timeSpeed; - - URIDs(const LV2_URID_Map* const uridMap) - : atomBlank(uridMap->map(uridMap->handle, LV2_ATOM__Blank)), - atomObject(uridMap->map(uridMap->handle, LV2_ATOM__Object)), - atomDouble(uridMap->map(uridMap->handle, LV2_ATOM__Double)), - atomFloat(uridMap->map(uridMap->handle, LV2_ATOM__Float)), - atomInt(uridMap->map(uridMap->handle, LV2_ATOM__Int)), - atomLong(uridMap->map(uridMap->handle, LV2_ATOM__Long)), - atomSequence(uridMap->map(uridMap->handle, LV2_ATOM__Sequence)), - atomString(uridMap->map(uridMap->handle, LV2_ATOM__String)), - distrhoState(uridMap->map(uridMap->handle, "urn:distrho:keyValueState")), - midiEvent(uridMap->map(uridMap->handle, LV2_MIDI__MidiEvent)), - timePosition(uridMap->map(uridMap->handle, LV2_TIME__Position)), - timeBar(uridMap->map(uridMap->handle, LV2_TIME__bar)), - timeBarBeat(uridMap->map(uridMap->handle, LV2_TIME__barBeat)), - timeBeat(uridMap->map(uridMap->handle, LV2_TIME__beat)), - timeBeatUnit(uridMap->map(uridMap->handle, LV2_TIME__beatUnit)), - timeBeatsPerBar(uridMap->map(uridMap->handle, LV2_TIME__beatsPerBar)), - timeBeatsPerMinute(uridMap->map(uridMap->handle, LV2_TIME__beatsPerMinute)), - timeTicksPerBeat(uridMap->map(uridMap->handle, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat)), - timeFrame(uridMap->map(uridMap->handle, LV2_TIME__frame)), - timeSpeed(uridMap->map(uridMap->handle, LV2_TIME__speed)) {} - } fURIDs; -#endif - - // LV2 features - const LV2_URID_Map* const fUridMap; - const LV2_Worker_Schedule* const fWorker; - -#if DISTRHO_PLUGIN_WANT_STATE - StringMap fStateMap; - bool* fNeededUiSends; - - void setState(const char* const key, const char* const newValue) - { - fPlugin.setState(key, newValue); - - // check if we want to save this key - if (! fPlugin.wantStateKey(key)) - return; - - // check if key already exists - for (StringMap::iterator it=fStateMap.begin(), ite=fStateMap.end(); it != ite; ++it) - { - const d_string& d_key(it->first); - - if (d_key == key) - { - it->second = newValue; - return; - } - } - - d_stderr("Failed to find plugin state with key \"%s\"", key); - } -#endif - - void updateParameterOutputs() - { - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (! fPlugin.isParameterOutput(i)) - continue; - - fLastControlValues[i] = fPlugin.getParameterValue(i); - - if (fPortControls[i] != nullptr) - *fPortControls[i] = fLastControlValues[i]; - } - -#if DISTRHO_PLUGIN_WANT_LATENCY - if (fPortLatency != nullptr) - *fPortLatency = fPlugin.getLatency(); -#endif - } -}; - -// ----------------------------------------------------------------------- - -static LV2_Handle lv2_instantiate(const LV2_Descriptor*, double sampleRate, const char*, const LV2_Feature* const* features) -{ - const LV2_Options_Option* options = nullptr; - const LV2_URID_Map* uridMap = nullptr; - const LV2_Worker_Schedule* worker = nullptr; - - for (int i=0; features[i] != nullptr; ++i) - { - if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) == 0) - options = (const LV2_Options_Option*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_URID__map) == 0) - uridMap = (const LV2_URID_Map*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_WORKER__schedule) == 0) - worker = (const LV2_Worker_Schedule*)features[i]->data; - } - - if (options == nullptr) - { - d_stderr("Options feature missing, cannot continue!"); - return nullptr; - } - - if (uridMap == nullptr) - { - d_stderr("URID Map feature missing, cannot continue!"); - return nullptr; - } - -#if DISTRHO_PLUGIN_WANT_STATE - if (worker == nullptr) - { - d_stderr("Worker feature missing, cannot continue!"); - return nullptr; - } -#endif - - d_lastBufferSize = 0; - - for (int i=0; options[i].key != 0; ++i) - { - if (options[i].key == uridMap->map(uridMap->handle, LV2_BUF_SIZE__maxBlockLength)) - { - if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__Int)) - d_lastBufferSize = *(const int*)options[i].value; - else - d_stderr("Host provides maxBlockLength but has wrong value type"); - - break; - } - } - - if (d_lastBufferSize == 0) - { - d_stderr("Host does not provide maxBlockLength option"); - d_lastBufferSize = 2048; - } - - d_lastSampleRate = sampleRate; - - return new PluginLv2(sampleRate, uridMap, worker); -} - -#define instancePtr ((PluginLv2*)instance) - -static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation) -{ - instancePtr->lv2_connect_port(port, dataLocation); -} - -static void lv2_activate(LV2_Handle instance) -{ - instancePtr->lv2_activate(); -} - -static void lv2_run(LV2_Handle instance, uint32_t sampleCount) -{ - instancePtr->lv2_run(sampleCount); -} - -static void lv2_deactivate(LV2_Handle instance) -{ - instancePtr->lv2_deactivate(); -} - -static void lv2_cleanup(LV2_Handle instance) -{ - delete instancePtr; -} - -// ----------------------------------------------------------------------- - -static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options) -{ - return instancePtr->lv2_get_options(options); -} - -static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options) -{ - return instancePtr->lv2_set_options(options); -} - -// ----------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_PROGRAMS -static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index) -{ - return instancePtr->lv2_get_program(index); -} - -static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program) -{ - instancePtr->lv2_select_program(bank, program); -} -#endif - -// ----------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_STATE -static LV2_State_Status lv2_save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t, const LV2_Feature* const*) -{ - return instancePtr->lv2_save(store, handle); -} - -static LV2_State_Status lv2_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t, const LV2_Feature* const*) -{ - return instancePtr->lv2_restore(retrieve, handle); -} - -LV2_Worker_Status lv2_work(LV2_Handle instance, LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data) -{ - return instancePtr->lv2_work(data); -} -#endif - -// ----------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -static void* lv2_get_instance_pointer(LV2_Handle instance) -{ - return instancePtr->lv2_get_instance_pointer(); -} -#endif - -// ----------------------------------------------------------------------- - -static const void* lv2_extension_data(const char* uri) -{ - static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options }; - - if (std::strcmp(uri, LV2_OPTIONS__interface) == 0) - return &options; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program }; - - if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0) - return &programs; -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - static const LV2_State_Interface state = { lv2_save, lv2_restore }; - static const LV2_Worker_Interface worker = { lv2_work, nullptr, nullptr }; - - if (std::strcmp(uri, LV2_STATE__interface) == 0) - return &state; - if (std::strcmp(uri, LV2_WORKER__interface) == 0) - return &worker; -#endif - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -# define DISTRHO_DIRECT_ACCESS_URI "urn:distrho:direct-access" - - struct LV2_DirectAccess_Interface { - void* (*get_instance_pointer)(LV2_Handle handle); - }; - - static const LV2_DirectAccess_Interface directaccess = { lv2_get_instance_pointer }; - - if (std::strcmp(uri, DISTRHO_DIRECT_ACCESS_URI) == 0) - return &directaccess; -#endif - - return nullptr; -} - -#undef instancePtr - -// ----------------------------------------------------------------------- - -static const LV2_Descriptor sLv2Descriptor = { - DISTRHO_PLUGIN_URI, - lv2_instantiate, - lv2_connect_port, - lv2_activate, - lv2_run, - lv2_deactivate, - lv2_cleanup, - lv2_extension_data -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -DISTRHO_PLUGIN_EXPORT -const LV2_Descriptor* lv2_descriptor(uint32_t index) -{ - USE_NAMESPACE_DISTRHO - return (index == 0) ? &sLv2Descriptor : nullptr; -} - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/DistrhoPluginLV2export.cpp b/libs/distrho/src/DistrhoPluginLV2export.cpp deleted file mode 100644 index c362d41..0000000 --- a/libs/distrho/src/DistrhoPluginLV2export.cpp +++ /dev/null @@ -1,405 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoPluginInternal.hpp" - -#include "lv2/atom.h" -#include "lv2/buf-size.h" -#include "lv2/data-access.h" -#include "lv2/instance-access.h" -#include "lv2/midi.h" -#include "lv2/options.h" -#include "lv2/port-props.h" -#include "lv2/resize-port.h" -#include "lv2/state.h" -#include "lv2/time.h" -#include "lv2/ui.h" -#include "lv2/units.h" -#include "lv2/urid.h" -#include "lv2/worker.h" -#include "lv2/lv2_kxstudio_properties.h" -#include "lv2/lv2_programs.h" - -#include <fstream> -#include <iostream> - -#ifndef DISTRHO_PLUGIN_URI -# error DISTRHO_PLUGIN_URI undefined! -#endif - -#ifndef DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE -# define DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE 2048 -#endif - -#define DISTRHO_LV2_USE_EVENTS_IN (DISTRHO_PLUGIN_HAS_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)) -#define DISTRHO_LV2_USE_EVENTS_OUT (DISTRHO_PLUGIN_HAS_MIDI_OUTPUT || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)) - -// ----------------------------------------------------------------------- - -DISTRHO_PLUGIN_EXPORT -void lv2_generate_ttl(const char* const basename) -{ - USE_NAMESPACE_DISTRHO - - // Dummy plugin to get data from - d_lastBufferSize = 512; - d_lastSampleRate = 44100.0; - PluginExporter plugin; - d_lastBufferSize = 0; - d_lastSampleRate = 0.0; - - d_string pluginDLL(basename); - d_string pluginTTL(pluginDLL + ".ttl"); - - // --------------------------------------------- - - { - std::cout << "Writing manifest.ttl..."; std::cout.flush(); - std::fstream manifestFile("manifest.ttl", std::ios::out); - - d_string manifestString; - manifestString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n"; - manifestString += "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"; -#if DISTRHO_PLUGIN_HAS_UI - manifestString += "@prefix ui: <" LV2_UI_PREFIX "> .\n"; -#endif - manifestString += "\n"; - - manifestString += "<" DISTRHO_PLUGIN_URI ">\n"; - manifestString += " a lv2:Plugin ;\n"; - manifestString += " lv2:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n"; - manifestString += " rdfs:seeAlso <" + pluginTTL + "> .\n"; - manifestString += "\n"; - -#if DISTRHO_PLUGIN_HAS_UI - manifestString += "<" DISTRHO_UI_URI ">\n"; -# if DISTRHO_OS_HAIKU - manifestString += " a ui:BeUI ;\n"; -# elif DISTRHO_OS_MAC - manifestString += " a ui:CocoaUI ;\n"; -# elif DISTRHO_OS_WINDOWS - manifestString += " a ui:WindowsUI ;\n"; -# else - manifestString += " a ui:X11UI ;\n"; -# endif -# if ! DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - d_string pluginUI(pluginDLL); - pluginUI.truncate(pluginDLL.rfind("_dsp")); - pluginUI += "_ui"; - - manifestString += " ui:binary <" + pluginUI + "." DISTRHO_DLL_EXTENSION "> ;\n"; -# else - manifestString += " ui:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n"; -#endif - manifestString += " lv2:extensionData ui:idleInterface ,\n"; -# if DISTRHO_PLUGIN_WANT_PROGRAMS - manifestString += " ui:showInterface ,\n"; - manifestString += " <" LV2_PROGRAMS__Interface "> ;\n"; -# else - manifestString += " ui:showInterface ;\n"; -# endif - manifestString += " lv2:optionalFeature ui:noUserResize ,\n"; - manifestString += " ui:resize ,\n"; - manifestString += " ui:touch ;\n"; -# if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - manifestString += " lv2:requiredFeature <" LV2_DATA_ACCESS_URI "> ,\n"; - manifestString += " <" LV2_INSTANCE_ACCESS_URI "> ,\n"; - manifestString += " <" LV2_OPTIONS__options "> ,\n"; -# else - manifestString += " lv2:requiredFeature <" LV2_OPTIONS__options "> ,\n"; -# endif - manifestString += " <" LV2_URID__map "> .\n"; -#endif - - manifestFile << manifestString << std::endl; - manifestFile.close(); - std::cout << " done!" << std::endl; - } - - // --------------------------------------------- - - { - std::cout << "Writing " << pluginTTL << "..."; std::cout.flush(); - std::fstream pluginFile(pluginTTL, std::ios::out); - - d_string pluginString; - - // header -#if DISTRHO_LV2_USE_EVENTS_IN - pluginString += "@prefix atom: <" LV2_ATOM_PREFIX "> .\n"; -#endif - pluginString += "@prefix doap: <http://usefulinc.com/ns/doap#> .\n"; - pluginString += "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"; - pluginString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n"; - pluginString += "@prefix rsz: <" LV2_RESIZE_PORT_PREFIX "> .\n"; -#if DISTRHO_PLUGIN_HAS_UI - pluginString += "@prefix ui: <" LV2_UI_PREFIX "> .\n"; -#endif - pluginString += "@prefix unit: <" LV2_UNITS_PREFIX "> .\n"; - pluginString += "\n"; - - // plugin - pluginString += "<" DISTRHO_PLUGIN_URI ">\n"; -#if DISTRHO_PLUGIN_IS_SYNTH - pluginString += " a lv2:InstrumentPlugin, lv2:Plugin ;\n"; -#else - pluginString += " a lv2:Plugin ;\n"; -#endif - pluginString += "\n"; - - // extensionData - pluginString += " lv2:extensionData <" LV2_STATE__interface "> "; -#if DISTRHO_PLUGIN_WANT_STATE - pluginString += ",\n <" LV2_OPTIONS__interface "> "; - pluginString += ",\n <" LV2_WORKER__interface "> "; -#endif -#if DISTRHO_PLUGIN_WANT_PROGRAMS - pluginString += ",\n <" LV2_PROGRAMS__Interface "> "; -#endif - pluginString += ";\n\n"; - - // optionalFeatures -#if DISTRHO_PLUGIN_IS_RT_SAFE - pluginString += " lv2:optionalFeature <" LV2_CORE__hardRTCapable "> ,\n"; - pluginString += " <" LV2_BUF_SIZE__boundedBlockLength "> ;\n"; -#else - pluginString += " lv2:optionalFeature <" LV2_BUF_SIZE__boundedBlockLength "> ;\n"; -#endif - pluginString += "\n"; - - // requiredFeatures - pluginString += " lv2:requiredFeature <" LV2_OPTIONS__options "> "; - pluginString += ",\n <" LV2_URID__map "> "; -#if DISTRHO_PLUGIN_WANT_STATE - pluginString += ",\n <" LV2_WORKER__schedule "> "; -#endif - pluginString += ";\n\n"; - - // UI -#if DISTRHO_PLUGIN_HAS_UI - pluginString += " ui:ui <" DISTRHO_UI_URI "> ;\n"; - pluginString += "\n"; -#endif - - { - uint32_t portIndex = 0; - -#if DISTRHO_PLUGIN_NUM_INPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i, ++portIndex) - { - if (i == 0) - pluginString += " lv2:port [\n"; - else - pluginString += " [\n"; - - pluginString += " a lv2:InputPort, lv2:AudioPort ;\n"; - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:symbol \"lv2_audio_in_" + d_string(i+1) + "\" ;\n"; - pluginString += " lv2:name \"Audio Input " + d_string(i+1) + "\" ;\n"; - - if (i+1 == DISTRHO_PLUGIN_NUM_INPUTS) - pluginString += " ] ;\n\n"; - else - pluginString += " ] ,\n"; - } - pluginString += "\n"; -#endif - -#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0 - for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i, ++portIndex) - { - if (i == 0) - pluginString += " lv2:port [\n"; - else - pluginString += " [\n"; - - pluginString += " a lv2:OutputPort, lv2:AudioPort ;\n"; - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:symbol \"lv2_audio_out_" + d_string(i+1) + "\" ;\n"; - pluginString += " lv2:name \"Audio Output " + d_string(i+1) + "\" ;\n"; - - if (i+1 == DISTRHO_PLUGIN_NUM_OUTPUTS) - pluginString += " ] ;\n\n"; - else - pluginString += " ] ,\n"; - } - pluginString += "\n"; -#endif - -#if DISTRHO_LV2_USE_EVENTS_IN - pluginString += " lv2:port [\n"; - pluginString += " a lv2:InputPort, atom:AtomPort ;\n"; - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:name \"Events Input\" ;\n"; - pluginString += " lv2:symbol \"lv2_events_in\" ;\n"; - pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n"; - pluginString += " atom:bufferType atom:Sequence ;\n"; -# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI) - pluginString += " atom:supports <" LV2_ATOM__String "> ;\n"; -# endif -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT - pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n"; -# endif -# if DISTRHO_PLUGIN_WANT_TIMEPOS - pluginString += " atom:supports <" LV2_TIME__Position "> ;\n"; -# endif - pluginString += " ] ;\n\n"; - ++portIndex; -#endif - -#if DISTRHO_LV2_USE_EVENTS_OUT - pluginString += " lv2:port [\n"; - pluginString += " a lv2:OutputPort, atom:AtomPort ;\n"; - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:name \"Events Output\" ;\n"; - pluginString += " lv2:symbol \"lv2_events_out\" ;\n"; - pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n"; - pluginString += " atom:bufferType atom:Sequence ;\n"; -# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI) - pluginString += " atom:supports <" LV2_ATOM__String "> ;\n"; -# endif -# if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT - pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n"; -# endif - pluginString += " ] ;\n\n"; - ++portIndex; -#endif - -#if DISTRHO_PLUGIN_WANT_LATENCY - pluginString += " lv2:port [\n"; - pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n"; - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:name \"Latency\" ;\n"; - pluginString += " lv2:symbol \"lv2_latency\" ;\n"; - pluginString += " lv2:designation lv2:latency ;\n"; - pluginString += " lv2:portProperty lv2:reportsLatency, lv2:integer ;\n"; - pluginString += " ] ;\n\n"; - ++portIndex; -#endif - - for (uint32_t i=0, count=plugin.getParameterCount(); i < count; ++i, ++portIndex) - { - if (i == 0) - pluginString += " lv2:port [\n"; - else - pluginString += " [\n"; - - if (plugin.isParameterOutput(i)) - pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n"; - else - pluginString += " a lv2:InputPort, lv2:ControlPort ;\n"; - - pluginString += " lv2:index " + d_string(portIndex) + " ;\n"; - pluginString += " lv2:name \"" + plugin.getParameterName(i) + "\" ;\n"; - - // symbol - { - d_string symbol(plugin.getParameterSymbol(i)); - - if (symbol.isEmpty()) - symbol = "lv2_port_" + d_string(portIndex-1); - - pluginString += " lv2:symbol \"" + symbol + "\" ;\n"; - } - - // ranges - { - const ParameterRanges& ranges(plugin.getParameterRanges(i)); - - if (plugin.getParameterHints(i) & kParameterIsInteger) - { - pluginString += " lv2:default " + d_string(int(plugin.getParameterValue(i))) + " ;\n"; - pluginString += " lv2:minimum " + d_string(int(ranges.min)) + " ;\n"; - pluginString += " lv2:maximum " + d_string(int(ranges.max)) + " ;\n"; - } - else - { - pluginString += " lv2:default " + d_string(plugin.getParameterValue(i)) + " ;\n"; - pluginString += " lv2:minimum " + d_string(ranges.min) + " ;\n"; - pluginString += " lv2:maximum " + d_string(ranges.max) + " ;\n"; - } - } - - // unit - { - const d_string& unit(plugin.getParameterUnit(i)); - - if (! unit.isEmpty()) - { - if (unit == "db" || unit == "dB") - { - pluginString += " unit:unit unit:db ;\n"; - } - else if (unit == "hz" || unit == "Hz") - { - pluginString += " unit:unit unit:hz ;\n"; - } - else if (unit == "khz" || unit == "kHz") - { - pluginString += " unit:unit unit:khz ;\n"; - } - else if (unit == "mhz" || unit == "mHz") - { - pluginString += " unit:unit unit:mhz ;\n"; - } - else if (unit == "%") - { - pluginString += " unit:unit unit:pc ;\n"; - } - else - { - pluginString += " unit:unit [\n"; - pluginString += " a unit:Unit ;\n"; - pluginString += " unit:name \"" + unit + "\" ;\n"; - pluginString += " unit:symbol \"" + unit + "\" ;\n"; - pluginString += " unit:render \"%f " + unit + "\" ;\n"; - pluginString += " ] ;\n"; - } - } - } - - // hints - { - const uint32_t hints(plugin.getParameterHints(i)); - - if (hints & kParameterIsBoolean) - pluginString += " lv2:portProperty lv2:toggled ;\n"; - if (hints & kParameterIsInteger) - pluginString += " lv2:portProperty lv2:integer ;\n"; - if (hints & kParameterIsLogarithmic) - pluginString += " lv2:portProperty <" LV2_PORT_PROPS__logarithmic "> ;\n"; - if ((hints & kParameterIsAutomable) == 0 && ! plugin.isParameterOutput(i)) - { - pluginString += " lv2:portProperty <" LV2_PORT_PROPS__expensive "> ,\n"; - pluginString += " <" LV2_KXSTUDIO_PROPERTIES__NonAutomable "> ;\n"; - } - } - - if (i+1 == count) - pluginString += " ] ;\n\n"; - else - pluginString += " ] ,\n"; - } - } - - pluginString += " doap:name \"" + d_string(plugin.getName()) + "\" ;\n"; - pluginString += " doap:maintainer [ foaf:name \"" + d_string(plugin.getMaker()) + "\" ] .\n"; - - pluginFile << pluginString << std::endl; - pluginFile.close(); - std::cout << " done!" << std::endl; - } -} diff --git a/libs/distrho/src/DistrhoPluginVST.cpp b/libs/distrho/src/DistrhoPluginVST.cpp deleted file mode 100644 index 57ea038..0000000 --- a/libs/distrho/src/DistrhoPluginVST.cpp +++ /dev/null @@ -1,1066 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoPluginInternal.hpp" - -#if DISTRHO_PLUGIN_HAS_UI -# include "DistrhoUIInternal.hpp" -#endif - -#ifndef __cdecl -# define __cdecl -#endif - -// has some conflicts -#ifdef noexcept -# undef noexcept -#endif - -#define VESTIGE_HEADER -#define VST_FORCE_DEPRECATED 0 - -#include <map> -#include <string> - -#ifdef VESTIGE_HEADER -# include "vestige/aeffectx.h" -#define effFlagsProgramChunks (1 << 5) -#define effSetProgramName 4 -#define effGetParamLabel 6 -#define effGetParamDisplay 7 -#define effGetChunk 23 -#define effSetChunk 24 -#define effCanBeAutomated 26 -#define effGetProgramNameIndexed 29 -#define effGetPlugCategory 35 -#define effIdle 53 -#define kPlugCategEffect 1 -#define kPlugCategSynth 2 -#define kVstVersion 2400 -struct ERect { - int16_t top, left, bottom, right; -}; -#else -# include "vst/aeffectx.h" -#endif - -START_NAMESPACE_DISTRHO - -typedef std::map<const d_string,d_string> StringMap; - -// ----------------------------------------------------------------------- - -void strncpy(char* const dst, const char* const src, const size_t size) -{ - std::strncpy(dst, src, size-1); - dst[size-1] = '\0'; -} - -void snprintf_param(char* const dst, const float value, const size_t size) -{ - std::snprintf(dst, size-1, "%f", value); - dst[size-1] = '\0'; -} - -#if DISTRHO_PLUGIN_HAS_UI -// ----------------------------------------------------------------------- - -class UiHelper -{ -public: - UiHelper() - : parameterChecks(nullptr), - parameterValues(nullptr) {} - - virtual ~UiHelper() - { - if (parameterChecks != nullptr) - { - delete[] parameterChecks; - parameterChecks = nullptr; - } - if (parameterValues != nullptr) - { - delete[] parameterValues; - parameterValues = nullptr; - } - } - - bool* parameterChecks; - float* parameterValues; - -#if DISTRHO_PLUGIN_WANT_STATE - virtual void setStateFromUI(const char* const newKey, const char* const newValue) = 0; -#endif -}; - -// ----------------------------------------------------------------------- - -class UIVst -{ -public: - UIVst(const audioMasterCallback audioMaster, AEffect* const effect, UiHelper* const uiHelper, PluginExporter* const plugin, const intptr_t winId) - : fAudioMaster(audioMaster), - fEffect(effect), - fUiHelper(uiHelper), - fPlugin(plugin), - fUI(this, winId, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer()) - { - } - - // ------------------------------------------------------------------- - - void idle() - { - for (uint32_t i=0, count = fPlugin->getParameterCount(); i < count; ++i) - { - if (fUiHelper->parameterChecks[i]) - { - fUiHelper->parameterChecks[i] = false; - fUI.parameterChanged(i, fUiHelper->parameterValues[i]); - } - } - - fUI.idle(); - } - - int16_t getWidth() const - { - return fUI.getWidth(); - } - - int16_t getHeight() const - { - return fUI.getHeight(); - } - - void setSampleRate(const double newSampleRate) - { - fUI.setSampleRate(newSampleRate, true); - } - - // ------------------------------------------------------------------- - // functions called from the plugin side, may block - -#if DISTRHO_PLUGIN_WANT_STATE - void setStateFromPlugin(const char* const key, const char* const value) - { - fUI.stateChanged(key, value); - } -#endif - - // ------------------------------------------------------------------- - -protected: - intptr_t hostCallback(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt) - { - return fAudioMaster(fEffect, opcode, index, value, ptr, opt); - } - - void editParameter(const uint32_t index, const bool started) - { - hostCallback(started ? audioMasterBeginEdit : audioMasterEndEdit, index, 0, nullptr, 0.0f); - } - - void setParameterValue(const uint32_t index, const float realValue) - { - const ParameterRanges& ranges(fPlugin->getParameterRanges(index)); - const float perValue(ranges.getNormalizedValue(realValue)); - - fPlugin->setParameterValue(index, realValue); - hostCallback(audioMasterAutomate, index, 0, nullptr, perValue); - } - - void setState(const char* const key, const char* const value) - { -#if DISTRHO_PLUGIN_WANT_STATE - fUiHelper->setStateFromUI(key, value); -#else - return; // unused - (void)key; - (void)value; -#endif - } - - void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity) - { -#if 0 //DISTRHO_PLUGIN_HAS_MIDI_INPUT - // TODO -#else - return; // unused - (void)channel; - (void)note; - (void)velocity; -#endif - } - - void setSize(const uint width, const uint height) - { - fUI.setWindowSize(width, height); - hostCallback(audioMasterSizeWindow, width, height, nullptr, 0.0f); - } - -private: - // Vst stuff - const audioMasterCallback fAudioMaster; - AEffect* const fEffect; - UiHelper* const fUiHelper; - PluginExporter* const fPlugin; - - // Plugin UI - UIExporter fUI; - - // ------------------------------------------------------------------- - // Callbacks - - #define handlePtr ((UIVst*)ptr) - - static void editParameterCallback(void* ptr, uint32_t index, bool started) - { - handlePtr->editParameter(index, started); - } - - static void setParameterCallback(void* ptr, uint32_t rindex, float value) - { - handlePtr->setParameterValue(rindex, value); - } - - static void setStateCallback(void* ptr, const char* key, const char* value) - { - handlePtr->setState(key, value); - } - - static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) - { - handlePtr->sendNote(channel, note, velocity); - } - - static void setSizeCallback(void* ptr, uint width, uint height) - { - handlePtr->setSize(width, height); - } - - #undef handlePtr -}; -#endif - -// ----------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_HAS_UI -class PluginVst : public UiHelper -#else -class PluginVst -#endif -{ -public: - PluginVst(const audioMasterCallback audioMaster, AEffect* const effect) - : fAudioMaster(audioMaster), - fEffect(effect) - { - std::memset(fProgramName, 0, sizeof(char)*(32+1)); - std::strcpy(fProgramName, "Default"); - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - fMidiEventCount = 0; -#endif - -#if DISTRHO_PLUGIN_HAS_UI - fVstUI = nullptr; - fVstRect.top = 0; - fVstRect.left = 0; - fVstRect.bottom = 0; - fVstRect.right = 0; - - if (const uint32_t paramCount = fPlugin.getParameterCount()) - { - parameterChecks = new bool[paramCount]; - parameterValues = new float[paramCount]; - - for (uint32_t i=0; i < paramCount; ++i) - { - parameterChecks[i] = false; - parameterValues[i] = 0.0f; - } - } -# if DISTRHO_OS_MAC -# ifdef __LP64__ - fUsingNsView = true; -# else -# warning 32bit VST UIs on OSX only work if the host supports "hasCockosViewAsConfig" - fUsingNsView = false; -# endif -# endif // DISTRHO_OS_MAC -#endif // DISTRHO_PLUGIN_HAS_UI - -#if DISTRHO_PLUGIN_WANT_STATE - fStateChunk = nullptr; - - for (uint32_t i=0, count=fPlugin.getStateCount(); i<count; ++i) - { - const d_string& d_key(fPlugin.getStateKey(i)); - fStateMap[d_key] = fPlugin.getStateDefaultValue(i); - } -#endif - } - - ~PluginVst() - { -#if DISTRHO_PLUGIN_WANT_STATE - if (fStateChunk != nullptr) - { - delete[] fStateChunk; - fStateChunk = nullptr; - } - - fStateMap.clear(); -#endif - } - - intptr_t vst_dispatcher(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt) - { - switch (opcode) - { - case effGetProgram: - return 0; - - case effSetProgramName: - if (char* const programName = (char*)ptr) - { - DISTRHO::strncpy(fProgramName, programName, 32); - return 1; - } - break; - - case effGetProgramName: - if (char* const programName = (char*)ptr) - { - DISTRHO::strncpy(programName, fProgramName, 24); - return 1; - } - break; - - case effGetProgramNameIndexed: - if (char* const programName = (char*)ptr) - { - DISTRHO::strncpy(programName, fProgramName, 24); - return 1; - } - break; - - case effGetParamDisplay: - if (ptr != nullptr && index < static_cast<int32_t>(fPlugin.getParameterCount())) - { - DISTRHO::snprintf_param((char*)ptr, fPlugin.getParameterValue(index), 24); - return 1; - } - break; - - case effSetSampleRate: - fPlugin.setSampleRate(opt, true); - -#if DISTRHO_PLUGIN_HAS_UI - if (fVstUI != nullptr) - fVstUI->setSampleRate(opt); -#endif - break; - - case effSetBlockSize: - fPlugin.setBufferSize(value, true); - break; - - case effMainsChanged: - if (value != 0) - { - fPlugin.activate(); -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - fMidiEventCount = 0; -#endif - } - else - { - fPlugin.deactivate(); - } - break; - -#if DISTRHO_PLUGIN_HAS_UI - case effEditGetRect: - if (fVstUI != nullptr) - { - fVstRect.right = fVstUI->getWidth(); - fVstRect.bottom = fVstUI->getHeight(); - } - else - { - d_lastUiSampleRate = fPlugin.getSampleRate(); - - UIExporter tmpUI(nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, fPlugin.getInstancePointer()); - fVstRect.right = tmpUI.getWidth(); - fVstRect.bottom = tmpUI.getHeight(); - tmpUI.quit(); - } - *(ERect**)ptr = &fVstRect; - return 1; - - case effEditOpen: - if (fVstUI == nullptr) - { -# if DISTRHO_OS_MAC - if (! fUsingNsView) - { - d_stderr("Host doesn't support hasCockosViewAsConfig, cannot use UI"); - return 0; - } -# endif - d_lastUiSampleRate = fPlugin.getSampleRate(); - - fVstUI = new UIVst(fAudioMaster, fEffect, this, &fPlugin, (intptr_t)ptr); - -# if DISTRHO_PLUGIN_WANT_STATE - for (StringMap::const_iterator cit=fStateMap.begin(), cite=fStateMap.end(); cit != cite; ++cit) - { - const d_string& key = cit->first; - const d_string& value = cit->second; - - fVstUI->setStateFromPlugin(key, value); - } -# endif - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - setParameterValueFromPlugin(i, fPlugin.getParameterValue(i)); - - fVstUI->idle(); - return 1; - } - break; - - case effEditClose: - if (fVstUI != nullptr) - { - delete fVstUI; - fVstUI = nullptr; - return 1; - } - break; - - //case effIdle: - case effEditIdle: - if (fVstUI != nullptr) - fVstUI->idle(); - break; -#endif // DISTRHO_PLUGIN_HAS_UI - -#if DISTRHO_PLUGIN_WANT_STATE - case effGetChunk: - if (ptr == nullptr) - return 0; - - if (fStateChunk != nullptr) - { - delete[] fStateChunk; - fStateChunk = nullptr; - } - - if (fPlugin.getStateCount() == 0) - { - fStateChunk = new char[1]; - fStateChunk[0] = '\0'; - return 1; - } - else - { - d_string chunkStr; - - for (StringMap::const_iterator cit=fStateMap.begin(), cite=fStateMap.end(); cit != cite; ++cit) - { - const d_string& key = cit->first; - const d_string& value = cit->second; - - // join key and value - d_string tmpStr; - tmpStr = key; - tmpStr += "\xff"; - tmpStr += value; - tmpStr += "\xff"; - - chunkStr += tmpStr; - } - - const std::size_t chunkSize(chunkStr.length()+1); - - fStateChunk = new char[chunkSize]; - std::memcpy(fStateChunk, chunkStr.buffer(), chunkStr.length()); - fStateChunk[chunkSize] = '\0'; - - for (std::size_t i=0; i<chunkSize; ++i) - { - if (fStateChunk[i] == '\xff') - fStateChunk[i] = '\0'; - } - - return chunkSize; - } - - *(void**)ptr = fStateChunk; - break; - - case effSetChunk: - { - if (value <= 1 || ptr == nullptr) - return 0; - - const char* key = (const char*)ptr; - const char* value = nullptr; - - for (;;) - { - if (key[0] == '\0') - break; - - value = key+(std::strlen(key)+1); - - setStateFromUI(key, value); - - if (fVstUI != nullptr) - fVstUI->setStateFromPlugin(key, value); - - // get next key - key = value+(std::strlen(value)+1); - } - - return 1; - } -#endif // DISTRHO_PLUGIN_WANT_STATE - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - case effProcessEvents: - if (const VstEvents* const events = (const VstEvents*)ptr) - { - if (events->numEvents == 0) - break; - - for (int i=0, count=events->numEvents; i < count; ++i) - { - const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)events->events[i]); - - if (vstMidiEvent == nullptr) - break; - if (vstMidiEvent->type != kVstMidiType) - continue; - if (fMidiEventCount >= kMaxMidiEvents) - break; - - MidiEvent& midiEvent(fMidiEvents[fMidiEventCount++]); - midiEvent.frame = vstMidiEvent->deltaFrames; - midiEvent.size = 3; - std::memcpy(midiEvent.data, vstMidiEvent->midiData, sizeof(uint8_t)*3); - } - } - break; -#endif - - case effCanBeAutomated: - if (index < static_cast<int32_t>(fPlugin.getParameterCount())) - { - const uint32_t hints(fPlugin.getParameterHints(index)); - - // must be automable, and not output - if ((hints & kParameterIsAutomable) != 0 && (hints & kParameterIsOutput) == 0) - return 1; - } - break; - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT || DISTRHO_PLUGIN_HAS_MIDI_OUTPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || DISTRHO_OS_MAC - case effCanDo: - if (const char* const canDo = (const char*)ptr) - { -# if DISTRHO_OS_MAC && DISTRHO_PLUGIN_HAS_UI - if (std::strcmp(canDo, "hasCockosViewAsConfig") == 0) - { - fUsingNsView = true; - return 0xbeef0000; - } -# endif -# if DISTRHO_PLUGIN_HAS_MIDI_INPUT - if (std::strcmp(canDo, "receiveVstEvents") == 0) - return 1; - if (std::strcmp(canDo, "receiveVstMidiEvent") == 0) - return 1; -# endif -# if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT - if (std::strcmp(canDo, "sendVstEvents") == 0) - return 1; - if (std::strcmp(canDo, "sendVstMidiEvent") == 0) - return 1; -# endif -# if DISTRHO_PLUGIN_WANT_TIMEPOS - if (std::strcmp(canDo, "receiveVstTimeInfo") == 0) - return 1; -# endif - } - break; -#endif - - //case effStartProcess: - //case effStopProcess: - // unused - // break; - } - - return 0; - } - - float vst_getParameter(const int32_t index) - { - const ParameterRanges& ranges(fPlugin.getParameterRanges(index)); - return ranges.getNormalizedValue(fPlugin.getParameterValue(index)); - } - - void vst_setParameter(const int32_t index, const float value) - { - const ParameterRanges& ranges(fPlugin.getParameterRanges(index)); - const float realValue(ranges.getUnnormalizedValue(value)); - fPlugin.setParameterValue(index, realValue); - -#if DISTRHO_PLUGIN_HAS_UI - if (fVstUI != nullptr) - setParameterValueFromPlugin(index, realValue); -#endif - } - - void vst_processReplacing(const float** const inputs, float** const outputs, const int32_t sampleFrames) - { -#if DISTRHO_PLUGIN_WANT_TIMEPOS - static const int kWantVstTimeFlags(kVstTransportPlaying|kVstPpqPosValid|kVstTempoValid|kVstTimeSigValid); - - if (const VstTimeInfo* const vstTimeInfo = (const VstTimeInfo*)fAudioMaster(fEffect, audioMasterGetTime, 0, kWantVstTimeFlags, nullptr, 0.0f)) - { - fTimePosition.frame = vstTimeInfo->samplePos; - fTimePosition.playing = (vstTimeInfo->flags & kVstTransportPlaying); - fTimePosition.bbt.valid = ((vstTimeInfo->flags & kVstTempoValid) != 0 || (vstTimeInfo->flags & kVstTimeSigValid) != 0); - - // ticksPerBeat is not possible with VST - fTimePosition.bbt.ticksPerBeat = 960.0; - - if (vstTimeInfo->flags & kVstTempoValid) - fTimePosition.bbt.beatsPerMinute = vstTimeInfo->tempo; - else - fTimePosition.bbt.beatsPerMinute = 120.0; - - if (vstTimeInfo->flags & (kVstPpqPosValid|kVstTimeSigValid)) - { - const int ppqPerBar = vstTimeInfo->timeSigNumerator * 4 / vstTimeInfo->timeSigDenominator; - const double barBeats = (std::fmod(vstTimeInfo->ppqPos, ppqPerBar) / ppqPerBar) * vstTimeInfo->timeSigDenominator; - const double rest = std::fmod(barBeats, 1.0); - - fTimePosition.bbt.bar = int(vstTimeInfo->ppqPos)/ppqPerBar + 1; - fTimePosition.bbt.beat = barBeats-rest+1; - fTimePosition.bbt.tick = rest*fTimePosition.bbt.ticksPerBeat+0.5; - fTimePosition.bbt.beatsPerBar = vstTimeInfo->timeSigNumerator; - fTimePosition.bbt.beatType = vstTimeInfo->timeSigDenominator; - } - else - { - fTimePosition.bbt.bar = 1; - fTimePosition.bbt.beat = 1; - fTimePosition.bbt.tick = 0; - fTimePosition.bbt.beatsPerBar = 4.0f; - fTimePosition.bbt.beatType = 4.0f; - } - - fTimePosition.bbt.barStartTick = fTimePosition.bbt.ticksPerBeat*fTimePosition.bbt.beatsPerBar*(fTimePosition.bbt.bar-1); - - fPlugin.setTimePosition(fTimePosition); - } -#endif - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - fPlugin.run(inputs, outputs, sampleFrames, fMidiEvents, fMidiEventCount); - fMidiEventCount = 0; -#else - fPlugin.run(inputs, outputs, sampleFrames); -#endif - -#if DISTRHO_PLUGIN_HAS_UI - if (fVstUI == nullptr) - return; - - for (uint32_t i=0, count=fPlugin.getParameterCount(); i < count; ++i) - { - if (fPlugin.isParameterOutput(i)) - setParameterValueFromPlugin(i, fPlugin.getParameterValue(i)); - } -#endif - } - - // ------------------------------------------------------------------- - - friend class UIVst; - -private: - // VST stuff - const audioMasterCallback fAudioMaster; - AEffect* const fEffect; - - // Plugin - PluginExporter fPlugin; - - // Temporary data - char fProgramName[32+1]; - -#if DISTRHO_PLUGIN_HAS_MIDI_INPUT - uint32_t fMidiEventCount; - MidiEvent fMidiEvents[kMaxMidiEvents]; -#endif - -#if DISTRHO_PLUGIN_WANT_TIMEPOS - TimePosition fTimePosition; -#endif - - // UI stuff -#if DISTRHO_PLUGIN_HAS_UI - UIVst* fVstUI; - ERect fVstRect; -# if DISTRHO_OS_MAC - bool fUsingNsView; -# endif -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - char* fStateChunk; - StringMap fStateMap; -#endif - - // ------------------------------------------------------------------- - // functions called from the plugin side, RT no block - -#if DISTRHO_PLUGIN_HAS_UI - void setParameterValueFromPlugin(const uint32_t index, const float realValue) - { - parameterValues[index] = realValue; - parameterChecks[index] = true; - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - // ------------------------------------------------------------------- - // functions called from the UI side, may block - - void setStateFromUI(const char* const key, const char* const newValue) override - { - fPlugin.setState(key, newValue); - - // check if we want to save this key - if (! fPlugin.wantStateKey(key)) - return; - - // check if key already exists - for (StringMap::iterator it=fStateMap.begin(), ite=fStateMap.end(); it != ite; ++it) - { - const d_string& d_key(it->first); - - if (d_key == key) - { - it->second = newValue; - return; - } - } - - d_stderr("Failed to find plugin state with key \"%s\"", key); - } -#endif -}; - -// ----------------------------------------------------------------------- - -struct VstObject { - audioMasterCallback audioMaster; - PluginVst* plugin; -}; - -#ifdef VESTIGE_HEADER -# define validObject effect != nullptr && effect->ptr3 != nullptr -# define validPlugin effect != nullptr && effect->ptr3 != nullptr && ((VstObject*)effect->ptr3)->plugin != nullptr -# define vstObjectPtr (VstObject*)effect->ptr3 -#else -# define validObject effect != nullptr && effect->object != nullptr -# define validPlugin effect != nullptr && effect->object != nullptr && ((VstObject*)effect->object)->plugin != nullptr -# define vstObjectPtr (VstObject*)effect->object -#endif - -#define pluginPtr (vstObjectPtr)->plugin - -static intptr_t vst_dispatcherCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt) -{ - // first internal init - const bool doInternalInit = (opcode == -1729 && index == 0xdead && value == 0xf00d); - - if (doInternalInit) - { - // set valid but dummy values - d_lastBufferSize = 512; - d_lastSampleRate = 44100.0; - } - - // Create dummy plugin to get data from - static PluginExporter plugin; - - if (doInternalInit) - { - // unset - d_lastBufferSize = 0; - d_lastSampleRate = 0.0; - - *(PluginExporter**)ptr = &plugin; - return 0; - } - - // handle base opcodes - switch (opcode) - { - case effOpen: - if (VstObject* const obj = vstObjectPtr) - { - // this must always be valid - DISTRHO_SAFE_ASSERT_RETURN(obj->audioMaster != nullptr, 0); - - // some hosts call effOpen twice - DISTRHO_SAFE_ASSERT_RETURN(obj->plugin == nullptr, 1); - - audioMasterCallback audioMaster = (audioMasterCallback)obj->audioMaster; - - d_lastBufferSize = audioMaster(effect, audioMasterGetBlockSize, 0, 0, nullptr, 0.0f); - d_lastSampleRate = audioMaster(effect, audioMasterGetSampleRate, 0, 0, nullptr, 0.0f); - - // some hosts are not ready at this point or return 0 buffersize/samplerate - if (d_lastBufferSize == 0) - d_lastBufferSize = 2048; - if (d_lastSampleRate <= 0.0) - d_lastSampleRate = 44100.0; - - obj->plugin = new PluginVst(audioMaster, effect); - return 1; - } - return 0; - - case effClose: - if (VstObject* const obj = vstObjectPtr) - { - if (obj->plugin != nullptr) - { - delete obj->plugin; - obj->plugin = nullptr; - } - -#if 0 - /* This code invalidates the object created in VSTPluginMain - * Probably not safe against all hosts */ - obj->audioMaster = nullptr; -# ifdef VESTIGE_HEADER - effect->ptr3 = nullptr; -# else - vstObjectPtr = nullptr; -# endif - delete obj; -#endif - - return 1; - } - //delete effect; - return 0; - - case effGetParamLabel: - if (ptr != nullptr && index < static_cast<int32_t>(plugin.getParameterCount())) - { - DISTRHO::strncpy((char*)ptr, plugin.getParameterUnit(index), 8); - return 1; - } - return 0; - - case effGetParamName: - if (ptr != nullptr && index < static_cast<int32_t>(plugin.getParameterCount())) - { - DISTRHO::strncpy((char*)ptr, plugin.getParameterName(index), 16); - return 1; - } - return 0; - - case effGetPlugCategory: -#if DISTRHO_PLUGIN_IS_SYNTH - return kPlugCategSynth; -#else - return kPlugCategEffect; -#endif - - case effGetEffectName: - if (char* const cptr = (char*)ptr) - { - DISTRHO::strncpy(cptr, plugin.getName(), 32); - return 1; - } - return 0; - - case effGetVendorString: - if (char* const cptr = (char*)ptr) - { - DISTRHO::strncpy(cptr, plugin.getMaker(), 32); - return 1; - } - return 0; - - case effGetProductString: - if (char* const cptr = (char*)ptr) - { - DISTRHO::strncpy(cptr, plugin.getLabel(), 32); - return 1; - } - return 0; - - case effGetVendorVersion: - return plugin.getVersion(); - - case effGetVstVersion: - return kVstVersion; - }; - - // handle advanced opcodes - if (validPlugin) - return pluginPtr->vst_dispatcher(opcode, index, value, ptr, opt); - - return 0; -} - -static float vst_getParameterCallback(AEffect* effect, int32_t index) -{ - if (validPlugin) - return pluginPtr->vst_getParameter(index); - return 0.0f; -} - -static void vst_setParameterCallback(AEffect* effect, int32_t index, float value) -{ - if (validPlugin) - pluginPtr->vst_setParameter(index, value); -} - -static void vst_processCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames) -{ - if (validPlugin) - pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames); -} - -static void vst_processReplacingCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames) -{ - if (validPlugin) - pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames); -} - -#undef pluginPtr -#undef validObject -#undef validPlugin -#undef vstObjectPtr - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -DISTRHO_PLUGIN_EXPORT -#if DISTRHO_OS_WINDOWS || DISTRHO_OS_MAC -const AEffect* VSTPluginMain(audioMasterCallback audioMaster); -#else -const AEffect* VSTPluginMain(audioMasterCallback audioMaster) asm ("main"); -#endif - -DISTRHO_PLUGIN_EXPORT -const AEffect* VSTPluginMain(audioMasterCallback audioMaster) -{ - USE_NAMESPACE_DISTRHO - - // old version - if (audioMaster(nullptr, audioMasterVersion, 0, 0, nullptr, 0.0f) == 0) - return nullptr; - - // first internal init - PluginExporter* plugin = nullptr; - vst_dispatcherCallback(nullptr, -1729, 0xdead, 0xf00d, &plugin, 0.0f); - DISTRHO_SAFE_ASSERT_RETURN(plugin != nullptr, nullptr); - - AEffect* const effect(new AEffect); - std::memset(effect, 0, sizeof(AEffect)); - - // vst fields - effect->magic = kEffectMagic; - effect->uniqueID = plugin->getUniqueId(); -#ifdef VESTIGE_HEADER - int32_t* const version = (int32_t*)&effect->unknown1; - *version = plugin->getVersion(); -#else - effect->version = plugin->getVersion(); -#endif - - // VST doesn't support parameter outputs, hide them - int numParams = 0; - bool outputsReached = false; - - for (uint32_t i=0, count=plugin->getParameterCount(); i < count; ++i) - { - if (! plugin->isParameterOutput(i)) - { - // parameter outputs must be all at the end - DISTRHO_SAFE_ASSERT_BREAK(! outputsReached); - ++numParams; - continue; - } - outputsReached = true; - } - - // plugin fields - effect->numParams = numParams; - effect->numPrograms = 1; - effect->numInputs = DISTRHO_PLUGIN_NUM_INPUTS; - effect->numOutputs = DISTRHO_PLUGIN_NUM_OUTPUTS; - - // plugin flags - effect->flags |= effFlagsCanReplacing; -#if DISTRHO_PLUGIN_IS_SYNTH - effect->flags |= effFlagsIsSynth; -#endif -#if DISTRHO_PLUGIN_HAS_UI - effect->flags |= effFlagsHasEditor; -#endif -#if DISTRHO_PLUGIN_WANT_STATE - effect->flags |= effFlagsProgramChunks; -#endif - - // static calls - effect->dispatcher = vst_dispatcherCallback; - effect->process = vst_processCallback; - effect->getParameter = vst_getParameterCallback; - effect->setParameter = vst_setParameterCallback; - effect->processReplacing = vst_processReplacingCallback; - - // pointers - VstObject* const obj(new VstObject()); - obj->audioMaster = audioMaster; - obj->plugin = nullptr; -#ifdef VESTIGE_HEADER - effect->ptr3 = obj; -#else - effect->object = obj; -#endif - - return effect; -} - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/DistrhoUI.cpp b/libs/distrho/src/DistrhoUI.cpp deleted file mode 100644 index 49e8c3e..0000000 --- a/libs/distrho/src/DistrhoUI.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoUIInternal.hpp" - -START_NAMESPACE_DISTRHO - -/* ------------------------------------------------------------------------------------------------------------ - * Static data, see DistrhoUIInternal.hpp */ - -double d_lastUiSampleRate = 0.0; -void* d_lastUiDspPtr = nullptr; -Window* d_lastUiWindow = nullptr; - -/* ------------------------------------------------------------------------------------------------------------ - * UI */ - -UI::UI() - : UIWidget(*d_lastUiWindow), - pData(new PrivateData()) -{ - UIWidget::setNeedsFullViewport(true); -} - -UI::~UI() -{ - delete pData; -} - -/* ------------------------------------------------------------------------------------------------------------ - * Host state */ - -double UI::d_getSampleRate() const noexcept -{ - return pData->sampleRate; -} - -void UI::d_editParameter(const uint32_t index, const bool started) -{ - pData->editParamCallback(index + pData->parameterOffset, started); -} - -void UI::d_setParameterValue(const uint32_t index, const float value) -{ - pData->setParamCallback(index + pData->parameterOffset, value); -} - -#if DISTRHO_PLUGIN_WANT_STATE -void UI::d_setState(const char* const key, const char* const value) -{ - pData->setStateCallback(key, value); -} -#endif - -#if DISTRHO_PLUGIN_IS_SYNTH -void UI::d_sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity) -{ - pData->sendNoteCallback(channel, note, velocity); -} -#endif - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -/* ------------------------------------------------------------------------------------------------------------ - * Direct DSP access */ - -void* UI::d_getPluginInstancePointer() const noexcept -{ - return pData->dspPtr; -} -#endif - -/* ------------------------------------------------------------------------------------------------------------ - * DSP/Plugin Callbacks (optional) */ - -void UI::d_sampleRateChanged(double) {} - -/* ------------------------------------------------------------------------------------------------------------ - * UI Callbacks (optional) */ - -void UI::d_uiFileBrowserSelected(const char*) -{ -} - -void UI::d_uiReshape(uint width, uint height) -{ - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0.0, static_cast<GLdouble>(width), static_cast<GLdouble>(height), 0.0, 0.0, 1.0); - glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height)); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); -} - -/* ------------------------------------------------------------------------------------------------------------ - * UI Resize Handling, internal */ - -void UI::onResize(const ResizeEvent& ev) -{ - pData->setSizeCallback(ev.size.getWidth(), ev.size.getHeight()); -} - -// ----------------------------------------------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO diff --git a/libs/distrho/src/DistrhoUIDSSI.cpp b/libs/distrho/src/DistrhoUIDSSI.cpp deleted file mode 100644 index 0a3d6f9..0000000 --- a/libs/distrho/src/DistrhoUIDSSI.cpp +++ /dev/null @@ -1,511 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoUIInternal.hpp" - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -# error DSSI UIs do not support direct access! -#endif - -#include "../extra/d_sleep.hpp" - -#include <lo/lo.h> - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- - -struct OscData { - lo_address addr; - const char* path; - lo_server server; - - OscData() - : addr(nullptr), - path(nullptr), - server(nullptr) {} - - void idle() const - { - if (server == nullptr) - return; - - while (lo_server_recv_noblock(server, 0) != 0) {} - } - - void send_configure(const char* const key, const char* const value) const - { - char targetPath[std::strlen(path)+11]; - std::strcpy(targetPath, path); - std::strcat(targetPath, "/configure"); - lo_send(addr, targetPath, "ss", key, value); - } - - void send_control(const int32_t index, const float value) const - { - char targetPath[std::strlen(path)+9]; - std::strcpy(targetPath, path); - std::strcat(targetPath, "/control"); - lo_send(addr, targetPath, "if", index, value); - } - - void send_midi(uchar data[4]) const - { - char targetPath[std::strlen(path)+6]; - std::strcpy(targetPath, path); - std::strcat(targetPath, "/midi"); - lo_send(addr, targetPath, "m", data); - } - - void send_update(const char* const url) const - { - char targetPath[std::strlen(path)+8]; - std::strcpy(targetPath, path); - std::strcat(targetPath, "/update"); - lo_send(addr, targetPath, "s", url); - } - - void send_exiting() const - { - char targetPath[std::strlen(path)+9]; - std::strcpy(targetPath, path); - std::strcat(targetPath, "/exiting"); - lo_send(addr, targetPath, ""); - } -}; - -// ----------------------------------------------------------------------- - -class UIDssi -{ -public: - UIDssi(const OscData& oscData, const char* const uiTitle) - : fUI(this, 0, nullptr, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback), - fHostClosed(false), - fOscData(oscData) - { - fUI.setWindowTitle(uiTitle); - } - - ~UIDssi() - { - if (fOscData.server != nullptr && ! fHostClosed) - fOscData.send_exiting(); - } - - void exec() - { - for (;;) - { - fOscData.idle(); - - if (fHostClosed || ! fUI.idle()) - break; - - d_msleep(30); - } - } - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_STATE - void dssiui_configure(const char* key, const char* value) - { - fUI.stateChanged(key, value); - } -#endif - - void dssiui_control(ulong index, float value) - { - fUI.parameterChanged(index, value); - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - void dssiui_program(ulong bank, ulong program) - { - fUI.programChanged(bank * 128 + program); - } -#endif - - void dssiui_samplerate(const double sampleRate) - { - fUI.setSampleRate(sampleRate, true); - } - - void dssiui_show() - { - fUI.setWindowVisible(true); - } - - void dssiui_hide() - { - fUI.setWindowVisible(false); - } - - void dssiui_quit() - { - fHostClosed = true; - fUI.quit(); - } - - // ------------------------------------------------------------------- - -protected: - void setParameterValue(const uint32_t rindex, const float value) - { - if (fOscData.server == nullptr) - return; - - fOscData.send_control(rindex, value); - } - - void setState(const char* const key, const char* const value) - { - if (fOscData.server == nullptr) - return; - - fOscData.send_configure(key, value); - } - - void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity) - { - if (fOscData.server == nullptr) - return; - if (channel > 0xF) - return; - - uint8_t mdata[4] = { 0, channel, note, velocity }; - mdata[1] += (velocity != 0) ? 0x90 : 0x80; - - fOscData.send_midi(mdata); - } - - void setSize(const uint width, const uint height) - { - fUI.setWindowSize(width, height); - } - -private: - UIExporter fUI; - bool fHostClosed; - - const OscData& fOscData; - - // ------------------------------------------------------------------- - // Callbacks - - #define uiPtr ((UIDssi*)ptr) - - static void setParameterCallback(void* ptr, uint32_t rindex, float value) - { - uiPtr->setParameterValue(rindex, value); - } - - static void setStateCallback(void* ptr, const char* key, const char* value) - { - uiPtr->setState(key, value); - } - - static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) - { - uiPtr->sendNote(channel, note, velocity); - } - - static void setSizeCallback(void* ptr, uint width, uint height) - { - uiPtr->setSize(width, height); - } - - #undef uiPtr -}; - -// ----------------------------------------------------------------------- - -static OscData gOscData; -static const char* gUiTitle = nullptr; -static UIDssi* globalUI = nullptr; - -static void initUiIfNeeded() -{ - if (globalUI != nullptr) - return; - - if (d_lastUiSampleRate == 0.0) - d_lastUiSampleRate = 44100.0; - - globalUI = new UIDssi(gOscData, gUiTitle); -} - -// ----------------------------------------------------------------------- - -int osc_debug_handler(const char* path, const char*, lo_arg**, int, lo_message, void*) -{ - d_debug("osc_debug_handler(\"%s\")", path); - return 0; - -#ifndef DEBUG - // unused - (void)path; -#endif -} - -void osc_error_handler(int num, const char* msg, const char* path) -{ - d_stderr("osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path); -} - -#if DISTRHO_PLUGIN_WANT_STATE -int osc_configure_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*) -{ - const char* const key = &argv[0]->s; - const char* const value = &argv[1]->s; - d_debug("osc_configure_handler(\"%s\", \"%s\")", key, value); - - initUiIfNeeded(); - - globalUI->dssiui_configure(key, value); - - return 0; -} -#endif - -int osc_control_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*) -{ - const int32_t rindex = argv[0]->i; - const float value = argv[1]->f; - d_debug("osc_control_handler(%i, %f)", rindex, value); - - int32_t index = rindex - DISTRHO_PLUGIN_NUM_INPUTS - DISTRHO_PLUGIN_NUM_OUTPUTS; - - // latency -#if DISTRHO_PLUGIN_WANT_LATENCY - index -= 1; -#endif - - if (index < 0) - return 0; - - initUiIfNeeded(); - - globalUI->dssiui_control(index, value); - - return 0; -} - -#if DISTRHO_PLUGIN_WANT_PROGRAMS -int osc_program_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*) -{ - const int32_t bank = argv[0]->i; - const int32_t program = argv[1]->f; - d_debug("osc_program_handler(%i, %i)", bank, program); - - initUiIfNeeded(); - - globalUI->dssiui_program(bank, program); - - return 0; -} -#endif - -int osc_sample_rate_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*) -{ - const int32_t sampleRate = argv[0]->i; - d_debug("osc_sample_rate_handler(%i)", sampleRate); - - d_lastUiSampleRate = sampleRate; - - if (globalUI != nullptr) - globalUI->dssiui_samplerate(sampleRate); - - return 0; -} - -int osc_show_handler(const char*, const char*, lo_arg**, int, lo_message, void*) -{ - d_debug("osc_show_handler()"); - - initUiIfNeeded(); - - globalUI->dssiui_show(); - - return 0; -} - -int osc_hide_handler(const char*, const char*, lo_arg**, int, lo_message, void*) -{ - d_debug("osc_hide_handler()"); - - if (globalUI != nullptr) - globalUI->dssiui_hide(); - - return 0; -} - -int osc_quit_handler(const char*, const char*, lo_arg**, int, lo_message, void*) -{ - d_debug("osc_quit_handler()"); - - if (globalUI != nullptr) - globalUI->dssiui_quit(); - - return 0; -} - -END_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- - -int main(int argc, char* argv[]) -{ - USE_NAMESPACE_DISTRHO - - // dummy test mode - if (argc == 1) - { - gUiTitle = "DSSI UI Test"; - - initUiIfNeeded(); - globalUI->dssiui_show(); - globalUI->exec(); - - delete globalUI; - globalUI = nullptr; - - return 0; - } - - if (argc != 5) - { - fprintf(stderr, "Usage: %s <osc-url> <plugin-dll> <plugin-label> <instance-name>\n", argv[0]); - return 1; - } - - const char* oscUrl = argv[1]; - const char* uiTitle = argv[4]; - - char* const oscHost = lo_url_get_hostname(oscUrl); - char* const oscPort = lo_url_get_port(oscUrl); - char* const oscPath = lo_url_get_path(oscUrl); - size_t oscPathSize = strlen(oscPath); - lo_address oscAddr = lo_address_new(oscHost, oscPort); - lo_server oscServer = lo_server_new_with_proto(nullptr, LO_UDP, osc_error_handler); - - char* const oscServerPath = lo_server_get_url(oscServer); - - char pluginPath[strlen(oscServerPath)+oscPathSize]; - strcpy(pluginPath, oscServerPath); - strcat(pluginPath, oscPath+1); - -#if DISTRHO_PLUGIN_WANT_STATE - char oscPathConfigure[oscPathSize+11]; - strcpy(oscPathConfigure, oscPath); - strcat(oscPathConfigure, "/configure"); - lo_server_add_method(oscServer, oscPathConfigure, "ss", osc_configure_handler, nullptr); -#endif - - char oscPathControl[oscPathSize+9]; - strcpy(oscPathControl, oscPath); - strcat(oscPathControl, "/control"); - lo_server_add_method(oscServer, oscPathControl, "if", osc_control_handler, nullptr); - - d_stdout("oscServerPath: \"%s\"", oscServerPath); - d_stdout("pluginPath: \"%s\"", pluginPath); - d_stdout("oscPathControl: \"%s\"", oscPathControl); - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - char oscPathProgram[oscPathSize+9]; - strcpy(oscPathProgram, oscPath); - strcat(oscPathProgram, "/program"); - lo_server_add_method(oscServer, oscPathProgram, "ii", osc_program_handler, nullptr); -#endif - - char oscPathSampleRate[oscPathSize+13]; - strcpy(oscPathSampleRate, oscPath); - strcat(oscPathSampleRate, "/sample-rate"); - lo_server_add_method(oscServer, oscPathSampleRate, "i", osc_sample_rate_handler, nullptr); - - char oscPathShow[oscPathSize+6]; - strcpy(oscPathShow, oscPath); - strcat(oscPathShow, "/show"); - lo_server_add_method(oscServer, oscPathShow, "", osc_show_handler, nullptr); - - char oscPathHide[oscPathSize+6]; - strcpy(oscPathHide, oscPath); - strcat(oscPathHide, "/hide"); - lo_server_add_method(oscServer, oscPathHide, "", osc_hide_handler, nullptr); - - char oscPathQuit[oscPathSize+6]; - strcpy(oscPathQuit, oscPath); - strcat(oscPathQuit, "/quit"); - lo_server_add_method(oscServer, oscPathQuit, "", osc_quit_handler, nullptr); - - lo_server_add_method(oscServer, nullptr, nullptr, osc_debug_handler, nullptr); - - gUiTitle = uiTitle; - - gOscData.addr = oscAddr; - gOscData.path = oscPath; - gOscData.server = oscServer; - gOscData.send_update(pluginPath); - - // wait for init - for (int i=0; i < 100; ++i) - { - lo_server_recv(oscServer); - - if (d_lastUiSampleRate != 0.0 || globalUI != nullptr) - break; - - d_msleep(50); - } - - int ret = 1; - - if (d_lastUiSampleRate != 0.0 || globalUI != nullptr) - { - initUiIfNeeded(); - - globalUI->exec(); - - delete globalUI; - globalUI = nullptr; - - ret = 0; - } - -#if DISTRHO_PLUGIN_WANT_STATE - lo_server_del_method(oscServer, oscPathConfigure, "ss"); -#endif - lo_server_del_method(oscServer, oscPathControl, "if"); -#if DISTRHO_PLUGIN_WANT_PROGRAMS - lo_server_del_method(oscServer, oscPathProgram, "ii"); -#endif - lo_server_del_method(oscServer, oscPathSampleRate, "i"); - lo_server_del_method(oscServer, oscPathShow, ""); - lo_server_del_method(oscServer, oscPathHide, ""); - lo_server_del_method(oscServer, oscPathQuit, ""); - lo_server_del_method(oscServer, nullptr, nullptr); - - std::free(oscServerPath); - std::free(oscHost); - std::free(oscPort); - std::free(oscPath); - - lo_address_free(oscAddr); - lo_server_free(oscServer); - - return ret; -} diff --git a/libs/distrho/src/DistrhoUIInternal.hpp b/libs/distrho/src/DistrhoUIInternal.hpp deleted file mode 100644 index a07719c..0000000 --- a/libs/distrho/src/DistrhoUIInternal.hpp +++ /dev/null @@ -1,393 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef DISTRHO_UI_INTERNAL_HPP_INCLUDED -#define DISTRHO_UI_INTERNAL_HPP_INCLUDED - -#include "../DistrhoUI.hpp" -#include "../../dgl/App.hpp" -#include "../../dgl/Window.hpp" - -using DGL::App; -using DGL::IdleCallback; -using DGL::Window; - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- -// Static data, see DistrhoUI.cpp - -extern double d_lastUiSampleRate; -extern void* d_lastUiDspPtr; -extern Window* d_lastUiWindow; - -// ----------------------------------------------------------------------- -// UI callbacks - -typedef void (*editParamFunc) (void* ptr, uint32_t rindex, bool started); -typedef void (*setParamFunc) (void* ptr, uint32_t rindex, float value); -typedef void (*setStateFunc) (void* ptr, const char* key, const char* value); -typedef void (*sendNoteFunc) (void* ptr, uint8_t channel, uint8_t note, uint8_t velo); -typedef void (*setSizeFunc) (void* ptr, uint width, uint height); - -// ----------------------------------------------------------------------- -// UI private data - -struct UI::PrivateData { - // DSP - double sampleRate; - uint32_t parameterOffset; -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - void* dspPtr; -#endif - - // Callbacks - editParamFunc editParamCallbackFunc; - setParamFunc setParamCallbackFunc; - setStateFunc setStateCallbackFunc; - sendNoteFunc sendNoteCallbackFunc; - setSizeFunc setSizeCallbackFunc; - void* ptr; - - PrivateData() noexcept - : sampleRate(d_lastUiSampleRate), - parameterOffset(0), -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - dspPtr(d_lastUiDspPtr), -#endif - editParamCallbackFunc(nullptr), - setParamCallbackFunc(nullptr), - setStateCallbackFunc(nullptr), - sendNoteCallbackFunc(nullptr), - setSizeCallbackFunc(nullptr), - ptr(nullptr) - { - DISTRHO_SAFE_ASSERT(d_isNotZero(sampleRate)); - -#if defined(DISTRHO_PLUGIN_TARGET_DSSI) || defined(DISTRHO_PLUGIN_TARGET_LV2) - parameterOffset += DISTRHO_PLUGIN_NUM_INPUTS + DISTRHO_PLUGIN_NUM_OUTPUTS; -# if DISTRHO_PLUGIN_WANT_LATENCY - parameterOffset += 1; -# endif -#endif - -#ifdef DISTRHO_PLUGIN_TARGET_LV2 -# if (DISTRHO_PLUGIN_IS_SYNTH || DISTRHO_PLUGIN_WANT_TIMEPOS || DISTRHO_PLUGIN_WANT_STATE) - parameterOffset += 1; -# if DISTRHO_PLUGIN_WANT_STATE - parameterOffset += 1; -# endif -# endif -#endif - } - - void editParamCallback(const uint32_t rindex, const bool started) - { - if (editParamCallbackFunc != nullptr) - editParamCallbackFunc(ptr, rindex, started); - } - - void setParamCallback(const uint32_t rindex, const float value) - { - if (setParamCallbackFunc != nullptr) - setParamCallbackFunc(ptr, rindex, value); - } - - void setStateCallback(const char* const key, const char* const value) - { - if (setStateCallbackFunc != nullptr) - setStateCallbackFunc(ptr, key, value); - } - - void sendNoteCallback(const uint8_t channel, const uint8_t note, const uint8_t velocity) - { - if (sendNoteCallbackFunc != nullptr) - sendNoteCallbackFunc(ptr, channel, note, velocity); - } - - void setSizeCallback(const uint width, const uint height) - { - if (setSizeCallbackFunc != nullptr) - setSizeCallbackFunc(ptr, width, height); - } -}; - -// ----------------------------------------------------------------------- -// Plugin Window, needed to take care of resize properly - -static inline -UI* createUiWrapper(void* const dspPtr, Window* const window) -{ - d_lastUiDspPtr = dspPtr; - d_lastUiWindow = window; - UI* const ret = createUI(); - d_lastUiDspPtr = nullptr; - d_lastUiWindow = nullptr; - return ret; -} - -class UIExporterWindow : public Window -{ -public: - UIExporterWindow(App& app, const intptr_t winId, void* const dspPtr) - : Window(app, winId), - fUI(createUiWrapper(dspPtr, this)), - fIsReady(false) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - // set window size - setResizable(false); - setSize(fUI->getWidth(), fUI->getHeight()); - } - - ~UIExporterWindow() - { - delete fUI; - } - - UI* getUI() const noexcept - { - return fUI; - } - - bool isReady() const noexcept - { - return fIsReady; - } - -protected: - // custom window reshape - void onReshape(uint width, uint height) override - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - fUI->d_uiReshape(width, height); - fIsReady = true; - } - - // custom file-browser selected - void fileBrowserSelected(const char* filename) override - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - fUI->d_uiFileBrowserSelected(filename); - } - -private: - UI* const fUI; - bool fIsReady; -}; - -// ----------------------------------------------------------------------- -// UI exporter class - -class UIExporter -{ -public: - UIExporter(void* const ptr, const intptr_t winId, - const editParamFunc editParamCall, const setParamFunc setParamCall, const setStateFunc setStateCall, const sendNoteFunc sendNoteCall, const setSizeFunc setSizeCall, - void* const dspPtr = nullptr) - : glApp(), - glWindow(glApp, winId, dspPtr), - fChangingSize(false), - fUI(glWindow.getUI()), - fData((fUI != nullptr) ? fUI->pData : nullptr) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - - fData->ptr = ptr; - fData->editParamCallbackFunc = editParamCall; - fData->setParamCallbackFunc = setParamCall; - fData->setStateCallbackFunc = setStateCall; - fData->sendNoteCallbackFunc = sendNoteCall; - fData->setSizeCallbackFunc = setSizeCall; - } - - // ------------------------------------------------------------------- - - uint getWidth() const noexcept - { - return glWindow.getWidth(); - } - - uint getHeight() const noexcept - { - return glWindow.getHeight(); - } - - bool isVisible() const noexcept - { - return glWindow.isVisible(); - } - - // ------------------------------------------------------------------- - - intptr_t getWindowId() const noexcept - { - return glWindow.getWindowId(); - } - - // ------------------------------------------------------------------- - - uint32_t getParameterOffset() const noexcept - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr, 0); - - return fData->parameterOffset; - } - - // ------------------------------------------------------------------- - - void parameterChanged(const uint32_t index, const float value) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - fUI->d_parameterChanged(index, value); - } - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - void programChanged(const uint32_t index) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - fUI->d_programChanged(index); - } -#endif - -#if DISTRHO_PLUGIN_WANT_STATE - void stateChanged(const char* const key, const char* const value) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); - DISTRHO_SAFE_ASSERT_RETURN(value != nullptr,); - - fUI->d_stateChanged(key, value); - } -#endif - - // ------------------------------------------------------------------- - - void exec(IdleCallback* const cb) - { - DISTRHO_SAFE_ASSERT_RETURN(cb != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - - glWindow.addIdleCallback(cb); - glWindow.setVisible(true); - glApp.exec(); - } - - void exec_idle() - { - if (glWindow.isReady()) - fUI->d_uiIdle(); - } - - bool idle() - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr, false); - - glApp.idle(); - - if (glWindow.isReady()) - fUI->d_uiIdle(); - - return ! glApp.isQuiting(); - } - - void quit() - { - glWindow.close(); - glApp.quit(); - } - - // ------------------------------------------------------------------- - - void setWindowSize(const uint width, const uint height, const bool updateUI = false) - { - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(! fChangingSize,); - - fChangingSize = true; - - if (updateUI) - fUI->setSize(width, height); - - glWindow.setSize(width, height); - - fChangingSize = false; - } - - void setWindowTitle(const char* const uiTitle) - { - glWindow.setTitle(uiTitle); - } - - void setWindowTransientWinId(const uintptr_t winId) - { - glWindow.setTransientWinId(winId); - } - - bool setWindowVisible(const bool yesNo) - { - glWindow.setVisible(yesNo); - - return ! glApp.isQuiting(); - } - - // ------------------------------------------------------------------- - - void setSampleRate(const double sampleRate, const bool doCallback = false) - { - DISTRHO_SAFE_ASSERT_RETURN(fData != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(fUI != nullptr,); - DISTRHO_SAFE_ASSERT(sampleRate > 0.0); - - if (d_isEqual(fData->sampleRate, sampleRate)) - return; - - fData->sampleRate = sampleRate; - - if (doCallback) - fUI->d_sampleRateChanged(sampleRate); - } - -private: - // ------------------------------------------------------------------- - // DGL Application and Window for this widget - - App glApp; - UIExporterWindow glWindow; - - // prevent recursion - bool fChangingSize; - - // ------------------------------------------------------------------- - // Widget and DistrhoUI data - - UI* const fUI; - UI::PrivateData* const fData; - - DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UIExporter) -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -#endif // DISTRHO_UI_INTERNAL_HPP_INCLUDED diff --git a/libs/distrho/src/DistrhoUILV2.cpp b/libs/distrho/src/DistrhoUILV2.cpp deleted file mode 100644 index 2aa6565..0000000 --- a/libs/distrho/src/DistrhoUILV2.cpp +++ /dev/null @@ -1,536 +0,0 @@ -/* - * DISTRHO Plugin Framework (DPF) - * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> - * - * Permission to use, copy, modify, and/or distribute this software for any purpose with - * or without fee is hereby granted, provided that the above copyright notice and this - * permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD - * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN - * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL - * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER - * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include "DistrhoUIInternal.hpp" - -#include "../extra/d_string.hpp" - -#include "lv2/atom.h" -#include "lv2/atom-util.h" -#include "lv2/data-access.h" -#include "lv2/instance-access.h" -#include "lv2/options.h" -#include "lv2/ui.h" -#include "lv2/urid.h" -#include "lv2/lv2_kxstudio_properties.h" -#include "lv2/lv2_programs.h" - -START_NAMESPACE_DISTRHO - -// ----------------------------------------------------------------------- - -class UiLv2 -{ -public: - UiLv2(const intptr_t winId, - const LV2_Options_Option* options, const LV2_URID_Map* const uridMap, const LV2UI_Resize* const uiResz, const LV2UI_Touch* uiTouch, - const LV2UI_Controller controller, const LV2UI_Write_Function writeFunc, - LV2UI_Widget* const widget, void* const dspPtr) - : fUI(this, winId, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, dspPtr), - fUridMap(uridMap), - fUiResize(uiResz), - fUiTouch(uiTouch), - fController(controller), - fWriteFunction(writeFunc), - fEventTransferURID(uridMap->map(uridMap->handle, LV2_ATOM__eventTransfer)), - fKeyValueURID(uridMap->map(uridMap->handle, "urn:distrho:keyValueState")), - fWinIdWasNull(winId == 0) - { - if (fUiResize != nullptr && winId != 0) - fUiResize->ui_resize(fUiResize->handle, fUI.getWidth(), fUI.getHeight()); - - if (widget != nullptr) - *widget = (LV2UI_Widget*)fUI.getWindowId(); - -#if DISTRHO_PLUGIN_WANT_STATE - // tell the DSP we're ready to receive msgs - setState("__dpf_ui_data__", ""); -#endif - - if (winId != 0) - return; - - // if winId == 0 then options must not be null - DISTRHO_SAFE_ASSERT_RETURN(options != nullptr,); - - const LV2_URID uridWindowTitle(uridMap->map(uridMap->handle, LV2_UI__windowTitle)); - const LV2_URID uridTransientWinId(uridMap->map(uridMap->handle, LV2_KXSTUDIO_PROPERTIES__TransientWindowId)); - - bool hasTitle = false; - - for (int i=0; options[i].key != 0; ++i) - { - if (options[i].key == uridTransientWinId) - { - if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__Long)) - { - if (const int64_t transientWinId = *(const int64_t*)options[i].value) - fUI.setWindowTransientWinId(static_cast<intptr_t>(transientWinId)); - } - else - d_stderr("Host provides transientWinId but has wrong value type"); - } - else if (options[i].key == uridWindowTitle) - { - if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__String)) - { - if (const char* const windowTitle = (const char*)options[i].value) - { - hasTitle = true; - fUI.setWindowTitle(windowTitle); - } - } - else - d_stderr("Host provides windowTitle but has wrong value type"); - } - } - - if (! hasTitle) - fUI.setWindowTitle(DISTRHO_PLUGIN_NAME); - } - - // ------------------------------------------------------------------- - - void lv2ui_port_event(const uint32_t rindex, const uint32_t bufferSize, const uint32_t format, const void* const buffer) - { - if (format == 0) - { - const uint32_t parameterOffset(fUI.getParameterOffset()); - - DISTRHO_SAFE_ASSERT_RETURN(rindex >= parameterOffset,) - DISTRHO_SAFE_ASSERT_RETURN(bufferSize == sizeof(float),) - - const float value(*(const float*)buffer); - fUI.parameterChanged(rindex-parameterOffset, value); - } -#if DISTRHO_PLUGIN_WANT_STATE - else if (format == fEventTransferURID) - { - const LV2_Atom* const atom((const LV2_Atom*)buffer); - - DISTRHO_SAFE_ASSERT_RETURN(atom->type == fKeyValueURID,); - - const char* const key = (const char*)LV2_ATOM_BODY_CONST(atom); - const char* const value = key+(std::strlen(key)+1); - - fUI.stateChanged(key, value); - } -#endif - } - - // ------------------------------------------------------------------- - - int lv2ui_idle() - { - if (fWinIdWasNull) - return (fUI.idle() && fUI.isVisible()) ? 0 : 1; - - return fUI.idle() ? 0 : 1; - } - - int lv2ui_show() - { - return fUI.setWindowVisible(true) ? 0 : 1; - } - - int lv2ui_hide() - { - return fUI.setWindowVisible(false) ? 0 : 1; - } - - int lv2ui_resize(uint width, uint height) - { - fUI.setWindowSize(width, height, true); - return 0; - } - - // ------------------------------------------------------------------- - - uint32_t lv2_get_options(LV2_Options_Option* const /*options*/) - { - // currently unused - return LV2_OPTIONS_ERR_UNKNOWN; - } - - uint32_t lv2_set_options(const LV2_Options_Option* const options) - { - for (int i=0; options[i].key != 0; ++i) - { - if (options[i].key == fUridMap->map(fUridMap->handle, LV2_CORE__sampleRate)) - { - if (options[i].type == fUridMap->map(fUridMap->handle, LV2_ATOM__Double)) - { - const double sampleRate(*(const double*)options[i].value); - fUI.setSampleRate(sampleRate); - continue; - } - else - { - d_stderr("Host changed sampleRate but with wrong value type"); - continue; - } - } - } - - return LV2_OPTIONS_SUCCESS; - } - - // ------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - void lv2ui_select_program(const uint32_t bank, const uint32_t program) - { - const uint32_t realProgram(bank * 128 + program); - - fUI.programChanged(realProgram); - } -#endif - - // ------------------------------------------------------------------- - -protected: - void editParameterValue(const uint32_t rindex, const bool started) - { - if (fUiTouch != nullptr && fUiTouch->touch != nullptr) - fUiTouch->touch(fUiTouch->handle, rindex, started); - } - - void setParameterValue(const uint32_t rindex, const float value) - { - DISTRHO_SAFE_ASSERT_RETURN(fWriteFunction != nullptr,); - - fWriteFunction(fController, rindex, sizeof(float), 0, &value); - } - - void setState(const char* const key, const char* const value) - { - DISTRHO_SAFE_ASSERT_RETURN(fWriteFunction != nullptr,); - - const uint32_t eventInPortIndex(DISTRHO_PLUGIN_NUM_INPUTS + DISTRHO_PLUGIN_NUM_OUTPUTS); - - // join key and value - d_string tmpStr; - tmpStr += key; - tmpStr += "\xff"; - tmpStr += value; - - tmpStr[std::strlen(key)] = '\0'; - - // set msg size (key + separator + value + null terminator) - const size_t msgSize(tmpStr.length()+1); - - // reserve atom space - const size_t atomSize(lv2_atom_pad_size(sizeof(LV2_Atom) + msgSize)); - char atomBuf[atomSize]; - std::memset(atomBuf, 0, atomSize); - - // set atom info - LV2_Atom* const atom((LV2_Atom*)atomBuf); - atom->size = msgSize; - atom->type = fKeyValueURID; - - // set atom data - std::memcpy(atomBuf + sizeof(LV2_Atom), tmpStr.buffer(), msgSize); - - // send to DSP side - fWriteFunction(fController, eventInPortIndex, atomSize, fEventTransferURID, atom); - } - - void sendNote(const uint8_t /*channel*/, const uint8_t /*note*/, const uint8_t /*velocity*/) - { - } - - void setSize(const uint width, const uint height) - { - fUI.setWindowSize(width, height); - - if (fUiResize != nullptr && ! fWinIdWasNull) - fUiResize->ui_resize(fUiResize->handle, width, height); - } - -private: - UIExporter fUI; - - // LV2 features - const LV2_URID_Map* const fUridMap; - const LV2UI_Resize* const fUiResize; - const LV2UI_Touch* const fUiTouch; - - // LV2 UI stuff - const LV2UI_Controller fController; - const LV2UI_Write_Function fWriteFunction; - - // Need to save this - const LV2_URID fEventTransferURID; - const LV2_URID fKeyValueURID; - - // using ui:showInterface if true - bool fWinIdWasNull; - - // ------------------------------------------------------------------- - // Callbacks - - #define uiPtr ((UiLv2*)ptr) - - static void editParameterCallback(void* ptr, uint32_t rindex, bool started) - { - uiPtr->editParameterValue(rindex, started); - } - - static void setParameterCallback(void* ptr, uint32_t rindex, float value) - { - uiPtr->setParameterValue(rindex, value); - } - - static void setStateCallback(void* ptr, const char* key, const char* value) - { - uiPtr->setState(key, value); - } - - static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) - { - uiPtr->sendNote(channel, note, velocity); - } - - static void setSizeCallback(void* ptr, uint width, uint height) - { - uiPtr->setSize(width, height); - } - - #undef uiPtr -}; - -// ----------------------------------------------------------------------- - -static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char* uri, const char*, LV2UI_Write_Function writeFunction, LV2UI_Controller controller, LV2UI_Widget* widget, const LV2_Feature* const* features) -{ - if (uri == nullptr || std::strcmp(uri, DISTRHO_PLUGIN_URI) != 0) - { - d_stderr("Invalid plugin URI"); - return nullptr; - } - - const LV2_Options_Option* options = nullptr; - const LV2_URID_Map* uridMap = nullptr; - const LV2UI_Resize* uiResize = nullptr; - const LV2UI_Touch* uiTouch = nullptr; - void* parentId = nullptr; - void* instance = nullptr; - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS -# define DISTRHO_DIRECT_ACCESS_URI "urn:distrho:direct-access" - - struct LV2_DirectAccess_Interface { - void* (*get_instance_pointer)(LV2_Handle handle); - }; - const LV2_Extension_Data_Feature* extData = nullptr; -#endif - - for (int i=0; features[i] != nullptr; ++i) - { - if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) == 0) - options = (const LV2_Options_Option*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_URID__map) == 0) - uridMap = (const LV2_URID_Map*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_UI__resize) == 0) - uiResize = (const LV2UI_Resize*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_UI__parent) == 0) - parentId = features[i]->data; -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - else if (std::strcmp(features[i]->URI, LV2_DATA_ACCESS_URI) == 0) - extData = (const LV2_Extension_Data_Feature*)features[i]->data; - else if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0) - instance = features[i]->data; -#endif - } - - if (options == nullptr && parentId == nullptr) - { - d_stderr("Options feature missing (needed for show-interface), cannot continue!"); - return nullptr; - } - - if (uridMap == nullptr) - { - d_stderr("URID Map feature missing, cannot continue!"); - return nullptr; - } - - if (parentId == nullptr) - { - d_stdout("Parent Window Id missing, host should be using ui:showInterface..."); - } - -#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS - if (extData == nullptr || instance == nullptr) - { - d_stderr("Data or instance access missing, cannot continue!"); - return nullptr; - } - - if (const LV2_DirectAccess_Interface* const directAccess = (const LV2_DirectAccess_Interface*)extData->data_access(DISTRHO_DIRECT_ACCESS_URI)) - instance = directAccess->get_instance_pointer(instance); - else - instance = nullptr; - - if (instance == nullptr) - { - d_stderr("Failed to get direct access, cannot continue!"); - return nullptr; - } -#endif - - const intptr_t winId((intptr_t)parentId); - - if (options != nullptr) - { - const LV2_URID uridSampleRate(uridMap->map(uridMap->handle, LV2_CORE__sampleRate)); - - for (int i=0; options[i].key != 0; ++i) - { - if (options[i].key == uridSampleRate) - { - if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__Double)) - d_lastUiSampleRate = *(const double*)options[i].value; - else - d_stderr("Host provides sampleRate but has wrong value type"); - - break; - } - } - } - - if (d_lastUiSampleRate == 0.0) - { - d_stdout("WARNING: this host does not send sample-rate information for LV2 UIs, using 44100 as fallback (this could be wrong)"); - d_lastUiSampleRate = 44100.0; - } - - return new UiLv2(winId, options, uridMap, uiResize, uiTouch, controller, writeFunction, widget, instance); -} - -#define uiPtr ((UiLv2*)ui) - -static void lv2ui_cleanup(LV2UI_Handle ui) -{ - delete uiPtr; -} - -static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) -{ - uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer); -} - -// ----------------------------------------------------------------------- - -static int lv2ui_idle(LV2UI_Handle ui) -{ - return uiPtr->lv2ui_idle(); -} - -static int lv2ui_show(LV2UI_Handle ui) -{ - return uiPtr->lv2ui_show(); -} - -static int lv2ui_hide(LV2UI_Handle ui) -{ - return uiPtr->lv2ui_hide(); -} - -static int lv2ui_resize(LV2UI_Handle ui, int width, int height) -{ - DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr, 1); - DISTRHO_SAFE_ASSERT_RETURN(width > 0, 1); - DISTRHO_SAFE_ASSERT_RETURN(height > 0, 1); - - return 1; // This needs more testing - //return uiPtr->lv2ui_resize(width, height); -} - -// ----------------------------------------------------------------------- - -static uint32_t lv2_get_options(LV2UI_Handle ui, LV2_Options_Option* options) -{ - return uiPtr->lv2_get_options(options); -} - -static uint32_t lv2_set_options(LV2UI_Handle ui, const LV2_Options_Option* options) -{ - return uiPtr->lv2_set_options(options); -} - -// ----------------------------------------------------------------------- - -#if DISTRHO_PLUGIN_WANT_PROGRAMS -static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program) -{ - uiPtr->lv2ui_select_program(bank, program); -} -#endif - -// ----------------------------------------------------------------------- - -static const void* lv2ui_extension_data(const char* uri) -{ - static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options }; - static const LV2UI_Idle_Interface uiIdle = { lv2ui_idle }; - static const LV2UI_Show_Interface uiShow = { lv2ui_show, lv2ui_hide }; - static const LV2UI_Resize uiResz = { nullptr, lv2ui_resize }; - - if (std::strcmp(uri, LV2_OPTIONS__interface) == 0) - return &options; - if (std::strcmp(uri, LV2_UI__idleInterface) == 0) - return &uiIdle; - if (std::strcmp(uri, LV2_UI__showInterface) == 0) - return &uiShow; - if (std::strcmp(uri, LV2_UI__resize) == 0) - return &uiResz; - -#if DISTRHO_PLUGIN_WANT_PROGRAMS - static const LV2_Programs_UI_Interface uiPrograms = { lv2ui_select_program }; - - if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0) - return &uiPrograms; -#endif - - return nullptr; -} - -#undef instancePtr - -// ----------------------------------------------------------------------- - -static const LV2UI_Descriptor sLv2UiDescriptor = { - DISTRHO_UI_URI, - lv2ui_instantiate, - lv2ui_cleanup, - lv2ui_port_event, - lv2ui_extension_data -}; - -// ----------------------------------------------------------------------- - -END_NAMESPACE_DISTRHO - -DISTRHO_PLUGIN_EXPORT -const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index) -{ - USE_NAMESPACE_DISTRHO - return (index == 0) ? &sLv2UiDescriptor : nullptr; -} - -// ----------------------------------------------------------------------- diff --git a/libs/distrho/src/dssi/dssi.h b/libs/distrho/src/dssi/dssi.h deleted file mode 100644 index eca373d..0000000 --- a/libs/distrho/src/dssi/dssi.h +++ /dev/null @@ -1,441 +0,0 @@ -/* -*- c-basic-offset: 4 -*- */ - -/* dssi.h - - DSSI version 1.0 - Copyright (c) 2004, 2009 Chris Cannam, Steve Harris and Sean Bolton - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public License - as published by the Free Software Foundation; either version 2.1 of - the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02110-1301 USA -*/ - -#ifndef DSSI_INCLUDED -#define DSSI_INCLUDED - -#include <ladspa.h> -#include "seq_event-compat.h" - -#define DSSI_VERSION "1.0" -#define DSSI_VERSION_MAJOR 1 -#define DSSI_VERSION_MINOR 0 - -#ifdef __cplusplus -extern "C" { -#endif - -/* - There is a need for an API that supports hosted MIDI soft synths - with GUIs in Linux audio applications. In time the GMPI initiative - should comprehensively address this need, but the requirement for - Linux applications to be able to support simple hosted synths is - here now, and GMPI is not. This proposal (the "DSSI Soft Synth - Interface" or DSSI, pronounced "dizzy") aims to provide a simple - solution in a way that we hope will prove complete and compelling - enough to support now, yet not so compelling as to supplant GMPI or - any other comprehensive future proposal. - - For simplicity and familiarity, this API is based as far as - possible on existing work -- the LADSPA plugin API for control - values and audio processing, and the ALSA sequencer event types for - MIDI event communication. The GUI part of the proposal is quite - new, but may also be applicable retroactively to LADSPA plugins - that do not otherwise support this synth interface. -*/ - -typedef struct _DSSI_Program_Descriptor { - - /** Bank number for this program. Note that DSSI does not support - MIDI-style separation of bank LSB and MSB values. There is no - restriction on the set of available banks: the numbers do not - need to be contiguous, there does not need to be a bank 0, etc. */ - unsigned long Bank; - - /** Program number (unique within its bank) for this program. - There is no restriction on the set of available programs: the - numbers do not need to be contiguous, there does not need to - be a program 0, etc. */ - unsigned long Program; - - /** Name of the program. */ - const char * Name; - -} DSSI_Program_Descriptor; - - -typedef struct _DSSI_Descriptor { - - /** - * DSSI_API_Version - * - * This member indicates the DSSI API level used by this plugin. - * If we're lucky, this will never be needed. For now all plugins - * must set it to 1. - */ - int DSSI_API_Version; - - /** - * LADSPA_Plugin - * - * A DSSI synth plugin consists of a LADSPA plugin plus an - * additional framework for controlling program settings and - * transmitting MIDI events. A plugin must fully implement the - * LADSPA descriptor fields as well as the required LADSPA - * functions including instantiate() and (de)activate(). It - * should also implement run(), with the same behaviour as if - * run_synth() (below) were called with no synth events. - * - * In order to instantiate a synth the host calls the LADSPA - * instantiate function, passing in this LADSPA_Descriptor - * pointer. The returned LADSPA_Handle is used as the argument - * for the DSSI functions below as well as for the LADSPA ones. - */ - const LADSPA_Descriptor *LADSPA_Plugin; - - /** - * configure() - * - * This member is a function pointer that sends a piece of - * configuration data to the plugin. The key argument specifies - * some aspect of the synth's configuration that is to be changed, - * and the value argument specifies a new value for it. A plugin - * that does not require this facility at all may set this member - * to NULL. - * - * This call is intended to set some session-scoped aspect of a - * plugin's behaviour, for example to tell the plugin to load - * sample data from a particular file. The plugin should act - * immediately on the request. The call should return NULL on - * success, or an error string that may be shown to the user. The - * host will free the returned value after use if it is non-NULL. - * - * Calls to configure() are not automated as timed events. - * Instead, a host should remember the last value associated with - * each key passed to configure() during a given session for a - * given plugin instance, and should call configure() with the - * correct value for each key the next time it instantiates the - * "same" plugin instance, for example on reloading a project in - * which the plugin was used before. Plugins should note that a - * host may typically instantiate a plugin multiple times with the - * same configuration values, and should share data between - * instances where practical. - * - * Calling configure() completely invalidates the program and bank - * information last obtained from the plugin. - * - * Reserved and special key prefixes - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * The DSSI: prefix - * ---------------- - * Configure keys starting with DSSI: are reserved for particular - * purposes documented in the DSSI specification. At the moment, - * there is one such key: DSSI:PROJECT_DIRECTORY. A host may call - * configure() passing this key and a directory path value. This - * indicates to the plugin and its UI that a directory at that - * path exists and may be used for project-local data. Plugins - * may wish to use the project directory as a fallback location - * when looking for other file data, or as a base for relative - * paths in other configuration values. - * - * The GLOBAL: prefix - * ------------------ - * Configure keys starting with GLOBAL: may be used by the plugin - * and its UI for any purpose, but are treated specially by the - * host. When one of these keys is used in a configure OSC call - * from the plugin UI, the host makes the corresponding configure - * call (preserving the GLOBAL: prefix) not only to the target - * plugin but also to all other plugins in the same instance - * group, as well as their UIs. Note that if any instance - * returns non-NULL from configure to indicate error, the host - * may stop there (and the set of plugins on which configure has - * been called will thus depend on the host implementation). - * See also the configure OSC call documentation in RFC.txt. - */ - char *(*configure)(LADSPA_Handle Instance, - const char *Key, - const char *Value); - - #define DSSI_RESERVED_CONFIGURE_PREFIX "DSSI:" - #define DSSI_GLOBAL_CONFIGURE_PREFIX "GLOBAL:" - #define DSSI_PROJECT_DIRECTORY_KEY \ - DSSI_RESERVED_CONFIGURE_PREFIX "PROJECT_DIRECTORY" - - /** - * get_program() - * - * This member is a function pointer that provides a description - * of a program (named preset sound) available on this synth. A - * plugin that does not support programs at all should set this - * member to NULL. - * - * The Index argument is an index into the plugin's list of - * programs, not a program number as represented by the Program - * field of the DSSI_Program_Descriptor. (This distinction is - * needed to support synths that use non-contiguous program or - * bank numbers.) - * - * This function returns a DSSI_Program_Descriptor pointer that is - * guaranteed to be valid only until the next call to get_program, - * deactivate, or configure, on the same plugin instance. This - * function must return NULL if passed an Index argument out of - * range, so that the host can use it to query the number of - * programs as well as their properties. - */ - const DSSI_Program_Descriptor *(*get_program)(LADSPA_Handle Instance, - unsigned long Index); - - /** - * select_program() - * - * This member is a function pointer that selects a new program - * for this synth. The program change should take effect - * immediately at the start of the next run_synth() call. (This - * means that a host providing the capability of changing programs - * between any two notes on a track must vary the block size so as - * to place the program change at the right place. A host that - * wanted to avoid this would probably just instantiate a plugin - * for each program.) - * - * A plugin that does not support programs at all should set this - * member NULL. Plugins should ignore a select_program() call - * with an invalid bank or program. - * - * A plugin is not required to select any particular default - * program on activate(): it's the host's duty to set a program - * explicitly. The current program is invalidated by any call to - * configure(). - * - * A plugin is permitted to re-write the values of its input - * control ports when select_program is called. The host should - * re-read the input control port values and update its own - * records appropriately. (This is the only circumstance in - * which a DSSI plugin is allowed to modify its own input ports.) - */ - void (*select_program)(LADSPA_Handle Instance, - unsigned long Bank, - unsigned long Program); - - /** - * get_midi_controller_for_port() - * - * This member is a function pointer that returns the MIDI - * controller number or NRPN that should be mapped to the given - * input control port. If the given port should not have any MIDI - * controller mapped to it, the function should return DSSI_NONE. - * The behaviour of this function is undefined if the given port - * number does not correspond to an input control port. A plugin - * that does not want MIDI controllers mapped to ports at all may - * set this member NULL. - * - * Correct values can be got using the macros DSSI_CC(num) and - * DSSI_NRPN(num) as appropriate, and values can be combined using - * bitwise OR: e.g. DSSI_CC(23) | DSSI_NRPN(1069) means the port - * should respond to CC #23 and NRPN #1069. - * - * The host is responsible for doing proper scaling from MIDI - * controller and NRPN value ranges to port ranges according to - * the plugin's LADSPA port hints. Hosts should not deliver - * through run_synth any MIDI controller events that have already - * been mapped to control port values. - * - * A plugin should not attempt to request mappings from - * controllers 0 or 32 (MIDI Bank Select MSB and LSB). - */ - int (*get_midi_controller_for_port)(LADSPA_Handle Instance, - unsigned long Port); - - /** - * run_synth() - * - * This member is a function pointer that runs a synth for a - * block. This is identical in function to the LADSPA run() - * function, except that it also supplies events to the synth. - * - * A plugin may provide this function, run_multiple_synths() (see - * below), both, or neither (if it is not in fact a synth). A - * plugin that does not provide this function must set this member - * to NULL. Authors of synth plugins are encouraged to provide - * this function if at all possible. - * - * The Events pointer points to a block of EventCount ALSA - * sequencer events, which is used to communicate MIDI and related - * events to the synth. Each event is timestamped relative to the - * start of the block, (mis)using the ALSA "tick time" field as a - * frame count. The host is responsible for ensuring that events - * with differing timestamps are already ordered by time. - * - * See also the notes on activation, port connection etc in - * ladpsa.h, in the context of the LADSPA run() function. - * - * Note Events - * ~~~~~~~~~~~ - * There are two minor requirements aimed at making the plugin - * writer's life as simple as possible: - * - * 1. A host must never send events of type SND_SEQ_EVENT_NOTE. - * Notes should always be sent as separate SND_SEQ_EVENT_NOTE_ON - * and NOTE_OFF events. A plugin should discard any one-point - * NOTE events it sees. - * - * 2. A host must not attempt to switch notes off by sending - * zero-velocity NOTE_ON events. It should always send true - * NOTE_OFFs. It is the host's responsibility to remap events in - * cases where an external MIDI source has sent it zero-velocity - * NOTE_ONs. - * - * Bank and Program Events - * ~~~~~~~~~~~~~~~~~~~~~~~ - * Hosts must map MIDI Bank Select MSB and LSB (0 and 32) - * controllers and MIDI Program Change events onto the banks and - * programs specified by the plugin, using the DSSI select_program - * call. No host should ever deliver a program change or bank - * select controller to a plugin via run_synth. - */ - void (*run_synth)(LADSPA_Handle Instance, - unsigned long SampleCount, - snd_seq_event_t *Events, - unsigned long EventCount); - - /** - * run_synth_adding() - * - * This member is a function pointer that runs an instance of a - * synth for a block, adding its outputs to the values already - * present at the output ports. This is provided for symmetry - * with LADSPA run_adding(), and is equally optional. A plugin - * that does not provide it must set this member to NULL. - */ - void (*run_synth_adding)(LADSPA_Handle Instance, - unsigned long SampleCount, - snd_seq_event_t *Events, - unsigned long EventCount); - - /** - * run_multiple_synths() - * - * This member is a function pointer that runs multiple synth - * instances for a block. This is very similar to run_synth(), - * except that Instances, Events, and EventCounts each point to - * arrays that hold the LADSPA handles, event buffers, and - * event counts for each of InstanceCount instances. That is, - * Instances points to an array of InstanceCount pointers to - * DSSI plugin instantiations, Events points to an array of - * pointers to each instantiation's respective event list, and - * EventCounts points to an array containing each instantiation's - * respective event count. - * - * A host using this function must guarantee that ALL active - * instances of the plugin are represented in each call to the - * function -- that is, a host may not call run_multiple_synths() - * for some instances of a given plugin and then call run_synth() - * as well for others. 'All .. instances of the plugin' means - * every instance sharing the same LADSPA label and shared object - * (*.so) file (rather than every instance sharing the same *.so). - * 'Active' means any instance for which activate() has been called - * but deactivate() has not. - * - * A plugin may provide this function, run_synths() (see above), - * both, or neither (if it not in fact a synth). A plugin that - * does not provide this function must set this member to NULL. - * Plugin authors implementing run_multiple_synths are strongly - * encouraged to implement run_synth as well if at all possible, - * to aid simplistic hosts, even where it would be less efficient - * to use it. - */ - void (*run_multiple_synths)(unsigned long InstanceCount, - LADSPA_Handle *Instances, - unsigned long SampleCount, - snd_seq_event_t **Events, - unsigned long *EventCounts); - - /** - * run_multiple_synths_adding() - * - * This member is a function pointer that runs multiple synth - * instances for a block, adding each synth's outputs to the - * values already present at the output ports. This is provided - * for symmetry with both the DSSI run_multiple_synths() and LADSPA - * run_adding() functions, and is equally optional. A plugin - * that does not provide it must set this member to NULL. - */ - void (*run_multiple_synths_adding)(unsigned long InstanceCount, - LADSPA_Handle *Instances, - unsigned long SampleCount, - snd_seq_event_t **Events, - unsigned long *EventCounts); - - /** - * set_custom_data() - */ - int (*set_custom_data)(LADSPA_Handle Instance, - void *Data, - unsigned long DataLength); - - /** - * get_custom_data() - */ - int (*get_custom_data)(LADSPA_Handle Instance, - void **Data, - unsigned long *DataLength); - -} DSSI_Descriptor; - -/** - * DSSI supports a plugin discovery method similar to that of LADSPA: - * - * - DSSI hosts may wish to locate DSSI plugin shared object files by - * searching the paths contained in the DSSI_PATH and LADSPA_PATH - * environment variables, if they are present. Both are expected - * to be colon-separated lists of directories to be searched (in - * order), and DSSI_PATH should be searched first if both variables - * are set. - * - * - Each shared object file containing DSSI plugins must include a - * function dssi_descriptor(), with the following function prototype - * and C-style linkage. Hosts may enumerate the plugin types - * available in the shared object file by repeatedly calling - * this function with successive Index values (beginning from 0), - * until a return value of NULL indicates no more plugin types are - * available. Each non-NULL return is the DSSI_Descriptor - * of a distinct plugin type. - */ - -const DSSI_Descriptor *dssi_descriptor(unsigned long Index); - -typedef const DSSI_Descriptor *(*DSSI_Descriptor_Function)(unsigned long Index); - -/* - * Macros to specify particular MIDI controllers in return values from - * get_midi_controller_for_port() - */ - -#define DSSI_CC_BITS 0x20000000 -#define DSSI_NRPN_BITS 0x40000000 - -#define DSSI_NONE -1 -#define DSSI_CONTROLLER_IS_SET(n) (DSSI_NONE != (n)) - -#define DSSI_CC(n) (DSSI_CC_BITS | (n)) -#define DSSI_IS_CC(n) (DSSI_CC_BITS & (n)) -#define DSSI_CC_NUMBER(n) ((n) & 0x7f) - -#define DSSI_NRPN(n) (DSSI_NRPN_BITS | ((n) << 7)) -#define DSSI_IS_NRPN(n) (DSSI_NRPN_BITS & (n)) -#define DSSI_NRPN_NUMBER(n) (((n) >> 7) & 0x3fff) - -#ifdef __cplusplus -} -#endif - -#endif /* DSSI_INCLUDED */ diff --git a/libs/distrho/src/dssi/seq_event-compat.h b/libs/distrho/src/dssi/seq_event-compat.h deleted file mode 100644 index 6619c23..0000000 --- a/libs/distrho/src/dssi/seq_event-compat.h +++ /dev/null @@ -1,272 +0,0 @@ -/* - * This library is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ - -#ifndef __ALSA_SEQ_EVENT_COMPAT_H -#define __ALSA_SEQ_EVENT_COMPAT_H - -/** - * Sequencer event data type - */ -typedef unsigned char snd_seq_event_type_t; - -/** Sequencer event type */ -enum snd_seq_event_type { - /** system status; event data type = #snd_seq_result_t */ - SND_SEQ_EVENT_SYSTEM = 0, - /** returned result status; event data type = #snd_seq_result_t */ - SND_SEQ_EVENT_RESULT, - - /** note on and off with duration; event data type = #snd_seq_ev_note_t */ - SND_SEQ_EVENT_NOTE = 5, - /** note on; event data type = #snd_seq_ev_note_t */ - SND_SEQ_EVENT_NOTEON, - /** note off; event data type = #snd_seq_ev_note_t */ - SND_SEQ_EVENT_NOTEOFF, - /** key pressure change (aftertouch); event data type = #snd_seq_ev_note_t */ - SND_SEQ_EVENT_KEYPRESS, - - /** controller; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_CONTROLLER = 10, - /** program change; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_PGMCHANGE, - /** channel pressure; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_CHANPRESS, - /** pitchwheel; event data type = #snd_seq_ev_ctrl_t; data is from -8192 to 8191) */ - SND_SEQ_EVENT_PITCHBEND, - /** 14 bit controller value; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_CONTROL14, - /** 14 bit NRPN; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_NONREGPARAM, - /** 14 bit RPN; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_REGPARAM, - - /** SPP with LSB and MSB values; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_SONGPOS = 20, - /** Song Select with song ID number; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_SONGSEL, - /** midi time code quarter frame; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_QFRAME, - /** SMF Time Signature event; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_TIMESIGN, - /** SMF Key Signature event; event data type = #snd_seq_ev_ctrl_t */ - SND_SEQ_EVENT_KEYSIGN, - - /** MIDI Real Time Start message; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_START = 30, - /** MIDI Real Time Continue message; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_CONTINUE, - /** MIDI Real Time Stop message; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_STOP, - /** Set tick queue position; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_SETPOS_TICK, - /** Set real-time queue position; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_SETPOS_TIME, - /** (SMF) Tempo event; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_TEMPO, - /** MIDI Real Time Clock message; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_CLOCK, - /** MIDI Real Time Tick message; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_TICK, - /** Queue timer skew; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_QUEUE_SKEW, - /** Sync position changed; event data type = #snd_seq_ev_queue_control_t */ - SND_SEQ_EVENT_SYNC_POS, - - /** Tune request; event data type = none */ - SND_SEQ_EVENT_TUNE_REQUEST = 40, - /** Reset to power-on state; event data type = none */ - SND_SEQ_EVENT_RESET, - /** Active sensing event; event data type = none */ - SND_SEQ_EVENT_SENSING, - - /** Echo-back event; event data type = any type */ - SND_SEQ_EVENT_ECHO = 50, - /** OSS emulation raw event; event data type = any type */ - SND_SEQ_EVENT_OSS, - - /** New client has connected; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_CLIENT_START = 60, - /** Client has left the system; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_CLIENT_EXIT, - /** Client status/info has changed; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_CLIENT_CHANGE, - /** New port was created; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_PORT_START, - /** Port was deleted from system; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_PORT_EXIT, - /** Port status/info has changed; event data type = #snd_seq_addr_t */ - SND_SEQ_EVENT_PORT_CHANGE, - - /** Ports connected; event data type = #snd_seq_connect_t */ - SND_SEQ_EVENT_PORT_SUBSCRIBED, - /** Ports disconnected; event data type = #snd_seq_connect_t */ - SND_SEQ_EVENT_PORT_UNSUBSCRIBED, - - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR0 = 90, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR1, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR2, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR3, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR4, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR5, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR6, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR7, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR8, - /** user-defined event; event data type = any (fixed size) */ - SND_SEQ_EVENT_USR9, - - /** system exclusive data (variable length); event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_SYSEX = 130, - /** error event; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_BOUNCE, - /** reserved for user apps; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_USR_VAR0 = 135, - /** reserved for user apps; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_USR_VAR1, - /** reserved for user apps; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_USR_VAR2, - /** reserved for user apps; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_USR_VAR3, - /** reserved for user apps; event data type = #snd_seq_ev_ext_t */ - SND_SEQ_EVENT_USR_VAR4, - - /** NOP; ignored in any case */ - SND_SEQ_EVENT_NONE = 255 -}; - -/** Sequencer event address */ -typedef struct snd_seq_addr { - unsigned char client; /**< Client id */ - unsigned char port; /**< Port id */ -} snd_seq_addr_t; - -/** Connection (subscription) between ports */ -typedef struct snd_seq_connect { - snd_seq_addr_t sender; /**< sender address */ - snd_seq_addr_t dest; /**< destination address */ -} snd_seq_connect_t; - -/** Real-time data record */ -typedef struct snd_seq_real_time { - unsigned int tv_sec; /**< seconds */ - unsigned int tv_nsec; /**< nanoseconds */ -} snd_seq_real_time_t; - -/** (MIDI) Tick-time data record */ -typedef unsigned int snd_seq_tick_time_t; - -/** unioned time stamp */ -typedef union snd_seq_timestamp { - snd_seq_tick_time_t tick; /**< tick-time */ - struct snd_seq_real_time time; /**< real-time */ -} snd_seq_timestamp_t; - -/** Note event */ -typedef struct snd_seq_ev_note { - unsigned char channel; /**< channel number */ - unsigned char note; /**< note */ - unsigned char velocity; /**< velocity */ - unsigned char off_velocity; /**< note-off velocity; only for #SND_SEQ_EVENT_NOTE */ - unsigned int duration; /**< duration until note-off; only for #SND_SEQ_EVENT_NOTE */ -} snd_seq_ev_note_t; - -/** Controller event */ -typedef struct snd_seq_ev_ctrl { - unsigned char channel; /**< channel number */ - unsigned char unused[3]; /**< reserved */ - unsigned int param; /**< control parameter */ - signed int value; /**< control value */ -} snd_seq_ev_ctrl_t; - -/** generic set of bytes (12x8 bit) */ -typedef struct snd_seq_ev_raw8 { - unsigned char d[12]; /**< 8 bit value */ -} snd_seq_ev_raw8_t; - -/** generic set of integers (3x32 bit) */ -typedef struct snd_seq_ev_raw32 { - unsigned int d[3]; /**< 32 bit value */ -} snd_seq_ev_raw32_t; - -/** external stored data */ -typedef struct snd_seq_ev_ext { - unsigned int len; /**< length of data */ - void *ptr; /**< pointer to data (note: can be 64-bit) */ -} __attribute__((packed)) snd_seq_ev_ext_t; - -/** Result events */ -typedef struct snd_seq_result { - int event; /**< processed event type */ - int result; /**< status */ -} snd_seq_result_t; - -/** Queue skew values */ -typedef struct snd_seq_queue_skew { - unsigned int value; /**< skew value */ - unsigned int base; /**< skew base */ -} snd_seq_queue_skew_t; - -/** queue timer control */ -typedef struct snd_seq_ev_queue_control { - unsigned char queue; /**< affected queue */ - unsigned char unused[3]; /**< reserved */ - union { - signed int value; /**< affected value (e.g. tempo) */ - snd_seq_timestamp_t time; /**< time */ - unsigned int position; /**< sync position */ - snd_seq_queue_skew_t skew; /**< queue skew */ - unsigned int d32[2]; /**< any data */ - unsigned char d8[8]; /**< any data */ - } param; /**< data value union */ -} snd_seq_ev_queue_control_t; - -/** Sequencer event */ -typedef struct snd_seq_event { - snd_seq_event_type_t type; /**< event type */ - unsigned char flags; /**< event flags */ - unsigned char tag; /**< tag */ - - unsigned char queue; /**< schedule queue */ - snd_seq_timestamp_t time; /**< schedule time */ - - snd_seq_addr_t source; /**< source address */ - snd_seq_addr_t dest; /**< destination address */ - - union { - snd_seq_ev_note_t note; /**< note information */ - snd_seq_ev_ctrl_t control; /**< MIDI control information */ - snd_seq_ev_raw8_t raw8; /**< raw8 data */ - snd_seq_ev_raw32_t raw32; /**< raw32 data */ - snd_seq_ev_ext_t ext; /**< external data */ - snd_seq_ev_queue_control_t queue; /**< queue control */ - snd_seq_timestamp_t time; /**< timestamp */ - snd_seq_addr_t addr; /**< address */ - snd_seq_connect_t connect; /**< connect information */ - snd_seq_result_t result; /**< operation result code */ - } data; /**< event data... */ -} snd_seq_event_t; - -#endif /* __ALSA_SEQ_EVENT_COMPAT_H */ - diff --git a/libs/distrho/src/lv2/atom-forge.h b/libs/distrho/src/lv2/atom-forge.h deleted file mode 100644 index d803d23..0000000 --- a/libs/distrho/src/lv2/atom-forge.h +++ /dev/null @@ -1,747 +0,0 @@ -/* - Copyright 2008-2013 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file forge.h An API for constructing LV2 atoms. - - This file provides an API for constructing Atoms which makes it relatively - simple to build nested atoms of arbitrary complexity without requiring - dynamic memory allocation. - - The API is based on successively appending the appropriate pieces to build a - complete Atom. The size of containers is automatically updated. Functions - that begin a container return (via their frame argument) a stack frame which - must be popped when the container is finished. - - All output is written to a user-provided buffer or sink function. This - makes it popssible to create create atoms on the stack, on the heap, in LV2 - port buffers, in a ringbuffer, or elsewhere, all using the same API. - - This entire API is realtime safe if used with a buffer or a realtime safe - sink, except lv2_atom_forge_init() which is only realtime safe if the URI - map function is. - - Note these functions are all static inline, do not take their address. - - This header is non-normative, it is provided for convenience. -*/ - -#ifndef LV2_ATOM_FORGE_H -#define LV2_ATOM_FORGE_H - -#include <assert.h> - -#include "atom.h" -#include "atom-util.h" -#include "urid.h" - -#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) -# define LV2_ATOM_FORGE_DEPRECATED __attribute__((__deprecated__)) -#else -# define LV2_ATOM_FORGE_DEPRECATED -#endif - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** Handle for LV2_Atom_Forge_Sink. */ -typedef void* LV2_Atom_Forge_Sink_Handle; - -/** A reference to a chunk of written output. */ -typedef intptr_t LV2_Atom_Forge_Ref; - -/** Sink function for writing output. See lv2_atom_forge_set_sink(). */ -typedef LV2_Atom_Forge_Ref -(*LV2_Atom_Forge_Sink)(LV2_Atom_Forge_Sink_Handle handle, - const void* buf, - uint32_t size); - -/** Function for resolving a reference. See lv2_atom_forge_set_sink(). */ -typedef LV2_Atom* -(*LV2_Atom_Forge_Deref_Func)(LV2_Atom_Forge_Sink_Handle handle, - LV2_Atom_Forge_Ref ref); - -/** A stack frame used for keeping track of nested Atom containers. */ -typedef struct _LV2_Atom_Forge_Frame { - struct _LV2_Atom_Forge_Frame* parent; - LV2_Atom_Forge_Ref ref; -} LV2_Atom_Forge_Frame; - -/** A "forge" for creating atoms by appending to a buffer. */ -typedef struct { - uint8_t* buf; - uint32_t offset; - uint32_t size; - - LV2_Atom_Forge_Sink sink; - LV2_Atom_Forge_Deref_Func deref; - LV2_Atom_Forge_Sink_Handle handle; - - LV2_Atom_Forge_Frame* stack; - - LV2_URID Blank LV2_ATOM_FORGE_DEPRECATED; - LV2_URID Bool; - LV2_URID Chunk; - LV2_URID Double; - LV2_URID Float; - LV2_URID Int; - LV2_URID Long; - LV2_URID Literal; - LV2_URID Object; - LV2_URID Path; - LV2_URID Property; - LV2_URID Resource LV2_ATOM_FORGE_DEPRECATED; - LV2_URID Sequence; - LV2_URID String; - LV2_URID Tuple; - LV2_URID URI; - LV2_URID URID; - LV2_URID Vector; -} LV2_Atom_Forge; - -static inline void -lv2_atom_forge_set_buffer(LV2_Atom_Forge* forge, uint8_t* buf, size_t size); - -/** - Initialise @p forge. - - URIs will be mapped using @p map and stored, a reference to @p map itself is - not held. -*/ -static inline void -lv2_atom_forge_init(LV2_Atom_Forge* forge, LV2_URID_Map* map) -{ -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - lv2_atom_forge_set_buffer(forge, NULL, 0); - forge->Blank = map->map(map->handle, LV2_ATOM__Blank); - forge->Bool = map->map(map->handle, LV2_ATOM__Bool); - forge->Chunk = map->map(map->handle, LV2_ATOM__Chunk); - forge->Double = map->map(map->handle, LV2_ATOM__Double); - forge->Float = map->map(map->handle, LV2_ATOM__Float); - forge->Int = map->map(map->handle, LV2_ATOM__Int); - forge->Long = map->map(map->handle, LV2_ATOM__Long); - forge->Literal = map->map(map->handle, LV2_ATOM__Literal); - forge->Object = map->map(map->handle, LV2_ATOM__Object); - forge->Path = map->map(map->handle, LV2_ATOM__Path); - forge->Property = map->map(map->handle, LV2_ATOM__Property); - forge->Resource = map->map(map->handle, LV2_ATOM__Resource); - forge->Sequence = map->map(map->handle, LV2_ATOM__Sequence); - forge->String = map->map(map->handle, LV2_ATOM__String); - forge->Tuple = map->map(map->handle, LV2_ATOM__Tuple); - forge->URI = map->map(map->handle, LV2_ATOM__URI); - forge->URID = map->map(map->handle, LV2_ATOM__URID); - forge->Vector = map->map(map->handle, LV2_ATOM__Vector); -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif -} - -static inline LV2_Atom* -lv2_atom_forge_deref(LV2_Atom_Forge* forge, LV2_Atom_Forge_Ref ref) -{ - if (forge->buf) { - return (LV2_Atom*)ref; - } else { - return forge->deref(forge->handle, ref); - } -} - -/** - @name Object Stack - @{ -*/ - -/** - Push a stack frame. - This is done automatically by container functions (which take a stack frame - pointer), but may be called by the user to push the top level container when - writing to an existing Atom. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_push(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - LV2_Atom_Forge_Ref ref) -{ - frame->parent = forge->stack; - frame->ref = ref; - forge->stack = frame; - return ref; -} - -/** Pop a stack frame. This must be called when a container is finished. */ -static inline void -lv2_atom_forge_pop(LV2_Atom_Forge* forge, LV2_Atom_Forge_Frame* frame) -{ - assert(frame == forge->stack); - forge->stack = frame->parent; -} - -/** Return true iff the top of the stack has the given type. */ -static inline bool -lv2_atom_forge_top_is(LV2_Atom_Forge* forge, uint32_t type) -{ - return forge->stack && forge->stack->ref && - (lv2_atom_forge_deref(forge, forge->stack->ref)->type == type); -} - -/** Return true iff @p type is an atom:Object. */ -static inline bool -lv2_atom_forge_is_object_type(const LV2_Atom_Forge* forge, uint32_t type) -{ -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - return (type == forge->Object || - type == forge->Blank || - type == forge->Resource); -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif -} - -/** Return true iff @p type is an atom:Object with a blank ID. */ -static inline bool -lv2_atom_forge_is_blank(const LV2_Atom_Forge* forge, - uint32_t type, - const LV2_Atom_Object_Body* body) -{ -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - return (type == forge->Blank || - (type == forge->Object && body->id == 0)); -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif -} - -/** - @} - @name Output Configuration - @{ -*/ - -/** Set the output buffer where @p forge will write atoms. */ -static inline void -lv2_atom_forge_set_buffer(LV2_Atom_Forge* forge, uint8_t* buf, size_t size) -{ - forge->buf = buf; - forge->size = (uint32_t)size; - forge->offset = 0; - forge->deref = NULL; - forge->sink = NULL; - forge->handle = NULL; - forge->stack = NULL; -} - -/** - Set the sink function where @p forge will write output. - - The return value of forge functions is an LV2_Atom_Forge_Ref which is an - integer type safe to use as a pointer but is otherwise opaque. The sink - function must return a ref that can be dereferenced to access as least - sizeof(LV2_Atom) bytes of the written data, so sizes can be updated. For - ringbuffers, this should be possible as long as the size of the buffer is a - multiple of sizeof(LV2_Atom), since atoms are always aligned. - - Note that 0 is an invalid reference, so if you are using a buffer offset be - sure to offset it such that 0 is never a valid reference. You will get - confusing errors otherwise. -*/ -static inline void -lv2_atom_forge_set_sink(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Sink sink, - LV2_Atom_Forge_Deref_Func deref, - LV2_Atom_Forge_Sink_Handle handle) -{ - forge->buf = NULL; - forge->size = forge->offset = 0; - forge->deref = deref; - forge->sink = sink; - forge->handle = handle; - forge->stack = NULL; -} - -/** - @} - @name Low Level Output - @{ -*/ - -/** - Write raw output. This is used internally, but is also useful for writing - atom types not explicitly supported by the forge API. Note the caller is - responsible for ensuring the output is approriately padded. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_raw(LV2_Atom_Forge* forge, const void* data, uint32_t size) -{ - LV2_Atom_Forge_Ref out = 0; - if (forge->sink) { - out = forge->sink(forge->handle, data, size); - } else { - out = (LV2_Atom_Forge_Ref)forge->buf + (LV2_Atom_Forge_Ref)forge->offset; - uint8_t* mem = forge->buf + forge->offset; - if (forge->offset + size > forge->size) { - return 0; - } - forge->offset += size; - memcpy(mem, data, size); - } - for (LV2_Atom_Forge_Frame* f = forge->stack; f; f = f->parent) { - lv2_atom_forge_deref(forge, f->ref)->size += size; - } - return out; -} - -/** Pad output accordingly so next write is 64-bit aligned. */ -static inline void -lv2_atom_forge_pad(LV2_Atom_Forge* forge, uint32_t written) -{ - const uint64_t pad = 0; - const uint32_t pad_size = lv2_atom_pad_size(written) - written; - lv2_atom_forge_raw(forge, &pad, pad_size); -} - -/** Write raw output, padding to 64-bits as necessary. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_write(LV2_Atom_Forge* forge, const void* data, uint32_t size) -{ - LV2_Atom_Forge_Ref out = lv2_atom_forge_raw(forge, data, size); - if (out) { - lv2_atom_forge_pad(forge, size); - } - return out; -} - -/** Write a null-terminated string body. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_string_body(LV2_Atom_Forge* forge, - const char* str, - uint32_t len) -{ - LV2_Atom_Forge_Ref out = lv2_atom_forge_raw(forge, str, len); - if (out && (out = lv2_atom_forge_raw(forge, "", 1))) { - lv2_atom_forge_pad(forge, len + 1); - } - return out; -} - -/** - @} - @name Atom Output - @{ -*/ - -/** Write an atom:Atom header. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_atom(LV2_Atom_Forge* forge, uint32_t size, uint32_t type) -{ - const LV2_Atom a = { size, type }; - return lv2_atom_forge_raw(forge, &a, sizeof(a)); -} - -/** Write a primitive (fixed-size) atom. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_primitive(LV2_Atom_Forge* forge, const LV2_Atom* a) -{ - if (lv2_atom_forge_top_is(forge, forge->Vector)) { - return lv2_atom_forge_raw(forge, LV2_ATOM_BODY_CONST(a), a->size); - } else { - return lv2_atom_forge_write( - forge, a, (uint32_t)sizeof(LV2_Atom) + a->size); - } -} - -/** Write an atom:Int. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_int(LV2_Atom_Forge* forge, int32_t val) -{ - const LV2_Atom_Int a = { { sizeof(val), forge->Int }, val }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom:Long. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_long(LV2_Atom_Forge* forge, int64_t val) -{ - const LV2_Atom_Long a = { { sizeof(val), forge->Long }, val }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom:Float. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_float(LV2_Atom_Forge* forge, float val) -{ - const LV2_Atom_Float a = { { sizeof(val), forge->Float }, val }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom:Double. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_double(LV2_Atom_Forge* forge, double val) -{ - const LV2_Atom_Double a = { { sizeof(val), forge->Double }, val }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom:Bool. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_bool(LV2_Atom_Forge* forge, bool val) -{ - const LV2_Atom_Bool a = { { sizeof(int32_t), forge->Bool }, val ? 1 : 0 }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom:URID. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_urid(LV2_Atom_Forge* forge, LV2_URID id) -{ - const LV2_Atom_URID a = { { sizeof(id), forge->URID }, id }; - return lv2_atom_forge_primitive(forge, &a.atom); -} - -/** Write an atom compatible with atom:String. Used internally. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_typed_string(LV2_Atom_Forge* forge, - uint32_t type, - const char* str, - uint32_t len) -{ - const LV2_Atom_String a = { { len + 1, type } }; - LV2_Atom_Forge_Ref out = lv2_atom_forge_raw(forge, &a, sizeof(a)); - if (out) { - if (!lv2_atom_forge_string_body(forge, str, len)) { - LV2_Atom* atom = lv2_atom_forge_deref(forge, out); - atom->size = atom->type = 0; - out = 0; - } - } - return out; -} - -/** Write an atom:String. Note that @p str need not be NULL terminated. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_string(LV2_Atom_Forge* forge, const char* str, uint32_t len) -{ - return lv2_atom_forge_typed_string(forge, forge->String, str, len); -} - -/** - Write an atom:URI. Note that @p uri need not be NULL terminated. - This does not map the URI, but writes the complete URI string. To write - a mapped URI, use lv2_atom_forge_urid(). -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_uri(LV2_Atom_Forge* forge, const char* uri, uint32_t len) -{ - return lv2_atom_forge_typed_string(forge, forge->URI, uri, len); -} - -/** Write an atom:Path. Note that @p path need not be NULL terminated. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_path(LV2_Atom_Forge* forge, const char* path, uint32_t len) -{ - return lv2_atom_forge_typed_string(forge, forge->Path, path, len); -} - -/** Write an atom:Literal. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_literal(LV2_Atom_Forge* forge, - const char* str, - uint32_t len, - uint32_t datatype, - uint32_t lang) -{ - const LV2_Atom_Literal a = { - { (uint32_t)(sizeof(LV2_Atom_Literal) - sizeof(LV2_Atom) + len + 1), - forge->Literal }, - { datatype, - lang } - }; - LV2_Atom_Forge_Ref out = lv2_atom_forge_raw(forge, &a, sizeof(a)); - if (out) { - if (!lv2_atom_forge_string_body(forge, str, len)) { - LV2_Atom* atom = lv2_atom_forge_deref(forge, out); - atom->size = atom->type = 0; - out = 0; - } - } - return out; -} - -/** Start an atom:Vector. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_vector_head(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - uint32_t child_size, - uint32_t child_type) -{ - const LV2_Atom_Vector a = { - { sizeof(LV2_Atom_Vector_Body), forge->Vector }, - { child_size, child_type } - }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -} - -/** Write a complete atom:Vector. */ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_vector(LV2_Atom_Forge* forge, - uint32_t child_size, - uint32_t child_type, - uint32_t n_elems, - const void* elems) -{ - const LV2_Atom_Vector a = { - { (uint32_t)(sizeof(LV2_Atom_Vector_Body) + n_elems * child_size), - forge->Vector }, - { child_size, child_type } - }; - LV2_Atom_Forge_Ref out = lv2_atom_forge_write(forge, &a, sizeof(a)); - if (out) { - lv2_atom_forge_write(forge, elems, child_size * n_elems); - } - return out; -} - -/** - Write the header of an atom:Tuple. - - The passed frame will be initialised to represent this tuple. To complete - the tuple, write a sequence of atoms, then pop the frame with - lv2_atom_forge_pop(). - - For example: - @code - // Write tuple (1, 2.0) - LV2_Atom_Forge_Frame frame; - LV2_Atom* tup = (LV2_Atom*)lv2_atom_forge_tuple(forge, &frame); - lv2_atom_forge_int32(forge, 1); - lv2_atom_forge_float(forge, 2.0); - lv2_atom_forge_pop(forge, &frame); - @endcode -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_tuple(LV2_Atom_Forge* forge, LV2_Atom_Forge_Frame* frame) -{ - const LV2_Atom_Tuple a = { { 0, forge->Tuple } }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -} - -/** - Write the header of an atom:Object. - - The passed frame will be initialised to represent this object. To complete - the object, write a sequence of properties, then pop the frame with - lv2_atom_forge_pop(). - - For example: - @code - LV2_URID eg_Cat = map("http://example.org/Cat"); - LV2_URID eg_name = map("http://example.org/name"); - - // Start object with type eg_Cat and blank ID - LV2_Atom_Forge_Frame frame; - lv2_atom_forge_object(forge, &frame, 0, eg_Cat); - - // Append property eg:name = "Hobbes" - lv2_atom_forge_key(forge, eg_name); - lv2_atom_forge_string(forge, "Hobbes", strlen("Hobbes")); - - // Finish object - lv2_atom_forge_pop(forge, &frame); - @endcode -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_object(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - LV2_URID id, - LV2_URID otype) -{ - const LV2_Atom_Object a = { - { (uint32_t)sizeof(LV2_Atom_Object_Body), forge->Object }, - { id, otype } - }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -} - -/** - The same as lv2_atom_forge_object(), but for object:Resource. - - This function is deprecated and should not be used in new code. - Use lv2_atom_forge_object() directly instead. -*/ -LV2_ATOM_FORGE_DEPRECATED -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_resource(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - LV2_URID id, - LV2_URID otype) -{ -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - const LV2_Atom_Object a = { - { (uint32_t)sizeof(LV2_Atom_Object_Body), forge->Resource }, - { id, otype } - }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif -} - -/** - The same as lv2_atom_forge_object(), but for object:Blank. - - This function is deprecated and should not be used in new code. - Use lv2_atom_forge_object() directly instead. -*/ -LV2_ATOM_FORGE_DEPRECATED -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_blank(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - uint32_t id, - LV2_URID otype) -{ -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - const LV2_Atom_Object a = { - { (uint32_t)sizeof(LV2_Atom_Object_Body), forge->Blank }, - { id, otype } - }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -#if defined(__clang__) -# pragma clang diagnostic pop -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -# pragma GCC diagnostic pop -#endif -} - -/** - Write a property key in an Object, to be followed by the value. - - See lv2_atom_forge_object() documentation for an example. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_key(LV2_Atom_Forge* forge, - LV2_URID key) -{ - const LV2_Atom_Property_Body a = { key, 0, { 0, 0 } }; - return lv2_atom_forge_write(forge, &a, 2 * (uint32_t)sizeof(uint32_t)); -} - -/** - Write the header for a property body in an object, with context. - - If you do not need the context, which is almost certainly the case, - use the simpler lv2_atom_forge_key() instead. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_property_head(LV2_Atom_Forge* forge, - LV2_URID key, - LV2_URID context) -{ - const LV2_Atom_Property_Body a = { key, context, { 0, 0 } }; - return lv2_atom_forge_write(forge, &a, 2 * (uint32_t)sizeof(uint32_t)); -} - -/** - Write the header for a Sequence. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_sequence_head(LV2_Atom_Forge* forge, - LV2_Atom_Forge_Frame* frame, - uint32_t unit) -{ - const LV2_Atom_Sequence a = { - { (uint32_t)sizeof(LV2_Atom_Sequence_Body), forge->Sequence }, - { unit, 0 } - }; - return lv2_atom_forge_push( - forge, frame, lv2_atom_forge_write(forge, &a, sizeof(a))); -} - -/** - Write the time stamp header of an Event (in a Sequence) in audio frames. - After this, call the appropriate forge method(s) to write the body. Note - the returned reference is to an LV2_Event which is NOT an Atom. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_frame_time(LV2_Atom_Forge* forge, int64_t frames) -{ - return lv2_atom_forge_write(forge, &frames, sizeof(frames)); -} - -/** - Write the time stamp header of an Event (in a Sequence) in beats. After - this, call the appropriate forge method(s) to write the body. Note the - returned reference is to an LV2_Event which is NOT an Atom. -*/ -static inline LV2_Atom_Forge_Ref -lv2_atom_forge_beat_time(LV2_Atom_Forge* forge, double beats) -{ - return lv2_atom_forge_write(forge, &beats, sizeof(beats)); -} - -/** - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_ATOM_FORGE_H */ diff --git a/libs/distrho/src/lv2/atom-helpers.h b/libs/distrho/src/lv2/atom-helpers.h deleted file mode 100644 index 97cef2c..0000000 --- a/libs/distrho/src/lv2/atom-helpers.h +++ /dev/null @@ -1,249 +0,0 @@ -// lv2_atom_helpers.h -// -/**************************************************************************** - Copyright (C) 2005-2013, rncbc aka Rui Nuno Capela. All rights reserved. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -*****************************************************************************/ - -/* Helper functions for LV2 atom:Sequence event buffer. - * - * tentatively adapted from: - * - * - lv2_evbuf.h,c - An abstract/opaque LV2 event buffer implementation. - * - * - event-helpers.h - Helper functions for the LV2 Event extension. - * <http://lv2plug.in/ns/ext/event> - * - * Copyright 2008-2012 David Robillard <http://drobilla.net> - */ - -#ifndef LV2_ATOM_HELPERS_H -#define LV2_ATOM_HELPERS_H - -#include <stdint.h> -#include <stdbool.h> -#include <string.h> -#include <stdlib.h> -#include <assert.h> - -#include "atom-util.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// An abstract/opaque LV2 atom:Sequence buffer. -// -typedef -struct _LV2_Atom_Buffer -{ - uint32_t capacity; - uint32_t chunk_type; - uint32_t sequence_type; - LV2_Atom_Sequence atoms; - -} LV2_Atom_Buffer; - - -// Clear and initialize an existing LV2 atom:Sequenece buffer. -// -static inline -void lv2_atom_buffer_reset ( LV2_Atom_Buffer *buf, bool input ) -{ - if (input) { - buf->atoms.atom.size = sizeof(LV2_Atom_Sequence_Body); - buf->atoms.atom.type = buf->sequence_type; - } else { - buf->atoms.atom.size = buf->capacity; - buf->atoms.atom.type = buf->chunk_type; - } -} - - -// Allocate a new, empty LV2 atom:Sequence buffer. -// -static inline -LV2_Atom_Buffer *lv2_atom_buffer_new ( - uint32_t capacity, uint32_t chunk_type, uint32_t sequence_type, bool input ) -{ - LV2_Atom_Buffer *buf = (LV2_Atom_Buffer *) - malloc(sizeof(LV2_Atom_Buffer) + sizeof(LV2_Atom_Sequence) + capacity); - - buf->capacity = capacity; - buf->chunk_type = chunk_type; - buf->sequence_type = sequence_type; - - lv2_atom_buffer_reset(buf, input); - - return buf; -} - - -// Free an LV2 atom:Sequenece buffer allocated with lv2_atome_buffer_new. -// -static inline -void lv2_atom_buffer_free ( LV2_Atom_Buffer *buf ) -{ - free(buf); -} - - -// Return the total padded size of events stored in a LV2 atom:Sequence buffer. -// -static inline -uint32_t lv2_atom_buffer_get_size ( LV2_Atom_Buffer *buf ) -{ - if (buf->atoms.atom.type == buf->sequence_type) - return buf->atoms.atom.size - uint32_t(sizeof(LV2_Atom_Sequence_Body)); - else - return 0; -} - - -// Return the actual LV2 atom:Sequence implementation. -// -static inline -LV2_Atom_Sequence *lv2_atom_buffer_get_sequence ( LV2_Atom_Buffer *buf ) -{ - return &buf->atoms; -} - - -// An iterator over an atom:Sequence buffer. -// -typedef -struct _LV2_Atom_Buffer_Iterator -{ - LV2_Atom_Buffer *buf; - uint32_t offset; - -} LV2_Atom_Buffer_Iterator; - - -// Reset an iterator to point to the start of an LV2 atom:Sequence buffer. -// -static inline -bool lv2_atom_buffer_begin ( - LV2_Atom_Buffer_Iterator *iter, LV2_Atom_Buffer *buf ) -{ - iter->buf = buf; - iter->offset = 0; - - return (buf->atoms.atom.size > 0); -} - - -// Reset an iterator to point to the end of an LV2 atom:Sequence buffer. -// -static inline -bool lv2_atom_buffer_end ( - LV2_Atom_Buffer_Iterator *iter, LV2_Atom_Buffer *buf ) -{ - iter->buf = buf; - iter->offset = lv2_atom_pad_size(lv2_atom_buffer_get_size(buf)); - - return (iter->offset < buf->capacity - sizeof(LV2_Atom_Event)); -} - - -// Check if a LV2 atom:Sequenece buffer iterator is valid. -// -static inline -bool lv2_atom_buffer_is_valid ( LV2_Atom_Buffer_Iterator *iter ) -{ - return iter->offset < lv2_atom_buffer_get_size(iter->buf); -} - - -// Advance a LV2 atom:Sequenece buffer iterator forward one event. -// -static inline -bool lv2_atom_buffer_increment ( LV2_Atom_Buffer_Iterator *iter ) -{ - if (!lv2_atom_buffer_is_valid(iter)) - return false; - - LV2_Atom_Buffer *buf = iter->buf; - LV2_Atom_Sequence *atoms = &buf->atoms; - uint32_t size = ((LV2_Atom_Event *) ((char *) - LV2_ATOM_CONTENTS(LV2_Atom_Sequence, atoms) + iter->offset))->body.size; - iter->offset += lv2_atom_pad_size(uint32_t(sizeof(LV2_Atom_Event)) + size); - - return true; -} - - -// Get the event currently pointed at a LV2 atom:Sequence buffer iterator. -// -static inline -LV2_Atom_Event *lv2_atom_buffer_get ( - LV2_Atom_Buffer_Iterator *iter, uint8_t **data ) -{ - if (!lv2_atom_buffer_is_valid(iter)) - return NULL; - - LV2_Atom_Buffer *buf = iter->buf; - LV2_Atom_Sequence *atoms = &buf->atoms; - LV2_Atom_Event *ev = (LV2_Atom_Event *) ((char *) - LV2_ATOM_CONTENTS(LV2_Atom_Sequence, atoms) + iter->offset); - - *data = (uint8_t *) LV2_ATOM_BODY(&ev->body); - - return ev; -} - - -// Write an event at a LV2 atom:Sequence buffer iterator. - -static inline -bool lv2_atom_buffer_write ( - LV2_Atom_Buffer_Iterator *iter, - uint32_t frames, - uint32_t /*subframes*/, - uint32_t type, - uint32_t size, - const uint8_t *data ) -{ - LV2_Atom_Buffer *buf = iter->buf; - LV2_Atom_Sequence *atoms = &buf->atoms; - if (buf->capacity - sizeof(LV2_Atom) - atoms->atom.size - < sizeof(LV2_Atom_Event) + size) - return false; - - LV2_Atom_Event *ev = (LV2_Atom_Event*) ((char *) - LV2_ATOM_CONTENTS(LV2_Atom_Sequence, atoms) + iter->offset); - - ev->time.frames = frames; - ev->body.type = type; - ev->body.size = size; - - memcpy(LV2_ATOM_BODY(&ev->body), data, size); - - size = lv2_atom_pad_size(uint32_t(sizeof(LV2_Atom_Event)) + size); - atoms->atom.size += size; - iter->offset += size; - - return true; -} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // LV2_ATOM_HELPERS_H - -// end of lv2_atom_helpers.h diff --git a/libs/distrho/src/lv2/atom-util.h b/libs/distrho/src/lv2/atom-util.h deleted file mode 100644 index c47c0f6..0000000 --- a/libs/distrho/src/lv2/atom-util.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - Copyright 2008-2013 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file util.h Helper functions for the LV2 Atom extension. - - Note these functions are all static inline, do not take their address. - - This header is non-normative, it is provided for convenience. -*/ - -#ifndef LV2_ATOM_UTIL_H -#define LV2_ATOM_UTIL_H - -#include <stdarg.h> -#include <stdint.h> -#include <string.h> - -#include "atom.h" - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** Pad a size to 64 bits. */ -static inline uint32_t -lv2_atom_pad_size(uint32_t size) -{ - return (size + 7U) & (~7U); -} - -/** Return the total size of @p atom, including the header. */ -static inline uint32_t -lv2_atom_total_size(const LV2_Atom* atom) -{ - return (uint32_t)sizeof(LV2_Atom) + atom->size; -} - -/** Return true iff @p atom is null. */ -static inline bool -lv2_atom_is_null(const LV2_Atom* atom) -{ - return !atom || (atom->type == 0 && atom->size == 0); -} - -/** Return true iff @p a is equal to @p b. */ -static inline bool -lv2_atom_equals(const LV2_Atom* a, const LV2_Atom* b) -{ - return (a == b) || ((a->type == b->type) && - (a->size == b->size) && - !memcmp(a + 1, b + 1, a->size)); -} - -/** - @name Sequence Iterator - @{ -*/ - -/** Get an iterator pointing to the first event in a Sequence body. */ -static inline const LV2_Atom_Event* -lv2_atom_sequence_begin(const LV2_Atom_Sequence_Body* body) -{ - return (const LV2_Atom_Event*)(body + 1); -} - -/** Get an iterator pointing to the end of a Sequence body. */ -static inline LV2_Atom_Event* -lv2_atom_sequence_end(LV2_Atom_Sequence_Body* body, uint32_t size) -{ - return (LV2_Atom_Event*)((uint8_t*)body + lv2_atom_pad_size(size)); -} - -/** Return true iff @p i has reached the end of @p body. */ -static inline bool -lv2_atom_sequence_is_end(const LV2_Atom_Sequence_Body* body, - uint32_t size, - const LV2_Atom_Event* i) -{ - return (const uint8_t*)i >= ((const uint8_t*)body + size); -} - -/** Return an iterator to the element following @p i. */ -static inline const LV2_Atom_Event* -lv2_atom_sequence_next(const LV2_Atom_Event* i) -{ - return (const LV2_Atom_Event*)((const uint8_t*)i - + sizeof(LV2_Atom_Event) - + lv2_atom_pad_size(i->body.size)); -} - -/** - A macro for iterating over all events in a Sequence. - @param seq The sequence to iterate over - @param iter The name of the iterator - - This macro is used similarly to a for loop (which it expands to), e.g.: - @code - LV2_ATOM_SEQUENCE_FOREACH(sequence, ev) { - // Do something with ev (an LV2_Atom_Event*) here... - } - @endcode -*/ -#define LV2_ATOM_SEQUENCE_FOREACH(seq, iter) \ - for (const LV2_Atom_Event* (iter) = lv2_atom_sequence_begin(&(seq)->body); \ - !lv2_atom_sequence_is_end(&(seq)->body, (seq)->atom.size, (iter)); \ - (iter) = lv2_atom_sequence_next(iter)) - -/** Like LV2_ATOM_SEQUENCE_FOREACH but for a headerless sequence body. */ -#define LV2_ATOM_SEQUENCE_BODY_FOREACH(body, size, iter) \ - for (const LV2_Atom_Event* (iter) = lv2_atom_sequence_begin(body); \ - !lv2_atom_sequence_is_end(body, size, (iter)); \ - (iter) = lv2_atom_sequence_next(iter)) - -/** - @} - @name Sequence Utilities - @{ -*/ - -/** - Clear all events from @p sequence. - - This simply resets the size field, the other fields are left untouched. -*/ -static inline void -lv2_atom_sequence_clear(LV2_Atom_Sequence* seq) -{ - seq->atom.size = sizeof(LV2_Atom_Sequence_Body); -} - -/** - Append an event at the end of @p sequence. - - @param seq Sequence to append to. - @param capacity Total capacity of the sequence atom - (e.g. as set by the host for sequence output ports). - @param event Event to write. - - @return A pointer to the newly written event in @p seq, - or NULL on failure (insufficient space). -*/ -static inline LV2_Atom_Event* -lv2_atom_sequence_append_event(LV2_Atom_Sequence* seq, - uint32_t capacity, - const LV2_Atom_Event* event) -{ - const uint32_t total_size = (uint32_t)sizeof(*event) + event->body.size; - if (capacity - seq->atom.size < total_size) { - return NULL; - } - - LV2_Atom_Event* e = lv2_atom_sequence_end(&seq->body, seq->atom.size); - memcpy(e, event, total_size); - - seq->atom.size += lv2_atom_pad_size(total_size); - - return e; -} - -/** - @} - @name Tuple Iterator - @{ -*/ - -/** Get an iterator pointing to the first element in @p tup. */ -static inline const LV2_Atom* -lv2_atom_tuple_begin(const LV2_Atom_Tuple* tup) -{ - return (const LV2_Atom*)(LV2_ATOM_BODY_CONST(tup)); -} - -/** Return true iff @p i has reached the end of @p body. */ -static inline bool -lv2_atom_tuple_is_end(const void* body, uint32_t size, const LV2_Atom* i) -{ - return (const uint8_t*)i >= ((const uint8_t*)body + size); -} - -/** Return an iterator to the element following @p i. */ -static inline const LV2_Atom* -lv2_atom_tuple_next(const LV2_Atom* i) -{ - return (const LV2_Atom*)( - (const uint8_t*)i + sizeof(LV2_Atom) + lv2_atom_pad_size(i->size)); -} - -/** - A macro for iterating over all properties of a Tuple. - @param tuple The tuple to iterate over - @param iter The name of the iterator - - This macro is used similarly to a for loop (which it expands to), e.g.: - @code - LV2_ATOMO_TUPLE_FOREACH(tuple, elem) { - // Do something with elem (an LV2_Atom*) here... - } - @endcode -*/ -#define LV2_ATOM_TUPLE_FOREACH(tuple, iter) \ - for (const LV2_Atom* (iter) = lv2_atom_tuple_begin(tuple); \ - !lv2_atom_tuple_is_end(LV2_ATOM_BODY_CONST(tuple), (tuple)->size, (iter)); \ - (iter) = lv2_atom_tuple_next(iter)) - -/** Like LV2_ATOM_TUPLE_FOREACH but for a headerless tuple body. */ -#define LV2_ATOM_TUPLE_BODY_FOREACH(body, size, iter) \ - for (const LV2_Atom* (iter) = (const LV2_Atom*)body; \ - !lv2_atom_tuple_is_end(body, size, (iter)); \ - (iter) = lv2_atom_tuple_next(iter)) - -/** - @} - @name Object Iterator - @{ -*/ - -/** Return a pointer to the first property in @p body. */ -static inline const LV2_Atom_Property_Body* -lv2_atom_object_begin(const LV2_Atom_Object_Body* body) -{ - return (const LV2_Atom_Property_Body*)(body + 1); -} - -/** Return true iff @p i has reached the end of @p obj. */ -static inline bool -lv2_atom_object_is_end(const LV2_Atom_Object_Body* body, - uint32_t size, - const LV2_Atom_Property_Body* i) -{ - return (const uint8_t*)i >= ((const uint8_t*)body + size); -} - -/** Return an iterator to the property following @p i. */ -static inline const LV2_Atom_Property_Body* -lv2_atom_object_next(const LV2_Atom_Property_Body* i) -{ - const LV2_Atom* const value = (const LV2_Atom*)( - (const uint8_t*)i + 2 * sizeof(uint32_t)); - return (const LV2_Atom_Property_Body*)( - (const uint8_t*)i + lv2_atom_pad_size( - (uint32_t)sizeof(LV2_Atom_Property_Body) + value->size)); -} - -/** - A macro for iterating over all properties of an Object. - @param obj The object to iterate over - @param iter The name of the iterator - - This macro is used similarly to a for loop (which it expands to), e.g.: - @code - LV2_ATOM_OBJECT_FOREACH(object, i) { - // Do something with prop (an LV2_Atom_Property_Body*) here... - } - @endcode -*/ -#define LV2_ATOM_OBJECT_FOREACH(obj, iter) \ - for (const LV2_Atom_Property_Body* (iter) = lv2_atom_object_begin(&(obj)->body); \ - !lv2_atom_object_is_end(&(obj)->body, (obj)->atom.size, (iter)); \ - (iter) = lv2_atom_object_next(iter)) - -/** Like LV2_ATOM_OBJECT_FOREACH but for a headerless object body. */ -#define LV2_ATOM_OBJECT_BODY_FOREACH(body, size, iter) \ - for (const LV2_Atom_Property_Body* (iter) = lv2_atom_object_begin(body); \ - !lv2_atom_object_is_end(body, size, (iter)); \ - (iter) = lv2_atom_object_next(iter)) - -/** - @} - @name Object Query - @{ -*/ - -/** A single entry in an Object query. */ -typedef struct { - uint32_t key; /**< Key to query (input set by user) */ - const LV2_Atom** value; /**< Found value (output set by query function) */ -} LV2_Atom_Object_Query; - -static const LV2_Atom_Object_Query LV2_ATOM_OBJECT_QUERY_END = { 0, NULL }; - -/** - Get an object's values for various keys. - - The value pointer of each item in @p query will be set to the location of - the corresponding value in @p object. Every value pointer in @p query MUST - be initialised to NULL. This function reads @p object in a single linear - sweep. By allocating @p query on the stack, objects can be "queried" - quickly without allocating any memory. This function is realtime safe. - - This function can only do "flat" queries, it is not smart enough to match - variables in nested objects. - - For example: - @code - const LV2_Atom* name = NULL; - const LV2_Atom* age = NULL; - LV2_Atom_Object_Query q[] = { - { urids.eg_name, &name }, - { urids.eg_age, &age }, - LV2_ATOM_OBJECT_QUERY_END - }; - lv2_atom_object_query(obj, q); - // name and age are now set to the appropriate values in obj, or NULL. - @endcode -*/ -static inline int -lv2_atom_object_query(const LV2_Atom_Object* object, - LV2_Atom_Object_Query* query) -{ - int matches = 0; - int n_queries = 0; - - /* Count number of query keys so we can short-circuit when done */ - for (LV2_Atom_Object_Query* q = query; q->key; ++q) { - ++n_queries; - } - - LV2_ATOM_OBJECT_FOREACH(object, prop) { - for (LV2_Atom_Object_Query* q = query; q->key; ++q) { - if (q->key == prop->key && !*q->value) { - *q->value = &prop->value; - if (++matches == n_queries) { - return matches; - } - break; - } - } - } - return matches; -} - -/** - Body only version of lv2_atom_object_get(). -*/ -static inline int -lv2_atom_object_body_get(uint32_t size, const LV2_Atom_Object_Body* body, ...) -{ - int matches = 0; - int n_queries = 0; - - /* Count number of keys so we can short-circuit when done */ - va_list args; - va_start(args, body); - for (n_queries = 0; va_arg(args, uint32_t); ++n_queries) { - if (!va_arg(args, const LV2_Atom**)) { - return -1; - } - } - va_end(args); - - LV2_ATOM_OBJECT_BODY_FOREACH(body, size, prop) { - va_start(args, body); - for (int i = 0; i < n_queries; ++i) { - uint32_t qkey = va_arg(args, uint32_t); - const LV2_Atom** qval = va_arg(args, const LV2_Atom**); - if (qkey == prop->key && !*qval) { - *qval = &prop->value; - if (++matches == n_queries) { - return matches; - } - break; - } - } - va_end(args); - } - return matches; -} - -/** - Variable argument version of lv2_atom_object_query(). - - This is nicer-looking in code, but a bit more error-prone since it is not - type safe and the argument list must be terminated. - - The arguments should be a series of uint32_t key and const LV2_Atom** value - pairs, terminated by a zero key. The value pointers MUST be initialized to - NULL. For example: - - @code - const LV2_Atom* name = NULL; - const LV2_Atom* age = NULL; - lv2_atom_object_get(obj, - uris.name_key, &name, - uris.age_key, &age, - 0); - @endcode -*/ -static inline int -lv2_atom_object_get(const LV2_Atom_Object* object, ...) -{ - int matches = 0; - int n_queries = 0; - - /* Count number of keys so we can short-circuit when done */ - va_list args; - va_start(args, object); - for (n_queries = 0; va_arg(args, uint32_t); ++n_queries) { - if (!va_arg(args, const LV2_Atom**)) { - return -1; - } - } - va_end(args); - - LV2_ATOM_OBJECT_FOREACH(object, prop) { - va_start(args, object); - for (int i = 0; i < n_queries; ++i) { - uint32_t qkey = va_arg(args, uint32_t); - const LV2_Atom** qval = va_arg(args, const LV2_Atom**); - if (qkey == prop->key && !*qval) { - *qval = &prop->value; - if (++matches == n_queries) { - return matches; - } - break; - } - } - va_end(args); - } - return matches; -} - -/** - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_ATOM_UTIL_H */ diff --git a/libs/distrho/src/lv2/atom.h b/libs/distrho/src/lv2/atom.h deleted file mode 100644 index 91c4fa3..0000000 --- a/libs/distrho/src/lv2/atom.h +++ /dev/null @@ -1,246 +0,0 @@ -/* - Copyright 2008-2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file atom.h C header for the LV2 Atom extension - <http://lv2plug.in/ns/ext/atom>. -*/ - -#ifndef LV2_ATOM_H -#define LV2_ATOM_H - -#include <stdint.h> -#include <stddef.h> - -#define LV2_ATOM_URI "http://lv2plug.in/ns/ext/atom" -#define LV2_ATOM_PREFIX LV2_ATOM_URI "#" - -#define LV2_ATOM__Atom LV2_ATOM_PREFIX "Atom" -#define LV2_ATOM__AtomPort LV2_ATOM_PREFIX "AtomPort" -#define LV2_ATOM__Blank LV2_ATOM_PREFIX "Blank" -#define LV2_ATOM__Bool LV2_ATOM_PREFIX "Bool" -#define LV2_ATOM__Chunk LV2_ATOM_PREFIX "Chunk" -#define LV2_ATOM__Double LV2_ATOM_PREFIX "Double" -#define LV2_ATOM__Event LV2_ATOM_PREFIX "Event" -#define LV2_ATOM__Float LV2_ATOM_PREFIX "Float" -#define LV2_ATOM__Int LV2_ATOM_PREFIX "Int" -#define LV2_ATOM__Literal LV2_ATOM_PREFIX "Literal" -#define LV2_ATOM__Long LV2_ATOM_PREFIX "Long" -#define LV2_ATOM__Number LV2_ATOM_PREFIX "Number" -#define LV2_ATOM__Object LV2_ATOM_PREFIX "Object" -#define LV2_ATOM__Path LV2_ATOM_PREFIX "Path" -#define LV2_ATOM__Property LV2_ATOM_PREFIX "Property" -#define LV2_ATOM__Resource LV2_ATOM_PREFIX "Resource" -#define LV2_ATOM__Sequence LV2_ATOM_PREFIX "Sequence" -#define LV2_ATOM__Sound LV2_ATOM_PREFIX "Sound" -#define LV2_ATOM__String LV2_ATOM_PREFIX "String" -#define LV2_ATOM__Tuple LV2_ATOM_PREFIX "Tuple" -#define LV2_ATOM__URI LV2_ATOM_PREFIX "URI" -#define LV2_ATOM__URID LV2_ATOM_PREFIX "URID" -#define LV2_ATOM__Vector LV2_ATOM_PREFIX "Vector" -#define LV2_ATOM__atomTransfer LV2_ATOM_PREFIX "atomTransfer" -#define LV2_ATOM__beatTime LV2_ATOM_PREFIX "beatTime" -#define LV2_ATOM__bufferType LV2_ATOM_PREFIX "bufferType" -#define LV2_ATOM__childType LV2_ATOM_PREFIX "childType" -#define LV2_ATOM__eventTransfer LV2_ATOM_PREFIX "eventTransfer" -#define LV2_ATOM__frameTime LV2_ATOM_PREFIX "frameTime" -#define LV2_ATOM__supports LV2_ATOM_PREFIX "supports" -#define LV2_ATOM__timeUnit LV2_ATOM_PREFIX "timeUnit" - -#define LV2_ATOM_REFERENCE_TYPE 0 - -#ifdef __cplusplus -extern "C" { -#endif - -/** This expression will fail to compile if double does not fit in 64 bits. */ -typedef char lv2_atom_assert_double_fits_in_64_bits[ - ((sizeof(double) <= sizeof(uint64_t)) * 2) - 1]; - -/** - Return a pointer to the contents of an Atom. The "contents" of an atom - is the data past the complete type-specific header. - @param type The type of the atom, e.g. LV2_Atom_String. - @param atom A variable-sized atom. -*/ -#define LV2_ATOM_CONTENTS(type, atom) \ - ((uint8_t*)(atom) + sizeof(type)) - -/** - Const version of LV2_ATOM_CONTENTS. -*/ -#define LV2_ATOM_CONTENTS_CONST(type, atom) \ - ((const uint8_t*)(atom) + sizeof(type)) - -/** - Return a pointer to the body of an Atom. The "body" of an atom is the - data just past the LV2_Atom head (i.e. the same offset for all types). -*/ -#define LV2_ATOM_BODY(atom) LV2_ATOM_CONTENTS(LV2_Atom, atom) - -/** - Const version of LV2_ATOM_BODY. -*/ -#define LV2_ATOM_BODY_CONST(atom) LV2_ATOM_CONTENTS_CONST(LV2_Atom, atom) - -/** The header of an atom:Atom. */ -typedef struct { - uint32_t size; /**< Size in bytes, not including type and size. */ - uint32_t type; /**< Type of this atom (mapped URI). */ -} LV2_Atom; - -/** An atom:Int or atom:Bool. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - int32_t body; /**< Integer value. */ -} LV2_Atom_Int; - -/** An atom:Long. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - int64_t body; /**< Integer value. */ -} LV2_Atom_Long; - -/** An atom:Float. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - float body; /**< Floating point value. */ -} LV2_Atom_Float; - -/** An atom:Double. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - double body; /**< Floating point value. */ -} LV2_Atom_Double; - -/** An atom:Bool. May be cast to LV2_Atom. */ -typedef LV2_Atom_Int LV2_Atom_Bool; - -/** An atom:URID. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - uint32_t body; /**< URID. */ -} LV2_Atom_URID; - -/** An atom:String. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - /* Contents (a null-terminated UTF-8 string) follow here. */ -} LV2_Atom_String; - -/** The body of an atom:Literal. */ -typedef struct { - uint32_t datatype; /**< Datatype URID. */ - uint32_t lang; /**< Language URID. */ - /* Contents (a null-terminated UTF-8 string) follow here. */ -} LV2_Atom_Literal_Body; - -/** An atom:Literal. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - LV2_Atom_Literal_Body body; /**< Body. */ -} LV2_Atom_Literal; - -/** An atom:Tuple. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - /* Contents (a series of complete atoms) follow here. */ -} LV2_Atom_Tuple; - -/** The body of an atom:Vector. */ -typedef struct { - uint32_t child_size; /**< The size of each element in the vector. */ - uint32_t child_type; /**< The type of each element in the vector. */ - /* Contents (a series of packed atom bodies) follow here. */ -} LV2_Atom_Vector_Body; - -/** An atom:Vector. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - LV2_Atom_Vector_Body body; /**< Body. */ -} LV2_Atom_Vector; - -/** The body of an atom:Property (e.g. in an atom:Object). */ -typedef struct { - uint32_t key; /**< Key (predicate) (mapped URI). */ - uint32_t context; /**< Context URID (may be, and generally is, 0). */ - LV2_Atom value; /**< Value atom header. */ - /* Value atom body follows here. */ -} LV2_Atom_Property_Body; - -/** An atom:Property. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - LV2_Atom_Property_Body body; /**< Body. */ -} LV2_Atom_Property; - -/** The body of an atom:Object. May be cast to LV2_Atom. */ -typedef struct { - uint32_t id; /**< URID, or 0 for blank. */ - uint32_t otype; /**< Type URID (same as rdf:type, for fast dispatch). */ - /* Contents (a series of property bodies) follow here. */ -} LV2_Atom_Object_Body; - -/** An atom:Object. May be cast to LV2_Atom. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - LV2_Atom_Object_Body body; /**< Body. */ -} LV2_Atom_Object; - -/** The header of an atom:Event. Note this type is NOT an LV2_Atom. */ -typedef struct { - /** Time stamp. Which type is valid is determined by context. */ - union { - int64_t frames; /**< Time in audio frames. */ - double beats; /**< Time in beats. */ - } time; - LV2_Atom body; /**< Event body atom header. */ - /* Body atom contents follow here. */ -} LV2_Atom_Event; - -/** - The body of an atom:Sequence (a sequence of events). - - The unit field is either a URID that described an appropriate time stamp - type, or may be 0 where a default stamp type is known. For - LV2_Descriptor::run(), the default stamp type is audio frames. - - The contents of a sequence is a series of LV2_Atom_Event, each aligned - to 64-bits, e.g.: - <pre> - | Event 1 (size 6) | Event 2 - | | | | | | | | | - | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | - |FRAMES |SUBFRMS|TYPE |SIZE |DATADATADATAPAD|FRAMES |SUBFRMS|... - </pre> -*/ -typedef struct { - uint32_t unit; /**< URID of unit of event time stamps. */ - uint32_t pad; /**< Currently unused. */ - /* Contents (a series of events) follow here. */ -} LV2_Atom_Sequence_Body; - -/** An atom:Sequence. */ -typedef struct { - LV2_Atom atom; /**< Atom header. */ - LV2_Atom_Sequence_Body body; /**< Body. */ -} LV2_Atom_Sequence; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_ATOM_H */ diff --git a/libs/distrho/src/lv2/buf-size.h b/libs/distrho/src/lv2/buf-size.h deleted file mode 100644 index 20cd8fd..0000000 --- a/libs/distrho/src/lv2/buf-size.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright 2007-2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_BUF_SIZE_H -#define LV2_BUF_SIZE_H - -#define LV2_BUF_SIZE_URI "http://lv2plug.in/ns/ext/buf-size" -#define LV2_BUF_SIZE_PREFIX LV2_BUF_SIZE_URI "#" - -#define LV2_BUF_SIZE__boundedBlockLength LV2_BUF_SIZE_PREFIX "boundedBlockLength" -#define LV2_BUF_SIZE__fixedBlockLength LV2_BUF_SIZE_PREFIX "fixedBlockLength" -#define LV2_BUF_SIZE__maxBlockLength LV2_BUF_SIZE_PREFIX "maxBlockLength" -#define LV2_BUF_SIZE__minBlockLength LV2_BUF_SIZE_PREFIX "minBlockLength" -#define LV2_BUF_SIZE__powerOf2BlockLength LV2_BUF_SIZE_PREFIX "powerOf2BlockLength" -#define LV2_BUF_SIZE__sequenceSize LV2_BUF_SIZE_PREFIX "sequenceSize" - -#endif /* LV2_BUF_SIZE_H */ diff --git a/libs/distrho/src/lv2/data-access.h b/libs/distrho/src/lv2/data-access.h deleted file mode 100644 index 68aaf62..0000000 --- a/libs/distrho/src/lv2/data-access.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - LV2 Data Access Extension - Copyright 2008-2011 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file data-access.h - C header for the LV2 Extension Data extension - <http://lv2plug.in/ns/ext/data-access>. - - This extension defines a method for (e.g.) plugin UIs to have (possibly - marshalled) access to the extension_data function on a plugin instance. -*/ - -#ifndef LV2_DATA_ACCESS_H -#define LV2_DATA_ACCESS_H - -#define LV2_DATA_ACCESS_URI "http://lv2plug.in/ns/ext/data-access" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - The data field of the LV2_Feature for this extension. - - To support this feature the host must pass an LV2_Feature struct to the - instantiate method with URI "http://lv2plug.in/ns/ext/data-access" - and data pointed to an instance of this struct. -*/ -typedef struct { - /** - A pointer to a method the UI can call to get data (of a type specified - by some other extension) from the plugin. - - This call never is never guaranteed to return anything, UIs should - degrade gracefully if direct access to the plugin data is not possible - (in which case this function will return NULL). - - This is for access to large data that can only possibly work if the UI - and plugin are running in the same process. For all other things, use - the normal LV2 UI communication system. - */ - const void* (*data_access)(const char* uri); -} LV2_Extension_Data_Feature; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_DATA_ACCESS_H */ diff --git a/libs/distrho/src/lv2/dynmanifest.h b/libs/distrho/src/lv2/dynmanifest.h deleted file mode 100644 index fad33c8..0000000 --- a/libs/distrho/src/lv2/dynmanifest.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - Dynamic manifest specification for LV2 - Copyright 2008-2011 Stefano D'Angelo <zanga.mail@gmail.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file dynmanifest.h - C header for the LV2 Dynamic Manifest extension - <http://lv2plug.in/ns/ext/dynmanifest>. - Revision: 1.2 -*/ - -#ifndef LV2_DYN_MANIFEST_H_INCLUDED -#define LV2_DYN_MANIFEST_H_INCLUDED - -#include <stdio.h> - -#include "lv2.h" - -#define LV2_DYN_MANIFEST_URI "http://lv2plug.in/ns/ext/dynmanifest" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Dynamic manifest generator handle. - - This handle indicates a particular status of a dynamic manifest generator. - The host MUST NOT attempt to interpret it and, unlikely LV2_Handle, it is - NOT even valid to compare this to NULL. The dynamic manifest generator MAY - use it to reference internal data. -*/ -typedef void * LV2_Dyn_Manifest_Handle; - -/** - Generate the dynamic manifest. - - @param handle Pointer to an uninitialized dynamic manifest generator handle. - - @param features NULL terminated array of LV2_Feature structs which represent - the features the host supports. The dynamic manifest generator may refuse to - (re)generate the dynamic manifest if required features are not found here - (however hosts SHOULD NOT use this as a discovery mechanism, instead of - reading the static manifest file). This array must always exist; if a host - has no features, it MUST pass a single element array containing NULL. - - @return 0 on success, otherwise a non-zero error code. The host SHOULD - evaluate the result of the operation by examining the returned value and - MUST NOT try to interpret the value of handle. -*/ -int lv2_dyn_manifest_open(LV2_Dyn_Manifest_Handle * handle, - const LV2_Feature *const * features); - -/** - Fetch a "list" of subject URIs described in the dynamic manifest. - - The dynamic manifest generator has to fill the resource only with the needed - triples to make the host aware of the "objects" it wants to expose. For - example, if the plugin library exposes a regular LV2 plugin, it should - output only a triple like the following: - - <http://www.example.com/plugin/uri> a lv2:Plugin . - - The objects that are elegible for exposure are those that would need to be - represented by a subject node in a static manifest. - - @param handle Dynamic manifest generator handle. - - @param fp FILE * identifying the resource the host has to set up for the - dynamic manifest generator. The host MUST pass a writable, empty resource to - this function, and the dynamic manifest generator MUST ONLY perform write - operations on it at the end of the stream (e.g., using only fprintf(), - fwrite() and similar). - - @return 0 on success, otherwise a non-zero error code. -*/ -int lv2_dyn_manifest_get_subjects(LV2_Dyn_Manifest_Handle handle, - FILE * fp); - -/** - Function that fetches data related to a specific URI. - - The dynamic manifest generator has to fill the resource with data related to - object represented by the given URI. For example, if the library exposes a - regular LV2 plugin whose URI, as retrieved by the host using - lv2_dyn_manifest_get_subjects() is http://www.example.com/plugin/uri, it - should output something like: - - <pre> - <http://www.example.com/plugin/uri> - a lv2:Plugin ; - doap:name "My Plugin" ; - lv2:binary <mylib.so> ; - etc:etc "..." . - </pre> - - @param handle Dynamic manifest generator handle. - - @param fp FILE * identifying the resource the host has to set up for the - dynamic manifest generator. The host MUST pass a writable resource to this - function, and the dynamic manifest generator MUST ONLY perform write - operations on it at the current position of the stream (e.g. using only - fprintf(), fwrite() and similar). - - @param uri URI to get data about (in the "plain" form, i.e., absolute URI - without Turtle prefixes). - - @return 0 on success, otherwise a non-zero error code. -*/ -int lv2_dyn_manifest_get_data(LV2_Dyn_Manifest_Handle handle, - FILE * fp, - const char * uri); - -/** - Function that ends the operations on the dynamic manifest generator. - - This function SHOULD be used by the dynamic manifest generator to perform - cleanup operations, etc. - - Once this function is called, referring to handle will cause undefined - behavior. - - @param handle Dynamic manifest generator handle. -*/ -void lv2_dyn_manifest_close(LV2_Dyn_Manifest_Handle handle); - -#ifdef __cplusplus -} -#endif - -#endif /* LV2_DYN_MANIFEST_H_INCLUDED */ diff --git a/libs/distrho/src/lv2/event-helpers.h b/libs/distrho/src/lv2/event-helpers.h deleted file mode 100644 index 5caaab5..0000000 --- a/libs/distrho/src/lv2/event-helpers.h +++ /dev/null @@ -1,266 +0,0 @@ -/* - Copyright 2008-2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file event-helpers.h Helper functions for the LV2 Event extension - <http://lv2plug.in/ns/ext/event>. -*/ - -#ifndef LV2_EVENT_HELPERS_H -#define LV2_EVENT_HELPERS_H - -#include <stdint.h> -#include <stdlib.h> -#include <string.h> - -#include "event.h" - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** @file - * Helper functions for the LV2 Event extension - * <http://lv2plug.in/ns/ext/event>. - * - * These functions are provided for convenience only, use of them is not - * required for supporting lv2ev (i.e. the events extension is defined by the - * raw buffer format described in lv2_event.h and NOT by this API). - * - * Note that these functions are all static inline which basically means: - * do not take the address of these functions. */ - - -/** Pad a size to 64 bits (for event sizes) */ -static inline uint16_t -lv2_event_pad_size(uint16_t size) -{ - return (uint16_t)(size + 7U) & (uint16_t)(~7U); -} - - -/** Initialize (empty, reset..) an existing event buffer. - * The contents of buf are ignored entirely and overwritten, except capacity - * which is unmodified. */ -static inline void -lv2_event_buffer_reset(LV2_Event_Buffer* buf, - uint16_t stamp_type, - uint8_t* data) -{ - buf->data = data; - buf->header_size = sizeof(LV2_Event_Buffer); - buf->stamp_type = stamp_type; - buf->event_count = 0; - buf->size = 0; -} - - -/** Allocate a new, empty event buffer. */ -static inline LV2_Event_Buffer* -lv2_event_buffer_new(uint32_t capacity, uint16_t stamp_type) -{ - const size_t size = sizeof(LV2_Event_Buffer) + capacity; - LV2_Event_Buffer* buf = (LV2_Event_Buffer*)malloc(size); - if (buf != NULL) { - buf->capacity = capacity; - lv2_event_buffer_reset(buf, stamp_type, (uint8_t *)(buf + 1)); - return buf; - } else { - return NULL; - } -} - - -/** An iterator over an LV2_Event_Buffer. - * - * Multiple simultaneous read iterators over a single buffer is fine, - * but changing the buffer invalidates all iterators (e.g. RW Lock). */ -typedef struct { - LV2_Event_Buffer* buf; - uint32_t offset; -} LV2_Event_Iterator; - - -/** Reset an iterator to point to the start of @a buf. - * @return True if @a iter is valid, otherwise false (buffer is empty) */ -static inline bool -lv2_event_begin(LV2_Event_Iterator* iter, - LV2_Event_Buffer* buf) -{ - iter->buf = buf; - iter->offset = 0; - return (buf->size > 0); -} - - -/** Check if @a iter is valid. - * @return True if @a iter is valid, otherwise false (past end of buffer) */ -static inline bool -lv2_event_is_valid(LV2_Event_Iterator* iter) -{ - return (iter->buf && (iter->offset < iter->buf->size)); -} - - -/** Advance @a iter forward one event. - * @a iter must be valid. - * @return True if @a iter is valid, otherwise false (reached end of buffer) */ -static inline bool -lv2_event_increment(LV2_Event_Iterator* iter) -{ - if (!lv2_event_is_valid(iter)) { - return false; - } - - LV2_Event* const ev = (LV2_Event*)( - (uint8_t*)iter->buf->data + iter->offset); - - iter->offset += lv2_event_pad_size( - (uint16_t)((uint16_t)sizeof(LV2_Event) + ev->size)); - - return true; -} - - -/** Dereference an event iterator (get the event currently pointed at). - * @a iter must be valid. - * @a data if non-NULL, will be set to point to the contents of the event - * returned. - * @return A Pointer to the event @a iter is currently pointing at, or NULL - * if the end of the buffer is reached (in which case @a data is - * also set to NULL). */ -static inline LV2_Event* -lv2_event_get(LV2_Event_Iterator* iter, - uint8_t** data) -{ - if (!lv2_event_is_valid(iter)) { - return NULL; - } - - LV2_Event* const ev = (LV2_Event*)( - (uint8_t*)iter->buf->data + iter->offset); - - if (data) - *data = (uint8_t*)ev + sizeof(LV2_Event); - - return ev; -} - - -/** Write an event at @a iter. - * The event (if any) pointed to by @a iter will be overwritten, and @a iter - * incremented to point to the following event (i.e. several calls to this - * function can be done in sequence without twiddling iter in-between). - * @return True if event was written, otherwise false (buffer is full). */ -static inline bool -lv2_event_write(LV2_Event_Iterator* iter, - uint32_t frames, - uint32_t subframes, - uint16_t type, - uint16_t size, - const uint8_t* data) -{ - if (!iter->buf) - return false; - - if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + size) - return false; - - LV2_Event* const ev = (LV2_Event*)( - (uint8_t*)iter->buf->data + iter->offset); - - ev->frames = frames; - ev->subframes = subframes; - ev->type = type; - ev->size = size; - memcpy((uint8_t*)ev + sizeof(LV2_Event), data, size); - ++iter->buf->event_count; - - size = lv2_event_pad_size((uint16_t)(sizeof(LV2_Event) + size)); - iter->buf->size += size; - iter->offset += size; - - return true; -} - - -/** Reserve space for an event in the buffer and return a pointer to - the memory where the caller can write the event data, or NULL if there - is not enough room in the buffer. */ -static inline uint8_t* -lv2_event_reserve(LV2_Event_Iterator* iter, - uint32_t frames, - uint32_t subframes, - uint16_t type, - uint16_t size) -{ - const uint16_t total_size = (uint16_t)(sizeof(LV2_Event) + size); - if (iter->buf->capacity - iter->buf->size < total_size) - return NULL; - - LV2_Event* const ev = (LV2_Event*)( - (uint8_t*)iter->buf->data + iter->offset); - - ev->frames = frames; - ev->subframes = subframes; - ev->type = type; - ev->size = size; - ++iter->buf->event_count; - - const uint16_t padded_size = lv2_event_pad_size(total_size); - iter->buf->size += padded_size; - iter->offset += padded_size; - - return (uint8_t*)ev + sizeof(LV2_Event); -} - - -/** Write an event at @a iter. - * The event (if any) pointed to by @a iter will be overwritten, and @a iter - * incremented to point to the following event (i.e. several calls to this - * function can be done in sequence without twiddling iter in-between). - * @return True if event was written, otherwise false (buffer is full). */ -static inline bool -lv2_event_write_event(LV2_Event_Iterator* iter, - const LV2_Event* ev, - const uint8_t* data) -{ - const uint16_t total_size = (uint16_t)(sizeof(LV2_Event) + ev->size); - if (iter->buf->capacity - iter->buf->size < total_size) - return false; - - LV2_Event* const write_ev = (LV2_Event*)( - (uint8_t*)iter->buf->data + iter->offset); - - *write_ev = *ev; - memcpy((uint8_t*)write_ev + sizeof(LV2_Event), data, ev->size); - ++iter->buf->event_count; - - const uint16_t padded_size = lv2_event_pad_size(total_size); - iter->buf->size += padded_size; - iter->offset += padded_size; - - return true; -} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_EVENT_HELPERS_H */ - diff --git a/libs/distrho/src/lv2/event.h b/libs/distrho/src/lv2/event.h deleted file mode 100644 index e33d862..0000000 --- a/libs/distrho/src/lv2/event.h +++ /dev/null @@ -1,294 +0,0 @@ -/* - Copyright 2008-2011 David Robillard <http://drobilla.net> - Copyright 2006-2007 Lars Luthman <lars.luthman@gmail.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file event.h - C API for the LV2 Event extension <http://lv2plug.in/ns/ext/event>. - - This extension is a generic transport mechanism for time stamped events - of any type (e.g. MIDI, OSC, ramps, etc). Each port can transport mixed - events of any type; the type of events and timestamps are defined by a URI - which is mapped to an integer by the host for performance reasons. - - This extension requires the host to support the LV2 URI Map extension. - Any host which supports this extension MUST guarantee that any call to - the LV2 URI Map uri_to_id function with the URI of this extension as the - 'map' argument returns a value within the range of uint16_t. -*/ - -#ifndef LV2_EVENT_H -#define LV2_EVENT_H - -#define LV2_EVENT_URI "http://lv2plug.in/ns/ext/event" -#define LV2_EVENT_PREFIX LV2_EVENT_URI "#" - -#define LV2_EVENT__Event LV2_EVENT_PREFIX "Event" -#define LV2_EVENT__EventPort LV2_EVENT_PREFIX "EventPort" -#define LV2_EVENT__FrameStamp LV2_EVENT_PREFIX "FrameStamp" -#define LV2_EVENT__TimeStamp LV2_EVENT_PREFIX "TimeStamp" -#define LV2_EVENT__generatesTimeStamp LV2_EVENT_PREFIX "generatesTimeStamp" -#define LV2_EVENT__generic LV2_EVENT_PREFIX "generic" -#define LV2_EVENT__inheritsEvent LV2_EVENT_PREFIX "inheritsEvent" -#define LV2_EVENT__inheritsTimeStamp LV2_EVENT_PREFIX "inheritsTimeStamp" -#define LV2_EVENT__supportsEvent LV2_EVENT_PREFIX "supportsEvent" -#define LV2_EVENT__supportsTimeStamp LV2_EVENT_PREFIX "supportsTimeStamp" - -#define LV2_EVENT_AUDIO_STAMP 0 - -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - The best Pulses Per Quarter Note for tempo-based uint32_t timestamps. - Equal to 2^12 * 5 * 7 * 9 * 11 * 13 * 17, which is evenly divisble - by all integers from 1 through 18 inclusive, and powers of 2 up to 2^12. -*/ -static const uint32_t LV2_EVENT_PPQN = 3136573440U; - -/** - An LV2 event (header only). - - LV2 events are generic time-stamped containers for any type of event. - The type field defines the format of a given event's contents. - - This struct defines the header of an LV2 event. An LV2 event is a single - chunk of POD (plain old data), usually contained in a flat buffer (see - LV2_EventBuffer below). Unless a required feature says otherwise, hosts may - assume a deep copy of an LV2 event can be created safely using a simple: - - memcpy(ev_copy, ev, sizeof(LV2_Event) + ev->size); (or equivalent) -*/ -typedef struct { - /** - The frames portion of timestamp. The units used here can optionally be - set for a port (with the lv2ev:timeUnits property), otherwise this is - audio frames, corresponding to the sample_count parameter of the LV2 run - method (e.g. frame 0 is the first frame for that call to run). - */ - uint32_t frames; - - /** - The sub-frames portion of timestamp. The units used here can optionally - be set for a port (with the lv2ev:timeUnits property), otherwise this is - 1/(2^32) of an audio frame. - */ - uint32_t subframes; - - /** - The type of this event, as a number which represents some URI - defining an event type. This value MUST be some value previously - returned from a call to the uri_to_id function defined in the LV2 - URI map extension (see lv2_uri_map.h). - There are special rules which must be followed depending on the type - of an event. If the plugin recognizes an event type, the definition - of that event type will describe how to interpret the event, and - any required behaviour. Otherwise, if the type is 0, this event is a - non-POD event and lv2_event_unref MUST be called if the event is - 'dropped' (see above). Even if the plugin does not understand an event, - it may pass the event through to an output by simply copying (and NOT - calling lv2_event_unref). These rules are designed to allow for generic - event handling plugins and large non-POD events, but with minimal hassle - on simple plugins that "don't care" about these more advanced features. - */ - uint16_t type; - - /** - The size of the data portion of this event in bytes, which immediately - follows. The header size (12 bytes) is not included in this value. - */ - uint16_t size; - - /* size bytes of data follow here */ -} LV2_Event; - - -/** - A buffer of LV2 events (header only). - - Like events (which this contains) an event buffer is a single chunk of POD: - the entire buffer (including contents) can be copied with a single memcpy. - The first contained event begins sizeof(LV2_EventBuffer) bytes after the - start of this struct. - - After this header, the buffer contains an event header (defined by struct - LV2_Event), followed by that event's contents (padded to 64 bits), followed - by another header, etc: - - | | | | | | | - | | | | | | | | | | | | | | | | | | | | | | | | | - |FRAMES |SUBFRMS|TYP|LEN|DATA..DATA..PAD|FRAMES | ... -*/ -typedef struct { - /** - The contents of the event buffer. This may or may not reside in the - same block of memory as this header, plugins must not assume either. - The host guarantees this points to at least capacity bytes of allocated - memory (though only size bytes of that are valid events). - */ - uint8_t* data; - - /** - The size of this event header in bytes (including everything). - - This is to allow for extending this header in the future without - breaking binary compatibility. Whenever this header is copied, - it MUST be done using this field (and NOT the sizeof this struct). - */ - uint16_t header_size; - - /** - The type of the time stamps for events in this buffer. - As a special exception, '0' always means audio frames and subframes - (1/UINT32_MAX'th of a frame) in the sample rate passed to instantiate. - - INPUTS: The host must set this field to the numeric ID of some URI - defining the meaning of the frames/subframes fields of contained events - (obtained by the LV2 URI Map uri_to_id function with the URI of this - extension as the 'map' argument, see lv2_uri_map.h). The host must - never pass a plugin a buffer which uses a stamp type the plugin does not - 'understand'. The value of this field must never change, except when - connect_port is called on the input port, at which time the host MUST - have set the stamp_type field to the value that will be used for all - subsequent run calls. - - OUTPUTS: The plugin may set this to any value that has been returned - from uri_to_id with the URI of this extension for a 'map' argument. - When connected to a buffer with connect_port, output ports MUST set this - field to the type of time stamp they will be writing. On any call to - connect_port on an event input port, the plugin may change this field on - any output port, it is the responsibility of the host to check if any of - these values have changed and act accordingly. - */ - uint16_t stamp_type; - - /** - The number of events in this buffer. - - INPUTS: The host must set this field to the number of events contained - in the data buffer before calling run(). The plugin must not change - this field. - - OUTPUTS: The plugin must set this field to the number of events it has - written to the buffer before returning from run(). Any initial value - should be ignored by the plugin. - */ - uint32_t event_count; - - /** - The size of the data buffer in bytes. - This is set by the host and must not be changed by the plugin. - The host is allowed to change this between run() calls. - */ - uint32_t capacity; - - /** - The size of the initial portion of the data buffer containing data. - - INPUTS: The host must set this field to the number of bytes used - by all events it has written to the buffer (including headers) - before calling the plugin's run(). - The plugin must not change this field. - - OUTPUTS: The plugin must set this field to the number of bytes - used by all events it has written to the buffer (including headers) - before returning from run(). - Any initial value should be ignored by the plugin. - */ - uint32_t size; -} LV2_Event_Buffer; - - -/** - Opaque pointer to host data. -*/ -typedef void* LV2_Event_Callback_Data; - - -/** - Non-POD events feature. - - To support this feature the host must pass an LV2_Feature struct to the - plugin's instantiate method with URI "http://lv2plug.in/ns/ext/event" - and data pointed to an instance of this struct. Note this feature - is not mandatory to support the event extension. -*/ -typedef struct { - /** - Opaque pointer to host data. - - The plugin MUST pass this to any call to functions in this struct. - Otherwise, it must not be interpreted in any way. - */ - LV2_Event_Callback_Data callback_data; - - /** - Take a reference to a non-POD event. - - If a plugin receives an event with type 0, it means the event is a - pointer to some object in memory and not a flat sequence of bytes - in the buffer. When receiving a non-POD event, the plugin already - has an implicit reference to the event. If the event is stored AND - passed to an output, lv2_event_ref MUST be called on that event. - If the event is only stored OR passed through, this is not necessary - (as the plugin already has 1 implicit reference). - - @param event An event received at an input that will not be copied to - an output or stored in any way. - - @param context The calling context. Like event types, this is a mapped - URI, see lv2_context.h. Simple plugin with just a run() method should - pass 0 here (the ID of the 'standard' LV2 run context). The host - guarantees that this function is realtime safe iff @a context is - realtime safe. - - PLUGINS THAT VIOLATE THESE RULES MAY CAUSE CRASHES AND MEMORY LEAKS. - */ - uint32_t (*lv2_event_ref)(LV2_Event_Callback_Data callback_data, - LV2_Event* event); - - /** - Drop a reference to a non-POD event. - - If a plugin receives an event with type 0, it means the event is a - pointer to some object in memory and not a flat sequence of bytes - in the buffer. If the plugin does not pass the event through to - an output or store it internally somehow, it MUST call this function - on the event (more information on using non-POD events below). - - @param event An event received at an input that will not be copied to an - output or stored in any way. - - @param context The calling context. Like event types, this is a mapped - URI, see lv2_context.h. Simple plugin with just a run() method should - pass 0 here (the ID of the 'standard' LV2 run context). The host - guarantees that this function is realtime safe iff @a context is - realtime safe. - - PLUGINS THAT VIOLATE THESE RULES MAY CAUSE CRASHES AND MEMORY LEAKS. - */ - uint32_t (*lv2_event_unref)(LV2_Event_Callback_Data callback_data, - LV2_Event* event); -} LV2_Event_Feature; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_EVENT_H */ diff --git a/libs/distrho/src/lv2/instance-access.h b/libs/distrho/src/lv2/instance-access.h deleted file mode 100644 index 06d8dde..0000000 --- a/libs/distrho/src/lv2/instance-access.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - LV2 Instance Access Extension - Copyright 2008-2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_INSTANCE_ACCESS_H -#define LV2_INSTANCE_ACCESS_H - -#define LV2_INSTANCE_ACCESS_URI "http://lv2plug.in/ns/ext/instance-access" - -/** - @file instance-access.h - C header for the LV2 Instance Access extension - <http://lv2plug.in/ns/ext/instance-access>. - - This extension defines a method for (e.g.) plugin UIs to get a direct - handle to an LV2 plugin instance (LV2_Handle), if possible. - - To support this feature the host must pass an LV2_Feature struct to the - UI instantiate method with URI "http://lv2plug.in/ns/ext/instance-access" - and data pointed directly to the LV2_Handle of the plugin instance. -*/ - -#endif /* LV2_INSTANCE_ACCESS_H */ - diff --git a/libs/distrho/src/lv2/log.h b/libs/distrho/src/lv2/log.h deleted file mode 100644 index 4b7b0f4..0000000 --- a/libs/distrho/src/lv2/log.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file log.h C header for the LV2 Log extension - <http://lv2plug.in/ns/ext/log>. -*/ - -#ifndef LV2_LOG_H -#define LV2_LOG_H - -#define LV2_LOG_URI "http://lv2plug.in/ns/ext/log" -#define LV2_LOG_PREFIX LV2_LOG_URI "#" - -#define LV2_LOG__Entry LV2_LOG_PREFIX "Entry" -#define LV2_LOG__Error LV2_LOG_PREFIX "Error" -#define LV2_LOG__Note LV2_LOG_PREFIX "Note" -#define LV2_LOG__Trace LV2_LOG_PREFIX "Trace" -#define LV2_LOG__Warning LV2_LOG_PREFIX "Warning" -#define LV2_LOG__log LV2_LOG_PREFIX "log" - -#include <stdarg.h> - -#include "urid.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __GNUC__ -/** Allow type checking of printf-like functions. */ -# define LV2_LOG_FUNC(fmt, arg1) __attribute__((format(printf, fmt, arg1))) -#else -# define LV2_LOG_FUNC(fmt, arg1) -#endif - -/** - Opaque data to host data for LV2_Log_Log. -*/ -typedef void* LV2_Log_Handle; - -/** - Log feature (LV2_LOG__log) -*/ -typedef struct _LV2_Log { - /** - Opaque pointer to host data. - - This MUST be passed to methods in this struct whenever they are called. - Otherwise, it must not be interpreted in any way. - */ - LV2_Log_Handle handle; - - /** - Log a message, passing format parameters directly. - - The API of this function matches that of the standard C printf function, - except for the addition of the first two parameters. This function may - be called from any non-realtime context, or from any context if @p type - is @ref LV2_LOG__Trace. - */ - LV2_LOG_FUNC(3, 4) - int (*printf)(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, ...); - - /** - Log a message, passing format parameters in a va_list. - - The API of this function matches that of the standard C vprintf - function, except for the addition of the first two parameters. This - function may be called from any non-realtime context, or from any - context if @p type is @ref LV2_LOG__Trace. - */ - LV2_LOG_FUNC(3, 0) - int (*vprintf)(LV2_Log_Handle handle, - LV2_URID type, - const char* fmt, - va_list ap); -} LV2_Log_Log; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_LOG_H */ diff --git a/libs/distrho/src/lv2/logger.h b/libs/distrho/src/lv2/logger.h deleted file mode 100644 index 9143544..0000000 --- a/libs/distrho/src/lv2/logger.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - Copyright 2012-2013 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file logger.h Convenience API for easy logging in plugin code. - - This file provides simple wrappers for the most common log operations for - use in plugin implementations. If host support for logging is not - available, then these functions will print to stderr instead. - - This header is non-normative, it is provided for convenience. -*/ - -#ifndef LV2_ATOM_LOGGER_H -#define LV2_ATOM_LOGGER_H - -#include <stdio.h> -#include <string.h> - -#include "log.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Logger convenience API state. -*/ -typedef struct { - LV2_Log_Log* log; - - LV2_URID Error; - LV2_URID Note; - LV2_URID Trace; - LV2_URID Warning; -} LV2_Log_Logger; - -/** - Initialise @p logger. - - URIs will be mapped using @p map and stored, a reference to @p map itself is - not held. Both @p map and @p log may be NULL when unsupported by the host, - in which case the implementation will fall back to printing to stderr. -*/ -static inline void -lv2_log_logger_init(LV2_Log_Logger* logger, - LV2_URID_Map* map, - LV2_Log_Log* log) -{ - memset(logger, 0, sizeof(LV2_Log_Logger)); - logger->log = log; - if (map) { - logger->Error = map->map(map->handle, LV2_LOG__Error); - logger->Note = map->map(map->handle, LV2_LOG__Note); - logger->Trace = map->map(map->handle, LV2_LOG__Trace); - logger->Warning = map->map(map->handle, LV2_LOG__Warning); - } -} - -/** - Log a message to the host, or stderr if support is unavailable. -*/ -LV2_LOG_FUNC(3, 0) -static inline int -lv2_log_vprintf(LV2_Log_Logger* logger, - LV2_URID type, - const char* fmt, - va_list args) -{ - if (logger->log) { - return logger->log->vprintf(logger->log->handle, type, fmt, args); - } else { - return vfprintf(stderr, fmt, args); - } -} - -/** Log an error via lv2_log_vprintf(). */ -LV2_LOG_FUNC(2, 3) -static inline int -lv2_log_error(LV2_Log_Logger* logger, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - const int ret = lv2_log_vprintf(logger, logger->Error, fmt, args); - va_end(args); - return ret; -} - -/** Log a note via lv2_log_vprintf(). */ -LV2_LOG_FUNC(2, 3) -static inline int -lv2_log_note(LV2_Log_Logger* logger, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - const int ret = lv2_log_vprintf(logger, logger->Note, fmt, args); - va_end(args); - return ret; -} - -/** Log a trace via lv2_log_vprintf(). */ -LV2_LOG_FUNC(2, 3) -static inline int -lv2_log_trace(LV2_Log_Logger* logger, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - const int ret = lv2_log_vprintf(logger, logger->Trace, fmt, args); - va_end(args); - return ret; -} - -/** Log a warning via lv2_log_vprintf(). */ -LV2_LOG_FUNC(2, 3) -static inline int -lv2_log_warning(LV2_Log_Logger* logger, const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - const int ret = lv2_log_vprintf(logger, logger->Warning, fmt, args); - va_end(args); - return ret; -} - -/** - @} -*/ - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_LOG_LOGGER_H */ diff --git a/libs/distrho/src/lv2/lv2-midifunctions.h b/libs/distrho/src/lv2/lv2-midifunctions.h deleted file mode 100644 index d068f49..0000000 --- a/libs/distrho/src/lv2/lv2-midifunctions.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** - - lv2-midifunctions.h - support file for using MIDI in LV2 plugins - - Copyright (C) 2006 Lars Luthman <lars.luthman@gmail.com> - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA - -****************************************************************************/ - -#ifndef LV2_MIDIFUNCTIONS -#define LV2_MIDIFUNCTIONS - -#include "lv2-miditype.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - LV2_MIDI* midi; - uint32_t frame_count; - uint32_t position; -} LV2_MIDIState; - - -inline double lv2midi_get_event(LV2_MIDIState* state, - double* timestamp, - uint32_t* size, - unsigned char** data) { - - if (state->position >= state->midi->size) { - state->position = state->midi->size; - *timestamp = state->frame_count; - *size = 0; - *data = NULL; - return *timestamp; - } - - *timestamp = *(double*)(state->midi->data + state->position); - *size = (uint32_t)*(size_t*)(state->midi->data + state->position + sizeof(double)); - *data = state->midi->data + state->position + - sizeof(double) + sizeof(size_t); - return *timestamp; -} - - -inline double lv2midi_step(LV2_MIDIState* state) { - - if (state->position >= state->midi->size) { - state->position = state->midi->size; - return state->frame_count; - } - - state->position += (uint32_t)sizeof(double); - size_t size = *(size_t*)(state->midi->data + state->position); - state->position += (uint32_t)sizeof(size_t); - state->position += (uint32_t)size; - return *(double*)(state->midi->data + state->position); -} - - -inline void lv2midi_put_event(LV2_MIDIState* state, - double timestamp, - uint32_t size, - const unsigned char* data) { - - if (state->midi->size + sizeof(double) + sizeof(size_t) + size < state->midi->capacity) - { - *((double*)(state->midi->data + state->midi->size)) = timestamp; - state->midi->size += (uint32_t)sizeof(double); - *((size_t*)(state->midi->data + state->midi->size)) = size; - state->midi->size += (uint32_t)sizeof(size_t); - memcpy(state->midi->data + state->midi->size, data, size); - - state->midi->size += size; - state->midi->event_count++; - } -} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif - diff --git a/libs/distrho/src/lv2/lv2-miditype.h b/libs/distrho/src/lv2/lv2-miditype.h deleted file mode 100644 index 7afcae8..0000000 --- a/libs/distrho/src/lv2/lv2-miditype.h +++ /dev/null @@ -1,175 +0,0 @@ -/**************************************************************************** - - lv2-miditype.h - header file for using MIDI in LV2 plugins - - Copyright (C) 2006 Lars Luthman <lars.luthman@gmail.com> - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA - -****************************************************************************/ - -#ifndef LV2_MIDITYPE_H -#define LV2_MIDITYPE_H - -#ifdef __cplusplus -extern "C" { -#endif - -/** This data structure is used to contain the MIDI events for one run() - cycle. The port buffer for a LV2 port that has the datatype - <http://ll-plugins.nongnu.org/lv2/ext/miditype> should be a pointer - to an instance of this struct. - - To store two Note On events on MIDI channel 0 in a buffer, with timestamps - 12 and 35.5, you could use something like this code (assuming that - midi_data is a variable of type LV2_MIDI): - @code - - size_t buffer_offset = 0; - *(double*)(midi_data->data + buffer_offset) = 12; - buffer_offset += sizeof(double); - *(size_t*)(midi_data->data + buffer_offset) = 3; - buffer_offset += sizeof(size_t); - midi_data->data[buffer_offset++] = 0x90; - midi_data->data[buffer_offset++] = 0x48; - midi_data->data[buffer_offset++] = 0x64; - ++midi_data->event_count; - - *(double*)(midi_data->data + buffer_offset) = 35.5; - buffer_offset += sizeof(double); - *(size_t*)(midi_data->data + buffer_offset) = 3; - buffer_offset += sizeof(size_t); - midi_data->data[buffer_offset++] = 0x90; - midi_data->data[buffer_offset++] = 0x55; - midi_data->data[buffer_offset++] = 0x64; - ++midi_data->event_count; - - midi_data->size = buffer_offset; - - @endcode - - This would be done by the host in the case of an input port, and by the - plugin in the case of an output port. Whoever is writing events to the - buffer must also take care not to exceed the capacity of the data buffer. - - To read events from a buffer, you could do something like this: - @code - - size_t buffer_offset = 0; - uint32_t i; - for (i = 0; i < midi_data->event_count; ++i) { - double timestamp = *(double*)(midi_data->data + buffer_offset); - buffer_offset += sizeof(double); - size_t size = *(size_t*)(midi_data->data + buffer_offset); - buffer_offset += sizeof(size_t); - do_something_with_event(timestamp, size, - midi_data->data + buffer_offset); - buffer_offset += size; - } - - @endcode -*/ -typedef struct { - - /** The number of MIDI events in the data buffer. - INPUT PORTS: It's the host's responsibility to set this field to the - number of MIDI events contained in the data buffer before calling the - plugin's run() function. The plugin may not change this field. - OUTPUT PORTS: It's the plugin's responsibility to set this field to the - number of MIDI events it has stored in the data buffer before returning - from the run() function. Any initial value should be ignored by the - plugin. - */ - uint32_t event_count; - - /** The size of the data buffer in bytes. It is set by the host and may not - be changed by the plugin. The host is allowed to change this between - run() calls. - */ - uint32_t capacity; - - /** The size of the initial part of the data buffer that actually contains - data. - INPUT PORTS: It's the host's responsibility to set this field to the - number of bytes used by all MIDI events it has written to the buffer - (including timestamps and size fields) before calling the plugin's - run() function. The plugin may not change this field. - OUTPUT PORTS: It's the plugin's responsibility to set this field to - the number of bytes used by all MIDI events it has written to the - buffer (including timestamps and size fields) before returning from - the run() function. Any initial value should be ignored by the plugin. - */ - uint32_t size; - - /** The data buffer that is used to store MIDI events. The events are packed - after each other, and the format of each event is as follows: - - First there is a timestamp, which should have the type "double", - i.e. have the same bit size as a double and the same bit layout as a - double (whatever that is on the current platform). This timestamp gives - the offset from the beginning of the current cycle, in frames, that - the MIDI event occurs on. It must be strictly smaller than the 'nframes' - parameter to the current run() call. The MIDI events in the buffer must - be ordered by their timestamp, e.g. an event with a timestamp of 123.23 - must be stored after an event with a timestamp of 65.0. - - The second part of the event is a size field, which should have the type - "size_t" (as defined in the standard C header stddef.h). It should - contain the size of the MIDI data for this event, i.e. the number of - bytes used to store the actual MIDI event. The bytes used by the - timestamp and the size field should not be counted. - - The third part of the event is the actual MIDI data. There are some - requirements that must be followed: - - * Running status is not allowed. Every event must have its own status - byte. - * Note On events with velocity 0 are not allowed. These events are - equivalent to Note Off in standard MIDI streams, but in order to make - plugins and hosts easier to write, as well as more efficient, only - proper Note Off events are allowed as Note Off. - * "Realtime events" (status bytes 0xF8 to 0xFF) are allowed, but may not - occur inside other events like they are allowed to in hardware MIDI - streams. - * All events must be fully contained in a single data buffer, i.e. events - may not "wrap around" by storing the first few bytes in one buffer and - then wait for the next run() call to store the rest of the event. If - there isn't enough space in the current data buffer to store an event, - the event will either have to wait until next run() call, be ignored, - or compensated for in some more clever way. - * All events must be valid MIDI events. This means for example that - only the first byte in each event (the status byte) may have the eighth - bit set, that Note On and Note Off events are always 3 bytes long etc. - The MIDI writer (host or plugin) is responsible for writing valid MIDI - events to the buffer, and the MIDI reader (plugin or host) can assume - that all events are valid. - - On a platform where double is 8 bytes and size_t is 4 bytes, the data - buffer layout for a 3-byte event followed by a 4-byte event may look - something like this: - _______________________________________________________________ - | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ... - |TIMESTAMP 1 |SIZE 1 |DATA |TIMESTAMP 2 |SIZE 2 |DATA | ... - - */ - unsigned char* data; - -} LV2_MIDI; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif diff --git a/libs/distrho/src/lv2/lv2.h b/libs/distrho/src/lv2/lv2.h deleted file mode 100644 index 6e0edaa..0000000 --- a/libs/distrho/src/lv2/lv2.h +++ /dev/null @@ -1,458 +0,0 @@ -/* - LV2 - An audio plugin interface specification. - Copyright 2006-2012 Steve Harris, David Robillard. - - Based on LADSPA, Copyright 2000-2002 Richard W.E. Furse, - Paul Barton-Davis, Stefan Westerfeld. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file lv2.h - API for the LV2 specification <http://lv2plug.in/ns/lv2core>. - Revision: 12.0 -*/ - -#ifndef LV2_H_INCLUDED -#define LV2_H_INCLUDED - -#include <stdint.h> - -#define LV2_CORE_URI "http://lv2plug.in/ns/lv2core" -#define LV2_CORE_PREFIX LV2_CORE_URI "#" - -#define LV2_CORE__AllpassPlugin LV2_CORE_PREFIX "AllpassPlugin" -#define LV2_CORE__AmplifierPlugin LV2_CORE_PREFIX "AmplifierPlugin" -#define LV2_CORE__AnalyserPlugin LV2_CORE_PREFIX "AnalyserPlugin" -#define LV2_CORE__AudioPort LV2_CORE_PREFIX "AudioPort" -#define LV2_CORE__BandpassPlugin LV2_CORE_PREFIX "BandpassPlugin" -#define LV2_CORE__CVPort LV2_CORE_PREFIX "CVPort" -#define LV2_CORE__ChorusPlugin LV2_CORE_PREFIX "ChorusPlugin" -#define LV2_CORE__CombPlugin LV2_CORE_PREFIX "CombPlugin" -#define LV2_CORE__CompressorPlugin LV2_CORE_PREFIX "CompressorPlugin" -#define LV2_CORE__ConstantPlugin LV2_CORE_PREFIX "ConstantPlugin" -#define LV2_CORE__ControlPort LV2_CORE_PREFIX "ControlPort" -#define LV2_CORE__ConverterPlugin LV2_CORE_PREFIX "ConverterPlugin" -#define LV2_CORE__DelayPlugin LV2_CORE_PREFIX "DelayPlugin" -#define LV2_CORE__DistortionPlugin LV2_CORE_PREFIX "DistortionPlugin" -#define LV2_CORE__DynamicsPlugin LV2_CORE_PREFIX "DynamicsPlugin" -#define LV2_CORE__EQPlugin LV2_CORE_PREFIX "EQPlugin" -#define LV2_CORE__EnvelopePlugin LV2_CORE_PREFIX "EnvelopePlugin" -#define LV2_CORE__ExpanderPlugin LV2_CORE_PREFIX "ExpanderPlugin" -#define LV2_CORE__ExtensionData LV2_CORE_PREFIX "ExtensionData" -#define LV2_CORE__Feature LV2_CORE_PREFIX "Feature" -#define LV2_CORE__FilterPlugin LV2_CORE_PREFIX "FilterPlugin" -#define LV2_CORE__FlangerPlugin LV2_CORE_PREFIX "FlangerPlugin" -#define LV2_CORE__FunctionPlugin LV2_CORE_PREFIX "FunctionPlugin" -#define LV2_CORE__GatePlugin LV2_CORE_PREFIX "GatePlugin" -#define LV2_CORE__GeneratorPlugin LV2_CORE_PREFIX "GeneratorPlugin" -#define LV2_CORE__HighpassPlugin LV2_CORE_PREFIX "HighpassPlugin" -#define LV2_CORE__InputPort LV2_CORE_PREFIX "InputPort" -#define LV2_CORE__InstrumentPlugin LV2_CORE_PREFIX "InstrumentPlugin" -#define LV2_CORE__LimiterPlugin LV2_CORE_PREFIX "LimiterPlugin" -#define LV2_CORE__LowpassPlugin LV2_CORE_PREFIX "LowpassPlugin" -#define LV2_CORE__MixerPlugin LV2_CORE_PREFIX "MixerPlugin" -#define LV2_CORE__ModulatorPlugin LV2_CORE_PREFIX "ModulatorPlugin" -#define LV2_CORE__MultiEQPlugin LV2_CORE_PREFIX "MultiEQPlugin" -#define LV2_CORE__OscillatorPlugin LV2_CORE_PREFIX "OscillatorPlugin" -#define LV2_CORE__OutputPort LV2_CORE_PREFIX "OutputPort" -#define LV2_CORE__ParaEQPlugin LV2_CORE_PREFIX "ParaEQPlugin" -#define LV2_CORE__PhaserPlugin LV2_CORE_PREFIX "PhaserPlugin" -#define LV2_CORE__PitchPlugin LV2_CORE_PREFIX "PitchPlugin" -#define LV2_CORE__Plugin LV2_CORE_PREFIX "Plugin" -#define LV2_CORE__PluginBase LV2_CORE_PREFIX "PluginBase" -#define LV2_CORE__Point LV2_CORE_PREFIX "Point" -#define LV2_CORE__Port LV2_CORE_PREFIX "Port" -#define LV2_CORE__PortProperty LV2_CORE_PREFIX "PortProperty" -#define LV2_CORE__Resource LV2_CORE_PREFIX "Resource" -#define LV2_CORE__ReverbPlugin LV2_CORE_PREFIX "ReverbPlugin" -#define LV2_CORE__ScalePoint LV2_CORE_PREFIX "ScalePoint" -#define LV2_CORE__SimulatorPlugin LV2_CORE_PREFIX "SimulatorPlugin" -#define LV2_CORE__SpatialPlugin LV2_CORE_PREFIX "SpatialPlugin" -#define LV2_CORE__Specification LV2_CORE_PREFIX "Specification" -#define LV2_CORE__SpectralPlugin LV2_CORE_PREFIX "SpectralPlugin" -#define LV2_CORE__UtilityPlugin LV2_CORE_PREFIX "UtilityPlugin" -#define LV2_CORE__WaveshaperPlugin LV2_CORE_PREFIX "WaveshaperPlugin" -#define LV2_CORE__appliesTo LV2_CORE_PREFIX "appliesTo" -#define LV2_CORE__binary LV2_CORE_PREFIX "binary" -#define LV2_CORE__connectionOptional LV2_CORE_PREFIX "connectionOptional" -#define LV2_CORE__control LV2_CORE_PREFIX "control" -#define LV2_CORE__default LV2_CORE_PREFIX "default" -#define LV2_CORE__designation LV2_CORE_PREFIX "designation" -#define LV2_CORE__documentation LV2_CORE_PREFIX "documentation" -#define LV2_CORE__enumeration LV2_CORE_PREFIX "enumeration" -#define LV2_CORE__extensionData LV2_CORE_PREFIX "extensionData" -#define LV2_CORE__freeWheeling LV2_CORE_PREFIX "freeWheeling" -#define LV2_CORE__hardRTCapable LV2_CORE_PREFIX "hardRTCapable" -#define LV2_CORE__inPlaceBroken LV2_CORE_PREFIX "inPlaceBroken" -#define LV2_CORE__index LV2_CORE_PREFIX "index" -#define LV2_CORE__integer LV2_CORE_PREFIX "integer" -#define LV2_CORE__isLive LV2_CORE_PREFIX "isLive" -#define LV2_CORE__latency LV2_CORE_PREFIX "latency" -#define LV2_CORE__maximum LV2_CORE_PREFIX "maximum" -#define LV2_CORE__microVersion LV2_CORE_PREFIX "microVersion" -#define LV2_CORE__minimum LV2_CORE_PREFIX "minimum" -#define LV2_CORE__minorVersion LV2_CORE_PREFIX "minorVersion" -#define LV2_CORE__name LV2_CORE_PREFIX "name" -#define LV2_CORE__optionalFeature LV2_CORE_PREFIX "optionalFeature" -#define LV2_CORE__port LV2_CORE_PREFIX "port" -#define LV2_CORE__portProperty LV2_CORE_PREFIX "portProperty" -#define LV2_CORE__project LV2_CORE_PREFIX "project" -#define LV2_CORE__prototype LV2_CORE_PREFIX "prototype" -#define LV2_CORE__reportsLatency LV2_CORE_PREFIX "reportsLatency" -#define LV2_CORE__requiredFeature LV2_CORE_PREFIX "requiredFeature" -#define LV2_CORE__sampleRate LV2_CORE_PREFIX "sampleRate" -#define LV2_CORE__scalePoint LV2_CORE_PREFIX "scalePoint" -#define LV2_CORE__symbol LV2_CORE_PREFIX "symbol" -#define LV2_CORE__toggled LV2_CORE_PREFIX "toggled" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Plugin Instance Handle. - - This is a handle for one particular instance of a plugin. It is valid to - compare to NULL (or 0 for C++) but otherwise the host MUST NOT attempt to - interpret it. -*/ -typedef void * LV2_Handle; - -/** - Feature. - - Features allow hosts to make additional functionality available to plugins - without requiring modification to the LV2 API. Extensions may define new - features and specify the @ref URI and @ref data to be used if necessary. - Some features, such as lv2:isLive, do not require the host to pass data. -*/ -typedef struct _LV2_Feature { - /** - A globally unique, case-sensitive identifier (URI) for this feature. - - This MUST be a valid URI string as defined by RFC 3986. - */ - const char * URI; - - /** - Pointer to arbitrary data. - - The format of this data is defined by the extension which describes the - feature with the given @ref URI. - */ - void * data; -} LV2_Feature; - -/** - Plugin Descriptor. - - This structure provides the core functions necessary to instantiate and use - a plugin. -*/ -typedef struct _LV2_Descriptor { - /** - A globally unique, case-sensitive identifier for this plugin. - - This MUST be a valid URI string as defined by RFC 3986. All plugins with - the same URI MUST be compatible to some degree, see - http://lv2plug.in/ns/lv2core for details. - */ - const char * URI; - - /** - Instantiate the plugin. - - Note that instance initialisation should generally occur in activate() - rather than here. If a host calls instantiate(), it MUST call cleanup() - at some point in the future. - - @param descriptor Descriptor of the plugin to instantiate. - - @param sample_rate Sample rate, in Hz, for the new plugin instance. - - @param bundle_path Path to the LV2 bundle which contains this plugin - binary. It MUST include the trailing directory separator (e.g. '/') so - that simply appending a filename will yield the path to that file in the - bundle. - - @param features A NULL terminated array of LV2_Feature structs which - represent the features the host supports. Plugins may refuse to - instantiate if required features are not found here. However, hosts MUST - NOT use this as a discovery mechanism: instead, use the RDF data to - determine which features are required and do not attempt to instantiate - unsupported plugins at all. This parameter MUST NOT be NULL, i.e. a host - that supports no features MUST pass a single element array containing - NULL. - - @return A handle for the new plugin instance, or NULL if instantiation - has failed. - */ - LV2_Handle (*instantiate)(const struct _LV2_Descriptor * descriptor, - double sample_rate, - const char * bundle_path, - const LV2_Feature *const * features); - - /** - Connect a port on a plugin instance to a memory location. - - Plugin writers should be aware that the host may elect to use the same - buffer for more than one port and even use the same buffer for both - input and output (see lv2:inPlaceBroken in lv2.ttl). - - If the plugin has the feature lv2:hardRTCapable then there are various - things that the plugin MUST NOT do within the connect_port() function; - see lv2core.ttl for details. - - connect_port() MUST be called at least once for each port before run() - is called, unless that port is lv2:connectionOptional. The plugin must - pay careful attention to the block size passed to run() since the block - allocated may only just be large enough to contain the data, and is not - guaranteed to remain constant between run() calls. - - connect_port() may be called more than once for a plugin instance to - allow the host to change the buffers that the plugin is reading or - writing. These calls may be made before or after activate() or - deactivate() calls. - - @param instance Plugin instance containing the port. - - @param port Index of the port to connect. The host MUST NOT try to - connect a port index that is not defined in the plugin's RDF data. If - it does, the plugin's behaviour is undefined (a crash is likely). - - @param data_location Pointer to data of the type defined by the port - type in the plugin's RDF data (e.g. an array of float for an - lv2:AudioPort). This pointer must be stored by the plugin instance and - used to read/write data when run() is called. Data present at the time - of the connect_port() call MUST NOT be considered meaningful. - */ - void (*connect_port)(LV2_Handle instance, - uint32_t port, - void * data_location); - - /** - Initialise a plugin instance and activate it for use. - - This is separated from instantiate() to aid real-time support and so - that hosts can reinitialise a plugin instance by calling deactivate() - and then activate(). In this case the plugin instance MUST reset all - state information dependent on the history of the plugin instance except - for any data locations provided by connect_port(). If there is nothing - for activate() to do then this field may be NULL. - - When present, hosts MUST call this function once before run() is called - for the first time. This call SHOULD be made as close to the run() call - as possible and indicates to real-time plugins that they are now live, - however plugins MUST NOT rely on a prompt call to run() after - activate(). - - The host MUST NOT call activate() again until deactivate() has been - called first. If a host calls activate(), it MUST call deactivate() at - some point in the future. Note that connect_port() may be called before - or after activate(). - */ - void (*activate)(LV2_Handle instance); - - /** - Run a plugin instance for a block. - - Note that if an activate() function exists then it must be called before - run(). If deactivate() is called for a plugin instance then run() may - not be called until activate() has been called again. - - If the plugin has the feature lv2:hardRTCapable then there are various - things that the plugin MUST NOT do within the run() function (see - lv2core.ttl for details). - - As a special case, when @p sample_count == 0, the plugin should update - any output ports that represent a single instant in time (e.g. control - ports, but not audio ports). This is particularly useful for latent - plugins, which should update their latency output port so hosts can - pre-roll plugins to compute latency. Plugins MUST NOT crash when - @p sample_count == 0. - - @param instance Instance to be run. - - @param sample_count The block size (in samples) for which the plugin - instance must run. - */ - void (*run)(LV2_Handle instance, - uint32_t sample_count); - - /** - Deactivate a plugin instance (counterpart to activate()). - - Hosts MUST deactivate all activated instances after they have been run() - for the last time. This call SHOULD be made as close to the last run() - call as possible and indicates to real-time plugins that they are no - longer live, however plugins MUST NOT rely on prompt deactivation. If - there is nothing for deactivate() to do then this field may be NULL - - Deactivation is not similar to pausing since the plugin instance will be - reinitialised by activate(). However, deactivate() itself MUST NOT fully - reset plugin state. For example, the host may deactivate a plugin, then - store its state (using some extension to do so). - - Hosts MUST NOT call deactivate() unless activate() was previously - called. Note that connect_port() may be called before or after - deactivate(). - */ - void (*deactivate)(LV2_Handle instance); - - /** - Clean up a plugin instance (counterpart to instantiate()). - - Once an instance of a plugin has been finished with it must be deleted - using this function. The instance handle passed ceases to be valid after - this call. - - If activate() was called for a plugin instance then a corresponding call - to deactivate() MUST be made before cleanup() is called. Hosts MUST NOT - call cleanup() unless instantiate() was previously called. - */ - void (*cleanup)(LV2_Handle instance); - - /** - Return additional plugin data defined by some extenion. - - A typical use of this facility is to return a struct containing function - pointers to extend the LV2_Descriptor API. - - The actual type and meaning of the returned object MUST be specified - precisely by the extension. This function MUST return NULL for any - unsupported URI. If a plugin does not support any extension data, this - field may be NULL. - - The host is never responsible for freeing the returned value. - */ - const void * (*extension_data)(const char * uri); -} LV2_Descriptor; - -/** - Put this (LV2_SYMBOL_EXPORT) before any functions that are to be loaded - by the host as a symbol from the dynamic library. -*/ -#ifdef _WIN32 -# define LV2_SYMBOL_EXPORT __declspec(dllexport) -#else -# define LV2_SYMBOL_EXPORT -#endif - -/** - Prototype for plugin accessor function. - - Plugins are discovered by hosts using RDF data (not by loading libraries). - See http://lv2plug.in for details on the discovery process, though most - hosts should use an existing library to implement this functionality. - - This is the simple plugin discovery API, suitable for most statically - defined plugins. Advanced plugins that need access to their bundle during - discovery can use lv2_lib_descriptor() instead. Plugin libraries MUST - include a function called "lv2_descriptor" or "lv2_lib_descriptor" with - C-style linkage, but SHOULD provide "lv2_descriptor" wherever possible. - - When it is time to load a plugin (designated by its URI), the host loads the - plugin's library, gets the lv2_descriptor() function from it, and uses this - function to find the LV2_Descriptor for the desired plugin. Plugins are - accessed by index using values from 0 upwards. This function MUST return - NULL for out of range indices, so the host can enumerate plugins by - increasing @p index until NULL is returned. - - Note that @p index has no meaning, hosts MUST NOT depend on it remaining - consistent between loads of the plugin library. -*/ -LV2_SYMBOL_EXPORT -const LV2_Descriptor * lv2_descriptor(uint32_t index); - -/** - Type of the lv2_descriptor() function in a library (old discovery API). -*/ -typedef const LV2_Descriptor * -(*LV2_Descriptor_Function)(uint32_t index); - -/** - Handle for a library descriptor. -*/ -typedef void* LV2_Lib_Handle; - -/** - Descriptor for a plugin library. - - To access a plugin library, the host creates an LV2_Lib_Descriptor via the - lv2_lib_descriptor() function in the shared object. -*/ -typedef struct { - /** - Opaque library data which must be passed as the first parameter to all - the methods of this struct. - */ - LV2_Lib_Handle handle; - - /** - The total size of this struct. This allows for this struct to be - expanded in the future if necessary. This MUST be set by the library to - sizeof(LV2_Lib_Descriptor). The host MUST NOT access any fields of this - struct beyond get_plugin() unless this field indicates they are present. - */ - uint32_t size; - - /** - Destroy this library descriptor and free all related resources. - */ - void (*cleanup)(LV2_Lib_Handle handle); - - /** - Plugin accessor. - - Plugins are accessed by index using values from 0 upwards. Out of range - indices MUST result in this function returning NULL, so the host can - enumerate plugins by increasing @a index until NULL is returned. - */ - const LV2_Descriptor * (*get_plugin)(LV2_Lib_Handle handle, - uint32_t index); -} LV2_Lib_Descriptor; - -/** - Prototype for library accessor function. - - This is the more advanced discovery API, which allows plugin libraries to - access their bundles during discovery, which makes it possible for plugins to - be dynamically defined by files in their bundle. This API also has an - explicit cleanup function, removing any need for non-portable shared library - destructors. Simple plugins that do not require these features may use - lv2_descriptor() instead. - - This is the entry point for a plugin library. Hosts load this symbol from - the library and call this function to obtain a library descriptor which can - be used to access all the contained plugins. The returned object must not - be destroyed (using LV2_Lib_Descriptor::cleanup()) until all plugins loaded - from that library have been destroyed. -*/ -const LV2_Lib_Descriptor * -lv2_lib_descriptor(const char * bundle_path, - const LV2_Feature *const * features); - -/** - Type of the lv2_lib_descriptor() function in an LV2 library. -*/ -typedef const LV2_Lib_Descriptor * -(*LV2_Lib_Descriptor_Function)(const char * bundle_path, - const LV2_Feature *const * features); - -#ifdef __cplusplus -} -#endif - -#endif /* LV2_H_INCLUDED */ diff --git a/libs/distrho/src/lv2/lv2_external_ui.h b/libs/distrho/src/lv2/lv2_external_ui.h deleted file mode 100755 index 789cd3f..0000000 --- a/libs/distrho/src/lv2/lv2_external_ui.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - LV2 External UI extension - This work is in public domain. - - This file 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. - - If you have questions, contact Filipe Coelho (aka falkTX) <falktx@falktx.com> - or ask in #lad channel, FreeNode IRC network. -*/ - -/** - @file lv2_external_ui.h - C header for the LV2 External UI extension <http://kxstudio.sf.net/ns/lv2ext/external-ui>. -*/ - -#ifndef LV2_EXTERNAL_UI_H -#define LV2_EXTERNAL_UI_H - -#include "ui.h" - -#define LV2_EXTERNAL_UI_URI "http://kxstudio.sf.net/ns/lv2ext/external-ui" -#define LV2_EXTERNAL_UI_PREFIX LV2_EXTERNAL_UI_URI "#" - -#define LV2_EXTERNAL_UI__Host LV2_EXTERNAL_UI_PREFIX "Host" -#define LV2_EXTERNAL_UI__Widget LV2_EXTERNAL_UI_PREFIX "Widget" - -/** This extension used to be defined by a lv2plug.in URI */ -#define LV2_EXTERNAL_UI_DEPRECATED_URI "http://lv2plug.in/ns/extensions/ui#external" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * When LV2_EXTERNAL_UI__Widget UI is instantiated, the returned - * LV2UI_Widget handle must be cast to pointer to LV2_External_UI_Widget. - * UI is created in invisible state. - */ -typedef struct _LV2_External_UI_Widget { - /** - * Host calls this function regulary. UI library implementing the - * callback may do IPC or redraw the UI. - * - * @param _this_ the UI context - */ - void (*run)(struct _LV2_External_UI_Widget * _this_); - - /** - * Host calls this function to make the plugin UI visible. - * - * @param _this_ the UI context - */ - void (*show)(struct _LV2_External_UI_Widget * _this_); - - /** - * Host calls this function to make the plugin UI invisible again. - * - * @param _this_ the UI context - */ - void (*hide)(struct _LV2_External_UI_Widget * _this_); - -} LV2_External_UI_Widget; - -#define LV2_EXTERNAL_UI_RUN(ptr) (ptr)->run(ptr) -#define LV2_EXTERNAL_UI_SHOW(ptr) (ptr)->show(ptr) -#define LV2_EXTERNAL_UI_HIDE(ptr) (ptr)->hide(ptr) - -/** - * On UI instantiation, host must supply LV2_EXTERNAL_UI__Host feature. - * LV2_Feature::data must be pointer to LV2_External_UI_Host. - */ -typedef struct _LV2_External_UI_Host { - /** - * Callback that plugin UI will call when UI (GUI window) is closed by user. - * This callback will be called during execution of LV2_External_UI_Widget::run() - * (i.e. not from background thread). - * - * After this callback is called, UI is defunct. Host must call LV2UI_Descriptor::cleanup(). - * If host wants to make the UI visible again, the UI must be reinstantiated. - * - * @note When using the depreated URI LV2_EXTERNAL_UI_DEPRECATED_URI, - * some hosts will not call LV2UI_Descriptor::cleanup() as they should, - * and may call show() again without re-initialization. - * - * @param controller Host context associated with plugin UI, as - * supplied to LV2UI_Descriptor::instantiate(). - */ - void (*ui_closed)(LV2UI_Controller controller); - - /** - * Optional (may be NULL) "user friendly" identifier which the UI - * may display to allow a user to easily associate this particular - * UI instance with the correct plugin instance as it is represented - * by the host (e.g. "track 1" or "channel 4"). - * - * If supplied by host, the string will be referenced only during - * LV2UI_Descriptor::instantiate() - */ - const char * plugin_human_id; - -} LV2_External_UI_Host; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_EXTERNAL_UI_H */ diff --git a/libs/distrho/src/lv2/lv2_kxstudio_properties.h b/libs/distrho/src/lv2/lv2_kxstudio_properties.h deleted file mode 100644 index e8b42a6..0000000 --- a/libs/distrho/src/lv2/lv2_kxstudio_properties.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - LV2 KXStudio Properties Extension - Copyright 2014 Filipe Coelho <falktx@falktx.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file lv2_kxstudio_properties.h - C header for the LV2 KXStudio Properties extension <http://kxstudio.sf.net/ns/lv2ext/props>. -*/ - -#ifndef LV2_KXSTUDIO_PROPERTIES_H -#define LV2_KXSTUDIO_PROPERTIES_H - -#define LV2_KXSTUDIO_PROPERTIES_URI "http://kxstudio.sf.net/ns/lv2ext/props" -#define LV2_KXSTUDIO_PROPERTIES_PREFIX LV2_KXSTUDIO_PROPERTIES_URI "#" - -#define LV2_KXSTUDIO_PROPERTIES__NonAutomable LV2_KXSTUDIO_PROPERTIES_PREFIX "NonAutomable" -#define LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat LV2_KXSTUDIO_PROPERTIES_PREFIX "TimePositionTicksPerBeat" -#define LV2_KXSTUDIO_PROPERTIES__TransientWindowId LV2_KXSTUDIO_PROPERTIES_PREFIX "TransientWindowId" - -#endif /* LV2_KXSTUDIO_PROPERTIES_H */ diff --git a/libs/distrho/src/lv2/lv2_programs.h b/libs/distrho/src/lv2/lv2_programs.h deleted file mode 100644 index 01e2877..0000000 --- a/libs/distrho/src/lv2/lv2_programs.h +++ /dev/null @@ -1,174 +0,0 @@ -/* - LV2 Programs Extension - Copyright 2012 Filipe Coelho <falktx@falktx.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file lv2_programs.h - C header for the LV2 programs extension <http://kxstudio.sf.net/ns/lv2ext/programs>. -*/ - -#ifndef LV2_PROGRAMS_H -#define LV2_PROGRAMS_H - -#include "lv2.h" -#include "ui.h" - -#define LV2_PROGRAMS_URI "http://kxstudio.sf.net/ns/lv2ext/programs" -#define LV2_PROGRAMS_PREFIX LV2_PROGRAMS_URI "#" - -#define LV2_PROGRAMS__Host LV2_PROGRAMS_PREFIX "Host" -#define LV2_PROGRAMS__Interface LV2_PROGRAMS_PREFIX "Interface" -#define LV2_PROGRAMS__UIInterface LV2_PROGRAMS_PREFIX "UIInterface" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void* LV2_Programs_Handle; - -typedef struct _LV2_Program_Descriptor { - - /** Bank number for this program. Note that this extension does not - support MIDI-style separation of bank LSB and MSB values. There is - no restriction on the set of available banks: the numbers do not - need to be contiguous, there does not need to be a bank 0, etc. */ - uint32_t bank; - - /** Program number (unique within its bank) for this program. There is - no restriction on the set of available programs: the numbers do not - need to be contiguous, there does not need to be a program 0, etc. */ - uint32_t program; - - /** Name of the program. */ - const char * name; - -} LV2_Program_Descriptor; - -/** - Programs extension, plugin data. - - When the plugin's extension_data is called with argument LV2_PROGRAMS__Interface, - the plugin MUST return an LV2_Programs_Instance structure, which remains valid - for the lifetime of the plugin. -*/ -typedef struct _LV2_Programs_Interface { - /** - * get_program() - * - * This member is a function pointer that provides a description - * of a program (named preset sound) available on this plugin. - * - * The index argument is an index into the plugin's list of - * programs, not a program number as represented by the Program - * field of the LV2_Program_Descriptor. (This distinction is - * needed to support plugins that use non-contiguous program or - * bank numbers.) - * - * This function returns a LV2_Program_Descriptor pointer that is - * guaranteed to be valid only until the next call to get_program - * or deactivate, on the same plugin instance. This function must - * return NULL if passed an index argument out of range, so that - * the host can use it to query the number of programs as well as - * their properties. - */ - const LV2_Program_Descriptor *(*get_program)(LV2_Handle handle, - uint32_t index); - - /** - * select_program() - * - * This member is a function pointer that selects a new program - * for this plugin. The program change should take effect - * immediately at the start of the next run() call. (This - * means that a host providing the capability of changing programs - * between any two notes on a track must vary the block size so as - * to place the program change at the right place. A host that - * wanted to avoid this would probably just instantiate a plugin - * for each program.) - * - * Plugins should ignore a select_program() call with an invalid - * bank or program. - * - * A plugin is not required to select any particular default - * program on activate(): it's the host's duty to set a program - * explicitly. - * - * A plugin is permitted to re-write the values of its input - * control ports when select_program is called. The host should - * re-read the input control port values and update its own - * records appropriately. (This is the only circumstance in which - * a LV2 plugin is allowed to modify its own control-input ports.) - */ - void (*select_program)(LV2_Handle handle, - uint32_t bank, - uint32_t program); - -} LV2_Programs_Interface; - -/** - Programs extension, UI data. - - When the UI's extension_data is called with argument LV2_PROGRAMS__UIInterface, - the UI MUST return an LV2_Programs_UI_Interface structure, which remains valid - for the lifetime of the UI. -*/ -typedef struct _LV2_Programs_UI_Interface { - /** - * select_program() - * - * This is exactly the same as select_program in LV2_Programs_Instance, - * but this struct relates to the UI instead of the plugin. - * - * When called, UIs should update their state to match the selected program. - */ - void (*select_program)(LV2UI_Handle handle, - uint32_t bank, - uint32_t program); - -} LV2_Programs_UI_Interface; - -/** - Feature data for LV2_PROGRAMS__Host. -*/ -typedef struct _LV2_Programs_Host { - /** - * Opaque host data. - */ - LV2_Programs_Handle handle; - - /** - * program_changed() - * - * Tell the host to reload a plugin's program. - * Parameter handle MUST be the 'handle' member of this struct. - * Parameter index is program index to change. - * When index is -1, host should reload all the programs. - * - * The plugin MUST NEVER call this function on a RT context or during run(). - * - * NOTE: This call is to inform the host about a program's bank, program or name change. - * It DOES NOT change the current selected program. - */ - void (*program_changed)(LV2_Programs_Handle handle, - int32_t index); - -} LV2_Programs_Host; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_PROGRAMS_H */ diff --git a/libs/distrho/src/lv2/lv2_rtmempool.h b/libs/distrho/src/lv2/lv2_rtmempool.h deleted file mode 100644 index 7988886..0000000 --- a/libs/distrho/src/lv2/lv2_rtmempool.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - LV2 realtime safe memory pool extension definition - This work is in public domain. - - This file 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. - - If you have questions, contact Filipe Coelho (aka falkTX) <falktx@falktx.com> - or ask in #lad channel, FreeNode IRC network. -*/ - -/** - * @file lv2_rtmempool.h - * C header for the LV2 rtmempool extension <http://kxstudio.sf.net/ns/lv2ext/rtmempool>. - * - */ - -#ifndef LV2_RTMEMPOOL_H -#define LV2_RTMEMPOOL_H - -#define LV2_RTSAFE_MEMORY_POOL_URI "http://kxstudio.sf.net/ns/lv2ext/rtmempool" -#define LV2_RTSAFE_MEMORY_POOL_PREFIX LV2_RTSAFE_MEMORY_POOL_URI "#" - -#define LV2_RTSAFE_MEMORY_POOL__Pool LV2_RTSAFE_MEMORY_POOL_URI "Pool" - -/** max size of memory pool name, in chars, including terminating zero char */ -#define LV2_RTSAFE_MEMORY_POOL_NAME_MAX 128 - -/** This extension used to be defined by a different URI */ -#define LV2_RTSAFE_MEMORY_POOL_DEPRECATED_URI "http://home.gna.org/lv2dynparam/rtmempool/v1" - -#ifdef __cplusplus -extern "C" { -#else -#include <stdbool.h> -#endif - -/** - * Opaque data to host data for LV2_RtMemPool_Pool. - */ -typedef void* LV2_RtMemPool_Handle; - -/** - * On instantiation, host must supply LV2_RTSAFE_MEMORY_POOL__Pool feature. - * LV2_Feature::data must be pointer to LV2_RtMemPool_Pool. - */ -typedef struct _LV2_RtMemPool_Pool { - /** - * This function is called when plugin wants to create memory pool - * - * <b>may/will sleep</b> - * - * @param pool_name pool name, for debug purposes, max RTSAFE_MEMORY_POOL_NAME_MAX chars, including terminating zero char. May be NULL. - * @param data_size memory chunk size - * @param min_preallocated min chunks preallocated - * @param max_preallocated max chunks preallocated - * - * @return Success status, true if successful - */ - bool (*create)(LV2_RtMemPool_Handle * handle_ptr, - const char * pool_name, - size_t data_size, - size_t min_preallocated, - size_t max_preallocated); - - /** - * This function is called when plugin wants to destroy previously created memory pool - * - * <b>may/will sleep</b> - */ - void (*destroy)(LV2_RtMemPool_Handle handle); - - /** - * This function is called when plugin wants to allocate memory in context where sleeping is not allowed - * - * <b>will not sleep</b> - * - * @return Pointer to allocated memory or NULL if memory no memory is available - */ - void * (*allocate_atomic)(LV2_RtMemPool_Handle handle); - - /** - * This function is called when plugin wants to allocate memory in context where sleeping is allowed - * - * <b>may/will sleep</b> - * - * @return Pointer to allocated memory or NULL if memory no memory is available (should not happen under normal conditions) - */ - void * (*allocate_sleepy)(LV2_RtMemPool_Handle handle); - - /** - * This function is called when plugin wants to deallocate previously allocated memory - * - * <b>will not sleep</b> - * - * @param memory_ptr pointer to previously allocated memory chunk - */ - void (*deallocate)(LV2_RtMemPool_Handle handle, - void * memory_ptr); - -} LV2_RtMemPool_Pool; - -/** - * Deprecated feature for backwards compatibility. - */ -typedef struct _LV2_RtMemPool_Pool_Deprecated { - unsigned char (*create)(const char*,size_t,size_t,size_t,LV2_RtMemPool_Handle*); - void (*destroy)(LV2_RtMemPool_Handle); - void* (*allocate_atomic)(LV2_RtMemPool_Handle); - void* (*allocate_sleepy)(LV2_RtMemPool_Handle); - void (*deallocate)(LV2_RtMemPool_Handle,void*); -} LV2_RtMemPool_Pool_Deprecated; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_RTMEMPOOL_H */ diff --git a/libs/distrho/src/lv2/midi.h b/libs/distrho/src/lv2/midi.h deleted file mode 100644 index 2c53c49..0000000 --- a/libs/distrho/src/lv2/midi.h +++ /dev/null @@ -1,226 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file midi.h - C definitions for the LV2 MIDI extension <http://lv2plug.in/ns/ext/midi>. -*/ - -#ifndef LV2_MIDI_H -#define LV2_MIDI_H - -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -#define LV2_MIDI_URI "http://lv2plug.in/ns/ext/midi" -#define LV2_MIDI_PREFIX LV2_MIDI_URI "#" - -#define LV2_MIDI__ActiveSense LV2_MIDI_PREFIX "ActiveSense" -#define LV2_MIDI__Aftertouch LV2_MIDI_PREFIX "Aftertouch" -#define LV2_MIDI__Bender LV2_MIDI_PREFIX "Bender" -#define LV2_MIDI__ChannelPressure LV2_MIDI_PREFIX "ChannelPressure" -#define LV2_MIDI__Chunk LV2_MIDI_PREFIX "Chunk" -#define LV2_MIDI__Clock LV2_MIDI_PREFIX "Clock" -#define LV2_MIDI__Continue LV2_MIDI_PREFIX "Continue" -#define LV2_MIDI__Controller LV2_MIDI_PREFIX "Controller" -#define LV2_MIDI__MidiEvent LV2_MIDI_PREFIX "MidiEvent" -#define LV2_MIDI__NoteOff LV2_MIDI_PREFIX "NoteOff" -#define LV2_MIDI__NoteOn LV2_MIDI_PREFIX "NoteOn" -#define LV2_MIDI__ProgramChange LV2_MIDI_PREFIX "ProgramChange" -#define LV2_MIDI__QuarterFrame LV2_MIDI_PREFIX "QuarterFrame" -#define LV2_MIDI__Reset LV2_MIDI_PREFIX "Reset" -#define LV2_MIDI__SongPosition LV2_MIDI_PREFIX "SongPosition" -#define LV2_MIDI__SongSelect LV2_MIDI_PREFIX "SongSelect" -#define LV2_MIDI__Start LV2_MIDI_PREFIX "Start" -#define LV2_MIDI__Stop LV2_MIDI_PREFIX "Stop" -#define LV2_MIDI__SystemCommon LV2_MIDI_PREFIX "SystemCommon" -#define LV2_MIDI__SystemExclusive LV2_MIDI_PREFIX "SystemExclusive" -#define LV2_MIDI__SystemMessage LV2_MIDI_PREFIX "SystemMessage" -#define LV2_MIDI__SystemRealtime LV2_MIDI_PREFIX "SystemRealtime" -#define LV2_MIDI__Tick LV2_MIDI_PREFIX "Tick" -#define LV2_MIDI__TuneRequest LV2_MIDI_PREFIX "TuneRequest" -#define LV2_MIDI__VoiceMessage LV2_MIDI_PREFIX "VoiceMessage" -#define LV2_MIDI__benderValue LV2_MIDI_PREFIX "benderValue" -#define LV2_MIDI__binding LV2_MIDI_PREFIX "binding" -#define LV2_MIDI__byteNumber LV2_MIDI_PREFIX "byteNumber" -#define LV2_MIDI__channel LV2_MIDI_PREFIX "channel" -#define LV2_MIDI__chunk LV2_MIDI_PREFIX "chunk" -#define LV2_MIDI__controllerNumber LV2_MIDI_PREFIX "controllerNumber" -#define LV2_MIDI__controllerValue LV2_MIDI_PREFIX "controllerValue" -#define LV2_MIDI__noteNumber LV2_MIDI_PREFIX "noteNumber" -#define LV2_MIDI__pressure LV2_MIDI_PREFIX "pressure" -#define LV2_MIDI__programNumber LV2_MIDI_PREFIX "programNumber" -#define LV2_MIDI__property LV2_MIDI_PREFIX "property" -#define LV2_MIDI__songNumber LV2_MIDI_PREFIX "songNumber" -#define LV2_MIDI__songPosition LV2_MIDI_PREFIX "songPosition" -#define LV2_MIDI__status LV2_MIDI_PREFIX "status" -#define LV2_MIDI__statusMask LV2_MIDI_PREFIX "statusMask" -#define LV2_MIDI__velocity LV2_MIDI_PREFIX "velocity" - -/** - MIDI Message Type. - - This includes both voice messages (which have a channel) and system messages - (which do not), as well as a sentinel value for invalid messages. To get - the type of a message suitable for use in a switch statement, use - lv2_midi_get_type() on the status byte. -*/ -typedef enum { - LV2_MIDI_MSG_INVALID = 0, /**< Invalid Message */ - LV2_MIDI_MSG_NOTE_OFF = 0x80, /**< Note Off */ - LV2_MIDI_MSG_NOTE_ON = 0x90, /**< Note On */ - LV2_MIDI_MSG_NOTE_PRESSURE = 0xA0, /**< Note Pressure */ - LV2_MIDI_MSG_CONTROLLER = 0xB0, /**< Controller */ - LV2_MIDI_MSG_PGM_CHANGE = 0xC0, /**< Program Change */ - LV2_MIDI_MSG_CHANNEL_PRESSURE = 0xD0, /**< Channel Pressure */ - LV2_MIDI_MSG_BENDER = 0xE0, /**< Pitch Bender */ - LV2_MIDI_MSG_SYSTEM_EXCLUSIVE = 0xF0, /**< System Exclusive Begin */ - LV2_MIDI_MSG_MTC_QUARTER = 0xF1, /**< MTC Quarter Frame */ - LV2_MIDI_MSG_SONG_POS = 0xF2, /**< Song Position */ - LV2_MIDI_MSG_SONG_SELECT = 0xF3, /**< Song Select */ - LV2_MIDI_MSG_TUNE_REQUEST = 0xF6, /**< Tune Request */ - LV2_MIDI_MSG_CLOCK = 0xF8, /**< Clock */ - LV2_MIDI_MSG_START = 0xFA, /**< Start */ - LV2_MIDI_MSG_CONTINUE = 0xFB, /**< Continue */ - LV2_MIDI_MSG_STOP = 0xFC, /**< Stop */ - LV2_MIDI_MSG_ACTIVE_SENSE = 0xFE, /**< Active Sensing */ - LV2_MIDI_MSG_RESET = 0xFF /**< Reset */ -} LV2_Midi_Message_Type; - -/** - Standard MIDI Controller Numbers. -*/ -typedef enum { - LV2_MIDI_CTL_MSB_BANK = 0x00, /**< Bank Selection */ - LV2_MIDI_CTL_MSB_MODWHEEL = 0x01, /**< Modulation */ - LV2_MIDI_CTL_MSB_BREATH = 0x02, /**< Breath */ - LV2_MIDI_CTL_MSB_FOOT = 0x04, /**< Foot */ - LV2_MIDI_CTL_MSB_PORTAMENTO_TIME = 0x05, /**< Portamento Time */ - LV2_MIDI_CTL_MSB_DATA_ENTRY = 0x06, /**< Data Entry */ - LV2_MIDI_CTL_MSB_MAIN_VOLUME = 0x07, /**< Main Volume */ - LV2_MIDI_CTL_MSB_BALANCE = 0x08, /**< Balance */ - LV2_MIDI_CTL_MSB_PAN = 0x0A, /**< Panpot */ - LV2_MIDI_CTL_MSB_EXPRESSION = 0x0B, /**< Expression */ - LV2_MIDI_CTL_MSB_EFFECT1 = 0x0C, /**< Effect1 */ - LV2_MIDI_CTL_MSB_EFFECT2 = 0x0D, /**< Effect2 */ - LV2_MIDI_CTL_MSB_GENERAL_PURPOSE1 = 0x10, /**< General Purpose 1 */ - LV2_MIDI_CTL_MSB_GENERAL_PURPOSE2 = 0x11, /**< General Purpose 2 */ - LV2_MIDI_CTL_MSB_GENERAL_PURPOSE3 = 0x12, /**< General Purpose 3 */ - LV2_MIDI_CTL_MSB_GENERAL_PURPOSE4 = 0x13, /**< General Purpose 4 */ - LV2_MIDI_CTL_LSB_BANK = 0x20, /**< Bank Selection */ - LV2_MIDI_CTL_LSB_MODWHEEL = 0x21, /**< Modulation */ - LV2_MIDI_CTL_LSB_BREATH = 0x22, /**< Breath */ - LV2_MIDI_CTL_LSB_FOOT = 0x24, /**< Foot */ - LV2_MIDI_CTL_LSB_PORTAMENTO_TIME = 0x25, /**< Portamento Time */ - LV2_MIDI_CTL_LSB_DATA_ENTRY = 0x26, /**< Data Entry */ - LV2_MIDI_CTL_LSB_MAIN_VOLUME = 0x27, /**< Main Volume */ - LV2_MIDI_CTL_LSB_BALANCE = 0x28, /**< Balance */ - LV2_MIDI_CTL_LSB_PAN = 0x2A, /**< Panpot */ - LV2_MIDI_CTL_LSB_EXPRESSION = 0x2B, /**< Expression */ - LV2_MIDI_CTL_LSB_EFFECT1 = 0x2C, /**< Effect1 */ - LV2_MIDI_CTL_LSB_EFFECT2 = 0x2D, /**< Effect2 */ - LV2_MIDI_CTL_LSB_GENERAL_PURPOSE1 = 0x30, /**< General Purpose 1 */ - LV2_MIDI_CTL_LSB_GENERAL_PURPOSE2 = 0x31, /**< General Purpose 2 */ - LV2_MIDI_CTL_LSB_GENERAL_PURPOSE3 = 0x32, /**< General Purpose 3 */ - LV2_MIDI_CTL_LSB_GENERAL_PURPOSE4 = 0x33, /**< General Purpose 4 */ - LV2_MIDI_CTL_SUSTAIN = 0x40, /**< Sustain Pedal */ - LV2_MIDI_CTL_PORTAMENTO = 0x41, /**< Portamento */ - LV2_MIDI_CTL_SOSTENUTO = 0x42, /**< Sostenuto */ - LV2_MIDI_CTL_SOFT_PEDAL = 0x43, /**< Soft Pedal */ - LV2_MIDI_CTL_LEGATO_FOOTSWITCH = 0x44, /**< Legato Foot Switch */ - LV2_MIDI_CTL_HOLD2 = 0x45, /**< Hold2 */ - LV2_MIDI_CTL_SC1_SOUND_VARIATION = 0x46, /**< SC1 Sound Variation */ - LV2_MIDI_CTL_SC2_TIMBRE = 0x47, /**< SC2 Timbre */ - LV2_MIDI_CTL_SC3_RELEASE_TIME = 0x48, /**< SC3 Release Time */ - LV2_MIDI_CTL_SC4_ATTACK_TIME = 0x49, /**< SC4 Attack Time */ - LV2_MIDI_CTL_SC5_BRIGHTNESS = 0x4A, /**< SC5 Brightness */ - LV2_MIDI_CTL_SC6 = 0x4B, /**< SC6 */ - LV2_MIDI_CTL_SC7 = 0x4C, /**< SC7 */ - LV2_MIDI_CTL_SC8 = 0x4D, /**< SC8 */ - LV2_MIDI_CTL_SC9 = 0x4E, /**< SC9 */ - LV2_MIDI_CTL_SC10 = 0x4F, /**< SC10 */ - LV2_MIDI_CTL_GENERAL_PURPOSE5 = 0x50, /**< General Purpose 5 */ - LV2_MIDI_CTL_GENERAL_PURPOSE6 = 0x51, /**< General Purpose 6 */ - LV2_MIDI_CTL_GENERAL_PURPOSE7 = 0x52, /**< General Purpose 7 */ - LV2_MIDI_CTL_GENERAL_PURPOSE8 = 0x53, /**< General Purpose 8 */ - LV2_MIDI_CTL_PORTAMENTO_CONTROL = 0x54, /**< Portamento Control */ - LV2_MIDI_CTL_E1_REVERB_DEPTH = 0x5B, /**< E1 Reverb Depth */ - LV2_MIDI_CTL_E2_TREMOLO_DEPTH = 0x5C, /**< E2 Tremolo Depth */ - LV2_MIDI_CTL_E3_CHORUS_DEPTH = 0x5D, /**< E3 Chorus Depth */ - LV2_MIDI_CTL_E4_DETUNE_DEPTH = 0x5E, /**< E4 Detune Depth */ - LV2_MIDI_CTL_E5_PHASER_DEPTH = 0x5F, /**< E5 Phaser Depth */ - LV2_MIDI_CTL_DATA_INCREMENT = 0x60, /**< Data Increment */ - LV2_MIDI_CTL_DATA_DECREMENT = 0x61, /**< Data Decrement */ - LV2_MIDI_CTL_NRPN_LSB = 0x62, /**< Non-registered Parameter Number */ - LV2_MIDI_CTL_NRPN_MSB = 0x63, /**< Non-registered Parameter Number */ - LV2_MIDI_CTL_RPN_LSB = 0x64, /**< Registered Parameter Number */ - LV2_MIDI_CTL_RPN_MSB = 0x65, /**< Registered Parameter Number */ - LV2_MIDI_CTL_ALL_SOUNDS_OFF = 0x78, /**< All Sounds Off */ - LV2_MIDI_CTL_RESET_CONTROLLERS = 0x79, /**< Reset Controllers */ - LV2_MIDI_CTL_LOCAL_CONTROL_SWITCH = 0x7A, /**< Local Control Switch */ - LV2_MIDI_CTL_ALL_NOTES_OFF = 0x7B, /**< All Notes Off */ - LV2_MIDI_CTL_OMNI_OFF = 0x7C, /**< Omni Off */ - LV2_MIDI_CTL_OMNI_ON = 0x7D, /**< Omni On */ - LV2_MIDI_CTL_MONO1 = 0x7E, /**< Mono1 */ - LV2_MIDI_CTL_MONO2 = 0x7F /**< Mono2 */ -} LV2_Midi_Controller; - -/** - Return true iff @p msg is a MIDI voice message (which has a channel). -*/ -static inline bool -lv2_midi_is_voice_message(const uint8_t* msg) { - return msg[0] >= 0x80 && msg[0] < 0xF0; -} - -/** - Return true iff @p msg is a MIDI system message (which has no channel). -*/ -static inline bool -lv2_midi_is_system_message(const uint8_t* msg) { - switch (msg[0]) { - case 0xF4: case 0xF5: case 0xF7: case 0xF9: case 0xFD: - return false; - default: - return (msg[0] & 0xF0) == 0xF0; - } -} - -/** - Return the type of a MIDI message. - @param msg Pointer to the start (status byte) of a MIDI message. -*/ -static inline LV2_Midi_Message_Type -lv2_midi_message_type(const uint8_t* msg) { - if (lv2_midi_is_voice_message(msg)) { - return (LV2_Midi_Message_Type)(msg[0] & 0xF0); - } else if (lv2_midi_is_system_message(msg)) { - return (LV2_Midi_Message_Type)msg[0]; - } else { - return LV2_MIDI_MSG_INVALID; - } -} - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_MIDI_H */ diff --git a/libs/distrho/src/lv2/morph.h b/libs/distrho/src/lv2/morph.h deleted file mode 100644 index df888df..0000000 --- a/libs/distrho/src/lv2/morph.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_MORPH_H -#define LV2_MORPH_H - -#include <stdint.h> - -#include "lv2.h" -#include "urid.h" - -#define LV2_MORPH_URI "http://lv2plug.in/ns/ext/morph" -#define LV2_MORPH_PREFIX LV2_MORPH_URI "#" - -#define LV2_MORPH__AutoMorphPort LV2_MORPH_PREFIX "AutoMorphPort" -#define LV2_MORPH__MorphPort LV2_MORPH_PREFIX "MorphPort" -#define LV2_MORPH__interface LV2_MORPH_PREFIX "interface" -#define LV2_MORPH__supportsType LV2_MORPH_PREFIX "supportsType" -#define LV2_MORPH__currentType LV2_MORPH_PREFIX "currentType" - -#endif /* LV2_MORPH_H */ diff --git a/libs/distrho/src/lv2/options.h b/libs/distrho/src/lv2/options.h deleted file mode 100644 index 5437db5..0000000 --- a/libs/distrho/src/lv2/options.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_OPTIONS_H -#define LV2_OPTIONS_H - -#include <stdint.h> - -#include "urid.h" -#include "lv2.h" - -#define LV2_OPTIONS_URI "http://lv2plug.in/ns/ext/options" -#define LV2_OPTIONS_PREFIX LV2_OPTIONS_URI "#" - -#define LV2_OPTIONS__Option LV2_OPTIONS_PREFIX "Option" -#define LV2_OPTIONS__interface LV2_OPTIONS_PREFIX "interface" -#define LV2_OPTIONS__options LV2_OPTIONS_PREFIX "options" -#define LV2_OPTIONS__requiredOption LV2_OPTIONS_PREFIX "requiredOption" -#define LV2_OPTIONS__supportedOption LV2_OPTIONS_PREFIX "supportedOption" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - The context of an Option, which defines the subject it applies to. -*/ -typedef enum { - /** - This option applies to the instance itself. The subject must be - ignored. - */ - LV2_OPTIONS_INSTANCE, - - /** - This option applies to some named resource. The subject is a URI mapped - to an integer (a LV2_URID, like the key) - */ - LV2_OPTIONS_RESOURCE, - - /** - This option applies to some blank node. The subject is a blank node - identifier, which is valid only within the current local scope. - */ - LV2_OPTIONS_BLANK, - - /** - This option applies to a port on the instance. The subject is the - port's index. - */ - LV2_OPTIONS_PORT -} LV2_Options_Context; - -/** - An option. - - This is a property with a subject, also known as a triple or statement. - - This struct is useful anywhere a statement needs to be passed where no - memory ownership issues are present (since the value is a const pointer). - - Options can be passed to an instance via the feature LV2_OPTIONS__options - with data pointed to an array of options terminated by a zeroed option, or - accessed/manipulated using LV2_Options_Interface. -*/ -typedef struct _LV2_Options_Option { - LV2_Options_Context context; /**< Context (type of subject). */ - uint32_t subject; /**< Subject. */ - LV2_URID key; /**< Key (property). */ - uint32_t size; /**< Size of value in bytes. */ - LV2_URID type; /**< Type of value (datatype). */ - const void* value; /**< Pointer to value (object). */ -} LV2_Options_Option; - -/** A status code for option functions. */ -typedef enum { - LV2_OPTIONS_SUCCESS = 0, /**< Completed successfully. */ - LV2_OPTIONS_ERR_UNKNOWN = 1, /**< Unknown error. */ - LV2_OPTIONS_ERR_BAD_SUBJECT = 1 << 1, /**< Invalid/unsupported subject. */ - LV2_OPTIONS_ERR_BAD_KEY = 1 << 2, /**< Invalid/unsupported key. */ - LV2_OPTIONS_ERR_BAD_VALUE = 1 << 3 /**< Invalid/unsupported value. */ -} LV2_Options_Status; - -/** - Interface for dynamically setting options (LV2_OPTIONS__interface). -*/ -typedef struct _LV2_Options_Interface { - /** - Get the given options. - - Each element of the passed options array MUST have type, subject, and - key set. All other fields (size, type, value) MUST be initialised to - zero, and are set to the option value if such an option is found. - - This function is in the "instantiation" LV2 threading class, so no other - instance functions may be called concurrently. - - @return Bitwise OR of LV2_Options_Status values. - */ - uint32_t (*get)(LV2_Handle instance, - LV2_Options_Option* options); - - /** - Set the given options. - - This function is in the "instantiation" LV2 threading class, so no other - instance functions may be called concurrently. - - @return Bitwise OR of LV2_Options_Status values. - */ - uint32_t (*set)(LV2_Handle instance, - const LV2_Options_Option* options); -} LV2_Options_Interface; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_OPTIONS_H */ diff --git a/libs/distrho/src/lv2/parameters.h b/libs/distrho/src/lv2/parameters.h deleted file mode 100644 index 9c06bab..0000000 --- a/libs/distrho/src/lv2/parameters.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_PARAMETERS_H -#define LV2_PARAMETERS_H - -#define LV2_PARAMETERS_URI "http://lv2plug.in/ns/ext/parameters" -#define LV2_PARAMETERS_PREFIX LV2_PARAMETERS_URI "#" - -#define LV2_PARAMETERS__CompressorControls LV2_PARAMETERS_PREFIX "CompressorControls" -#define LV2_PARAMETERS__ControlGroup LV2_PARAMETERS_PREFIX "ControlGroup" -#define LV2_PARAMETERS__EnvelopeControls LV2_PARAMETERS_PREFIX "EnvelopeControls" -#define LV2_PARAMETERS__FilterControls LV2_PARAMETERS_PREFIX "FilterControls" -#define LV2_PARAMETERS__OscillatorControls LV2_PARAMETERS_PREFIX "OscillatorControls" -#define LV2_PARAMETERS__amplitude LV2_PARAMETERS_PREFIX "amplitude" -#define LV2_PARAMETERS__attack LV2_PARAMETERS_PREFIX "attack" -#define LV2_PARAMETERS__bypass LV2_PARAMETERS_PREFIX "bypass" -#define LV2_PARAMETERS__cutoffFrequency LV2_PARAMETERS_PREFIX "cutoffFrequency" -#define LV2_PARAMETERS__decay LV2_PARAMETERS_PREFIX "decay" -#define LV2_PARAMETERS__delay LV2_PARAMETERS_PREFIX "delay" -#define LV2_PARAMETERS__dryLevel LV2_PARAMETERS_PREFIX "dryLevel" -#define LV2_PARAMETERS__frequency LV2_PARAMETERS_PREFIX "frequency" -#define LV2_PARAMETERS__gain LV2_PARAMETERS_PREFIX "gain" -#define LV2_PARAMETERS__hold LV2_PARAMETERS_PREFIX "hold" -#define LV2_PARAMETERS__pulseWidth LV2_PARAMETERS_PREFIX "pulseWidth" -#define LV2_PARAMETERS__ratio LV2_PARAMETERS_PREFIX "ratio" -#define LV2_PARAMETERS__release LV2_PARAMETERS_PREFIX "release" -#define LV2_PARAMETERS__resonance LV2_PARAMETERS_PREFIX "resonance" -#define LV2_PARAMETERS__sampleRate LV2_PARAMETERS_PREFIX "sampleRate" -#define LV2_PARAMETERS__sustain LV2_PARAMETERS_PREFIX "sustain" -#define LV2_PARAMETERS__threshold LV2_PARAMETERS_PREFIX "threshold" -#define LV2_PARAMETERS__waveform LV2_PARAMETERS_PREFIX "waveform" -#define LV2_PARAMETERS__wetDryRatio LV2_PARAMETERS_PREFIX "wetDryRatio" -#define LV2_PARAMETERS__wetLevel LV2_PARAMETERS_PREFIX "wetLevel" - -#endif /* LV2_PARAMETERS_H */ diff --git a/libs/distrho/src/lv2/patch.h b/libs/distrho/src/lv2/patch.h deleted file mode 100644 index 3224264..0000000 --- a/libs/distrho/src/lv2/patch.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file patch.h C header for the LV2 Patch extension - <http://lv2plug.in/ns/ext/patch>. - - The patch extension is purely data, this header merely defines URIs - for convenience. -*/ - -#ifndef LV2_PATCH_H -#define LV2_PATCH_H - -#define LV2_PATCH_URI "http://lv2plug.in/ns/ext/patch" -#define LV2_PATCH_PREFIX LV2_PATCH_URI "#" - -#define LV2_PATCH__Ack LV2_PATCH_PREFIX "Ack" -#define LV2_PATCH__Delete LV2_PATCH_PREFIX "Delete" -#define LV2_PATCH__Error LV2_PATCH_PREFIX "Error" -#define LV2_PATCH__Get LV2_PATCH_PREFIX "Get" -#define LV2_PATCH__Message LV2_PATCH_PREFIX "Message" -#define LV2_PATCH__Move LV2_PATCH_PREFIX "Move" -#define LV2_PATCH__Patch LV2_PATCH_PREFIX "Patch" -#define LV2_PATCH__Post LV2_PATCH_PREFIX "Post" -#define LV2_PATCH__Put LV2_PATCH_PREFIX "Put" -#define LV2_PATCH__Request LV2_PATCH_PREFIX "Request" -#define LV2_PATCH__Response LV2_PATCH_PREFIX "Response" -#define LV2_PATCH__Set LV2_PATCH_PREFIX "Set" -#define LV2_PATCH__add LV2_PATCH_PREFIX "add" -#define LV2_PATCH__body LV2_PATCH_PREFIX "body" -#define LV2_PATCH__destination LV2_PATCH_PREFIX "destination" -#define LV2_PATCH__property LV2_PATCH_PREFIX "property" -#define LV2_PATCH__readable LV2_PATCH_PREFIX "readable" -#define LV2_PATCH__remove LV2_PATCH_PREFIX "remove" -#define LV2_PATCH__request LV2_PATCH_PREFIX "request" -#define LV2_PATCH__subject LV2_PATCH_PREFIX "subject" -#define LV2_PATCH__sequenceNumber LV2_PATCH_PREFIX "sequenceNumber" -#define LV2_PATCH__value LV2_PATCH_PREFIX "value" -#define LV2_PATCH__wildcard LV2_PATCH_PREFIX "wildcard" -#define LV2_PATCH__writable LV2_PATCH_PREFIX "writable" - -#endif /* LV2_PATCH_H */ diff --git a/libs/distrho/src/lv2/port-groups.h b/libs/distrho/src/lv2/port-groups.h deleted file mode 100644 index 4dd8cf4..0000000 --- a/libs/distrho/src/lv2/port-groups.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file port-groups.h - C definitions for the LV2 Port Groups extension - <http://lv2plug.in/ns/ext/port-groups>. -*/ - -#ifndef LV2_PORT_GROUPS_H -#define LV2_PORT_GROUPS_H - -#define LV2_PORT_GROUPS_URI "http://lv2plug.in/ns/ext/port-groups" -#define LV2_PORT_GROUPS_PREFIX LV2_PORT_GROUPS_URI "#" - -#define LV2_PORT_GROUPS__DiscreteGroup LV2_PORT_GROUPS_PREFIX "DiscreteGroup" -#define LV2_PORT_GROUPS__Element LV2_PORT_GROUPS_PREFIX "Element" -#define LV2_PORT_GROUPS__FivePointOneGroup LV2_PORT_GROUPS_PREFIX "FivePointOneGroup" -#define LV2_PORT_GROUPS__FivePointZeroGroup LV2_PORT_GROUPS_PREFIX "FivePointZeroGroup" -#define LV2_PORT_GROUPS__FourPointZeroGroup LV2_PORT_GROUPS_PREFIX "FourPointZeroGroup" -#define LV2_PORT_GROUPS__Group LV2_PORT_GROUPS_PREFIX "Group" -#define LV2_PORT_GROUPS__InputGroup LV2_PORT_GROUPS_PREFIX "InputGroup" -#define LV2_PORT_GROUPS__MidSideGroup LV2_PORT_GROUPS_PREFIX "MidSideGroup" -#define LV2_PORT_GROUPS__MonoGroup LV2_PORT_GROUPS_PREFIX "MonoGroup" -#define LV2_PORT_GROUPS__OutputGroup LV2_PORT_GROUPS_PREFIX "OutputGroup" -#define LV2_PORT_GROUPS__SevenPointOneGroup LV2_PORT_GROUPS_PREFIX "SevenPointOneGroup" -#define LV2_PORT_GROUPS__SevenPointOneWideGroup LV2_PORT_GROUPS_PREFIX "SevenPointOneWideGroup" -#define LV2_PORT_GROUPS__SixPointOneGroup LV2_PORT_GROUPS_PREFIX "SixPointOneGroup" -#define LV2_PORT_GROUPS__StereoGroup LV2_PORT_GROUPS_PREFIX "StereoGroup" -#define LV2_PORT_GROUPS__ThreePointZeroGroup LV2_PORT_GROUPS_PREFIX "ThreePointZeroGroup" -#define LV2_PORT_GROUPS__center LV2_PORT_GROUPS_PREFIX "center" -#define LV2_PORT_GROUPS__centerLeft LV2_PORT_GROUPS_PREFIX "centerLeft" -#define LV2_PORT_GROUPS__centerRight LV2_PORT_GROUPS_PREFIX "centerRight" -#define LV2_PORT_GROUPS__element LV2_PORT_GROUPS_PREFIX "element" -#define LV2_PORT_GROUPS__group LV2_PORT_GROUPS_PREFIX "group" -#define LV2_PORT_GROUPS__left LV2_PORT_GROUPS_PREFIX "left" -#define LV2_PORT_GROUPS__lowFrequencyEffects LV2_PORT_GROUPS_PREFIX "lowFrequencyEffects" -#define LV2_PORT_GROUPS__mainInput LV2_PORT_GROUPS_PREFIX "mainInput" -#define LV2_PORT_GROUPS__mainOutput LV2_PORT_GROUPS_PREFIX "mainOutput" -#define LV2_PORT_GROUPS__rearCenter LV2_PORT_GROUPS_PREFIX "rearCenter" -#define LV2_PORT_GROUPS__rearLeft LV2_PORT_GROUPS_PREFIX "rearLeft" -#define LV2_PORT_GROUPS__rearRight LV2_PORT_GROUPS_PREFIX "rearRight" -#define LV2_PORT_GROUPS__right LV2_PORT_GROUPS_PREFIX "right" -#define LV2_PORT_GROUPS__side LV2_PORT_GROUPS_PREFIX "side" -#define LV2_PORT_GROUPS__sideChainOf LV2_PORT_GROUPS_PREFIX "sideChainOf" -#define LV2_PORT_GROUPS__sideLeft LV2_PORT_GROUPS_PREFIX "sideLeft" -#define LV2_PORT_GROUPS__sideRight LV2_PORT_GROUPS_PREFIX "sideRight" -#define LV2_PORT_GROUPS__source LV2_PORT_GROUPS_PREFIX "source" -#define LV2_PORT_GROUPS__subGroupOf LV2_PORT_GROUPS_PREFIX "subGroupOf" - -#endif /* LV2_PORT_GROUPS_H */ diff --git a/libs/distrho/src/lv2/port-props.h b/libs/distrho/src/lv2/port-props.h deleted file mode 100644 index 11274cc..0000000 --- a/libs/distrho/src/lv2/port-props.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file port-props.h - C definitions for the LV2 Port Props extension - <http://lv2plug.in/ns/ext/port-props>. -*/ - -#ifndef LV2_PORT_PROPS_H -#define LV2_PORT_PROPS_H - -#define LV2_PORT_PROPS_URI "http://lv2plug.in/ns/ext/port-props" -#define LV2_PORT_PROPS_PREFIX LV2_PORT_PROPS_URI "#" - -#define LV2_PORT_PROPS__causesArtifacts LV2_PORT_PROPS_PREFIX "causesArtifacts" -#define LV2_PORT_PROPS__continuousCV LV2_PORT_PROPS_PREFIX "continuousCV" -#define LV2_PORT_PROPS__discreteCV LV2_PORT_PROPS_PREFIX "discreteCV" -#define LV2_PORT_PROPS__displayPriority LV2_PORT_PROPS_PREFIX "displayPriority" -#define LV2_PORT_PROPS__expensive LV2_PORT_PROPS_PREFIX "expensive" -#define LV2_PORT_PROPS__hasStrictBounds LV2_PORT_PROPS_PREFIX "hasStrictBounds" -#define LV2_PORT_PROPS__logarithmic LV2_PORT_PROPS_PREFIX "logarithmic" -#define LV2_PORT_PROPS__notAutomatic LV2_PORT_PROPS_PREFIX "notAutomatic" -#define LV2_PORT_PROPS__notOnGUI LV2_PORT_PROPS_PREFIX "notOnGUI" -#define LV2_PORT_PROPS__rangeSteps LV2_PORT_PROPS_PREFIX "rangeSteps" -#define LV2_PORT_PROPS__supportsStrictBounds LV2_PORT_PROPS_PREFIX "supportsStrictBounds" -#define LV2_PORT_PROPS__trigger LV2_PORT_PROPS_PREFIX "trigger" - -#endif /* LV2_PORT_PROPS_H */ diff --git a/libs/distrho/src/lv2/presets.h b/libs/distrho/src/lv2/presets.h deleted file mode 100644 index 4851feb..0000000 --- a/libs/distrho/src/lv2/presets.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file presets.h - - C definitions for the LV2 Presets extension - <http://lv2plug.in/ns/ext/presets>. -*/ - -#ifndef LV2_PRESETS_H -#define LV2_PRESETS_H - -#define LV2_PRESETS_URI "http://lv2plug.in/ns/ext/presets" -#define LV2_PRESETS_PREFIX LV2_PRESETS_URI "#" - -#define LV2_PRESETS__Preset LV2_PRESETS_PREFIX "Preset" -#define LV2_PRESETS__preset LV2_PRESETS_PREFIX "preset" -#define LV2_PRESETS__value LV2_PRESETS_PREFIX "value" - -#endif /* LV2_PRESETS_H */ diff --git a/libs/distrho/src/lv2/resize-port.h b/libs/distrho/src/lv2/resize-port.h deleted file mode 100644 index fa3abd7..0000000 --- a/libs/distrho/src/lv2/resize-port.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright 2007-2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -#ifndef LV2_RESIZE_PORT_H -#define LV2_RESIZE_PORT_H - -#include <stddef.h> -#include <stdint.h> - -#define LV2_RESIZE_PORT_URI "http://lv2plug.in/ns/ext/resize-port" -#define LV2_RESIZE_PORT_PREFIX LV2_RESIZE_PORT_URI "#" - -#define LV2_RESIZE_PORT__asLargeAs LV2_RESIZE_PORT_PREFIX "asLargeAs" -#define LV2_RESIZE_PORT__minimumSize LV2_RESIZE_PORT_PREFIX "minimumSize" -#define LV2_RESIZE_PORT__resize LV2_RESIZE_PORT_PREFIX "resize" - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** A status code for state functions. */ -typedef enum { - LV2_RESIZE_PORT_SUCCESS = 0, /**< Completed successfully. */ - LV2_RESIZE_PORT_ERR_UNKNOWN = 1, /**< Unknown error. */ - LV2_RESIZE_PORT_ERR_NO_SPACE = 2 /**< Insufficient space. */ -} LV2_Resize_Port_Status; - -typedef void* LV2_Resize_Port_Feature_Data; - -typedef struct { - LV2_Resize_Port_Feature_Data data; - - /** - Resize a port buffer to at least @a size bytes. - - This function MAY return an error, in which case the port buffer was not - resized and the port is still connected to the same location. Plugins - MUST gracefully handle this situation. - - This function is in the audio threading class. - - The host MUST preserve the contents of the port buffer when resizing. - - Plugins MAY resize a port many times in a single run callback. Hosts - SHOULD make this as inexpensive as possible. - */ - LV2_Resize_Port_Status (*resize)(LV2_Resize_Port_Feature_Data data, - uint32_t index, - size_t size); -} LV2_Resize_Port_Resize; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_RESIZE_PORT_H */ - diff --git a/libs/distrho/src/lv2/state.h b/libs/distrho/src/lv2/state.h deleted file mode 100644 index 09787d9..0000000 --- a/libs/distrho/src/lv2/state.h +++ /dev/null @@ -1,352 +0,0 @@ -/* - Copyright 2010-2012 David Robillard <http://drobilla.net> - Copyright 2010 Leonard Ritter <paniq@paniq.org> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file state.h - C API for the LV2 State extension <http://lv2plug.in/ns/ext/state>. -*/ - -#ifndef LV2_STATE_H -#define LV2_STATE_H - -#include <stddef.h> -#include <stdint.h> - -#include "lv2.h" - -#define LV2_STATE_URI "http://lv2plug.in/ns/ext/state" -#define LV2_STATE_PREFIX LV2_STATE_URI "#" - -#define LV2_STATE__State LV2_STATE_PREFIX "State" -#define LV2_STATE__interface LV2_STATE_PREFIX "interface" -#define LV2_STATE__loadDefaultState LV2_STATE_PREFIX "loadDefaultState" -#define LV2_STATE__makePath LV2_STATE_PREFIX "makePath" -#define LV2_STATE__mapPath LV2_STATE_PREFIX "mapPath" -#define LV2_STATE__state LV2_STATE_PREFIX "state" - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -typedef void* LV2_State_Handle; -typedef void* LV2_State_Map_Path_Handle; -typedef void* LV2_State_Make_Path_Handle; - -/** - Flags describing value characteristics. - - These flags are used along with the value's type URI to determine how to - (de-)serialise the value data, or whether it is even possible to do so. -*/ -typedef enum { - /** - Plain Old Data. - - Values with this flag contain no pointers or references to other areas - of memory. It is safe to copy POD values with a simple memcpy and store - them for the duration of the process. A POD value is not necessarily - safe to trasmit between processes or machines (e.g. filenames are POD), - see LV2_STATE_IS_PORTABLE for details. - - Implementations MUST NOT attempt to copy or serialise a non-POD value if - they do not understand its type (and thus know how to correctly do so). - */ - LV2_STATE_IS_POD = 1, - - /** - Portable (architecture independent) data. - - Values with this flag are in a format that is usable on any - architecture. A portable value saved on one machine can be restored on - another machine regardless of architecture. The format of portable - values MUST NOT depend on architecture-specific properties like - endianness or alignment. Portable values MUST NOT contain filenames. - */ - LV2_STATE_IS_PORTABLE = 1 << 1, - - /** - Native data. - - This flag is used by the host to indicate that the saved data is only - going to be used locally in the currently running process (e.g. for - instance duplication or snapshots), so the plugin should use the most - efficient representation possible and not worry about serialisation - and portability. - */ - LV2_STATE_IS_NATIVE = 1 << 2 -} LV2_State_Flags; - -/** A status code for state functions. */ -typedef enum { - LV2_STATE_SUCCESS = 0, /**< Completed successfully. */ - LV2_STATE_ERR_UNKNOWN = 1, /**< Unknown error. */ - LV2_STATE_ERR_BAD_TYPE = 2, /**< Failed due to unsupported type. */ - LV2_STATE_ERR_BAD_FLAGS = 3, /**< Failed due to unsupported flags. */ - LV2_STATE_ERR_NO_FEATURE = 4, /**< Failed due to missing features. */ - LV2_STATE_ERR_NO_PROPERTY = 5 /**< Failed due to missing property. */ -} LV2_State_Status; - -/** - A host-provided function to store a property. - @param handle Must be the handle passed to LV2_State_Interface.save(). - @param key The key to store @p value under (URID). - @param value Pointer to the value to be stored. - @param size The size of @p value in bytes. - @param type The type of @p value (URID). - @param flags LV2_State_Flags for @p value. - @return 0 on success, otherwise a non-zero error code. - - The host passes a callback of this type to LV2_State_Interface.save(). This - callback is called repeatedly by the plugin to store all the properties that - describe its current state. - - DO NOT INVENT NONSENSE URI SCHEMES FOR THE KEY. Best is to use keys from - existing vocabularies. If nothing appropriate is available, use http URIs - that point to somewhere you can host documents so documentation can be made - resolvable (e.g. a child of the plugin or project URI). If this is not - possible, invent a URN scheme, e.g. urn:myproj:whatever. The plugin MUST - NOT pass an invalid URI key. - - The host MAY fail to store a property for whatever reason, but SHOULD - store any property that is LV2_STATE_IS_POD and LV2_STATE_IS_PORTABLE. - Implementations SHOULD use the types from the LV2 Atom extension - (http://lv2plug.in/ns/ext/atom) wherever possible. The plugin SHOULD - attempt to fall-back and avoid the error if possible. - - Note that @p size MUST be > 0, and @p value MUST point to a valid region of - memory @p size bytes long (this is required to make restore unambiguous). - - The plugin MUST NOT attempt to use this function outside of the - LV2_State_Interface.restore() context. -*/ -typedef LV2_State_Status (*LV2_State_Store_Function)( - LV2_State_Handle handle, - uint32_t key, - const void* value, - size_t size, - uint32_t type, - uint32_t flags); - -/** - A host-provided function to retrieve a property. - @param handle Must be the handle passed to LV2_State_Interface.restore(). - @param key The key of the property to retrieve (URID). - @param size (Output) If non-NULL, set to the size of the restored value. - @param type (Output) If non-NULL, set to the type of the restored value. - @param flags (Output) If non-NULL, set to the flags for the restored value. - @return A pointer to the restored value (object), or NULL if no value - has been stored under @p key. - - A callback of this type is passed by the host to - LV2_State_Interface.restore(). This callback is called repeatedly by the - plugin to retrieve any properties it requires to restore its state. - - The returned value MUST remain valid until LV2_State_Interface.restore() - returns. The plugin MUST NOT attempt to use this function, or any value - returned from it, outside of the LV2_State_Interface.restore() context. -*/ -typedef const void* (*LV2_State_Retrieve_Function)( - LV2_State_Handle handle, - uint32_t key, - size_t* size, - uint32_t* type, - uint32_t* flags); - -/** - LV2 Plugin State Interface. - - When the plugin's extension_data is called with argument - LV2_STATE__interface, the plugin MUST return an LV2_State_Interface - structure, which remains valid for the lifetime of the plugin. - - The host can use the contained function pointers to save and restore the - state of a plugin instance at any time, provided the threading restrictions - of the functions are met. - - Stored data is only guaranteed to be compatible between instances of plugins - with the same URI (i.e. if a change to a plugin would cause a fatal error - when restoring state saved by a previous version of that plugin, the plugin - URI MUST change just as it must when ports change incompatibly). Plugin - authors should consider this possibility, and always store sensible data - with meaningful types to avoid such problems in the future. -*/ -typedef struct _LV2_State_Interface { - /** - Save plugin state using a host-provided @p store callback. - - @param instance The instance handle of the plugin. - @param store The host-provided store callback. - @param handle An opaque pointer to host data which MUST be passed as the - handle parameter to @p store if it is called. - @param flags Flags describing desired properties of this save. These - flags may be used to determine the most appropriate values to store. - @param features Extensible parameter for passing any additional - features to be used for this save. - - The plugin is expected to store everything necessary to completely - restore its state later. Plugins SHOULD store simple POD data whenever - possible, and consider the possibility of state being restored much - later on a different machine. - - The @p handle pointer and @p store function MUST NOT be used - beyond the scope of save(). - - This function has its own special threading class: it may not be called - concurrently with any "Instantiation" function, but it may be called - concurrently with functions in any other class, unless the definition of - that class prohibits it (e.g. it may not be called concurrently with a - "Discovery" function, but it may be called concurrently with an "Audio" - function. The plugin is responsible for any locking or lock-free - techniques necessary to make this possible. - - Note that in the simple case where state is only modified by restore(), - there are no synchronization issues since save() is never called - concurrently with restore() (though run() may read it during a save). - - Plugins that dynamically modify state while running, however, must take - care to do so in such a way that a concurrent call to save() will save a - consistent representation of plugin state for a single instant in time. - */ - LV2_State_Status (*save)(LV2_Handle instance, - LV2_State_Store_Function store, - LV2_State_Handle handle, - uint32_t flags, - const LV2_Feature *const * features); - - /** - Restore plugin state using a host-provided @p retrieve callback. - - @param instance The instance handle of the plugin. - @param retrieve The host-provided retrieve callback. - @param handle An opaque pointer to host data which MUST be passed as the - handle parameter to @p retrieve if it is called. - @param flags Currently unused. - @param features Extensible parameter for passing any additional - features to be used for this restore. - - The plugin MAY assume a restored value was set by a previous call to - LV2_State_Interface.save() by a plugin with the same URI. - - The plugin MUST gracefully fall back to a default value when a value can - not be retrieved. This allows the host to reset the plugin state with - an empty map. - - The @p handle pointer and @p store function MUST NOT be used - beyond the scope of restore(). - - This function is in the "Instantiation" threading class as defined by - LV2. This means it MUST NOT be called concurrently with any other - function on the same plugin instance. - */ - LV2_State_Status (*restore)(LV2_Handle instance, - LV2_State_Retrieve_Function retrieve, - LV2_State_Handle handle, - uint32_t flags, - const LV2_Feature *const * features); -} LV2_State_Interface; - -/** - Feature data for state:mapPath (LV2_STATE__mapPath). -*/ -typedef struct { - /** - Opaque host data. - */ - LV2_State_Map_Path_Handle handle; - - /** - Map an absolute path to an abstract path for use in plugin state. - @param handle MUST be the @p handle member of this struct. - @param absolute_path The absolute path of a file. - @return An abstract path suitable for use in plugin state. - - The plugin MUST use this function to map any paths that will be stored - in plugin state. The returned value is an abstract path which MAY not - be an actual file system path; @ref absolute_path() MUST be used to map - it to an actual path in order to use the file. - - Plugins MUST NOT make any assumptions about abstract paths except that - they can be mapped back to the absolute path of the "same" file (though - not necessarily the same original path) using @ref absolute_path(). - - This function may only be called within the context of - LV2_State_Interface methods. The caller is responsible for freeing the - returned value with free(). - */ - char* (*abstract_path)(LV2_State_Map_Path_Handle handle, - const char* absolute_path); - - /** - Map an abstract path from plugin state to an absolute path. - @param handle MUST be the @p handle member of this struct. - @param abstract_path An abstract path (e.g. a path from plugin state). - @return An absolute file system path. - - The plugin MUST use this function in order to actually open or otherwise - use any paths loaded from plugin state. - - This function may only be called within the context of - LV2_State_Interface methods. The caller is responsible for freeing the - returned value with free(). - */ - char* (*absolute_path)(LV2_State_Map_Path_Handle handle, - const char* abstract_path); -} LV2_State_Map_Path; - -/** - Feature data for state:makePath (@ref LV2_STATE__makePath). -*/ -typedef struct { - /** - Opaque host data. - */ - LV2_State_Make_Path_Handle handle; - - /** - Return a path the plugin may use to create a new file. - @param handle MUST be the @p handle member of this struct. - @param path The path of the new file within a namespace unique to this - plugin instance. - @return The absolute path to use for the new file. - - This function can be used by plugins to create files and directories, - either at state saving time (if this feature is passed to - LV2_State_Interface.save()) or any time (if this feature is passed to - LV2_Descriptor.instantiate()). - - The host MUST do whatever is necessary for the plugin to be able to - create a file at the returned path (e.g. using fopen), including - creating any leading directories. - - If this function is passed to LV2_Descriptor.instantiate(), it may be - called from any non-realtime context. If it is passed to - LV2_State_Interface.save(), it may only be called within the dynamic - scope of that function call. - - The caller is responsible for freeing the returned value with free(). - */ - char* (*path)(LV2_State_Make_Path_Handle handle, - const char* path); -} LV2_State_Make_Path; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_STATE_H */ diff --git a/libs/distrho/src/lv2/time.h b/libs/distrho/src/lv2/time.h deleted file mode 100644 index 3bb0614..0000000 --- a/libs/distrho/src/lv2/time.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright 2011 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file time.h C header for the LV2 Time extension - <http://lv2plug.in/ns/ext/time>. -*/ - -#ifndef LV2_TIME_H -#define LV2_TIME_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define LV2_TIME_URI "http://lv2plug.in/ns/ext/time" - -#define LV2_TIME__Time LV2_TIME_URI "#Time" -#define LV2_TIME__Position LV2_TIME_URI "#Position" -#define LV2_TIME__Rate LV2_TIME_URI "#Rate" -#define LV2_TIME__position LV2_TIME_URI "#position" -#define LV2_TIME__barBeat LV2_TIME_URI "#barBeat" -#define LV2_TIME__bar LV2_TIME_URI "#bar" -#define LV2_TIME__beat LV2_TIME_URI "#beat" -#define LV2_TIME__beatUnit LV2_TIME_URI "#beatUnit" -#define LV2_TIME__beatsPerBar LV2_TIME_URI "#beatsPerBar" -#define LV2_TIME__beatsPerMinute LV2_TIME_URI "#beatsPerMinute" -#define LV2_TIME__frame LV2_TIME_URI "#frame" -#define LV2_TIME__framesPerSecond LV2_TIME_URI "#framesPerSecond" -#define LV2_TIME__speed LV2_TIME_URI "#speed" - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_TIME_H */ diff --git a/libs/distrho/src/lv2/ui.h b/libs/distrho/src/lv2/ui.h deleted file mode 100644 index 9ee4bd1..0000000 --- a/libs/distrho/src/lv2/ui.h +++ /dev/null @@ -1,430 +0,0 @@ -/* - LV2 UI Extension - Copyright 2009-2014 David Robillard <d@drobilla.net> - Copyright 2006-2011 Lars Luthman <lars.luthman@gmail.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file ui.h User Interface API. - - For high-level documentation, see <http://lv2plug.in/ns/extensions/ui>. -*/ - -#ifndef LV2_UI_H -#define LV2_UI_H - -#include <stdint.h> - -#include "lv2.h" - -#define LV2_UI_URI "http://lv2plug.in/ns/extensions/ui" -#define LV2_UI_PREFIX LV2_UI_URI "#" - -#define LV2_UI__CocoaUI LV2_UI_PREFIX "CocoaUI" -#define LV2_UI__Gtk3UI LV2_UI_PREFIX "Gtk3UI" -#define LV2_UI__GtkUI LV2_UI_PREFIX "GtkUI" -#define LV2_UI__PortNotification LV2_UI_PREFIX "PortNotification" -#define LV2_UI__Qt4UI LV2_UI_PREFIX "Qt4UI" -#define LV2_UI__UI LV2_UI_PREFIX "UI" -#define LV2_UI__WindowsUI LV2_UI_PREFIX "WindowsUI" -#define LV2_UI__X11UI LV2_UI_PREFIX "X11UI" -#define LV2_UI__binary LV2_UI_PREFIX "binary" -#define LV2_UI__fixedSize LV2_UI_PREFIX "fixedSize" -#define LV2_UI__idleInterface LV2_UI_PREFIX "idleInterface" -#define LV2_UI__noUserResize LV2_UI_PREFIX "noUserResize" -#define LV2_UI__notifyType LV2_UI_PREFIX "notifyType" -#define LV2_UI__parent LV2_UI_PREFIX "parent" -#define LV2_UI__plugin LV2_UI_PREFIX "plugin" -#define LV2_UI__portIndex LV2_UI_PREFIX "portIndex" -#define LV2_UI__portMap LV2_UI_PREFIX "portMap" -#define LV2_UI__portNotification LV2_UI_PREFIX "portNotification" -#define LV2_UI__portSubscribe LV2_UI_PREFIX "portSubscribe" -#define LV2_UI__resize LV2_UI_PREFIX "resize" -#define LV2_UI__showInterface LV2_UI_PREFIX "showInterface" -#define LV2_UI__touch LV2_UI_PREFIX "touch" -#define LV2_UI__ui LV2_UI_PREFIX "ui" -#define LV2_UI__updateRate LV2_UI_PREFIX "updateRate" -#define LV2_UI__windowTitle LV2_UI_PREFIX "windowTitle" - -/** - The index returned by LV2_UI_Port_Port::port_index() for unknown ports. -*/ -#define LV2UI_INVALID_PORT_INDEX ((uint32_t)-1) - -#ifdef __cplusplus -extern "C" { -#else -# include <stdbool.h> -#endif - -/** - A pointer to some widget or other type of UI handle. - - The actual type is defined by the type of the UI. -*/ -typedef void* LV2UI_Widget; - -/** - A pointer to UI instance internals. - - The host may compare this to NULL, but otherwise MUST NOT interpret it. -*/ -typedef void* LV2UI_Handle; - -/** - A pointer to a controller provided by the host. - - The UI may compare this to NULL, but otherwise MUST NOT interpret it. -*/ -typedef void* LV2UI_Controller; - -/** - A pointer to opaque data for a feature. -*/ -typedef void* LV2UI_Feature_Handle; - -/** - A host-provided function that sends data to a plugin's input ports. - - The @p buffer parameter must point to a block of data, @p buffer_size bytes - large. The format of this data and how the host should use it is defined by - the @p port_protocol. This buffer is owned by the UI and is only valid for - the duration of this call. - - The @p port_protocol parameter should either be 0 or the URID for a - ui:PortProtocol. If it is 0, the protocol is implicitly ui:floatProtocol, - the port MUST be an lv2:ControlPort input, @p buffer MUST point to a single - float value, and @p buffer_size MUST be sizeof(float). - - The UI SHOULD NOT use a protocol not supported by the host, but the host - MUST gracefully ignore any protocol it does not understand. -*/ -typedef void (*LV2UI_Write_Function)(LV2UI_Controller controller, - uint32_t port_index, - uint32_t buffer_size, - uint32_t port_protocol, - const void* buffer); - -/** - A plugin UI. - - A pointer to an object of this type is returned by the lv2ui_descriptor() - function. -*/ -typedef struct _LV2UI_Descriptor { - /** - The URI for this UI (not for the plugin it controls). - */ - const char* URI; - - /** - Create a new UI and return a handle to it. This function works - similarly to LV2_Descriptor::instantiate(). - - @param descriptor The descriptor for the UI to instantiate. - - @param plugin_uri The URI of the plugin that this UI will control. - - @param bundle_path The path to the bundle containing this UI, including - the trailing directory separator. - - @param write_function A function that the UI can use to send data to the - plugin's input ports. - - @param controller A handle for the plugin instance to be passed as the - first parameter of UI methods. - - @param widget (output) widget pointer. The UI points this at its main - widget, which has the type defined by the UI type in the data file. - - @param features An array of LV2_Feature pointers. The host must pass - all feature URIs that it and the UI supports and any additional data, as - in LV2_Descriptor::instantiate(). Note that UI features and plugin - features are not necessarily the same. - - */ - LV2UI_Handle (*instantiate)(const struct _LV2UI_Descriptor* descriptor, - const char* plugin_uri, - const char* bundle_path, - LV2UI_Write_Function write_function, - LV2UI_Controller controller, - LV2UI_Widget* widget, - const LV2_Feature* const* features); - - - /** - Destroy the UI. The host must not try to access the widget after - calling this function. - */ - void (*cleanup)(LV2UI_Handle ui); - - /** - Tell the UI that something interesting has happened at a plugin port. - - What is "interesting" and how it is written to @p buffer is defined by - @p format, which has the same meaning as in LV2UI_Write_Function(). - Format 0 is a special case for lv2:ControlPort, where this function - should be called when the port value changes (but not necessarily for - every change), @p buffer_size must be sizeof(float), and @p buffer - points to a single IEEE-754 float. - - By default, the host should only call this function for lv2:ControlPort - inputs. However, the UI can request updates for other ports statically - with ui:portNotification or dynamicaly with ui:portSubscribe. - - The UI MUST NOT retain any reference to @p buffer after this function - returns, it is only valid for the duration of the call. - - This member may be NULL if the UI is not interested in any port events. - */ - void (*port_event)(LV2UI_Handle ui, - uint32_t port_index, - uint32_t buffer_size, - uint32_t format, - const void* buffer); - - /** - Return a data structure associated with an extension URI, typically an - interface struct with additional function pointers - - This member may be set to NULL if the UI is not interested in supporting - any extensions. This is similar to LV2_Descriptor::extension_data(). - - */ - const void* (*extension_data)(const char* uri); -} LV2UI_Descriptor; - -/** - Feature/interface for resizable UIs (LV2_UI__resize). - - This structure is used in two ways: as a feature passed by the host via - LV2UI_Descriptor::instantiate(), or as an interface provided by a UI via - LV2UI_Descriptor::extension_data()). -*/ -typedef struct _LV2UI_Resize { - /** - Pointer to opaque data which must be passed to ui_resize(). - */ - LV2UI_Feature_Handle handle; - - /** - Request/advertise a size change. - - When provided by the host, the UI may call this function to inform the - host about the size of the UI. - - When provided by the UI, the host may call this function to notify the - UI that it should change its size accordingly. - - @return 0 on success. - */ - int (*ui_resize)(LV2UI_Feature_Handle handle, int width, int height); -} LV2UI_Resize; - -/** - Feature to map port symbols to UIs. - - This can be used by the UI to get the index for a port with the given - symbol. This makes it possible to implement and distribute a UI separately - from the plugin (since symbol, unlike index, is a stable port identifier). -*/ -typedef struct _LV2UI_Port_Map { - /** - Pointer to opaque data which must be passed to port_index(). - */ - LV2UI_Feature_Handle handle; - - /** - Get the index for the port with the given @p symbol. - - @return The index of the port, or LV2UI_INVALID_PORT_INDEX if no such - port is found. - */ - uint32_t (*port_index)(LV2UI_Feature_Handle handle, const char* symbol); -} LV2UI_Port_Map; - -/** - Feature to subscribe to port updates (LV2_UI__portSubscribe). -*/ -typedef struct _LV2UI_Port_Subscribe { - /** - Pointer to opaque data which must be passed to subscribe() and - unsubscribe(). - */ - LV2UI_Feature_Handle handle; - - /** - Subscribe to updates for a port. - - This means that the host will call the UI's port_event() function when - the port value changes (as defined by protocol). - - Calling this function with the same @p port_index and @p port_protocol - as an already active subscription has no effect. - - @param handle The handle field of this struct. - @param port_index The index of the port. - @param port_protocol The URID of the ui:PortProtocol. - @param features Features for this subscription. - @return 0 on success. - */ - uint32_t (*subscribe)(LV2UI_Feature_Handle handle, - uint32_t port_index, - uint32_t port_protocol, - const LV2_Feature* const* features); - - /** - Unsubscribe from updates for a port. - - This means that the host will cease calling calling port_event() when - the port value changes. - - Calling this function with a @p port_index and @p port_protocol that - does not refer to an active port subscription has no effect. - - @param handle The handle field of this struct. - @param port_index The index of the port. - @param port_protocol The URID of the ui:PortProtocol. - @param features Features for this subscription. - @return 0 on success. - */ - uint32_t (*unsubscribe)(LV2UI_Feature_Handle handle, - uint32_t port_index, - uint32_t port_protocol, - const LV2_Feature* const* features); -} LV2UI_Port_Subscribe; - -/** - A feature to notify the host that the user has grabbed a UI control. -*/ -typedef struct _LV2UI_Touch { - /** - Pointer to opaque data which must be passed to ui_resize(). - */ - LV2UI_Feature_Handle handle; - - /** - Notify the host that a control has been grabbed or released. - - The host should cease automating the port or otherwise manipulating the - port value until the control has been ungrabbed. - - @param handle The handle field of this struct. - @param port_index The index of the port associated with the control. - @param grabbed If true, the control has been grabbed, otherwise the - control has been released. - */ - void (*touch)(LV2UI_Feature_Handle handle, - uint32_t port_index, - bool grabbed); -} LV2UI_Touch; - -/** - UI Idle Interface (LV2_UI__idleInterface) - - UIs can provide this interface to have an idle() callback called by the host - rapidly to update the UI. -*/ -typedef struct _LV2UI_Idle_Interface { - /** - Run a single iteration of the UI's idle loop. - - This will be called rapidly in the UI thread at a rate appropriate - for a toolkit main loop. There are no precise timing guarantees, but - the host should attempt to call idle() at a high enough rate for smooth - animation, at least 30Hz. - - @return non-zero if the UI has been closed, in which case the host - should stop calling idle(), and can either completely destroy the UI, or - re-show it and resume calling idle(). - */ - int (*idle)(LV2UI_Handle ui); -} LV2UI_Idle_Interface; - -/** - UI Show Interface (LV2_UI__showInterface) - - UIs can provide this interface to show and hide a window, which allows them - to function in hosts unable to embed their widget. This allows any UI to - provide a fallback for embedding that works in any host. - - If used: - - The host MUST use LV2UI_Idle_Interface to drive the UI. - - The UI MUST return non-zero from LV2UI_Idle_Interface::idle() when it has been closed. - - If idle() returns non-zero, the host MUST call hide() and stop calling - idle(). It MAY later call show() then resume calling idle(). -*/ -typedef struct _LV2UI_Show_Interface { - /** - Show a window for this UI. - - The window title MAY have been passed by the host to - LV2UI_Descriptor::instantiate() as an LV2_Options_Option with key - LV2_UI__windowTitle. - - @return 0 on success, or anything else to stop being called. - */ - int (*show)(LV2UI_Handle ui); - - /** - Hide the window for this UI. - - @return 0 on success, or anything else to stop being called. - */ - int (*hide)(LV2UI_Handle ui); -} LV2UI_Show_Interface; - -/** - Peak data for a slice of time, the update format for ui:peakProtocol. -*/ -typedef struct _LV2UI_Peak_Data { - /** - The start of the measurement period. This is just a running counter - that is only meaningful in comparison to previous values and must not be - interpreted as an absolute time. - */ - uint32_t period_start; - - /** - The size of the measurement period, in the same units as period_start. - */ - uint32_t period_size; - - /** - The peak value for the measurement period. This should be the maximal - value for abs(sample) over all the samples in the period. - */ - float peak; -} LV2UI_Peak_Data; - -/** - Prototype for UI accessor function. - - This is the entry point to a UI library, which works in the same way as - lv2_descriptor() but for UIs rather than plugins. -*/ -LV2_SYMBOL_EXPORT -const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index); - -/** - The type of the lv2ui_descriptor() function. -*/ -typedef const LV2UI_Descriptor* (*LV2UI_DescriptorFunction)(uint32_t index); - -#ifdef __cplusplus -} -#endif - -#endif /* LV2_UI_H */ diff --git a/libs/distrho/src/lv2/units.h b/libs/distrho/src/lv2/units.h deleted file mode 100644 index a40f097..0000000 --- a/libs/distrho/src/lv2/units.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file units.h - C definitions for the LV2 Units extension - <http://lv2plug.in/ns/extensions/units>. -*/ - -#ifndef LV2_UNITS_H -#define LV2_UNITS_H - -#define LV2_UNITS_URI "http://lv2plug.in/ns/extensions/units" -#define LV2_UNITS_PREFIX LV2_UNITS_URI "#" - -#define LV2_UNITS__Conversion LV2_UNITS_PREFIX "Conversion" -#define LV2_UNITS__Unit LV2_UNITS_PREFIX "Unit" -#define LV2_UNITS__bar LV2_UNITS_PREFIX "bar" -#define LV2_UNITS__beat LV2_UNITS_PREFIX "beat" -#define LV2_UNITS__bpm LV2_UNITS_PREFIX "bpm" -#define LV2_UNITS__cent LV2_UNITS_PREFIX "cent" -#define LV2_UNITS__cm LV2_UNITS_PREFIX "cm" -#define LV2_UNITS__coef LV2_UNITS_PREFIX "coef" -#define LV2_UNITS__conversion LV2_UNITS_PREFIX "conversion" -#define LV2_UNITS__db LV2_UNITS_PREFIX "db" -#define LV2_UNITS__degree LV2_UNITS_PREFIX "degree" -#define LV2_UNITS__frame LV2_UNITS_PREFIX "frame" -#define LV2_UNITS__hz LV2_UNITS_PREFIX "hz" -#define LV2_UNITS__inch LV2_UNITS_PREFIX "inch" -#define LV2_UNITS__khz LV2_UNITS_PREFIX "khz" -#define LV2_UNITS__km LV2_UNITS_PREFIX "km" -#define LV2_UNITS__m LV2_UNITS_PREFIX "m" -#define LV2_UNITS__mhz LV2_UNITS_PREFIX "mhz" -#define LV2_UNITS__midiNote LV2_UNITS_PREFIX "midiNote" -#define LV2_UNITS__mile LV2_UNITS_PREFIX "mile" -#define LV2_UNITS__min LV2_UNITS_PREFIX "min" -#define LV2_UNITS__mm LV2_UNITS_PREFIX "mm" -#define LV2_UNITS__ms LV2_UNITS_PREFIX "ms" -#define LV2_UNITS__name LV2_UNITS_PREFIX "name" -#define LV2_UNITS__oct LV2_UNITS_PREFIX "oct" -#define LV2_UNITS__pc LV2_UNITS_PREFIX "pc" -#define LV2_UNITS__prefixConversion LV2_UNITS_PREFIX "prefixConversion" -#define LV2_UNITS__render LV2_UNITS_PREFIX "render" -#define LV2_UNITS__s LV2_UNITS_PREFIX "s" -#define LV2_UNITS__semitone12TET LV2_UNITS_PREFIX "semitone12TET" -#define LV2_UNITS__symbol LV2_UNITS_PREFIX "symbol" -#define LV2_UNITS__unit LV2_UNITS_PREFIX "unit" - -#endif /* LV2_UNITS_H */ diff --git a/libs/distrho/src/lv2/uri-map.h b/libs/distrho/src/lv2/uri-map.h deleted file mode 100644 index 2062af3..0000000 --- a/libs/distrho/src/lv2/uri-map.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright 2008-2011 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file - C header for the LV2 URI Map extension <http://lv2plug.in/ns/ext/uri-map>. - - This extension defines a simple mechanism for plugins to map URIs to - integers, usually for performance reasons (e.g. processing events typed by - URIs in real time). The expected use case is for plugins to map URIs to - integers for things they 'understand' at instantiation time, and store those - values for use in the audio thread without doing any string comparison. - This allows the extensibility of RDF with the performance of integers (or - centrally defined enumerations). -*/ - -#ifndef LV2_URI_MAP_H -#define LV2_URI_MAP_H - -#define LV2_URI_MAP_URI "http://lv2plug.in/ns/ext/uri-map" - -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Opaque pointer to host data. -*/ -typedef void* LV2_URI_Map_Callback_Data; - -/** - URI Map Feature. - - To support this feature the host must pass an LV2_Feature struct to the - plugin's instantiate method with URI "http://lv2plug.in/ns/ext/uri-map" - and data pointed to an instance of this struct. -*/ -typedef struct { - /** - Opaque pointer to host data. - - The plugin MUST pass this to any call to functions in this struct. - Otherwise, it must not be interpreted in any way. - */ - LV2_URI_Map_Callback_Data callback_data; - - /** - Get the numeric ID of a URI from the host. - - @param callback_data Must be the callback_data member of this struct. - @param map The 'context' of this URI. Certain extensions may define a - URI that must be passed here with certain restrictions on the return - value (e.g. limited range). This value may be NULL if the plugin needs - an ID for a URI in general. Extensions SHOULD NOT define a context - unless there is a specific need to do so, e.g. to restrict the range of - the returned value. - @param uri The URI to be mapped to an integer ID. - - This function is referentially transparent; any number of calls with the - same arguments is guaranteed to return the same value over the life of a - plugin instance (though the same URI may return different values with a - different map parameter). However, this function is not necessarily very - fast: plugins SHOULD cache any IDs they might need in performance - critical situations. - - The return value 0 is reserved and indicates that an ID for that URI - could not be created for whatever reason. Extensions MAY define more - precisely what this means in a certain context, but in general plugins - SHOULD handle this situation as gracefully as possible. However, hosts - SHOULD NOT return 0 from this function in non-exceptional circumstances - (e.g. the URI map SHOULD be dynamic). Hosts that statically support only - a fixed set of URIs should not expect plugins to function correctly. - */ - uint32_t (*uri_to_id)(LV2_URI_Map_Callback_Data callback_data, - const char* map, - const char* uri); -} LV2_URI_Map_Feature; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_URI_MAP_H */ diff --git a/libs/distrho/src/lv2/urid.h b/libs/distrho/src/lv2/urid.h deleted file mode 100644 index c317f7f..0000000 --- a/libs/distrho/src/lv2/urid.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright 2008-2012 David Robillard <http://drobilla.net> - Copyright 2011 Gabriel M. Beddingfield <gabrbedd@gmail.com> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file urid.h - C header for the LV2 URID extension <http://lv2plug.in/ns/ext/urid> -*/ - -#ifndef LV2_URID_H -#define LV2_URID_H - -#define LV2_URID_URI "http://lv2plug.in/ns/ext/urid" -#define LV2_URID_PREFIX LV2_URID_URI "#" - -#define LV2_URID__map LV2_URID_PREFIX "map" -#define LV2_URID__unmap LV2_URID_PREFIX "unmap" - -/* Legacy defines */ -#define LV2_URID_MAP_URI LV2_URID__map -#define LV2_URID_UNMAP_URI LV2_URID__unmap - -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Opaque pointer to host data for LV2_URID_Map. -*/ -typedef void* LV2_URID_Map_Handle; - -/** - Opaque pointer to host data for LV2_URID_Unmap. -*/ -typedef void* LV2_URID_Unmap_Handle; - -/** - URI mapped to an integer. -*/ -typedef uint32_t LV2_URID; - -/** - URID Map Feature (LV2_URID__map) -*/ -typedef struct _LV2_URID_Map { - /** - Opaque pointer to host data. - - This MUST be passed to map_uri() whenever it is called. - Otherwise, it must not be interpreted in any way. - */ - LV2_URID_Map_Handle handle; - - /** - Get the numeric ID of a URI. - - If the ID does not already exist, it will be created. - - This function is referentially transparent; any number of calls with the - same arguments is guaranteed to return the same value over the life of a - plugin instance. Note, however, that several URIs MAY resolve to the - same ID if the host considers those URIs equivalent. - - This function is not necessarily very fast or RT-safe: plugins SHOULD - cache any IDs they might need in performance critical situations. - - The return value 0 is reserved and indicates that an ID for that URI - could not be created for whatever reason. However, hosts SHOULD NOT - return 0 from this function in non-exceptional circumstances (i.e. the - URI map SHOULD be dynamic). - - @param handle Must be the callback_data member of this struct. - @param uri The URI to be mapped to an integer ID. - */ - LV2_URID (*map)(LV2_URID_Map_Handle handle, - const char* uri); -} LV2_URID_Map; - -/** - URI Unmap Feature (LV2_URID__unmap) -*/ -typedef struct _LV2_URID_Unmap { - /** - Opaque pointer to host data. - - This MUST be passed to unmap() whenever it is called. - Otherwise, it must not be interpreted in any way. - */ - LV2_URID_Unmap_Handle handle; - - /** - Get the URI for a previously mapped numeric ID. - - Returns NULL if @p urid is not yet mapped. Otherwise, the corresponding - URI is returned in a canonical form. This MAY not be the exact same - string that was originally passed to LV2_URID_Map::map(), but it MUST be - an identical URI according to the URI syntax specification (RFC3986). A - non-NULL return for a given @p urid will always be the same for the life - of the plugin. Plugins that intend to perform string comparison on - unmapped URIs SHOULD first canonicalise URI strings with a call to - map_uri() followed by a call to unmap_uri(). - - @param handle Must be the callback_data member of this struct. - @param urid The ID to be mapped back to the URI string. - */ - const char* (*unmap)(LV2_URID_Unmap_Handle handle, - LV2_URID urid); -} LV2_URID_Unmap; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_URID_H */ diff --git a/libs/distrho/src/lv2/worker.h b/libs/distrho/src/lv2/worker.h deleted file mode 100644 index fc09d55..0000000 --- a/libs/distrho/src/lv2/worker.h +++ /dev/null @@ -1,158 +0,0 @@ -/* - Copyright 2012 David Robillard <http://drobilla.net> - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -/** - @file worker.h C header for the LV2 Worker extension - <http://lv2plug.in/ns/ext/worker>. -*/ - -#ifndef LV2_WORKER_H -#define LV2_WORKER_H - -#include <stdint.h> - -#include "lv2.h" - -#define LV2_WORKER_URI "http://lv2plug.in/ns/ext/worker" -#define LV2_WORKER_PREFIX LV2_WORKER_URI "#" - -#define LV2_WORKER__interface LV2_WORKER_PREFIX "interface" -#define LV2_WORKER__schedule LV2_WORKER_PREFIX "schedule" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - A status code for worker functions. -*/ -typedef enum { - LV2_WORKER_SUCCESS = 0, /**< Completed successfully. */ - LV2_WORKER_ERR_UNKNOWN = 1, /**< Unknown error. */ - LV2_WORKER_ERR_NO_SPACE = 2 /**< Failed due to lack of space. */ -} LV2_Worker_Status; - -typedef void* LV2_Worker_Respond_Handle; - -/** - A function to respond to run() from the worker method. - - The @p data MUST be safe for the host to copy and later pass to - work_response(), and the host MUST guarantee that it will be eventually - passed to work_response() if this function returns LV2_WORKER_SUCCESS. -*/ -typedef LV2_Worker_Status (*LV2_Worker_Respond_Function)( - LV2_Worker_Respond_Handle handle, - uint32_t size, - const void* data); - -/** - LV2 Plugin Worker Interface. - - This is the interface provided by the plugin to implement a worker method. - The plugin's extension_data() method should return an LV2_Worker_Interface - when called with LV2_WORKER__interface as its argument. -*/ -typedef struct _LV2_Worker_Interface { - /** - The worker method. This is called by the host in a non-realtime context - as requested, possibly with an arbitrary message to handle. - - A response can be sent to run() using @p respond. The plugin MUST NOT - make any assumptions about which thread calls this method, other than - the fact that there are no real-time requirements. - - @param instance The LV2 instance this is a method on. - @param respond A function for sending a response to run(). - @param handle Must be passed to @p respond if it is called. - @param size The size of @p data. - @param data Data from run(), or NULL. - */ - LV2_Worker_Status (*work)(LV2_Handle instance, - LV2_Worker_Respond_Function respond, - LV2_Worker_Respond_Handle handle, - uint32_t size, - const void* data); - - /** - Handle a response from the worker. This is called by the host in the - run() context when a response from the worker is ready. - - @param instance The LV2 instance this is a method on. - @param size The size of @p body. - @param body Message body, or NULL. - */ - LV2_Worker_Status (*work_response)(LV2_Handle instance, - uint32_t size, - const void* body); - - /** - Called when all responses for this cycle have been delivered. - - Since work_response() may be called after run() finished, this provides - a hook for code that must run after the cycle is completed. - - This field may be NULL if the plugin has no use for it. Otherwise, the - host MUST call it after every run(), regardless of whether or not any - responses were sent that cycle. - */ - LV2_Worker_Status (*end_run)(LV2_Handle instance); -} LV2_Worker_Interface; - -typedef void* LV2_Worker_Schedule_Handle; - -typedef struct _LV2_Worker_Schedule { - /** - Opaque host data. - */ - LV2_Worker_Schedule_Handle handle; - - /** - Request from run() that the host call the worker. - - This function is in the audio threading class. It should be called from - run() to request that the host call the work() method in a non-realtime - context with the given arguments. - - This function is always safe to call from run(), but it is not - guaranteed that the worker is actually called from a different thread. - In particular, when free-wheeling (e.g. for offline rendering), the - worker may be executed immediately. This allows single-threaded - processing with sample accuracy and avoids timing problems when run() is - executing much faster or slower than real-time. - - Plugins SHOULD be written in such a way that if the worker runs - immediately, and responses from the worker are delivered immediately, - the effect of the work takes place immediately with sample accuracy. - - The @p data MUST be safe for the host to copy and later pass to work(), - and the host MUST guarantee that it will be eventually passed to work() - if this function returns LV2_WORKER_SUCCESS. - - @param handle The handle field of this struct. - @param size The size of @p data. - @param data Message to pass to work(), or NULL. - */ - LV2_Worker_Status (*schedule_work)(LV2_Worker_Schedule_Handle handle, - uint32_t size, - const void* data); -} LV2_Worker_Schedule; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* LV2_WORKER_H */ diff --git a/libs/distrho/src/vestige/aeffectx.h b/libs/distrho/src/vestige/aeffectx.h deleted file mode 100644 index 23f84f2..0000000 --- a/libs/distrho/src/vestige/aeffectx.h +++ /dev/null @@ -1,275 +0,0 @@ -/* - * aeffectx.h - simple header to allow VeSTige compilation and eventually work - * - * Copyright (c) 2006 Javier Serrano Polo <jasp00/at/users.sourceforge.net> - * - * This file is part of Linux MultiMedia Studio - http://lmms.sourceforge.net - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program (see COPYING); if not, write to the - * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301 USA. - * - */ -#include <stdint.h> -#ifndef _AEFFECTX_H -#define _AEFFECTX_H - -#define CCONST(a, b, c, d)( ( ( (int) a ) << 24 ) | \ - ( ( (int) b ) << 16 ) | \ - ( ( (int) c ) << 8 ) | \ - ( ( (int) d ) << 0 ) ) - -#define audioMasterAutomate 0 -#define audioMasterVersion 1 -#define audioMasterCurrentId 2 -#define audioMasterIdle 3 -#define audioMasterPinConnected 4 -// unsupported? 5 -#define audioMasterWantMidi 6 -#define audioMasterGetTime 7 -#define audioMasterProcessEvents 8 -#define audioMasterSetTime 9 -#define audioMasterTempoAt 10 -#define audioMasterGetNumAutomatableParameters 11 -#define audioMasterGetParameterQuantization 12 -#define audioMasterIOChanged 13 -#define audioMasterNeedIdle 14 -#define audioMasterSizeWindow 15 -#define audioMasterGetSampleRate 16 -#define audioMasterGetBlockSize 17 -#define audioMasterGetInputLatency 18 -#define audioMasterGetOutputLatency 19 -#define audioMasterGetPreviousPlug 20 -#define audioMasterGetNextPlug 21 -#define audioMasterWillReplaceOrAccumulate 22 -#define audioMasterGetCurrentProcessLevel 23 -#define audioMasterGetAutomationState 24 -#define audioMasterOfflineStart 25 -#define audioMasterOfflineRead 26 -#define audioMasterOfflineWrite 27 -#define audioMasterOfflineGetCurrentPass 28 -#define audioMasterOfflineGetCurrentMetaPass 29 -#define audioMasterSetOutputSampleRate 30 -// unsupported? 31 -#define audioMasterGetSpeakerArrangement 31 // deprecated in 2.4? -#define audioMasterGetVendorString 32 -#define audioMasterGetProductString 33 -#define audioMasterGetVendorVersion 34 -#define audioMasterVendorSpecific 35 -#define audioMasterSetIcon 36 -#define audioMasterCanDo 37 -#define audioMasterGetLanguage 38 -#define audioMasterOpenWindow 39 -#define audioMasterCloseWindow 40 -#define audioMasterGetDirectory 41 -#define audioMasterUpdateDisplay 42 -#define audioMasterBeginEdit 43 -#define audioMasterEndEdit 44 -#define audioMasterOpenFileSelector 45 -#define audioMasterCloseFileSelector 46 // currently unused -#define audioMasterEditFile 47 // currently unused -#define audioMasterGetChunkFile 48 // currently unused -#define audioMasterGetInputSpeakerArrangement 49 // currently unused - -#define effFlagsHasEditor 1 -#define effFlagsCanReplacing (1 << 4) // very likely -#define effFlagsIsSynth (1 << 8) // currently unused - -#define effOpen 0 -#define effClose 1 // currently unused -#define effSetProgram 2 // currently unused -#define effGetProgram 3 // currently unused -#define effGetProgramName 5 // currently unused -#define effGetParamName 8 // currently unused -#define effSetSampleRate 10 -#define effSetBlockSize 11 -#define effMainsChanged 12 -#define effEditGetRect 13 -#define effEditOpen 14 -#define effEditClose 15 -#define effEditIdle 19 -#define effEditTop 20 -#define effProcessEvents 25 -#define effGetEffectName 45 -#define effGetVendorString 47 -#define effGetProductString 48 -#define effGetVendorVersion 49 -#define effCanDo 51 // currently unused -/* from http://asseca.com/vst-24-specs/efGetParameterProperties.html */ -#define effGetParameterProperties 56 -#define effGetVstVersion 58 // currently unused - -#define kEffectMagic (CCONST( 'V', 's', 't', 'P' )) -#define kVstLangEnglish 1 -#define kVstMidiType 1 - -struct RemoteVstPlugin; - -#define kVstTransportPlaying (1 << 1) - -#define kVstNanosValid (1 << 8) -#define kVstPpqPosValid (1 << 9) -#define kVstTempoValid (1 << 10) -#define kVstBarsValid (1 << 11) -#define kVstCyclePosValid (1 << 12) -#define kVstTimeSigValid (1 << 13) -#define kVstSmpteValid (1 << 14) -#define kVstClockValid (1 << 15) - -struct _VstMidiEvent -{ - // 00 - int type; - // 04 - int byteSize; - // 08 - int deltaFrames; - // 0c? - int flags; - // 10? - int noteLength; - // 14? - int noteOffset; - // 18 - char midiData[4]; - // 1c? - char detune; - // 1d? - char noteOffVelocity; - // 1e? - char reserved1; - // 1f? - char reserved2; -}; - -typedef struct _VstMidiEvent VstMidiEvent; - - -struct _VstEvent -{ - char dump[sizeof (VstMidiEvent)]; - -}; - -typedef struct _VstEvent VstEvent; - -struct _VstEvents -{ - // 00 - int numEvents; - // 04 - void *reserved; - // 08 - VstEvent * events[2]; -}; - -typedef struct _VstEvents VstEvents; - -/* this struct taken from http://asseca.com/vst-24-specs/efGetParameterProperties.html */ -struct _VstParameterProperties -{ - float stepFloat; - float smallStepFloat; - float largeStepFloat; - char label[64]; - int32_t flags; - int32_t minInteger; - int32_t maxInteger; - int32_t stepInteger; - int32_t largeStepInteger; - char shortLabel[8]; -}; - -typedef struct _VstParameterProperties VstParameterProperties; - -/* this enum taken from http://asseca.com/vst-24-specs/efGetParameterProperties.html */ -enum VstParameterFlags -{ - kVstParameterIsSwitch = 1 << 0, /* parameter is a switch (on/off) */ - kVstParameterUsesIntegerMinMax = 1 << 1, /* minInteger, maxInteger valid */ - kVstParameterUsesFloatStep = 1 << 2, /* stepFloat, smallStepFloat, largeStepFloat valid */ - kVstParameterUsesIntStep = 1 << 3, /* stepInteger, largeStepInteger valid */ - kVstParameterSupportsDisplayIndex = 1 << 4, /* displayIndex valid */ - kVstParameterSupportsDisplayCategory = 1 << 5, /* category, etc. valid */ - kVstParameterCanRamp = 1 << 6 /* set if parameter value can ramp up/down */ -}; - -struct _AEffect -{ - // Never use virtual functions!!! - // 00-03 - int magic; - // dispatcher 04-07 - intptr_t (* dispatcher) (struct _AEffect *, int, int, intptr_t, void *, float); - // process, quite sure 08-0b - void (* process) (struct _AEffect *, float **, float **, int); - // setParameter 0c-0f - void (* setParameter) (struct _AEffect *, int, float); - // getParameter 10-13 - float (* getParameter) (struct _AEffect *, int); - // programs 14-17 - int numPrograms; - // Params 18-1b - int numParams; - // Input 1c-1f - int numInputs; - // Output 20-23 - int numOutputs; - // flags 24-27 - int flags; - // Fill somewhere 28-2b - void *ptr1; - void *ptr2; - // Zeroes 2c-2f 30-33 34-37 38-3b - char empty3[4 + 4 + 4]; - // 1.0f 3c-3f - float unkown_float; - // An object? pointer 40-43 - void *ptr3; - // Zeroes 44-47 - void *user; - // Id 48-4b - int32_t uniqueID; - // Don't know 4c-4f - char unknown1[4]; - // processReplacing 50-53 - void (* processReplacing) (struct _AEffect *, float **, float **, int); -}; - -typedef struct _AEffect AEffect; - -typedef struct _VstTimeInfo -{ - /* info from online documentation of VST provided by Steinberg */ - - double samplePos; - double sampleRate; - double nanoSeconds; - double ppqPos; - double tempo; - double barStartPos; - double cycleStartPos; - double cycleEndPos; - int32_t timeSigNumerator; - int32_t timeSigDenominator; - int32_t smpteOffset; - int32_t smpteFrameRate; - int32_t samplesToNextClock; - int32_t flags; - -} VstTimeInfo; - -typedef intptr_t (* audioMasterCallback) (AEffect *, int32_t, int32_t, intptr_t, void *, float); - -#endif diff --git a/libs/generate-ttl.sh b/libs/generate-ttl.sh deleted file mode 100755 index 2515e11..0000000 --- a/libs/generate-ttl.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash - -set -e - -if [ -d bin ]; then - cd bin -else - echo "Please run this script from the source root folder" - exit -fi - -PWD=`dirname $0` - -if [ -f ../../$PWD/lv2_ttl_generator.exe ]; then - GEN=../../$PWD/lv2_ttl_generator.exe - EXT=dll -else - GEN=../../$PWD/lv2_ttl_generator - if [ -d /Library/Audio ]; then - EXT=dylib - else - EXT=so - fi -fi - -FOLDERS=`find . -type d -name \*.lv2` - -for i in $FOLDERS; do - cd $i - FILE=`ls *.$EXT | sort | head -n 1` - $GEN ./$FILE - cd .. -done diff --git a/libs/generate-vst-bundles.sh b/libs/generate-vst-bundles.sh deleted file mode 100755 index 5f17687..0000000 --- a/libs/generate-vst-bundles.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash - -set -e - -if [ -d bin ]; then - cd bin -else - echo "Please run this script from the root folder" - exit -fi - -PWD=`pwd` - -if [ ! -d /System/Library ]; then - echo "This doesn't seem to be OSX, please stop!" - exit 0 -fi - -rm -rf *.vst/ - -PLUGINS=`ls | grep vst.dylib` - -for i in $PLUGINS; do - FILE=`echo $i | awk 'sub("-vst.dylib","")'` - cp -r ../libs/plugin.vst/ $FILE.vst - mv $i $FILE.vst/Contents/MacOS/$FILE - rm -f $FILE.vst/Contents/MacOS/deleteme - sed -i -e "s/X-PROJECTNAME-X/$FILE/" $FILE.vst/Contents/Info.plist - rm -f $FILE.vst/Contents/Info.plist-e - SetFile -a B $FILE.vst -done - -cd .. diff --git a/libs/lv2-ttl-generator/GNUmakefile b/libs/lv2-ttl-generator/GNUmakefile deleted file mode 100644 index 0052be4..0000000 --- a/libs/lv2-ttl-generator/GNUmakefile +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/makefile -f - -all: build - -ifeq ($(WIN32), true) -build: ../lv2_ttl_generator.exe -else -build: ../lv2_ttl_generator -endif - -../lv2_ttl_generator: lv2_ttl_generator.c - $(CC) lv2_ttl_generator.c -o ../lv2_ttl_generator -ldl - -../lv2_ttl_generator.exe: lv2_ttl_generator.c - $(CC) lv2_ttl_generator.c -o ../lv2_ttl_generator.exe -static - touch ../lv2_ttl_generator - -clean: - rm -f ../lv2_ttl_generator ../lv2_ttl_generator.exe diff --git a/libs/lv2-ttl-generator/lv2_ttl_generator.c b/libs/lv2-ttl-generator/lv2_ttl_generator.c deleted file mode 100644 index 5ef2b14..0000000 --- a/libs/lv2-ttl-generator/lv2_ttl_generator.c +++ /dev/null @@ -1,89 +0,0 @@ -/* - * DPF LV2 *.ttl generator - */ - -#include <stdio.h> -#include <string.h> - -#ifdef _WIN32 - #include <windows.h> - #define TTL_GENERATOR_WINDOWS -#else - #include <dlfcn.h> -#endif - -#ifndef nullptr - #define nullptr (0) -#endif - -typedef void (*TTL_Generator_Function)(const char* basename); - -int main(int argc, char* argv[]) -{ - if (argc != 2) - { - printf("usage: %s /path/to/plugin-DLL\n", argv[0]); - return 1; - } - -#ifdef TTL_GENERATOR_WINDOWS - const HMODULE handle = LoadLibraryA(argv[1]); -#else - void* const handle = dlopen(argv[1], RTLD_LAZY); -#endif - - if (! handle) - { -#ifdef TTL_GENERATOR_WINDOWS - printf("Failed to open plugin DLL\n"); -#else - printf("Failed to open plugin DLL, error was:\n%s\n", dlerror()); -#endif - return 2; - } - -#ifdef TTL_GENERATOR_WINDOWS - const TTL_Generator_Function ttlFn = (TTL_Generator_Function)GetProcAddress(handle, "lv2_generate_ttl"); -#else - const TTL_Generator_Function ttlFn = (TTL_Generator_Function)dlsym(handle, "lv2_generate_ttl"); -#endif - - if (ttlFn != NULL) - { - char basename[strlen(argv[1])+1]; - -#ifdef TTL_GENERATOR_WINDOWS - char* base2 = strrchr(argv[1], '\\'); -#else - char* base2 = strrchr(argv[1], '/'); -#endif - if (base2 != NULL) - { - strcpy(basename, base2+1); - basename[strrchr(base2, '.')-base2-1] = '\0'; - } - else if (argv[1][0] == '.' && argv[1][1] == '/') - { - strcpy(basename, argv[1]+2); - basename[strrchr(basename, '.')-basename] = '\0'; - } - else - { - strcpy(basename, argv[1]); - } - - printf("Generate ttl data for '%s', basename: '%s'\n", argv[1], basename); - - ttlFn(basename); - } - else - printf("Failed to find 'lv2_generate_ttl' function\n"); - -#ifdef TTL_GENERATOR_WINDOWS - FreeLibrary(handle); -#else - dlclose(handle); -#endif - - return 0; -} diff --git a/libs/plugin.vst/Contents/Info.plist b/libs/plugin.vst/Contents/Info.plist deleted file mode 100644 index df723b5..0000000 --- a/libs/plugin.vst/Contents/Info.plist +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> -<plist version="1.0"> -<dict> - <key>CFBundleDevelopmentRegion</key> - <string>English</string> - <key>CFBundleExecutable</key> - <string>X-PROJECTNAME-X</string> - <key>CFBundleIconFile</key> - <string></string> - <key>CFBundleIdentifier</key> - <string>net.sf.distrho.X-PROJECTNAME-X</string> - <key>CFBundleInfoDictionaryVersion</key> - <string>6.0</string> - <key>CFBundlePackageType</key> - <string>BNDL</string> - <key>CFBundleSignature</key> - <string>????</string> - <key>CFBundleVersion</key> - <string>1.0</string> - <key>CSResourcesFileMapped</key> - <true/> -</dict> -</plist> diff --git a/libs/plugin.vst/Contents/MacOS/deleteme b/libs/plugin.vst/Contents/MacOS/deleteme deleted file mode 100644 index 8d1c8b6..0000000 --- a/libs/plugin.vst/Contents/MacOS/deleteme +++ /dev/null @@ -1 +0,0 @@ - diff --git a/libs/plugin.vst/Contents/PkgInfo b/libs/plugin.vst/Contents/PkgInfo deleted file mode 100644 index 43c9cb0..0000000 --- a/libs/plugin.vst/Contents/PkgInfo +++ /dev/null @@ -1 +0,0 @@ -BNDL???? diff --git a/libs/plugin.vst/Contents/Resources/empty.lproj b/libs/plugin.vst/Contents/Resources/empty.lproj deleted file mode 100644 index e69de29..0000000 --- a/libs/plugin.vst/Contents/Resources/empty.lproj +++ /dev/null diff --git a/libs/png2rgba.py b/libs/png2rgba.py deleted file mode 100755 index 938597c..0000000 --- a/libs/png2rgba.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python - -import os, numpy, sys -import Image - -# ----------------------------------------------------- - -def png2rgba(namespace, filenames): - - fdH = open("%s.hpp" % namespace, "w") - fdH.write("/* (Auto-generated binary data file). */\n") - fdH.write("\n") - fdH.write("#ifndef BINARY_%s_HPP\n" % namespace.upper()) - fdH.write("#define BINARY_%s_HPP\n" % namespace.upper()) - fdH.write("\n") - fdH.write("namespace %s\n" % namespace) - fdH.write("{\n") - - fdC = open("%s.cpp" % namespace, "w") - fdC.write("/* (Auto-generated binary data file). */\n") - fdC.write("\n") - fdC.write("#include \"%s.hpp\"\n" % namespace) - fdC.write("\n") - - tempIndex = 1 - - for filename in filenames: - shortFilename = filename.rsplit(os.sep, 1)[-1].split(".", 1)[0] - shortFilename = shortFilename.replace("-", "_") - - png = Image.open(filename) - pngNumpy = numpy.array(png) - pngData = pngNumpy.tolist() - #pngData.reverse() - - height = len(pngData) - for dataBlock in pngData: - width = len(dataBlock) - channels = len(dataBlock[0]) - break - else: - print("Invalid image found, cannot continue!") - quit() - - if channels not in (3, 4): - print("Invalid image channel count, cannot continue!") - quit() - - print("Generating data for \"%s\" using '%s' type" % (filename, "GL_BGR" if channels == 3 else "GL_BGRA")) - #print(" Width: %i" % width) - #print(" Height: %i" % height) - #print(" DataSize: %i" % (width * height * channels)) - - fdH.write(" extern const char* %sData;\n" % shortFilename) - fdH.write(" const unsigned int %sDataSize = %i;\n" % (shortFilename, width * height * channels)) - fdH.write(" const unsigned int %sWidth = %i;\n" % (shortFilename, width)) - fdH.write(" const unsigned int %sHeight = %i;\n" % (shortFilename, height)) - - if tempIndex != len(filenames): - fdH.write("\n") - - fdC.write("static const unsigned char temp%i[] = {\n" % tempIndex) - - curColumn = 1 - fdC.write(" ") - - for dataBlock in pngData: - if curColumn == 0: - fdC.write(" ") - - for data in dataBlock: - if channels == 3: - r, g, b = data - fdC.write(" %3u, %3u, %3u," % (b, g, r)) - else: - r, g, b, a = data - - if filename in ("artwork/claw1.png", - "artwork/claw2.png", - "artwork/run1.png", - "artwork/run2.png", - "artwork/run3.png", - "artwork/run4.png", - "artwork/scratch1.png", - "artwork/scratch2.png", - "artwork/sit.png", - "artwork/tail.png"): - if r == 255: - a -= 38 - if a < 0: a = 0 - #a = 0 - #else: - #r = g = b = 255 - - fdC.write(" %3u, %3u, %3u, %3u," % (b, g, r, a)) - - if curColumn > 20: - fdC.write("\n ") - curColumn = 1 - else: - curColumn += 1 - - fdC.write("};\n") - fdC.write("const char* %s::%sData = (const char*)temp%i;\n" % (namespace, shortFilename, tempIndex)) - - if tempIndex != len(filenames): - fdC.write("\n") - - tempIndex += 1 - - fdH.write("}\n") - fdH.write("\n") - fdH.write("#endif // BINARY_%s_HPP\n" % namespace.upper()) - fdH.write("\n") - fdH.close() - - fdC.write("\n") - fdC.close() - -# ----------------------------------------------------- - -if __name__ == '__main__': - if len(sys.argv) != 3: - print("Usage: %s <namespace> <artwork-folder>" % sys.argv[0]) - quit() - - namespace = sys.argv[1] - artFolder = sys.argv[2] - - if not os.path.exists(artFolder): - print("Folder '%s' does not exist" % artFolder) - quit() - - # find png files - pngFiles = [] - - for root, dirs, files in os.walk(artFolder): - for name in [name for name in files if name.lower().endswith(".png")]: - pngFiles.append(os.path.join(root, name)) - - pngFiles.sort() - - # create code now - png2rgba(namespace, pngFiles) diff --git a/plugins/Makefile.mk b/plugins/Makefile.mk index 340de08..dcfe8ec 100644 --- a/plugins/Makefile.mk +++ b/plugins/Makefile.mk @@ -14,42 +14,53 @@ include ../../Makefile.mk TARGET_DIR = ../../bin BUILD_C_FLAGS += -I. -BUILD_CXX_FLAGS += -I. -I.. -I../../libs/distrho -I../../libs/dgl +BUILD_CXX_FLAGS += -I. -I.. -I../../dpf/distrho -I../../dpf/dgl -# -------------------------------------------------------------- -# Set plugin binary file targets +ifeq ($(HAVE_DGL),true) +BASE_FLAGS += -DHAVE_DGL +endif + +ifeq ($(HAVE_JACK),true) +BASE_FLAGS += -DHAVE_JACK +endif -jack = $(TARGET_DIR)/$(NAME) -ladspa_dsp = $(TARGET_DIR)/$(NAME)-ladspa.$(EXT) -dssi_dsp = $(TARGET_DIR)/$(NAME)-dssi.$(EXT) -dssi_ui = $(TARGET_DIR)/$(NAME)-dssi/$(NAME)_ui -lv2 = $(TARGET_DIR)/$(NAME).lv2/$(NAME).$(EXT) -lv2_dsp = $(TARGET_DIR)/$(NAME).lv2/$(NAME)_dsp.$(EXT) -lv2_ui = $(TARGET_DIR)/$(NAME).lv2/$(NAME)_ui.$(EXT) -vst = $(TARGET_DIR)/$(NAME)-vst.$(EXT) - -ifeq ($(WIN32),true) -dssi_ui += .exe +ifeq ($(HAVE_LIBLO),true) +BASE_FLAGS += -DHAVE_LIBLO endif -# TODO: MacOS VST bundle +# -------------------------------------------------------------- +# Set plugin binary file targets + +jack = $(TARGET_DIR)/$(NAME)$(APP_EXT) +ladspa_dsp = $(TARGET_DIR)/$(NAME)-ladspa$(LIB_EXT) +dssi_dsp = $(TARGET_DIR)/$(NAME)-dssi$(LIB_EXT) +dssi_ui = $(TARGET_DIR)/$(NAME)-dssi/$(NAME)_ui$(APP_EXT) +lv2 = $(TARGET_DIR)/$(NAME).lv2/$(NAME)$(LIB_EXT) +lv2_dsp = $(TARGET_DIR)/$(NAME).lv2/$(NAME)_dsp$(LIB_EXT) +lv2_ui = $(TARGET_DIR)/$(NAME).lv2/$(NAME)_ui$(LIB_EXT) +vst = $(TARGET_DIR)/$(NAME)-vst$(LIB_EXT) # -------------------------------------------------------------- # Set distrho code files -DISTRHO_PLUGIN_FILES = ../../libs/distrho/DistrhoPluginMain.cpp -DISTRHO_UI_FILES = ../../libs/distrho/DistrhoUIMain.cpp ../../libs/libdgl.a +DISTRHO_PLUGIN_FILES = ../../dpf/distrho/DistrhoPluginMain.cpp + +ifeq ($(HAVE_DGL),true) +DISTRHO_UI_FILES = ../../dpf/distrho/DistrhoUIMain.cpp ../../dpf/libdgl.a +endif # -------------------------------------------------------------- # Handle plugins without UI ifeq ($(TARGET_NOUI),true) +ifneq ($(HAVE_DGL),true) dssi_ui = lv2_ui = DISTRHO_UI_FILES = DGL_LIBS = OBJS_UI = endif +endif # -------------------------------------------------------------- # all needs to be first @@ -60,13 +71,13 @@ all: # Common %.c.o: %.c - $(CC) $< $(BUILD_C_FLAGS) -c -o $@ + $(CC) $< $(BUILD_C_FLAGS) -MD -MP -c -o $@ %.cpp.o: %.cpp - $(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ + $(CXX) $< $(BUILD_CXX_FLAGS) -MD -MP -c -o $@ clean: - rm -f *.o + rm -f *.d *.o rm -rf $(TARGET_DIR)/$(NAME) $(TARGET_DIR)/$(NAME)-* $(TARGET_DIR)/$(NAME).lv2/ # -------------------------------------------------------------- @@ -90,7 +101,9 @@ $(ladspa_dsp): $(OBJS_DSP) $(DISTRHO_PLUGIN_FILES) # -------------------------------------------------------------- # DSSI -dssi: $(dssi_dsp) $(dssi_ui) +dssi: $(dssi_dsp) $(dssi_ui) +dssi_dsp: $(dssi_dsp) +dssi_ui: $(dssi_ui) $(dssi_dsp): $(OBJS_DSP) $(DISTRHO_PLUGIN_FILES) mkdir -p $(shell dirname $@) @@ -104,6 +117,7 @@ $(dssi_ui): $(OBJS_UI) $(DISTRHO_UI_FILES) # LV2 lv2_one: $(lv2) +lv2_dsp: $(lv2_dsp) lv2_sep: $(lv2_dsp) $(lv2_ui) $(lv2): $(OBJS_DSP) $(OBJS_UI) $(DISTRHO_PLUGIN_FILES) $(DISTRHO_UI_FILES) @@ -128,3 +142,10 @@ $(vst): $(OBJS_DSP) $(OBJS_UI) $(DISTRHO_PLUGIN_FILES) $(DISTRHO_UI_FILES) $(CXX) $^ $(BUILD_CXX_FLAGS) $(LINK_FLAGS) $(DGL_LIBS) $(SHARED) -DDISTRHO_PLUGIN_TARGET_VST -o $@ # -------------------------------------------------------------- + +-include $(OBJS_DSP:%.o=%.d) +ifeq ($(HAVE_DGL),true) +-include $(OBJS_UI:%.o=%.d) +endif + +# -------------------------------------------------------------- diff --git a/plugins/ZaMultiComp/Makefile b/plugins/ZaMultiComp/Makefile index 8e807bb..67956bd 100644 --- a/plugins/ZaMultiComp/Makefile +++ b/plugins/ZaMultiComp/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZaMultiComp/ZaMultiCompPlugin.cpp b/plugins/ZaMultiComp/ZaMultiCompPlugin.cpp index 79e0fa2..75b02ac 100644 --- a/plugins/ZaMultiComp/ZaMultiCompPlugin.cpp +++ b/plugins/ZaMultiComp/ZaMultiCompPlugin.cpp @@ -25,13 +25,13 @@ ZaMultiCompPlugin::ZaMultiCompPlugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZaMultiCompPlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZaMultiCompPlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -227,7 +227,7 @@ void ZaMultiCompPlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZaMultiCompPlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZaMultiCompPlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -238,7 +238,7 @@ void ZaMultiCompPlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZaMultiCompPlugin::d_getParameterValue(uint32_t index) const +float ZaMultiCompPlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -310,7 +310,7 @@ float ZaMultiCompPlugin::d_getParameterValue(uint32_t index) const } } -void ZaMultiCompPlugin::d_setParameterValue(uint32_t index, float value) +void ZaMultiCompPlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -392,7 +392,7 @@ void ZaMultiCompPlugin::d_setParameterValue(uint32_t index, float value) } } -void ZaMultiCompPlugin::d_setProgram(uint32_t index) +void ZaMultiCompPlugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -423,13 +423,13 @@ void ZaMultiCompPlugin::d_setProgram(uint32_t index) /* Default variable values */ /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZaMultiCompPlugin::d_activate() +void ZaMultiCompPlugin::activate() { int i; for (i = 0; i < MAX_COMP; i++) { @@ -493,7 +493,7 @@ void ZaMultiCompPlugin::set_hp_coeffs(float fc, float q, float sr, int i, float float ZaMultiCompPlugin::run_comp(int k, float in) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float width=(knee-0.99f)*6.f; float release_coeff = exp(-1000.f/(release * srate)); float attack_coeff; @@ -548,9 +548,9 @@ float ZaMultiCompPlugin::run_comp(int k, float in) return sanitize_denormal(out); } -void ZaMultiCompPlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZaMultiCompPlugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float max = 0.f; int tog1 = (toggle[0] > 0.5f) ? 1 : 0; diff --git a/plugins/ZaMultiComp/ZaMultiCompPlugin.hpp b/plugins/ZaMultiComp/ZaMultiCompPlugin.hpp index fde8c4f..2cc963e 100644 --- a/plugins/ZaMultiComp/ZaMultiCompPlugin.hpp +++ b/plugins/ZaMultiComp/ZaMultiCompPlugin.hpp @@ -71,27 +71,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZaMultiComp"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'M', 'C', 'P'); } @@ -99,15 +99,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -134,8 +134,8 @@ protected: void set_lp_coeffs(float fc, float q, float sr, int i, float gain); void set_hp_coeffs(float fc, float q, float sr, int i, float gain); - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZaMultiComp/ZaMultiCompUI.cpp b/plugins/ZaMultiComp/ZaMultiCompUI.cpp index 39ea785..8bea548 100644 --- a/plugins/ZaMultiComp/ZaMultiCompUI.cpp +++ b/plugins/ZaMultiComp/ZaMultiCompUI.cpp @@ -180,13 +180,13 @@ ZaMultiCompUI::ZaMultiCompUI() fToggleListen1->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZaMultiCompUI::d_parameterChanged(uint32_t index, float value) +void ZaMultiCompUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -272,7 +272,7 @@ void ZaMultiCompUI::d_parameterChanged(uint32_t index, float value) } } -void ZaMultiCompUI::d_programChanged(uint32_t index) +void ZaMultiCompUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -305,96 +305,96 @@ void ZaMultiCompUI::d_programChanged(uint32_t index) void ZaMultiCompUI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobAttack) - d_editParameter(ZaMultiCompPlugin::paramAttack, true); + editParameter(ZaMultiCompPlugin::paramAttack, true); else if (knob == fKnobRelease) - d_editParameter(ZaMultiCompPlugin::paramRelease, true); + editParameter(ZaMultiCompPlugin::paramRelease, true); else if (knob == fKnobThresh) - d_editParameter(ZaMultiCompPlugin::paramThresh, true); + editParameter(ZaMultiCompPlugin::paramThresh, true); else if (knob == fKnobRatio) - d_editParameter(ZaMultiCompPlugin::paramRatio, true); + editParameter(ZaMultiCompPlugin::paramRatio, true); else if (knob == fKnobKnee) - d_editParameter(ZaMultiCompPlugin::paramKnee, true); + editParameter(ZaMultiCompPlugin::paramKnee, true); else if (knob == fKnobGlobalGain) - d_editParameter(ZaMultiCompPlugin::paramGlobalGain, true); + editParameter(ZaMultiCompPlugin::paramGlobalGain, true); else if (knob == fKnobMakeup1) - d_editParameter(ZaMultiCompPlugin::paramMakeup1, true); + editParameter(ZaMultiCompPlugin::paramMakeup1, true); else if (knob == fKnobMakeup2) - d_editParameter(ZaMultiCompPlugin::paramMakeup2, true); + editParameter(ZaMultiCompPlugin::paramMakeup2, true); else if (knob == fKnobMakeup3) - d_editParameter(ZaMultiCompPlugin::paramMakeup3, true); + editParameter(ZaMultiCompPlugin::paramMakeup3, true); else if (knob == fKnobXover1) - d_editParameter(ZaMultiCompPlugin::paramXover1, true); + editParameter(ZaMultiCompPlugin::paramXover1, true); else if (knob == fKnobXover2) - d_editParameter(ZaMultiCompPlugin::paramXover2, true); + editParameter(ZaMultiCompPlugin::paramXover2, true); } void ZaMultiCompUI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobAttack) - d_editParameter(ZaMultiCompPlugin::paramAttack, false); + editParameter(ZaMultiCompPlugin::paramAttack, false); else if (knob == fKnobRelease) - d_editParameter(ZaMultiCompPlugin::paramRelease, false); + editParameter(ZaMultiCompPlugin::paramRelease, false); else if (knob == fKnobThresh) - d_editParameter(ZaMultiCompPlugin::paramThresh, false); + editParameter(ZaMultiCompPlugin::paramThresh, false); else if (knob == fKnobRatio) - d_editParameter(ZaMultiCompPlugin::paramRatio, false); + editParameter(ZaMultiCompPlugin::paramRatio, false); else if (knob == fKnobKnee) - d_editParameter(ZaMultiCompPlugin::paramKnee, false); + editParameter(ZaMultiCompPlugin::paramKnee, false); else if (knob == fKnobGlobalGain) - d_editParameter(ZaMultiCompPlugin::paramGlobalGain, false); + editParameter(ZaMultiCompPlugin::paramGlobalGain, false); else if (knob == fKnobMakeup1) - d_editParameter(ZaMultiCompPlugin::paramMakeup1, false); + editParameter(ZaMultiCompPlugin::paramMakeup1, false); else if (knob == fKnobMakeup2) - d_editParameter(ZaMultiCompPlugin::paramMakeup2, false); + editParameter(ZaMultiCompPlugin::paramMakeup2, false); else if (knob == fKnobMakeup3) - d_editParameter(ZaMultiCompPlugin::paramMakeup3, false); + editParameter(ZaMultiCompPlugin::paramMakeup3, false); else if (knob == fKnobXover1) - d_editParameter(ZaMultiCompPlugin::paramXover1, false); + editParameter(ZaMultiCompPlugin::paramXover1, false); else if (knob == fKnobXover2) - d_editParameter(ZaMultiCompPlugin::paramXover2, false); + editParameter(ZaMultiCompPlugin::paramXover2, false); } void ZaMultiCompUI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobAttack) - d_setParameterValue(ZaMultiCompPlugin::paramAttack, value); + setParameterValue(ZaMultiCompPlugin::paramAttack, value); else if (knob == fKnobRelease) - d_setParameterValue(ZaMultiCompPlugin::paramRelease, value); + setParameterValue(ZaMultiCompPlugin::paramRelease, value); else if (knob == fKnobThresh) - d_setParameterValue(ZaMultiCompPlugin::paramThresh, value); + setParameterValue(ZaMultiCompPlugin::paramThresh, value); else if (knob == fKnobRatio) - d_setParameterValue(ZaMultiCompPlugin::paramRatio, value); + setParameterValue(ZaMultiCompPlugin::paramRatio, value); else if (knob == fKnobKnee) - d_setParameterValue(ZaMultiCompPlugin::paramKnee, value); + setParameterValue(ZaMultiCompPlugin::paramKnee, value); else if (knob == fKnobGlobalGain) - d_setParameterValue(ZaMultiCompPlugin::paramGlobalGain, value); + setParameterValue(ZaMultiCompPlugin::paramGlobalGain, value); else if (knob == fKnobMakeup1) - d_setParameterValue(ZaMultiCompPlugin::paramMakeup1, value); + setParameterValue(ZaMultiCompPlugin::paramMakeup1, value); else if (knob == fKnobMakeup2) - d_setParameterValue(ZaMultiCompPlugin::paramMakeup2, value); + setParameterValue(ZaMultiCompPlugin::paramMakeup2, value); else if (knob == fKnobMakeup3) - d_setParameterValue(ZaMultiCompPlugin::paramMakeup3, value); + setParameterValue(ZaMultiCompPlugin::paramMakeup3, value); else if (knob == fKnobXover1) - d_setParameterValue(ZaMultiCompPlugin::paramXover1, value); + setParameterValue(ZaMultiCompPlugin::paramXover1, value); else if (knob == fKnobXover2) - d_setParameterValue(ZaMultiCompPlugin::paramXover2, value); + setParameterValue(ZaMultiCompPlugin::paramXover2, value); } void ZaMultiCompUI::imageToggleClicked(ImageToggle* toggle, int) { float v = toggle->getValue(); if (toggle == fToggleBypass1) - d_setParameterValue(ZaMultiCompPlugin::paramToggle1, v); + setParameterValue(ZaMultiCompPlugin::paramToggle1, v); else if (toggle == fToggleBypass2) - d_setParameterValue(ZaMultiCompPlugin::paramToggle2, v); + setParameterValue(ZaMultiCompPlugin::paramToggle2, v); else if (toggle == fToggleBypass3) - d_setParameterValue(ZaMultiCompPlugin::paramToggle3, v); + setParameterValue(ZaMultiCompPlugin::paramToggle3, v); else if (toggle == fToggleListen1) - d_setParameterValue(ZaMultiCompPlugin::paramListen1, v); + setParameterValue(ZaMultiCompPlugin::paramListen1, v); else if (toggle == fToggleListen2) - d_setParameterValue(ZaMultiCompPlugin::paramListen2, v); + setParameterValue(ZaMultiCompPlugin::paramListen2, v); else if (toggle == fToggleListen3) - d_setParameterValue(ZaMultiCompPlugin::paramListen3, v); + setParameterValue(ZaMultiCompPlugin::paramListen3, v); } void ZaMultiCompUI::onDisplay() diff --git a/plugins/ZaMultiComp/ZaMultiCompUI.hpp b/plugins/ZaMultiComp/ZaMultiCompUI.hpp index 1ef3dc0..23f3789 100644 --- a/plugins/ZaMultiComp/ZaMultiCompUI.hpp +++ b/plugins/ZaMultiComp/ZaMultiCompUI.hpp @@ -44,8 +44,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZaMultiCompX2/Makefile b/plugins/ZaMultiCompX2/Makefile index 61eaff1..ab019d4 100644 --- a/plugins/ZaMultiCompX2/Makefile +++ b/plugins/ZaMultiCompX2/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.cpp b/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.cpp index 4504d99..6e46d65 100644 --- a/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.cpp +++ b/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.cpp @@ -25,13 +25,13 @@ ZaMultiCompX2Plugin::ZaMultiCompX2Plugin() : Plugin(paramCount, 2, 0) { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZaMultiCompX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZaMultiCompX2Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -263,7 +263,7 @@ void ZaMultiCompX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZaMultiCompX2Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZaMultiCompX2Plugin::initProgramName(uint32_t index, String& programName) { switch(index) { case 0: @@ -333,12 +333,19 @@ void ZaMultiCompX2Plugin::loadProgram(uint32_t index) outr = -45.0; break; } + /* Default variable values */ + maxL = 0.f; + maxR = 0.f; + limit = 0.f; + + /* reset filter values */ + activate(); } // ----------------------------------------------------------------------- // Internal data -float ZaMultiCompX2Plugin::d_getParameterValue(uint32_t index) const +float ZaMultiCompX2Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -422,7 +429,7 @@ float ZaMultiCompX2Plugin::d_getParameterValue(uint32_t index) const } } -void ZaMultiCompX2Plugin::d_setParameterValue(uint32_t index, float value) +void ZaMultiCompX2Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -516,34 +523,20 @@ void ZaMultiCompX2Plugin::d_setParameterValue(uint32_t index, float value) } } -void ZaMultiCompX2Plugin::d_setProgram(uint32_t index) -{ - /* Default parameter values */ - loadProgram(index); - - /* Default variable values */ - maxL = 0.f; - maxR = 0.f; - limit = 0.f; - - /* reset filter values */ - d_activate(); -} - -void ZaMultiCompX2Plugin::d_setState(const char*, const char*) +void ZaMultiCompX2Plugin::setState(const char*, const char*) { resetl = true; resetr = true; } -void ZaMultiCompX2Plugin::d_initState(unsigned int, d_string&, d_string&) +void ZaMultiCompX2Plugin::initState(unsigned int, String&, String&) { } // ----------------------------------------------------------------------- // Process -void ZaMultiCompX2Plugin::d_activate() +void ZaMultiCompX2Plugin::activate() { int i,j; for (i = 0; i < MAX_COMP; i++) @@ -613,7 +606,7 @@ void ZaMultiCompX2Plugin::set_hp_coeffs(float fc, float q, float sr, int i, int void ZaMultiCompX2Plugin::run_limit(float inL, float inR, float *outL, float *outR) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float width=0.01; float threshdb = -0.5; float attack_coeff = exp(-1000.f/(0.001 * srate)); @@ -692,7 +685,7 @@ void ZaMultiCompX2Plugin::run_limit(float inL, float inR, float *outL, float *ou void ZaMultiCompX2Plugin::run_comp(int k, float inL, float inR, float *outL, float *outR) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float width=(knee-0.99f)*6.f; float attack_coeff = exp(-1000.f/(attack * srate)); float release_coeff = exp(-1000.f/(release * srate)); @@ -792,9 +785,9 @@ void ZaMultiCompX2Plugin::run_comp(int k, float inL, float inR, float *outL, flo old_yg[1][k] = Ryg; } -void ZaMultiCompX2Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZaMultiCompX2Plugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float maxxL = maxL; float maxxR = maxR; diff --git a/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.hpp b/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.hpp index a7ee283..bfa525b 100644 --- a/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.hpp +++ b/plugins/ZaMultiCompX2/ZaMultiCompX2Plugin.hpp @@ -83,27 +83,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZaMultiCompX2"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'M', 'M', '2'); } @@ -111,19 +111,18 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; - void d_initState(uint32_t, d_string&, d_string&) override; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; + void initState(uint32_t, String&, String&) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; - void d_setState(const char* key, const char* value) override; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; + void setState(const char* key, const char* value) override; - void loadProgram(uint32_t index); // ------------------------------------------------------------------- // Process @@ -150,8 +149,8 @@ protected: void set_lp_coeffs(float fc, float q, float sr, int i, int ch, float gain); void set_hp_coeffs(float fc, float q, float sr, int i, int ch, float gain); - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZaMultiCompX2/ZaMultiCompX2UI.cpp b/plugins/ZaMultiCompX2/ZaMultiCompX2UI.cpp index 5bd92d3..9f82730 100644 --- a/plugins/ZaMultiCompX2/ZaMultiCompX2UI.cpp +++ b/plugins/ZaMultiCompX2/ZaMultiCompX2UI.cpp @@ -218,7 +218,7 @@ ZaMultiCompX2UI::ZaMultiCompX2UI() } // set default values - d_programChanged(0); + programLoaded(0); } void ZaMultiCompX2UI::compcurve(float in, int k, float *outx, float* outy) { @@ -274,7 +274,7 @@ void ZaMultiCompX2UI::calc_compcurves() { // ----------------------------------------------------------------------- // DSP Callbacks -void ZaMultiCompX2UI::d_parameterChanged(uint32_t index, float value) +void ZaMultiCompX2UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -409,7 +409,7 @@ void ZaMultiCompX2UI::d_parameterChanged(uint32_t index, float value) } } -void ZaMultiCompX2UI::d_programChanged(uint32_t index) +void ZaMultiCompX2UI::programLoaded(uint32_t index) { if (index != 0) return; @@ -436,7 +436,7 @@ void ZaMultiCompX2UI::d_programChanged(uint32_t index) fToggleStereo->setValue(0.0f); } -void ZaMultiCompX2UI::d_stateChanged(const char*, const char*) +void ZaMultiCompX2UI::stateChanged(const char*, const char*) { } @@ -446,141 +446,141 @@ void ZaMultiCompX2UI::d_stateChanged(const char*, const char*) void ZaMultiCompX2UI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobAttack) - d_editParameter(ZaMultiCompX2Plugin::paramAttack, true); + editParameter(ZaMultiCompX2Plugin::paramAttack, true); else if (knob == fKnobRelease) - d_editParameter(ZaMultiCompX2Plugin::paramRelease, true); + editParameter(ZaMultiCompX2Plugin::paramRelease, true); else if (knob == fKnobThresh1) - d_editParameter(ZaMultiCompX2Plugin::paramThresh1, true); + editParameter(ZaMultiCompX2Plugin::paramThresh1, true); else if (knob == fKnobThresh2) - d_editParameter(ZaMultiCompX2Plugin::paramThresh2, true); + editParameter(ZaMultiCompX2Plugin::paramThresh2, true); else if (knob == fKnobThresh3) - d_editParameter(ZaMultiCompX2Plugin::paramThresh3, true); + editParameter(ZaMultiCompX2Plugin::paramThresh3, true); else if (knob == fKnobRatio) - d_editParameter(ZaMultiCompX2Plugin::paramRatio, true); + editParameter(ZaMultiCompX2Plugin::paramRatio, true); else if (knob == fKnobKnee) - d_editParameter(ZaMultiCompX2Plugin::paramKnee, true); + editParameter(ZaMultiCompX2Plugin::paramKnee, true); else if (knob == fKnobGlobalGain) - d_editParameter(ZaMultiCompX2Plugin::paramGlobalGain, true); + editParameter(ZaMultiCompX2Plugin::paramGlobalGain, true); else if (knob == fKnobMakeup1) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup1, true); + editParameter(ZaMultiCompX2Plugin::paramMakeup1, true); else if (knob == fKnobMakeup2) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup2, true); + editParameter(ZaMultiCompX2Plugin::paramMakeup2, true); else if (knob == fKnobMakeup3) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup3, true); + editParameter(ZaMultiCompX2Plugin::paramMakeup3, true); else if (knob == fKnobXover1) - d_editParameter(ZaMultiCompX2Plugin::paramXover1, true); + editParameter(ZaMultiCompX2Plugin::paramXover1, true); else if (knob == fKnobXover2) - d_editParameter(ZaMultiCompX2Plugin::paramXover2, true); + editParameter(ZaMultiCompX2Plugin::paramXover2, true); } void ZaMultiCompX2UI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobAttack) - d_editParameter(ZaMultiCompX2Plugin::paramAttack, false); + editParameter(ZaMultiCompX2Plugin::paramAttack, false); else if (knob == fKnobRelease) - d_editParameter(ZaMultiCompX2Plugin::paramRelease, false); + editParameter(ZaMultiCompX2Plugin::paramRelease, false); else if (knob == fKnobThresh1) - d_editParameter(ZaMultiCompX2Plugin::paramThresh1, false); + editParameter(ZaMultiCompX2Plugin::paramThresh1, false); else if (knob == fKnobThresh2) - d_editParameter(ZaMultiCompX2Plugin::paramThresh2, false); + editParameter(ZaMultiCompX2Plugin::paramThresh2, false); else if (knob == fKnobThresh3) - d_editParameter(ZaMultiCompX2Plugin::paramThresh3, false); + editParameter(ZaMultiCompX2Plugin::paramThresh3, false); else if (knob == fKnobRatio) - d_editParameter(ZaMultiCompX2Plugin::paramRatio, false); + editParameter(ZaMultiCompX2Plugin::paramRatio, false); else if (knob == fKnobKnee) - d_editParameter(ZaMultiCompX2Plugin::paramKnee, false); + editParameter(ZaMultiCompX2Plugin::paramKnee, false); else if (knob == fKnobGlobalGain) - d_editParameter(ZaMultiCompX2Plugin::paramGlobalGain, false); + editParameter(ZaMultiCompX2Plugin::paramGlobalGain, false); else if (knob == fKnobMakeup1) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup1, false); + editParameter(ZaMultiCompX2Plugin::paramMakeup1, false); else if (knob == fKnobMakeup2) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup2, false); + editParameter(ZaMultiCompX2Plugin::paramMakeup2, false); else if (knob == fKnobMakeup3) - d_editParameter(ZaMultiCompX2Plugin::paramMakeup3, false); + editParameter(ZaMultiCompX2Plugin::paramMakeup3, false); else if (knob == fKnobXover1) - d_editParameter(ZaMultiCompX2Plugin::paramXover1, false); + editParameter(ZaMultiCompX2Plugin::paramXover1, false); else if (knob == fKnobXover2) - d_editParameter(ZaMultiCompX2Plugin::paramXover2, false); + editParameter(ZaMultiCompX2Plugin::paramXover2, false); } void ZaMultiCompX2UI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobAttack) - d_setParameterValue(ZaMultiCompX2Plugin::paramAttack, value); + setParameterValue(ZaMultiCompX2Plugin::paramAttack, value); else if (knob == fKnobRelease) - d_setParameterValue(ZaMultiCompX2Plugin::paramRelease, value); + setParameterValue(ZaMultiCompX2Plugin::paramRelease, value); else if (knob == fKnobThresh1) { - d_setParameterValue(ZaMultiCompX2Plugin::paramThresh1, value); + setParameterValue(ZaMultiCompX2Plugin::paramThresh1, value); fThresh[0] = value; } else if (knob == fKnobThresh2) { - d_setParameterValue(ZaMultiCompX2Plugin::paramThresh2, value); + setParameterValue(ZaMultiCompX2Plugin::paramThresh2, value); fThresh[1] = value; } else if (knob == fKnobThresh3) { - d_setParameterValue(ZaMultiCompX2Plugin::paramThresh3, value); + setParameterValue(ZaMultiCompX2Plugin::paramThresh3, value); fThresh[2] = value; } else if (knob == fKnobRatio) { - d_setParameterValue(ZaMultiCompX2Plugin::paramRatio, value); + setParameterValue(ZaMultiCompX2Plugin::paramRatio, value); fRatio = value; } else if (knob == fKnobKnee) { - d_setParameterValue(ZaMultiCompX2Plugin::paramKnee, value); + setParameterValue(ZaMultiCompX2Plugin::paramKnee, value); fKnee = value; } else if (knob == fKnobGlobalGain) { - d_setParameterValue(ZaMultiCompX2Plugin::paramGlobalGain, value); + setParameterValue(ZaMultiCompX2Plugin::paramGlobalGain, value); fMaster = value; } else if (knob == fKnobMakeup1) { - d_setParameterValue(ZaMultiCompX2Plugin::paramMakeup1, value); + setParameterValue(ZaMultiCompX2Plugin::paramMakeup1, value); fMakeup[0] = value; } else if (knob == fKnobMakeup2) { - d_setParameterValue(ZaMultiCompX2Plugin::paramMakeup2, value); + setParameterValue(ZaMultiCompX2Plugin::paramMakeup2, value); fMakeup[1] = value; } else if (knob == fKnobMakeup3) { - d_setParameterValue(ZaMultiCompX2Plugin::paramMakeup3, value); + setParameterValue(ZaMultiCompX2Plugin::paramMakeup3, value); fMakeup[2] = value; } else if (knob == fKnobXover1) - d_setParameterValue(ZaMultiCompX2Plugin::paramXover1, value); + setParameterValue(ZaMultiCompX2Plugin::paramXover1, value); else if (knob == fKnobXover2) - d_setParameterValue(ZaMultiCompX2Plugin::paramXover2, value); + setParameterValue(ZaMultiCompX2Plugin::paramXover2, value); } void ZaMultiCompX2UI::imageToggleClicked(ImageToggle* toggle, int) { float v = toggle->getValue(); if (toggle == fToggleBypass1) { - d_setParameterValue(ZaMultiCompX2Plugin::paramToggle1, v); + setParameterValue(ZaMultiCompX2Plugin::paramToggle1, v); fBypass[0] = v; } else if (toggle == fToggleBypass2) { - d_setParameterValue(ZaMultiCompX2Plugin::paramToggle2, v); + setParameterValue(ZaMultiCompX2Plugin::paramToggle2, v); fBypass[1] = v; } else if (toggle == fToggleBypass3) { - d_setParameterValue(ZaMultiCompX2Plugin::paramToggle3, v); + setParameterValue(ZaMultiCompX2Plugin::paramToggle3, v); fBypass[2] = v; } else if (toggle == fToggleListen1) - d_setParameterValue(ZaMultiCompX2Plugin::paramListen1, v); + setParameterValue(ZaMultiCompX2Plugin::paramListen1, v); else if (toggle == fToggleListen2) - d_setParameterValue(ZaMultiCompX2Plugin::paramListen2, v); + setParameterValue(ZaMultiCompX2Plugin::paramListen2, v); else if (toggle == fToggleListen3) - d_setParameterValue(ZaMultiCompX2Plugin::paramListen3, v); + setParameterValue(ZaMultiCompX2Plugin::paramListen3, v); else if (toggle == fToggleStereo) - d_setParameterValue(ZaMultiCompX2Plugin::paramStereoDet, v); + setParameterValue(ZaMultiCompX2Plugin::paramStereoDet, v); } void ZaMultiCompX2UI::onDisplay() { fImgBackground.draw(); - d_setState("stateMeterReset", ""); + setState("stateMeterReset", ""); // draw leds static const float sLedSpacing = 15.5f; diff --git a/plugins/ZaMultiCompX2/ZaMultiCompX2UI.hpp b/plugins/ZaMultiCompX2/ZaMultiCompX2UI.hpp index d9023f4..9afa5b5 100644 --- a/plugins/ZaMultiCompX2/ZaMultiCompX2UI.hpp +++ b/plugins/ZaMultiCompX2/ZaMultiCompX2UI.hpp @@ -52,9 +52,9 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; - void d_stateChanged(const char*, const char*) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; + void stateChanged(const char*, const char*) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamAutoSat/DistrhoPluginInfo.h b/plugins/ZamAutoSat/DistrhoPluginInfo.h index 9ee8f5e..aa2a80d 100644 --- a/plugins/ZamAutoSat/DistrhoPluginInfo.h +++ b/plugins/ZamAutoSat/DistrhoPluginInfo.h @@ -27,7 +27,7 @@ #define DISTRHO_PLUGIN_NUM_OUTPUTS 1 #define DISTRHO_PLUGIN_WANT_LATENCY 0 -#define DISTRHO_PLUGIN_WANT_PROGRAMS 1 +#define DISTRHO_PLUGIN_WANT_PROGRAMS 0 #define DISTRHO_PLUGIN_WANT_STATE 0 #define DISTRHO_PLUGIN_WANT_TIMEPOS 0 #define DISTRHO_PLUGIN_IS_RT_SAFE 1 diff --git a/plugins/ZamAutoSat/Makefile b/plugins/ZamAutoSat/Makefile index 267c9dc..b73f088 100644 --- a/plugins/ZamAutoSat/Makefile +++ b/plugins/ZamAutoSat/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamAutoSat/ZamAutoSatPlugin.cpp b/plugins/ZamAutoSat/ZamAutoSatPlugin.cpp index d617d07..cb90056 100644 --- a/plugins/ZamAutoSat/ZamAutoSatPlugin.cpp +++ b/plugins/ZamAutoSat/ZamAutoSatPlugin.cpp @@ -22,13 +22,10 @@ START_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- ZamAutoSatPlugin::ZamAutoSatPlugin() - : Plugin(paramCount, 1, 0) // 1 program, 0 states + : Plugin(paramCount, 0, 0) // 0 programs, 0 states { - // set default values - d_setProgram(0); - // reset - d_deactivate(); + deactivate(); } ZamAutoSatPlugin::~ZamAutoSatPlugin() @@ -38,50 +35,34 @@ ZamAutoSatPlugin::~ZamAutoSatPlugin() // ----------------------------------------------------------------------- // Init -void ZamAutoSatPlugin::d_initParameter(uint32_t, Parameter&) +void ZamAutoSatPlugin::initParameter(uint32_t, Parameter&) { } -void ZamAutoSatPlugin::d_initProgramName(uint32_t index, d_string& programName) -{ - if (index != 0) - return; - - programName = "Default"; -} - // ----------------------------------------------------------------------- // Internal data -float ZamAutoSatPlugin::d_getParameterValue(uint32_t) const +float ZamAutoSatPlugin::getParameterValue(uint32_t) const { return 0.0f; } -void ZamAutoSatPlugin::d_setParameterValue(uint32_t, float) +void ZamAutoSatPlugin::setParameterValue(uint32_t, float) { } -void ZamAutoSatPlugin::d_setProgram(uint32_t index) -{ - if (index != 0) - return; - - d_activate(); -} - // ----------------------------------------------------------------------- // Process -void ZamAutoSatPlugin::d_activate() +void ZamAutoSatPlugin::activate() { } -void ZamAutoSatPlugin::d_deactivate() +void ZamAutoSatPlugin::deactivate() { } -void ZamAutoSatPlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamAutoSatPlugin::run(const float** inputs, float** outputs, uint32_t frames) { uint32_t i; for (i = 0; i < frames; i++) { diff --git a/plugins/ZamAutoSat/ZamAutoSatPlugin.hpp b/plugins/ZamAutoSat/ZamAutoSatPlugin.hpp index 0933397..194527e 100644 --- a/plugins/ZamAutoSat/ZamAutoSatPlugin.hpp +++ b/plugins/ZamAutoSat/ZamAutoSatPlugin.hpp @@ -39,27 +39,27 @@ protected: // -------------------------------------------------------------------
// Information
- const char* d_getLabel() const noexcept override
+ const char* getLabel() const noexcept override
{
return "ZamAutoSat";
}
- const char* d_getMaker() const noexcept override
+ const char* getMaker() const noexcept override
{
return "Damien Zammit";
}
- const char* d_getLicense() const noexcept override
+ const char* getLicense() const noexcept override
{
return "GPL v2+";
}
- uint32_t d_getVersion() const noexcept override
+ uint32_t getVersion() const noexcept override
{
return 0x1000;
}
- int64_t d_getUniqueId() const noexcept override
+ int64_t getUniqueId() const noexcept override
{
return d_cconst('Z', 'S', 'A', 'T');
}
@@ -67,20 +67,18 @@ protected: // -------------------------------------------------------------------
// Init
- void d_initParameter(uint32_t index, Parameter& parameter) ;
- void d_initProgramName(uint32_t index, d_string& programName) ;
+ void initParameter(uint32_t index, Parameter& parameter) override;
// -------------------------------------------------------------------
// Internal data
- float d_getParameterValue(uint32_t index) const ;
- void d_setParameterValue(uint32_t index, float value) ;
- void d_setProgram(uint32_t index) ;
+ float getParameterValue(uint32_t index) const override;
+ void setParameterValue(uint32_t index, float value) override;
// -------------------------------------------------------------------
- void d_activate() ;
- void d_deactivate() ;
- void d_run(const float** inputs, float** outputs, uint32_t frames) override;
+ void activate() override;
+ void deactivate() override;
+ void run(const float** inputs, float** outputs, uint32_t frames) override;
// -------------------------------------------------------------------
diff --git a/plugins/ZamAutoSat/ZamAutoSatUI.cpp b/plugins/ZamAutoSat/ZamAutoSatUI.cpp index 2857f11..a087d7d 100644 --- a/plugins/ZamAutoSat/ZamAutoSatUI.cpp +++ b/plugins/ZamAutoSat/ZamAutoSatUI.cpp @@ -38,11 +38,7 @@ ZamAutoSatUI::~ZamAutoSatUI() // ----------------------------------------------------------------------- // DSP Callbacks -void ZamAutoSatUI::d_parameterChanged(uint32_t, float) -{ -} - -void ZamAutoSatUI::d_programChanged(uint32_t) +void ZamAutoSatUI::parameterChanged(uint32_t, float) { } diff --git a/plugins/ZamAutoSat/ZamAutoSatUI.hpp b/plugins/ZamAutoSat/ZamAutoSatUI.hpp index 59cefa7..c19b984 100644 --- a/plugins/ZamAutoSat/ZamAutoSatUI.hpp +++ b/plugins/ZamAutoSat/ZamAutoSatUI.hpp @@ -41,8 +41,7 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) ; + void parameterChanged(uint32_t index, float value) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamChild670/Makefile b/plugins/ZamChild670/Makefile index e073ead..a5ade5d 100644 --- a/plugins/ZamChild670/Makefile +++ b/plugins/ZamChild670/Makefile @@ -32,10 +32,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamChild670/ZamChild670Plugin.cpp b/plugins/ZamChild670/ZamChild670Plugin.cpp index 71a2378..7403723 100644 --- a/plugins/ZamChild670/ZamChild670Plugin.cpp +++ b/plugins/ZamChild670/ZamChild670Plugin.cpp @@ -34,8 +34,8 @@ ZamChild670Plugin::ZamChild670Plugin() ACThreshold, timeConstantSelect, DCThreshold, inputLevel, ACThreshold, timeConstantSelect, DCThreshold, true, false, true, outputGain, false); - zamchild = new Wavechild670(d_getSampleRate(), *params); - d_setProgram(0); + zamchild = new Wavechild670(getSampleRate(), *params); + loadProgram(0); } ZamChild670Plugin::~ZamChild670Plugin() @@ -47,7 +47,7 @@ ZamChild670Plugin::~ZamChild670Plugin() // ----------------------------------------------------------------------- // Init -void ZamChild670Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamChild670Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -99,7 +99,7 @@ void ZamChild670Plugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamChild670Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamChild670Plugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -110,7 +110,7 @@ void ZamChild670Plugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamChild670Plugin::d_getParameterValue(uint32_t index) const +float ZamChild670Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -134,7 +134,7 @@ float ZamChild670Plugin::d_getParameterValue(uint32_t index) const } } -void ZamChild670Plugin::d_setParameterValue(uint32_t index, float value) +void ZamChild670Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -156,7 +156,7 @@ void ZamChild670Plugin::d_setParameterValue(uint32_t index, float value) } } -void ZamChild670Plugin::d_setProgram(uint32_t index) +void ZamChild670Plugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -169,13 +169,13 @@ void ZamChild670Plugin::d_setProgram(uint32_t index) outputGain = from_dB(0.0); /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamChild670Plugin::d_activate() +void ZamChild670Plugin::activate() { params->inputLevelA = params->inputLevelB = from_dB(inputLevel); params->ACThresholdA = params->ACThresholdB = ACThreshold; @@ -186,7 +186,7 @@ void ZamChild670Plugin::d_activate() zamchild->warmUp(); } -void ZamChild670Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamChild670Plugin::run(const float** inputs, float** outputs, uint32_t frames) { params->inputLevelA = params->inputLevelB = from_dB(inputLevel); params->ACThresholdA = params->ACThresholdB = ACThreshold; diff --git a/plugins/ZamChild670/ZamChild670Plugin.hpp b/plugins/ZamChild670/ZamChild670Plugin.hpp index 762d547..1900ca9 100644 --- a/plugins/ZamChild670/ZamChild670Plugin.hpp +++ b/plugins/ZamChild670/ZamChild670Plugin.hpp @@ -45,27 +45,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamChild670"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'C', 'L', 'D'); } @@ -73,15 +73,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -103,8 +103,8 @@ protected: return (20.f*log10(g)); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamChild670/ZamChild670UI.cpp b/plugins/ZamChild670/ZamChild670UI.cpp index 8416781..8b602a1 100644 --- a/plugins/ZamChild670/ZamChild670UI.cpp +++ b/plugins/ZamChild670/ZamChild670UI.cpp @@ -67,13 +67,13 @@ ZamChild670UI::ZamChild670UI() fKnobOutgain->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamChild670UI::d_parameterChanged(uint32_t index, float value) +void ZamChild670UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -92,7 +92,7 @@ void ZamChild670UI::d_parameterChanged(uint32_t index, float value) } } -void ZamChild670UI::d_programChanged(uint32_t) +void ZamChild670UI::programLoaded(uint32_t) { // Default values fKnobIngain->setValue(-12.0f); @@ -106,17 +106,17 @@ void ZamChild670UI::d_programChanged(uint32_t) void ZamChild670UI::imageKnobDragStarted(ImageKnob* knob) { - d_editParameter(knob->getId(), true); + editParameter(knob->getId(), true); } void ZamChild670UI::imageKnobDragFinished(ImageKnob* knob) { - d_editParameter(knob->getId(), false); + editParameter(knob->getId(), false); } void ZamChild670UI::imageKnobValueChanged(ImageKnob* knob, float value) { - d_setParameterValue(knob->getId(), value); + setParameterValue(knob->getId(), value); } void ZamChild670UI::onDisplay() diff --git a/plugins/ZamChild670/ZamChild670UI.hpp b/plugins/ZamChild670/ZamChild670UI.hpp index 292f67e..80abe9c 100644 --- a/plugins/ZamChild670/ZamChild670UI.hpp +++ b/plugins/ZamChild670/ZamChild670UI.hpp @@ -40,8 +40,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamComp/Makefile b/plugins/ZamComp/Makefile index aff19e5..9e756a4 100644 --- a/plugins/ZamComp/Makefile +++ b/plugins/ZamComp/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamComp/ZamCompPlugin.cpp b/plugins/ZamComp/ZamCompPlugin.cpp index 93bea2d..3c125e3 100644 --- a/plugins/ZamComp/ZamCompPlugin.cpp +++ b/plugins/ZamComp/ZamCompPlugin.cpp @@ -25,13 +25,13 @@ ZamCompPlugin::ZamCompPlugin() : Plugin(paramCount, 3, 0) { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamCompPlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamCompPlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -110,7 +110,7 @@ void ZamCompPlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamCompPlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamCompPlugin::initProgramName(uint32_t index, String& programName) { switch(index) { case 0: @@ -159,12 +159,14 @@ void ZamCompPlugin::loadProgram(uint32_t index) outlevel = -45.0; break; } + /* reset filter values */ + activate(); } // ----------------------------------------------------------------------- // Internal data -float ZamCompPlugin::d_getParameterValue(uint32_t index) const +float ZamCompPlugin::getParameterValue(uint32_t index) const { switch (index) { case paramAttack: @@ -196,7 +198,7 @@ float ZamCompPlugin::d_getParameterValue(uint32_t index) const } } -void ZamCompPlugin::d_setParameterValue(uint32_t index, float value) +void ZamCompPlugin::setParameterValue(uint32_t index, float value) { switch (index) { case paramAttack: @@ -226,28 +228,19 @@ void ZamCompPlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamCompPlugin::d_setProgram(uint32_t index) -{ - /* Default parameter values */ - loadProgram(index); - - /* reset filter values */ - d_activate(); -} - // ----------------------------------------------------------------------- // Process -void ZamCompPlugin::d_activate() +void ZamCompPlugin::activate() { gainr = 0.0f; outlevel = -45.f; old_yl = old_y1 = old_yg = 0.0f; } -void ZamCompPlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamCompPlugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float width=(knee-0.99f)*6.f; float cdb=0.f; float attack_coeff = exp(-1000.f/(attack * srate)); diff --git a/plugins/ZamComp/ZamCompPlugin.hpp b/plugins/ZamComp/ZamCompPlugin.hpp index acbaf98..a1698b0 100644 --- a/plugins/ZamComp/ZamCompPlugin.hpp +++ b/plugins/ZamComp/ZamCompPlugin.hpp @@ -46,27 +46,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamComp"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'C', 'M', 'P'); } @@ -74,16 +74,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; - void loadProgram(uint32_t index); + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -105,8 +104,8 @@ protected: return (20.f*log10(g)); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamComp/ZamCompUI.cpp b/plugins/ZamComp/ZamCompUI.cpp index c7385ed..9cbdcca 100644 --- a/plugins/ZamComp/ZamCompUI.cpp +++ b/plugins/ZamComp/ZamCompUI.cpp @@ -98,13 +98,13 @@ ZamCompUI::ZamCompUI() fKnobMakeup->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamCompUI::d_parameterChanged(uint32_t index, float value) +void ZamCompUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -143,7 +143,7 @@ void ZamCompUI::d_parameterChanged(uint32_t index, float value) } } -void ZamCompUI::d_programChanged(uint32_t index) +void ZamCompUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -162,17 +162,17 @@ void ZamCompUI::d_programChanged(uint32_t index) void ZamCompUI::imageKnobDragStarted(ImageKnob* knob) { - d_editParameter(knob->getId(), true); + editParameter(knob->getId(), true); } void ZamCompUI::imageKnobDragFinished(ImageKnob* knob) { - d_editParameter(knob->getId(), false); + editParameter(knob->getId(), false); } void ZamCompUI::imageKnobValueChanged(ImageKnob* knob, float value) { - d_setParameterValue(knob->getId(), value); + setParameterValue(knob->getId(), value); } void ZamCompUI::onDisplay() diff --git a/plugins/ZamComp/ZamCompUI.hpp b/plugins/ZamComp/ZamCompUI.hpp index a4ee620..08f880c 100644 --- a/plugins/ZamComp/ZamCompUI.hpp +++ b/plugins/ZamComp/ZamCompUI.hpp @@ -39,8 +39,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamCompX2/Makefile b/plugins/ZamCompX2/Makefile index ea18465..229b1e9 100644 --- a/plugins/ZamCompX2/Makefile +++ b/plugins/ZamCompX2/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamCompX2/ZamCompX2Plugin.cpp b/plugins/ZamCompX2/ZamCompX2Plugin.cpp index 00f1160..b31936c 100644 --- a/plugins/ZamCompX2/ZamCompX2Plugin.cpp +++ b/plugins/ZamCompX2/ZamCompX2Plugin.cpp @@ -25,13 +25,13 @@ ZamCompX2Plugin::ZamCompX2Plugin() : Plugin(paramCount, 3, 0) { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamCompX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamCompX2Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -120,7 +120,7 @@ void ZamCompX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) } -void ZamCompX2Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamCompX2Plugin::initProgramName(uint32_t index, String& programName) { switch(index) { case 0: @@ -172,12 +172,14 @@ void ZamCompX2Plugin::loadProgram(uint32_t index) outlevel = -45.0; break; } + /* reset filter values */ + activate(); } // ----------------------------------------------------------------------- // Internal data -float ZamCompX2Plugin::d_getParameterValue(uint32_t index) const +float ZamCompX2Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -213,7 +215,7 @@ float ZamCompX2Plugin::d_getParameterValue(uint32_t index) const } } -void ZamCompX2Plugin::d_setParameterValue(uint32_t index, float value) +void ZamCompX2Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -247,28 +249,19 @@ void ZamCompX2Plugin::d_setParameterValue(uint32_t index, float value) } } -void ZamCompX2Plugin::d_setProgram(uint32_t index) -{ - /* Default parameter values */ - loadProgram(index); - - /* reset filter values */ - d_activate(); -} - // ----------------------------------------------------------------------- // Process -void ZamCompX2Plugin::d_activate() +void ZamCompX2Plugin::activate() { gainred = 0.0f; outlevel = -45.0f; oldL_yl = oldL_y1 = oldR_yl = oldR_y1 = oldL_yg = oldR_yg = 0.f; } -void ZamCompX2Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamCompX2Plugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); float width=(knee-0.99f)*6.f; float cdb=0.f; float attack_coeff = exp(-1000.f/(attack * srate)); diff --git a/plugins/ZamCompX2/ZamCompX2Plugin.hpp b/plugins/ZamCompX2/ZamCompX2Plugin.hpp index 82e8b6e..5d14ccb 100644 --- a/plugins/ZamCompX2/ZamCompX2Plugin.hpp +++ b/plugins/ZamCompX2/ZamCompX2Plugin.hpp @@ -51,27 +51,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamCompX2"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'C', 'P', '2'); } @@ -79,17 +79,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; - - void loadProgram(uint32_t index); + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -111,8 +109,8 @@ protected: return (20.f*log10(g)); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamCompX2/ZamCompX2UI.cpp b/plugins/ZamCompX2/ZamCompX2UI.cpp index 36b7a7f..7c4bcfc 100644 --- a/plugins/ZamCompX2/ZamCompX2UI.cpp +++ b/plugins/ZamCompX2/ZamCompX2UI.cpp @@ -108,13 +108,13 @@ ZamCompX2UI::ZamCompX2UI() fToggleStereo->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamCompX2UI::d_parameterChanged(uint32_t index, float value) +void ZamCompX2UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -156,7 +156,7 @@ void ZamCompX2UI::d_parameterChanged(uint32_t index, float value) } } -void ZamCompX2UI::d_programChanged(uint32_t index) +void ZamCompX2UI::programLoaded(uint32_t index) { if (index != 0) return; @@ -176,24 +176,24 @@ void ZamCompX2UI::d_programChanged(uint32_t index) void ZamCompX2UI::imageKnobDragStarted(ImageKnob* knob) { - d_editParameter(knob->getId(), true); + editParameter(knob->getId(), true); } void ZamCompX2UI::imageKnobDragFinished(ImageKnob* knob) { - d_editParameter(knob->getId(), false); + editParameter(knob->getId(), false); } void ZamCompX2UI::imageKnobValueChanged(ImageKnob* knob, float value) { - d_setParameterValue(knob->getId(), value); + setParameterValue(knob->getId(), value); } void ZamCompX2UI::imageToggleClicked(ImageToggle* imageToggle, int) { int flip = !imageToggle->getValue(); if (imageToggle == fToggleStereo) - d_setParameterValue(ZamCompX2Plugin::paramStereo, flip); + setParameterValue(ZamCompX2Plugin::paramStereo, flip); } void ZamCompX2UI::onDisplay() diff --git a/plugins/ZamCompX2/ZamCompX2UI.hpp b/plugins/ZamCompX2/ZamCompX2UI.hpp index 9eb1edb..53a03fe 100644 --- a/plugins/ZamCompX2/ZamCompX2UI.hpp +++ b/plugins/ZamCompX2/ZamCompX2UI.hpp @@ -44,8 +44,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamEQ2/Makefile b/plugins/ZamEQ2/Makefile index bbb2a8e..e951524 100644 --- a/plugins/ZamEQ2/Makefile +++ b/plugins/ZamEQ2/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamEQ2/ZamEQ2Plugin.cpp b/plugins/ZamEQ2/ZamEQ2Plugin.cpp index 8fa0207..126d039 100644 --- a/plugins/ZamEQ2/ZamEQ2Plugin.cpp +++ b/plugins/ZamEQ2/ZamEQ2Plugin.cpp @@ -25,13 +25,13 @@ ZamEQ2Plugin::ZamEQ2Plugin() : Plugin(paramCount, 4, 0) { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamEQ2Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamEQ2Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -146,7 +146,7 @@ void ZamEQ2Plugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamEQ2Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamEQ2Plugin::initProgramName(uint32_t index, String& programName) { switch(index) { case 0: @@ -224,12 +224,14 @@ void ZamEQ2Plugin::loadProgram(uint32_t index) togglepeaks = 0.0; break; } + /* reset filter values */ + activate(); } // ----------------------------------------------------------------------- // Internal data -float ZamEQ2Plugin::d_getParameterValue(uint32_t index) const +float ZamEQ2Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -274,7 +276,7 @@ float ZamEQ2Plugin::d_getParameterValue(uint32_t index) const } } -void ZamEQ2Plugin::d_setParameterValue(uint32_t index, float value) +void ZamEQ2Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -317,19 +319,10 @@ void ZamEQ2Plugin::d_setParameterValue(uint32_t index, float value) } } -void ZamEQ2Plugin::d_setProgram(uint32_t index) -{ - /* Default parameter values */ - loadProgram(index); - - /* reset filter values */ - d_activate(); -} - // ----------------------------------------------------------------------- // Process -void ZamEQ2Plugin::d_activate() +void ZamEQ2Plugin::activate() { int i; for (i = 0; i < MAX_FILT; ++i) { @@ -436,9 +429,9 @@ float ZamEQ2Plugin::run_filter(int i, int ch, double in) return (float) out; } -void ZamEQ2Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamEQ2Plugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); lowshelf(0, 0, srate, freql, gainl); peq(1, 0, srate, freq1, gain1, q1); diff --git a/plugins/ZamEQ2/ZamEQ2Plugin.hpp b/plugins/ZamEQ2/ZamEQ2Plugin.hpp index 2f67244..1597a05 100644 --- a/plugins/ZamEQ2/ZamEQ2Plugin.hpp +++ b/plugins/ZamEQ2/ZamEQ2Plugin.hpp @@ -52,27 +52,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamEQ2"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'E', 'Q', '2'); } @@ -80,17 +80,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; - - void loadProgram(uint32_t index); + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -117,8 +115,8 @@ protected: return (x >= 0.f ? 1 : -1); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; void peq(int i, int ch, float srate, float fc, float g, float bw); void lowshelf(int i, int ch, float srate, float fc, float g); diff --git a/plugins/ZamEQ2/ZamEQ2UI.cpp b/plugins/ZamEQ2/ZamEQ2UI.cpp index ba7f543..37722fd 100644 --- a/plugins/ZamEQ2/ZamEQ2UI.cpp +++ b/plugins/ZamEQ2/ZamEQ2UI.cpp @@ -127,13 +127,13 @@ ZamEQ2UI::ZamEQ2UI() fCanvasArea.setSize(305,180); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamEQ2UI::d_parameterChanged(uint32_t index, float value) +void ZamEQ2UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -173,7 +173,7 @@ void ZamEQ2UI::d_parameterChanged(uint32_t index, float value) } } -void ZamEQ2UI::d_programChanged(uint32_t index) +void ZamEQ2UI::programLoaded(uint32_t index) { if (index != 0) return; @@ -199,91 +199,91 @@ void ZamEQ2UI::d_programChanged(uint32_t index) void ZamEQ2UI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobGain1) - d_editParameter(ZamEQ2Plugin::paramGain1, true); + editParameter(ZamEQ2Plugin::paramGain1, true); else if (knob == fKnobQ1) - d_editParameter(ZamEQ2Plugin::paramQ1, true); + editParameter(ZamEQ2Plugin::paramQ1, true); else if (knob == fKnobFreq1) - d_editParameter(ZamEQ2Plugin::paramFreq1, true); + editParameter(ZamEQ2Plugin::paramFreq1, true); else if (knob == fKnobGain2) - d_editParameter(ZamEQ2Plugin::paramGain2, true); + editParameter(ZamEQ2Plugin::paramGain2, true); else if (knob == fKnobQ2) - d_editParameter(ZamEQ2Plugin::paramQ2, true); + editParameter(ZamEQ2Plugin::paramQ2, true); else if (knob == fKnobFreq2) - d_editParameter(ZamEQ2Plugin::paramFreq2, true); + editParameter(ZamEQ2Plugin::paramFreq2, true); else if (knob == fKnobGainL) - d_editParameter(ZamEQ2Plugin::paramGainL, true); + editParameter(ZamEQ2Plugin::paramGainL, true); else if (knob == fKnobFreqL) - d_editParameter(ZamEQ2Plugin::paramFreqL, true); + editParameter(ZamEQ2Plugin::paramFreqL, true); else if (knob == fKnobGainH) - d_editParameter(ZamEQ2Plugin::paramGainH, true); + editParameter(ZamEQ2Plugin::paramGainH, true); else if (knob == fKnobFreqH) - d_editParameter(ZamEQ2Plugin::paramFreqH, true); + editParameter(ZamEQ2Plugin::paramFreqH, true); } void ZamEQ2UI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobGain1) - d_editParameter(ZamEQ2Plugin::paramGain1, false); + editParameter(ZamEQ2Plugin::paramGain1, false); else if (knob == fKnobQ1) - d_editParameter(ZamEQ2Plugin::paramQ1, false); + editParameter(ZamEQ2Plugin::paramQ1, false); else if (knob == fKnobFreq1) - d_editParameter(ZamEQ2Plugin::paramFreq1, false); + editParameter(ZamEQ2Plugin::paramFreq1, false); else if (knob == fKnobGain2) - d_editParameter(ZamEQ2Plugin::paramGain2, false); + editParameter(ZamEQ2Plugin::paramGain2, false); else if (knob == fKnobQ2) - d_editParameter(ZamEQ2Plugin::paramQ2, false); + editParameter(ZamEQ2Plugin::paramQ2, false); else if (knob == fKnobFreq2) - d_editParameter(ZamEQ2Plugin::paramFreq2, false); + editParameter(ZamEQ2Plugin::paramFreq2, false); else if (knob == fKnobGainL) - d_editParameter(ZamEQ2Plugin::paramGainL, false); + editParameter(ZamEQ2Plugin::paramGainL, false); else if (knob == fKnobFreqL) - d_editParameter(ZamEQ2Plugin::paramFreqL, false); + editParameter(ZamEQ2Plugin::paramFreqL, false); else if (knob == fKnobGainH) - d_editParameter(ZamEQ2Plugin::paramGainH, false); + editParameter(ZamEQ2Plugin::paramGainH, false); else if (knob == fKnobFreqH) - d_editParameter(ZamEQ2Plugin::paramFreqH, false); + editParameter(ZamEQ2Plugin::paramFreqH, false); } void ZamEQ2UI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobGain1) - d_setParameterValue(ZamEQ2Plugin::paramGain1, value); + setParameterValue(ZamEQ2Plugin::paramGain1, value); else if (knob == fKnobQ1) - d_setParameterValue(ZamEQ2Plugin::paramQ1, value); + setParameterValue(ZamEQ2Plugin::paramQ1, value); else if (knob == fKnobFreq1) - d_setParameterValue(ZamEQ2Plugin::paramFreq1, value); + setParameterValue(ZamEQ2Plugin::paramFreq1, value); else if (knob == fKnobGain2) - d_setParameterValue(ZamEQ2Plugin::paramGain2, value); + setParameterValue(ZamEQ2Plugin::paramGain2, value); else if (knob == fKnobQ2) - d_setParameterValue(ZamEQ2Plugin::paramQ2, value); + setParameterValue(ZamEQ2Plugin::paramQ2, value); else if (knob == fKnobFreq2) - d_setParameterValue(ZamEQ2Plugin::paramFreq2, value); + setParameterValue(ZamEQ2Plugin::paramFreq2, value); else if (knob == fKnobGainL) - d_setParameterValue(ZamEQ2Plugin::paramGainL, value); + setParameterValue(ZamEQ2Plugin::paramGainL, value); else if (knob == fKnobFreqL) - d_setParameterValue(ZamEQ2Plugin::paramFreqL, value); + setParameterValue(ZamEQ2Plugin::paramFreqL, value); else if (knob == fKnobGainH) - d_setParameterValue(ZamEQ2Plugin::paramGainH, value); + setParameterValue(ZamEQ2Plugin::paramGainH, value); else if (knob == fKnobFreqH) - d_setParameterValue(ZamEQ2Plugin::paramFreqH, value); + setParameterValue(ZamEQ2Plugin::paramFreqH, value); } void ZamEQ2UI::imageSliderDragStarted(ImageSlider* slider) { if (slider == fSliderMaster) - d_editParameter(ZamEQ2Plugin::paramMaster, true); + editParameter(ZamEQ2Plugin::paramMaster, true); } void ZamEQ2UI::imageSliderDragFinished(ImageSlider* slider) { if (slider == fSliderMaster) - d_editParameter(ZamEQ2Plugin::paramMaster, false); + editParameter(ZamEQ2Plugin::paramMaster, false); } void ZamEQ2UI::imageSliderValueChanged(ImageSlider* slider, float value) { if (slider == fSliderMaster) - d_setParameterValue(ZamEQ2Plugin::paramMaster, value); + setParameterValue(ZamEQ2Plugin::paramMaster, value); } void ZamEQ2UI::lowshelf(int i, int ch, float srate, float fc, float g) @@ -367,7 +367,7 @@ void ZamEQ2UI::peq(int i, int ch, float srate, float fc, float g, float bw) void ZamEQ2UI::calceqcurve(float x[], float y[]) { - float SR = d_getSampleRate(); + float SR = getSampleRate(); float p1 = 10000.; float p2 = 5000.; float c2 = log10(1.+SR); diff --git a/plugins/ZamEQ2/ZamEQ2UI.hpp b/plugins/ZamEQ2/ZamEQ2UI.hpp index 0b4bb80..53ce272 100644 --- a/plugins/ZamEQ2/ZamEQ2UI.hpp +++ b/plugins/ZamEQ2/ZamEQ2UI.hpp @@ -97,8 +97,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamGEQ31/Makefile b/plugins/ZamGEQ31/Makefile index 3badc26..97864db 100644 --- a/plugins/ZamGEQ31/Makefile +++ b/plugins/ZamGEQ31/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamGEQ31/ZamGEQ31Plugin.cpp b/plugins/ZamGEQ31/ZamGEQ31Plugin.cpp index aac00ea..a674bec 100644 --- a/plugins/ZamGEQ31/ZamGEQ31Plugin.cpp +++ b/plugins/ZamGEQ31/ZamGEQ31Plugin.cpp @@ -25,13 +25,13 @@ ZamGEQ31Plugin::ZamGEQ31Plugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamGEQ31Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamGEQ31Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -326,7 +326,7 @@ void ZamGEQ31Plugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamGEQ31Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamGEQ31Plugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -337,7 +337,7 @@ void ZamGEQ31Plugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamGEQ31Plugin::d_getParameterValue(uint32_t index) const +float ZamGEQ31Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -442,7 +442,7 @@ float ZamGEQ31Plugin::d_getParameterValue(uint32_t index) const } } -void ZamGEQ31Plugin::d_setParameterValue(uint32_t index, float value) +void ZamGEQ31Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -590,7 +590,7 @@ double ZamGEQ31Plugin::run_filter(int i, int ch, double in) return out; } -void ZamGEQ31Plugin::d_setProgram(uint32_t index) +void ZamGEQ31Plugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -633,19 +633,19 @@ void ZamGEQ31Plugin::d_setProgram(uint32_t index) freq[29] = 16000.; freq[30] = 20000.; master = 0.f; - float srate = d_getSampleRate(); + float srate = getSampleRate(); for (int i=0; i < MAX_FILT; ++i) { peq(i, srate, freq[i], 0., 1./3.); } /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamGEQ31Plugin::d_activate() +void ZamGEQ31Plugin::activate() { int i; for (i = 0; i < MAX_FILT; ++i) { @@ -682,9 +682,9 @@ double ZamGEQ31Plugin::run_filter(int i, int ch, double in) } */ -void ZamGEQ31Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamGEQ31Plugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); int i; for (i = 0; i < MAX_FILT; i++) { diff --git a/plugins/ZamGEQ31/ZamGEQ31Plugin.hpp b/plugins/ZamGEQ31/ZamGEQ31Plugin.hpp index fae6b8c..2520c9d 100644 --- a/plugins/ZamGEQ31/ZamGEQ31Plugin.hpp +++ b/plugins/ZamGEQ31/ZamGEQ31Plugin.hpp @@ -72,27 +72,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamGEQ31"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1001; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'G', '3', '1'); } @@ -100,15 +100,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -135,8 +135,8 @@ protected: return (x >= 0.f ? 1 : -1); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; void peq(int i, float srate, float fc, float g, float bw); double run_filter(int i, int ch, double in); diff --git a/plugins/ZamGEQ31/ZamGEQ31UI.cpp b/plugins/ZamGEQ31/ZamGEQ31UI.cpp index 1db4782..f6f1c6d 100644 --- a/plugins/ZamGEQ31/ZamGEQ31UI.cpp +++ b/plugins/ZamGEQ31/ZamGEQ31UI.cpp @@ -390,13 +390,13 @@ ZamGEQ31UI::ZamGEQ31UI() fSliderGain31->setInverted(true); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamGEQ31UI::d_parameterChanged(uint32_t index, float value) +void ZamGEQ31UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -499,7 +499,7 @@ void ZamGEQ31UI::d_parameterChanged(uint32_t index, float value) } } -void ZamGEQ31UI::d_programChanged(uint32_t index) +void ZamGEQ31UI::programLoaded(uint32_t index) { if (index != 0) return; @@ -546,217 +546,217 @@ void ZamGEQ31UI::d_programChanged(uint32_t index) void ZamGEQ31UI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobMaster) - d_editParameter(ZamGEQ31Plugin::paramMaster, true); + editParameter(ZamGEQ31Plugin::paramMaster, true); } void ZamGEQ31UI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobMaster) - d_editParameter(ZamGEQ31Plugin::paramMaster, false); + editParameter(ZamGEQ31Plugin::paramMaster, false); } void ZamGEQ31UI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobMaster) - d_setParameterValue(ZamGEQ31Plugin::paramMaster, value); + setParameterValue(ZamGEQ31Plugin::paramMaster, value); } void ZamGEQ31UI::imageSliderDragStarted(ImageSlider* slider) { if (slider == fSliderGain1) - d_editParameter(ZamGEQ31Plugin::paramGain1, true); + editParameter(ZamGEQ31Plugin::paramGain1, true); else if (slider == fSliderGain2) - d_editParameter(ZamGEQ31Plugin::paramGain2, true); + editParameter(ZamGEQ31Plugin::paramGain2, true); else if (slider == fSliderGain3) - d_editParameter(ZamGEQ31Plugin::paramGain3, true); + editParameter(ZamGEQ31Plugin::paramGain3, true); else if (slider == fSliderGain4) - d_editParameter(ZamGEQ31Plugin::paramGain4, true); + editParameter(ZamGEQ31Plugin::paramGain4, true); else if (slider == fSliderGain5) - d_editParameter(ZamGEQ31Plugin::paramGain5, true); + editParameter(ZamGEQ31Plugin::paramGain5, true); else if (slider == fSliderGain6) - d_editParameter(ZamGEQ31Plugin::paramGain6, true); + editParameter(ZamGEQ31Plugin::paramGain6, true); else if (slider == fSliderGain7) - d_editParameter(ZamGEQ31Plugin::paramGain7, true); + editParameter(ZamGEQ31Plugin::paramGain7, true); else if (slider == fSliderGain8) - d_editParameter(ZamGEQ31Plugin::paramGain8, true); + editParameter(ZamGEQ31Plugin::paramGain8, true); else if (slider == fSliderGain9) - d_editParameter(ZamGEQ31Plugin::paramGain9, true); + editParameter(ZamGEQ31Plugin::paramGain9, true); else if (slider == fSliderGain10) - d_editParameter(ZamGEQ31Plugin::paramGain10, true); + editParameter(ZamGEQ31Plugin::paramGain10, true); else if (slider == fSliderGain11) - d_editParameter(ZamGEQ31Plugin::paramGain11, true); + editParameter(ZamGEQ31Plugin::paramGain11, true); else if (slider == fSliderGain12) - d_editParameter(ZamGEQ31Plugin::paramGain12, true); + editParameter(ZamGEQ31Plugin::paramGain12, true); else if (slider == fSliderGain13) - d_editParameter(ZamGEQ31Plugin::paramGain13, true); + editParameter(ZamGEQ31Plugin::paramGain13, true); else if (slider == fSliderGain14) - d_editParameter(ZamGEQ31Plugin::paramGain14, true); + editParameter(ZamGEQ31Plugin::paramGain14, true); else if (slider == fSliderGain15) - d_editParameter(ZamGEQ31Plugin::paramGain15, true); + editParameter(ZamGEQ31Plugin::paramGain15, true); else if (slider == fSliderGain16) - d_editParameter(ZamGEQ31Plugin::paramGain16, true); + editParameter(ZamGEQ31Plugin::paramGain16, true); else if (slider == fSliderGain17) - d_editParameter(ZamGEQ31Plugin::paramGain17, true); + editParameter(ZamGEQ31Plugin::paramGain17, true); else if (slider == fSliderGain18) - d_editParameter(ZamGEQ31Plugin::paramGain18, true); + editParameter(ZamGEQ31Plugin::paramGain18, true); else if (slider == fSliderGain19) - d_editParameter(ZamGEQ31Plugin::paramGain19, true); + editParameter(ZamGEQ31Plugin::paramGain19, true); else if (slider == fSliderGain20) - d_editParameter(ZamGEQ31Plugin::paramGain20, true); + editParameter(ZamGEQ31Plugin::paramGain20, true); else if (slider == fSliderGain21) - d_editParameter(ZamGEQ31Plugin::paramGain21, true); + editParameter(ZamGEQ31Plugin::paramGain21, true); else if (slider == fSliderGain22) - d_editParameter(ZamGEQ31Plugin::paramGain22, true); + editParameter(ZamGEQ31Plugin::paramGain22, true); else if (slider == fSliderGain23) - d_editParameter(ZamGEQ31Plugin::paramGain23, true); + editParameter(ZamGEQ31Plugin::paramGain23, true); else if (slider == fSliderGain24) - d_editParameter(ZamGEQ31Plugin::paramGain24, true); + editParameter(ZamGEQ31Plugin::paramGain24, true); else if (slider == fSliderGain25) - d_editParameter(ZamGEQ31Plugin::paramGain25, true); + editParameter(ZamGEQ31Plugin::paramGain25, true); else if (slider == fSliderGain26) - d_editParameter(ZamGEQ31Plugin::paramGain26, true); + editParameter(ZamGEQ31Plugin::paramGain26, true); else if (slider == fSliderGain27) - d_editParameter(ZamGEQ31Plugin::paramGain27, true); + editParameter(ZamGEQ31Plugin::paramGain27, true); else if (slider == fSliderGain28) - d_editParameter(ZamGEQ31Plugin::paramGain28, true); + editParameter(ZamGEQ31Plugin::paramGain28, true); else if (slider == fSliderGain29) - d_editParameter(ZamGEQ31Plugin::paramGain29, true); + editParameter(ZamGEQ31Plugin::paramGain29, true); else if (slider == fSliderGain30) - d_editParameter(ZamGEQ31Plugin::paramGain30, true); + editParameter(ZamGEQ31Plugin::paramGain30, true); else if (slider == fSliderGain31) - d_editParameter(ZamGEQ31Plugin::paramGain31, true); + editParameter(ZamGEQ31Plugin::paramGain31, true); } void ZamGEQ31UI::imageSliderDragFinished(ImageSlider* slider) { if (slider == fSliderGain1) - d_editParameter(ZamGEQ31Plugin::paramGain1, false); + editParameter(ZamGEQ31Plugin::paramGain1, false); else if (slider == fSliderGain2) - d_editParameter(ZamGEQ31Plugin::paramGain2, false); + editParameter(ZamGEQ31Plugin::paramGain2, false); else if (slider == fSliderGain3) - d_editParameter(ZamGEQ31Plugin::paramGain3, false); + editParameter(ZamGEQ31Plugin::paramGain3, false); else if (slider == fSliderGain4) - d_editParameter(ZamGEQ31Plugin::paramGain4, false); + editParameter(ZamGEQ31Plugin::paramGain4, false); else if (slider == fSliderGain5) - d_editParameter(ZamGEQ31Plugin::paramGain5, false); + editParameter(ZamGEQ31Plugin::paramGain5, false); else if (slider == fSliderGain6) - d_editParameter(ZamGEQ31Plugin::paramGain6, false); + editParameter(ZamGEQ31Plugin::paramGain6, false); else if (slider == fSliderGain7) - d_editParameter(ZamGEQ31Plugin::paramGain7, false); + editParameter(ZamGEQ31Plugin::paramGain7, false); else if (slider == fSliderGain8) - d_editParameter(ZamGEQ31Plugin::paramGain8, false); + editParameter(ZamGEQ31Plugin::paramGain8, false); else if (slider == fSliderGain9) - d_editParameter(ZamGEQ31Plugin::paramGain9, false); + editParameter(ZamGEQ31Plugin::paramGain9, false); else if (slider == fSliderGain10) - d_editParameter(ZamGEQ31Plugin::paramGain10, false); + editParameter(ZamGEQ31Plugin::paramGain10, false); else if (slider == fSliderGain11) - d_editParameter(ZamGEQ31Plugin::paramGain11, false); + editParameter(ZamGEQ31Plugin::paramGain11, false); else if (slider == fSliderGain12) - d_editParameter(ZamGEQ31Plugin::paramGain12, false); + editParameter(ZamGEQ31Plugin::paramGain12, false); else if (slider == fSliderGain13) - d_editParameter(ZamGEQ31Plugin::paramGain13, false); + editParameter(ZamGEQ31Plugin::paramGain13, false); else if (slider == fSliderGain14) - d_editParameter(ZamGEQ31Plugin::paramGain14, false); + editParameter(ZamGEQ31Plugin::paramGain14, false); else if (slider == fSliderGain15) - d_editParameter(ZamGEQ31Plugin::paramGain15, false); + editParameter(ZamGEQ31Plugin::paramGain15, false); else if (slider == fSliderGain16) - d_editParameter(ZamGEQ31Plugin::paramGain16, false); + editParameter(ZamGEQ31Plugin::paramGain16, false); else if (slider == fSliderGain17) - d_editParameter(ZamGEQ31Plugin::paramGain17, false); + editParameter(ZamGEQ31Plugin::paramGain17, false); else if (slider == fSliderGain18) - d_editParameter(ZamGEQ31Plugin::paramGain18, false); + editParameter(ZamGEQ31Plugin::paramGain18, false); else if (slider == fSliderGain19) - d_editParameter(ZamGEQ31Plugin::paramGain19, false); + editParameter(ZamGEQ31Plugin::paramGain19, false); else if (slider == fSliderGain20) - d_editParameter(ZamGEQ31Plugin::paramGain20, false); + editParameter(ZamGEQ31Plugin::paramGain20, false); else if (slider == fSliderGain21) - d_editParameter(ZamGEQ31Plugin::paramGain21, false); + editParameter(ZamGEQ31Plugin::paramGain21, false); else if (slider == fSliderGain22) - d_editParameter(ZamGEQ31Plugin::paramGain22, false); + editParameter(ZamGEQ31Plugin::paramGain22, false); else if (slider == fSliderGain23) - d_editParameter(ZamGEQ31Plugin::paramGain23, false); + editParameter(ZamGEQ31Plugin::paramGain23, false); else if (slider == fSliderGain24) - d_editParameter(ZamGEQ31Plugin::paramGain24, false); + editParameter(ZamGEQ31Plugin::paramGain24, false); else if (slider == fSliderGain25) - d_editParameter(ZamGEQ31Plugin::paramGain25, false); + editParameter(ZamGEQ31Plugin::paramGain25, false); else if (slider == fSliderGain26) - d_editParameter(ZamGEQ31Plugin::paramGain26, false); + editParameter(ZamGEQ31Plugin::paramGain26, false); else if (slider == fSliderGain27) - d_editParameter(ZamGEQ31Plugin::paramGain27, false); + editParameter(ZamGEQ31Plugin::paramGain27, false); else if (slider == fSliderGain28) - d_editParameter(ZamGEQ31Plugin::paramGain28, false); + editParameter(ZamGEQ31Plugin::paramGain28, false); else if (slider == fSliderGain29) - d_editParameter(ZamGEQ31Plugin::paramGain29, false); + editParameter(ZamGEQ31Plugin::paramGain29, false); else if (slider == fSliderGain30) - d_editParameter(ZamGEQ31Plugin::paramGain30, false); + editParameter(ZamGEQ31Plugin::paramGain30, false); else if (slider == fSliderGain31) - d_editParameter(ZamGEQ31Plugin::paramGain31, false); + editParameter(ZamGEQ31Plugin::paramGain31, false); } void ZamGEQ31UI::imageSliderValueChanged(ImageSlider* slider, float value) { if (slider == fSliderGain1) - d_setParameterValue(ZamGEQ31Plugin::paramGain1, value); + setParameterValue(ZamGEQ31Plugin::paramGain1, value); else if (slider == fSliderGain2) - d_setParameterValue(ZamGEQ31Plugin::paramGain2, value); + setParameterValue(ZamGEQ31Plugin::paramGain2, value); else if (slider == fSliderGain3) - d_setParameterValue(ZamGEQ31Plugin::paramGain3, value); + setParameterValue(ZamGEQ31Plugin::paramGain3, value); else if (slider == fSliderGain4) - d_setParameterValue(ZamGEQ31Plugin::paramGain4, value); + setParameterValue(ZamGEQ31Plugin::paramGain4, value); else if (slider == fSliderGain5) - d_setParameterValue(ZamGEQ31Plugin::paramGain5, value); + setParameterValue(ZamGEQ31Plugin::paramGain5, value); else if (slider == fSliderGain6) - d_setParameterValue(ZamGEQ31Plugin::paramGain6, value); + setParameterValue(ZamGEQ31Plugin::paramGain6, value); else if (slider == fSliderGain7) - d_setParameterValue(ZamGEQ31Plugin::paramGain7, value); + setParameterValue(ZamGEQ31Plugin::paramGain7, value); else if (slider == fSliderGain8) - d_setParameterValue(ZamGEQ31Plugin::paramGain8, value); + setParameterValue(ZamGEQ31Plugin::paramGain8, value); else if (slider == fSliderGain9) - d_setParameterValue(ZamGEQ31Plugin::paramGain9, value); + setParameterValue(ZamGEQ31Plugin::paramGain9, value); else if (slider == fSliderGain10) - d_setParameterValue(ZamGEQ31Plugin::paramGain10, value); + setParameterValue(ZamGEQ31Plugin::paramGain10, value); else if (slider == fSliderGain11) - d_setParameterValue(ZamGEQ31Plugin::paramGain11, value); + setParameterValue(ZamGEQ31Plugin::paramGain11, value); else if (slider == fSliderGain12) - d_setParameterValue(ZamGEQ31Plugin::paramGain12, value); + setParameterValue(ZamGEQ31Plugin::paramGain12, value); else if (slider == fSliderGain13) - d_setParameterValue(ZamGEQ31Plugin::paramGain13, value); + setParameterValue(ZamGEQ31Plugin::paramGain13, value); else if (slider == fSliderGain14) - d_setParameterValue(ZamGEQ31Plugin::paramGain14, value); + setParameterValue(ZamGEQ31Plugin::paramGain14, value); else if (slider == fSliderGain15) - d_setParameterValue(ZamGEQ31Plugin::paramGain15, value); + setParameterValue(ZamGEQ31Plugin::paramGain15, value); else if (slider == fSliderGain16) - d_setParameterValue(ZamGEQ31Plugin::paramGain16, value); + setParameterValue(ZamGEQ31Plugin::paramGain16, value); else if (slider == fSliderGain17) - d_setParameterValue(ZamGEQ31Plugin::paramGain17, value); + setParameterValue(ZamGEQ31Plugin::paramGain17, value); else if (slider == fSliderGain18) - d_setParameterValue(ZamGEQ31Plugin::paramGain18, value); + setParameterValue(ZamGEQ31Plugin::paramGain18, value); else if (slider == fSliderGain19) - d_setParameterValue(ZamGEQ31Plugin::paramGain19, value); + setParameterValue(ZamGEQ31Plugin::paramGain19, value); else if (slider == fSliderGain20) - d_setParameterValue(ZamGEQ31Plugin::paramGain20, value); + setParameterValue(ZamGEQ31Plugin::paramGain20, value); else if (slider == fSliderGain21) - d_setParameterValue(ZamGEQ31Plugin::paramGain21, value); + setParameterValue(ZamGEQ31Plugin::paramGain21, value); else if (slider == fSliderGain22) - d_setParameterValue(ZamGEQ31Plugin::paramGain22, value); + setParameterValue(ZamGEQ31Plugin::paramGain22, value); else if (slider == fSliderGain23) - d_setParameterValue(ZamGEQ31Plugin::paramGain23, value); + setParameterValue(ZamGEQ31Plugin::paramGain23, value); else if (slider == fSliderGain24) - d_setParameterValue(ZamGEQ31Plugin::paramGain24, value); + setParameterValue(ZamGEQ31Plugin::paramGain24, value); else if (slider == fSliderGain25) - d_setParameterValue(ZamGEQ31Plugin::paramGain25, value); + setParameterValue(ZamGEQ31Plugin::paramGain25, value); else if (slider == fSliderGain26) - d_setParameterValue(ZamGEQ31Plugin::paramGain26, value); + setParameterValue(ZamGEQ31Plugin::paramGain26, value); else if (slider == fSliderGain27) - d_setParameterValue(ZamGEQ31Plugin::paramGain27, value); + setParameterValue(ZamGEQ31Plugin::paramGain27, value); else if (slider == fSliderGain28) - d_setParameterValue(ZamGEQ31Plugin::paramGain28, value); + setParameterValue(ZamGEQ31Plugin::paramGain28, value); else if (slider == fSliderGain29) - d_setParameterValue(ZamGEQ31Plugin::paramGain29, value); + setParameterValue(ZamGEQ31Plugin::paramGain29, value); else if (slider == fSliderGain30) - d_setParameterValue(ZamGEQ31Plugin::paramGain30, value); + setParameterValue(ZamGEQ31Plugin::paramGain30, value); else if (slider == fSliderGain31) - d_setParameterValue(ZamGEQ31Plugin::paramGain31, value); + setParameterValue(ZamGEQ31Plugin::paramGain31, value); } void ZamGEQ31UI::onDisplay() diff --git a/plugins/ZamGEQ31/ZamGEQ31UI.hpp b/plugins/ZamGEQ31/ZamGEQ31UI.hpp index 2e7ff98..806d9e6 100644 --- a/plugins/ZamGEQ31/ZamGEQ31UI.hpp +++ b/plugins/ZamGEQ31/ZamGEQ31UI.hpp @@ -57,8 +57,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamGEQ31X2/Makefile b/plugins/ZamGEQ31X2/Makefile index cacf442..72903fb 100644 --- a/plugins/ZamGEQ31X2/Makefile +++ b/plugins/ZamGEQ31X2/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.cpp b/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.cpp index 96e3de3..3647874 100644 --- a/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.cpp +++ b/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.cpp @@ -25,13 +25,13 @@ ZamGEQ31X2Plugin::ZamGEQ31X2Plugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamGEQ31X2Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamGEQ31X2Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -614,7 +614,7 @@ void ZamGEQ31X2Plugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamGEQ31X2Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamGEQ31X2Plugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -625,7 +625,7 @@ void ZamGEQ31X2Plugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamGEQ31X2Plugin::d_getParameterValue(uint32_t index) const +float ZamGEQ31X2Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -826,7 +826,7 @@ float ZamGEQ31X2Plugin::d_getParameterValue(uint32_t index) const } } -void ZamGEQ31X2Plugin::d_setParameterValue(uint32_t index, float value) +void ZamGEQ31X2Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -1070,7 +1070,7 @@ double ZamGEQ31X2Plugin::run_filter(int i, int ch, double in) return out; } -void ZamGEQ31X2Plugin::d_setProgram(uint32_t index) +void ZamGEQ31X2Plugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -1115,20 +1115,20 @@ void ZamGEQ31X2Plugin::d_setProgram(uint32_t index) freq[30] = 20000.; master = 0.f; link = 0; - float srate = d_getSampleRate(); + float srate = getSampleRate(); for (int i=0; i < MAX_FILT; ++i) { peq(i, 0, srate, freq[i], 0., 1./3.); peq(i, 1, srate, freq[i], 0., 1./3.); } /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamGEQ31X2Plugin::d_activate() +void ZamGEQ31X2Plugin::activate() { int i; for (i = 0; i < MAX_FILT; ++i) { @@ -1169,9 +1169,9 @@ double ZamGEQ31X2Plugin::run_filter(int i, int ch, double in) } */ -void ZamGEQ31X2Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamGEQ31X2Plugin::run(const float** inputs, float** outputs, uint32_t frames) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); int i; for (i = 0; i < MAX_FILT; i++) { diff --git a/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.hpp b/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.hpp index 96d3309..da3044b 100644 --- a/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.hpp +++ b/plugins/ZamGEQ31X2/ZamGEQ31X2Plugin.hpp @@ -104,27 +104,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamGEQ31X2"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1001; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'G', '3', '2'); } @@ -132,15 +132,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -167,8 +167,8 @@ protected: return (x >= 0.f ? 1 : -1); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; void peq(int i, int ch, float srate, float fc, float g, float bw); double run_filter(int i, int ch, double in); diff --git a/plugins/ZamGEQ31X2/ZamGEQ31X2UI.cpp b/plugins/ZamGEQ31X2/ZamGEQ31X2UI.cpp index bff3a57..d4ae51a 100644 --- a/plugins/ZamGEQ31X2/ZamGEQ31X2UI.cpp +++ b/plugins/ZamGEQ31X2/ZamGEQ31X2UI.cpp @@ -740,13 +740,13 @@ ZamGEQ31X2UI::ZamGEQ31X2UI() fSliderGain31R->setInverted(true); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamGEQ31X2UI::d_parameterChanged(uint32_t index, float value) +void ZamGEQ31X2UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -942,7 +942,7 @@ void ZamGEQ31X2UI::d_parameterChanged(uint32_t index, float value) } } -void ZamGEQ31X2UI::d_programChanged(uint32_t index) +void ZamGEQ31X2UI::programLoaded(uint32_t index) { if (index != 0) return; @@ -1020,391 +1020,391 @@ void ZamGEQ31X2UI::d_programChanged(uint32_t index) void ZamGEQ31X2UI::imageSliderDragStarted(ImageSlider* slider) { if (slider == fSliderMaster) - d_editParameter(ZamGEQ31X2Plugin::paramMaster, true); + editParameter(ZamGEQ31X2Plugin::paramMaster, true); else if (slider == fSliderGain1L) - d_editParameter(ZamGEQ31X2Plugin::paramGain1L, true); + editParameter(ZamGEQ31X2Plugin::paramGain1L, true); else if (slider == fSliderGain2L) - d_editParameter(ZamGEQ31X2Plugin::paramGain2L, true); + editParameter(ZamGEQ31X2Plugin::paramGain2L, true); else if (slider == fSliderGain3L) - d_editParameter(ZamGEQ31X2Plugin::paramGain3L, true); + editParameter(ZamGEQ31X2Plugin::paramGain3L, true); else if (slider == fSliderGain4L) - d_editParameter(ZamGEQ31X2Plugin::paramGain4L, true); + editParameter(ZamGEQ31X2Plugin::paramGain4L, true); else if (slider == fSliderGain5L) - d_editParameter(ZamGEQ31X2Plugin::paramGain5L, true); + editParameter(ZamGEQ31X2Plugin::paramGain5L, true); else if (slider == fSliderGain6L) - d_editParameter(ZamGEQ31X2Plugin::paramGain6L, true); + editParameter(ZamGEQ31X2Plugin::paramGain6L, true); else if (slider == fSliderGain7L) - d_editParameter(ZamGEQ31X2Plugin::paramGain7L, true); + editParameter(ZamGEQ31X2Plugin::paramGain7L, true); else if (slider == fSliderGain8L) - d_editParameter(ZamGEQ31X2Plugin::paramGain8L, true); + editParameter(ZamGEQ31X2Plugin::paramGain8L, true); else if (slider == fSliderGain9L) - d_editParameter(ZamGEQ31X2Plugin::paramGain9L, true); + editParameter(ZamGEQ31X2Plugin::paramGain9L, true); else if (slider == fSliderGain10L) - d_editParameter(ZamGEQ31X2Plugin::paramGain10L, true); + editParameter(ZamGEQ31X2Plugin::paramGain10L, true); else if (slider == fSliderGain11L) - d_editParameter(ZamGEQ31X2Plugin::paramGain11L, true); + editParameter(ZamGEQ31X2Plugin::paramGain11L, true); else if (slider == fSliderGain12L) - d_editParameter(ZamGEQ31X2Plugin::paramGain12L, true); + editParameter(ZamGEQ31X2Plugin::paramGain12L, true); else if (slider == fSliderGain13L) - d_editParameter(ZamGEQ31X2Plugin::paramGain13L, true); + editParameter(ZamGEQ31X2Plugin::paramGain13L, true); else if (slider == fSliderGain14L) - d_editParameter(ZamGEQ31X2Plugin::paramGain14L, true); + editParameter(ZamGEQ31X2Plugin::paramGain14L, true); else if (slider == fSliderGain15L) - d_editParameter(ZamGEQ31X2Plugin::paramGain15L, true); + editParameter(ZamGEQ31X2Plugin::paramGain15L, true); else if (slider == fSliderGain16L) - d_editParameter(ZamGEQ31X2Plugin::paramGain16L, true); + editParameter(ZamGEQ31X2Plugin::paramGain16L, true); else if (slider == fSliderGain17L) - d_editParameter(ZamGEQ31X2Plugin::paramGain17L, true); + editParameter(ZamGEQ31X2Plugin::paramGain17L, true); else if (slider == fSliderGain18L) - d_editParameter(ZamGEQ31X2Plugin::paramGain18L, true); + editParameter(ZamGEQ31X2Plugin::paramGain18L, true); else if (slider == fSliderGain19L) - d_editParameter(ZamGEQ31X2Plugin::paramGain19L, true); + editParameter(ZamGEQ31X2Plugin::paramGain19L, true); else if (slider == fSliderGain20L) - d_editParameter(ZamGEQ31X2Plugin::paramGain20L, true); + editParameter(ZamGEQ31X2Plugin::paramGain20L, true); else if (slider == fSliderGain21L) - d_editParameter(ZamGEQ31X2Plugin::paramGain21L, true); + editParameter(ZamGEQ31X2Plugin::paramGain21L, true); else if (slider == fSliderGain22L) - d_editParameter(ZamGEQ31X2Plugin::paramGain22L, true); + editParameter(ZamGEQ31X2Plugin::paramGain22L, true); else if (slider == fSliderGain23L) - d_editParameter(ZamGEQ31X2Plugin::paramGain23L, true); + editParameter(ZamGEQ31X2Plugin::paramGain23L, true); else if (slider == fSliderGain24L) - d_editParameter(ZamGEQ31X2Plugin::paramGain24L, true); + editParameter(ZamGEQ31X2Plugin::paramGain24L, true); else if (slider == fSliderGain25L) - d_editParameter(ZamGEQ31X2Plugin::paramGain25L, true); + editParameter(ZamGEQ31X2Plugin::paramGain25L, true); else if (slider == fSliderGain26L) - d_editParameter(ZamGEQ31X2Plugin::paramGain26L, true); + editParameter(ZamGEQ31X2Plugin::paramGain26L, true); else if (slider == fSliderGain27L) - d_editParameter(ZamGEQ31X2Plugin::paramGain27L, true); + editParameter(ZamGEQ31X2Plugin::paramGain27L, true); else if (slider == fSliderGain28L) - d_editParameter(ZamGEQ31X2Plugin::paramGain28L, true); + editParameter(ZamGEQ31X2Plugin::paramGain28L, true); else if (slider == fSliderGain29L) - d_editParameter(ZamGEQ31X2Plugin::paramGain29L, true); + editParameter(ZamGEQ31X2Plugin::paramGain29L, true); else if (slider == fSliderGain30L) - d_editParameter(ZamGEQ31X2Plugin::paramGain30L, true); + editParameter(ZamGEQ31X2Plugin::paramGain30L, true); else if (slider == fSliderGain31L) - d_editParameter(ZamGEQ31X2Plugin::paramGain31L, true); + editParameter(ZamGEQ31X2Plugin::paramGain31L, true); else if (slider == fSliderGain1R) - d_editParameter(ZamGEQ31X2Plugin::paramGain1R, true); + editParameter(ZamGEQ31X2Plugin::paramGain1R, true); else if (slider == fSliderGain2R) - d_editParameter(ZamGEQ31X2Plugin::paramGain2R, true); + editParameter(ZamGEQ31X2Plugin::paramGain2R, true); else if (slider == fSliderGain3R) - d_editParameter(ZamGEQ31X2Plugin::paramGain3R, true); + editParameter(ZamGEQ31X2Plugin::paramGain3R, true); else if (slider == fSliderGain4R) - d_editParameter(ZamGEQ31X2Plugin::paramGain4R, true); + editParameter(ZamGEQ31X2Plugin::paramGain4R, true); else if (slider == fSliderGain5R) - d_editParameter(ZamGEQ31X2Plugin::paramGain5R, true); + editParameter(ZamGEQ31X2Plugin::paramGain5R, true); else if (slider == fSliderGain6R) - d_editParameter(ZamGEQ31X2Plugin::paramGain6R, true); + editParameter(ZamGEQ31X2Plugin::paramGain6R, true); else if (slider == fSliderGain7R) - d_editParameter(ZamGEQ31X2Plugin::paramGain7R, true); + editParameter(ZamGEQ31X2Plugin::paramGain7R, true); else if (slider == fSliderGain8R) - d_editParameter(ZamGEQ31X2Plugin::paramGain8R, true); + editParameter(ZamGEQ31X2Plugin::paramGain8R, true); else if (slider == fSliderGain9R) - d_editParameter(ZamGEQ31X2Plugin::paramGain9R, true); + editParameter(ZamGEQ31X2Plugin::paramGain9R, true); else if (slider == fSliderGain10R) - d_editParameter(ZamGEQ31X2Plugin::paramGain10R, true); + editParameter(ZamGEQ31X2Plugin::paramGain10R, true); else if (slider == fSliderGain11R) - d_editParameter(ZamGEQ31X2Plugin::paramGain11R, true); + editParameter(ZamGEQ31X2Plugin::paramGain11R, true); else if (slider == fSliderGain12R) - d_editParameter(ZamGEQ31X2Plugin::paramGain12R, true); + editParameter(ZamGEQ31X2Plugin::paramGain12R, true); else if (slider == fSliderGain13R) - d_editParameter(ZamGEQ31X2Plugin::paramGain13R, true); + editParameter(ZamGEQ31X2Plugin::paramGain13R, true); else if (slider == fSliderGain14R) - d_editParameter(ZamGEQ31X2Plugin::paramGain14R, true); + editParameter(ZamGEQ31X2Plugin::paramGain14R, true); else if (slider == fSliderGain15R) - d_editParameter(ZamGEQ31X2Plugin::paramGain15R, true); + editParameter(ZamGEQ31X2Plugin::paramGain15R, true); else if (slider == fSliderGain16R) - d_editParameter(ZamGEQ31X2Plugin::paramGain16R, true); + editParameter(ZamGEQ31X2Plugin::paramGain16R, true); else if (slider == fSliderGain17R) - d_editParameter(ZamGEQ31X2Plugin::paramGain17R, true); + editParameter(ZamGEQ31X2Plugin::paramGain17R, true); else if (slider == fSliderGain18R) - d_editParameter(ZamGEQ31X2Plugin::paramGain18R, true); + editParameter(ZamGEQ31X2Plugin::paramGain18R, true); else if (slider == fSliderGain19R) - d_editParameter(ZamGEQ31X2Plugin::paramGain19R, true); + editParameter(ZamGEQ31X2Plugin::paramGain19R, true); else if (slider == fSliderGain20R) - d_editParameter(ZamGEQ31X2Plugin::paramGain20R, true); + editParameter(ZamGEQ31X2Plugin::paramGain20R, true); else if (slider == fSliderGain21R) - d_editParameter(ZamGEQ31X2Plugin::paramGain21R, true); + editParameter(ZamGEQ31X2Plugin::paramGain21R, true); else if (slider == fSliderGain22R) - d_editParameter(ZamGEQ31X2Plugin::paramGain22R, true); + editParameter(ZamGEQ31X2Plugin::paramGain22R, true); else if (slider == fSliderGain23R) - d_editParameter(ZamGEQ31X2Plugin::paramGain23R, true); + editParameter(ZamGEQ31X2Plugin::paramGain23R, true); else if (slider == fSliderGain24R) - d_editParameter(ZamGEQ31X2Plugin::paramGain24R, true); + editParameter(ZamGEQ31X2Plugin::paramGain24R, true); else if (slider == fSliderGain25R) - d_editParameter(ZamGEQ31X2Plugin::paramGain25R, true); + editParameter(ZamGEQ31X2Plugin::paramGain25R, true); else if (slider == fSliderGain26R) - d_editParameter(ZamGEQ31X2Plugin::paramGain26R, true); + editParameter(ZamGEQ31X2Plugin::paramGain26R, true); else if (slider == fSliderGain27R) - d_editParameter(ZamGEQ31X2Plugin::paramGain27R, true); + editParameter(ZamGEQ31X2Plugin::paramGain27R, true); else if (slider == fSliderGain28R) - d_editParameter(ZamGEQ31X2Plugin::paramGain28R, true); + editParameter(ZamGEQ31X2Plugin::paramGain28R, true); else if (slider == fSliderGain29R) - d_editParameter(ZamGEQ31X2Plugin::paramGain29R, true); + editParameter(ZamGEQ31X2Plugin::paramGain29R, true); else if (slider == fSliderGain30R) - d_editParameter(ZamGEQ31X2Plugin::paramGain30R, true); + editParameter(ZamGEQ31X2Plugin::paramGain30R, true); else if (slider == fSliderGain31R) - d_editParameter(ZamGEQ31X2Plugin::paramGain31R, true); + editParameter(ZamGEQ31X2Plugin::paramGain31R, true); } void ZamGEQ31X2UI::imageSliderDragFinished(ImageSlider* slider) { if (slider == fSliderMaster) - d_editParameter(ZamGEQ31X2Plugin::paramMaster, false); + editParameter(ZamGEQ31X2Plugin::paramMaster, false); else if (slider == fSliderGain1L) - d_editParameter(ZamGEQ31X2Plugin::paramGain1L, false); + editParameter(ZamGEQ31X2Plugin::paramGain1L, false); else if (slider == fSliderGain2L) - d_editParameter(ZamGEQ31X2Plugin::paramGain2L, false); + editParameter(ZamGEQ31X2Plugin::paramGain2L, false); else if (slider == fSliderGain3L) - d_editParameter(ZamGEQ31X2Plugin::paramGain3L, false); + editParameter(ZamGEQ31X2Plugin::paramGain3L, false); else if (slider == fSliderGain4L) - d_editParameter(ZamGEQ31X2Plugin::paramGain4L, false); + editParameter(ZamGEQ31X2Plugin::paramGain4L, false); else if (slider == fSliderGain5L) - d_editParameter(ZamGEQ31X2Plugin::paramGain5L, false); + editParameter(ZamGEQ31X2Plugin::paramGain5L, false); else if (slider == fSliderGain6L) - d_editParameter(ZamGEQ31X2Plugin::paramGain6L, false); + editParameter(ZamGEQ31X2Plugin::paramGain6L, false); else if (slider == fSliderGain7L) - d_editParameter(ZamGEQ31X2Plugin::paramGain7L, false); + editParameter(ZamGEQ31X2Plugin::paramGain7L, false); else if (slider == fSliderGain8L) - d_editParameter(ZamGEQ31X2Plugin::paramGain8L, false); + editParameter(ZamGEQ31X2Plugin::paramGain8L, false); else if (slider == fSliderGain9L) - d_editParameter(ZamGEQ31X2Plugin::paramGain9L, false); + editParameter(ZamGEQ31X2Plugin::paramGain9L, false); else if (slider == fSliderGain10L) - d_editParameter(ZamGEQ31X2Plugin::paramGain10L, false); + editParameter(ZamGEQ31X2Plugin::paramGain10L, false); else if (slider == fSliderGain11L) - d_editParameter(ZamGEQ31X2Plugin::paramGain11L, false); + editParameter(ZamGEQ31X2Plugin::paramGain11L, false); else if (slider == fSliderGain12L) - d_editParameter(ZamGEQ31X2Plugin::paramGain12L, false); + editParameter(ZamGEQ31X2Plugin::paramGain12L, false); else if (slider == fSliderGain13L) - d_editParameter(ZamGEQ31X2Plugin::paramGain13L, false); + editParameter(ZamGEQ31X2Plugin::paramGain13L, false); else if (slider == fSliderGain14L) - d_editParameter(ZamGEQ31X2Plugin::paramGain14L, false); + editParameter(ZamGEQ31X2Plugin::paramGain14L, false); else if (slider == fSliderGain15L) - d_editParameter(ZamGEQ31X2Plugin::paramGain15L, false); + editParameter(ZamGEQ31X2Plugin::paramGain15L, false); else if (slider == fSliderGain16L) - d_editParameter(ZamGEQ31X2Plugin::paramGain16L, false); + editParameter(ZamGEQ31X2Plugin::paramGain16L, false); else if (slider == fSliderGain17L) - d_editParameter(ZamGEQ31X2Plugin::paramGain17L, false); + editParameter(ZamGEQ31X2Plugin::paramGain17L, false); else if (slider == fSliderGain18L) - d_editParameter(ZamGEQ31X2Plugin::paramGain18L, false); + editParameter(ZamGEQ31X2Plugin::paramGain18L, false); else if (slider == fSliderGain19L) - d_editParameter(ZamGEQ31X2Plugin::paramGain19L, false); + editParameter(ZamGEQ31X2Plugin::paramGain19L, false); else if (slider == fSliderGain20L) - d_editParameter(ZamGEQ31X2Plugin::paramGain20L, false); + editParameter(ZamGEQ31X2Plugin::paramGain20L, false); else if (slider == fSliderGain21L) - d_editParameter(ZamGEQ31X2Plugin::paramGain21L, false); + editParameter(ZamGEQ31X2Plugin::paramGain21L, false); else if (slider == fSliderGain22L) - d_editParameter(ZamGEQ31X2Plugin::paramGain22L, false); + editParameter(ZamGEQ31X2Plugin::paramGain22L, false); else if (slider == fSliderGain23L) - d_editParameter(ZamGEQ31X2Plugin::paramGain23L, false); + editParameter(ZamGEQ31X2Plugin::paramGain23L, false); else if (slider == fSliderGain24L) - d_editParameter(ZamGEQ31X2Plugin::paramGain24L, false); + editParameter(ZamGEQ31X2Plugin::paramGain24L, false); else if (slider == fSliderGain25L) - d_editParameter(ZamGEQ31X2Plugin::paramGain25L, false); + editParameter(ZamGEQ31X2Plugin::paramGain25L, false); else if (slider == fSliderGain26L) - d_editParameter(ZamGEQ31X2Plugin::paramGain26L, false); + editParameter(ZamGEQ31X2Plugin::paramGain26L, false); else if (slider == fSliderGain27L) - d_editParameter(ZamGEQ31X2Plugin::paramGain27L, false); + editParameter(ZamGEQ31X2Plugin::paramGain27L, false); else if (slider == fSliderGain28L) - d_editParameter(ZamGEQ31X2Plugin::paramGain28L, false); + editParameter(ZamGEQ31X2Plugin::paramGain28L, false); else if (slider == fSliderGain29L) - d_editParameter(ZamGEQ31X2Plugin::paramGain29L, false); + editParameter(ZamGEQ31X2Plugin::paramGain29L, false); else if (slider == fSliderGain30L) - d_editParameter(ZamGEQ31X2Plugin::paramGain30L, false); + editParameter(ZamGEQ31X2Plugin::paramGain30L, false); else if (slider == fSliderGain31L) - d_editParameter(ZamGEQ31X2Plugin::paramGain31L, false); + editParameter(ZamGEQ31X2Plugin::paramGain31L, false); else if (slider == fSliderGain1R) - d_editParameter(ZamGEQ31X2Plugin::paramGain1R, false); + editParameter(ZamGEQ31X2Plugin::paramGain1R, false); else if (slider == fSliderGain2R) - d_editParameter(ZamGEQ31X2Plugin::paramGain2R, false); + editParameter(ZamGEQ31X2Plugin::paramGain2R, false); else if (slider == fSliderGain3R) - d_editParameter(ZamGEQ31X2Plugin::paramGain3R, false); + editParameter(ZamGEQ31X2Plugin::paramGain3R, false); else if (slider == fSliderGain4R) - d_editParameter(ZamGEQ31X2Plugin::paramGain4R, false); + editParameter(ZamGEQ31X2Plugin::paramGain4R, false); else if (slider == fSliderGain5R) - d_editParameter(ZamGEQ31X2Plugin::paramGain5R, false); + editParameter(ZamGEQ31X2Plugin::paramGain5R, false); else if (slider == fSliderGain6R) - d_editParameter(ZamGEQ31X2Plugin::paramGain6R, false); + editParameter(ZamGEQ31X2Plugin::paramGain6R, false); else if (slider == fSliderGain7R) - d_editParameter(ZamGEQ31X2Plugin::paramGain7R, false); + editParameter(ZamGEQ31X2Plugin::paramGain7R, false); else if (slider == fSliderGain8R) - d_editParameter(ZamGEQ31X2Plugin::paramGain8R, false); + editParameter(ZamGEQ31X2Plugin::paramGain8R, false); else if (slider == fSliderGain9R) - d_editParameter(ZamGEQ31X2Plugin::paramGain9R, false); + editParameter(ZamGEQ31X2Plugin::paramGain9R, false); else if (slider == fSliderGain10R) - d_editParameter(ZamGEQ31X2Plugin::paramGain10R, false); + editParameter(ZamGEQ31X2Plugin::paramGain10R, false); else if (slider == fSliderGain11R) - d_editParameter(ZamGEQ31X2Plugin::paramGain11R, false); + editParameter(ZamGEQ31X2Plugin::paramGain11R, false); else if (slider == fSliderGain12R) - d_editParameter(ZamGEQ31X2Plugin::paramGain12R, false); + editParameter(ZamGEQ31X2Plugin::paramGain12R, false); else if (slider == fSliderGain13R) - d_editParameter(ZamGEQ31X2Plugin::paramGain13R, false); + editParameter(ZamGEQ31X2Plugin::paramGain13R, false); else if (slider == fSliderGain14R) - d_editParameter(ZamGEQ31X2Plugin::paramGain14R, false); + editParameter(ZamGEQ31X2Plugin::paramGain14R, false); else if (slider == fSliderGain15R) - d_editParameter(ZamGEQ31X2Plugin::paramGain15R, false); + editParameter(ZamGEQ31X2Plugin::paramGain15R, false); else if (slider == fSliderGain16R) - d_editParameter(ZamGEQ31X2Plugin::paramGain16R, false); + editParameter(ZamGEQ31X2Plugin::paramGain16R, false); else if (slider == fSliderGain17R) - d_editParameter(ZamGEQ31X2Plugin::paramGain17R, false); + editParameter(ZamGEQ31X2Plugin::paramGain17R, false); else if (slider == fSliderGain18R) - d_editParameter(ZamGEQ31X2Plugin::paramGain18R, false); + editParameter(ZamGEQ31X2Plugin::paramGain18R, false); else if (slider == fSliderGain19R) - d_editParameter(ZamGEQ31X2Plugin::paramGain19R, false); + editParameter(ZamGEQ31X2Plugin::paramGain19R, false); else if (slider == fSliderGain20R) - d_editParameter(ZamGEQ31X2Plugin::paramGain20R, false); + editParameter(ZamGEQ31X2Plugin::paramGain20R, false); else if (slider == fSliderGain21R) - d_editParameter(ZamGEQ31X2Plugin::paramGain21R, false); + editParameter(ZamGEQ31X2Plugin::paramGain21R, false); else if (slider == fSliderGain22R) - d_editParameter(ZamGEQ31X2Plugin::paramGain22R, false); + editParameter(ZamGEQ31X2Plugin::paramGain22R, false); else if (slider == fSliderGain23R) - d_editParameter(ZamGEQ31X2Plugin::paramGain23R, false); + editParameter(ZamGEQ31X2Plugin::paramGain23R, false); else if (slider == fSliderGain24R) - d_editParameter(ZamGEQ31X2Plugin::paramGain24R, false); + editParameter(ZamGEQ31X2Plugin::paramGain24R, false); else if (slider == fSliderGain25R) - d_editParameter(ZamGEQ31X2Plugin::paramGain25R, false); + editParameter(ZamGEQ31X2Plugin::paramGain25R, false); else if (slider == fSliderGain26R) - d_editParameter(ZamGEQ31X2Plugin::paramGain26R, false); + editParameter(ZamGEQ31X2Plugin::paramGain26R, false); else if (slider == fSliderGain27R) - d_editParameter(ZamGEQ31X2Plugin::paramGain27R, false); + editParameter(ZamGEQ31X2Plugin::paramGain27R, false); else if (slider == fSliderGain28R) - d_editParameter(ZamGEQ31X2Plugin::paramGain28R, false); + editParameter(ZamGEQ31X2Plugin::paramGain28R, false); else if (slider == fSliderGain29R) - d_editParameter(ZamGEQ31X2Plugin::paramGain29R, false); + editParameter(ZamGEQ31X2Plugin::paramGain29R, false); else if (slider == fSliderGain30R) - d_editParameter(ZamGEQ31X2Plugin::paramGain30R, false); + editParameter(ZamGEQ31X2Plugin::paramGain30R, false); else if (slider == fSliderGain31R) - d_editParameter(ZamGEQ31X2Plugin::paramGain31R, false); + editParameter(ZamGEQ31X2Plugin::paramGain31R, false); } void ZamGEQ31X2UI::imageSliderValueChanged(ImageSlider* slider, float value) { if (slider == fSliderMaster) - d_setParameterValue(ZamGEQ31X2Plugin::paramMaster, value); + setParameterValue(ZamGEQ31X2Plugin::paramMaster, value); else if (slider == fSliderGain1L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain1L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain1L, value); else if (slider == fSliderGain2L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain2L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain2L, value); else if (slider == fSliderGain3L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain3L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain3L, value); else if (slider == fSliderGain4L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain4L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain4L, value); else if (slider == fSliderGain5L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain5L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain5L, value); else if (slider == fSliderGain6L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain6L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain6L, value); else if (slider == fSliderGain7L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain7L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain7L, value); else if (slider == fSliderGain8L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain8L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain8L, value); else if (slider == fSliderGain9L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain9L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain9L, value); else if (slider == fSliderGain10L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain10L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain10L, value); else if (slider == fSliderGain11L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain11L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain11L, value); else if (slider == fSliderGain12L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain12L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain12L, value); else if (slider == fSliderGain13L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain13L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain13L, value); else if (slider == fSliderGain14L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain14L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain14L, value); else if (slider == fSliderGain15L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain15L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain15L, value); else if (slider == fSliderGain16L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain16L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain16L, value); else if (slider == fSliderGain17L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain17L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain17L, value); else if (slider == fSliderGain18L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain18L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain18L, value); else if (slider == fSliderGain19L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain19L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain19L, value); else if (slider == fSliderGain20L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain20L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain20L, value); else if (slider == fSliderGain21L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain21L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain21L, value); else if (slider == fSliderGain22L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain22L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain22L, value); else if (slider == fSliderGain23L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain23L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain23L, value); else if (slider == fSliderGain24L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain24L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain24L, value); else if (slider == fSliderGain25L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain25L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain25L, value); else if (slider == fSliderGain26L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain26L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain26L, value); else if (slider == fSliderGain27L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain27L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain27L, value); else if (slider == fSliderGain28L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain28L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain28L, value); else if (slider == fSliderGain29L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain29L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain29L, value); else if (slider == fSliderGain30L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain30L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain30L, value); else if (slider == fSliderGain31L) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain31L, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain31L, value); else if (slider == fSliderGain1R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain1R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain1R, value); else if (slider == fSliderGain2R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain2R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain2R, value); else if (slider == fSliderGain3R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain3R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain3R, value); else if (slider == fSliderGain4R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain4R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain4R, value); else if (slider == fSliderGain5R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain5R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain5R, value); else if (slider == fSliderGain6R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain6R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain6R, value); else if (slider == fSliderGain7R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain7R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain7R, value); else if (slider == fSliderGain8R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain8R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain8R, value); else if (slider == fSliderGain9R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain9R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain9R, value); else if (slider == fSliderGain10R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain10R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain10R, value); else if (slider == fSliderGain11R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain11R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain11R, value); else if (slider == fSliderGain12R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain12R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain12R, value); else if (slider == fSliderGain13R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain13R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain13R, value); else if (slider == fSliderGain14R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain14R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain14R, value); else if (slider == fSliderGain15R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain15R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain15R, value); else if (slider == fSliderGain16R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain16R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain16R, value); else if (slider == fSliderGain17R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain17R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain17R, value); else if (slider == fSliderGain18R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain18R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain18R, value); else if (slider == fSliderGain19R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain19R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain19R, value); else if (slider == fSliderGain20R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain20R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain20R, value); else if (slider == fSliderGain21R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain21R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain21R, value); else if (slider == fSliderGain22R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain22R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain22R, value); else if (slider == fSliderGain23R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain23R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain23R, value); else if (slider == fSliderGain24R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain24R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain24R, value); else if (slider == fSliderGain25R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain25R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain25R, value); else if (slider == fSliderGain26R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain26R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain26R, value); else if (slider == fSliderGain27R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain27R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain27R, value); else if (slider == fSliderGain28R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain28R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain28R, value); else if (slider == fSliderGain29R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain29R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain29R, value); else if (slider == fSliderGain30R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain30R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain30R, value); else if (slider == fSliderGain31R) - d_setParameterValue(ZamGEQ31X2Plugin::paramGain31R, value); + setParameterValue(ZamGEQ31X2Plugin::paramGain31R, value); } void ZamGEQ31X2UI::onDisplay() diff --git a/plugins/ZamGEQ31X2/ZamGEQ31X2UI.hpp b/plugins/ZamGEQ31X2/ZamGEQ31X2UI.hpp index f2250fa..3c8f7c4 100644 --- a/plugins/ZamGEQ31X2/ZamGEQ31X2UI.hpp +++ b/plugins/ZamGEQ31X2/ZamGEQ31X2UI.hpp @@ -55,8 +55,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamGate/Makefile b/plugins/ZamGate/Makefile index 5ae5766..96d1b31 100644 --- a/plugins/ZamGate/Makefile +++ b/plugins/ZamGate/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamGate/ZamGatePlugin.cpp b/plugins/ZamGate/ZamGatePlugin.cpp index 3924a4c..25b5b9b 100644 --- a/plugins/ZamGate/ZamGatePlugin.cpp +++ b/plugins/ZamGate/ZamGatePlugin.cpp @@ -25,13 +25,13 @@ ZamGatePlugin::ZamGatePlugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamGatePlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamGatePlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -42,7 +42,7 @@ void ZamGatePlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -void ZamGatePlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamGatePlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -106,7 +106,7 @@ void ZamGatePlugin::d_initParameter(uint32_t index, Parameter& parameter) // ----------------------------------------------------------------------- // Internal data -float ZamGatePlugin::d_getParameterValue(uint32_t index) const +float ZamGatePlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -133,7 +133,7 @@ float ZamGatePlugin::d_getParameterValue(uint32_t index) const } } -void ZamGatePlugin::d_setParameterValue(uint32_t index, float value) +void ZamGatePlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -158,7 +158,7 @@ void ZamGatePlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamGatePlugin::d_setProgram(uint32_t index) +void ZamGatePlugin::loadProgram(uint32_t index) { attack = 50.0; release = 100.0; @@ -166,13 +166,13 @@ void ZamGatePlugin::d_setProgram(uint32_t index) gainr = 0.0; makeup = 0.0; outlevel = -45.0; - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamGatePlugin::d_activate() +void ZamGatePlugin::activate() { int i; gatestatel = 0.f; @@ -202,7 +202,7 @@ float ZamGatePlugin::averageabs(float samples[]) return sqrt(average); } -void ZamGatePlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamGatePlugin::run(const float** inputs, float** outputs, uint32_t frames) { uint32_t i; float absamplel, absample; @@ -211,7 +211,7 @@ void ZamGatePlugin::d_run(const float** inputs, float** outputs, uint32_t frames float gl; float ming; float fs; - fs = d_getSampleRate(); + fs = getSampleRate(); gl = gatestatel; att = 1000.f / (attack * fs); rel = 1000.f / (release * fs); diff --git a/plugins/ZamGate/ZamGatePlugin.hpp b/plugins/ZamGate/ZamGatePlugin.hpp index a891029..f80f3e2 100644 --- a/plugins/ZamGate/ZamGatePlugin.hpp +++ b/plugins/ZamGate/ZamGatePlugin.hpp @@ -47,27 +47,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamGate"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'G', 'A', 'T'); } @@ -75,19 +75,19 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; static inline float sanitize_denormal(float v) { diff --git a/plugins/ZamGate/ZamGateUI.cpp b/plugins/ZamGate/ZamGateUI.cpp index 123ca90..0d8b895 100644 --- a/plugins/ZamGate/ZamGateUI.cpp +++ b/plugins/ZamGate/ZamGateUI.cpp @@ -79,13 +79,13 @@ ZamGateUI::ZamGateUI() fKnobMakeup->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamGateUI::d_parameterChanged(uint32_t index, float value) +void ZamGateUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -118,7 +118,7 @@ void ZamGateUI::d_parameterChanged(uint32_t index, float value) } } -void ZamGateUI::d_programChanged(uint32_t index) +void ZamGateUI::programLoaded(uint32_t index) { // Default values fKnobAttack->setValue(50.0f); @@ -132,17 +132,17 @@ void ZamGateUI::d_programChanged(uint32_t index) void ZamGateUI::imageKnobDragStarted(ImageKnob* knob) { - d_editParameter(knob->getId(), true); + editParameter(knob->getId(), true); } void ZamGateUI::imageKnobDragFinished(ImageKnob* knob) { - d_editParameter(knob->getId(), false); + editParameter(knob->getId(), false); } void ZamGateUI::imageKnobValueChanged(ImageKnob* knob, float value) { - d_setParameterValue(knob->getId(), value); + setParameterValue(knob->getId(), value); } void ZamGateUI::onDisplay() diff --git a/plugins/ZamGate/ZamGateUI.hpp b/plugins/ZamGate/ZamGateUI.hpp index 53d0092..84a3d2d 100644 --- a/plugins/ZamGate/ZamGateUI.hpp +++ b/plugins/ZamGate/ZamGateUI.hpp @@ -39,8 +39,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) ; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamGateX2/Makefile b/plugins/ZamGateX2/Makefile index 50803ad..479f1d4 100644 --- a/plugins/ZamGateX2/Makefile +++ b/plugins/ZamGateX2/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamGateX2/ZamGateX2Plugin.cpp b/plugins/ZamGateX2/ZamGateX2Plugin.cpp index af61dbc..0e29d38 100644 --- a/plugins/ZamGateX2/ZamGateX2Plugin.cpp +++ b/plugins/ZamGateX2/ZamGateX2Plugin.cpp @@ -25,13 +25,13 @@ ZamGateX2Plugin::ZamGateX2Plugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamGateX2Plugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamGateX2Plugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -42,7 +42,7 @@ void ZamGateX2Plugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -void ZamGateX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamGateX2Plugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -106,7 +106,7 @@ void ZamGateX2Plugin::d_initParameter(uint32_t index, Parameter& parameter) // ----------------------------------------------------------------------- // Internal data -float ZamGateX2Plugin::d_getParameterValue(uint32_t index) const +float ZamGateX2Plugin::getParameterValue(uint32_t index) const { switch (index) { @@ -133,7 +133,7 @@ float ZamGateX2Plugin::d_getParameterValue(uint32_t index) const } } -void ZamGateX2Plugin::d_setParameterValue(uint32_t index, float value) +void ZamGateX2Plugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -158,7 +158,7 @@ void ZamGateX2Plugin::d_setParameterValue(uint32_t index, float value) } } -void ZamGateX2Plugin::d_setProgram(uint32_t index) +void ZamGateX2Plugin::loadProgram(uint32_t index) { attack = 50.0; release = 100.0; @@ -166,13 +166,13 @@ void ZamGateX2Plugin::d_setProgram(uint32_t index) gainr = 0.0; makeup = 0.0; outlevel = -45.0; - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamGateX2Plugin::d_activate() +void ZamGateX2Plugin::activate() { int i; gatestatel = 0.f; @@ -213,7 +213,7 @@ float ZamGateX2Plugin::averageabs(float samples[]) return sqrt(average); } -void ZamGateX2Plugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamGateX2Plugin::run(const float** inputs, float** outputs, uint32_t frames) { uint32_t i; float absamplel, absampler, absample; @@ -222,7 +222,7 @@ void ZamGateX2Plugin::d_run(const float** inputs, float** outputs, uint32_t fram float gl, gr; float ming; float fs; - fs = d_getSampleRate(); + fs = getSampleRate(); gl = gatestatel; gr = gatestater; att = 1000.f / (attack * fs); diff --git a/plugins/ZamGateX2/ZamGateX2Plugin.hpp b/plugins/ZamGateX2/ZamGateX2Plugin.hpp index 0b6533e..586493a 100644 --- a/plugins/ZamGateX2/ZamGateX2Plugin.hpp +++ b/plugins/ZamGateX2/ZamGateX2Plugin.hpp @@ -47,27 +47,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamGateX2"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'G', 'T', '2'); } @@ -75,19 +75,19 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) override; - void d_initProgramName(uint32_t index, d_string& programName) override; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) override; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; static inline float sanitize_denormal(float v) { diff --git a/plugins/ZamGateX2/ZamGateX2UI.cpp b/plugins/ZamGateX2/ZamGateX2UI.cpp index 6372173..c682380 100644 --- a/plugins/ZamGateX2/ZamGateX2UI.cpp +++ b/plugins/ZamGateX2/ZamGateX2UI.cpp @@ -79,13 +79,13 @@ ZamGateX2UI::ZamGateX2UI() fKnobMakeup->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamGateX2UI::d_parameterChanged(uint32_t index, float value) +void ZamGateX2UI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -118,7 +118,7 @@ void ZamGateX2UI::d_parameterChanged(uint32_t index, float value) } } -void ZamGateX2UI::d_programChanged(uint32_t index) +void ZamGateX2UI::programLoaded(uint32_t index) { // Default values fKnobAttack->setValue(50.0f); @@ -132,17 +132,17 @@ void ZamGateX2UI::d_programChanged(uint32_t index) void ZamGateX2UI::imageKnobDragStarted(ImageKnob* knob) { - d_editParameter(knob->getId(), true); + editParameter(knob->getId(), true); } void ZamGateX2UI::imageKnobDragFinished(ImageKnob* knob) { - d_editParameter(knob->getId(), false); + editParameter(knob->getId(), false); } void ZamGateX2UI::imageKnobValueChanged(ImageKnob* knob, float value) { - d_setParameterValue(knob->getId(), value); + setParameterValue(knob->getId(), value); } void ZamGateX2UI::onDisplay() diff --git a/plugins/ZamGateX2/ZamGateX2UI.hpp b/plugins/ZamGateX2/ZamGateX2UI.hpp index 9a342ba..7a80933 100644 --- a/plugins/ZamGateX2/ZamGateX2UI.hpp +++ b/plugins/ZamGateX2/ZamGateX2UI.hpp @@ -39,8 +39,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) ; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamNoise/Makefile b/plugins/ZamNoise/Makefile index 8e724c6..3ea904e 100644 --- a/plugins/ZamNoise/Makefile +++ b/plugins/ZamNoise/Makefile @@ -28,10 +28,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamNoise/ZamNoisePlugin.cpp b/plugins/ZamNoise/ZamNoisePlugin.cpp index 18a3dfb..3347340 100644 --- a/plugins/ZamNoise/ZamNoisePlugin.cpp +++ b/plugins/ZamNoise/ZamNoisePlugin.cpp @@ -25,14 +25,14 @@ ZamNoisePlugin::ZamNoisePlugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { - ZamNoisePlugin::init(d_getSampleRate()); - zamnoise = new Denoise(d_getSampleRate()); + ZamNoisePlugin::init(getSampleRate()); + zamnoise = new Denoise(getSampleRate()); // set default values - d_setProgram(0); + loadProgram(0); // reset - d_deactivate(); + deactivate(); } ZamNoisePlugin::~ZamNoisePlugin() @@ -44,7 +44,7 @@ ZamNoisePlugin::~ZamNoisePlugin() // ----------------------------------------------------------------------- // Init -void ZamNoisePlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamNoisePlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -62,7 +62,7 @@ void ZamNoisePlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamNoisePlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamNoisePlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -73,7 +73,7 @@ void ZamNoisePlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamNoisePlugin::d_getParameterValue(uint32_t index) const +float ZamNoisePlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -86,7 +86,7 @@ float ZamNoisePlugin::d_getParameterValue(uint32_t index) const } } -void ZamNoisePlugin::d_setParameterValue(uint32_t index, float value) +void ZamNoisePlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -99,14 +99,14 @@ void ZamNoisePlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamNoisePlugin::d_setProgram(uint32_t index) +void ZamNoisePlugin::loadProgram(uint32_t index) { if (index != 0) return; noisetoggle = 0.f; - d_activate(); + activate(); } @@ -126,15 +126,15 @@ void ZamNoisePlugin::init (float fsamp) // ----------------------------------------------------------------------- // Process -void ZamNoisePlugin::d_activate() +void ZamNoisePlugin::activate() { } -void ZamNoisePlugin::d_deactivate() +void ZamNoisePlugin::deactivate() { } -void ZamNoisePlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamNoisePlugin::run(const float** inputs, float** outputs, uint32_t frames) { zamnoise->process(inputs[0], outputs[0], buffer.cbi, frames, (int)noisetoggle); } diff --git a/plugins/ZamNoise/ZamNoisePlugin.hpp b/plugins/ZamNoise/ZamNoisePlugin.hpp index 4870148..dada683 100644 --- a/plugins/ZamNoise/ZamNoisePlugin.hpp +++ b/plugins/ZamNoise/ZamNoisePlugin.hpp @@ -47,27 +47,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamNoise"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'N', 'O', 'I'); } @@ -75,20 +75,20 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) override; + void initProgramName(uint32_t index, String& programName) override; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const ; - void d_setParameterValue(uint32_t index, float value) ; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- - void d_activate() ; - void d_deactivate() ; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void deactivate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- float noisetoggle; diff --git a/plugins/ZamNoise/ZamNoiseUI.cpp b/plugins/ZamNoise/ZamNoiseUI.cpp index 26a3ca9..a2001d6 100644 --- a/plugins/ZamNoise/ZamNoiseUI.cpp +++ b/plugins/ZamNoise/ZamNoiseUI.cpp @@ -40,7 +40,7 @@ ZamNoiseUI::ZamNoiseUI() fToggleNoise->setCallback(this); fToggleNoise->setValue(0.f); - d_programChanged(0); + programLoaded(0); } ZamNoiseUI::~ZamNoiseUI() @@ -50,7 +50,7 @@ ZamNoiseUI::~ZamNoiseUI() // ----------------------------------------------------------------------- // DSP Callbacks -void ZamNoiseUI::d_parameterChanged(uint32_t index, float value) +void ZamNoiseUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -61,7 +61,7 @@ void ZamNoiseUI::d_parameterChanged(uint32_t index, float value) } -void ZamNoiseUI::d_programChanged(uint32_t index) +void ZamNoiseUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -73,7 +73,7 @@ void ZamNoiseUI::imageToggleClicked(ImageToggle*, int) { float toggle = fToggleNoise->getValue(); fToggleNoise->setValue(toggle); - d_setParameterValue(ZamNoisePlugin::paramNoiseToggle, toggle); + setParameterValue(ZamNoisePlugin::paramNoiseToggle, toggle); } diff --git a/plugins/ZamNoise/ZamNoiseUI.hpp b/plugins/ZamNoise/ZamNoiseUI.hpp index b423f3b..5eb72e9 100644 --- a/plugins/ZamNoise/ZamNoiseUI.hpp +++ b/plugins/ZamNoise/ZamNoiseUI.hpp @@ -44,8 +44,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) ; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamPiano/Makefile b/plugins/ZamPiano/Makefile index 72f117e..24543c9 100644 --- a/plugins/ZamPiano/Makefile +++ b/plugins/ZamPiano/Makefile @@ -29,11 +29,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack lv2_sep -#all: jack dssi lv2_sep vst +TARGETS += dssi_dsp +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi_ui +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: dssi lv2_sep vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamPiano/ZamPianoPlugin.cpp b/plugins/ZamPiano/ZamPianoPlugin.cpp index 296da98..28f57df 100644 --- a/plugins/ZamPiano/ZamPianoPlugin.cpp +++ b/plugins/ZamPiano/ZamPianoPlugin.cpp @@ -25,7 +25,7 @@ ZamPianoPlugin::ZamPianoPlugin() : Plugin(paramCount, 1, 0) // 1 program, 0 states { // set default values - d_setProgram(0); + loadProgram(0); } ZamPianoPlugin::~ZamPianoPlugin() @@ -40,7 +40,7 @@ ZamPianoPlugin::~ZamPianoPlugin() // ----------------------------------------------------------------------- // Init -void ZamPianoPlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamPianoPlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -146,7 +146,7 @@ void ZamPianoPlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamPianoPlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamPianoPlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -157,7 +157,7 @@ void ZamPianoPlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamPianoPlugin::d_getParameterValue(uint32_t index) const +float ZamPianoPlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -200,7 +200,7 @@ float ZamPianoPlugin::d_getParameterValue(uint32_t index) const } } -void ZamPianoPlugin::d_setParameterValue(uint32_t index, float value) +void ZamPianoPlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -240,22 +240,22 @@ void ZamPianoPlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamPianoPlugin::d_setProgram(uint32_t index) +void ZamPianoPlugin::loadProgram(uint32_t index) { if (index != 0) return; /* Default parameter values */ /* reset filter values */ - d_activate(); + activate(); } /* -void ZamPianoPlugin::d_setState(const char*, const char*) +void ZamPianoPlugin::setState(const char*, const char*) { } -void ZamPianoPlugin::d_initStateKey(unsigned int, d_string&) +void ZamPianoPlugin::initStateKey(unsigned int, String&) { } */ @@ -263,7 +263,7 @@ void ZamPianoPlugin::d_initStateKey(unsigned int, d_string&) // ----------------------------------------------------------------------- // Process -void ZamPianoPlugin::d_activate() +void ZamPianoPlugin::activate() { int i; for (i = 0; i < 88; i++) { @@ -288,7 +288,7 @@ void ZamPianoPlugin::d_activate() } } -void ZamPianoPlugin::d_run(const float** inputs, float** outputs, uint32_t frames, +void ZamPianoPlugin::run(const float** inputs, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) { uint32_t i, j; diff --git a/plugins/ZamPiano/ZamPianoPlugin.hpp b/plugins/ZamPiano/ZamPianoPlugin.hpp index 414f9ad..ae4561e 100644 --- a/plugins/ZamPiano/ZamPianoPlugin.hpp +++ b/plugins/ZamPiano/ZamPianoPlugin.hpp @@ -60,27 +60,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamPiano"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'P', 'N', '2'); } @@ -88,15 +88,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -118,8 +118,8 @@ protected: return (20.f*log10(g)); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames, + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamPiano/ZamPianoUI.cpp b/plugins/ZamPiano/ZamPianoUI.cpp index 8c384b4..47f1610 100644 --- a/plugins/ZamPiano/ZamPianoUI.cpp +++ b/plugins/ZamPiano/ZamPianoUI.cpp @@ -96,13 +96,13 @@ ZamPianoUI::ZamPianoUI() fKnobWidth->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamPianoUI::d_parameterChanged(uint32_t index, float value) +void ZamPianoUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -133,7 +133,7 @@ void ZamPianoUI::d_parameterChanged(uint32_t index, float value) } } -void ZamPianoUI::d_programChanged(uint32_t index) +void ZamPianoUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -154,61 +154,61 @@ void ZamPianoUI::d_programChanged(uint32_t index) void ZamPianoUI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobBright) - d_editParameter(ZamPianoPlugin::paramBright, true); + editParameter(ZamPianoPlugin::paramBright, true); else if (knob == fKnobDetune) - d_editParameter(ZamPianoPlugin::paramDetuning, true); + editParameter(ZamPianoPlugin::paramDetuning, true); else if (knob == fKnobHammer) - d_editParameter(ZamPianoPlugin::paramHammerHard, true); + editParameter(ZamPianoPlugin::paramHammerHard, true); else if (knob == fKnobStiff) - d_editParameter(ZamPianoPlugin::paramStiffness, true); + editParameter(ZamPianoPlugin::paramStiffness, true); else if (knob == fKnobReverbGain) - d_editParameter(ZamPianoPlugin::paramReverbGain, true); + editParameter(ZamPianoPlugin::paramReverbGain, true); else if (knob == fKnobReverbRoom) - d_editParameter(ZamPianoPlugin::paramReverbRoom, true); + editParameter(ZamPianoPlugin::paramReverbRoom, true); else if (knob == fKnobPan) - d_editParameter(ZamPianoPlugin::paramPanAngle, true); + editParameter(ZamPianoPlugin::paramPanAngle, true); else if (knob == fKnobWidth) - d_editParameter(ZamPianoPlugin::paramSpatialWidth, true); + editParameter(ZamPianoPlugin::paramSpatialWidth, true); } void ZamPianoUI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobBright) - d_editParameter(ZamPianoPlugin::paramBright, false); + editParameter(ZamPianoPlugin::paramBright, false); else if (knob == fKnobDetune) - d_editParameter(ZamPianoPlugin::paramDetuning, false); + editParameter(ZamPianoPlugin::paramDetuning, false); else if (knob == fKnobHammer) - d_editParameter(ZamPianoPlugin::paramHammerHard, false); + editParameter(ZamPianoPlugin::paramHammerHard, false); else if (knob == fKnobStiff) - d_editParameter(ZamPianoPlugin::paramStiffness, false); + editParameter(ZamPianoPlugin::paramStiffness, false); else if (knob == fKnobReverbGain) - d_editParameter(ZamPianoPlugin::paramReverbGain, false); + editParameter(ZamPianoPlugin::paramReverbGain, false); else if (knob == fKnobReverbRoom) - d_editParameter(ZamPianoPlugin::paramReverbRoom, false); + editParameter(ZamPianoPlugin::paramReverbRoom, false); else if (knob == fKnobPan) - d_editParameter(ZamPianoPlugin::paramPanAngle, false); + editParameter(ZamPianoPlugin::paramPanAngle, false); else if (knob == fKnobWidth) - d_editParameter(ZamPianoPlugin::paramSpatialWidth, false); + editParameter(ZamPianoPlugin::paramSpatialWidth, false); } void ZamPianoUI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobBright) - d_setParameterValue(ZamPianoPlugin::paramBright, value); + setParameterValue(ZamPianoPlugin::paramBright, value); else if (knob == fKnobDetune) - d_setParameterValue(ZamPianoPlugin::paramDetuning, value); + setParameterValue(ZamPianoPlugin::paramDetuning, value); else if (knob == fKnobHammer) - d_setParameterValue(ZamPianoPlugin::paramHammerHard, value); + setParameterValue(ZamPianoPlugin::paramHammerHard, value); else if (knob == fKnobStiff) - d_setParameterValue(ZamPianoPlugin::paramStiffness, value); + setParameterValue(ZamPianoPlugin::paramStiffness, value); else if (knob == fKnobReverbGain) - d_setParameterValue(ZamPianoPlugin::paramReverbGain, value); + setParameterValue(ZamPianoPlugin::paramReverbGain, value); else if (knob == fKnobReverbRoom) - d_setParameterValue(ZamPianoPlugin::paramReverbRoom, value); + setParameterValue(ZamPianoPlugin::paramReverbRoom, value); else if (knob == fKnobPan) - d_setParameterValue(ZamPianoPlugin::paramPanAngle, value); + setParameterValue(ZamPianoPlugin::paramPanAngle, value); else if (knob == fKnobWidth) - d_setParameterValue(ZamPianoPlugin::paramSpatialWidth, value); + setParameterValue(ZamPianoPlugin::paramSpatialWidth, value); } void ZamPianoUI::onDisplay() diff --git a/plugins/ZamPiano/ZamPianoUI.hpp b/plugins/ZamPiano/ZamPianoUI.hpp index ad81a8a..c2c85b4 100644 --- a/plugins/ZamPiano/ZamPianoUI.hpp +++ b/plugins/ZamPiano/ZamPianoUI.hpp @@ -39,8 +39,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamSFZ/Makefile b/plugins/ZamSFZ/Makefile index aa1ba72..1398b0f 100644 --- a/plugins/ZamSFZ/Makefile +++ b/plugins/ZamSFZ/Makefile @@ -35,11 +35,29 @@ LINK_FLAGS += $(shell pkg-config --libs sndfile rubberband) # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack lv2_sep -#all: jack dssi lv2_sep vst +TARGETS += dssi_dsp +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi_ui +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: dssi lv2_sep vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamSFZ/ZamSFZPlugin.cpp b/plugins/ZamSFZ/ZamSFZPlugin.cpp index 93ca4a5..c7bd616 100644 --- a/plugins/ZamSFZ/ZamSFZPlugin.cpp +++ b/plugins/ZamSFZ/ZamSFZPlugin.cpp @@ -25,13 +25,13 @@ ZamSFZPlugin::ZamSFZPlugin() : Plugin(paramCount, 1, 1) // 1 program, 1 state { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamSFZPlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamSFZPlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -47,7 +47,7 @@ void ZamSFZPlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamSFZPlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamSFZPlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -58,7 +58,7 @@ void ZamSFZPlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamSFZPlugin::d_getParameterValue(uint32_t index) const +float ZamSFZPlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -70,7 +70,7 @@ float ZamSFZPlugin::d_getParameterValue(uint32_t index) const } } -void ZamSFZPlugin::d_setParameterValue(uint32_t index, float value) +void ZamSFZPlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -80,7 +80,7 @@ void ZamSFZPlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamSFZPlugin::d_setState(const char* key, const char* value) +void ZamSFZPlugin::setState(const char* key, const char* value) { if (strcmp(key, "filepath") == 0) { char *tmp; @@ -93,18 +93,18 @@ void ZamSFZPlugin::d_setState(const char* key, const char* value) printf("Path: %s\nFile: %s\n", path.c_str(), filename.c_str()); sfz.clearsamples(); sfz.loadsamples(path, filename); - sfz.pitchshiftsamples((int)d_getSampleRate()); + sfz.pitchshiftsamples((int)getSampleRate()); loading = false; } } -void ZamSFZPlugin::d_initState(unsigned int key, d_string& val, d_string&) +void ZamSFZPlugin::initState(unsigned int key, String& val, d_string&) { if (key == 0) val = "filepath"; } -void ZamSFZPlugin::d_setProgram(uint32_t index) +void ZamSFZPlugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -136,21 +136,21 @@ void ZamSFZPlugin::d_setProgram(uint32_t index) env_y[0] = 0.f; env_y[MAX_ENV-1] = 0.f; /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamSFZPlugin::d_activate() +void ZamSFZPlugin::activate() { } -void ZamSFZPlugin::d_run(const float**, float** outputs, uint32_t frames, +void ZamSFZPlugin::run(const float**, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); int slowfactor = (int) srate / (speed * 2400); // 1-20 ~ 20-1 uint32_t i; diff --git a/plugins/ZamSFZ/ZamSFZPlugin.hpp b/plugins/ZamSFZ/ZamSFZPlugin.hpp index 90ff40a..24e38cb 100644 --- a/plugins/ZamSFZ/ZamSFZPlugin.hpp +++ b/plugins/ZamSFZ/ZamSFZPlugin.hpp @@ -46,27 +46,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamSFZ"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'S', 'F', 'Z'); } @@ -74,16 +74,16 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -106,11 +106,11 @@ protected: } float wavetable(int i, int note); - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames, + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) override; - void d_setState(const char* key, const char* value) override; - void d_initState(unsigned int, d_string&, d_string&) override; + void setState(const char* key, const char* value) override; + void initState(unsigned int, String&, d_string&) override; // ------------------------------------------------------------------- private: diff --git a/plugins/ZamSFZ/ZamSFZUI.cpp b/plugins/ZamSFZ/ZamSFZUI.cpp index 3bb4d69..6c4b5f4 100644 --- a/plugins/ZamSFZ/ZamSFZUI.cpp +++ b/plugins/ZamSFZ/ZamSFZUI.cpp @@ -53,13 +53,13 @@ ZamSFZUI::ZamSFZUI() fButtonLoad->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamSFZUI::d_parameterChanged(uint32_t index, float value) +void ZamSFZUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -69,7 +69,7 @@ void ZamSFZUI::d_parameterChanged(uint32_t index, float value) } } -void ZamSFZUI::d_programChanged(uint32_t index) +void ZamSFZUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -77,7 +77,7 @@ void ZamSFZUI::d_programChanged(uint32_t index) fKnobGain->setValue(0.0f); } -void ZamSFZUI::d_stateChanged(const char* key, const char*) +void ZamSFZUI::stateChanged(const char* key, const char*) { if (strcmp(key, "filepath") == 0) { printf("state changed... do something?\n"); @@ -88,7 +88,7 @@ void ZamSFZUI::d_uiFileBrowserSelected(const char* filename) { // if a file was selected, tell DSP if (filename != nullptr) - d_setState("filepath", filename); + setState("filepath", filename); } // ----------------------------------------------------------------------- @@ -97,19 +97,19 @@ void ZamSFZUI::d_uiFileBrowserSelected(const char* filename) void ZamSFZUI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobGain) - d_editParameter(ZamSFZPlugin::paramGain, true); + editParameter(ZamSFZPlugin::paramGain, true); } void ZamSFZUI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobGain) - d_editParameter(ZamSFZPlugin::paramGain, false); + editParameter(ZamSFZPlugin::paramGain, false); } void ZamSFZUI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobGain) - d_setParameterValue(ZamSFZPlugin::paramGain, value); + setParameterValue(ZamSFZPlugin::paramGain, value); } void ZamSFZUI::imageButtonClicked(ImageButton*, int) diff --git a/plugins/ZamSFZ/ZamSFZUI.hpp b/plugins/ZamSFZ/ZamSFZUI.hpp index e82f406..b90daaf 100644 --- a/plugins/ZamSFZ/ZamSFZUI.hpp +++ b/plugins/ZamSFZ/ZamSFZUI.hpp @@ -42,9 +42,9 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; - void d_stateChanged(const char* key, const char* value) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; + void stateChanged(const char* key, const char* value) override; void d_uiFileBrowserSelected(const char* filename) override; diff --git a/plugins/ZamSynth/Makefile b/plugins/ZamSynth/Makefile index 56a0426..cd68dd2 100644 --- a/plugins/ZamSynth/Makefile +++ b/plugins/ZamSynth/Makefile @@ -27,10 +27,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack dssi lv2_sep vst +TARGETS += dssi_dsp +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi_ui +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: dssi lv2_sep vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamSynth/ZamSynthPlugin.cpp b/plugins/ZamSynth/ZamSynthPlugin.cpp index 6addb0b..8546a7a 100644 --- a/plugins/ZamSynth/ZamSynthPlugin.cpp +++ b/plugins/ZamSynth/ZamSynthPlugin.cpp @@ -25,13 +25,13 @@ ZamSynthPlugin::ZamSynthPlugin() : Plugin(paramCount, 1, 1) // 1 program, 1 state { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamSynthPlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamSynthPlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -65,7 +65,7 @@ void ZamSynthPlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamSynthPlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamSynthPlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -76,7 +76,7 @@ void ZamSynthPlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamSynthPlugin::d_getParameterValue(uint32_t index) const +float ZamSynthPlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -94,7 +94,7 @@ float ZamSynthPlugin::d_getParameterValue(uint32_t index) const } } -void ZamSynthPlugin::d_setParameterValue(uint32_t index, float value) +void ZamSynthPlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -110,7 +110,7 @@ void ZamSynthPlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamSynthPlugin::d_setProgram(uint32_t index) +void ZamSynthPlugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -134,17 +134,17 @@ void ZamSynthPlugin::d_setProgram(uint32_t index) curvoice = voice; //ptr to first voice for (int i = 0; i < AREAHEIGHT; i++) { - wave_y[i] = sin(i*2.*M_PI/d_getSampleRate());//*1000 + wave_y[i] = sin(i*2.*M_PI/getSampleRate());//*1000 } for (int i = 0; i < MAX_ENV; i++) { - env_y[i] = (sin(i*2.*M_PI/d_getSampleRate()*1000./2.)) > 0.f ? sin(i*2.*M_PI/d_getSampleRate()*1000./2.) : 0.f; + env_y[i] = (sin(i*2.*M_PI/getSampleRate()*1000./2.)) > 0.f ? sin(i*2.*M_PI/d_getSampleRate()*1000./2.) : 0.f; } /* reset filter values */ - d_activate(); + activate(); } -void ZamSynthPlugin::d_setState(const char* key, const char* value) +void ZamSynthPlugin::setState(const char* key, const char* value) { if (strcmp(key, "waveform") == 0) { char* tmp; @@ -173,7 +173,7 @@ void ZamSynthPlugin::d_setState(const char* key, const char* value) } } -void ZamSynthPlugin::d_initStateKey(unsigned int index, d_string& key) +void ZamSynthPlugin::initStateKey(unsigned int index, String& key) { if (index == 0) key = "waveform"; if (index == 1) key = "envelope"; @@ -182,7 +182,7 @@ void ZamSynthPlugin::d_initStateKey(unsigned int index, d_string& key) // ----------------------------------------------------------------------- // Process -void ZamSynthPlugin::d_activate() +void ZamSynthPlugin::activate() { } @@ -193,10 +193,10 @@ float ZamSynthPlugin::wavetable(float in) //return (sin(in)); } -void ZamSynthPlugin::d_run(const float**, float** outputs, uint32_t frames, +void ZamSynthPlugin::run(const float**, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) { - float srate = d_getSampleRate(); + float srate = getSampleRate(); int slowfactor = (int) srate / (speed * 2400); // 1-20 ~ 20-1 uint32_t i; float RD_0; diff --git a/plugins/ZamSynth/ZamSynthPlugin.hpp b/plugins/ZamSynth/ZamSynthPlugin.hpp index dfcb044..cefc33f 100644 --- a/plugins/ZamSynth/ZamSynthPlugin.hpp +++ b/plugins/ZamSynth/ZamSynthPlugin.hpp @@ -45,27 +45,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamSynth"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1000; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'S', 'T', 'H'); } @@ -73,15 +73,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -104,11 +104,11 @@ protected: } float wavetable(float in); - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames, + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames, const MidiEvent* midievent, uint32_t midicount) override; - void d_setState(const char* key, const char* value) override; - void d_initStateKey(unsigned int key, d_string& val) override; + void setState(const char* key, const char* value) override; + void initStateKey(unsigned int key, String& val) override; // ------------------------------------------------------------------- private: diff --git a/plugins/ZamSynth/ZamSynthUI.cpp b/plugins/ZamSynth/ZamSynthUI.cpp index 92233be..6933d5d 100644 --- a/plugins/ZamSynth/ZamSynthUI.cpp +++ b/plugins/ZamSynth/ZamSynthUI.cpp @@ -79,10 +79,10 @@ ZamSynthUI::ZamSynthUI() fToggleGraph->setValue(0.f); // set default values - d_programChanged(0); + programLoaded(0); } -void ZamSynthUI::d_stateChanged(const char* key, const char* value) +void ZamSynthUI::stateChanged(const char* key, const char* value) { if (strcmp(key, "waveform") == 0) { char* tmp; @@ -114,7 +114,7 @@ void ZamSynthUI::d_stateChanged(const char* key, const char* value) // ----------------------------------------------------------------------- // DSP Callbacks -void ZamSynthUI::d_parameterChanged(uint32_t index, float value) +void ZamSynthUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -130,7 +130,7 @@ void ZamSynthUI::d_parameterChanged(uint32_t index, float value) } } -void ZamSynthUI::d_programChanged(uint32_t index) +void ZamSynthUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -145,25 +145,25 @@ void ZamSynthUI::d_programChanged(uint32_t index) void ZamSynthUI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobGain) - d_editParameter(ZamSynthPlugin::paramGain, true); + editParameter(ZamSynthPlugin::paramGain, true); else if (knob == fKnobSpeed) - d_editParameter(ZamSynthPlugin::paramSpeed, true); + editParameter(ZamSynthPlugin::paramSpeed, true); } void ZamSynthUI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobGain) - d_editParameter(ZamSynthPlugin::paramGain, false); + editParameter(ZamSynthPlugin::paramGain, false); else if (knob == fKnobSpeed) - d_editParameter(ZamSynthPlugin::paramSpeed, false); + editParameter(ZamSynthPlugin::paramSpeed, false); } void ZamSynthUI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobGain) - d_setParameterValue(ZamSynthPlugin::paramGain, value); + setParameterValue(ZamSynthPlugin::paramGain, value); else if (knob == fKnobSpeed) - d_setParameterValue(ZamSynthPlugin::paramSpeed, value); + setParameterValue(ZamSynthPlugin::paramSpeed, value); } void ZamSynthUI::imageButtonClicked(ImageButton*, int) @@ -189,16 +189,16 @@ void ZamSynthUI::imageButtonClicked(ImageButton*, int) } if (fToggleGraph->getValue() == 1.f) - d_setState("envelope", tmp); + setState("envelope", tmp); else - d_setState("waveform", tmp); + setState("waveform", tmp); } void ZamSynthUI::imageToggleClicked(ImageToggle*, int) { float toggle = fToggleGraph->getValue(); fToggleGraph->setValue(toggle); - d_setParameterValue(ZamSynthPlugin::paramGraph, toggle); + setParameterValue(ZamSynthPlugin::paramGraph, toggle); } void ZamSynthUI::gaussiansmooth(float* smoothed, float* xs, float* ys, int n, int radius) @@ -284,9 +284,9 @@ bool ZamSynthUI::onMotion(const MotionEvent& ev) gr[x-10] = y-10; if (gr == env_y) - d_setState("envelope",tmp); + setState("envelope",tmp); else - d_setState("waveform",tmp); + setState("waveform",tmp); repaint(); } diff --git a/plugins/ZamSynth/ZamSynthUI.hpp b/plugins/ZamSynth/ZamSynthUI.hpp index 291990f..dcae528 100644 --- a/plugins/ZamSynth/ZamSynthUI.hpp +++ b/plugins/ZamSynth/ZamSynthUI.hpp @@ -64,9 +64,9 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) override; - void d_programChanged(uint32_t index) override; - void d_stateChanged(const char*, const char*) override; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; + void stateChanged(const char*, const char*) override; // ------------------------------------------------------------------- // Widget Callbacks diff --git a/plugins/ZamTube/Makefile b/plugins/ZamTube/Makefile index 0764115..0925dac 100644 --- a/plugins/ZamTube/Makefile +++ b/plugins/ZamTube/Makefile @@ -28,10 +28,29 @@ include ../Makefile.mk # -------------------------------------------------------------- # Enable all possible plugin types +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_JACK),true) +TARGETS += jack +endif +endif + ifeq ($(LINUX),true) -all: jack ladspa dssi lv2_sep vst +TARGETS += ladspa +ifeq ($(HAVE_DGL),true) +ifeq ($(HAVE_LIBLO),true) +TARGETS += dssi +endif +endif +endif + +ifeq ($(HAVE_DGL),true) +TARGETS += lv2_sep else -all: ladspa vst +TARGETS += lv2_dsp endif +TARGETS += vst + +all: $(TARGETS) + # -------------------------------------------------------------- diff --git a/plugins/ZamTube/ZamTubePlugin.cpp b/plugins/ZamTube/ZamTubePlugin.cpp index 6b829e3..e4aa101 100644 --- a/plugins/ZamTube/ZamTubePlugin.cpp +++ b/plugins/ZamTube/ZamTubePlugin.cpp @@ -32,13 +32,13 @@ ZamTubePlugin::ZamTubePlugin() I1(&S1), I3(&Ck,&Rk), S2(&Co,&Ro), I4(&S2), P2(&I4,&E) { // set default values - d_setProgram(0); + loadProgram(0); } // ----------------------------------------------------------------------- // Init -void ZamTubePlugin::d_initParameter(uint32_t index, Parameter& parameter) +void ZamTubePlugin::initParameter(uint32_t index, Parameter& parameter) { switch (index) { @@ -108,7 +108,7 @@ void ZamTubePlugin::d_initParameter(uint32_t index, Parameter& parameter) } } -void ZamTubePlugin::d_initProgramName(uint32_t index, d_string& programName) +void ZamTubePlugin::initProgramName(uint32_t index, String& programName) { if (index != 0) return; @@ -119,7 +119,7 @@ void ZamTubePlugin::d_initProgramName(uint32_t index, d_string& programName) // ----------------------------------------------------------------------- // Internal data -float ZamTubePlugin::d_getParameterValue(uint32_t index) const +float ZamTubePlugin::getParameterValue(uint32_t index) const { switch (index) { @@ -149,7 +149,7 @@ float ZamTubePlugin::d_getParameterValue(uint32_t index) const } } -void ZamTubePlugin::d_setParameterValue(uint32_t index, float value) +void ZamTubePlugin::setParameterValue(uint32_t index, float value) { switch (index) { @@ -177,7 +177,7 @@ void ZamTubePlugin::d_setParameterValue(uint32_t index, float value) } } -void ZamTubePlugin::d_setProgram(uint32_t index) +void ZamTubePlugin::loadProgram(uint32_t index) { if (index != 0) return; @@ -194,16 +194,16 @@ void ZamTubePlugin::d_setProgram(uint32_t index) /* Default variable values */ /* reset filter values */ - d_activate(); + activate(); } // ----------------------------------------------------------------------- // Process -void ZamTubePlugin::d_activate() +void ZamTubePlugin::activate() { - T Fs = d_getSampleRate(); + T Fs = getSampleRate(); // Passive components T ci = 0.0000001; //100nF @@ -297,7 +297,7 @@ void ZamTubePlugin::d_activate() for (int i=0; i<4; i++) fRec24[i] = 0; } -void ZamTubePlugin::d_run(const float** inputs, float** outputs, uint32_t frames) +void ZamTubePlugin::run(const float** inputs, float** outputs, uint32_t frames) { T tubetone = 0.f; diff --git a/plugins/ZamTube/ZamTubePlugin.hpp b/plugins/ZamTube/ZamTubePlugin.hpp index 4a23b59..6e12d82 100644 --- a/plugins/ZamTube/ZamTubePlugin.hpp +++ b/plugins/ZamTube/ZamTubePlugin.hpp @@ -121,27 +121,27 @@ protected: // ------------------------------------------------------------------- // Information - const char* d_getLabel() const noexcept override + const char* getLabel() const noexcept override { return "ZamTube"; } - const char* d_getMaker() const noexcept override + const char* getMaker() const noexcept override { return "Damien Zammit"; } - const char* d_getLicense() const noexcept override + const char* getLicense() const noexcept override { return "GPL v2+"; } - uint32_t d_getVersion() const noexcept override + uint32_t getVersion() const noexcept override { return 0x1500; } - int64_t d_getUniqueId() const noexcept override + int64_t getUniqueId() const noexcept override { return d_cconst('Z', 'T', 'U', 'B'); } @@ -149,15 +149,15 @@ protected: // ------------------------------------------------------------------- // Init - void d_initParameter(uint32_t index, Parameter& parameter) ; - void d_initProgramName(uint32_t index, d_string& programName) ; + void initParameter(uint32_t index, Parameter& parameter) ; + void initProgramName(uint32_t index, String& programName) ; // ------------------------------------------------------------------- // Internal data - float d_getParameterValue(uint32_t index) const override; - void d_setParameterValue(uint32_t index, float value) override; - void d_setProgram(uint32_t index) ; + float getParameterValue(uint32_t index) const override; + void setParameterValue(uint32_t index, float value) override; + void loadProgram(uint32_t index) override; // ------------------------------------------------------------------- // Process @@ -179,8 +179,8 @@ protected: return (20.f*log10(g)); } - void d_activate() override; - void d_run(const float** inputs, float** outputs, uint32_t frames) override; + void activate() override; + void run(const float** inputs, float** outputs, uint32_t frames) override; // ------------------------------------------------------------------- diff --git a/plugins/ZamTube/ZamTubeUI.cpp b/plugins/ZamTube/ZamTubeUI.cpp index f999e66..50fc349 100644 --- a/plugins/ZamTube/ZamTubeUI.cpp +++ b/plugins/ZamTube/ZamTubeUI.cpp @@ -107,13 +107,13 @@ ZamTubeUI::ZamTubeUI() fToggleInsane->setCallback(this); // set default values - d_programChanged(0); + programLoaded(0); } // ----------------------------------------------------------------------- // DSP Callbacks -void ZamTubeUI::d_parameterChanged(uint32_t index, float value) +void ZamTubeUI::parameterChanged(uint32_t index, float value) { switch (index) { @@ -138,7 +138,7 @@ void ZamTubeUI::d_parameterChanged(uint32_t index, float value) } } -void ZamTubeUI::d_programChanged(uint32_t index) +void ZamTubeUI::programLoaded(uint32_t index) { if (index != 0) return; @@ -159,65 +159,65 @@ void ZamTubeUI::d_programChanged(uint32_t index) void ZamTubeUI::imageKnobDragStarted(ImageKnob* knob) { if (knob == fKnobTube) - d_editParameter(ZamTubePlugin::paramTubedrive, true); + editParameter(ZamTubePlugin::paramTubedrive, true); else if (knob == fKnobBass) - d_editParameter(ZamTubePlugin::paramBass, true); + editParameter(ZamTubePlugin::paramBass, true); else if (knob == fKnobMids) - d_editParameter(ZamTubePlugin::paramMiddle, true); + editParameter(ZamTubePlugin::paramMiddle, true); else if (knob == fKnobTreb) - d_editParameter(ZamTubePlugin::paramTreble, true); + editParameter(ZamTubePlugin::paramTreble, true); else if (knob == fKnobGain) - d_editParameter(ZamTubePlugin::paramGain, true); + editParameter(ZamTubePlugin::paramGain, true); } void ZamTubeUI::imageKnobDragFinished(ImageKnob* knob) { if (knob == fKnobTube) - d_editParameter(ZamTubePlugin::paramTubedrive, false); + editParameter(ZamTubePlugin::paramTubedrive, false); else if (knob == fKnobBass) - d_editParameter(ZamTubePlugin::paramBass, false); + editParameter(ZamTubePlugin::paramBass, false); else if (knob == fKnobMids) - d_editParameter(ZamTubePlugin::paramMiddle, false); + editParameter(ZamTubePlugin::paramMiddle, false); else if (knob == fKnobTreb) - d_editParameter(ZamTubePlugin::paramTreble, false); + editParameter(ZamTubePlugin::paramTreble, false); else if (knob == fKnobGain) - d_editParameter(ZamTubePlugin::paramGain, false); + editParameter(ZamTubePlugin::paramGain, false); } void ZamTubeUI::imageKnobValueChanged(ImageKnob* knob, float value) { if (knob == fKnobTube) - d_setParameterValue(ZamTubePlugin::paramTubedrive, value); + setParameterValue(ZamTubePlugin::paramTubedrive, value); else if (knob == fKnobBass) - d_setParameterValue(ZamTubePlugin::paramBass, value); + setParameterValue(ZamTubePlugin::paramBass, value); else if (knob == fKnobMids) - d_setParameterValue(ZamTubePlugin::paramMiddle, value); + setParameterValue(ZamTubePlugin::paramMiddle, value); else if (knob == fKnobTreb) - d_setParameterValue(ZamTubePlugin::paramTreble, value); + setParameterValue(ZamTubePlugin::paramTreble, value); else if (knob == fKnobGain) - d_setParameterValue(ZamTubePlugin::paramGain, value); + setParameterValue(ZamTubePlugin::paramGain, value); } void ZamTubeUI::imageSliderDragStarted(ImageSlider*) { - d_editParameter(ZamTubePlugin::paramToneStack, true); + editParameter(ZamTubePlugin::paramToneStack, true); } void ZamTubeUI::imageSliderDragFinished(ImageSlider*) { - d_editParameter(ZamTubePlugin::paramToneStack, false); + editParameter(ZamTubePlugin::paramToneStack, false); } void ZamTubeUI::imageSliderValueChanged(ImageSlider*, float value) { - d_setParameterValue(ZamTubePlugin::paramToneStack, value); + setParameterValue(ZamTubePlugin::paramToneStack, value); } void ZamTubeUI::imageToggleClicked(ImageToggle* toggle, int) { float v = toggle->getValue(); if (toggle == fToggleInsane) { - d_setParameterValue(ZamTubePlugin::paramInsane, v); + setParameterValue(ZamTubePlugin::paramInsane, v); } } diff --git a/plugins/ZamTube/ZamTubeUI.hpp b/plugins/ZamTube/ZamTubeUI.hpp index f76eb4e..c4f6b12 100644 --- a/plugins/ZamTube/ZamTubeUI.hpp +++ b/plugins/ZamTube/ZamTubeUI.hpp @@ -47,8 +47,8 @@ protected: // ------------------------------------------------------------------- // DSP Callbacks - void d_parameterChanged(uint32_t index, float value) ; - void d_programChanged(uint32_t index) ; + void parameterChanged(uint32_t index, float value) override; + void programLoaded(uint32_t index) override; // ------------------------------------------------------------------- // Widget Callbacks |