адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
@@ -0,0 +1,81 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
package com.rmsl.juce;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Region;
import android.view.SurfaceView;
public class JuceOpenGLView extends SurfaceView
{
private long host = 0;
JuceOpenGLView (Context context, long nativeThis)
{
super (context);
host = nativeThis;
}
public void cancel ()
{
host = 0;
}
//==============================================================================
@Override
public boolean gatherTransparentRegion (Region unused)
{
// Returning true indicates that the view is opaque at this point.
// Without this, the green TalkBack borders cannot be seen on OpenGL views.
return true;
}
@Override
protected void dispatchDraw (Canvas canvas)
{
super.dispatchDraw (canvas);
if (host != 0)
onDrawNative (host, canvas);
}
//==============================================================================
private native void onAttchedWindowNative (long nativeThis);
private native void onDetachedFromWindowNative (long nativeThis);
private native void onDrawNative (long nativeThis, Canvas canvas);
}
@@ -0,0 +1,151 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/** @internal This macro contains a list of GL extension functions that need to be dynamically loaded on Windows/Linux.
@see OpenGLExtensionFunctions
*/
#define JUCE_GL_BASE_FUNCTIONS \
X (glActiveTexture) \
X (glBindBuffer) \
X (glDeleteBuffers) \
X (glGenBuffers) \
X (glBufferData) \
X (glBufferSubData) \
X (glCreateProgram) \
X (glDeleteProgram) \
X (glCreateShader) \
X (glDeleteShader) \
X (glShaderSource) \
X (glCompileShader) \
X (glAttachShader) \
X (glLinkProgram) \
X (glUseProgram) \
X (glGetShaderiv) \
X (glGetShaderInfoLog) \
X (glGetProgramInfoLog) \
X (glGetProgramiv) \
X (glGetUniformLocation) \
X (glGetAttribLocation) \
X (glVertexAttribPointer) \
X (glEnableVertexAttribArray) \
X (glDisableVertexAttribArray) \
X (glUniform1f) \
X (glUniform1i) \
X (glUniform2f) \
X (glUniform3f) \
X (glUniform4f) \
X (glUniform4i) \
X (glUniform1fv) \
X (glUniformMatrix2fv) \
X (glUniformMatrix3fv) \
X (glUniformMatrix4fv) \
X (glBindAttribLocation)
/** @internal This macro contains a list of GL extension functions that need to be dynamically loaded on Windows/Linux.
@see OpenGLExtensionFunctions
*/
#define JUCE_GL_EXTENSION_FUNCTIONS \
X (glIsRenderbuffer) \
X (glBindRenderbuffer) \
X (glDeleteRenderbuffers) \
X (glGenRenderbuffers) \
X (glRenderbufferStorage) \
X (glGetRenderbufferParameteriv) \
X (glIsFramebuffer) \
X (glBindFramebuffer) \
X (glDeleteFramebuffers) \
X (glGenFramebuffers) \
X (glCheckFramebufferStatus) \
X (glFramebufferTexture2D) \
X (glFramebufferRenderbuffer) \
X (glGetFramebufferAttachmentParameteriv)
/** @internal This macro contains a list of GL extension functions that need to be dynamically loaded on Windows/Linux.
@see OpenGLExtensionFunctions
*/
#define JUCE_GL_VERTEXBUFFER_FUNCTIONS \
X (glGenVertexArrays) \
X (glDeleteVertexArrays) \
X (glBindVertexArray)
/** This class contains a generated list of OpenGL extension functions, which are either dynamically loaded
for a specific GL context, or simply call-through to the appropriate OS function where available.
This class is provided for backwards compatibility. In new code, you should prefer to use
functions from the juce::gl namespace. By importing all these symbols with
`using namespace ::juce::gl;`, all GL enumerations and functions will be made available at
global scope. This may be helpful if you need to write code with C source compatibility, or
which is compatible with a different extension-loading library.
All the normal guidance about `using namespace` should still apply - don't do this in a header,
or at all if you can possibly avoid it!
@tags{OpenGL}
*/
struct OpenGLExtensionFunctions
{
//==============================================================================
/** @cond */
[[deprecated ("A more complete set of GL commands can be found in the juce::gl namespace. "
"You should use juce::gl::loadFunctions() to load GL functions.")]]
static void initialise();
/** @endcond */
#if JUCE_WINDOWS
/** @cond */
typedef char GLchar;
typedef pointer_sized_int GLsizeiptr;
typedef pointer_sized_int GLintptr;
/** @endcond */
#endif
#define X(name) static decltype (::juce::gl::name)& name;
JUCE_GL_BASE_FUNCTIONS
JUCE_GL_EXTENSION_FUNCTIONS
JUCE_GL_VERTEXBUFFER_FUNCTIONS
#undef X
};
enum MissingOpenGLDefinitions
{
#if JUCE_ANDROID
JUCE_RGBA_FORMAT = ::juce::gl::GL_RGBA,
#else
JUCE_RGBA_FORMAT = ::juce::gl::GL_BGRA_EXT,
#endif
};
} // namespace juce
@@ -0,0 +1,435 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
// This byte-code is generated from native/java/com/rmsl/juce/JuceOpenGLView.java with min sdk version 16
// See juce_core/native/java/README.txt on how to generate this byte-code.
static const uint8 javaJuceOpenGLView[] =
{
0x1f, 0x8b, 0x08, 0x08, 0x7e, 0xb3, 0x66, 0x68, 0x00, 0x03, 0x63, 0x6c,
0x61, 0x73, 0x73, 0x65, 0x73, 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0x70, 0xb6, 0x44, 0xe0, 0x70, 0xbe, 0x90, 0x58, 0x18,
0xe7, 0xcf, 0x18, 0x29, 0x16, 0xee, 0xf7, 0xef, 0x03, 0x89, 0x1e, 0xde,
0x73, 0x1a, 0x0b, 0x6b, 0xf9, 0x33, 0x08, 0x62, 0xe1, 0xde, 0xe0, 0x5e,
0x45, 0x43, 0xdd, 0x9f, 0x6b, 0x7f, 0x00, 0xa1, 0xe3, 0x13, 0x23, 0x10,
0x05, 0x00, 0x00
};
bool OpenGLHelpers::isOpenGLES()
{
return eglQueryAPI() == EGL_OPENGL_ES_API;
}
//==============================================================================
//==============================================================================
class OpenGLContext::NativeContext : private SurfaceHolderCallback
{
public:
NativeContext (Component& comp,
const OpenGLPixelFormat& pixelFormat,
void* /*contextToShareWith*/,
bool useMultisamplingIn,
API apiIn,
Version versionIn,
Profile profileIn)
: component (comp),
api (apiIn),
version (versionIn),
profile (profileIn)
{
auto env = getEnv();
// Do we have a native peer that we can attach to?
if (component.getPeer()->getNativeHandle() == nullptr)
return;
// Initialise the EGL display
if (! initEGLDisplay (pixelFormat, useMultisamplingIn))
return;
// create a native surface view
surfaceView = GlobalRef (LocalRef<jobject> (env->NewObject (JuceOpenGLViewSurface,
JuceOpenGLViewSurface.constructor,
getAppContext().get(),
reinterpret_cast<jlong> (this))));
if (surfaceView.get() == nullptr)
return;
surfaceHolderCallback = GlobalRef (CreateJavaInterface (this, "android/view/SurfaceHolder$Callback"));
if (surfaceHolderCallback == nullptr)
return;
if (LocalRef<jobject> holder { env->CallObjectMethod (surfaceView, AndroidSurfaceView.getHolder) })
env->CallVoidMethod (holder, AndroidSurfaceHolder.addCallback, surfaceHolderCallback.get());
// add the view to the view hierarchy
// after this the nativecontext can receive callbacks
env->CallVoidMethod ((jobject) component.getPeer()->getNativeHandle(),
AndroidViewGroup.addView,
surfaceView.get());
// initialise the geometry of the view
updateWindowPosition();
hasInitialised = true;
}
~NativeContext() override
{
auto env = getEnv();
if (surfaceView != nullptr && surfaceHolderCallback != nullptr)
if (LocalRef<jobject> holder { env->CallObjectMethod (surfaceView, AndroidSurfaceView.getHolder) })
env->CallVoidMethod (holder, AndroidSurfaceHolder.removeCallback, surfaceHolderCallback.get());
if (LocalRef viewParent { env->CallObjectMethod (surfaceView.get(), JuceOpenGLViewSurface.getParent) })
env->CallVoidMethod (viewParent, AndroidViewGroup.removeView, surfaceView.get());
}
//==============================================================================
InitResult initialiseOnRenderThread (OpenGLContext& ctx)
{
// The "real" initialisation happens when the surface is created. Here, we'll
// just return true if the initialisation happened successfully, or false if
// it hasn't happened yet, or was unsuccessful.
const std::lock_guard lock { nativeHandleMutex };
if (! hasInitialised)
return InitResult::fatal;
if (context.get() == EGL_NO_CONTEXT && surface.get() == EGL_NO_SURFACE)
return InitResult::retry;
juceContext = &ctx;
return InitResult::success;
}
void shutdownOnRenderThread()
{
const std::lock_guard lock { nativeHandleMutex };
juceContext = nullptr;
}
//==============================================================================
bool makeActive() const noexcept
{
const std::lock_guard lock { nativeHandleMutex };
return hasInitialised
&& surface.get() != EGL_NO_SURFACE
&& context.get() != EGL_NO_CONTEXT
&& eglMakeCurrent (display, surface.get(), surface.get(), context.get());
}
bool isActive() const noexcept
{
const std::lock_guard lock { nativeHandleMutex };
return eglGetCurrentContext() == context.get();
}
static void deactivateCurrentContext()
{
eglMakeCurrent (display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
//==============================================================================
void swapBuffers() const noexcept { eglSwapBuffers (display, surface.get()); }
bool setSwapInterval (int) { return false; }
int getSwapInterval() const { return 0; }
//==============================================================================
bool createdOk() const noexcept { return hasInitialised; }
void* getRawContext() const noexcept { return surfaceView.get(); }
GLuint getFrameBufferID() const noexcept { return 0; }
//==============================================================================
void updateWindowPosition()
{
const auto physical = computePhysicalBounds();
if (std::exchange (physicalBounds, physical) == physical)
return;
getEnv()->CallVoidMethod (surfaceView.get(),
JuceOpenGLViewSurface.layout,
(jint) physical.getX(),
(jint) physical.getY(),
(jint) physical.getRight(),
(jint) physical.getBottom());
}
//==============================================================================
// Android Surface Callbacks:
void surfaceChanged ([[maybe_unused]] LocalRef<jobject> holder,
[[maybe_unused]] int format,
[[maybe_unused]] int width,
[[maybe_unused]] int height) override
{
}
void surfaceCreated (LocalRef<jobject>) override;
void surfaceDestroyed (LocalRef<jobject>) override;
//==============================================================================
struct Locker
{
explicit Locker (NativeContext& ctx) : lock (ctx.mutex) {}
const ScopedLock lock;
};
Component& component;
private:
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
METHOD (constructor, "<init>", "(Landroid/content/Context;J)V") \
METHOD (getParent, "getParent", "()Landroid/view/ViewParent;") \
METHOD (layout, "layout", "(IIII)V" ) \
CALLBACK (generatedCallback<&NativeContext::dispatchDraw>, "onDrawNative", "(JLandroid/graphics/Canvas;)V")
DECLARE_JNI_CLASS_WITH_BYTECODE (JuceOpenGLViewSurface, "com/rmsl/juce/JuceOpenGLView", 24, javaJuceOpenGLView)
#undef JNI_CLASS_MEMBERS
//==============================================================================
static void dispatchDraw (JNIEnv*, NativeContext& t, jobject /*canvas*/)
{
const std::lock_guard lock { t.nativeHandleMutex };
if (t.juceContext != nullptr)
t.juceContext->triggerRepaint();
}
bool tryChooseConfig (Span<const EGLint> optionalAttribs)
{
std::vector<EGLint> allAttribs
{
EGL_RENDERABLE_TYPE, api == OpenGLAPI::openGLES ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_ALPHA_SIZE, 0,
EGL_DEPTH_SIZE, 16
};
allAttribs.insert (allAttribs.end(), optionalAttribs.begin(), optionalAttribs.end());
allAttribs.push_back (EGL_NONE);
EGLint numConfigs{};
return eglChooseConfig (display, allAttribs.data(), &config, 1, &numConfigs);
}
//==============================================================================
bool initEGLDisplay (const OpenGLPixelFormat& pixelFormat, bool multisample)
{
[[maybe_unused]] const auto didBind = eglBindAPI (api == OpenGLAPI::openGL ? EGL_OPENGL_API : EGL_OPENGL_ES_API);
// Failed to bind the requested OpenGL API
jassert (didBind);
// already initialised?
if (display != EGL_NO_DISPLAY)
return true;
if ((display = eglGetDisplay (EGL_DEFAULT_DISPLAY)) == EGL_NO_DISPLAY)
{
jassertfalse;
return false;
}
if (! eglInitialize (display, nullptr, nullptr))
{
jassertfalse;
return false;
}
const EGLint optionalFlags[]
{
EGL_SAMPLE_BUFFERS, multisample ? 1 : 0,
EGL_SAMPLES, pixelFormat.multisamplingLevel
};
for (const auto& num : { 4, 0 })
{
if (tryChooseConfig (Span { optionalFlags, (size_t) num }))
return true;
}
eglTerminate (display);
jassertfalse;
return false;
}
Rectangle<int> computePhysicalBounds() const
{
if (auto* peer = component.getPeer())
{
const auto peerBounds = peer->getAreaCoveredBy (component).toFloat();
const auto desktopScale = peer->getComponent().getDesktopScaleFactor();
const auto globalRect = Rectangle { peer->localToGlobal (peerBounds.getTopLeft()),
peer->localToGlobal (peerBounds.getBottomRight()) }
/ desktopScale;
const auto& displays = Desktop::getInstance().getDisplays();
const Rectangle physical { displays.logicalToPhysical (globalRect.getTopLeft()),
displays.logicalToPhysical (globalRect.getBottomRight()) };
const auto physicalPeerPos = displays.logicalToPhysical (peer->localToGlobal (Point<float>{}) / desktopScale);
return (physical - physicalPeerPos).toNearestInt();
}
return component.getBounds();
}
struct NativeWindowReleaser
{
void operator() (ANativeWindow* ptr) const { if (ptr != nullptr) ANativeWindow_release (ptr); }
};
static std::unique_ptr<ANativeWindow, NativeWindowReleaser> getNativeWindowFromSurfaceHolder (jobject holder)
{
auto* env = getEnv();
if (holder == nullptr)
return nullptr;
const LocalRef<jobject> jSurface (env->CallObjectMethod (holder, AndroidSurfaceHolder.getSurface));
if (jSurface == nullptr)
return nullptr;
constexpr auto numAttempts = 2;
for (auto i = 0; i < numAttempts; Thread::sleep (200), ++i)
if (auto* ptr = ANativeWindow_fromSurface (env, jSurface.get()))
return std::unique_ptr<ANativeWindow, NativeWindowReleaser> { ptr };
return nullptr;
}
//==============================================================================
CriticalSection mutex;
bool hasInitialised = false;
GlobalRef surfaceView;
Rectangle<int> physicalBounds;
mutable std::mutex nativeHandleMutex;
OpenGLContext* juceContext = nullptr;
EGLHelpers::PtrEGLSurface surface{};
EGLHelpers::PtrEGLContext context{};
GlobalRef surfaceHolderCallback;
API api{};
Version version{};
Profile profile{};
inline static EGLDisplay display = EGL_NO_DISPLAY;
inline static EGLConfig config;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return eglGetCurrentContext() != EGL_NO_CONTEXT;
}
} // namespace juce
@@ -0,0 +1,333 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
@interface JuceGLView : UIView
{
}
+ (Class) layerClass;
@end
@implementation JuceGLView
+ (Class) layerClass
{
return [CAEAGLLayer class];
}
@end
extern "C" GLvoid glResolveMultisampleFramebufferAPPLE();
namespace juce
{
bool OpenGLHelpers::isOpenGLES()
{
return true;
}
class OpenGLContext::NativeContext
{
public:
NativeContext (Component& c,
const OpenGLPixelFormat& pixFormat,
void* contextToShare,
bool multisampling,
[[maybe_unused]] API apiIn,
Version versionIn,
[[maybe_unused]] Profile profileIn)
: component (c),
useDepthBuffer (pixFormat.depthBufferBits > 0),
useMSAA (multisampling)
{
// Only OpenGL ES is supported on iOS
jassert (apiIn == OpenGLAPI::openGLES);
// Only core profile is supported on iOS
jassert (profileIn == OpenGLProfile::core);
JUCE_AUTORELEASEPOOL
{
if (auto* peer = component.getPeer())
{
auto bounds = peer->getAreaCoveredBy (component);
view = [[JuceGLView alloc] initWithFrame: convertToCGRect (bounds)];
view.opaque = YES;
view.hidden = NO;
view.backgroundColor = [UIColor blackColor];
view.userInteractionEnabled = NO;
glLayer = (CAEAGLLayer*) [view layer];
glLayer.opaque = true;
updateWindowPosition();
[((UIView*) peer->getNativeHandle()) addSubview: view];
const auto shouldUseES3 = versionIn >= Version { 3, 0 }
&& [[UIDevice currentDevice].systemVersion floatValue] >= 7.0;
[[maybe_unused]] const auto gotContext = (shouldUseES3 && createContext (kEAGLRenderingAPIOpenGLES3, contextToShare))
|| createContext (kEAGLRenderingAPIOpenGLES2, contextToShare);
jassert (gotContext);
if (context != nil)
{
// I'd prefer to put this stuff in the initialiseOnRenderThread() call, but doing
// so causes mysterious timing-related failures.
[EAGLContext setCurrentContext: context.get()];
gl::loadFunctions();
openGLVersion = getOpenGLVersion();
createGLBuffers();
deactivateCurrentContext();
}
else
{
jassertfalse;
}
}
else
{
jassertfalse;
}
}
}
~NativeContext()
{
context.reset();
[view removeFromSuperview];
[view release];
}
InitResult initialiseOnRenderThread (OpenGLContext&) { return InitResult::success; }
void shutdownOnRenderThread()
{
JUCE_CHECK_OPENGL_ERROR
freeGLBuffers();
deactivateCurrentContext();
}
bool createdOk() const noexcept { return getRawContext() != nullptr; }
void* getRawContext() const noexcept { return context.get(); }
GLuint getFrameBufferID() const noexcept { return useMSAA ? msaaBufferHandle : frameBufferHandle; }
bool makeActive() const noexcept
{
if (! [EAGLContext setCurrentContext: context.get()])
return false;
glBindFramebuffer (GL_FRAMEBUFFER, useMSAA ? msaaBufferHandle
: frameBufferHandle);
return true;
}
bool isActive() const noexcept
{
return [EAGLContext currentContext] == context.get();
}
static void deactivateCurrentContext()
{
[EAGLContext setCurrentContext: nil];
}
void swapBuffers()
{
if (useMSAA)
{
glBindFramebuffer (GL_DRAW_FRAMEBUFFER, frameBufferHandle);
glBindFramebuffer (GL_READ_FRAMEBUFFER, msaaBufferHandle);
if (openGLVersion >= Version { 3, 0 })
{
const auto w = lastBounds.getWidth();
const auto h = lastBounds.getHeight();
glBlitFramebuffer (0, 0, w, h,
0, 0, w, h,
GL_COLOR_BUFFER_BIT,
GL_NEAREST);
}
else
{
::glResolveMultisampleFramebufferAPPLE();
}
}
glBindRenderbuffer (GL_RENDERBUFFER, colorBufferHandle);
[context.get() presentRenderbuffer: GL_RENDERBUFFER];
if (! std::exchange (needToRebuildBuffers, false))
return;
freeGLBuffers();
createGLBuffers();
makeActive();
}
void updateWindowPosition()
{
auto* peer = component.getTopLevelComponent()->getPeer();
if (peer == nullptr)
return;
const auto bounds = peer->getAreaCoveredBy (component);
view.frame = convertToCGRect (bounds);
glLayer.contentsScale = (CGFloat) (Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale
/ component.getDesktopScaleFactor());
const auto msaaBounds = bounds * glLayer.contentsScale;
needToRebuildBuffers |= std::exchange (lastBounds, msaaBounds) != msaaBounds;
}
bool setSwapInterval (int numFramesPerSwap) noexcept
{
swapFrames = numFramesPerSwap;
return false;
}
int getSwapInterval() const noexcept { return swapFrames; }
struct Locker
{
explicit Locker (NativeContext& ctx) : lock (ctx.mutex) {}
const ScopedLock lock;
};
private:
CriticalSection mutex;
Component& component;
JuceGLView* view = nil;
CAEAGLLayer* glLayer = nil;
NSUniquePtr<EAGLContext> context;
Version openGLVersion{};
const bool useDepthBuffer, useMSAA;
GLuint frameBufferHandle = 0, colorBufferHandle = 0, depthBufferHandle = 0,
msaaColorHandle = 0, msaaBufferHandle = 0;
Rectangle<int> lastBounds;
int swapFrames = 0;
bool needToRebuildBuffers = false;
bool createContext (EAGLRenderingAPI type, void* contextToShare)
{
jassert (context == nil);
context.reset ([EAGLContext alloc]);
if (contextToShare != nullptr)
[context.get() initWithAPI: type sharegroup: [(EAGLContext*) contextToShare sharegroup]];
else
[context.get() initWithAPI: type];
return context != nil;
}
//==============================================================================
void createGLBuffers()
{
glGenFramebuffers (1, &frameBufferHandle);
glGenRenderbuffers (1, &colorBufferHandle);
glBindFramebuffer (GL_FRAMEBUFFER, frameBufferHandle);
glBindRenderbuffer (GL_RENDERBUFFER, colorBufferHandle);
glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorBufferHandle);
[[maybe_unused]] bool ok = [context.get() renderbufferStorage: GL_RENDERBUFFER fromDrawable: glLayer];
jassert (ok);
GLint width, height;
glGetRenderbufferParameteriv (GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
glGetRenderbufferParameteriv (GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
if (useMSAA)
{
glGenFramebuffers (1, &msaaBufferHandle);
glGenRenderbuffers (1, &msaaColorHandle);
glBindFramebuffer (GL_FRAMEBUFFER, msaaBufferHandle);
glBindRenderbuffer (GL_RENDERBUFFER, msaaColorHandle);
glRenderbufferStorageMultisample (GL_RENDERBUFFER, 4, GL_RGBA8, width, height);
glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, msaaColorHandle);
}
if (useDepthBuffer)
{
glGenRenderbuffers (1, &depthBufferHandle);
glBindRenderbuffer (GL_RENDERBUFFER, depthBufferHandle);
if (useMSAA)
glRenderbufferStorageMultisample (GL_RENDERBUFFER, 4, GL_DEPTH_COMPONENT16, width, height);
else
glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferHandle);
}
jassert (glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
JUCE_CHECK_OPENGL_ERROR
}
void freeGLBuffers()
{
JUCE_CHECK_OPENGL_ERROR
[context.get() renderbufferStorage: GL_RENDERBUFFER fromDrawable: nil];
deleteFrameBuffer (frameBufferHandle);
deleteFrameBuffer (msaaBufferHandle);
deleteRenderBuffer (colorBufferHandle);
deleteRenderBuffer (depthBufferHandle);
deleteRenderBuffer (msaaColorHandle);
JUCE_CHECK_OPENGL_ERROR
}
static void deleteFrameBuffer (GLuint& i) { if (i != 0) glDeleteFramebuffers (1, &i); i = 0; }
static void deleteRenderBuffer (GLuint& i) { if (i != 0) glDeleteRenderbuffers (1, &i); i = 0; }
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return [EAGLContext currentContext] != nil;
}
} // namespace juce
@@ -0,0 +1,447 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
struct XFreeDeleter
{
void operator() (void* ptr) const
{
if (ptr != nullptr)
X11Symbols::getInstance()->xFree (ptr);
}
};
template <typename Data>
std::unique_ptr<Data, XFreeDeleter> makeXFreePtr (Data* raw) { return std::unique_ptr<Data, XFreeDeleter> (raw); }
//==============================================================================
// Defined in juce_Windowing_linux.cpp
void juce_LinuxAddRepaintListener (ComponentPeer*, Component* dummy);
void juce_LinuxRemoveRepaintListener (ComponentPeer*, Component* dummy);
bool OpenGLHelpers::isOpenGLES()
{
return eglQueryAPI() == EGL_OPENGL_ES_API;
}
class PeerListener : private ComponentMovementWatcher
{
public:
PeerListener (Component& comp, Window embeddedWindow)
: ComponentMovementWatcher (&comp),
window (embeddedWindow),
association (comp.getPeer(), window) {}
private:
using ComponentMovementWatcher::componentMovedOrResized,
ComponentMovementWatcher::componentVisibilityChanged;
void componentMovedOrResized (bool, bool) override {}
void componentVisibilityChanged() override {}
void componentPeerChanged() override
{
// This should not be rewritten as a ternary expression or similar.
// The old association must be destroyed before the new one is created.
association = {};
if (auto* comp = getComponent())
association = ScopedWindowAssociation (comp->getPeer(), window);
}
Window window{};
ScopedWindowAssociation association;
};
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wzero-as-null-pointer-constant")
static constexpr EGLContext nullContext = EGL_NO_CONTEXT;
static constexpr EGLDisplay nullDisplay = EGL_NO_DISPLAY;
static constexpr EGLSurface nullSurface = EGL_NO_SURFACE;
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
//==============================================================================
class OpenGLContext::NativeContext
{
private:
struct DummyComponent : public Component
{
explicit DummyComponent (NativeContext& nativeParentContext)
: native (nativeParentContext)
{
}
void handleCommandMessage (int commandId) override
{
if (commandId == 0)
native.triggerRepaint();
}
NativeContext& native;
};
using PtrEGLContext = EGLHelpers::PtrEGLContext;
using PtrEGLSurface = EGLHelpers::PtrEGLSurface;
public:
NativeContext (Component& comp,
const OpenGLPixelFormat& cPixelFormat,
void* shareContext,
bool useMultisamplingIn,
API apiIn,
Version versionIn,
Profile profileIn)
: component (comp),
contextToShareWith (shareContext),
dummy (*this),
api (apiIn),
version (versionIn),
profile (profileIn)
{
const auto* ext = eglQueryString (nullDisplay, EGL_EXTENSIONS);
if (ext == nullptr)
{
// JUCE needs the EGL implementation to support at least the X11
// platform extension.
jassertfalse;
return;
}
const auto platformDisplayToken = std::invoke ([&]() -> std::optional<EGLenum>
{
if (strstr (ext, "EGL_KHR_platform_x11") != nullptr)
return EGL_PLATFORM_X11_KHR;
if (strstr (ext, "EGL_EXT_platform_x11") != nullptr)
return EGL_PLATFORM_X11_EXT;
return {};
});
if (! platformDisplayToken.has_value())
{
// At the moment JUCE can only create a GL context under X11.
// If this EGL implementation doesn't support X11, things would break
// when we tried to pass an X11 display/window/etc. into EGL functions.
jassertfalse;
return;
}
display = XWindowSystem::getInstance()->getDisplay();
XWindowSystemUtilities::ScopedXLock xLock;
X11Symbols::getInstance()->xSync (display, False);
eglDisplay = eglGetPlatformDisplay (*platformDisplayToken, display, nullptr);
if (eglDisplay == nullDisplay)
return;
{
EGLint major = 0, minor = 0;
if (! eglInitialize (eglDisplay, &major, &minor))
return;
}
const EGLint optionalAttribs[]
{
EGL_SAMPLE_BUFFERS, useMultisamplingIn ? 1 : 0,
EGL_SAMPLES, cPixelFormat.multisamplingLevel
};
if (! tryChooseConfig (cPixelFormat, optionalAttribs) && ! tryChooseConfig (cPixelFormat, {}))
return;
EGLint nativeVisualId = 0;
eglGetConfigAttrib (eglDisplay, eglConfig, EGL_NATIVE_VISUAL_ID, &nativeVisualId);
auto* peer = component.getPeer();
jassert (peer != nullptr);
auto windowH = (Window) peer->getNativeHandle();
auto [visual, depth] = std::invoke ([this, nativeVisualId]() -> std::tuple<Visual*, int>
{
XVisualInfo visualInfo{};
visualInfo.visualid = (VisualID) nativeVisualId;
int numVisuals = 0;
auto xVisualInfo = makeXFreePtr (X11Symbols::getInstance()->xGetVisualInfo (display,
VisualIDMask,
&visualInfo,
&numVisuals));
if (xVisualInfo != nullptr && numVisuals > 0)
return { xVisualInfo->visual,
xVisualInfo->depth };
return { DefaultVisual (display, DefaultScreen (display)),
DefaultDepth (display, DefaultScreen (display)) };
});
auto colourMap = X11Symbols::getInstance()->xCreateColormap (display, windowH, visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap = colourMap;
swa.border_pixel = 0;
swa.event_mask = embeddedWindowEventMask;
const auto physicalBounds = getPhysicalBounds();
embeddedWindow = X11Symbols::getInstance()->xCreateWindow (display,
windowH,
physicalBounds.getX(),
physicalBounds.getY(),
(unsigned int) jmax (1, physicalBounds.getWidth()),
(unsigned int) jmax (1, physicalBounds.getHeight()),
0,
depth,
InputOutput,
visual,
CWBorderPixel | CWColormap | CWEventMask,
&swa);
peerListener.emplace (component, embeddedWindow);
X11Symbols::getInstance()->xMapWindow (display, embeddedWindow);
X11Symbols::getInstance()->xFreeColormap (display, colourMap);
X11Symbols::getInstance()->xSync (display, False);
juce_LinuxAddRepaintListener (peer, &dummy);
constructorDidComplete = true;
}
~NativeContext()
{
eglSurface.reset();
renderContext.reset();
if (eglDisplay != nullDisplay)
eglTerminate (eglDisplay);
if (auto* peer = component.getPeer())
{
juce_LinuxRemoveRepaintListener (peer, &dummy);
if (embeddedWindow != 0)
{
XWindowSystemUtilities::ScopedXLock xLock;
X11Symbols::getInstance()->xUnmapWindow (display, embeddedWindow);
X11Symbols::getInstance()->xDestroyWindow (display, embeddedWindow);
X11Symbols::getInstance()->xSync (display, False);
XEvent event;
while (X11Symbols::getInstance()->xCheckWindowEvent (display,
embeddedWindow,
embeddedWindowEventMask,
&event) == True)
{
}
}
}
}
InitResult initialiseOnRenderThread (OpenGLContext& c)
{
renderContext = EGLHelpers::initEGLContext (api, version, profile, eglDisplay, eglConfig, contextToShareWith);
if (renderContext == nullptr)
return InitResult::fatal;
eglSurface = PtrEGLSurface { eglCreatePlatformWindowSurface (eglDisplay,
eglConfig,
&embeddedWindow,
nullptr),
eglDisplay };
if (eglSurface == nullptr)
return InitResult::fatal;
c.makeActive();
context = &c;
return InitResult::success;
}
void shutdownOnRenderThread()
{
context = nullptr;
deactivateCurrentContext();
renderContext.reset();
eglSurface.reset();
}
bool makeActive() const noexcept
{
return renderContext != nullptr
&& eglSurface != nullptr
&& eglMakeCurrent (eglDisplay, eglSurface.get(), eglSurface.get(), renderContext.get());
}
bool isActive() const noexcept
{
return eglGetCurrentContext() == renderContext.get() && renderContext != nullptr;
}
static void deactivateCurrentContext()
{
const auto currentDisplay = eglGetCurrentDisplay();
if (currentDisplay != nullDisplay)
eglMakeCurrent (currentDisplay, nullSurface, nullSurface, nullContext);
}
void swapBuffers()
{
eglSwapBuffers (eglDisplay, eglSurface.get());
}
Rectangle<int> getPhysicalBounds() const
{
if (auto* peer = component.getPeer())
{
const auto peerBounds = peer->getAreaCoveredBy (component);
const auto physicalBounds = peerBounds.toDouble() * peer->getPlatformScaleFactor();
return physicalBounds.toNearestInt();
}
return component.getBounds();
}
void updateWindowPosition()
{
const auto physicalBounds = getPhysicalBounds();
XWindowSystemUtilities::ScopedXLock xLock;
X11Symbols::getInstance()->xMoveResizeWindow (display,
embeddedWindow,
physicalBounds.getX(),
physicalBounds.getY(),
(unsigned int) jmax (1, physicalBounds.getWidth()),
(unsigned int) jmax (1, physicalBounds.getHeight()));
}
bool setSwapInterval (int numFramesPerSwap)
{
if (numFramesPerSwap == swapFrames)
return true;
swapFrames = numFramesPerSwap;
eglSwapInterval (eglDisplay, numFramesPerSwap);
return true;
}
int getSwapInterval() const { return swapFrames; }
bool createdOk() const noexcept { return constructorDidComplete; }
void* getRawContext() const noexcept { return renderContext.get(); }
GLuint getFrameBufferID() const noexcept { return 0; }
void triggerRepaint()
{
if (context != nullptr)
context->triggerRepaint();
}
struct Locker
{
explicit Locker (NativeContext& ctx) : lock (ctx.mutex) {}
const ScopedLock lock;
};
private:
bool tryChooseConfig (const OpenGLPixelFormat& format, Span<const EGLint> optionalAttribs)
{
std::vector<EGLint> allAttribs
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, api == OpenGLAPI::openGLES ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT,
EGL_RED_SIZE, format.redBits,
EGL_GREEN_SIZE, format.greenBits,
EGL_BLUE_SIZE, format.blueBits,
EGL_ALPHA_SIZE, format.alphaBits,
EGL_DEPTH_SIZE, format.depthBufferBits,
EGL_STENCIL_SIZE, format.stencilBufferBits,
};
allAttribs.insert (allAttribs.end(), optionalAttribs.begin(), optionalAttribs.end());
allAttribs.push_back (EGL_NONE);
EGLint numConfigs = 0;
return eglChooseConfig (eglDisplay, allAttribs.data(), &eglConfig, 1, &numConfigs) && numConfigs > 0;
}
static constexpr int embeddedWindowEventMask = ExposureMask | StructureNotifyMask;
CriticalSection mutex;
Component& component;
EGLDisplay eglDisplay = nullDisplay;
PtrEGLContext renderContext;
PtrEGLSurface eglSurface;
Window embeddedWindow = {};
std::optional<PeerListener> peerListener;
int swapFrames = 0;
EGLConfig eglConfig = nullptr;
void* contextToShareWith;
OpenGLContext* context = nullptr;
DummyComponent dummy;
::Display* display = nullptr;
API api{};
Version version{};
Profile profile{};
bool constructorDidComplete = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return eglGetCurrentContext() != nullContext;
}
} // namespace juce
@@ -0,0 +1,376 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
JUCE_BEGIN_IGNORE_DEPRECATION_WARNINGS
bool OpenGLHelpers::isOpenGLES()
{
return false;
}
class OpenGLContext::NativeContext
{
public:
NativeContext (Component& component,
const OpenGLPixelFormat& pixFormat,
void* contextToShare,
bool shouldUseMultisampling,
[[maybe_unused]] API apiIn,
Version versionIn,
Profile profileIn)
: owner (component)
{
// OpenGL ES is not supported on macOS
jassert (apiIn == API::openGL);
const auto attribs = createAttribs (versionIn,
profileIn,
pixFormat,
shouldUseMultisampling);
NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs.data()];
static MouseForwardingNSOpenGLViewClass cls;
view = [cls.createInstance() initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
pixelFormat: format];
if ([view respondsToSelector: @selector (setWantsBestResolutionOpenGLSurface:)])
[view setWantsBestResolutionOpenGLSurface: YES];
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
[[NSNotificationCenter defaultCenter] addObserver: view
selector: @selector (_surfaceNeedsUpdate:)
name: NSViewGlobalFrameDidChangeNotification
object: view];
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
shareContext: (NSOpenGLContext*) contextToShare] autorelease];
[view setOpenGLContext: renderContext];
[format release];
viewAttachment = NSViewComponent::attachViewToComponent (component, view);
}
~NativeContext()
{
[[NSNotificationCenter defaultCenter] removeObserver: view];
[renderContext clearDrawable];
[renderContext setView: nil];
[view setOpenGLContext: nil];
[view release];
}
static std::vector<NSOpenGLPixelFormatAttribute> createAttribs (Version version,
Profile profile,
const OpenGLPixelFormat& pixFormat,
bool shouldUseMultisampling)
{
const auto versionEnum = std::invoke ([&]
{
if (version == Version { 3, 2 })
{
// Only the core profile is supported for OpenGL 3.2
jassert (profile == Profile::core);
return NSOpenGLProfileVersion3_2Core;
}
if (version != Version{} && profile != Profile::compatibility)
{
return NSOpenGLProfileVersion4_1Core;
}
// Using the default legacy compatibility context, even though the core profile
// was requested.
jassert (profile == Profile::compatibility);
return NSOpenGLProfileVersionLegacy;
});
std::vector<NSOpenGLPixelFormatAttribute> attribs
{
NSOpenGLPFAOpenGLProfile, versionEnum,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAClosestPolicy,
NSOpenGLPFANoRecovery,
NSOpenGLPFAColorSize, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits),
NSOpenGLPFAAlphaSize, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.alphaBits),
NSOpenGLPFADepthSize, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.depthBufferBits),
NSOpenGLPFAStencilSize, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.stencilBufferBits),
NSOpenGLPFAAccumSize, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
+ pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits)
};
if (shouldUseMultisampling)
{
attribs.insert (attribs.cend(),
{
NSOpenGLPFAMultisample,
NSOpenGLPFASampleBuffers, static_cast<NSOpenGLPixelFormatAttribute> (1),
NSOpenGLPFASamples, static_cast<NSOpenGLPixelFormatAttribute> (pixFormat.multisamplingLevel)
});
}
attribs.push_back (0);
return attribs;
}
InitResult initialiseOnRenderThread (OpenGLContext&) { return InitResult::success; }
void shutdownOnRenderThread() { deactivateCurrentContext(); }
bool createdOk() const noexcept { return getRawContext() != nullptr; }
NSOpenGLView* getNSView() const noexcept { return view; }
NSOpenGLContext* getRawContext() const noexcept { return renderContext; }
GLuint getFrameBufferID() const noexcept { return 0; }
bool makeActive() const noexcept
{
jassert (renderContext != nil);
if ([renderContext view] != view)
[renderContext setView: view];
if (NSOpenGLContext* context = [view openGLContext])
{
[context makeCurrentContext];
return true;
}
return false;
}
bool isActive() const noexcept
{
return [NSOpenGLContext currentContext] == renderContext;
}
static void deactivateCurrentContext()
{
[NSOpenGLContext clearCurrentContext];
}
struct Locker
{
Locker (NativeContext& nc) : cglContext ((CGLContextObj) [nc.renderContext CGLContextObj])
{
CGLLockContext (cglContext);
}
~Locker()
{
CGLUnlockContext (cglContext);
}
private:
CGLContextObj cglContext;
};
void swapBuffers()
{
auto now = Time::getMillisecondCounterHiRes();
[renderContext flushBuffer];
if (const auto minSwapTime = minSwapTimeMs.get(); minSwapTime > 0)
{
// When our window is entirely occluded by other windows, flushBuffer
// fails to wait for the swap interval, so the render loop spins at full
// speed, burning CPU. This hack detects when things are going too fast
// and sleeps if necessary.
auto swapTime = Time::getMillisecondCounterHiRes() - now;
auto frameTime = (int) std::min ((uint64_t) std::numeric_limits<int>::max(),
(uint64_t) now - (uint64_t) lastSwapTime);
if (swapTime < 0.5 && frameTime < minSwapTime - 3)
{
if (underrunCounter > 3)
{
Thread::sleep (2 * (minSwapTime - frameTime));
now = Time::getMillisecondCounterHiRes();
}
else
{
++underrunCounter;
}
}
else
{
if (underrunCounter > 0)
--underrunCounter;
}
}
lastSwapTime = now;
}
void updateWindowPosition()
{
if (auto* peer = owner.getTopLevelComponent()->getPeer())
{
const auto newArea = peer->getAreaCoveredBy (owner);
if (convertToRectInt ([view frame]) != newArea)
[view setFrame: makeCGRect (newArea)];
}
}
bool setSwapInterval (int numFramesPerSwapIn)
{
// The macOS OpenGL programming guide says that numFramesPerSwap
// can only be 0 or 1.
jassert (isPositiveAndBelow (numFramesPerSwapIn, 2));
[renderContext setValues: (const GLint*) &numFramesPerSwapIn
forParameter: getSwapIntervalParameter()];
minSwapTimeMs.setFramesPerSwap (numFramesPerSwapIn);
return true;
}
int getSwapInterval() const
{
GLint numFrames = 0;
[renderContext getValues: &numFrames
forParameter: getSwapIntervalParameter()];
return numFrames;
}
void setNominalVideoRefreshPeriodS (double periodS)
{
jassert (periodS > 0.0);
minSwapTimeMs.setVideoRefreshPeriodS (periodS);
}
static NSOpenGLContextParameter getSwapIntervalParameter()
{
if (@available (macOS 10.12, *))
return NSOpenGLContextParameterSwapInterval;
return NSOpenGLCPSwapInterval;
}
class MinSwapTimeMs
{
public:
int get() const
{
return minSwapTimeMs;
}
void setFramesPerSwap (int n)
{
const std::scoped_lock lock { mutex };
numFramesPerSwap = n;
updateMinSwapTime();
}
void setVideoRefreshPeriodS (double n)
{
const std::scoped_lock lock { mutex };
videoRefreshPeriodS = n;
updateMinSwapTime();
}
private:
void updateMinSwapTime()
{
minSwapTimeMs = static_cast<int> (numFramesPerSwap * 1000 * videoRefreshPeriodS);
}
std::mutex mutex;
std::atomic<int> minSwapTimeMs { 0 };
int numFramesPerSwap = 0;
double videoRefreshPeriodS = 1.0 / 60.0;
};
Component& owner;
NSOpenGLContext* renderContext = nil;
NSOpenGLView* view = nil;
ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
double lastSwapTime = 0;
int underrunCounter = 0;
MinSwapTimeMs minSwapTimeMs;
//==============================================================================
struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
{
MouseForwardingNSOpenGLViewClass() : ObjCClass ("JUCEGLView_")
{
addMethod (@selector (rightMouseDown:), [] (id self, SEL, NSEvent* ev)
{
[[(NSOpenGLView*) self superview] rightMouseDown: ev];
});
addMethod (@selector (rightMouseUp:), [] (id self, SEL, NSEvent* ev)
{
[[(NSOpenGLView*) self superview] rightMouseUp: ev];
});
addMethod (@selector (acceptsFirstMouse:), [] (id, SEL, NSEvent*) -> BOOL
{
return YES;
});
addMethod (@selector (accessibilityHitTest:), [] (id self, SEL, NSPoint p) -> id
{
return [[(NSOpenGLView*) self superview] accessibilityHitTest: p];
});
addMethod (@selector (hitTest:), [] (id, SEL, NSPoint) -> NSView*
{
return nil;
});
registerClass();
}
};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return CGLGetCurrentContext() != CGLContextObj();
}
JUCE_END_IGNORE_DEPRECATION_WARNINGS
} // namespace juce
@@ -0,0 +1,462 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
extern ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component&, Component* parent);
bool OpenGLHelpers::isOpenGLES()
{
return false;
}
//==============================================================================
class OpenGLContext::NativeContext : private AsyncUpdater
{
public:
NativeContext (Component& component,
const OpenGLPixelFormat& pixelFormat,
void* contextToShareWithIn,
bool /*useMultisampling*/,
[[maybe_unused]] API apiIn,
Version versionIn,
Profile profileIn)
: safeComponent (&component),
sharedContext (contextToShareWithIn)
{
// OpenGL ES is not supported on Windows
jassert (apiIn == API::openGL);
placeholderComponent.reset (new PlaceholderComponent (*this));
createNativeWindow (component);
PIXELFORMATDESCRIPTOR pfd;
initialisePixelFormatDescriptor (pfd, pixelFormat);
auto pixFormat = ChoosePixelFormat (dc.get(), &pfd);
if (pixFormat != 0)
SetPixelFormat (dc.get(), pixFormat, &pfd);
initialiseWGLExtensions (dc.get());
renderContext.reset (createRenderContext (versionIn, profileIn, dc.get()));
if (renderContext != nullptr)
{
makeActive();
auto wglFormat = wglChoosePixelFormatExtension (pixelFormat);
deactivateCurrentContext();
if (wglFormat != pixFormat && wglFormat != 0)
{
// can't change the pixel format of a window, so need to delete the
// old one and create a new one.
dc.reset();
nativeWindow = nullptr;
createNativeWindow (component);
if (SetPixelFormat (dc.get(), wglFormat, &pfd))
{
renderContext.reset();
renderContext.reset (createRenderContext (versionIn, profileIn, dc.get()));
}
}
component.getTopLevelComponent()->repaint();
component.repaint();
}
}
~NativeContext() override
{
cancelPendingUpdate();
renderContext.reset();
dc.reset();
}
InitResult initialiseOnRenderThread (OpenGLContext& c)
{
threadAwarenessSetter.emplace (nativeWindow->getNativeHandle());
context = &c;
if (sharedContext != nullptr)
{
if (! wglShareLists ((HGLRC) sharedContext, renderContext.get()))
{
TCHAR messageBuffer[256] = {};
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
GetLastError(),
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
messageBuffer,
(DWORD) numElementsInArray (messageBuffer) - 1,
nullptr);
DBG (messageBuffer);
jassertfalse;
}
}
return InitResult::success;
}
void shutdownOnRenderThread()
{
deactivateCurrentContext();
context = nullptr;
threadAwarenessSetter.reset();
}
static void deactivateCurrentContext() { wglMakeCurrent (nullptr, nullptr); }
bool makeActive() const noexcept { return isActive() || wglMakeCurrent (dc.get(), renderContext.get()) != FALSE; }
bool isActive() const noexcept { return wglGetCurrentContext() == renderContext.get(); }
void swapBuffers() noexcept
{
SwapBuffers (dc.get());
if (! std::exchange (haveBuffersBeenSwapped, true))
triggerAsyncUpdate();
}
bool setSwapInterval (int numFramesPerSwap)
{
jassert (isActive()); // this can only be called when the context is active
return wglSwapIntervalEXT != nullptr && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
}
int getSwapInterval() const
{
jassert (isActive()); // this can only be called when the context is active
return wglGetSwapIntervalEXT != nullptr ? wglGetSwapIntervalEXT() : 0;
}
void updateWindowPosition()
{
if (nativeWindow != nullptr)
{
const auto bounds = getPhysicalBounds();
const ScopedThreadDPIAwarenessSetter scope { nativeWindow->getNativeHandle() };
SetWindowPos ((HWND) nativeWindow->getNativeHandle(),
nullptr,
bounds.getX(),
bounds.getY(),
bounds.getWidth(),
bounds.getHeight(),
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
}
bool createdOk() const noexcept { return getRawContext() != nullptr; }
void* getRawContext() const noexcept { return renderContext.get(); }
unsigned int getFrameBufferID() const noexcept { return 0; }
void triggerRepaint()
{
if (context != nullptr)
context->triggerRepaint();
}
struct Locker
{
explicit Locker (NativeContext& ctx) : lock (ctx.mutex) {}
const ScopedLock lock;
};
HWND getNativeHandle()
{
if (nativeWindow != nullptr)
return (HWND) nativeWindow->getNativeHandle();
return nullptr;
}
private:
//==============================================================================
Rectangle<int> getPhysicalBounds() const
{
if (safeComponent == nullptr)
return {};
auto& component = *safeComponent;
if (auto* peer = component.getPeer())
{
const auto peerBounds = peer->getAreaCoveredBy (component);
const auto physicalBounds = peerBounds.toDouble() * peer->getPlatformScaleFactor();
return physicalBounds.toNearestInt();
}
return component.getBounds();
}
void handleAsyncUpdate() override
{
nativeWindow->setVisible (true);
}
static void initialiseWGLExtensions (HDC dcIn)
{
static bool initialised = false;
if (initialised)
return;
initialised = true;
const auto dummyContext = wglCreateContext (dcIn);
wglMakeCurrent (dcIn, dummyContext);
#define JUCE_INIT_WGL_FUNCTION(name) name = (type_ ## name) OpenGLHelpers::getExtensionFunction (#name);
JUCE_INIT_WGL_FUNCTION (wglChoosePixelFormatARB)
JUCE_INIT_WGL_FUNCTION (wglSwapIntervalEXT)
JUCE_INIT_WGL_FUNCTION (wglGetSwapIntervalEXT)
JUCE_INIT_WGL_FUNCTION (wglCreateContextAttribsARB)
#undef JUCE_INIT_WGL_FUNCTION
wglMakeCurrent (nullptr, nullptr);
wglDeleteContext (dummyContext);
}
static void initialisePixelFormatDescriptor (PIXELFORMATDESCRIPTOR& pfd, const OpenGLPixelFormat& pixelFormat)
{
zerostruct (pfd);
pfd.nSize = sizeof (pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
pfd.cRedBits = (BYTE) pixelFormat.redBits;
pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
+ pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
}
static HGLRC createRenderContext (Version version, Profile profile, HDC dcIn)
{
if (version != Version{} && wglCreateContextAttribsARB != nullptr)
{
#if JUCE_DEBUG
constexpr auto contextFlags = WGL_CONTEXT_DEBUG_BIT_ARB;
constexpr auto noErrorChecking = GL_FALSE;
#else
constexpr auto contextFlags = 0;
constexpr auto noErrorChecking = GL_TRUE;
#endif
const int attribs[]
{
WGL_CONTEXT_MAJOR_VERSION_ARB, version.major,
WGL_CONTEXT_MINOR_VERSION_ARB, version.minor,
WGL_CONTEXT_PROFILE_MASK_ARB, (int) (profile == OpenGLProfile::core ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB),
WGL_CONTEXT_FLAGS_ARB, contextFlags,
WGL_CONTEXT_OPENGL_NO_ERROR_ARB, noErrorChecking,
0
};
const auto c = wglCreateContextAttribsARB (dcIn, nullptr, attribs);
if (c != nullptr)
return c;
}
return wglCreateContext (dcIn);
}
//==============================================================================
struct PlaceholderComponent : public Component
{
explicit PlaceholderComponent (NativeContext& c)
: context (c)
{
setOpaque (true);
}
// The windowing code will call this when a paint callback happens
void handleCommandMessage (int) override { context.triggerRepaint(); }
NativeContext& context;
};
//==============================================================================
void nativeScaleFactorChanged (double newScaleFactor)
{
if (approximatelyEqual (newScaleFactor, nativeScaleFactor)
|| safeComponent == nullptr)
return;
nativeScaleFactor = newScaleFactor;
updateWindowPosition();
}
void createNativeWindow (Component& component)
{
safeComponent = &component;
auto* topComp = component.getTopLevelComponent();
{
auto* parentHWND = topComp->getWindowHandle();
ScopedThreadDPIAwarenessSetter setter { parentHWND };
nativeWindow.reset (createNonRepaintingEmbeddedWindowsPeer (*placeholderComponent, topComp));
}
if (auto* peer = topComp->getPeer())
{
nativeScaleFactor = peer->getPlatformScaleFactor();
updateWindowPosition();
}
dc = { GetDC ((HWND) nativeWindow->getNativeHandle()),
DeviceContextDeleter { (HWND) nativeWindow->getNativeHandle() } };
}
int wglChoosePixelFormatExtension (const OpenGLPixelFormat& pixelFormat) const
{
int format = 0;
if (wglChoosePixelFormatARB != nullptr)
{
int atts[64];
auto* ptr = atts;
const int common[]
{
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB, pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits,
WGL_RED_BITS_ARB, pixelFormat.redBits,
WGL_GREEN_BITS_ARB, pixelFormat.greenBits,
WGL_BLUE_BITS_ARB, pixelFormat.blueBits,
WGL_ALPHA_BITS_ARB, pixelFormat.alphaBits,
WGL_DEPTH_BITS_ARB, pixelFormat.depthBufferBits,
WGL_STENCIL_BITS_ARB, pixelFormat.stencilBufferBits,
WGL_ACCUM_RED_BITS_ARB, pixelFormat.accumulationBufferRedBits,
WGL_ACCUM_GREEN_BITS_ARB, pixelFormat.accumulationBufferGreenBits,
WGL_ACCUM_BLUE_BITS_ARB, pixelFormat.accumulationBufferBlueBits,
WGL_ACCUM_ALPHA_BITS_ARB, pixelFormat.accumulationBufferAlphaBits,
};
ptr = std::copy (std::begin (common), std::end (common), ptr);
if (pixelFormat.multisamplingLevel > 0
&& OpenGLHelpers::isExtensionSupported ("GL_ARB_multisample"))
{
const int multisample[]
{
WGL_SAMPLE_BUFFERS_ARB, 1,
WGL_SAMPLES_ARB, pixelFormat.multisamplingLevel,
};
ptr = std::copy (std::begin (multisample), std::end (multisample), ptr);
}
*ptr++ = 0;
jassert (std::distance (atts, ptr) <= numElementsInArray (atts));
UINT formatsCount = 0;
wglChoosePixelFormatARB (dc.get(), atts, nullptr, 1, &format, &formatsCount);
}
return format;
}
//==============================================================================
#define JUCE_DECLARE_WGL_EXTENSION_FUNCTION(name, returnType, params) \
typedef returnType (__stdcall *type_ ## name) params; static type_ ## name name;
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglChoosePixelFormatARB, BOOL, (HDC, const int*, const FLOAT*, UINT, int*, UINT*))
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglSwapIntervalEXT, BOOL, (int))
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglGetSwapIntervalEXT, int, ())
JUCE_DECLARE_WGL_EXTENSION_FUNCTION (wglCreateContextAttribsARB, HGLRC, (HDC, HGLRC, const int*))
#undef JUCE_DECLARE_WGL_EXTENSION_FUNCTION
//==============================================================================
struct RenderContextDeleter
{
void operator() (HGLRC ptr) const { wglDeleteContext (ptr); }
};
struct DeviceContextDeleter
{
void operator() (HDC ptr) const { ReleaseDC (hwnd, ptr); }
HWND hwnd;
};
CriticalSection mutex;
std::unique_ptr<PlaceholderComponent> placeholderComponent;
std::unique_ptr<ComponentPeer> nativeWindow;
std::optional<ScopedThreadDPIAwarenessSetter> threadAwarenessSetter;
Component::SafePointer<Component> safeComponent;
std::unique_ptr<std::remove_pointer_t<HGLRC>, RenderContextDeleter> renderContext;
std::unique_ptr<std::remove_pointer_t<HDC>, DeviceContextDeleter> dc;
OpenGLContext* context = nullptr;
void* sharedContext = nullptr;
double nativeScaleFactor = 1.0;
bool haveBuffersBeenSwapped = false;
NativeScaleFactorNotifier scaleFactorNotifier { safeComponent.getComponent(),
[this] (auto x) { nativeScaleFactorChanged (x); } };
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return wglGetCurrentContext() != nullptr;
}
} // namespace juce