git subrepo clone --branch=sono6good https://github.com/essej/JUCE.git deps/juce

subrepo:
  subdir:   "deps/juce"
  merged:   "b13f9084e"
upstream:
  origin:   "https://github.com/essej/JUCE.git"
  branch:   "sono6good"
  commit:   "b13f9084e"
git-subrepo:
  version:  "0.4.3"
  origin:   "https://github.com/ingydotnet/git-subrepo.git"
  commit:   "2f68596"
This commit is contained in:
essej
2022-04-18 17:51:22 -04:00
parent 63e175fee6
commit 25bd5d8adb
3210 changed files with 1045392 additions and 0 deletions

View File

@ -0,0 +1,81 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
package com.rmsl.juce;
import android.content.Context;
import android.graphics.Canvas;
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
protected void onAttachedToWindow ()
{
super.onAttachedToWindow ();
if (host != 0)
onAttchedWindowNative (host);
}
@Override
protected void onDetachedFromWindow ()
{
if (host != 0)
onDetachedFromWindowNative (host);
super.onDetachedFromWindow ();
}
@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);
}

View File

@ -0,0 +1,140 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR 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
{
//==============================================================================
#ifndef DOXYGEN
[[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();
#endif
#if JUCE_WINDOWS && ! defined (DOXYGEN)
typedef char GLchar;
typedef pointer_sized_int GLsizeiptr;
typedef pointer_sized_int GLintptr;
#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

View File

@ -0,0 +1,385 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR 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[] =
{31,139,8,8,95,114,161,94,0,3,74,117,99,101,79,112,101,110,71,76,86,105,101,119,83,117,114,102,97,99,101,46,100,101,120,0,109,
84,75,107,19,81,20,62,119,230,38,169,105,76,99,218,138,86,144,32,5,55,173,83,53,98,33,173,86,90,170,196,193,34,173,81,106,93,
12,147,169,153,210,204,196,100,154,22,65,40,110,234,170,43,23,34,46,93,22,87,62,138,27,65,168,235,174,213,133,11,23,254,129,
162,136,130,223,125,196,164,208,129,239,126,231,125,206,188,78,217,91,75,142,156,191,64,151,223,190,187,182,183,251,251,212,240,
247,216,223,197,205,174,170,255,233,209,230,135,123,183,222,252,225,68,53,34,90,43,229,179,164,175,5,216,142,145,178,199,129,
93,205,63,0,6,140,224,72,129,71,153,210,159,225,152,50,137,182,193,239,13,162,143,192,14,240,25,216,3,50,240,13,1,54,48,3,204,
2,119,128,5,192,1,124,224,1,240,16,120,2,108,2,207,129,87,192,14,240,5,248,9,196,184,234,7,145,32,82,76,207,149,208,136,233,
249,187,180,252,20,189,15,105,249,5,228,164,150,95,66,238,214,242,86,135,253,181,161,234,102,100,15,83,214,50,225,233,209,61,179,
154,251,100,127,46,253,226,76,73,86,113,92,199,113,76,218,171,245,62,173,247,75,54,232,168,182,183,238,69,92,134,230,188,42,139,
251,226,210,214,205,213,124,181,28,209,57,153,57,15,105,126,144,40,141,92,38,99,251,185,154,191,229,77,203,124,67,246,56,129,
227,8,56,204,49,154,163,217,9,68,161,236,89,52,28,197,51,19,122,109,162,155,248,205,180,124,6,76,206,51,216,202,201,136,26,7,
230,140,116,17,103,157,57,67,58,231,224,232,36,162,67,124,6,92,206,198,246,221,179,33,117,166,245,182,28,31,243,3,63,186,68,172,
72,189,197,21,215,155,169,121,193,85,187,228,123,171,103,150,156,166,67,199,109,39,40,215,67,191,108,185,97,16,121,65,100,77,
10,94,139,10,29,174,251,117,167,86,241,221,134,53,233,4,77,167,81,160,129,255,174,38,42,89,179,43,245,69,199,245,68,213,2,157,
180,221,176,106,213,171,141,101,107,9,13,173,253,93,11,196,74,100,148,138,100,150,138,54,4,27,130,93,164,184,235,4,174,183,44,
25,29,40,225,170,41,40,85,246,27,53,39,114,43,83,117,103,149,120,37,108,68,148,12,156,200,111,122,115,21,191,65,217,48,184,18,
69,142,91,241,202,115,225,109,63,40,135,171,212,47,109,194,164,12,55,100,56,245,133,193,148,167,66,167,235,97,85,7,15,28,100,
213,25,41,248,208,86,107,60,18,13,79,27,61,217,68,250,226,204,48,13,83,34,125,157,166,89,58,145,30,223,152,167,60,41,30,7,111,
220,29,195,11,224,248,248,248,250,58,223,54,249,99,131,12,128,1,49,246,213,100,252,23,176,197,13,254,141,31,214,239,145,117,
112,107,111,24,29,187,195,236,216,31,173,239,94,236,144,24,181,247,72,156,218,187,132,229,148,79,236,19,150,105,255,203,70,78,
213,23,59,198,212,49,226,255,160,156,202,205,235,159,87,200,98,135,253,3,40,26,5,36,252,4,0,0,0,0};
//==============================================================================
struct AndroidGLCallbacks
{
static void attachedToWindow (JNIEnv*, jobject, jlong);
static void detachedFromWindow (JNIEnv*, jobject, jlong);
static void dispatchDraw (JNIEnv*, jobject, jlong, jobject);
};
//==============================================================================
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
METHOD (constructor, "<init>", "(Landroid/content/Context;J)V") \
METHOD (getParent, "getParent", "()Landroid/view/ViewParent;") \
METHOD (getHolder, "getHolder", "()Landroid/view/SurfaceHolder;") \
METHOD (layout, "layout", "(IIII)V" ) \
CALLBACK (AndroidGLCallbacks::attachedToWindow, "onAttchedWindowNative", "(J)V") \
CALLBACK (AndroidGLCallbacks::detachedFromWindow, "onDetachedFromWindowNative", "(J)V") \
CALLBACK (AndroidGLCallbacks::dispatchDraw, "onDrawNative", "(JLandroid/graphics/Canvas;)V")
DECLARE_JNI_CLASS_WITH_BYTECODE (JuceOpenGLViewSurface, "com/rmsl/juce/JuceOpenGLView", 16, javaJuceOpenGLView, sizeof(javaJuceOpenGLView))
#undef JNI_CLASS_MEMBERS
//==============================================================================
class OpenGLContext::NativeContext : private SurfaceHolderCallback
{
public:
NativeContext (Component& comp,
const OpenGLPixelFormat& pixelFormat,
void* /*contextToShareWith*/,
bool useMultisamplingIn,
OpenGLVersion)
: component (comp),
surface (EGL_NO_SURFACE), context (EGL_NO_CONTEXT)
{
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;
// 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
auto bounds = component.getTopLevelComponent()->getLocalArea (&component, component.getLocalBounds());
bounds *= component.getDesktopScaleFactor();
updateWindowPosition (bounds);
hasInitialised = true;
}
~NativeContext() override
{
auto env = getEnv();
if (jobject viewParent = env->CallObjectMethod (surfaceView.get(), JuceOpenGLViewSurface.getParent))
env->CallVoidMethod (viewParent, AndroidViewGroup.removeView, surfaceView.get());
}
//==============================================================================
bool initialiseOnRenderThread (OpenGLContext& aContext)
{
jassert (hasInitialised);
// has the context already attached?
jassert (surface == EGL_NO_SURFACE && context == EGL_NO_CONTEXT);
auto env = getEnv();
ANativeWindow* window = nullptr;
LocalRef<jobject> holder (env->CallObjectMethod (surfaceView.get(), JuceOpenGLViewSurface.getHolder));
if (holder != nullptr)
{
LocalRef<jobject> jSurface (env->CallObjectMethod (holder.get(), AndroidSurfaceHolder.getSurface));
if (jSurface != nullptr)
{
window = ANativeWindow_fromSurface(env, jSurface.get());
// if we didn't succeed the first time, wait 25ms and try again
if (window == nullptr)
{
Thread::sleep (200);
window = ANativeWindow_fromSurface (env, jSurface.get());
}
}
}
if (window == nullptr)
{
// failed to get a pointer to the native window after second try so bail out
jassertfalse;
return false;
}
// create the surface
surface = eglCreateWindowSurface (display, config, window, nullptr);
jassert (surface != EGL_NO_SURFACE);
ANativeWindow_release (window);
// create the OpenGL context
EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
context = eglCreateContext (display, config, EGL_NO_CONTEXT, contextAttribs);
jassert (context != EGL_NO_CONTEXT);
juceContext = &aContext;
return true;
}
void shutdownOnRenderThread()
{
jassert (hasInitialised);
// is there a context available to detach?
jassert (surface != EGL_NO_SURFACE && context != EGL_NO_CONTEXT);
eglDestroyContext (display, context);
context = EGL_NO_CONTEXT;
eglDestroySurface (display, surface);
surface = EGL_NO_SURFACE;
}
//==============================================================================
bool makeActive() const noexcept
{
if (! hasInitialised)
return false;
if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT)
return false;
if (! eglMakeCurrent (display, surface, surface, context))
return false;
return true;
}
bool isActive() const noexcept { return eglGetCurrentContext() == context; }
static void deactivateCurrentContext()
{
eglMakeCurrent (display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
//==============================================================================
void swapBuffers() const noexcept { eglSwapBuffers (display, surface); }
bool setSwapInterval (const 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 (Rectangle<int> bounds)
{
if (lastBounds != bounds)
{
auto env = getEnv();
lastBounds = bounds;
auto r = bounds * Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
env->CallVoidMethod (surfaceView.get(), JuceOpenGLViewSurface.layout,
(jint) r.getX(), (jint) r.getY(), (jint) r.getRight(), (jint) r.getBottom());
}
}
//==============================================================================
// Android Surface Callbacks:
void surfaceChanged (LocalRef<jobject> holder, int format, int width, int height) override
{
ignoreUnused (holder, format, width, height);
}
void surfaceCreated (LocalRef<jobject> holder) override;
void surfaceDestroyed (LocalRef<jobject> holder) override;
//==============================================================================
struct Locker { Locker (NativeContext&) {} };
Component& component;
private:
//==============================================================================
friend struct AndroidGLCallbacks;
void attachedToWindow()
{
auto* env = getEnv();
LocalRef<jobject> holder (env->CallObjectMethod (surfaceView.get(), JuceOpenGLViewSurface.getHolder));
if (surfaceHolderCallback == nullptr)
surfaceHolderCallback = GlobalRef (CreateJavaInterface (this, "android/view/SurfaceHolder$Callback"));
env->CallVoidMethod (holder, AndroidSurfaceHolder.addCallback, surfaceHolderCallback.get());
}
void detachedFromWindow()
{
if (surfaceHolderCallback != nullptr)
{
auto* env = getEnv();
LocalRef<jobject> holder (env->CallObjectMethod (surfaceView.get(), JuceOpenGLViewSurface.getHolder));
env->CallVoidMethod (holder.get(), AndroidSurfaceHolder.removeCallback, surfaceHolderCallback.get());
surfaceHolderCallback.clear();
}
}
void dispatchDraw (jobject /*canvas*/)
{
if (juceContext != nullptr)
juceContext->triggerRepaint();
}
bool tryChooseConfig (const std::vector<EGLint>& optionalAttribs)
{
std::vector<EGLint> allAttribs
{
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_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)
{
// 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;
}
if (tryChooseConfig ({ EGL_SAMPLE_BUFFERS, multisample ? 1 : 0, EGL_SAMPLES, pixelFormat.multisamplingLevel }))
return true;
if (tryChooseConfig ({}))
return true;
eglTerminate (display);
jassertfalse;
return false;
}
//==============================================================================
bool hasInitialised = false;
GlobalRef surfaceView;
Rectangle<int> lastBounds;
OpenGLContext* juceContext = nullptr;
EGLSurface surface;
EGLContext context;
GlobalRef surfaceHolderCallback;
static EGLDisplay display;
static EGLConfig config;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
void AndroidGLCallbacks::attachedToWindow (JNIEnv*, jobject /*this*/, jlong host)
{
if (auto* nativeContext = reinterpret_cast<OpenGLContext::NativeContext*> (host))
nativeContext->attachedToWindow();
}
void AndroidGLCallbacks::detachedFromWindow (JNIEnv*, jobject /*this*/, jlong host)
{
if (auto* nativeContext = reinterpret_cast<OpenGLContext::NativeContext*> (host))
nativeContext->detachedFromWindow();
}
void AndroidGLCallbacks::dispatchDraw (JNIEnv*, jobject /*this*/, jlong host, jobject canvas)
{
if (auto* nativeContext = reinterpret_cast<OpenGLContext::NativeContext*> (host))
nativeContext->dispatchDraw (canvas);
}
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return eglGetCurrentContext() != EGL_NO_CONTEXT;
}
} // namespace juce

View File

@ -0,0 +1,315 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
@interface JuceGLView : UIView
{
}
+ (Class) layerClass;
@end
@implementation JuceGLView
+ (Class) layerClass
{
return [CAEAGLLayer class];
}
@end
extern "C" GLvoid glResolveMultisampleFramebufferAPPLE();
namespace juce
{
class OpenGLContext::NativeContext
{
public:
NativeContext (Component& c,
const OpenGLPixelFormat& pixFormat,
void* contextToShare,
bool multisampling,
OpenGLVersion version)
: component (c), openGLversion (version),
useDepthBuffer (pixFormat.depthBufferBits > 0),
useMSAA (multisampling)
{
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 (bounds);
[((UIView*) peer->getNativeHandle()) addSubview: view];
if (version == openGL3_2 && [[UIDevice currentDevice].systemVersion floatValue] >= 7.0)
{
if (! createContext (kEAGLRenderingAPIOpenGLES3, contextToShare))
{
releaseContext();
createContext (kEAGLRenderingAPIOpenGLES2, contextToShare);
}
}
else
{
createContext (kEAGLRenderingAPIOpenGLES2, contextToShare);
}
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];
gl::loadFunctions();
createGLBuffers();
deactivateCurrentContext();
}
else
{
jassertfalse;
}
}
else
{
jassertfalse;
}
}
}
~NativeContext()
{
releaseContext();
[view removeFromSuperview];
[view release];
}
bool initialiseOnRenderThread (OpenGLContext&) { return true; }
void shutdownOnRenderThread()
{
JUCE_CHECK_OPENGL_ERROR
freeGLBuffers();
deactivateCurrentContext();
}
bool createdOk() const noexcept { return getRawContext() != nullptr; }
void* getRawContext() const noexcept { return context; }
GLuint getFrameBufferID() const noexcept { return useMSAA ? msaaBufferHandle : frameBufferHandle; }
bool makeActive() const noexcept
{
if (! [EAGLContext setCurrentContext: context])
return false;
glBindFramebuffer (GL_FRAMEBUFFER, useMSAA ? msaaBufferHandle
: frameBufferHandle);
return true;
}
bool isActive() const noexcept
{
return [EAGLContext currentContext] == context;
}
static void deactivateCurrentContext()
{
[EAGLContext setCurrentContext: nil];
}
void swapBuffers()
{
if (useMSAA)
{
glBindFramebuffer (GL_DRAW_FRAMEBUFFER, frameBufferHandle);
glBindFramebuffer (GL_READ_FRAMEBUFFER, msaaBufferHandle);
if (openGLversion >= openGL3_2)
{
auto w = roundToInt (lastBounds.getWidth() * glLayer.contentsScale);
auto h = roundToInt (lastBounds.getHeight() * glLayer.contentsScale);
glBlitFramebuffer (0, 0, w, h,
0, 0, w, h,
GL_COLOR_BUFFER_BIT,
GL_NEAREST);
}
else
{
::glResolveMultisampleFramebufferAPPLE();
}
}
glBindRenderbuffer (GL_RENDERBUFFER, colorBufferHandle);
[context presentRenderbuffer: GL_RENDERBUFFER];
if (needToRebuildBuffers)
{
needToRebuildBuffers = false;
freeGLBuffers();
createGLBuffers();
makeActive();
}
}
void updateWindowPosition (Rectangle<int> bounds)
{
view.frame = convertToCGRect (bounds);
glLayer.contentsScale = (CGFloat) (Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale
/ component.getDesktopScaleFactor());
if (lastBounds != bounds)
{
lastBounds = bounds;
needToRebuildBuffers = true;
}
}
bool setSwapInterval (int numFramesPerSwap) noexcept
{
swapFrames = numFramesPerSwap;
return false;
}
int getSwapInterval() const noexcept { return swapFrames; }
struct Locker { Locker (NativeContext&) {} };
private:
Component& component;
JuceGLView* view = nil;
CAEAGLLayer* glLayer = nil;
EAGLContext* context = nil;
const OpenGLVersion 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 = [EAGLContext alloc];
context = contextToShare != nullptr
? [context initWithAPI: type sharegroup: [(EAGLContext*) contextToShare sharegroup]]
: [context initWithAPI: type];
return context != nil;
}
void releaseContext()
{
[context release];
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);
bool ok = [context renderbufferStorage: GL_RENDERBUFFER fromDrawable: glLayer];
jassert (ok); ignoreUnused (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 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

View File

@ -0,0 +1,286 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
extern XContext windowHandleXContext;
//==============================================================================
// Defined juce_linux_Windowing.cpp
void juce_LinuxAddRepaintListener (ComponentPeer*, Component* dummy);
void juce_LinuxRemoveRepaintListener (ComponentPeer*, Component* dummy);
//==============================================================================
class OpenGLContext::NativeContext
{
private:
struct DummyComponent : public Component
{
DummyComponent (OpenGLContext::NativeContext& nativeParentContext)
: native (nativeParentContext)
{
}
void handleCommandMessage (int commandId) override
{
if (commandId == 0)
native.triggerRepaint();
}
OpenGLContext::NativeContext& native;
};
public:
NativeContext (Component& comp,
const OpenGLPixelFormat& cPixelFormat,
void* shareContext,
bool useMultisamplingIn,
OpenGLVersion)
: component (comp), contextToShareWith (shareContext), dummy (*this)
{
display = XWindowSystem::getInstance()->getDisplay();
XWindowSystemUtilities::ScopedXLock xLock;
X11Symbols::getInstance()->xSync (display, False);
const std::vector<GLint> optionalAttribs
{
GLX_SAMPLE_BUFFERS, useMultisamplingIn ? 1 : 0,
GLX_SAMPLES, cPixelFormat.multisamplingLevel
};
if (! tryChooseVisual (cPixelFormat, optionalAttribs) && ! tryChooseVisual (cPixelFormat, {}))
return;
auto* peer = component.getPeer();
jassert (peer != nullptr);
auto windowH = (Window) peer->getNativeHandle();
auto colourMap = X11Symbols::getInstance()->xCreateColormap (display, windowH, bestVisual->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap = colourMap;
swa.border_pixel = 0;
swa.event_mask = embeddedWindowEventMask;
auto glBounds = component.getTopLevelComponent()
->getLocalArea (&component, component.getLocalBounds());
glBounds = Desktop::getInstance().getDisplays().logicalToPhysical (glBounds);
embeddedWindow = X11Symbols::getInstance()->xCreateWindow (display, windowH,
glBounds.getX(), glBounds.getY(),
(unsigned int) jmax (1, glBounds.getWidth()),
(unsigned int) jmax (1, glBounds.getHeight()),
0, bestVisual->depth,
InputOutput,
bestVisual->visual,
CWBorderPixel | CWColormap | CWEventMask,
&swa);
X11Symbols::getInstance()->xSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
X11Symbols::getInstance()->xMapWindow (display, embeddedWindow);
X11Symbols::getInstance()->xFreeColormap (display, colourMap);
X11Symbols::getInstance()->xSync (display, False);
juce_LinuxAddRepaintListener (peer, &dummy);
}
~NativeContext()
{
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)
{
}
}
}
if (bestVisual != nullptr)
X11Symbols::getInstance()->xFree (bestVisual);
}
bool initialiseOnRenderThread (OpenGLContext& c)
{
XWindowSystemUtilities::ScopedXLock xLock;
renderContext = glXCreateContext (display, bestVisual, (GLXContext) contextToShareWith, GL_TRUE);
c.makeActive();
context = &c;
return true;
}
void shutdownOnRenderThread()
{
XWindowSystemUtilities::ScopedXLock xLock;
context = nullptr;
deactivateCurrentContext();
glXDestroyContext (display, renderContext);
renderContext = nullptr;
}
bool makeActive() const noexcept
{
XWindowSystemUtilities::ScopedXLock xLock;
return renderContext != nullptr
&& glXMakeCurrent (display, embeddedWindow, renderContext);
}
bool isActive() const noexcept
{
XWindowSystemUtilities::ScopedXLock xLock;
return glXGetCurrentContext() == renderContext && renderContext != nullptr;
}
static void deactivateCurrentContext()
{
if (auto* display = XWindowSystem::getInstance()->getDisplay())
{
XWindowSystemUtilities::ScopedXLock xLock;
glXMakeCurrent (display, None, nullptr);
}
}
void swapBuffers()
{
XWindowSystemUtilities::ScopedXLock xLock;
glXSwapBuffers (display, embeddedWindow);
}
void updateWindowPosition (Rectangle<int> newBounds)
{
bounds = newBounds;
auto physicalBounds = Desktop::getInstance().getDisplays().logicalToPhysical (bounds);
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;
if (auto GLXSwapIntervalSGI
= (PFNGLXSWAPINTERVALSGIPROC) OpenGLHelpers::getExtensionFunction ("glXSwapIntervalSGI"))
{
XWindowSystemUtilities::ScopedXLock xLock;
swapFrames = numFramesPerSwap;
GLXSwapIntervalSGI (numFramesPerSwap);
return true;
}
return false;
}
int getSwapInterval() const { return swapFrames; }
bool createdOk() const noexcept { return true; }
void* getRawContext() const noexcept { return renderContext; }
GLuint getFrameBufferID() const noexcept { return 0; }
void triggerRepaint()
{
if (context != nullptr)
context->triggerRepaint();
}
struct Locker { Locker (NativeContext&) {} };
private:
bool tryChooseVisual (const OpenGLPixelFormat& format, const std::vector<GLint>& optionalAttribs)
{
std::vector<GLint> allAttribs
{
GLX_RGBA,
GLX_DOUBLEBUFFER,
GLX_RED_SIZE, format.redBits,
GLX_GREEN_SIZE, format.greenBits,
GLX_BLUE_SIZE, format.blueBits,
GLX_ALPHA_SIZE, format.alphaBits,
GLX_DEPTH_SIZE, format.depthBufferBits,
GLX_STENCIL_SIZE, format.stencilBufferBits,
GLX_ACCUM_RED_SIZE, format.accumulationBufferRedBits,
GLX_ACCUM_GREEN_SIZE, format.accumulationBufferGreenBits,
GLX_ACCUM_BLUE_SIZE, format.accumulationBufferBlueBits,
GLX_ACCUM_ALPHA_SIZE, format.accumulationBufferAlphaBits
};
allAttribs.insert (allAttribs.end(), optionalAttribs.begin(), optionalAttribs.end());
allAttribs.push_back (None);
bestVisual = glXChooseVisual (display, X11Symbols::getInstance()->xDefaultScreen (display), allAttribs.data());
return bestVisual != nullptr;
}
static constexpr int embeddedWindowEventMask = ExposureMask | StructureNotifyMask;
Component& component;
GLXContext renderContext = {};
Window embeddedWindow = {};
int swapFrames = 1;
Rectangle<int> bounds;
XVisualInfo* bestVisual = nullptr;
void* contextToShareWith;
OpenGLContext* context = nullptr;
DummyComponent dummy;
::Display* display = nullptr;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
XWindowSystemUtilities::ScopedXLock xLock;
return glXGetCurrentContext() != nullptr;
}
} // namespace juce

View File

@ -0,0 +1,282 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
class OpenGLContext::NativeContext
{
public:
NativeContext (Component& component,
const OpenGLPixelFormat& pixFormat,
void* contextToShare,
bool shouldUseMultisampling,
OpenGLVersion version)
{
NSOpenGLPixelFormatAttribute attribs[64] = { 0 };
createAttribs (attribs, version, pixFormat, shouldUseMultisampling);
NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
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 void createAttribs (NSOpenGLPixelFormatAttribute* attribs, OpenGLVersion version,
const OpenGLPixelFormat& pixFormat, bool shouldUseMultisampling)
{
ignoreUnused (version);
int numAttribs = 0;
attribs[numAttribs++] = NSOpenGLPFAOpenGLProfile;
attribs[numAttribs++] = version >= openGL3_2 ? NSOpenGLProfileVersion3_2Core
: NSOpenGLProfileVersionLegacy;
attribs[numAttribs++] = NSOpenGLPFADoubleBuffer;
attribs[numAttribs++] = NSOpenGLPFAClosestPolicy;
attribs[numAttribs++] = NSOpenGLPFANoRecovery;
attribs[numAttribs++] = NSOpenGLPFAColorSize;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.redBits + pixFormat.greenBits + pixFormat.blueBits);
attribs[numAttribs++] = NSOpenGLPFAAlphaSize;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.alphaBits;
attribs[numAttribs++] = NSOpenGLPFADepthSize;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.depthBufferBits;
attribs[numAttribs++] = NSOpenGLPFAStencilSize;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.stencilBufferBits;
attribs[numAttribs++] = NSOpenGLPFAAccumSize;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) (pixFormat.accumulationBufferRedBits + pixFormat.accumulationBufferGreenBits
+ pixFormat.accumulationBufferBlueBits + pixFormat.accumulationBufferAlphaBits);
if (shouldUseMultisampling)
{
attribs[numAttribs++] = NSOpenGLPFAMultisample;
attribs[numAttribs++] = NSOpenGLPFASampleBuffers;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) 1;
attribs[numAttribs++] = NSOpenGLPFASamples;
attribs[numAttribs++] = (NSOpenGLPixelFormatAttribute) pixFormat.multisamplingLevel;
}
}
bool initialiseOnRenderThread (OpenGLContext&) { return true; }
void shutdownOnRenderThread() { deactivateCurrentContext(); }
bool createdOk() const noexcept { return getRawContext() != nullptr; }
void* getRawContext() const noexcept { return static_cast<void*> (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 (minSwapTimeMs > 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) (now - lastSwapTime);
if (swapTime < 0.5 && frameTime < minSwapTimeMs - 3)
{
if (underrunCounter > 3)
{
Thread::sleep (2 * (minSwapTimeMs - frameTime));
now = Time::getMillisecondCounterHiRes();
}
else
{
++underrunCounter;
}
}
else
{
if (underrunCounter > 0)
--underrunCounter;
}
}
lastSwapTime = now;
}
void updateWindowPosition (Rectangle<int>) {}
bool setSwapInterval (int numFramesPerSwapIn)
{
numFramesPerSwap = numFramesPerSwapIn;
// The macOS OpenGL programming guide says that numFramesPerSwap
// can only be 0 or 1.
jassert (isPositiveAndBelow (numFramesPerSwap, 2));
[renderContext setValues: (const GLint*) &numFramesPerSwap
#if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
forParameter: NSOpenGLContextParameterSwapInterval];
#else
forParameter: NSOpenGLCPSwapInterval];
#endif
updateMinSwapTime();
return true;
}
int getSwapInterval() const
{
GLint numFrames = 0;
[renderContext getValues: &numFrames
#if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
forParameter: NSOpenGLContextParameterSwapInterval];
#else
forParameter: NSOpenGLCPSwapInterval];
#endif
return numFrames;
}
void setNominalVideoRefreshPeriodS (double periodS)
{
jassert (periodS > 0.0);
videoRefreshPeriodS = periodS;
updateMinSwapTime();
}
void updateMinSwapTime()
{
minSwapTimeMs = static_cast<int> (numFramesPerSwap * 1000 * videoRefreshPeriodS);
}
NSOpenGLContext* renderContext = nil;
NSOpenGLView* view = nil;
ReferenceCountedObjectPtr<ReferenceCountedObject> viewAttachment;
double lastSwapTime = 0;
int minSwapTimeMs = 0, underrunCounter = 0, numFramesPerSwap = 0;
double videoRefreshPeriodS = 1.0 / 60.0;
//==============================================================================
struct MouseForwardingNSOpenGLViewClass : public ObjCClass<NSOpenGLView>
{
MouseForwardingNSOpenGLViewClass() : ObjCClass<NSOpenGLView> ("JUCEGLView_")
{
addMethod (@selector (rightMouseDown:), rightMouseDown, "v@:@");
addMethod (@selector (rightMouseUp:), rightMouseUp, "v@:@");
addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
registerClass();
}
private:
static void rightMouseDown (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseDown: ev]; }
static void rightMouseUp (id self, SEL, NSEvent* ev) { [[(NSOpenGLView*) self superview] rightMouseUp: ev]; }
static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return CGLGetCurrentContext() != CGLContextObj();
}
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
} // namespace juce

View File

@ -0,0 +1,329 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
extern ComponentPeer* createNonRepaintingEmbeddedWindowsPeer (Component&, void* parent);
//==============================================================================
class OpenGLContext::NativeContext : private ComponentPeer::ScaleFactorListener
{
public:
NativeContext (Component& component,
const OpenGLPixelFormat& pixelFormat,
void* contextToShareWithIn,
bool /*useMultisampling*/,
OpenGLVersion)
{
dummyComponent.reset (new DummyComponent (*this));
createNativeWindow (component);
PIXELFORMATDESCRIPTOR pfd;
initialisePixelFormatDescriptor (pfd, pixelFormat);
auto pixFormat = ChoosePixelFormat (dc, &pfd);
if (pixFormat != 0)
SetPixelFormat (dc, pixFormat, &pfd);
renderContext = wglCreateContext (dc);
if (renderContext != nullptr)
{
makeActive();
initialiseGLExtensions();
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..
releaseDC();
nativeWindow = nullptr;
createNativeWindow (component);
if (SetPixelFormat (dc, wglFormat, &pfd))
{
deleteRenderContext();
renderContext = wglCreateContext (dc);
}
}
if (contextToShareWithIn != nullptr)
wglShareLists ((HGLRC) contextToShareWithIn, renderContext);
component.getTopLevelComponent()->repaint();
component.repaint();
}
}
~NativeContext() override
{
deleteRenderContext();
releaseDC();
if (safeComponent != nullptr)
if (auto* peer = safeComponent->getTopLevelComponent()->getPeer())
peer->removeScaleFactorListener (this);
}
bool initialiseOnRenderThread (OpenGLContext& c)
{
threadAwarenessSetter = std::make_unique<ScopedThreadDPIAwarenessSetter> (nativeWindow->getNativeHandle());
context = &c;
return true;
}
void shutdownOnRenderThread()
{
deactivateCurrentContext();
context = nullptr;
threadAwarenessSetter = nullptr;
}
static void deactivateCurrentContext() { wglMakeCurrent (nullptr, nullptr); }
bool makeActive() const noexcept { return isActive() || wglMakeCurrent (dc, renderContext) != FALSE; }
bool isActive() const noexcept { return wglGetCurrentContext() == renderContext; }
void swapBuffers() const noexcept { SwapBuffers (dc); }
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 (Rectangle<int> bounds)
{
if (nativeWindow != nullptr)
{
if (! approximatelyEqual (nativeScaleFactor, 1.0))
bounds = (bounds.toDouble() * nativeScaleFactor).toNearestInt();
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; }
unsigned int getFrameBufferID() const noexcept { return 0; }
void triggerRepaint()
{
if (context != nullptr)
context->triggerRepaint();
}
struct Locker { Locker (NativeContext&) {} };
HWND getNativeHandle()
{
if (nativeWindow != nullptr)
return (HWND) nativeWindow->getNativeHandle();
return nullptr;
}
private:
struct DummyComponent : public Component
{
DummyComponent (NativeContext& c) : context (c) {}
// The windowing code will call this when a paint callback happens
void handleCommandMessage (int) override { context.triggerRepaint(); }
NativeContext& context;
};
std::unique_ptr<DummyComponent> dummyComponent;
std::unique_ptr<ComponentPeer> nativeWindow;
std::unique_ptr<ScopedThreadDPIAwarenessSetter> threadAwarenessSetter;
HGLRC renderContext;
HDC dc;
OpenGLContext* context = {};
Component::SafePointer<Component> safeComponent;
double nativeScaleFactor = 1.0;
#define JUCE_DECLARE_WGL_EXTENSION_FUNCTION(name, returnType, params) \
typedef returnType (__stdcall *type_ ## name) params; 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, ())
#undef JUCE_DECLARE_WGL_EXTENSION_FUNCTION
void nativeScaleFactorChanged (double newScaleFactor) override
{
if (approximatelyEqual (newScaleFactor, nativeScaleFactor)
|| safeComponent == nullptr)
return;
if (auto* peer = safeComponent->getTopLevelComponent()->getPeer())
{
nativeScaleFactor = newScaleFactor;
updateWindowPosition (peer->getAreaCoveredBy (*safeComponent));
}
}
void initialiseGLExtensions()
{
#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);
#undef JUCE_INIT_WGL_FUNCTION
}
void createNativeWindow (Component& component)
{
auto* topComp = component.getTopLevelComponent();
{
auto* parentHWND = topComp->getWindowHandle();
ScopedThreadDPIAwarenessSetter setter { parentHWND };
nativeWindow.reset (createNonRepaintingEmbeddedWindowsPeer (*dummyComponent, parentHWND));
}
if (auto* peer = topComp->getPeer())
{
safeComponent = Component::SafePointer<Component> (&component);
nativeScaleFactor = peer->getPlatformScaleFactor();
updateWindowPosition (peer->getAreaCoveredBy (component));
peer->addScaleFactorListener (this);
}
nativeWindow->setVisible (true);
dc = GetDC ((HWND) nativeWindow->getNativeHandle());
}
void deleteRenderContext()
{
if (renderContext != nullptr)
{
wglDeleteContext (renderContext);
renderContext = nullptr;
}
}
void releaseDC()
{
ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
}
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;
}
int wglChoosePixelFormatExtension (const OpenGLPixelFormat& pixelFormat) const
{
int format = 0;
if (wglChoosePixelFormatARB != nullptr)
{
int atts[64];
int n = 0;
atts[n++] = WGL_DRAW_TO_WINDOW_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_SUPPORT_OPENGL_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_DOUBLE_BUFFER_ARB; atts[n++] = GL_TRUE;
atts[n++] = WGL_PIXEL_TYPE_ARB; atts[n++] = WGL_TYPE_RGBA_ARB;
atts[n++] = WGL_ACCELERATION_ARB;
atts[n++] = WGL_FULL_ACCELERATION_ARB;
atts[n++] = WGL_COLOR_BITS_ARB; atts[n++] = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
atts[n++] = WGL_RED_BITS_ARB; atts[n++] = pixelFormat.redBits;
atts[n++] = WGL_GREEN_BITS_ARB; atts[n++] = pixelFormat.greenBits;
atts[n++] = WGL_BLUE_BITS_ARB; atts[n++] = pixelFormat.blueBits;
atts[n++] = WGL_ALPHA_BITS_ARB; atts[n++] = pixelFormat.alphaBits;
atts[n++] = WGL_DEPTH_BITS_ARB; atts[n++] = pixelFormat.depthBufferBits;
atts[n++] = WGL_STENCIL_BITS_ARB; atts[n++] = pixelFormat.stencilBufferBits;
atts[n++] = WGL_ACCUM_RED_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferRedBits;
atts[n++] = WGL_ACCUM_GREEN_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferGreenBits;
atts[n++] = WGL_ACCUM_BLUE_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferBlueBits;
atts[n++] = WGL_ACCUM_ALPHA_BITS_ARB; atts[n++] = pixelFormat.accumulationBufferAlphaBits;
if (pixelFormat.multisamplingLevel > 0
&& OpenGLHelpers::isExtensionSupported ("GL_ARB_multisample"))
{
atts[n++] = WGL_SAMPLE_BUFFERS_ARB;
atts[n++] = 1;
atts[n++] = WGL_SAMPLES_ARB;
atts[n++] = pixelFormat.multisamplingLevel;
}
atts[n++] = 0;
jassert (n <= numElementsInArray (atts));
UINT formatsCount = 0;
wglChoosePixelFormatARB (dc, atts, nullptr, 1, &format, &formatsCount);
}
return format;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeContext)
};
//==============================================================================
bool OpenGLHelpers::isContextActive()
{
return wglGetCurrentContext() != nullptr;
}
} // namespace juce