Cleanup: use snake case, replace "m_" prefix with "_" suffix

Follow our own C++ conventions for GHOST.
This commit is contained in:
Campbell Barton
2025-08-16 14:32:52 +10:00
parent c888bc55e7
commit ebfa7edeb1
109 changed files with 3571 additions and 3609 deletions

View File

@@ -93,16 +93,16 @@ extern uint64_t GHOST_GetMilliSeconds(GHOST_SystemHandle systemhandle);
* Note that, on most operating systems, messages need to be processed in order * Note that, on most operating systems, messages need to be processed in order
* for the timer callbacks to be invoked. * for the timer callbacks to be invoked.
* \param systemhandle: The handle to the system. * \param systemhandle: The handle to the system.
* \param delay: The time to wait for the first call to the timerProc (in milliseconds). * \param delay: The time to wait for the first call to the timer_proc (in milliseconds).
* \param interval: The interval between calls to the timerProc (in milliseconds). * \param interval: The interval between calls to the timer_proc (in milliseconds).
* \param timerProc: The callback invoked when the interval expires. * \param timer_proc: The callback invoked when the interval expires.
* \param userData: Placeholder for user data. * \param user_data: Placeholder for user data.
* \return A timer task (0 if timer task installation failed). * \return A timer task (0 if timer task installation failed).
*/ */
extern GHOST_TimerTaskHandle GHOST_InstallTimer(GHOST_SystemHandle systemhandle, extern GHOST_TimerTaskHandle GHOST_InstallTimer(GHOST_SystemHandle systemhandle,
uint64_t delay, uint64_t delay,
uint64_t interval, uint64_t interval,
GHOST_TimerProcPtr timerProc, GHOST_TimerProcPtr timer_proc,
GHOST_TUserDataPtr user_data); GHOST_TUserDataPtr user_data);
/** /**
@@ -162,7 +162,7 @@ extern GHOST_TSuccess GHOST_GetAllDisplayDimensions(GHOST_SystemHandle systemhan
* \param height: The height the window. * \param height: The height the window.
* \param state: The state of the window when opened. * \param state: The state of the window when opened.
* \param is_dialog: Stay on top of parent window, no icon in taskbar, can't be minimized. * \param is_dialog: Stay on top of parent window, no icon in taskbar, can't be minimized.
* \param gpuSettings: Misc GPU options. * \param gpu_settings: Misc GPU options.
* \return A handle to the new window ( == nullptr if creation failed). * \return A handle to the new window ( == nullptr if creation failed).
*/ */
extern GHOST_WindowHandle GHOST_CreateWindow(GHOST_SystemHandle systemhandle, extern GHOST_WindowHandle GHOST_CreateWindow(GHOST_SystemHandle systemhandle,
@@ -174,17 +174,17 @@ extern GHOST_WindowHandle GHOST_CreateWindow(GHOST_SystemHandle systemhandle,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
bool is_dialog, bool is_dialog,
GHOST_GPUSettings gpuSettings); GHOST_GPUSettings gpu_settings);
/** /**
* Create a new off-screen context. * Create a new off-screen context.
* Never explicitly delete the context, use #disposeContext() instead. * Never explicitly delete the context, use #disposeContext() instead.
* \param systemhandle: The handle to the system. * \param systemhandle: The handle to the system.
* \param gpuSettings: Misc GPU options. * \param gpu_settings: Misc GPU options.
* \return A handle to the new context ( == nullptr if creation failed). * \return A handle to the new context ( == nullptr if creation failed).
*/ */
extern GHOST_ContextHandle GHOST_CreateGPUContext(GHOST_SystemHandle systemhandle, extern GHOST_ContextHandle GHOST_CreateGPUContext(GHOST_SystemHandle systemhandle,
GHOST_GPUSettings gpuSettings); GHOST_GPUSettings gpu_settings);
/** /**
* Dispose of a context. * Dispose of a context.
@@ -433,7 +433,7 @@ extern GHOST_TSuccess GHOST_SetCursorGrab(GHOST_WindowHandle windowhandle,
* Returns the state of a modifier key (outside the message queue). * Returns the state of a modifier key (outside the message queue).
* \param systemhandle: The handle to the system. * \param systemhandle: The handle to the system.
* \param mask: The modifier key state to retrieve. * \param mask: The modifier key state to retrieve.
* \param isDown: Pointer to return modifier state in. * \param is_down: Pointer to return modifier state in.
* \return Indication of success. * \return Indication of success.
*/ */
extern GHOST_TSuccess GHOST_GetModifierKeyState(GHOST_SystemHandle systemhandle, extern GHOST_TSuccess GHOST_GetModifierKeyState(GHOST_SystemHandle systemhandle,
@@ -444,7 +444,7 @@ extern GHOST_TSuccess GHOST_GetModifierKeyState(GHOST_SystemHandle systemhandle,
* Returns the state of a mouse button (outside the message queue). * Returns the state of a mouse button (outside the message queue).
* \param systemhandle: The handle to the system. * \param systemhandle: The handle to the system.
* \param mask: The button state to retrieve. * \param mask: The button state to retrieve.
* \param isDown: Pointer to return button state in. * \param is_down: Pointer to return button state in.
* \return Indication of success. * \return Indication of success.
*/ */
extern GHOST_TSuccess GHOST_GetButtonState(GHOST_SystemHandle systemhandle, extern GHOST_TSuccess GHOST_GetButtonState(GHOST_SystemHandle systemhandle,
@@ -511,10 +511,10 @@ extern GHOST_TimerProcPtr GHOST_GetTimerProc(GHOST_TimerTaskHandle timertaskhand
/** /**
* Changes the timer callback. * Changes the timer callback.
* \param timertaskhandle: The handle to the timer-task. * \param timertaskhandle: The handle to the timer-task.
* \param timerProc: The timer callback. * \param timer_proc: The timer callback.
*/ */
extern void GHOST_SetTimerProc(GHOST_TimerTaskHandle timertaskhandle, extern void GHOST_SetTimerProc(GHOST_TimerTaskHandle timertaskhandle,
GHOST_TimerProcPtr timerProc); GHOST_TimerProcPtr timer_proc);
/** /**
* Returns the timer user data. * Returns the timer user data.
@@ -592,17 +592,17 @@ extern GHOST_TWindowDecorationStyleFlags GHOST_GetWindowDecorationStyleFlags(
/** /**
* Set the window decoration style flags. * Set the window decoration style flags.
* \param styleFlags: Window decoration style flags. * \param style_flags: Window decoration style flags.
*/ */
extern void GHOST_SetWindowDecorationStyleFlags(GHOST_WindowHandle windowhandle, extern void GHOST_SetWindowDecorationStyleFlags(GHOST_WindowHandle windowhandle,
GHOST_TWindowDecorationStyleFlags styleFlags); GHOST_TWindowDecorationStyleFlags style_flags);
/** /**
* Set the window decoration style settings. * Set the window decoration style settings.
* \param decorationSettings: Window decoration style settings. * \param decoration_settings: Window decoration style settings.
*/ */
extern void GHOST_SetWindowDecorationStyleSettings( extern void GHOST_SetWindowDecorationStyleSettings(
GHOST_WindowHandle windowhandle, GHOST_WindowDecorationStyleSettings decorationSettings); GHOST_WindowHandle windowhandle, GHOST_WindowDecorationStyleSettings decoration_settings);
/** /**
* Apply the window decoration style using the current flags and settings. * Apply the window decoration style using the current flags and settings.
@@ -699,11 +699,11 @@ extern GHOST_TSuccess GHOST_SetWindowState(GHOST_WindowHandle windowhandle,
/** /**
* Sets the window "modified" status, indicating unsaved changes. * Sets the window "modified" status, indicating unsaved changes.
* \param windowhandle: The handle to the window. * \param windowhandle: The handle to the window.
* \param isUnsavedChanges: Unsaved changes or not. * \param is_unsaved_changes: Unsaved changes or not.
* \return Indication of success. * \return Indication of success.
*/ */
extern GHOST_TSuccess GHOST_SetWindowModifiedState(GHOST_WindowHandle windowhandle, extern GHOST_TSuccess GHOST_SetWindowModifiedState(GHOST_WindowHandle windowhandle,
bool isUnsavedChanges); bool is_unsaved_changes);
/** /**
* Sets the order of the window (bottom, top). * Sets the order of the window (bottom, top).
@@ -847,7 +847,7 @@ extern GHOST_TSuccess GHOST_IsEmptyRectangle(GHOST_RectangleHandle rectanglehand
/** /**
* Returns whether this rectangle is valid. * Returns whether this rectangle is valid.
* Valid rectangles are rectangles that have m_l <= m_r and m_t <= m_b. * Valid rectangles are rectangles that have l_ <= r_ and t_ <= b_.
* Thus, empty rectangles are valid. * Thus, empty rectangles are valid.
* \param rectanglehandle: The handle to the rectangle. * \param rectanglehandle: The handle to the rectangle.
* \return Success value (true == valid rectangle) * \return Success value (true == valid rectangle)

View File

@@ -184,16 +184,16 @@ class GHOST_ISystem {
* \note On most operating systems, messages need to be processed in order * \note On most operating systems, messages need to be processed in order
* for the timer callbacks to be invoked. * for the timer callbacks to be invoked.
* *
* \param delay: The time to wait for the first call to the #timerProc (in milliseconds). * \param delay: The time to wait for the first call to the #timer_proc (in milliseconds).
* \param interval: The interval between calls to the #timerProc. * \param interval: The interval between calls to the #timer_proc.
* \param timerProc: The callback invoked when the interval expires. * \param timer_proc: The callback invoked when the interval expires.
* \param userData: Placeholder for user data. * \param user_data: Placeholder for user data.
* \return A timer task (0 if timer task installation failed). * \return A timer task (0 if timer task installation failed).
*/ */
virtual GHOST_ITimerTask *installTimer(uint64_t delay, virtual GHOST_ITimerTask *installTimer(uint64_t delay,
uint64_t interval, uint64_t interval,
GHOST_TimerProcPtr timerProc, GHOST_TimerProcPtr timer_proc,
GHOST_TUserDataPtr userData = nullptr) = 0; GHOST_TUserDataPtr user_data = nullptr) = 0;
/** /**
* Removes a timer. * Removes a timer.
@@ -235,10 +235,10 @@ class GHOST_ISystem {
* \param width: The width the window. * \param width: The width the window.
* \param height: The height the window. * \param height: The height the window.
* \param state: The state of the window when opened. * \param state: The state of the window when opened.
* \param gpuSettings: Misc GPU settings. * \param gpu_settings: Misc GPU settings.
* \param exclusive: Use to show the window on top and ignore others (used full-screen). * \param exclusive: Use to show the window on top and ignore others (used full-screen).
* \param is_dialog: Stay on top of parent window, no icon in taskbar, can't be minimized. * \param is_dialog: Stay on top of parent window, no icon in taskbar, can't be minimized.
* \param parentWindow: Parent (embedder) window * \param parent_window: Parent (embedder) window
* \return The new window (or 0 if creation failed). * \return The new window (or 0 if creation failed).
*/ */
virtual GHOST_IWindow *createWindow(const char *title, virtual GHOST_IWindow *createWindow(const char *title,
@@ -247,10 +247,10 @@ class GHOST_ISystem {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive = false, const bool exclusive = false,
const bool is_dialog = false, const bool is_dialog = false,
const GHOST_IWindow *parentWindow = nullptr) = 0; const GHOST_IWindow *parent_window = nullptr) = 0;
/** /**
* Dispose a window. * Dispose a window.
@@ -264,7 +264,7 @@ class GHOST_ISystem {
* Never explicitly delete the context, use #disposeContext() instead. * Never explicitly delete the context, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
virtual GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) = 0; virtual GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) = 0;
/** /**
* Dispose of a context. * Dispose of a context.
@@ -397,18 +397,18 @@ class GHOST_ISystem {
/** /**
* Returns the state of a modifier key (outside the message queue). * Returns the state of a modifier key (outside the message queue).
* \param mask: The modifier key state to retrieve. * \param mask: The modifier key state to retrieve.
* \param isDown: The state of a modifier key (true == pressed). * \param is_down: The state of a modifier key (true == pressed).
* \return Indication of success. * \return Indication of success.
*/ */
virtual GHOST_TSuccess getModifierKeyState(GHOST_TModifierKey mask, bool &isDown) const = 0; virtual GHOST_TSuccess getModifierKeyState(GHOST_TModifierKey mask, bool &is_down) const = 0;
/** /**
* Returns the state of a mouse button (outside the message queue). * Returns the state of a mouse button (outside the message queue).
* \param mask: The button state to retrieve. * \param mask: The button state to retrieve.
* \param isDown: Button state. * \param is_down: Button state.
* \return Indication of success. * \return Indication of success.
*/ */
virtual GHOST_TSuccess getButtonState(GHOST_TButton mask, bool &isDown) const = 0; virtual GHOST_TSuccess getButtonState(GHOST_TButton mask, bool &is_down) const = 0;
/** /**
* Enable multi-touch gestures if supported. * Enable multi-touch gestures if supported.
@@ -535,11 +535,11 @@ class GHOST_ISystem {
virtual GHOST_TSuccess exit() = 0; virtual GHOST_TSuccess exit() = 0;
/** The one and only system */ /** The one and only system */
static GHOST_ISystem *m_system; static GHOST_ISystem *system_;
static const char *m_system_backend_id; static const char *system_backend_id_;
/** Function to call that sets the back-trace. */ /** Function to call that sets the back-trace. */
static GHOST_TBacktraceFn m_backtrace_fn; static GHOST_TBacktraceFn backtrace_fn_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ISystem") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ISystem")
}; };

View File

@@ -80,7 +80,7 @@ class GHOST_ISystemPaths {
private: private:
/** The one and only system paths. */ /** The one and only system paths. */
static GHOST_ISystemPaths *m_systemPaths; static GHOST_ISystemPaths *system_paths_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ISystemPaths") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ISystemPaths")
}; };

View File

@@ -14,7 +14,7 @@
/** /**
* Interface for a timer task. * Interface for a timer task.
* Timer tasks are created by the system and can be installed by the system. * Timer tasks are created by the system and can be installed by the system.
* After installation, the timer callback-procedure or "timerProc" will be called * After installation, the timer callback-procedure or "timer_proc" will be called
* periodically. You should not need to inherit this class. It is passed to the * periodically. You should not need to inherit this class. It is passed to the
* application in the timer-callback.<br> * application in the timer-callback.<br>
* <br> * <br>
@@ -38,9 +38,9 @@ class GHOST_ITimerTask {
/** /**
* Changes the timer callback. * Changes the timer callback.
* \param timerProc: The timer callback. * \param timer_proc: The timer callback.
*/ */
virtual void setTimerProc(const GHOST_TimerProcPtr timerProc) = 0; virtual void setTimerProc(const GHOST_TimerProcPtr timer_proc) = 0;
/** /**
* Returns the timer user data. * Returns the timer user data.
@@ -50,9 +50,9 @@ class GHOST_ITimerTask {
/** /**
* Changes the time user data. * Changes the time user data.
* \param userData: The timer user data. * \param user_data: The timer user data.
*/ */
virtual void setUserData(const GHOST_TUserDataPtr userData) = 0; virtual void setUserData(const GHOST_TUserDataPtr user_data) = 0;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ITimerTask") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_ITimerTask")
}; };

View File

@@ -94,16 +94,16 @@ class GHOST_IWindow {
/** /**
* Set the window decoration style flags. * Set the window decoration style flags.
* \param styleFlags: Window decoration style flags. * \param style_flags: Window decoration style flags.
*/ */
virtual void setWindowDecorationStyleFlags(GHOST_TWindowDecorationStyleFlags styleFlags) = 0; virtual void setWindowDecorationStyleFlags(GHOST_TWindowDecorationStyleFlags style_flags) = 0;
/** /**
* Set the window decoration style settings. * Set the window decoration style settings.
* \param decorationSettings: Window decoration style settings. * \param decoration_settings: Window decoration style settings.
*/ */
virtual void setWindowDecorationStyleSettings( virtual void setWindowDecorationStyleSettings(
GHOST_WindowDecorationStyleSettings decorationSettings) = 0; GHOST_WindowDecorationStyleSettings decoration_settings) = 0;
/** /**
* Apply the window decoration style using the current flags and settings. * Apply the window decoration style using the current flags and settings.
@@ -164,7 +164,7 @@ class GHOST_IWindow {
/** /**
* Tells if the ongoing drag & drop object can be accepted upon mouse drop * Tells if the ongoing drag & drop object can be accepted upon mouse drop
*/ */
virtual void setAcceptDragOperation(bool canAccept) = 0; virtual void setAcceptDragOperation(bool can_accept) = 0;
/** /**
* Returns acceptance of the dropped object. * Returns acceptance of the dropped object.
@@ -187,10 +187,10 @@ class GHOST_IWindow {
/** /**
* Sets the window "modified" status, indicating unsaved changes. * Sets the window "modified" status, indicating unsaved changes.
* \param isUnsavedChanges: Unsaved changes or not. * \param is_unsaved_changes: Unsaved changes or not.
* \return Indication of success. * \return Indication of success.
*/ */
virtual GHOST_TSuccess setModifiedState(bool isUnsavedChanges) = 0; virtual GHOST_TSuccess setModifiedState(bool is_unsaved_changes) = 0;
/** /**
* Gets the window "modified" status, indicating unsaved changes. * Gets the window "modified" status, indicating unsaved changes.
@@ -220,11 +220,11 @@ class GHOST_IWindow {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: pointer to location to return swap interval. * \param interval_out: pointer to location to return swap interval.
* (left untouched if there is an error) * (left untouched if there is an error)
* \return A boolean success indicator of if swap interval was successfully read. * \return A boolean success indicator of if swap interval was successfully read.
*/ */
virtual GHOST_TSuccess getSwapInterval(int &intervalOut) = 0; virtual GHOST_TSuccess getSwapInterval(int &interval_out) = 0;
/** /**
* Activates the drawing context of this window. * Activates the drawing context of this window.
@@ -258,9 +258,9 @@ class GHOST_IWindow {
/** /**
* Changes the window user data. * Changes the window user data.
* \param userData: The window user data. * \param user_data: The window user data.
*/ */
virtual void setUserData(const GHOST_TUserDataPtr userData) = 0; virtual void setUserData(const GHOST_TUserDataPtr user_data) = 0;
virtual bool isDialog() const = 0; virtual bool isDialog() const = 0;
@@ -291,10 +291,10 @@ class GHOST_IWindow {
/** /**
* Set the shape of the cursor. * Set the shape of the cursor.
* \param cursorShape: The new cursor shape type id. * \param cursor_shape: The new cursor shape type id.
* \return Indication of success. * \return Indication of success.
*/ */
virtual GHOST_TSuccess setCursorShape(GHOST_TStandardCursor cursorShape) = 0; virtual GHOST_TSuccess setCursorShape(GHOST_TStandardCursor cursor_shape) = 0;
/** /**
* Gets the cursor grab region, if unset the window is used. * Gets the cursor grab region, if unset the window is used.
@@ -316,7 +316,7 @@ class GHOST_IWindow {
* Test if the standard cursor shape is supported by current platform. * Test if the standard cursor shape is supported by current platform.
* \return Indication of success. * \return Indication of success.
*/ */
virtual GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor cursorShape) = 0; virtual GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor cursor_shape) = 0;
/** /**
* Set the shape of the cursor to a custom cursor. * Set the shape of the cursor to a custom cursor.

View File

@@ -27,7 +27,7 @@ class GHOST_Rect {
* \param b: requested bottom coordinate of the rectangle. * \param b: requested bottom coordinate of the rectangle.
*/ */
GHOST_Rect(int32_t l = 0, int32_t t = 0, int32_t r = 0, int32_t b = 0) GHOST_Rect(int32_t l = 0, int32_t t = 0, int32_t r = 0, int32_t b = 0)
: m_l(l), m_t(t), m_r(r), m_b(b) : l_(l), t_(t), r_(r), b_(b)
{ {
} }
@@ -66,7 +66,7 @@ class GHOST_Rect {
/** /**
* Returns whether this rectangle is valid. * Returns whether this rectangle is valid.
* Valid rectangles are rectangles that have m_l <= m_r and m_t <= m_b. * Valid rectangles are rectangles that have l_ <= r_ and t_ <= b_.
* Thus, empty rectangles are valid. * Thus, empty rectangles are valid.
* \return boolean value (true==valid rectangle) * \return boolean value (true==valid rectangle)
*/ */
@@ -151,33 +151,33 @@ class GHOST_Rect {
virtual bool clip(GHOST_Rect &r) const; virtual bool clip(GHOST_Rect &r) const;
/** Left coordinate of the rectangle */ /** Left coordinate of the rectangle */
int32_t m_l; int32_t l_;
/** Top coordinate of the rectangle */ /** Top coordinate of the rectangle */
int32_t m_t; int32_t t_;
/** Right coordinate of the rectangle */ /** Right coordinate of the rectangle */
int32_t m_r; int32_t r_;
/** Bottom coordinate of the rectangle */ /** Bottom coordinate of the rectangle */
int32_t m_b; int32_t b_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_Rect") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_Rect")
}; };
inline int32_t GHOST_Rect::getWidth() const inline int32_t GHOST_Rect::getWidth() const
{ {
return m_r - m_l; return r_ - l_;
} }
inline int32_t GHOST_Rect::getHeight() const inline int32_t GHOST_Rect::getHeight() const
{ {
return m_b - m_t; return b_ - t_;
} }
inline void GHOST_Rect::set(int32_t l, int32_t t, int32_t r, int32_t b) inline void GHOST_Rect::set(int32_t l, int32_t t, int32_t r, int32_t b)
{ {
m_l = l; l_ = l;
m_t = t; t_ = t;
m_r = r; r_ = r;
m_b = b; b_ = b;
} }
inline bool GHOST_Rect::isEmpty() const inline bool GHOST_Rect::isEmpty() const
@@ -187,38 +187,38 @@ inline bool GHOST_Rect::isEmpty() const
inline bool GHOST_Rect::isValid() const inline bool GHOST_Rect::isValid() const
{ {
return (m_l <= m_r) && (m_t <= m_b); return (l_ <= r_) && (t_ <= b_);
} }
inline void GHOST_Rect::unionRect(const GHOST_Rect &r) inline void GHOST_Rect::unionRect(const GHOST_Rect &r)
{ {
if (r.m_l < m_l) { if (r.l_ < l_) {
m_l = r.m_l; l_ = r.l_;
} }
if (r.m_r > m_r) { if (r.r_ > r_) {
m_r = r.m_r; r_ = r.r_;
} }
if (r.m_t < m_t) { if (r.t_ < t_) {
m_t = r.m_t; t_ = r.t_;
} }
if (r.m_b > m_b) { if (r.b_ > b_) {
m_b = r.m_b; b_ = r.b_;
} }
} }
inline void GHOST_Rect::unionPoint(int32_t x, int32_t y) inline void GHOST_Rect::unionPoint(int32_t x, int32_t y)
{ {
if (x < m_l) { if (x < l_) {
m_l = x; l_ = x;
} }
if (x > m_r) { if (x > r_) {
m_r = x; r_ = x;
} }
if (y < m_t) { if (y < t_) {
m_t = y; t_ = y;
} }
if (y > m_b) { if (y > b_) {
m_b = y; b_ = y;
} }
} }
@@ -233,18 +233,18 @@ inline void GHOST_Rect::wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAx
} }
if (axis & GHOST_kAxisX) { if (axis & GHOST_kAxisX) {
while (x - ofs < m_l) { while (x - ofs < l_) {
x += w - (ofs * 2); x += w - (ofs * 2);
} }
while (x + ofs > m_r) { while (x + ofs > r_) {
x -= w - (ofs * 2); x -= w - (ofs * 2);
} }
} }
if (axis & GHOST_kAxisY) { if (axis & GHOST_kAxisY) {
while (y - ofs < m_t) { while (y - ofs < t_) {
y += h - (ofs * 2); y += h - (ofs * 2);
} }
while (y + ofs > m_b) { while (y + ofs > b_) {
y -= h - (ofs * 2); y -= h - (ofs * 2);
} }
} }
@@ -252,22 +252,22 @@ inline void GHOST_Rect::wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAx
inline void GHOST_Rect::clampPoint(int32_t &x, int32_t &y) inline void GHOST_Rect::clampPoint(int32_t &x, int32_t &y)
{ {
if (x < m_l) { if (x < l_) {
x = m_l; x = l_;
} }
else if (x > m_r) { else if (x > r_) {
x = m_r; x = r_;
} }
if (y < m_t) { if (y < t_) {
y = m_t; y = t_;
} }
else if (y > m_b) { else if (y > b_) {
y = m_b; y = b_;
} }
} }
inline bool GHOST_Rect::isInside(int32_t x, int32_t y) const inline bool GHOST_Rect::isInside(int32_t x, int32_t y) const
{ {
return (x >= m_l) && (x <= m_r) && (y >= m_t) && (y <= m_b); return (x >= l_) && (x <= r_) && (y >= t_) && (y <= b_);
} }

View File

@@ -822,19 +822,19 @@ typedef struct {
/*is_stereo_visual*/ false, /*is_debug*/ false, /*vsync*/ GHOST_kVSyncModeUnset, \ /*is_stereo_visual*/ false, /*is_debug*/ false, /*vsync*/ GHOST_kVSyncModeUnset, \
} }
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings) \ #define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings) \
{ \ { \
/*is_stereo_visual*/ false, \ /*is_stereo_visual*/ false, \
/*is_debug*/ (((gpuSettings).flags & GHOST_gpuDebugContext) != 0), \ /*is_debug*/ (((gpu_settings).flags & GHOST_gpuDebugContext) != 0), \
/*vsync*/ GHOST_kVSyncModeUnset, \ /*vsync*/ GHOST_kVSyncModeUnset, \
} }
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings) \ #define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings) \
{ \ { \
/*is_stereo_visual*/ (((gpuSettings).flags & GHOST_gpuStereoVisual) != 0), \ /*is_stereo_visual*/ (((gpu_settings).flags & GHOST_gpuStereoVisual) != 0), \
/*is_debug*/ (((gpuSettings).flags & GHOST_gpuDebugContext) != 0), /*vsync*/ \ /*is_debug*/ (((gpu_settings).flags & GHOST_gpuDebugContext) != 0), /*vsync*/ \
(((gpuSettings).flags & GHOST_gpuVSyncIsOverridden) ? (gpuSettings).vsync : \ (((gpu_settings).flags & GHOST_gpuVSyncIsOverridden) ? (gpu_settings).vsync : \
GHOST_kVSyncModeUnset), \ GHOST_kVSyncModeUnset), \
} }
typedef struct { typedef struct {

View File

@@ -17,19 +17,19 @@ bool GHOST_Buttons::get(GHOST_TButton mask) const
{ {
switch (mask) { switch (mask) {
case GHOST_kButtonMaskLeft: case GHOST_kButtonMaskLeft:
return m_ButtonLeft; return button_left_;
case GHOST_kButtonMaskMiddle: case GHOST_kButtonMaskMiddle:
return m_ButtonMiddle; return button_middle_;
case GHOST_kButtonMaskRight: case GHOST_kButtonMaskRight:
return m_ButtonRight; return button_right_;
case GHOST_kButtonMaskButton4: case GHOST_kButtonMaskButton4:
return m_Button4; return button4_;
case GHOST_kButtonMaskButton5: case GHOST_kButtonMaskButton5:
return m_Button5; return button5_;
case GHOST_kButtonMaskButton6: case GHOST_kButtonMaskButton6:
return m_Button6; return button6_;
case GHOST_kButtonMaskButton7: case GHOST_kButtonMaskButton7:
return m_Button7; return button7_;
default: default:
return false; return false;
} }
@@ -39,25 +39,25 @@ void GHOST_Buttons::set(GHOST_TButton mask, bool down)
{ {
switch (mask) { switch (mask) {
case GHOST_kButtonMaskLeft: case GHOST_kButtonMaskLeft:
m_ButtonLeft = down; button_left_ = down;
break; break;
case GHOST_kButtonMaskMiddle: case GHOST_kButtonMaskMiddle:
m_ButtonMiddle = down; button_middle_ = down;
break; break;
case GHOST_kButtonMaskRight: case GHOST_kButtonMaskRight:
m_ButtonRight = down; button_right_ = down;
break; break;
case GHOST_kButtonMaskButton4: case GHOST_kButtonMaskButton4:
m_Button4 = down; button4_ = down;
break; break;
case GHOST_kButtonMaskButton5: case GHOST_kButtonMaskButton5:
m_Button5 = down; button5_ = down;
break; break;
case GHOST_kButtonMaskButton6: case GHOST_kButtonMaskButton6:
m_Button6 = down; button6_ = down;
break; break;
case GHOST_kButtonMaskButton7: case GHOST_kButtonMaskButton7:
m_Button7 = down; button7_ = down;
break; break;
default: default:
break; break;
@@ -66,13 +66,13 @@ void GHOST_Buttons::set(GHOST_TButton mask, bool down)
void GHOST_Buttons::clear() void GHOST_Buttons::clear()
{ {
m_ButtonLeft = false; button_left_ = false;
m_ButtonMiddle = false; button_middle_ = false;
m_ButtonRight = false; button_right_ = false;
m_Button4 = false; button4_ = false;
m_Button5 = false; button5_ = false;
m_Button6 = false; button6_ = false;
m_Button7 = false; button7_ = false;
} }
GHOST_Buttons::~GHOST_Buttons() = default; GHOST_Buttons::~GHOST_Buttons() = default;

View File

@@ -42,11 +42,11 @@ struct GHOST_Buttons {
*/ */
void clear(); void clear();
uint8_t m_ButtonLeft : 1; uint8_t button_left_ : 1;
uint8_t m_ButtonMiddle : 1; uint8_t button_middle_ : 1;
uint8_t m_ButtonRight : 1; uint8_t button_right_ : 1;
uint8_t m_Button4 : 1; uint8_t button4_ : 1;
uint8_t m_Button5 : 1; uint8_t button5_ : 1;
uint8_t m_Button6 : 1; uint8_t button6_ : 1;
uint8_t m_Button7 : 1; uint8_t button7_ : 1;
}; };

View File

@@ -139,11 +139,11 @@ GHOST_TSuccess GHOST_GetAllDisplayDimensions(GHOST_SystemHandle systemhandle,
} }
GHOST_ContextHandle GHOST_CreateGPUContext(GHOST_SystemHandle systemhandle, GHOST_ContextHandle GHOST_CreateGPUContext(GHOST_SystemHandle systemhandle,
GHOST_GPUSettings gpuSettings) GHOST_GPUSettings gpu_settings)
{ {
GHOST_ISystem *system = (GHOST_ISystem *)systemhandle; GHOST_ISystem *system = (GHOST_ISystem *)systemhandle;
return (GHOST_ContextHandle)system->createOffscreenContext(gpuSettings); return (GHOST_ContextHandle)system->createOffscreenContext(gpu_settings);
} }
GHOST_TSuccess GHOST_DisposeGPUContext(GHOST_SystemHandle systemhandle, GHOST_TSuccess GHOST_DisposeGPUContext(GHOST_SystemHandle systemhandle,
@@ -164,7 +164,7 @@ GHOST_WindowHandle GHOST_CreateWindow(GHOST_SystemHandle systemhandle,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
bool is_dialog, bool is_dialog,
GHOST_GPUSettings gpuSettings) GHOST_GPUSettings gpu_settings)
{ {
GHOST_ISystem *system = (GHOST_ISystem *)systemhandle; GHOST_ISystem *system = (GHOST_ISystem *)systemhandle;
@@ -174,7 +174,7 @@ GHOST_WindowHandle GHOST_CreateWindow(GHOST_SystemHandle systemhandle,
width, width,
height, height,
state, state,
gpuSettings, gpu_settings,
false, false,
is_dialog, is_dialog,
(GHOST_IWindow *)parent_windowhandle); (GHOST_IWindow *)parent_windowhandle);
@@ -417,10 +417,10 @@ void GHOST_GetCursorGrabState(GHOST_WindowHandle windowhandle,
GHOST_Rect bounds_rect; GHOST_Rect bounds_rect;
bool use_software_cursor; bool use_software_cursor;
window->getCursorGrabState(*r_mode, *r_axis_flag, bounds_rect, use_software_cursor); window->getCursorGrabState(*r_mode, *r_axis_flag, bounds_rect, use_software_cursor);
r_bounds[0] = bounds_rect.m_l; r_bounds[0] = bounds_rect.l_;
r_bounds[1] = bounds_rect.m_t; r_bounds[1] = bounds_rect.t_;
r_bounds[2] = bounds_rect.m_r; r_bounds[2] = bounds_rect.r_;
r_bounds[3] = bounds_rect.m_b; r_bounds[3] = bounds_rect.b_;
*r_use_software_cursor = use_software_cursor; *r_use_software_cursor = use_software_cursor;
} }
@@ -591,17 +591,17 @@ GHOST_TWindowDecorationStyleFlags GHOST_GetWindowDecorationStyleFlags(
} }
void GHOST_SetWindowDecorationStyleFlags(GHOST_WindowHandle windowhandle, void GHOST_SetWindowDecorationStyleFlags(GHOST_WindowHandle windowhandle,
GHOST_TWindowDecorationStyleFlags styleFlags) GHOST_TWindowDecorationStyleFlags style_flags)
{ {
GHOST_IWindow *window = (GHOST_IWindow *)windowhandle; GHOST_IWindow *window = (GHOST_IWindow *)windowhandle;
window->setWindowDecorationStyleFlags(styleFlags); window->setWindowDecorationStyleFlags(style_flags);
} }
void GHOST_SetWindowDecorationStyleSettings(GHOST_WindowHandle windowhandle, void GHOST_SetWindowDecorationStyleSettings(
GHOST_WindowDecorationStyleSettings decorationSettings) GHOST_WindowHandle windowhandle, GHOST_WindowDecorationStyleSettings decoration_settings)
{ {
GHOST_IWindow *window = (GHOST_IWindow *)windowhandle; GHOST_IWindow *window = (GHOST_IWindow *)windowhandle;
window->setWindowDecorationStyleSettings(decorationSettings); window->setWindowDecorationStyleSettings(decoration_settings);
} }
GHOST_TSuccess GHOST_ApplyWindowDecorationStyle(GHOST_WindowHandle windowhandle) GHOST_TSuccess GHOST_ApplyWindowDecorationStyle(GHOST_WindowHandle windowhandle)
@@ -690,11 +690,12 @@ GHOST_TSuccess GHOST_SetWindowState(GHOST_WindowHandle windowhandle, GHOST_TWind
return window->setState(state); return window->setState(state);
} }
GHOST_TSuccess GHOST_SetWindowModifiedState(GHOST_WindowHandle windowhandle, bool isUnsavedChanges) GHOST_TSuccess GHOST_SetWindowModifiedState(GHOST_WindowHandle windowhandle,
bool is_unsaved_changes)
{ {
GHOST_IWindow *window = (GHOST_IWindow *)windowhandle; GHOST_IWindow *window = (GHOST_IWindow *)windowhandle;
return window->setModifiedState(isUnsavedChanges); return window->setModifiedState(is_unsaved_changes);
} }
GHOST_TSuccess GHOST_SetWindowOrder(GHOST_WindowHandle windowhandle, GHOST_TWindowOrder order) GHOST_TSuccess GHOST_SetWindowOrder(GHOST_WindowHandle windowhandle, GHOST_TWindowOrder order)
@@ -808,10 +809,10 @@ void GHOST_GetRectangle(
{ {
const GHOST_Rect *rect = (GHOST_Rect *)rectanglehandle; const GHOST_Rect *rect = (GHOST_Rect *)rectanglehandle;
*l = rect->m_l; *l = rect->l_;
*t = rect->m_t; *t = rect->t_;
*r = rect->m_r; *r = rect->r_;
*b = rect->m_b; *b = rect->b_;
} }
void GHOST_SetRectangle( void GHOST_SetRectangle(

View File

@@ -15,13 +15,13 @@
#include "GHOST_Debug.hh" #include "GHOST_Debug.hh"
GHOST_CallbackEventConsumer::GHOST_CallbackEventConsumer(GHOST_EventCallbackProcPtr eventCallback, GHOST_CallbackEventConsumer::GHOST_CallbackEventConsumer(GHOST_EventCallbackProcPtr eventCallback,
GHOST_TUserDataPtr userData) GHOST_TUserDataPtr user_data)
{ {
m_eventCallback = eventCallback; event_callback_ = eventCallback;
m_userData = userData; user_data_ = user_data;
} }
bool GHOST_CallbackEventConsumer::processEvent(const GHOST_IEvent *event) bool GHOST_CallbackEventConsumer::processEvent(const GHOST_IEvent *event)
{ {
return m_eventCallback((GHOST_EventHandle)event, m_userData); return event_callback_((GHOST_EventHandle)event, user_data_);
} }

View File

@@ -21,10 +21,10 @@ class GHOST_CallbackEventConsumer : public GHOST_IEventConsumer {
/** /**
* Constructor. * Constructor.
* \param eventCallback: The call-back routine invoked. * \param eventCallback: The call-back routine invoked.
* \param userData: The data passed back through the call-back routine. * \param user_data: The data passed back through the call-back routine.
*/ */
GHOST_CallbackEventConsumer(GHOST_EventCallbackProcPtr eventCallback, GHOST_CallbackEventConsumer(GHOST_EventCallbackProcPtr eventCallback,
GHOST_TUserDataPtr userData); GHOST_TUserDataPtr user_data);
/** /**
* Destructor. * Destructor.
@@ -40,9 +40,9 @@ class GHOST_CallbackEventConsumer : public GHOST_IEventConsumer {
protected: protected:
/** The call-back routine invoked. */ /** The call-back routine invoked. */
GHOST_EventCallbackProcPtr m_eventCallback; GHOST_EventCallbackProcPtr event_callback_;
/** The data passed back through the call-back routine. */ /** The data passed back through the call-back routine. */
GHOST_TUserDataPtr m_userData; GHOST_TUserDataPtr user_data_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_CallbackEventConsumer") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_CallbackEventConsumer")
}; };

View File

@@ -23,7 +23,7 @@ class GHOST_Context : public GHOST_IContext {
* Constructor. * Constructor.
* \param context_params: Parameters to use when initializing the context. * \param context_params: Parameters to use when initializing the context.
*/ */
GHOST_Context(const GHOST_ContextParams &context_params) : m_context_params(context_params) {} GHOST_Context(const GHOST_ContextParams &context_params) : context_params_(context_params) {}
/** /**
* Destructor. * Destructor.
@@ -86,7 +86,7 @@ class GHOST_Context : public GHOST_IContext {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
virtual GHOST_TSuccess getSwapInterval(int & /*interval*/) virtual GHOST_TSuccess getSwapInterval(int & /*interval*/)
@@ -99,7 +99,7 @@ class GHOST_Context : public GHOST_IContext {
*/ */
void *getUserData() void *getUserData()
{ {
return m_user_data; return user_data_;
} }
/** /**
@@ -107,7 +107,7 @@ class GHOST_Context : public GHOST_IContext {
*/ */
void setUserData(void *user_data) void setUserData(void *user_data)
{ {
m_user_data = user_data; user_data_ = user_data;
} }
/** /**
@@ -117,13 +117,13 @@ class GHOST_Context : public GHOST_IContext {
*/ */
bool isStereoVisual() const bool isStereoVisual() const
{ {
return m_context_params.is_stereo_visual; return context_params_.is_stereo_visual;
} }
/** Get the VSync value. */ /** Get the VSync value. */
virtual GHOST_TVSyncModes getVSync() virtual GHOST_TVSyncModes getVSync()
{ {
return m_context_params.vsync; return context_params_.vsync;
} }
/** /**
@@ -166,10 +166,10 @@ class GHOST_Context : public GHOST_IContext {
#endif #endif
protected: protected:
GHOST_ContextParams m_context_params; GHOST_ContextParams context_params_;
/** Caller specified, not for internal use. */ /** Caller specified, not for internal use. */
void *m_user_data = nullptr; void *user_data_ = nullptr;
#ifdef WITH_OPENGL_BACKEND #ifdef WITH_OPENGL_BACKEND
static void initClearGL(); static void initClearGL();

View File

@@ -21,15 +21,15 @@ HMODULE GHOST_ContextD3D::s_d3d_lib = nullptr;
PFN_D3D11_CREATE_DEVICE GHOST_ContextD3D::s_D3D11CreateDeviceFn = nullptr; PFN_D3D11_CREATE_DEVICE GHOST_ContextD3D::s_D3D11CreateDeviceFn = nullptr;
GHOST_ContextD3D::GHOST_ContextD3D(const GHOST_ContextParams &context_params, HWND hWnd) GHOST_ContextD3D::GHOST_ContextD3D(const GHOST_ContextParams &context_params, HWND hWnd)
: GHOST_Context(context_params), m_hWnd(hWnd) : GHOST_Context(context_params), h_wnd_(hWnd)
{ {
} }
GHOST_ContextD3D::~GHOST_ContextD3D() GHOST_ContextD3D::~GHOST_ContextD3D()
{ {
m_device->Release(); device_->Release();
m_device_ctx->ClearState(); device_ctx_->ClearState();
m_device_ctx->Release(); device_ctx_->Release();
} }
GHOST_TSuccess GHOST_ContextD3D::swapBuffers() GHOST_TSuccess GHOST_ContextD3D::swapBuffers()
@@ -95,9 +95,9 @@ GHOST_TSuccess GHOST_ContextD3D::initializeDrawingContext()
nullptr, nullptr,
0, 0,
D3D11_SDK_VERSION, D3D11_SDK_VERSION,
&m_device, &device_,
nullptr, nullptr,
&m_device_ctx); &device_ctx_);
WIN32_CHK(hres == S_OK); WIN32_CHK(hres == S_OK);
@@ -115,7 +115,7 @@ class GHOST_SharedOpenGLResource {
HANDLE device; HANDLE device;
GLuint fbo; GLuint fbo;
HANDLE render_target{nullptr}; HANDLE render_target{nullptr};
} m_shared; } shared_;
enum RenderTarget { TARGET_RENDERBUF, TARGET_TEX2D }; enum RenderTarget { TARGET_RENDERBUF, TARGET_TEX2D };
@@ -126,7 +126,7 @@ class GHOST_SharedOpenGLResource {
unsigned int height, unsigned int height,
DXGI_FORMAT format, DXGI_FORMAT format,
ID3D11RenderTargetView *render_target = nullptr) ID3D11RenderTargetView *render_target = nullptr)
: m_device(device), m_device_ctx(device_ctx), m_cur_width(width), m_cur_height(height) : device_(device), device_ctx_(device_ctx), cur_width_(width), cur_height_(height)
{ {
if (!render_target) { if (!render_target) {
D3D11_TEXTURE2D_DESC texDesc{}; D3D11_TEXTURE2D_DESC texDesc{};
@@ -158,17 +158,17 @@ class GHOST_SharedOpenGLResource {
tex->Release(); tex->Release();
} }
m_render_target = render_target; render_target_ = render_target;
if (m_render_target) { if (render_target_) {
ID3D11Resource *backbuffer_res = nullptr; ID3D11Resource *backbuffer_res = nullptr;
m_render_target->GetResource(&backbuffer_res); render_target_->GetResource(&backbuffer_res);
if (backbuffer_res) { if (backbuffer_res) {
backbuffer_res->QueryInterface<ID3D11Texture2D>(&m_render_target_tex); backbuffer_res->QueryInterface<ID3D11Texture2D>(&render_target_tex_);
backbuffer_res->Release(); backbuffer_res->Release();
} }
} }
if (!m_render_target || !m_render_target_tex) { if (!render_target_ || !render_target_tex_) {
fprintf(stderr, "Error creating render target for shared DirectX-OpenGL resource\n"); fprintf(stderr, "Error creating render target for shared DirectX-OpenGL resource\n");
return; return;
} }
@@ -176,39 +176,39 @@ class GHOST_SharedOpenGLResource {
~GHOST_SharedOpenGLResource() ~GHOST_SharedOpenGLResource()
{ {
if (m_render_target_tex) { if (render_target_tex_) {
m_render_target_tex->Release(); render_target_tex_->Release();
} }
if (m_render_target) { if (render_target_) {
m_render_target->Release(); render_target_->Release();
} }
if (m_is_initialized) { if (is_initialized_) {
#if 0 /* TODO: Causes an access violation since Blender 3.4 (a296b8f694d1). */ #if 0 /* TODO: Causes an access violation since Blender 3.4 (a296b8f694d1). */
if (m_shared.render_target if (shared_.render_target
# if 1 # if 1
/* TODO: #wglDXUnregisterObjectNV() causes an access violation on AMD when the shared /* TODO: #wglDXUnregisterObjectNV() causes an access violation on AMD when the shared
* resource is a GL texture. Since there is currently no good alternative, just skip * resource is a GL texture. Since there is currently no good alternative, just skip
* unregistering the shared resource. */ * unregistering the shared resource. */
&& !m_use_gl_texture2d && !use_gl_texture2d_
# endif # endif
) { ) {
wglDXUnregisterObjectNV(m_shared.device, m_shared.render_target); wglDXUnregisterObjectNV(shared_.device, shared_.render_target);
} }
if (m_shared.device) { if (shared_.device) {
wglDXCloseDeviceNV(m_shared.device); wglDXCloseDeviceNV(shared_.device);
} }
glDeleteFramebuffers(1, &m_shared.fbo); glDeleteFramebuffers(1, &shared_.fbo);
if (m_use_gl_texture2d) { if (use_gl_texture2d_) {
glDeleteTextures(1, &m_gl_render_target); glDeleteTextures(1, &gl_render_target_);
} }
else { else {
glDeleteRenderbuffers(1, &m_gl_render_target); glDeleteRenderbuffers(1, &gl_render_target_);
} }
#else #else
glDeleteFramebuffers(1, &m_shared.fbo); glDeleteFramebuffers(1, &shared_.fbo);
if (m_use_gl_texture2d) { if (use_gl_texture2d_) {
glDeleteTextures(1, &m_gl_render_target); glDeleteTextures(1, &gl_render_target_);
} }
#endif #endif
} }
@@ -217,11 +217,11 @@ class GHOST_SharedOpenGLResource {
/* Returns true if the shared object was successfully registered, false otherwise. */ /* Returns true if the shared object was successfully registered, false otherwise. */
bool reregisterSharedObject(RenderTarget target) bool reregisterSharedObject(RenderTarget target)
{ {
if (m_shared.render_target) { if (shared_.render_target) {
wglDXUnregisterObjectNV(m_shared.device, m_shared.render_target); wglDXUnregisterObjectNV(shared_.device, shared_.render_target);
} }
if (!m_render_target_tex) { if (!render_target_tex_) {
return false; return false;
} }
@@ -229,21 +229,21 @@ class GHOST_SharedOpenGLResource {
glTexImage2D(GL_TEXTURE_2D, glTexImage2D(GL_TEXTURE_2D,
0, 0,
GL_RGBA8, GL_RGBA8,
m_cur_width, cur_width_,
m_cur_height, cur_height_,
0, 0,
GL_RGBA, GL_RGBA,
GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE,
nullptr); nullptr);
} }
m_shared.render_target = wglDXRegisterObjectNV(m_shared.device, shared_.render_target = wglDXRegisterObjectNV(shared_.device,
m_render_target_tex, render_target_tex_,
m_gl_render_target, gl_render_target_,
(target == TARGET_TEX2D) ? GL_TEXTURE_2D : (target == TARGET_TEX2D) ? GL_TEXTURE_2D :
GL_RENDERBUFFER, GL_RENDERBUFFER,
WGL_ACCESS_READ_WRITE_NV); WGL_ACCESS_READ_WRITE_NV);
if (!m_shared.render_target) { if (!shared_.render_target) {
fprintf(stderr, "Error registering shared object using wglDXRegisterObjectNV()\n"); fprintf(stderr, "Error registering shared object using wglDXRegisterObjectNV()\n");
return false; return false;
} }
@@ -253,55 +253,55 @@ class GHOST_SharedOpenGLResource {
GHOST_TSuccess initialize() GHOST_TSuccess initialize()
{ {
m_shared.device = wglDXOpenDeviceNV(m_device); shared_.device = wglDXOpenDeviceNV(device_);
if (m_shared.device == nullptr) { if (shared_.device == nullptr) {
fprintf(stderr, "Error opening shared device using wglDXOpenDeviceNV()\n"); fprintf(stderr, "Error opening shared device using wglDXOpenDeviceNV()\n");
return GHOST_kFailure; return GHOST_kFailure;
} }
/* Build the render-buffer. */ /* Build the render-buffer. */
glGenRenderbuffers(1, &m_gl_render_target); glGenRenderbuffers(1, &gl_render_target_);
glBindRenderbuffer(GL_RENDERBUFFER, m_gl_render_target); glBindRenderbuffer(GL_RENDERBUFFER, gl_render_target_);
if (!reregisterSharedObject(TARGET_RENDERBUF)) { if (!reregisterSharedObject(TARGET_RENDERBUF)) {
glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindRenderbuffer(GL_RENDERBUFFER, 0);
if (m_gl_render_target) { if (gl_render_target_) {
glDeleteRenderbuffers(1, &m_gl_render_target); glDeleteRenderbuffers(1, &gl_render_target_);
} }
/* Fall back to texture 2d. */ /* Fall back to texture 2d. */
m_use_gl_texture2d = true; use_gl_texture2d_ = true;
glGenTextures(1, &m_gl_render_target); glGenTextures(1, &gl_render_target_);
glBindTexture(GL_TEXTURE_2D, m_gl_render_target); glBindTexture(GL_TEXTURE_2D, gl_render_target_);
reregisterSharedObject(TARGET_TEX2D); reregisterSharedObject(TARGET_TEX2D);
} }
/* Build the frame-buffer. */ /* Build the frame-buffer. */
glGenFramebuffers(1, &m_shared.fbo); glGenFramebuffers(1, &shared_.fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_shared.fbo); glBindFramebuffer(GL_FRAMEBUFFER, shared_.fbo);
if (m_use_gl_texture2d) { if (use_gl_texture2d_) {
glFramebufferTexture2D( glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_gl_render_target, 0); GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gl_render_target_, 0);
} }
else { else {
glFramebufferRenderbuffer( glFramebufferRenderbuffer(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_gl_render_target); GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, gl_render_target_);
} }
m_is_initialized = true; is_initialized_ = true;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
void ensureUpdated(unsigned int width, unsigned int height) void ensureUpdated(unsigned int width, unsigned int height)
{ {
if (m_is_initialized == false) { if (is_initialized_ == false) {
initialize(); initialize();
} }
if ((m_cur_width != width) || (m_cur_height != height)) { if ((cur_width_ != width) || (cur_height_ != height)) {
m_cur_width = width; cur_width_ = width;
m_cur_height = height; cur_height_ = height;
reregisterSharedObject(m_use_gl_texture2d ? TARGET_TEX2D : TARGET_RENDERBUF); reregisterSharedObject(use_gl_texture2d_ ? TARGET_TEX2D : TARGET_RENDERBUF);
} }
} }
@@ -310,7 +310,7 @@ class GHOST_SharedOpenGLResource {
GLint fbo; GLint fbo;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo); glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fbo);
if (!m_render_target || !m_render_target_tex) { if (!render_target_ || !render_target_tex_) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -318,13 +318,13 @@ class GHOST_SharedOpenGLResource {
#ifdef NDEBUG #ifdef NDEBUG
const float clear_col[] = {0.8f, 0.5f, 1.0f, 1.0f}; const float clear_col[] = {0.8f, 0.5f, 1.0f, 1.0f};
m_device_ctx->ClearRenderTargetView(m_render_target, clear_col); device_ctx_->ClearRenderTargetView(render_target_, clear_col);
#endif #endif
m_device_ctx->OMSetRenderTargets(1, &m_render_target, nullptr); device_ctx_->OMSetRenderTargets(1, &render_target_, nullptr);
beginGLOnly(); beginGLOnly();
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_shared.fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, shared_.fbo);
GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER); GLenum err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (err != GL_FRAMEBUFFER_COMPLETE) { if (err != GL_FRAMEBUFFER_COMPLETE) {
fprintf( fprintf(
@@ -343,25 +343,25 @@ class GHOST_SharedOpenGLResource {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
ID3D11RenderTargetView *m_render_target{nullptr}; ID3D11RenderTargetView *render_target_{nullptr};
ID3D11Texture2D *m_render_target_tex{nullptr}; ID3D11Texture2D *render_target_tex_{nullptr};
private: private:
void beginGLOnly() void beginGLOnly()
{ {
wglDXLockObjectsNV(m_shared.device, 1, &m_shared.render_target); wglDXLockObjectsNV(shared_.device, 1, &shared_.render_target);
} }
void endGLOnly() void endGLOnly()
{ {
wglDXUnlockObjectsNV(m_shared.device, 1, &m_shared.render_target); wglDXUnlockObjectsNV(shared_.device, 1, &shared_.render_target);
} }
ID3D11Device *m_device; ID3D11Device *device_;
ID3D11DeviceContext *m_device_ctx; ID3D11DeviceContext *device_ctx_;
GLuint m_gl_render_target; GLuint gl_render_target_;
unsigned int m_cur_width, m_cur_height; unsigned int cur_width_, cur_height_;
bool m_is_initialized{false}; bool is_initialized_{false};
bool m_use_gl_texture2d{false}; bool use_gl_texture2d_{false};
}; };
GHOST_SharedOpenGLResource *GHOST_ContextD3D::createSharedOpenGLResource( GHOST_SharedOpenGLResource *GHOST_ContextD3D::createSharedOpenGLResource(
@@ -377,7 +377,7 @@ GHOST_SharedOpenGLResource *GHOST_ContextD3D::createSharedOpenGLResource(
return nullptr; return nullptr;
} }
GHOST_SharedOpenGLResource *shared_res = new GHOST_SharedOpenGLResource( GHOST_SharedOpenGLResource *shared_res = new GHOST_SharedOpenGLResource(
m_device, m_device_ctx, width, height, format, render_target); device_, device_ctx_, width, height, format, render_target);
return shared_res; return shared_res;
} }
@@ -402,5 +402,5 @@ GHOST_TSuccess GHOST_ContextD3D::blitFromOpenGLContext(GHOST_SharedOpenGLResourc
ID3D11Texture2D *GHOST_ContextD3D::getSharedTexture2D(GHOST_SharedOpenGLResource *shared_res) ID3D11Texture2D *GHOST_ContextD3D::getSharedTexture2D(GHOST_SharedOpenGLResource *shared_res)
{ {
return shared_res->m_render_target_tex; return shared_res->render_target_tex_;
} }

View File

@@ -78,7 +78,7 @@ class GHOST_ContextD3D : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int & /*unused*/) override GHOST_TSuccess getSwapInterval(int & /*unused*/) override
@@ -120,8 +120,8 @@ class GHOST_ContextD3D : public GHOST_Context {
static HMODULE s_d3d_lib; static HMODULE s_d3d_lib;
static PFN_D3D11_CREATE_DEVICE s_D3D11CreateDeviceFn; static PFN_D3D11_CREATE_DEVICE s_D3D11CreateDeviceFn;
HWND m_hWnd; HWND h_wnd_;
ID3D11Device *m_device; ID3D11Device *device_;
ID3D11DeviceContext *m_device_ctx; ID3D11DeviceContext *device_ctx_;
}; };

View File

@@ -197,65 +197,65 @@ GHOST_ContextEGL::GHOST_ContextEGL(const GHOST_System *const system,
EGLint contextResetNotificationStrategy, EGLint contextResetNotificationStrategy,
EGLenum api) EGLenum api)
: GHOST_Context(context_params), : GHOST_Context(context_params),
m_system(system), system_(system),
m_nativeDisplay(nativeDisplay), native_display_(nativeDisplay),
m_nativeWindow(nativeWindow), native_window_(nativeWindow),
m_contextProfileMask(contextProfileMask), context_profile_mask_(contextProfileMask),
m_contextMajorVersion(contextMajorVersion), context_major_version_(contextMajorVersion),
m_contextMinorVersion(contextMinorVersion), context_minor_version_(contextMinorVersion),
m_contextFlags(contextFlags), context_flags_(contextFlags),
m_contextResetNotificationStrategy(contextResetNotificationStrategy), context_reset_notification_strategy_(contextResetNotificationStrategy),
m_api(api), api_(api),
m_context(EGL_NO_CONTEXT), context_(EGL_NO_CONTEXT),
m_surface(EGL_NO_SURFACE), surface_(EGL_NO_SURFACE),
m_display(EGL_NO_DISPLAY), display_(EGL_NO_DISPLAY),
m_config(EGL_NO_CONFIG_KHR), config_(EGL_NO_CONFIG_KHR),
m_swap_interval(1), swap_interval_(1),
m_sharedContext( shared_context_(
choose_api(api, s_gl_sharedContext, s_gles_sharedContext, s_vg_sharedContext)), choose_api(api, s_gl_sharedContext, s_gles_sharedContext, s_vg_sharedContext)),
m_sharedCount(choose_api(api, s_gl_sharedCount, s_gles_sharedCount, s_vg_sharedCount)), shared_count_(choose_api(api, s_gl_sharedCount, s_gles_sharedCount, s_vg_sharedCount)),
m_surface_from_native_window(false) surface_from_native_window_(false)
{ {
} }
GHOST_ContextEGL::~GHOST_ContextEGL() GHOST_ContextEGL::~GHOST_ContextEGL()
{ {
if (m_display != EGL_NO_DISPLAY) { if (display_ != EGL_NO_DISPLAY) {
bindAPI(m_api); bindAPI(api_);
if (m_context != EGL_NO_CONTEXT) { if (context_ != EGL_NO_CONTEXT) {
if (m_context == ::eglGetCurrentContext()) { if (context_ == ::eglGetCurrentContext()) {
EGL_CHK(::eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); EGL_CHK(::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
} }
if (m_context != m_sharedContext || m_sharedCount == 1) { if (context_ != shared_context_ || shared_count_ == 1) {
assert(m_sharedCount > 0); assert(shared_count_ > 0);
m_sharedCount--; shared_count_--;
if (m_sharedCount == 0) { if (shared_count_ == 0) {
m_sharedContext = EGL_NO_CONTEXT; shared_context_ = EGL_NO_CONTEXT;
} }
EGL_CHK(::eglDestroyContext(m_display, m_context)); EGL_CHK(::eglDestroyContext(display_, context_));
} }
} }
if (m_surface != EGL_NO_SURFACE) { if (surface_ != EGL_NO_SURFACE) {
EGL_CHK(::eglDestroySurface(m_display, m_surface)); EGL_CHK(::eglDestroySurface(display_, surface_));
} }
} }
} }
GHOST_TSuccess GHOST_ContextEGL::swapBuffers() GHOST_TSuccess GHOST_ContextEGL::swapBuffers()
{ {
return EGL_CHK(::eglSwapBuffers(m_display, m_surface)) ? GHOST_kSuccess : GHOST_kFailure; return EGL_CHK(::eglSwapBuffers(display_, surface_)) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextEGL::setSwapInterval(int interval) GHOST_TSuccess GHOST_ContextEGL::setSwapInterval(int interval)
{ {
if (epoxy_egl_version(m_display) >= 11) { if (epoxy_egl_version(display_) >= 11) {
if (EGL_CHK(::eglSwapInterval(m_display, interval))) { if (EGL_CHK(::eglSwapInterval(display_, interval))) {
m_swap_interval = interval; swap_interval_ = interval;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -264,48 +264,48 @@ GHOST_TSuccess GHOST_ContextEGL::setSwapInterval(int interval)
return GHOST_kFailure; return GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextEGL::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextEGL::getSwapInterval(int &interval_out)
{ {
/* This is a bit of a kludge because there does not seem to /* This is a bit of a kludge because there does not seem to
* be a way to query the swap interval with EGL. */ * be a way to query the swap interval with EGL. */
intervalOut = m_swap_interval; interval_out = swap_interval_;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
EGLDisplay GHOST_ContextEGL::getDisplay() const EGLDisplay GHOST_ContextEGL::getDisplay() const
{ {
return m_display; return display_;
} }
EGLConfig GHOST_ContextEGL::getConfig() const EGLConfig GHOST_ContextEGL::getConfig() const
{ {
return m_config; return config_;
} }
EGLContext GHOST_ContextEGL::getContext() const EGLContext GHOST_ContextEGL::getContext() const
{ {
return m_context; return context_;
} }
GHOST_TSuccess GHOST_ContextEGL::activateDrawingContext() GHOST_TSuccess GHOST_ContextEGL::activateDrawingContext()
{ {
if (m_display) { if (display_) {
active_context_ = this; active_context_ = this;
bindAPI(m_api); bindAPI(api_);
return EGL_CHK(::eglMakeCurrent(m_display, m_surface, m_surface, m_context)) ? GHOST_kSuccess : return EGL_CHK(::eglMakeCurrent(display_, surface_, surface_, context_)) ? GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
} }
return GHOST_kFailure; return GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextEGL::releaseDrawingContext() GHOST_TSuccess GHOST_ContextEGL::releaseDrawingContext()
{ {
if (m_display) { if (display_) {
active_context_ = nullptr; active_context_ = nullptr;
bindAPI(m_api); bindAPI(api_);
return EGL_CHK(::eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) ? return EGL_CHK(::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) ?
GHOST_kSuccess : GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
} }
@@ -314,7 +314,7 @@ GHOST_TSuccess GHOST_ContextEGL::releaseDrawingContext()
inline bool GHOST_ContextEGL::bindAPI(EGLenum api) inline bool GHOST_ContextEGL::bindAPI(EGLenum api)
{ {
if (epoxy_egl_version(m_display) >= 12) { if (epoxy_egl_version(display_) >= 12) {
return (EGL_CHK(eglBindAPI(api)) == EGL_TRUE); return (EGL_CHK(eglBindAPI(api)) == EGL_TRUE);
} }
@@ -336,10 +336,10 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
std::vector<EGLint> attrib_list; std::vector<EGLint> attrib_list;
EGLint num_config = 0; EGLint num_config = 0;
if (m_context_params.is_stereo_visual) { if (context_params_.is_stereo_visual) {
fprintf(stderr, "Warning! Stereo OpenGL ES contexts are not supported.\n"); fprintf(stderr, "Warning! Stereo OpenGL ES contexts are not supported.\n");
} }
m_context_params.is_stereo_visual = false; /* It doesn't matter what the Window wants. */ context_params_.is_stereo_visual = false; /* It doesn't matter what the Window wants. */
EGLDisplay prev_display = eglGetCurrentDisplay(); EGLDisplay prev_display = eglGetCurrentDisplay();
EGLSurface prev_draw = eglGetCurrentSurface(EGL_DRAW); EGLSurface prev_draw = eglGetCurrentSurface(EGL_DRAW);
@@ -348,18 +348,18 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
EGLint egl_major = 0, egl_minor = 0; EGLint egl_major = 0, egl_minor = 0;
if (!EGL_CHK((m_display = ::eglGetDisplay(m_nativeDisplay)) != EGL_NO_DISPLAY)) { if (!EGL_CHK((display_ = ::eglGetDisplay(native_display_)) != EGL_NO_DISPLAY)) {
goto error; goto error;
} }
{ {
const EGLBoolean init_display_result = ::eglInitialize(m_display, &egl_major, &egl_minor); const EGLBoolean init_display_result = ::eglInitialize(display_, &egl_major, &egl_minor);
const EGLint init_display_error = (init_display_result) ? 0 : eglGetError(); const EGLint init_display_error = (init_display_result) ? 0 : eglGetError();
if (!init_display_result || (egl_major == 0 && egl_minor == 0)) { if (!init_display_result || (egl_major == 0 && egl_minor == 0)) {
/* We failed to create a regular render window, retry and see if we can create a headless /* We failed to create a regular render window, retry and see if we can create a headless
* render context. */ * render context. */
::eglTerminate(m_display); ::eglTerminate(display_);
const char *egl_extension_st = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); const char *egl_extension_st = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
assert(egl_extension_st != nullptr); assert(egl_extension_st != nullptr);
@@ -375,10 +375,10 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
goto error; goto error;
} }
m_display = eglGetPlatformDisplayEXT( display_ = eglGetPlatformDisplayEXT(
EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, nullptr); EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, nullptr);
const EGLBoolean headless_result = ::eglInitialize(m_display, &egl_major, &egl_minor); const EGLBoolean headless_result = ::eglInitialize(display_, &egl_major, &egl_minor);
const EGLint init_headless_error = (headless_result) ? 0 : eglGetError(); const EGLint init_headless_error = (headless_result) ? 0 : eglGetError();
if (!headless_result) { if (!headless_result) {
@@ -393,10 +393,10 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
fprintf(stderr, "EGL Version %d.%d\n", egl_major, egl_minor); fprintf(stderr, "EGL Version %d.%d\n", egl_major, egl_minor);
#endif #endif
if (!EGL_CHK(::eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))) { if (!EGL_CHK(::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))) {
goto error; goto error;
} }
if (!bindAPI(m_api)) { if (!bindAPI(api_)) {
goto error; goto error;
} }
@@ -404,40 +404,40 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
attrib_list.reserve(20); attrib_list.reserve(20);
if (m_api == EGL_OPENGL_ES_API && epoxy_egl_version(m_display) >= 12) { if (api_ == EGL_OPENGL_ES_API && epoxy_egl_version(display_) >= 12) {
/* According to the spec it seems that you are required to set EGL_RENDERABLE_TYPE, /* According to the spec it seems that you are required to set EGL_RENDERABLE_TYPE,
* but some implementations (ANGLE) do not seem to care. */ * but some implementations (ANGLE) do not seem to care. */
if (m_contextMajorVersion == 1) { if (context_major_version_ == 1) {
attrib_list.push_back(EGL_RENDERABLE_TYPE); attrib_list.push_back(EGL_RENDERABLE_TYPE);
attrib_list.push_back(EGL_OPENGL_ES_BIT); attrib_list.push_back(EGL_OPENGL_ES_BIT);
} }
else if (m_contextMajorVersion == 2) { else if (context_major_version_ == 2) {
attrib_list.push_back(EGL_RENDERABLE_TYPE); attrib_list.push_back(EGL_RENDERABLE_TYPE);
attrib_list.push_back(EGL_OPENGL_ES2_BIT); attrib_list.push_back(EGL_OPENGL_ES2_BIT);
} }
else if (m_contextMajorVersion == 3) { else if (context_major_version_ == 3) {
attrib_list.push_back(EGL_RENDERABLE_TYPE); attrib_list.push_back(EGL_RENDERABLE_TYPE);
attrib_list.push_back(EGL_OPENGL_ES3_BIT_KHR); attrib_list.push_back(EGL_OPENGL_ES3_BIT_KHR);
} }
else { else {
fprintf(stderr, fprintf(stderr,
"Warning! Unable to request an ES context of version %d.%d\n", "Warning! Unable to request an ES context of version %d.%d\n",
m_contextMajorVersion, context_major_version_,
m_contextMinorVersion); context_minor_version_);
} }
if (!((m_contextMajorVersion == 1) || if (!((context_major_version_ == 1) ||
(m_contextMajorVersion == 2 && epoxy_egl_version(m_display) >= 13) || (context_major_version_ == 2 && epoxy_egl_version(display_) >= 13) ||
(m_contextMajorVersion == 3 && (context_major_version_ == 3 &&
epoxy_has_egl_extension(m_display, "KHR_create_context")) || epoxy_has_egl_extension(display_, "KHR_create_context")) ||
(m_contextMajorVersion == 3 && epoxy_egl_version(m_display) >= 15))) (context_major_version_ == 3 && epoxy_egl_version(display_) >= 15)))
{ {
fprintf(stderr, fprintf(stderr,
"Warning! May not be able to create a version %d.%d ES context with version %d.%d " "Warning! May not be able to create a version %d.%d ES context with version %d.%d "
"of EGL\n", "of EGL\n",
m_contextMajorVersion, context_major_version_,
m_contextMinorVersion, context_minor_version_,
egl_major, egl_major,
egl_minor); egl_minor);
} }
@@ -456,7 +456,7 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
attrib_list.push_back(EGL_BLUE_SIZE); attrib_list.push_back(EGL_BLUE_SIZE);
attrib_list.push_back(8); attrib_list.push_back(8);
if (m_nativeWindow == 0) { if (native_window_ == 0) {
/* Off-screen surface. */ /* Off-screen surface. */
attrib_list.push_back(EGL_SURFACE_TYPE); attrib_list.push_back(EGL_SURFACE_TYPE);
attrib_list.push_back(EGL_PBUFFER_BIT); attrib_list.push_back(EGL_PBUFFER_BIT);
@@ -464,7 +464,7 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
attrib_list.push_back(EGL_NONE); attrib_list.push_back(EGL_NONE);
if (!EGL_CHK(::eglChooseConfig(m_display, &(attrib_list[0]), &m_config, 1, &num_config))) { if (!EGL_CHK(::eglChooseConfig(display_, &(attrib_list[0]), &config_, 1, &num_config))) {
goto error; goto error;
} }
@@ -473,7 +473,7 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
goto error; goto error;
} }
if (m_nativeWindow != 0) { if (native_window_ != 0) {
std::vector<EGLint> surface_attrib_list; std::vector<EGLint> surface_attrib_list;
surface_attrib_list.reserve(3); surface_attrib_list.reserve(3);
#ifdef WITH_GHOST_WAYLAND #ifdef WITH_GHOST_WAYLAND
@@ -483,7 +483,7 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
* See #102994. */ * See #102994. */
/* EGL_EXT_present_opaque isn't added to the latest release of epoxy, but is part of the latest /* EGL_EXT_present_opaque isn't added to the latest release of epoxy, but is part of the latest
* EGL https://github.com/KhronosGroup/EGL-Registry/blob/main/api/egl.xml */ * EGL https://github.com/KhronosGroup/EGL-Registry/blob/main/api/egl.xml */
if (epoxy_has_egl_extension(m_display, "EGL_EXT_present_opaque")) { if (epoxy_has_egl_extension(display_, "EGL_EXT_present_opaque")) {
# ifndef EGL_PRESENT_OPAQUE_EXT # ifndef EGL_PRESENT_OPAQUE_EXT
# define EGL_PRESENT_OPAQUE_EXT 0x31DF # define EGL_PRESENT_OPAQUE_EXT 0x31DF
# endif # endif
@@ -493,9 +493,9 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
#endif #endif
surface_attrib_list.push_back(EGL_NONE); surface_attrib_list.push_back(EGL_NONE);
m_surface = ::eglCreateWindowSurface( surface_ = ::eglCreateWindowSurface(
m_display, m_config, m_nativeWindow, surface_attrib_list.data()); display_, config_, native_window_, surface_attrib_list.data());
m_surface_from_native_window = true; surface_from_native_window_ = true;
} }
else { else {
static const EGLint pb_attrib_list[] = { static const EGLint pb_attrib_list[] = {
@@ -505,101 +505,100 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
1, 1,
EGL_NONE, EGL_NONE,
}; };
m_surface = ::eglCreatePbufferSurface(m_display, m_config, pb_attrib_list); surface_ = ::eglCreatePbufferSurface(display_, config_, pb_attrib_list);
} }
if (!EGL_CHK(m_surface != EGL_NO_SURFACE)) { if (!EGL_CHK(surface_ != EGL_NO_SURFACE)) {
goto error; goto error;
} }
attrib_list.clear(); attrib_list.clear();
if (epoxy_egl_version(m_display) >= 15 || if (epoxy_egl_version(display_) >= 15 || epoxy_has_egl_extension(display_, "KHR_create_context"))
epoxy_has_egl_extension(m_display, "KHR_create_context"))
{ {
if (m_api == EGL_OPENGL_API || m_api == EGL_OPENGL_ES_API) { if (api_ == EGL_OPENGL_API || api_ == EGL_OPENGL_ES_API) {
if (m_contextMajorVersion != 0) { if (context_major_version_ != 0) {
attrib_list.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR); attrib_list.push_back(EGL_CONTEXT_MAJOR_VERSION_KHR);
attrib_list.push_back(m_contextMajorVersion); attrib_list.push_back(context_major_version_);
} }
if (m_contextMinorVersion != 0) { if (context_minor_version_ != 0) {
attrib_list.push_back(EGL_CONTEXT_MINOR_VERSION_KHR); attrib_list.push_back(EGL_CONTEXT_MINOR_VERSION_KHR);
attrib_list.push_back(m_contextMinorVersion); attrib_list.push_back(context_minor_version_);
} }
if (m_contextFlags != 0) { if (context_flags_ != 0) {
attrib_list.push_back(EGL_CONTEXT_FLAGS_KHR); attrib_list.push_back(EGL_CONTEXT_FLAGS_KHR);
attrib_list.push_back(m_contextFlags); attrib_list.push_back(context_flags_);
} }
} }
else { else {
if (m_contextMajorVersion != 0 || m_contextMinorVersion != 0) { if (context_major_version_ != 0 || context_minor_version_ != 0) {
fprintf(stderr, fprintf(stderr,
"Warning! Cannot request specific versions of %s contexts.", "Warning! Cannot request specific versions of %s contexts.",
api_string(m_api).c_str()); api_string(api_).c_str());
} }
if (m_contextFlags != 0) { if (context_flags_ != 0) {
fprintf(stderr, "Warning! Flags cannot be set on %s contexts.", api_string(m_api).c_str()); fprintf(stderr, "Warning! Flags cannot be set on %s contexts.", api_string(api_).c_str());
} }
} }
if (m_api == EGL_OPENGL_API) { if (api_ == EGL_OPENGL_API) {
if (m_contextProfileMask != 0) { if (context_profile_mask_ != 0) {
attrib_list.push_back(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR); attrib_list.push_back(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR);
attrib_list.push_back(m_contextProfileMask); attrib_list.push_back(context_profile_mask_);
} }
} }
else { else {
if (m_contextProfileMask != 0) { if (context_profile_mask_ != 0) {
fprintf( fprintf(
stderr, "Warning! Cannot select profile for %s contexts.", api_string(m_api).c_str()); stderr, "Warning! Cannot select profile for %s contexts.", api_string(api_).c_str());
} }
} }
if (m_api == EGL_OPENGL_API || epoxy_egl_version(m_display) >= 15) { if (api_ == EGL_OPENGL_API || epoxy_egl_version(display_) >= 15) {
if (m_contextResetNotificationStrategy != 0) { if (context_reset_notification_strategy_ != 0) {
attrib_list.push_back(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR); attrib_list.push_back(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR);
attrib_list.push_back(m_contextResetNotificationStrategy); attrib_list.push_back(context_reset_notification_strategy_);
} }
} }
else { else {
if (m_contextResetNotificationStrategy != 0) { if (context_reset_notification_strategy_ != 0) {
fprintf(stderr, fprintf(stderr,
"Warning! EGL %d.%d cannot set the reset notification strategy on %s contexts.", "Warning! EGL %d.%d cannot set the reset notification strategy on %s contexts.",
egl_major, egl_major,
egl_minor, egl_minor,
api_string(m_api).c_str()); api_string(api_).c_str());
} }
} }
} }
else { else {
if (m_api == EGL_OPENGL_ES_API) { if (api_ == EGL_OPENGL_ES_API) {
if (m_contextMajorVersion != 0) { if (context_major_version_ != 0) {
attrib_list.push_back(EGL_CONTEXT_CLIENT_VERSION); attrib_list.push_back(EGL_CONTEXT_CLIENT_VERSION);
attrib_list.push_back(m_contextMajorVersion); attrib_list.push_back(context_major_version_);
} }
} }
else { else {
if (m_contextMajorVersion != 0 || m_contextMinorVersion != 0) { if (context_major_version_ != 0 || context_minor_version_ != 0) {
fprintf(stderr, fprintf(stderr,
"Warning! EGL %d.%d is unable to select between versions of %s.", "Warning! EGL %d.%d is unable to select between versions of %s.",
egl_major, egl_major,
egl_minor, egl_minor,
api_string(m_api).c_str()); api_string(api_).c_str());
} }
} }
if (m_contextFlags != 0) { if (context_flags_ != 0) {
fprintf(stderr, "Warning! EGL %d.%d is unable to set context flags.", egl_major, egl_minor); fprintf(stderr, "Warning! EGL %d.%d is unable to set context flags.", egl_major, egl_minor);
} }
if (m_contextProfileMask != 0) { if (context_profile_mask_ != 0) {
fprintf(stderr, fprintf(stderr,
"Warning! EGL %d.%d is unable to select between profiles.", "Warning! EGL %d.%d is unable to select between profiles.",
egl_major, egl_major,
egl_minor); egl_minor);
} }
if (m_contextResetNotificationStrategy != 0) { if (context_reset_notification_strategy_ != 0) {
fprintf(stderr, fprintf(stderr,
"Warning! EGL %d.%d is unable to set the reset notification strategies.", "Warning! EGL %d.%d is unable to set the reset notification strategies.",
egl_major, egl_major,
@@ -609,19 +608,19 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
attrib_list.push_back(EGL_NONE); attrib_list.push_back(EGL_NONE);
m_context = ::eglCreateContext(m_display, m_config, m_sharedContext, &(attrib_list[0])); context_ = ::eglCreateContext(display_, config_, shared_context_, &(attrib_list[0]));
if (!EGL_CHK(m_context != EGL_NO_CONTEXT)) { if (!EGL_CHK(context_ != EGL_NO_CONTEXT)) {
goto error; goto error;
} }
if (m_sharedContext == EGL_NO_CONTEXT) { if (shared_context_ == EGL_NO_CONTEXT) {
m_sharedContext = m_context; shared_context_ = context_;
} }
m_sharedCount++; shared_count_++;
if (!EGL_CHK(::eglMakeCurrent(m_display, m_surface, m_surface, m_context))) { if (!EGL_CHK(::eglMakeCurrent(display_, surface_, surface_, context_))) {
goto error; goto error;
} }
@@ -632,9 +631,9 @@ GHOST_TSuccess GHOST_ContextEGL::initializeDrawingContext()
} }
} }
if (m_nativeWindow != 0) { if (native_window_ != 0) {
initClearGL(); initClearGL();
::eglSwapBuffers(m_display, m_surface); ::eglSwapBuffers(display_, surface_);
} }
active_context_ = this; active_context_ = this;
@@ -649,11 +648,11 @@ error:
GHOST_TSuccess GHOST_ContextEGL::releaseNativeHandles() GHOST_TSuccess GHOST_ContextEGL::releaseNativeHandles()
{ {
m_nativeDisplay = nullptr; native_display_ = nullptr;
m_nativeWindow = 0; native_window_ = 0;
if (m_surface_from_native_window) { if (surface_from_native_window_) {
m_surface = EGL_NO_SURFACE; surface_ = EGL_NO_SURFACE;
} }
return GHOST_kSuccess; return GHOST_kSuccess;

View File

@@ -90,10 +90,10 @@ class GHOST_ContextEGL : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
EGLDisplay getDisplay() const; EGLDisplay getDisplay() const;
@@ -104,33 +104,33 @@ class GHOST_ContextEGL : public GHOST_Context {
private: private:
bool bindAPI(EGLenum api); bool bindAPI(EGLenum api);
const GHOST_System *const m_system; const GHOST_System *const system_;
EGLNativeDisplayType m_nativeDisplay; EGLNativeDisplayType native_display_;
EGLNativeWindowType m_nativeWindow; EGLNativeWindowType native_window_;
const EGLint m_contextProfileMask; const EGLint context_profile_mask_;
const EGLint m_contextMajorVersion; const EGLint context_major_version_;
const EGLint m_contextMinorVersion; const EGLint context_minor_version_;
const EGLint m_contextFlags; const EGLint context_flags_;
const EGLint m_contextResetNotificationStrategy; const EGLint context_reset_notification_strategy_;
const EGLenum m_api; const EGLenum api_;
EGLContext m_context; EGLContext context_;
EGLSurface m_surface; EGLSurface surface_;
EGLDisplay m_display; EGLDisplay display_;
EGLConfig m_config; EGLConfig config_;
EGLint m_swap_interval; EGLint swap_interval_;
EGLContext &m_sharedContext; EGLContext &shared_context_;
EGLint &m_sharedCount; EGLint &shared_count_;
/** /**
* True when the surface is created from `m_nativeWindow`. * True when the surface is created from `native_window_`.
*/ */
bool m_surface_from_native_window; bool surface_from_native_window_;
static EGLContext s_gl_sharedContext; static EGLContext s_gl_sharedContext;
static EGLint s_gl_sharedCount; static EGLint s_gl_sharedCount;

View File

@@ -38,27 +38,27 @@ GHOST_ContextGLX::GHOST_ContextGLX(const GHOST_ContextParams &context_params,
int contextFlags, int contextFlags,
int contextResetNotificationStrategy) int contextResetNotificationStrategy)
: GHOST_Context(context_params), : GHOST_Context(context_params),
m_display(display), display_(display),
m_fbconfig(fbconfig), fbconfig_(fbconfig),
m_window(window), window_(window),
m_contextProfileMask(contextProfileMask), context_profile_mask_(contextProfileMask),
m_contextMajorVersion(contextMajorVersion), context_major_version_(contextMajorVersion),
m_contextMinorVersion(contextMinorVersion), context_minor_version_(contextMinorVersion),
m_contextFlags(contextFlags), context_flags_(contextFlags),
m_contextResetNotificationStrategy(contextResetNotificationStrategy), context_reset_notification_strategy_(contextResetNotificationStrategy),
m_context(None) context_(None)
{ {
assert(m_display != nullptr); assert(display_ != nullptr);
} }
GHOST_ContextGLX::~GHOST_ContextGLX() GHOST_ContextGLX::~GHOST_ContextGLX()
{ {
if (m_display != nullptr) { if (display_ != nullptr) {
if (m_context != None) { if (context_ != None) {
if (m_window != 0 && m_context == ::glXGetCurrentContext()) { if (window_ != 0 && context_ == ::glXGetCurrentContext()) {
::glXMakeCurrent(m_display, None, nullptr); ::glXMakeCurrent(display_, None, nullptr);
} }
if (m_context != s_sharedContext || s_sharedCount == 1) { if (context_ != s_sharedContext || s_sharedCount == 1) {
assert(s_sharedCount > 0); assert(s_sharedCount > 0);
s_sharedCount--; s_sharedCount--;
@@ -67,7 +67,7 @@ GHOST_ContextGLX::~GHOST_ContextGLX()
s_sharedContext = nullptr; s_sharedContext = nullptr;
} }
::glXDestroyContext(m_display, m_context); ::glXDestroyContext(display_, context_);
} }
} }
} }
@@ -75,27 +75,27 @@ GHOST_ContextGLX::~GHOST_ContextGLX()
GHOST_TSuccess GHOST_ContextGLX::swapBuffers() GHOST_TSuccess GHOST_ContextGLX::swapBuffers()
{ {
::glXSwapBuffers(m_display, m_window); ::glXSwapBuffers(display_, window_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextGLX::activateDrawingContext() GHOST_TSuccess GHOST_ContextGLX::activateDrawingContext()
{ {
if (m_display == nullptr) { if (display_ == nullptr) {
return GHOST_kFailure; return GHOST_kFailure;
} }
active_context_ = this; active_context_ = this;
return ::glXMakeCurrent(m_display, m_window, m_context) ? GHOST_kSuccess : GHOST_kFailure; return ::glXMakeCurrent(display_, window_, context_) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextGLX::releaseDrawingContext() GHOST_TSuccess GHOST_ContextGLX::releaseDrawingContext()
{ {
if (m_display == nullptr) { if (display_ == nullptr) {
return GHOST_kFailure; return GHOST_kFailure;
} }
active_context_ = nullptr; active_context_ = nullptr;
return ::glXMakeCurrent(m_display, None, nullptr) ? GHOST_kSuccess : GHOST_kFailure; return ::glXMakeCurrent(display_, None, nullptr) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext() GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
@@ -108,8 +108,8 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
#ifdef USE_GLXEW_INIT_WORKAROUND #ifdef USE_GLXEW_INIT_WORKAROUND
const GLubyte *extStart = (GLubyte *)""; const GLubyte *extStart = (GLubyte *)"";
const GLubyte *extEnd; const GLubyte *extEnd;
if (glXQueryExtension(m_display, nullptr, nullptr)) { if (glXQueryExtension(display_, nullptr, nullptr)) {
extStart = (const GLubyte *)glXGetClientString(m_display, GLX_EXTENSIONS); extStart = (const GLubyte *)glXGetClientString(display_, GLX_EXTENSIONS);
if ((extStart == nullptr) || if ((extStart == nullptr) ||
(glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddressARB( (glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddressARB(
(const GLubyte *)"glXChooseFBConfig")) == nullptr || (const GLubyte *)"glXChooseFBConfig")) == nullptr ||
@@ -150,11 +150,11 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
#endif /* USE_GLXEW_INIT_WORKAROUND */ #endif /* USE_GLXEW_INIT_WORKAROUND */
if (GLXEW_ARB_create_context) { if (GLXEW_ARB_create_context) {
int profileBitCore = m_contextProfileMask & GLX_CONTEXT_CORE_PROFILE_BIT_ARB; int profileBitCore = context_profile_mask_ & GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
int profileBitCompat = m_contextProfileMask & GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; int profileBitCompat = context_profile_mask_ & GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
#ifdef WITH_GLEW_ES #ifdef WITH_GLEW_ES
int profileBitES = m_contextProfileMask & GLX_CONTEXT_ES_PROFILE_BIT_EXT; int profileBitES = context_profile_mask_ & GLX_CONTEXT_ES_PROFILE_BIT_EXT;
#endif #endif
if (!GLXEW_ARB_create_context_profile && profileBitCore) { if (!GLXEW_ARB_create_context_profile && profileBitCore) {
@@ -165,11 +165,11 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
} }
#ifdef WITH_GLEW_ES #ifdef WITH_GLEW_ES
if (!GLXEW_EXT_create_context_es_profile && profileBitES && m_contextMajorVersion == 1) { if (!GLXEW_EXT_create_context_es_profile && profileBitES && context_major_version_ == 1) {
fprintf(stderr, "Warning! OpenGL ES profile not available.\n"); fprintf(stderr, "Warning! OpenGL ES profile not available.\n");
} }
if (!GLXEW_EXT_create_context_es2_profile && profileBitES && m_contextMajorVersion == 2) { if (!GLXEW_EXT_create_context_es2_profile && profileBitES && context_major_version_ == 2) {
fprintf(stderr, "Warning! OpenGL ES2 profile not available.\n"); fprintf(stderr, "Warning! OpenGL ES2 profile not available.\n");
} }
#endif #endif
@@ -189,7 +189,7 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
} }
#endif #endif
if (profileMask != m_contextProfileMask) { if (profileMask != context_profile_mask_) {
fprintf(stderr, "Warning! Ignoring untested OpenGL context profile mask bits."); fprintf(stderr, "Warning! Ignoring untested OpenGL context profile mask bits.");
} }
/* max 10 attributes plus terminator */ /* max 10 attributes plus terminator */
@@ -201,22 +201,22 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
attribs[i++] = profileMask; attribs[i++] = profileMask;
} }
if (m_contextMajorVersion != 0) { if (context_major_version_ != 0) {
attribs[i++] = GLX_CONTEXT_MAJOR_VERSION_ARB; attribs[i++] = GLX_CONTEXT_MAJOR_VERSION_ARB;
attribs[i++] = m_contextMajorVersion; attribs[i++] = context_major_version_;
attribs[i++] = GLX_CONTEXT_MINOR_VERSION_ARB; attribs[i++] = GLX_CONTEXT_MINOR_VERSION_ARB;
attribs[i++] = m_contextMinorVersion; attribs[i++] = context_minor_version_;
} }
if (m_contextFlags != 0) { if (context_flags_ != 0) {
attribs[i++] = GLX_CONTEXT_FLAGS_ARB; attribs[i++] = GLX_CONTEXT_FLAGS_ARB;
attribs[i++] = m_contextFlags; attribs[i++] = context_flags_;
} }
if (m_contextResetNotificationStrategy != 0) { if (context_reset_notification_strategy_ != 0) {
if (GLXEW_ARB_create_context_robustness) { if (GLXEW_ARB_create_context_robustness) {
attribs[i++] = GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB; attribs[i++] = GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB;
attribs[i++] = m_contextResetNotificationStrategy; attribs[i++] = context_reset_notification_strategy_;
} }
else { else {
fprintf(stderr, "Warning! Cannot set the reset notification strategy."); fprintf(stderr, "Warning! Cannot set the reset notification strategy.");
@@ -230,12 +230,11 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
int pbuffer_attribs[] = {GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, None}; int pbuffer_attribs[] = {GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, None};
/* Create a GL 3.x context */ /* Create a GL 3.x context */
if (m_fbconfig) { if (fbconfig_) {
m_context = glXCreateContextAttribsARB( context_ = glXCreateContextAttribsARB(display_, fbconfig_, s_sharedContext, true, attribs);
m_display, m_fbconfig, s_sharedContext, true, attribs);
if (!m_window) { if (!window_) {
m_window = (Window)glXCreatePbuffer(m_display, m_fbconfig, pbuffer_attribs); window_ = (Window)glXCreatePbuffer(display_, fbconfig_, pbuffer_attribs);
} }
} }
else { else {
@@ -244,22 +243,21 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
int glx_attribs[64]; int glx_attribs[64];
int fbcount = 0; int fbcount = 0;
GHOST_X11_GL_GetAttributes( GHOST_X11_GL_GetAttributes(glx_attribs, 64, context_params_.is_stereo_visual, false, true);
glx_attribs, 64, m_context_params.is_stereo_visual, false, true);
framebuffer_config = glXChooseFBConfig( framebuffer_config = glXChooseFBConfig(
m_display, DefaultScreen(m_display), glx_attribs, &fbcount); display_, DefaultScreen(display_), glx_attribs, &fbcount);
} }
if (framebuffer_config) { if (framebuffer_config) {
m_context = glXCreateContextAttribsARB( context_ = glXCreateContextAttribsARB(
m_display, framebuffer_config[0], s_sharedContext, True, attribs); display_, framebuffer_config[0], s_sharedContext, True, attribs);
if (!m_window) { if (!window_) {
m_window = (Window)glXCreatePbuffer(m_display, framebuffer_config[0], pbuffer_attribs); window_ = (Window)glXCreatePbuffer(display_, framebuffer_config[0], pbuffer_attribs);
} }
m_fbconfig = framebuffer_config[0]; fbconfig_ = framebuffer_config[0];
XFree(framebuffer_config); XFree(framebuffer_config);
} }
} }
@@ -271,15 +269,15 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_context != nullptr) { if (context_ != nullptr) {
const uchar *version; const uchar *version;
if (!s_sharedContext) { if (!s_sharedContext) {
s_sharedContext = m_context; s_sharedContext = context_;
} }
s_sharedCount++; s_sharedCount++;
glXMakeCurrent(m_display, m_window, m_context); glXMakeCurrent(display_, window_, context_);
/* For performance measurements with VSync disabled. */ /* For performance measurements with VSync disabled. */
{ {
@@ -289,9 +287,9 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
} }
} }
if (m_window) { if (window_) {
initClearGL(); initClearGL();
::glXSwapBuffers(m_display, m_window); ::glXSwapBuffers(display_, window_);
} }
version = glGetString(GL_VERSION); version = glGetString(GL_VERSION);
@@ -316,28 +314,28 @@ GHOST_TSuccess GHOST_ContextGLX::initializeDrawingContext()
GHOST_TSuccess GHOST_ContextGLX::releaseNativeHandles() GHOST_TSuccess GHOST_ContextGLX::releaseNativeHandles()
{ {
m_window = 0; window_ = 0;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextGLX::setSwapInterval(int interval) GHOST_TSuccess GHOST_ContextGLX::setSwapInterval(int interval)
{ {
if (epoxy_has_glx_extension(m_display, DefaultScreen(m_display), "GLX_EXT_swap_control")) { if (epoxy_has_glx_extension(display_, DefaultScreen(display_), "GLX_EXT_swap_control")) {
::glXSwapIntervalEXT(m_display, m_window, interval); ::glXSwapIntervalEXT(display_, window_, interval);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextGLX::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextGLX::getSwapInterval(int &interval_out)
{ {
if (epoxy_has_glx_extension(m_display, DefaultScreen(m_display), "GLX_EXT_swap_control")) { if (epoxy_has_glx_extension(display_, DefaultScreen(display_), "GLX_EXT_swap_control")) {
uint interval = 0; uint interval = 0;
::glXQueryDrawable(m_display, m_window, GLX_SWAP_INTERVAL_EXT, &interval); ::glXQueryDrawable(display_, window_, GLX_SWAP_INTERVAL_EXT, &interval);
intervalOut = int(interval); interval_out = int(interval);
return GHOST_kSuccess; return GHOST_kSuccess;
} }

View File

@@ -84,23 +84,23 @@ class GHOST_ContextGLX : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
private: private:
Display *m_display; Display *display_;
GLXFBConfig m_fbconfig; GLXFBConfig fbconfig_;
Window m_window; Window window_;
const int m_contextProfileMask; const int context_profile_mask_;
const int m_contextMajorVersion; const int context_major_version_;
const int m_contextMinorVersion; const int context_minor_version_;
const int m_contextFlags; const int context_flags_;
const int m_contextResetNotificationStrategy; const int context_reset_notification_strategy_;
GLXContext m_context; GLXContext context_;
/** The first created OpenGL context (for sharing display lists) */ /** The first created OpenGL context (for sharing display lists) */
static GLXContext s_sharedContext; static GLXContext s_sharedContext;

View File

@@ -92,10 +92,10 @@ class GHOST_ContextMTL : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
/** /**
* Updates the drawing context of this window. * Updates the drawing context of this window.
@@ -129,15 +129,15 @@ class GHOST_ContextMTL : public GHOST_Context {
private: private:
/** Metal state */ /** Metal state */
NSView *m_metalView; NSView *metal_view_;
CAMetalLayer *m_metalLayer; CAMetalLayer *metal_layer_;
MTLRenderPipelineState *m_metalRenderPipeline; MTLRenderPipelineState *metal_render_pipeline_;
bool m_ownsMetalDevice; bool owns_metal_device_;
/** The virtualized default frame-buffer's texture. */ /** The virtualized default frame-buffer's texture. */
/** /**
* Texture that you can render into with Metal. The texture will be * Texture that you can render into with Metal. The texture will be
* composited on top of `m_defaultFramebufferMetalTexture` whenever * composited on top of `default_framebuffer_metal_texture_` whenever
* `swapBuffers` is called. * `swapBuffers` is called.
*/ */
static const int METAL_SWAPCHAIN_SIZE = 3; static const int METAL_SWAPCHAIN_SIZE = 3;
@@ -145,7 +145,7 @@ class GHOST_ContextMTL : public GHOST_Context {
id<MTLTexture> texture; id<MTLTexture> texture;
unsigned int index; unsigned int index;
}; };
MTLSwapchainTexture m_defaultFramebufferMetalTexture[METAL_SWAPCHAIN_SIZE]; MTLSwapchainTexture default_framebuffer_metal_texture_[METAL_SWAPCHAIN_SIZE];
unsigned int current_swapchain_index = 0; unsigned int current_swapchain_index = 0;
/* Present callback. /* Present callback.

View File

@@ -50,46 +50,46 @@ GHOST_ContextMTL::GHOST_ContextMTL(const GHOST_ContextParams &context_params,
NSView *metalView, NSView *metalView,
CAMetalLayer *metalLayer) CAMetalLayer *metalLayer)
: GHOST_Context(context_params), : GHOST_Context(context_params),
m_metalView(metalView), metal_view_(metalView),
m_metalLayer(metalLayer), metal_layer_(metalLayer),
m_metalRenderPipeline(nil) metal_render_pipeline_(nil)
{ {
@autoreleasepool { @autoreleasepool {
/* Initialize Metal Swap-chain. */ /* Initialize Metal Swap-chain. */
current_swapchain_index = 0; current_swapchain_index = 0;
for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) { for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) {
m_defaultFramebufferMetalTexture[i].texture = nil; default_framebuffer_metal_texture_[i].texture = nil;
m_defaultFramebufferMetalTexture[i].index = i; default_framebuffer_metal_texture_[i].index = i;
} }
if (m_metalView) { if (metal_view_) {
m_ownsMetalDevice = false; owns_metal_device_ = false;
metalInit(); metalInit();
} }
else { else {
/* Prepare offscreen GHOST Context Metal device. */ /* Prepare offscreen GHOST Context Metal device. */
id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice(); id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice();
if (m_context_params.is_debug) { if (context_params_.is_debug) {
printf("Selected Metal Device: %s\n", [metalDevice.name UTF8String]); printf("Selected Metal Device: %s\n", [metalDevice.name UTF8String]);
} }
m_ownsMetalDevice = true; owns_metal_device_ = true;
if (metalDevice) { if (metalDevice) {
m_metalLayer = [[CAMetalLayer alloc] init]; metal_layer_ = [[CAMetalLayer alloc] init];
m_metalLayer.edgeAntialiasingMask = 0; metal_layer_.edgeAntialiasingMask = 0;
m_metalLayer.masksToBounds = NO; metal_layer_.masksToBounds = NO;
m_metalLayer.opaque = YES; metal_layer_.opaque = YES;
m_metalLayer.framebufferOnly = YES; metal_layer_.framebufferOnly = YES;
m_metalLayer.presentsWithTransaction = NO; metal_layer_.presentsWithTransaction = NO;
[m_metalLayer removeAllAnimations]; [metal_layer_ removeAllAnimations];
m_metalLayer.device = metalDevice; metal_layer_.device = metalDevice;
m_metalLayer.allowsNextDrawableTimeout = NO; metal_layer_.allowsNextDrawableTimeout = NO;
{ {
const GHOST_TVSyncModes vsync = getVSync(); const GHOST_TVSyncModes vsync = getVSync();
if (vsync != GHOST_kVSyncModeUnset) { if (vsync != GHOST_kVSyncModeUnset) {
m_metalLayer.displaySyncEnabled = (vsync == GHOST_kVSyncModeOff) ? NO : YES; metal_layer_.displaySyncEnabled = (vsync == GHOST_kVSyncModeOff) ? NO : YES;
} }
} }
@@ -99,11 +99,11 @@ GHOST_ContextMTL::GHOST_ContextMTL(const GHOST_ContextParams &context_params,
* 3. Setting the extended sRGB color space so that the OS knows how to interpret the * 3. Setting the extended sRGB color space so that the OS knows how to interpret the
* values. * values.
*/ */
m_metalLayer.wantsExtendedDynamicRangeContent = YES; metal_layer_.wantsExtendedDynamicRangeContent = YES;
m_metalLayer.pixelFormat = METAL_FRAMEBUFFERPIXEL_FORMAT_EDR; metal_layer_.pixelFormat = METAL_FRAMEBUFFERPIXEL_FORMAT_EDR;
const CFStringRef name = kCGColorSpaceExtendedSRGB; const CFStringRef name = kCGColorSpaceExtendedSRGB;
CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name); CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name);
m_metalLayer.colorspace = colorspace; metal_layer_.colorspace = colorspace;
CGColorSpaceRelease(colorspace); CGColorSpaceRelease(colorspace);
metalInit(); metalInit();
@@ -123,10 +123,10 @@ GHOST_ContextMTL::~GHOST_ContextMTL()
{ {
metalFree(); metalFree();
if (m_ownsMetalDevice) { if (owns_metal_device_) {
if (m_metalLayer) { if (metal_layer_) {
[m_metalLayer release]; [metal_layer_ release];
m_metalLayer = nil; metal_layer_ = nil;
} }
} }
assert(s_sharedCount); assert(s_sharedCount);
@@ -140,7 +140,7 @@ GHOST_ContextMTL::~GHOST_ContextMTL()
GHOST_TSuccess GHOST_ContextMTL::swapBuffers() GHOST_TSuccess GHOST_ContextMTL::swapBuffers()
{ {
if (m_metalView) { if (metal_view_) {
metalSwapBuffers(); metalSwapBuffers();
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -152,9 +152,9 @@ GHOST_TSuccess GHOST_ContextMTL::setSwapInterval(int interval)
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextMTL::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextMTL::getSwapInterval(int &interval_out)
{ {
intervalOut = mtl_SwapInterval; interval_out = mtl_SwapInterval;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -178,7 +178,7 @@ unsigned int GHOST_ContextMTL::getDefaultFramebuffer()
GHOST_TSuccess GHOST_ContextMTL::updateDrawingContext() GHOST_TSuccess GHOST_ContextMTL::updateDrawingContext()
{ {
if (m_metalView) { if (metal_view_) {
metalUpdateFramebuffer(); metalUpdateFramebuffer();
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -194,7 +194,7 @@ id<MTLTexture> GHOST_ContextMTL::metalOverlayTexture()
updateDrawingContext(); updateDrawingContext();
/* Return texture. */ /* Return texture. */
return m_defaultFramebufferMetalTexture[current_swapchain_index].texture; return default_framebuffer_metal_texture_[current_swapchain_index].texture;
} }
MTLCommandQueue *GHOST_ContextMTL::metalCommandQueue() MTLCommandQueue *GHOST_ContextMTL::metalCommandQueue()
@@ -203,7 +203,7 @@ MTLCommandQueue *GHOST_ContextMTL::metalCommandQueue()
} }
MTLDevice *GHOST_ContextMTL::metalDevice() MTLDevice *GHOST_ContextMTL::metalDevice()
{ {
id<MTLDevice> device = m_metalLayer.device; id<MTLDevice> device = metal_layer_.device;
return (MTLDevice *)device; return (MTLDevice *)device;
} }
@@ -216,7 +216,7 @@ void GHOST_ContextMTL::metalRegisterPresentCallback(void (*callback)(
GHOST_TSuccess GHOST_ContextMTL::initializeDrawingContext() GHOST_TSuccess GHOST_ContextMTL::initializeDrawingContext()
{ {
@autoreleasepool { @autoreleasepool {
if (m_metalView) { if (metal_view_) {
metalInitFramebuffer(); metalInitFramebuffer();
} }
} }
@@ -226,7 +226,7 @@ GHOST_TSuccess GHOST_ContextMTL::initializeDrawingContext()
GHOST_TSuccess GHOST_ContextMTL::releaseNativeHandles() GHOST_TSuccess GHOST_ContextMTL::releaseNativeHandles()
{ {
m_metalView = nil; metal_view_ = nil;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -234,7 +234,7 @@ GHOST_TSuccess GHOST_ContextMTL::releaseNativeHandles()
void GHOST_ContextMTL::metalInit() void GHOST_ContextMTL::metalInit()
{ {
@autoreleasepool { @autoreleasepool {
id<MTLDevice> device = m_metalLayer.device; id<MTLDevice> device = metal_layer_.device;
/* Create a command queue for blit/present operation. /* Create a command queue for blit/present operation.
* NOTE: All context should share a single command queue * NOTE: All context should share a single command queue
@@ -303,7 +303,7 @@ void GHOST_ContextMTL::metalInit()
/* Ensure library is released. */ /* Ensure library is released. */
[library autorelease]; [library autorelease];
m_metalRenderPipeline = (MTLRenderPipelineState *)[device metal_render_pipeline_ = (MTLRenderPipelineState *)[device
newRenderPipelineStateWithDescriptor:desc newRenderPipelineStateWithDescriptor:desc
error:&error]; error:&error];
if (error) { if (error) {
@@ -332,15 +332,15 @@ void GHOST_ContextMTL::metalInit()
void GHOST_ContextMTL::metalFree() void GHOST_ContextMTL::metalFree()
{ {
if (m_metalRenderPipeline) { if (metal_render_pipeline_) {
[m_metalRenderPipeline release]; [metal_render_pipeline_ release];
m_metalRenderPipeline = nil; metal_render_pipeline_ = nil;
} }
for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) { for (int i = 0; i < METAL_SWAPCHAIN_SIZE; i++) {
if (m_defaultFramebufferMetalTexture[i].texture) { if (default_framebuffer_metal_texture_[i].texture) {
[m_defaultFramebufferMetalTexture[i].texture release]; [default_framebuffer_metal_texture_[i].texture release];
m_defaultFramebufferMetalTexture[i].texture = nil; default_framebuffer_metal_texture_[i].texture = nil;
} }
} }
} }
@@ -353,22 +353,22 @@ void GHOST_ContextMTL::metalInitFramebuffer()
void GHOST_ContextMTL::metalUpdateFramebuffer() void GHOST_ContextMTL::metalUpdateFramebuffer()
{ {
@autoreleasepool { @autoreleasepool {
const NSRect bounds = [m_metalView bounds]; const NSRect bounds = [metal_view_ bounds];
const NSSize backingSize = [m_metalView convertSizeToBacking:bounds.size]; const NSSize backingSize = [metal_view_ convertSizeToBacking:bounds.size];
const size_t width = size_t(backingSize.width); const size_t width = size_t(backingSize.width);
const size_t height = size_t(backingSize.height); const size_t height = size_t(backingSize.height);
if (m_defaultFramebufferMetalTexture[current_swapchain_index].texture && if (default_framebuffer_metal_texture_[current_swapchain_index].texture &&
m_defaultFramebufferMetalTexture[current_swapchain_index].texture.width == width && default_framebuffer_metal_texture_[current_swapchain_index].texture.width == width &&
m_defaultFramebufferMetalTexture[current_swapchain_index].texture.height == height) default_framebuffer_metal_texture_[current_swapchain_index].texture.height == height)
{ {
return; return;
} }
/* Free old texture */ /* Free old texture */
[m_defaultFramebufferMetalTexture[current_swapchain_index].texture release]; [default_framebuffer_metal_texture_[current_swapchain_index].texture release];
id<MTLDevice> device = m_metalLayer.device; id<MTLDevice> device = metal_layer_.device;
MTLTextureDescriptor *overlayDesc = [MTLTextureDescriptor MTLTextureDescriptor *overlayDesc = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:METAL_FRAMEBUFFERPIXEL_FORMAT_EDR texture2DDescriptorWithPixelFormat:METAL_FRAMEBUFFERPIXEL_FORMAT_EDR
width:width width:width
@@ -387,14 +387,14 @@ void GHOST_ContextMTL::metalUpdateFramebuffer()
stringWithFormat:@"Metal Overlay for GHOST Context %p", this]; //@""; stringWithFormat:@"Metal Overlay for GHOST Context %p", this]; //@"";
} }
m_defaultFramebufferMetalTexture[current_swapchain_index].texture = overlayTex; default_framebuffer_metal_texture_[current_swapchain_index].texture = overlayTex;
/* Clear texture on create */ /* Clear texture on create */
id<MTLCommandBuffer> cmdBuffer = [s_sharedMetalCommandQueue commandBuffer]; id<MTLCommandBuffer> cmdBuffer = [s_sharedMetalCommandQueue commandBuffer];
MTLRenderPassDescriptor *passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; MTLRenderPassDescriptor *passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor];
{ {
auto attachment = [passDescriptor.colorAttachments objectAtIndexedSubscript:0]; auto attachment = [passDescriptor.colorAttachments objectAtIndexedSubscript:0];
attachment.texture = m_defaultFramebufferMetalTexture[current_swapchain_index].texture; attachment.texture = default_framebuffer_metal_texture_[current_swapchain_index].texture;
attachment.loadAction = MTLLoadActionClear; attachment.loadAction = MTLLoadActionClear;
attachment.clearColor = MTLClearColorMake(0.294, 0.294, 0.294, 1.000); attachment.clearColor = MTLClearColorMake(0.294, 0.294, 0.294, 1.000);
attachment.storeAction = MTLStoreActionStore; attachment.storeAction = MTLStoreActionStore;
@@ -406,7 +406,7 @@ void GHOST_ContextMTL::metalUpdateFramebuffer()
} }
[cmdBuffer commit]; [cmdBuffer commit];
m_metalLayer.drawableSize = CGSizeMake(CGFloat(width), CGFloat(height)); metal_layer_.drawableSize = CGSizeMake(CGFloat(width), CGFloat(height));
} }
} }
@@ -415,7 +415,7 @@ void GHOST_ContextMTL::metalSwapBuffers()
@autoreleasepool { @autoreleasepool {
updateDrawingContext(); updateDrawingContext();
id<CAMetalDrawable> drawable = [m_metalLayer nextDrawable]; id<CAMetalDrawable> drawable = [metal_layer_ nextDrawable];
if (!drawable) { if (!drawable) {
return; return;
} }
@@ -430,10 +430,10 @@ void GHOST_ContextMTL::metalSwapBuffers()
} }
assert(contextPresentCallback); assert(contextPresentCallback);
assert(m_defaultFramebufferMetalTexture[current_swapchain_index].texture != nil); assert(default_framebuffer_metal_texture_[current_swapchain_index].texture != nil);
(*contextPresentCallback)(passDescriptor, (*contextPresentCallback)(passDescriptor,
(id<MTLRenderPipelineState>)m_metalRenderPipeline, (id<MTLRenderPipelineState>)metal_render_pipeline_,
m_defaultFramebufferMetalTexture[current_swapchain_index].texture, default_framebuffer_metal_texture_[current_swapchain_index].texture,
drawable); drawable);
} }
} }

View File

@@ -45,13 +45,13 @@ GHOST_TSuccess GHOST_ContextNone::releaseNativeHandles()
GHOST_TSuccess GHOST_ContextNone::setSwapInterval(int interval) GHOST_TSuccess GHOST_ContextNone::setSwapInterval(int interval)
{ {
m_swapInterval = interval; swap_interval_ = interval;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextNone::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextNone::getSwapInterval(int &interval_out)
{ {
intervalOut = m_swapInterval; interval_out = swap_interval_;
return GHOST_kSuccess; return GHOST_kSuccess;
} }

View File

@@ -60,11 +60,11 @@ class GHOST_ContextNone : public GHOST_Context {
/** /**
* Dummy function * Dummy function
* \param intervalOut: Gets whatever was set by #setSwapInterval. * \param interval_out: Gets whatever was set by #setSwapInterval.
* \return Always succeeds. * \return Always succeeds.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
private: private:
int m_swapInterval = 1; int swap_interval_ = 1;
}; };

View File

@@ -24,28 +24,28 @@ GHOST_ContextSDL::GHOST_ContextSDL(const GHOST_ContextParams &context_params,
int contextFlags, int contextFlags,
int contextResetNotificationStrategy) int contextResetNotificationStrategy)
: GHOST_Context(context_params), : GHOST_Context(context_params),
m_window(window), window_(window),
m_hidden_window(nullptr), hidden_window_(nullptr),
m_contextProfileMask(contextProfileMask), context_profile_mask_(contextProfileMask),
m_contextMajorVersion(contextMajorVersion), context_major_version_(contextMajorVersion),
m_contextMinorVersion(contextMinorVersion), context_minor_version_(contextMinorVersion),
m_contextFlags(contextFlags), context_flags_(contextFlags),
m_contextResetNotificationStrategy(contextResetNotificationStrategy), context_reset_notification_strategy_(contextResetNotificationStrategy),
m_context(nullptr) context_(nullptr)
{ {
// assert(m_window != nullptr); // assert(window_ != nullptr);
} }
GHOST_ContextSDL::~GHOST_ContextSDL() GHOST_ContextSDL::~GHOST_ContextSDL()
{ {
if (m_context == nullptr) { if (context_ == nullptr) {
return; return;
} }
if (m_window != nullptr && m_context == SDL_GL_GetCurrentContext()) { if (window_ != nullptr && context_ == SDL_GL_GetCurrentContext()) {
SDL_GL_MakeCurrent(m_window, nullptr); SDL_GL_MakeCurrent(window_, nullptr);
} }
if (m_context != s_sharedContext || s_sharedCount == 1) { if (context_ != s_sharedContext || s_sharedCount == 1) {
assert(s_sharedCount > 0); assert(s_sharedCount > 0);
s_sharedCount--; s_sharedCount--;
@@ -53,33 +53,33 @@ GHOST_ContextSDL::~GHOST_ContextSDL()
if (s_sharedCount == 0) { if (s_sharedCount == 0) {
s_sharedContext = nullptr; s_sharedContext = nullptr;
} }
SDL_GL_DeleteContext(m_context); SDL_GL_DeleteContext(context_);
} }
if (m_hidden_window != nullptr) { if (hidden_window_ != nullptr) {
SDL_DestroyWindow(m_hidden_window); SDL_DestroyWindow(hidden_window_);
} }
} }
GHOST_TSuccess GHOST_ContextSDL::swapBuffers() GHOST_TSuccess GHOST_ContextSDL::swapBuffers()
{ {
SDL_GL_SwapWindow(m_window); SDL_GL_SwapWindow(window_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextSDL::activateDrawingContext() GHOST_TSuccess GHOST_ContextSDL::activateDrawingContext()
{ {
if (m_context == nullptr) { if (context_ == nullptr) {
return GHOST_kFailure; return GHOST_kFailure;
} }
active_context_ = this; active_context_ = this;
return SDL_GL_MakeCurrent(m_window, m_context) ? GHOST_kSuccess : GHOST_kFailure; return SDL_GL_MakeCurrent(window_, context_) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextSDL::releaseDrawingContext() GHOST_TSuccess GHOST_ContextSDL::releaseDrawingContext()
{ {
if (m_context == nullptr) { if (context_ == nullptr) {
return GHOST_kFailure; return GHOST_kFailure;
} }
active_context_ = nullptr; active_context_ = nullptr;
@@ -91,10 +91,10 @@ GHOST_TSuccess GHOST_ContextSDL::initializeDrawingContext()
{ {
const bool needAlpha = false; const bool needAlpha = false;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, m_contextProfileMask); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, context_profile_mask_);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, m_contextMajorVersion); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, context_major_version_);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, m_contextMinorVersion); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, context_minor_version_);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, m_contextFlags); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, context_flags_);
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
@@ -106,33 +106,33 @@ GHOST_TSuccess GHOST_ContextSDL::initializeDrawingContext()
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
} }
if (m_context_params.is_stereo_visual) { if (context_params_.is_stereo_visual) {
SDL_GL_SetAttribute(SDL_GL_STEREO, 1); SDL_GL_SetAttribute(SDL_GL_STEREO, 1);
} }
if (m_window == nullptr) { if (window_ == nullptr) {
m_hidden_window = SDL_CreateWindow("Offscreen Context Windows", hidden_window_ = SDL_CreateWindow("Offscreen Context Windows",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
1, 1,
1, 1,
SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS |
SDL_WINDOW_HIDDEN); SDL_WINDOW_HIDDEN);
m_window = m_hidden_window; window_ = hidden_window_;
} }
m_context = SDL_GL_CreateContext(m_window); context_ = SDL_GL_CreateContext(window_);
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_context != nullptr) { if (context_ != nullptr) {
if (!s_sharedContext) { if (!s_sharedContext) {
s_sharedContext = m_context; s_sharedContext = context_;
} }
s_sharedCount++; s_sharedCount++;
success = (SDL_GL_MakeCurrent(m_window, m_context) < 0) ? GHOST_kFailure : GHOST_kSuccess; success = (SDL_GL_MakeCurrent(window_, context_) < 0) ? GHOST_kFailure : GHOST_kSuccess;
{ {
const GHOST_TVSyncModes vsync = getVSync(); const GHOST_TVSyncModes vsync = getVSync();
@@ -142,7 +142,7 @@ GHOST_TSuccess GHOST_ContextSDL::initializeDrawingContext()
} }
initClearGL(); initClearGL();
SDL_GL_SwapWindow(m_window); SDL_GL_SwapWindow(window_);
active_context_ = this; active_context_ = this;
success = GHOST_kSuccess; success = GHOST_kSuccess;
@@ -156,7 +156,7 @@ GHOST_TSuccess GHOST_ContextSDL::initializeDrawingContext()
GHOST_TSuccess GHOST_ContextSDL::releaseNativeHandles() GHOST_TSuccess GHOST_ContextSDL::releaseNativeHandles()
{ {
m_window = nullptr; window_ = nullptr;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -169,8 +169,8 @@ GHOST_TSuccess GHOST_ContextSDL::setSwapInterval(int interval)
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_ContextSDL::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextSDL::getSwapInterval(int &interval_out)
{ {
intervalOut = SDL_GL_GetSwapInterval(); interval_out = SDL_GL_GetSwapInterval();
return GHOST_kSuccess; return GHOST_kSuccess;
} }

View File

@@ -84,22 +84,22 @@ class GHOST_ContextSDL : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
private: private:
SDL_Window *m_window; SDL_Window *window_;
SDL_Window *m_hidden_window; SDL_Window *hidden_window_;
const int m_contextProfileMask; const int context_profile_mask_;
const int m_contextMajorVersion; const int context_major_version_;
const int m_contextMinorVersion; const int context_minor_version_;
const int m_contextFlags; const int context_flags_;
const int m_contextResetNotificationStrategy; const int context_reset_notification_strategy_;
SDL_GLContext m_context; /* m_sdl_glcontext */ SDL_GLContext context_; /* sdl_glcontext_ */
/** The first created OpenGL context (for sharing display lists) */ /** The first created OpenGL context (for sharing display lists) */
static SDL_GLContext s_sharedContext; static SDL_GLContext s_sharedContext;

View File

@@ -569,26 +569,26 @@ GHOST_ContextVK::GHOST_ContextVK(const GHOST_ContextParams &context_params,
const GHOST_GPUDevice &preferred_device) const GHOST_GPUDevice &preferred_device)
: GHOST_Context(context_params), : GHOST_Context(context_params),
#ifdef _WIN32 #ifdef _WIN32
m_hwnd(hwnd), hwnd_(hwnd),
#elif defined(__APPLE__) #elif defined(__APPLE__)
m_metal_layer(metal_layer), metal_layer_(metal_layer),
#else #else
m_platform(platform), platform_(platform),
/* X11 */ /* X11 */
m_display(display), display_(display),
m_window(window), window_(window),
/* Wayland */ /* Wayland */
m_wayland_surface(wayland_surface), wayland_surface_(wayland_surface),
m_wayland_display(wayland_display), wayland_display_(wayland_display),
m_wayland_window_info(wayland_window_info), wayland_window_info_(wayland_window_info),
#endif #endif
m_context_major_version(contextMajorVersion), context_major_version_(contextMajorVersion),
m_context_minor_version(contextMinorVersion), context_minor_version_(contextMinorVersion),
m_preferred_device(preferred_device), preferred_device_(preferred_device),
m_surface(VK_NULL_HANDLE), surface_(VK_NULL_HANDLE),
m_swapchain(VK_NULL_HANDLE), swapchain_(VK_NULL_HANDLE),
m_frame_data(GHOST_FRAMES_IN_FLIGHT), frame_data_(GHOST_FRAMES_IN_FLIGHT),
m_render_frame(0) render_frame_(0)
{ {
} }
@@ -600,8 +600,8 @@ GHOST_ContextVK::~GHOST_ContextVK()
destroySwapchain(); destroySwapchain();
if (m_surface != VK_NULL_HANDLE) { if (surface_ != VK_NULL_HANDLE) {
vkDestroySurfaceKHR(device_vk.instance, m_surface, nullptr); vkDestroySurfaceKHR(device_vk.instance, surface_, nullptr);
} }
device_vk.users--; device_vk.users--;
@@ -629,8 +629,8 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
* to be complete, it is also safe in the callback to clean up resources associated with the next * to be complete, it is also safe in the callback to clean up resources associated with the next
* frame. * frame.
*/ */
m_render_frame = (m_render_frame + 1) % m_frame_data.size(); render_frame_ = (render_frame_ + 1) % frame_data_.size();
GHOST_Frame &submission_frame_data = m_frame_data[m_render_frame]; GHOST_Frame &submission_frame_data = frame_data_[render_frame_];
/* Wait for previous time that the frame was used to finish rendering. Presenting can /* Wait for previous time that the frame was used to finish rendering. Presenting can
* still happen in parallel, but acquiring needs can only happen when the frame acquire semaphore * still happen in parallel, but acquiring needs can only happen when the frame acquire semaphore
* has been signaled and waited for. */ * has been signaled and waited for. */
@@ -641,13 +641,12 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
/* Wayland doesn't provide a WSI with windowing capabilities, therefore cannot detect whether the /* Wayland doesn't provide a WSI with windowing capabilities, therefore cannot detect whether the
* swap-chain needs to be recreated. But as a side effect we can recreate the swap-chain before * swap-chain needs to be recreated. But as a side effect we can recreate the swap-chain before
* presenting. */ * presenting. */
if (m_wayland_window_info) { if (wayland_window_info_) {
const bool recreate_swapchain = const bool recreate_swapchain = ((wayland_window_info_->size[0] !=
((m_wayland_window_info->size[0] != std::max(render_extent_.width, render_extent_min_.width)) ||
std::max(m_render_extent.width, m_render_extent_min.width)) || (wayland_window_info_->size[1] !=
(m_wayland_window_info->size[1] != std::max(render_extent_.height, render_extent_min_.height)));
std::max(m_render_extent.height, m_render_extent_min.height))); use_hdr_swapchain = wayland_window_info_->is_color_managed;
use_hdr_swapchain = m_wayland_window_info->is_color_managed;
if (recreate_swapchain) { if (recreate_swapchain) {
/* Swap-chain is out of date. Recreate swap-chain. */ /* Swap-chain is out of date. Recreate swap-chain. */
@@ -657,21 +656,21 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
#endif #endif
/* There is no valid swapchain as the previous window was minimized. User can have maximized the /* There is no valid swapchain as the previous window was minimized. User can have maximized the
* window so we need to check if the swapchain can be created. */ * window so we need to check if the swapchain can be created. */
if (m_swapchain == VK_NULL_HANDLE) { if (swapchain_ == VK_NULL_HANDLE) {
recreateSwapchain(use_hdr_swapchain); recreateSwapchain(use_hdr_swapchain);
} }
/* Acquiree next image, swapchain can be (or become) invalid when minimizing window.*/ /* Acquiree next image, swapchain can be (or become) invalid when minimizing window.*/
uint32_t image_index = 0; uint32_t image_index = 0;
if (m_swapchain != VK_NULL_HANDLE) { if (swapchain_ != VK_NULL_HANDLE) {
/* Some platforms (NVIDIA/Wayland) can receive an out of date swapchain when acquiring the next /* Some platforms (NVIDIA/Wayland) can receive an out of date swapchain when acquiring the next
* swapchain image. Other do it when calling vkQueuePresent. */ * swapchain image. Other do it when calling vkQueuePresent. */
VkResult acquire_result = VK_ERROR_OUT_OF_DATE_KHR; VkResult acquire_result = VK_ERROR_OUT_OF_DATE_KHR;
while (m_swapchain != VK_NULL_HANDLE && while (swapchain_ != VK_NULL_HANDLE &&
(acquire_result == VK_ERROR_OUT_OF_DATE_KHR || acquire_result == VK_SUBOPTIMAL_KHR)) (acquire_result == VK_ERROR_OUT_OF_DATE_KHR || acquire_result == VK_SUBOPTIMAL_KHR))
{ {
acquire_result = vkAcquireNextImageKHR(device, acquire_result = vkAcquireNextImageKHR(device,
m_swapchain, swapchain_,
UINT64_MAX, UINT64_MAX,
submission_frame_data.acquire_semaphore, submission_frame_data.acquire_semaphore,
VK_NULL_HANDLE, VK_NULL_HANDLE,
@@ -684,7 +683,7 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
/* Fast path for invalid swapchains. When not valid we don't acquire/present, but we do render to /* Fast path for invalid swapchains. When not valid we don't acquire/present, but we do render to
* make sure the render graphs don't keep memory allocated that isn't used. */ * make sure the render graphs don't keep memory allocated that isn't used. */
if (m_swapchain == VK_NULL_HANDLE) { if (swapchain_ == VK_NULL_HANDLE) {
CLOG_TRACE( CLOG_TRACE(
&LOG, &LOG,
"Swap-chain invalid (due to minimized window), perform rendering to reduce render graph " "Swap-chain invalid (due to minimized window), perform rendering to reduce render graph "
@@ -702,14 +701,14 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
CLOG_DEBUG(&LOG, CLOG_DEBUG(&LOG,
"Acquired swap-chain image (render_frame=%lu, image_index=%u)", "Acquired swap-chain image (render_frame=%lu, image_index=%u)",
m_render_frame, render_frame_,
image_index); image_index);
GHOST_SwapchainImage &swapchain_image = m_swapchain_images[image_index]; GHOST_SwapchainImage &swapchain_image = swapchain_images_[image_index];
GHOST_VulkanSwapChainData swap_chain_data; GHOST_VulkanSwapChainData swap_chain_data;
swap_chain_data.image = swapchain_image.vk_image; swap_chain_data.image = swapchain_image.vk_image;
swap_chain_data.surface_format = m_surface_format; swap_chain_data.surface_format = surface_format_;
swap_chain_data.extent = m_render_extent; swap_chain_data.extent = render_extent_;
swap_chain_data.submission_fence = submission_frame_data.submission_fence; swap_chain_data.submission_fence = submission_frame_data.submission_fence;
swap_chain_data.acquire_semaphore = submission_frame_data.acquire_semaphore; swap_chain_data.acquire_semaphore = submission_frame_data.acquire_semaphore;
swap_chain_data.present_semaphore = swapchain_image.present_semaphore; swap_chain_data.present_semaphore = swapchain_image.present_semaphore;
@@ -724,14 +723,14 @@ GHOST_TSuccess GHOST_ContextVK::swapBuffers()
present_info.waitSemaphoreCount = 1; present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = &swapchain_image.present_semaphore; present_info.pWaitSemaphores = &swapchain_image.present_semaphore;
present_info.swapchainCount = 1; present_info.swapchainCount = 1;
present_info.pSwapchains = &m_swapchain; present_info.pSwapchains = &swapchain_;
present_info.pImageIndices = &image_index; present_info.pImageIndices = &image_index;
present_info.pResults = nullptr; present_info.pResults = nullptr;
VkResult present_result = VK_SUCCESS; VkResult present_result = VK_SUCCESS;
{ {
std::scoped_lock lock(vulkan_device->queue_mutex); std::scoped_lock lock(vulkan_device->queue_mutex);
present_result = vkQueuePresentKHR(m_present_queue, &present_info); present_result = vkQueuePresentKHR(present_queue_, &present_info);
} }
if (present_result == VK_ERROR_OUT_OF_DATE_KHR || present_result == VK_SUBOPTIMAL_KHR) { if (present_result == VK_ERROR_OUT_OF_DATE_KHR || present_result == VK_SUBOPTIMAL_KHR) {
@@ -758,8 +757,8 @@ GHOST_TSuccess GHOST_ContextVK::getVulkanSwapChainFormat(
GHOST_VulkanSwapChainData *r_swap_chain_data) GHOST_VulkanSwapChainData *r_swap_chain_data)
{ {
r_swap_chain_data->image = VK_NULL_HANDLE; r_swap_chain_data->image = VK_NULL_HANDLE;
r_swap_chain_data->surface_format = m_surface_format; r_swap_chain_data->surface_format = surface_format_;
r_swap_chain_data->extent = m_render_extent; r_swap_chain_data->extent = render_extent_;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -781,7 +780,7 @@ GHOST_TSuccess GHOST_ContextVK::getVulkanHandles(GHOST_VulkanHandles &r_handles)
vulkan_device->physical_device, vulkan_device->physical_device,
vulkan_device->device, vulkan_device->device,
vulkan_device->generic_queue_family, vulkan_device->generic_queue_family,
m_graphic_queue, graphic_queue_,
&vulkan_device->queue_mutex, &vulkan_device->queue_mutex,
}; };
} }
@@ -938,7 +937,7 @@ GHOST_TSuccess GHOST_ContextVK::initializeFrameData()
VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0}; VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0};
const VkFenceCreateInfo vk_fence_create_info = { const VkFenceCreateInfo vk_fence_create_info = {
VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, VK_FENCE_CREATE_SIGNALED_BIT}; VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, VK_FENCE_CREATE_SIGNALED_BIT};
for (GHOST_SwapchainImage &swapchain_image : m_swapchain_images) { for (GHOST_SwapchainImage &swapchain_image : swapchain_images_) {
/* VK_EXT_swapchain_maintenance1 reuses present semaphores. */ /* VK_EXT_swapchain_maintenance1 reuses present semaphores. */
if (swapchain_image.present_semaphore == VK_NULL_HANDLE) { if (swapchain_image.present_semaphore == VK_NULL_HANDLE) {
VK_CHECK(vkCreateSemaphore( VK_CHECK(vkCreateSemaphore(
@@ -946,8 +945,8 @@ GHOST_TSuccess GHOST_ContextVK::initializeFrameData()
} }
} }
for (int index = 0; index < m_frame_data.size(); index++) { for (int index = 0; index < frame_data_.size(); index++) {
GHOST_Frame &frame_data = m_frame_data[index]; GHOST_Frame &frame_data = frame_data_[index];
/* VK_EXT_swapchain_maintenance1 reuses acquire semaphores. */ /* VK_EXT_swapchain_maintenance1 reuses acquire semaphores. */
if (frame_data.acquire_semaphore == VK_NULL_HANDLE) { if (frame_data.acquire_semaphore == VK_NULL_HANDLE) {
VK_CHECK(vkCreateSemaphore( VK_CHECK(vkCreateSemaphore(
@@ -968,13 +967,13 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
VkPhysicalDevice physical_device = vulkan_device->physical_device; VkPhysicalDevice physical_device = vulkan_device->physical_device;
m_surface_format = {}; surface_format_ = {};
if (!selectSurfaceFormat(physical_device, m_surface, use_hdr_swapchain, m_surface_format)) { if (!selectSurfaceFormat(physical_device, surface_, use_hdr_swapchain, surface_format_)) {
return GHOST_kFailure; return GHOST_kFailure;
} }
VkPresentModeKHR present_mode; VkPresentModeKHR present_mode;
if (!selectPresentMode(getVSync(), physical_device, m_surface, &present_mode)) { if (!selectPresentMode(getVSync(), physical_device, surface_, &present_mode)) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -989,7 +988,7 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
VkSurfacePresentModeEXT vk_surface_present_mode = { VkSurfacePresentModeEXT vk_surface_present_mode = {
VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT, nullptr, present_mode}; VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT, nullptr, present_mode};
VkPhysicalDeviceSurfaceInfo2KHR vk_physical_device_surface_info = { VkPhysicalDeviceSurfaceInfo2KHR vk_physical_device_surface_info = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, &vk_surface_present_mode, m_surface}; VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, &vk_surface_present_mode, surface_};
VkSurfaceCapabilitiesKHR capabilities = {}; VkSurfaceCapabilitiesKHR capabilities = {};
if (vulkan_device->use_vk_ext_swapchain_maintenance_1) { if (vulkan_device->use_vk_ext_swapchain_maintenance_1) {
@@ -998,12 +997,12 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
capabilities = vk_surface_capabilities.surfaceCapabilities; capabilities = vk_surface_capabilities.surfaceCapabilities;
} }
else { else {
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, m_surface, &capabilities); vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, surface_, &capabilities);
} }
m_render_extent = capabilities.currentExtent; render_extent_ = capabilities.currentExtent;
m_render_extent_min = capabilities.minImageExtent; render_extent_min_ = capabilities.minImageExtent;
if (m_render_extent.width == UINT32_MAX) { if (render_extent_.width == UINT32_MAX) {
/* Window Manager is going to set the surface size based on the given size. /* Window Manager is going to set the surface size based on the given size.
* Choose something between minImageExtent and maxImageExtent. */ * Choose something between minImageExtent and maxImageExtent. */
int width = 0; int width = 0;
@@ -1011,9 +1010,9 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
#ifdef WITH_GHOST_WAYLAND #ifdef WITH_GHOST_WAYLAND
/* Wayland doesn't provide a windowing API via WSI. */ /* Wayland doesn't provide a windowing API via WSI. */
if (m_wayland_window_info) { if (wayland_window_info_) {
width = m_wayland_window_info->size[0]; width = wayland_window_info_->size[0];
height = m_wayland_window_info->size[1]; height = wayland_window_info_->size[1];
} }
#endif #endif
@@ -1022,32 +1021,32 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
height = 720; height = 720;
} }
m_render_extent.width = width; render_extent_.width = width;
m_render_extent.height = height; render_extent_.height = height;
if (capabilities.minImageExtent.width > m_render_extent.width) { if (capabilities.minImageExtent.width > render_extent_.width) {
m_render_extent.width = capabilities.minImageExtent.width; render_extent_.width = capabilities.minImageExtent.width;
} }
if (capabilities.minImageExtent.height > m_render_extent.height) { if (capabilities.minImageExtent.height > render_extent_.height) {
m_render_extent.height = capabilities.minImageExtent.height; render_extent_.height = capabilities.minImageExtent.height;
} }
} }
if (vulkan_device->use_vk_ext_swapchain_maintenance_1) { if (vulkan_device->use_vk_ext_swapchain_maintenance_1) {
if (vk_surface_present_scaling_capabilities.minScaledImageExtent.width > m_render_extent.width) if (vk_surface_present_scaling_capabilities.minScaledImageExtent.width > render_extent_.width)
{ {
m_render_extent.width = vk_surface_present_scaling_capabilities.minScaledImageExtent.width; render_extent_.width = vk_surface_present_scaling_capabilities.minScaledImageExtent.width;
} }
if (vk_surface_present_scaling_capabilities.minScaledImageExtent.height > if (vk_surface_present_scaling_capabilities.minScaledImageExtent.height >
m_render_extent.height) render_extent_.height)
{ {
m_render_extent.height = vk_surface_present_scaling_capabilities.minScaledImageExtent.height; render_extent_.height = vk_surface_present_scaling_capabilities.minScaledImageExtent.height;
} }
} }
/* Discard swapchain resources of current swapchain. */ /* Discard swapchain resources of current swapchain. */
GHOST_FrameDiscard &discard_pile = m_frame_data[m_render_frame].discard_pile; GHOST_FrameDiscard &discard_pile = frame_data_[render_frame_].discard_pile;
for (GHOST_SwapchainImage &swapchain_image : m_swapchain_images) { for (GHOST_SwapchainImage &swapchain_image : swapchain_images_) {
swapchain_image.vk_image = VK_NULL_HANDLE; swapchain_image.vk_image = VK_NULL_HANDLE;
if (swapchain_image.present_semaphore != VK_NULL_HANDLE) { if (swapchain_image.present_semaphore != VK_NULL_HANDLE) {
discard_pile.semaphores.push_back(swapchain_image.present_semaphore); discard_pile.semaphores.push_back(swapchain_image.present_semaphore);
@@ -1060,10 +1059,10 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
* *
* VUID-VkSwapchainCreateInfoKHR-imageExtent-01689 * VUID-VkSwapchainCreateInfoKHR-imageExtent-01689
*/ */
if (m_render_extent.width == 0 || m_render_extent.height == 0) { if (render_extent_.width == 0 || render_extent_.height == 0) {
if (m_swapchain) { if (swapchain_) {
discard_pile.swapchains.push_back(m_swapchain); discard_pile.swapchains.push_back(swapchain_);
m_swapchain = VK_NULL_HANDLE; swapchain_ = VK_NULL_HANDLE;
} }
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -1080,7 +1079,7 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
image_count_requested = capabilities.maxImageCount; image_count_requested = capabilities.maxImageCount;
} }
VkSwapchainKHR old_swapchain = m_swapchain; VkSwapchainKHR old_swapchain = swapchain_;
/* First time we stretch the swapchain image as it can happen that the first frame size isn't /* First time we stretch the swapchain image as it can happen that the first frame size isn't
* correctly reported by the initial swapchain. All subsequent creations will use one to one as * correctly reported by the initial swapchain. All subsequent creations will use one to one as
@@ -1106,11 +1105,11 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
if (vulkan_device->use_vk_ext_swapchain_maintenance_1) { if (vulkan_device->use_vk_ext_swapchain_maintenance_1) {
create_info.pNext = &vk_swapchain_present_scaling; create_info.pNext = &vk_swapchain_present_scaling;
} }
create_info.surface = m_surface; create_info.surface = surface_;
create_info.minImageCount = image_count_requested; create_info.minImageCount = image_count_requested;
create_info.imageFormat = m_surface_format.format; create_info.imageFormat = surface_format_.format;
create_info.imageColorSpace = m_surface_format.colorSpace; create_info.imageColorSpace = surface_format_.colorSpace;
create_info.imageExtent = m_render_extent; create_info.imageExtent = render_extent_;
create_info.imageArrayLayers = 1; create_info.imageArrayLayers = 1;
create_info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; create_info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
create_info.preTransform = capabilities.currentTransform; create_info.preTransform = capabilities.currentTransform;
@@ -1123,38 +1122,38 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
create_info.pQueueFamilyIndices = nullptr; create_info.pQueueFamilyIndices = nullptr;
VkDevice device = vulkan_device->device; VkDevice device = vulkan_device->device;
VK_CHECK(vkCreateSwapchainKHR(device, &create_info, nullptr, &m_swapchain)); VK_CHECK(vkCreateSwapchainKHR(device, &create_info, nullptr, &swapchain_));
/* image_count may not be what we requested! Getter for final value. */ /* image_count may not be what we requested! Getter for final value. */
uint32_t actual_image_count = 0; uint32_t actual_image_count = 0;
vkGetSwapchainImagesKHR(device, m_swapchain, &actual_image_count, nullptr); vkGetSwapchainImagesKHR(device, swapchain_, &actual_image_count, nullptr);
/* Some platforms require a minimum amount of render frames that is larger than we expect. When /* Some platforms require a minimum amount of render frames that is larger than we expect. When
* that happens we should increase the number of frames in flight. We could also consider * that happens we should increase the number of frames in flight. We could also consider
* splitting the frame in flight and image specific data. */ * splitting the frame in flight and image specific data. */
assert(actual_image_count <= GHOST_FRAMES_IN_FLIGHT); assert(actual_image_count <= GHOST_FRAMES_IN_FLIGHT);
m_swapchain_images.resize(actual_image_count); swapchain_images_.resize(actual_image_count);
std::vector<VkImage> swapchain_images(actual_image_count); std::vector<VkImage> swapchain_images(actual_image_count);
vkGetSwapchainImagesKHR(device, m_swapchain, &actual_image_count, swapchain_images.data()); vkGetSwapchainImagesKHR(device, swapchain_, &actual_image_count, swapchain_images.data());
for (int index = 0; index < actual_image_count; index++) { for (int index = 0; index < actual_image_count; index++) {
m_swapchain_images[index].vk_image = swapchain_images[index]; swapchain_images_[index].vk_image = swapchain_images[index];
} }
CLOG_DEBUG(&LOG, CLOG_DEBUG(&LOG,
"Vulkan: recreating swapchain: width=%u, height=%u, format=%d, colorSpace=%d, " "Vulkan: recreating swapchain: width=%u, height=%u, format=%d, colorSpace=%d, "
"present_mode=%d, image_count_requested=%u, image_count_acquired=%u, swapchain=%lx, " "present_mode=%d, image_count_requested=%u, image_count_acquired=%u, swapchain=%lx, "
"old_swapchain=%lx", "old_swapchain=%lx",
m_render_extent.width, render_extent_.width,
m_render_extent.height, render_extent_.height,
m_surface_format.format, surface_format_.format,
m_surface_format.colorSpace, surface_format_.colorSpace,
present_mode, present_mode,
image_count_requested, image_count_requested,
actual_image_count, actual_image_count,
uint64_t(m_swapchain), uint64_t(swapchain_),
uint64_t(old_swapchain)); uint64_t(old_swapchain));
/* Construct new semaphores. It can be that image_count is larger than previously. We only need /* Construct new semaphores. It can be that image_count is larger than previously. We only need
* to fill in where the handle is `VK_NULL_HANDLE`. */ * to fill in where the handle is `VK_NULL_HANDLE`. */
/* Previous handles from the frame data cannot be used and should be discarded. */ /* Previous handles from the frame data cannot be used and should be discarded. */
for (GHOST_Frame &frame : m_frame_data) { for (GHOST_Frame &frame : frame_data_) {
discard_pile.semaphores.push_back(frame.acquire_semaphore); discard_pile.semaphores.push_back(frame.acquire_semaphore);
frame.acquire_semaphore = VK_NULL_HANDLE; frame.acquire_semaphore = VK_NULL_HANDLE;
} }
@@ -1163,7 +1162,7 @@ GHOST_TSuccess GHOST_ContextVK::recreateSwapchain(bool use_hdr_swapchain)
} }
initializeFrameData(); initializeFrameData();
m_image_count = actual_image_count; image_count_ = actual_image_count;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1173,18 +1172,18 @@ GHOST_TSuccess GHOST_ContextVK::destroySwapchain()
assert(vulkan_device.has_value() && vulkan_device->device != VK_NULL_HANDLE); assert(vulkan_device.has_value() && vulkan_device->device != VK_NULL_HANDLE);
VkDevice device = vulkan_device->device; VkDevice device = vulkan_device->device;
if (m_swapchain != VK_NULL_HANDLE) { if (swapchain_ != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(device, m_swapchain, nullptr); vkDestroySwapchainKHR(device, swapchain_, nullptr);
} }
VK_CHECK(vkDeviceWaitIdle(device)); VK_CHECK(vkDeviceWaitIdle(device));
for (GHOST_SwapchainImage &swapchain_image : m_swapchain_images) { for (GHOST_SwapchainImage &swapchain_image : swapchain_images_) {
swapchain_image.destroy(device); swapchain_image.destroy(device);
} }
m_swapchain_images.clear(); swapchain_images_.clear();
for (GHOST_Frame &frame_data : m_frame_data) { for (GHOST_Frame &frame_data : frame_data_) {
frame_data.destroy(device); frame_data.destroy(device);
} }
m_frame_data.clear(); frame_data_.clear();
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1196,7 +1195,7 @@ const char *GHOST_ContextVK::getPlatformSpecificSurfaceExtension() const
#elif defined(__APPLE__) #elif defined(__APPLE__)
return VK_EXT_METAL_SURFACE_EXTENSION_NAME; return VK_EXT_METAL_SURFACE_EXTENSION_NAME;
#else /* UNIX/Linux */ #else /* UNIX/Linux */
switch (m_platform) { switch (platform_) {
# ifdef WITH_GHOST_X11 # ifdef WITH_GHOST_X11
case GHOST_kVulkanPlatformX11: case GHOST_kVulkanPlatformX11:
return VK_KHR_XLIB_SURFACE_EXTENSION_NAME; return VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
@@ -1218,22 +1217,22 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
{ {
bool use_hdr_swapchain = false; bool use_hdr_swapchain = false;
#ifdef _WIN32 #ifdef _WIN32
const bool use_window_surface = (m_hwnd != nullptr); const bool use_window_surface = (hwnd_ != nullptr);
#elif defined(__APPLE__) #elif defined(__APPLE__)
const bool use_window_surface = (m_metal_layer != nullptr); const bool use_window_surface = (metal_layer_ != nullptr);
#else /* UNIX/Linux */ #else /* UNIX/Linux */
bool use_window_surface = false; bool use_window_surface = false;
switch (m_platform) { switch (platform_) {
# ifdef WITH_GHOST_X11 # ifdef WITH_GHOST_X11
case GHOST_kVulkanPlatformX11: case GHOST_kVulkanPlatformX11:
use_window_surface = (m_display != nullptr) && (m_window != (Window) nullptr); use_window_surface = (display_ != nullptr) && (window_ != (Window) nullptr);
break; break;
# endif # endif
# ifdef WITH_GHOST_WAYLAND # ifdef WITH_GHOST_WAYLAND
case GHOST_kVulkanPlatformWayland: case GHOST_kVulkanPlatformWayland:
use_window_surface = (m_wayland_display != nullptr) && (m_wayland_surface != nullptr); use_window_surface = (wayland_display_ != nullptr) && (wayland_surface_ != nullptr);
if (m_wayland_window_info) { if (wayland_window_info_) {
use_hdr_swapchain = m_wayland_window_info->is_color_managed; use_hdr_swapchain = wayland_window_info_->is_color_managed;
} }
break; break;
# endif # endif
@@ -1248,7 +1247,7 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
vector<const char *> optional_device_extensions; vector<const char *> optional_device_extensions;
vector<const char *> extensions_enabled; vector<const char *> extensions_enabled;
if (m_context_params.is_debug) { if (context_params_.is_debug) {
requireExtension(extensions_available, extensions_enabled, VK_EXT_DEBUG_UTILS_EXTENSION_NAME); requireExtension(extensions_available, extensions_enabled, VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
} }
@@ -1262,7 +1261,7 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
/* X11 doesn't use the correct swapchain offset, flipping can squash the first frames. */ /* X11 doesn't use the correct swapchain offset, flipping can squash the first frames. */
const bool use_swapchain_maintenance1 = const bool use_swapchain_maintenance1 =
#ifdef WITH_GHOST_X11 #ifdef WITH_GHOST_X11
m_platform != GHOST_kVulkanPlatformX11 && platform_ != GHOST_kVulkanPlatformX11 &&
#endif #endif
contains_extension(extensions_available, VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) && contains_extension(extensions_available, VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) &&
contains_extension(extensions_available, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME); contains_extension(extensions_available, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME);
@@ -1309,7 +1308,7 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.pEngineName = "Blender"; app_info.pEngineName = "Blender";
app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.apiVersion = VK_MAKE_VERSION(m_context_major_version, m_context_minor_version, 0); app_info.apiVersion = VK_MAKE_VERSION(context_major_version_, context_minor_version_, 0);
/* Create Instance */ /* Create Instance */
VkInstanceCreateInfo create_info = {}; VkInstanceCreateInfo create_info = {};
@@ -1333,24 +1332,24 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
VkWin32SurfaceCreateInfoKHR surface_create_info = {}; VkWin32SurfaceCreateInfoKHR surface_create_info = {};
surface_create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; surface_create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
surface_create_info.hinstance = GetModuleHandle(nullptr); surface_create_info.hinstance = GetModuleHandle(nullptr);
surface_create_info.hwnd = m_hwnd; surface_create_info.hwnd = hwnd_;
VK_CHECK(vkCreateWin32SurfaceKHR(instance, &surface_create_info, nullptr, &m_surface)); VK_CHECK(vkCreateWin32SurfaceKHR(instance, &surface_create_info, nullptr, &surface_));
#elif defined(__APPLE__) #elif defined(__APPLE__)
VkMetalSurfaceCreateInfoEXT info = {}; VkMetalSurfaceCreateInfoEXT info = {};
info.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT; info.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
info.pNext = nullptr; info.pNext = nullptr;
info.flags = 0; info.flags = 0;
info.pLayer = m_metal_layer; info.pLayer = metal_layer_;
VK_CHECK(vkCreateMetalSurfaceEXT(instance, &info, nullptr, &m_surface)); VK_CHECK(vkCreateMetalSurfaceEXT(instance, &info, nullptr, &surface_));
#else #else
switch (m_platform) { switch (platform_) {
# ifdef WITH_GHOST_X11 # ifdef WITH_GHOST_X11
case GHOST_kVulkanPlatformX11: { case GHOST_kVulkanPlatformX11: {
VkXlibSurfaceCreateInfoKHR surface_create_info = {}; VkXlibSurfaceCreateInfoKHR surface_create_info = {};
surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
surface_create_info.dpy = m_display; surface_create_info.dpy = display_;
surface_create_info.window = m_window; surface_create_info.window = window_;
VK_CHECK(vkCreateXlibSurfaceKHR(instance, &surface_create_info, nullptr, &m_surface)); VK_CHECK(vkCreateXlibSurfaceKHR(instance, &surface_create_info, nullptr, &surface_));
break; break;
} }
# endif # endif
@@ -1358,14 +1357,14 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
case GHOST_kVulkanPlatformWayland: { case GHOST_kVulkanPlatformWayland: {
VkWaylandSurfaceCreateInfoKHR surface_create_info = {}; VkWaylandSurfaceCreateInfoKHR surface_create_info = {};
surface_create_info.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; surface_create_info.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
surface_create_info.display = m_wayland_display; surface_create_info.display = wayland_display_;
surface_create_info.surface = m_wayland_surface; surface_create_info.surface = wayland_surface_;
VK_CHECK(vkCreateWaylandSurfaceKHR(instance, &surface_create_info, nullptr, &m_surface)); VK_CHECK(vkCreateWaylandSurfaceKHR(instance, &surface_create_info, nullptr, &surface_));
break; break;
} }
# endif # endif
case GHOST_kVulkanPlatformHeadless: { case GHOST_kVulkanPlatformHeadless: {
m_surface = VK_NULL_HANDLE; surface_ = VK_NULL_HANDLE;
break; break;
} }
} }
@@ -1373,19 +1372,18 @@ GHOST_TSuccess GHOST_ContextVK::initializeDrawingContext()
#endif #endif
} }
if (!ensure_vulkan_device(instance, m_surface, m_preferred_device, required_device_extensions)) { if (!ensure_vulkan_device(instance, surface_, preferred_device_, required_device_extensions)) {
return GHOST_kFailure; return GHOST_kFailure;
} }
vulkan_device->users++; vulkan_device->users++;
vulkan_device->ensure_device(required_device_extensions, optional_device_extensions); vulkan_device->ensure_device(required_device_extensions, optional_device_extensions);
vkGetDeviceQueue( vkGetDeviceQueue(vulkan_device->device, vulkan_device->generic_queue_family, 0, &graphic_queue_);
vulkan_device->device, vulkan_device->generic_queue_family, 0, &m_graphic_queue);
if (use_window_surface) { if (use_window_surface) {
vkGetDeviceQueue( vkGetDeviceQueue(
vulkan_device->device, vulkan_device->generic_queue_family, 0, &m_present_queue); vulkan_device->device, vulkan_device->generic_queue_family, 0, &present_queue_);
recreateSwapchain(use_hdr_swapchain); recreateSwapchain(use_hdr_swapchain);
} }

View File

@@ -192,10 +192,10 @@ class GHOST_ContextVK : public GHOST_Context {
/** /**
* Gets the current swap interval for swapBuffers. * Gets the current swap interval for swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int & /*intervalOut*/) override GHOST_TSuccess getSwapInterval(int & /*interval_out*/) override
{ {
return GHOST_kFailure; return GHOST_kFailure;
}; };
@@ -212,38 +212,38 @@ class GHOST_ContextVK : public GHOST_Context {
private: private:
#ifdef _WIN32 #ifdef _WIN32
HWND m_hwnd; HWND hwnd_;
#elif defined(__APPLE__) #elif defined(__APPLE__)
CAMetalLayer *m_metal_layer; CAMetalLayer *metal_layer_;
#else /* Linux */ #else /* Linux */
GHOST_TVulkanPlatformType m_platform; GHOST_TVulkanPlatformType platform_;
/* X11 */ /* X11 */
Display *m_display; Display *display_;
Window m_window; Window window_;
/* Wayland */ /* Wayland */
wl_surface *m_wayland_surface; wl_surface *wayland_surface_;
wl_display *m_wayland_display; wl_display *wayland_display_;
const GHOST_ContextVK_WindowInfo *m_wayland_window_info; const GHOST_ContextVK_WindowInfo *wayland_window_info_;
#endif #endif
const int m_context_major_version; const int context_major_version_;
const int m_context_minor_version; const int context_minor_version_;
const GHOST_GPUDevice m_preferred_device; const GHOST_GPUDevice preferred_device_;
VkQueue m_graphic_queue; VkQueue graphic_queue_;
VkQueue m_present_queue; VkQueue present_queue_;
/* For display only. */ /* For display only. */
VkSurfaceKHR m_surface; VkSurfaceKHR surface_;
VkSwapchainKHR m_swapchain; VkSwapchainKHR swapchain_;
std::vector<GHOST_SwapchainImage> m_swapchain_images; std::vector<GHOST_SwapchainImage> swapchain_images_;
std::vector<GHOST_Frame> m_frame_data; std::vector<GHOST_Frame> frame_data_;
uint64_t m_render_frame; uint64_t render_frame_;
uint64_t m_image_count; uint64_t image_count_;
VkExtent2D m_render_extent; VkExtent2D render_extent_;
VkExtent2D m_render_extent_min; VkExtent2D render_extent_min_;
VkSurfaceFormatKHR m_surface_format; VkSurfaceFormatKHR surface_format_;
std::function<void(const GHOST_VulkanSwapChainData *)> swap_buffers_pre_callback_; std::function<void(const GHOST_VulkanSwapChainData *)> swap_buffers_pre_callback_;
std::function<void(void)> swap_buffers_post_callback_; std::function<void(void)> swap_buffers_post_callback_;

View File

@@ -35,33 +35,33 @@ GHOST_ContextWGL::GHOST_ContextWGL(const GHOST_ContextParams &context_params,
int contextFlags, int contextFlags,
int contextResetNotificationStrategy) int contextResetNotificationStrategy)
: GHOST_Context(context_params), : GHOST_Context(context_params),
m_hWnd(hWnd), h_wnd_(hWnd),
m_hDC(hDC), h_DC_(hDC),
m_contextProfileMask(contextProfileMask), context_profile_mask_(contextProfileMask),
m_contextMajorVersion(contextMajorVersion), context_major_version_(contextMajorVersion),
m_contextMinorVersion(contextMinorVersion), context_minor_version_(contextMinorVersion),
m_contextFlags(contextFlags), context_flags_(contextFlags),
m_alphaBackground(alphaBackground), alpha_background_(alphaBackground),
m_contextResetNotificationStrategy(contextResetNotificationStrategy), context_reset_notification_strategy_(contextResetNotificationStrategy),
m_hGLRC(nullptr) h_GLRC_(nullptr)
#ifndef NDEBUG #ifndef NDEBUG
, ,
m_dummyVendor(nullptr), dummy_vendor_(nullptr),
m_dummyRenderer(nullptr), dummy_renderer_(nullptr),
m_dummyVersion(nullptr) dummy_version_(nullptr)
#endif #endif
{ {
assert(m_hDC != nullptr); assert(h_DC_ != nullptr);
} }
GHOST_ContextWGL::~GHOST_ContextWGL() GHOST_ContextWGL::~GHOST_ContextWGL()
{ {
if (m_hGLRC != nullptr) { if (h_GLRC_ != nullptr) {
if (m_hGLRC == ::wglGetCurrentContext()) { if (h_GLRC_ == ::wglGetCurrentContext()) {
WIN32_CHK(::wglMakeCurrent(nullptr, nullptr)); WIN32_CHK(::wglMakeCurrent(nullptr, nullptr));
} }
if (m_hGLRC != s_sharedHGLRC || s_sharedCount == 1) { if (h_GLRC_ != s_sharedHGLRC || s_sharedCount == 1) {
assert(s_sharedCount > 0); assert(s_sharedCount > 0);
s_sharedCount--; s_sharedCount--;
@@ -70,27 +70,27 @@ GHOST_ContextWGL::~GHOST_ContextWGL()
s_sharedHGLRC = nullptr; s_sharedHGLRC = nullptr;
} }
WIN32_CHK(::wglDeleteContext(m_hGLRC)); WIN32_CHK(::wglDeleteContext(h_GLRC_));
} }
} }
#ifndef NDEBUG #ifndef NDEBUG
if (m_dummyRenderer) { if (dummy_renderer_) {
free((void *)m_dummyRenderer); free((void *)dummy_renderer_);
free((void *)m_dummyVendor); free((void *)dummy_vendor_);
free((void *)m_dummyVersion); free((void *)dummy_version_);
} }
#endif #endif
} }
GHOST_TSuccess GHOST_ContextWGL::swapBuffers() GHOST_TSuccess GHOST_ContextWGL::swapBuffers()
{ {
return WIN32_CHK(::SwapBuffers(m_hDC)) ? GHOST_kSuccess : GHOST_kFailure; return WIN32_CHK(::SwapBuffers(h_DC_)) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_ContextWGL::setSwapInterval(int interval) GHOST_TSuccess GHOST_ContextWGL::setSwapInterval(int interval)
{ {
if (epoxy_has_wgl_extension(m_hDC, "WGL_EXT_swap_control")) { if (epoxy_has_wgl_extension(h_DC_, "WGL_EXT_swap_control")) {
return WIN32_CHK(::wglSwapIntervalEXT(interval)) == TRUE ? GHOST_kSuccess : GHOST_kFailure; return WIN32_CHK(::wglSwapIntervalEXT(interval)) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
} }
else { else {
@@ -98,10 +98,10 @@ GHOST_TSuccess GHOST_ContextWGL::setSwapInterval(int interval)
} }
} }
GHOST_TSuccess GHOST_ContextWGL::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_ContextWGL::getSwapInterval(int &interval_out)
{ {
if (epoxy_has_wgl_extension(m_hDC, "WGL_EXT_swap_control")) { if (epoxy_has_wgl_extension(h_DC_, "WGL_EXT_swap_control")) {
intervalOut = ::wglGetSwapIntervalEXT(); interval_out = ::wglGetSwapIntervalEXT();
return GHOST_kSuccess; return GHOST_kSuccess;
} }
else { else {
@@ -111,7 +111,7 @@ GHOST_TSuccess GHOST_ContextWGL::getSwapInterval(int &intervalOut)
GHOST_TSuccess GHOST_ContextWGL::activateDrawingContext() GHOST_TSuccess GHOST_ContextWGL::activateDrawingContext()
{ {
if (WIN32_CHK(::wglMakeCurrent(m_hDC, m_hGLRC))) { if (WIN32_CHK(::wglMakeCurrent(h_DC_, h_GLRC_))) {
active_context_ = this; active_context_ = this;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -124,7 +124,7 @@ GHOST_TSuccess GHOST_ContextWGL::releaseDrawingContext()
{ {
/* Calling wglMakeCurrent(nullptr, nullptr) without an active context returns an error, /* Calling wglMakeCurrent(nullptr, nullptr) without an active context returns an error,
* so we always pass the device context handle. */ * so we always pass the device context handle. */
if (WIN32_CHK(::wglMakeCurrent(m_hDC, nullptr))) { if (WIN32_CHK(::wglMakeCurrent(h_DC_, nullptr))) {
active_context_ = nullptr; active_context_ = nullptr;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -450,7 +450,7 @@ int GHOST_ContextWGL::_choose_pixel_format_arb_1(bool stereoVisual, bool needAlp
uint nNumFormats; uint nNumFormats;
WIN32_CHK(wglChoosePixelFormatARB( WIN32_CHK(wglChoosePixelFormatARB(
m_hDC, &(iAttributes[0]), nullptr, _MAX_PIXEL_FORMATS, iPixelFormats, &nNumFormats)); h_DC_, &(iAttributes[0]), nullptr, _MAX_PIXEL_FORMATS, iPixelFormats, &nNumFormats));
if (nNumFormats > 0) { if (nNumFormats > 0) {
iPixelFormat = iPixelFormats[0]; iPixelFormat = iPixelFormats[0];
@@ -460,7 +460,7 @@ int GHOST_ContextWGL::_choose_pixel_format_arb_1(bool stereoVisual, bool needAlp
if (iPixelFormat != 0) { if (iPixelFormat != 0) {
if (needAlpha) { if (needAlpha) {
int alphaBits, iQuery = WGL_ALPHA_BITS_ARB; int alphaBits, iQuery = WGL_ALPHA_BITS_ARB;
wglGetPixelFormatAttribivARB(m_hDC, iPixelFormat, 0, 1, &iQuery, &alphaBits); wglGetPixelFormatAttribivARB(h_DC_, iPixelFormat, 0, 1, &iQuery, &alphaBits);
if (alphaBits == 0) { if (alphaBits == 0) {
fprintf(stderr, "Warning! Unable to find a frame buffer with alpha channel.\n"); fprintf(stderr, "Warning! Unable to find a frame buffer with alpha channel.\n");
} }
@@ -480,7 +480,7 @@ int GHOST_ContextWGL::choose_pixel_format_arb(bool stereoVisual, bool needAlpha)
iPixelFormat = _choose_pixel_format_arb_1(false, needAlpha); iPixelFormat = _choose_pixel_format_arb_1(false, needAlpha);
m_context_params.is_stereo_visual = false; /* Set context property to actual value. */ context_params_.is_stereo_visual = false; /* Set context property to actual value. */
} }
return iPixelFormat; return iPixelFormat;
@@ -508,18 +508,18 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
WIN32_CHK(GetLastError() == NO_ERROR); WIN32_CHK(GetLastError() == NO_ERROR);
{ {
const bool needAlpha = m_alphaBackground; const bool needAlpha = alpha_background_;
DummyContextWGL dummy(m_hDC, m_hWnd, m_context_params.is_stereo_visual, needAlpha); DummyContextWGL dummy(h_DC_, h_wnd_, context_params_.is_stereo_visual, needAlpha);
if (!dummy.has_WGL_ARB_create_context || ::GetPixelFormat(m_hDC) == 0) { if (!dummy.has_WGL_ARB_create_context || ::GetPixelFormat(h_DC_) == 0) {
int iPixelFormat = 0; int iPixelFormat = 0;
if (dummy.has_WGL_ARB_pixel_format) { if (dummy.has_WGL_ARB_pixel_format) {
iPixelFormat = choose_pixel_format_arb(m_context_params.is_stereo_visual, needAlpha); iPixelFormat = choose_pixel_format_arb(context_params_.is_stereo_visual, needAlpha);
} }
if (iPixelFormat == 0) { if (iPixelFormat == 0) {
iPixelFormat = choose_pixel_format_legacy(m_hDC, dummy.preferredPFD); iPixelFormat = choose_pixel_format_legacy(h_DC_, dummy.preferredPFD);
} }
if (iPixelFormat == 0) { if (iPixelFormat == 0) {
@@ -528,7 +528,7 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
PIXELFORMATDESCRIPTOR chosenPFD; PIXELFORMATDESCRIPTOR chosenPFD;
int lastPFD = ::DescribePixelFormat( int lastPFD = ::DescribePixelFormat(
m_hDC, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &chosenPFD); h_DC_, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &chosenPFD);
if (!WIN32_CHK(lastPFD != 0)) { if (!WIN32_CHK(lastPFD != 0)) {
goto error; goto error;
@@ -538,14 +538,14 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
fprintf(stderr, "Warning! Unable to find a pixel format with an alpha channel.\n"); fprintf(stderr, "Warning! Unable to find a pixel format with an alpha channel.\n");
} }
if (!WIN32_CHK(::SetPixelFormat(m_hDC, iPixelFormat, &chosenPFD))) { if (!WIN32_CHK(::SetPixelFormat(h_DC_, iPixelFormat, &chosenPFD))) {
goto error; goto error;
} }
} }
if (dummy.has_WGL_ARB_create_context) { if (dummy.has_WGL_ARB_create_context) {
int profileBitCore = m_contextProfileMask & WGL_CONTEXT_CORE_PROFILE_BIT_ARB; int profileBitCore = context_profile_mask_ & WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
int profileBitCompat = m_contextProfileMask & WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; int profileBitCompat = context_profile_mask_ & WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
if (!dummy.has_WGL_ARB_create_context_profile && profileBitCore) { if (!dummy.has_WGL_ARB_create_context_profile && profileBitCore) {
fprintf(stderr, "Warning! OpenGL core profile not available.\n"); fprintf(stderr, "Warning! OpenGL core profile not available.\n");
@@ -565,7 +565,7 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
profileMask |= profileBitCompat; profileMask |= profileBitCompat;
} }
if (profileMask != m_contextProfileMask) { if (profileMask != context_profile_mask_) {
fprintf(stderr, "Warning! Ignoring untested OpenGL context profile mask bits."); fprintf(stderr, "Warning! Ignoring untested OpenGL context profile mask bits.");
} }
@@ -576,25 +576,25 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
iAttributes.push_back(profileMask); iAttributes.push_back(profileMask);
} }
if (m_contextMajorVersion != 0) { if (context_major_version_ != 0) {
iAttributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); iAttributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
iAttributes.push_back(m_contextMajorVersion); iAttributes.push_back(context_major_version_);
} }
if (m_contextMinorVersion != 0) { if (context_minor_version_ != 0) {
iAttributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); iAttributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
iAttributes.push_back(m_contextMinorVersion); iAttributes.push_back(context_minor_version_);
} }
if (m_contextFlags != 0) { if (context_flags_ != 0) {
iAttributes.push_back(WGL_CONTEXT_FLAGS_ARB); iAttributes.push_back(WGL_CONTEXT_FLAGS_ARB);
iAttributes.push_back(m_contextFlags); iAttributes.push_back(context_flags_);
} }
if (m_contextResetNotificationStrategy != 0) { if (context_reset_notification_strategy_ != 0) {
if (dummy.has_WGL_ARB_create_context_robustness) { if (dummy.has_WGL_ARB_create_context_robustness) {
iAttributes.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB); iAttributes.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);
iAttributes.push_back(m_contextResetNotificationStrategy); iAttributes.push_back(context_reset_notification_strategy_);
} }
else { else {
fprintf(stderr, "Warning! Cannot set the reset notification strategy."); fprintf(stderr, "Warning! Cannot set the reset notification strategy.");
@@ -603,15 +603,15 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
iAttributes.push_back(0); iAttributes.push_back(0);
m_hGLRC = ::wglCreateContextAttribsARB(m_hDC, s_sharedHGLRC, &(iAttributes[0])); h_GLRC_ = ::wglCreateContextAttribsARB(h_DC_, s_sharedHGLRC, &(iAttributes[0]));
} }
} }
/* Silence warnings interpreted as errors by users when trying to get /* Silence warnings interpreted as errors by users when trying to get
* a context with version higher than 3.3 Core. */ * a context with version higher than 3.3 Core. */
{ {
const bool silent = m_contextMajorVersion > 3; const bool silent = context_major_version_ > 3;
if (!WIN32_CHK_SILENT(m_hGLRC != nullptr, silent)) { if (!WIN32_CHK_SILENT(h_GLRC_ != nullptr, silent)) {
goto error; goto error;
} }
} }
@@ -626,10 +626,10 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
s_sharedCount++; s_sharedCount++;
if (s_sharedHGLRC == nullptr) { if (s_sharedHGLRC == nullptr) {
s_sharedHGLRC = m_hGLRC; s_sharedHGLRC = h_GLRC_;
} }
if (!WIN32_CHK(::wglMakeCurrent(m_hDC, m_hGLRC))) { if (!WIN32_CHK(::wglMakeCurrent(h_DC_, h_GLRC_))) {
goto error; goto error;
} }
@@ -643,7 +643,7 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
} }
initClearGL(); initClearGL();
::SwapBuffers(m_hDC); ::SwapBuffers(h_DC_);
#ifndef NDEBUG #ifndef NDEBUG
{ {
@@ -651,11 +651,11 @@ GHOST_TSuccess GHOST_ContextWGL::initializeDrawingContext()
const char *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); const char *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
const char *version = reinterpret_cast<const char *>(glGetString(GL_VERSION)); const char *version = reinterpret_cast<const char *>(glGetString(GL_VERSION));
reportContextString("Vendor", m_dummyVendor, vendor); reportContextString("Vendor", dummy_vendor_, vendor);
reportContextString("Renderer", m_dummyRenderer, renderer); reportContextString("Renderer", dummy_renderer_, renderer);
reportContextString("Version", m_dummyVersion, version); reportContextString("Version", dummy_version_, version);
fprintf(stderr, "Context Version: %d.%d\n", m_contextMajorVersion, m_contextMinorVersion); fprintf(stderr, "Context Version: %d.%d\n", context_major_version_, context_minor_version_);
} }
#endif #endif
@@ -668,11 +668,11 @@ error:
GHOST_TSuccess GHOST_ContextWGL::releaseNativeHandles() GHOST_TSuccess GHOST_ContextWGL::releaseNativeHandles()
{ {
GHOST_TSuccess success = m_hGLRC != s_sharedHGLRC || s_sharedCount == 1 ? GHOST_kSuccess : GHOST_TSuccess success = h_GLRC_ != s_sharedHGLRC || s_sharedCount == 1 ? GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
m_hWnd = nullptr; h_wnd_ = nullptr;
m_hDC = nullptr; h_DC_ = nullptr;
return success; return success;
} }

View File

@@ -79,31 +79,31 @@ class GHOST_ContextWGL : public GHOST_Context {
/** /**
* Gets the current swap interval for #swapBuffers. * Gets the current swap interval for #swapBuffers.
* \param intervalOut: Variable to store the swap interval if it can be read. * \param interval_out: Variable to store the swap interval if it can be read.
* \return Whether the swap interval can be read. * \return Whether the swap interval can be read.
*/ */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
private: private:
int choose_pixel_format_arb(bool stereoVisual, bool needAlpha); int choose_pixel_format_arb(bool stereoVisual, bool needAlpha);
int _choose_pixel_format_arb_1(bool stereoVisual, bool needAlpha); int _choose_pixel_format_arb_1(bool stereoVisual, bool needAlpha);
HWND m_hWnd; HWND h_wnd_;
HDC m_hDC; HDC h_DC_;
const int m_contextProfileMask; const int context_profile_mask_;
const int m_contextMajorVersion; const int context_major_version_;
const int m_contextMinorVersion; const int context_minor_version_;
const int m_contextFlags; const int context_flags_;
const bool m_alphaBackground; const bool alpha_background_;
const int m_contextResetNotificationStrategy; const int context_reset_notification_strategy_;
HGLRC m_hGLRC; HGLRC h_GLRC_;
#ifndef NDEBUG #ifndef NDEBUG
const char *m_dummyVendor; const char *dummy_vendor_;
const char *m_dummyRenderer; const char *dummy_renderer_;
const char *m_dummyVersion; const char *dummy_version_;
#endif #endif
static HGLRC s_sharedHGLRC; static HGLRC s_sharedHGLRC;

View File

@@ -19,11 +19,11 @@ void printLastError(void);
#endif /* WITH_GHOST_DEBUG */ #endif /* WITH_GHOST_DEBUG */
GHOST_DropTargetWin32::GHOST_DropTargetWin32(GHOST_WindowWin32 *window, GHOST_SystemWin32 *system) GHOST_DropTargetWin32::GHOST_DropTargetWin32(GHOST_WindowWin32 *window, GHOST_SystemWin32 *system)
: m_window(window), m_system(system) : window_(window), system_(system)
{ {
m_cRef = 1; c_ref_ = 1;
m_hWnd = window->getHWND(); h_wnd_ = window->getHWND();
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
} }
GHOST_DropTargetWin32::~GHOST_DropTargetWin32() {} GHOST_DropTargetWin32::~GHOST_DropTargetWin32() {}
@@ -54,7 +54,7 @@ HRESULT __stdcall GHOST_DropTargetWin32::QueryInterface(REFIID riid, void **ppv_
ULONG __stdcall GHOST_DropTargetWin32::AddRef(void) ULONG __stdcall GHOST_DropTargetWin32::AddRef(void)
{ {
return ::InterlockedIncrement(&m_cRef); return ::InterlockedIncrement(&c_ref_);
} }
/* /*
@@ -62,7 +62,7 @@ ULONG __stdcall GHOST_DropTargetWin32::AddRef(void)
*/ */
ULONG __stdcall GHOST_DropTargetWin32::Release(void) ULONG __stdcall GHOST_DropTargetWin32::Release(void)
{ {
ULONG refs = ::InterlockedDecrement(&m_cRef); ULONG refs = ::InterlockedDecrement(&c_ref_);
if (refs == 0) { if (refs == 0) {
delete this; delete this;
@@ -82,12 +82,12 @@ HRESULT __stdcall GHOST_DropTargetWin32::DragEnter(IDataObject *p_data_object,
DWORD *pdw_effect) DWORD *pdw_effect)
{ {
/* We accept all drop by default. */ /* We accept all drop by default. */
m_window->setAcceptDragOperation(true); window_->setAcceptDragOperation(true);
*pdw_effect = DROPEFFECT_NONE; *pdw_effect = DROPEFFECT_NONE;
m_draggedObjectType = getGhostType(p_data_object); dragged_object_type_ = getGhostType(p_data_object);
m_system->pushDragDropEvent( system_->pushDragDropEvent(
GHOST_kEventDraggingEntered, m_draggedObjectType, m_window, pt.x, pt.y, nullptr); GHOST_kEventDraggingEntered, dragged_object_type_, window_, pt.x, pt.y, nullptr);
return S_OK; return S_OK;
} }
@@ -98,7 +98,7 @@ HRESULT __stdcall GHOST_DropTargetWin32::DragOver(DWORD /*grf_key_state*/,
POINTL pt, POINTL pt,
DWORD *pdw_effect) DWORD *pdw_effect)
{ {
if (m_window->canAcceptDragOperation()) { if (window_->canAcceptDragOperation()) {
*pdw_effect = allowedDropEffect(*pdw_effect); *pdw_effect = allowedDropEffect(*pdw_effect);
} }
else { else {
@@ -106,8 +106,8 @@ HRESULT __stdcall GHOST_DropTargetWin32::DragOver(DWORD /*grf_key_state*/,
/* XXX Uncomment to test drop. Drop will not be called if `pdw_effect == DROPEFFECT_NONE`. */ /* XXX Uncomment to test drop. Drop will not be called if `pdw_effect == DROPEFFECT_NONE`. */
// *pdw_effect = DROPEFFECT_COPY; // *pdw_effect = DROPEFFECT_COPY;
} }
m_system->pushDragDropEvent( system_->pushDragDropEvent(
GHOST_kEventDraggingUpdated, m_draggedObjectType, m_window, pt.x, pt.y, nullptr); GHOST_kEventDraggingUpdated, dragged_object_type_, window_, pt.x, pt.y, nullptr);
return S_OK; return S_OK;
} }
@@ -116,9 +116,9 @@ HRESULT __stdcall GHOST_DropTargetWin32::DragOver(DWORD /*grf_key_state*/,
*/ */
HRESULT __stdcall GHOST_DropTargetWin32::DragLeave(void) HRESULT __stdcall GHOST_DropTargetWin32::DragLeave(void)
{ {
m_system->pushDragDropEvent( system_->pushDragDropEvent(
GHOST_kEventDraggingExited, m_draggedObjectType, m_window, 0, 0, nullptr); GHOST_kEventDraggingExited, dragged_object_type_, window_, 0, 0, nullptr);
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
return S_OK; return S_OK;
} }
@@ -132,17 +132,17 @@ HRESULT __stdcall GHOST_DropTargetWin32::Drop(IDataObject *p_data_object,
DWORD *pdw_effect) DWORD *pdw_effect)
{ {
void *data = getGhostData(p_data_object); void *data = getGhostData(p_data_object);
if (m_window->canAcceptDragOperation()) { if (window_->canAcceptDragOperation()) {
*pdw_effect = allowedDropEffect(*pdw_effect); *pdw_effect = allowedDropEffect(*pdw_effect);
} }
else { else {
*pdw_effect = DROPEFFECT_NONE; *pdw_effect = DROPEFFECT_NONE;
} }
if (data) { if (data) {
m_system->pushDragDropEvent( system_->pushDragDropEvent(
GHOST_kEventDraggingDropDone, m_draggedObjectType, m_window, pt.x, pt.y, data); GHOST_kEventDraggingDropDone, dragged_object_type_, window_, pt.x, pt.y, data);
} }
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
return S_OK; return S_OK;
} }

View File

@@ -123,15 +123,15 @@ class GHOST_DropTargetWin32 : public IDropTarget {
/* Private member variables */ /* Private member variables */
/* COM reference count. */ /* COM reference count. */
LONG m_cRef; LONG c_ref_;
/* Handle of the associated window. */ /* Handle of the associated window. */
HWND m_hWnd; HWND h_wnd_;
/* The associated GHOST_WindowWin32. */ /* The associated GHOST_WindowWin32. */
GHOST_WindowWin32 *m_window; GHOST_WindowWin32 *window_;
/* The System. */ /* The System. */
GHOST_SystemWin32 *m_system; GHOST_SystemWin32 *system_;
/* Data type of the dragged object */ /* Data type of the dragged object */
GHOST_TDragnDropTypes m_draggedObjectType; GHOST_TDragnDropTypes dragged_object_type_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_DropTargetWin32") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_DropTargetWin32")
}; };

View File

@@ -16,41 +16,41 @@
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
bool GHOST_DropTargetX11::m_xdndInitialized = false; bool GHOST_DropTargetX11::xdnd_initialized_ = false;
DndClass GHOST_DropTargetX11::m_dndClass; DndClass GHOST_DropTargetX11::dnd_class_;
Atom *GHOST_DropTargetX11::m_dndTypes = nullptr; Atom *GHOST_DropTargetX11::dnd_types_ = nullptr;
Atom *GHOST_DropTargetX11::m_dndActions = nullptr; Atom *GHOST_DropTargetX11::dnd_actions_ = nullptr;
const char *GHOST_DropTargetX11::m_dndMimeTypes[] = { const char *GHOST_DropTargetX11::dnd_mime_types_[] = {
"url/url", "text/uri-list", "text/plain", "application/octet-stream"}; "url/url", "text/uri-list", "text/plain", "application/octet-stream"};
int GHOST_DropTargetX11::m_refCounter = 0; int GHOST_DropTargetX11::ref_counter_ = 0;
#define dndTypeURLID 0 #define dndTypeURLID 0
#define dndTypeURIListID 1 #define dndTypeURIListID 1
#define dndTypePlainTextID 2 #define dndTypePlainTextID 2
#define dndTypeOctetStreamID 3 #define dndTypeOctetStreamID 3
#define dndTypeURL m_dndTypes[dndTypeURLID] #define dndTypeURL dnd_types_[dndTypeURLID]
#define dndTypeURIList m_dndTypes[dndTypeURIListID] #define dndTypeURIList dnd_types_[dndTypeURIListID]
#define dndTypePlainText m_dndTypes[dndTypePlainTextID] #define dndTypePlainText dnd_types_[dndTypePlainTextID]
#define dndTypeOctetStream m_dndTypes[dndTypeOctetStreamID] #define dndTypeOctetStream dnd_types_[dndTypeOctetStreamID]
void GHOST_DropTargetX11::Initialize() void GHOST_DropTargetX11::Initialize()
{ {
Display *display = m_system->getXDisplay(); Display *display = system_->getXDisplay();
int dndTypesCount = ARRAY_SIZE(m_dndMimeTypes); int dndTypesCount = ARRAY_SIZE(dnd_mime_types_);
int counter; int counter;
xdnd_init(&m_dndClass, display); xdnd_init(&dnd_class_, display);
m_dndTypes = new Atom[dndTypesCount + 1]; dnd_types_ = new Atom[dndTypesCount + 1];
XInternAtoms(display, (char **)m_dndMimeTypes, dndTypesCount, 0, m_dndTypes); XInternAtoms(display, (char **)dnd_mime_types_, dndTypesCount, 0, dnd_types_);
m_dndTypes[dndTypesCount] = 0; dnd_types_[dndTypesCount] = 0;
m_dndActions = new Atom[8]; dnd_actions_ = new Atom[8];
counter = 0; counter = 0;
m_dndActions[counter++] = m_dndClass.XdndActionCopy; dnd_actions_[counter++] = dnd_class_.XdndActionCopy;
m_dndActions[counter++] = m_dndClass.XdndActionMove; dnd_actions_[counter++] = dnd_class_.XdndActionMove;
#if 0 /* Not supported yet */ #if 0 /* Not supported yet */
dndActions[counter++] = dnd->XdndActionLink; dndActions[counter++] = dnd->XdndActionLink;
@@ -60,41 +60,41 @@ void GHOST_DropTargetX11::Initialize()
dndActions[counter++] = dnd->XdndActionDescription; dndActions[counter++] = dnd->XdndActionDescription;
#endif #endif
m_dndActions[counter++] = 0; dnd_actions_[counter++] = 0;
} }
void GHOST_DropTargetX11::Uninitialize() void GHOST_DropTargetX11::Uninitialize()
{ {
xdnd_shut(&m_dndClass); xdnd_shut(&dnd_class_);
delete[] m_dndActions; delete[] dnd_actions_;
delete[] m_dndTypes; delete[] dnd_types_;
} }
GHOST_DropTargetX11::GHOST_DropTargetX11(GHOST_WindowX11 *window, GHOST_SystemX11 *system) GHOST_DropTargetX11::GHOST_DropTargetX11(GHOST_WindowX11 *window, GHOST_SystemX11 *system)
: m_window(window), m_system(system) : window_(window), system_(system)
{ {
if (!m_xdndInitialized) { if (!xdnd_initialized_) {
Initialize(); Initialize();
m_xdndInitialized = true; xdnd_initialized_ = true;
GHOST_PRINT("XDND initialized\n"); GHOST_PRINT("XDND initialized\n");
} }
Window wnd = window->getXWindow(); Window wnd = window->getXWindow();
xdnd_set_dnd_aware(&m_dndClass, wnd, nullptr); xdnd_set_dnd_aware(&dnd_class_, wnd, nullptr);
xdnd_set_type_list(&m_dndClass, wnd, m_dndTypes); xdnd_set_type_list(&dnd_class_, wnd, dnd_types_);
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
m_refCounter++; ref_counter_++;
} }
GHOST_DropTargetX11::~GHOST_DropTargetX11() GHOST_DropTargetX11::~GHOST_DropTargetX11()
{ {
m_refCounter--; ref_counter_--;
if (m_refCounter == 0) { if (ref_counter_ == 0) {
Uninitialize(); Uninitialize();
m_xdndInitialized = false; xdnd_initialized_ = false;
GHOST_PRINT("XDND uninitialized\n"); GHOST_PRINT("XDND uninitialized\n");
} }
} }
@@ -170,7 +170,7 @@ void *GHOST_DropTargetX11::getGhostData(Atom dropType, const uchar *dropBuffer,
tmpBuffer[dropBufferSize] = 0; tmpBuffer[dropBufferSize] = 0;
if (dropType == dndTypeURIList) { if (dropType == dndTypeURIList) {
m_draggedObjectType = GHOST_kDragnDropTypeFilenames; dragged_object_type_ = GHOST_kDragnDropTypeFilenames;
data = getURIListGhostData(tmpBuffer, dropBufferSize); data = getURIListGhostData(tmpBuffer, dropBufferSize);
} }
else if (dropType == dndTypeURL) { else if (dropType == dndTypeURL) {
@@ -178,17 +178,17 @@ void *GHOST_DropTargetX11::getGhostData(Atom dropType, const uchar *dropBuffer,
char *decodedPath = FileUrlDecode((const char *)tmpBuffer); char *decodedPath = FileUrlDecode((const char *)tmpBuffer);
if (decodedPath) { if (decodedPath) {
m_draggedObjectType = GHOST_kDragnDropTypeString; dragged_object_type_ = GHOST_kDragnDropTypeString;
data = decodedPath; data = decodedPath;
} }
} }
else if (ELEM(dropType, dndTypePlainText, dndTypeOctetStream)) { else if (ELEM(dropType, dndTypePlainText, dndTypeOctetStream)) {
m_draggedObjectType = GHOST_kDragnDropTypeString; dragged_object_type_ = GHOST_kDragnDropTypeString;
data = tmpBuffer; data = tmpBuffer;
needsFree = false; needsFree = false;
} }
else { else {
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
} }
if (needsFree) { if (needsFree) {
@@ -204,10 +204,10 @@ bool GHOST_DropTargetX11::GHOST_HandleClientMessage(XEvent *event)
uchar *dropBuffer; uchar *dropBuffer;
int dropBufferSize, dropX, dropY; int dropBufferSize, dropX, dropY;
if (xdnd_get_drop(m_system->getXDisplay(), if (xdnd_get_drop(system_->getXDisplay(),
event, event,
m_dndTypes, dnd_types_,
m_dndActions, dnd_actions_,
&dropBuffer, &dropBuffer,
&dropBufferSize, &dropBufferSize,
&dropType, &dropType,
@@ -217,13 +217,13 @@ bool GHOST_DropTargetX11::GHOST_HandleClientMessage(XEvent *event)
void *data = getGhostData(dropType, dropBuffer, dropBufferSize); void *data = getGhostData(dropType, dropBuffer, dropBufferSize);
if (data) { if (data) {
m_system->pushDragDropEvent( system_->pushDragDropEvent(
GHOST_kEventDraggingDropDone, m_draggedObjectType, m_window, dropX, dropY, data); GHOST_kEventDraggingDropDone, dragged_object_type_, window_, dropX, dropY, data);
} }
free(dropBuffer); free(dropBuffer);
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
return true; return true;
} }

View File

@@ -73,30 +73,30 @@ class GHOST_DropTargetX11 {
char *FileUrlDecode(const char *fileUrl); char *FileUrlDecode(const char *fileUrl);
/* The associated GHOST_WindowWin32. */ /* The associated GHOST_WindowWin32. */
GHOST_WindowX11 *m_window; GHOST_WindowX11 *window_;
/* The System. */ /* The System. */
GHOST_SystemX11 *m_system; GHOST_SystemX11 *system_;
/* Data type of the dragged object */ /* Data type of the dragged object */
GHOST_TDragnDropTypes m_draggedObjectType; GHOST_TDragnDropTypes dragged_object_type_;
/* Is drag-and-drop stuff initialized. */ /* Is drag-and-drop stuff initialized. */
static bool m_xdndInitialized; static bool xdnd_initialized_;
/* Class holding internal stiff of `xdnd` library. */ /* Class holding internal stiff of `xdnd` library. */
static DndClass m_dndClass; static DndClass dnd_class_;
/* List of supported types to be dragged into. */ /* List of supported types to be dragged into. */
static Atom *m_dndTypes; static Atom *dnd_types_;
/* List of supported drag-and-drop actions. */ /* List of supported drag-and-drop actions. */
static Atom *m_dndActions; static Atom *dnd_actions_;
/* List of supported MIME types to be dragged into. */ /* List of supported MIME types to be dragged into. */
static const char *m_dndMimeTypes[]; static const char *dnd_mime_types_[];
/* Counter of references to global #XDND structures. */ /* Counter of references to global #XDND structures. */
static int m_refCounter; static int ref_counter_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_DropTargetX11") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_DropTargetX11")
}; };

View File

@@ -23,41 +23,41 @@ class GHOST_Event : public GHOST_IEvent {
* \param window: The generating window (or nullptr if system event). * \param window: The generating window (or nullptr if system event).
*/ */
GHOST_Event(uint64_t msec, GHOST_TEventType type, GHOST_IWindow *window) GHOST_Event(uint64_t msec, GHOST_TEventType type, GHOST_IWindow *window)
: m_type(type), m_time(msec), m_window(window) : type_(type), time_(msec), window_(window)
{ {
} }
/** \copydoc #GHOST_IEvent::getType */ /** \copydoc #GHOST_IEvent::getType */
GHOST_TEventType getType() const override GHOST_TEventType getType() const override
{ {
return m_type; return type_;
} }
/** \copydoc #GHOST_IEvent::getTime */ /** \copydoc #GHOST_IEvent::getTime */
uint64_t getTime() const override uint64_t getTime() const override
{ {
return m_time; return time_;
} }
/** \copydoc #GHOST_IEvent::getWindow */ /** \copydoc #GHOST_IEvent::getWindow */
GHOST_IWindow *getWindow() const override GHOST_IWindow *getWindow() const override
{ {
return m_window; return window_;
} }
/** \copydoc #GHOST_IEvent::getData */ /** \copydoc #GHOST_IEvent::getData */
GHOST_TEventDataPtr getData() const override GHOST_TEventDataPtr getData() const override
{ {
return m_data; return data_;
} }
protected: protected:
/** Type of this event. */ /** Type of this event. */
GHOST_TEventType m_type; GHOST_TEventType type_;
/** The time this event was generated. */ /** The time this event was generated. */
uint64_t m_time; uint64_t time_;
/** Pointer to the generating window. */ /** Pointer to the generating window. */
GHOST_IWindow *m_window; GHOST_IWindow *window_;
/** Pointer to the event data. */ /** Pointer to the event data. */
GHOST_TEventDataPtr m_data = nullptr; GHOST_TEventDataPtr data_ = nullptr;
}; };

View File

@@ -30,12 +30,12 @@ class GHOST_EventButton : public GHOST_Event {
GHOST_IWindow *window, GHOST_IWindow *window,
GHOST_TButton button, GHOST_TButton button,
const GHOST_TabletData &tablet) const GHOST_TabletData &tablet)
: GHOST_Event(time, type, window), m_buttonEventData({button, tablet}) : GHOST_Event(time, type, window), button_event_data_({button, tablet})
{ {
m_data = &m_buttonEventData; data_ = &button_event_data_;
} }
protected: protected:
/** The button event data. */ /** The button event data. */
GHOST_TEventButtonData m_buttonEventData; GHOST_TEventButtonData button_event_data_;
}; };

View File

@@ -30,12 +30,12 @@ class GHOST_EventCursor : public GHOST_Event {
int32_t x, int32_t x,
int32_t y, int32_t y,
const GHOST_TabletData &tablet) const GHOST_TabletData &tablet)
: GHOST_Event(msec, type, window), m_cursorEventData({x, y, tablet}) : GHOST_Event(msec, type, window), cursor_event_data_({x, y, tablet})
{ {
m_data = &m_cursorEventData; data_ = &cursor_event_data_;
} }
protected: protected:
/** The x,y-coordinates of the cursor position. */ /** The x,y-coordinates of the cursor position. */
GHOST_TEventCursorData m_cursorEventData; GHOST_TEventCursorData cursor_event_data_;
}; };

View File

@@ -64,26 +64,26 @@ class GHOST_EventDragnDrop : public GHOST_Event {
GHOST_TDragnDropDataPtr data) GHOST_TDragnDropDataPtr data)
: GHOST_Event(time, type, window) : GHOST_Event(time, type, window)
{ {
m_dragnDropEventData.x = x; dragn_drop_event_data_.x = x;
m_dragnDropEventData.y = y; dragn_drop_event_data_.y = y;
m_dragnDropEventData.dataType = dataType; dragn_drop_event_data_.dataType = dataType;
m_dragnDropEventData.data = data; dragn_drop_event_data_.data = data;
m_data = &m_dragnDropEventData; data_ = &dragn_drop_event_data_;
} }
~GHOST_EventDragnDrop() override ~GHOST_EventDragnDrop() override
{ {
/* Free the dropped object data. */ /* Free the dropped object data. */
if (m_dragnDropEventData.data == nullptr) { if (dragn_drop_event_data_.data == nullptr) {
return; return;
} }
switch (m_dragnDropEventData.dataType) { switch (dragn_drop_event_data_.dataType) {
case GHOST_kDragnDropTypeBitmap: case GHOST_kDragnDropTypeBitmap:
IMB_freeImBuf((ImBuf *)m_dragnDropEventData.data); IMB_freeImBuf((ImBuf *)dragn_drop_event_data_.data);
break; break;
case GHOST_kDragnDropTypeFilenames: { case GHOST_kDragnDropTypeFilenames: {
GHOST_TStringArray *strArray = (GHOST_TStringArray *)m_dragnDropEventData.data; GHOST_TStringArray *strArray = (GHOST_TStringArray *)dragn_drop_event_data_.data;
int i; int i;
for (i = 0; i < strArray->count; i++) { for (i = 0; i < strArray->count; i++) {
@@ -95,7 +95,7 @@ class GHOST_EventDragnDrop : public GHOST_Event {
break; break;
} }
case GHOST_kDragnDropTypeString: case GHOST_kDragnDropTypeString:
free(m_dragnDropEventData.data); free(dragn_drop_event_data_.data);
break; break;
default: default:
@@ -105,5 +105,5 @@ class GHOST_EventDragnDrop : public GHOST_Event {
protected: protected:
/** The x,y-coordinates of the cursor position. */ /** The x,y-coordinates of the cursor position. */
GHOST_TEventDragnDropData m_dragnDropEventData; GHOST_TEventDragnDropData dragn_drop_event_data_;
}; };

View File

@@ -29,10 +29,10 @@ class GHOST_EventKey : public GHOST_Event {
uint64_t msec, GHOST_TEventType type, GHOST_IWindow *window, GHOST_TKey key, bool is_repeat) uint64_t msec, GHOST_TEventType type, GHOST_IWindow *window, GHOST_TKey key, bool is_repeat)
: GHOST_Event(msec, type, window) : GHOST_Event(msec, type, window)
{ {
m_keyEventData.key = key; key_event_data_.key = key;
m_keyEventData.utf8_buf[0] = '\0'; key_event_data_.utf8_buf[0] = '\0';
m_keyEventData.is_repeat = is_repeat; key_event_data_.is_repeat = is_repeat;
m_data = &m_keyEventData; data_ = &key_event_data_;
} }
/** /**
@@ -51,18 +51,18 @@ class GHOST_EventKey : public GHOST_Event {
const char utf8_buf[6]) const char utf8_buf[6])
: GHOST_Event(msec, type, window) : GHOST_Event(msec, type, window)
{ {
m_keyEventData.key = key; key_event_data_.key = key;
if (utf8_buf) { if (utf8_buf) {
memcpy(m_keyEventData.utf8_buf, utf8_buf, sizeof(m_keyEventData.utf8_buf)); memcpy(key_event_data_.utf8_buf, utf8_buf, sizeof(key_event_data_.utf8_buf));
} }
else { else {
m_keyEventData.utf8_buf[0] = '\0'; key_event_data_.utf8_buf[0] = '\0';
} }
m_keyEventData.is_repeat = is_repeat; key_event_data_.is_repeat = is_repeat;
m_data = &m_keyEventData; data_ = &key_event_data_;
} }
protected: protected:
/** The key event data. */ /** The key event data. */
GHOST_TEventKeyData m_keyEventData; GHOST_TEventKeyData key_event_data_;
}; };

View File

@@ -20,24 +20,24 @@ GHOST_EventManager::~GHOST_EventManager()
{ {
disposeEvents(); disposeEvents();
TConsumerVector::iterator iter = m_consumers.begin(); TConsumerVector::iterator iter = consumers_.begin();
while (iter != m_consumers.end()) { while (iter != consumers_.end()) {
GHOST_IEventConsumer *consumer = *iter; GHOST_IEventConsumer *consumer = *iter;
delete consumer; delete consumer;
iter = m_consumers.erase(iter); iter = consumers_.erase(iter);
} }
} }
uint32_t GHOST_EventManager::getNumEvents() uint32_t GHOST_EventManager::getNumEvents()
{ {
return uint32_t(m_events.size()); return uint32_t(events_.size());
} }
uint32_t GHOST_EventManager::getNumEvents(GHOST_TEventType type) uint32_t GHOST_EventManager::getNumEvents(GHOST_TEventType type)
{ {
uint32_t numEvents = 0; uint32_t numEvents = 0;
TEventStack::iterator p; TEventStack::iterator p;
for (p = m_events.begin(); p != m_events.end(); ++p) { for (p = events_.begin(); p != events_.end(); ++p) {
if ((*p)->getType() == type) { if ((*p)->getType() == type) {
numEvents++; numEvents++;
} }
@@ -49,8 +49,8 @@ GHOST_TSuccess GHOST_EventManager::pushEvent(const GHOST_IEvent *event)
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
GHOST_ASSERT(event, "invalid event"); GHOST_ASSERT(event, "invalid event");
if (m_events.size() < m_events.max_size()) { if (events_.size() < events_.max_size()) {
m_events.push_front(event); events_.push_front(event);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
else { else {
@@ -63,23 +63,23 @@ void GHOST_EventManager::dispatchEvent(const GHOST_IEvent *event)
{ {
TConsumerVector::iterator iter; TConsumerVector::iterator iter;
for (iter = m_consumers.begin(); iter != m_consumers.end(); ++iter) { for (iter = consumers_.begin(); iter != consumers_.end(); ++iter) {
(*iter)->processEvent(event); (*iter)->processEvent(event);
} }
} }
void GHOST_EventManager::dispatchEvent() void GHOST_EventManager::dispatchEvent()
{ {
const GHOST_IEvent *event = m_events.back(); const GHOST_IEvent *event = events_.back();
m_events.pop_back(); events_.pop_back();
m_handled_events.push_back(event); handled_events_.push_back(event);
dispatchEvent(event); dispatchEvent(event);
} }
void GHOST_EventManager::dispatchEvents() void GHOST_EventManager::dispatchEvents()
{ {
while (!m_events.empty()) { while (!events_.empty()) {
dispatchEvent(); dispatchEvent();
} }
@@ -92,12 +92,11 @@ GHOST_TSuccess GHOST_EventManager::addConsumer(GHOST_IEventConsumer *consumer)
GHOST_ASSERT(consumer, "invalid consumer"); GHOST_ASSERT(consumer, "invalid consumer");
/* Check to see whether the consumer is already in our list. */ /* Check to see whether the consumer is already in our list. */
TConsumerVector::const_iterator iter = std::find( TConsumerVector::const_iterator iter = std::find(consumers_.begin(), consumers_.end(), consumer);
m_consumers.begin(), m_consumers.end(), consumer);
if (iter == m_consumers.end()) { if (iter == consumers_.end()) {
/* Add the consumer. */ /* Add the consumer. */
m_consumers.push_back(consumer); consumers_.push_back(consumer);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
else { else {
@@ -112,11 +111,11 @@ GHOST_TSuccess GHOST_EventManager::removeConsumer(GHOST_IEventConsumer *consumer
GHOST_ASSERT(consumer, "invalid consumer"); GHOST_ASSERT(consumer, "invalid consumer");
/* Check to see whether the consumer is in our list. */ /* Check to see whether the consumer is in our list. */
TConsumerVector::iterator iter = std::find(m_consumers.begin(), m_consumers.end(), consumer); TConsumerVector::iterator iter = std::find(consumers_.begin(), consumers_.end(), consumer);
if (iter != m_consumers.end()) { if (iter != consumers_.end()) {
/* Remove the consumer. */ /* Remove the consumer. */
m_consumers.erase(iter); consumers_.erase(iter);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
else { else {
@@ -128,8 +127,8 @@ GHOST_TSuccess GHOST_EventManager::removeConsumer(GHOST_IEventConsumer *consumer
void GHOST_EventManager::removeWindowEvents(const GHOST_IWindow *window) void GHOST_EventManager::removeWindowEvents(const GHOST_IWindow *window)
{ {
TEventStack::iterator iter; TEventStack::iterator iter;
iter = m_events.begin(); iter = events_.begin();
while (iter != m_events.end()) { while (iter != events_.end()) {
const GHOST_IEvent *event = *iter; const GHOST_IEvent *event = *iter;
if (event->getWindow() == window) { if (event->getWindow() == window) {
GHOST_PRINT("GHOST_EventManager::removeWindowEvents(): removing event\n"); GHOST_PRINT("GHOST_EventManager::removeWindowEvents(): removing event\n");
@@ -138,8 +137,8 @@ void GHOST_EventManager::removeWindowEvents(const GHOST_IWindow *window)
* The iterator will become invalid. * The iterator will become invalid.
*/ */
delete event; delete event;
m_events.erase(iter); events_.erase(iter);
iter = m_events.begin(); iter = events_.begin();
} }
else { else {
++iter; ++iter;
@@ -150,8 +149,8 @@ void GHOST_EventManager::removeWindowEvents(const GHOST_IWindow *window)
void GHOST_EventManager::removeTypeEvents(GHOST_TEventType type, const GHOST_IWindow *window) void GHOST_EventManager::removeTypeEvents(GHOST_TEventType type, const GHOST_IWindow *window)
{ {
TEventStack::iterator iter; TEventStack::iterator iter;
iter = m_events.begin(); iter = events_.begin();
while (iter != m_events.end()) { while (iter != events_.end()) {
const GHOST_IEvent *event = *iter; const GHOST_IEvent *event = *iter;
if ((event->getType() == type) && (!window || (event->getWindow() == window))) { if ((event->getType() == type) && (!window || (event->getWindow() == window))) {
GHOST_PRINT("GHOST_EventManager::removeTypeEvents(): removing event\n"); GHOST_PRINT("GHOST_EventManager::removeTypeEvents(): removing event\n");
@@ -160,8 +159,8 @@ void GHOST_EventManager::removeTypeEvents(GHOST_TEventType type, const GHOST_IWi
* The iterator will become invalid. * The iterator will become invalid.
*/ */
delete event; delete event;
m_events.erase(iter); events_.erase(iter);
iter = m_events.begin(); iter = events_.begin();
} }
else { else {
++iter; ++iter;
@@ -171,15 +170,15 @@ void GHOST_EventManager::removeTypeEvents(GHOST_TEventType type, const GHOST_IWi
void GHOST_EventManager::disposeEvents() void GHOST_EventManager::disposeEvents()
{ {
while (m_handled_events.empty() == false) { while (handled_events_.empty() == false) {
GHOST_ASSERT(m_handled_events[0], "invalid event"); GHOST_ASSERT(handled_events_[0], "invalid event");
delete m_handled_events[0]; delete handled_events_[0];
m_handled_events.pop_front(); handled_events_.pop_front();
} }
while (m_events.empty() == false) { while (events_.empty() == false) {
GHOST_ASSERT(m_events[0], "invalid event"); GHOST_ASSERT(events_[0], "invalid event");
delete m_events[0]; delete events_[0];
m_events.pop_front(); events_.pop_front();
} }
} }

View File

@@ -111,14 +111,14 @@ class GHOST_EventManager {
using TEventStack = std::deque<const GHOST_IEvent *>; using TEventStack = std::deque<const GHOST_IEvent *>;
/** The event stack. */ /** The event stack. */
std::deque<const GHOST_IEvent *> m_events; std::deque<const GHOST_IEvent *> events_;
std::deque<const GHOST_IEvent *> m_handled_events; std::deque<const GHOST_IEvent *> handled_events_;
/** A vector with event consumers. */ /** A vector with event consumers. */
using TConsumerVector = std::vector<GHOST_IEventConsumer *>; using TConsumerVector = std::vector<GHOST_IEventConsumer *>;
/** The list with event consumers. */ /** The list with event consumers. */
TConsumerVector m_consumers; TConsumerVector consumers_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_EventManager") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_EventManager")
}; };

View File

@@ -16,24 +16,24 @@
class GHOST_EventNDOFMotion : public GHOST_Event { class GHOST_EventNDOFMotion : public GHOST_Event {
protected: protected:
GHOST_TEventNDOFMotionData m_axisData; GHOST_TEventNDOFMotionData axis_data_;
public: public:
GHOST_EventNDOFMotion(uint64_t time, GHOST_IWindow *window) GHOST_EventNDOFMotion(uint64_t time, GHOST_IWindow *window)
: GHOST_Event(time, GHOST_kEventNDOFMotion, window) : GHOST_Event(time, GHOST_kEventNDOFMotion, window)
{ {
m_data = &m_axisData; data_ = &axis_data_;
} }
}; };
class GHOST_EventNDOFButton : public GHOST_Event { class GHOST_EventNDOFButton : public GHOST_Event {
protected: protected:
GHOST_TEventNDOFButtonData m_buttonData; GHOST_TEventNDOFButtonData button_data_;
public: public:
GHOST_EventNDOFButton(uint64_t time, GHOST_IWindow *window) GHOST_EventNDOFButton(uint64_t time, GHOST_IWindow *window)
: GHOST_Event(time, GHOST_kEventNDOFButton, window) : GHOST_Event(time, GHOST_kEventNDOFButton, window)
{ {
m_data = &m_buttonData; data_ = &button_data_;
} }
}; };

View File

@@ -29,13 +29,13 @@ class GHOST_EventString : public GHOST_Event {
GHOST_TEventDataPtr data_ptr) GHOST_TEventDataPtr data_ptr)
: GHOST_Event(msec, type, window) : GHOST_Event(msec, type, window)
{ {
m_data = data_ptr; data_ = data_ptr;
} }
~GHOST_EventString() override ~GHOST_EventString() override
{ {
if (m_data) { if (data_) {
free((void *)m_data); free((void *)data_);
} }
} }
}; };

View File

@@ -34,16 +34,16 @@ class GHOST_EventTrackpad : public GHOST_Event {
bool isDirectionInverted) bool isDirectionInverted)
: GHOST_Event(msec, GHOST_kEventTrackpad, window) : GHOST_Event(msec, GHOST_kEventTrackpad, window)
{ {
m_trackpadEventData.subtype = subtype; trackpad_event_data_.subtype = subtype;
m_trackpadEventData.x = x; trackpad_event_data_.x = x;
m_trackpadEventData.y = y; trackpad_event_data_.y = y;
m_trackpadEventData.deltaX = deltaX; trackpad_event_data_.deltaX = deltaX;
m_trackpadEventData.deltaY = deltaY; trackpad_event_data_.deltaY = deltaY;
m_trackpadEventData.isDirectionInverted = isDirectionInverted; trackpad_event_data_.isDirectionInverted = isDirectionInverted;
m_data = &m_trackpadEventData; data_ = &trackpad_event_data_;
} }
protected: protected:
/** The mouse pan data */ /** The mouse pan data */
GHOST_TEventTrackpadData m_trackpadEventData; GHOST_TEventTrackpadData trackpad_event_data_;
}; };

View File

@@ -28,11 +28,11 @@ class GHOST_EventWheel : public GHOST_Event {
GHOST_EventWheel(uint64_t msec, GHOST_IWindow *window, GHOST_TEventWheelAxis axis, int32_t value) GHOST_EventWheel(uint64_t msec, GHOST_IWindow *window, GHOST_TEventWheelAxis axis, int32_t value)
: GHOST_Event(msec, GHOST_kEventWheel, window) : GHOST_Event(msec, GHOST_kEventWheel, window)
{ {
m_wheelEventData.axis = axis; wheel_event_data_.axis = axis;
m_wheelEventData.value = value; wheel_event_data_.value = value;
m_data = &m_wheelEventData; data_ = &wheel_event_data_;
} }
protected: protected:
GHOST_TEventWheelData m_wheelEventData; GHOST_TEventWheelData wheel_event_data_;
}; };

View File

@@ -34,10 +34,10 @@
static CLG_LogRef LOG = {"ghost.system"}; static CLG_LogRef LOG = {"ghost.system"};
GHOST_ISystem *GHOST_ISystem::m_system = nullptr; GHOST_ISystem *GHOST_ISystem::system_ = nullptr;
const char *GHOST_ISystem::m_system_backend_id = nullptr; const char *GHOST_ISystem::system_backend_id_ = nullptr;
GHOST_TBacktraceFn GHOST_ISystem::m_backtrace_fn = nullptr; GHOST_TBacktraceFn GHOST_ISystem::backtrace_fn_ = nullptr;
GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool background) GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool background)
{ {
@@ -52,7 +52,7 @@ GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool b
std::vector<GHOST_BackendInfo> backends_attempted; std::vector<GHOST_BackendInfo> backends_attempted;
GHOST_TSuccess success; GHOST_TSuccess success;
if (!m_system) { if (!system_) {
#if defined(WITH_HEADLESS) #if defined(WITH_HEADLESS)
/* Pass. */ /* Pass. */
@@ -72,98 +72,98 @@ GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool b
backends_attempted.push_back({"WAYLAND"}); backends_attempted.push_back({"WAYLAND"});
try { try {
CLOG_INFO(&LOG, "Create Wayland system"); CLOG_INFO(&LOG, "Create Wayland system");
m_system = new GHOST_SystemWayland(background); system_ = new GHOST_SystemWayland(background);
} }
catch (const std::runtime_error &e) { catch (const std::runtime_error &e) {
if (verbose) { if (verbose) {
backends_attempted.back().failure_msg = e.what(); backends_attempted.back().failure_msg = e.what();
} }
CLOG_INFO(&LOG, "Wayland system not created, falling back to X11"); CLOG_INFO(&LOG, "Wayland system not created, falling back to X11");
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
# ifdef WITH_GHOST_WAYLAND_DYNLOAD # ifdef WITH_GHOST_WAYLAND_DYNLOAD
ghost_wl_dynload_libraries_exit(); ghost_wl_dynload_libraries_exit();
# endif # endif
} }
} }
else { else {
m_system = nullptr; system_ = nullptr;
} }
if (!m_system) { if (!system_) {
/* Try to fall back to X11. */ /* Try to fall back to X11. */
backends_attempted.push_back({"X11"}); backends_attempted.push_back({"X11"});
try { try {
CLOG_INFO(&LOG, "Create X11 system"); CLOG_INFO(&LOG, "Create X11 system");
m_system = new GHOST_SystemX11(); system_ = new GHOST_SystemX11();
} }
catch (const std::runtime_error &e) { catch (const std::runtime_error &e) {
if (verbose) { if (verbose) {
backends_attempted.back().failure_msg = e.what(); backends_attempted.back().failure_msg = e.what();
} }
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
} }
} }
#elif defined(WITH_GHOST_X11) #elif defined(WITH_GHOST_X11)
backends_attempted.push_back({"X11"}); backends_attempted.push_back({"X11"});
try { try {
CLOG_INFO(&LOG, "Create X11 system"); CLOG_INFO(&LOG, "Create X11 system");
m_system = new GHOST_SystemX11(); system_ = new GHOST_SystemX11();
} }
catch (const std::runtime_error &e) { catch (const std::runtime_error &e) {
if (verbose) { if (verbose) {
backends_attempted.back().failure_msg = e.what(); backends_attempted.back().failure_msg = e.what();
} }
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
} }
#elif defined(WITH_GHOST_WAYLAND) #elif defined(WITH_GHOST_WAYLAND)
if (has_wayland_libraries) { if (has_wayland_libraries) {
backends_attempted.push_back({"WAYLAND"}); backends_attempted.push_back({"WAYLAND"});
try { try {
CLOG_INFO(&LOG, "Create Wayland system"); CLOG_INFO(&LOG, "Create Wayland system");
m_system = new GHOST_SystemWayland(background); system_ = new GHOST_SystemWayland(background);
} }
catch (const std::runtime_error &e) { catch (const std::runtime_error &e) {
if (verbose) { if (verbose) {
backends_attempted.back().failure_msg = e.what(); backends_attempted.back().failure_msg = e.what();
} }
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
# ifdef WITH_GHOST_WAYLAND_DYNLOAD # ifdef WITH_GHOST_WAYLAND_DYNLOAD
ghost_wl_dynload_libraries_exit(); ghost_wl_dynload_libraries_exit();
# endif # endif
} }
} }
else { else {
m_system = nullptr; system_ = nullptr;
} }
#elif defined(WITH_GHOST_SDL) #elif defined(WITH_GHOST_SDL)
backends_attempted.push_back({"SDL"}); backends_attempted.push_back({"SDL"});
try { try {
CLOG_INFO(&LOG, "Create SDL system"); CLOG_INFO(&LOG, "Create SDL system");
m_system = new GHOST_SystemSDL(); system_ = new GHOST_SystemSDL();
} }
catch (const std::runtime_error &e) { catch (const std::runtime_error &e) {
if (verbose) { if (verbose) {
backends_attempted.back().failure_msg = e.what(); backends_attempted.back().failure_msg = e.what();
} }
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
} }
#elif defined(WIN32) #elif defined(WIN32)
backends_attempted.push_back({"WIN32"}); backends_attempted.push_back({"WIN32"});
CLOG_INFO(&LOG, "Create Windows system"); CLOG_INFO(&LOG, "Create Windows system");
m_system = new GHOST_SystemWin32(); system_ = new GHOST_SystemWin32();
#elif defined(__APPLE__) #elif defined(__APPLE__)
backends_attempted.push_back({"COCOA"}); backends_attempted.push_back({"COCOA"});
CLOG_INFO(&LOG, "Create Cocoa system"); CLOG_INFO(&LOG, "Create Cocoa system");
m_system = new GHOST_SystemCocoa(); system_ = new GHOST_SystemCocoa();
#endif #endif
if (m_system) { if (system_) {
m_system_backend_id = backends_attempted.back().id; system_backend_id_ = backends_attempted.back().id;
} }
else if (verbose || CLOG_CHECK(&LOG, CLG_LEVEL_INFO)) { else if (verbose || CLOG_CHECK(&LOG, CLG_LEVEL_INFO)) {
bool show_messages = false; bool show_messages = false;
@@ -191,13 +191,13 @@ GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool b
} }
CLOG_STR_INFO_NOCHECK(&LOG, msg.c_str()); CLOG_STR_INFO_NOCHECK(&LOG, msg.c_str());
} }
success = m_system != nullptr ? GHOST_kSuccess : GHOST_kFailure; success = system_ != nullptr ? GHOST_kSuccess : GHOST_kFailure;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
} }
if (success) { if (success) {
success = m_system->init(); success = system_->init();
} }
return success; return success;
} }
@@ -205,7 +205,7 @@ GHOST_TSuccess GHOST_ISystem::createSystem(bool verbose, [[maybe_unused]] bool b
GHOST_TSuccess GHOST_ISystem::createSystemBackground() GHOST_TSuccess GHOST_ISystem::createSystemBackground()
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (!m_system) { if (!system_) {
#if !defined(WITH_HEADLESS) #if !defined(WITH_HEADLESS)
/* Try to create a off-screen render surface with the graphical systems. */ /* Try to create a off-screen render surface with the graphical systems. */
CLOG_INFO(&LOG, "Create background system"); CLOG_INFO(&LOG, "Create background system");
@@ -216,14 +216,14 @@ GHOST_TSuccess GHOST_ISystem::createSystemBackground()
/* Try to fall back to headless mode if all else fails. */ /* Try to fall back to headless mode if all else fails. */
#endif #endif
CLOG_INFO(&LOG, "Create headless system"); CLOG_INFO(&LOG, "Create headless system");
m_system = new GHOST_SystemHeadless(); system_ = new GHOST_SystemHeadless();
success = m_system != nullptr ? GHOST_kSuccess : GHOST_kFailure; success = system_ != nullptr ? GHOST_kSuccess : GHOST_kFailure;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
} }
if (success) { if (success) {
success = m_system->init(); success = system_->init();
} }
return success; return success;
} }
@@ -232,9 +232,9 @@ GHOST_TSuccess GHOST_ISystem::disposeSystem()
{ {
CLOG_DEBUG(&LOG, "Dispose system"); CLOG_DEBUG(&LOG, "Dispose system");
GHOST_TSuccess success = GHOST_kSuccess; GHOST_TSuccess success = GHOST_kSuccess;
if (m_system) { if (system_) {
delete m_system; delete system_;
m_system = nullptr; system_ = nullptr;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -244,20 +244,20 @@ GHOST_TSuccess GHOST_ISystem::disposeSystem()
GHOST_ISystem *GHOST_ISystem::getSystem() GHOST_ISystem *GHOST_ISystem::getSystem()
{ {
return m_system; return system_;
} }
const char *GHOST_ISystem::getSystemBackend() const char *GHOST_ISystem::getSystemBackend()
{ {
return m_system_backend_id; return system_backend_id_;
} }
GHOST_TBacktraceFn GHOST_ISystem::getBacktraceFn() GHOST_TBacktraceFn GHOST_ISystem::getBacktraceFn()
{ {
return GHOST_ISystem::m_backtrace_fn; return GHOST_ISystem::backtrace_fn_;
} }
void GHOST_ISystem::setBacktraceFn(GHOST_TBacktraceFn backtrace_fn) void GHOST_ISystem::setBacktraceFn(GHOST_TBacktraceFn backtrace_fn)
{ {
GHOST_ISystem::m_backtrace_fn = backtrace_fn; GHOST_ISystem::backtrace_fn_ = backtrace_fn;
} }

View File

@@ -22,22 +22,22 @@
# endif # endif
#endif #endif
GHOST_ISystemPaths *GHOST_ISystemPaths::m_systemPaths = nullptr; GHOST_ISystemPaths *GHOST_ISystemPaths::system_paths_ = nullptr;
GHOST_TSuccess GHOST_ISystemPaths::create() GHOST_TSuccess GHOST_ISystemPaths::create()
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (!m_systemPaths) { if (!system_paths_) {
#ifdef WIN32 #ifdef WIN32
m_systemPaths = new GHOST_SystemPathsWin32(); system_paths_ = new GHOST_SystemPathsWin32();
#else #else
# ifdef __APPLE__ # ifdef __APPLE__
m_systemPaths = new GHOST_SystemPathsCocoa(); system_paths_ = new GHOST_SystemPathsCocoa();
# else # else
m_systemPaths = new GHOST_SystemPathsUnix(); system_paths_ = new GHOST_SystemPathsUnix();
# endif # endif
#endif #endif
success = m_systemPaths != nullptr ? GHOST_kSuccess : GHOST_kFailure; success = system_paths_ != nullptr ? GHOST_kSuccess : GHOST_kFailure;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -48,9 +48,9 @@ GHOST_TSuccess GHOST_ISystemPaths::create()
GHOST_TSuccess GHOST_ISystemPaths::dispose() GHOST_TSuccess GHOST_ISystemPaths::dispose()
{ {
GHOST_TSuccess success = GHOST_kSuccess; GHOST_TSuccess success = GHOST_kSuccess;
if (m_systemPaths) { if (system_paths_) {
delete m_systemPaths; delete system_paths_;
m_systemPaths = nullptr; system_paths_ = nullptr;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -60,8 +60,8 @@ GHOST_TSuccess GHOST_ISystemPaths::dispose()
GHOST_ISystemPaths *GHOST_ISystemPaths::get() GHOST_ISystemPaths *GHOST_ISystemPaths::get()
{ {
if (!m_systemPaths) { if (!system_paths_) {
create(); create();
} }
return m_systemPaths; return system_paths_;
} }

View File

@@ -150,8 +150,8 @@ void GHOST_ImeWin32::DestroyImeWindow(HWND /*window_handle*/)
void GHOST_ImeWin32::MoveImeWindow(HWND /*window_handle*/, HIMC imm_context) void GHOST_ImeWin32::MoveImeWindow(HWND /*window_handle*/, HIMC imm_context)
{ {
int x = caret_rect_.m_l; int x = caret_rect_.l_;
int y = caret_rect_.m_t; int y = caret_rect_.t_;
const int kCaretMargin = 1; const int kCaretMargin = 1;
/** /**
* As written in a comment in GHOST_ImeWin32::CreateImeWindow(), * As written in a comment in GHOST_ImeWin32::CreateImeWindow(),
@@ -193,7 +193,7 @@ void GHOST_ImeWin32::MoveImeWindow(HWND /*window_handle*/, HIMC imm_context)
void GHOST_ImeWin32::UpdateImeWindow(HWND window_handle) void GHOST_ImeWin32::UpdateImeWindow(HWND window_handle)
{ {
/* Just move the IME window attached to the given window. */ /* Just move the IME window attached to the given window. */
if (caret_rect_.m_l >= 0 && caret_rect_.m_t >= 0) { if (caret_rect_.l_ >= 0 && caret_rect_.t_ >= 0) {
HIMC imm_context = ::ImmGetContext(window_handle); HIMC imm_context = ::ImmGetContext(window_handle);
if (imm_context) { if (imm_context) {
MoveImeWindow(window_handle, imm_context); MoveImeWindow(window_handle, imm_context);
@@ -460,7 +460,7 @@ void GHOST_ImeWin32::BeginIME(HWND window_handle, const GHOST_Rect &caret_rect,
* This update is used for moving an IME window when a renderer process * This update is used for moving an IME window when a renderer process
* resize/moves the input caret. * resize/moves the input caret.
*/ */
if (caret_rect.m_l >= 0 && caret_rect.m_t >= 0) { if (caret_rect.l_ >= 0 && caret_rect.t_ >= 0) {
caret_rect_ = caret_rect; caret_rect_ = caret_rect;
MoveImeWindow(window_handle, imm_context); MoveImeWindow(window_handle, imm_context);
} }

View File

@@ -36,7 +36,7 @@ class GHOST_EventIME : public GHOST_Event {
const void *customdata) const void *customdata)
: GHOST_Event(msec, type, window) : GHOST_Event(msec, type, window)
{ {
this->m_data = customdata; this->data_ = customdata;
} }
}; };

View File

@@ -67,25 +67,25 @@ bool GHOST_ModifierKeys::get(GHOST_TModifierKey mask) const
{ {
switch (mask) { switch (mask) {
case GHOST_kModifierKeyLeftShift: case GHOST_kModifierKeyLeftShift:
return m_LeftShift; return left_shift_;
case GHOST_kModifierKeyRightShift: case GHOST_kModifierKeyRightShift:
return m_RightShift; return right_shift_;
case GHOST_kModifierKeyLeftAlt: case GHOST_kModifierKeyLeftAlt:
return m_LeftAlt; return left_alt_;
case GHOST_kModifierKeyRightAlt: case GHOST_kModifierKeyRightAlt:
return m_RightAlt; return right_alt_;
case GHOST_kModifierKeyLeftControl: case GHOST_kModifierKeyLeftControl:
return m_LeftControl; return left_control_;
case GHOST_kModifierKeyRightControl: case GHOST_kModifierKeyRightControl:
return m_RightControl; return right_control_;
case GHOST_kModifierKeyLeftOS: case GHOST_kModifierKeyLeftOS:
return m_LeftOS; return left_os_;
case GHOST_kModifierKeyRightOS: case GHOST_kModifierKeyRightOS:
return m_RightOS; return right_os_;
case GHOST_kModifierKeyLeftHyper: case GHOST_kModifierKeyLeftHyper:
return m_LeftHyper; return left_hyper_;
case GHOST_kModifierKeyRightHyper: case GHOST_kModifierKeyRightHyper:
return m_RightHyper; return right_hyper_;
default: default:
GHOST_ASSERT(0, "Invalid key!"); GHOST_ASSERT(0, "Invalid key!");
return false; return false;
@@ -96,34 +96,34 @@ void GHOST_ModifierKeys::set(GHOST_TModifierKey mask, bool down)
{ {
switch (mask) { switch (mask) {
case GHOST_kModifierKeyLeftShift: case GHOST_kModifierKeyLeftShift:
m_LeftShift = down; left_shift_ = down;
break; break;
case GHOST_kModifierKeyRightShift: case GHOST_kModifierKeyRightShift:
m_RightShift = down; right_shift_ = down;
break; break;
case GHOST_kModifierKeyLeftAlt: case GHOST_kModifierKeyLeftAlt:
m_LeftAlt = down; left_alt_ = down;
break; break;
case GHOST_kModifierKeyRightAlt: case GHOST_kModifierKeyRightAlt:
m_RightAlt = down; right_alt_ = down;
break; break;
case GHOST_kModifierKeyLeftControl: case GHOST_kModifierKeyLeftControl:
m_LeftControl = down; left_control_ = down;
break; break;
case GHOST_kModifierKeyRightControl: case GHOST_kModifierKeyRightControl:
m_RightControl = down; right_control_ = down;
break; break;
case GHOST_kModifierKeyLeftOS: case GHOST_kModifierKeyLeftOS:
m_LeftOS = down; left_os_ = down;
break; break;
case GHOST_kModifierKeyRightOS: case GHOST_kModifierKeyRightOS:
m_RightOS = down; right_os_ = down;
break; break;
case GHOST_kModifierKeyLeftHyper: case GHOST_kModifierKeyLeftHyper:
m_LeftHyper = down; left_hyper_ = down;
break; break;
case GHOST_kModifierKeyRightHyper: case GHOST_kModifierKeyRightHyper:
m_RightHyper = down; right_hyper_ = down;
break; break;
default: default:
GHOST_ASSERT(0, "Invalid key!"); GHOST_ASSERT(0, "Invalid key!");
@@ -133,23 +133,23 @@ void GHOST_ModifierKeys::set(GHOST_TModifierKey mask, bool down)
void GHOST_ModifierKeys::clear() void GHOST_ModifierKeys::clear()
{ {
m_LeftShift = false; left_shift_ = false;
m_RightShift = false; right_shift_ = false;
m_LeftAlt = false; left_alt_ = false;
m_RightAlt = false; right_alt_ = false;
m_LeftControl = false; left_control_ = false;
m_RightControl = false; right_control_ = false;
m_LeftOS = false; left_os_ = false;
m_RightOS = false; right_os_ = false;
m_LeftHyper = false; left_hyper_ = false;
m_RightHyper = false; right_hyper_ = false;
} }
bool GHOST_ModifierKeys::equals(const GHOST_ModifierKeys &keys) const bool GHOST_ModifierKeys::equals(const GHOST_ModifierKeys &keys) const
{ {
return (m_LeftShift == keys.m_LeftShift) && (m_RightShift == keys.m_RightShift) && return (left_shift_ == keys.left_shift_) && (right_shift_ == keys.right_shift_) &&
(m_LeftAlt == keys.m_LeftAlt) && (m_RightAlt == keys.m_RightAlt) && (left_alt_ == keys.left_alt_) && (right_alt_ == keys.right_alt_) &&
(m_LeftControl == keys.m_LeftControl) && (m_RightControl == keys.m_RightControl) && (left_control_ == keys.left_control_) && (right_control_ == keys.right_control_) &&
(m_LeftOS == keys.m_LeftOS) && (m_RightOS == keys.m_RightOS) && (left_os_ == keys.left_os_) && (right_os_ == keys.right_os_) &&
(m_LeftHyper == keys.m_LeftHyper) && (m_RightHyper == keys.m_RightHyper); (left_hyper_ == keys.left_hyper_) && (right_hyper_ == keys.right_hyper_);
} }

View File

@@ -57,20 +57,20 @@ struct GHOST_ModifierKeys {
bool equals(const GHOST_ModifierKeys &keys) const; bool equals(const GHOST_ModifierKeys &keys) const;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_LeftShift : 1; uint8_t left_shift_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_RightShift : 1; uint8_t right_shift_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_LeftAlt : 1; uint8_t left_alt_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_RightAlt : 1; uint8_t right_alt_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_LeftControl : 1; uint8_t left_control_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_RightControl : 1; uint8_t right_control_ : 1;
/** Bit-field that stores the appropriate key state. */ /** Bit-field that stores the appropriate key state. */
uint8_t m_LeftOS : 1; uint8_t left_os_ : 1;
uint8_t m_RightOS : 1; uint8_t right_os_ : 1;
uint8_t m_LeftHyper : 1; uint8_t left_hyper_ : 1;
uint8_t m_RightHyper : 1; uint8_t right_hyper_ : 1;
}; };

View File

@@ -12,39 +12,39 @@ void GHOST_Rect::inset(int32_t i)
{ {
if (i > 0) { if (i > 0) {
/* Grow the rectangle. */ /* Grow the rectangle. */
m_l -= i; l_ -= i;
m_r += i; r_ += i;
m_t -= i; t_ -= i;
m_b += i; b_ += i;
} }
else if (i < 0) { else if (i < 0) {
/* Shrink the rectangle, check for insets larger than half the size. */ /* Shrink the rectangle, check for insets larger than half the size. */
int32_t i2 = i * 2; int32_t i2 = i * 2;
if (getWidth() > i2) { if (getWidth() > i2) {
m_l += i; l_ += i;
m_r -= i; r_ -= i;
} }
else { else {
m_l = m_l + ((m_r - m_l) / 2); l_ = l_ + ((r_ - l_) / 2);
m_r = m_l; r_ = l_;
} }
if (getHeight() > i2) { if (getHeight() > i2) {
m_t += i; t_ += i;
m_b -= i; b_ -= i;
} }
else { else {
m_t = m_t + ((m_b - m_t) / 2); t_ = t_ + ((b_ - t_) / 2);
m_b = m_t; b_ = t_;
} }
} }
} }
GHOST_TVisibility GHOST_Rect::getVisibility(GHOST_Rect &r) const GHOST_TVisibility GHOST_Rect::getVisibility(GHOST_Rect &r) const
{ {
bool lt = isInside(r.m_l, r.m_t); bool lt = isInside(r.l_, r.t_);
bool rt = isInside(r.m_r, r.m_t); bool rt = isInside(r.r_, r.t_);
bool lb = isInside(r.m_l, r.m_b); bool lb = isInside(r.l_, r.b_);
bool rb = isInside(r.m_r, r.m_b); bool rb = isInside(r.r_, r.b_);
GHOST_TVisibility v; GHOST_TVisibility v;
if (lt && rt && lb && rb) { if (lt && rt && lb && rb) {
/* All points inside, rectangle is inside this. */ /* All points inside, rectangle is inside this. */
@@ -53,7 +53,7 @@ GHOST_TVisibility GHOST_Rect::getVisibility(GHOST_Rect &r) const
else if (!(lt || rt || lb || rb)) { else if (!(lt || rt || lb || rb)) {
/* None of the points inside. /* None of the points inside.
* Check to see whether the rectangle is larger than this one. */ * Check to see whether the rectangle is larger than this one. */
if ((r.m_l < m_l) && (r.m_t < m_t) && (r.m_r > m_r) && (r.m_b > m_b)) { if ((r.l_ < l_) && (r.t_ < t_) && (r.r_ > r_) && (r.b_ > b_)) {
v = GHOST_kPartiallyVisible; v = GHOST_kPartiallyVisible;
} }
else { else {
@@ -69,12 +69,12 @@ GHOST_TVisibility GHOST_Rect::getVisibility(GHOST_Rect &r) const
void GHOST_Rect::setCenter(int32_t cx, int32_t cy) void GHOST_Rect::setCenter(int32_t cx, int32_t cy)
{ {
int32_t offset = cx - (m_l + (m_r - m_l) / 2); int32_t offset = cx - (l_ + (r_ - l_) / 2);
m_l += offset; l_ += offset;
m_r += offset; r_ += offset;
offset = cy - (m_t + (m_b - m_t) / 2); offset = cy - (t_ + (b_ - t_) / 2);
m_t += offset; t_ += offset;
m_b += offset; b_ += offset;
} }
void GHOST_Rect::setCenter(int32_t cx, int32_t cy, int32_t w, int32_t h) void GHOST_Rect::setCenter(int32_t cx, int32_t cy, int32_t w, int32_t h)
@@ -83,29 +83,29 @@ void GHOST_Rect::setCenter(int32_t cx, int32_t cy, int32_t w, int32_t h)
w_2 = w >> 1; w_2 = w >> 1;
h_2 = h >> 1; h_2 = h >> 1;
m_l = cx - w_2; l_ = cx - w_2;
m_t = cy - h_2; t_ = cy - h_2;
m_r = m_l + w; r_ = l_ + w;
m_b = m_t + h; b_ = t_ + h;
} }
bool GHOST_Rect::clip(GHOST_Rect &r) const bool GHOST_Rect::clip(GHOST_Rect &r) const
{ {
bool clipped = false; bool clipped = false;
if (r.m_l < m_l) { if (r.l_ < l_) {
r.m_l = m_l; r.l_ = l_;
clipped = true; clipped = true;
} }
if (r.m_t < m_t) { if (r.t_ < t_) {
r.m_t = m_t; r.t_ = t_;
clipped = true; clipped = true;
} }
if (r.m_r > m_r) { if (r.r_ > r_) {
r.m_r = m_r; r.r_ = r_;
clipped = true; clipped = true;
} }
if (r.m_b > m_b) { if (r.b_ > b_) {
r.m_b = m_b; r.b_ = b_;
clipped = true; clipped = true;
} }
return clipped; return clipped;

View File

@@ -18,18 +18,18 @@
#endif #endif
GHOST_System::GHOST_System() GHOST_System::GHOST_System()
: m_nativePixel(false), : native_pixel_(false),
m_windowFocus(true), window_focus_(true),
m_autoFocus(true), auto_focus_(true),
m_timerManager(nullptr), timer_manager_(nullptr),
m_windowManager(nullptr), window_manager_(nullptr),
m_eventManager(nullptr), event_manager_(nullptr),
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
m_ndofManager(nullptr), ndof_manager_(nullptr),
#endif #endif
m_multitouchGestures(true), multitouch_gestures_(true),
m_tabletAPI(GHOST_kTabletAutomatic), tablet_api_(GHOST_kTabletAutomatic),
m_is_debug_enabled(false) is_debug_enabled_(false)
{ {
} }
@@ -57,15 +57,15 @@ GHOST_TSuccess GHOST_System::putClipboardImage(uint * /*rgba*/,
GHOST_ITimerTask *GHOST_System::installTimer(uint64_t delay, GHOST_ITimerTask *GHOST_System::installTimer(uint64_t delay,
uint64_t interval, uint64_t interval,
GHOST_TimerProcPtr timerProc, GHOST_TimerProcPtr timer_proc,
GHOST_TUserDataPtr userData) GHOST_TUserDataPtr user_data)
{ {
uint64_t millis = getMilliSeconds(); uint64_t millis = getMilliSeconds();
GHOST_TimerTask *timer = new GHOST_TimerTask(millis + delay, interval, timerProc, userData); GHOST_TimerTask *timer = new GHOST_TimerTask(millis + delay, interval, timer_proc, user_data);
if (timer) { if (timer) {
if (m_timerManager->addTimer(timer) == GHOST_kSuccess) { if (timer_manager_->addTimer(timer) == GHOST_kSuccess) {
/* Check to see whether we need to fire the timer right away. */ /* Check to see whether we need to fire the timer right away. */
m_timerManager->fireTimers(millis); timer_manager_->fireTimers(millis);
} }
else { else {
delete timer; delete timer;
@@ -79,7 +79,7 @@ GHOST_TSuccess GHOST_System::removeTimer(GHOST_ITimerTask *timerTask)
{ {
GHOST_TSuccess success = GHOST_kFailure; GHOST_TSuccess success = GHOST_kFailure;
if (timerTask) { if (timerTask) {
success = m_timerManager->removeTimer((GHOST_TimerTask *)timerTask); success = timer_manager_->removeTimer((GHOST_TimerTask *)timerTask);
} }
return success; return success;
} }
@@ -91,9 +91,9 @@ GHOST_TSuccess GHOST_System::disposeWindow(GHOST_IWindow *window)
/* /*
* Remove all pending events for the window. * Remove all pending events for the window.
*/ */
if (m_windowManager->getWindowFound(window)) { if (window_manager_->getWindowFound(window)) {
m_eventManager->removeWindowEvents(window); event_manager_->removeWindowEvents(window);
success = m_windowManager->removeWindow(window); success = window_manager_->removeWindow(window);
if (success) { if (success) {
delete window; delete window;
} }
@@ -106,7 +106,7 @@ GHOST_TSuccess GHOST_System::disposeWindow(GHOST_IWindow *window)
bool GHOST_System::validWindow(GHOST_IWindow *window) bool GHOST_System::validWindow(GHOST_IWindow *window)
{ {
return m_windowManager->getWindowFound(window); return window_manager_->getWindowFound(window);
} }
GHOST_IWindow *GHOST_System::getWindowUnderCursor(int32_t x, int32_t y) GHOST_IWindow *GHOST_System::getWindowUnderCursor(int32_t x, int32_t y)
@@ -115,7 +115,7 @@ GHOST_IWindow *GHOST_System::getWindowUnderCursor(int32_t x, int32_t y)
* It is imperfect but usable in most cases. Ideally each platform should provide * It is imperfect but usable in most cases. Ideally each platform should provide
* a custom version of this function that properly considers z-order. */ * a custom version of this function that properly considers z-order. */
std::vector<GHOST_IWindow *> windows = m_windowManager->getWindows(); std::vector<GHOST_IWindow *> windows = window_manager_->getWindows();
std::vector<GHOST_IWindow *>::reverse_iterator iwindow_iter; std::vector<GHOST_IWindow *>::reverse_iterator iwindow_iter;
/* Search through the windows in reverse order because in most cases /* Search through the windows in reverse order because in most cases
@@ -143,23 +143,23 @@ void GHOST_System::dispatchEvents()
{ {
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
/* NDOF Motion event is sent only once per dispatch, so do it now: */ /* NDOF Motion event is sent only once per dispatch, so do it now: */
if (m_ndofManager) { if (ndof_manager_) {
m_ndofManager->sendMotionEvent(); ndof_manager_->sendMotionEvent();
} }
#endif #endif
if (m_eventManager) { if (event_manager_) {
m_eventManager->dispatchEvents(); event_manager_->dispatchEvents();
} }
m_timerManager->fireTimers(getMilliSeconds()); timer_manager_->fireTimers(getMilliSeconds());
} }
GHOST_TSuccess GHOST_System::addEventConsumer(GHOST_IEventConsumer *consumer) GHOST_TSuccess GHOST_System::addEventConsumer(GHOST_IEventConsumer *consumer)
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_eventManager) { if (event_manager_) {
success = m_eventManager->addConsumer(consumer); success = event_manager_->addConsumer(consumer);
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -170,8 +170,8 @@ GHOST_TSuccess GHOST_System::addEventConsumer(GHOST_IEventConsumer *consumer)
GHOST_TSuccess GHOST_System::removeEventConsumer(GHOST_IEventConsumer *consumer) GHOST_TSuccess GHOST_System::removeEventConsumer(GHOST_IEventConsumer *consumer)
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_eventManager) { if (event_manager_) {
success = m_eventManager->removeConsumer(consumer); success = event_manager_->removeConsumer(consumer);
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -182,8 +182,8 @@ GHOST_TSuccess GHOST_System::removeEventConsumer(GHOST_IEventConsumer *consumer)
GHOST_TSuccess GHOST_System::pushEvent(const GHOST_IEvent *event) GHOST_TSuccess GHOST_System::pushEvent(const GHOST_IEvent *event)
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_eventManager) { if (event_manager_) {
success = m_eventManager->pushEvent(event); success = event_manager_->pushEvent(event);
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -219,43 +219,43 @@ uint32_t GHOST_System::getCursorPreferredLogicalSize() const
return uint32_t(24); return uint32_t(24);
} }
GHOST_TSuccess GHOST_System::getModifierKeyState(GHOST_TModifierKey mask, bool &isDown) const GHOST_TSuccess GHOST_System::getModifierKeyState(GHOST_TModifierKey mask, bool &is_down) const
{ {
GHOST_ModifierKeys keys; GHOST_ModifierKeys keys;
/* Get the state of all modifier keys. */ /* Get the state of all modifier keys. */
GHOST_TSuccess success = getModifierKeys(keys); GHOST_TSuccess success = getModifierKeys(keys);
if (success) { if (success) {
/* Isolate the state of the key requested. */ /* Isolate the state of the key requested. */
isDown = keys.get(mask); is_down = keys.get(mask);
} }
return success; return success;
} }
GHOST_TSuccess GHOST_System::getButtonState(GHOST_TButton mask, bool &isDown) const GHOST_TSuccess GHOST_System::getButtonState(GHOST_TButton mask, bool &is_down) const
{ {
GHOST_Buttons buttons; GHOST_Buttons buttons;
/* Get the state of all mouse buttons. */ /* Get the state of all mouse buttons. */
GHOST_TSuccess success = getButtons(buttons); GHOST_TSuccess success = getButtons(buttons);
if (success) { if (success) {
/* Isolate the state of the mouse button requested. */ /* Isolate the state of the mouse button requested. */
isDown = buttons.get(mask); is_down = buttons.get(mask);
} }
return success; return success;
} }
void GHOST_System::setMultitouchGestures(const bool use) void GHOST_System::setMultitouchGestures(const bool use)
{ {
m_multitouchGestures = use; multitouch_gestures_ = use;
} }
void GHOST_System::setTabletAPI(GHOST_TTabletAPI api) void GHOST_System::setTabletAPI(GHOST_TTabletAPI api)
{ {
m_tabletAPI = api; tablet_api_ = api;
} }
GHOST_TTabletAPI GHOST_System::getTabletAPI() GHOST_TTabletAPI GHOST_System::getTabletAPI()
{ {
return m_tabletAPI; return tablet_api_;
} }
GHOST_TSuccess GHOST_System::getPixelAtCursor(float /*r_color*/[3]) const GHOST_TSuccess GHOST_System::getPixelAtCursor(float /*r_color*/[3]) const
@@ -266,26 +266,26 @@ GHOST_TSuccess GHOST_System::getPixelAtCursor(float /*r_color*/[3]) const
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
void GHOST_System::setNDOFDeadZone(float deadzone) void GHOST_System::setNDOFDeadZone(float deadzone)
{ {
if (this->m_ndofManager) { if (this->ndof_manager_) {
this->m_ndofManager->setDeadZone(deadzone); this->ndof_manager_->setDeadZone(deadzone);
} }
} }
#endif #endif
GHOST_TSuccess GHOST_System::init() GHOST_TSuccess GHOST_System::init()
{ {
m_timerManager = new GHOST_TimerManager(); timer_manager_ = new GHOST_TimerManager();
m_windowManager = new GHOST_WindowManager(); window_manager_ = new GHOST_WindowManager();
m_eventManager = new GHOST_EventManager(); event_manager_ = new GHOST_EventManager();
#ifdef WITH_GHOST_DEBUG #ifdef WITH_GHOST_DEBUG
if (m_eventManager) { if (event_manager_) {
m_eventPrinter = new GHOST_EventPrinter(); event_printer_ = new GHOST_EventPrinter();
m_eventManager->addConsumer(m_eventPrinter); event_manager_->addConsumer(event_printer_);
} }
#endif /* WITH_GHOST_DEBUG */ #endif /* WITH_GHOST_DEBUG */
if (m_timerManager && m_windowManager && m_eventManager) { if (timer_manager_ && window_manager_ && event_manager_) {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -296,18 +296,18 @@ GHOST_TSuccess GHOST_System::exit()
/** WARNING: exit() may run more than once, since it may need to be called from a derived class /** WARNING: exit() may run more than once, since it may need to be called from a derived class
* destructor. Take it into account when modifying this function. */ * destructor. Take it into account when modifying this function. */
delete m_windowManager; delete window_manager_;
m_windowManager = nullptr; window_manager_ = nullptr;
delete m_timerManager; delete timer_manager_;
m_timerManager = nullptr; timer_manager_ = nullptr;
delete m_eventManager; delete event_manager_;
m_eventManager = nullptr; event_manager_ = nullptr;
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
delete m_ndofManager; delete ndof_manager_;
m_ndofManager = nullptr; ndof_manager_ = nullptr;
#endif #endif
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -315,26 +315,26 @@ GHOST_TSuccess GHOST_System::exit()
bool GHOST_System::useNativePixel() bool GHOST_System::useNativePixel()
{ {
m_nativePixel = true; native_pixel_ = true;
return true; return true;
} }
void GHOST_System::useWindowFocus(const bool use_focus) void GHOST_System::useWindowFocus(const bool use_focus)
{ {
m_windowFocus = use_focus; window_focus_ = use_focus;
} }
void GHOST_System::setAutoFocus(const bool auto_focus) void GHOST_System::setAutoFocus(const bool auto_focus)
{ {
m_autoFocus = auto_focus; auto_focus_ = auto_focus;
} }
void GHOST_System::initDebug(GHOST_Debug debug) void GHOST_System::initDebug(GHOST_Debug debug)
{ {
m_is_debug_enabled = debug.flags & GHOST_kDebugDefault; is_debug_enabled_ = debug.flags & GHOST_kDebugDefault;
} }
bool GHOST_System::isDebugEnabled() bool GHOST_System::isDebugEnabled()
{ {
return m_is_debug_enabled; return is_debug_enabled_;
} }

View File

@@ -56,8 +56,8 @@ class GHOST_System : public GHOST_ISystem {
/** \copydoc #GHOST_ISystem::installTimer */ /** \copydoc #GHOST_ISystem::installTimer */
GHOST_ITimerTask *installTimer(uint64_t delay, GHOST_ITimerTask *installTimer(uint64_t delay,
uint64_t interval, uint64_t interval,
GHOST_TimerProcPtr timerProc, GHOST_TimerProcPtr timer_proc,
GHOST_TUserDataPtr userData = nullptr) override; GHOST_TUserDataPtr user_data = nullptr) override;
/** \copydoc #GHOST_ISystem::removeTimer */ /** \copydoc #GHOST_ISystem::removeTimer */
GHOST_TSuccess removeTimer(GHOST_ITimerTask *timerTask) override; GHOST_TSuccess removeTimer(GHOST_ITimerTask *timerTask) override;
@@ -69,23 +69,23 @@ class GHOST_System : public GHOST_ISystem {
GHOST_TSuccess disposeWindow(GHOST_IWindow *window) override; GHOST_TSuccess disposeWindow(GHOST_IWindow *window) override;
/** \copydoc #GHOST_ISystem::createOffscreenContext */ /** \copydoc #GHOST_ISystem::createOffscreenContext */
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override = 0; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override = 0;
/** \copydoc #GHOST_ISystem::validWindow */ /** \copydoc #GHOST_ISystem::validWindow */
bool validWindow(GHOST_IWindow *window) override; bool validWindow(GHOST_IWindow *window) override;
/** \copydoc #GHOST_ISystem::useNativePixel */ /** \copydoc #GHOST_ISystem::useNativePixel */
bool useNativePixel() override; bool useNativePixel() override;
bool m_nativePixel; bool native_pixel_;
/** \copydoc #GHOST_ISystem::useWindowFocus */ /** \copydoc #GHOST_ISystem::useWindowFocus */
void useWindowFocus(const bool use_focus) override; void useWindowFocus(const bool use_focus) override;
bool m_windowFocus; bool window_focus_;
/** \copydoc #GHOST_ISystem::setAutoFocus */ /** \copydoc #GHOST_ISystem::setAutoFocus */
void setAutoFocus(const bool auto_focus) override; void setAutoFocus(const bool auto_focus) override;
bool m_autoFocus; bool auto_focus_;
/** \copydoc #GHOST_ISystem::getWindowUnderCursor */ /** \copydoc #GHOST_ISystem::getWindowUnderCursor */
GHOST_IWindow *getWindowUnderCursor(int32_t x, int32_t y) override; GHOST_IWindow *getWindowUnderCursor(int32_t x, int32_t y) override;
@@ -142,10 +142,10 @@ class GHOST_System : public GHOST_ISystem {
***************************************************************************************/ ***************************************************************************************/
/** \copydoc #GHOST_ISystem::getModifierKeyState */ /** \copydoc #GHOST_ISystem::getModifierKeyState */
GHOST_TSuccess getModifierKeyState(GHOST_TModifierKey mask, bool &isDown) const override; GHOST_TSuccess getModifierKeyState(GHOST_TModifierKey mask, bool &is_down) const override;
/** \copydoc #GHOST_ISystem::getButtonState */ /** \copydoc #GHOST_ISystem::getButtonState */
GHOST_TSuccess getButtonState(GHOST_TButton mask, bool &isDown) const override; GHOST_TSuccess getButtonState(GHOST_TButton mask, bool &is_down) const override;
/** \copydoc #GHOST_ISystem::setMultitouchGestures */ /** \copydoc #GHOST_ISystem::setMultitouchGestures */
void setMultitouchGestures(const bool use) override; void setMultitouchGestures(const bool use) override;
@@ -257,51 +257,51 @@ class GHOST_System : public GHOST_ISystem {
GHOST_TSuccess exit() override; GHOST_TSuccess exit() override;
/** The timer manager. */ /** The timer manager. */
GHOST_TimerManager *m_timerManager; GHOST_TimerManager *timer_manager_;
/** The window manager. */ /** The window manager. */
GHOST_WindowManager *m_windowManager; GHOST_WindowManager *window_manager_;
/** The event manager. */ /** The event manager. */
GHOST_EventManager *m_eventManager; GHOST_EventManager *event_manager_;
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
/** The N-degree of freedom device manager */ /** The N-degree of freedom device manager */
GHOST_NDOFManager *m_ndofManager; GHOST_NDOFManager *ndof_manager_;
#endif #endif
#ifdef WITH_GHOST_DEBUG #ifdef WITH_GHOST_DEBUG
/** Prints all the events. */ /** Prints all the events. */
GHOST_EventPrinter *m_eventPrinter; GHOST_EventPrinter *event_printer_;
#endif // WITH_GHOST_DEBUG #endif // WITH_GHOST_DEBUG
/** Use multi-touch gestures. */ /** Use multi-touch gestures. */
bool m_multitouchGestures; bool multitouch_gestures_;
/** Which tablet API to use. */ /** Which tablet API to use. */
GHOST_TTabletAPI m_tabletAPI; GHOST_TTabletAPI tablet_api_;
bool m_is_debug_enabled; bool is_debug_enabled_;
}; };
inline GHOST_TimerManager *GHOST_System::getTimerManager() const inline GHOST_TimerManager *GHOST_System::getTimerManager() const
{ {
return m_timerManager; return timer_manager_;
} }
inline GHOST_EventManager *GHOST_System::getEventManager() const inline GHOST_EventManager *GHOST_System::getEventManager() const
{ {
return m_eventManager; return event_manager_;
} }
inline GHOST_WindowManager *GHOST_System::getWindowManager() const inline GHOST_WindowManager *GHOST_System::getWindowManager() const
{ {
return m_windowManager; return window_manager_;
} }
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
inline GHOST_NDOFManager *GHOST_System::getNDOFManager() const inline GHOST_NDOFManager *GHOST_System::getNDOFManager() const
{ {
return m_ndofManager; return ndof_manager_;
} }
#endif #endif

View File

@@ -78,9 +78,9 @@ class GHOST_SystemCocoa : public GHOST_System {
* \param width: The width the window. * \param width: The width the window.
* \param height: The height the window. * \param height: The height the window.
* \param state: The state of the window when opened. * \param state: The state of the window when opened.
* \param gpuSettings: Misc GPU settings. * \param gpu_settings: Misc GPU settings.
* \param exclusive: Use to show the window on top and ignore others (used full-screen). * \param exclusive: Use to show the window on top and ignore others (used full-screen).
* \param parentWindow: Parent (embedder) window. * \param parent_window: Parent (embedder) window.
* \return The new window (or 0 if creation failed). * \return The new window (or 0 if creation failed).
*/ */
GHOST_IWindow *createWindow(const char *title, GHOST_IWindow *createWindow(const char *title,
@@ -89,17 +89,17 @@ class GHOST_SystemCocoa : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive = false, const bool exclusive = false,
const bool is_dialog = false, const bool is_dialog = false,
const GHOST_IWindow *parentWindow = nullptr) override; const GHOST_IWindow *parent_window = nullptr) override;
/** /**
* Create a new off-screen context. * Create a new off-screen context.
* Never explicitly delete the context, use #disposeContext() instead. * Never explicitly delete the context, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override;
/** /**
* Dispose of a context. * Dispose of a context.
@@ -333,23 +333,23 @@ class GHOST_SystemCocoa : public GHOST_System {
/** Event has been processed directly by Cocoa (or NDOF manager) /** Event has been processed directly by Cocoa (or NDOF manager)
* and has sent a ghost event to be dispatched */ * and has sent a ghost event to be dispatched */
bool m_outsideLoopEventProcessed; bool outside_loop_event_processed_;
/** Raised window is not yet known by the window manager, /** Raised window is not yet known by the window manager,
* so delay application become active event handling */ * so delay application become active event handling */
bool m_needDelayedApplicationBecomeActiveEventProcessing; bool need_delayed_application_become_active_event_processing_;
/** State of the modifiers. */ /** State of the modifiers. */
uint32_t m_modifierMask; uint32_t modifier_mask_;
/** Ignores window size messages (when window is dragged). */ /** Ignores window size messages (when window is dragged). */
bool m_ignoreWindowSizedMessages; bool ignore_window_sized_messages_;
/** Temporarily ignore momentum scroll events */ /** Temporarily ignore momentum scroll events */
bool m_ignoreMomentumScroll; bool ignore_momentum_scroll_;
/** Is the scroll wheel event generated by a multi-touch trackpad or mouse? */ /** Is the scroll wheel event generated by a multi-touch trackpad or mouse? */
bool m_multiTouchScroll; bool multi_touch_scroll_;
/** To prevent multiple warp, we store the time of the last warp event /** To prevent multiple warp, we store the time of the last warp event
* and ignore mouse moved events generated before that. */ * and ignore mouse moved events generated before that. */
double m_last_warp_timestamp; double last_warp_timestamp_;
}; };

View File

@@ -382,7 +382,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
@implementation CocoaAppDelegate : NSObject @implementation CocoaAppDelegate : NSObject
@synthesize systemCocoa = m_systemCocoa; @synthesize systemCocoa = system_cocoa_;
- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)systemCocoa - (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)systemCocoa
{ {
@@ -394,7 +394,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
selector:@selector(windowWillClose:) selector:@selector(windowWillClose:)
name:NSWindowWillCloseNotification name:NSWindowWillCloseNotification
object:nil]; object:nil];
m_systemCocoa = systemCocoa; system_cocoa_ = systemCocoa;
} }
return self; return self;
@@ -411,7 +411,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{ {
if (m_systemCocoa->m_windowFocus) { if (system_cocoa_->window_focus_) {
/* Raise application to front, convenient when starting from the terminal /* Raise application to front, convenient when starting from the terminal
* and important for launching the animation player. we call this after the * and important for launching the animation player. we call this after the
* application finishes launching, as doing it earlier can make us end up * application finishes launching, as doing it earlier can make us end up
@@ -424,7 +424,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{ {
return m_systemCocoa->handleOpenDocumentRequest(filename); return system_cocoa_->handleOpenDocumentRequest(filename);
} }
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
@@ -432,7 +432,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
/* TODO: implement graceful termination through Cocoa mechanism /* TODO: implement graceful termination through Cocoa mechanism
* to avoid session log off to be canceled. */ * to avoid session log off to be canceled. */
/* Note that Command-Q is already handled by key-handler. */ /* Note that Command-Q is already handled by key-handler. */
m_systemCocoa->handleQuitRequest(); system_cocoa_->handleQuitRequest();
return NSTerminateCancel; return NSTerminateCancel;
} }
@@ -448,7 +448,7 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
- (void)applicationWillBecomeActive:(NSNotification *)aNotification - (void)applicationWillBecomeActive:(NSNotification *)aNotification
{ {
m_systemCocoa->handleApplicationBecomeActiveEvent(); system_cocoa_->handleApplicationBecomeActiveEvent();
} }
- (void)toggleFullScreen:(NSNotification *)notification - (void)toggleFullScreen:(NSNotification *)notification
@@ -537,14 +537,14 @@ extern "C" int GHOST_HACK_getFirstFile(char buf[FIRSTFILEBUFLG])
GHOST_SystemCocoa::GHOST_SystemCocoa() GHOST_SystemCocoa::GHOST_SystemCocoa()
{ {
m_modifierMask = 0; modifier_mask_ = 0;
m_outsideLoopEventProcessed = false; outside_loop_event_processed_ = false;
m_needDelayedApplicationBecomeActiveEventProcessing = false; need_delayed_application_become_active_event_processing_ = false;
m_ignoreWindowSizedMessages = false; ignore_window_sized_messages_ = false;
m_ignoreMomentumScroll = false; ignore_momentum_scroll_ = false;
m_multiTouchScroll = false; multi_touch_scroll_ = false;
m_last_warp_timestamp = 0; last_warp_timestamp_ = 0;
} }
GHOST_SystemCocoa::~GHOST_SystemCocoa() GHOST_SystemCocoa::~GHOST_SystemCocoa()
@@ -569,7 +569,7 @@ GHOST_TSuccess GHOST_SystemCocoa::init()
if (success) { if (success) {
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
m_ndofManager = new GHOST_NDOFManagerCocoa(*this); ndof_manager_ = new GHOST_NDOFManagerCocoa(*this);
#endif #endif
// ProcessSerialNumber psn; // ProcessSerialNumber psn;
@@ -720,12 +720,12 @@ GHOST_IWindow *GHOST_SystemCocoa::createWindow(const char *title,
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool /*exclusive*/, const bool /*exclusive*/,
const bool is_dialog, const bool is_dialog,
const GHOST_IWindow *parentWindow) const GHOST_IWindow *parent_window)
{ {
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
GHOST_IWindow *window = nullptr; GHOST_IWindow *window = nullptr;
@autoreleasepool { @autoreleasepool {
/* Get the available rect for including window contents. */ /* Get the available rect for including window contents. */
@@ -744,17 +744,17 @@ GHOST_IWindow *GHOST_SystemCocoa::createWindow(const char *title,
width, width,
height, height,
state, state,
gpuSettings.context_type, gpu_settings.context_type,
context_params, context_params,
is_dialog, is_dialog,
(GHOST_WindowCocoa *)parentWindow, (GHOST_WindowCocoa *)parent_window,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (window->getValid()) { if (window->getValid()) {
/* Store the pointer to the window. */ /* Store the pointer to the window. */
GHOST_ASSERT(m_windowManager, "m_windowManager not initialized"); GHOST_ASSERT(window_manager_, "window_manager_ not initialized");
m_windowManager->addWindow(window); window_manager_->addWindow(window);
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
/* Need to tell window manager the new window is the active one /* Need to tell window manager the new window is the active one
* (Cocoa does not send the event activate upon window creation). */ * (Cocoa does not send the event activate upon window creation). */
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window));
@@ -774,16 +774,16 @@ GHOST_IWindow *GHOST_SystemCocoa::createWindow(const char *title,
* Never explicitly delete the context, use #disposeContext() instead. * Never explicitly delete the context, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
GHOST_IContext *GHOST_SystemCocoa::createOffscreenContext(GHOST_GPUSettings gpuSettings) GHOST_IContext *GHOST_SystemCocoa::createOffscreenContext(GHOST_GPUSettings gpu_settings)
{ {
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
context_params_offscreen, nullptr, 1, 2, gpuSettings.preferred_device); context_params_offscreen, nullptr, 1, 2, gpu_settings.preferred_device);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -834,7 +834,7 @@ GHOST_IWindow *GHOST_SystemCocoa::getWindowUnderCursor(int32_t x, int32_t y)
return nil; return nil;
} }
return m_windowManager->getWindowAssociatedWithOSWindow((const void *)nswindow); return window_manager_->getWindowAssociatedWithOSWindow((const void *)nswindow);
} }
} }
@@ -856,7 +856,7 @@ GHOST_TSuccess GHOST_SystemCocoa::getCursorPosition(int32_t &x, int32_t &y) cons
*/ */
GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(int32_t x, int32_t y) GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(int32_t x, int32_t y)
{ {
GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)m_windowManager->getActiveWindow(); GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)window_manager_->getActiveWindow();
if (!window) { if (!window) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -870,7 +870,7 @@ GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(int32_t x, int32_t y)
/* Force mouse move event (not pushed by Cocoa). */ /* Force mouse move event (not pushed by Cocoa). */
pushEvent(new GHOST_EventCursor( pushEvent(new GHOST_EventCursor(
getMilliSeconds(), GHOST_kEventCursorMove, window, x, y, window->GetCocoaTabletData())); getMilliSeconds(), GHOST_kEventCursorMove, window, x, y, window->GetCocoaTabletData()));
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -912,7 +912,7 @@ GHOST_TSuccess GHOST_SystemCocoa::getPixelAtCursor(float r_color[3]) const
GHOST_TSuccess GHOST_SystemCocoa::setMouseCursorPosition(int32_t x, int32_t y) GHOST_TSuccess GHOST_SystemCocoa::setMouseCursorPosition(int32_t x, int32_t y)
{ {
float xf = float(x), yf = float(y); float xf = float(x), yf = float(y);
GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)m_windowManager->getActiveWindow(); GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)window_manager_->getActiveWindow();
if (!window) { if (!window) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -944,12 +944,12 @@ GHOST_TSuccess GHOST_SystemCocoa::setMouseCursorPosition(int32_t x, int32_t y)
GHOST_TSuccess GHOST_SystemCocoa::getModifierKeys(GHOST_ModifierKeys &keys) const GHOST_TSuccess GHOST_SystemCocoa::getModifierKeys(GHOST_ModifierKeys &keys) const
{ {
keys.set(GHOST_kModifierKeyLeftOS, (m_modifierMask & NSEventModifierFlagCommand) ? true : false); keys.set(GHOST_kModifierKeyLeftOS, (modifier_mask_ & NSEventModifierFlagCommand) ? true : false);
keys.set(GHOST_kModifierKeyLeftAlt, (m_modifierMask & NSEventModifierFlagOption) ? true : false); keys.set(GHOST_kModifierKeyLeftAlt, (modifier_mask_ & NSEventModifierFlagOption) ? true : false);
keys.set(GHOST_kModifierKeyLeftShift, keys.set(GHOST_kModifierKeyLeftShift,
(m_modifierMask & NSEventModifierFlagShift) ? true : false); (modifier_mask_ & NSEventModifierFlagShift) ? true : false);
keys.set(GHOST_kModifierKeyLeftControl, keys.set(GHOST_kModifierKeyLeftControl,
(m_modifierMask & NSEventModifierFlagControl) ? true : false); (modifier_mask_ & NSEventModifierFlagControl) ? true : false);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1065,16 +1065,16 @@ bool GHOST_SystemCocoa::processEvents(bool /*waitForEvent*/)
} while (waitForEvent && !anyProcessed); /* Needed only for timer implementation. */ } while (waitForEvent && !anyProcessed); /* Needed only for timer implementation. */
#endif #endif
if (m_needDelayedApplicationBecomeActiveEventProcessing) { if (need_delayed_application_become_active_event_processing_) {
handleApplicationBecomeActiveEvent(); handleApplicationBecomeActiveEvent();
} }
if (m_outsideLoopEventProcessed) { if (outside_loop_event_processed_) {
m_outsideLoopEventProcessed = false; outside_loop_event_processed_ = false;
return true; return true;
} }
m_ignoreWindowSizedMessages = false; ignore_window_sized_messages_ = false;
return anyProcessed; return anyProcessed;
} }
@@ -1083,7 +1083,7 @@ bool GHOST_SystemCocoa::processEvents(bool /*waitForEvent*/)
GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent() GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
{ {
@autoreleasepool { @autoreleasepool {
for (GHOST_IWindow *iwindow : m_windowManager->getWindows()) { for (GHOST_IWindow *iwindow : window_manager_->getWindows()) {
GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow; GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow;
if (window->isDialog()) { if (window->isDialog()) {
[window->getViewWindow() makeKeyAndOrderFront:nil]; [window->getViewWindow() makeKeyAndOrderFront:nil];
@@ -1092,19 +1092,19 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
/* Update the modifiers key mask, as its status may have changed when the application /* Update the modifiers key mask, as its status may have changed when the application
* was not active (that is when update events are sent to another application). */ * was not active (that is when update events are sent to another application). */
GHOST_IWindow *window = m_windowManager->getActiveWindow(); GHOST_IWindow *window = window_manager_->getActiveWindow();
if (!window) { if (!window) {
m_needDelayedApplicationBecomeActiveEventProcessing = true; need_delayed_application_become_active_event_processing_ = true;
return GHOST_kFailure; return GHOST_kFailure;
} }
m_needDelayedApplicationBecomeActiveEventProcessing = false; need_delayed_application_become_active_event_processing_ = false;
const unsigned int modifiers = [[[NSApplication sharedApplication] currentEvent] const unsigned int modifiers = [[[NSApplication sharedApplication] currentEvent]
modifierFlags]; modifierFlags];
if ((modifiers & NSEventModifierFlagShift) != (m_modifierMask & NSEventModifierFlagShift)) { if ((modifiers & NSEventModifierFlagShift) != (modifier_mask_ & NSEventModifierFlagShift)) {
pushEvent(new GHOST_EventKey(getMilliSeconds(), pushEvent(new GHOST_EventKey(getMilliSeconds(),
(modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown : (modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown :
GHOST_kEventKeyUp, GHOST_kEventKeyUp,
@@ -1112,7 +1112,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
GHOST_kKeyLeftShift, GHOST_kKeyLeftShift,
false)); false));
} }
if ((modifiers & NSEventModifierFlagControl) != (m_modifierMask & NSEventModifierFlagControl)) if ((modifiers & NSEventModifierFlagControl) != (modifier_mask_ & NSEventModifierFlagControl))
{ {
pushEvent(new GHOST_EventKey(getMilliSeconds(), pushEvent(new GHOST_EventKey(getMilliSeconds(),
(modifiers & NSEventModifierFlagControl) ? GHOST_kEventKeyDown : (modifiers & NSEventModifierFlagControl) ? GHOST_kEventKeyDown :
@@ -1121,7 +1121,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
GHOST_kKeyLeftControl, GHOST_kKeyLeftControl,
false)); false));
} }
if ((modifiers & NSEventModifierFlagOption) != (m_modifierMask & NSEventModifierFlagOption)) { if ((modifiers & NSEventModifierFlagOption) != (modifier_mask_ & NSEventModifierFlagOption)) {
pushEvent(new GHOST_EventKey(getMilliSeconds(), pushEvent(new GHOST_EventKey(getMilliSeconds(),
(modifiers & NSEventModifierFlagOption) ? GHOST_kEventKeyDown : (modifiers & NSEventModifierFlagOption) ? GHOST_kEventKeyDown :
GHOST_kEventKeyUp, GHOST_kEventKeyUp,
@@ -1129,7 +1129,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
GHOST_kKeyLeftAlt, GHOST_kKeyLeftAlt,
false)); false));
} }
if ((modifiers & NSEventModifierFlagCommand) != (m_modifierMask & NSEventModifierFlagCommand)) if ((modifiers & NSEventModifierFlagCommand) != (modifier_mask_ & NSEventModifierFlagCommand))
{ {
pushEvent(new GHOST_EventKey(getMilliSeconds(), pushEvent(new GHOST_EventKey(getMilliSeconds(),
(modifiers & NSEventModifierFlagCommand) ? GHOST_kEventKeyDown : (modifiers & NSEventModifierFlagCommand) ? GHOST_kEventKeyDown :
@@ -1139,16 +1139,16 @@ GHOST_TSuccess GHOST_SystemCocoa::handleApplicationBecomeActiveEvent()
false)); false));
} }
m_modifierMask = modifiers; modifier_mask_ = modifiers;
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
} }
bool GHOST_SystemCocoa::hasDialogWindow() bool GHOST_SystemCocoa::hasDialogWindow()
{ {
for (GHOST_IWindow *iwindow : m_windowManager->getWindows()) { for (GHOST_IWindow *iwindow : window_manager_->getWindows()) {
GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow; GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)iwindow;
if (window->isDialog()) { if (window->isDialog()) {
return true; return true;
@@ -1159,7 +1159,7 @@ bool GHOST_SystemCocoa::hasDialogWindow()
void GHOST_SystemCocoa::notifyExternalEventProcessed() void GHOST_SystemCocoa::notifyExternalEventProcessed()
{ {
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
} }
/* NOTE: called from #NSWindow delegate. */ /* NOTE: called from #NSWindow delegate. */
@@ -1174,16 +1174,16 @@ GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType,
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window));
break; break;
case GHOST_kEventWindowActivate: case GHOST_kEventWindowActivate:
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
window->loadCursor(window->getCursorVisibility(), window->getCursorShape()); window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window));
break; break;
case GHOST_kEventWindowDeactivate: case GHOST_kEventWindowDeactivate:
m_windowManager->setWindowInactive(window); window_manager_->setWindowInactive(window);
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowDeactivate, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowDeactivate, window));
break; break;
case GHOST_kEventWindowUpdate: case GHOST_kEventWindowUpdate:
if (m_nativePixel) { if (native_pixel_) {
window->setNativePixelSize(); window->setNativePixelSize();
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventNativeResolutionChange, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventNativeResolutionChange, window));
} }
@@ -1193,7 +1193,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType,
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowMove, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowMove, window));
break; break;
case GHOST_kEventWindowSize: case GHOST_kEventWindowSize:
if (!m_ignoreWindowSizedMessages) { if (!ignore_window_sized_messages_) {
/* Enforce only one resize message per event loop /* Enforce only one resize message per event loop
* (coalescing all the live resize messages). */ * (coalescing all the live resize messages). */
window->updateDrawingContext(); window->updateDrawingContext();
@@ -1205,12 +1205,12 @@ GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType,
window, window,
GHOST_kButtonMaskLeft, GHOST_kButtonMaskLeft,
GHOST_TABLET_DATA_NONE)); GHOST_TABLET_DATA_NONE));
// m_ignoreWindowSizedMessages = true; // ignore_window_sized_messages_ = true;
} }
break; break;
case GHOST_kEventNativeResolutionChange: case GHOST_kEventNativeResolutionChange:
if (m_nativePixel) { if (native_pixel_) {
window->setNativePixelSize(); window->setNativePixelSize();
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventNativeResolutionChange, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventNativeResolutionChange, window));
} }
@@ -1220,7 +1220,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleWindowEvent(GHOST_TEventType eventType,
break; break;
} }
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1390,13 +1390,13 @@ GHOST_TSuccess GHOST_SystemCocoa::handleDraggingEvent(GHOST_TEventType eventType
default: default:
return GHOST_kFailure; return GHOST_kFailure;
} }
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
void GHOST_SystemCocoa::handleQuitRequest() void GHOST_SystemCocoa::handleQuitRequest()
{ {
GHOST_Window *window = (GHOST_Window *)m_windowManager->getActiveWindow(); GHOST_Window *window = (GHOST_Window *)window_manager_->getActiveWindow();
/* Discard quit event if we are in cursor grab sequence. */ /* Discard quit event if we are in cursor grab sequence. */
if (window && window->getCursorGrabModeIsWarp()) { if (window && window->getCursorGrabModeIsWarp()) {
@@ -1405,7 +1405,7 @@ void GHOST_SystemCocoa::handleQuitRequest()
/* Push the event to Blender so it can open a dialog if needed. */ /* Push the event to Blender so it can open a dialog if needed. */
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventQuitRequest, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventQuitRequest, window));
m_outsideLoopEventProcessed = true; outside_loop_event_processed_ = true;
} }
bool GHOST_SystemCocoa::handleOpenDocumentRequest(void *filepathStr) bool GHOST_SystemCocoa::handleOpenDocumentRequest(void *filepathStr)
@@ -1421,9 +1421,9 @@ bool GHOST_SystemCocoa::handleOpenDocumentRequest(void *filepathStr)
[[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil]; [[windowsList objectAtIndex:0] makeKeyAndOrderFront:nil];
} }
GHOST_Window *window = m_windowManager->getWindows().empty() ? GHOST_Window *window = window_manager_->getWindows().empty() ?
nullptr : nullptr :
(GHOST_Window *)m_windowManager->getWindows().front(); (GHOST_Window *)window_manager_->getWindows().front();
if (!window) { if (!window) {
return NO; return NO;
@@ -1457,7 +1457,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleTabletEvent(void *eventPtr, short eventT
{ {
NSEvent *event = (NSEvent *)eventPtr; NSEvent *event = (NSEvent *)eventPtr;
GHOST_IWindow *window = m_windowManager->getWindowAssociatedWithOSWindow( GHOST_IWindow *window = window_manager_->getWindowAssociatedWithOSWindow(
(const void *)event.window); (const void *)event.window);
if (!window) { if (!window) {
// printf("\nW failure for event 0x%x",event.type); // printf("\nW failure for event 0x%x",event.type);
@@ -1536,10 +1536,10 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
/* event.window returns other windows if mouse-over, that's OSX input standard /* event.window returns other windows if mouse-over, that's OSX input standard
* however, if mouse exits window(s), the windows become inactive, until you click. * however, if mouse exits window(s), the windows become inactive, until you click.
* We then fall back to the active window from ghost. */ * We then fall back to the active window from ghost. */
GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)m_windowManager GHOST_WindowCocoa *window = (GHOST_WindowCocoa *)window_manager_
->getWindowAssociatedWithOSWindow((const void *)event.window); ->getWindowAssociatedWithOSWindow((const void *)event.window);
if (!window) { if (!window) {
window = (GHOST_WindowCocoa *)m_windowManager->getActiveWindow(); window = (GHOST_WindowCocoa *)window_manager_->getActiveWindow();
if (!window) { if (!window) {
// printf("\nW failure for event 0x%x", event.type); // printf("\nW failure for event 0x%x", event.type);
return GHOST_kFailure; return GHOST_kFailure;
@@ -1636,7 +1636,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
case GHOST_kGrabWrap: { case GHOST_kGrabWrap: {
/* Wrap cursor at area/window boundaries. */ /* Wrap cursor at area/window boundaries. */
const NSTimeInterval timestamp = event.timestamp; const NSTimeInterval timestamp = event.timestamp;
if (timestamp < m_last_warp_timestamp) { if (timestamp < last_warp_timestamp_) {
/* After warping we can still receive older unwrapped mouse events, /* After warping we can still receive older unwrapped mouse events,
* ignore those. */ * ignore those. */
break; break;
@@ -1652,10 +1652,10 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
/* Switch back to Cocoa coordinates orientation /* Switch back to Cocoa coordinates orientation
* (y=0 at bottom, the same as blender internal BTW!), and to client coordinates. */ * (y=0 at bottom, the same as blender internal BTW!), and to client coordinates. */
window->getClientBounds(windowBounds); window->getClientBounds(windowBounds);
window->screenToClient(bounds.m_l, bounds.m_b, correctedBounds.m_l, correctedBounds.m_t); window->screenToClient(bounds.l_, bounds.b_, correctedBounds.l_, correctedBounds.t_);
window->screenToClient(bounds.m_r, bounds.m_t, correctedBounds.m_r, correctedBounds.m_b); window->screenToClient(bounds.r_, bounds.t_, correctedBounds.r_, correctedBounds.b_);
correctedBounds.m_b = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_b; correctedBounds.b_ = (windowBounds.b_ - windowBounds.t_) - correctedBounds.b_;
correctedBounds.m_t = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_t; correctedBounds.t_ = (windowBounds.b_ - windowBounds.t_) - correctedBounds.t_;
/* Get accumulation from previous mouse warps. */ /* Get accumulation from previous mouse warps. */
int32_t x_accum, y_accum; int32_t x_accum, y_accum;
@@ -1681,7 +1681,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
y_accum + (y_mouse - warped_y_mouse)); y_accum + (y_mouse - warped_y_mouse));
/* This is the current time that matches NSEvent timestamp. */ /* This is the current time that matches NSEvent timestamp. */
m_last_warp_timestamp = [[NSProcessInfo processInfo] systemUptime]; last_warp_timestamp_ = [[NSProcessInfo processInfo] systemUptime];
} }
/* Generate event. */ /* Generate event. */
@@ -1721,27 +1721,27 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
* change from e.g. scrolling to zooming. this works around the * change from e.g. scrolling to zooming. this works around the
* issue by ignoring momentum scroll after a key press */ * issue by ignoring momentum scroll after a key press */
if (momentumPhase) { if (momentumPhase) {
if (m_ignoreMomentumScroll) { if (ignore_momentum_scroll_) {
break; break;
} }
} }
else { else {
m_ignoreMomentumScroll = false; ignore_momentum_scroll_ = false;
} }
/* we assume phases are only set for gestures from trackpad or magic /* we assume phases are only set for gestures from trackpad or magic
* mouse events. note that using tablet at the same time may not work * mouse events. note that using tablet at the same time may not work
* since this is a static variable */ * since this is a static variable */
if (phase == NSEventPhaseBegan && m_multitouchGestures) { if (phase == NSEventPhaseBegan && multitouch_gestures_) {
m_multiTouchScroll = true; multi_touch_scroll_ = true;
} }
else if (phase == NSEventPhaseEnded) { else if (phase == NSEventPhaseEnded) {
m_multiTouchScroll = false; multi_touch_scroll_ = false;
} }
/* Standard scroll-wheel case, if no swiping happened, /* Standard scroll-wheel case, if no swiping happened,
* and no momentum (kinetic scroll) works. */ * and no momentum (kinetic scroll) works. */
if (!m_multiTouchScroll && momentumPhase == NSEventPhaseNone) { if (!multi_touch_scroll_ && momentumPhase == NSEventPhaseNone) {
if (event.deltaX != 0.0) { if (event.deltaX != 0.0) {
const int32_t delta = event.deltaX > 0.0 ? 1 : -1; const int32_t delta = event.deltaX > 0.0 ? 1 : -1;
pushEvent(new GHOST_EventWheel( pushEvent(new GHOST_EventWheel(
@@ -1832,7 +1832,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr) GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
{ {
NSEvent *event = (NSEvent *)eventPtr; NSEvent *event = (NSEvent *)eventPtr;
GHOST_IWindow *window = m_windowManager->getWindowAssociatedWithOSWindow( GHOST_IWindow *window = window_manager_->getWindowAssociatedWithOSWindow(
(const void *)event.window); (const void *)event.window);
if (!window) { if (!window) {
@@ -1877,11 +1877,11 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
} }
/* no text with command key pressed */ /* no text with command key pressed */
if (m_modifierMask & NSEventModifierFlagCommand) { if (modifier_mask_ & NSEventModifierFlagCommand) {
utf8_buf[0] = '\0'; utf8_buf[0] = '\0';
} }
if ((keyCode == GHOST_kKeyQ) && (m_modifierMask & NSEventModifierFlagCommand)) { if ((keyCode == GHOST_kKeyQ) && (modifier_mask_ & NSEventModifierFlagCommand)) {
break; /* Command-Q is directly handled by Cocoa. */ break; /* Command-Q is directly handled by Cocoa. */
} }
@@ -1913,13 +1913,13 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
utf8_buf); utf8_buf);
#endif #endif
} }
m_ignoreMomentumScroll = true; ignore_momentum_scroll_ = true;
break; break;
} }
case NSEventTypeFlagsChanged: { case NSEventTypeFlagsChanged: {
const unsigned int modifiers = event.modifierFlags; const unsigned int modifiers = event.modifierFlags;
if ((modifiers & NSEventModifierFlagShift) != (m_modifierMask & NSEventModifierFlagShift)) { if ((modifiers & NSEventModifierFlagShift) != (modifier_mask_ & NSEventModifierFlagShift)) {
pushEvent(new GHOST_EventKey(event.timestamp * 1000, pushEvent(new GHOST_EventKey(event.timestamp * 1000,
(modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown : (modifiers & NSEventModifierFlagShift) ? GHOST_kEventKeyDown :
GHOST_kEventKeyUp, GHOST_kEventKeyUp,
@@ -1928,7 +1928,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
false)); false));
} }
if ((modifiers & NSEventModifierFlagControl) != if ((modifiers & NSEventModifierFlagControl) !=
(m_modifierMask & NSEventModifierFlagControl)) (modifier_mask_ & NSEventModifierFlagControl))
{ {
pushEvent(new GHOST_EventKey( pushEvent(new GHOST_EventKey(
event.timestamp * 1000, event.timestamp * 1000,
@@ -1937,7 +1937,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
GHOST_kKeyLeftControl, GHOST_kKeyLeftControl,
false)); false));
} }
if ((modifiers & NSEventModifierFlagOption) != (m_modifierMask & NSEventModifierFlagOption)) if ((modifiers & NSEventModifierFlagOption) != (modifier_mask_ & NSEventModifierFlagOption))
{ {
pushEvent(new GHOST_EventKey( pushEvent(new GHOST_EventKey(
event.timestamp * 1000, event.timestamp * 1000,
@@ -1947,7 +1947,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
false)); false));
} }
if ((modifiers & NSEventModifierFlagCommand) != if ((modifiers & NSEventModifierFlagCommand) !=
(m_modifierMask & NSEventModifierFlagCommand)) (modifier_mask_ & NSEventModifierFlagCommand))
{ {
pushEvent(new GHOST_EventKey( pushEvent(new GHOST_EventKey(
event.timestamp * 1000, event.timestamp * 1000,
@@ -1957,8 +1957,8 @@ GHOST_TSuccess GHOST_SystemCocoa::handleKeyEvent(void *eventPtr)
false)); false));
} }
m_modifierMask = modifiers; modifier_mask_ = modifiers;
m_ignoreMomentumScroll = true; ignore_momentum_scroll_ = true;
break; break;
} }

View File

@@ -109,22 +109,22 @@ class GHOST_SystemHeadless : public GHOST_System {
void getAllDisplayDimensions(uint32_t & /*width*/, uint32_t & /*height*/) const override void getAllDisplayDimensions(uint32_t & /*width*/, uint32_t & /*height*/) const override
{ /* nop */ { /* nop */
} }
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override
{ {
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
/* This may not be used depending on the build configuration. */ /* This may not be used depending on the build configuration. */
(void)context_params_offscreen; (void)context_params_offscreen;
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
# ifdef _WIN32 # ifdef _WIN32
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
context_params_offscreen, (HWND)0, 1, 2, gpuSettings.preferred_device); context_params_offscreen, (HWND)0, 1, 2, gpu_settings.preferred_device);
# elif defined(__APPLE__) # elif defined(__APPLE__)
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
context_params_offscreen, nullptr, 1, 2, gpuSettings.preferred_device); context_params_offscreen, nullptr, 1, 2, gpu_settings.preferred_device);
# else # else
GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen, GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen,
GHOST_kVulkanPlatformHeadless, GHOST_kVulkanPlatformHeadless,
@@ -135,7 +135,7 @@ class GHOST_SystemHeadless : public GHOST_System {
nullptr, nullptr,
1, 1,
2, 2,
gpuSettings.preferred_device); gpu_settings.preferred_device);
# endif # endif
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
@@ -203,20 +203,21 @@ class GHOST_SystemHeadless : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool /*exclusive*/, const bool /*exclusive*/,
const bool /*is_dialog*/, const bool /*is_dialog*/,
const GHOST_IWindow *parentWindow) override const GHOST_IWindow *parent_window) override
{ {
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(
gpu_settings);
return new GHOST_WindowNULL(title, return new GHOST_WindowNULL(title,
left, left,
top, top,
width, width,
height, height,
state, state,
parentWindow, parent_window,
gpuSettings.context_type, gpu_settings.context_type,
context_params); context_params);
} }

View File

@@ -44,14 +44,14 @@ GHOST_IWindow *GHOST_SystemSDL::createWindow(const char *title,
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive, const bool exclusive,
const bool /*is_dialog*/, const bool /*is_dialog*/,
const GHOST_IWindow *parentWindow) const GHOST_IWindow *parent_window)
{ {
GHOST_WindowSDL *window = nullptr; GHOST_WindowSDL *window = nullptr;
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
window = new GHOST_WindowSDL(this, window = new GHOST_WindowSDL(this,
title, title,
@@ -60,10 +60,10 @@ GHOST_IWindow *GHOST_SystemSDL::createWindow(const char *title,
width, width,
height, height,
state, state,
gpuSettings.context_type, gpu_settings.context_type,
context_params, context_params,
exclusive, exclusive,
parentWindow); parent_window);
if (window) { if (window) {
if (GHOST_kWindowStateFullScreen == state) { if (GHOST_kWindowStateFullScreen == state) {
@@ -78,7 +78,7 @@ GHOST_IWindow *GHOST_SystemSDL::createWindow(const char *title,
} }
if (window->getValid()) { if (window->getValid()) {
m_windowManager->addWindow(window); window_manager_->addWindow(window);
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window));
} }
else { else {
@@ -131,12 +131,12 @@ uint8_t GHOST_SystemSDL::getNumDisplays() const
return SDL_GetNumVideoDisplays(); return SDL_GetNumVideoDisplays();
} }
GHOST_IContext *GHOST_SystemSDL::createOffscreenContext(GHOST_GPUSettings gpuSettings) GHOST_IContext *GHOST_SystemSDL::createOffscreenContext(GHOST_GPUSettings gpu_settings)
{ {
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_OPENGL_BACKEND #ifdef WITH_OPENGL_BACKEND
case GHOST_kDrawingContextTypeOpenGL: { case GHOST_kDrawingContextTypeOpenGL: {
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
@@ -495,7 +495,7 @@ void GHOST_SystemSDL::processEvent(SDL_Event *sdl_event)
case SDL_QUIT: { case SDL_QUIT: {
const SDL_QuitEvent &sdl_sub_evt = sdl_event->quit; const SDL_QuitEvent &sdl_sub_evt = sdl_event->quit;
const uint64_t event_ms = sdl_sub_evt.timestamp; const uint64_t event_ms = sdl_sub_evt.timestamp;
GHOST_IWindow *window = m_windowManager->getActiveWindow(); GHOST_IWindow *window = window_manager_->getActiveWindow();
g_event = new GHOST_Event(event_ms, GHOST_kEventQuitRequest, window); g_event = new GHOST_Event(event_ms, GHOST_kEventQuitRequest, window);
break; break;
} }
@@ -534,12 +534,12 @@ void GHOST_SystemSDL::processEvent(SDL_Event *sdl_event)
/* Can't use #setCursorPosition because the mouse may have no focus! */ /* Can't use #setCursorPosition because the mouse may have no focus! */
if (x_new != x_root || y_new != y_root) { if (x_new != x_root || y_new != y_root) {
if (1 /* `xme.time > m_last_warp` */) { if (1 /* `xme.time > last_warp_` */) {
/* when wrapping we don't need to add an event because the /* when wrapping we don't need to add an event because the
* #setCursorPosition call will cause a new event after */ * #setCursorPosition call will cause a new event after */
SDL_WarpMouseInWindow(sdl_win, x_new - x_win, y_new - y_win); /* wrap */ SDL_WarpMouseInWindow(sdl_win, x_new - x_win, y_new - y_win); /* wrap */
window->setCursorGrabAccum(x_accum + (x_root - x_new), y_accum + (y_root - y_new)); window->setCursorGrabAccum(x_accum + (x_root - x_new), y_accum + (y_root - y_new));
// m_last_warp = lastEventTime(xme.time); // last_warp_ = lastEventTime(xme.time);
} }
else { else {
// setCursorPosition(x_new, y_new); /* wrap but don't accumulate */ // setCursorPosition(x_new, y_new); /* wrap but don't accumulate */
@@ -677,8 +677,8 @@ GHOST_TSuccess GHOST_SystemSDL::setCursorPosition(int32_t x, int32_t y)
bool GHOST_SystemSDL::generateWindowExposeEvents() bool GHOST_SystemSDL::generateWindowExposeEvents()
{ {
std::vector<GHOST_WindowSDL *>::iterator w_start = m_dirty_windows.begin(); std::vector<GHOST_WindowSDL *>::iterator w_start = dirty_windows_.begin();
std::vector<GHOST_WindowSDL *>::const_iterator w_end = m_dirty_windows.end(); std::vector<GHOST_WindowSDL *>::const_iterator w_end = dirty_windows_.end();
bool anyProcessed = false; bool anyProcessed = false;
for (; w_start != w_end; ++w_start) { for (; w_start != w_end; ++w_start) {
@@ -695,7 +695,7 @@ bool GHOST_SystemSDL::generateWindowExposeEvents()
} }
} }
m_dirty_windows.clear(); dirty_windows_.clear();
return anyProcessed; return anyProcessed;
} }
@@ -709,19 +709,19 @@ bool GHOST_SystemSDL::processEvents(bool waitForEvent)
do { do {
GHOST_TimerManager *timerMgr = getTimerManager(); GHOST_TimerManager *timerMgr = getTimerManager();
if (waitForEvent && m_dirty_windows.empty() && !SDL_HasEvents(SDL_FIRSTEVENT, SDL_LASTEVENT)) { if (waitForEvent && dirty_windows_.empty() && !SDL_HasEvents(SDL_FIRSTEVENT, SDL_LASTEVENT)) {
uint64_t next = timerMgr->nextFireTime(); uint64_t next = timerMgr->nextFireTime();
if (next == GHOST_kFireTimeNever) { if (next == GHOST_kFireTimeNever) {
SDL_WaitEventTimeout(nullptr, -1); SDL_WaitEventTimeout(nullptr, -1);
// SleepTillEvent(m_display, -1); // SleepTillEvent(display_, -1);
} }
else { else {
int64_t maxSleep = next - getMilliSeconds(); int64_t maxSleep = next - getMilliSeconds();
if (maxSleep >= 0) { if (maxSleep >= 0) {
SDL_WaitEventTimeout(nullptr, next - getMilliSeconds()); SDL_WaitEventTimeout(nullptr, next - getMilliSeconds());
// SleepTillEvent(m_display, next - getMilliSeconds()); /* X11. */ // SleepTillEvent(display_, next - getMilliSeconds()); /* X11. */
} }
} }
} }
@@ -754,7 +754,7 @@ GHOST_WindowSDL *GHOST_SystemSDL::findGhostWindow(SDL_Window *sdl_win)
* We should always check the window manager's list of windows * We should always check the window manager's list of windows
* and only process events on these windows. */ * and only process events on these windows. */
const std::vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const std::vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
std::vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); std::vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
std::vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end(); std::vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
@@ -772,7 +772,7 @@ void GHOST_SystemSDL::addDirtyWindow(GHOST_WindowSDL *bad_wind)
{ {
GHOST_ASSERT((bad_wind != nullptr), "addDirtyWindow() nullptr ptr trapped (window)"); GHOST_ASSERT((bad_wind != nullptr), "addDirtyWindow() nullptr ptr trapped (window)");
m_dirty_windows.push_back(bad_wind); dirty_windows_.push_back(bad_wind);
} }
GHOST_TSuccess GHOST_SystemSDL::getButtons(GHOST_Buttons &buttons) const GHOST_TSuccess GHOST_SystemSDL::getButtons(GHOST_Buttons &buttons) const

View File

@@ -61,7 +61,7 @@ class GHOST_SystemSDL : public GHOST_System {
void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override; void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override;
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override;
GHOST_TSuccess disposeContext(GHOST_IContext *context) override; GHOST_TSuccess disposeContext(GHOST_IContext *context) override;
@@ -74,10 +74,10 @@ class GHOST_SystemSDL : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive = false, const bool exclusive = false,
const bool is_dialog = false, const bool is_dialog = false,
const GHOST_IWindow *parentWindow = nullptr) override; const GHOST_IWindow *parent_window = nullptr) override;
/* SDL specific */ /* SDL specific */
GHOST_WindowSDL *findGhostWindow(SDL_Window *sdl_win); GHOST_WindowSDL *findGhostWindow(SDL_Window *sdl_win);
@@ -87,5 +87,5 @@ class GHOST_SystemSDL : public GHOST_System {
void processEvent(SDL_Event *sdl_event); void processEvent(SDL_Event *sdl_event);
/** The vector of windows that need to be updated. */ /** The vector of windows that need to be updated. */
std::vector<GHOST_WindowSDL *> m_dirty_windows; std::vector<GHOST_WindowSDL *> dirty_windows_;
}; };

View File

@@ -3175,12 +3175,12 @@ static void relative_pointer_handle_relative_motion_impl(GWL_Seat *seat,
GHOST_Rect bounds; GHOST_Rect bounds;
win->getClientBounds(bounds); win->getClientBounds(bounds);
/* Needed or the cursor is considered outside the window and doesn't restore the location. */ /* Needed or the cursor is considered outside the window and doesn't restore the location. */
bounds.m_r -= 1; bounds.r_ -= 1;
bounds.m_b -= 1; bounds.b_ -= 1;
bounds.m_l = win->wl_fixed_from_window(wl_fixed_from_int(bounds.m_l)); bounds.l_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.l_));
bounds.m_t = win->wl_fixed_from_window(wl_fixed_from_int(bounds.m_t)); bounds.t_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.t_));
bounds.m_r = win->wl_fixed_from_window(wl_fixed_from_int(bounds.m_r)); bounds.r_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.r_));
bounds.m_b = win->wl_fixed_from_window(wl_fixed_from_int(bounds.m_b)); bounds.b_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.b_));
bounds.clampPoint(UNPACK2(seat->pointer.xy)); bounds.clampPoint(UNPACK2(seat->pointer.xy));
} }
#endif #endif
@@ -5945,7 +5945,7 @@ class GHOST_EventIME : public GHOST_Event {
/* Make sure that we keep a copy of the IME input. Otherwise it might get lost /* Make sure that we keep a copy of the IME input. Otherwise it might get lost
* because we overwrite it before it can be read in Blender. (See #137346). */ * because we overwrite it before it can be read in Blender. (See #137346). */
this->event_ime_data = *customdata; this->event_ime_data = *customdata;
this->m_data = &this->event_ime_data; this->data_ = &this->event_ime_data;
} }
}; };
@@ -7744,7 +7744,7 @@ GHOST_TSuccess GHOST_SystemWayland::init()
if (success) { if (success) {
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
m_ndofManager = new GHOST_NDOFManagerUnix(*this); ndof_manager_ = new GHOST_NDOFManagerUnix(*this);
#endif #endif
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -7815,7 +7815,7 @@ bool GHOST_SystemWayland::processEvents(bool waitForEvent)
} }
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
if (static_cast<GHOST_NDOFManagerUnix *>(m_ndofManager)->processEvents()) { if (static_cast<GHOST_NDOFManagerUnix *>(ndof_manager_)->processEvents()) {
/* As NDOF bypasses WAYLAND event handling, /* As NDOF bypasses WAYLAND event handling,
* never wait for an event when an NDOF event was found. */ * never wait for an event when an NDOF event was found. */
waitForEvent = false; waitForEvent = false;
@@ -8403,10 +8403,10 @@ static GHOST_TSuccess getCursorPositionClientRelative_impl(
GHOST_Rect wrap_bounds_scale; GHOST_Rect wrap_bounds_scale;
wrap_bounds_scale.m_l = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.m_l)); wrap_bounds_scale.l_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.l_));
wrap_bounds_scale.m_t = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.m_t)); wrap_bounds_scale.t_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.t_));
wrap_bounds_scale.m_r = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.m_r)); wrap_bounds_scale.r_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.r_));
wrap_bounds_scale.m_b = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.m_b)); wrap_bounds_scale.b_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.b_));
wrap_bounds_scale.wrapPoint(UNPACK2(xy_wrap), 0, win->getCursorGrabAxis()); wrap_bounds_scale.wrapPoint(UNPACK2(xy_wrap), 0, win->getCursorGrabAxis());
x = wl_fixed_to_int(win->wl_fixed_to_window(xy_wrap[0])); x = wl_fixed_to_int(win->wl_fixed_to_window(xy_wrap[0]));
@@ -8578,16 +8578,16 @@ void GHOST_SystemWayland::getAllDisplayDimensions(uint32_t &width, uint32_t &hei
} }
} }
GHOST_IContext *GHOST_SystemWayland::createOffscreenContext(GHOST_GPUSettings gpuSettings) GHOST_IContext *GHOST_SystemWayland::createOffscreenContext(GHOST_GPUSettings gpu_settings)
{ {
#ifdef USE_EVENT_BACKGROUND_THREAD #ifdef USE_EVENT_BACKGROUND_THREAD
std::lock_guard lock_server_guard{*server_mutex}; std::lock_guard lock_server_guard{*server_mutex};
#endif #endif
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
@@ -8603,7 +8603,7 @@ GHOST_IContext *GHOST_SystemWayland::createOffscreenContext(GHOST_GPUSettings gp
nullptr, nullptr,
1, 1,
2, 2,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
context->setUserData(wl_surface); context->setUserData(wl_surface);
@@ -8712,12 +8712,12 @@ GHOST_IWindow *GHOST_SystemWayland::createWindow(const char *title,
const uint32_t width, const uint32_t width,
const uint32_t height, const uint32_t height,
const GHOST_TWindowState state, const GHOST_TWindowState state,
const GHOST_GPUSettings gpuSettings, const GHOST_GPUSettings gpu_settings,
const bool exclusive, const bool exclusive,
const bool is_dialog, const bool is_dialog,
const GHOST_IWindow *parentWindow) const GHOST_IWindow *parent_window)
{ {
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
/* Globally store pointer to window manager. */ /* Globally store pointer to window manager. */
GHOST_WindowWayland *window = new GHOST_WindowWayland(this, GHOST_WindowWayland *window = new GHOST_WindowWayland(this,
@@ -8727,17 +8727,17 @@ GHOST_IWindow *GHOST_SystemWayland::createWindow(const char *title,
width, width,
height, height,
state, state,
parentWindow, parent_window,
gpuSettings.context_type, gpu_settings.context_type,
is_dialog, is_dialog,
context_params, context_params,
exclusive, exclusive,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (window) { if (window) {
if (window->getValid()) { if (window->getValid()) {
m_windowManager->addWindow(window); window_manager_->addWindow(window);
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
const uint64_t event_ms = getMilliSeconds(); const uint64_t event_ms = getMilliSeconds();
pushEvent(new GHOST_Event(event_ms, GHOST_kEventWindowSize, window)); pushEvent(new GHOST_Event(event_ms, GHOST_kEventWindowSize, window));
} }
@@ -8826,7 +8826,7 @@ GHOST_TSuccess GHOST_SystemWayland::cursor_shape_set(const GHOST_TStandardCursor
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_SystemWayland::cursor_shape_check(const GHOST_TStandardCursor cursorShape) GHOST_TSuccess GHOST_SystemWayland::cursor_shape_check(const GHOST_TStandardCursor cursor_shape)
{ {
/* No need to lock `server_mutex`. */ /* No need to lock `server_mutex`. */
GWL_Seat *seat = gwl_display_seat_active_get(display_); GWL_Seat *seat = gwl_display_seat_active_get(display_);
@@ -8839,7 +8839,7 @@ GHOST_TSuccess GHOST_SystemWayland::cursor_shape_check(const GHOST_TStandardCurs
} }
const std::optional<wp_cursor_shape_device_v1_shape> wl_shape = const std::optional<wp_cursor_shape_device_v1_shape> wl_shape =
gwl_seat_cursor_find_wl_shape_from_ghost(cursorShape); gwl_seat_cursor_find_wl_shape_from_ghost(cursor_shape);
if (wl_shape == std::nullopt) { if (wl_shape == std::nullopt) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -9156,10 +9156,10 @@ static GWL_SeatStateGrab seat_grab_state_from_mode(const GHOST_TGrabCursorMode m
void GHOST_SystemWayland::setMultitouchGestures(const bool use) void GHOST_SystemWayland::setMultitouchGestures(const bool use)
{ {
if (m_multitouchGestures == use) { if (multitouch_gestures_ == use) {
return; return;
} }
m_multitouchGestures = use; multitouch_gestures_ = use;
#ifdef USE_EVENT_BACKGROUND_THREAD #ifdef USE_EVENT_BACKGROUND_THREAD
/* Ensure this listeners aren't removed while events are generated. */ /* Ensure this listeners aren't removed while events are generated. */
@@ -9708,14 +9708,14 @@ bool GHOST_SystemWayland::window_cursor_grab_set(const GHOST_TGrabCursorMode mod
GHOST_Rect bounds_scale; GHOST_Rect bounds_scale;
bounds_scale.m_l = gwl_window_scale_wl_fixed_from(scale_params, bounds_scale.l_ = gwl_window_scale_wl_fixed_from(scale_params,
wl_fixed_from_int(wrap_bounds->m_l)); wl_fixed_from_int(wrap_bounds->l_));
bounds_scale.m_t = gwl_window_scale_wl_fixed_from(scale_params, bounds_scale.t_ = gwl_window_scale_wl_fixed_from(scale_params,
wl_fixed_from_int(wrap_bounds->m_t)); wl_fixed_from_int(wrap_bounds->t_));
bounds_scale.m_r = gwl_window_scale_wl_fixed_from(scale_params, bounds_scale.r_ = gwl_window_scale_wl_fixed_from(scale_params,
wl_fixed_from_int(wrap_bounds->m_r)); wl_fixed_from_int(wrap_bounds->r_));
bounds_scale.m_b = gwl_window_scale_wl_fixed_from(scale_params, bounds_scale.b_ = gwl_window_scale_wl_fixed_from(scale_params,
wl_fixed_from_int(wrap_bounds->m_b)); wl_fixed_from_int(wrap_bounds->b_));
bounds_scale.wrapPoint(UNPACK2(xy_next), 0, wrap_axis); bounds_scale.wrapPoint(UNPACK2(xy_next), 0, wrap_axis);

View File

@@ -208,7 +208,7 @@ class GHOST_SystemWayland : public GHOST_System {
void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override; void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override;
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override;
GHOST_TSuccess disposeContext(GHOST_IContext *context) override; GHOST_TSuccess disposeContext(GHOST_IContext *context) override;
@@ -218,10 +218,10 @@ class GHOST_SystemWayland : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive, const bool exclusive,
const bool is_dialog, const bool is_dialog,
const GHOST_IWindow *parentWindow) override; const GHOST_IWindow *parent_window) override;
GHOST_TCapabilityFlag getCapabilities() const override; GHOST_TCapabilityFlag getCapabilities() const override;
@@ -231,7 +231,7 @@ class GHOST_SystemWayland : public GHOST_System {
GHOST_TSuccess cursor_shape_set(GHOST_TStandardCursor shape); GHOST_TSuccess cursor_shape_set(GHOST_TStandardCursor shape);
GHOST_TSuccess cursor_shape_check(GHOST_TStandardCursor cursorShape); GHOST_TSuccess cursor_shape_check(GHOST_TStandardCursor cursor_shape);
GHOST_TSuccess cursor_shape_custom_set(const GHOST_CursorGenerator &cg); GHOST_TSuccess cursor_shape_custom_set(const GHOST_CursorGenerator &cg);

View File

@@ -162,9 +162,9 @@ static void initRawInput()
typedef BOOL(API *GHOST_WIN32_EnableNonClientDpiScaling)(HWND); typedef BOOL(API *GHOST_WIN32_EnableNonClientDpiScaling)(HWND);
GHOST_SystemWin32::GHOST_SystemWin32() : m_hasPerformanceCounter(false), m_freq(0) GHOST_SystemWin32::GHOST_SystemWin32() : has_performance_counter_(false), freq_(0)
{ {
m_consoleStatus = true; console_status_ = true;
/* Tell Windows we are per monitor DPI aware. This disables the default /* Tell Windows we are per monitor DPI aware. This disables the default
* blurry scaling and enables WM_DPICHANGED to allow us to draw at proper DPI. */ * blurry scaling and enables WM_DPICHANGED to allow us to draw at proper DPI. */
@@ -183,7 +183,7 @@ GHOST_SystemWin32::GHOST_SystemWin32() : m_hasPerformanceCounter(false), m_freq(
OleInitialize(0); OleInitialize(0);
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
m_ndofManager = new GHOST_NDOFManagerWin32(*this); ndof_manager_ = new GHOST_NDOFManagerWin32(*this);
#endif #endif
} }
@@ -206,14 +206,14 @@ uint64_t GHOST_SystemWin32::performanceCounterToMillis(__int64 perf_ticks) const
/* Calculate the time passed since system initialization. */ /* Calculate the time passed since system initialization. */
__int64 delta = perf_ticks * 1000; __int64 delta = perf_ticks * 1000;
uint64_t t = uint64_t(delta / m_freq); uint64_t t = uint64_t(delta / freq_);
return t; return t;
} }
uint64_t GHOST_SystemWin32::getMilliSeconds() const uint64_t GHOST_SystemWin32::getMilliSeconds() const
{ {
/* Hardware does not support high resolution timers. We will use GetTickCount instead then. */ /* Hardware does not support high resolution timers. We will use GetTickCount instead then. */
if (!m_hasPerformanceCounter) { if (!has_performance_counter_) {
return ::GetTickCount64(); return ::GetTickCount64();
} }
@@ -266,12 +266,12 @@ GHOST_IWindow *GHOST_SystemWin32::createWindow(const char *title,
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool /*exclusive*/, const bool /*exclusive*/,
const bool is_dialog, const bool is_dialog,
const GHOST_IWindow *parentWindow) const GHOST_IWindow *parent_window)
{ {
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
GHOST_WindowWin32 *window = new GHOST_WindowWin32(this, GHOST_WindowWin32 *window = new GHOST_WindowWin32(this,
title, title,
left, left,
@@ -279,16 +279,16 @@ GHOST_IWindow *GHOST_SystemWin32::createWindow(const char *title,
width, width,
height, height,
state, state,
gpuSettings.context_type, gpu_settings.context_type,
context_params, context_params,
(GHOST_WindowWin32 *)parentWindow, (GHOST_WindowWin32 *)parent_window,
is_dialog, is_dialog,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (window->getValid()) { if (window->getValid()) {
/* Store the pointer to the window */ /* Store the pointer to the window */
m_windowManager->addWindow(window); window_manager_->addWindow(window);
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
} }
else { else {
GHOST_PRINT("GHOST_SystemWin32::createWindow(): window invalid\n"); GHOST_PRINT("GHOST_SystemWin32::createWindow(): window invalid\n");
@@ -304,16 +304,16 @@ GHOST_IWindow *GHOST_SystemWin32::createWindow(const char *title,
* Never explicitly delete the window, use #disposeContext() instead. * Never explicitly delete the window, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
GHOST_IContext *GHOST_SystemWin32::createOffscreenContext(GHOST_GPUSettings gpuSettings) GHOST_IContext *GHOST_SystemWin32::createOffscreenContext(GHOST_GPUSettings gpu_settings)
{ {
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
context_params_offscreen, (HWND)0, 1, 2, gpuSettings.preferred_device); context_params_offscreen, (HWND)0, 1, 2, gpu_settings.preferred_device);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -389,7 +389,7 @@ GHOST_TSuccess GHOST_SystemWin32::disposeContext(GHOST_IContext *context)
*/ */
GHOST_ContextD3D *GHOST_SystemWin32::createOffscreenContextD3D() GHOST_ContextD3D *GHOST_SystemWin32::createOffscreenContextD3D()
{ {
/* NOTE: the `gpuSettings` could be passed in here, as it is with similar functions. */ /* NOTE: the `gpu_settings` could be passed in here, as it is with similar functions. */
const GHOST_ContextParams context_params_offscreen = GHOST_CONTEXT_PARAMS_NONE; const GHOST_ContextParams context_params_offscreen = GHOST_CONTEXT_PARAMS_NONE;
HWND wnd = CreateWindowA("STATIC", HWND wnd = CreateWindowA("STATIC",
"Blender XR", "Blender XR",
@@ -464,7 +464,7 @@ bool GHOST_SystemWin32::processEvents(bool waitForEvent)
/* `PeekMessage` above is allowed to dispatch messages to the `wndproc` without us /* `PeekMessage` above is allowed to dispatch messages to the `wndproc` without us
* noticing, so we need to check the event manager here to see if there are * noticing, so we need to check the event manager here to see if there are
* events waiting in the queue. */ * events waiting in the queue. */
hasEventHandled |= this->m_eventManager->getNumEvents() > 0; hasEventHandled |= this->event_manager_->getNumEvents() > 0;
} while (waitForEvent && !hasEventHandled); } while (waitForEvent && !hasEventHandled);
@@ -563,7 +563,7 @@ GHOST_IWindow *GHOST_SystemWin32::getWindowUnderCursor(int32_t /*x*/, int32_t /*
return nullptr; return nullptr;
} }
return m_windowManager->getWindowAssociatedWithOSWindow((const void *)win); return window_manager_->getWindowAssociatedWithOSWindow((const void *)win);
} }
GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys &keys) const GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys &keys) const
@@ -637,7 +637,7 @@ GHOST_TSuccess GHOST_SystemWin32::init()
initRawInput(); initRawInput();
/* Determine whether this system has a high frequency performance counter. */ /* Determine whether this system has a high frequency performance counter. */
m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER *)&m_freq) == TRUE; has_performance_counter_ = ::QueryPerformanceFrequency((LARGE_INTEGER *)&freq_) == TRUE;
if (success) { if (success) {
WNDCLASSW wc = {0}; WNDCLASSW wc = {0};
@@ -723,7 +723,7 @@ GHOST_TKey GHOST_SystemWin32::processSpecialKey(short vKey, short /*scanCode*/)
key = GHOST_kKeyQuote; key = GHOST_kKeyQuote;
} }
else if (vKey == VK_OEM_8) { else if (vKey == VK_OEM_8) {
if (PRIMARYLANGID(m_langId) == LANG_FRENCH) { if (PRIMARYLANGID(lang_id_) == LANG_FRENCH) {
/* OEM key; used purely for shortcuts. */ /* OEM key; used purely for shortcuts. */
key = GHOST_kKeyF13; key = GHOST_kKeyF13;
} }
@@ -1269,7 +1269,7 @@ void GHOST_SystemWin32::processWheelEventVertical(GHOST_WindowWin32 *window,
{ {
GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem(); GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
int acc = system->m_wheelDeltaAccumVertical; int acc = system->wheel_delta_accum_vertical_;
int delta = GET_WHEEL_DELTA_WPARAM(wParam); int delta = GET_WHEEL_DELTA_WPARAM(wParam);
if (acc * delta < 0) { if (acc * delta < 0) {
@@ -1285,7 +1285,7 @@ void GHOST_SystemWin32::processWheelEventVertical(GHOST_WindowWin32 *window,
getMessageTime(system), window, GHOST_kEventWheelAxisVertical, direction)); getMessageTime(system), window, GHOST_kEventWheelAxisVertical, direction));
acc -= WHEEL_DELTA; acc -= WHEEL_DELTA;
} }
system->m_wheelDeltaAccumVertical = acc * direction; system->wheel_delta_accum_vertical_ = acc * direction;
} }
/** This is almost the same as #processWheelEventVertical. */ /** This is almost the same as #processWheelEventVertical. */
@@ -1295,7 +1295,7 @@ void GHOST_SystemWin32::processWheelEventHorizontal(GHOST_WindowWin32 *window,
{ {
GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem(); GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
int acc = system->m_wheelDeltaAccumHorizontal; int acc = system->wheel_delta_accum_horizontal_;
int delta = GET_WHEEL_DELTA_WPARAM(wParam); int delta = GET_WHEEL_DELTA_WPARAM(wParam);
if (acc * delta < 0) { if (acc * delta < 0) {
@@ -1311,7 +1311,7 @@ void GHOST_SystemWin32::processWheelEventHorizontal(GHOST_WindowWin32 *window,
getMessageTime(system), window, GHOST_kEventWheelAxisHorizontal, direction)); getMessageTime(system), window, GHOST_kEventWheelAxisHorizontal, direction));
acc -= WHEEL_DELTA; acc -= WHEEL_DELTA;
} }
system->m_wheelDeltaAccumHorizontal = acc * direction; system->wheel_delta_accum_horizontal_ = acc * direction;
} }
GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_WindowWin32 *window, RAWINPUT const &raw) GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_WindowWin32 *window, RAWINPUT const &raw)
@@ -1329,7 +1329,7 @@ GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_WindowWin32 *window, RA
/* If the keyboard layout includes AltGr and the virtual key is Control, yet the /* If the keyboard layout includes AltGr and the virtual key is Control, yet the
* scan-code is actually for Right Alt (ALTGR_MAKE_CODE scan code with E0 prefix). * scan-code is actually for Right Alt (ALTGR_MAKE_CODE scan code with E0 prefix).
* Ignore these, so treating AltGR as regular Alt. #68256 */ * Ignore these, so treating AltGR as regular Alt. #68256 */
if (system->m_hasAltGr && vk == VK_CONTROL && raw.data.keyboard.MakeCode == ALTGR_MAKE_CODE && if (system->has_alt_gr_ && vk == VK_CONTROL && raw.data.keyboard.MakeCode == ALTGR_MAKE_CODE &&
(raw.data.keyboard.Flags & RI_KEY_E0)) (raw.data.keyboard.Flags & RI_KEY_E0))
{ {
return nullptr; return nullptr;
@@ -1380,7 +1380,7 @@ GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_WindowWin32 *window, RA
/* TODO: #ToUnicodeEx can respond with up to 4 UTF16 chars (only 2 here). /* TODO: #ToUnicodeEx can respond with up to 4 UTF16 chars (only 2 here).
* Could be up to 24 UTF8 bytes. */ * Could be up to 24 UTF8 bytes. */
if ((r = ToUnicodeEx( if ((r = ToUnicodeEx(
vk, raw.data.keyboard.MakeCode, state, utf16, 2, 0, system->m_keylayout))) vk, raw.data.keyboard.MakeCode, state, utf16, 2, 0, system->keylayout_)))
{ {
if ((r > 0 && r < 3)) { if ((r > 0 && r < 3)) {
utf16[r] = 0; utf16[r] = 0;
@@ -1429,7 +1429,7 @@ GHOST_Event *GHOST_SystemWin32::processWindowSizeEvent(GHOST_WindowWin32 *window
GHOST_Event *sizeEvent = new GHOST_Event(getMessageTime(system), GHOST_kEventWindowSize, window); GHOST_Event *sizeEvent = new GHOST_Event(getMessageTime(system), GHOST_kEventWindowSize, window);
/* We get WM_SIZE before we fully init. Do not dispatch before we are continuously resizing. */ /* We get WM_SIZE before we fully init. Do not dispatch before we are continuously resizing. */
if (window->m_inLiveResize) { if (window->in_live_resize_) {
system->pushEvent(sizeEvent); system->pushEvent(sizeEvent);
system->dispatchEvents(); system->dispatchEvents();
return nullptr; return nullptr;
@@ -1524,7 +1524,7 @@ bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize); GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
/* Since there can be multiple NDOF devices connected, always set the current device. */ /* Since there can be multiple NDOF devices connected, always set the current device. */
if (info.dwType == RIM_TYPEHID) { if (info.dwType == RIM_TYPEHID) {
m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId); ndof_manager_->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
} }
else { else {
GHOST_PRINT("<!> not a HID device... mouse/kb perhaps?\n"); GHOST_PRINT("<!> not a HID device... mouse/kb perhaps?\n");
@@ -1542,12 +1542,12 @@ bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
const short *axis = (short *)(data + 1); const short *axis = (short *)(data + 1);
/* Massage into blender view coords (same goes for rotation). */ /* Massage into blender view coords (same goes for rotation). */
const int t[3] = {axis[0], -axis[2], axis[1]}; const int t[3] = {axis[0], -axis[2], axis[1]};
m_ndofManager->updateTranslation(t, now); ndof_manager_->updateTranslation(t, now);
if (raw.data.hid.dwSizeHid == 13) { if (raw.data.hid.dwSizeHid == 13) {
/* This report also includes rotation. */ /* This report also includes rotation. */
const int r[3] = {-axis[3], axis[5], -axis[4]}; const int r[3] = {-axis[3], axis[5], -axis[4]};
m_ndofManager->updateRotation(r, now); ndof_manager_->updateRotation(r, now);
/* I've never gotten one of these, has anyone else? */ /* I've never gotten one of these, has anyone else? */
GHOST_PRINT("ndof: combined T + R\n"); GHOST_PRINT("ndof: combined T + R\n");
@@ -1558,13 +1558,13 @@ bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
const short *axis = (short *)(data + 1); const short *axis = (short *)(data + 1);
const int r[3] = {-axis[0], axis[2], -axis[1]}; const int r[3] = {-axis[0], axis[2], -axis[1]};
m_ndofManager->updateRotation(r, now); ndof_manager_->updateRotation(r, now);
break; break;
} }
case 0x3: { /* Buttons bitmask (older devices). */ case 0x3: { /* Buttons bitmask (older devices). */
int button_bits; int button_bits;
memcpy(&button_bits, data + 1, sizeof(button_bits)); memcpy(&button_bits, data + 1, sizeof(button_bits));
m_ndofManager->updateButtonsBitmask(button_bits, now); ndof_manager_->updateButtonsBitmask(button_bits, now);
break; break;
} }
case 0x1c: { /* Buttons numbers (newer devices). */ case 0x1c: { /* Buttons numbers (newer devices). */
@@ -1573,7 +1573,7 @@ bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
for (int i = 0; i < buttons.size(); i++) { for (int i = 0; i < buttons.size(); i++) {
buttons[i] = static_cast<GHOST_NDOF_ButtonT>(*(payload + i)); buttons[i] = static_cast<GHOST_NDOF_ButtonT>(*(payload + i));
} }
m_ndofManager->updateButtonsArray(buttons, now, NDOF_Button_Type::ShortButton); ndof_manager_->updateButtonsArray(buttons, now, NDOF_Button_Type::ShortButton);
break; break;
} }
case 0x1d: { /* Buttons (long press, newer devices). */ case 0x1d: { /* Buttons (long press, newer devices). */
@@ -1582,7 +1582,7 @@ bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
for (int i = 0; i < buttons.size(); i++) { for (int i = 0; i < buttons.size(); i++) {
buttons[i] = translateLongButtonToNDOFButton(*(payload + i)); buttons[i] = translateLongButtonToNDOFButton(*(payload + i));
} }
m_ndofManager->updateButtonsArray(buttons, now, NDOF_Button_Type::LongButton); ndof_manager_->updateButtonsArray(buttons, now, NDOF_Button_Type::LongButton);
break; break;
} }
} }
@@ -1653,10 +1653,10 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
if (msg == WM_NCCREATE) { if (msg == WM_NCCREATE) {
/* Tell Windows to automatically handle scaling of non-client areas /* Tell Windows to automatically handle scaling of non-client areas
* such as the caption bar. #EnableNonClientDpiScaling was introduced in Windows 10. */ * such as the caption bar. #EnableNonClientDpiScaling was introduced in Windows 10. */
HMODULE m_user32 = ::LoadLibrary("User32.dll"); HMODULE user32_ = ::LoadLibrary("User32.dll");
if (m_user32) { if (user32_) {
GHOST_WIN32_EnableNonClientDpiScaling fpEnableNonClientDpiScaling = GHOST_WIN32_EnableNonClientDpiScaling fpEnableNonClientDpiScaling =
(GHOST_WIN32_EnableNonClientDpiScaling)::GetProcAddress(m_user32, (GHOST_WIN32_EnableNonClientDpiScaling)::GetProcAddress(user32_,
"EnableNonClientDpiScaling"); "EnableNonClientDpiScaling");
if (fpEnableNonClientDpiScaling) { if (fpEnableNonClientDpiScaling) {
fpEnableNonClientDpiScaling(hwnd); fpEnableNonClientDpiScaling(hwnd);
@@ -1997,19 +1997,19 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
break; break;
} }
case WM_MOUSEMOVE: { case WM_MOUSEMOVE: {
if (!window->m_mousePresent) { if (!window->mouse_present_) {
WINTAB_PRINTF("HWND %p mouse enter\n", window->getHWND()); WINTAB_PRINTF("HWND %p mouse enter\n", window->getHWND());
TRACKMOUSEEVENT tme = {sizeof(tme)}; TRACKMOUSEEVENT tme = {sizeof(tme)};
/* Request WM_MOUSELEAVE message when the cursor leaves the client area. */ /* Request WM_MOUSELEAVE message when the cursor leaves the client area. */
tme.dwFlags = TME_LEAVE; tme.dwFlags = TME_LEAVE;
if (system->m_autoFocus) { if (system->auto_focus_) {
/* Request WM_MOUSEHOVER message after 100ms when in the client area. */ /* Request WM_MOUSEHOVER message after 100ms when in the client area. */
tme.dwFlags |= TME_HOVER; tme.dwFlags |= TME_HOVER;
tme.dwHoverTime = 100; tme.dwHoverTime = 100;
} }
tme.hwndTrack = hwnd; tme.hwndTrack = hwnd;
TrackMouseEvent(&tme); TrackMouseEvent(&tme);
window->m_mousePresent = true; window->mouse_present_ = true;
GHOST_Wintab *wt = window->getWintab(); GHOST_Wintab *wt = window->getWintab();
if (wt) { if (wt) {
wt->gainFocus(); wt->gainFocus();
@@ -2025,7 +2025,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
} }
case WM_MOUSEHOVER: { case WM_MOUSEHOVER: {
/* Mouse Tracking is now off. TrackMouseEvent restarts in MouseMove. */ /* Mouse Tracking is now off. TrackMouseEvent restarts in MouseMove. */
window->m_mousePresent = false; window->mouse_present_ = false;
/* Auto-focus only occurs within Blender windows, not with _other_ applications. We are /* Auto-focus only occurs within Blender windows, not with _other_ applications. We are
* notified of change of focus from our console, but it returns null from GetFocus. */ * notified of change of focus from our console, but it returns null from GetFocus. */
@@ -2100,7 +2100,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
} }
case WM_MOUSELEAVE: { case WM_MOUSELEAVE: {
WINTAB_PRINTF("HWND %p mouse leave\n", window->getHWND()); WINTAB_PRINTF("HWND %p mouse leave\n", window->getHWND());
window->m_mousePresent = false; window->mouse_present_ = false;
if (window->getTabletData().Active == GHOST_kTabletModeNone) { if (window->getTabletData().Active == GHOST_kTabletModeNone) {
/* FIXME: document why the cursor motion event on mouse leave is needed. */ /* FIXME: document why the cursor motion event on mouse leave is needed. */
int32_t screen_co[2] = {0, 0}; int32_t screen_co[2] = {0, 0};
@@ -2150,8 +2150,8 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
* If the windows use different input queues, the message is sent asynchronously, * If the windows use different input queues, the message is sent asynchronously,
* so the window is activated immediately. */ * so the window is activated immediately. */
system->m_wheelDeltaAccumVertical = 0; system->wheel_delta_accum_vertical_ = 0;
system->m_wheelDeltaAccumHorizontal = 0; system->wheel_delta_accum_horizontal_ = 0;
event = processWindowEvent( event = processWindowEvent(
LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window); LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
/* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
@@ -2171,11 +2171,11 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
* message specifies the SC_MOVE or SC_SIZE value. The operation is complete when * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when
* DefWindowProc returns. * DefWindowProc returns.
*/ */
window->m_inLiveResize = 1; window->in_live_resize_ = 1;
break; break;
} }
case WM_EXITSIZEMOVE: { case WM_EXITSIZEMOVE: {
window->m_inLiveResize = 0; window->in_live_resize_ = 0;
break; break;
} }
case WM_PAINT: { case WM_PAINT: {
@@ -2185,7 +2185,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
* function when the application obtains a WM_PAINT message by using the GetMessage or * function when the application obtains a WM_PAINT message by using the GetMessage or
* PeekMessage function. * PeekMessage function.
*/ */
if (!window->m_inLiveResize) { if (!window->in_live_resize_) {
event = processWindowEvent(GHOST_kEventWindowUpdate, window); event = processWindowEvent(GHOST_kEventWindowUpdate, window);
::ValidateRect(hwnd, nullptr); ::ValidateRect(hwnd, nullptr);
} }
@@ -2234,7 +2234,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
* message without calling DefWindowProc. * message without calling DefWindowProc.
*/ */
/* See #WM_SIZE comment. */ /* See #WM_SIZE comment. */
if (window->m_inLiveResize) { if (window->in_live_resize_) {
system->pushEvent(processWindowEvent(GHOST_kEventWindowMove, window)); system->pushEvent(processWindowEvent(GHOST_kEventWindowMove, window));
system->dispatchEvents(); system->dispatchEvents();
} }
@@ -2380,7 +2380,7 @@ LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, uint msg, WPARAM wParam,
/* The DM_POINTERHITTEST message is sent to a window, when pointer input is first /* The DM_POINTERHITTEST message is sent to a window, when pointer input is first
* detected, in order to determine the most probable input target for Direct * detected, in order to determine the most probable input target for Direct
* Manipulation. */ * Manipulation. */
if (system->m_multitouchGestures) { if (system->multitouch_gestures_) {
window->onPointerHitTest(wParam); window->onPointerHitTest(wParam);
} }
break; break;
@@ -2950,13 +2950,13 @@ bool GHOST_SystemWin32::setConsoleWindowState(GHOST_TConsoleWindowState action)
case GHOST_kConsoleWindowStateHideForNonConsoleLaunch: { case GHOST_kConsoleWindowStateHideForNonConsoleLaunch: {
if (!isStartedFromCommandPrompt()) { if (!isStartedFromCommandPrompt()) {
ShowWindow(wnd, SW_HIDE); ShowWindow(wnd, SW_HIDE);
m_consoleStatus = false; console_status_ = false;
} }
break; break;
} }
case GHOST_kConsoleWindowStateHide: { case GHOST_kConsoleWindowStateHide: {
ShowWindow(wnd, SW_HIDE); ShowWindow(wnd, SW_HIDE);
m_consoleStatus = false; console_status_ = false;
break; break;
} }
case GHOST_kConsoleWindowStateShow: { case GHOST_kConsoleWindowStateShow: {
@@ -2964,18 +2964,18 @@ bool GHOST_SystemWin32::setConsoleWindowState(GHOST_TConsoleWindowState action)
if (!isStartedFromCommandPrompt()) { if (!isStartedFromCommandPrompt()) {
DeleteMenu(GetSystemMenu(wnd, FALSE), SC_CLOSE, MF_BYCOMMAND); DeleteMenu(GetSystemMenu(wnd, FALSE), SC_CLOSE, MF_BYCOMMAND);
} }
m_consoleStatus = true; console_status_ = true;
break; break;
} }
case GHOST_kConsoleWindowStateToggle: { case GHOST_kConsoleWindowStateToggle: {
ShowWindow(wnd, m_consoleStatus ? SW_HIDE : SW_SHOW); ShowWindow(wnd, console_status_ ? SW_HIDE : SW_SHOW);
m_consoleStatus = !m_consoleStatus; console_status_ = !console_status_;
if (m_consoleStatus && !isStartedFromCommandPrompt()) { if (console_status_ && !isStartedFromCommandPrompt()) {
DeleteMenu(GetSystemMenu(wnd, FALSE), SC_CLOSE, MF_BYCOMMAND); DeleteMenu(GetSystemMenu(wnd, FALSE), SC_CLOSE, MF_BYCOMMAND);
} }
break; break;
} }
} }
return m_consoleStatus; return console_status_;
} }

View File

@@ -101,9 +101,9 @@ class GHOST_SystemWin32 : public GHOST_System {
* \param width: The width the window. * \param width: The width the window.
* \param height: The height the window. * \param height: The height the window.
* \param state: The state of the window when opened. * \param state: The state of the window when opened.
* \param gpuSettings: Misc GPU settings. * \param gpu_settings: Misc GPU settings.
* \param exclusive: Use to show the window on top and ignore others (used full-screen). * \param exclusive: Use to show the window on top and ignore others (used full-screen).
* \param parentWindow: Parent window. * \param parent_window: Parent window.
* \return The new window (or 0 if creation failed). * \return The new window (or 0 if creation failed).
*/ */
GHOST_IWindow *createWindow(const char *title, GHOST_IWindow *createWindow(const char *title,
@@ -112,17 +112,17 @@ class GHOST_SystemWin32 : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive = false, const bool exclusive = false,
const bool is_dialog = false, const bool is_dialog = false,
const GHOST_IWindow *parentWindow = nullptr) override; const GHOST_IWindow *parent_window = nullptr) override;
/** /**
* Create a new off-screen context. * Create a new off-screen context.
* Never explicitly delete the window, use #disposeContext() instead. * Never explicitly delete the window, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override;
/** /**
* Dispose of a context. * Dispose of a context.
@@ -387,7 +387,7 @@ class GHOST_SystemWin32 : public GHOST_System {
static void processWheelEventHorizontal(GHOST_WindowWin32 *window, WPARAM wParam, LPARAM lParam); static void processWheelEventHorizontal(GHOST_WindowWin32 *window, WPARAM wParam, LPARAM lParam);
/** /**
* Creates a key event and updates the key data stored locally (m_modifierKeys). * Creates a key event and updates the key data stored locally (modifier_keys_).
* In most cases this is a straightforward conversion of key codes. * In most cases this is a straightforward conversion of key codes.
* For the modifier keys however, we want to distinguish left and right keys. * For the modifier keys however, we want to distinguish left and right keys.
* \param window: The window receiving the event (the active window). * \param window: The window receiving the event (the active window).
@@ -476,40 +476,40 @@ class GHOST_SystemWin32 : public GHOST_System {
bool setConsoleWindowState(GHOST_TConsoleWindowState action) override; bool setConsoleWindowState(GHOST_TConsoleWindowState action) override;
/** State variable set at initialization. */ /** State variable set at initialization. */
bool m_hasPerformanceCounter; bool has_performance_counter_;
/** High frequency timer variable. */ /** High frequency timer variable. */
__int64 m_freq; __int64 freq_;
/** AltGr on current keyboard layout. */ /** AltGr on current keyboard layout. */
bool m_hasAltGr; bool has_alt_gr_;
/** Language identifier. */ /** Language identifier. */
WORD m_langId; WORD lang_id_;
/** Stores keyboard layout. */ /** Stores keyboard layout. */
HKL m_keylayout; HKL keylayout_;
/** Console status. */ /** Console status. */
bool m_consoleStatus; bool console_status_;
/** Wheel delta accumulators. */ /** Wheel delta accumulators. */
int m_wheelDeltaAccumVertical; int wheel_delta_accum_vertical_;
int m_wheelDeltaAccumHorizontal; int wheel_delta_accum_horizontal_;
}; };
inline void GHOST_SystemWin32::handleKeyboardChange() inline void GHOST_SystemWin32::handleKeyboardChange()
{ {
m_keylayout = GetKeyboardLayout(0); /* Get keylayout for current thread. */ keylayout_ = GetKeyboardLayout(0); /* Get keylayout for current thread. */
int i; int i;
SHORT s; SHORT s;
/* Save the language identifier. */ /* Save the language identifier. */
m_langId = LOWORD(m_keylayout); lang_id_ = LOWORD(keylayout_);
for (m_hasAltGr = false, i = 32; i < 256; ++i) { for (has_alt_gr_ = false, i = 32; i < 256; ++i) {
s = VkKeyScanEx((char)i, m_keylayout); s = VkKeyScanEx((char)i, keylayout_);
/* `s == -1` means no key that translates passed char code high byte contains shift state. /* `s == -1` means no key that translates passed char code high byte contains shift state.
* bit 2 Control pressed, bit 4 `Alt` pressed if both are pressed, * bit 2 Control pressed, bit 4 `Alt` pressed if both are pressed,
* we have `AltGr` key-combination on key-layout. */ * we have `AltGr` key-combination on key-layout. */
if (s != -1 && (s & 0x600) == 0x600) { if (s != -1 && (s & 0x600) == 0x600) {
m_hasAltGr = true; has_alt_gr_ = true;
break; break;
} }
} }

View File

@@ -104,17 +104,17 @@ using namespace std;
GHOST_SystemX11::GHOST_SystemX11() GHOST_SystemX11::GHOST_SystemX11()
: GHOST_System(), : GHOST_System(),
m_xkb_descr(nullptr), xkb_descr_(nullptr),
m_keyboard_vector{0}, keyboard_vector_{0},
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
m_last_key_time(0), last_key_time_(0),
#endif #endif
m_keycode_last_repeat_key(uint(-1)) keycode_last_repeat_key_(uint(-1))
{ {
XInitThreads(); XInitThreads();
m_display = XOpenDisplay(nullptr); display_ = XOpenDisplay(nullptr);
if (!m_display) { if (!display_) {
throw std::runtime_error("unable to open a display!"); throw std::runtime_error("unable to open a display!");
} }
@@ -127,17 +127,17 @@ GHOST_SystemX11::GHOST_SystemX11()
/* NOTE: Don't open connection to XIM server here, because the locale has to be /* NOTE: Don't open connection to XIM server here, because the locale has to be
* set before opening the connection but `setlocale()` has not been called yet. * set before opening the connection but `setlocale()` has not been called yet.
* the connection will be opened after entering the event loop. */ * the connection will be opened after entering the event loop. */
m_xim = nullptr; xim_ = nullptr;
#endif #endif
#define GHOST_INTERN_ATOM_IF_EXISTS(atom) \ #define GHOST_INTERN_ATOM_IF_EXISTS(atom) \
{ \ { \
m_atom.atom = XInternAtom(m_display, #atom, True); \ atom_.atom = XInternAtom(display_, #atom, True); \
} \ } \
(void)0 (void)0
#define GHOST_INTERN_ATOM(atom) \ #define GHOST_INTERN_ATOM(atom) \
{ \ { \
m_atom.atom = XInternAtom(m_display, #atom, False); \ atom_.atom = XInternAtom(display_, #atom, False); \
} \ } \
(void)0 (void)0
@@ -162,16 +162,16 @@ GHOST_SystemX11::GHOST_SystemX11()
GHOST_INTERN_ATOM(INCR); GHOST_INTERN_ATOM(INCR);
GHOST_INTERN_ATOM(UTF8_STRING); GHOST_INTERN_ATOM(UTF8_STRING);
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
m_atom.TABLET = XInternAtom(m_display, XI_TABLET, False); atom_.TABLET = XInternAtom(display_, XI_TABLET, False);
#endif #endif
#undef GHOST_INTERN_ATOM_IF_EXISTS #undef GHOST_INTERN_ATOM_IF_EXISTS
#undef GHOST_INTERN_ATOM #undef GHOST_INTERN_ATOM
m_last_warp_x = 0; last_warp_x_ = 0;
m_last_warp_y = 0; last_warp_y_ = 0;
m_last_release_keycode = 0; last_release_keycode_ = 0;
m_last_release_time = 0; last_release_time_ = 0;
/* Use detectable auto-repeat, mac and windows also do this. */ /* Use detectable auto-repeat, mac and windows also do this. */
int use_xkb; int use_xkb;
@@ -179,14 +179,14 @@ GHOST_SystemX11::GHOST_SystemX11()
int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion; int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
use_xkb = XkbQueryExtension( use_xkb = XkbQueryExtension(
m_display, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor); display_, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor);
if (use_xkb) { if (use_xkb) {
XkbSetDetectableAutoRepeat(m_display, true, nullptr); XkbSetDetectableAutoRepeat(display_, true, nullptr);
m_xkb_descr = XkbGetMap(m_display, 0, XkbUseCoreKbd); xkb_descr_ = XkbGetMap(display_, 0, XkbUseCoreKbd);
if (m_xkb_descr) { if (xkb_descr_) {
XkbGetNames(m_display, XkbKeyNamesMask, m_xkb_descr); XkbGetNames(display_, XkbKeyNamesMask, xkb_descr_);
XkbGetControls(m_display, XkbPerKeyRepeatMask | XkbRepeatKeysMask, m_xkb_descr); XkbGetControls(display_, XkbPerKeyRepeatMask | XkbRepeatKeysMask, xkb_descr_);
} }
} }
@@ -197,23 +197,23 @@ GHOST_SystemX11::GHOST_SystemX11()
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
/* Detect if we have XINPUT (for reuse). */ /* Detect if we have XINPUT (for reuse). */
{ {
memset(&m_xinput_version, 0, sizeof(m_xinput_version)); memset(&xinput_version_, 0, sizeof(xinput_version_));
XExtensionVersion *version = XGetExtensionVersion(m_display, INAME); XExtensionVersion *version = XGetExtensionVersion(display_, INAME);
if (version && (version != (XExtensionVersion *)NoSuchExtension)) { if (version && (version != (XExtensionVersion *)NoSuchExtension)) {
if (version->present) { if (version->present) {
m_xinput_version = *version; xinput_version_ = *version;
} }
XFree(version); XFree(version);
} }
} }
# ifdef USE_XINPUT_HOTPLUG # ifdef USE_XINPUT_HOTPLUG
if (m_xinput_version.present) { if (xinput_version_.present) {
XEventClass class_presence; XEventClass class_presence;
int xi_presence; int xi_presence;
DevicePresence(m_display, xi_presence, class_presence); DevicePresence(display_, xi_presence, class_presence);
XSelectExtensionEvent( XSelectExtensionEvent(
m_display, RootWindow(m_display, DefaultScreen(m_display)), &class_presence, 1); display_, RootWindow(display_, DefaultScreen(display_)), &class_presence, 1);
(void)xi_presence; (void)xi_presence;
} }
# endif /* USE_XINPUT_HOTPLUG */ # endif /* USE_XINPUT_HOTPLUG */
@@ -225,8 +225,8 @@ GHOST_SystemX11::GHOST_SystemX11()
GHOST_SystemX11::~GHOST_SystemX11() GHOST_SystemX11::~GHOST_SystemX11()
{ {
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
if (m_xim) { if (xim_) {
XCloseIM(m_xim); XCloseIM(xim_);
} }
#endif #endif
@@ -235,11 +235,11 @@ GHOST_SystemX11::~GHOST_SystemX11()
clearXInputDevices(); clearXInputDevices();
#endif /* WITH_X11_XINPUT */ #endif /* WITH_X11_XINPUT */
if (m_xkb_descr) { if (xkb_descr_) {
XkbFreeKeyboard(m_xkb_descr, XkbAllComponentsMask, true); XkbFreeKeyboard(xkb_descr_, XkbAllComponentsMask, true);
} }
XCloseDisplay(m_display); XCloseDisplay(display_);
} }
GHOST_TSuccess GHOST_SystemX11::init() GHOST_TSuccess GHOST_SystemX11::init()
@@ -248,7 +248,7 @@ GHOST_TSuccess GHOST_SystemX11::init()
if (success) { if (success) {
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
m_ndofManager = new GHOST_NDOFManagerUnix(*this); ndof_manager_ = new GHOST_NDOFManagerUnix(*this);
#endif #endif
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -333,7 +333,7 @@ uint8_t GHOST_SystemX11::getNumDisplays() const
void GHOST_SystemX11::getMainDisplayDimensions(uint32_t &width, uint32_t &height) const void GHOST_SystemX11::getMainDisplayDimensions(uint32_t &width, uint32_t &height) const
{ {
if (m_display) { if (display_) {
/* NOTE(@ideasman42): for this to work as documented, /* NOTE(@ideasman42): for this to work as documented,
* we would need to use Xinerama check r54370 for code that did this, * we would need to use Xinerama check r54370 for code that did this,
* we've since removed since its not worth the extra dependency. */ * we've since removed since its not worth the extra dependency. */
@@ -343,9 +343,9 @@ void GHOST_SystemX11::getMainDisplayDimensions(uint32_t &width, uint32_t &height
void GHOST_SystemX11::getAllDisplayDimensions(uint32_t &width, uint32_t &height) const void GHOST_SystemX11::getAllDisplayDimensions(uint32_t &width, uint32_t &height) const
{ {
if (m_display) { if (display_) {
width = DisplayWidth(m_display, DefaultScreen(m_display)); width = DisplayWidth(display_, DefaultScreen(display_));
height = DisplayHeight(m_display, DefaultScreen(m_display)); height = DisplayHeight(display_, DefaultScreen(display_));
} }
} }
@@ -355,32 +355,32 @@ GHOST_IWindow *GHOST_SystemX11::createWindow(const char *title,
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive, const bool exclusive,
const bool is_dialog, const bool is_dialog,
const GHOST_IWindow *parentWindow) const GHOST_IWindow *parent_window)
{ {
GHOST_WindowX11 *window = nullptr; GHOST_WindowX11 *window = nullptr;
if (!m_display) { if (!display_) {
return nullptr; return nullptr;
} }
const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpuSettings); const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
window = new GHOST_WindowX11(this, window = new GHOST_WindowX11(this,
m_display, display_,
title, title,
left, left,
top, top,
width, width,
height, height,
state, state,
(GHOST_WindowX11 *)parentWindow, (GHOST_WindowX11 *)parent_window,
gpuSettings.context_type, gpu_settings.context_type,
is_dialog, is_dialog,
context_params, context_params,
exclusive, exclusive,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (window) { if (window) {
/* Both are now handle in GHOST_WindowX11.cc /* Both are now handle in GHOST_WindowX11.cc
@@ -388,8 +388,8 @@ GHOST_IWindow *GHOST_SystemX11::createWindow(const char *title,
if (window->getValid()) { if (window->getValid()) {
/* Store the pointer to the window */ /* Store the pointer to the window */
m_windowManager->addWindow(window); window_manager_->addWindow(window);
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window)); pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window));
} }
else { else {
@@ -400,24 +400,24 @@ GHOST_IWindow *GHOST_SystemX11::createWindow(const char *title,
return window; return window;
} }
GHOST_IContext *GHOST_SystemX11::createOffscreenContext(GHOST_GPUSettings gpuSettings) GHOST_IContext *GHOST_SystemX11::createOffscreenContext(GHOST_GPUSettings gpu_settings)
{ {
const GHOST_ContextParams context_params_offscreen = const GHOST_ContextParams context_params_offscreen =
GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpuSettings); GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings);
switch (gpuSettings.context_type) { switch (gpu_settings.context_type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen, GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen,
GHOST_kVulkanPlatformX11, GHOST_kVulkanPlatformX11,
0, 0,
m_display, display_,
nullptr, nullptr,
nullptr, nullptr,
nullptr, nullptr,
1, 1,
2, 2,
gpuSettings.preferred_device); gpu_settings.preferred_device);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -432,7 +432,7 @@ GHOST_IContext *GHOST_SystemX11::createOffscreenContext(GHOST_GPUSettings gpuSet
GHOST_Context *context = new GHOST_ContextGLX( GHOST_Context *context = new GHOST_ContextGLX(
context_params_offscreen, context_params_offscreen,
(Window) nullptr, (Window) nullptr,
m_display, display_,
(GLXFBConfig) nullptr, (GLXFBConfig) nullptr,
GLX_CONTEXT_CORE_PROFILE_BIT_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
4, 4,
@@ -474,22 +474,22 @@ static void destroyIMCallback(XIM /*xim*/, XPointer ptr, XPointer /*data*/)
bool GHOST_SystemX11::openX11_IM() bool GHOST_SystemX11::openX11_IM()
{ {
if (!m_display) { if (!display_) {
return false; return false;
} }
/* set locale modifiers such as `@im=ibus` specified by XMODIFIERS. */ /* set locale modifiers such as `@im=ibus` specified by XMODIFIERS. */
XSetLocaleModifiers(""); XSetLocaleModifiers("");
m_xim = XOpenIM(m_display, nullptr, (char *)GHOST_X11_RES_NAME, (char *)GHOST_X11_RES_CLASS); xim_ = XOpenIM(display_, nullptr, (char *)GHOST_X11_RES_NAME, (char *)GHOST_X11_RES_CLASS);
if (!m_xim) { if (!xim_) {
return false; return false;
} }
XIMCallback destroy; XIMCallback destroy;
destroy.callback = (XIMProc)destroyIMCallback; destroy.callback = (XIMProc)destroyIMCallback;
destroy.client_data = (XPointer)&m_xim; destroy.client_data = (XPointer)&xim_;
XSetIMValues(m_xim, XNDestroyCallback, &destroy, nullptr); XSetIMValues(xim_, XNDestroyCallback, &destroy, nullptr);
return true; return true;
} }
#endif #endif
@@ -506,7 +506,7 @@ GHOST_WindowX11 *GHOST_SystemX11::findGhostWindow(Window xwind) const
* We should always check the window manager's list of windows * We should always check the window manager's list of windows
* and only process events on these windows. */ * and only process events on these windows. */
const vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end(); vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
@@ -583,7 +583,7 @@ Time GHOST_SystemX11::lastEventTime(Time default_time)
init_timestamp_data data; init_timestamp_data data;
data.timestamp = default_time; data.timestamp = default_time;
XEvent ev; XEvent ev;
XCheckIfEvent(m_display, &ev, &init_timestamp_scanner, (XPointer)&data); XCheckIfEvent(display_, &ev, &init_timestamp_scanner, (XPointer)&data);
return data.timestamp; return data.timestamp;
} }
@@ -598,17 +598,17 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
do { do {
GHOST_TimerManager *timerMgr = getTimerManager(); GHOST_TimerManager *timerMgr = getTimerManager();
if (waitForEvent && m_dirty_windows.empty() && !XPending(m_display)) { if (waitForEvent && dirty_windows_.empty() && !XPending(display_)) {
uint64_t next = timerMgr->nextFireTime(); uint64_t next = timerMgr->nextFireTime();
if (next == GHOST_kFireTimeNever) { if (next == GHOST_kFireTimeNever) {
SleepTillEvent(m_display, -1); SleepTillEvent(display_, -1);
} }
else { else {
const int64_t maxSleep = next - getMilliSeconds(); const int64_t maxSleep = next - getMilliSeconds();
if (maxSleep >= 0) { if (maxSleep >= 0) {
SleepTillEvent(m_display, next - getMilliSeconds()); SleepTillEvent(display_, next - getMilliSeconds());
} }
} }
} }
@@ -617,20 +617,20 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
anyProcessed = true; anyProcessed = true;
} }
while (XPending(m_display)) { while (XPending(display_)) {
XEvent xevent; XEvent xevent;
XNextEvent(m_display, &xevent); XNextEvent(display_, &xevent);
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
/* open connection to XIM server and create input context (XIC) /* open connection to XIM server and create input context (XIC)
* when receiving the first FocusIn or KeyPress event after startup, * when receiving the first FocusIn or KeyPress event after startup,
* or recover XIM and XIC when the XIM server has been restarted */ * or recover XIM and XIC when the XIM server has been restarted */
if (ELEM(xevent.type, FocusIn, KeyPress)) { if (ELEM(xevent.type, FocusIn, KeyPress)) {
if (!m_xim && openX11_IM()) { if (!xim_ && openX11_IM()) {
GHOST_PRINT("Connected to XIM server\n"); GHOST_PRINT("Connected to XIM server\n");
} }
if (m_xim) { if (xim_) {
GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window); GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
if (window && !window->getX11_XIC() && window->createX11_XIC()) { if (window && !window->getX11_XIC() && window->createX11_XIC()) {
GHOST_PRINT("XIM input context created\n"); GHOST_PRINT("XIM input context created\n");
@@ -647,7 +647,7 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
/* Ensure generated time-stamps are non-zero. */ /* Ensure generated time-stamps are non-zero. */
if (ELEM(xevent.type, KeyPress, KeyRelease)) { if (ELEM(xevent.type, KeyPress, KeyRelease)) {
if (xevent.xkey.time != 0) { if (xevent.xkey.time != 0) {
m_last_key_time = xevent.xkey.time; last_key_time_ = xevent.xkey.time;
} }
} }
@@ -660,12 +660,12 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
/* When using auto-repeat, some key-press events can actually come *after* the /* When using auto-repeat, some key-press events can actually come *after* the
* last key-release. The next code takes care of that. */ * last key-release. The next code takes care of that. */
if (xevent.type == KeyRelease) { if (xevent.type == KeyRelease) {
m_last_release_keycode = xevent.xkey.keycode; last_release_keycode_ = xevent.xkey.keycode;
m_last_release_time = xevent.xkey.time; last_release_time_ = xevent.xkey.time;
} }
else if (xevent.type == KeyPress) { else if (xevent.type == KeyPress) {
if ((xevent.xkey.keycode == m_last_release_keycode) && if ((xevent.xkey.keycode == last_release_keycode_) &&
(xevent.xkey.time <= m_last_release_time)) (xevent.xkey.time <= last_release_time_))
{ {
continue; continue;
} }
@@ -685,15 +685,15 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
/* use previous event's window, because KeymapNotify event /* use previous event's window, because KeymapNotify event
* has no window information. */ * has no window information. */
GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window); GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
if (window && XPending(m_display) >= 2) { if (window && XPending(display_) >= 2) {
XNextEvent(m_display, &xevent); XNextEvent(display_, &xevent);
if (xevent.type == KeymapNotify) { if (xevent.type == KeymapNotify) {
XEvent xev_next; XEvent xev_next;
/* check if KeyPress or KeyRelease event was generated /* check if KeyPress or KeyRelease event was generated
* in order to confirm the window is active. */ * in order to confirm the window is active. */
XPeekEvent(m_display, &xev_next); XPeekEvent(display_, &xev_next);
if (ELEM(xev_next.type, KeyPress, KeyRelease)) { if (ELEM(xev_next.type, KeyPress, KeyRelease)) {
const uint64_t event_ms = ms_from_input_time(xev_next.xkey.time); const uint64_t event_ms = ms_from_input_time(xev_next.xkey.time);
@@ -712,7 +712,7 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
}; };
for (int i = 0; i < int(ARRAY_SIZE(modifiers)); i++) { for (int i = 0; i < int(ARRAY_SIZE(modifiers)); i++) {
KeyCode kc = XKeysymToKeycode(m_display, modifiers[i]); KeyCode kc = XKeysymToKeycode(display_, modifiers[i]);
if (kc != 0 && ((xevent.xkeymap.key_vector[kc >> 3] >> (kc & 7)) & 1) != 0) { if (kc != 0 && ((xevent.xkeymap.key_vector[kc >> 3] >> (kc & 7)) & 1) != 0) {
pushEvent(new GHOST_EventKey(event_ms, pushEvent(new GHOST_EventKey(event_ms,
GHOST_kEventKeyDown, GHOST_kEventKeyDown,
@@ -734,7 +734,7 @@ bool GHOST_SystemX11::processEvents(bool waitForEvent)
} }
#ifdef WITH_INPUT_NDOF #ifdef WITH_INPUT_NDOF
if (static_cast<GHOST_NDOFManagerUnix *>(m_ndofManager)->processEvents()) { if (static_cast<GHOST_NDOFManagerUnix *>(ndof_manager_)->processEvents()) {
anyProcessed = true; anyProcessed = true;
} }
#endif #endif
@@ -801,12 +801,12 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
/* Set to true if this key will repeat. */ /* Set to true if this key will repeat. */
bool is_repeat_keycode = false; bool is_repeat_keycode = false;
if (m_xkb_descr != nullptr) { if (xkb_descr_ != nullptr) {
/* Use XKB support. */ /* Use XKB support. */
is_repeat_keycode = ( is_repeat_keycode = (
/* Should always be true, check just in case. */ /* Should always be true, check just in case. */
(xke->keycode < (XkbPerKeyBitArraySize << 3)) && (xke->keycode < (XkbPerKeyBitArraySize << 3)) &&
bit_is_on(m_xkb_descr->ctrls->per_key_repeat, xke->keycode)); bit_is_on(xkb_descr_->ctrls->per_key_repeat, xke->keycode));
} }
else { else {
/* No XKB support (filter by modifier). */ /* No XKB support (filter by modifier). */
@@ -834,30 +834,30 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
if (is_repeat_keycode) { if (is_repeat_keycode) {
if (xe->type == KeyPress) { if (xe->type == KeyPress) {
if (m_keycode_last_repeat_key == xke->keycode) { if (keycode_last_repeat_key_ == xke->keycode) {
is_repeat = true; is_repeat = true;
} }
m_keycode_last_repeat_key = xke->keycode; keycode_last_repeat_key_ = xke->keycode;
} }
else { else {
if (m_keycode_last_repeat_key == xke->keycode) { if (keycode_last_repeat_key_ == xke->keycode) {
m_keycode_last_repeat_key = uint(-1); keycode_last_repeat_key_ = uint(-1);
} }
} }
} }
} }
else if (xe->type == EnterNotify) { else if (xe->type == EnterNotify) {
/* We can't tell how the key state changed, clear it to avoid stuck keys. */ /* We can't tell how the key state changed, clear it to avoid stuck keys. */
m_keycode_last_repeat_key = uint(-1); keycode_last_repeat_key_ = uint(-1);
} }
#ifdef USE_XINPUT_HOTPLUG #ifdef USE_XINPUT_HOTPLUG
/* Hot-Plug support */ /* Hot-Plug support */
if (m_xinput_version.present) { if (xinput_version_.present) {
XEventClass class_presence; XEventClass class_presence;
int xi_presence; int xi_presence;
DevicePresence(m_display, xi_presence, class_presence); DevicePresence(display_, xi_presence, class_presence);
(void)class_presence; (void)class_presence;
if (xe->type == xi_presence) { if (xe->type == xi_presence) {
@@ -868,7 +868,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
/* update all window events */ /* update all window events */
{ {
const vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end(); vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
@@ -895,7 +895,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
if (window->GetTabletData().Active != GHOST_kTabletModeNone) { if (window->GetTabletData().Active != GHOST_kTabletModeNone) {
bool any_proximity = false; bool any_proximity = false;
for (const GHOST_TabletX11 &xtablet : m_xtablets) { for (const GHOST_TabletX11 &xtablet : xtablets_) {
if (checkTabletProximity(xe->xany.display, xtablet.Device)) { if (checkTabletProximity(xe->xany.display, xtablet.Device)) {
any_proximity = true; any_proximity = true;
} }
@@ -947,14 +947,14 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
const int32_t subregion_div = 4; /* One quarter of the region. */ const int32_t subregion_div = 4; /* One quarter of the region. */
const int32_t size[2] = {bounds.getWidth(), bounds.getHeight()}; const int32_t size[2] = {bounds.getWidth(), bounds.getHeight()};
const int32_t center[2] = { const int32_t center[2] = {
(bounds.m_l + bounds.m_r) / 2, (bounds.l_ + bounds.r_) / 2,
(bounds.m_t + bounds.m_b) / 2, (bounds.t_ + bounds.b_) / 2,
}; };
/* Shrink the box to prevent the cursor escaping. */ /* Shrink the box to prevent the cursor escaping. */
bounds.m_l = center[0] - (size[0] / (subregion_div * 2)); bounds.l_ = center[0] - (size[0] / (subregion_div * 2));
bounds.m_r = center[0] + (size[0] / (subregion_div * 2)); bounds.r_ = center[0] + (size[0] / (subregion_div * 2));
bounds.m_t = center[1] - (size[1] / (subregion_div * 2)); bounds.t_ = center[1] - (size[1] / (subregion_div * 2));
bounds.m_b = center[1] + (size[1] / (subregion_div * 2)); bounds.b_ = center[1] + (size[1] / (subregion_div * 2));
bounds_margin = 0; bounds_margin = 0;
bounds_axis = GHOST_TAxisFlag(GHOST_kAxisX | GHOST_kAxisY); bounds_axis = GHOST_TAxisFlag(GHOST_kAxisX | GHOST_kAxisY);
} }
@@ -983,13 +983,13 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
* We also have to add a few extra milliseconds of 'padding', as sometimes we get two * We also have to add a few extra milliseconds of 'padding', as sometimes we get two
* close events that will generate extra wrap on the same axis within those few * close events that will generate extra wrap on the same axis within those few
* milliseconds. */ * milliseconds. */
if (x_new != xme.x_root && xme.time > m_last_warp_x) { if (x_new != xme.x_root && xme.time > last_warp_x_) {
x_accum += (xme.x_root - x_new); x_accum += (xme.x_root - x_new);
m_last_warp_x = lastEventTime(xme.time) + 25; last_warp_x_ = lastEventTime(xme.time) + 25;
} }
if (y_new != xme.y_root && xme.time > m_last_warp_y) { if (y_new != xme.y_root && xme.time > last_warp_y_) {
y_accum += (xme.y_root - y_new); y_accum += (xme.y_root - y_new);
m_last_warp_y = lastEventTime(xme.time) + 25; last_warp_y_ = lastEventTime(xme.time) + 25;
} }
window->setCursorGrabAccum(x_accum, y_accum); window->setCursorGrabAccum(x_accum, y_accum);
/* When wrapping we don't need to add an event because the /* When wrapping we don't need to add an event because the
@@ -1021,7 +1021,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
XKeyEvent *xke = &(xe->xkey); XKeyEvent *xke = &(xe->xkey);
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
/* Can be zero for XIM generated events. */ /* Can be zero for XIM generated events. */
const Time time = xke->time ? xke->time : m_last_key_time; const Time time = xke->time ? xke->time : last_key_time_;
#else #else
const Time time = xke->time; const Time time = xke->time;
#endif #endif
@@ -1093,7 +1093,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
/* Only allow a limited set of keys from XLookupKeysym, /* Only allow a limited set of keys from XLookupKeysym,
* all others we take from XLookupString, unless it gives unknown key... */ * all others we take from XLookupString, unless it gives unknown key... */
gkey = ghost_key_from_keysym_or_keycode(key_sym, m_xkb_descr, xke->keycode); gkey = ghost_key_from_keysym_or_keycode(key_sym, xkb_descr_, xke->keycode);
switch (gkey) { switch (gkey) {
case GHOST_kKeyRightAlt: case GHOST_kKeyRightAlt:
case GHOST_kKeyLeftAlt: case GHOST_kKeyLeftAlt:
@@ -1159,7 +1159,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
key_sym = XLookupKeysym(xke, 0); key_sym = XLookupKeysym(xke, 0);
} }
gkey = ghost_key_from_keysym_or_keycode(key_sym, m_xkb_descr, xke->keycode); gkey = ghost_key_from_keysym_or_keycode(key_sym, xkb_descr_, xke->keycode);
if (!XLookupString(xke, &ascii, 1, nullptr, nullptr)) { if (!XLookupString(xke, &ascii, 1, nullptr, nullptr)) {
ascii = '\0'; ascii = '\0';
@@ -1209,7 +1209,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
status == XLookupKeySym ? "XLookupKeySym" : status == XLookupKeySym ? "XLookupKeySym" :
"Unknown status")); "Unknown status"));
printf("'%.*s' %p %p\n", len, utf8_buf, xic, m_xim); printf("'%.*s' %p %p\n", len, utf8_buf, xic, xim_);
} }
} }
else { else {
@@ -1356,10 +1356,10 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
case ClientMessage: { case ClientMessage: {
XClientMessageEvent &xcme = xe->xclient; XClientMessageEvent &xcme = xe->xclient;
if (((Atom)xcme.data.l[0]) == m_atom.WM_DELETE_WINDOW) { if (((Atom)xcme.data.l[0]) == atom_.WM_DELETE_WINDOW) {
g_event = new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window); g_event = new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window);
} }
else if (((Atom)xcme.data.l[0]) == m_atom.WM_TAKE_FOCUS) { else if (((Atom)xcme.data.l[0]) == atom_.WM_TAKE_FOCUS) {
XWindowAttributes attr; XWindowAttributes attr;
Window fwin; Window fwin;
int revert_to; int revert_to;
@@ -1374,11 +1374,11 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
* to be sure that our windows is mapped * to be sure that our windows is mapped
* or this call fail and close blender. * or this call fail and close blender.
*/ */
if (XGetWindowAttributes(m_display, xcme.window, &attr) == True) { if (XGetWindowAttributes(display_, xcme.window, &attr) == True) {
if (XGetInputFocus(m_display, &fwin, &revert_to) == True) { if (XGetInputFocus(display_, &fwin, &revert_to) == True) {
if (attr.map_state == IsViewable) { if (attr.map_state == IsViewable) {
if (fwin != xcme.window) { if (fwin != xcme.window) {
XSetInputFocus(m_display, xcme.window, RevertToParent, xcme.data.l[1]); XSetInputFocus(display_, xcme.window, RevertToParent, xcme.data.l[1]);
} }
} }
} }
@@ -1432,10 +1432,10 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
#endif #endif
if (xce.type == EnterNotify) { if (xce.type == EnterNotify) {
m_windowManager->setActiveWindow(window); window_manager_->setActiveWindow(window);
} }
else { else {
m_windowManager->setWindowInactive(window); window_manager_->setWindowInactive(window);
} }
break; break;
@@ -1450,13 +1450,13 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
* state, and receipt of an #UnmapNotify event will * state, and receipt of an #UnmapNotify event will
* indicate a transition to the Iconic state. ] * indicate a transition to the Iconic state. ]
*/ */
if (window->m_post_init == True) { if (window->post_init_ == True) {
/* /*
* Now we are sure that the window is * Now we are sure that the window is
* mapped, so only need change the state. * mapped, so only need change the state.
*/ */
window->setState(window->m_post_state); window->setState(window->post_state_);
window->m_post_init = False; window->post_init_ = False;
} }
break; break;
case UnmapNotify: case UnmapNotify:
@@ -1482,14 +1482,10 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
nxe.xselection.time = xse->time; nxe.xselection.time = xse->time;
/* Check to see if the requester is asking for String */ /* Check to see if the requester is asking for String */
if (ELEM(xse->target, if (ELEM(xse->target, atom_.UTF8_STRING, atom_.STRING, atom_.COMPOUND_TEXT, atom_.C_STRING))
m_atom.UTF8_STRING,
m_atom.STRING,
m_atom.COMPOUND_TEXT,
m_atom.C_STRING))
{ {
if (xse->selection == XInternAtom(m_display, "PRIMARY", False)) { if (xse->selection == XInternAtom(display_, "PRIMARY", False)) {
XChangeProperty(m_display, XChangeProperty(display_,
xse->requestor, xse->requestor,
xse->property, xse->property,
xse->target, xse->target,
@@ -1498,8 +1494,8 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
(uchar *)txt_select_buffer, (uchar *)txt_select_buffer,
strlen(txt_select_buffer)); strlen(txt_select_buffer));
} }
else if (xse->selection == XInternAtom(m_display, "CLIPBOARD", False)) { else if (xse->selection == XInternAtom(display_, "CLIPBOARD", False)) {
XChangeProperty(m_display, XChangeProperty(display_,
xse->requestor, xse->requestor,
xse->property, xse->property,
xse->target, xse->target,
@@ -1509,13 +1505,10 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
strlen(txt_cut_buffer)); strlen(txt_cut_buffer));
} }
} }
else if (xse->target == m_atom.TARGETS) { else if (xse->target == atom_.TARGETS) {
const Atom atom_list[] = {m_atom.TARGETS, const Atom atom_list[] = {
m_atom.UTF8_STRING, atom_.TARGETS, atom_.UTF8_STRING, atom_.STRING, atom_.COMPOUND_TEXT, atom_.C_STRING};
m_atom.STRING, XChangeProperty(display_,
m_atom.COMPOUND_TEXT,
m_atom.C_STRING};
XChangeProperty(m_display,
xse->requestor, xse->requestor,
xse->property, xse->property,
XA_ATOM, XA_ATOM,
@@ -1523,7 +1516,7 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
PropModeReplace, PropModeReplace,
reinterpret_cast<const uchar *>(atom_list), reinterpret_cast<const uchar *>(atom_list),
ARRAY_SIZE(atom_list)); ARRAY_SIZE(atom_list));
XFlush(m_display); XFlush(display_);
} }
else { else {
/* Change property to None because we do not support the selection request target. */ /* Change property to None because we do not support the selection request target. */
@@ -1531,14 +1524,14 @@ void GHOST_SystemX11::processEvent(XEvent *xe)
} }
/* Send the event to the client 0 0 == False, #SelectionNotify */ /* Send the event to the client 0 0 == False, #SelectionNotify */
XSendEvent(m_display, xse->requestor, 0, 0, &nxe); XSendEvent(display_, xse->requestor, 0, 0, &nxe);
XFlush(m_display); XFlush(display_);
break; break;
} }
default: { default: {
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
for (GHOST_TabletX11 &xtablet : m_xtablets) { for (GHOST_TabletX11 &xtablet : xtablets_) {
if (ELEM(xe->type, xtablet.MotionEvent, xtablet.PressEvent)) { if (ELEM(xe->type, xtablet.MotionEvent, xtablet.PressEvent)) {
const XDeviceMotionEvent *data = (const XDeviceMotionEvent *)xe; const XDeviceMotionEvent *data = (const XDeviceMotionEvent *)xe;
if (data->deviceid != xtablet.ID) { if (data->deviceid != xtablet.ID) {
@@ -1626,20 +1619,14 @@ GHOST_TSuccess GHOST_SystemX11::getPixelAtCursor(float r_color[3]) const
if (getCursorPosition(x, y) == GHOST_kFailure) { if (getCursorPosition(x, y) == GHOST_kFailure) {
return GHOST_kFailure; return GHOST_kFailure;
} }
XImage *image = XGetImage(m_display, XImage *image = XGetImage(
XRootWindow(m_display, XDefaultScreen(m_display)), display_, XRootWindow(display_, XDefaultScreen(display_)), x, y, 1, 1, AllPlanes, XYPixmap);
x,
y,
1,
1,
AllPlanes,
XYPixmap);
if (image == nullptr) { if (image == nullptr) {
return GHOST_kFailure; return GHOST_kFailure;
} }
c.pixel = XGetPixel(image, 0, 0); c.pixel = XGetPixel(image, 0, 0);
XFree(image); XFree(image);
XQueryColor(m_display, XDefaultColormap(m_display, XDefaultScreen(m_display)), &c); XQueryColor(display_, XDefaultColormap(display_, XDefaultScreen(display_)), &c);
/* X11 returns colors in the [0, 65535] range, so we need to scale back to [0, 1]. */ /* X11 returns colors in the [0, 65535] range, so we need to scale back to [0, 1]. */
r_color[0] = c.red / 65535.0f; r_color[0] = c.red / 65535.0f;
@@ -1653,46 +1640,45 @@ GHOST_TSuccess GHOST_SystemX11::getModifierKeys(GHOST_ModifierKeys &keys) const
/* Analyze the masks returned from #XQueryPointer. */ /* Analyze the masks returned from #XQueryPointer. */
memset((void *)m_keyboard_vector, 0, sizeof(m_keyboard_vector)); memset((void *)keyboard_vector_, 0, sizeof(keyboard_vector_));
XQueryKeymap(m_display, (char *)m_keyboard_vector); XQueryKeymap(display_, (char *)keyboard_vector_);
/* Now translate key symbols into key-codes and test with vector. */ /* Now translate key symbols into key-codes and test with vector. */
const static KeyCode shift_l = XKeysymToKeycode(m_display, XK_Shift_L); const static KeyCode shift_l = XKeysymToKeycode(display_, XK_Shift_L);
const static KeyCode shift_r = XKeysymToKeycode(m_display, XK_Shift_R); const static KeyCode shift_r = XKeysymToKeycode(display_, XK_Shift_R);
const static KeyCode control_l = XKeysymToKeycode(m_display, XK_Control_L); const static KeyCode control_l = XKeysymToKeycode(display_, XK_Control_L);
const static KeyCode control_r = XKeysymToKeycode(m_display, XK_Control_R); const static KeyCode control_r = XKeysymToKeycode(display_, XK_Control_R);
const static KeyCode alt_l = XKeysymToKeycode(m_display, XK_Alt_L); const static KeyCode alt_l = XKeysymToKeycode(display_, XK_Alt_L);
const static KeyCode alt_r = XKeysymToKeycode(m_display, XK_Alt_R); const static KeyCode alt_r = XKeysymToKeycode(display_, XK_Alt_R);
const static KeyCode super_l = XKeysymToKeycode(m_display, XK_Super_L); const static KeyCode super_l = XKeysymToKeycode(display_, XK_Super_L);
const static KeyCode super_r = XKeysymToKeycode(m_display, XK_Super_R); const static KeyCode super_r = XKeysymToKeycode(display_, XK_Super_R);
const static KeyCode hyper_l = XKeysymToKeycode(m_display, XK_Hyper_L); const static KeyCode hyper_l = XKeysymToKeycode(display_, XK_Hyper_L);
const static KeyCode hyper_r = XKeysymToKeycode(m_display, XK_Hyper_R); const static KeyCode hyper_r = XKeysymToKeycode(display_, XK_Hyper_R);
/* shift */ /* shift */
keys.set(GHOST_kModifierKeyLeftShift, keys.set(GHOST_kModifierKeyLeftShift,
((m_keyboard_vector[shift_l >> 3] >> (shift_l & 7)) & 1) != 0); ((keyboard_vector_[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightShift, keys.set(GHOST_kModifierKeyRightShift,
((m_keyboard_vector[shift_r >> 3] >> (shift_r & 7)) & 1) != 0); ((keyboard_vector_[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
/* control */ /* control */
keys.set(GHOST_kModifierKeyLeftControl, keys.set(GHOST_kModifierKeyLeftControl,
((m_keyboard_vector[control_l >> 3] >> (control_l & 7)) & 1) != 0); ((keyboard_vector_[control_l >> 3] >> (control_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightControl, keys.set(GHOST_kModifierKeyRightControl,
((m_keyboard_vector[control_r >> 3] >> (control_r & 7)) & 1) != 0); ((keyboard_vector_[control_r >> 3] >> (control_r & 7)) & 1) != 0);
/* alt */ /* alt */
keys.set(GHOST_kModifierKeyLeftAlt, ((m_keyboard_vector[alt_l >> 3] >> (alt_l & 7)) & 1) != 0); keys.set(GHOST_kModifierKeyLeftAlt, ((keyboard_vector_[alt_l >> 3] >> (alt_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightAlt, ((m_keyboard_vector[alt_r >> 3] >> (alt_r & 7)) & 1) != 0); keys.set(GHOST_kModifierKeyRightAlt, ((keyboard_vector_[alt_r >> 3] >> (alt_r & 7)) & 1) != 0);
/* super (windows) - only one GHOST-kModifierKeyOS, so mapping to either */ /* super (windows) - only one GHOST-kModifierKeyOS, so mapping to either */
keys.set(GHOST_kModifierKeyLeftOS, keys.set(GHOST_kModifierKeyLeftOS, ((keyboard_vector_[super_l >> 3] >> (super_l & 7)) & 1) != 0);
((m_keyboard_vector[super_l >> 3] >> (super_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightOS, keys.set(GHOST_kModifierKeyRightOS,
((m_keyboard_vector[super_r >> 3] >> (super_r & 7)) & 1) != 0); ((keyboard_vector_[super_r >> 3] >> (super_r & 7)) & 1) != 0);
/* hyper */ /* hyper */
keys.set(GHOST_kModifierKeyLeftHyper, keys.set(GHOST_kModifierKeyLeftHyper,
((m_keyboard_vector[hyper_l >> 3] >> (hyper_l & 7)) & 1) != 0); ((keyboard_vector_[hyper_l >> 3] >> (hyper_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightHyper, keys.set(GHOST_kModifierKeyRightHyper,
((m_keyboard_vector[hyper_r >> 3] >> (hyper_r & 7)) & 1) != 0); ((keyboard_vector_[hyper_r >> 3] >> (hyper_r & 7)) & 1) != 0);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1703,8 +1689,8 @@ GHOST_TSuccess GHOST_SystemX11::getButtons(GHOST_Buttons &buttons) const
int rx, ry, wx, wy; int rx, ry, wx, wy;
uint mask_return; uint mask_return;
if (XQueryPointer(m_display, if (XQueryPointer(display_,
RootWindow(m_display, DefaultScreen(m_display)), RootWindow(display_, DefaultScreen(display_)),
&root_return, &root_return,
&child_return, &child_return,
&rx, &rx,
@@ -1757,7 +1743,7 @@ static GHOST_TSuccess getCursorPosition_impl(Display *display,
GHOST_TSuccess GHOST_SystemX11::getCursorPosition(int32_t &x, int32_t &y) const GHOST_TSuccess GHOST_SystemX11::getCursorPosition(int32_t &x, int32_t &y) const
{ {
Window child_return; Window child_return;
return getCursorPosition_impl(m_display, x, y, &child_return); return getCursorPosition_impl(display_, x, y, &child_return);
} }
GHOST_TSuccess GHOST_SystemX11::setCursorPosition(int32_t x, int32_t y) GHOST_TSuccess GHOST_SystemX11::setCursorPosition(int32_t x, int32_t y)
@@ -1771,7 +1757,7 @@ GHOST_TSuccess GHOST_SystemX11::setCursorPosition(int32_t x, int32_t y)
#ifdef WITH_XWAYLAND_HACK #ifdef WITH_XWAYLAND_HACK
Window child_return = None; Window child_return = None;
if (getCursorPosition_impl(m_display, cx, cy, &child_return) == GHOST_kFailure) { if (getCursorPosition_impl(display_, cx, cy, &child_return) == GHOST_kFailure) {
return GHOST_kFailure; return GHOST_kFailure;
} }
#else #else
@@ -1786,34 +1772,34 @@ GHOST_TSuccess GHOST_SystemX11::setCursorPosition(int32_t x, int32_t y)
#ifdef WITH_XWAYLAND_HACK #ifdef WITH_XWAYLAND_HACK
if (use_xwayland_hack) { if (use_xwayland_hack) {
if (child_return != None) { if (child_return != None) {
XFixesHideCursor(m_display, child_return); XFixesHideCursor(display_, child_return);
} }
} }
#endif #endif
#if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP) #if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP)
if ((m_xinput_version.present) && (m_xinput_version.major_version >= 2)) { if ((xinput_version_.present) && (xinput_version_.major_version >= 2)) {
/* Needed to account for XInput "Coordinate Transformation Matrix", see #48901 */ /* Needed to account for XInput "Coordinate Transformation Matrix", see #48901 */
int device_id; int device_id;
if (XIGetClientPointer(m_display, None, &device_id) != False) { if (XIGetClientPointer(display_, None, &device_id) != False) {
XIWarpPointer(m_display, device_id, None, None, 0, 0, 0, 0, relx, rely); XIWarpPointer(display_, device_id, None, None, 0, 0, 0, 0, relx, rely);
} }
} }
else else
#endif #endif
{ {
XWarpPointer(m_display, None, None, 0, 0, 0, 0, relx, rely); XWarpPointer(display_, None, None, 0, 0, 0, 0, relx, rely);
} }
#ifdef WITH_XWAYLAND_HACK #ifdef WITH_XWAYLAND_HACK
if (use_xwayland_hack) { if (use_xwayland_hack) {
if (child_return != None) { if (child_return != None) {
XFixesShowCursor(m_display, child_return); XFixesShowCursor(display_, child_return);
} }
} }
#endif #endif
XSync(m_display, 0); /* Sync to process all requests */ XSync(display_, 0); /* Sync to process all requests */
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1840,13 +1826,13 @@ void GHOST_SystemX11::addDirtyWindow(GHOST_WindowX11 *bad_wind)
{ {
GHOST_ASSERT((bad_wind != nullptr), "addDirtyWindow() nullptr ptr trapped (window)"); GHOST_ASSERT((bad_wind != nullptr), "addDirtyWindow() nullptr ptr trapped (window)");
m_dirty_windows.push_back(bad_wind); dirty_windows_.push_back(bad_wind);
} }
bool GHOST_SystemX11::generateWindowExposeEvents() bool GHOST_SystemX11::generateWindowExposeEvents()
{ {
vector<GHOST_WindowX11 *>::const_iterator w_start = m_dirty_windows.begin(); vector<GHOST_WindowX11 *>::const_iterator w_start = dirty_windows_.begin();
vector<GHOST_WindowX11 *>::const_iterator w_end = m_dirty_windows.end(); vector<GHOST_WindowX11 *>::const_iterator w_end = dirty_windows_.end();
bool anyProcessed = false; bool anyProcessed = false;
for (; w_start != w_end; ++w_start) { for (; w_start != w_end; ++w_start) {
@@ -1861,7 +1847,7 @@ bool GHOST_SystemX11::generateWindowExposeEvents()
} }
} }
m_dirty_windows.clear(); dirty_windows_.clear();
return anyProcessed; return anyProcessed;
} }
@@ -2056,7 +2042,7 @@ void GHOST_SystemX11::getClipboard_xcout(
ulong pty_size, pty_items; ulong pty_size, pty_items;
uchar *ltxt = *txt; uchar *ltxt = *txt;
const vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it); GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
Window win = window->getXWindow(); Window win = window->getXWindow();
@@ -2071,7 +2057,7 @@ void GHOST_SystemX11::getClipboard_xcout(
} }
/* Send a selection request */ /* Send a selection request */
XConvertSelection(m_display, sel, target, m_atom.XCLIP_OUT, win, CurrentTime); XConvertSelection(display_, sel, target, atom_.XCLIP_OUT, win, CurrentTime);
*context = XCLIB_XCOUT_SENTCONVSEL; *context = XCLIB_XCOUT_SENTCONVSEL;
return; return;
@@ -2080,23 +2066,23 @@ void GHOST_SystemX11::getClipboard_xcout(
return; return;
} }
if (target == m_atom.UTF8_STRING && evt->xselection.property == None) { if (target == atom_.UTF8_STRING && evt->xselection.property == None) {
*context = XCLIB_XCOUT_FALLBACK_UTF8; *context = XCLIB_XCOUT_FALLBACK_UTF8;
return; return;
} }
if (target == m_atom.COMPOUND_TEXT && evt->xselection.property == None) { if (target == atom_.COMPOUND_TEXT && evt->xselection.property == None) {
*context = XCLIB_XCOUT_FALLBACK_COMP; *context = XCLIB_XCOUT_FALLBACK_COMP;
return; return;
} }
if (target == m_atom.TEXT && evt->xselection.property == None) { if (target == atom_.TEXT && evt->xselection.property == None) {
*context = XCLIB_XCOUT_FALLBACK_TEXT; *context = XCLIB_XCOUT_FALLBACK_TEXT;
return; return;
} }
/* find the size and format of the data in property */ /* find the size and format of the data in property */
XGetWindowProperty(m_display, XGetWindowProperty(display_,
win, win,
m_atom.XCLIP_OUT, atom_.XCLIP_OUT,
0, 0,
0, 0,
False, False,
@@ -2108,10 +2094,10 @@ void GHOST_SystemX11::getClipboard_xcout(
&buffer); &buffer);
XFree(buffer); XFree(buffer);
if (pty_type == m_atom.INCR) { if (pty_type == atom_.INCR) {
/* start INCR mechanism by deleting property */ /* start INCR mechanism by deleting property */
XDeleteProperty(m_display, win, m_atom.XCLIP_OUT); XDeleteProperty(display_, win, atom_.XCLIP_OUT);
XFlush(m_display); XFlush(display_);
*context = XCLIB_XCOUT_INCR; *context = XCLIB_XCOUT_INCR;
return; return;
} }
@@ -2125,9 +2111,9 @@ void GHOST_SystemX11::getClipboard_xcout(
} }
/* Not using INCR mechanism, just read the property. */ /* Not using INCR mechanism, just read the property. */
XGetWindowProperty(m_display, XGetWindowProperty(display_,
win, win,
m_atom.XCLIP_OUT, atom_.XCLIP_OUT,
0, 0,
long(pty_size), long(pty_size),
False, False,
@@ -2139,7 +2125,7 @@ void GHOST_SystemX11::getClipboard_xcout(
&buffer); &buffer);
/* finished with property, delete it */ /* finished with property, delete it */
XDeleteProperty(m_display, win, m_atom.XCLIP_OUT); XDeleteProperty(display_, win, atom_.XCLIP_OUT);
/* copy the buffer to the pointer for returned data */ /* copy the buffer to the pointer for returned data */
ltxt = (uchar *)malloc(pty_items); ltxt = (uchar *)malloc(pty_items);
@@ -2174,9 +2160,9 @@ void GHOST_SystemX11::getClipboard_xcout(
} }
/* check size and format of the property */ /* check size and format of the property */
XGetWindowProperty(m_display, XGetWindowProperty(display_,
win, win,
m_atom.XCLIP_OUT, atom_.XCLIP_OUT,
0, 0,
0, 0,
False, False,
@@ -2192,14 +2178,14 @@ void GHOST_SystemX11::getClipboard_xcout(
* to tell the other X client that we have read * to tell the other X client that we have read
* it and to send the next property */ * it and to send the next property */
XFree(buffer); XFree(buffer);
XDeleteProperty(m_display, win, m_atom.XCLIP_OUT); XDeleteProperty(display_, win, atom_.XCLIP_OUT);
return; return;
} }
if (pty_size == 0) { if (pty_size == 0) {
/* no more data, exit from loop */ /* no more data, exit from loop */
XFree(buffer); XFree(buffer);
XDeleteProperty(m_display, win, m_atom.XCLIP_OUT); XDeleteProperty(display_, win, atom_.XCLIP_OUT);
*context = XCLIB_XCOUT_NONE; *context = XCLIB_XCOUT_NONE;
/* this means that an INCR transfer is now /* this means that an INCR transfer is now
@@ -2211,9 +2197,9 @@ void GHOST_SystemX11::getClipboard_xcout(
/* if we have come this far, the property contains /* if we have come this far, the property contains
* text, we know the size. */ * text, we know the size. */
XGetWindowProperty(m_display, XGetWindowProperty(display_,
win, win,
m_atom.XCLIP_OUT, atom_.XCLIP_OUT,
0, 0,
long(pty_size), long(pty_size),
False, False,
@@ -2241,8 +2227,8 @@ void GHOST_SystemX11::getClipboard_xcout(
XFree(buffer); XFree(buffer);
/* delete property to get the next item */ /* delete property to get the next item */
XDeleteProperty(m_display, win, m_atom.XCLIP_OUT); XDeleteProperty(display_, win, atom_.XCLIP_OUT);
XFlush(m_display); XFlush(display_);
return; return;
} }
} }
@@ -2250,7 +2236,7 @@ void GHOST_SystemX11::getClipboard_xcout(
char *GHOST_SystemX11::getClipboard(bool selection) const char *GHOST_SystemX11::getClipboard(bool selection) const
{ {
Atom sseln; Atom sseln;
Atom target = m_atom.UTF8_STRING; Atom target = atom_.UTF8_STRING;
Window owner; Window owner;
/* From `xclip.c` `doOut()` v0.11. */ /* From `xclip.c` `doOut()` v0.11. */
@@ -2260,21 +2246,21 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
uint context = XCLIB_XCOUT_NONE; uint context = XCLIB_XCOUT_NONE;
if (selection == True) { if (selection == True) {
sseln = m_atom.PRIMARY; sseln = atom_.PRIMARY;
} }
else { else {
sseln = m_atom.CLIPBOARD; sseln = atom_.CLIPBOARD;
} }
const vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it); GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
Window win = window->getXWindow(); Window win = window->getXWindow();
/* check if we are the owner. */ /* check if we are the owner. */
owner = XGetSelectionOwner(m_display, sseln); owner = XGetSelectionOwner(display_, sseln);
if (owner == win) { if (owner == win) {
if (sseln == m_atom.CLIPBOARD) { if (sseln == atom_.CLIPBOARD) {
size_t sel_buf_size = strlen(txt_cut_buffer) + 1; size_t sel_buf_size = strlen(txt_cut_buffer) + 1;
sel_buf = (char *)malloc(sel_buf_size); sel_buf = (char *)malloc(sel_buf_size);
memcpy(sel_buf, txt_cut_buffer, sel_buf_size); memcpy(sel_buf, txt_cut_buffer, sel_buf_size);
@@ -2296,7 +2282,7 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
/* only get an event if xcout() is doing something */ /* only get an event if xcout() is doing something */
bool restore_this_event = false; bool restore_this_event = false;
if (context != XCLIB_XCOUT_NONE) { if (context != XCLIB_XCOUT_NONE) {
XNextEvent(m_display, &evt); XNextEvent(display_, &evt);
restore_this_event = (evt.type != SelectionNotify); restore_this_event = (evt.type != SelectionNotify);
} }
@@ -2310,19 +2296,19 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
/* Fallback is needed. Set #XA_STRING to target and restart the loop. */ /* Fallback is needed. Set #XA_STRING to target and restart the loop. */
if (context == XCLIB_XCOUT_FALLBACK) { if (context == XCLIB_XCOUT_FALLBACK) {
context = XCLIB_XCOUT_NONE; context = XCLIB_XCOUT_NONE;
target = m_atom.STRING; target = atom_.STRING;
continue; continue;
} }
if (context == XCLIB_XCOUT_FALLBACK_UTF8) { if (context == XCLIB_XCOUT_FALLBACK_UTF8) {
/* utf8 fail, move to compound text. */ /* utf8 fail, move to compound text. */
context = XCLIB_XCOUT_NONE; context = XCLIB_XCOUT_NONE;
target = m_atom.COMPOUND_TEXT; target = atom_.COMPOUND_TEXT;
continue; continue;
} }
if (context == XCLIB_XCOUT_FALLBACK_COMP) { if (context == XCLIB_XCOUT_FALLBACK_COMP) {
/* Compound text fail, move to text. */ /* Compound text fail, move to text. */
context = XCLIB_XCOUT_NONE; context = XCLIB_XCOUT_NONE;
target = m_atom.TEXT; target = atom_.TEXT;
continue; continue;
} }
if (context == XCLIB_XCOUT_FALLBACK_TEXT) { if (context == XCLIB_XCOUT_FALLBACK_TEXT) {
@@ -2337,7 +2323,7 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
} }
while (!restore_events.empty()) { while (!restore_events.empty()) {
XPutBackEvent(m_display, &restore_events.back()); XPutBackEvent(display_, &restore_events.back());
restore_events.pop_back(); restore_events.pop_back();
} }
@@ -2347,7 +2333,7 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
memcpy(tmp_data, (char *)sel_buf, sel_len); memcpy(tmp_data, (char *)sel_buf, sel_len);
tmp_data[sel_len] = '\0'; tmp_data[sel_len] = '\0';
if (sseln == m_atom.STRING) { if (sseln == atom_.STRING) {
XFree(sel_buf); XFree(sel_buf);
} }
else { else {
@@ -2361,17 +2347,17 @@ char *GHOST_SystemX11::getClipboard(bool selection) const
void GHOST_SystemX11::putClipboard(const char *buffer, bool selection) const void GHOST_SystemX11::putClipboard(const char *buffer, bool selection) const
{ {
Window m_window, owner; Window window_, owner;
const vector<GHOST_IWindow *> &win_vec = m_windowManager->getWindows(); const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin(); vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it); GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
m_window = window->getXWindow(); window_ = window->getXWindow();
if (buffer) { if (buffer) {
if (selection == False) { if (selection == False) {
XSetSelectionOwner(m_display, m_atom.CLIPBOARD, m_window, CurrentTime); XSetSelectionOwner(display_, atom_.CLIPBOARD, window_, CurrentTime);
owner = XGetSelectionOwner(m_display, m_atom.CLIPBOARD); owner = XGetSelectionOwner(display_, atom_.CLIPBOARD);
if (txt_cut_buffer) { if (txt_cut_buffer) {
free((void *)txt_cut_buffer); free((void *)txt_cut_buffer);
} }
@@ -2381,8 +2367,8 @@ void GHOST_SystemX11::putClipboard(const char *buffer, bool selection) const
memcpy(txt_cut_buffer, buffer, buffer_size); memcpy(txt_cut_buffer, buffer, buffer_size);
} }
else { else {
XSetSelectionOwner(m_display, m_atom.PRIMARY, m_window, CurrentTime); XSetSelectionOwner(display_, atom_.PRIMARY, window_, CurrentTime);
owner = XGetSelectionOwner(m_display, m_atom.PRIMARY); owner = XGetSelectionOwner(display_, atom_.PRIMARY);
if (txt_select_buffer) { if (txt_select_buffer) {
free((void *)txt_select_buffer); free((void *)txt_select_buffer);
} }
@@ -2392,7 +2378,7 @@ void GHOST_SystemX11::putClipboard(const char *buffer, bool selection) const
memcpy(txt_select_buffer, buffer, buffer_size); memcpy(txt_select_buffer, buffer, buffer_size);
} }
if (owner != m_window) { if (owner != window_) {
fprintf(stderr, "failed to own primary\n"); fprintf(stderr, "failed to own primary\n");
} }
} }
@@ -2520,34 +2506,34 @@ GHOST_TSuccess GHOST_SystemX11::showMessageBox(const char *title,
Window window; Window window;
XEvent e; XEvent e;
int screen = DefaultScreen(m_display); int screen = DefaultScreen(display_);
window = XCreateSimpleWindow(m_display, window = XCreateSimpleWindow(display_,
RootWindow(m_display, screen), RootWindow(display_, screen),
0, 0,
0, 0,
dialog_data.width, dialog_data.width,
dialog_data.height, dialog_data.height,
1, 1,
BlackPixel(m_display, screen), BlackPixel(display_, screen),
WhitePixel(m_display, screen)); WhitePixel(display_, screen));
/* Window Should not be resizable */ /* Window Should not be resizable */
{ {
hints.flags = PSize | PMinSize | PMaxSize; hints.flags = PSize | PMinSize | PMaxSize;
hints.min_width = hints.max_width = hints.base_width = dialog_data.width; hints.min_width = hints.max_width = hints.base_width = dialog_data.width;
hints.min_height = hints.max_height = hints.base_height = dialog_data.height; hints.min_height = hints.max_height = hints.base_height = dialog_data.height;
XSetWMNormalHints(m_display, window, &hints); XSetWMNormalHints(display_, window, &hints);
} }
/* Set title */ /* Set title */
{ {
Atom wm_Name = XInternAtom(m_display, "_NET_WM_NAME", False); Atom wm_Name = XInternAtom(display_, "_NET_WM_NAME", False);
Atom utf8Str = XInternAtom(m_display, "UTF8_STRING", False); Atom utf8Str = XInternAtom(display_, "UTF8_STRING", False);
Atom winType = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE", False); Atom winType = XInternAtom(display_, "_NET_WM_WINDOW_TYPE", False);
Atom typeDialog = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE_DIALOG", False); Atom typeDialog = XInternAtom(display_, "_NET_WM_WINDOW_TYPE_DIALOG", False);
XChangeProperty(m_display, XChangeProperty(display_,
window, window,
wm_Name, wm_Name,
utf8Str, utf8Str,
@@ -2557,40 +2543,40 @@ GHOST_TSuccess GHOST_SystemX11::showMessageBox(const char *title,
int(strlen(title))); int(strlen(title)));
XChangeProperty( XChangeProperty(
m_display, window, winType, XA_ATOM, 32, PropModeReplace, (uchar *)&typeDialog, 1); display_, window, winType, XA_ATOM, 32, PropModeReplace, (uchar *)&typeDialog, 1);
} }
/* Create buttons GC */ /* Create buttons GC */
XGCValues buttonBorderGCValues; XGCValues buttonBorderGCValues;
buttonBorderGCValues.foreground = BlackPixel(m_display, screen); buttonBorderGCValues.foreground = BlackPixel(display_, screen);
buttonBorderGCValues.background = WhitePixel(m_display, screen); buttonBorderGCValues.background = WhitePixel(display_, screen);
XGCValues buttonGCValues; XGCValues buttonGCValues;
buttonGCValues.foreground = WhitePixel(m_display, screen); buttonGCValues.foreground = WhitePixel(display_, screen);
buttonGCValues.background = BlackPixel(m_display, screen); buttonGCValues.background = BlackPixel(display_, screen);
GC buttonBorderGC = XCreateGC(m_display, window, GCForeground, &buttonBorderGCValues); GC buttonBorderGC = XCreateGC(display_, window, GCForeground, &buttonBorderGCValues);
GC buttonGC = XCreateGC(m_display, window, GCForeground, &buttonGCValues); GC buttonGC = XCreateGC(display_, window, GCForeground, &buttonGCValues);
XSelectInput(m_display, window, ExposureMask | ButtonPressMask | ButtonReleaseMask); XSelectInput(display_, window, ExposureMask | ButtonPressMask | ButtonReleaseMask);
XMapWindow(m_display, window); XMapWindow(display_, window);
const bool has_link = link && strlen(link); const bool has_link = link && strlen(link);
while (true) { while (true) {
XNextEvent(m_display, &e); XNextEvent(display_, &e);
if (e.type == Expose) { if (e.type == Expose) {
for (int i = 0; i < textLines; i++) { for (int i = 0; i < textLines; i++) {
XDrawString(m_display, XDrawString(display_,
window, window,
DefaultGC(m_display, screen), DefaultGC(display_, screen),
dialog_data.padding_x, dialog_data.padding_x,
dialog_data.padding_x + (i + 1) * dialog_data.line_height, dialog_data.padding_x + (i + 1) * dialog_data.line_height,
text_splitted[i], text_splitted[i],
int(strlen(text_splitted[i]))); int(strlen(text_splitted[i])));
} }
dialog_data.drawButton(m_display, window, buttonBorderGC, buttonGC, 1, continue_label); dialog_data.drawButton(display_, window, buttonBorderGC, buttonGC, 1, continue_label);
if (has_link) { if (has_link) {
dialog_data.drawButton(m_display, window, buttonBorderGC, buttonGC, 2, help_label); dialog_data.drawButton(display_, window, buttonBorderGC, buttonGC, 2, help_label);
} }
} }
else if (e.type == ButtonRelease) { else if (e.type == ButtonRelease) {
@@ -2615,9 +2601,9 @@ GHOST_TSuccess GHOST_SystemX11::showMessageBox(const char *title,
} }
free(text_splitted); free(text_splitted);
XDestroyWindow(m_display, window); XDestroyWindow(display_, window);
XFreeGC(m_display, buttonBorderGC); XFreeGC(display_, buttonBorderGC);
XFreeGC(m_display, buttonGC); XFreeGC(display_, buttonGC);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -2768,7 +2754,7 @@ static GHOST_TTabletMode tablet_mode_from_name(const char *name, const char *typ
void GHOST_SystemX11::refreshXInputDevices() void GHOST_SystemX11::refreshXInputDevices()
{ {
if (m_xinput_version.present) { if (xinput_version_.present) {
/* Close tablet devices. */ /* Close tablet devices. */
clearXInputDevices(); clearXInputDevices();
@@ -2777,10 +2763,10 @@ void GHOST_SystemX11::refreshXInputDevices()
{ {
int device_count; int device_count;
XDeviceInfo *device_info = XListInputDevices(m_display, &device_count); XDeviceInfo *device_info = XListInputDevices(display_, &device_count);
for (int i = 0; i < device_count; ++i) { for (int i = 0; i < device_count; ++i) {
char *device_type = device_info[i].type ? XGetAtomName(m_display, device_info[i].type) : char *device_type = device_info[i].type ? XGetAtomName(display_, device_info[i].type) :
nullptr; nullptr;
GHOST_TTabletMode tablet_mode = tablet_mode_from_name(device_info[i].name, device_type); GHOST_TTabletMode tablet_mode = tablet_mode_from_name(device_info[i].name, device_type);
@@ -2796,7 +2782,7 @@ void GHOST_SystemX11::refreshXInputDevices()
GHOST_TabletX11 xtablet = {tablet_mode}; GHOST_TabletX11 xtablet = {tablet_mode};
xtablet.ID = device_info[i].id; xtablet.ID = device_info[i].id;
xtablet.Device = XOpenDevice(m_display, xtablet.ID); xtablet.Device = XOpenDevice(display_, xtablet.ID);
if (xtablet.Device != nullptr) { if (xtablet.Device != nullptr) {
/* Find how many pressure levels tablet has */ /* Find how many pressure levels tablet has */
@@ -2828,7 +2814,7 @@ void GHOST_SystemX11::refreshXInputDevices()
} }
} }
m_xtablets.push_back(xtablet); xtablets_.push_back(xtablet);
} }
} }
@@ -2841,13 +2827,13 @@ void GHOST_SystemX11::refreshXInputDevices()
void GHOST_SystemX11::clearXInputDevices() void GHOST_SystemX11::clearXInputDevices()
{ {
for (GHOST_TabletX11 &xtablet : m_xtablets) { for (GHOST_TabletX11 &xtablet : xtablets_) {
if (xtablet.Device) { if (xtablet.Device) {
XCloseDevice(m_display, xtablet.Device); XCloseDevice(display_, xtablet.Device);
} }
} }
m_xtablets.clear(); xtablets_.clear();
} }
#endif /* WITH_X11_XINPUT */ #endif /* WITH_X11_XINPUT */

View File

@@ -113,9 +113,9 @@ class GHOST_SystemX11 : public GHOST_System {
* \param width: The width the window. * \param width: The width the window.
* \param height: The height the window. * \param height: The height the window.
* \param state: The state of the window when opened. * \param state: The state of the window when opened.
* \param stereoVisual: Create a stereo visual for quad buffered stereo. * \param gpu_settings: Misc GPU settings.
* \param exclusive: Use to show the window on top and ignore others (used full-screen). * \param exclusive: Use to show the window on top and ignore others (used full-screen).
* \param parentWindow: Parent (embedder) window. * \param parent_window: Parent (embedder) window.
* \return The new window (or 0 if creation failed). * \return The new window (or 0 if creation failed).
*/ */
GHOST_IWindow *createWindow(const char *title, GHOST_IWindow *createWindow(const char *title,
@@ -124,17 +124,17 @@ class GHOST_SystemX11 : public GHOST_System {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_GPUSettings gpuSettings, GHOST_GPUSettings gpu_settings,
const bool exclusive = false, const bool exclusive = false,
const bool is_dialog = false, const bool is_dialog = false,
const GHOST_IWindow *parentWindow = nullptr) override; const GHOST_IWindow *parent_window = nullptr) override;
/** /**
* Create a new off-screen context. * Create a new off-screen context.
* Never explicitly delete the context, use #disposeContext() instead. * Never explicitly delete the context, use #disposeContext() instead.
* \return The new context (or 0 if creation failed). * \return The new context (or 0 if creation failed).
*/ */
GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpuSettings) override; GHOST_IContext *createOffscreenContext(GHOST_GPUSettings gpu_settings) override;
/** /**
* Dispose of a context. * Dispose of a context.
@@ -190,13 +190,13 @@ class GHOST_SystemX11 : public GHOST_System {
Display *getXDisplay() Display *getXDisplay()
{ {
return m_display; return display_;
} }
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
XIM getX11_XIM() XIM getX11_XIM()
{ {
return m_xim; return xim_;
} }
#endif #endif
@@ -289,7 +289,7 @@ class GHOST_SystemX11 : public GHOST_System {
std::vector<GHOST_TabletX11> &GetXTablets() std::vector<GHOST_TabletX11> &GetXTablets()
{ {
return m_xtablets; return xtablets_;
} }
#endif // WITH_X11_XINPUT #endif // WITH_X11_XINPUT
@@ -325,50 +325,50 @@ class GHOST_SystemX11 : public GHOST_System {
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
Atom TABLET; Atom TABLET;
#endif #endif
} m_atom; } atom_;
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
XExtensionVersion m_xinput_version; XExtensionVersion xinput_version_;
#endif #endif
private: private:
Display *m_display; Display *display_;
/** Use for scan-code look-ups. */ /** Use for scan-code look-ups. */
XkbDescRec *m_xkb_descr; XkbDescRec *xkb_descr_;
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
XIM m_xim; XIM xim_;
#endif #endif
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
/* Tablet devices */ /* Tablet devices */
std::vector<GHOST_TabletX11> m_xtablets; std::vector<GHOST_TabletX11> xtablets_;
#endif #endif
/** The vector of windows that need to be updated. */ /** The vector of windows that need to be updated. */
std::vector<GHOST_WindowX11 *> m_dirty_windows; std::vector<GHOST_WindowX11 *> dirty_windows_;
/** A vector of keyboard key masks. */ /** A vector of keyboard key masks. */
char m_keyboard_vector[32]; char keyboard_vector_[32];
/** /**
* To prevent multiple warp, we store the time of the last warp event * To prevent multiple warp, we store the time of the last warp event
* and stop accumulating all events generated before that. * and stop accumulating all events generated before that.
*/ */
Time m_last_warp_x; Time last_warp_x_;
Time m_last_warp_y; Time last_warp_y_;
/* Detect auto-repeat glitch. */ /* Detect auto-repeat glitch. */
unsigned int m_last_release_keycode; unsigned int last_release_keycode_;
Time m_last_release_time; Time last_release_time_;
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
/** Last key press or release, to apply to XIM generated events. */ /** Last key press or release, to apply to XIM generated events. */
Time m_last_key_time; Time last_key_time_;
#endif #endif
uint m_keycode_last_repeat_key; uint keycode_last_repeat_key_;
/** /**
* Return the ghost window associated with the * Return the ghost window associated with the

View File

@@ -25,13 +25,13 @@ GHOST_TimerManager::~GHOST_TimerManager()
uint32_t GHOST_TimerManager::getNumTimers() uint32_t GHOST_TimerManager::getNumTimers()
{ {
return uint32_t(m_timers.size()); return uint32_t(timers_.size());
} }
bool GHOST_TimerManager::getTimerFound(GHOST_TimerTask *timer) bool GHOST_TimerManager::getTimerFound(GHOST_TimerTask *timer)
{ {
TTimerVector::const_iterator iter = std::find(m_timers.begin(), m_timers.end(), timer); TTimerVector::const_iterator iter = std::find(timers_.begin(), timers_.end(), timer);
return iter != m_timers.end(); return iter != timers_.end();
} }
GHOST_TSuccess GHOST_TimerManager::addTimer(GHOST_TimerTask *timer) GHOST_TSuccess GHOST_TimerManager::addTimer(GHOST_TimerTask *timer)
@@ -39,7 +39,7 @@ GHOST_TSuccess GHOST_TimerManager::addTimer(GHOST_TimerTask *timer)
GHOST_TSuccess success; GHOST_TSuccess success;
if (!getTimerFound(timer)) { if (!getTimerFound(timer)) {
/* Add the timer task. */ /* Add the timer task. */
m_timers.push_back(timer); timers_.push_back(timer);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
else { else {
@@ -51,10 +51,10 @@ GHOST_TSuccess GHOST_TimerManager::addTimer(GHOST_TimerTask *timer)
GHOST_TSuccess GHOST_TimerManager::removeTimer(GHOST_TimerTask *timer) GHOST_TSuccess GHOST_TimerManager::removeTimer(GHOST_TimerTask *timer)
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
TTimerVector::iterator iter = std::find(m_timers.begin(), m_timers.end(), timer); TTimerVector::iterator iter = std::find(timers_.begin(), timers_.end(), timer);
if (iter != m_timers.end()) { if (iter != timers_.end()) {
/* Remove the timer task. */ /* Remove the timer task. */
m_timers.erase(iter); timers_.erase(iter);
delete timer; delete timer;
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
@@ -69,7 +69,7 @@ uint64_t GHOST_TimerManager::nextFireTime()
uint64_t smallest = GHOST_kFireTimeNever; uint64_t smallest = GHOST_kFireTimeNever;
TTimerVector::iterator iter; TTimerVector::iterator iter;
for (iter = m_timers.begin(); iter != m_timers.end(); ++iter) { for (iter = timers_.begin(); iter != timers_.end(); ++iter) {
const uint64_t next = (*iter)->getNext(); const uint64_t next = (*iter)->getNext();
smallest = std::min(next, smallest); smallest = std::min(next, smallest);
} }
@@ -82,7 +82,7 @@ bool GHOST_TimerManager::fireTimers(uint64_t time)
TTimerVector::iterator iter; TTimerVector::iterator iter;
bool anyProcessed = false; bool anyProcessed = false;
for (iter = m_timers.begin(); iter != m_timers.end(); ++iter) { for (iter = timers_.begin(); iter != timers_.end(); ++iter) {
if (fireTimer(time, *iter)) { if (fireTimer(time, *iter)) {
anyProcessed = true; anyProcessed = true;
} }
@@ -98,9 +98,9 @@ bool GHOST_TimerManager::fireTimer(uint64_t time, GHOST_TimerTask *task)
/* Check if the timer should be fired. */ /* Check if the timer should be fired. */
if (time > next) { if (time > next) {
/* Fire the timer. */ /* Fire the timer. */
GHOST_TimerProcPtr timerProc = task->getTimerProc(); GHOST_TimerProcPtr timer_proc = task->getTimerProc();
uint64_t start = task->getStart(); uint64_t start = task->getStart();
timerProc(task, time - start); timer_proc(task, time - start);
/* Update the time at which we will fire it again. */ /* Update the time at which we will fire it again. */
uint64_t interval = task->getInterval(); uint64_t interval = task->getInterval();
@@ -116,8 +116,8 @@ bool GHOST_TimerManager::fireTimer(uint64_t time, GHOST_TimerTask *task)
void GHOST_TimerManager::disposeTimers() void GHOST_TimerManager::disposeTimers()
{ {
while (m_timers.empty() == false) { while (timers_.empty() == false) {
delete m_timers[0]; delete timers_[0];
m_timers.erase(m_timers.begin()); timers_.erase(timers_.begin());
} }
} }

View File

@@ -90,7 +90,7 @@ class GHOST_TimerManager {
using TTimerVector = std::vector<GHOST_TimerTask *>; using TTimerVector = std::vector<GHOST_TimerTask *>;
/** The list with event consumers. */ /** The list with event consumers. */
TTimerVector m_timers; TTimerVector timers_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_TimerManager") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_TimerManager")
}; };

View File

@@ -19,19 +19,19 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
/** /**
* Constructor. * Constructor.
* \param start: The timer start time. * \param start: The timer start time.
* \param interval: The interval between calls to the #timerProc. * \param interval: The interval between calls to the #timer_proc.
* \param timerProc: The callback invoked when the interval expires. * \param timer_proc: The callback invoked when the interval expires.
* \param userData: The timer user data. * \param user_data: The timer user data.
*/ */
GHOST_TimerTask(uint64_t start, GHOST_TimerTask(uint64_t start,
uint64_t interval, uint64_t interval,
GHOST_TimerProcPtr timerProc, GHOST_TimerProcPtr timer_proc,
GHOST_TUserDataPtr userData = nullptr) GHOST_TUserDataPtr user_data = nullptr)
: m_start(start), : start_(start),
m_interval(interval), interval_(interval),
m_next(start), next_(start),
m_timerProc(timerProc), timer_proc_(timer_proc),
m_userData(userData) user_data_(user_data)
{ {
} }
@@ -41,7 +41,7 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
uint64_t getStart() const uint64_t getStart() const
{ {
return m_start; return start_;
} }
/** /**
@@ -50,7 +50,7 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
void setStart(uint64_t start) void setStart(uint64_t start)
{ {
m_start = start; start_ = start;
} }
/** /**
@@ -59,7 +59,7 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
uint64_t getInterval() const uint64_t getInterval() const
{ {
return m_interval; return interval_;
} }
/** /**
@@ -68,49 +68,49 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
void setInterval(uint64_t interval) void setInterval(uint64_t interval)
{ {
m_interval = interval; interval_ = interval;
} }
/** /**
* Returns the time the timerProc will be called. * Returns the time the timer_proc will be called.
* \return The time the timerProc will be called. * \return The time the timer_proc will be called.
*/ */
uint64_t getNext() const uint64_t getNext() const
{ {
return m_next; return next_;
} }
/** /**
* Changes the time the timerProc will be called. * Changes the time the timer_proc will be called.
* \param next: The time the timerProc will be called. * \param next: The time the timer_proc will be called.
*/ */
void setNext(uint64_t next) void setNext(uint64_t next)
{ {
m_next = next; next_ = next;
} }
/** \copydoc #GHOST_ITimerTask::getTimerProc */ /** \copydoc #GHOST_ITimerTask::getTimerProc */
GHOST_TimerProcPtr getTimerProc() const override GHOST_TimerProcPtr getTimerProc() const override
{ {
return m_timerProc; return timer_proc_;
} }
/** \copydoc #GHOST_ITimerTask::setTimerProc */ /** \copydoc #GHOST_ITimerTask::setTimerProc */
void setTimerProc(const GHOST_TimerProcPtr timerProc) override void setTimerProc(const GHOST_TimerProcPtr timer_proc) override
{ {
m_timerProc = timerProc; timer_proc_ = timer_proc;
} }
/** \copydoc #GHOST_ITimerTask::getUserData */ /** \copydoc #GHOST_ITimerTask::getUserData */
GHOST_TUserDataPtr getUserData() const override GHOST_TUserDataPtr getUserData() const override
{ {
return m_userData; return user_data_;
} }
/** \copydoc #GHOST_ITimerTask::setUserData */ /** \copydoc #GHOST_ITimerTask::setUserData */
void setUserData(const GHOST_TUserDataPtr userData) override void setUserData(const GHOST_TUserDataPtr user_data) override
{ {
m_userData = userData; user_data_ = user_data;
} }
/** /**
@@ -119,7 +119,7 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
uint32_t getAuxData() const uint32_t getAuxData() const
{ {
return m_auxData; return aux_data_;
} }
/** /**
@@ -128,25 +128,25 @@ class GHOST_TimerTask : public GHOST_ITimerTask {
*/ */
void setAuxData(uint32_t auxData) void setAuxData(uint32_t auxData)
{ {
m_auxData = auxData; aux_data_ = auxData;
} }
protected: protected:
/** The time the timer task was started. */ /** The time the timer task was started. */
uint64_t m_start; uint64_t start_;
/** The interval between calls. */ /** The interval between calls. */
uint64_t m_interval; uint64_t interval_;
/** The time the timerProc will be called. */ /** The time the timer_proc will be called. */
uint64_t m_next; uint64_t next_;
/** The callback invoked when the timer expires. */ /** The callback invoked when the timer expires. */
GHOST_TimerProcPtr m_timerProc; GHOST_TimerProcPtr timer_proc_;
/** The timer task user data. */ /** The timer task user data. */
GHOST_TUserDataPtr m_userData; GHOST_TUserDataPtr user_data_;
/** Auxiliary storage room. */ /** Auxiliary storage room. */
uint32_t m_auxData = 0; uint32_t aux_data_ = 0;
}; };

View File

@@ -20,15 +20,15 @@ GHOST_DirectManipulationHelper::GHOST_DirectManipulationHelper(
directManipulationEventHandler, directManipulationEventHandler,
DWORD directManipulationViewportHandlerCookie, DWORD directManipulationViewportHandlerCookie,
bool isScrollDirectionInverted) bool isScrollDirectionInverted)
: m_hWnd(hWnd), : h_wnd_(hWnd),
m_scrollDirectionRegKey(nullptr), scroll_direction_reg_key_(nullptr),
m_scrollDirectionChangeEvent(nullptr), scroll_direction_change_event_(nullptr),
m_directManipulationManager(directManipulationManager), direct_manipulation_manager_(directManipulationManager),
m_directManipulationUpdateManager(directManipulationUpdateManager), direct_manipulation_update_manager_(directManipulationUpdateManager),
m_directManipulationViewport(directManipulationViewport), direct_manipulation_viewport_(directManipulationViewport),
m_directManipulationEventHandler(directManipulationEventHandler), direct_manipulation_event_handler_(directManipulationEventHandler),
m_directManipulationViewportHandlerCookie(directManipulationViewportHandlerCookie), direct_manipulation_viewport_handler_cookie_(directManipulationViewportHandlerCookie),
m_isScrollDirectionInverted(isScrollDirectionInverted) is_scroll_direction_inverted_(isScrollDirectionInverted)
{ {
} }
@@ -137,29 +137,29 @@ bool GHOST_DirectManipulationHelper::getScrollDirectionFromReg()
void GHOST_DirectManipulationHelper::registerScrollDirectionChangeListener() void GHOST_DirectManipulationHelper::registerScrollDirectionChangeListener()
{ {
if (!m_scrollDirectionRegKey) { if (!scroll_direction_reg_key_) {
HRESULT hr = HRESULT_FROM_WIN32( HRESULT hr = HRESULT_FROM_WIN32(
RegOpenKeyExW(HKEY_CURRENT_USER, RegOpenKeyExW(HKEY_CURRENT_USER,
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PrecisionTouchPad\\", L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\PrecisionTouchPad\\",
0, 0,
KEY_NOTIFY, KEY_NOTIFY,
&m_scrollDirectionRegKey)); &scroll_direction_reg_key_));
if (!SUCCEEDED(hr)) { if (!SUCCEEDED(hr)) {
GHOST_PRINT("Failed to open scroll direction registry key\n"); GHOST_PRINT("Failed to open scroll direction registry key\n");
return; return;
} }
} }
if (!m_scrollDirectionChangeEvent) { if (!scroll_direction_change_event_) {
m_scrollDirectionChangeEvent = CreateEventW(nullptr, true, false, nullptr); scroll_direction_change_event_ = CreateEventW(nullptr, true, false, nullptr);
} }
else { else {
ResetEvent(m_scrollDirectionChangeEvent); ResetEvent(scroll_direction_change_event_);
} }
HRESULT hr = HRESULT_FROM_WIN32(RegNotifyChangeKeyValue(m_scrollDirectionRegKey, HRESULT hr = HRESULT_FROM_WIN32(RegNotifyChangeKeyValue(scroll_direction_reg_key_,
true, true,
REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_LAST_SET,
m_scrollDirectionChangeEvent, scroll_direction_change_event_,
true)); true));
if (!SUCCEEDED(hr)) { if (!SUCCEEDED(hr)) {
GHOST_PRINT("Failed to register scroll direction change listener\n"); GHOST_PRINT("Failed to register scroll direction change listener\n");
@@ -169,61 +169,62 @@ void GHOST_DirectManipulationHelper::registerScrollDirectionChangeListener()
void GHOST_DirectManipulationHelper::onPointerHitTest(UINT32 pointerId) void GHOST_DirectManipulationHelper::onPointerHitTest(UINT32 pointerId)
{ {
[[maybe_unused]] HRESULT hr = m_directManipulationViewport->SetContact(pointerId); [[maybe_unused]] HRESULT hr = direct_manipulation_viewport_->SetContact(pointerId);
GHOST_ASSERT(SUCCEEDED(hr), "Viewport set contact failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "Viewport set contact failed\n");
if (WaitForSingleObject(m_scrollDirectionChangeEvent, 0) == WAIT_OBJECT_0) { if (WaitForSingleObject(scroll_direction_change_event_, 0) == WAIT_OBJECT_0) {
m_isScrollDirectionInverted = getScrollDirectionFromReg(); is_scroll_direction_inverted_ = getScrollDirectionFromReg();
registerScrollDirectionChangeListener(); registerScrollDirectionChangeListener();
} }
} }
void GHOST_DirectManipulationHelper::update() void GHOST_DirectManipulationHelper::update()
{ {
if (m_directManipulationEventHandler->dm_status == DIRECTMANIPULATION_RUNNING || if (direct_manipulation_event_handler_->dm_status == DIRECTMANIPULATION_RUNNING ||
m_directManipulationEventHandler->dm_status == DIRECTMANIPULATION_INERTIA) direct_manipulation_event_handler_->dm_status == DIRECTMANIPULATION_INERTIA)
{ {
[[maybe_unused]] HRESULT hr = m_directManipulationUpdateManager->Update(nullptr); [[maybe_unused]] HRESULT hr = direct_manipulation_update_manager_->Update(nullptr);
GHOST_ASSERT(SUCCEEDED(hr), "DirectManipulationUpdateManager update failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "DirectManipulationUpdateManager update failed\n");
} }
} }
void GHOST_DirectManipulationHelper::setDPI(uint16_t dpi) void GHOST_DirectManipulationHelper::setDPI(uint16_t dpi)
{ {
m_directManipulationEventHandler->dpi = dpi; direct_manipulation_event_handler_->dpi = dpi;
} }
GHOST_TTrackpadInfo GHOST_DirectManipulationHelper::getTrackpadInfo() GHOST_TTrackpadInfo GHOST_DirectManipulationHelper::getTrackpadInfo()
{ {
GHOST_TTrackpadInfo result = m_directManipulationEventHandler->accumulated_values; GHOST_TTrackpadInfo result = direct_manipulation_event_handler_->accumulated_values;
result.isScrollDirectionInverted = m_isScrollDirectionInverted; result.isScrollDirectionInverted = is_scroll_direction_inverted_;
m_directManipulationEventHandler->accumulated_values = {0, 0, 0}; direct_manipulation_event_handler_->accumulated_values = {0, 0, 0};
return result; return result;
} }
GHOST_DirectManipulationHelper::~GHOST_DirectManipulationHelper() GHOST_DirectManipulationHelper::~GHOST_DirectManipulationHelper()
{ {
HRESULT hr; HRESULT hr;
hr = m_directManipulationViewport->Stop(); hr = direct_manipulation_viewport_->Stop();
GHOST_ASSERT(SUCCEEDED(hr), "Viewport stop failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "Viewport stop failed\n");
hr = m_directManipulationViewport->RemoveEventHandler(m_directManipulationViewportHandlerCookie); hr = direct_manipulation_viewport_->RemoveEventHandler(
direct_manipulation_viewport_handler_cookie_);
GHOST_ASSERT(SUCCEEDED(hr), "Viewport remove event handler failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "Viewport remove event handler failed\n");
hr = m_directManipulationViewport->Abandon(); hr = direct_manipulation_viewport_->Abandon();
GHOST_ASSERT(SUCCEEDED(hr), "Viewport abandon failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "Viewport abandon failed\n");
hr = m_directManipulationManager->Deactivate(m_hWnd); hr = direct_manipulation_manager_->Deactivate(h_wnd_);
GHOST_ASSERT(SUCCEEDED(hr), "DirectManipulationManager deactivate failed\n"); GHOST_ASSERT(SUCCEEDED(hr), "DirectManipulationManager deactivate failed\n");
if (m_scrollDirectionChangeEvent) { if (scroll_direction_change_event_) {
CloseHandle(m_scrollDirectionChangeEvent); CloseHandle(scroll_direction_change_event_);
m_scrollDirectionChangeEvent = nullptr; scroll_direction_change_event_ = nullptr;
} }
if (m_scrollDirectionRegKey) { if (scroll_direction_reg_key_) {
RegCloseKey(m_scrollDirectionRegKey); RegCloseKey(scroll_direction_reg_key_);
m_scrollDirectionRegKey = nullptr; scroll_direction_reg_key_ = nullptr;
} }
} }

View File

@@ -124,17 +124,17 @@ class GHOST_DirectManipulationHelper {
*/ */
void registerScrollDirectionChangeListener(); void registerScrollDirectionChangeListener();
HWND m_hWnd; HWND h_wnd_;
HKEY m_scrollDirectionRegKey; HKEY scroll_direction_reg_key_;
HANDLE m_scrollDirectionChangeEvent; HANDLE scroll_direction_change_event_;
Microsoft::WRL::ComPtr<IDirectManipulationManager> m_directManipulationManager; Microsoft::WRL::ComPtr<IDirectManipulationManager> direct_manipulation_manager_;
Microsoft::WRL::ComPtr<IDirectManipulationUpdateManager> m_directManipulationUpdateManager; Microsoft::WRL::ComPtr<IDirectManipulationUpdateManager> direct_manipulation_update_manager_;
Microsoft::WRL::ComPtr<IDirectManipulationViewport> m_directManipulationViewport; Microsoft::WRL::ComPtr<IDirectManipulationViewport> direct_manipulation_viewport_;
Microsoft::WRL::ComPtr<GHOST_DirectManipulationViewportEventHandler> Microsoft::WRL::ComPtr<GHOST_DirectManipulationViewportEventHandler>
m_directManipulationEventHandler; direct_manipulation_event_handler_;
DWORD m_directManipulationViewportHandlerCookie; DWORD direct_manipulation_viewport_handler_cookie_;
bool m_isScrollDirectionInverted; bool is_scroll_direction_inverted_;
}; };

View File

@@ -21,37 +21,37 @@ GHOST_Window::GHOST_Window(uint32_t width,
GHOST_TWindowState state, GHOST_TWindowState state,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
const bool /*exclusive*/) const bool /*exclusive*/)
: m_drawingContextType(GHOST_kDrawingContextTypeNone), : drawing_context_type_(GHOST_kDrawingContextTypeNone),
m_userData(nullptr), user_data_(nullptr),
m_cursorVisible(true), cursor_visible_(true),
m_cursorGrab(GHOST_kGrabDisable), cursor_grab_(GHOST_kGrabDisable),
m_cursorGrabAxis(GHOST_kAxisNone), cursor_grab_axis_(GHOST_kAxisNone),
m_cursorGrabInitPos{0, 0}, cursor_grab_init_pos_{0, 0},
m_cursorGrabAccumPos{0, 0}, cursor_grab_accum_pos_{0, 0},
m_cursorShape(GHOST_kStandardCursorDefault), cursor_shape_(GHOST_kStandardCursorDefault),
m_progressBarVisible(false), progress_bar_visible_(false),
m_canAcceptDragOperation(false), can_accept_drag_operation_(false),
m_isUnsavedChanges(false), is_unsaved_changes_(false),
m_windowDecorationStyleFlags(GHOST_kDecorationNone), window_decoration_style_flags_(GHOST_kDecorationNone),
m_windowDecorationStyleSettings(), window_decoration_style_settings_(),
m_want_context_params(context_params), want_context_params_(context_params),
m_nativePixelSize(1.0f), native_pixel_size_(1.0f),
m_context(nullptr) context_(nullptr)
{ {
const GHOST_ContextParams context_params_none = GHOST_CONTEXT_PARAMS_NONE; const GHOST_ContextParams context_params_none = GHOST_CONTEXT_PARAMS_NONE;
m_context = new GHOST_ContextNone(context_params_none); context_ = new GHOST_ContextNone(context_params_none);
m_fullScreen = state == GHOST_kWindowStateFullScreen; full_screen_ = state == GHOST_kWindowStateFullScreen;
if (m_fullScreen) { if (full_screen_) {
m_fullScreenWidth = width; full_screen_width_ = width;
m_fullScreenHeight = height; full_screen_height_ = height;
} }
} }
GHOST_Window::~GHOST_Window() GHOST_Window::~GHOST_Window()
{ {
delete m_context; delete context_;
} }
void *GHOST_Window::getOSWindow() const void *GHOST_Window::getOSWindow() const
@@ -61,98 +61,98 @@ void *GHOST_Window::getOSWindow() const
GHOST_TWindowDecorationStyleFlags GHOST_Window::getWindowDecorationStyleFlags() GHOST_TWindowDecorationStyleFlags GHOST_Window::getWindowDecorationStyleFlags()
{ {
return m_windowDecorationStyleFlags; return window_decoration_style_flags_;
} }
void GHOST_Window::setWindowDecorationStyleFlags(GHOST_TWindowDecorationStyleFlags styleFlags) void GHOST_Window::setWindowDecorationStyleFlags(GHOST_TWindowDecorationStyleFlags style_flags)
{ {
m_windowDecorationStyleFlags = styleFlags; window_decoration_style_flags_ = style_flags;
} }
void GHOST_Window::setWindowDecorationStyleSettings( void GHOST_Window::setWindowDecorationStyleSettings(
GHOST_WindowDecorationStyleSettings decorationSettings) GHOST_WindowDecorationStyleSettings decoration_settings)
{ {
m_windowDecorationStyleSettings = decorationSettings; window_decoration_style_settings_ = decoration_settings;
} }
GHOST_TSuccess GHOST_Window::setDrawingContextType(GHOST_TDrawingContextType type) GHOST_TSuccess GHOST_Window::setDrawingContextType(GHOST_TDrawingContextType type)
{ {
if (type != m_drawingContextType) { if (type != drawing_context_type_) {
delete m_context; delete context_;
m_context = nullptr; context_ = nullptr;
if (type != GHOST_kDrawingContextTypeNone) { if (type != GHOST_kDrawingContextTypeNone) {
m_context = newDrawingContext(type); context_ = newDrawingContext(type);
} }
if (m_context != nullptr) { if (context_ != nullptr) {
m_drawingContextType = type; drawing_context_type_ = type;
} }
else { else {
m_context = new GHOST_ContextNone(m_want_context_params); context_ = new GHOST_ContextNone(want_context_params_);
m_drawingContextType = GHOST_kDrawingContextTypeNone; drawing_context_type_ = GHOST_kDrawingContextTypeNone;
} }
return (type == m_drawingContextType) ? GHOST_kSuccess : GHOST_kFailure; return (type == drawing_context_type_) ? GHOST_kSuccess : GHOST_kFailure;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_IContext *GHOST_Window::getDrawingContext() GHOST_IContext *GHOST_Window::getDrawingContext()
{ {
return m_context; return context_;
} }
GHOST_TSuccess GHOST_Window::swapBuffers() GHOST_TSuccess GHOST_Window::swapBuffers()
{ {
return m_context->swapBuffers(); return context_->swapBuffers();
} }
GHOST_TSuccess GHOST_Window::setSwapInterval(int interval) GHOST_TSuccess GHOST_Window::setSwapInterval(int interval)
{ {
return m_context->setSwapInterval(interval); return context_->setSwapInterval(interval);
} }
GHOST_TSuccess GHOST_Window::getSwapInterval(int &intervalOut) GHOST_TSuccess GHOST_Window::getSwapInterval(int &interval_out)
{ {
return m_context->getSwapInterval(intervalOut); return context_->getSwapInterval(interval_out);
} }
GHOST_Context *GHOST_Window::getContext() GHOST_Context *GHOST_Window::getContext()
{ {
return m_context; return context_;
} }
uint GHOST_Window::getDefaultFramebuffer() uint GHOST_Window::getDefaultFramebuffer()
{ {
return (m_context) ? m_context->getDefaultFramebuffer() : 0; return (context_) ? context_->getDefaultFramebuffer() : 0;
} }
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
GHOST_TSuccess GHOST_Window::getVulkanSwapChainFormat(GHOST_VulkanSwapChainData *r_swap_chain_data) GHOST_TSuccess GHOST_Window::getVulkanSwapChainFormat(GHOST_VulkanSwapChainData *r_swap_chain_data)
{ {
return m_context->getVulkanSwapChainFormat(r_swap_chain_data); return context_->getVulkanSwapChainFormat(r_swap_chain_data);
} }
#endif #endif
GHOST_TSuccess GHOST_Window::activateDrawingContext() GHOST_TSuccess GHOST_Window::activateDrawingContext()
{ {
return m_context->activateDrawingContext(); return context_->activateDrawingContext();
} }
GHOST_TSuccess GHOST_Window::updateDrawingContext() GHOST_TSuccess GHOST_Window::updateDrawingContext()
{ {
return m_context->updateDrawingContext(); return context_->updateDrawingContext();
} }
GHOST_TSuccess GHOST_Window::releaseNativeHandles() GHOST_TSuccess GHOST_Window::releaseNativeHandles()
{ {
return m_context->releaseNativeHandles(); return context_->releaseNativeHandles();
} }
GHOST_TSuccess GHOST_Window::setCursorVisibility(bool visible) GHOST_TSuccess GHOST_Window::setCursorVisibility(bool visible)
{ {
if (setWindowCursorVisibility(visible)) { if (setWindowCursorVisibility(visible)) {
m_cursorVisible = visible; cursor_visible_ = visible;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -163,29 +163,29 @@ GHOST_TSuccess GHOST_Window::setCursorGrab(GHOST_TGrabCursorMode mode,
GHOST_Rect *bounds, GHOST_Rect *bounds,
int32_t mouse_ungrab_xy[2]) int32_t mouse_ungrab_xy[2])
{ {
if (m_cursorGrab == mode) { if (cursor_grab_ == mode) {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
/* Override with new location. */ /* Override with new location. */
if (mouse_ungrab_xy) { if (mouse_ungrab_xy) {
assert(mode == GHOST_kGrabDisable); assert(mode == GHOST_kGrabDisable);
m_cursorGrabInitPos[0] = mouse_ungrab_xy[0]; cursor_grab_init_pos_[0] = mouse_ungrab_xy[0];
m_cursorGrabInitPos[1] = mouse_ungrab_xy[1]; cursor_grab_init_pos_[1] = mouse_ungrab_xy[1];
} }
if (setWindowCursorGrab(mode)) { if (setWindowCursorGrab(mode)) {
if (mode == GHOST_kGrabDisable) { if (mode == GHOST_kGrabDisable) {
m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; cursor_grab_bounds_.l_ = cursor_grab_bounds_.r_ = -1;
} }
else if (bounds) { else if (bounds) {
m_cursorGrabBounds = *bounds; cursor_grab_bounds_ = *bounds;
} }
else { /* if bounds not defined, use window */ else { /* if bounds not defined, use window */
getClientBounds(m_cursorGrabBounds); getClientBounds(cursor_grab_bounds_);
} }
m_cursorGrab = mode; cursor_grab_ = mode;
m_cursorGrabAxis = wrap_axis; cursor_grab_axis_ = wrap_axis;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -193,11 +193,11 @@ GHOST_TSuccess GHOST_Window::setCursorGrab(GHOST_TGrabCursorMode mode,
GHOST_TSuccess GHOST_Window::getCursorGrabBounds(GHOST_Rect &bounds) const GHOST_TSuccess GHOST_Window::getCursorGrabBounds(GHOST_Rect &bounds) const
{ {
if (!(m_cursorGrab == GHOST_kGrabWrap || m_cursorGrab == GHOST_kGrabHide)) { if (!(cursor_grab_ == GHOST_kGrabWrap || cursor_grab_ == GHOST_kGrabHide)) {
return GHOST_kFailure; return GHOST_kFailure;
} }
bounds = m_cursorGrabBounds; bounds = cursor_grab_bounds_;
return (bounds.m_l == -1 && bounds.m_r == -1) ? GHOST_kFailure : GHOST_kSuccess; return (bounds.l_ == -1 && bounds.r_ == -1) ? GHOST_kFailure : GHOST_kSuccess;
} }
void GHOST_Window::getCursorGrabState(GHOST_TGrabCursorMode &mode, void GHOST_Window::getCursorGrabState(GHOST_TGrabCursorMode &mode,
@@ -205,19 +205,19 @@ void GHOST_Window::getCursorGrabState(GHOST_TGrabCursorMode &mode,
GHOST_Rect &bounds, GHOST_Rect &bounds,
bool &use_software_cursor) bool &use_software_cursor)
{ {
mode = m_cursorGrab; mode = cursor_grab_;
if (m_cursorGrab == GHOST_kGrabWrap) { if (cursor_grab_ == GHOST_kGrabWrap) {
bounds = m_cursorGrabBounds; bounds = cursor_grab_bounds_;
wrap_axis = m_cursorGrabAxis; wrap_axis = cursor_grab_axis_;
} }
else { else {
bounds.m_l = -1; bounds.l_ = -1;
bounds.m_r = -1; bounds.r_ = -1;
bounds.m_t = -1; bounds.t_ = -1;
bounds.m_b = -1; bounds.b_ = -1;
wrap_axis = GHOST_kAxisNone; wrap_axis = GHOST_kAxisNone;
} }
use_software_cursor = (m_cursorGrab != GHOST_kGrabDisable) ? getCursorGrabUseSoftwareDisplay() : use_software_cursor = (cursor_grab_ != GHOST_kGrabDisable) ? getCursorGrabUseSoftwareDisplay() :
false; false;
} }
@@ -227,10 +227,10 @@ bool GHOST_Window::getCursorGrabUseSoftwareDisplay()
return false; return false;
} }
GHOST_TSuccess GHOST_Window::setCursorShape(GHOST_TStandardCursor cursorShape) GHOST_TSuccess GHOST_Window::setCursorShape(GHOST_TStandardCursor cursor_shape)
{ {
if (setWindowCursorShape(cursorShape)) { if (setWindowCursorShape(cursor_shape)) {
m_cursorShape = cursorShape; cursor_shape_ = cursor_shape;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -243,7 +243,7 @@ GHOST_TSuccess GHOST_Window::setCustomCursorShape(const uint8_t *bitmap,
bool can_invert_color) bool can_invert_color)
{ {
if (setWindowCustomCursorShape(bitmap, mask, size, hot_spot, can_invert_color)) { if (setWindowCustomCursorShape(bitmap, mask, size, hot_spot, can_invert_color)) {
m_cursorShape = GHOST_kStandardCursorCustom; cursor_shape_ = GHOST_kStandardCursorCustom;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -252,7 +252,7 @@ GHOST_TSuccess GHOST_Window::setCustomCursorShape(const uint8_t *bitmap,
GHOST_TSuccess GHOST_Window::setCustomCursorGenerator(GHOST_CursorGenerator *cursor_generator) GHOST_TSuccess GHOST_Window::setCustomCursorGenerator(GHOST_CursorGenerator *cursor_generator)
{ {
if (setWindowCustomCursorGenerator(cursor_generator)) { if (setWindowCustomCursorGenerator(cursor_generator)) {
m_cursorShape = GHOST_kStandardCursorCustom; cursor_shape_ = GHOST_kStandardCursorCustom;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
return GHOST_kFailure; return GHOST_kFailure;
@@ -264,24 +264,24 @@ GHOST_TSuccess GHOST_Window::getCursorBitmap(GHOST_CursorBitmapRef * /*bitmap*/)
return GHOST_kFailure; return GHOST_kFailure;
} }
void GHOST_Window::setAcceptDragOperation(bool canAccept) void GHOST_Window::setAcceptDragOperation(bool can_accept)
{ {
m_canAcceptDragOperation = canAccept; can_accept_drag_operation_ = can_accept;
} }
bool GHOST_Window::canAcceptDragOperation() const bool GHOST_Window::canAcceptDragOperation() const
{ {
return m_canAcceptDragOperation; return can_accept_drag_operation_;
} }
GHOST_TSuccess GHOST_Window::setModifiedState(bool isUnsavedChanges) GHOST_TSuccess GHOST_Window::setModifiedState(bool is_unsaved_changes)
{ {
m_isUnsavedChanges = isUnsavedChanges; is_unsaved_changes_ = is_unsaved_changes;
return GHOST_kSuccess; return GHOST_kSuccess;
} }
bool GHOST_Window::getModifiedState() bool GHOST_Window::getModifiedState()
{ {
return m_isUnsavedChanges; return is_unsaved_changes_;
} }

View File

@@ -58,7 +58,7 @@ class GHOST_Window : public GHOST_IWindow {
* virtual GHOST_TSuccess setOrder(GHOST_TWindowOrder order) = 0; * virtual GHOST_TSuccess setOrder(GHOST_TWindowOrder order) = 0;
* virtual GHOST_TSuccess swapBuffers() = 0; * virtual GHOST_TSuccess swapBuffers() = 0;
* virtual GHOST_TSuccess setSwapInterval() = 0; * virtual GHOST_TSuccess setSwapInterval() = 0;
* virtual GHOST_TSuccess getSwapInterval(int& intervalOut) = 0; * virtual GHOST_TSuccess getSwapInterval(int& interval_out) = 0;
* virtual GHOST_TSuccess activateDrawingContext() = 0; * virtual GHOST_TSuccess activateDrawingContext() = 0;
* virtual GHOST_TSuccess invalidate() = 0; * virtual GHOST_TSuccess invalidate() = 0;
*/ */
@@ -72,7 +72,7 @@ class GHOST_Window : public GHOST_IWindow {
/** \copydoc #GHOST_IWindow::getValid */ /** \copydoc #GHOST_IWindow::getValid */
bool getValid() const override bool getValid() const override
{ {
return m_context != nullptr; return context_ != nullptr;
} }
/** \copydoc #GHOST_IWindow::getOSWindow */ /** \copydoc #GHOST_IWindow::getOSWindow */
@@ -89,11 +89,11 @@ class GHOST_Window : public GHOST_IWindow {
/** \copydoc #GHOST_IWindow::setWindowDecorationStyleFlags */ /** \copydoc #GHOST_IWindow::setWindowDecorationStyleFlags */
virtual void setWindowDecorationStyleFlags( virtual void setWindowDecorationStyleFlags(
GHOST_TWindowDecorationStyleFlags styleFlags) override; GHOST_TWindowDecorationStyleFlags style_flags) override;
/** \copydoc #GHOST_IWindow::setWindowDecorationStyleSettings */ /** \copydoc #GHOST_IWindow::setWindowDecorationStyleSettings */
virtual void setWindowDecorationStyleSettings( virtual void setWindowDecorationStyleSettings(
GHOST_WindowDecorationStyleSettings decorationSettings) override; GHOST_WindowDecorationStyleSettings decoration_settings) override;
/** \copydoc #GHOST_IWindow::applyWindowDecorationStyle */ /** \copydoc #GHOST_IWindow::applyWindowDecorationStyle */
virtual GHOST_TSuccess applyWindowDecorationStyle() override virtual GHOST_TSuccess applyWindowDecorationStyle() override
@@ -110,7 +110,7 @@ class GHOST_Window : public GHOST_IWindow {
} }
/** \copydoc #GHOST_IWindow::setCursorShape */ /** \copydoc #GHOST_IWindow::setCursorShape */
GHOST_TSuccess setCursorShape(GHOST_TStandardCursor cursorShape) override; GHOST_TSuccess setCursorShape(GHOST_TStandardCursor cursor_shape) override;
/** \copydoc #GHOST_IWindow::setCustomCursorShape */ /** \copydoc #GHOST_IWindow::setCustomCursorShape */
GHOST_TSuccess setCustomCursorShape(const uint8_t *bitmap, GHOST_TSuccess setCustomCursorShape(const uint8_t *bitmap,
@@ -167,16 +167,16 @@ class GHOST_Window : public GHOST_IWindow {
/** \copydoc #GHOST_IWindow::setSwapInterval */ /** \copydoc #GHOST_IWindow::setSwapInterval */
GHOST_TSuccess setSwapInterval(int interval) override; GHOST_TSuccess setSwapInterval(int interval) override;
/** \copydoc #GHOST_IWindow::getSwapInterval */ /** \copydoc #GHOST_IWindow::getSwapInterval */
GHOST_TSuccess getSwapInterval(int &intervalOut) override; GHOST_TSuccess getSwapInterval(int &interval_out) override;
/** \copydoc #GHOST_IWindow::setAcceptDragOperation */ /** \copydoc #GHOST_IWindow::setAcceptDragOperation */
void setAcceptDragOperation(bool canAccept) override; void setAcceptDragOperation(bool can_accept) override;
/** \copydoc #GHOST_IWindow::canAcceptDragOperation */ /** \copydoc #GHOST_IWindow::canAcceptDragOperation */
bool canAcceptDragOperation() const override; bool canAcceptDragOperation() const override;
/** \copydoc #GHOST_IWindow::setModifiedState */ /** \copydoc #GHOST_IWindow::setModifiedState */
GHOST_TSuccess setModifiedState(bool isUnsavedChanges) override; GHOST_TSuccess setModifiedState(bool is_unsaved_changes) override;
/** \copydoc #GHOST_IWindow::getModifiedState */ /** \copydoc #GHOST_IWindow::getModifiedState */
bool getModifiedState() override; bool getModifiedState() override;
@@ -226,20 +226,20 @@ class GHOST_Window : public GHOST_IWindow {
/** \copydoc #GHOST_IWindow::getUserData */ /** \copydoc #GHOST_IWindow::getUserData */
GHOST_TUserDataPtr getUserData() const override GHOST_TUserDataPtr getUserData() const override
{ {
return m_userData; return user_data_;
} }
/** \copydoc #GHOST_IWindow::setUserData */ /** \copydoc #GHOST_IWindow::setUserData */
void setUserData(const GHOST_TUserDataPtr userData) override void setUserData(const GHOST_TUserDataPtr user_data) override
{ {
m_userData = userData; user_data_ = user_data;
} }
/** \copydoc #GHOST_IWindow::getNativePixelSize */ /** \copydoc #GHOST_IWindow::getNativePixelSize */
float getNativePixelSize() override float getNativePixelSize() override
{ {
if (m_nativePixelSize > 0.0f) { if (native_pixel_size_ > 0.0f) {
return m_nativePixelSize; return native_pixel_size_;
} }
return 1.0f; return 1.0f;
} }
@@ -305,107 +305,107 @@ class GHOST_Window : public GHOST_IWindow {
GHOST_TSuccess releaseNativeHandles(); GHOST_TSuccess releaseNativeHandles();
/** The drawing context installed in this window. */ /** The drawing context installed in this window. */
GHOST_TDrawingContextType m_drawingContextType; GHOST_TDrawingContextType drawing_context_type_;
/** The window user data */ /** The window user data */
GHOST_TUserDataPtr m_userData; GHOST_TUserDataPtr user_data_;
/** The current visibility of the cursor */ /** The current visibility of the cursor */
bool m_cursorVisible; bool cursor_visible_;
/** The current grabbed state of the cursor */ /** The current grabbed state of the cursor */
GHOST_TGrabCursorMode m_cursorGrab; GHOST_TGrabCursorMode cursor_grab_;
/** Grab cursor axis. */ /** Grab cursor axis. */
GHOST_TAxisFlag m_cursorGrabAxis; GHOST_TAxisFlag cursor_grab_axis_;
/** Initial grab location. */ /** Initial grab location. */
int32_t m_cursorGrabInitPos[2]; int32_t cursor_grab_init_pos_[2];
/** Accumulated offset from m_cursorGrabInitPos. */ /** Accumulated offset from cursor_grab_init_pos_. */
int32_t m_cursorGrabAccumPos[2]; int32_t cursor_grab_accum_pos_[2];
/** Wrap the cursor within this region. */ /** Wrap the cursor within this region. */
GHOST_Rect m_cursorGrabBounds; GHOST_Rect cursor_grab_bounds_;
/** The current shape of the cursor */ /** The current shape of the cursor */
GHOST_TStandardCursor m_cursorShape; GHOST_TStandardCursor cursor_shape_;
/** The presence of progress indicator with the application icon */ /** The presence of progress indicator with the application icon */
bool m_progressBarVisible; bool progress_bar_visible_;
/** The acceptance of the "drop candidate" of the current drag & drop operation. */ /** The acceptance of the "drop candidate" of the current drag & drop operation. */
bool m_canAcceptDragOperation; bool can_accept_drag_operation_;
/** Modified state : are there unsaved changes */ /** Modified state : are there unsaved changes */
bool m_isUnsavedChanges; bool is_unsaved_changes_;
/** Stores whether this is a full screen window. */ /** Stores whether this is a full screen window. */
bool m_fullScreen; bool full_screen_;
/** Window Decoration Styles. */ /** Window Decoration Styles. */
GHOST_TWindowDecorationStyleFlags m_windowDecorationStyleFlags; GHOST_TWindowDecorationStyleFlags window_decoration_style_flags_;
GHOST_WindowDecorationStyleSettings m_windowDecorationStyleSettings; GHOST_WindowDecorationStyleSettings window_decoration_style_settings_;
/** The desired parameters to use when initializing the context for this window. */ /** The desired parameters to use when initializing the context for this window. */
GHOST_ContextParams m_want_context_params; GHOST_ContextParams want_context_params_;
/** Full-screen width */ /** Full-screen width */
uint32_t m_fullScreenWidth; uint32_t full_screen_width_;
/** Full-screen height */ /** Full-screen height */
uint32_t m_fullScreenHeight; uint32_t full_screen_height_;
/* OSX only, retina screens */ /* OSX only, retina screens */
float m_nativePixelSize; float native_pixel_size_;
private: private:
GHOST_Context *m_context; GHOST_Context *context_;
}; };
inline GHOST_TDrawingContextType GHOST_Window::getDrawingContextType() inline GHOST_TDrawingContextType GHOST_Window::getDrawingContextType()
{ {
return m_drawingContextType; return drawing_context_type_;
} }
inline bool GHOST_Window::getCursorVisibility() const inline bool GHOST_Window::getCursorVisibility() const
{ {
return m_cursorVisible; return cursor_visible_;
} }
inline GHOST_TGrabCursorMode GHOST_Window::getCursorGrabMode() const inline GHOST_TGrabCursorMode GHOST_Window::getCursorGrabMode() const
{ {
return m_cursorGrab; return cursor_grab_;
} }
inline bool GHOST_Window::getCursorGrabModeIsWarp() const inline bool GHOST_Window::getCursorGrabModeIsWarp() const
{ {
return (m_cursorGrab == GHOST_kGrabWrap) || (m_cursorGrab == GHOST_kGrabHide); return (cursor_grab_ == GHOST_kGrabWrap) || (cursor_grab_ == GHOST_kGrabHide);
} }
inline GHOST_TAxisFlag GHOST_Window::getCursorGrabAxis() const inline GHOST_TAxisFlag GHOST_Window::getCursorGrabAxis() const
{ {
return m_cursorGrabAxis; return cursor_grab_axis_;
} }
inline void GHOST_Window::getCursorGrabInitPos(int32_t &x, int32_t &y) const inline void GHOST_Window::getCursorGrabInitPos(int32_t &x, int32_t &y) const
{ {
x = m_cursorGrabInitPos[0]; x = cursor_grab_init_pos_[0];
y = m_cursorGrabInitPos[1]; y = cursor_grab_init_pos_[1];
} }
inline void GHOST_Window::getCursorGrabAccum(int32_t &x, int32_t &y) const inline void GHOST_Window::getCursorGrabAccum(int32_t &x, int32_t &y) const
{ {
x = m_cursorGrabAccumPos[0]; x = cursor_grab_accum_pos_[0];
y = m_cursorGrabAccumPos[1]; y = cursor_grab_accum_pos_[1];
} }
inline void GHOST_Window::setCursorGrabAccum(int32_t x, int32_t y) inline void GHOST_Window::setCursorGrabAccum(int32_t x, int32_t y)
{ {
m_cursorGrabAccumPos[0] = x; cursor_grab_accum_pos_[0] = x;
m_cursorGrabAccumPos[1] = y; cursor_grab_accum_pos_[1] = y;
} }
inline GHOST_TStandardCursor GHOST_Window::getCursorShape() const inline GHOST_TStandardCursor GHOST_Window::getCursorShape() const
{ {
return m_cursorShape; return cursor_shape_;
} }

View File

@@ -54,7 +54,7 @@ class GHOST_WindowCocoa : public GHOST_Window {
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
bool dialog, bool dialog,
GHOST_WindowCocoa *parentWindow, GHOST_WindowCocoa *parent_window,
const GHOST_GPUDevice &preferred_device); const GHOST_GPUDevice &preferred_device);
/** /**
@@ -139,10 +139,10 @@ class GHOST_WindowCocoa : public GHOST_Window {
/** /**
* Sets the window "modified" status, indicating unsaved changes * Sets the window "modified" status, indicating unsaved changes
* \param isUnsavedChanges: Unsaved changes or not. * \param is_unsaved_changes: Unsaved changes or not.
* \return Indication of success. * \return Indication of success.
*/ */
GHOST_TSuccess setModifiedState(bool isUnsavedChanges) override; GHOST_TSuccess setModifiedState(bool is_unsaved_changes) override;
/** /**
* Converts a point in screen coordinates to client rectangle coordinates * Converts a point in screen coordinates to client rectangle coordinates
@@ -217,7 +217,7 @@ class GHOST_WindowCocoa : public GHOST_Window {
GHOST_TabletData &GetCocoaTabletData() GHOST_TabletData &GetCocoaTabletData()
{ {
return m_tablet; return tablet_;
} }
/** /**
@@ -236,17 +236,17 @@ class GHOST_WindowCocoa : public GHOST_Window {
/** public function to get the window containing the view */ /** public function to get the window containing the view */
BlenderWindow *getViewWindow() const BlenderWindow *getViewWindow() const
{ {
return m_window; return window_;
}; };
/* Internal value to ensure proper redraws during animations */ /* Internal value to ensure proper redraws during animations */
void setImmediateDraw(bool value) void setImmediateDraw(bool value)
{ {
m_immediateDraw = value; immediate_draw_ = value;
} }
bool getImmediateDraw() const bool getImmediateDraw() const
{ {
return m_immediateDraw; return immediate_draw_;
} }
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
@@ -297,23 +297,23 @@ class GHOST_WindowCocoa : public GHOST_Window {
bool can_invert_color) override; bool can_invert_color) override;
/** The window containing the view */ /** The window containing the view */
BlenderWindow *m_window; BlenderWindow *window_;
/** The view, either Metal or OpenGL */ /** The view, either Metal or OpenGL */
CocoaOpenGLView *m_openGLView; CocoaOpenGLView *opengl_view_;
CocoaMetalView *m_metalView; CocoaMetalView *metal_view_;
CAMetalLayer *m_metalLayer; CAMetalLayer *metal_layer_;
/** The mother SystemCocoa class to send events */ /** The mother SystemCocoa class to send events */
GHOST_SystemCocoa *m_systemCocoa; GHOST_SystemCocoa *system_cocoa_;
NSCursor *m_customCursor; NSCursor *custom_cursor_;
GHOST_TabletData m_tablet; GHOST_TabletData tablet_;
bool m_immediateDraw; bool immediate_draw_;
bool m_is_dialog; bool is_dialog_;
GHOST_GPUDevice m_preferred_device; GHOST_GPUDevice preferred_device_;
}; };
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
@@ -331,7 +331,7 @@ class GHOST_EventIME : public GHOST_Event {
const void *customdata) const void *customdata)
: GHOST_Event(msec, type, window) : GHOST_Event(msec, type, window)
{ {
this->m_data = customdata; this->data_ = customdata;
} }
}; };

View File

@@ -51,8 +51,8 @@
@implementation BlenderWindowDelegate : NSObject @implementation BlenderWindowDelegate : NSObject
@synthesize systemCocoa = m_systemCocoa; @synthesize systemCocoa = system_cocoa_;
@synthesize windowCocoa = m_windowCocoa; @synthesize windowCocoa = window_cocoa_;
- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa - (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
windowCocoa:(GHOST_WindowCocoa *)winCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
@@ -60,8 +60,8 @@
self = [super init]; self = [super init];
if (self) { if (self) {
m_systemCocoa = sysCocoa; system_cocoa_ = sysCocoa;
m_windowCocoa = winCocoa; window_cocoa_ = winCocoa;
} }
return self; return self;
@@ -69,34 +69,34 @@
- (void)windowDidBecomeKey:(NSNotification *)notification - (void)windowDidBecomeKey:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowActivate, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowActivate, window_cocoa_);
/* Workaround for broken app-switching when combining Command-Tab and mission-control. */ /* Workaround for broken app-switching when combining Command-Tab and mission-control. */
[(NSWindow *)m_windowCocoa->getOSWindow() orderFrontRegardless]; [(NSWindow *)window_cocoa_->getOSWindow() orderFrontRegardless];
} }
- (void)windowDidResignKey:(NSNotification *)notification - (void)windowDidResignKey:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowDeactivate, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowDeactivate, window_cocoa_);
} }
- (void)windowDidExpose:(NSNotification *)notification - (void)windowDidExpose:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowUpdate, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowUpdate, window_cocoa_);
} }
- (void)windowDidMove:(NSNotification *)notification - (void)windowDidMove:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowMove, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowMove, window_cocoa_);
} }
- (void)windowWillMove:(NSNotification *)notification - (void)windowWillMove:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowMove, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowMove, window_cocoa_);
} }
- (void)windowWillEnterFullScreen:(NSNotification *)notification - (void)windowWillEnterFullScreen:(NSNotification *)notification
{ {
m_windowCocoa->setImmediateDraw(true); window_cocoa_->setImmediateDraw(true);
} }
- (void)windowDidEnterFullScreen:(NSNotification *)notification - (void)windowDidEnterFullScreen:(NSNotification *)notification
@@ -104,21 +104,21 @@
/* macOS does not send a window resize event when switching between zoomed /* macOS does not send a window resize event when switching between zoomed
* and full-screen, when automatic show/hide of dock and menu bar are enabled. * and full-screen, when automatic show/hide of dock and menu bar are enabled.
* Send our own to prevent artifacts. */ * Send our own to prevent artifacts. */
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
m_windowCocoa->setImmediateDraw(false); window_cocoa_->setImmediateDraw(false);
} }
- (void)windowWillExitFullScreen:(NSNotification *)notification - (void)windowWillExitFullScreen:(NSNotification *)notification
{ {
m_windowCocoa->setImmediateDraw(true); window_cocoa_->setImmediateDraw(true);
} }
- (void)windowDidExitFullScreen:(NSNotification *)notification - (void)windowDidExitFullScreen:(NSNotification *)notification
{ {
/* See comment for windowWillEnterFullScreen. */ /* See comment for windowWillEnterFullScreen. */
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
m_windowCocoa->setImmediateDraw(false); window_cocoa_->setImmediateDraw(false);
} }
- (void)windowDidResize:(NSNotification *)notification - (void)windowDidResize:(NSNotification *)notification
@@ -128,25 +128,25 @@
#endif #endif
{ {
/* Send event only once, at end of resize operation (when user has released mouse button). */ /* Send event only once, at end of resize operation (when user has released mouse button). */
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
} }
/* Live resize, send event, gets handled in wm_window.c. /* Live resize, send event, gets handled in wm_window.c.
* Needed because live resize runs in a modal loop, not letting main loop run */ * Needed because live resize runs in a modal loop, not letting main loop run */
if ([[notification object] inLiveResize]) { if ([[notification object] inLiveResize]) {
m_systemCocoa->dispatchEvents(); system_cocoa_->dispatchEvents();
} }
} }
- (void)windowDidChangeBackingProperties:(NSNotification *)notification - (void)windowDidChangeBackingProperties:(NSNotification *)notification
{ {
m_systemCocoa->handleWindowEvent(GHOST_kEventNativeResolutionChange, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventNativeResolutionChange, window_cocoa_);
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowSize, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowSize, window_cocoa_);
} }
- (BOOL)windowShouldClose:(id)sender; - (BOOL)windowShouldClose:(id)sender;
{ {
/* Let Blender close the window rather than closing immediately. */ /* Let Blender close the window rather than closing immediately. */
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowClose, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowClose, window_cocoa_);
return false; return false;
} }
@@ -169,9 +169,9 @@
@implementation BlenderWindow @implementation BlenderWindow
@synthesize systemCocoa = m_systemCocoa; @synthesize systemCocoa = system_cocoa_;
@synthesize windowCocoa = m_windowCocoa; @synthesize windowCocoa = window_cocoa_;
@synthesize draggedObjectType = m_draggedObjectType; @synthesize draggedObjectType = dragged_object_type_;
- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa - (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
windowCocoa:(GHOST_WindowCocoa *)winCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
@@ -186,8 +186,8 @@
defer:flag]; defer:flag];
if (self) { if (self) {
m_systemCocoa = sysCocoa; system_cocoa_ = sysCocoa;
m_windowCocoa = winCocoa; window_cocoa_ = winCocoa;
} }
return self; return self;
@@ -196,7 +196,7 @@
- (BOOL)canBecomeKeyWindow - (BOOL)canBecomeKeyWindow
{ {
/* Don't make other windows active when a dialog window is open. */ /* Don't make other windows active when a dialog window is open. */
return (m_windowCocoa->isDialog() || !m_systemCocoa->hasDialogWindow()); return (window_cocoa_->isDialog() || !system_cocoa_->hasDialogWindow());
} }
/* The drag & drop dragging destination methods. */ /* The drag & drop dragging destination methods. */
@@ -205,23 +205,23 @@
@autoreleasepool { @autoreleasepool {
NSPasteboard *draggingPBoard = sender.draggingPasteboard; NSPasteboard *draggingPBoard = sender.draggingPasteboard;
if ([[draggingPBoard types] containsObject:NSPasteboardTypeTIFF]) { if ([[draggingPBoard types] containsObject:NSPasteboardTypeTIFF]) {
m_draggedObjectType = GHOST_kDragnDropTypeBitmap; dragged_object_type_ = GHOST_kDragnDropTypeBitmap;
} }
else if ([[draggingPBoard types] containsObject:NSFilenamesPboardType]) { else if ([[draggingPBoard types] containsObject:NSFilenamesPboardType]) {
m_draggedObjectType = GHOST_kDragnDropTypeFilenames; dragged_object_type_ = GHOST_kDragnDropTypeFilenames;
} }
else if ([[draggingPBoard types] containsObject:NSPasteboardTypeString]) { else if ([[draggingPBoard types] containsObject:NSPasteboardTypeString]) {
m_draggedObjectType = GHOST_kDragnDropTypeString; dragged_object_type_ = GHOST_kDragnDropTypeString;
} }
else { else {
return NSDragOperationNone; return NSDragOperationNone;
} }
const NSPoint mouseLocation = sender.draggingLocation; const NSPoint mouseLocation = sender.draggingLocation;
m_windowCocoa->setAcceptDragOperation(TRUE); /* Drag operation is accepted by default. */ window_cocoa_->setAcceptDragOperation(TRUE); /* Drag operation is accepted by default. */
m_systemCocoa->handleDraggingEvent(GHOST_kEventDraggingEntered, system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingEntered,
m_draggedObjectType, dragged_object_type_,
m_windowCocoa, window_cocoa_,
mouseLocation.x, mouseLocation.x,
mouseLocation.y, mouseLocation.y,
nil); nil);
@@ -238,25 +238,25 @@
{ {
const NSPoint mouseLocation = [sender draggingLocation]; const NSPoint mouseLocation = [sender draggingLocation];
m_systemCocoa->handleDraggingEvent(GHOST_kEventDraggingUpdated, system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingUpdated,
m_draggedObjectType, dragged_object_type_,
m_windowCocoa, window_cocoa_,
mouseLocation.x, mouseLocation.x,
mouseLocation.y, mouseLocation.y,
nil); nil);
return m_windowCocoa->canAcceptDragOperation() ? NSDragOperationCopy : NSDragOperationNone; return window_cocoa_->canAcceptDragOperation() ? NSDragOperationCopy : NSDragOperationNone;
} }
- (void)draggingExited:(id<NSDraggingInfo>)sender - (void)draggingExited:(id<NSDraggingInfo>)sender
{ {
m_systemCocoa->handleDraggingEvent( system_cocoa_->handleDraggingEvent(
GHOST_kEventDraggingExited, m_draggedObjectType, m_windowCocoa, 0, 0, nil); GHOST_kEventDraggingExited, dragged_object_type_, window_cocoa_, 0, 0, nil);
m_draggedObjectType = GHOST_kDragnDropTypeUnknown; dragged_object_type_ = GHOST_kDragnDropTypeUnknown;
} }
- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender
{ {
if (m_windowCocoa->canAcceptDragOperation()) { if (window_cocoa_->canAcceptDragOperation()) {
return YES; return YES;
} }
return NO; return NO;
@@ -268,7 +268,7 @@
NSPasteboard *draggingPBoard = sender.draggingPasteboard; NSPasteboard *draggingPBoard = sender.draggingPasteboard;
id data; id data;
switch (m_draggedObjectType) { switch (dragged_object_type_) {
case GHOST_kDragnDropTypeBitmap: { case GHOST_kDragnDropTypeBitmap: {
if (![NSImage canInitWithPasteboard:draggingPBoard]) { if (![NSImage canInitWithPasteboard:draggingPBoard]) {
return NO; return NO;
@@ -290,9 +290,9 @@
} }
const NSPoint mouseLocation = sender.draggingLocation; const NSPoint mouseLocation = sender.draggingLocation;
m_systemCocoa->handleDraggingEvent(GHOST_kEventDraggingDropDone, system_cocoa_->handleDraggingEvent(GHOST_kEventDraggingDropDone,
m_draggedObjectType, dragged_object_type_,
m_windowCocoa, window_cocoa_,
mouseLocation.x, mouseLocation.x,
mouseLocation.y, mouseLocation.y,
(void *)data); (void *)data);
@@ -329,19 +329,19 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
bool is_dialog, bool is_dialog,
GHOST_WindowCocoa *parentWindow, GHOST_WindowCocoa *parent_window,
const GHOST_GPUDevice &preferred_device) const GHOST_GPUDevice &preferred_device)
: GHOST_Window(width, height, state, context_params, false), : GHOST_Window(width, height, state, context_params, false),
m_openGLView(nil), opengl_view_(nil),
m_metalView(nil), metal_view_(nil),
m_metalLayer(nil), metal_layer_(nil),
m_systemCocoa(systemCocoa), system_cocoa_(systemCocoa),
m_customCursor(nullptr), custom_cursor_(nullptr),
m_immediateDraw(false), immediate_draw_(false),
m_is_dialog(is_dialog), is_dialog_(is_dialog),
m_preferred_device(preferred_device) preferred_device_(preferred_device)
{ {
m_fullScreen = false; full_screen_ = false;
@autoreleasepool { @autoreleasepool {
/* Create the window. */ /* Create the window. */
@@ -357,21 +357,21 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
styleMask |= NSWindowStyleMaskMiniaturizable; styleMask |= NSWindowStyleMaskMiniaturizable;
} }
m_window = [[BlenderWindow alloc] initWithSystemCocoa:systemCocoa window_ = [[BlenderWindow alloc] initWithSystemCocoa:systemCocoa
windowCocoa:this windowCocoa:this
contentRect:rect contentRect:rect
styleMask:styleMask styleMask:styleMask
backing:NSBackingStoreBuffered backing:NSBackingStoreBuffered
defer:NO]; defer:NO];
/* By default, AppKit repositions the window in the context of the current "mainMonitor" /* By default, AppKit repositions the window in the context of the current "mainMonitor"
* (the monitor which has focus), bypass this by forcing the window back into its correct * (the monitor which has focus), bypass this by forcing the window back into its correct
* position. Since we use global screen coordinate indexed on the first, primary screen. * position. Since we use global screen coordinate indexed on the first, primary screen.
*/ */
[m_window setFrameOrigin:NSMakePoint(left, bottom)]; [window_ setFrameOrigin:NSMakePoint(left, bottom)];
/* Forbid to resize the window below the blender defined minimum one. */ /* Forbid to resize the window below the blender defined minimum one. */
const NSSize minSize = {320, 240}; const NSSize minSize = {320, 240};
m_window.contentMinSize = minSize; window_.contentMinSize = minSize;
/* Create NSView inside the window. */ /* Create NSView inside the window. */
id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice(); id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice();
@@ -379,14 +379,14 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
if (metalDevice) { if (metalDevice) {
/* Create metal layer and view if supported. */ /* Create metal layer and view if supported. */
m_metalLayer = [[CAMetalLayer alloc] init]; metal_layer_ = [[CAMetalLayer alloc] init];
m_metalLayer.edgeAntialiasingMask = 0; metal_layer_.edgeAntialiasingMask = 0;
m_metalLayer.masksToBounds = NO; metal_layer_.masksToBounds = NO;
m_metalLayer.opaque = YES; metal_layer_.opaque = YES;
m_metalLayer.framebufferOnly = YES; metal_layer_.framebufferOnly = YES;
m_metalLayer.presentsWithTransaction = NO; metal_layer_.presentsWithTransaction = NO;
[m_metalLayer removeAllAnimations]; [metal_layer_ removeAllAnimations];
m_metalLayer.device = metalDevice; metal_layer_.device = metalDevice;
if (type == GHOST_kDrawingContextTypeMetal) { if (type == GHOST_kDrawingContextTypeMetal) {
/* Enable EDR support. This is done by: /* Enable EDR support. This is done by:
@@ -395,30 +395,30 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
* 3. Setting the extended sRGB color space so that the OS knows how to interpret the * 3. Setting the extended sRGB color space so that the OS knows how to interpret the
* values. * values.
*/ */
m_metalLayer.wantsExtendedDynamicRangeContent = YES; metal_layer_.wantsExtendedDynamicRangeContent = YES;
m_metalLayer.pixelFormat = MTLPixelFormatRGBA16Float; metal_layer_.pixelFormat = MTLPixelFormatRGBA16Float;
const CFStringRef name = kCGColorSpaceExtendedSRGB; const CFStringRef name = kCGColorSpaceExtendedSRGB;
CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name); CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(name);
m_metalLayer.colorspace = colorspace; metal_layer_.colorspace = colorspace;
CGColorSpaceRelease(colorspace); CGColorSpaceRelease(colorspace);
} }
m_metalView = [[CocoaMetalView alloc] initWithSystemCocoa:systemCocoa metal_view_ = [[CocoaMetalView alloc] initWithSystemCocoa:systemCocoa
windowCocoa:this windowCocoa:this
frame:rect]; frame:rect];
m_metalView.wantsLayer = YES; metal_view_.wantsLayer = YES;
m_metalView.layer = m_metalLayer; metal_view_.layer = metal_layer_;
view = m_metalView; view = metal_view_;
} }
else { else {
/* Fall back to OpenGL view if there is no Metal support. */ /* Fall back to OpenGL view if there is no Metal support. */
m_openGLView = [[CocoaOpenGLView alloc] initWithSystemCocoa:systemCocoa opengl_view_ = [[CocoaOpenGLView alloc] initWithSystemCocoa:systemCocoa
windowCocoa:this windowCocoa:this
frame:rect]; frame:rect];
view = m_openGLView; view = opengl_view_;
} }
if (m_systemCocoa->m_nativePixel) { if (system_cocoa_->native_pixel_) {
/* Needs to happen early when building with the 10.14 SDK, otherwise /* Needs to happen early when building with the 10.14 SDK, otherwise
* has no effect until resizing the window. */ * has no effect until resizing the window. */
if ([view respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) { if ([view respondsToSelector:@selector(setWantsBestResolutionOpenGLSurface:)]) {
@@ -426,10 +426,10 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
} }
} }
m_window.contentView = view; window_.contentView = view;
m_window.initialFirstResponder = view; window_.initialFirstResponder = view;
[m_window makeKeyAndOrderFront:nil]; [window_ makeKeyAndOrderFront:nil];
setDrawingContextType(type); setDrawingContextType(type);
updateDrawingContext(); updateDrawingContext();
@@ -437,29 +437,29 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
setTitle(title); setTitle(title);
m_tablet = GHOST_TABLET_DATA_NONE; tablet_ = GHOST_TABLET_DATA_NONE;
BlenderWindowDelegate *windowDelegate = [[BlenderWindowDelegate alloc] BlenderWindowDelegate *windowDelegate = [[BlenderWindowDelegate alloc]
initWithSystemCocoa:systemCocoa initWithSystemCocoa:systemCocoa
windowCocoa:this]; windowCocoa:this];
m_window.delegate = windowDelegate; window_.delegate = windowDelegate;
m_window.acceptsMouseMovedEvents = YES; window_.acceptsMouseMovedEvents = YES;
NSView *contentview = m_window.contentView; NSView *contentview = window_.contentView;
contentview.allowedTouchTypes = (NSTouchTypeMaskDirect | NSTouchTypeMaskIndirect); contentview.allowedTouchTypes = (NSTouchTypeMaskDirect | NSTouchTypeMaskIndirect);
[m_window registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, [window_ registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType,
NSPasteboardTypeString, NSPasteboardTypeString,
NSPasteboardTypeTIFF, NSPasteboardTypeTIFF,
nil]]; nil]];
if (is_dialog && parentWindow) { if (is_dialog && parent_window) {
[parentWindow->getViewWindow() addChildWindow:m_window ordered:NSWindowAbove]; [parent_window->getViewWindow() addChildWindow:window_ ordered:NSWindowAbove];
m_window.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary; window_.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary;
} }
else { else {
m_window.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; window_.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary;
} }
if (state == GHOST_kWindowStateFullScreen) { if (state == GHOST_kWindowStateFullScreen) {
@@ -473,40 +473,40 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(GHOST_SystemCocoa *systemCocoa,
GHOST_WindowCocoa::~GHOST_WindowCocoa() GHOST_WindowCocoa::~GHOST_WindowCocoa()
{ {
@autoreleasepool { @autoreleasepool {
if (m_customCursor) { if (custom_cursor_) {
[m_customCursor release]; [custom_cursor_ release];
m_customCursor = nil; custom_cursor_ = nil;
} }
releaseNativeHandles(); releaseNativeHandles();
if (m_openGLView) { if (opengl_view_) {
[m_openGLView release]; [opengl_view_ release];
m_openGLView = nil; opengl_view_ = nil;
} }
if (m_metalView) { if (metal_view_) {
[m_metalView release]; [metal_view_ release];
m_metalView = nil; metal_view_ = nil;
} }
if (m_metalLayer) { if (metal_layer_) {
[m_metalLayer release]; [metal_layer_ release];
m_metalLayer = nil; metal_layer_ = nil;
} }
if (m_window) { if (window_) {
[m_window close]; [window_ close];
} }
/* Check for other blender opened windows and make the front-most key /* Check for other blender opened windows and make the front-most key
* NOTE: for some reason the closed window is still in the list. */ * NOTE: for some reason the closed window is still in the list. */
NSArray *windowsList = [NSApp orderedWindows]; NSArray *windowsList = [NSApp orderedWindows];
for (int a = 0; a < [windowsList count]; a++) { for (int a = 0; a < [windowsList count]; a++) {
if (m_window != (BlenderWindow *)[windowsList objectAtIndex:a]) { if (window_ != (BlenderWindow *)[windowsList objectAtIndex:a]) {
[[windowsList objectAtIndex:a] makeKeyWindow]; [[windowsList objectAtIndex:a] makeKeyWindow];
break; break;
} }
} }
m_window = nil; window_ = nil;
} }
} }
@@ -516,13 +516,13 @@ GHOST_WindowCocoa::~GHOST_WindowCocoa()
bool GHOST_WindowCocoa::getValid() const bool GHOST_WindowCocoa::getValid() const
{ {
NSView *view = (m_openGLView) ? m_openGLView : m_metalView; NSView *view = (opengl_view_) ? opengl_view_ : metal_view_;
return GHOST_Window::getValid() && m_window != nullptr && view != nullptr; return GHOST_Window::getValid() && window_ != nullptr && view != nullptr;
} }
void *GHOST_WindowCocoa::getOSWindow() const void *GHOST_WindowCocoa::getOSWindow() const
{ {
return (void *)m_window; return (void *)window_;
} }
void GHOST_WindowCocoa::setTitle(const char *title) void GHOST_WindowCocoa::setTitle(const char *title)
@@ -531,7 +531,7 @@ void GHOST_WindowCocoa::setTitle(const char *title)
@autoreleasepool { @autoreleasepool {
NSString *windowTitle = [[NSString alloc] initWithCString:title encoding:NSUTF8StringEncoding]; NSString *windowTitle = [[NSString alloc] initWithCString:title encoding:NSUTF8StringEncoding];
m_window.title = windowTitle; window_.title = windowTitle;
[windowTitle release]; [windowTitle release];
} }
@@ -543,7 +543,7 @@ std::string GHOST_WindowCocoa::getTitle() const
std::string title; std::string title;
@autoreleasepool { @autoreleasepool {
NSString *windowTitle = m_window.title; NSString *windowTitle = window_.title;
if (windowTitle != nil) { if (windowTitle != nil) {
title = windowTitle.UTF8String; title = windowTitle.UTF8String;
} }
@@ -560,7 +560,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setPath(const char *filepath)
encoding:NSUTF8StringEncoding] encoding:NSUTF8StringEncoding]
autorelease]; autorelease];
m_window.representedFilename = associatedFileName; window_.representedFilename = associatedFileName;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -569,14 +569,14 @@ GHOST_TSuccess GHOST_WindowCocoa::setPath(const char *filepath)
GHOST_TSuccess GHOST_WindowCocoa::applyWindowDecorationStyle() GHOST_TSuccess GHOST_WindowCocoa::applyWindowDecorationStyle()
{ {
@autoreleasepool { @autoreleasepool {
if (m_windowDecorationStyleFlags & GHOST_kDecorationColoredTitleBar) { if (window_decoration_style_flags_ & GHOST_kDecorationColoredTitleBar) {
const float *background_color = m_windowDecorationStyleSettings.colored_titlebar_bg_color; const float *background_color = window_decoration_style_settings_.colored_titlebar_bg_color;
/* Title-bar background color. */ /* Title-bar background color. */
m_window.backgroundColor = [NSColor colorWithRed:background_color[0] window_.backgroundColor = [NSColor colorWithRed:background_color[0]
green:background_color[1] green:background_color[1]
blue:background_color[2] blue:background_color[2]
alpha:1.0]; alpha:1.0];
/* Title-bar foreground color. /* Title-bar foreground color.
* Use the value component of the title-bar background's HSV representation to determine * Use the value component of the title-bar background's HSV representation to determine
@@ -588,11 +588,11 @@ GHOST_TSuccess GHOST_WindowCocoa::applyWindowDecorationStyle()
const NSAppearanceName win_appearance = hsv_v > 0.5 ? NSAppearanceNameVibrantLight : const NSAppearanceName win_appearance = hsv_v > 0.5 ? NSAppearanceNameVibrantLight :
NSAppearanceNameVibrantDark; NSAppearanceNameVibrantDark;
m_window.appearance = [NSAppearance appearanceNamed:win_appearance]; window_.appearance = [NSAppearance appearanceNamed:win_appearance];
m_window.titlebarAppearsTransparent = YES; window_.titlebarAppearsTransparent = YES;
} }
else { else {
m_window.titlebarAppearsTransparent = NO; window_.titlebarAppearsTransparent = NO;
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -605,7 +605,7 @@ void GHOST_WindowCocoa::getWindowBounds(GHOST_Rect &bounds) const
@autoreleasepool { @autoreleasepool {
/* All coordinates are based off the primary screen. */ /* All coordinates are based off the primary screen. */
const NSRect screenFrame = [getPrimaryScreen() visibleFrame]; const NSRect screenFrame = [getPrimaryScreen() visibleFrame];
const NSRect windowFrame = m_window.frame; const NSRect windowFrame = window_.frame;
/* Flip the Y axis, from bottom left coordinate to top left, which is the expected coordinate /* Flip the Y axis, from bottom left coordinate to top left, which is the expected coordinate
* return format for GHOST, even though the Window Manager later reflips it to bottom-left * return format for GHOST, even though the Window Manager later reflips it to bottom-left
@@ -616,11 +616,11 @@ void GHOST_WindowCocoa::getWindowBounds(GHOST_Rect &bounds) const
/* Flip the coordinates vertically from a bottom-left origin to a top-left origin, /* Flip the coordinates vertically from a bottom-left origin to a top-left origin,
* as expected by GHOST. */ * as expected by GHOST. */
bounds.m_b = screenMaxY - windowFrame.origin.y; bounds.b_ = screenMaxY - windowFrame.origin.y;
bounds.m_t = screenMaxY - windowFrame.origin.y - windowFrame.size.height; bounds.t_ = screenMaxY - windowFrame.origin.y - windowFrame.size.height;
bounds.m_l = windowFrame.origin.x; bounds.l_ = windowFrame.origin.x;
bounds.m_r = windowFrame.origin.x + windowFrame.size.width; bounds.r_ = windowFrame.origin.x + windowFrame.size.width;
} }
} }
@@ -633,21 +633,21 @@ void GHOST_WindowCocoa::getClientBounds(GHOST_Rect &bounds) const
const NSRect screenFrame = [getPrimaryScreen() visibleFrame]; const NSRect screenFrame = [getPrimaryScreen() visibleFrame];
/* Screen Content Rectangle (excluding Menu Bar and Dock). */ /* Screen Content Rectangle (excluding Menu Bar and Dock). */
const NSRect screenContentRect = [NSWindow contentRectForFrameRect:screenFrame const NSRect screenContentRect = [NSWindow contentRectForFrameRect:screenFrame
styleMask:[m_window styleMask]]; styleMask:[window_ styleMask]];
const NSRect windowFrame = m_window.frame; const NSRect windowFrame = window_.frame;
/* Window Content Rectangle (excluding Titlebar and borders) */ /* Window Content Rectangle (excluding Titlebar and borders) */
const NSRect windowContentRect = [m_window contentRectForFrameRect:windowFrame]; const NSRect windowContentRect = [window_ contentRectForFrameRect:windowFrame];
const int32_t screenMaxY = screenContentRect.origin.y + screenContentRect.size.height; const int32_t screenMaxY = screenContentRect.origin.y + screenContentRect.size.height;
/* Flip the coordinates vertically from a bottom-left origin to a top-left origin, /* Flip the coordinates vertically from a bottom-left origin to a top-left origin,
* as expected by GHOST. */ * as expected by GHOST. */
bounds.m_b = screenMaxY - windowContentRect.origin.y; bounds.b_ = screenMaxY - windowContentRect.origin.y;
bounds.m_t = screenMaxY - windowContentRect.origin.y - windowContentRect.size.height; bounds.t_ = screenMaxY - windowContentRect.origin.y - windowContentRect.size.height;
bounds.m_l = windowContentRect.origin.x; bounds.l_ = windowContentRect.origin.x;
bounds.m_r = windowContentRect.origin.x + windowContentRect.size.width; bounds.r_ = windowContentRect.origin.x + windowContentRect.size.width;
} }
} }
@@ -661,7 +661,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientWidth(uint32_t width)
if ((uint32_t(cBnds.getWidth())) != width) { if ((uint32_t(cBnds.getWidth())) != width) {
const NSSize size = {(CGFloat)width, (CGFloat)cBnds.getHeight()}; const NSSize size = {(CGFloat)width, (CGFloat)cBnds.getHeight()};
[m_window setContentSize:size]; [window_ setContentSize:size];
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -677,7 +677,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientHeight(uint32_t height)
if ((uint32_t(cBnds.getHeight())) != height) { if ((uint32_t(cBnds.getHeight())) != height) {
const NSSize size = {(CGFloat)cBnds.getWidth(), (CGFloat)height}; const NSSize size = {(CGFloat)cBnds.getWidth(), (CGFloat)height};
[m_window setContentSize:size]; [window_ setContentSize:size];
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -692,7 +692,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setClientSize(uint32_t width, uint32_t height)
getClientBounds(cBnds); getClientBounds(cBnds);
if (((uint32_t(cBnds.getWidth())) != width) || ((uint32_t(cBnds.getHeight())) != height)) { if (((uint32_t(cBnds.getWidth())) != width) || ((uint32_t(cBnds.getHeight())) != height)) {
const NSSize size = {(CGFloat)width, (CGFloat)height}; const NSSize size = {(CGFloat)width, (CGFloat)height};
[m_window setContentSize:size]; [window_ setContentSize:size];
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -703,22 +703,22 @@ GHOST_TWindowState GHOST_WindowCocoa::getState() const
GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid"); GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::getState(): window invalid");
@autoreleasepool { @autoreleasepool {
NSUInteger masks = m_window.styleMask; NSUInteger masks = window_.styleMask;
if (masks & NSWindowStyleMaskFullScreen) { if (masks & NSWindowStyleMaskFullScreen) {
/* Lion style full-screen. */ /* Lion style full-screen. */
if (!m_immediateDraw) { if (!immediate_draw_) {
return GHOST_kWindowStateFullScreen; return GHOST_kWindowStateFullScreen;
} }
return GHOST_kWindowStateNormal; return GHOST_kWindowStateNormal;
} }
if (m_window.isMiniaturized) { if (window_.isMiniaturized) {
return GHOST_kWindowStateMinimized; return GHOST_kWindowStateMinimized;
} }
if (m_window.isZoomed) { if (window_.isZoomed) {
return GHOST_kWindowStateMaximized; return GHOST_kWindowStateMaximized;
} }
if (m_immediateDraw) { if (immediate_draw_) {
return GHOST_kWindowStateFullScreen; return GHOST_kWindowStateFullScreen;
} }
return GHOST_kWindowStateNormal; return GHOST_kWindowStateNormal;
@@ -763,7 +763,7 @@ void GHOST_WindowCocoa::screenToClientIntern(int32_t inX,
NSRect screenCoord; NSRect screenCoord;
screenCoord.origin = {(CGFloat)inX, (CGFloat)inY}; screenCoord.origin = {(CGFloat)inX, (CGFloat)inY};
const NSRect baseCoord = [m_window convertRectFromScreen:screenCoord]; const NSRect baseCoord = [window_ convertRectFromScreen:screenCoord];
outX = baseCoord.origin.x; outX = baseCoord.origin.x;
outY = baseCoord.origin.y; outY = baseCoord.origin.y;
@@ -777,7 +777,7 @@ void GHOST_WindowCocoa::clientToScreenIntern(int32_t inX,
NSRect baseCoord; NSRect baseCoord;
baseCoord.origin = {(CGFloat)inX, (CGFloat)inY}; baseCoord.origin = {(CGFloat)inX, (CGFloat)inY};
const NSRect screenCoord = [m_window convertRectToScreen:baseCoord]; const NSRect screenCoord = [window_ convertRectToScreen:baseCoord];
outX = screenCoord.origin.x; outX = screenCoord.origin.x;
outY = screenCoord.origin.y; outY = screenCoord.origin.y;
@@ -785,7 +785,7 @@ void GHOST_WindowCocoa::clientToScreenIntern(int32_t inX,
NSScreen *GHOST_WindowCocoa::getScreen() const NSScreen *GHOST_WindowCocoa::getScreen() const
{ {
return m_window.screen; return window_.screen;
} }
NSScreen *GHOST_WindowCocoa::getPrimaryScreen() NSScreen *GHOST_WindowCocoa::getPrimaryScreen()
@@ -797,13 +797,13 @@ NSScreen *GHOST_WindowCocoa::getPrimaryScreen()
/* called for event, when window leaves monitor to another */ /* called for event, when window leaves monitor to another */
void GHOST_WindowCocoa::setNativePixelSize() void GHOST_WindowCocoa::setNativePixelSize()
{ {
NSView *view = (m_openGLView) ? m_openGLView : m_metalView; NSView *view = (opengl_view_) ? opengl_view_ : metal_view_;
const NSRect backingBounds = [view convertRectToBacking:[view bounds]]; const NSRect backingBounds = [view convertRectToBacking:[view bounds]];
GHOST_Rect rect; GHOST_Rect rect;
getClientBounds(rect); getClientBounds(rect);
m_nativePixelSize = float(backingBounds.size.width) / float(rect.getWidth()); native_pixel_size_ = float(backingBounds.size.width) / float(rect.getWidth());
} }
/** /**
@@ -820,34 +820,34 @@ GHOST_TSuccess GHOST_WindowCocoa::setState(GHOST_TWindowState state)
@autoreleasepool { @autoreleasepool {
switch (state) { switch (state) {
case GHOST_kWindowStateMinimized: case GHOST_kWindowStateMinimized:
[m_window miniaturize:nil]; [window_ miniaturize:nil];
break; break;
case GHOST_kWindowStateMaximized: case GHOST_kWindowStateMaximized:
[m_window zoom:nil]; [window_ zoom:nil];
break; break;
case GHOST_kWindowStateFullScreen: { case GHOST_kWindowStateFullScreen: {
const NSUInteger masks = m_window.styleMask; const NSUInteger masks = window_.styleMask;
if (!(masks & NSWindowStyleMaskFullScreen)) { if (!(masks & NSWindowStyleMaskFullScreen)) {
[m_window toggleFullScreen:nil]; [window_ toggleFullScreen:nil];
} }
break; break;
} }
case GHOST_kWindowStateNormal: case GHOST_kWindowStateNormal:
default: default:
@autoreleasepool { @autoreleasepool {
const NSUInteger masks = m_window.styleMask; const NSUInteger masks = window_.styleMask;
if (masks & NSWindowStyleMaskFullScreen) { if (masks & NSWindowStyleMaskFullScreen) {
/* Lion style full-screen. */ /* Lion style full-screen. */
[m_window toggleFullScreen:nil]; [window_ toggleFullScreen:nil];
} }
else if (m_window.isMiniaturized) { else if (window_.isMiniaturized) {
[m_window deminiaturize:nil]; [window_ deminiaturize:nil];
} }
else if (m_window.isZoomed) { else if (window_.isZoomed) {
[m_window zoom:nil]; [window_ zoom:nil];
} }
} }
break; break;
@@ -856,12 +856,12 @@ GHOST_TSuccess GHOST_WindowCocoa::setState(GHOST_TWindowState state)
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_WindowCocoa::setModifiedState(bool isUnsavedChanges) GHOST_TSuccess GHOST_WindowCocoa::setModifiedState(bool is_unsaved_changes)
{ {
@autoreleasepool { @autoreleasepool {
m_window.documentEdited = isUnsavedChanges; window_.documentEdited = is_unsaved_changes;
} }
return GHOST_Window::setModifiedState(isUnsavedChanges); return GHOST_Window::setModifiedState(is_unsaved_changes);
} }
GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order) GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order)
@@ -871,12 +871,12 @@ GHOST_TSuccess GHOST_WindowCocoa::setOrder(GHOST_TWindowOrder order)
@autoreleasepool { @autoreleasepool {
if (order == GHOST_kWindowOrderTop) { if (order == GHOST_kWindowOrderTop) {
[NSApp activateIgnoringOtherApps:YES]; [NSApp activateIgnoringOtherApps:YES];
[m_window makeKeyAndOrderFront:nil]; [window_ makeKeyAndOrderFront:nil];
} }
else { else {
NSArray *windowsList; NSArray *windowsList;
[m_window orderBack:nil]; [window_ orderBack:nil];
/* Check for other blender opened windows and make the front-most key. */ /* Check for other blender opened windows and make the front-most key. */
windowsList = [NSApp orderedWindows]; windowsList = [NSApp orderedWindows];
@@ -898,7 +898,7 @@ GHOST_Context *GHOST_WindowCocoa::newDrawingContext(GHOST_TDrawingContextType ty
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
m_want_context_params, m_metalLayer, 1, 2, true, m_preferred_device); want_context_params_, metal_layer_, 1, 2, true, preferred_device_);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -910,7 +910,7 @@ GHOST_Context *GHOST_WindowCocoa::newDrawingContext(GHOST_TDrawingContextType ty
#ifdef WITH_METAL_BACKEND #ifdef WITH_METAL_BACKEND
case GHOST_kDrawingContextTypeMetal: { case GHOST_kDrawingContextTypeMetal: {
GHOST_Context *context = new GHOST_ContextMTL( GHOST_Context *context = new GHOST_ContextMTL(
m_want_context_params, m_metalView, m_metalLayer); want_context_params_, metal_view_, metal_layer_);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -934,7 +934,7 @@ GHOST_TSuccess GHOST_WindowCocoa::invalidate()
GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid"); GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::invalidate(): window invalid");
@autoreleasepool { @autoreleasepool {
NSView *view = (m_openGLView) ? m_openGLView : m_metalView; NSView *view = (opengl_view_) ? opengl_view_ : metal_view_;
view.needsDisplay = YES; view.needsDisplay = YES;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -976,7 +976,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setProgressBar(float progress)
[NSApp setApplicationIconImage:dockIcon]; [NSApp setApplicationIconImage:dockIcon];
[dockIcon release]; [dockIcon release];
m_progressBarVisible = true; progress_bar_visible_ = true;
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -984,10 +984,10 @@ GHOST_TSuccess GHOST_WindowCocoa::setProgressBar(float progress)
GHOST_TSuccess GHOST_WindowCocoa::endProgressBar() GHOST_TSuccess GHOST_WindowCocoa::endProgressBar()
{ {
if (!m_progressBarVisible) { if (!progress_bar_visible_) {
return GHOST_kFailure; return GHOST_kFailure;
} }
m_progressBarVisible = false; progress_bar_visible_ = false;
/* Reset application icon to remove the progress bar. */ /* Reset application icon to remove the progress bar. */
@autoreleasepool { @autoreleasepool {
@@ -1040,8 +1040,8 @@ NSCursor *GHOST_WindowCocoa::getStandardCursor(GHOST_TStandardCursor shape) cons
@autoreleasepool { @autoreleasepool {
switch (shape) { switch (shape) {
case GHOST_kStandardCursorCustom: case GHOST_kStandardCursorCustom:
if (m_customCursor) { if (custom_cursor_) {
return m_customCursor; return custom_cursor_;
} }
else { else {
return nullptr; return nullptr;
@@ -1158,13 +1158,13 @@ void GHOST_WindowCocoa::loadCursor(bool visible, GHOST_TStandardCursor shape) co
bool GHOST_WindowCocoa::isDialog() const bool GHOST_WindowCocoa::isDialog() const
{ {
return m_is_dialog; return is_dialog_;
} }
GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorVisibility(bool visible) GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorVisibility(bool visible)
{ {
@autoreleasepool { @autoreleasepool {
if (m_window.isVisible) { if (window_.isVisible) {
loadCursor(visible, getCursorShape()); loadCursor(visible, getCursorShape());
} }
} }
@@ -1178,7 +1178,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode
/* No need to perform grab without warp as it is always enabled in OS X. */ /* No need to perform grab without warp as it is always enabled in OS X. */
if (mode != GHOST_kGrabNormal) { if (mode != GHOST_kGrabNormal) {
@autoreleasepool { @autoreleasepool {
m_systemCocoa->getCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]); system_cocoa_->getCursorPosition(cursor_grab_init_pos_[0], cursor_grab_init_pos_[1]);
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
if (mode == GHOST_kGrabHide) { if (mode == GHOST_kGrabHide) {
@@ -1186,20 +1186,20 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode
} }
/* Make window key if it wasn't to get the mouse move events. */ /* Make window key if it wasn't to get the mouse move events. */
[m_window makeKeyWindow]; [window_ makeKeyWindow];
} }
} }
} }
else { else {
if (m_cursorGrab == GHOST_kGrabHide) { if (cursor_grab_ == GHOST_kGrabHide) {
m_systemCocoa->setCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]); system_cocoa_->setCursorPosition(cursor_grab_init_pos_[0], cursor_grab_init_pos_[1]);
setWindowCursorVisibility(true); setWindowCursorVisibility(true);
} }
/* Almost works without but important otherwise the mouse GHOST location /* Almost works without but important otherwise the mouse GHOST location
* can be incorrect on exit. */ * can be incorrect on exit. */
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; /* disable */ cursor_grab_bounds_.l_ = cursor_grab_bounds_.r_ = -1; /* disable */
} }
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -1208,7 +1208,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode
GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorShape(GHOST_TStandardCursor shape) GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorShape(GHOST_TStandardCursor shape)
{ {
@autoreleasepool { @autoreleasepool {
if (m_window.isVisible) { if (window_.isVisible) {
loadCursor(getCursorVisibility(), shape); loadCursor(getCursorVisibility(), shape);
} }
} }
@@ -1251,9 +1251,9 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(const uint8_t *bitm
const bool can_invert_color) const bool can_invert_color)
{ {
@autoreleasepool { @autoreleasepool {
if (m_customCursor) { if (custom_cursor_) {
[m_customCursor release]; [custom_cursor_ release];
m_customCursor = nil; custom_cursor_ = nil;
} }
NSBitmapImageRep *cursorImageRep = [[NSBitmapImageRep alloc] NSBitmapImageRep *cursorImageRep = [[NSBitmapImageRep alloc]
@@ -1294,12 +1294,12 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(const uint8_t *bitm
const NSPoint hotSpotPoint = {(CGFloat)(hot_spot[0]), (CGFloat)(hot_spot[1])}; const NSPoint hotSpotPoint = {(CGFloat)(hot_spot[0]), (CGFloat)(hot_spot[1])};
/* Foreground and background color parameter is not handled for now (10.6). */ /* Foreground and background color parameter is not handled for now (10.6). */
m_customCursor = [[NSCursor alloc] initWithImage:cursorImage hotSpot:hotSpotPoint]; custom_cursor_ = [[NSCursor alloc] initWithImage:cursorImage hotSpot:hotSpotPoint];
[cursorImageRep release]; [cursorImageRep release];
[cursorImage release]; [cursorImage release];
if (m_window.isVisible) { if (window_.isVisible) {
loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom); loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
} }
} }
@@ -1309,21 +1309,21 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCustomCursorShape(const uint8_t *bitm
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
void GHOST_WindowCocoa::beginIME(int32_t x, int32_t y, int32_t w, int32_t h, bool completed) void GHOST_WindowCocoa::beginIME(int32_t x, int32_t y, int32_t w, int32_t h, bool completed)
{ {
if (m_openGLView) { if (opengl_view_) {
[m_openGLView beginIME:x y:y w:w h:h completed:completed]; [opengl_view_ beginIME:x y:y w:w h:h completed:completed];
} }
else { else {
[m_metalView beginIME:x y:y w:w h:h completed:completed]; [metal_view_ beginIME:x y:y w:w h:h completed:completed];
} }
} }
void GHOST_WindowCocoa::endIME() void GHOST_WindowCocoa::endIME()
{ {
if (m_openGLView) { if (opengl_view_) {
[m_openGLView endIME]; [opengl_view_ endIME];
} }
else { else {
[m_metalView endIME]; [metal_view_ endIME];
} }
} }
#endif /* WITH_INPUT_IME */ #endif /* WITH_INPUT_IME */

View File

@@ -15,9 +15,9 @@
#include "GHOST_Window.hh" #include "GHOST_Window.hh"
#include <algorithm> #include <algorithm>
GHOST_WindowManager::GHOST_WindowManager() : m_activeWindow(nullptr) {} GHOST_WindowManager::GHOST_WindowManager() : active_window_(nullptr) {}
/* m_windows is freed by GHOST_System::disposeWindow */ /* windows_ is freed by GHOST_System::disposeWindow */
GHOST_WindowManager::~GHOST_WindowManager() = default; GHOST_WindowManager::~GHOST_WindowManager() = default;
GHOST_TSuccess GHOST_WindowManager::addWindow(GHOST_IWindow *window) GHOST_TSuccess GHOST_WindowManager::addWindow(GHOST_IWindow *window)
@@ -26,7 +26,7 @@ GHOST_TSuccess GHOST_WindowManager::addWindow(GHOST_IWindow *window)
if (window) { if (window) {
if (!getWindowFound(window)) { if (!getWindowFound(window)) {
/* Store the pointer to the window. */ /* Store the pointer to the window. */
m_windows.push_back(window); windows_.push_back(window);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
} }
@@ -37,11 +37,10 @@ GHOST_TSuccess GHOST_WindowManager::removeWindow(const GHOST_IWindow *window)
{ {
GHOST_TSuccess success = GHOST_kFailure; GHOST_TSuccess success = GHOST_kFailure;
if (window) { if (window) {
std::vector<GHOST_IWindow *>::iterator result = find( std::vector<GHOST_IWindow *>::iterator result = find(windows_.begin(), windows_.end(), window);
m_windows.begin(), m_windows.end(), window); if (result != windows_.end()) {
if (result != m_windows.end()) {
setWindowInactive(window); setWindowInactive(window);
m_windows.erase(result); windows_.erase(result);
success = GHOST_kSuccess; success = GHOST_kSuccess;
} }
} }
@@ -53,8 +52,8 @@ bool GHOST_WindowManager::getWindowFound(const GHOST_IWindow *window) const
bool found = false; bool found = false;
if (window) { if (window) {
std::vector<GHOST_IWindow *>::const_iterator result = find( std::vector<GHOST_IWindow *>::const_iterator result = find(
m_windows.begin(), m_windows.end(), window); windows_.begin(), windows_.end(), window);
if (result != m_windows.end()) { if (result != windows_.end()) {
found = true; found = true;
} }
} }
@@ -64,9 +63,9 @@ bool GHOST_WindowManager::getWindowFound(const GHOST_IWindow *window) const
GHOST_TSuccess GHOST_WindowManager::setActiveWindow(GHOST_IWindow *window) GHOST_TSuccess GHOST_WindowManager::setActiveWindow(GHOST_IWindow *window)
{ {
GHOST_TSuccess success = GHOST_kSuccess; GHOST_TSuccess success = GHOST_kSuccess;
if (window != m_activeWindow) { if (window != active_window_) {
if (getWindowFound(window)) { if (getWindowFound(window)) {
m_activeWindow = window; active_window_ = window;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -77,26 +76,26 @@ GHOST_TSuccess GHOST_WindowManager::setActiveWindow(GHOST_IWindow *window)
GHOST_IWindow *GHOST_WindowManager::getActiveWindow() const GHOST_IWindow *GHOST_WindowManager::getActiveWindow() const
{ {
return m_activeWindow; return active_window_;
} }
void GHOST_WindowManager::setWindowInactive(const GHOST_IWindow *window) void GHOST_WindowManager::setWindowInactive(const GHOST_IWindow *window)
{ {
if (window == m_activeWindow) { if (window == active_window_) {
m_activeWindow = nullptr; active_window_ = nullptr;
} }
} }
const std::vector<GHOST_IWindow *> &GHOST_WindowManager::getWindows() const const std::vector<GHOST_IWindow *> &GHOST_WindowManager::getWindows() const
{ {
return m_windows; return windows_;
} }
GHOST_IWindow *GHOST_WindowManager::getWindowAssociatedWithOSWindow(const void *osWindow) GHOST_IWindow *GHOST_WindowManager::getWindowAssociatedWithOSWindow(const void *osWindow)
{ {
std::vector<GHOST_IWindow *>::iterator iter; std::vector<GHOST_IWindow *>::iterator iter;
for (iter = m_windows.begin(); iter != m_windows.end(); ++iter) { for (iter = windows_.begin(); iter != windows_.end(); ++iter) {
if ((*iter)->getOSWindow() == osWindow) { if ((*iter)->getOSWindow() == osWindow) {
return *iter; return *iter;
} }

View File

@@ -86,10 +86,10 @@ class GHOST_WindowManager {
protected: protected:
/** The list of windows managed */ /** The list of windows managed */
std::vector<GHOST_IWindow *> m_windows; std::vector<GHOST_IWindow *> windows_;
/** The active window. */ /** The active window. */
GHOST_IWindow *m_activeWindow; GHOST_IWindow *active_window_;
MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_WindowManager") MEM_CXX_CLASS_ALLOC_FUNCS("GHOST:GHOST_WindowManager")
}; };

View File

@@ -17,7 +17,7 @@ class GHOST_SystemHeadless;
class GHOST_WindowNULL : public GHOST_Window { class GHOST_WindowNULL : public GHOST_Window {
public: public:
GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor /*cursorShape*/) override GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor /*cursor_shape*/) override
{ {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -28,7 +28,7 @@ class GHOST_WindowNULL : public GHOST_Window {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
const GHOST_IWindow * /*parentWindow*/, const GHOST_IWindow * /*parent_window*/,
GHOST_TDrawingContextType /*type*/, GHOST_TDrawingContextType /*type*/,
const GHOST_ContextParams &context_params) const GHOST_ContextParams &context_params)
: GHOST_Window(width, height, state, context_params, false) : GHOST_Window(width, height, state, context_params, false)

View File

@@ -23,30 +23,30 @@ GHOST_WindowSDL::GHOST_WindowSDL(GHOST_SystemSDL *system,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
const bool exclusive, const bool exclusive,
const GHOST_IWindow * /*parentWindow*/) const GHOST_IWindow * /*parent_window*/)
: GHOST_Window(width, height, state, context_params, exclusive), : GHOST_Window(width, height, state, context_params, exclusive),
m_system(system), system_(system),
m_valid_setup(false), valid_setup_(false),
m_invalid_window(false), invalid_window_(false),
m_sdl_custom_cursor(nullptr) sdl_custom_cursor_(nullptr)
{ {
/* creating the window _must_ come after setting attributes */ /* creating the window _must_ come after setting attributes */
m_sdl_win = SDL_CreateWindow(title, sdl_win_ = SDL_CreateWindow(title,
left, left,
top, top,
width, width,
height, height,
SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
/* now set up the rendering context. */ /* now set up the rendering context. */
if (setDrawingContextType(type) == GHOST_kSuccess) { if (setDrawingContextType(type) == GHOST_kSuccess) {
m_valid_setup = true; valid_setup_ = true;
GHOST_PRINT("Created window\n"); GHOST_PRINT("Created window\n");
} }
if (exclusive) { if (exclusive) {
SDL_RaiseWindow(m_sdl_win); SDL_RaiseWindow(sdl_win_);
} }
setTitle(title); setTitle(title);
@@ -54,13 +54,13 @@ GHOST_WindowSDL::GHOST_WindowSDL(GHOST_SystemSDL *system,
GHOST_WindowSDL::~GHOST_WindowSDL() GHOST_WindowSDL::~GHOST_WindowSDL()
{ {
if (m_sdl_custom_cursor) { if (sdl_custom_cursor_) {
SDL_FreeCursor(m_sdl_custom_cursor); SDL_FreeCursor(sdl_custom_cursor_);
} }
releaseNativeHandles(); releaseNativeHandles();
SDL_DestroyWindow(m_sdl_win); SDL_DestroyWindow(sdl_win_);
} }
GHOST_Context *GHOST_WindowSDL::newDrawingContext(GHOST_TDrawingContextType type) GHOST_Context *GHOST_WindowSDL::newDrawingContext(GHOST_TDrawingContextType type)
@@ -71,8 +71,8 @@ GHOST_Context *GHOST_WindowSDL::newDrawingContext(GHOST_TDrawingContextType type
case GHOST_kDrawingContextTypeOpenGL: { case GHOST_kDrawingContextTypeOpenGL: {
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
GHOST_Context *context = new GHOST_ContextSDL( GHOST_Context *context = new GHOST_ContextSDL(
m_want_context_params, want_context_params_,
m_sdl_win, sdl_win_,
0, /* Profile bit. */ 0, /* Profile bit. */
4, 4,
minor, minor,
@@ -96,9 +96,9 @@ GHOST_Context *GHOST_WindowSDL::newDrawingContext(GHOST_TDrawingContextType type
GHOST_TSuccess GHOST_WindowSDL::invalidate() GHOST_TSuccess GHOST_WindowSDL::invalidate()
{ {
if (m_invalid_window == false) { if (invalid_window_ == false) {
m_system->addDirtyWindow(this); system_->addDirtyWindow(this);
m_invalid_window = true; invalid_window_ = true;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -108,18 +108,18 @@ GHOST_TSuccess GHOST_WindowSDL::setState(GHOST_TWindowState state)
{ {
switch (state) { switch (state) {
case GHOST_kWindowStateNormal: case GHOST_kWindowStateNormal:
SDL_SetWindowFullscreen(m_sdl_win, SDL_FALSE); SDL_SetWindowFullscreen(sdl_win_, SDL_FALSE);
SDL_RestoreWindow(m_sdl_win); SDL_RestoreWindow(sdl_win_);
break; break;
case GHOST_kWindowStateMaximized: case GHOST_kWindowStateMaximized:
SDL_SetWindowFullscreen(m_sdl_win, SDL_FALSE); SDL_SetWindowFullscreen(sdl_win_, SDL_FALSE);
SDL_MaximizeWindow(m_sdl_win); SDL_MaximizeWindow(sdl_win_);
break; break;
case GHOST_kWindowStateMinimized: case GHOST_kWindowStateMinimized:
SDL_MinimizeWindow(m_sdl_win); SDL_MinimizeWindow(sdl_win_);
break; break;
case GHOST_kWindowStateFullScreen: case GHOST_kWindowStateFullScreen:
SDL_SetWindowFullscreen(m_sdl_win, SDL_TRUE); SDL_SetWindowFullscreen(sdl_win_, SDL_TRUE);
break; break;
default: default:
break; break;
@@ -130,7 +130,7 @@ GHOST_TSuccess GHOST_WindowSDL::setState(GHOST_TWindowState state)
GHOST_TWindowState GHOST_WindowSDL::getState() const GHOST_TWindowState GHOST_WindowSDL::getState() const
{ {
Uint32 flags = SDL_GetWindowFlags(m_sdl_win); Uint32 flags = SDL_GetWindowFlags(sdl_win_);
if (flags & SDL_WINDOW_FULLSCREEN) { if (flags & SDL_WINDOW_FULLSCREEN) {
return GHOST_kWindowStateFullScreen; return GHOST_kWindowStateFullScreen;
@@ -146,17 +146,17 @@ GHOST_TWindowState GHOST_WindowSDL::getState() const
bool GHOST_WindowSDL::getValid() const bool GHOST_WindowSDL::getValid() const
{ {
return GHOST_Window::getValid() && m_valid_setup; return GHOST_Window::getValid() && valid_setup_;
} }
void GHOST_WindowSDL::setTitle(const char *title) void GHOST_WindowSDL::setTitle(const char *title)
{ {
SDL_SetWindowTitle(m_sdl_win, title); SDL_SetWindowTitle(sdl_win_, title);
} }
std::string GHOST_WindowSDL::getTitle() const std::string GHOST_WindowSDL::getTitle() const
{ {
return SDL_GetWindowTitle(m_sdl_win); return SDL_GetWindowTitle(sdl_win_);
} }
void GHOST_WindowSDL::getWindowBounds(GHOST_Rect &bounds) const void GHOST_WindowSDL::getWindowBounds(GHOST_Rect &bounds) const
@@ -167,34 +167,34 @@ void GHOST_WindowSDL::getWindowBounds(GHOST_Rect &bounds) const
void GHOST_WindowSDL::getClientBounds(GHOST_Rect &bounds) const void GHOST_WindowSDL::getClientBounds(GHOST_Rect &bounds) const
{ {
int x, y, w, h; int x, y, w, h;
SDL_GetWindowSize(m_sdl_win, &w, &h); SDL_GetWindowSize(sdl_win_, &w, &h);
SDL_GetWindowPosition(m_sdl_win, &x, &y); SDL_GetWindowPosition(sdl_win_, &x, &y);
bounds.m_l = x; bounds.l_ = x;
bounds.m_r = x + w; bounds.r_ = x + w;
bounds.m_t = y; bounds.t_ = y;
bounds.m_b = y + h; bounds.b_ = y + h;
} }
GHOST_TSuccess GHOST_WindowSDL::setClientWidth(uint32_t width) GHOST_TSuccess GHOST_WindowSDL::setClientWidth(uint32_t width)
{ {
int height; int height;
SDL_GetWindowSize(m_sdl_win, nullptr, &height); SDL_GetWindowSize(sdl_win_, nullptr, &height);
SDL_SetWindowSize(m_sdl_win, width, height); SDL_SetWindowSize(sdl_win_, width, height);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_WindowSDL::setClientHeight(uint32_t height) GHOST_TSuccess GHOST_WindowSDL::setClientHeight(uint32_t height)
{ {
int width; int width;
SDL_GetWindowSize(m_sdl_win, &width, nullptr); SDL_GetWindowSize(sdl_win_, &width, nullptr);
SDL_SetWindowSize(m_sdl_win, width, height); SDL_SetWindowSize(sdl_win_, width, height);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_WindowSDL::setClientSize(uint32_t width, uint32_t height) GHOST_TSuccess GHOST_WindowSDL::setClientSize(uint32_t width, uint32_t height)
{ {
SDL_SetWindowSize(m_sdl_win, width, height); SDL_SetWindowSize(sdl_win_, width, height);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -202,7 +202,7 @@ void GHOST_WindowSDL::screenToClient(int32_t inX, int32_t inY, int32_t &outX, in
{ {
/* XXXSDL_WEAK_ABS_COORDS */ /* XXXSDL_WEAK_ABS_COORDS */
int x_win, y_win; int x_win, y_win;
SDL_GetWindowPosition(m_sdl_win, &x_win, &y_win); SDL_GetWindowPosition(sdl_win_, &x_win, &y_win);
outX = inX - x_win; outX = inX - x_win;
outY = inY - y_win; outY = inY - y_win;
@@ -211,7 +211,7 @@ void GHOST_WindowSDL::clientToScreen(int32_t inX, int32_t inY, int32_t &outX, in
{ {
/* XXXSDL_WEAK_ABS_COORDS */ /* XXXSDL_WEAK_ABS_COORDS */
int x_win, y_win; int x_win, y_win;
SDL_GetWindowPosition(m_sdl_win, &x_win, &y_win); SDL_GetWindowPosition(sdl_win_, &x_win, &y_win);
outX = inX + x_win; outX = inX + x_win;
outY = inY + y_win; outY = inY + y_win;
@@ -623,14 +623,14 @@ GHOST_TSuccess GHOST_WindowSDL::setWindowCustomCursorShape(const uint8_t *bitmap
const int hot_spot[2], const int hot_spot[2],
bool /*can_invert_color*/) bool /*can_invert_color*/)
{ {
if (m_sdl_custom_cursor) { if (sdl_custom_cursor_) {
SDL_FreeCursor(m_sdl_custom_cursor); SDL_FreeCursor(sdl_custom_cursor_);
} }
m_sdl_custom_cursor = sdl_ghost_CreateCursor( sdl_custom_cursor_ = sdl_ghost_CreateCursor(
bitmap, mask, size[0], size[1], hot_spot[0], hot_spot[1]); bitmap, mask, size[0], size[1], hot_spot[0], hot_spot[1]);
SDL_SetCursor(m_sdl_custom_cursor); SDL_SetCursor(sdl_custom_cursor_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -642,7 +642,7 @@ GHOST_TSuccess GHOST_WindowSDL::setWindowCursorVisibility(bool visible)
uint16_t GHOST_WindowSDL::getDPIHint() uint16_t GHOST_WindowSDL::getDPIHint()
{ {
int displayIndex = SDL_GetWindowDisplayIndex(m_sdl_win); int displayIndex = SDL_GetWindowDisplayIndex(sdl_win_);
if (displayIndex < 0) { if (displayIndex < 0) {
return 96; return 96;
} }

View File

@@ -26,12 +26,12 @@ class GHOST_SystemSDL;
class GHOST_WindowSDL : public GHOST_Window { class GHOST_WindowSDL : public GHOST_Window {
private: private:
GHOST_SystemSDL *m_system; GHOST_SystemSDL *system_;
bool m_valid_setup; bool valid_setup_;
bool m_invalid_window; bool invalid_window_;
SDL_Window *m_sdl_win; SDL_Window *sdl_win_;
SDL_Cursor *m_sdl_custom_cursor; SDL_Cursor *sdl_custom_cursor_;
public: public:
GHOST_WindowSDL(GHOST_SystemSDL *system, GHOST_WindowSDL(GHOST_SystemSDL *system,
@@ -44,14 +44,14 @@ class GHOST_WindowSDL : public GHOST_Window {
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
const bool exclusive = false, const bool exclusive = false,
const GHOST_IWindow *parentWindow = nullptr); const GHOST_IWindow *parent_window = nullptr);
~GHOST_WindowSDL(); ~GHOST_WindowSDL();
/* SDL specific */ /* SDL specific */
SDL_Window *getSDLWindow() SDL_Window *getSDLWindow()
{ {
return m_sdl_win; return sdl_win_;
} }
GHOST_TSuccess invalidate() override; GHOST_TSuccess invalidate() override;
@@ -63,7 +63,7 @@ class GHOST_WindowSDL : public GHOST_Window {
void validate() void validate()
{ {
m_invalid_window = false; invalid_window_ = false;
} }
bool getValid() const override; bool getValid() const override;

View File

@@ -49,8 +49,8 @@
@implementation COCOA_VIEW_CLASS @implementation COCOA_VIEW_CLASS
@synthesize systemCocoa = m_systemCocoa; @synthesize systemCocoa = system_cocoa_;
@synthesize windowCocoa = m_windowCocoa; @synthesize windowCocoa = window_cocoa_;
- (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa - (instancetype)initWithSystemCocoa:(GHOST_SystemCocoa *)sysCocoa
windowCocoa:(GHOST_WindowCocoa *)winCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
@@ -59,8 +59,8 @@
self = [super init]; self = [super init];
if (self) { if (self) {
m_systemCocoa = sysCocoa; system_cocoa_ = sysCocoa;
m_windowCocoa = winCocoa; window_cocoa_ = winCocoa;
composing = false; composing = false;
composing_text = nil; composing_text = nil;
@@ -108,7 +108,7 @@
#endif #endif
if (!ime_process) { if (!ime_process) {
m_systemCocoa->handleKeyEvent(event); system_cocoa_->handleKeyEvent(event);
} }
/* Start or continue composing? */ /* Start or continue composing? */
@@ -127,7 +127,7 @@
const int controlCharForKorean = (GHOST_IME_COMPOSITION_EVENT | GHOST_IME_RESULT_EVENT | const int controlCharForKorean = (GHOST_IME_COMPOSITION_EVENT | GHOST_IME_RESULT_EVENT |
GHOST_IME_KEY_CONTROL_CHAR); GHOST_IME_KEY_CONTROL_CHAR);
if (((ime.state_flag & controlCharForKorean) == controlCharForKorean)) { if (((ime.state_flag & controlCharForKorean) == controlCharForKorean)) {
m_systemCocoa->handleKeyEvent(event); system_cocoa_->handleKeyEvent(event);
} }
ime.state_flag &= ~(GHOST_IME_COMPOSITION_EVENT | GHOST_IME_RESULT_EVENT); ime.state_flag &= ~(GHOST_IME_COMPOSITION_EVENT | GHOST_IME_RESULT_EVENT);
@@ -142,19 +142,19 @@
#define HANDLE_KEY_EVENT(eventType) \ #define HANDLE_KEY_EVENT(eventType) \
-(void)eventType : (NSEvent *)event \ -(void)eventType : (NSEvent *)event \
{ \ { \
m_systemCocoa->handleKeyEvent(event); \ system_cocoa_->handleKeyEvent(event); \
} }
#define HANDLE_MOUSE_EVENT(eventType) \ #define HANDLE_MOUSE_EVENT(eventType) \
-(void)eventType : (NSEvent *)event \ -(void)eventType : (NSEvent *)event \
{ \ { \
m_systemCocoa->handleMouseEvent(event); \ system_cocoa_->handleMouseEvent(event); \
} }
#define HANDLE_TABLET_EVENT(eventType) \ #define HANDLE_TABLET_EVENT(eventType) \
-(void)eventType : (NSEvent *)event \ -(void)eventType : (NSEvent *)event \
{ \ { \
m_systemCocoa->handleMouseEvent(event); \ system_cocoa_->handleMouseEvent(event); \
} }
HANDLE_KEY_EVENT(keyUp) HANDLE_KEY_EVENT(keyUp)
@@ -190,12 +190,12 @@ HANDLE_TABLET_EVENT(tabletProximity)
} }
else { else {
[super drawRect:rect]; [super drawRect:rect];
m_systemCocoa->handleWindowEvent(GHOST_kEventWindowUpdate, m_windowCocoa); system_cocoa_->handleWindowEvent(GHOST_kEventWindowUpdate, window_cocoa_);
/* For some cases like entering full-screen we need to redraw immediately /* For some cases like entering full-screen we need to redraw immediately
* so our window does not show blank during the animation */ * so our window does not show blank during the animation */
if (m_windowCocoa->getImmediateDraw()) { if (window_cocoa_->getImmediateDraw()) {
m_systemCocoa->dispatchEvents(); system_cocoa_->dispatchEvents();
} }
} }
} }
@@ -391,7 +391,7 @@ HANDLE_TABLET_EVENT(tabletProximity)
- (void)setImeCandidateWinPos:(int32_t)x y:(int32_t)y w:(int32_t)w h:(int32_t)h - (void)setImeCandidateWinPos:(int32_t)x y:(int32_t)y w:(int32_t)w h:(int32_t)h
{ {
int32_t outX, outY; int32_t outX, outY;
m_windowCocoa->clientToScreen(x, y, outX, outY); window_cocoa_->clientToScreen(x, y, outX, outY);
ime.candidate_window_position = NSMakeRect((CGFloat)outX, (CGFloat)outY, (CGFloat)w, (CGFloat)h); ime.candidate_window_position = NSMakeRect((CGFloat)outX, (CGFloat)outY, (CGFloat)w, (CGFloat)h);
} }
@@ -417,8 +417,8 @@ HANDLE_TABLET_EVENT(tabletProximity)
- (void)processImeEvent:(GHOST_TEventType)imeEventType - (void)processImeEvent:(GHOST_TEventType)imeEventType
{ {
GHOST_Event *event = new GHOST_EventIME( GHOST_Event *event = new GHOST_EventIME(
m_systemCocoa->getMilliSeconds(), imeEventType, m_windowCocoa, &ime.event); system_cocoa_->getMilliSeconds(), imeEventType, window_cocoa_, &ime.event);
m_systemCocoa->pushEvent(event); system_cocoa_->pushEvent(event);
} }
- (std::string)convertNSString:(NSString *)inString - (std::string)convertNSString:(NSString *)inString

View File

@@ -1731,7 +1731,7 @@ GHOST_WindowWayland::GHOST_WindowWayland(GHOST_SystemWayland *system,
const uint32_t width, const uint32_t width,
const uint32_t height, const uint32_t height,
const GHOST_TWindowState state, const GHOST_TWindowState state,
const GHOST_IWindow *parentWindow, const GHOST_IWindow *parent_window,
const GHOST_TDrawingContextType type, const GHOST_TDrawingContextType type,
const bool is_dialog, const bool is_dialog,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
@@ -1813,9 +1813,9 @@ GHOST_WindowWayland::GHOST_WindowWayland(GHOST_SystemWayland *system,
libdecor_frame_set_min_content_size(decor.frame, UNPACK2(size_min)); libdecor_frame_set_min_content_size(decor.frame, UNPACK2(size_min));
libdecor_frame_set_app_id(decor.frame, xdg_app_id); libdecor_frame_set_app_id(decor.frame, xdg_app_id);
if (parentWindow) { if (parent_window) {
GWL_LibDecor_Window &decor_parent = GWL_LibDecor_Window &decor_parent =
*dynamic_cast<const GHOST_WindowWayland *>(parentWindow)->window_->libdecor; *dynamic_cast<const GHOST_WindowWayland *>(parent_window)->window_->libdecor;
libdecor_frame_set_parent(decor.frame, decor_parent.frame); libdecor_frame_set_parent(decor.frame, decor_parent.frame);
} }
} }
@@ -1834,9 +1834,9 @@ GHOST_WindowWayland::GHOST_WindowWayland(GHOST_SystemWayland *system,
xdg_surface_add_listener(decor.surface, &xdg_surface_listener, window_); xdg_surface_add_listener(decor.surface, &xdg_surface_listener, window_);
xdg_toplevel_add_listener(decor.toplevel, &xdg_toplevel_listener, window_); xdg_toplevel_add_listener(decor.toplevel, &xdg_toplevel_listener, window_);
if (parentWindow && is_dialog) { if (parent_window && is_dialog) {
GWL_XDG_Decor_Window &decor_parent = GWL_XDG_Decor_Window &decor_parent =
*dynamic_cast<const GHOST_WindowWayland *>(parentWindow)->window_->xdg_decor; *dynamic_cast<const GHOST_WindowWayland *>(parent_window)->window_->xdg_decor;
xdg_toplevel_set_parent(decor.toplevel, decor_parent.toplevel); xdg_toplevel_set_parent(decor.toplevel, decor_parent.toplevel);
} }
} }
@@ -2172,9 +2172,9 @@ GHOST_TSuccess GHOST_WindowWayland::swapBuffers()
} }
#endif /* USE_EVENT_BACKGROUND_THREAD */ #endif /* USE_EVENT_BACKGROUND_THREAD */
GHOST_TSuccess GHOST_WindowWayland::hasCursorShape(GHOST_TStandardCursor cursorShape) GHOST_TSuccess GHOST_WindowWayland::hasCursorShape(GHOST_TStandardCursor cursor_shape)
{ {
return system_->cursor_shape_check(cursorShape); return system_->cursor_shape_check(cursor_shape);
} }
GHOST_TSuccess GHOST_WindowWayland::setWindowCursorGrab(GHOST_TGrabCursorMode mode) GHOST_TSuccess GHOST_WindowWayland::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
@@ -2185,7 +2185,7 @@ GHOST_TSuccess GHOST_WindowWayland::setWindowCursorGrab(GHOST_TGrabCursorMode mo
GHOST_Rect bounds_buf; GHOST_Rect bounds_buf;
const GHOST_Rect *bounds = nullptr; const GHOST_Rect *bounds = nullptr;
if (m_cursorGrab == GHOST_kGrabWrap) { if (cursor_grab_ == GHOST_kGrabWrap) {
if (getCursorGrabBounds(bounds_buf) == GHOST_kFailure) { if (getCursorGrabBounds(bounds_buf) == GHOST_kFailure) {
getClientBounds(bounds_buf); getClientBounds(bounds_buf);
} }
@@ -2193,10 +2193,10 @@ GHOST_TSuccess GHOST_WindowWayland::setWindowCursorGrab(GHOST_TGrabCursorMode mo
} }
if (system_->window_cursor_grab_set(mode, if (system_->window_cursor_grab_set(mode,
m_cursorGrab, cursor_grab_,
m_cursorGrabInitPos, cursor_grab_init_pos_,
bounds, bounds,
m_cursorGrabAxis, cursor_grab_axis_,
window_->wl.surface, window_->wl.surface,
this->scale_params_get())) this->scale_params_get()))
{ {
@@ -2214,16 +2214,16 @@ GHOST_TSuccess GHOST_WindowWayland::setWindowCursorShape(GHOST_TStandardCursor s
const bool is_active = this == static_cast<const GHOST_WindowWayland *>( const bool is_active = this == static_cast<const GHOST_WindowWayland *>(
system_->getWindowManager()->getActiveWindow()); system_->getWindowManager()->getActiveWindow());
gwl_window_cursor_custom_clear(&window_->cursor_generator); gwl_window_cursor_custom_clear(&window_->cursor_generator);
m_cursorShape = shape; cursor_shape_ = shape;
GHOST_TSuccess ok; GHOST_TSuccess ok;
if (is_active) { if (is_active) {
ok = system_->cursor_shape_set(m_cursorShape); ok = system_->cursor_shape_set(cursor_shape_);
GHOST_TSuccess ok_test = ok; GHOST_TSuccess ok_test = ok;
if (ok == GHOST_kFailure) { if (ok == GHOST_kFailure) {
/* Failed, try again with the default cursor. */ /* Failed, try again with the default cursor. */
m_cursorShape = GHOST_kStandardCursorDefault; cursor_shape_ = GHOST_kStandardCursorDefault;
ok_test = system_->cursor_shape_set(m_cursorShape); ok_test = system_->cursor_shape_set(cursor_shape_);
} }
wl_display *display = system_->wl_display_get(); wl_display *display = system_->wl_display_get();
@@ -2243,7 +2243,7 @@ GHOST_TSuccess GHOST_WindowWayland::setWindowCursorShape(GHOST_TStandardCursor s
/* Set later when activating the window. */ /* Set later when activating the window. */
ok = system_->cursor_shape_check(shape); ok = system_->cursor_shape_check(shape);
if (ok == GHOST_kFailure) { if (ok == GHOST_kFailure) {
m_cursorShape = GHOST_kStandardCursorDefault; cursor_shape_ = GHOST_kStandardCursorDefault;
} }
} }
return ok; return ok;
@@ -2254,7 +2254,7 @@ bool GHOST_WindowWayland::getCursorGrabUseSoftwareDisplay()
#ifdef USE_EVENT_BACKGROUND_THREAD #ifdef USE_EVENT_BACKGROUND_THREAD
std::lock_guard lock_server_guard{*system_->server_mutex}; std::lock_guard lock_server_guard{*system_->server_mutex};
#endif #endif
return system_->cursor_grab_use_software_display_get(m_cursorGrab); return system_->cursor_grab_use_software_display_get(cursor_grab_);
} }
GHOST_TSuccess GHOST_WindowWayland::setWindowCustomCursorGenerator( GHOST_TSuccess GHOST_WindowWayland::setWindowCustomCursorGenerator(
@@ -2264,7 +2264,7 @@ GHOST_TSuccess GHOST_WindowWayland::setWindowCustomCursorGenerator(
#ifdef USE_EVENT_BACKGROUND_THREAD #ifdef USE_EVENT_BACKGROUND_THREAD
std::lock_guard lock_server_guard{*system_->server_mutex}; std::lock_guard lock_server_guard{*system_->server_mutex};
#endif #endif
m_cursorShape = GHOST_kStandardCursorCustom; cursor_shape_ = GHOST_kStandardCursorCustom;
if (window_->cursor_generator) { if (window_->cursor_generator) {
gwl_window_cursor_custom_free(window_->cursor_generator); gwl_window_cursor_custom_free(window_->cursor_generator);
} }
@@ -2457,13 +2457,13 @@ GHOST_Context *GHOST_WindowWayland::newDrawingContext(GHOST_TDrawingContextType
{ {
switch (type) { switch (type) {
case GHOST_kDrawingContextTypeNone: { case GHOST_kDrawingContextTypeNone: {
GHOST_Context *context = new GHOST_ContextNone(m_want_context_params); GHOST_Context *context = new GHOST_ContextNone(want_context_params_);
return context; return context;
} }
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_ContextVK *context = new GHOST_ContextVK(m_want_context_params, GHOST_ContextVK *context = new GHOST_ContextVK(want_context_params_,
GHOST_kVulkanPlatformWayland, GHOST_kVulkanPlatformWayland,
0, 0,
nullptr, nullptr,
@@ -2486,14 +2486,14 @@ GHOST_Context *GHOST_WindowWayland::newDrawingContext(GHOST_TDrawingContextType
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
GHOST_Context *context = new GHOST_ContextEGL( GHOST_Context *context = new GHOST_ContextEGL(
system_, system_,
m_want_context_params, want_context_params_,
EGLNativeWindowType(window_->backend.egl_window), EGLNativeWindowType(window_->backend.egl_window),
EGLNativeDisplayType(system_->wl_display_get()), EGLNativeDisplayType(system_->wl_display_get()),
EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
4, 4,
minor, minor,
GHOST_OPENGL_EGL_CONTEXT_FLAGS | GHOST_OPENGL_EGL_CONTEXT_FLAGS |
(m_want_context_params.is_debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0), (want_context_params_.is_debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0),
GHOST_OPENGL_EGL_RESET_NOTIFICATION_STRATEGY, GHOST_OPENGL_EGL_RESET_NOTIFICATION_STRATEGY,
EGL_OPENGL_API); EGL_OPENGL_API);
@@ -2675,7 +2675,7 @@ GHOST_TSuccess GHOST_WindowWayland::cursor_shape_refresh()
return GHOST_kSuccess; return GHOST_kSuccess;
} }
#endif #endif
return gwl_window_cursor_shape_refresh(m_cursorShape, window_->cursor_generator, system_); return gwl_window_cursor_shape_refresh(cursor_shape_, window_->cursor_generator, system_);
} }
void GHOST_WindowWayland::outputs_changed_update_scale_tag() void GHOST_WindowWayland::outputs_changed_update_scale_tag()

View File

@@ -64,7 +64,7 @@ struct GWL_Window;
class GHOST_WindowWayland : public GHOST_Window { class GHOST_WindowWayland : public GHOST_Window {
public: public:
GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor cursorShape) override; GHOST_TSuccess hasCursorShape(GHOST_TStandardCursor cursor_shape) override;
GHOST_WindowWayland(GHOST_SystemWayland *system, GHOST_WindowWayland(GHOST_SystemWayland *system,
const char *title, const char *title,
@@ -73,7 +73,7 @@ class GHOST_WindowWayland : public GHOST_Window {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
const GHOST_IWindow *parentWindow, const GHOST_IWindow *parent_window,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const bool is_dialog, const bool is_dialog,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,

View File

@@ -60,31 +60,31 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
GHOST_WindowWin32 *parentwindow, GHOST_WindowWin32 *parent_window,
bool dialog, bool dialog,
const GHOST_GPUDevice &preferred_device) const GHOST_GPUDevice &preferred_device)
: GHOST_Window(width, height, state, context_params, false), : GHOST_Window(width, height, state, context_params, false),
m_mousePresent(false), mouse_present_(false),
m_inLiveResize(false), in_live_resize_(false),
m_system(system), system_(system),
m_dropTarget(nullptr), drop_target_(nullptr),
m_hWnd(0), h_wnd_(0),
m_hDC(0), h_DC_(0),
m_isDialog(dialog), is_dialog_(dialog),
m_preferred_device(preferred_device), preferred_device_(preferred_device),
m_hasMouseCaptured(false), has_mouse_captured_(false),
m_hasGrabMouse(false), has_grab_mouse_(false),
m_nPressedButtons(0), n_pressed_buttons_(0),
m_customCursor(0), custom_cursor_(0),
m_Bar(nullptr), bar_(nullptr),
m_wintab(nullptr), wintab_(nullptr),
m_lastPointerTabletData(GHOST_TABLET_DATA_NONE), last_pointer_tablet_data_(GHOST_TABLET_DATA_NONE),
m_normal_state(GHOST_kWindowStateNormal), normal_state_(GHOST_kWindowStateNormal),
m_user32(::LoadLibrary("user32.dll")), user32_(::LoadLibrary("user32.dll")),
m_parentWindowHwnd(parentwindow ? parentwindow->m_hWnd : HWND_DESKTOP), parent_window_hwnd_(parent_window ? parent_window->h_wnd_ : HWND_DESKTOP),
m_directManipulationHelper(nullptr) direct_manipulation_helper_(nullptr)
{ {
DWORD style = parentwindow ? DWORD style = parent_window ?
WS_POPUPWINDOW | WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX : WS_POPUPWINDOW | WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX :
WS_OVERLAPPEDWINDOW; WS_OVERLAPPEDWINDOW;
@@ -93,7 +93,7 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
} }
/* Forces owned windows onto taskbar and allows minimization. */ /* Forces owned windows onto taskbar and allows minimization. */
DWORD extended_style = parentwindow ? WS_EX_APPWINDOW : 0; DWORD extended_style = parent_window ? WS_EX_APPWINDOW : 0;
if (dialog) { if (dialog) {
/* When we are ready to make windows of this type: /* When we are ready to make windows of this type:
@@ -106,7 +106,7 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
adjustWindowRectForClosestMonitor(&win_rect, style, extended_style); adjustWindowRectForClosestMonitor(&win_rect, style, extended_style);
wchar_t *title_16 = alloc_utf16_from_8((char *)title, 0); wchar_t *title_16 = alloc_utf16_from_8((char *)title, 0);
m_hWnd = ::CreateWindowExW(extended_style, /* window extended style */ h_wnd_ = ::CreateWindowExW(extended_style, /* window extended style */
s_windowClassName, /* pointer to registered class name */ s_windowClassName, /* pointer to registered class name */
title_16, /* pointer to window name */ title_16, /* pointer to window name */
style, /* window style */ style, /* window style */
@@ -114,20 +114,20 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
win_rect.top, /* vertical position of window */ win_rect.top, /* vertical position of window */
win_rect.right - win_rect.left, /* window width */ win_rect.right - win_rect.left, /* window width */
win_rect.bottom - win_rect.top, /* window height */ win_rect.bottom - win_rect.top, /* window height */
m_parentWindowHwnd, /* handle to parent or owner window */ parent_window_hwnd_, /* handle to parent or owner window */
0, /* handle to menu or child-window identifier */ 0, /* handle to menu or child-window identifier */
::GetModuleHandle(0), /* handle to application instance */ ::GetModuleHandle(0), /* handle to application instance */
0); /* pointer to window-creation data */ 0); /* pointer to window-creation data */
free(title_16); free(title_16);
if (m_hWnd == nullptr) { if (h_wnd_ == nullptr) {
return; return;
} }
registerWindowAppUserModelProperties(); registerWindowAppUserModelProperties();
/* Store the device context. */ /* Store the device context. */
m_hDC = ::GetDC(m_hWnd); h_DC_ = ::GetDC(h_wnd_);
if (!setDrawingContextType(type)) { if (!setDrawingContextType(type)) {
const char *title = "Blender - Unsupported Graphics Card Configuration"; const char *title = "Blender - Unsupported Graphics Card Configuration";
@@ -157,34 +157,34 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
"this issue. Installing the latest driver for your graphics card could also help."; "this issue. Installing the latest driver for your graphics card could also help.";
} }
} }
MessageBox(m_hWnd, text, title, MB_OK | MB_ICONERROR); MessageBox(h_wnd_, text, title, MB_OK | MB_ICONERROR);
::ReleaseDC(m_hWnd, m_hDC); ::ReleaseDC(h_wnd_, h_DC_);
::DestroyWindow(m_hWnd); ::DestroyWindow(h_wnd_);
m_hWnd = nullptr; h_wnd_ = nullptr;
if (!parentwindow) { if (!parent_window) {
exit(0); exit(0);
} }
return; return;
} }
RegisterTouchWindow(m_hWnd, 0); RegisterTouchWindow(h_wnd_, 0);
/* Register as drop-target. #OleInitialize(0) required first, done in GHOST_SystemWin32. */ /* Register as drop-target. #OleInitialize(0) required first, done in GHOST_SystemWin32. */
m_dropTarget = new GHOST_DropTargetWin32(this, m_system); drop_target_ = new GHOST_DropTargetWin32(this, system_);
::RegisterDragDrop(m_hWnd, m_dropTarget); ::RegisterDragDrop(h_wnd_, drop_target_);
/* Store a pointer to this class in the window structure. */ /* Store a pointer to this class in the window structure. */
::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR)this); ::SetWindowLongPtr(h_wnd_, GWLP_USERDATA, (LONG_PTR)this);
if (!m_system->m_windowFocus) { if (!system_->window_focus_) {
/* If we don't want focus then lower to bottom. */ /* If we don't want focus then lower to bottom. */
::SetWindowPos(m_hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); ::SetWindowPos(h_wnd_, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
} }
if (parentwindow) { if (parent_window) {
/* Release any parent capture to allow immediate interaction (#90110). */ /* Release any parent capture to allow immediate interaction (#90110). */
::ReleaseCapture(); ::ReleaseCapture();
parentwindow->lostMouseCapture(); parent_window->lostMouseCapture();
} }
/* Show the window. */ /* Show the window. */
@@ -195,17 +195,17 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
nCmdShow = SW_SHOWMAXIMIZED; nCmdShow = SW_SHOWMAXIMIZED;
break; break;
case GHOST_kWindowStateMinimized: case GHOST_kWindowStateMinimized:
nCmdShow = (m_system->m_windowFocus) ? SW_SHOWMINIMIZED : SW_SHOWMINNOACTIVE; nCmdShow = (system_->window_focus_) ? SW_SHOWMINIMIZED : SW_SHOWMINNOACTIVE;
break; break;
case GHOST_kWindowStateNormal: case GHOST_kWindowStateNormal:
default: default:
nCmdShow = (m_system->m_windowFocus) ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE; nCmdShow = (system_->window_focus_) ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
break; break;
} }
ThemeRefresh(); ThemeRefresh();
::ShowWindow(m_hWnd, nCmdShow); ::ShowWindow(h_wnd_, nCmdShow);
/* Initialize WINTAB. */ /* Initialize WINTAB. */
if (system->getTabletAPI() != GHOST_kTabletWinPointer) { if (system->getTabletAPI() != GHOST_kTabletWinPointer) {
@@ -214,99 +214,99 @@ GHOST_WindowWin32::GHOST_WindowWin32(GHOST_SystemWin32 *system,
/* Allow the showing of a progress bar on the taskbar. */ /* Allow the showing of a progress bar on the taskbar. */
CoCreateInstance( CoCreateInstance(
CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID *)&m_Bar); CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID *)&bar_);
/* Initialize Direct Manipulation. */ /* Initialize Direct Manipulation. */
m_directManipulationHelper = GHOST_DirectManipulationHelper::create(m_hWnd, getDPIHint()); direct_manipulation_helper_ = GHOST_DirectManipulationHelper::create(h_wnd_, getDPIHint());
} }
void GHOST_WindowWin32::updateDirectManipulation() void GHOST_WindowWin32::updateDirectManipulation()
{ {
if (!m_directManipulationHelper) { if (!direct_manipulation_helper_) {
return; return;
} }
m_directManipulationHelper->update(); direct_manipulation_helper_->update();
} }
void GHOST_WindowWin32::onPointerHitTest(WPARAM wParam) void GHOST_WindowWin32::onPointerHitTest(WPARAM wParam)
{ {
/* Only #DM_POINTERHITTEST can be the first message of input sequence of touch-pad input. */ /* Only #DM_POINTERHITTEST can be the first message of input sequence of touch-pad input. */
if (!m_directManipulationHelper) { if (!direct_manipulation_helper_) {
return; return;
} }
UINT32 pointerId = GET_POINTERID_WPARAM(wParam); UINT32 pointerId = GET_POINTERID_WPARAM(wParam);
POINTER_INPUT_TYPE pointerType; POINTER_INPUT_TYPE pointerType;
if (GetPointerType(pointerId, &pointerType) && pointerType == PT_TOUCHPAD) { if (GetPointerType(pointerId, &pointerType) && pointerType == PT_TOUCHPAD) {
m_directManipulationHelper->onPointerHitTest(pointerId); direct_manipulation_helper_->onPointerHitTest(pointerId);
} }
} }
GHOST_TTrackpadInfo GHOST_WindowWin32::getTrackpadInfo() GHOST_TTrackpadInfo GHOST_WindowWin32::getTrackpadInfo()
{ {
if (!m_directManipulationHelper) { if (!direct_manipulation_helper_) {
return {0, 0, 0}; return {0, 0, 0};
} }
return m_directManipulationHelper->getTrackpadInfo(); return direct_manipulation_helper_->getTrackpadInfo();
} }
GHOST_WindowWin32::~GHOST_WindowWin32() GHOST_WindowWin32::~GHOST_WindowWin32()
{ {
if (m_hWnd) { if (h_wnd_) {
unregisterWindowAppUserModelProperties(); unregisterWindowAppUserModelProperties();
} }
if (m_Bar) { if (bar_) {
m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS); bar_->SetProgressState(h_wnd_, TBPF_NOPROGRESS);
m_Bar->Release(); bar_->Release();
m_Bar = nullptr; bar_ = nullptr;
} }
closeWintab(); closeWintab();
if (m_user32) { if (user32_) {
FreeLibrary(m_user32); FreeLibrary(user32_);
m_user32 = nullptr; user32_ = nullptr;
} }
if (m_customCursor) { if (custom_cursor_) {
DestroyCursor(m_customCursor); DestroyCursor(custom_cursor_);
m_customCursor = nullptr; custom_cursor_ = nullptr;
} }
if (m_hWnd != nullptr && m_hDC != nullptr && releaseNativeHandles()) { if (h_wnd_ != nullptr && h_DC_ != nullptr && releaseNativeHandles()) {
::ReleaseDC(m_hWnd, m_hDC); ::ReleaseDC(h_wnd_, h_DC_);
m_hDC = nullptr; h_DC_ = nullptr;
} }
if (m_hWnd) { if (h_wnd_) {
/* If this window is referenced by others as parent, clear that relation or windows will free /* If this window is referenced by others as parent, clear that relation or windows will free
* the handle while we still reference it. */ * the handle while we still reference it. */
for (GHOST_IWindow *iter_win : m_system->getWindowManager()->getWindows()) { for (GHOST_IWindow *iter_win : system_->getWindowManager()->getWindows()) {
GHOST_WindowWin32 *iter_winwin = (GHOST_WindowWin32 *)iter_win; GHOST_WindowWin32 *iter_winwin = (GHOST_WindowWin32 *)iter_win;
if (iter_winwin->m_parentWindowHwnd == m_hWnd) { if (iter_winwin->parent_window_hwnd_ == h_wnd_) {
::SetWindowLongPtr(iter_winwin->m_hWnd, GWLP_HWNDPARENT, 0); ::SetWindowLongPtr(iter_winwin->h_wnd_, GWLP_HWNDPARENT, 0);
iter_winwin->m_parentWindowHwnd = 0; iter_winwin->parent_window_hwnd_ = 0;
} }
} }
if (m_dropTarget) { if (drop_target_) {
/* Disable DragDrop. */ /* Disable DragDrop. */
RevokeDragDrop(m_hWnd); RevokeDragDrop(h_wnd_);
/* Release our reference of the DropTarget and it will delete itself eventually. */ /* Release our reference of the DropTarget and it will delete itself eventually. */
m_dropTarget->Release(); drop_target_->Release();
m_dropTarget = nullptr; drop_target_ = nullptr;
} }
::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, 0); ::SetWindowLongPtr(h_wnd_, GWLP_USERDATA, 0);
::DestroyWindow(m_hWnd); ::DestroyWindow(h_wnd_);
m_hWnd = 0; h_wnd_ = 0;
} }
delete m_directManipulationHelper; delete direct_manipulation_helper_;
m_directManipulationHelper = nullptr; direct_manipulation_helper_ = nullptr;
} }
void GHOST_WindowWin32::adjustWindowRectForClosestMonitor(LPRECT win_rect, void GHOST_WindowWin32::adjustWindowRectForClosestMonitor(LPRECT win_rect,
@@ -330,9 +330,9 @@ void GHOST_WindowWin32::adjustWindowRectForClosestMonitor(LPRECT win_rect,
/* With Windows 10 and newer we can adjust for chrome that differs with DPI and scale. */ /* With Windows 10 and newer we can adjust for chrome that differs with DPI and scale. */
GHOST_WIN32_AdjustWindowRectExForDpi fpAdjustWindowRectExForDpi = nullptr; GHOST_WIN32_AdjustWindowRectExForDpi fpAdjustWindowRectExForDpi = nullptr;
if (m_user32) { if (user32_) {
fpAdjustWindowRectExForDpi = (GHOST_WIN32_AdjustWindowRectExForDpi)::GetProcAddress( fpAdjustWindowRectExForDpi = (GHOST_WIN32_AdjustWindowRectExForDpi)::GetProcAddress(
m_user32, "AdjustWindowRectExForDpi"); user32_, "AdjustWindowRectExForDpi");
} }
/* Adjust to allow for caption, borders, shadows, scaling, etc. Resulting values can be /* Adjust to allow for caption, borders, shadows, scaling, etc. Resulting values can be
@@ -352,30 +352,30 @@ void GHOST_WindowWin32::adjustWindowRectForClosestMonitor(LPRECT win_rect,
bool GHOST_WindowWin32::getValid() const bool GHOST_WindowWin32::getValid() const
{ {
return GHOST_Window::getValid() && m_hWnd != 0 && m_hDC != 0; return GHOST_Window::getValid() && h_wnd_ != 0 && h_DC_ != 0;
} }
HWND GHOST_WindowWin32::getHWND() const HWND GHOST_WindowWin32::getHWND() const
{ {
return m_hWnd; return h_wnd_;
} }
void *GHOST_WindowWin32::getOSWindow() const void *GHOST_WindowWin32::getOSWindow() const
{ {
return (void *)m_hWnd; return (void *)h_wnd_;
} }
void GHOST_WindowWin32::setTitle(const char *title) void GHOST_WindowWin32::setTitle(const char *title)
{ {
wchar_t *title_16 = alloc_utf16_from_8((char *)title, 0); wchar_t *title_16 = alloc_utf16_from_8((char *)title, 0);
::SetWindowTextW(m_hWnd, (wchar_t *)title_16); ::SetWindowTextW(h_wnd_, (wchar_t *)title_16);
free(title_16); free(title_16);
} }
std::string GHOST_WindowWin32::getTitle() const std::string GHOST_WindowWin32::getTitle() const
{ {
std::wstring wtitle(::GetWindowTextLengthW(m_hWnd) + 1, L'\0'); std::wstring wtitle(::GetWindowTextLengthW(h_wnd_) + 1, L'\0');
::GetWindowTextW(m_hWnd, &wtitle[0], wtitle.capacity()); ::GetWindowTextW(h_wnd_, &wtitle[0], wtitle.capacity());
std::string title(count_utf_8_from_16(wtitle.c_str()) + 1, '\0'); std::string title(count_utf_8_from_16(wtitle.c_str()) + 1, '\0');
conv_utf_16_to_8(wtitle.c_str(), &title[0], title.capacity()); conv_utf_16_to_8(wtitle.c_str(), &title[0], title.capacity());
@@ -388,11 +388,11 @@ GHOST_TSuccess GHOST_WindowWin32::applyWindowDecorationStyle()
/* DWMWINDOWATTRIBUTE::DWMWA_CAPTION_COLOR */ /* DWMWINDOWATTRIBUTE::DWMWA_CAPTION_COLOR */
constexpr DWORD caption_color_attr = 35; constexpr DWORD caption_color_attr = 35;
if (m_windowDecorationStyleFlags & GHOST_kDecorationColoredTitleBar) { if (window_decoration_style_flags_ & GHOST_kDecorationColoredTitleBar) {
const float *color = m_windowDecorationStyleSettings.colored_titlebar_bg_color; const float *color = window_decoration_style_settings_.colored_titlebar_bg_color;
const COLORREF colorref = RGB( const COLORREF colorref = RGB(
char(color[0] * 255.0f), char(color[1] * 255.0f), char(color[2] * 255.0f)); char(color[0] * 255.0f), char(color[1] * 255.0f), char(color[2] * 255.0f));
if (!SUCCEEDED(DwmSetWindowAttribute(m_hWnd, caption_color_attr, &colorref, sizeof(colorref)))) if (!SUCCEEDED(DwmSetWindowAttribute(h_wnd_, caption_color_attr, &colorref, sizeof(colorref))))
{ {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -403,39 +403,39 @@ GHOST_TSuccess GHOST_WindowWin32::applyWindowDecorationStyle()
void GHOST_WindowWin32::getWindowBounds(GHOST_Rect &bounds) const void GHOST_WindowWin32::getWindowBounds(GHOST_Rect &bounds) const
{ {
RECT rect; RECT rect;
::GetWindowRect(m_hWnd, &rect); ::GetWindowRect(h_wnd_, &rect);
bounds.m_b = rect.bottom; bounds.b_ = rect.bottom;
bounds.m_l = rect.left; bounds.l_ = rect.left;
bounds.m_r = rect.right; bounds.r_ = rect.right;
bounds.m_t = rect.top; bounds.t_ = rect.top;
} }
void GHOST_WindowWin32::getClientBounds(GHOST_Rect &bounds) const void GHOST_WindowWin32::getClientBounds(GHOST_Rect &bounds) const
{ {
RECT rect; RECT rect;
POINT coord; POINT coord;
if (!IsIconic(m_hWnd)) { if (!IsIconic(h_wnd_)) {
::GetClientRect(m_hWnd, &rect); ::GetClientRect(h_wnd_, &rect);
coord.x = rect.left; coord.x = rect.left;
coord.y = rect.top; coord.y = rect.top;
::ClientToScreen(m_hWnd, &coord); ::ClientToScreen(h_wnd_, &coord);
bounds.m_l = coord.x; bounds.l_ = coord.x;
bounds.m_t = coord.y; bounds.t_ = coord.y;
coord.x = rect.right; coord.x = rect.right;
coord.y = rect.bottom; coord.y = rect.bottom;
::ClientToScreen(m_hWnd, &coord); ::ClientToScreen(h_wnd_, &coord);
bounds.m_r = coord.x; bounds.r_ = coord.x;
bounds.m_b = coord.y; bounds.b_ = coord.y;
} }
else { else {
bounds.m_b = 0; bounds.b_ = 0;
bounds.m_l = 0; bounds.l_ = 0;
bounds.m_r = 0; bounds.r_ = 0;
bounds.m_t = 0; bounds.t_ = 0;
} }
} }
@@ -448,7 +448,7 @@ GHOST_TSuccess GHOST_WindowWin32::setClientWidth(uint32_t width)
getWindowBounds(wBnds); getWindowBounds(wBnds);
int cx = wBnds.getWidth() + width - cBnds.getWidth(); int cx = wBnds.getWidth() + width - cBnds.getWidth();
int cy = wBnds.getHeight(); int cy = wBnds.getHeight();
success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ? success = ::SetWindowPos(h_wnd_, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
GHOST_kSuccess : GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
} }
@@ -467,7 +467,7 @@ GHOST_TSuccess GHOST_WindowWin32::setClientHeight(uint32_t height)
getWindowBounds(wBnds); getWindowBounds(wBnds);
int cx = wBnds.getWidth(); int cx = wBnds.getWidth();
int cy = wBnds.getHeight() + height - cBnds.getHeight(); int cy = wBnds.getHeight() + height - cBnds.getHeight();
success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ? success = ::SetWindowPos(h_wnd_, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
GHOST_kSuccess : GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
} }
@@ -486,7 +486,7 @@ GHOST_TSuccess GHOST_WindowWin32::setClientSize(uint32_t width, uint32_t height)
getWindowBounds(wBnds); getWindowBounds(wBnds);
int cx = wBnds.getWidth() + width - cBnds.getWidth(); int cx = wBnds.getWidth() + width - cBnds.getWidth();
int cy = wBnds.getHeight() + height - cBnds.getHeight(); int cy = wBnds.getHeight() + height - cBnds.getHeight();
success = ::SetWindowPos(m_hWnd, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ? success = ::SetWindowPos(h_wnd_, HWND_TOP, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOZORDER) ?
GHOST_kSuccess : GHOST_kSuccess :
GHOST_kFailure; GHOST_kFailure;
} }
@@ -498,11 +498,11 @@ GHOST_TSuccess GHOST_WindowWin32::setClientSize(uint32_t width, uint32_t height)
GHOST_TWindowState GHOST_WindowWin32::getState() const GHOST_TWindowState GHOST_WindowWin32::getState() const
{ {
if (::IsIconic(m_hWnd)) { if (::IsIconic(h_wnd_)) {
return GHOST_kWindowStateMinimized; return GHOST_kWindowStateMinimized;
} }
else if (::IsZoomed(m_hWnd)) { else if (::IsZoomed(h_wnd_)) {
LONG_PTR result = ::GetWindowLongPtr(m_hWnd, GWL_STYLE); LONG_PTR result = ::GetWindowLongPtr(h_wnd_, GWL_STYLE);
return (result & WS_CAPTION) ? GHOST_kWindowStateMaximized : GHOST_kWindowStateFullScreen; return (result & WS_CAPTION) ? GHOST_kWindowStateMaximized : GHOST_kWindowStateFullScreen;
} }
return GHOST_kWindowStateNormal; return GHOST_kWindowStateNormal;
@@ -514,7 +514,7 @@ void GHOST_WindowWin32::screenToClient(int32_t inX,
int32_t &outY) const int32_t &outY) const
{ {
POINT point = {inX, inY}; POINT point = {inX, inY};
::ScreenToClient(m_hWnd, &point); ::ScreenToClient(h_wnd_, &point);
outX = point.x; outX = point.x;
outY = point.y; outY = point.y;
} }
@@ -525,7 +525,7 @@ void GHOST_WindowWin32::clientToScreen(int32_t inX,
int32_t &outY) const int32_t &outY) const
{ {
POINT point = {inX, inY}; POINT point = {inX, inY};
::ClientToScreen(m_hWnd, &point); ::ClientToScreen(h_wnd_, &point);
outX = point.x; outX = point.x;
outY = point.y; outY = point.y;
} }
@@ -533,10 +533,10 @@ void GHOST_WindowWin32::clientToScreen(int32_t inX,
GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state) GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
{ {
GHOST_TWindowState curstate = getState(); GHOST_TWindowState curstate = getState();
LONG_PTR style = GetWindowLongPtr(m_hWnd, GWL_STYLE) | WS_CAPTION; LONG_PTR style = GetWindowLongPtr(h_wnd_, GWL_STYLE) | WS_CAPTION;
WINDOWPLACEMENT wp; WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT); wp.length = sizeof(WINDOWPLACEMENT);
::GetWindowPlacement(m_hWnd, &wp); ::GetWindowPlacement(h_wnd_, &wp);
switch (state) { switch (state) {
case GHOST_kWindowStateMinimized: case GHOST_kWindowStateMinimized:
@@ -547,7 +547,7 @@ GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
break; break;
case GHOST_kWindowStateFullScreen: case GHOST_kWindowStateFullScreen:
if (curstate != state && curstate != GHOST_kWindowStateMinimized) { if (curstate != state && curstate != GHOST_kWindowStateMinimized) {
m_normal_state = curstate; normal_state_ = curstate;
} }
wp.showCmd = SW_SHOWMAXIMIZED; wp.showCmd = SW_SHOWMAXIMIZED;
wp.ptMaxPosition.x = 0; wp.ptMaxPosition.x = 0;
@@ -556,22 +556,21 @@ GHOST_TSuccess GHOST_WindowWin32::setState(GHOST_TWindowState state)
break; break;
case GHOST_kWindowStateNormal: case GHOST_kWindowStateNormal:
default: default:
if (curstate == GHOST_kWindowStateFullScreen && if (curstate == GHOST_kWindowStateFullScreen && normal_state_ == GHOST_kWindowStateMaximized)
m_normal_state == GHOST_kWindowStateMaximized)
{ {
wp.showCmd = SW_SHOWMAXIMIZED; wp.showCmd = SW_SHOWMAXIMIZED;
m_normal_state = GHOST_kWindowStateNormal; normal_state_ = GHOST_kWindowStateNormal;
} }
else { else {
wp.showCmd = SW_SHOWNORMAL; wp.showCmd = SW_SHOWNORMAL;
} }
break; break;
} }
::SetWindowLongPtr(m_hWnd, GWL_STYLE, style); ::SetWindowLongPtr(h_wnd_, GWL_STYLE, style);
/* #SetWindowLongPtr Docs: /* #SetWindowLongPtr Docs:
* Frame changes not visible until #SetWindowPos with #SWP_FRAMECHANGED. */ * Frame changes not visible until #SetWindowPos with #SWP_FRAMECHANGED. */
::SetWindowPos(m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); ::SetWindowPos(h_wnd_, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
return ::SetWindowPlacement(m_hWnd, &wp) == TRUE ? GHOST_kSuccess : GHOST_kFailure; return ::SetWindowPlacement(h_wnd_, &wp) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order) GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
@@ -580,7 +579,7 @@ GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
if (order == GHOST_kWindowOrderBottom) { if (order == GHOST_kWindowOrderBottom) {
hWndInsertAfter = HWND_BOTTOM; hWndInsertAfter = HWND_BOTTOM;
hWndToRaise = ::GetWindow(m_hWnd, GW_HWNDNEXT); /* the window to raise */ hWndToRaise = ::GetWindow(h_wnd_, GW_HWNDNEXT); /* the window to raise */
} }
else { else {
if (getState() == GHOST_kWindowStateMinimized) { if (getState() == GHOST_kWindowStateMinimized) {
@@ -590,7 +589,7 @@ GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
hWndToRaise = nullptr; hWndToRaise = nullptr;
} }
if (::SetWindowPos(m_hWnd, hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == FALSE) { if (::SetWindowPos(h_wnd_, hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) == FALSE) {
return GHOST_kFailure; return GHOST_kFailure;
} }
@@ -605,8 +604,8 @@ GHOST_TSuccess GHOST_WindowWin32::setOrder(GHOST_TWindowOrder order)
GHOST_TSuccess GHOST_WindowWin32::invalidate() GHOST_TSuccess GHOST_WindowWin32::invalidate()
{ {
GHOST_TSuccess success; GHOST_TSuccess success;
if (m_hWnd) { if (h_wnd_) {
success = ::InvalidateRect(m_hWnd, 0, FALSE) != 0 ? GHOST_kSuccess : GHOST_kFailure; success = ::InvalidateRect(h_wnd_, 0, FALSE) != 0 ? GHOST_kSuccess : GHOST_kFailure;
} }
else { else {
success = GHOST_kFailure; success = GHOST_kFailure;
@@ -620,7 +619,7 @@ GHOST_Context *GHOST_WindowWin32::newDrawingContext(GHOST_TDrawingContextType ty
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK( GHOST_Context *context = new GHOST_ContextVK(
m_want_context_params, m_hWnd, 1, 2, m_preferred_device); want_context_params_, h_wnd_, 1, 2, preferred_device_);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -633,14 +632,14 @@ GHOST_Context *GHOST_WindowWin32::newDrawingContext(GHOST_TDrawingContextType ty
case GHOST_kDrawingContextTypeOpenGL: { case GHOST_kDrawingContextTypeOpenGL: {
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
GHOST_Context *context = new GHOST_ContextWGL( GHOST_Context *context = new GHOST_ContextWGL(
m_want_context_params, want_context_params_,
false, false,
m_hWnd, h_wnd_,
m_hDC, h_DC_,
WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
4, 4,
minor, minor,
(m_want_context_params.is_debug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0), (want_context_params_.is_debug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY); GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
@@ -653,7 +652,7 @@ GHOST_Context *GHOST_WindowWin32::newDrawingContext(GHOST_TDrawingContextType ty
#endif #endif
case GHOST_kDrawingContextTypeD3D: { case GHOST_kDrawingContextTypeD3D: {
GHOST_Context *context = new GHOST_ContextD3D(m_want_context_params, m_hWnd); GHOST_Context *context = new GHOST_ContextD3D(want_context_params_, h_wnd_);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
@@ -670,44 +669,44 @@ GHOST_Context *GHOST_WindowWin32::newDrawingContext(GHOST_TDrawingContextType ty
void GHOST_WindowWin32::lostMouseCapture() void GHOST_WindowWin32::lostMouseCapture()
{ {
if (m_hasMouseCaptured) { if (has_mouse_captured_) {
m_hasGrabMouse = false; has_grab_mouse_ = false;
m_nPressedButtons = 0; n_pressed_buttons_ = 0;
m_hasMouseCaptured = false; has_mouse_captured_ = false;
} }
} }
bool GHOST_WindowWin32::isDialog() const bool GHOST_WindowWin32::isDialog() const
{ {
return m_isDialog; return is_dialog_;
} }
void GHOST_WindowWin32::updateMouseCapture(GHOST_MouseCaptureEventWin32 event) void GHOST_WindowWin32::updateMouseCapture(GHOST_MouseCaptureEventWin32 event)
{ {
switch (event) { switch (event) {
case MousePressed: case MousePressed:
m_nPressedButtons++; n_pressed_buttons_++;
break; break;
case MouseReleased: case MouseReleased:
if (m_nPressedButtons) { if (n_pressed_buttons_) {
m_nPressedButtons--; n_pressed_buttons_--;
} }
break; break;
case OperatorGrab: case OperatorGrab:
m_hasGrabMouse = true; has_grab_mouse_ = true;
break; break;
case OperatorUngrab: case OperatorUngrab:
m_hasGrabMouse = false; has_grab_mouse_ = false;
break; break;
} }
if (!m_nPressedButtons && !m_hasGrabMouse && m_hasMouseCaptured) { if (!n_pressed_buttons_ && !has_grab_mouse_ && has_mouse_captured_) {
::ReleaseCapture(); ::ReleaseCapture();
m_hasMouseCaptured = false; has_mouse_captured_ = false;
} }
else if ((m_nPressedButtons || m_hasGrabMouse) && !m_hasMouseCaptured) { else if ((n_pressed_buttons_ || has_grab_mouse_) && !has_mouse_captured_) {
::SetCapture(m_hWnd); ::SetCapture(h_wnd_);
m_hasMouseCaptured = true; has_mouse_captured_ = true;
} }
} }
@@ -720,8 +719,8 @@ HCURSOR GHOST_WindowWin32::getStandardCursor(GHOST_TStandardCursor shape) const
switch (shape) { switch (shape) {
case GHOST_kStandardCursorCustom: case GHOST_kStandardCursorCustom:
if (m_customCursor) { if (custom_cursor_) {
return m_customCursor; return custom_cursor_;
} }
else { else {
return nullptr; return nullptr;
@@ -789,7 +788,7 @@ void GHOST_WindowWin32::loadCursor(bool visible, GHOST_TStandardCursor shape) co
GHOST_TSuccess GHOST_WindowWin32::setWindowCursorVisibility(bool visible) GHOST_TSuccess GHOST_WindowWin32::setWindowCursorVisibility(bool visible)
{ {
if (::GetForegroundWindow() == m_hWnd) { if (::GetForegroundWindow() == h_wnd_) {
loadCursor(visible, getCursorShape()); loadCursor(visible, getCursorShape());
} }
@@ -800,7 +799,7 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCursorGrab(GHOST_TGrabCursorMode mode
{ {
if (mode != GHOST_kGrabDisable) { if (mode != GHOST_kGrabDisable) {
if (mode != GHOST_kGrabNormal) { if (mode != GHOST_kGrabNormal) {
m_system->getCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]); system_->getCursorPosition(cursor_grab_init_pos_[0], cursor_grab_init_pos_[1]);
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
if (mode == GHOST_kGrabHide) { if (mode == GHOST_kGrabHide) {
@@ -810,41 +809,41 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCursorGrab(GHOST_TGrabCursorMode mode
updateMouseCapture(OperatorGrab); updateMouseCapture(OperatorGrab);
} }
else { else {
if (m_cursorGrab == GHOST_kGrabHide) { if (cursor_grab_ == GHOST_kGrabHide) {
m_system->setCursorPosition(m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]); system_->setCursorPosition(cursor_grab_init_pos_[0], cursor_grab_init_pos_[1]);
setWindowCursorVisibility(true); setWindowCursorVisibility(true);
} }
if (m_cursorGrab != GHOST_kGrabNormal) { if (cursor_grab_ != GHOST_kGrabNormal) {
/* Use to generate a mouse move event, otherwise the last event /* Use to generate a mouse move event, otherwise the last event
* blender gets can be outside the screen causing menus not to show * blender gets can be outside the screen causing menus not to show
* properly unless the user moves the mouse. */ * properly unless the user moves the mouse. */
int32_t pos[2]; int32_t pos[2];
m_system->getCursorPosition(pos[0], pos[1]); system_->getCursorPosition(pos[0], pos[1]);
m_system->setCursorPosition(pos[0], pos[1]); system_->setCursorPosition(pos[0], pos[1]);
} }
/* Almost works without but important otherwise the mouse GHOST location /* Almost works without but important otherwise the mouse GHOST location
* can be incorrect on exit. */ * can be incorrect on exit. */
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; /* disable */ cursor_grab_bounds_.l_ = cursor_grab_bounds_.r_ = -1; /* disable */
updateMouseCapture(OperatorUngrab); updateMouseCapture(OperatorUngrab);
} }
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cursorShape) GHOST_TSuccess GHOST_WindowWin32::setWindowCursorShape(GHOST_TStandardCursor cursor_shape)
{ {
if (::GetForegroundWindow() == m_hWnd) { if (::GetForegroundWindow() == h_wnd_) {
loadCursor(getCursorVisibility(), cursorShape); loadCursor(getCursorVisibility(), cursor_shape);
} }
return GHOST_kSuccess; return GHOST_kSuccess;
} }
GHOST_TSuccess GHOST_WindowWin32::hasCursorShape(GHOST_TStandardCursor cursorShape) GHOST_TSuccess GHOST_WindowWin32::hasCursorShape(GHOST_TStandardCursor cursor_shape)
{ {
return (getStandardCursor(cursorShape)) ? GHOST_kSuccess : GHOST_kFailure; return (getStandardCursor(cursor_shape)) ? GHOST_kSuccess : GHOST_kFailure;
} }
GHOST_TSuccess GHOST_WindowWin32::getPointerInfo( GHOST_TSuccess GHOST_WindowWin32::getPointerInfo(
@@ -930,7 +929,7 @@ GHOST_TSuccess GHOST_WindowWin32::getPointerInfo(
} }
if (!outPointerInfo.empty()) { if (!outPointerInfo.empty()) {
m_lastPointerTabletData = outPointerInfo.back().tabletData; last_pointer_tablet_data_ = outPointerInfo.back().tabletData;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -938,31 +937,31 @@ GHOST_TSuccess GHOST_WindowWin32::getPointerInfo(
void GHOST_WindowWin32::resetPointerPenInfo() void GHOST_WindowWin32::resetPointerPenInfo()
{ {
m_lastPointerTabletData = GHOST_TABLET_DATA_NONE; last_pointer_tablet_data_ = GHOST_TABLET_DATA_NONE;
} }
GHOST_Wintab *GHOST_WindowWin32::getWintab() const GHOST_Wintab *GHOST_WindowWin32::getWintab() const
{ {
return m_wintab; return wintab_;
} }
void GHOST_WindowWin32::loadWintab(bool enable) void GHOST_WindowWin32::loadWintab(bool enable)
{ {
if (!m_wintab) { if (!wintab_) {
WINTAB_PRINTF("Loading Wintab for window %p\n", m_hWnd); WINTAB_PRINTF("Loading Wintab for window %p\n", h_wnd_);
if (m_wintab = GHOST_Wintab::loadWintab(m_hWnd)) { if (wintab_ = GHOST_Wintab::loadWintab(h_wnd_)) {
if (enable) { if (enable) {
m_wintab->enable(); wintab_->enable();
/* Focus Wintab if cursor is inside this window. This ensures Wintab is enabled when the /* Focus Wintab if cursor is inside this window. This ensures Wintab is enabled when the
* tablet is used to change the Tablet API. */ * tablet is used to change the Tablet API. */
int32_t x, y; int32_t x, y;
if (m_system->getCursorPosition(x, y)) { if (system_->getCursorPosition(x, y)) {
GHOST_Rect rect; GHOST_Rect rect;
getClientBounds(rect); getClientBounds(rect);
if (rect.isInside(x, y)) { if (rect.isInside(x, y)) {
m_wintab->gainFocus(); wintab_->gainFocus();
} }
} }
} }
@@ -972,18 +971,18 @@ void GHOST_WindowWin32::loadWintab(bool enable)
void GHOST_WindowWin32::closeWintab() void GHOST_WindowWin32::closeWintab()
{ {
WINTAB_PRINTF("Closing Wintab for window %p\n", m_hWnd); WINTAB_PRINTF("Closing Wintab for window %p\n", h_wnd_);
delete m_wintab; delete wintab_;
m_wintab = nullptr; wintab_ = nullptr;
} }
bool GHOST_WindowWin32::usingTabletAPI(GHOST_TTabletAPI api) const bool GHOST_WindowWin32::usingTabletAPI(GHOST_TTabletAPI api) const
{ {
if (m_system->getTabletAPI() == api) { if (system_->getTabletAPI() == api) {
return true; return true;
} }
else if (m_system->getTabletAPI() == GHOST_kTabletAutomatic) { else if (system_->getTabletAPI() == GHOST_kTabletAutomatic) {
if (m_wintab && m_wintab->devicesPresent()) { if (wintab_ && wintab_->devicesPresent()) {
return api == GHOST_kTabletWintab; return api == GHOST_kTabletWintab;
} }
else { else {
@@ -998,10 +997,10 @@ bool GHOST_WindowWin32::usingTabletAPI(GHOST_TTabletAPI api) const
GHOST_TabletData GHOST_WindowWin32::getTabletData() GHOST_TabletData GHOST_WindowWin32::getTabletData()
{ {
if (usingTabletAPI(GHOST_kTabletWintab)) { if (usingTabletAPI(GHOST_kTabletWintab)) {
return m_wintab ? m_wintab->getLastTabletData() : GHOST_TABLET_DATA_NONE; return wintab_ ? wintab_->getLastTabletData() : GHOST_TABLET_DATA_NONE;
} }
else { else {
return m_lastPointerTabletData; return last_pointer_tablet_data_;
} }
} }
@@ -1022,25 +1021,25 @@ void GHOST_WindowWin32::ThemeRefresh()
/* `20 == DWMWA_USE_IMMERSIVE_DARK_MODE` in Windows 11 SDK. /* `20 == DWMWA_USE_IMMERSIVE_DARK_MODE` in Windows 11 SDK.
* This value was undocumented for Windows 10 versions 2004 and later, * This value was undocumented for Windows 10 versions 2004 and later,
* supported for Windows 11 Build 22000 and later. */ * supported for Windows 11 Build 22000 and later. */
DwmSetWindowAttribute(this->m_hWnd, 20, &DarkMode, sizeof(DarkMode)); DwmSetWindowAttribute(this->h_wnd_, 20, &DarkMode, sizeof(DarkMode));
} }
} }
void GHOST_WindowWin32::updateDPI() void GHOST_WindowWin32::updateDPI()
{ {
if (m_directManipulationHelper) { if (direct_manipulation_helper_) {
m_directManipulationHelper->setDPI(getDPIHint()); direct_manipulation_helper_->setDPI(getDPIHint());
} }
} }
uint16_t GHOST_WindowWin32::getDPIHint() uint16_t GHOST_WindowWin32::getDPIHint()
{ {
if (m_user32) { if (user32_) {
GHOST_WIN32_GetDpiForWindow fpGetDpiForWindow = (GHOST_WIN32_GetDpiForWindow)::GetProcAddress( GHOST_WIN32_GetDpiForWindow fpGetDpiForWindow = (GHOST_WIN32_GetDpiForWindow)::GetProcAddress(
m_user32, "GetDpiForWindow"); user32_, "GetDpiForWindow");
if (fpGetDpiForWindow) { if (fpGetDpiForWindow) {
return fpGetDpiForWindow(this->m_hWnd); return fpGetDpiForWindow(this->h_wnd_);
} }
} }
@@ -1086,9 +1085,9 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(const uint8_t *bitm
cols++; cols++;
} }
if (m_customCursor) { if (custom_cursor_) {
DestroyCursor(m_customCursor); DestroyCursor(custom_cursor_);
m_customCursor = nullptr; custom_cursor_ = nullptr;
} }
memset(&andData, 0xFF, sizeof(andData)); memset(&andData, 0xFF, sizeof(andData));
@@ -1107,14 +1106,14 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(const uint8_t *bitm
andData[y] = ~fullMaskRow; andData[y] = ~fullMaskRow;
} }
m_customCursor = ::CreateCursor( custom_cursor_ = ::CreateCursor(
::GetModuleHandle(0), hot_spot[0], hot_spot[1], 32, 32, andData, xorData); ::GetModuleHandle(0), hot_spot[0], hot_spot[1], 32, 32, andData, xorData);
if (!m_customCursor) { if (!custom_cursor_) {
return GHOST_kFailure; return GHOST_kFailure;
} }
if (::GetForegroundWindow() == m_hWnd) { if (::GetForegroundWindow() == h_wnd_) {
loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom); loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
} }
@@ -1138,7 +1137,7 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(const uint8_t *bitm
header.bV5BlueMask = 0x000000FF; header.bV5BlueMask = 0x000000FF;
header.bV5AlphaMask = 0xFF000000; header.bV5AlphaMask = 0xFF000000;
HDC hdc = GetDC(m_hWnd); HDC hdc = GetDC(h_wnd_);
void *bits = nullptr; void *bits = nullptr;
HBITMAP bmp = CreateDIBSection( HBITMAP bmp = CreateDIBSection(
hdc, (BITMAPINFO *)&header, DIB_RGB_COLORS, (void **)&bits, NULL, (DWORD)0); hdc, (BITMAPINFO *)&header, DIB_RGB_COLORS, (void **)&bits, NULL, (DWORD)0);
@@ -1166,15 +1165,15 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(const uint8_t *bitm
icon_info.hbmMask = empty_mask; icon_info.hbmMask = empty_mask;
icon_info.hbmColor = bmp; icon_info.hbmColor = bmp;
m_customCursor = CreateIconIndirect(&icon_info); custom_cursor_ = CreateIconIndirect(&icon_info);
DeleteObject(bmp); DeleteObject(bmp);
DeleteObject(empty_mask); DeleteObject(empty_mask);
if (!m_customCursor) { if (!custom_cursor_) {
return GHOST_kFailure; return GHOST_kFailure;
} }
if (::GetForegroundWindow() == m_hWnd) { if (::GetForegroundWindow() == h_wnd_) {
loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom); loadCursor(getCursorVisibility(), GHOST_kStandardCursorCustom);
} }
@@ -1184,7 +1183,7 @@ GHOST_TSuccess GHOST_WindowWin32::setWindowCustomCursorShape(const uint8_t *bitm
GHOST_TSuccess GHOST_WindowWin32::setProgressBar(float progress) GHOST_TSuccess GHOST_WindowWin32::setProgressBar(float progress)
{ {
/* #SetProgressValue sets state to #TBPF_NORMAL automatically. */ /* #SetProgressValue sets state to #TBPF_NORMAL automatically. */
if (m_Bar && S_OK == m_Bar->SetProgressValue(m_hWnd, 10000 * progress, 10000)) { if (bar_ && S_OK == bar_->SetProgressValue(h_wnd_, 10000 * progress, 10000)) {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1193,7 +1192,7 @@ GHOST_TSuccess GHOST_WindowWin32::setProgressBar(float progress)
GHOST_TSuccess GHOST_WindowWin32::endProgressBar() GHOST_TSuccess GHOST_WindowWin32::endProgressBar()
{ {
if (m_Bar && S_OK == m_Bar->SetProgressState(m_hWnd, TBPF_NOPROGRESS)) { if (bar_ && S_OK == bar_->SetProgressState(h_wnd_, TBPF_NOPROGRESS)) {
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1203,12 +1202,12 @@ GHOST_TSuccess GHOST_WindowWin32::endProgressBar()
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
void GHOST_WindowWin32::beginIME(int32_t x, int32_t y, int32_t /*w*/, int32_t h, bool completed) void GHOST_WindowWin32::beginIME(int32_t x, int32_t y, int32_t /*w*/, int32_t h, bool completed)
{ {
m_imeInput.BeginIME(m_hWnd, GHOST_Rect(x, y - h, x, y), completed); ime_input_.BeginIME(h_wnd_, GHOST_Rect(x, y - h, x, y), completed);
} }
void GHOST_WindowWin32::endIME() void GHOST_WindowWin32::endIME()
{ {
m_imeInput.EndIME(m_hWnd); ime_input_.EndIME(h_wnd_);
} }
#endif /* WITH_INPUT_IME */ #endif /* WITH_INPUT_IME */
@@ -1225,7 +1224,7 @@ void GHOST_WindowWin32::registerWindowAppUserModelProperties()
return; return;
} }
HRESULT hr = SHGetPropertyStoreForWindow(m_hWnd, IID_PPV_ARGS(&pstore)); HRESULT hr = SHGetPropertyStoreForWindow(h_wnd_, IID_PPV_ARGS(&pstore));
if (!SUCCEEDED(hr)) { if (!SUCCEEDED(hr)) {
return; return;
} }
@@ -1253,7 +1252,7 @@ void GHOST_WindowWin32::registerWindowAppUserModelProperties()
void GHOST_WindowWin32::unregisterWindowAppUserModelProperties() void GHOST_WindowWin32::unregisterWindowAppUserModelProperties()
{ {
IPropertyStore *pstore; IPropertyStore *pstore;
HRESULT hr = SHGetPropertyStoreForWindow(m_hWnd, IID_PPV_ARGS(&pstore)); HRESULT hr = SHGetPropertyStoreForWindow(h_wnd_, IID_PPV_ARGS(&pstore));
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
PROPVARIANT value; PROPVARIANT value;
PropVariantInit(&value); PropVariantInit(&value);

View File

@@ -77,7 +77,7 @@ class GHOST_WindowWin32 : public GHOST_Window {
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
GHOST_WindowWin32 *parentWindow, GHOST_WindowWin32 *parent_window,
bool dialog, bool dialog,
const GHOST_GPUDevice &preferred_device); const GHOST_GPUDevice &preferred_device);
@@ -238,10 +238,10 @@ class GHOST_WindowWin32 : public GHOST_Window {
/** /**
* Loads the windows equivalent of a standard GHOST cursor. * Loads the windows equivalent of a standard GHOST cursor.
* \param visible: Flag for cursor visibility. * \param visible: Flag for cursor visibility.
* \param cursorShape: The cursor shape. * \param cursor_shape: The cursor shape.
*/ */
HCURSOR getStandardCursor(GHOST_TStandardCursor shape) const; HCURSOR getStandardCursor(GHOST_TStandardCursor shape) const;
void loadCursor(bool visible, GHOST_TStandardCursor cursorShape) const; void loadCursor(bool visible, GHOST_TStandardCursor cursor_shape) const;
/** /**
* Query whether given tablet API should be used. * Query whether given tablet API should be used.
@@ -294,10 +294,10 @@ class GHOST_WindowWin32 : public GHOST_Window {
uint16_t getDPIHint() override; uint16_t getDPIHint() override;
/** True if the mouse is either over or captured by the window. */ /** True if the mouse is either over or captured by the window. */
bool m_mousePresent; bool mouse_present_;
/** True if the window currently resizing. */ /** True if the window currently resizing. */
bool m_inLiveResize; bool in_live_resize_;
/** Called when OS colors change and when the window is created. */ /** Called when OS colors change and when the window is created. */
void ThemeRefresh(); void ThemeRefresh();
@@ -305,7 +305,7 @@ class GHOST_WindowWin32 : public GHOST_Window {
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
GHOST_ImeWin32 *getImeInput() GHOST_ImeWin32 *getImeInput()
{ {
return &m_imeInput; return &ime_input_;
} }
void beginIME(int32_t x, int32_t y, int32_t w, int32_t h, bool completed); void beginIME(int32_t x, int32_t y, int32_t w, int32_t h, bool completed);
@@ -368,52 +368,52 @@ class GHOST_WindowWin32 : public GHOST_Window {
void unregisterWindowAppUserModelProperties(); void unregisterWindowAppUserModelProperties();
/** Pointer to system. */ /** Pointer to system. */
GHOST_SystemWin32 *m_system; GHOST_SystemWin32 *system_;
/** Pointer to COM #IDropTarget implementer. */ /** Pointer to COM #IDropTarget implementer. */
GHOST_DropTargetWin32 *m_dropTarget; GHOST_DropTargetWin32 *drop_target_;
/** Window handle. */ /** Window handle. */
HWND m_hWnd; HWND h_wnd_;
/** Device context handle. */ /** Device context handle. */
HDC m_hDC; HDC h_DC_;
bool m_isDialog; bool is_dialog_;
GHOST_GPUDevice m_preferred_device; GHOST_GPUDevice preferred_device_;
/** Flag for if window has captured the mouse. */ /** Flag for if window has captured the mouse. */
bool m_hasMouseCaptured; bool has_mouse_captured_;
/** /**
* Flag if an operator grabs the mouse with #WM_cursor_grab_enable, #WM_cursor_grab_disable * Flag if an operator grabs the mouse with #WM_cursor_grab_enable, #WM_cursor_grab_disable
* Multiple grabs must be released with a single un-grab. * Multiple grabs must be released with a single un-grab.
*/ */
bool m_hasGrabMouse; bool has_grab_mouse_;
/** Count of number of pressed buttons. */ /** Count of number of pressed buttons. */
int m_nPressedButtons; int n_pressed_buttons_;
/** HCURSOR structure of the custom cursor. */ /** HCURSOR structure of the custom cursor. */
HCURSOR m_customCursor; HCURSOR custom_cursor_;
/** ITaskbarList3 structure for progress bar. */ /** ITaskbarList3 structure for progress bar. */
ITaskbarList3 *m_Bar; ITaskbarList3 *bar_;
static const wchar_t *s_windowClassName; static const wchar_t *s_windowClassName;
static const int s_maxTitleLength; static const int s_maxTitleLength;
/** Pointer to Wintab manager if Wintab is loaded. */ /** Pointer to Wintab manager if Wintab is loaded. */
GHOST_Wintab *m_wintab; GHOST_Wintab *wintab_;
/** Most recent tablet data. */ /** Most recent tablet data. */
GHOST_TabletData m_lastPointerTabletData; GHOST_TabletData last_pointer_tablet_data_;
GHOST_TWindowState m_normal_state; GHOST_TWindowState normal_state_;
/** `user32.dll` handle */ /** `user32.dll` handle */
HMODULE m_user32; HMODULE user32_;
HWND m_parentWindowHwnd; HWND parent_window_hwnd_;
GHOST_DirectManipulationHelper *m_directManipulationHelper; GHOST_DirectManipulationHelper *direct_manipulation_helper_;
#ifdef WITH_INPUT_IME #ifdef WITH_INPUT_IME
/** Handle input method editors event */ /** Handle input method editors event */
GHOST_ImeWin32 m_imeInput; GHOST_ImeWin32 ime_input_;
#endif #endif
}; };

View File

@@ -107,46 +107,46 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_WindowX11 *parentWindow, GHOST_WindowX11 *parent_window,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const bool is_dialog, const bool is_dialog,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
const bool exclusive, const bool exclusive,
const GHOST_GPUDevice &preferred_device) const GHOST_GPUDevice &preferred_device)
: GHOST_Window(width, height, state, context_params, exclusive), : GHOST_Window(width, height, state, context_params, exclusive),
m_display(display), display_(display),
m_visualInfo(nullptr), visual_info_(nullptr),
m_fbconfig(nullptr), fbconfig_(nullptr),
m_normal_state(GHOST_kWindowStateNormal), normal_state_(GHOST_kWindowStateNormal),
m_system(system), system_(system),
m_invalid_window(false), invalid_window_(false),
m_empty_cursor(None), empty_cursor_(None),
m_custom_cursor(None), custom_cursor_(None),
m_visible_cursor(None), visible_cursor_(None),
#ifdef WITH_XDND #ifdef WITH_XDND
m_dropTarget(nullptr), drop_target_(nullptr),
#endif #endif
m_tabletData(GHOST_TABLET_DATA_NONE), tablet_data_(GHOST_TABLET_DATA_NONE),
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
m_xic(nullptr), xic_(nullptr),
#endif #endif
m_valid_setup(false), valid_setup_(false),
m_preferred_device(preferred_device) preferred_device_(preferred_device)
{ {
#ifdef WITH_OPENGL_BACKEND #ifdef WITH_OPENGL_BACKEND
if (type == GHOST_kDrawingContextTypeOpenGL) { if (type == GHOST_kDrawingContextTypeOpenGL) {
m_visualInfo = get_x11_visualinfo(m_display); visual_info_ = get_x11_visualinfo(display_);
} }
else else
#endif #endif
{ {
XVisualInfo tmp = {nullptr}; XVisualInfo tmp = {nullptr};
int n; int n;
m_visualInfo = XGetVisualInfo(m_display, 0, &tmp, &n); visual_info_ = XGetVisualInfo(display_, 0, &tmp, &n);
} }
/* caller needs to check 'getValid()' */ /* caller needs to check 'getValid()' */
if (m_visualInfo == nullptr) { if (visual_info_ == nullptr) {
fprintf(stderr, "initial window could not find the GLX extension\n"); fprintf(stderr, "initial window could not find the GLX extension\n");
return; return;
} }
@@ -174,25 +174,25 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
xattributes_valuemask |= CWColormap; xattributes_valuemask |= CWColormap;
xattributes.colormap = XCreateColormap( xattributes.colormap = XCreateColormap(
m_display, RootWindow(m_display, m_visualInfo->screen), m_visualInfo->visual, AllocNone); display_, RootWindow(display_, visual_info_->screen), visual_info_->visual, AllocNone);
/* create the window! */ /* create the window! */
m_window = XCreateWindow(m_display, window_ = XCreateWindow(display_,
RootWindow(m_display, m_visualInfo->screen), RootWindow(display_, visual_info_->screen),
left, left,
top, top,
width, width,
height, height,
0, /* no border. */ 0, /* no border. */
m_visualInfo->depth, visual_info_->depth,
InputOutput, InputOutput,
m_visualInfo->visual, visual_info_->visual,
xattributes_valuemask, xattributes_valuemask,
&xattributes); &xattributes);
#ifdef WITH_XDND #ifdef WITH_XDND
/* initialize drop target for newly created window */ /* initialize drop target for newly created window */
m_dropTarget = new GHOST_DropTargetX11(this, m_system); drop_target_ = new GHOST_DropTargetX11(this, system_);
GHOST_PRINT("Set drop target\n"); GHOST_PRINT("Set drop target\n");
#endif #endif
@@ -200,22 +200,22 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
Atom atoms[2]; Atom atoms[2];
int count = 0; int count = 0;
if (state == GHOST_kWindowStateMaximized) { if (state == GHOST_kWindowStateMaximized) {
atoms[count++] = m_system->m_atom._NET_WM_STATE_MAXIMIZED_VERT; atoms[count++] = system_->atom_._NET_WM_STATE_MAXIMIZED_VERT;
atoms[count++] = m_system->m_atom._NET_WM_STATE_MAXIMIZED_HORZ; atoms[count++] = system_->atom_._NET_WM_STATE_MAXIMIZED_HORZ;
} }
else { else {
atoms[count++] = m_system->m_atom._NET_WM_STATE_FULLSCREEN; atoms[count++] = system_->atom_._NET_WM_STATE_FULLSCREEN;
} }
XChangeProperty(m_display, XChangeProperty(display_,
m_window, window_,
m_system->m_atom._NET_WM_STATE, system_->atom_._NET_WM_STATE,
XA_ATOM, XA_ATOM,
32, 32,
PropModeReplace, PropModeReplace,
(uchar *)atoms, (uchar *)atoms,
count); count);
m_post_init = False; post_init_ = False;
} }
/* /*
* One of the problem with WM-spec is that can't set a property * One of the problem with WM-spec is that can't set a property
@@ -225,20 +225,20 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
* To fix this, we first need know that the window is really * To fix this, we first need know that the window is really
* map waiting for the MapNotify event. * map waiting for the MapNotify event.
* *
* So, m_post_init indicate that we need wait for the MapNotify * So, post_init_ indicate that we need wait for the MapNotify
* event and then set the Window state to the m_post_state. * event and then set the Window state to the post_state_.
*/ */
else if (!ELEM(state, GHOST_kWindowStateNormal, GHOST_kWindowStateMinimized)) { else if (!ELEM(state, GHOST_kWindowStateNormal, GHOST_kWindowStateMinimized)) {
m_post_init = True; post_init_ = True;
m_post_state = state; post_state_ = state;
} }
else { else {
m_post_init = False; post_init_ = False;
m_post_state = GHOST_kWindowStateNormal; post_state_ = GHOST_kWindowStateNormal;
} }
if (is_dialog && parentWindow) { if (is_dialog && parent_window) {
setDialogHints(parentWindow); setDialogHints(parent_window);
} }
/* Create some hints for the window manager on how /* Create some hints for the window manager on how
@@ -254,7 +254,7 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
xsizehints->min_height = 240; /* Limits are also arbitrary, but should not allow 1x1 window. */ xsizehints->min_height = 240; /* Limits are also arbitrary, but should not allow 1x1 window. */
xsizehints->max_width = 65535; xsizehints->max_width = 65535;
xsizehints->max_height = 65535; xsizehints->max_height = 65535;
XSetWMNormalHints(m_display, m_window, xsizehints); XSetWMNormalHints(display_, window_, xsizehints);
XFree(xsizehints); XFree(xsizehints);
} }
@@ -266,29 +266,29 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
memcpy(wmclass, title, len * sizeof(char)); memcpy(wmclass, title, len * sizeof(char));
xclasshint->res_name = wmclass; xclasshint->res_name = wmclass;
xclasshint->res_class = wmclass; xclasshint->res_class = wmclass;
XSetClassHint(m_display, m_window, xclasshint); XSetClassHint(display_, window_, xclasshint);
free(wmclass); free(wmclass);
XFree(xclasshint); XFree(xclasshint);
} }
/* The basic for a good ICCCM "work" */ /* The basic for a good ICCCM "work" */
if (m_system->m_atom.WM_PROTOCOLS) { if (system_->atom_.WM_PROTOCOLS) {
Atom atoms[2]; Atom atoms[2];
int natom = 0; int natom = 0;
if (m_system->m_atom.WM_DELETE_WINDOW) { if (system_->atom_.WM_DELETE_WINDOW) {
atoms[natom] = m_system->m_atom.WM_DELETE_WINDOW; atoms[natom] = system_->atom_.WM_DELETE_WINDOW;
natom++; natom++;
} }
if (m_system->m_atom.WM_TAKE_FOCUS && m_system->m_windowFocus) { if (system_->atom_.WM_TAKE_FOCUS && system_->window_focus_) {
atoms[natom] = m_system->m_atom.WM_TAKE_FOCUS; atoms[natom] = system_->atom_.WM_TAKE_FOCUS;
natom++; natom++;
} }
if (natom) { if (natom) {
// printf("Register atoms: %d\n", natom); // printf("Register atoms: %d\n", natom);
XSetWMProtocols(m_display, m_window, atoms, natom); XSetWMProtocols(display_, window_, atoms, natom);
} }
} }
@@ -296,17 +296,17 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
{ {
XWMHints *xwmhints = XAllocWMHints(); XWMHints *xwmhints = XAllocWMHints();
xwmhints->initial_state = NormalState; xwmhints->initial_state = NormalState;
xwmhints->input = (m_system->m_windowFocus) ? True : False; xwmhints->input = (system_->window_focus_) ? True : False;
xwmhints->flags = InputHint | StateHint; xwmhints->flags = InputHint | StateHint;
XSetWMHints(display, m_window, xwmhints); XSetWMHints(display, window_, xwmhints);
XFree(xwmhints); XFree(xwmhints);
} }
/* set the icon */ /* set the icon */
{ {
Atom _NET_WM_ICON = XInternAtom(m_display, "_NET_WM_ICON", False); Atom _NET_WM_ICON = XInternAtom(display_, "_NET_WM_ICON", False);
XChangeProperty(m_display, XChangeProperty(display_,
m_window, window_,
_NET_WM_ICON, _NET_WM_ICON,
XA_CARDINAL, XA_CARDINAL,
32, 32,
@@ -317,10 +317,10 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
/* set the process ID (_NET_WM_PID) */ /* set the process ID (_NET_WM_PID) */
{ {
Atom _NET_WM_PID = XInternAtom(m_display, "_NET_WM_PID", False); Atom _NET_WM_PID = XInternAtom(display_, "_NET_WM_PID", False);
pid_t pid = getpid(); pid_t pid = getpid();
XChangeProperty( XChangeProperty(
m_display, m_window, _NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, (uchar *)&pid, 1); display_, window_, _NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, (uchar *)&pid, 1);
} }
/* set the hostname (WM_CLIENT_MACHINE) */ /* set the hostname (WM_CLIENT_MACHINE) */
@@ -334,7 +334,7 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
text_array[0] = hostname; text_array[0] = hostname;
XStringListToTextProperty(text_array, 1, &text_prop); XStringListToTextProperty(text_array, 1, &text_prop);
XSetWMClientMachine(m_display, m_window, &text_prop); XSetWMClientMachine(display_, window_, &text_prop);
XFree(text_prop.value); XFree(text_prop.value);
} }
@@ -344,7 +344,7 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
/* now set up the rendering context. */ /* now set up the rendering context. */
if (setDrawingContextType(type) == GHOST_kSuccess) { if (setDrawingContextType(type) == GHOST_kSuccess) {
m_valid_setup = true; valid_setup_ = true;
GHOST_PRINT("Created window\n"); GHOST_PRINT("Created window\n");
} }
else { else {
@@ -360,19 +360,19 @@ GHOST_WindowX11::GHOST_WindowX11(GHOST_SystemX11 *system,
setTitle(title); setTitle(title);
if (exclusive && system->m_windowFocus) { if (exclusive && system->window_focus_) {
XMapRaised(m_display, m_window); XMapRaised(display_, window_);
} }
else { else {
XMapWindow(m_display, m_window); XMapWindow(display_, window_);
if (!system->m_windowFocus) { if (!system->window_focus_) {
XLowerWindow(m_display, m_window); XLowerWindow(display_, window_);
} }
} }
GHOST_PRINT("Mapped window\n"); GHOST_PRINT("Mapped window\n");
XFlush(m_display); XFlush(display_);
} }
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
@@ -389,36 +389,36 @@ static Bool destroyICCallback(XIC /*xic*/, XPointer ptr, XPointer /*data*/)
bool GHOST_WindowX11::createX11_XIC() bool GHOST_WindowX11::createX11_XIC()
{ {
XIM xim = m_system->getX11_XIM(); XIM xim = system_->getX11_XIM();
if (!xim) { if (!xim) {
return false; return false;
} }
XICCallback destroy; XICCallback destroy;
destroy.callback = (XICProc)destroyICCallback; destroy.callback = (XICProc)destroyICCallback;
destroy.client_data = (XPointer)&m_xic; destroy.client_data = (XPointer)&xic_;
m_xic = XCreateIC(xim, xic_ = XCreateIC(xim,
XNClientWindow, XNClientWindow,
m_window, window_,
XNFocusWindow, XNFocusWindow,
m_window, window_,
XNInputStyle, XNInputStyle,
XIMPreeditNothing | XIMStatusNothing, XIMPreeditNothing | XIMStatusNothing,
XNResourceName, XNResourceName,
GHOST_X11_RES_NAME, GHOST_X11_RES_NAME,
XNResourceClass, XNResourceClass,
GHOST_X11_RES_CLASS, GHOST_X11_RES_CLASS,
XNDestroyCallback, XNDestroyCallback,
&destroy, &destroy,
nullptr); nullptr);
if (!m_xic) { if (!xic_) {
return false; return false;
} }
ulong fevent; ulong fevent;
XGetICValues(m_xic, XNFilterEvents, &fevent, nullptr); XGetICValues(xic_, XNFilterEvents, &fevent, nullptr);
XSelectInput(m_display, XSelectInput(display_,
m_window, window_,
ExposureMask | StructureNotifyMask | KeyPressMask | KeyReleaseMask | ExposureMask | StructureNotifyMask | KeyPressMask | KeyReleaseMask |
EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | FocusChangeMask | PropertyChangeMask | KeymapStateMask | PointerMotionMask | FocusChangeMask | PropertyChangeMask | KeymapStateMask |
@@ -430,10 +430,10 @@ bool GHOST_WindowX11::createX11_XIC()
#ifdef WITH_X11_XINPUT #ifdef WITH_X11_XINPUT
void GHOST_WindowX11::refreshXInputDevices() void GHOST_WindowX11::refreshXInputDevices()
{ {
if (m_system->m_xinput_version.present) { if (system_->xinput_version_.present) {
std::vector<XEventClass> xevents; std::vector<XEventClass> xevents;
for (GHOST_SystemX11::GHOST_TabletX11 &xtablet : m_system->GetXTablets()) { for (GHOST_SystemX11::GHOST_TabletX11 &xtablet : system_->GetXTablets()) {
/* With modern XInput (XLIB 1.6.2 at least and/or EVDEV 2.9.0) and some 'no-name' tablets /* With modern XInput (XLIB 1.6.2 at least and/or EVDEV 2.9.0) and some 'no-name' tablets
* like 'UC-LOGIC Tablet WP5540U', we also need to 'select' ButtonPress for motion event, * like 'UC-LOGIC Tablet WP5540U', we also need to 'select' ButtonPress for motion event,
* otherwise we do not get any tablet motion event once pen is pressed... See #43367. * otherwise we do not get any tablet motion event once pen is pressed... See #43367.
@@ -458,7 +458,7 @@ void GHOST_WindowX11::refreshXInputDevices()
} }
} }
XSelectExtensionEvent(m_display, m_window, xevents.data(), int(xevents.size())); XSelectExtensionEvent(display_, window_, xevents.data(), int(xevents.size()));
} }
} }
@@ -466,33 +466,33 @@ void GHOST_WindowX11::refreshXInputDevices()
Window GHOST_WindowX11::getXWindow() Window GHOST_WindowX11::getXWindow()
{ {
return m_window; return window_;
} }
bool GHOST_WindowX11::getValid() const bool GHOST_WindowX11::getValid() const
{ {
return GHOST_Window::getValid() && m_valid_setup; return GHOST_Window::getValid() && valid_setup_;
} }
void GHOST_WindowX11::setTitle(const char *title) void GHOST_WindowX11::setTitle(const char *title)
{ {
Atom name = XInternAtom(m_display, "_NET_WM_NAME", 0); Atom name = XInternAtom(display_, "_NET_WM_NAME", 0);
Atom utf8str = XInternAtom(m_display, "UTF8_STRING", 0); Atom utf8str = XInternAtom(display_, "UTF8_STRING", 0);
XChangeProperty( XChangeProperty(
m_display, m_window, name, utf8str, 8, PropModeReplace, (const uchar *)title, strlen(title)); display_, window_, name, utf8str, 8, PropModeReplace, (const uchar *)title, strlen(title));
/* This should convert to valid x11 string /* This should convert to valid x11 string
* and getTitle would need matching change */ * and getTitle would need matching change */
XStoreName(m_display, m_window, title); XStoreName(display_, window_, title);
XFlush(m_display); XFlush(display_);
} }
std::string GHOST_WindowX11::getTitle() const std::string GHOST_WindowX11::getTitle() const
{ {
char *name = nullptr; char *name = nullptr;
XFetchName(m_display, m_window, &name); XFetchName(display_, window_, &name);
std::string title = name ? name : "untitled"; std::string title = name ? name : "untitled";
XFree(name); XFree(name);
return title; return title;
@@ -512,8 +512,8 @@ void GHOST_WindowX11::getClientBounds(GHOST_Rect &bounds) const
uint w_return, h_return, border_w_return, depth_return; uint w_return, h_return, border_w_return, depth_return;
int32_t screen_x, screen_y; int32_t screen_x, screen_y;
XGetGeometry(m_display, XGetGeometry(display_,
m_window, window_,
&root_return, &root_return,
&x_return, &x_return,
&y_return, &y_return,
@@ -524,10 +524,10 @@ void GHOST_WindowX11::getClientBounds(GHOST_Rect &bounds) const
clientToScreen(0, 0, screen_x, screen_y); clientToScreen(0, 0, screen_x, screen_y);
bounds.m_l = screen_x; bounds.l_ = screen_x;
bounds.m_r = bounds.m_l + w_return; bounds.r_ = bounds.l_ + w_return;
bounds.m_t = screen_y; bounds.t_ = screen_y;
bounds.m_b = bounds.m_t + h_return; bounds.b_ = bounds.t_ + h_return;
} }
GHOST_TSuccess GHOST_WindowX11::setClientWidth(uint32_t width) GHOST_TSuccess GHOST_WindowX11::setClientWidth(uint32_t width)
@@ -535,7 +535,7 @@ GHOST_TSuccess GHOST_WindowX11::setClientWidth(uint32_t width)
XWindowChanges values; XWindowChanges values;
uint value_mask = CWWidth; uint value_mask = CWWidth;
values.width = width; values.width = width;
XConfigureWindow(m_display, m_window, value_mask, &values); XConfigureWindow(display_, window_, value_mask, &values);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -545,7 +545,7 @@ GHOST_TSuccess GHOST_WindowX11::setClientHeight(uint32_t height)
XWindowChanges values; XWindowChanges values;
uint value_mask = CWHeight; uint value_mask = CWHeight;
values.height = height; values.height = height;
XConfigureWindow(m_display, m_window, value_mask, &values); XConfigureWindow(display_, window_, value_mask, &values);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -555,7 +555,7 @@ GHOST_TSuccess GHOST_WindowX11::setClientSize(uint32_t width, uint32_t height)
uint value_mask = CWWidth | CWHeight; uint value_mask = CWWidth | CWHeight;
values.width = width; values.width = width;
values.height = height; values.height = height;
XConfigureWindow(m_display, m_window, value_mask, &values); XConfigureWindow(display_, window_, value_mask, &values);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -567,7 +567,7 @@ void GHOST_WindowX11::screenToClient(int32_t inX, int32_t inY, int32_t &outX, in
/* Use (0, 0) instead of (inX, inY) to work around overflow of signed int16 in /* Use (0, 0) instead of (inX, inY) to work around overflow of signed int16 in
* the implementation of this function. */ * the implementation of this function. */
XTranslateCoordinates( XTranslateCoordinates(
m_display, RootWindow(m_display, m_visualInfo->screen), m_window, 0, 0, &ax, &ay, &temp); display_, RootWindow(display_, visual_info_->screen), window_, 0, 0, &ax, &ay, &temp);
outX = ax + inX; outX = ax + inX;
outY = ay + inY; outY = ay + inY;
} }
@@ -578,27 +578,21 @@ void GHOST_WindowX11::clientToScreen(int32_t inX, int32_t inY, int32_t &outX, in
Window temp; Window temp;
XTranslateCoordinates( XTranslateCoordinates(
m_display, m_window, RootWindow(m_display, m_visualInfo->screen), inX, inY, &ax, &ay, &temp); display_, window_, RootWindow(display_, visual_info_->screen), inX, inY, &ax, &ay, &temp);
outX = ax; outX = ax;
outY = ay; outY = ay;
} }
GHOST_TSuccess GHOST_WindowX11::setDialogHints(GHOST_WindowX11 *parentWindow) GHOST_TSuccess GHOST_WindowX11::setDialogHints(GHOST_WindowX11 *parent_window)
{ {
Atom atom_window_type = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE", False); Atom atom_window_type = XInternAtom(display_, "_NET_WM_WINDOW_TYPE", False);
Atom atom_dialog = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE_DIALOG", False); Atom atom_dialog = XInternAtom(display_, "_NET_WM_WINDOW_TYPE_DIALOG", False);
MotifWmHints hints = {0}; MotifWmHints hints = {0};
XChangeProperty(m_display, XChangeProperty(
m_window, display_, window_, atom_window_type, XA_ATOM, 32, PropModeReplace, (uchar *)&atom_dialog, 1);
atom_window_type, XSetTransientForHint(display_, window_, parent_window->window_);
XA_ATOM,
32,
PropModeReplace,
(uchar *)&atom_dialog,
1);
XSetTransientForHint(m_display, m_window, parentWindow->m_window);
/* Disable minimizing of the window for now. /* Disable minimizing of the window for now.
* Actually, most window managers disable minimizing and maximizing for dialogs, ignoring this. * Actually, most window managers disable minimizing and maximizing for dialogs, ignoring this.
@@ -607,10 +601,10 @@ GHOST_TSuccess GHOST_WindowX11::setDialogHints(GHOST_WindowX11 *parentWindow)
hints.flags = MWM_HINTS_FUNCTIONS; hints.flags = MWM_HINTS_FUNCTIONS;
hints.functions = MWM_FUNCTION_RESIZE | MWM_FUNCTION_MOVE | MWM_FUNCTION_MAXIMIZE | hints.functions = MWM_FUNCTION_RESIZE | MWM_FUNCTION_MOVE | MWM_FUNCTION_MAXIMIZE |
MWM_FUNCTION_CLOSE; MWM_FUNCTION_CLOSE;
XChangeProperty(m_display, XChangeProperty(display_,
m_window, window_,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
32, 32,
PropModeReplace, PropModeReplace,
(uchar *)&hints, (uchar *)&hints,
@@ -630,13 +624,13 @@ void GHOST_WindowX11::icccmSetState(int state)
xev.xclient.type = ClientMessage; xev.xclient.type = ClientMessage;
xev.xclient.serial = 0; xev.xclient.serial = 0;
xev.xclient.send_event = True; xev.xclient.send_event = True;
xev.xclient.display = m_display; xev.xclient.display = display_;
xev.xclient.window = m_window; xev.xclient.window = window_;
xev.xclient.format = 32; xev.xclient.format = 32;
xev.xclient.message_type = m_system->m_atom.WM_CHANGE_STATE; xev.xclient.message_type = system_->atom_.WM_CHANGE_STATE;
xev.xclient.data.l[0] = state; xev.xclient.data.l[0] = state;
XSendEvent(m_display, XSendEvent(display_,
RootWindow(m_display, m_visualInfo->screen), RootWindow(display_, visual_info_->screen),
False, False,
SubstructureNotifyMask | SubstructureRedirectMask, SubstructureNotifyMask | SubstructureRedirectMask,
&xev); &xev);
@@ -654,13 +648,13 @@ int GHOST_WindowX11::icccmGetState() const
CARD32 st; CARD32 st;
prop_ret = nullptr; prop_ret = nullptr;
ret = XGetWindowProperty(m_display, ret = XGetWindowProperty(display_,
m_window, window_,
m_system->m_atom.WM_STATE, system_->atom_.WM_STATE,
0, 0,
2, 2,
False, False,
m_system->m_atom.WM_STATE, system_->atom_.WM_STATE,
&type_ret, &type_ret,
&format_ret, &format_ret,
&num_ret, &num_ret,
@@ -687,8 +681,8 @@ void GHOST_WindowX11::netwmMaximized(bool set)
xev.xclient.type = ClientMessage; xev.xclient.type = ClientMessage;
xev.xclient.serial = 0; xev.xclient.serial = 0;
xev.xclient.send_event = True; xev.xclient.send_event = True;
xev.xclient.window = m_window; xev.xclient.window = window_;
xev.xclient.message_type = m_system->m_atom._NET_WM_STATE; xev.xclient.message_type = system_->atom_._NET_WM_STATE;
xev.xclient.format = 32; xev.xclient.format = 32;
if (set == True) { if (set == True) {
@@ -698,12 +692,12 @@ void GHOST_WindowX11::netwmMaximized(bool set)
xev.xclient.data.l[0] = _NET_WM_STATE_REMOVE; xev.xclient.data.l[0] = _NET_WM_STATE_REMOVE;
} }
xev.xclient.data.l[1] = m_system->m_atom._NET_WM_STATE_MAXIMIZED_HORZ; xev.xclient.data.l[1] = system_->atom_._NET_WM_STATE_MAXIMIZED_HORZ;
xev.xclient.data.l[2] = m_system->m_atom._NET_WM_STATE_MAXIMIZED_VERT; xev.xclient.data.l[2] = system_->atom_._NET_WM_STATE_MAXIMIZED_VERT;
xev.xclient.data.l[3] = 0; xev.xclient.data.l[3] = 0;
xev.xclient.data.l[4] = 0; xev.xclient.data.l[4] = 0;
XSendEvent(m_display, XSendEvent(display_,
RootWindow(m_display, m_visualInfo->screen), RootWindow(display_, visual_info_->screen),
False, False,
SubstructureRedirectMask | SubstructureNotifyMask, SubstructureRedirectMask | SubstructureNotifyMask,
&xev); &xev);
@@ -719,9 +713,9 @@ bool GHOST_WindowX11::netwmIsMaximized() const
prop_ret = nullptr; prop_ret = nullptr;
st = False; st = False;
ret = XGetWindowProperty(m_display, ret = XGetWindowProperty(display_,
m_window, window_,
m_system->m_atom._NET_WM_STATE, system_->atom_._NET_WM_STATE,
0, 0,
INT_MAX, INT_MAX,
False, False,
@@ -734,10 +728,10 @@ bool GHOST_WindowX11::netwmIsMaximized() const
if ((ret == Success) && (prop_ret) && (format_ret == 32)) { if ((ret == Success) && (prop_ret) && (format_ret == 32)) {
count = 0; count = 0;
for (i = 0; i < num_ret; i++) { for (i = 0; i < num_ret; i++) {
if (prop_ret[i] == m_system->m_atom._NET_WM_STATE_MAXIMIZED_HORZ) { if (prop_ret[i] == system_->atom_._NET_WM_STATE_MAXIMIZED_HORZ) {
count++; count++;
} }
if (prop_ret[i] == m_system->m_atom._NET_WM_STATE_MAXIMIZED_VERT) { if (prop_ret[i] == system_->atom_._NET_WM_STATE_MAXIMIZED_VERT) {
count++; count++;
} }
if (count == 2) { if (count == 2) {
@@ -760,8 +754,8 @@ void GHOST_WindowX11::netwmFullScreen(bool set)
xev.xclient.type = ClientMessage; xev.xclient.type = ClientMessage;
xev.xclient.serial = 0; xev.xclient.serial = 0;
xev.xclient.send_event = True; xev.xclient.send_event = True;
xev.xclient.window = m_window; xev.xclient.window = window_;
xev.xclient.message_type = m_system->m_atom._NET_WM_STATE; xev.xclient.message_type = system_->atom_._NET_WM_STATE;
xev.xclient.format = 32; xev.xclient.format = 32;
if (set == True) { if (set == True) {
@@ -771,12 +765,12 @@ void GHOST_WindowX11::netwmFullScreen(bool set)
xev.xclient.data.l[0] = _NET_WM_STATE_REMOVE; xev.xclient.data.l[0] = _NET_WM_STATE_REMOVE;
} }
xev.xclient.data.l[1] = m_system->m_atom._NET_WM_STATE_FULLSCREEN; xev.xclient.data.l[1] = system_->atom_._NET_WM_STATE_FULLSCREEN;
xev.xclient.data.l[2] = 0; xev.xclient.data.l[2] = 0;
xev.xclient.data.l[3] = 0; xev.xclient.data.l[3] = 0;
xev.xclient.data.l[4] = 0; xev.xclient.data.l[4] = 0;
XSendEvent(m_display, XSendEvent(display_,
RootWindow(m_display, m_visualInfo->screen), RootWindow(display_, visual_info_->screen),
False, False,
SubstructureRedirectMask | SubstructureNotifyMask, SubstructureRedirectMask | SubstructureNotifyMask,
&xev); &xev);
@@ -792,9 +786,9 @@ bool GHOST_WindowX11::netwmIsFullScreen() const
prop_ret = nullptr; prop_ret = nullptr;
st = False; st = False;
ret = XGetWindowProperty(m_display, ret = XGetWindowProperty(display_,
m_window, window_,
m_system->m_atom._NET_WM_STATE, system_->atom_._NET_WM_STATE,
0, 0,
INT_MAX, INT_MAX,
False, False,
@@ -806,7 +800,7 @@ bool GHOST_WindowX11::netwmIsFullScreen() const
(uchar **)&prop_ret); (uchar **)&prop_ret);
if ((ret == Success) && (prop_ret) && (format_ret == 32)) { if ((ret == Success) && (prop_ret) && (format_ret == 32)) {
for (i = 0; i < num_ret; i++) { for (i = 0; i < num_ret; i++) {
if (prop_ret[i] == m_system->m_atom._NET_WM_STATE_FULLSCREEN) { if (prop_ret[i] == system_->atom_._NET_WM_STATE_FULLSCREEN) {
st = True; st = True;
break; break;
} }
@@ -831,10 +825,10 @@ void GHOST_WindowX11::motifFullScreen(bool set)
hints.decorations = 1; hints.decorations = 1;
} }
XChangeProperty(m_display, XChangeProperty(display_,
m_window, window_,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
32, 32,
PropModeReplace, PropModeReplace,
(uchar *)&hints, (uchar *)&hints,
@@ -851,13 +845,13 @@ bool GHOST_WindowX11::motifIsFullScreen() const
prop_ret = nullptr; prop_ret = nullptr;
state = False; state = False;
st = XGetWindowProperty(m_display, st = XGetWindowProperty(display_,
m_window, window_,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
0, 0,
INT_MAX, INT_MAX,
False, False,
m_system->m_atom._MOTIF_WM_HINTS, system_->atom_._MOTIF_WM_HINTS,
&type_ret, &type_ret,
&format_ret, &format_ret,
&num_ret, &num_ret,
@@ -929,7 +923,7 @@ GHOST_TSuccess GHOST_WindowX11::setState(GHOST_TWindowState state)
is_motif_full = motifIsFullScreen(); is_motif_full = motifIsFullScreen();
if (state == GHOST_kWindowStateNormal) { if (state == GHOST_kWindowStateNormal) {
state = m_normal_state; state = normal_state_;
} }
if (state == GHOST_kWindowStateNormal) { if (state == GHOST_kWindowStateNormal) {
@@ -955,7 +949,7 @@ GHOST_TSuccess GHOST_WindowX11::setState(GHOST_TWindowState state)
return GHOST_kFailure; return GHOST_kFailure;
} }
m_normal_state = cur_state; normal_state_ = cur_state;
if (is_max == True) { if (is_max == True) {
netwmMaximized(False); netwmMaximized(False);
@@ -1012,9 +1006,9 @@ GHOST_TSuccess GHOST_WindowX11::setOrder(GHOST_TWindowOrder order)
* window managers ignore the former (e.g. KWIN from KDE) and others * window managers ignore the former (e.g. KWIN from KDE) and others
* don't implement the latter (e.g. FLUXBOX before 0.9.9). */ * don't implement the latter (e.g. FLUXBOX before 0.9.9). */
XRaiseWindow(m_display, m_window); XRaiseWindow(display_, window_);
atom = XInternAtom(m_display, "_NET_ACTIVE_WINDOW", True); atom = XInternAtom(display_, "_NET_ACTIVE_WINDOW", True);
if (atom != None) { if (atom != None) {
Window root; Window root;
@@ -1024,33 +1018,33 @@ GHOST_TSuccess GHOST_WindowX11::setOrder(GHOST_TWindowOrder order)
xev.xclient.type = ClientMessage; xev.xclient.type = ClientMessage;
xev.xclient.serial = 0; xev.xclient.serial = 0;
xev.xclient.send_event = True; xev.xclient.send_event = True;
xev.xclient.window = m_window; xev.xclient.window = window_;
xev.xclient.message_type = atom; xev.xclient.message_type = atom;
xev.xclient.format = 32; xev.xclient.format = 32;
xev.xclient.data.l[0] = 1; xev.xclient.data.l[0] = 1;
xev.xclient.data.l[1] = CurrentTime; xev.xclient.data.l[1] = CurrentTime;
xev.xclient.data.l[2] = m_window; xev.xclient.data.l[2] = window_;
xev.xclient.data.l[3] = 0; xev.xclient.data.l[3] = 0;
xev.xclient.data.l[4] = 0; xev.xclient.data.l[4] = 0;
root = RootWindow(m_display, m_visualInfo->screen); root = RootWindow(display_, visual_info_->screen);
eventmask = SubstructureRedirectMask | SubstructureNotifyMask; eventmask = SubstructureRedirectMask | SubstructureNotifyMask;
XSendEvent(m_display, root, False, eventmask, &xev); XSendEvent(display_, root, False, eventmask, &xev);
} }
XGetWindowAttributes(m_display, m_window, &attr); XGetWindowAttributes(display_, window_, &attr);
/* Minimized windows give bad match error. */ /* Minimized windows give bad match error. */
if (attr.map_state == IsViewable) { if (attr.map_state == IsViewable) {
XSetInputFocus(m_display, m_window, RevertToPointerRoot, CurrentTime); XSetInputFocus(display_, window_, RevertToPointerRoot, CurrentTime);
} }
XFlush(m_display); XFlush(display_);
} }
else if (order == GHOST_kWindowOrderBottom) { else if (order == GHOST_kWindowOrderBottom) {
XLowerWindow(m_display, m_window); XLowerWindow(display_, window_);
XFlush(m_display); XFlush(display_);
} }
else { else {
return GHOST_kFailure; return GHOST_kFailure;
@@ -1061,8 +1055,8 @@ GHOST_TSuccess GHOST_WindowX11::setOrder(GHOST_TWindowOrder order)
bool GHOST_WindowX11::isDialog() const bool GHOST_WindowX11::isDialog() const
{ {
Atom atom_window_type = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE", False); Atom atom_window_type = XInternAtom(display_, "_NET_WM_WINDOW_TYPE", False);
Atom atom_dialog = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE_DIALOG", False); Atom atom_dialog = XInternAtom(display_, "_NET_WM_WINDOW_TYPE_DIALOG", False);
Atom *prop_ret; Atom *prop_ret;
ulong bytes_after, num_ret; ulong bytes_after, num_ret;
@@ -1072,8 +1066,8 @@ bool GHOST_WindowX11::isDialog() const
prop_ret = nullptr; prop_ret = nullptr;
st = False; st = False;
ret = XGetWindowProperty(m_display, ret = XGetWindowProperty(display_,
m_window, window_,
atom_window_type, atom_window_type,
0, 0,
INT_MAX, INT_MAX,
@@ -1112,9 +1106,9 @@ GHOST_TSuccess GHOST_WindowX11::invalidate()
* At the same time we queue the dirty windows in the system class * At the same time we queue the dirty windows in the system class
* and generate events for them at the next processEvents call. */ * and generate events for them at the next processEvents call. */
if (m_invalid_window == false) { if (invalid_window_ == false) {
m_system->addDirtyWindow(this); system_->addDirtyWindow(this);
m_invalid_window = true; invalid_window_ = true;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -1127,59 +1121,59 @@ GHOST_TSuccess GHOST_WindowX11::invalidate()
void GHOST_WindowX11::validate() void GHOST_WindowX11::validate()
{ {
m_invalid_window = false; invalid_window_ = false;
} }
GHOST_WindowX11::~GHOST_WindowX11() GHOST_WindowX11::~GHOST_WindowX11()
{ {
std::map<uint, Cursor>::iterator it = m_standard_cursors.begin(); std::map<uint, Cursor>::iterator it = standard_cursors_.begin();
for (; it != m_standard_cursors.end(); ++it) { for (; it != standard_cursors_.end(); ++it) {
XFreeCursor(m_display, it->second); XFreeCursor(display_, it->second);
} }
if (m_empty_cursor) { if (empty_cursor_) {
XFreeCursor(m_display, m_empty_cursor); XFreeCursor(display_, empty_cursor_);
} }
if (m_custom_cursor) { if (custom_cursor_) {
XFreeCursor(m_display, m_custom_cursor); XFreeCursor(display_, custom_cursor_);
} }
if (m_valid_setup) { if (valid_setup_) {
static Atom Primary_atom, Clipboard_atom; static Atom Primary_atom, Clipboard_atom;
Window p_owner, c_owner; Window p_owner, c_owner;
/* Change the owner of the Atoms to None if we are the owner. */ /* Change the owner of the Atoms to None if we are the owner. */
Primary_atom = XInternAtom(m_display, "PRIMARY", False); Primary_atom = XInternAtom(display_, "PRIMARY", False);
Clipboard_atom = XInternAtom(m_display, "CLIPBOARD", False); Clipboard_atom = XInternAtom(display_, "CLIPBOARD", False);
p_owner = XGetSelectionOwner(m_display, Primary_atom); p_owner = XGetSelectionOwner(display_, Primary_atom);
c_owner = XGetSelectionOwner(m_display, Clipboard_atom); c_owner = XGetSelectionOwner(display_, Clipboard_atom);
if (p_owner == m_window) { if (p_owner == window_) {
XSetSelectionOwner(m_display, Primary_atom, None, CurrentTime); XSetSelectionOwner(display_, Primary_atom, None, CurrentTime);
} }
if (c_owner == m_window) { if (c_owner == window_) {
XSetSelectionOwner(m_display, Clipboard_atom, None, CurrentTime); XSetSelectionOwner(display_, Clipboard_atom, None, CurrentTime);
} }
} }
if (m_visualInfo) { if (visual_info_) {
XFree(m_visualInfo); XFree(visual_info_);
} }
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
if (m_xic) { if (xic_) {
XDestroyIC(m_xic); XDestroyIC(xic_);
} }
#endif #endif
#ifdef WITH_XDND #ifdef WITH_XDND
delete m_dropTarget; delete drop_target_;
#endif #endif
releaseNativeHandles(); releaseNativeHandles();
if (m_valid_setup) { if (valid_setup_) {
XDestroyWindow(m_display, m_window); XDestroyWindow(display_, window_);
} }
} }
@@ -1188,16 +1182,16 @@ GHOST_Context *GHOST_WindowX11::newDrawingContext(GHOST_TDrawingContextType type
switch (type) { switch (type) {
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
case GHOST_kDrawingContextTypeVulkan: { case GHOST_kDrawingContextTypeVulkan: {
GHOST_Context *context = new GHOST_ContextVK(m_want_context_params, GHOST_Context *context = new GHOST_ContextVK(want_context_params_,
GHOST_kVulkanPlatformX11, GHOST_kVulkanPlatformX11,
m_window, window_,
m_display, display_,
nullptr, nullptr,
nullptr, nullptr,
nullptr, nullptr,
1, 1,
2, 2,
m_preferred_device); preferred_device_);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
} }
@@ -1212,15 +1206,15 @@ GHOST_Context *GHOST_WindowX11::newDrawingContext(GHOST_TDrawingContextType type
/* Try to initialize an EGL context. */ /* Try to initialize an EGL context. */
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
GHOST_Context *context = GHOST_ContextEGL( GHOST_Context *context = GHOST_ContextEGL(
this->m_system, this->system_,
m_want_context_params, want_context_params_,
EGLNativeWindowType(m_window), EGLNativeWindowType(window_),
EGLNativeDisplayType(m_display), EGLNativeDisplayType(display_),
EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
4, 4,
minor, minor,
GHOST_OPENGL_EGL_CONTEXT_FLAGS | GHOST_OPENGL_EGL_CONTEXT_FLAGS |
(m_want_context_params.is_debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0), (want_context_params_.is_debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0),
GHOST_OPENGL_EGL_RESET_NOTIFICATION_STRATEGY, GHOST_OPENGL_EGL_RESET_NOTIFICATION_STRATEGY,
EGL_OPENGL_API); EGL_OPENGL_API);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
@@ -1233,15 +1227,15 @@ GHOST_Context *GHOST_WindowX11::newDrawingContext(GHOST_TDrawingContextType type
for (int minor = 6; minor >= 3; --minor) { for (int minor = 6; minor >= 3; --minor) {
GHOST_Context *context = new GHOST_ContextGLX( GHOST_Context *context = new GHOST_ContextGLX(
m_want_context_params, want_context_params_,
m_window, window_,
m_display, display_,
(GLXFBConfig)m_fbconfig, (GLXFBConfig)fbconfig_,
GLX_CONTEXT_CORE_PROFILE_BIT_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
4, 4,
minor, minor,
GHOST_OPENGL_GLX_CONTEXT_FLAGS | GHOST_OPENGL_GLX_CONTEXT_FLAGS |
(m_want_context_params.is_debug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0), (want_context_params_.is_debug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY); GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY);
if (context->initializeDrawingContext()) { if (context->initializeDrawingContext()) {
return context; return context;
@@ -1313,12 +1307,12 @@ GHOST_TSuccess GHOST_WindowX11::getStandardCursor(GHOST_TStandardCursor g_cursor
return GHOST_kFailure; return GHOST_kFailure;
} }
xcursor = m_standard_cursors[xcursor_id]; xcursor = standard_cursors_[xcursor_id];
if (!xcursor) { if (!xcursor) {
xcursor = XCreateFontCursor(m_display, xcursor_id); xcursor = XCreateFontCursor(display_, xcursor_id);
m_standard_cursors[xcursor_id] = xcursor; standard_cursors_[xcursor_id] = xcursor;
} }
return GHOST_kSuccess; return GHOST_kSuccess;
@@ -1326,20 +1320,20 @@ GHOST_TSuccess GHOST_WindowX11::getStandardCursor(GHOST_TStandardCursor g_cursor
Cursor GHOST_WindowX11::getEmptyCursor() Cursor GHOST_WindowX11::getEmptyCursor()
{ {
if (!m_empty_cursor) { if (!empty_cursor_) {
Pixmap blank; Pixmap blank;
XColor dummy = {0}; XColor dummy = {0};
char data[1] = {0}; char data[1] = {0};
/* make a blank cursor */ /* make a blank cursor */
blank = XCreateBitmapFromData( blank = XCreateBitmapFromData(
m_display, RootWindow(m_display, m_visualInfo->screen), data, 1, 1); display_, RootWindow(display_, visual_info_->screen), data, 1, 1);
m_empty_cursor = XCreatePixmapCursor(m_display, blank, blank, &dummy, &dummy, 0, 0); empty_cursor_ = XCreatePixmapCursor(display_, blank, blank, &dummy, &dummy, 0, 0);
XFreePixmap(m_display, blank); XFreePixmap(display_, blank);
} }
return m_empty_cursor; return empty_cursor_;
} }
GHOST_TSuccess GHOST_WindowX11::setWindowCursorVisibility(bool visible) GHOST_TSuccess GHOST_WindowX11::setWindowCursorVisibility(bool visible)
@@ -1347,8 +1341,8 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorVisibility(bool visible)
Cursor xcursor; Cursor xcursor;
if (visible) { if (visible) {
if (m_visible_cursor) { if (visible_cursor_) {
xcursor = m_visible_cursor; xcursor = visible_cursor_;
} }
else if (getStandardCursor(getCursorShape(), xcursor) == GHOST_kFailure) { else if (getStandardCursor(getCursorShape(), xcursor) == GHOST_kFailure) {
getStandardCursor(getCursorShape(), xcursor); getStandardCursor(getCursorShape(), xcursor);
@@ -1358,8 +1352,8 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorVisibility(bool visible)
xcursor = getEmptyCursor(); xcursor = getEmptyCursor();
} }
XDefineCursor(m_display, m_window, xcursor); XDefineCursor(display_, window_, xcursor);
XFlush(m_display); XFlush(display_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1368,7 +1362,7 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
{ {
if (mode != GHOST_kGrabDisable) { if (mode != GHOST_kGrabDisable) {
if (mode != GHOST_kGrabNormal) { if (mode != GHOST_kGrabNormal) {
m_system->getCursorPosition(UNPACK2(m_cursorGrabInitPos)); system_->getCursorPosition(UNPACK2(cursor_grab_init_pos_));
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
if (mode == GHOST_kGrabHide) { if (mode == GHOST_kGrabHide) {
@@ -1376,8 +1370,8 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
} }
} }
#ifdef GHOST_X11_GRAB #ifdef GHOST_X11_GRAB
XGrabPointer(m_display, XGrabPointer(display_,
m_window, window_,
False, False,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync,
@@ -1388,45 +1382,44 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
#endif #endif
} }
else { else {
if (m_cursorGrab == GHOST_kGrabHide) { if (cursor_grab_ == GHOST_kGrabHide) {
m_system->setCursorPosition(UNPACK2(m_cursorGrabInitPos)); system_->setCursorPosition(UNPACK2(cursor_grab_init_pos_));
} }
if (m_cursorGrab != GHOST_kGrabNormal) { if (cursor_grab_ != GHOST_kGrabNormal) {
/* use to generate a mouse move event, otherwise the last event /* use to generate a mouse move event, otherwise the last event
* blender gets can be outside the screen causing menus not to show * blender gets can be outside the screen causing menus not to show
* properly unless the user moves the mouse */ * properly unless the user moves the mouse */
#if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP) #if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP)
if ((m_system->m_xinput_version.present) && (m_system->m_xinput_version.major_version >= 2)) if ((system_->xinput_version_.present) && (system_->xinput_version_.major_version >= 2)) {
{
int device_id; int device_id;
if (XIGetClientPointer(m_display, None, &device_id) != False) { if (XIGetClientPointer(display_, None, &device_id) != False) {
XIWarpPointer(m_display, device_id, None, None, 0, 0, 0, 0, 0, 0); XIWarpPointer(display_, device_id, None, None, 0, 0, 0, 0, 0, 0);
} }
} }
else else
#endif #endif
{ {
XWarpPointer(m_display, None, None, 0, 0, 0, 0, 0, 0); XWarpPointer(display_, None, None, 0, 0, 0, 0, 0, 0);
} }
} }
/* Perform this last so to workaround XWayland bug, see: #53004. */ /* Perform this last so to workaround XWayland bug, see: #53004. */
if (m_cursorGrab == GHOST_kGrabHide) { if (cursor_grab_ == GHOST_kGrabHide) {
setWindowCursorVisibility(true); setWindowCursorVisibility(true);
} }
/* Almost works without but important /* Almost works without but important
* otherwise the mouse GHOST location can be incorrect on exit. */ * otherwise the mouse GHOST location can be incorrect on exit. */
setCursorGrabAccum(0, 0); setCursorGrabAccum(0, 0);
m_cursorGrabBounds.m_l = m_cursorGrabBounds.m_r = -1; /* disable */ cursor_grab_bounds_.l_ = cursor_grab_bounds_.r_ = -1; /* disable */
#ifdef GHOST_X11_GRAB #ifdef GHOST_X11_GRAB
XUngrabPointer(m_display, CurrentTime); XUngrabPointer(display_, CurrentTime);
#endif #endif
} }
XFlush(m_display); XFlush(display_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1438,10 +1431,10 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCursorShape(GHOST_TStandardCursor shape
getStandardCursor(GHOST_kStandardCursorDefault, xcursor); getStandardCursor(GHOST_kStandardCursorDefault, xcursor);
} }
m_visible_cursor = xcursor; visible_cursor_ = xcursor;
XDefineCursor(m_display, m_window, xcursor); XDefineCursor(display_, window_, xcursor);
XFlush(m_display); XFlush(display_);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1458,36 +1451,36 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCustomCursorShape(const uint8_t *bitmap
const int hot_spot[2], const int hot_spot[2],
bool /*can_invert_color*/) bool /*can_invert_color*/)
{ {
Colormap colormap = DefaultColormap(m_display, m_visualInfo->screen); Colormap colormap = DefaultColormap(display_, visual_info_->screen);
Pixmap bitmap_pix, mask_pix; Pixmap bitmap_pix, mask_pix;
XColor fg, bg; XColor fg, bg;
if (XAllocNamedColor(m_display, colormap, "White", &fg, &fg) == 0) { if (XAllocNamedColor(display_, colormap, "White", &fg, &fg) == 0) {
return GHOST_kFailure; return GHOST_kFailure;
} }
if (XAllocNamedColor(m_display, colormap, "Black", &bg, &bg) == 0) { if (XAllocNamedColor(display_, colormap, "Black", &bg, &bg) == 0) {
return GHOST_kFailure; return GHOST_kFailure;
} }
if (m_custom_cursor) { if (custom_cursor_) {
XFreeCursor(m_display, m_custom_cursor); XFreeCursor(display_, custom_cursor_);
} }
bitmap_pix = XCreateBitmapFromData(m_display, m_window, (char *)bitmap, size[0], size[1]); bitmap_pix = XCreateBitmapFromData(display_, window_, (char *)bitmap, size[0], size[1]);
mask_pix = XCreateBitmapFromData(m_display, m_window, (char *)mask, size[0], size[1]); mask_pix = XCreateBitmapFromData(display_, window_, (char *)mask, size[0], size[1]);
m_custom_cursor = XCreatePixmapCursor( custom_cursor_ = XCreatePixmapCursor(
m_display, bitmap_pix, mask_pix, &fg, &bg, hot_spot[0], hot_spot[1]); display_, bitmap_pix, mask_pix, &fg, &bg, hot_spot[0], hot_spot[1]);
XDefineCursor(m_display, m_window, m_custom_cursor); XDefineCursor(display_, window_, custom_cursor_);
XFlush(m_display); XFlush(display_);
m_visible_cursor = m_custom_cursor; visible_cursor_ = custom_cursor_;
XFreePixmap(m_display, bitmap_pix); XFreePixmap(display_, bitmap_pix);
XFreePixmap(m_display, mask_pix); XFreePixmap(display_, mask_pix);
XFreeColors(m_display, colormap, &fg.pixel, 1, 0L); XFreeColors(display_, colormap, &fg.pixel, 1, 0L);
XFreeColors(m_display, colormap, &bg.pixel, 1, 0L); XFreeColors(display_, colormap, &bg.pixel, 1, 0L);
return GHOST_kSuccess; return GHOST_kSuccess;
} }
@@ -1495,7 +1488,7 @@ GHOST_TSuccess GHOST_WindowX11::setWindowCustomCursorShape(const uint8_t *bitmap
uint16_t GHOST_WindowX11::getDPIHint() uint16_t GHOST_WindowX11::getDPIHint()
{ {
/* Try to read DPI setting set using xrdb */ /* Try to read DPI setting set using xrdb */
char *resMan = XResourceManagerString(m_display); char *resMan = XResourceManagerString(display_);
if (resMan) { if (resMan) {
XrmDatabase xrdb = XrmGetStringDatabase(resMan); XrmDatabase xrdb = XrmGetStringDatabase(resMan);
if (xrdb) { if (xrdb) {
@@ -1519,7 +1512,7 @@ uint16_t GHOST_WindowX11::getDPIHint()
/* Fall back to calculating DPI using X reported DPI, set using `xrandr --dpi`. */ /* Fall back to calculating DPI using X reported DPI, set using `xrandr --dpi`. */
XWindowAttributes attr; XWindowAttributes attr;
if (!XGetWindowAttributes(m_display, m_window, &attr)) { if (!XGetWindowAttributes(display_, window_, &attr)) {
/* Failed to get window attributes, return X11 default DPI */ /* Failed to get window attributes, return X11 default DPI */
return 96; return 96;
} }

View File

@@ -42,7 +42,7 @@ class GHOST_WindowX11 : public GHOST_Window {
* \param width: The width the window. * \param width: The width the window.
* \param height: The height the window. * \param height: The height the window.
* \param state: The state the window is initially opened with. * \param state: The state the window is initially opened with.
* \param parentWindow: Parent (embedder) window. * \param parent_window: Parent (embedder) window.
* \param type: The type of drawing context installed in this window. * \param type: The type of drawing context installed in this window.
* \param context_params: Parameters to use when initializing the context. * \param context_params: Parameters to use when initializing the context.
* \param preferred_device: Preferred device to use when new device will be created. * \param preferred_device: Preferred device to use when new device will be created.
@@ -55,7 +55,7 @@ class GHOST_WindowX11 : public GHOST_Window {
uint32_t width, uint32_t width,
uint32_t height, uint32_t height,
GHOST_TWindowState state, GHOST_TWindowState state,
GHOST_WindowX11 *parentWindow, GHOST_WindowX11 *parent_window,
GHOST_TDrawingContextType type, GHOST_TDrawingContextType type,
const bool is_dialog, const bool is_dialog,
const GHOST_ContextParams &context_params, const GHOST_ContextParams &context_params,
@@ -120,13 +120,13 @@ class GHOST_WindowX11 : public GHOST_Window {
GHOST_TabletData &GetTabletData() GHOST_TabletData &GetTabletData()
{ {
return m_tabletData; return tablet_data_;
} }
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
XIC getX11_XIC() XIC getX11_XIC()
{ {
return m_xic; return xic_;
} }
bool createX11_XIC(); bool createX11_XIC();
@@ -139,7 +139,7 @@ class GHOST_WindowX11 : public GHOST_Window {
#ifdef WITH_XDND #ifdef WITH_XDND
GHOST_DropTargetX11 *getDropTarget() GHOST_DropTargetX11 *getDropTarget()
{ {
return m_dropTarget; return drop_target_;
} }
#endif #endif
@@ -148,10 +148,10 @@ class GHOST_WindowX11 : public GHOST_Window {
* in FullScree or Maximized state. * in FullScree or Maximized state.
* Check GHOST_WindowX11.cc * Check GHOST_WindowX11.cc
*/ */
bool m_post_init; bool post_init_;
GHOST_TWindowState m_post_state; GHOST_TWindowState post_state_;
GHOST_TSuccess setDialogHints(GHOST_WindowX11 *parentWindow); GHOST_TSuccess setDialogHints(GHOST_WindowX11 *parent_window);
uint16_t getDPIHint() override; uint16_t getDPIHint() override;
@@ -204,43 +204,43 @@ class GHOST_WindowX11 : public GHOST_Window {
Cursor getEmptyCursor(); Cursor getEmptyCursor();
Window m_window; Window window_;
Display *m_display; Display *display_;
XVisualInfo *m_visualInfo; XVisualInfo *visual_info_;
void *m_fbconfig; void *fbconfig_;
GHOST_TWindowState m_normal_state; GHOST_TWindowState normal_state_;
/** A pointer to the typed system class. */ /** A pointer to the typed system class. */
GHOST_SystemX11 *m_system; GHOST_SystemX11 *system_;
/** Used to concatenate calls to invalidate() on this window. */ /** Used to concatenate calls to invalidate() on this window. */
bool m_invalid_window; bool invalid_window_;
/** XCursor structure of an empty (blank) cursor */ /** XCursor structure of an empty (blank) cursor */
Cursor m_empty_cursor; Cursor empty_cursor_;
/** XCursor structure of the custom cursor */ /** XCursor structure of the custom cursor */
Cursor m_custom_cursor; Cursor custom_cursor_;
/** XCursor to show when cursor is visible */ /** XCursor to show when cursor is visible */
Cursor m_visible_cursor; Cursor visible_cursor_;
/** Cache of XC_* ID's to XCursor structures */ /** Cache of XC_* ID's to XCursor structures */
std::map<uint, Cursor> m_standard_cursors; std::map<uint, Cursor> standard_cursors_;
#ifdef WITH_XDND #ifdef WITH_XDND
GHOST_DropTargetX11 *m_dropTarget; GHOST_DropTargetX11 *drop_target_;
#endif #endif
GHOST_TabletData m_tabletData; GHOST_TabletData tablet_data_;
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING) #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
XIC m_xic; XIC xic_;
#endif #endif
bool m_valid_setup; bool valid_setup_;
GHOST_GPUDevice m_preferred_device; GHOST_GPUDevice preferred_device_;
void icccmSetState(int state); void icccmSetState(int state);
int icccmGetState() const; int icccmGetState() const;

View File

@@ -224,20 +224,20 @@ GHOST_Wintab::GHOST_Wintab(unique_hmodule handle,
Coord tablet, Coord tablet,
Coord system, Coord system,
size_t queueSize) size_t queueSize)
: m_handle{std::move(handle)}, : handle_{std::move(handle)},
m_fpInfo{info}, fp_info_{info},
m_fpGet{get}, fp_get_{get},
m_fpSet{set}, fp_set_{set},
m_fpPacketsGet{packetsGet}, fp_packets_get_{packetsGet},
m_fpEnable{enable}, fp_enable_{enable},
m_fpOverlap{overlap}, fp_overlap_{overlap},
m_context{std::move(hctx)}, context_{std::move(hctx)},
m_tabletCoord{tablet}, tablet_coord_{tablet},
m_systemCoord{system}, system_coord_{system},
m_pkts{queueSize} pkts_{queueSize}
{ {
m_fpInfo(WTI_INTERFACE, IFC_NDEVICES, &m_numDevices); fp_info_(WTI_INTERFACE, IFC_NDEVICES, &num_devices_);
WINTAB_PRINTF("Wintab Devices: %d\n", m_numDevices); WINTAB_PRINTF("Wintab Devices: %d\n", num_devices_);
updateCursorInfo(); updateCursorInfo();
@@ -247,63 +247,63 @@ GHOST_Wintab::GHOST_Wintab(unique_hmodule handle,
GHOST_Wintab::~GHOST_Wintab() GHOST_Wintab::~GHOST_Wintab()
{ {
WINTAB_PRINTF("Closing Wintab context %p\n", m_context.get()); WINTAB_PRINTF("Closing Wintab context %p\n", context_.get());
} }
void GHOST_Wintab::enable() void GHOST_Wintab::enable()
{ {
m_fpEnable(m_context.get(), true); fp_enable_(context_.get(), true);
m_enabled = true; enabled_ = true;
} }
void GHOST_Wintab::disable() void GHOST_Wintab::disable()
{ {
if (m_focused) { if (focused_) {
loseFocus(); loseFocus();
} }
m_fpEnable(m_context.get(), false); fp_enable_(context_.get(), false);
m_enabled = false; enabled_ = false;
} }
void GHOST_Wintab::gainFocus() void GHOST_Wintab::gainFocus()
{ {
m_fpOverlap(m_context.get(), true); fp_overlap_(context_.get(), true);
m_focused = true; focused_ = true;
} }
void GHOST_Wintab::loseFocus() void GHOST_Wintab::loseFocus()
{ {
if (m_lastTabletData.Active != GHOST_kTabletModeNone) { if (last_tablet_data_.Active != GHOST_kTabletModeNone) {
leaveRange(); leaveRange();
} }
/* Mouse mode of tablet or display layout may change when Wintab or Window is inactive. Don't /* Mouse mode of tablet or display layout may change when Wintab or Window is inactive. Don't
* trust for mouse movement until re-verified. */ * trust for mouse movement until re-verified. */
m_coordTrusted = false; coord_trusted_ = false;
m_fpOverlap(m_context.get(), false); fp_overlap_(context_.get(), false);
m_focused = false; focused_ = false;
} }
void GHOST_Wintab::leaveRange() void GHOST_Wintab::leaveRange()
{ {
/* Button state can't be tracked while out of range, reset it. */ /* Button state can't be tracked while out of range, reset it. */
m_buttons = 0; buttons_ = 0;
/* Set to none to indicate tablet is inactive. */ /* Set to none to indicate tablet is inactive. */
m_lastTabletData = GHOST_TABLET_DATA_NONE; last_tablet_data_ = GHOST_TABLET_DATA_NONE;
/* Clear the packet queue. */ /* Clear the packet queue. */
m_fpPacketsGet(m_context.get(), m_pkts.size(), m_pkts.data()); fp_packets_get_(context_.get(), pkts_.size(), pkts_.data());
} }
void GHOST_Wintab::remapCoordinates() void GHOST_Wintab::remapCoordinates()
{ {
LOGCONTEXT lc = {0}; LOGCONTEXT lc = {0};
if (m_fpInfo(WTI_DEFSYSCTX, 0, &lc)) { if (fp_info_(WTI_DEFSYSCTX, 0, &lc)) {
extractCoordinates(lc, m_tabletCoord, m_systemCoord); extractCoordinates(lc, tablet_coord_, system_coord_);
modifyContext(lc); modifyContext(lc);
m_fpSet(m_context.get(), &lc); fp_set_(context_.get(), &lc);
} }
} }
@@ -311,52 +311,52 @@ void GHOST_Wintab::updateCursorInfo()
{ {
AXIS Pressure, Orientation[3]; AXIS Pressure, Orientation[3];
BOOL pressureSupport = m_fpInfo(WTI_DEVICES, DVC_NPRESSURE, &Pressure); BOOL pressureSupport = fp_info_(WTI_DEVICES, DVC_NPRESSURE, &Pressure);
m_maxPressure = pressureSupport ? Pressure.axMax : 0; max_pressure_ = pressureSupport ? Pressure.axMax : 0;
WINTAB_PRINTF("HCTX %p %s maxPressure: %d\n", m_context.get(), __func__, m_maxPressure); WINTAB_PRINTF("HCTX %p %s maxPressure: %d\n", context_.get(), __func__, max_pressure_);
BOOL tiltSupport = m_fpInfo(WTI_DEVICES, DVC_ORIENTATION, &Orientation); BOOL tiltSupport = fp_info_(WTI_DEVICES, DVC_ORIENTATION, &Orientation);
/* Check if tablet supports azimuth [0] and altitude [1], encoded in axResolution. */ /* Check if tablet supports azimuth [0] and altitude [1], encoded in axResolution. */
if (tiltSupport && Orientation[0].axResolution && Orientation[1].axResolution) { if (tiltSupport && Orientation[0].axResolution && Orientation[1].axResolution) {
m_maxAzimuth = Orientation[0].axMax; max_azimuth_ = Orientation[0].axMax;
m_maxAltitude = Orientation[1].axMax; max_altitude_ = Orientation[1].axMax;
} }
else { else {
m_maxAzimuth = m_maxAltitude = 0; max_azimuth_ = max_altitude_ = 0;
} }
WINTAB_PRINTF("HCTX %p %s maxAzimuth: %d, maxAltitude: %d\n", WINTAB_PRINTF("HCTX %p %s maxAzimuth: %d, maxAltitude: %d\n",
m_context.get(), context_.get(),
__func__, __func__,
m_maxAzimuth, max_azimuth_,
m_maxAltitude); max_altitude_);
} }
void GHOST_Wintab::processInfoChange(LPARAM lParam) void GHOST_Wintab::processInfoChange(LPARAM lParam)
{ {
/* Update number of connected Wintab digitizers. */ /* Update number of connected Wintab digitizers. */
if (LOWORD(lParam) == WTI_INTERFACE && HIWORD(lParam) == IFC_NDEVICES) { if (LOWORD(lParam) == WTI_INTERFACE && HIWORD(lParam) == IFC_NDEVICES) {
m_fpInfo(WTI_INTERFACE, IFC_NDEVICES, &m_numDevices); fp_info_(WTI_INTERFACE, IFC_NDEVICES, &num_devices_);
WINTAB_PRINTF("HCTX %p %s numDevices: %d\n", m_context.get(), __func__, m_numDevices); WINTAB_PRINTF("HCTX %p %s numDevices: %d\n", context_.get(), __func__, num_devices_);
} }
} }
bool GHOST_Wintab::devicesPresent() bool GHOST_Wintab::devicesPresent()
{ {
return m_numDevices > 0; return num_devices_ > 0;
} }
GHOST_TabletData GHOST_Wintab::getLastTabletData() GHOST_TabletData GHOST_Wintab::getLastTabletData()
{ {
return m_lastTabletData; return last_tablet_data_;
} }
void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo) void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo)
{ {
const int numPackets = m_fpPacketsGet(m_context.get(), m_pkts.size(), m_pkts.data()); const int numPackets = fp_packets_get_(context_.get(), pkts_.size(), pkts_.data());
outWintabInfo.reserve(numPackets); outWintabInfo.reserve(numPackets);
for (int i = 0; i < numPackets; i++) { for (int i = 0; i < numPackets; i++) {
const PACKET pkt = m_pkts[i]; const PACKET pkt = pkts_[i];
GHOST_WintabInfoWin32 out; GHOST_WintabInfoWin32 out;
/* % 3 for multiple devices ("DualTrack"). */ /* % 3 for multiple devices ("DualTrack"). */
@@ -376,11 +376,11 @@ void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo)
out.x = pkt.pkX; out.x = pkt.pkX;
out.y = pkt.pkY; out.y = pkt.pkY;
if (m_maxPressure > 0) { if (max_pressure_ > 0) {
out.tabletData.Pressure = float(pkt.pkNormalPressure) / float(m_maxPressure); out.tabletData.Pressure = float(pkt.pkNormalPressure) / float(max_pressure_);
} }
if ((m_maxAzimuth > 0) && (m_maxAltitude > 0)) { if ((max_azimuth_ > 0) && (max_altitude_ > 0)) {
/* From the wintab spec: /* From the wintab spec:
* orAzimuth: Specifies the clockwise rotation of the cursor about the z axis through a * orAzimuth: Specifies the clockwise rotation of the cursor about the z axis through a
* full circular range. * full circular range.
@@ -397,8 +397,8 @@ void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo)
ORIENTATION ort = pkt.pkOrientation; ORIENTATION ort = pkt.pkOrientation;
/* Convert raw fixed point data to radians. */ /* Convert raw fixed point data to radians. */
float altRad = float((fabs(float(ort.orAltitude)) / float(m_maxAltitude)) * M_PI_2); float altRad = float((fabs(float(ort.orAltitude)) / float(max_altitude_)) * M_PI_2);
float azmRad = float((float(ort.orAzimuth) / float(m_maxAzimuth)) * M_PI * 2.0); float azmRad = float((float(ort.orAzimuth) / float(max_azimuth_)) * M_PI * 2.0);
/* Find length of the stylus' projected vector on the XY plane. */ /* Find length of the stylus' projected vector on the XY plane. */
float vecLen = cos(altRad); float vecLen = cos(altRad);
@@ -416,9 +416,9 @@ void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo)
/* Some Wintab libraries don't handle relative button input, so we track button presses /* Some Wintab libraries don't handle relative button input, so we track button presses
* manually. */ * manually. */
DWORD buttonsChanged = m_buttons ^ pkt.pkButtons; DWORD buttonsChanged = buttons_ ^ pkt.pkButtons;
/* We only needed the prior button state to compare to current, so we can overwrite it now. */ /* We only needed the prior button state to compare to current, so we can overwrite it now. */
m_buttons = pkt.pkButtons; buttons_ = pkt.pkButtons;
/* Iterate over button flag indices until all flags are clear. */ /* Iterate over button flag indices until all flags are clear. */
for (WORD buttonIndex = 0; buttonsChanged; buttonIndex++, buttonsChanged >>= 1) { for (WORD buttonIndex = 0; buttonsChanged; buttonIndex++, buttonsChanged >>= 1) {
@@ -443,7 +443,7 @@ void GHOST_Wintab::getInput(std::vector<GHOST_WintabInfoWin32> &outWintabInfo)
} }
if (!outWintabInfo.empty()) { if (!outWintabInfo.empty()) {
m_lastTabletData = outWintabInfo.back().tabletData; last_tablet_data_ = outWintabInfo.back().tabletData;
} }
} }
@@ -453,8 +453,8 @@ GHOST_TButton GHOST_Wintab::mapWintabToGhostButton(uint cursor, WORD physicalBut
BYTE logicalButtons[numButtons] = {0}; BYTE logicalButtons[numButtons] = {0};
BYTE systemButtons[numButtons] = {0}; BYTE systemButtons[numButtons] = {0};
if (!m_fpInfo(WTI_CURSORS + cursor, CSR_BUTTONMAP, &logicalButtons) || if (!fp_info_(WTI_CURSORS + cursor, CSR_BUTTONMAP, &logicalButtons) ||
!m_fpInfo(WTI_CURSORS + cursor, CSR_SYSBTNMAP, &systemButtons)) !fp_info_(WTI_CURSORS + cursor, CSR_SYSBTNMAP, &systemButtons))
{ {
return GHOST_kButtonMaskNone; return GHOST_kButtonMaskNone;
} }
@@ -506,13 +506,13 @@ void GHOST_Wintab::mapWintabToSysCoordinates(int x_in, int y_in, int &x_out, int
return outPoint; return outPoint;
}; };
x_out = remap(x_in, m_tabletCoord.x, m_systemCoord.x); x_out = remap(x_in, tablet_coord_.x, system_coord_.x);
y_out = remap(y_in, m_tabletCoord.y, m_systemCoord.y); y_out = remap(y_in, tablet_coord_.y, system_coord_.y);
} }
bool GHOST_Wintab::trustCoordinates() bool GHOST_Wintab::trustCoordinates()
{ {
return m_coordTrusted; return coord_trusted_;
} }
bool GHOST_Wintab::testCoordinates(int sysX, int sysY, int wtX, int wtY) bool GHOST_Wintab::testCoordinates(int sysX, int sysY, int wtX, int wtY)
@@ -521,30 +521,30 @@ bool GHOST_Wintab::testCoordinates(int sysX, int sysY, int wtX, int wtY)
/* Allow off by one pixel tolerance in case of rounding error. */ /* Allow off by one pixel tolerance in case of rounding error. */
if (abs(sysX - wtX) <= 1 && abs(sysY - wtY) <= 1) { if (abs(sysX - wtX) <= 1 && abs(sysY - wtY) <= 1) {
m_coordTrusted = true; coord_trusted_ = true;
return true; return true;
} }
else { else {
m_coordTrusted = false; coord_trusted_ = false;
return false; return false;
} }
} }
bool GHOST_Wintab::m_debug = false; bool GHOST_Wintab::debug_ = false;
void GHOST_Wintab::setDebug(bool debug) void GHOST_Wintab::setDebug(bool debug)
{ {
m_debug = debug; debug_ = debug;
} }
bool GHOST_Wintab::getDebug() bool GHOST_Wintab::getDebug()
{ {
return m_debug; return debug_;
} }
void GHOST_Wintab::printContextDebugInfo() void GHOST_Wintab::printContextDebugInfo()
{ {
if (!m_debug) { if (!debug_) {
return; return;
} }
@@ -553,7 +553,7 @@ void GHOST_Wintab::printContextDebugInfo()
BYTE systemButtons[32] = {0}; BYTE systemButtons[32] = {0};
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
printf("initializeWintab cursor %d buttons\n", i); printf("initializeWintab cursor %d buttons\n", i);
uint lbut = m_fpInfo(WTI_CURSORS + i, CSR_BUTTONMAP, &logicalButtons); uint lbut = fp_info_(WTI_CURSORS + i, CSR_BUTTONMAP, &logicalButtons);
if (lbut) { if (lbut) {
printf("%d", logicalButtons[0]); printf("%d", logicalButtons[0]);
for (int j = 1; j < lbut; j++) { for (int j = 1; j < lbut; j++) {
@@ -564,7 +564,7 @@ void GHOST_Wintab::printContextDebugInfo()
else { else {
printf("logical button error\n"); printf("logical button error\n");
} }
uint sbut = m_fpInfo(WTI_CURSORS + i, CSR_SYSBTNMAP, &systemButtons); uint sbut = fp_info_(WTI_CURSORS + i, CSR_SYSBTNMAP, &systemButtons);
if (sbut) { if (sbut) {
printf("%d", systemButtons[0]); printf("%d", systemButtons[0]);
for (int j = 1; j < sbut; j++) { for (int j = 1; j < sbut; j++) {
@@ -581,8 +581,8 @@ void GHOST_Wintab::printContextDebugInfo()
/* Print open context constraints. */ /* Print open context constraints. */
uint maxcontexts, opencontexts; uint maxcontexts, opencontexts;
m_fpInfo(WTI_INTERFACE, IFC_NCONTEXTS, &maxcontexts); fp_info_(WTI_INTERFACE, IFC_NCONTEXTS, &maxcontexts);
m_fpInfo(WTI_STATUS, STA_CONTEXTS, &opencontexts); fp_info_(WTI_STATUS, STA_CONTEXTS, &opencontexts);
printf("%u max contexts, %u open contexts\n", maxcontexts, opencontexts); printf("%u max contexts, %u open contexts\n", maxcontexts, opencontexts);
/* Print system information. */ /* Print system information. */
@@ -613,52 +613,52 @@ void GHOST_Wintab::printContextDebugInfo()
LOGCONTEXT lc; LOGCONTEXT lc;
/* Print system context. */ /* Print system context. */
m_fpInfo(WTI_DEFSYSCTX, 0, &lc); fp_info_(WTI_DEFSYSCTX, 0, &lc);
printf("WTI_DEFSYSCTX\n"); printf("WTI_DEFSYSCTX\n");
printContextRanges(lc); printContextRanges(lc);
/* Print system context, manually populated. */ /* Print system context, manually populated. */
m_fpInfo(WTI_DEFSYSCTX, CTX_INORGX, &lc.lcInOrgX); fp_info_(WTI_DEFSYSCTX, CTX_INORGX, &lc.lcInOrgX);
m_fpInfo(WTI_DEFSYSCTX, CTX_INORGY, &lc.lcInOrgY); fp_info_(WTI_DEFSYSCTX, CTX_INORGY, &lc.lcInOrgY);
m_fpInfo(WTI_DEFSYSCTX, CTX_INEXTX, &lc.lcInExtX); fp_info_(WTI_DEFSYSCTX, CTX_INEXTX, &lc.lcInExtX);
m_fpInfo(WTI_DEFSYSCTX, CTX_INEXTY, &lc.lcInExtY); fp_info_(WTI_DEFSYSCTX, CTX_INEXTY, &lc.lcInExtY);
m_fpInfo(WTI_DEFSYSCTX, CTX_OUTORGX, &lc.lcOutOrgX); fp_info_(WTI_DEFSYSCTX, CTX_OUTORGX, &lc.lcOutOrgX);
m_fpInfo(WTI_DEFSYSCTX, CTX_OUTORGY, &lc.lcOutOrgY); fp_info_(WTI_DEFSYSCTX, CTX_OUTORGY, &lc.lcOutOrgY);
m_fpInfo(WTI_DEFSYSCTX, CTX_OUTEXTX, &lc.lcOutExtX); fp_info_(WTI_DEFSYSCTX, CTX_OUTEXTX, &lc.lcOutExtX);
m_fpInfo(WTI_DEFSYSCTX, CTX_OUTEXTY, &lc.lcOutExtY); fp_info_(WTI_DEFSYSCTX, CTX_OUTEXTY, &lc.lcOutExtY);
m_fpInfo(WTI_DEFSYSCTX, CTX_SYSORGX, &lc.lcSysOrgX); fp_info_(WTI_DEFSYSCTX, CTX_SYSORGX, &lc.lcSysOrgX);
m_fpInfo(WTI_DEFSYSCTX, CTX_SYSORGY, &lc.lcSysOrgY); fp_info_(WTI_DEFSYSCTX, CTX_SYSORGY, &lc.lcSysOrgY);
m_fpInfo(WTI_DEFSYSCTX, CTX_SYSEXTX, &lc.lcSysExtX); fp_info_(WTI_DEFSYSCTX, CTX_SYSEXTX, &lc.lcSysExtX);
m_fpInfo(WTI_DEFSYSCTX, CTX_SYSEXTY, &lc.lcSysExtY); fp_info_(WTI_DEFSYSCTX, CTX_SYSEXTY, &lc.lcSysExtY);
printf("WTI_DEFSYSCTX CTX_*\n"); printf("WTI_DEFSYSCTX CTX_*\n");
printContextRanges(lc); printContextRanges(lc);
for (uint i = 0; i < m_numDevices; i++) { for (uint i = 0; i < num_devices_; i++) {
/* Print individual device system context. */ /* Print individual device system context. */
m_fpInfo(WTI_DSCTXS + i, 0, &lc); fp_info_(WTI_DSCTXS + i, 0, &lc);
printf("WTI_DSCTXS %u\n", i); printf("WTI_DSCTXS %u\n", i);
printContextRanges(lc); printContextRanges(lc);
/* Print individual device system context, manually populated. */ /* Print individual device system context, manually populated. */
m_fpInfo(WTI_DSCTXS + i, CTX_INORGX, &lc.lcInOrgX); fp_info_(WTI_DSCTXS + i, CTX_INORGX, &lc.lcInOrgX);
m_fpInfo(WTI_DSCTXS + i, CTX_INORGY, &lc.lcInOrgY); fp_info_(WTI_DSCTXS + i, CTX_INORGY, &lc.lcInOrgY);
m_fpInfo(WTI_DSCTXS + i, CTX_INEXTX, &lc.lcInExtX); fp_info_(WTI_DSCTXS + i, CTX_INEXTX, &lc.lcInExtX);
m_fpInfo(WTI_DSCTXS + i, CTX_INEXTY, &lc.lcInExtY); fp_info_(WTI_DSCTXS + i, CTX_INEXTY, &lc.lcInExtY);
m_fpInfo(WTI_DSCTXS + i, CTX_OUTORGX, &lc.lcOutOrgX); fp_info_(WTI_DSCTXS + i, CTX_OUTORGX, &lc.lcOutOrgX);
m_fpInfo(WTI_DSCTXS + i, CTX_OUTORGY, &lc.lcOutOrgY); fp_info_(WTI_DSCTXS + i, CTX_OUTORGY, &lc.lcOutOrgY);
m_fpInfo(WTI_DSCTXS + i, CTX_OUTEXTX, &lc.lcOutExtX); fp_info_(WTI_DSCTXS + i, CTX_OUTEXTX, &lc.lcOutExtX);
m_fpInfo(WTI_DSCTXS + i, CTX_OUTEXTY, &lc.lcOutExtY); fp_info_(WTI_DSCTXS + i, CTX_OUTEXTY, &lc.lcOutExtY);
m_fpInfo(WTI_DSCTXS + i, CTX_SYSORGX, &lc.lcSysOrgX); fp_info_(WTI_DSCTXS + i, CTX_SYSORGX, &lc.lcSysOrgX);
m_fpInfo(WTI_DSCTXS + i, CTX_SYSORGY, &lc.lcSysOrgY); fp_info_(WTI_DSCTXS + i, CTX_SYSORGY, &lc.lcSysOrgY);
m_fpInfo(WTI_DSCTXS + i, CTX_SYSEXTX, &lc.lcSysExtX); fp_info_(WTI_DSCTXS + i, CTX_SYSEXTX, &lc.lcSysExtX);
m_fpInfo(WTI_DSCTXS + i, CTX_SYSEXTY, &lc.lcSysExtY); fp_info_(WTI_DSCTXS + i, CTX_SYSEXTY, &lc.lcSysExtY);
printf("WTI_DSCTX %u CTX_*\n", i); printf("WTI_DSCTX %u CTX_*\n", i);
printContextRanges(lc); printContextRanges(lc);
/* Print device axis. */ /* Print device axis. */
AXIS axis_x, axis_y; AXIS axis_x, axis_y;
m_fpInfo(WTI_DEVICES + i, DVC_X, &axis_x); fp_info_(WTI_DEVICES + i, DVC_X, &axis_x);
m_fpInfo(WTI_DEVICES + i, DVC_Y, &axis_y); fp_info_(WTI_DEVICES + i, DVC_Y, &axis_y);
printf("WTI_DEVICES %u axis_x org: %d, axis_y org: %d axis_x ext: %d, axis_y ext: %d\n", printf("WTI_DEVICES %u axis_x org: %d, axis_y org: %d axis_x ext: %d, axis_y ext: %d\n",
i, i,
axis_x.axMin, axis_x.axMin,

View File

@@ -183,24 +183,24 @@ class GHOST_Wintab {
private: private:
/** Wintab DLL handle. */ /** Wintab DLL handle. */
unique_hmodule m_handle; unique_hmodule handle_;
/** Wintab API functions. */ /** Wintab API functions. */
GHOST_WIN32_WTInfo m_fpInfo = nullptr; GHOST_WIN32_WTInfo fp_info_ = nullptr;
GHOST_WIN32_WTGet m_fpGet = nullptr; GHOST_WIN32_WTGet fp_get_ = nullptr;
GHOST_WIN32_WTSet m_fpSet = nullptr; GHOST_WIN32_WTSet fp_set_ = nullptr;
GHOST_WIN32_WTPacketsGet m_fpPacketsGet = nullptr; GHOST_WIN32_WTPacketsGet fp_packets_get_ = nullptr;
GHOST_WIN32_WTEnable m_fpEnable = nullptr; GHOST_WIN32_WTEnable fp_enable_ = nullptr;
GHOST_WIN32_WTOverlap m_fpOverlap = nullptr; GHOST_WIN32_WTOverlap fp_overlap_ = nullptr;
/** Stores the Wintab tablet context. */ /** Stores the Wintab tablet context. */
unique_hctx m_context; unique_hctx context_;
/** Whether the context is enabled. */ /** Whether the context is enabled. */
bool m_enabled = false; bool enabled_ = false;
/** Whether the context has focus and is at the top of overlap order. */ /** Whether the context has focus and is at the top of overlap order. */
bool m_focused = false; bool focused_ = false;
/** Pressed button map. */ /** Pressed button map. */
DWORD m_buttons = 0; DWORD buttons_ = 0;
/** Range of a coordinate space. */ /** Range of a coordinate space. */
struct Range { struct Range {
@@ -218,25 +218,25 @@ class GHOST_Wintab {
Range y = {}; Range y = {};
}; };
/** Whether Wintab coordinates are trusted. */ /** Whether Wintab coordinates are trusted. */
bool m_coordTrusted = false; bool coord_trusted_ = false;
/** Tablet input range. */ /** Tablet input range. */
Coord m_tabletCoord = {}; Coord tablet_coord_ = {};
/** System output range. */ /** System output range. */
Coord m_systemCoord = {}; Coord system_coord_ = {};
int m_maxPressure = 0; int max_pressure_ = 0;
int m_maxAzimuth = 0; int max_azimuth_ = 0;
int m_maxAltitude = 0; int max_altitude_ = 0;
/** Number of connected Wintab devices. */ /** Number of connected Wintab devices. */
UINT m_numDevices = 0; UINT num_devices_ = 0;
/** Reusable buffer to read in Wintab packets. */ /** Reusable buffer to read in Wintab packets. */
std::vector<PACKET> m_pkts; std::vector<PACKET> pkts_;
/** Most recently received tablet data, or none if pen is not in range. */ /** Most recently received tablet data, or none if pen is not in range. */
GHOST_TabletData m_lastTabletData = GHOST_TABLET_DATA_NONE; GHOST_TabletData last_tablet_data_ = GHOST_TABLET_DATA_NONE;
/** Whether Wintab logging is enabled. */ /** Whether Wintab logging is enabled. */
static bool m_debug; static bool debug_;
GHOST_Wintab(unique_hmodule handle, GHOST_Wintab(unique_hmodule handle,
GHOST_WIN32_WTInfo info, GHOST_WIN32_WTInfo info,

View File

@@ -34,7 +34,7 @@ GHOST_XrActionSpace::GHOST_XrActionSpace(XrSession session,
action_space_info.subactionPath = subaction_path; action_space_info.subactionPath = subaction_path;
copy_ghost_pose_to_openxr_pose(pose, action_space_info.poseInActionSpace); copy_ghost_pose_to_openxr_pose(pose, action_space_info.poseInActionSpace);
CHECK_XR(xrCreateActionSpace(session, &action_space_info, &m_space), CHECK_XR(xrCreateActionSpace(session, &action_space_info, &space_),
(std::string("Failed to create space \"") + subaction_path_str + "\" for action \"" + (std::string("Failed to create space \"") + subaction_path_str + "\" for action \"" +
action_name + "\" and profile \"" + profile_path + "\".") action_name + "\" and profile \"" + profile_path + "\".")
.data()); .data());
@@ -42,14 +42,14 @@ GHOST_XrActionSpace::GHOST_XrActionSpace(XrSession session,
GHOST_XrActionSpace::~GHOST_XrActionSpace() GHOST_XrActionSpace::~GHOST_XrActionSpace()
{ {
if (m_space != XR_NULL_HANDLE) { if (space_ != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySpace(m_space)); CHECK_XR_ASSERT(xrDestroySpace(space_));
} }
} }
XrSpace GHOST_XrActionSpace::getSpace() const XrSpace GHOST_XrActionSpace::getSpace() const
{ {
return m_space; return space_;
} }
/** \} */ /** \} */
@@ -65,7 +65,7 @@ GHOST_XrActionProfile::GHOST_XrActionProfile(XrInstance instance,
GHOST_XrActionType type, GHOST_XrActionType type,
const GHOST_XrActionProfileInfo &info) const GHOST_XrActionProfileInfo &info)
{ {
CHECK_XR(xrStringToPath(instance, info.profile_path, &m_profile), CHECK_XR(xrStringToPath(instance, info.profile_path, &profile_),
(std::string("Failed to get interaction profile path \"") + info.profile_path + "\".") (std::string("Failed to get interaction profile path \"") + info.profile_path + "\".")
.data()); .data());
@@ -77,7 +77,7 @@ GHOST_XrActionProfile::GHOST_XrActionProfile(XrInstance instance,
/* Create bindings. */ /* Create bindings. */
XrInteractionProfileSuggestedBinding bindings_info{ XrInteractionProfileSuggestedBinding bindings_info{
XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING}; XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
bindings_info.interactionProfile = m_profile; bindings_info.interactionProfile = profile_;
bindings_info.countSuggestedBindings = 1; bindings_info.countSuggestedBindings = 1;
for (uint32_t subaction_idx = 0; subaction_idx < info.count_subaction_paths; ++subaction_idx) { for (uint32_t subaction_idx = 0; subaction_idx < info.count_subaction_paths; ++subaction_idx) {
@@ -86,7 +86,7 @@ GHOST_XrActionProfile::GHOST_XrActionProfile(XrInstance instance,
const std::string interaction_path = std::string(subaction_path_str) + const std::string interaction_path = std::string(subaction_path_str) +
binding_info.component_path; binding_info.component_path;
if (m_bindings.find(interaction_path) != m_bindings.end()) { if (bindings_.find(interaction_path) != bindings_.end()) {
continue; continue;
} }
@@ -104,11 +104,11 @@ GHOST_XrActionProfile::GHOST_XrActionProfile(XrInstance instance,
"\". Are the action and profile paths correct?") "\". Are the action and profile paths correct?")
.data()); .data());
m_bindings.insert({interaction_path, sbinding.binding}); bindings_.insert({interaction_path, sbinding.binding});
if (m_subaction_data.find(subaction_path_str) == m_subaction_data.end()) { if (subaction_data_.find(subaction_path_str) == subaction_data_.end()) {
std::map<std::string, GHOST_XrSubactionData>::iterator it = std::map<std::string, GHOST_XrSubactionData>::iterator it =
m_subaction_data subaction_data_
.emplace( .emplace(
std::piecewise_construct, std::make_tuple(subaction_path_str), std::make_tuple()) std::piecewise_construct, std::make_tuple(subaction_path_str), std::make_tuple())
.first; .first;
@@ -141,12 +141,12 @@ GHOST_XrActionProfile::GHOST_XrActionProfile(XrInstance instance,
XrPath GHOST_XrActionProfile::getProfile() const XrPath GHOST_XrActionProfile::getProfile() const
{ {
return m_profile; return profile_;
} }
const GHOST_XrSubactionData *GHOST_XrActionProfile::getSubaction(XrPath subaction_path) const const GHOST_XrSubactionData *GHOST_XrActionProfile::getSubaction(XrPath subaction_path) const
{ {
for (auto &[subaction_path_str, subaction] : m_subaction_data) { for (auto &[subaction_path_str, subaction] : subaction_data_) {
if (subaction.subaction_path == subaction_path) { if (subaction.subaction_path == subaction_path) {
return &subaction; return &subaction;
} }
@@ -157,17 +157,15 @@ const GHOST_XrSubactionData *GHOST_XrActionProfile::getSubaction(XrPath subactio
void GHOST_XrActionProfile::getBindings( void GHOST_XrActionProfile::getBindings(
XrAction action, std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const XrAction action, std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const
{ {
std::map<XrPath, std::vector<XrActionSuggestedBinding>>::iterator it = r_bindings.find( std::map<XrPath, std::vector<XrActionSuggestedBinding>>::iterator it = r_bindings.find(profile_);
m_profile);
if (it == r_bindings.end()) { if (it == r_bindings.end()) {
it = r_bindings it = r_bindings.emplace(std::piecewise_construct, std::make_tuple(profile_), std::make_tuple())
.emplace(std::piecewise_construct, std::make_tuple(m_profile), std::make_tuple())
.first; .first;
} }
std::vector<XrActionSuggestedBinding> &sbindings = it->second; std::vector<XrActionSuggestedBinding> &sbindings = it->second;
for (auto &[path, binding] : m_bindings) { for (auto &[path, binding] : bindings_) {
XrActionSuggestedBinding sbinding; XrActionSuggestedBinding sbinding;
sbinding.action = action; sbinding.action = action;
sbinding.binding = binding; sbinding.binding = binding;
@@ -186,20 +184,20 @@ void GHOST_XrActionProfile::getBindings(
GHOST_XrAction::GHOST_XrAction(XrInstance instance, GHOST_XrAction::GHOST_XrAction(XrInstance instance,
XrActionSet action_set, XrActionSet action_set,
const GHOST_XrActionInfo &info) const GHOST_XrActionInfo &info)
: m_type(info.type), : type_(info.type),
m_states(info.states), states_(info.states),
m_float_thresholds(info.float_thresholds), float_thresholds_(info.float_thresholds),
m_axis_flags(info.axis_flags), axis_flags_(info.axis_flags),
m_custom_data_( custom_data_(
std::make_unique<GHOST_C_CustomDataWrapper>(info.customdata, info.customdata_free_fn)) std::make_unique<GHOST_C_CustomDataWrapper>(info.customdata, info.customdata_free_fn))
{ {
m_subaction_paths.resize(info.count_subaction_paths); subaction_paths_.resize(info.count_subaction_paths);
for (uint32_t i = 0; i < info.count_subaction_paths; ++i) { for (uint32_t i = 0; i < info.count_subaction_paths; ++i) {
const char *subaction_path_str = info.subaction_paths[i]; const char *subaction_path_str = info.subaction_paths[i];
CHECK_XR(xrStringToPath(instance, subaction_path_str, &m_subaction_paths[i]), CHECK_XR(xrStringToPath(instance, subaction_path_str, &subaction_paths_[i]),
(std::string("Failed to get user path \"") + subaction_path_str + "\".").data()); (std::string("Failed to get user path \"") + subaction_path_str + "\".").data());
m_subaction_indices.insert({subaction_path_str, i}); subaction_indices_.insert({subaction_path_str, i});
} }
XrActionCreateInfo action_info{XR_TYPE_ACTION_CREATE_INFO}; XrActionCreateInfo action_info{XR_TYPE_ACTION_CREATE_INFO};
@@ -226,9 +224,9 @@ GHOST_XrAction::GHOST_XrAction(XrInstance instance,
break; break;
} }
action_info.countSubactionPaths = info.count_subaction_paths; action_info.countSubactionPaths = info.count_subaction_paths;
action_info.subactionPaths = m_subaction_paths.data(); action_info.subactionPaths = subaction_paths_.data();
CHECK_XR(xrCreateAction(action_set, &action_info, &m_action), CHECK_XR(xrCreateAction(action_set, &action_info, &action_),
(std::string("Failed to create action \"") + info.name + (std::string("Failed to create action \"") + info.name +
"\". Action name and/or paths are invalid. Name must not contain upper " "\". Action name and/or paths are invalid. Name must not contain upper "
"case letters or special characters other than '-', '_', or '.'.") "case letters or special characters other than '-', '_', or '.'.")
@@ -237,8 +235,8 @@ GHOST_XrAction::GHOST_XrAction(XrInstance instance,
GHOST_XrAction::~GHOST_XrAction() GHOST_XrAction::~GHOST_XrAction()
{ {
if (m_action != XR_NULL_HANDLE) { if (action_ != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroyAction(m_action)); CHECK_XR_ASSERT(xrDestroyAction(action_));
} }
} }
@@ -246,13 +244,13 @@ bool GHOST_XrAction::createBinding(XrInstance instance,
XrSession session, XrSession session,
const GHOST_XrActionProfileInfo &info) const GHOST_XrActionProfileInfo &info)
{ {
if (m_profiles.find(info.profile_path) != m_profiles.end()) { if (profiles_.find(info.profile_path) != profiles_.end()) {
return false; return false;
} }
m_profiles.emplace(std::piecewise_construct, profiles_.emplace(std::piecewise_construct,
std::make_tuple(info.profile_path), std::make_tuple(info.profile_path),
std::make_tuple(instance, session, m_action, m_type, info)); std::make_tuple(instance, session, action_, type_, info));
return true; return true;
} }
@@ -260,7 +258,7 @@ bool GHOST_XrAction::createBinding(XrInstance instance,
void GHOST_XrAction::destroyBinding(const char *profile_path) void GHOST_XrAction::destroyBinding(const char *profile_path)
{ {
/* It's possible nothing is removed. */ /* It's possible nothing is removed. */
m_profiles.erase(profile_path); profiles_.erase(profile_path);
} }
void GHOST_XrAction::updateState(XrSession session, void GHOST_XrAction::updateState(XrSession session,
@@ -268,16 +266,16 @@ void GHOST_XrAction::updateState(XrSession session,
XrSpace reference_space, XrSpace reference_space,
const XrTime &predicted_display_time) const XrTime &predicted_display_time)
{ {
const bool is_float_action = (m_type == GHOST_kXrActionTypeFloatInput || const bool is_float_action = (type_ == GHOST_kXrActionTypeFloatInput ||
m_type == GHOST_kXrActionTypeVector2fInput); type_ == GHOST_kXrActionTypeVector2fInput);
const bool is_button_action = (is_float_action || m_type == GHOST_kXrActionTypeBooleanInput); const bool is_button_action = (is_float_action || type_ == GHOST_kXrActionTypeBooleanInput);
XrActionStateGetInfo state_info{XR_TYPE_ACTION_STATE_GET_INFO}; XrActionStateGetInfo state_info{XR_TYPE_ACTION_STATE_GET_INFO};
state_info.action = m_action; state_info.action = action_;
const size_t count_subaction_paths = m_subaction_paths.size(); const size_t count_subaction_paths = subaction_paths_.size();
for (size_t subaction_idx = 0; subaction_idx < count_subaction_paths; ++subaction_idx) { for (size_t subaction_idx = 0; subaction_idx < count_subaction_paths; ++subaction_idx) {
state_info.subactionPath = m_subaction_paths[subaction_idx]; state_info.subactionPath = subaction_paths_[subaction_idx];
/* Set subaction data based on current interaction profile. */ /* Set subaction data based on current interaction profile. */
XrInteractionProfileState profile_state{XR_TYPE_INTERACTION_PROFILE_STATE}; XrInteractionProfileState profile_state{XR_TYPE_INTERACTION_PROFILE_STATE};
@@ -285,7 +283,7 @@ void GHOST_XrAction::updateState(XrSession session,
"Failed to get current interaction profile."); "Failed to get current interaction profile.");
const GHOST_XrSubactionData *subaction = nullptr; const GHOST_XrSubactionData *subaction = nullptr;
for (auto &[profile_path, profile] : m_profiles) { for (auto &[profile_path, profile] : profiles_) {
if (profile.getProfile() == profile_state.interactionProfile) { if (profile.getProfile() == profile_state.interactionProfile) {
subaction = profile.getSubaction(state_info.subactionPath); subaction = profile.getSubaction(state_info.subactionPath);
break; break;
@@ -294,21 +292,21 @@ void GHOST_XrAction::updateState(XrSession session,
if (subaction != nullptr) { if (subaction != nullptr) {
if (is_float_action) { if (is_float_action) {
m_float_thresholds[subaction_idx] = subaction->float_threshold; float_thresholds_[subaction_idx] = subaction->float_threshold;
} }
if (is_button_action) { if (is_button_action) {
m_axis_flags[subaction_idx] = subaction->axis_flag; axis_flags_[subaction_idx] = subaction->axis_flag;
} }
} }
switch (m_type) { switch (type_) {
case GHOST_kXrActionTypeBooleanInput: { case GHOST_kXrActionTypeBooleanInput: {
XrActionStateBoolean state{XR_TYPE_ACTION_STATE_BOOLEAN}; XrActionStateBoolean state{XR_TYPE_ACTION_STATE_BOOLEAN};
CHECK_XR(xrGetActionStateBoolean(session, &state_info, &state), CHECK_XR(xrGetActionStateBoolean(session, &state_info, &state),
(std::string("Failed to get state for boolean action \"") + action_name + "\".") (std::string("Failed to get state for boolean action \"") + action_name + "\".")
.data()); .data());
if (state.isActive) { if (state.isActive) {
((bool *)m_states)[subaction_idx] = state.currentState; ((bool *)states_)[subaction_idx] = state.currentState;
} }
break; break;
} }
@@ -318,7 +316,7 @@ void GHOST_XrAction::updateState(XrSession session,
xrGetActionStateFloat(session, &state_info, &state), xrGetActionStateFloat(session, &state_info, &state),
(std::string("Failed to get state for float action \"") + action_name + "\".").data()); (std::string("Failed to get state for float action \"") + action_name + "\".").data());
if (state.isActive) { if (state.isActive) {
((float *)m_states)[subaction_idx] = state.currentState; ((float *)states_)[subaction_idx] = state.currentState;
} }
break; break;
} }
@@ -328,7 +326,7 @@ void GHOST_XrAction::updateState(XrSession session,
(std::string("Failed to get state for vector2f action \"") + action_name + "\".") (std::string("Failed to get state for vector2f action \"") + action_name + "\".")
.data()); .data());
if (state.isActive) { if (state.isActive) {
memcpy(((float(*)[2])m_states)[subaction_idx], &state.currentState, sizeof(float[2])); memcpy(((float(*)[2])states_)[subaction_idx], &state.currentState, sizeof(float[2]));
} }
break; break;
} }
@@ -339,7 +337,7 @@ void GHOST_XrAction::updateState(XrSession session,
CHECK_XR(xrGetActionStatePose(session, &state_info, &state), CHECK_XR(xrGetActionStatePose(session, &state_info, &state),
(std::string("Failed to get state for pose action \"") + action_name + "\".") (std::string("Failed to get state for pose action \"") + action_name + "\".")
.data()); .data());
((GHOST_XrPose *)m_states)[subaction_idx].is_active = state.isActive; ((GHOST_XrPose *)states_)[subaction_idx].is_active = state.isActive;
if (state.isActive) { if (state.isActive) {
XrSpace pose_space = ((subaction != nullptr) && (subaction->space != nullptr)) ? XrSpace pose_space = ((subaction != nullptr) && (subaction->space != nullptr)) ?
subaction->space->getSpace() : subaction->space->getSpace() :
@@ -352,7 +350,7 @@ void GHOST_XrAction::updateState(XrSession session,
(std::string("Failed to query pose space for action \"") + action_name + "\".") (std::string("Failed to query pose space for action \"") + action_name + "\".")
.data()); .data());
copy_openxr_pose_to_ghost_pose(space_location.pose, copy_openxr_pose_to_ghost_pose(space_location.pose,
((GHOST_XrPose *)m_states)[subaction_idx]); ((GHOST_XrPose *)states_)[subaction_idx]);
} }
} }
} }
@@ -379,19 +377,19 @@ void GHOST_XrAction::applyHapticFeedback(XrSession session,
vibration.amplitude = amplitude; vibration.amplitude = amplitude;
XrHapticActionInfo haptic_info{XR_TYPE_HAPTIC_ACTION_INFO}; XrHapticActionInfo haptic_info{XR_TYPE_HAPTIC_ACTION_INFO};
haptic_info.action = m_action; haptic_info.action = action_;
if (subaction_path_str != nullptr) { if (subaction_path_str != nullptr) {
SubactionIndexMap::iterator it = m_subaction_indices.find(subaction_path_str); SubactionIndexMap::iterator it = subaction_indices_.find(subaction_path_str);
if (it != m_subaction_indices.end()) { if (it != subaction_indices_.end()) {
haptic_info.subactionPath = m_subaction_paths[it->second]; haptic_info.subactionPath = subaction_paths_[it->second];
CHECK_XR( CHECK_XR(
xrApplyHapticFeedback(session, &haptic_info, (const XrHapticBaseHeader *)&vibration), xrApplyHapticFeedback(session, &haptic_info, (const XrHapticBaseHeader *)&vibration),
(std::string("Failed to apply haptic action \"") + action_name + "\".").data()); (std::string("Failed to apply haptic action \"") + action_name + "\".").data());
} }
} }
else { else {
for (const XrPath &subaction_path : m_subaction_paths) { for (const XrPath &subaction_path : subaction_paths_) {
haptic_info.subactionPath = subaction_path; haptic_info.subactionPath = subaction_path;
CHECK_XR( CHECK_XR(
xrApplyHapticFeedback(session, &haptic_info, (const XrHapticBaseHeader *)&vibration), xrApplyHapticFeedback(session, &haptic_info, (const XrHapticBaseHeader *)&vibration),
@@ -405,18 +403,18 @@ void GHOST_XrAction::stopHapticFeedback(XrSession session,
const char *subaction_path_str) const char *subaction_path_str)
{ {
XrHapticActionInfo haptic_info{XR_TYPE_HAPTIC_ACTION_INFO}; XrHapticActionInfo haptic_info{XR_TYPE_HAPTIC_ACTION_INFO};
haptic_info.action = m_action; haptic_info.action = action_;
if (subaction_path_str != nullptr) { if (subaction_path_str != nullptr) {
SubactionIndexMap::iterator it = m_subaction_indices.find(subaction_path_str); SubactionIndexMap::iterator it = subaction_indices_.find(subaction_path_str);
if (it != m_subaction_indices.end()) { if (it != subaction_indices_.end()) {
haptic_info.subactionPath = m_subaction_paths[it->second]; haptic_info.subactionPath = subaction_paths_[it->second];
CHECK_XR(xrStopHapticFeedback(session, &haptic_info), CHECK_XR(xrStopHapticFeedback(session, &haptic_info),
(std::string("Failed to stop haptic action \"") + action_name + "\".").data()); (std::string("Failed to stop haptic action \"") + action_name + "\".").data());
} }
} }
else { else {
for (const XrPath &subaction_path : m_subaction_paths) { for (const XrPath &subaction_path : subaction_paths_) {
haptic_info.subactionPath = subaction_path; haptic_info.subactionPath = subaction_path;
CHECK_XR(xrStopHapticFeedback(session, &haptic_info), CHECK_XR(xrStopHapticFeedback(session, &haptic_info),
(std::string("Failed to stop haptic action \"") + action_name + "\".").data()); (std::string("Failed to stop haptic action \"") + action_name + "\".").data());
@@ -426,17 +424,17 @@ void GHOST_XrAction::stopHapticFeedback(XrSession session,
void *GHOST_XrAction::getCustomdata() void *GHOST_XrAction::getCustomdata()
{ {
if (m_custom_data_ == nullptr) { if (custom_data_ == nullptr) {
return nullptr; return nullptr;
} }
return m_custom_data_->custom_data_; return custom_data_->custom_data_;
} }
void GHOST_XrAction::getBindings( void GHOST_XrAction::getBindings(
std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const
{ {
for (auto &[path, profile] : m_profiles) { for (auto &[path, profile] : profiles_) {
profile.getBindings(m_action, r_bindings); profile.getBindings(action_, r_bindings);
} }
} }
@@ -448,7 +446,7 @@ void GHOST_XrAction::getBindings(
* \{ */ * \{ */
GHOST_XrActionSet::GHOST_XrActionSet(XrInstance instance, const GHOST_XrActionSetInfo &info) GHOST_XrActionSet::GHOST_XrActionSet(XrInstance instance, const GHOST_XrActionSetInfo &info)
: m_custom_data_( : custom_data_(
std::make_unique<GHOST_C_CustomDataWrapper>(info.customdata, info.customdata_free_fn)) std::make_unique<GHOST_C_CustomDataWrapper>(info.customdata, info.customdata_free_fn))
{ {
XrActionSetCreateInfo action_set_info{XR_TYPE_ACTION_SET_CREATE_INFO}; XrActionSetCreateInfo action_set_info{XR_TYPE_ACTION_SET_CREATE_INFO};
@@ -459,7 +457,7 @@ GHOST_XrActionSet::GHOST_XrActionSet(XrInstance instance, const GHOST_XrActionSe
action_set_info.priority = 0; /* Use same (default) priority for all action sets. */ action_set_info.priority = 0; /* Use same (default) priority for all action sets. */
CHECK_XR(xrCreateActionSet(instance, &action_set_info, &m_action_set), CHECK_XR(xrCreateActionSet(instance, &action_set_info, &action_set_),
(std::string("Failed to create action set \"") + info.name + (std::string("Failed to create action set \"") + info.name +
"\". Name must not contain upper case letters or special characters " "\". Name must not contain upper case letters or special characters "
"other than '-', '_', or '.'.") "other than '-', '_', or '.'.")
@@ -470,22 +468,22 @@ GHOST_XrActionSet::~GHOST_XrActionSet()
{ {
/* This needs to be done before xrDestroyActionSet() to avoid an assertion in the GHOST_XrAction /* This needs to be done before xrDestroyActionSet() to avoid an assertion in the GHOST_XrAction
* destructor (which calls xrDestroyAction()). */ * destructor (which calls xrDestroyAction()). */
m_actions.clear(); actions_.clear();
if (m_action_set != XR_NULL_HANDLE) { if (action_set_ != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroyActionSet(m_action_set)); CHECK_XR_ASSERT(xrDestroyActionSet(action_set_));
} }
} }
bool GHOST_XrActionSet::createAction(XrInstance instance, const GHOST_XrActionInfo &info) bool GHOST_XrActionSet::createAction(XrInstance instance, const GHOST_XrActionInfo &info)
{ {
if (m_actions.find(info.name) != m_actions.end()) { if (actions_.find(info.name) != actions_.end()) {
return false; return false;
} }
m_actions.emplace(std::piecewise_construct, actions_.emplace(std::piecewise_construct,
std::make_tuple(info.name), std::make_tuple(info.name),
std::make_tuple(instance, m_action_set, info)); std::make_tuple(instance, action_set_, info));
return true; return true;
} }
@@ -493,13 +491,13 @@ bool GHOST_XrActionSet::createAction(XrInstance instance, const GHOST_XrActionIn
void GHOST_XrActionSet::destroyAction(const char *action_name) void GHOST_XrActionSet::destroyAction(const char *action_name)
{ {
/* It's possible nothing is removed. */ /* It's possible nothing is removed. */
m_actions.erase(action_name); actions_.erase(action_name);
} }
GHOST_XrAction *GHOST_XrActionSet::findAction(const char *action_name) GHOST_XrAction *GHOST_XrActionSet::findAction(const char *action_name)
{ {
std::map<std::string, GHOST_XrAction>::iterator it = m_actions.find(action_name); std::map<std::string, GHOST_XrAction>::iterator it = actions_.find(action_name);
if (it == m_actions.end()) { if (it == actions_.end()) {
return nullptr; return nullptr;
} }
return &it->second; return &it->second;
@@ -509,33 +507,33 @@ void GHOST_XrActionSet::updateStates(XrSession session,
XrSpace reference_space, XrSpace reference_space,
const XrTime &predicted_display_time) const XrTime &predicted_display_time)
{ {
for (auto &[name, action] : m_actions) { for (auto &[name, action] : actions_) {
action.updateState(session, name.data(), reference_space, predicted_display_time); action.updateState(session, name.data(), reference_space, predicted_display_time);
} }
} }
XrActionSet GHOST_XrActionSet::getActionSet() const XrActionSet GHOST_XrActionSet::getActionSet() const
{ {
return m_action_set; return action_set_;
} }
void *GHOST_XrActionSet::getCustomdata() void *GHOST_XrActionSet::getCustomdata()
{ {
if (m_custom_data_ == nullptr) { if (custom_data_ == nullptr) {
return nullptr; return nullptr;
} }
return m_custom_data_->custom_data_; return custom_data_->custom_data_;
} }
uint32_t GHOST_XrActionSet::getActionCount() const uint32_t GHOST_XrActionSet::getActionCount() const
{ {
return uint32_t(m_actions.size()); return uint32_t(actions_.size());
} }
void GHOST_XrActionSet::getActionCustomdataArray(void **r_customdata_array) void GHOST_XrActionSet::getActionCustomdataArray(void **r_customdata_array)
{ {
uint32_t i = 0; uint32_t i = 0;
for (auto &[name, action] : m_actions) { for (auto &[name, action] : actions_) {
r_customdata_array[i++] = action.getCustomdata(); r_customdata_array[i++] = action.getCustomdata();
} }
} }
@@ -543,7 +541,7 @@ void GHOST_XrActionSet::getActionCustomdataArray(void **r_customdata_array)
void GHOST_XrActionSet::getBindings( void GHOST_XrActionSet::getBindings(
std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const
{ {
for (auto &[name, action] : m_actions) { for (auto &[name, action] : actions_) {
action.getBindings(r_bindings); action.getBindings(r_bindings);
} }
} }

View File

@@ -34,7 +34,7 @@ class GHOST_XrActionSpace {
XrSpace getSpace() const; XrSpace getSpace() const;
private: private:
XrSpace m_space = XR_NULL_HANDLE; XrSpace space_ = XR_NULL_HANDLE;
}; };
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
@@ -64,12 +64,12 @@ class GHOST_XrActionProfile {
std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const; std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const;
private: private:
XrPath m_profile = XR_NULL_PATH; XrPath profile_ = XR_NULL_PATH;
/** Sub-action data identified by user `subaction` path. */ /** Sub-action data identified by user `subaction` path. */
std::map<std::string, GHOST_XrSubactionData> m_subaction_data; std::map<std::string, GHOST_XrSubactionData> subaction_data_;
/** Bindings identified by interaction (user `subaction` + component) path. */ /** Bindings identified by interaction (user `subaction` + component) path. */
std::map<std::string, XrPath> m_bindings; std::map<std::string, XrPath> bindings_;
}; };
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
@@ -105,20 +105,20 @@ class GHOST_XrAction {
private: private:
using SubactionIndexMap = std::map<std::string, uint32_t>; using SubactionIndexMap = std::map<std::string, uint32_t>;
XrAction m_action = XR_NULL_HANDLE; XrAction action_ = XR_NULL_HANDLE;
GHOST_XrActionType m_type; GHOST_XrActionType type_;
SubactionIndexMap m_subaction_indices; SubactionIndexMap subaction_indices_;
std::vector<XrPath> m_subaction_paths; std::vector<XrPath> subaction_paths_;
/** States for each subaction path. */ /** States for each subaction path. */
void *m_states; void *states_;
/** Input thresholds/regions for each subaction path. */ /** Input thresholds/regions for each subaction path. */
float *m_float_thresholds; float *float_thresholds_;
int16_t *m_axis_flags; int16_t *axis_flags_;
std::unique_ptr<GHOST_C_CustomDataWrapper> m_custom_data_ = nullptr; /* wmXrAction */ std::unique_ptr<GHOST_C_CustomDataWrapper> custom_data_ = nullptr; /* wmXrAction */
/** Profiles identified by interaction profile path. */ /** Profiles identified by interaction profile path. */
std::map<std::string, GHOST_XrActionProfile> m_profiles; std::map<std::string, GHOST_XrActionProfile> profiles_;
}; };
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */
@@ -144,11 +144,11 @@ class GHOST_XrActionSet {
void getBindings(std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const; void getBindings(std::map<XrPath, std::vector<XrActionSuggestedBinding>> &r_bindings) const;
private: private:
XrActionSet m_action_set = XR_NULL_HANDLE; XrActionSet action_set_ = XR_NULL_HANDLE;
std::unique_ptr<GHOST_C_CustomDataWrapper> m_custom_data_ = nullptr; /* wmXrActionSet */ std::unique_ptr<GHOST_C_CustomDataWrapper> custom_data_ = nullptr; /* wmXrActionSet */
std::map<std::string, GHOST_XrAction> m_actions; std::map<std::string, GHOST_XrAction> actions_;
}; };
/* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */

View File

@@ -47,9 +47,9 @@ void *GHOST_XrContext::s_error_handler_customdata = nullptr;
* \{ */ * \{ */
GHOST_XrContext::GHOST_XrContext(const GHOST_XrContextCreateInfo *create_info) GHOST_XrContext::GHOST_XrContext(const GHOST_XrContextCreateInfo *create_info)
: m_oxr(std::make_unique<OpenXRInstanceData>()), : oxr_(std::make_unique<OpenXRInstanceData>()),
m_debug(create_info->context_flag & GHOST_kXrContextDebug), debug_(create_info->context_flag & GHOST_kXrContextDebug),
m_debug_time(create_info->context_flag & GHOST_kXrContextDebugTime) debug_time_(create_info->context_flag & GHOST_kXrContextDebugTime)
{ {
} }
@@ -57,15 +57,15 @@ GHOST_XrContext::~GHOST_XrContext()
{ {
/* Destroy session data first. Otherwise xrDestroyInstance will implicitly do it, before the /* Destroy session data first. Otherwise xrDestroyInstance will implicitly do it, before the
* session had a chance to do so explicitly. */ * session had a chance to do so explicitly. */
m_session = nullptr; session_ = nullptr;
if (m_oxr->debug_messenger != XR_NULL_HANDLE) { if (oxr_->debug_messenger != XR_NULL_HANDLE) {
assert(m_oxr->s_xrDestroyDebugUtilsMessengerEXT_fn != nullptr); assert(oxr_->s_xrDestroyDebugUtilsMessengerEXT_fn != nullptr);
m_oxr->s_xrDestroyDebugUtilsMessengerEXT_fn(m_oxr->debug_messenger); oxr_->s_xrDestroyDebugUtilsMessengerEXT_fn(oxr_->debug_messenger);
} }
if (m_oxr->instance != XR_NULL_HANDLE) { if (oxr_->instance != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroyInstance(m_oxr->instance)); CHECK_XR_ASSERT(xrDestroyInstance(oxr_->instance));
m_oxr->instance = XR_NULL_HANDLE; oxr_->instance = XR_NULL_HANDLE;
} }
} }
@@ -83,12 +83,12 @@ void GHOST_XrContext::initialize(const GHOST_XrContextCreateInfo *create_info)
const std::vector<GHOST_TXrGraphicsBinding> graphics_binding_types = const std::vector<GHOST_TXrGraphicsBinding> graphics_binding_types =
determineGraphicsBindingTypesToEnable(create_info); determineGraphicsBindingTypesToEnable(create_info);
assert(m_oxr->instance == XR_NULL_HANDLE); assert(oxr_->instance == XR_NULL_HANDLE);
createOpenXRInstance(graphics_binding_types); createOpenXRInstance(graphics_binding_types);
storeInstanceProperties(); storeInstanceProperties();
/* Multiple bindings may be enabled. Now that we know the runtime in use, settle for one. */ /* Multiple bindings may be enabled. Now that we know the runtime in use, settle for one. */
m_gpu_binding_type = determineGraphicsBindingTypeToUse(graphics_binding_types, create_info); gpu_binding_type_ = determineGraphicsBindingTypeToUse(graphics_binding_types, create_info);
printInstanceInfo(); printInstanceInfo();
if (isDebugMode()) { if (isDebugMode()) {
@@ -105,17 +105,17 @@ void GHOST_XrContext::createOpenXRInstance(
XR_MAX_APPLICATION_NAME_SIZE); XR_MAX_APPLICATION_NAME_SIZE);
create_info.applicationInfo.apiVersion = XR_CURRENT_API_VERSION; create_info.applicationInfo.apiVersion = XR_CURRENT_API_VERSION;
getAPILayersToEnable(m_enabled_layers); getAPILayersToEnable(enabled_layers_);
getExtensionsToEnable(graphics_binding_types, m_enabled_extensions); getExtensionsToEnable(graphics_binding_types, enabled_extensions_);
create_info.enabledApiLayerCount = m_enabled_layers.size(); create_info.enabledApiLayerCount = enabled_layers_.size();
create_info.enabledApiLayerNames = m_enabled_layers.data(); create_info.enabledApiLayerNames = enabled_layers_.data();
create_info.enabledExtensionCount = m_enabled_extensions.size(); create_info.enabledExtensionCount = enabled_extensions_.size();
create_info.enabledExtensionNames = m_enabled_extensions.data(); create_info.enabledExtensionNames = enabled_extensions_.data();
if (isDebugMode()) { if (isDebugMode()) {
printExtensionsAndAPILayersToEnable(); printExtensionsAndAPILayersToEnable();
} }
CHECK_XR(xrCreateInstance(&create_info, &m_oxr->instance), CHECK_XR(xrCreateInstance(&create_info, &oxr_->instance),
"Failed to connect to an OpenXR runtime."); "Failed to connect to an OpenXR runtime.");
} }
@@ -129,13 +129,13 @@ void GHOST_XrContext::storeInstanceProperties()
{"Varjo OpenXR Runtime", OPENXR_RUNTIME_VARJO}}; {"Varjo OpenXR Runtime", OPENXR_RUNTIME_VARJO}};
decltype(runtime_map)::const_iterator runtime_map_iter; decltype(runtime_map)::const_iterator runtime_map_iter;
m_oxr->instance_properties.type = XR_TYPE_INSTANCE_PROPERTIES; oxr_->instance_properties.type = XR_TYPE_INSTANCE_PROPERTIES;
CHECK_XR(xrGetInstanceProperties(m_oxr->instance, &m_oxr->instance_properties), CHECK_XR(xrGetInstanceProperties(oxr_->instance, &oxr_->instance_properties),
"Failed to get OpenXR runtime information. Do you have an active runtime set up?"); "Failed to get OpenXR runtime information. Do you have an active runtime set up?");
runtime_map_iter = runtime_map.find(m_oxr->instance_properties.runtimeName); runtime_map_iter = runtime_map.find(oxr_->instance_properties.runtimeName);
if (runtime_map_iter != runtime_map.end()) { if (runtime_map_iter != runtime_map.end()) {
m_runtime_id = runtime_map_iter->second; runtime_id_ = runtime_map_iter->second;
} }
} }
@@ -157,32 +157,32 @@ void GHOST_XrContext::printSDKVersion()
void GHOST_XrContext::printInstanceInfo() void GHOST_XrContext::printInstanceInfo()
{ {
assert(m_oxr->instance != XR_NULL_HANDLE); assert(oxr_->instance != XR_NULL_HANDLE);
printf("Connected to OpenXR runtime: %s (Version %u.%u.%u)\n", printf("Connected to OpenXR runtime: %s (Version %u.%u.%u)\n",
m_oxr->instance_properties.runtimeName, oxr_->instance_properties.runtimeName,
XR_VERSION_MAJOR(m_oxr->instance_properties.runtimeVersion), XR_VERSION_MAJOR(oxr_->instance_properties.runtimeVersion),
XR_VERSION_MINOR(m_oxr->instance_properties.runtimeVersion), XR_VERSION_MINOR(oxr_->instance_properties.runtimeVersion),
XR_VERSION_PATCH(m_oxr->instance_properties.runtimeVersion)); XR_VERSION_PATCH(oxr_->instance_properties.runtimeVersion));
} }
void GHOST_XrContext::printAvailableAPILayersAndExtensionsInfo() void GHOST_XrContext::printAvailableAPILayersAndExtensionsInfo()
{ {
puts("Available OpenXR API-layers/extensions:"); puts("Available OpenXR API-layers/extensions:");
for (const XrApiLayerProperties &layer_info : m_oxr->layers) { for (const XrApiLayerProperties &layer_info : oxr_->layers) {
printf("Layer: %s\n", layer_info.layerName); printf("Layer: %s\n", layer_info.layerName);
} }
for (const XrExtensionProperties &ext_info : m_oxr->extensions) { for (const XrExtensionProperties &ext_info : oxr_->extensions) {
printf("Extension: %s\n", ext_info.extensionName); printf("Extension: %s\n", ext_info.extensionName);
} }
} }
void GHOST_XrContext::printExtensionsAndAPILayersToEnable() void GHOST_XrContext::printExtensionsAndAPILayersToEnable()
{ {
for (const char *layer_name : m_enabled_layers) { for (const char *layer_name : enabled_layers_) {
printf("Enabling OpenXR API-Layer: %s\n", layer_name); printf("Enabling OpenXR API-Layer: %s\n", layer_name);
} }
for (const char *ext_name : m_enabled_extensions) { for (const char *ext_name : enabled_extensions_) {
printf("Enabling OpenXR Extension: %s\n", ext_name); printf("Enabling OpenXR Extension: %s\n", ext_name);
} }
} }
@@ -190,7 +190,7 @@ void GHOST_XrContext::printExtensionsAndAPILayersToEnable()
static XrBool32 debug_messenger_func(XrDebugUtilsMessageSeverityFlagsEXT /*messageSeverity*/, static XrBool32 debug_messenger_func(XrDebugUtilsMessageSeverityFlagsEXT /*messageSeverity*/,
XrDebugUtilsMessageTypeFlagsEXT /*messageTypes*/, XrDebugUtilsMessageTypeFlagsEXT /*messageTypes*/,
const XrDebugUtilsMessengerCallbackDataEXT *callbackData, const XrDebugUtilsMessengerCallbackDataEXT *callbackData,
void * /*userData*/) void * /*user_data*/)
{ {
puts("OpenXR Debug Message:"); puts("OpenXR Debug Message:");
puts(callbackData->message); puts(callbackData->message);
@@ -203,16 +203,16 @@ void GHOST_XrContext::initDebugMessenger()
/* Extension functions need to be obtained through xrGetInstanceProcAddr(). */ /* Extension functions need to be obtained through xrGetInstanceProcAddr(). */
if (XR_FAILED(xrGetInstanceProcAddr( if (XR_FAILED(xrGetInstanceProcAddr(
m_oxr->instance, oxr_->instance,
"xrCreateDebugUtilsMessengerEXT", "xrCreateDebugUtilsMessengerEXT",
(PFN_xrVoidFunction *)&m_oxr->s_xrCreateDebugUtilsMessengerEXT_fn)) || (PFN_xrVoidFunction *)&oxr_->s_xrCreateDebugUtilsMessengerEXT_fn)) ||
XR_FAILED(xrGetInstanceProcAddr( XR_FAILED(xrGetInstanceProcAddr(
m_oxr->instance, oxr_->instance,
"xrDestroyDebugUtilsMessengerEXT", "xrDestroyDebugUtilsMessengerEXT",
(PFN_xrVoidFunction *)&m_oxr->s_xrDestroyDebugUtilsMessengerEXT_fn))) (PFN_xrVoidFunction *)&oxr_->s_xrDestroyDebugUtilsMessengerEXT_fn)))
{ {
m_oxr->s_xrCreateDebugUtilsMessengerEXT_fn = nullptr; oxr_->s_xrCreateDebugUtilsMessengerEXT_fn = nullptr;
m_oxr->s_xrDestroyDebugUtilsMessengerEXT_fn = nullptr; oxr_->s_xrDestroyDebugUtilsMessengerEXT_fn = nullptr;
fprintf(stderr, fprintf(stderr,
"Could not use XR_EXT_debug_utils to enable debug prints. Not a fatal error, " "Could not use XR_EXT_debug_utils to enable debug prints. Not a fatal error, "
@@ -229,8 +229,8 @@ void GHOST_XrContext::initDebugMessenger()
XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
create_info.userCallback = debug_messenger_func; create_info.userCallback = debug_messenger_func;
if (XR_FAILED(m_oxr->s_xrCreateDebugUtilsMessengerEXT_fn( if (XR_FAILED(oxr_->s_xrCreateDebugUtilsMessengerEXT_fn(
m_oxr->instance, &create_info, &m_oxr->debug_messenger))) oxr_->instance, &create_info, &oxr_->debug_messenger)))
{ {
fprintf(stderr, fprintf(stderr,
"Failed to create OpenXR debug messenger. Not a fatal error, continuing without the " "Failed to create OpenXR debug messenger. Not a fatal error, continuing without the "
@@ -249,14 +249,12 @@ void GHOST_XrContext::dispatchErrorMessage(const GHOST_XrException *exception) c
{ {
GHOST_XrError error; GHOST_XrError error;
error.user_message = exception->m_msg.data(); error.user_message = exception->msg_.data();
error.customdata = s_error_handler_customdata; error.customdata = s_error_handler_customdata;
if (isDebugMode()) { if (isDebugMode()) {
fprintf(stderr, fprintf(
"Error: \t%s\n\tOpenXR error value: %i\n", stderr, "Error: \t%s\n\tOpenXR error value: %i\n", error.user_message, exception->result_);
error.user_message,
exception->m_result);
} }
/* Potentially destroys GHOST_XrContext */ /* Potentially destroys GHOST_XrContext */
@@ -305,7 +303,7 @@ void GHOST_XrContext::initExtensionsEx(std::vector<XrExtensionProperties> &exten
void GHOST_XrContext::initExtensions() void GHOST_XrContext::initExtensions()
{ {
initExtensionsEx(m_oxr->extensions, nullptr); initExtensionsEx(oxr_->extensions, nullptr);
} }
void GHOST_XrContext::initApiLayers() void GHOST_XrContext::initApiLayers()
@@ -321,17 +319,17 @@ void GHOST_XrContext::initApiLayers()
return; return;
} }
m_oxr->layers = std::vector<XrApiLayerProperties>(layer_count); oxr_->layers = std::vector<XrApiLayerProperties>(layer_count);
for (XrApiLayerProperties &layer : m_oxr->layers) { for (XrApiLayerProperties &layer : oxr_->layers) {
layer.type = XR_TYPE_API_LAYER_PROPERTIES; layer.type = XR_TYPE_API_LAYER_PROPERTIES;
} }
/* Actually get the layers. */ /* Actually get the layers. */
CHECK_XR(xrEnumerateApiLayerProperties(layer_count, &layer_count, m_oxr->layers.data()), CHECK_XR(xrEnumerateApiLayerProperties(layer_count, &layer_count, oxr_->layers.data()),
"Failed to query OpenXR runtime information. Do you have an active runtime set up?"); "Failed to query OpenXR runtime information. Do you have an active runtime set up?");
for (const XrApiLayerProperties &layer : m_oxr->layers) { for (const XrApiLayerProperties &layer : oxr_->layers) {
/* Each layer may have own extensions. */ /* Each layer may have own extensions. */
initExtensionsEx(m_oxr->extensions, layer.layerName); initExtensionsEx(oxr_->extensions, layer.layerName);
} }
} }
@@ -376,7 +374,7 @@ void GHOST_XrContext::getAPILayersToEnable(std::vector<const char *> &r_ext_name
r_ext_names.reserve(try_layers.size()); r_ext_names.reserve(try_layers.size());
for (const std::string &layer : try_layers) { for (const std::string &layer : try_layers) {
if (openxr_layer_is_available(m_oxr->layers, layer)) { if (openxr_layer_is_available(oxr_->layers, layer)) {
r_ext_names.push_back(layer.data()); r_ext_names.push_back(layer.data());
} }
} }
@@ -456,19 +454,19 @@ void GHOST_XrContext::getExtensionsToEnable(
* we have more info about the runtime). */ * we have more info about the runtime). */
for (GHOST_TXrGraphicsBinding type : graphics_binding_types) { for (GHOST_TXrGraphicsBinding type : graphics_binding_types) {
const char *gpu_binding = openxr_ext_name_from_wm_gpu_binding(type); const char *gpu_binding = openxr_ext_name_from_wm_gpu_binding(type);
assert(openxr_extension_is_available(m_oxr->extensions, gpu_binding)); assert(openxr_extension_is_available(oxr_->extensions, gpu_binding));
r_ext_names.push_back(gpu_binding); r_ext_names.push_back(gpu_binding);
} }
#if defined(WITH_GHOST_X11) #if defined(WITH_GHOST_X11)
if (openxr_extension_is_available(m_oxr->extensions, XR_MNDX_EGL_ENABLE_EXTENSION_NAME)) { if (openxr_extension_is_available(oxr_->extensions, XR_MNDX_EGL_ENABLE_EXTENSION_NAME)) {
/* Use EGL if that backend is available. */ /* Use EGL if that backend is available. */
r_ext_names.push_back(XR_MNDX_EGL_ENABLE_EXTENSION_NAME); r_ext_names.push_back(XR_MNDX_EGL_ENABLE_EXTENSION_NAME);
} }
#endif #endif
for (const std::string_view &ext : try_ext) { for (const std::string_view &ext : try_ext) {
if (openxr_extension_is_available(m_oxr->extensions, ext)) { if (openxr_extension_is_available(oxr_->extensions, ext)) {
r_ext_names.push_back(ext.data()); r_ext_names.push_back(ext.data());
} }
} }
@@ -489,7 +487,7 @@ std::vector<GHOST_TXrGraphicsBinding> GHOST_XrContext::determineGraphicsBindingT
assert(create_info->gpu_binding_candidates[i] != GHOST_kXrGraphicsUnknown); assert(create_info->gpu_binding_candidates[i] != GHOST_kXrGraphicsUnknown);
const char *ext_name = openxr_ext_name_from_wm_gpu_binding( const char *ext_name = openxr_ext_name_from_wm_gpu_binding(
create_info->gpu_binding_candidates[i]); create_info->gpu_binding_candidates[i]);
if (openxr_extension_is_available(m_oxr->extensions, ext_name)) { if (openxr_extension_is_available(oxr_->extensions, ext_name)) {
result.push_back(create_info->gpu_binding_candidates[i]); result.push_back(create_info->gpu_binding_candidates[i]);
} }
} }
@@ -510,7 +508,7 @@ GHOST_TXrGraphicsBinding GHOST_XrContext::determineGraphicsBindingTypeToUse(
#ifdef WIN32 #ifdef WIN32
/* The SteamVR OpenGL backend currently fails for NVIDIA GPU's. Disable it and allow falling /* The SteamVR OpenGL backend currently fails for NVIDIA GPU's. Disable it and allow falling
* back to the DirectX one. */ * back to the DirectX one. */
if ((m_runtime_id == OPENXR_RUNTIME_STEAMVR) && (type == GHOST_kXrGraphicsOpenGL) && if ((runtime_id_ == OPENXR_RUNTIME_STEAMVR) && (type == GHOST_kXrGraphicsOpenGL) &&
((create_info->context_flag & GHOST_kXrContextGpuNVIDIA) != 0)) ((create_info->context_flag & GHOST_kXrContextGpuNVIDIA) != 0))
{ {
continue; continue;
@@ -536,36 +534,36 @@ GHOST_TXrGraphicsBinding GHOST_XrContext::determineGraphicsBindingTypeToUse(
void GHOST_XrContext::startSession(const GHOST_XrSessionBeginInfo *begin_info) void GHOST_XrContext::startSession(const GHOST_XrSessionBeginInfo *begin_info)
{ {
m_custom_funcs.session_create_fn = begin_info->create_fn; custom_funcs_.session_create_fn = begin_info->create_fn;
m_custom_funcs.session_exit_fn = begin_info->exit_fn; custom_funcs_.session_exit_fn = begin_info->exit_fn;
m_custom_funcs.session_exit_customdata = begin_info->exit_customdata; custom_funcs_.session_exit_customdata = begin_info->exit_customdata;
if (m_session == nullptr) { if (session_ == nullptr) {
m_session = std::make_unique<GHOST_XrSession>(*this); session_ = std::make_unique<GHOST_XrSession>(*this);
} }
m_session->start(begin_info); session_->start(begin_info);
} }
void GHOST_XrContext::endSession() void GHOST_XrContext::endSession()
{ {
if (m_session) { if (session_) {
if (m_session->isRunning()) { if (session_->isRunning()) {
m_session->requestEnd(); session_->requestEnd();
} }
else { else {
m_session = nullptr; session_ = nullptr;
} }
} }
} }
bool GHOST_XrContext::isSessionRunning() const bool GHOST_XrContext::isSessionRunning() const
{ {
return m_session && m_session->isRunning(); return session_ && session_->isRunning();
} }
void GHOST_XrContext::drawSessionViews(void *draw_customdata) void GHOST_XrContext::drawSessionViews(void *draw_customdata)
{ {
m_session->draw(draw_customdata); session_->draw(draw_customdata);
} }
/** /**
@@ -573,10 +571,9 @@ void GHOST_XrContext::drawSessionViews(void *draw_customdata)
*/ */
void GHOST_XrContext::handleSessionStateChange(const XrEventDataSessionStateChanged &lifecycle) void GHOST_XrContext::handleSessionStateChange(const XrEventDataSessionStateChanged &lifecycle)
{ {
if (m_session && if (session_ && session_->handleStateChangeEvent(lifecycle) == GHOST_XrSession::SESSION_DESTROY)
m_session->handleStateChangeEvent(lifecycle) == GHOST_XrSession::SESSION_DESTROY)
{ {
m_session = nullptr; session_ = nullptr;
} }
} }
@@ -590,46 +587,46 @@ void GHOST_XrContext::handleSessionStateChange(const XrEventDataSessionStateChan
GHOST_XrSession *GHOST_XrContext::getSession() GHOST_XrSession *GHOST_XrContext::getSession()
{ {
return m_session.get(); return session_.get();
} }
const GHOST_XrSession *GHOST_XrContext::getSession() const const GHOST_XrSession *GHOST_XrContext::getSession() const
{ {
return m_session.get(); return session_.get();
} }
void GHOST_XrContext::setGraphicsContextBindFuncs(GHOST_XrGraphicsContextBindFn bind_fn, void GHOST_XrContext::setGraphicsContextBindFuncs(GHOST_XrGraphicsContextBindFn bind_fn,
GHOST_XrGraphicsContextUnbindFn unbind_fn) GHOST_XrGraphicsContextUnbindFn unbind_fn)
{ {
if (m_session) { if (session_) {
m_session->unbindGraphicsContext(); session_->unbindGraphicsContext();
} }
m_custom_funcs.gpu_ctx_bind_fn = bind_fn; custom_funcs_.gpu_ctx_bind_fn = bind_fn;
m_custom_funcs.gpu_ctx_unbind_fn = unbind_fn; custom_funcs_.gpu_ctx_unbind_fn = unbind_fn;
} }
void GHOST_XrContext::setDrawViewFunc(GHOST_XrDrawViewFn draw_view_fn) void GHOST_XrContext::setDrawViewFunc(GHOST_XrDrawViewFn draw_view_fn)
{ {
m_custom_funcs.draw_view_fn = draw_view_fn; custom_funcs_.draw_view_fn = draw_view_fn;
} }
void GHOST_XrContext::setPassthroughEnabledFunc( void GHOST_XrContext::setPassthroughEnabledFunc(
GHOST_XrPassthroughEnabledFn passthrough_enabled_fn) GHOST_XrPassthroughEnabledFn passthrough_enabled_fn)
{ {
m_custom_funcs.passthrough_enabled_fn = passthrough_enabled_fn; custom_funcs_.passthrough_enabled_fn = passthrough_enabled_fn;
} }
void GHOST_XrContext::setDisablePassthroughFunc( void GHOST_XrContext::setDisablePassthroughFunc(
GHOST_XrDisablePassthroughFn disable_passthrough_fn) GHOST_XrDisablePassthroughFn disable_passthrough_fn)
{ {
m_custom_funcs.disable_passthrough_fn = disable_passthrough_fn; custom_funcs_.disable_passthrough_fn = disable_passthrough_fn;
} }
bool GHOST_XrContext::needsUpsideDownDrawing() const bool GHOST_XrContext::needsUpsideDownDrawing() const
{ {
/* Must only be called after the session was started */ /* Must only be called after the session was started */
assert(m_session); assert(session_);
return m_session->needsUpsideDownDrawing(); return session_->needsUpsideDownDrawing();
} }
/** \} */ /* Public Accessors and Mutators */ /** \} */ /* Public Accessors and Mutators */
@@ -640,38 +637,38 @@ bool GHOST_XrContext::needsUpsideDownDrawing() const
GHOST_TXrOpenXRRuntimeID GHOST_XrContext::getOpenXRRuntimeID() const GHOST_TXrOpenXRRuntimeID GHOST_XrContext::getOpenXRRuntimeID() const
{ {
return m_runtime_id; return runtime_id_;
} }
const GHOST_XrCustomFuncs &GHOST_XrContext::getCustomFuncs() const const GHOST_XrCustomFuncs &GHOST_XrContext::getCustomFuncs() const
{ {
return m_custom_funcs; return custom_funcs_;
} }
GHOST_TXrGraphicsBinding GHOST_XrContext::getGraphicsBindingType() const GHOST_TXrGraphicsBinding GHOST_XrContext::getGraphicsBindingType() const
{ {
return m_gpu_binding_type; return gpu_binding_type_;
} }
XrInstance GHOST_XrContext::getInstance() const XrInstance GHOST_XrContext::getInstance() const
{ {
return m_oxr->instance; return oxr_->instance;
} }
bool GHOST_XrContext::isDebugMode() const bool GHOST_XrContext::isDebugMode() const
{ {
return m_debug; return debug_;
} }
bool GHOST_XrContext::isDebugTimeMode() const bool GHOST_XrContext::isDebugTimeMode() const
{ {
return m_debug_time; return debug_time_;
} }
bool GHOST_XrContext::isExtensionEnabled(const char *ext) const bool GHOST_XrContext::isExtensionEnabled(const char *ext) const
{ {
bool contains = std::find(m_enabled_extensions.begin(), m_enabled_extensions.end(), ext) != bool contains = std::find(enabled_extensions_.begin(), enabled_extensions_.end(), ext) !=
m_enabled_extensions.end(); enabled_extensions_.end();
return contains; return contains;
} }

View File

@@ -97,26 +97,26 @@ class GHOST_XrContext : public GHOST_IXrContext {
static GHOST_XrErrorHandlerFn s_error_handler; static GHOST_XrErrorHandlerFn s_error_handler;
static void *s_error_handler_customdata; static void *s_error_handler_customdata;
std::unique_ptr<OpenXRInstanceData> m_oxr; std::unique_ptr<OpenXRInstanceData> oxr_;
GHOST_TXrOpenXRRuntimeID m_runtime_id = OPENXR_RUNTIME_UNKNOWN; GHOST_TXrOpenXRRuntimeID runtime_id_ = OPENXR_RUNTIME_UNKNOWN;
/* The active GHOST XR Session. Null while no session runs. */ /* The active GHOST XR Session. Null while no session runs. */
std::unique_ptr<class GHOST_XrSession> m_session; std::unique_ptr<class GHOST_XrSession> session_;
/** Active graphics binding type. */ /** Active graphics binding type. */
GHOST_TXrGraphicsBinding m_gpu_binding_type = GHOST_kXrGraphicsUnknown; GHOST_TXrGraphicsBinding gpu_binding_type_ = GHOST_kXrGraphicsUnknown;
/** Names of enabled extensions. */ /** Names of enabled extensions. */
std::vector<const char *> m_enabled_extensions; std::vector<const char *> enabled_extensions_;
/** Names of enabled API-layers. */ /** Names of enabled API-layers. */
std::vector<const char *> m_enabled_layers; std::vector<const char *> enabled_layers_;
GHOST_XrCustomFuncs m_custom_funcs; GHOST_XrCustomFuncs custom_funcs_;
/** Enable debug message prints and OpenXR API validation layers. */ /** Enable debug message prints and OpenXR API validation layers. */
bool m_debug = false; bool debug_ = false;
bool m_debug_time = false; bool debug_time_ = false;
void createOpenXRInstance(const std::vector<GHOST_TXrGraphicsBinding> &graphics_binding_types); void createOpenXRInstance(const std::vector<GHOST_TXrGraphicsBinding> &graphics_binding_types);
void storeInstanceProperties(); void storeInstanceProperties();

View File

@@ -411,33 +411,33 @@ GHOST_XrControllerModel::GHOST_XrControllerModel(XrInstance instance,
{ {
init_controller_model_extension_functions(instance); init_controller_model_extension_functions(instance);
CHECK_XR(xrStringToPath(instance, subaction_path_str, &m_subaction_path), CHECK_XR(xrStringToPath(instance, subaction_path_str, &subaction_path_),
(std::string("Failed to get user path \"") + subaction_path_str + "\".").data()); (std::string("Failed to get user path \"") + subaction_path_str + "\".").data());
} }
GHOST_XrControllerModel::~GHOST_XrControllerModel() GHOST_XrControllerModel::~GHOST_XrControllerModel()
{ {
if (m_load_task.valid()) { if (load_task_.valid()) {
m_load_task.wait(); load_task_.wait();
} }
} }
void GHOST_XrControllerModel::load(XrSession session) void GHOST_XrControllerModel::load(XrSession session)
{ {
if (m_data_loaded || m_load_task.valid()) { if (data_loaded_ || load_task_.valid()) {
return; return;
} }
/* Get model key. */ /* Get model key. */
XrControllerModelKeyStateMSFT key_state{XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT}; XrControllerModelKeyStateMSFT key_state{XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT};
CHECK_XR(g_xrGetControllerModelKeyMSFT(session, m_subaction_path, &key_state), CHECK_XR(g_xrGetControllerModelKeyMSFT(session, subaction_path_, &key_state),
"Failed to get controller model key state."); "Failed to get controller model key state.");
if (key_state.modelKey != XR_NULL_CONTROLLER_MODEL_KEY_MSFT) { if (key_state.modelKey != XR_NULL_CONTROLLER_MODEL_KEY_MSFT) {
m_model_key = key_state.modelKey; model_key_ = key_state.modelKey;
/* Load asynchronously. */ /* Load asynchronously. */
m_load_task = std::async(std::launch::async, load_task_ = std::async(std::launch::async,
[&, session = session]() { return loadControllerModel(session); }); [&, session = session]() { return loadControllerModel(session); });
} }
} }
@@ -445,11 +445,11 @@ void GHOST_XrControllerModel::loadControllerModel(XrSession session)
{ {
/* Load binary buffers. */ /* Load binary buffers. */
uint32_t buf_size = 0; uint32_t buf_size = 0;
CHECK_XR(g_xrLoadControllerModelMSFT(session, m_model_key, 0, &buf_size, nullptr), CHECK_XR(g_xrLoadControllerModelMSFT(session, model_key_, 0, &buf_size, nullptr),
"Failed to get controller model buffer size."); "Failed to get controller model buffer size.");
std::vector<uint8_t> buf((size_t(buf_size))); std::vector<uint8_t> buf((size_t(buf_size)));
CHECK_XR(g_xrLoadControllerModelMSFT(session, m_model_key, buf_size, &buf_size, buf.data()), CHECK_XR(g_xrLoadControllerModelMSFT(session, model_key_, buf_size, &buf_size, buf.data()),
"Failed to load controller model binary buffers."); "Failed to load controller model binary buffers.");
/* Convert to glTF model. */ /* Convert to glTF model. */
@@ -489,17 +489,17 @@ void GHOST_XrControllerModel::loadControllerModel(XrSession session)
/* Get node properties. */ /* Get node properties. */
XrControllerModelPropertiesMSFT model_properties{XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT}; XrControllerModelPropertiesMSFT model_properties{XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT};
model_properties.nodeCapacityInput = 0; model_properties.nodeCapacityInput = 0;
CHECK_XR(g_xrGetControllerModelPropertiesMSFT(session, m_model_key, &model_properties), CHECK_XR(g_xrGetControllerModelPropertiesMSFT(session, model_key_, &model_properties),
"Failed to get controller model node properties count."); "Failed to get controller model node properties count.");
std::vector<XrControllerModelNodePropertiesMSFT> node_properties( std::vector<XrControllerModelNodePropertiesMSFT> node_properties(
model_properties.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT}); model_properties.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT});
model_properties.nodeCapacityInput = uint32_t(node_properties.size()); model_properties.nodeCapacityInput = uint32_t(node_properties.size());
model_properties.nodeProperties = node_properties.data(); model_properties.nodeProperties = node_properties.data();
CHECK_XR(g_xrGetControllerModelPropertiesMSFT(session, m_model_key, &model_properties), CHECK_XR(g_xrGetControllerModelPropertiesMSFT(session, model_key_, &model_properties),
"Failed to get controller model node properties."); "Failed to get controller model node properties.");
m_node_state_indices.resize(node_properties.size(), -1); node_state_indices_.resize(node_properties.size(), -1);
/* Get mesh vertex data. */ /* Get mesh vertex data. */
const tinygltf::Scene &default_scene = gltf_model.scenes.at( const tinygltf::Scene &default_scene = gltf_model.scenes.at(
@@ -516,26 +516,26 @@ void GHOST_XrControllerModel::loadControllerModel(XrSession session)
root_transform, root_transform,
root_name, root_name,
node_properties, node_properties,
m_vertices, vertices_,
m_indices, indices_,
m_components, components_,
m_nodes, nodes_,
m_node_state_indices); node_state_indices_);
} }
m_data_loaded = true; data_loaded_ = true;
} }
void GHOST_XrControllerModel::updateComponents(XrSession session) void GHOST_XrControllerModel::updateComponents(XrSession session)
{ {
if (!m_data_loaded) { if (!data_loaded_) {
return; return;
} }
/* Get node states. */ /* Get node states. */
XrControllerModelStateMSFT model_state{XR_TYPE_CONTROLLER_MODEL_STATE_MSFT}; XrControllerModelStateMSFT model_state{XR_TYPE_CONTROLLER_MODEL_STATE_MSFT};
model_state.nodeCapacityInput = 0; model_state.nodeCapacityInput = 0;
CHECK_XR(g_xrGetControllerModelStateMSFT(session, m_model_key, &model_state), CHECK_XR(g_xrGetControllerModelStateMSFT(session, model_key_, &model_state),
"Failed to get controller model node state count."); "Failed to get controller model node state count.");
const uint32_t count = model_state.nodeCountOutput; const uint32_t count = model_state.nodeCountOutput;
@@ -543,17 +543,17 @@ void GHOST_XrControllerModel::updateComponents(XrSession session)
count, {XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT}); count, {XR_TYPE_CONTROLLER_MODEL_NODE_STATE_MSFT});
model_state.nodeCapacityInput = count; model_state.nodeCapacityInput = count;
model_state.nodeStates = node_states.data(); model_state.nodeStates = node_states.data();
CHECK_XR(g_xrGetControllerModelStateMSFT(session, m_model_key, &model_state), CHECK_XR(g_xrGetControllerModelStateMSFT(session, model_key_, &model_state),
"Failed to get controller model node states."); "Failed to get controller model node states.");
/* Update node local transforms. */ /* Update node local transforms. */
assert(m_node_state_indices.size() == count); assert(node_state_indices_.size() == count);
for (uint32_t state_idx = 0; state_idx < count; ++state_idx) { for (uint32_t state_idx = 0; state_idx < count; ++state_idx) {
const int32_t &node_idx = m_node_state_indices[state_idx]; const int32_t &node_idx = node_state_indices_[state_idx];
if (node_idx >= 0) { if (node_idx >= 0) {
const XrPosef &pose = node_states[state_idx].nodePose; const XrPosef &pose = node_states[state_idx].nodePose;
Eigen::Matrix4f &m = *(Eigen::Matrix4f *)m_nodes[node_idx].local_transform; Eigen::Matrix4f &m = *(Eigen::Matrix4f *)nodes_[node_idx].local_transform;
Eigen::Quaternionf q( Eigen::Quaternionf q(
pose.orientation.w, pose.orientation.x, pose.orientation.y, pose.orientation.z); pose.orientation.w, pose.orientation.x, pose.orientation.y, pose.orientation.z);
m.setIdentity(); m.setIdentity();
@@ -563,16 +563,16 @@ void GHOST_XrControllerModel::updateComponents(XrSession session)
} }
/* Calculate component transforms (in world space). */ /* Calculate component transforms (in world space). */
std::vector<Eigen::Matrix4f> world_transforms(m_nodes.size()); std::vector<Eigen::Matrix4f> world_transforms(nodes_.size());
uint32_t i = 0; uint32_t i = 0;
for (const GHOST_XrControllerModelNode &node : m_nodes) { for (const GHOST_XrControllerModelNode &node : nodes_) {
world_transforms[i] = (node.parent_idx >= 0) ? world_transforms[node.parent_idx] * world_transforms[i] = (node.parent_idx >= 0) ? world_transforms[node.parent_idx] *
*(Eigen::Matrix4f *)node.local_transform : *(Eigen::Matrix4f *)node.local_transform :
*(Eigen::Matrix4f *)node.local_transform; *(Eigen::Matrix4f *)node.local_transform;
if (node.component_idx >= 0) { if (node.component_idx >= 0) {
memcpy(m_components[node.component_idx].transform, memcpy(components_[node.component_idx].transform,
world_transforms[i].data(), world_transforms[i].data(),
sizeof(m_components[node.component_idx].transform)); sizeof(components_[node.component_idx].transform));
} }
++i; ++i;
} }
@@ -580,13 +580,13 @@ void GHOST_XrControllerModel::updateComponents(XrSession session)
void GHOST_XrControllerModel::getData(GHOST_XrControllerModelData &r_data) void GHOST_XrControllerModel::getData(GHOST_XrControllerModelData &r_data)
{ {
if (m_data_loaded) { if (data_loaded_) {
r_data.count_vertices = uint32_t(m_vertices.size()); r_data.count_vertices = uint32_t(vertices_.size());
r_data.vertices = m_vertices.data(); r_data.vertices = vertices_.data();
r_data.count_indices = uint32_t(m_indices.size()); r_data.count_indices = uint32_t(indices_.size());
r_data.indices = m_indices.data(); r_data.indices = indices_.data();
r_data.count_components = uint32_t(m_components.size()); r_data.count_components = uint32_t(components_.size());
r_data.components = m_components.data(); r_data.components = components_.data();
} }
else { else {
r_data.count_vertices = 0; r_data.count_vertices = 0;

View File

@@ -30,18 +30,18 @@ class GHOST_XrControllerModel {
void getData(GHOST_XrControllerModelData &r_data); void getData(GHOST_XrControllerModelData &r_data);
private: private:
XrPath m_subaction_path = XR_NULL_PATH; XrPath subaction_path_ = XR_NULL_PATH;
XrControllerModelKeyMSFT m_model_key = XR_NULL_CONTROLLER_MODEL_KEY_MSFT; XrControllerModelKeyMSFT model_key_ = XR_NULL_CONTROLLER_MODEL_KEY_MSFT;
std::future<void> m_load_task; std::future<void> load_task_;
std::atomic<bool> m_data_loaded = false; std::atomic<bool> data_loaded_ = false;
std::vector<GHOST_XrControllerModelVertex> m_vertices; std::vector<GHOST_XrControllerModelVertex> vertices_;
std::vector<uint32_t> m_indices; std::vector<uint32_t> indices_;
std::vector<GHOST_XrControllerModelComponent> m_components; std::vector<GHOST_XrControllerModelComponent> components_;
std::vector<GHOST_XrControllerModelNode> m_nodes; std::vector<GHOST_XrControllerModelNode> nodes_;
/** Maps node states to nodes. */ /** Maps node states to nodes. */
std::vector<int32_t> m_node_state_indices; std::vector<int32_t> node_state_indices_;
void loadControllerModel(XrSession session); void loadControllerModel(XrSession session);
}; };

View File

@@ -15,17 +15,16 @@ class GHOST_XrException : public std::exception {
friend class GHOST_XrContext; friend class GHOST_XrContext;
public: public:
GHOST_XrException(const char *msg, int result = 0) GHOST_XrException(const char *msg, int result = 0) : std::exception(), msg_(msg), result_(result)
: std::exception(), m_msg(msg), m_result(result)
{ {
} }
const char *what() const noexcept override const char *what() const noexcept override
{ {
return m_msg.data(); return msg_.data();
} }
private: private:
std::string m_msg; std::string msg_;
int m_result; int result_;
}; };

View File

@@ -62,8 +62,8 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
public: public:
~GHOST_XrGraphicsBindingOpenGL() ~GHOST_XrGraphicsBindingOpenGL()
{ {
if (m_fbo != 0) { if (fbo_ != 0) {
glDeleteFramebuffers(1, &m_fbo); glDeleteFramebuffers(1, &fbo_);
} }
} }
@@ -75,19 +75,19 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
int gl_major_version, gl_minor_version; int gl_major_version, gl_minor_version;
# if defined(WIN32) # if defined(WIN32)
GHOST_ContextWGL &ctx_gl = static_cast<GHOST_ContextWGL &>(ghost_ctx); GHOST_ContextWGL &ctx_gl = static_cast<GHOST_ContextWGL &>(ghost_ctx);
gl_major_version = ctx_gl.m_contextMajorVersion; gl_major_version = ctx_gl.context_major_version_;
gl_minor_version = ctx_gl.m_contextMinorVersion; gl_minor_version = ctx_gl.context_minor_version_;
# elif defined(WITH_GHOST_X11) || defined(WITH_GHOST_WAYLAND) # elif defined(WITH_GHOST_X11) || defined(WITH_GHOST_WAYLAND)
if (dynamic_cast<GHOST_ContextEGL *>(&ghost_ctx)) { if (dynamic_cast<GHOST_ContextEGL *>(&ghost_ctx)) {
GHOST_ContextEGL &ctx_gl = static_cast<GHOST_ContextEGL &>(ghost_ctx); GHOST_ContextEGL &ctx_gl = static_cast<GHOST_ContextEGL &>(ghost_ctx);
gl_major_version = ctx_gl.m_contextMajorVersion; gl_major_version = ctx_gl.context_major_version_;
gl_minor_version = ctx_gl.m_contextMinorVersion; gl_minor_version = ctx_gl.context_minor_version_;
} }
# if defined(WITH_GHOST_X11) # if defined(WITH_GHOST_X11)
else { else {
GHOST_ContextGLX &ctx_gl = static_cast<GHOST_ContextGLX &>(ghost_ctx); GHOST_ContextGLX &ctx_gl = static_cast<GHOST_ContextGLX &>(ghost_ctx);
gl_major_version = ctx_gl.m_contextMajorVersion; gl_major_version = ctx_gl.context_major_version_;
gl_minor_version = ctx_gl.m_contextMinorVersion; gl_minor_version = ctx_gl.context_minor_version_;
} }
# endif # endif
# endif # endif
@@ -146,7 +146,7 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
GHOST_ContextEGL &ctx_egl = static_cast<GHOST_ContextEGL &>(ghost_ctx); GHOST_ContextEGL &ctx_egl = static_cast<GHOST_ContextEGL &>(ghost_ctx);
const bool is_wayland = ( const bool is_wayland = (
# if defined(WITH_GHOST_WAYLAND) # if defined(WITH_GHOST_WAYLAND)
dynamic_cast<const GHOST_SystemWayland *const>(ctx_egl.m_system) != nullptr dynamic_cast<const GHOST_SystemWayland *const>(ctx_egl.system_) != nullptr
# else # else
false false
# endif # endif
@@ -156,7 +156,7 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
# if defined(WITH_GHOST_WAYLAND) # if defined(WITH_GHOST_WAYLAND)
/* #GHOST_SystemWayland */ /* #GHOST_SystemWayland */
oxr_binding.wl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR; oxr_binding.wl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR;
oxr_binding.wl.display = (wl_display *)ctx_egl.m_nativeDisplay; oxr_binding.wl.display = (wl_display *)ctx_egl.native_display_;
# else # else
GHOST_ASSERT(false, "Unexpected State: logical error, unreachable!"); GHOST_ASSERT(false, "Unexpected State: logical error, unreachable!");
# endif /* !WITH_GHOST_WAYLAND */ # endif /* !WITH_GHOST_WAYLAND */
@@ -183,13 +183,13 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
else { /* `!is_ctx_egl` */ else { /* `!is_ctx_egl` */
# if defined(WITH_GHOST_X11) # if defined(WITH_GHOST_X11)
GHOST_ContextGLX &ctx_glx = static_cast<GHOST_ContextGLX &>(ghost_ctx); GHOST_ContextGLX &ctx_glx = static_cast<GHOST_ContextGLX &>(ghost_ctx);
XVisualInfo *visual_info = glXGetVisualFromFBConfig(ctx_glx.m_display, ctx_glx.m_fbconfig); XVisualInfo *visual_info = glXGetVisualFromFBConfig(ctx_glx.display_, ctx_glx.fbconfig_);
oxr_binding.glx.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR; oxr_binding.glx.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR;
oxr_binding.glx.xDisplay = ctx_glx.m_display; oxr_binding.glx.xDisplay = ctx_glx.display_;
oxr_binding.glx.glxFBConfig = ctx_glx.m_fbconfig; oxr_binding.glx.glxFBConfig = ctx_glx.fbconfig_;
oxr_binding.glx.glxDrawable = ctx_glx.m_window; oxr_binding.glx.glxDrawable = ctx_glx.window_;
oxr_binding.glx.glxContext = ctx_glx.m_context; oxr_binding.glx.glxContext = ctx_glx.context_;
oxr_binding.glx.visualid = visual_info->visualid; oxr_binding.glx.visualid = visual_info->visualid;
XFree(visual_info); XFree(visual_info);
@@ -201,12 +201,12 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
GHOST_ContextWGL &ctx_wgl = static_cast<GHOST_ContextWGL &>(ghost_ctx); GHOST_ContextWGL &ctx_wgl = static_cast<GHOST_ContextWGL &>(ghost_ctx);
oxr_binding.wgl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR; oxr_binding.wgl.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR;
oxr_binding.wgl.hDC = ctx_wgl.m_hDC; oxr_binding.wgl.hDC = ctx_wgl.h_DC_;
oxr_binding.wgl.hGLRC = ctx_wgl.m_hGLRC; oxr_binding.wgl.hGLRC = ctx_wgl.h_GLRC_;
# endif /* WIN32 */ # endif /* WIN32 */
/* Generate a frame-buffer to use for blitting into the texture. */ /* Generate a frame-buffer to use for blitting into the texture. */
glGenFramebuffers(1, &m_fbo); glGenFramebuffers(1, &fbo_);
} }
std::optional<int64_t> chooseSwapchainFormat(const std::vector<int64_t> &runtime_formats, std::optional<int64_t> chooseSwapchainFormat(const std::vector<int64_t> &runtime_formats,
@@ -269,7 +269,7 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
} }
/* Keep alive. */ /* Keep alive. */
m_image_cache.push_back(std::move(ogl_images)); image_cache_.push_back(std::move(ogl_images));
return base_images; return base_images;
} }
@@ -281,7 +281,7 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
XrSwapchainImageOpenGLKHR &ogl_swapchain_image = reinterpret_cast<XrSwapchainImageOpenGLKHR &>( XrSwapchainImageOpenGLKHR &ogl_swapchain_image = reinterpret_cast<XrSwapchainImageOpenGLKHR &>(
swapchain_image); swapchain_image);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_);
glFramebufferTexture2D( glFramebufferTexture2D(
GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ogl_swapchain_image.image, 0); GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ogl_swapchain_image.image, 0);
@@ -307,8 +307,8 @@ class GHOST_XrGraphicsBindingOpenGL : public GHOST_IXrGraphicsBinding {
} }
private: private:
std::list<std::vector<XrSwapchainImageOpenGLKHR>> m_image_cache; std::list<std::vector<XrSwapchainImageOpenGLKHR>> image_cache_;
GLuint m_fbo = 0; GLuint fbo_ = 0;
}; };
#endif #endif

View File

@@ -68,12 +68,12 @@ static std::optional<int64_t> choose_swapchain_format_from_candidates(
GHOST_XrGraphicsBindingD3D::GHOST_XrGraphicsBindingD3D() : GHOST_IXrGraphicsBinding() GHOST_XrGraphicsBindingD3D::GHOST_XrGraphicsBindingD3D() : GHOST_IXrGraphicsBinding()
{ {
m_ghost_d3d_ctx = GHOST_SystemWin32::createOffscreenContextD3D(); ghost_d3d_ctx_ = GHOST_SystemWin32::createOffscreenContextD3D();
} }
GHOST_XrGraphicsBindingD3D::~GHOST_XrGraphicsBindingD3D() GHOST_XrGraphicsBindingD3D::~GHOST_XrGraphicsBindingD3D()
{ {
if (m_ghost_d3d_ctx) { if (ghost_d3d_ctx_) {
GHOST_SystemWin32::disposeContextD3D(m_ghost_d3d_ctx); GHOST_SystemWin32::disposeContextD3D(ghost_d3d_ctx_);
} }
} }
@@ -115,7 +115,7 @@ bool GHOST_XrGraphicsBindingD3D::checkVersionRequirements(
*r_requirement_info = strstream.str(); *r_requirement_info = strstream.str();
} }
return m_ghost_d3d_ctx->m_device->GetFeatureLevel() >= gpu_requirements.minFeatureLevel; return ghost_d3d_ctx_->device_->GetFeatureLevel() >= gpu_requirements.minFeatureLevel;
} }
void GHOST_XrGraphicsBindingD3D::initFromGhostContext( void GHOST_XrGraphicsBindingD3D::initFromGhostContext(
@@ -125,7 +125,7 @@ void GHOST_XrGraphicsBindingD3D::initFromGhostContext(
) )
{ {
oxr_binding.d3d11.type = XR_TYPE_GRAPHICS_BINDING_D3D11_KHR; oxr_binding.d3d11.type = XR_TYPE_GRAPHICS_BINDING_D3D11_KHR;
oxr_binding.d3d11.device = m_ghost_d3d_ctx->m_device; oxr_binding.d3d11.device = ghost_d3d_ctx_->device_;
} }
std::optional<int64_t> GHOST_XrGraphicsBindingD3D::chooseSwapchainFormat( std::optional<int64_t> GHOST_XrGraphicsBindingD3D::chooseSwapchainFormat(
@@ -190,14 +190,14 @@ std::vector<XrSwapchainImageBaseHeader *> GHOST_XrGraphicsBindingD3D::createSwap
} }
/* Keep alive. */ /* Keep alive. */
m_image_cache.push_back(std::move(d3d_images)); image_cache_.push_back(std::move(d3d_images));
return base_images; return base_images;
} }
bool GHOST_XrGraphicsBindingD3D::needsUpsideDownDrawing(GHOST_Context &) const bool GHOST_XrGraphicsBindingD3D::needsUpsideDownDrawing(GHOST_Context &) const
{ {
return m_ghost_d3d_ctx->isUpsideDown(); return ghost_d3d_ctx_->isUpsideDown();
} }
/* \} */ /* \} */
@@ -208,15 +208,15 @@ bool GHOST_XrGraphicsBindingD3D::needsUpsideDownDrawing(GHOST_Context &) const
GHOST_XrGraphicsBindingOpenGLD3D::GHOST_XrGraphicsBindingOpenGLD3D(GHOST_Context &ghost_ctx) GHOST_XrGraphicsBindingOpenGLD3D::GHOST_XrGraphicsBindingOpenGLD3D(GHOST_Context &ghost_ctx)
: GHOST_XrGraphicsBindingD3D(), m_ghost_wgl_ctx(static_cast<GHOST_ContextWGL &>(ghost_ctx)) : GHOST_XrGraphicsBindingD3D(), ghost_wgl_ctx_(static_cast<GHOST_ContextWGL &>(ghost_ctx))
{ {
} }
GHOST_XrGraphicsBindingOpenGLD3D::~GHOST_XrGraphicsBindingOpenGLD3D() GHOST_XrGraphicsBindingOpenGLD3D::~GHOST_XrGraphicsBindingOpenGLD3D()
{ {
if (m_shared_resource) { if (shared_resource_) {
m_ghost_d3d_ctx->disposeSharedOpenGLResource(m_shared_resource); ghost_d3d_ctx_->disposeSharedOpenGLResource(shared_resource_);
m_shared_resource = nullptr; shared_resource_ = nullptr;
} }
} }
@@ -237,26 +237,26 @@ void GHOST_XrGraphicsBindingOpenGLD3D::submitToSwapchainImage(
CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(D3D11_RTV_DIMENSION_TEXTURE2D, CD3D11_RENDER_TARGET_VIEW_DESC rtv_desc(D3D11_RTV_DIMENSION_TEXTURE2D,
DXGI_FORMAT_R8G8B8A8_UNORM); DXGI_FORMAT_R8G8B8A8_UNORM);
m_ghost_ctx->m_device->CreateRenderTargetView(d3d_swapchain_image.texture, &rtv_desc, &rtv); ghost_ctx_->device_->CreateRenderTargetView(d3d_swapchain_image.texture, &rtv_desc, &rtv);
if (!m_shared_resource) { if (!shared_resource_) {
DXGI_FORMAT format; DXGI_FORMAT format;
ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format); ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format);
m_shared_resource = m_ghost_ctx->createSharedOpenGLResource( shared_resource_ = ghost_ctx_->createSharedOpenGLResource(
draw_info.width, draw_info.height, format, rtv); draw_info.width, draw_info.height, format, rtv);
} }
m_ghost_ctx->blitFromOpenGLContext(m_shared_resource, draw_info.width, draw_info.height); ghost_ctx_->blitFromOpenGLContext(shared_resource_, draw_info.width, draw_info.height);
#else #else
if (!m_shared_resource) { if (!shared_resource_) {
DXGI_FORMAT format; DXGI_FORMAT format;
ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format); ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format);
m_shared_resource = m_ghost_d3d_ctx->createSharedOpenGLResource( shared_resource_ = ghost_d3d_ctx_->createSharedOpenGLResource(
draw_info.width, draw_info.height, format); draw_info.width, draw_info.height, format);
} }
m_ghost_d3d_ctx->blitFromOpenGLContext(m_shared_resource, draw_info.width, draw_info.height); ghost_d3d_ctx_->blitFromOpenGLContext(shared_resource_, draw_info.width, draw_info.height);
m_ghost_d3d_ctx->m_device_ctx->OMSetRenderTargets(0, nullptr, nullptr); ghost_d3d_ctx_->device_ctx_->OMSetRenderTargets(0, nullptr, nullptr);
m_ghost_d3d_ctx->m_device_ctx->CopyResource( ghost_d3d_ctx_->device_ctx_->CopyResource(d3d_swapchain_image.texture,
d3d_swapchain_image.texture, m_ghost_d3d_ctx->getSharedTexture2D(m_shared_resource)); ghost_d3d_ctx_->getSharedTexture2D(shared_resource_));
#endif #endif
} }
@@ -270,7 +270,7 @@ void GHOST_XrGraphicsBindingOpenGLD3D::submitToSwapchainImage(
GHOST_XrGraphicsBindingVulkanD3D::GHOST_XrGraphicsBindingVulkanD3D(GHOST_Context &ghost_ctx) GHOST_XrGraphicsBindingVulkanD3D::GHOST_XrGraphicsBindingVulkanD3D(GHOST_Context &ghost_ctx)
: GHOST_XrGraphicsBindingD3D(), m_ghost_ctx(static_cast<GHOST_ContextVK &>(ghost_ctx)) : GHOST_XrGraphicsBindingD3D(), ghost_ctx_(static_cast<GHOST_ContextVK &>(ghost_ctx))
{ {
} }
@@ -289,14 +289,14 @@ void GHOST_XrGraphicsBindingVulkanD3D::submitToSwapchainImage(
component_size = 4 * sizeof(uint16_t); component_size = 4 * sizeof(uint16_t);
} }
ID3D11Device *d3d_device = m_ghost_d3d_ctx->m_device; ID3D11Device *d3d_device = ghost_d3d_ctx_->device_;
ID3D11DeviceContext *d3d_device_ctx = m_ghost_d3d_ctx->m_device_ctx; ID3D11DeviceContext *d3d_device_ctx = ghost_d3d_ctx_->device_ctx_;
DXGI_FORMAT format; DXGI_FORMAT format;
ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format); ghost_format_to_dx_format(draw_info.swapchain_format, draw_info.expects_srgb_buffer, format);
/* Acquire frame buffer image. */ /* Acquire frame buffer image. */
GHOST_VulkanOpenXRData openxr_data = {GHOST_kVulkanXRModeCPU}; GHOST_VulkanOpenXRData openxr_data = {GHOST_kVulkanXRModeCPU};
m_ghost_ctx.openxr_acquire_framebuffer_image_callback_(&openxr_data); ghost_ctx_.openxr_acquire_framebuffer_image_callback_(&openxr_data);
/* Upload the data to a D3D Texture */ /* Upload the data to a D3D Texture */
D3D11_TEXTURE2D_DESC desc; D3D11_TEXTURE2D_DESC desc;
@@ -328,7 +328,7 @@ void GHOST_XrGraphicsBindingVulkanD3D::submitToSwapchainImage(
texture->Release(); texture->Release();
/* Release frame buffer image. */ /* Release frame buffer image. */
m_ghost_ctx.openxr_release_framebuffer_image_callback_(&openxr_data); ghost_ctx_.openxr_release_framebuffer_image_callback_(&openxr_data);
} }
/* \} */ /* \} */

View File

@@ -51,9 +51,9 @@ class GHOST_XrGraphicsBindingD3D : public GHOST_IXrGraphicsBinding {
protected: protected:
/** Secondary DirectX 11 context used by OpenXR. */ /** Secondary DirectX 11 context used by OpenXR. */
GHOST_ContextD3D *m_ghost_d3d_ctx = nullptr; GHOST_ContextD3D *ghost_d3d_ctx_ = nullptr;
std::list<std::vector<XrSwapchainImageD3D11KHR>> m_image_cache; std::list<std::vector<XrSwapchainImageD3D11KHR>> image_cache_;
}; };
/** /**
@@ -71,9 +71,9 @@ class GHOST_XrGraphicsBindingOpenGLD3D : public GHOST_XrGraphicsBindingD3D {
private: private:
/** Primary OpenGL context for Blender to use for drawing. */ /** Primary OpenGL context for Blender to use for drawing. */
GHOST_ContextWGL &m_ghost_wgl_ctx; GHOST_ContextWGL &ghost_wgl_ctx_;
/** Handle to shared resource object. */ /** Handle to shared resource object. */
GHOST_SharedOpenGLResource *m_shared_resource = nullptr; GHOST_SharedOpenGLResource *shared_resource_ = nullptr;
}; };
#ifdef WITH_VULKAN_BACKEND #ifdef WITH_VULKAN_BACKEND
@@ -90,6 +90,6 @@ class GHOST_XrGraphicsBindingVulkanD3D : public GHOST_XrGraphicsBindingD3D {
private: private:
/** Primary Vulkan context for Blender to use for drawing. */ /** Primary Vulkan context for Blender to use for drawing. */
GHOST_ContextVK &m_ghost_ctx; GHOST_ContextVK &ghost_ctx_;
}; };
#endif #endif

View File

@@ -33,7 +33,7 @@ PFN_xrCreateVulkanDeviceKHR GHOST_XrGraphicsBindingVulkan::s_xrCreateVulkanDevic
* \{ */ * \{ */
GHOST_XrGraphicsBindingVulkan::GHOST_XrGraphicsBindingVulkan(GHOST_Context &ghost_ctx) GHOST_XrGraphicsBindingVulkan::GHOST_XrGraphicsBindingVulkan(GHOST_Context &ghost_ctx)
: GHOST_IXrGraphicsBinding(), m_ghost_ctx(static_cast<GHOST_ContextVK &>(ghost_ctx)) : GHOST_IXrGraphicsBinding(), ghost_ctx_(static_cast<GHOST_ContextVK &>(ghost_ctx))
{ {
} }
@@ -46,49 +46,49 @@ GHOST_XrGraphicsBindingVulkan::GHOST_XrGraphicsBindingVulkan(GHOST_Context &ghos
GHOST_XrGraphicsBindingVulkan::~GHOST_XrGraphicsBindingVulkan() GHOST_XrGraphicsBindingVulkan::~GHOST_XrGraphicsBindingVulkan()
{ {
/* Destroy buffer */ /* Destroy buffer */
if (m_vk_buffer != VK_NULL_HANDLE) { if (vk_buffer_ != VK_NULL_HANDLE) {
vmaUnmapMemory(m_vma_allocator, m_vk_buffer_allocation); vmaUnmapMemory(vma_allocator_, vk_buffer_allocation_);
vmaDestroyBuffer(m_vma_allocator, m_vk_buffer, m_vk_buffer_allocation); vmaDestroyBuffer(vma_allocator_, vk_buffer_, vk_buffer_allocation_);
m_vk_buffer = VK_NULL_HANDLE; vk_buffer_ = VK_NULL_HANDLE;
m_vk_buffer_allocation = VK_NULL_HANDLE; vk_buffer_allocation_ = VK_NULL_HANDLE;
} }
for (ImportedMemory &imported_memory : m_imported_memory) { for (ImportedMemory &imported_memory : imported_memory_) {
vkDestroyImage(m_vk_device, imported_memory.vk_image_xr, nullptr); vkDestroyImage(vk_device_, imported_memory.vk_image_xr, nullptr);
vkFreeMemory(m_vk_device, imported_memory.vk_device_memory_xr, nullptr); vkFreeMemory(vk_device_, imported_memory.vk_device_memory_xr, nullptr);
} }
m_imported_memory.clear(); imported_memory_.clear();
/* Destroy VMA */ /* Destroy VMA */
if (m_vma_allocator != VK_NULL_HANDLE) { if (vma_allocator_ != VK_NULL_HANDLE) {
vmaDestroyAllocator(m_vma_allocator); vmaDestroyAllocator(vma_allocator_);
m_vma_allocator = VK_NULL_HANDLE; vma_allocator_ = VK_NULL_HANDLE;
} }
/* Destroy command buffer */ /* Destroy command buffer */
if (m_vk_command_buffer != VK_NULL_HANDLE) { if (vk_command_buffer_ != VK_NULL_HANDLE) {
vkFreeCommandBuffers(m_vk_device, m_vk_command_pool, 1, &m_vk_command_buffer); vkFreeCommandBuffers(vk_device_, vk_command_pool_, 1, &vk_command_buffer_);
m_vk_command_buffer = VK_NULL_HANDLE; vk_command_buffer_ = VK_NULL_HANDLE;
} }
/* Destroy command pool */ /* Destroy command pool */
if (m_vk_command_pool != VK_NULL_HANDLE) { if (vk_command_pool_ != VK_NULL_HANDLE) {
vkDestroyCommandPool(m_vk_device, m_vk_command_pool, nullptr); vkDestroyCommandPool(vk_device_, vk_command_pool_, nullptr);
m_vk_command_pool = VK_NULL_HANDLE; vk_command_pool_ = VK_NULL_HANDLE;
} }
m_vk_queue = VK_NULL_HANDLE; vk_queue_ = VK_NULL_HANDLE;
/* Destroy device */ /* Destroy device */
if (m_vk_device != VK_NULL_HANDLE) { if (vk_device_ != VK_NULL_HANDLE) {
vkDestroyDevice(m_vk_device, nullptr); vkDestroyDevice(vk_device_, nullptr);
m_vk_device = VK_NULL_HANDLE; vk_device_ = VK_NULL_HANDLE;
} }
/* Destroy instance */ /* Destroy instance */
if (m_vk_instance != VK_NULL_HANDLE) { if (vk_instance_ != VK_NULL_HANDLE) {
vkDestroyInstance(m_vk_instance, nullptr); vkDestroyInstance(vk_instance_, nullptr);
m_vk_instance = VK_NULL_HANDLE; vk_instance_ = VK_NULL_HANDLE;
} }
s_xrGetVulkanGraphicsRequirements2KHR_fn = nullptr; s_xrGetVulkanGraphicsRequirements2KHR_fn = nullptr;
@@ -133,7 +133,7 @@ bool GHOST_XrGraphicsBindingVulkan::checkVersionRequirements(GHOST_Context &ghos
/* Check if the Vulkan API instance version is supported. */ /* Check if the Vulkan API instance version is supported. */
GHOST_ContextVK &context_vk = static_cast<GHOST_ContextVK &>(ghost_ctx); GHOST_ContextVK &context_vk = static_cast<GHOST_ContextVK &>(ghost_ctx);
const XrVersion vk_version = XR_MAKE_VERSION( const XrVersion vk_version = XR_MAKE_VERSION(
context_vk.m_context_major_version, context_vk.m_context_minor_version, 0); context_vk.context_major_version_, context_vk.context_minor_version_, 0);
if (vk_version < xr_graphics_requirements.minApiVersionSupported || if (vk_version < xr_graphics_requirements.minApiVersionSupported ||
vk_version > xr_graphics_requirements.maxApiVersionSupported) vk_version > xr_graphics_requirements.maxApiVersionSupported)
{ {
@@ -181,28 +181,27 @@ void GHOST_XrGraphicsBindingVulkan::initFromGhostContext(GHOST_Context & /*ghost
nullptr}; nullptr};
VkResult vk_result; VkResult vk_result;
CHECK_XR(s_xrCreateVulkanInstanceKHR_fn( CHECK_XR(s_xrCreateVulkanInstanceKHR_fn(
instance, &xr_instance_create_info, &m_vk_instance, &vk_result), instance, &xr_instance_create_info, &vk_instance_, &vk_result),
"Unable to create an OpenXR compatible Vulkan instance."); "Unable to create an OpenXR compatible Vulkan instance.");
/* Physical device selection */ /* Physical device selection */
XrVulkanGraphicsDeviceGetInfoKHR xr_device_get_info = { XrVulkanGraphicsDeviceGetInfoKHR xr_device_get_info = {
XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR, nullptr, system_id, m_vk_instance}; XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR, nullptr, system_id, vk_instance_};
CHECK_XR( CHECK_XR(s_xrGetVulkanGraphicsDevice2KHR_fn(instance, &xr_device_get_info, &vk_physical_device_),
s_xrGetVulkanGraphicsDevice2KHR_fn(instance, &xr_device_get_info, &m_vk_physical_device), "Unable to create an OpenXR compatible Vulkan physical device.");
"Unable to create an OpenXR compatible Vulkan physical device.");
/* Queue family */ /* Queue family */
uint32_t vk_queue_family_count = 0; uint32_t vk_queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(m_vk_physical_device, &vk_queue_family_count, nullptr); vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device_, &vk_queue_family_count, nullptr);
std::vector<VkQueueFamilyProperties> vk_queue_families(vk_queue_family_count); std::vector<VkQueueFamilyProperties> vk_queue_families(vk_queue_family_count);
m_graphics_queue_family = 0; graphics_queue_family_ = 0;
vkGetPhysicalDeviceQueueFamilyProperties( vkGetPhysicalDeviceQueueFamilyProperties(
m_vk_physical_device, &vk_queue_family_count, vk_queue_families.data()); vk_physical_device_, &vk_queue_family_count, vk_queue_families.data());
for (uint32_t i = 0; i < vk_queue_family_count; i++) { for (uint32_t i = 0; i < vk_queue_family_count; i++) {
if (vk_queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT && if (vk_queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT &&
vk_queue_families[i].queueFlags & VK_QUEUE_TRANSFER_BIT) vk_queue_families[i].queueFlags & VK_QUEUE_TRANSFER_BIT)
{ {
m_graphics_queue_family = i; graphics_queue_family_ = i;
break; break;
} }
} }
@@ -212,7 +211,7 @@ void GHOST_XrGraphicsBindingVulkan::initFromGhostContext(GHOST_Context & /*ghost
VkDeviceQueueCreateInfo vk_queue_create_info = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, VkDeviceQueueCreateInfo vk_queue_create_info = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr, nullptr,
0, 0,
m_graphics_queue_family, graphics_queue_family_,
1, 1,
&queue_priority}; &queue_priority};
VkDeviceCreateInfo vk_device_create_info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, VkDeviceCreateInfo vk_device_create_info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
@@ -229,60 +228,59 @@ void GHOST_XrGraphicsBindingVulkan::initFromGhostContext(GHOST_Context & /*ghost
system_id, system_id,
0, 0,
vkGetInstanceProcAddr, vkGetInstanceProcAddr,
m_vk_physical_device, vk_physical_device_,
&vk_device_create_info, &vk_device_create_info,
nullptr}; nullptr};
CHECK_XR( CHECK_XR(s_xrCreateVulkanDeviceKHR_fn(instance, &xr_device_create_info, &vk_device_, &vk_result),
s_xrCreateVulkanDeviceKHR_fn(instance, &xr_device_create_info, &m_vk_device, &vk_result), "Unable to create an OpenXR compatible Vulkan logical device.");
"Unable to create an OpenXR compatible Vulkan logical device.");
vkGetDeviceQueue(m_vk_device, m_graphics_queue_family, 0, &m_vk_queue); vkGetDeviceQueue(vk_device_, graphics_queue_family_, 0, &vk_queue_);
/* Command buffer pool */ /* Command buffer pool */
VkCommandPoolCreateInfo vk_command_pool_create_info = { VkCommandPoolCreateInfo vk_command_pool_create_info = {
VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
nullptr, nullptr,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
m_graphics_queue_family}; graphics_queue_family_};
vkCreateCommandPool(m_vk_device, &vk_command_pool_create_info, nullptr, &m_vk_command_pool); vkCreateCommandPool(vk_device_, &vk_command_pool_create_info, nullptr, &vk_command_pool_);
/* Command buffer */ /* Command buffer */
VkCommandBufferAllocateInfo vk_command_buffer_allocate_info = { VkCommandBufferAllocateInfo vk_command_buffer_allocate_info = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
nullptr, nullptr,
m_vk_command_pool, vk_command_pool_,
VK_COMMAND_BUFFER_LEVEL_PRIMARY, VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1}; 1};
vkAllocateCommandBuffers(m_vk_device, &vk_command_buffer_allocate_info, &m_vk_command_buffer); vkAllocateCommandBuffers(vk_device_, &vk_command_buffer_allocate_info, &vk_command_buffer_);
/* Select the best data transfer mode based on the OpenXR device and ContextVK. */ /* Select the best data transfer mode based on the OpenXR device and ContextVK. */
m_data_transfer_mode = choseDataTransferMode(); data_transfer_mode_ = choseDataTransferMode();
if (m_data_transfer_mode == GHOST_kVulkanXRModeCPU) { if (data_transfer_mode_ == GHOST_kVulkanXRModeCPU) {
/* VMA */ /* VMA */
VmaAllocatorCreateInfo allocator_create_info = {}; VmaAllocatorCreateInfo allocator_create_info = {};
allocator_create_info.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; allocator_create_info.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
allocator_create_info.vulkanApiVersion = VK_API_VERSION_1_2; allocator_create_info.vulkanApiVersion = VK_API_VERSION_1_2;
allocator_create_info.physicalDevice = m_vk_physical_device; allocator_create_info.physicalDevice = vk_physical_device_;
allocator_create_info.device = m_vk_device; allocator_create_info.device = vk_device_;
allocator_create_info.instance = m_vk_instance; allocator_create_info.instance = vk_instance_;
vmaCreateAllocator(&allocator_create_info, &m_vma_allocator); vmaCreateAllocator(&allocator_create_info, &vma_allocator_);
} }
/* Update the binding struct */ /* Update the binding struct */
oxr_binding.vk.type = XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR; oxr_binding.vk.type = XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR;
oxr_binding.vk.next = nullptr; oxr_binding.vk.next = nullptr;
oxr_binding.vk.instance = m_vk_instance; oxr_binding.vk.instance = vk_instance_;
oxr_binding.vk.physicalDevice = m_vk_physical_device; oxr_binding.vk.physicalDevice = vk_physical_device_;
oxr_binding.vk.device = m_vk_device; oxr_binding.vk.device = vk_device_;
oxr_binding.vk.queueFamilyIndex = m_graphics_queue_family; oxr_binding.vk.queueFamilyIndex = graphics_queue_family_;
oxr_binding.vk.queueIndex = 0; oxr_binding.vk.queueIndex = 0;
} }
GHOST_TVulkanXRModes GHOST_XrGraphicsBindingVulkan::choseDataTransferMode() GHOST_TVulkanXRModes GHOST_XrGraphicsBindingVulkan::choseDataTransferMode()
{ {
GHOST_VulkanHandles vulkan_handles; GHOST_VulkanHandles vulkan_handles;
m_ghost_ctx.getVulkanHandles(vulkan_handles); ghost_ctx_.getVulkanHandles(vulkan_handles);
/* Retrieve the Context physical device properties. */ /* Retrieve the Context physical device properties. */
VkPhysicalDeviceVulkan11Properties vk_physical_device_vulkan11_properties = { VkPhysicalDeviceVulkan11Properties vk_physical_device_vulkan11_properties = {
@@ -296,7 +294,7 @@ GHOST_TVulkanXRModes GHOST_XrGraphicsBindingVulkan::choseDataTransferMode()
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES};
VkPhysicalDeviceProperties2 xr_physical_device_properties = { VkPhysicalDeviceProperties2 xr_physical_device_properties = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &xr_physical_device_vulkan11_properties}; VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &xr_physical_device_vulkan11_properties};
vkGetPhysicalDeviceProperties2(m_vk_physical_device, &xr_physical_device_properties); vkGetPhysicalDeviceProperties2(vk_physical_device_, &xr_physical_device_properties);
/* When the physical device properties match between the Vulkan device and the Xr devices we /* When the physical device properties match between the Vulkan device and the Xr devices we
* assume that they are the same physical device in the machine and we can use shared memory. * assume that they are the same physical device in the machine and we can use shared memory.
@@ -418,7 +416,7 @@ std::vector<XrSwapchainImageBaseHeader *> GHOST_XrGraphicsBindingVulkan::createS
for (XrSwapchainImageVulkan2KHR &image : vulkan_images) { for (XrSwapchainImageVulkan2KHR &image : vulkan_images) {
base_images.push_back(reinterpret_cast<XrSwapchainImageBaseHeader *>(&image)); base_images.push_back(reinterpret_cast<XrSwapchainImageBaseHeader *>(&image));
} }
m_image_cache.push_back(std::move(vulkan_images)); image_cache_.push_back(std::move(vulkan_images));
return base_images; return base_images;
} }
@@ -430,7 +428,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImage(
XrSwapchainImageVulkan2KHR &vulkan_image = *reinterpret_cast<XrSwapchainImageVulkan2KHR *>( XrSwapchainImageVulkan2KHR &vulkan_image = *reinterpret_cast<XrSwapchainImageVulkan2KHR *>(
&swapchain_image); &swapchain_image);
switch (m_data_transfer_mode) { switch (data_transfer_mode_) {
case GHOST_kVulkanXRModeFD: case GHOST_kVulkanXRModeFD:
case GHOST_kVulkanXRModeWin32: case GHOST_kVulkanXRModeWin32:
submitToSwapchainImageGpu(vulkan_image, draw_info); submitToSwapchainImageGpu(vulkan_image, draw_info);
@@ -452,7 +450,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageCpu(
{ {
/* Acquire frame buffer image. */ /* Acquire frame buffer image. */
GHOST_VulkanOpenXRData openxr_data = {GHOST_kVulkanXRModeCPU}; GHOST_VulkanOpenXRData openxr_data = {GHOST_kVulkanXRModeCPU};
m_ghost_ctx.openxr_acquire_framebuffer_image_callback_(&openxr_data); ghost_ctx_.openxr_acquire_framebuffer_image_callback_(&openxr_data);
/* Import render result. */ /* Import render result. */
VkDeviceSize component_size = 4 * sizeof(uint8_t); VkDeviceSize component_size = 4 * sizeof(uint8_t);
@@ -464,14 +462,14 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageCpu(
VkDeviceSize image_data_size = openxr_data.extent.width * openxr_data.extent.height * VkDeviceSize image_data_size = openxr_data.extent.width * openxr_data.extent.height *
component_size; component_size;
if (m_vk_buffer != VK_NULL_HANDLE && m_vk_buffer_allocation_info.size < image_data_size) { if (vk_buffer_ != VK_NULL_HANDLE && vk_buffer_allocation_info_.size < image_data_size) {
vmaUnmapMemory(m_vma_allocator, m_vk_buffer_allocation); vmaUnmapMemory(vma_allocator_, vk_buffer_allocation_);
vmaDestroyBuffer(m_vma_allocator, m_vk_buffer, m_vk_buffer_allocation); vmaDestroyBuffer(vma_allocator_, vk_buffer_, vk_buffer_allocation_);
m_vk_buffer = VK_NULL_HANDLE; vk_buffer_ = VK_NULL_HANDLE;
m_vk_buffer_allocation = VK_NULL_HANDLE; vk_buffer_allocation_ = VK_NULL_HANDLE;
} }
if (m_vk_buffer == VK_NULL_HANDLE) { if (vk_buffer_ == VK_NULL_HANDLE) {
VkBufferCreateInfo vk_buffer_create_info = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, VkBufferCreateInfo vk_buffer_create_info = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
nullptr, nullptr,
0, 0,
@@ -484,20 +482,18 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageCpu(
allocation_create_info.usage = VMA_MEMORY_USAGE_AUTO; allocation_create_info.usage = VMA_MEMORY_USAGE_AUTO;
allocation_create_info.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; allocation_create_info.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
allocation_create_info.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; allocation_create_info.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
vmaCreateBuffer(m_vma_allocator, vmaCreateBuffer(vma_allocator_,
&vk_buffer_create_info, &vk_buffer_create_info,
&allocation_create_info, &allocation_create_info,
&m_vk_buffer, &vk_buffer_,
&m_vk_buffer_allocation, &vk_buffer_allocation_,
&m_vk_buffer_allocation_info); &vk_buffer_allocation_info_);
vmaMapMemory( vmaMapMemory(vma_allocator_, vk_buffer_allocation_, &vk_buffer_allocation_info_.pMappedData);
m_vma_allocator, m_vk_buffer_allocation, &m_vk_buffer_allocation_info.pMappedData);
} }
std::memcpy( std::memcpy(vk_buffer_allocation_info_.pMappedData, openxr_data.cpu.image_data, image_data_size);
m_vk_buffer_allocation_info.pMappedData, openxr_data.cpu.image_data, image_data_size);
/* Copy frame buffer image to swapchain image. */ /* Copy frame buffer image to swapchain image. */
VkCommandBuffer vk_command_buffer = m_vk_command_buffer; VkCommandBuffer vk_command_buffer = vk_command_buffer_;
/* - Begin command recording */ /* - Begin command recording */
VkCommandBufferBeginInfo vk_command_buffer_begin_info = { VkCommandBufferBeginInfo vk_command_buffer_begin_info = {
@@ -538,7 +534,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageCpu(
{draw_info.ofsx, draw_info.ofsy, 0}, {draw_info.ofsx, draw_info.ofsy, 0},
{openxr_data.extent.width, openxr_data.extent.height, 1}}; {openxr_data.extent.width, openxr_data.extent.height, 1}};
vkCmdCopyBufferToImage(vk_command_buffer, vkCmdCopyBufferToImage(vk_command_buffer,
m_vk_buffer, vk_buffer_,
swapchain_image.image, swapchain_image.image,
VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
1, 1,
@@ -549,16 +545,16 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageCpu(
/* - Submit command buffer to queue. */ /* - Submit command buffer to queue. */
VkSubmitInfo vk_submit_info = { VkSubmitInfo vk_submit_info = {
VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &vk_command_buffer}; VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &vk_command_buffer};
vkQueueSubmit(m_vk_queue, 1, &vk_submit_info, VK_NULL_HANDLE); vkQueueSubmit(vk_queue_, 1, &vk_submit_info, VK_NULL_HANDLE);
/* - Wait until device is idle. */ /* - Wait until device is idle. */
vkQueueWaitIdle(m_vk_queue); vkQueueWaitIdle(vk_queue_);
/* - Reset command buffer for next eye/frame */ /* - Reset command buffer for next eye/frame */
vkResetCommandBuffer(vk_command_buffer, 0); vkResetCommandBuffer(vk_command_buffer, 0);
/* Release frame buffer image. */ /* Release frame buffer image. */
m_ghost_ctx.openxr_release_framebuffer_image_callback_(&openxr_data); ghost_ctx_.openxr_release_framebuffer_image_callback_(&openxr_data);
} }
/* \} */ /* \} */
@@ -572,28 +568,28 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
{ {
/* Check for previous imported memory. */ /* Check for previous imported memory. */
ImportedMemory *imported_memory = nullptr; ImportedMemory *imported_memory = nullptr;
for (ImportedMemory &item : m_imported_memory) { for (ImportedMemory &item : imported_memory_) {
if (item.view_idx == draw_info.view_idx) { if (item.view_idx == draw_info.view_idx) {
imported_memory = &item; imported_memory = &item;
} }
} }
/* No previous imported memory found, creating a new. */ /* No previous imported memory found, creating a new. */
if (imported_memory == nullptr) { if (imported_memory == nullptr) {
m_imported_memory.push_back( imported_memory_.push_back(
{draw_info.view_idx, VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE}); {draw_info.view_idx, VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE});
imported_memory = &m_imported_memory.back(); imported_memory = &imported_memory_.back();
} }
GHOST_VulkanOpenXRData openxr_data = {m_data_transfer_mode}; GHOST_VulkanOpenXRData openxr_data = {data_transfer_mode_};
openxr_data.gpu.vk_image_blender = imported_memory->vk_image_blender; openxr_data.gpu.vk_image_blender = imported_memory->vk_image_blender;
m_ghost_ctx.openxr_acquire_framebuffer_image_callback_(&openxr_data); ghost_ctx_.openxr_acquire_framebuffer_image_callback_(&openxr_data);
imported_memory->vk_image_blender = openxr_data.gpu.vk_image_blender; imported_memory->vk_image_blender = openxr_data.gpu.vk_image_blender;
/* Create an image handle */ /* Create an image handle */
if (openxr_data.gpu.new_handle) { if (openxr_data.gpu.new_handle) {
if (imported_memory->vk_image_xr) { if (imported_memory->vk_image_xr) {
vkDestroyImage(m_vk_device, imported_memory->vk_image_xr, nullptr); vkDestroyImage(vk_device_, imported_memory->vk_image_xr, nullptr);
vkFreeMemory(m_vk_device, imported_memory->vk_device_memory_xr, nullptr); vkFreeMemory(vk_device_, imported_memory->vk_device_memory_xr, nullptr);
imported_memory->vk_device_memory_xr = VK_NULL_HANDLE; imported_memory->vk_device_memory_xr = VK_NULL_HANDLE;
imported_memory->vk_image_xr = VK_NULL_HANDLE; imported_memory->vk_image_xr = VK_NULL_HANDLE;
} }
@@ -601,7 +597,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
VkExternalMemoryImageCreateInfo vk_external_memory_image_info = { VkExternalMemoryImageCreateInfo vk_external_memory_image_info = {
VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, nullptr, 0}; VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, nullptr, 0};
switch (m_data_transfer_mode) { switch (data_transfer_mode_) {
case GHOST_kVulkanXRModeFD: case GHOST_kVulkanXRModeFD:
vk_external_memory_image_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT; vk_external_memory_image_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
break; break;
@@ -629,12 +625,12 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
nullptr, nullptr,
VK_IMAGE_LAYOUT_UNDEFINED}; VK_IMAGE_LAYOUT_UNDEFINED};
vkCreateImage(m_vk_device, &vk_image_info, nullptr, &imported_memory->vk_image_xr); vkCreateImage(vk_device_, &vk_image_info, nullptr, &imported_memory->vk_image_xr);
/* Get the memory requirements */ /* Get the memory requirements */
VkMemoryRequirements vk_memory_requirements = {}; VkMemoryRequirements vk_memory_requirements = {};
vkGetImageMemoryRequirements( vkGetImageMemoryRequirements(
m_vk_device, imported_memory->vk_image_xr, &vk_memory_requirements); vk_device_, imported_memory->vk_image_xr, &vk_memory_requirements);
/* Import the memory */ /* Import the memory */
VkMemoryDedicatedAllocateInfo vk_memory_dedicated_allocation_info = { VkMemoryDedicatedAllocateInfo vk_memory_dedicated_allocation_info = {
@@ -642,7 +638,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
nullptr, nullptr,
imported_memory->vk_image_xr, imported_memory->vk_image_xr,
VK_NULL_HANDLE}; VK_NULL_HANDLE};
switch (m_data_transfer_mode) { switch (data_transfer_mode_) {
case GHOST_kVulkanXRModeFD: { case GHOST_kVulkanXRModeFD: {
VkImportMemoryFdInfoKHR import_memory_info = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, VkImportMemoryFdInfoKHR import_memory_info = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
&vk_memory_dedicated_allocation_info, &vk_memory_dedicated_allocation_info,
@@ -652,7 +648,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
&import_memory_info, &import_memory_info,
vk_memory_requirements.size}; vk_memory_requirements.size};
vkAllocateMemory( vkAllocateMemory(
m_vk_device, &allocate_info, nullptr, &imported_memory->vk_device_memory_xr); vk_device_, &allocate_info, nullptr, &imported_memory->vk_device_memory_xr);
break; break;
} }
@@ -667,7 +663,7 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
&import_memory_info, &import_memory_info,
vk_memory_requirements.size}; vk_memory_requirements.size};
vkAllocateMemory( vkAllocateMemory(
m_vk_device, &allocate_info, nullptr, &imported_memory->vk_device_memory_xr); vk_device_, &allocate_info, nullptr, &imported_memory->vk_device_memory_xr);
#endif #endif
break; break;
} }
@@ -677,14 +673,14 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
} }
/* Bind the imported memory to the image. */ /* Bind the imported memory to the image. */
vkBindImageMemory(m_vk_device, vkBindImageMemory(vk_device_,
imported_memory->vk_image_xr, imported_memory->vk_image_xr,
imported_memory->vk_device_memory_xr, imported_memory->vk_device_memory_xr,
openxr_data.gpu.memory_offset); openxr_data.gpu.memory_offset);
} }
/* Copy frame buffer image to swapchain image. */ /* Copy frame buffer image to swapchain image. */
VkCommandBuffer vk_command_buffer = m_vk_command_buffer; VkCommandBuffer vk_command_buffer = vk_command_buffer_;
/* Begin command recording */ /* Begin command recording */
VkCommandBufferBeginInfo vk_command_buffer_begin_info = { VkCommandBufferBeginInfo vk_command_buffer_begin_info = {
@@ -767,10 +763,10 @@ void GHOST_XrGraphicsBindingVulkan::submitToSwapchainImageGpu(
/* Submit command buffer to queue. */ /* Submit command buffer to queue. */
VkSubmitInfo vk_submit_info = { VkSubmitInfo vk_submit_info = {
VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &vk_command_buffer}; VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &vk_command_buffer};
vkQueueSubmit(m_vk_queue, 1, &vk_submit_info, VK_NULL_HANDLE); vkQueueSubmit(vk_queue_, 1, &vk_submit_info, VK_NULL_HANDLE);
/* Wait until device is idle. */ /* Wait until device is idle. */
vkQueueWaitIdle(m_vk_queue); vkQueueWaitIdle(vk_queue_);
/* Reset command buffer for next eye/frame. */ /* Reset command buffer for next eye/frame. */
vkResetCommandBuffer(vk_command_buffer, 0); vkResetCommandBuffer(vk_command_buffer, 0);

View File

@@ -50,21 +50,21 @@ class GHOST_XrGraphicsBindingVulkan : public GHOST_IXrGraphicsBinding {
bool needsUpsideDownDrawing(GHOST_Context &ghost_ctx) const override; bool needsUpsideDownDrawing(GHOST_Context &ghost_ctx) const override;
private: private:
GHOST_ContextVK &m_ghost_ctx; GHOST_ContextVK &ghost_ctx_;
VkInstance m_vk_instance = VK_NULL_HANDLE; VkInstance vk_instance_ = VK_NULL_HANDLE;
VkPhysicalDevice m_vk_physical_device = VK_NULL_HANDLE; VkPhysicalDevice vk_physical_device_ = VK_NULL_HANDLE;
uint32_t m_graphics_queue_family = 0; uint32_t graphics_queue_family_ = 0;
VkQueue m_vk_queue = VK_NULL_HANDLE; VkQueue vk_queue_ = VK_NULL_HANDLE;
VkDevice m_vk_device = VK_NULL_HANDLE; VkDevice vk_device_ = VK_NULL_HANDLE;
VmaAllocator m_vma_allocator = VK_NULL_HANDLE; VmaAllocator vma_allocator_ = VK_NULL_HANDLE;
VmaAllocation m_vk_buffer_allocation = VK_NULL_HANDLE; VmaAllocation vk_buffer_allocation_ = VK_NULL_HANDLE;
VkBuffer m_vk_buffer = VK_NULL_HANDLE; VkBuffer vk_buffer_ = VK_NULL_HANDLE;
VmaAllocationInfo m_vk_buffer_allocation_info = {}; VmaAllocationInfo vk_buffer_allocation_info_ = {};
GHOST_TVulkanXRModes m_data_transfer_mode = GHOST_kVulkanXRModeCPU; GHOST_TVulkanXRModes data_transfer_mode_ = GHOST_kVulkanXRModeCPU;
std::list<std::vector<XrSwapchainImageVulkan2KHR>> m_image_cache; std::list<std::vector<XrSwapchainImageVulkan2KHR>> image_cache_;
VkCommandPool m_vk_command_pool = VK_NULL_HANDLE; VkCommandPool vk_command_pool_ = VK_NULL_HANDLE;
struct ImportedMemory { struct ImportedMemory {
char view_idx; char view_idx;
@@ -72,7 +72,7 @@ class GHOST_XrGraphicsBindingVulkan : public GHOST_IXrGraphicsBinding {
VkImage vk_image_xr; VkImage vk_image_xr;
VkDeviceMemory vk_device_memory_xr; VkDeviceMemory vk_device_memory_xr;
}; };
std::vector<ImportedMemory> m_imported_memory; std::vector<ImportedMemory> imported_memory_;
GHOST_TVulkanXRModes choseDataTransferMode(); GHOST_TVulkanXRModes choseDataTransferMode();
void submitToSwapchainImageCpu(XrSwapchainImageVulkan2KHR &swapchain_image, void submitToSwapchainImageCpu(XrSwapchainImageVulkan2KHR &swapchain_image,
@@ -85,7 +85,7 @@ class GHOST_XrGraphicsBindingVulkan : public GHOST_IXrGraphicsBinding {
* *
* This can be improved by having a single command buffer per swap-chain image. * This can be improved by having a single command buffer per swap-chain image.
*/ */
VkCommandBuffer m_vk_command_buffer = VK_NULL_HANDLE; VkCommandBuffer vk_command_buffer_ = VK_NULL_HANDLE;
static PFN_xrGetVulkanGraphicsRequirements2KHR s_xrGetVulkanGraphicsRequirements2KHR_fn; static PFN_xrGetVulkanGraphicsRequirements2KHR s_xrGetVulkanGraphicsRequirements2KHR_fn;
static PFN_xrGetVulkanGraphicsDevice2KHR s_xrGetVulkanGraphicsDevice2KHR_fn; static PFN_xrGetVulkanGraphicsDevice2KHR s_xrGetVulkanGraphicsDevice2KHR_fn;

View File

@@ -66,7 +66,7 @@ struct GHOST_XrDrawInfo {
* \{ */ * \{ */
GHOST_XrSession::GHOST_XrSession(GHOST_XrContext &xr_context) GHOST_XrSession::GHOST_XrSession(GHOST_XrContext &xr_context)
: m_context(&xr_context), m_oxr(std::make_unique<OpenXRSessionData>()) : context_(&xr_context), oxr_(std::make_unique<OpenXRSessionData>())
{ {
} }
@@ -74,29 +74,29 @@ GHOST_XrSession::~GHOST_XrSession()
{ {
unbindGraphicsContext(); unbindGraphicsContext();
m_oxr->swapchains.clear(); oxr_->swapchains.clear();
m_oxr->action_sets.clear(); oxr_->action_sets.clear();
if (m_oxr->reference_space != XR_NULL_HANDLE) { if (oxr_->reference_space != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySpace(m_oxr->reference_space)); CHECK_XR_ASSERT(xrDestroySpace(oxr_->reference_space));
} }
if (m_oxr->view_space != XR_NULL_HANDLE) { if (oxr_->view_space != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySpace(m_oxr->view_space)); CHECK_XR_ASSERT(xrDestroySpace(oxr_->view_space));
} }
if (m_oxr->combined_eye_space != XR_NULL_HANDLE) { if (oxr_->combined_eye_space != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySpace(m_oxr->combined_eye_space)); CHECK_XR_ASSERT(xrDestroySpace(oxr_->combined_eye_space));
} }
if (m_oxr->session != XR_NULL_HANDLE) { if (oxr_->session != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySession(m_oxr->session)); CHECK_XR_ASSERT(xrDestroySession(oxr_->session));
} }
m_oxr->session = XR_NULL_HANDLE; oxr_->session = XR_NULL_HANDLE;
m_oxr->session_state = XR_SESSION_STATE_UNKNOWN; oxr_->session_state = XR_SESSION_STATE_UNKNOWN;
m_oxr->passthrough_supported = false; oxr_->passthrough_supported = false;
m_oxr->passthrough_layer.layerHandle = XR_NULL_HANDLE; oxr_->passthrough_layer.layerHandle = XR_NULL_HANDLE;
m_context->getCustomFuncs().session_exit_fn(m_context->getCustomFuncs().session_exit_customdata); context_->getCustomFuncs().session_exit_fn(context_->getCustomFuncs().session_exit_customdata);
} }
/** /**
@@ -105,14 +105,14 @@ GHOST_XrSession::~GHOST_XrSession()
*/ */
void GHOST_XrSession::initSystem() void GHOST_XrSession::initSystem()
{ {
assert(m_context->getInstance() != XR_NULL_HANDLE); assert(context_->getInstance() != XR_NULL_HANDLE);
assert(m_oxr->system_id == XR_NULL_SYSTEM_ID); assert(oxr_->system_id == XR_NULL_SYSTEM_ID);
XrSystemGetInfo system_info = {}; XrSystemGetInfo system_info = {};
system_info.type = XR_TYPE_SYSTEM_GET_INFO; system_info.type = XR_TYPE_SYSTEM_GET_INFO;
system_info.formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; system_info.formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
CHECK_XR(xrGetSystem(m_context->getInstance(), &system_info, &m_oxr->system_id), CHECK_XR(xrGetSystem(context_->getInstance(), &system_info, &oxr_->system_id),
"Failed to get device information. Is a device plugged in?"); "Failed to get device information. Is a device plugged in?");
} }
@@ -211,9 +211,9 @@ static void create_reference_spaces(OpenXRSessionData &oxr,
void GHOST_XrSession::start(const GHOST_XrSessionBeginInfo *begin_info) void GHOST_XrSession::start(const GHOST_XrSessionBeginInfo *begin_info)
{ {
assert(m_context->getInstance() != XR_NULL_HANDLE); assert(context_->getInstance() != XR_NULL_HANDLE);
assert(m_oxr->session == XR_NULL_HANDLE); assert(oxr_->session == XR_NULL_HANDLE);
if (m_context->getCustomFuncs().gpu_ctx_bind_fn == nullptr) { if (context_->getCustomFuncs().gpu_ctx_bind_fn == nullptr) {
throw GHOST_XrException( throw GHOST_XrException(
"Invalid API usage: No way to bind graphics context to the XR session. Call " "Invalid API usage: No way to bind graphics context to the XR session. Call "
"GHOST_XrGraphicsContextBindFuncs() with valid parameters before starting the " "GHOST_XrGraphicsContextBindFuncs() with valid parameters before starting the "
@@ -223,7 +223,7 @@ void GHOST_XrSession::start(const GHOST_XrSessionBeginInfo *begin_info)
initSystem(); initSystem();
bindGraphicsContext(); bindGraphicsContext();
if (m_gpu_ctx == nullptr) { if (gpu_ctx_ == nullptr) {
throw GHOST_XrException( throw GHOST_XrException(
"Invalid API usage: No graphics context returned through the callback set with " "Invalid API usage: No graphics context returned through the callback set with "
"GHOST_XrGraphicsContextBindFuncs(). This is required for session starting (through " "GHOST_XrGraphicsContextBindFuncs(). This is required for session starting (through "
@@ -231,62 +231,62 @@ void GHOST_XrSession::start(const GHOST_XrSessionBeginInfo *begin_info)
} }
std::string requirement_str; std::string requirement_str;
m_gpu_binding = GHOST_XrGraphicsBindingCreateFromType(m_context->getGraphicsBindingType(), gpu_binding_ = GHOST_XrGraphicsBindingCreateFromType(context_->getGraphicsBindingType(),
*m_gpu_ctx); *gpu_ctx_);
if (!m_gpu_binding->checkVersionRequirements( if (!gpu_binding_->checkVersionRequirements(
*m_gpu_ctx, m_context->getInstance(), m_oxr->system_id, &requirement_str)) *gpu_ctx_, context_->getInstance(), oxr_->system_id, &requirement_str))
{ {
std::ostringstream strstream; std::ostringstream strstream;
strstream << "Available graphics context version does not meet the following requirements: " strstream << "Available graphics context version does not meet the following requirements: "
<< requirement_str; << requirement_str;
throw GHOST_XrException(strstream.str().data()); throw GHOST_XrException(strstream.str().data());
} }
m_gpu_binding->initFromGhostContext(*m_gpu_ctx, m_context->getInstance(), m_oxr->system_id); gpu_binding_->initFromGhostContext(*gpu_ctx_, context_->getInstance(), oxr_->system_id);
XrSessionCreateInfo create_info = {}; XrSessionCreateInfo create_info = {};
create_info.type = XR_TYPE_SESSION_CREATE_INFO; create_info.type = XR_TYPE_SESSION_CREATE_INFO;
create_info.systemId = m_oxr->system_id; create_info.systemId = oxr_->system_id;
create_info.next = &m_gpu_binding->oxr_binding; create_info.next = &gpu_binding_->oxr_binding;
CHECK_XR(xrCreateSession(m_context->getInstance(), &create_info, &m_oxr->session), CHECK_XR(xrCreateSession(context_->getInstance(), &create_info, &oxr_->session),
"Failed to create VR session. The OpenXR runtime may have additional requirements for " "Failed to create VR session. The OpenXR runtime may have additional requirements for "
"the graphics driver that are not met. Other causes are possible too however.\nTip: " "the graphics driver that are not met. Other causes are possible too however.\nTip: "
"The --debug-xr command line option for Blender might allow the runtime to output " "The --debug-xr command line option for Blender might allow the runtime to output "
"detailed error information to the command line."); "detailed error information to the command line.");
prepareDrawing(); prepareDrawing();
create_reference_spaces(*m_oxr, begin_info->base_pose, m_context->isDebugMode()); create_reference_spaces(*oxr_, begin_info->base_pose, context_->isDebugMode());
/* Create and bind actions here. */ /* Create and bind actions here. */
m_context->getCustomFuncs().session_create_fn(); context_->getCustomFuncs().session_create_fn();
} }
void GHOST_XrSession::requestEnd() void GHOST_XrSession::requestEnd()
{ {
xrRequestExitSession(m_oxr->session); xrRequestExitSession(oxr_->session);
} }
void GHOST_XrSession::beginSession() void GHOST_XrSession::beginSession()
{ {
XrSessionBeginInfo begin_info = {XR_TYPE_SESSION_BEGIN_INFO}; XrSessionBeginInfo begin_info = {XR_TYPE_SESSION_BEGIN_INFO};
begin_info.primaryViewConfigurationType = m_oxr->view_type; begin_info.primaryViewConfigurationType = oxr_->view_type;
CHECK_XR(xrBeginSession(m_oxr->session, &begin_info), "Failed to cleanly begin the VR session."); CHECK_XR(xrBeginSession(oxr_->session, &begin_info), "Failed to cleanly begin the VR session.");
} }
void GHOST_XrSession::endSession() void GHOST_XrSession::endSession()
{ {
assert(m_oxr->session != XR_NULL_HANDLE); assert(oxr_->session != XR_NULL_HANDLE);
CHECK_XR(xrEndSession(m_oxr->session), "Failed to cleanly end the VR session."); CHECK_XR(xrEndSession(oxr_->session), "Failed to cleanly end the VR session.");
} }
GHOST_XrSession::LifeExpectancy GHOST_XrSession::handleStateChangeEvent( GHOST_XrSession::LifeExpectancy GHOST_XrSession::handleStateChangeEvent(
const XrEventDataSessionStateChanged &lifecycle) const XrEventDataSessionStateChanged &lifecycle)
{ {
m_oxr->session_state = lifecycle.state; oxr_->session_state = lifecycle.state;
/* Runtime may send events for apparently destroyed session. Our handle should be nullptr then. /* Runtime may send events for apparently destroyed session. Our handle should be nullptr then.
*/ */
assert(m_oxr->session == XR_NULL_HANDLE || m_oxr->session == lifecycle.session); assert(oxr_->session == XR_NULL_HANDLE || oxr_->session == lifecycle.session);
switch (lifecycle.state) { switch (lifecycle.state) {
case XR_SESSION_STATE_READY: case XR_SESSION_STATE_READY:
@@ -313,34 +313,33 @@ GHOST_XrSession::LifeExpectancy GHOST_XrSession::handleStateChangeEvent(
void GHOST_XrSession::prepareDrawing() void GHOST_XrSession::prepareDrawing()
{ {
assert(m_context->getInstance() != XR_NULL_HANDLE); assert(context_->getInstance() != XR_NULL_HANDLE);
std::vector<XrViewConfigurationView> view_configs; std::vector<XrViewConfigurationView> view_configs;
uint32_t view_count; uint32_t view_count;
/* Attempt to use quad view if supported. */ /* Attempt to use quad view if supported. */
if (m_context->isExtensionEnabled(XR_VARJO_QUAD_VIEWS_EXTENSION_NAME)) { if (context_->isExtensionEnabled(XR_VARJO_QUAD_VIEWS_EXTENSION_NAME)) {
m_oxr->view_type = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO; oxr_->view_type = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
} }
m_oxr->foveation_supported = m_context->isExtensionEnabled( oxr_->foveation_supported = context_->isExtensionEnabled(
XR_VARJO_FOVEATED_RENDERING_EXTENSION_NAME); XR_VARJO_FOVEATED_RENDERING_EXTENSION_NAME);
CHECK_XR( CHECK_XR(xrEnumerateViewConfigurationViews(
xrEnumerateViewConfigurationViews( context_->getInstance(), oxr_->system_id, oxr_->view_type, 0, &view_count, nullptr),
m_context->getInstance(), m_oxr->system_id, m_oxr->view_type, 0, &view_count, nullptr), "Failed to get count of view configurations.");
"Failed to get count of view configurations.");
view_configs.resize(view_count, {XR_TYPE_VIEW_CONFIGURATION_VIEW}); view_configs.resize(view_count, {XR_TYPE_VIEW_CONFIGURATION_VIEW});
CHECK_XR(xrEnumerateViewConfigurationViews(m_context->getInstance(), CHECK_XR(xrEnumerateViewConfigurationViews(context_->getInstance(),
m_oxr->system_id, oxr_->system_id,
m_oxr->view_type, oxr_->view_type,
view_configs.size(), view_configs.size(),
&view_count, &view_count,
view_configs.data()), view_configs.data()),
"Failed to get view configurations."); "Failed to get view configurations.");
/* If foveated rendering is used, query the foveated views. */ /* If foveated rendering is used, query the foveated views. */
if (m_oxr->foveation_supported) { if (oxr_->foveation_supported) {
std::vector<XrFoveatedViewConfigurationViewVARJO> request_foveated_config{ std::vector<XrFoveatedViewConfigurationViewVARJO> request_foveated_config{
view_count, {XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO, nullptr, XR_TRUE}}; view_count, {XR_TYPE_FOVEATED_VIEW_CONFIGURATION_VIEW_VARJO, nullptr, XR_TRUE}};
@@ -350,9 +349,9 @@ void GHOST_XrSession::prepareDrawing()
for (uint32_t i = 0; i < view_count; i++) { for (uint32_t i = 0; i < view_count; i++) {
foveated_views[i].next = &request_foveated_config[i]; foveated_views[i].next = &request_foveated_config[i];
} }
CHECK_XR(xrEnumerateViewConfigurationViews(m_context->getInstance(), CHECK_XR(xrEnumerateViewConfigurationViews(context_->getInstance(),
m_oxr->system_id, oxr_->system_id,
m_oxr->view_type, oxr_->view_type,
view_configs.size(), view_configs.size(),
&view_count, &view_count,
foveated_views.data()), foveated_views.data()),
@@ -369,12 +368,12 @@ void GHOST_XrSession::prepareDrawing()
} }
for (const XrViewConfigurationView &view_config : view_configs) { for (const XrViewConfigurationView &view_config : view_configs) {
m_oxr->swapchains.emplace_back(*m_gpu_binding, m_oxr->session, view_config); oxr_->swapchains.emplace_back(*gpu_binding_, oxr_->session, view_config);
} }
m_oxr->views.resize(view_count, {XR_TYPE_VIEW}); oxr_->views.resize(view_count, {XR_TYPE_VIEW});
m_draw_info = std::make_unique<GHOST_XrDrawInfo>(); draw_info_ = std::make_unique<GHOST_XrDrawInfo>();
} }
void GHOST_XrSession::beginFrameDrawing() void GHOST_XrSession::beginFrameDrawing()
@@ -384,30 +383,30 @@ void GHOST_XrSession::beginFrameDrawing()
XrFrameState frame_state = {XR_TYPE_FRAME_STATE}; XrFrameState frame_state = {XR_TYPE_FRAME_STATE};
/* TODO Blocking call. Drawing should run on a separate thread to avoid interferences. */ /* TODO Blocking call. Drawing should run on a separate thread to avoid interferences. */
CHECK_XR(xrWaitFrame(m_oxr->session, &wait_info, &frame_state), CHECK_XR(xrWaitFrame(oxr_->session, &wait_info, &frame_state),
"Failed to synchronize frame rates between Blender and the device."); "Failed to synchronize frame rates between Blender and the device.");
/* Check if we have foveation available for the current frame. */ /* Check if we have foveation available for the current frame. */
m_draw_info->foveation_active = false; draw_info_->foveation_active = false;
if (m_oxr->foveation_supported) { if (oxr_->foveation_supported) {
XrSpaceLocation render_gaze_location{XR_TYPE_SPACE_LOCATION}; XrSpaceLocation render_gaze_location{XR_TYPE_SPACE_LOCATION};
CHECK_XR(xrLocateSpace(m_oxr->combined_eye_space, CHECK_XR(xrLocateSpace(oxr_->combined_eye_space,
m_oxr->view_space, oxr_->view_space,
frame_state.predictedDisplayTime, frame_state.predictedDisplayTime,
&render_gaze_location), &render_gaze_location),
"Failed to locate combined eye space."); "Failed to locate combined eye space.");
m_draw_info->foveation_active = (render_gaze_location.locationFlags & draw_info_->foveation_active = (render_gaze_location.locationFlags &
XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) != 0; XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) != 0;
} }
CHECK_XR(xrBeginFrame(m_oxr->session, &begin_info), CHECK_XR(xrBeginFrame(oxr_->session, &begin_info),
"Failed to submit frame rendering start state."); "Failed to submit frame rendering start state.");
m_draw_info->frame_state = frame_state; draw_info_->frame_state = frame_state;
if (m_context->isDebugTimeMode()) { if (context_->isDebugTimeMode()) {
m_draw_info->frame_begin_time = std::chrono::high_resolution_clock::now(); draw_info_->frame_begin_time = std::chrono::high_resolution_clock::now();
} }
} }
@@ -439,15 +438,15 @@ void GHOST_XrSession::endFrameDrawing(std::vector<XrCompositionLayerBaseHeader *
{ {
XrFrameEndInfo end_info = {XR_TYPE_FRAME_END_INFO}; XrFrameEndInfo end_info = {XR_TYPE_FRAME_END_INFO};
end_info.displayTime = m_draw_info->frame_state.predictedDisplayTime; end_info.displayTime = draw_info_->frame_state.predictedDisplayTime;
end_info.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end_info.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
end_info.layerCount = layers.size(); end_info.layerCount = layers.size();
end_info.layers = layers.data(); end_info.layers = layers.data();
CHECK_XR(xrEndFrame(m_oxr->session, &end_info), "Failed to submit rendered frame."); CHECK_XR(xrEndFrame(oxr_->session, &end_info), "Failed to submit rendered frame.");
if (m_context->isDebugTimeMode()) { if (context_->isDebugTimeMode()) {
print_debug_timings(*m_draw_info); print_debug_timings(*draw_info_);
} }
} }
@@ -460,17 +459,17 @@ void GHOST_XrSession::draw(void *draw_customdata)
beginFrameDrawing(); beginFrameDrawing();
if (m_context->getCustomFuncs().passthrough_enabled_fn(draw_customdata)) { if (context_->getCustomFuncs().passthrough_enabled_fn(draw_customdata)) {
enablePassthrough(); enablePassthrough();
if (m_oxr->passthrough_supported) { if (oxr_->passthrough_supported) {
layers.push_back((XrCompositionLayerBaseHeader *)&m_oxr->passthrough_layer); layers.push_back((XrCompositionLayerBaseHeader *)&oxr_->passthrough_layer);
} }
else { else {
m_context->getCustomFuncs().disable_passthrough_fn(draw_customdata); context_->getCustomFuncs().disable_passthrough_fn(draw_customdata);
} }
} }
if (m_draw_info->frame_state.shouldRender) { if (draw_info_->frame_state.shouldRender) {
proj_layer = drawLayer(projection_layer_views, draw_customdata); proj_layer = drawLayer(projection_layer_views, draw_customdata);
if (layers.size() > 0) { if (layers.size() > 0) {
proj_layer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT; proj_layer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
@@ -518,8 +517,8 @@ void GHOST_XrSession::drawView(GHOST_XrSwapchain &swapchain,
ghost_xr_draw_view_info_from_view(view, draw_view_info); ghost_xr_draw_view_info_from_view(view, draw_view_info);
/* Draw! */ /* Draw! */
m_context->getCustomFuncs().draw_view_fn(&draw_view_info, draw_customdata); context_->getCustomFuncs().draw_view_fn(&draw_view_info, draw_customdata);
m_gpu_binding->submitToSwapchainImage(swapchain_image, draw_view_info); gpu_binding_->submitToSwapchainImage(swapchain_image, draw_view_info);
} }
XrCompositionLayerProjection GHOST_XrSession::drawLayer( XrCompositionLayerProjection GHOST_XrSession::drawLayer(
@@ -533,59 +532,58 @@ XrCompositionLayerProjection GHOST_XrSession::drawLayer(
XrSpaceLocation view_location{XR_TYPE_SPACE_LOCATION}; XrSpaceLocation view_location{XR_TYPE_SPACE_LOCATION};
uint32_t view_count; uint32_t view_count;
viewloc_info.viewConfigurationType = m_oxr->view_type; viewloc_info.viewConfigurationType = oxr_->view_type;
viewloc_info.displayTime = m_draw_info->frame_state.predictedDisplayTime; viewloc_info.displayTime = draw_info_->frame_state.predictedDisplayTime;
viewloc_info.space = m_oxr->reference_space; viewloc_info.space = oxr_->reference_space;
if (m_draw_info->foveation_active) { if (draw_info_->foveation_active) {
viewloc_info.next = &foveated_info; viewloc_info.next = &foveated_info;
} }
CHECK_XR(xrLocateViews(m_oxr->session, CHECK_XR(xrLocateViews(oxr_->session,
&viewloc_info, &viewloc_info,
&view_state, &view_state,
m_oxr->views.size(), oxr_->views.size(),
&view_count, &view_count,
m_oxr->views.data()), oxr_->views.data()),
"Failed to query frame view and projection state."); "Failed to query frame view and projection state.");
assert(m_oxr->swapchains.size() == view_count); assert(oxr_->swapchains.size() == view_count);
CHECK_XR( CHECK_XR(xrLocateSpace(
xrLocateSpace( oxr_->view_space, oxr_->reference_space, viewloc_info.displayTime, &view_location),
m_oxr->view_space, m_oxr->reference_space, viewloc_info.displayTime, &view_location), "Failed to query frame view space");
"Failed to query frame view space");
r_proj_layer_views.resize(view_count); r_proj_layer_views.resize(view_count);
std::vector<XrSwapchainImageBaseHeader *> swapchain_images; std::vector<XrSwapchainImageBaseHeader *> swapchain_images;
swapchain_images.resize(view_count); swapchain_images.resize(view_count);
for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) { for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
GHOST_XrSwapchain &swapchain = m_oxr->swapchains[view_idx]; GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
swapchain_images[view_idx] = swapchain.acquireDrawableSwapchainImage(); swapchain_images[view_idx] = swapchain.acquireDrawableSwapchainImage();
} }
m_gpu_binding->submitToSwapchainBegin(); gpu_binding_->submitToSwapchainBegin();
for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) { for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
GHOST_XrSwapchain &swapchain = m_oxr->swapchains[view_idx]; GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
XrSwapchainImageBaseHeader &swapchain_image = *swapchain_images[view_idx]; XrSwapchainImageBaseHeader &swapchain_image = *swapchain_images[view_idx];
drawView(swapchain, drawView(swapchain,
swapchain_image, swapchain_image,
r_proj_layer_views[view_idx], r_proj_layer_views[view_idx],
view_location, view_location,
m_oxr->views[view_idx], oxr_->views[view_idx],
view_idx, view_idx,
draw_customdata); draw_customdata);
} }
m_gpu_binding->submitToSwapchainEnd(); gpu_binding_->submitToSwapchainEnd();
for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) { for (uint32_t view_idx = 0; view_idx < view_count; view_idx++) {
GHOST_XrSwapchain &swapchain = m_oxr->swapchains[view_idx]; GHOST_XrSwapchain &swapchain = oxr_->swapchains[view_idx];
swapchain.releaseImage(); swapchain.releaseImage();
swapchain_images[view_idx] = nullptr; swapchain_images[view_idx] = nullptr;
} }
layer.space = m_oxr->reference_space; layer.space = oxr_->reference_space;
layer.viewCount = r_proj_layer_views.size(); layer.viewCount = r_proj_layer_views.size();
layer.views = r_proj_layer_views.data(); layer.views = r_proj_layer_views.data();
@@ -594,7 +592,7 @@ XrCompositionLayerProjection GHOST_XrSession::drawLayer(
bool GHOST_XrSession::needsUpsideDownDrawing() const bool GHOST_XrSession::needsUpsideDownDrawing() const
{ {
return m_gpu_binding && m_gpu_binding->needsUpsideDownDrawing(*m_gpu_ctx); return gpu_binding_ && gpu_binding_->needsUpsideDownDrawing(*gpu_ctx_);
} }
/** \} */ /* Drawing */ /** \} */ /* Drawing */
@@ -605,10 +603,10 @@ bool GHOST_XrSession::needsUpsideDownDrawing() const
bool GHOST_XrSession::isRunning() const bool GHOST_XrSession::isRunning() const
{ {
if (m_oxr->session == XR_NULL_HANDLE) { if (oxr_->session == XR_NULL_HANDLE) {
return false; return false;
} }
switch (m_oxr->session_state) { switch (oxr_->session_state) {
case XR_SESSION_STATE_READY: case XR_SESSION_STATE_READY:
case XR_SESSION_STATE_SYNCHRONIZED: case XR_SESSION_STATE_SYNCHRONIZED:
case XR_SESSION_STATE_VISIBLE: case XR_SESSION_STATE_VISIBLE:
@@ -633,18 +631,18 @@ bool GHOST_XrSession::isRunning() const
void GHOST_XrSession::bindGraphicsContext() void GHOST_XrSession::bindGraphicsContext()
{ {
const GHOST_XrCustomFuncs &custom_funcs = m_context->getCustomFuncs(); const GHOST_XrCustomFuncs &custom_funcs = context_->getCustomFuncs();
assert(custom_funcs.gpu_ctx_bind_fn); assert(custom_funcs.gpu_ctx_bind_fn);
m_gpu_ctx = static_cast<GHOST_Context *>(custom_funcs.gpu_ctx_bind_fn()); gpu_ctx_ = static_cast<GHOST_Context *>(custom_funcs.gpu_ctx_bind_fn());
} }
void GHOST_XrSession::unbindGraphicsContext() void GHOST_XrSession::unbindGraphicsContext()
{ {
const GHOST_XrCustomFuncs &custom_funcs = m_context->getCustomFuncs(); const GHOST_XrCustomFuncs &custom_funcs = context_->getCustomFuncs();
if (custom_funcs.gpu_ctx_unbind_fn) { if (custom_funcs.gpu_ctx_unbind_fn) {
custom_funcs.gpu_ctx_unbind_fn((GHOST_ContextHandle)m_gpu_ctx); custom_funcs.gpu_ctx_unbind_fn((GHOST_ContextHandle)gpu_ctx_);
} }
m_gpu_ctx = nullptr; gpu_ctx_ = nullptr;
} }
/** \} */ /* Graphics Context Injection */ /** \} */ /* Graphics Context Injection */
@@ -665,12 +663,12 @@ static GHOST_XrActionSet *find_action_set(OpenXRSessionData *oxr, const char *ac
bool GHOST_XrSession::createActionSet(const GHOST_XrActionSetInfo &info) bool GHOST_XrSession::createActionSet(const GHOST_XrActionSetInfo &info)
{ {
std::map<std::string, GHOST_XrActionSet> &action_sets = m_oxr->action_sets; std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
if (action_sets.find(info.name) != action_sets.end()) { if (action_sets.find(info.name) != action_sets.end()) {
return false; return false;
} }
XrInstance instance = m_context->getInstance(); XrInstance instance = context_->getInstance();
action_sets.emplace( action_sets.emplace(
std::piecewise_construct, std::make_tuple(info.name), std::make_tuple(instance, info)); std::piecewise_construct, std::make_tuple(info.name), std::make_tuple(instance, info));
@@ -680,7 +678,7 @@ bool GHOST_XrSession::createActionSet(const GHOST_XrActionSetInfo &info)
void GHOST_XrSession::destroyActionSet(const char *action_set_name) void GHOST_XrSession::destroyActionSet(const char *action_set_name)
{ {
std::map<std::string, GHOST_XrActionSet> &action_sets = m_oxr->action_sets; std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
/* It's possible nothing is removed. */ /* It's possible nothing is removed. */
action_sets.erase(action_set_name); action_sets.erase(action_set_name);
} }
@@ -689,12 +687,12 @@ bool GHOST_XrSession::createActions(const char *action_set_name,
uint32_t count, uint32_t count,
const GHOST_XrActionInfo *infos) const GHOST_XrActionInfo *infos)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return false; return false;
} }
XrInstance instance = m_context->getInstance(); XrInstance instance = context_->getInstance();
for (uint32_t i = 0; i < count; ++i) { for (uint32_t i = 0; i < count; ++i) {
if (!action_set->createAction(instance, infos[i])) { if (!action_set->createAction(instance, infos[i])) {
@@ -709,7 +707,7 @@ void GHOST_XrSession::destroyActions(const char *action_set_name,
uint32_t count, uint32_t count,
const char *const *action_names) const char *const *action_names)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return; return;
} }
@@ -723,13 +721,13 @@ bool GHOST_XrSession::createActionBindings(const char *action_set_name,
uint32_t count, uint32_t count,
const GHOST_XrActionProfileInfo *infos) const GHOST_XrActionProfileInfo *infos)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return false; return false;
} }
XrInstance instance = m_context->getInstance(); XrInstance instance = context_->getInstance();
XrSession session = m_oxr->session; XrSession session = oxr_->session;
for (uint32_t profile_idx = 0; profile_idx < count; ++profile_idx) { for (uint32_t profile_idx = 0; profile_idx < count; ++profile_idx) {
const GHOST_XrActionProfileInfo &info = infos[profile_idx]; const GHOST_XrActionProfileInfo &info = infos[profile_idx];
@@ -750,7 +748,7 @@ void GHOST_XrSession::destroyActionBindings(const char *action_set_name,
const char *const *action_names, const char *const *action_names,
const char *const *profile_paths) const char *const *profile_paths)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return; return;
} }
@@ -769,7 +767,7 @@ bool GHOST_XrSession::attachActionSets()
{ {
/* Suggest action bindings for all action sets. */ /* Suggest action bindings for all action sets. */
std::map<XrPath, std::vector<XrActionSuggestedBinding>> profile_bindings; std::map<XrPath, std::vector<XrActionSuggestedBinding>> profile_bindings;
for (auto &[name, action_set] : m_oxr->action_sets) { for (auto &[name, action_set] : oxr_->action_sets) {
action_set.getBindings(profile_bindings); action_set.getBindings(profile_bindings);
} }
@@ -779,7 +777,7 @@ bool GHOST_XrSession::attachActionSets()
XrInteractionProfileSuggestedBinding bindings_info{ XrInteractionProfileSuggestedBinding bindings_info{
XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING}; XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
XrInstance instance = m_context->getInstance(); XrInstance instance = context_->getInstance();
for (auto &[profile, bindings] : profile_bindings) { for (auto &[profile, bindings] : profile_bindings) {
bindings_info.interactionProfile = profile; bindings_info.interactionProfile = profile;
@@ -792,17 +790,17 @@ bool GHOST_XrSession::attachActionSets()
/* Attach action sets. */ /* Attach action sets. */
XrSessionActionSetsAttachInfo attach_info{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO}; XrSessionActionSetsAttachInfo attach_info{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO};
attach_info.countActionSets = uint32_t(m_oxr->action_sets.size()); attach_info.countActionSets = uint32_t(oxr_->action_sets.size());
/* Create an aligned copy of the action sets to pass to xrAttachSessionActionSets(). */ /* Create an aligned copy of the action sets to pass to xrAttachSessionActionSets(). */
std::vector<XrActionSet> action_sets(attach_info.countActionSets); std::vector<XrActionSet> action_sets(attach_info.countActionSets);
uint32_t i = 0; uint32_t i = 0;
for (auto &[name, action_set] : m_oxr->action_sets) { for (auto &[name, action_set] : oxr_->action_sets) {
action_sets[i++] = action_set.getActionSet(); action_sets[i++] = action_set.getActionSet();
} }
attach_info.actionSets = action_sets.data(); attach_info.actionSets = action_sets.data();
CHECK_XR(xrAttachSessionActionSets(m_oxr->session, &attach_info), CHECK_XR(xrAttachSessionActionSets(oxr_->session, &attach_info),
"Failed to attach XR action sets."); "Failed to attach XR action sets.");
return true; return true;
@@ -810,7 +808,7 @@ bool GHOST_XrSession::attachActionSets()
bool GHOST_XrSession::syncActions(const char *action_set_name) bool GHOST_XrSession::syncActions(const char *action_set_name)
{ {
std::map<std::string, GHOST_XrActionSet> &action_sets = m_oxr->action_sets; std::map<std::string, GHOST_XrActionSet> &action_sets = oxr_->action_sets;
XrActionsSyncInfo sync_info{XR_TYPE_ACTIONS_SYNC_INFO}; XrActionsSyncInfo sync_info{XR_TYPE_ACTIONS_SYNC_INFO};
sync_info.countActiveActionSets = (action_set_name != nullptr) ? 1 : sync_info.countActiveActionSets = (action_set_name != nullptr) ? 1 :
@@ -823,7 +821,7 @@ bool GHOST_XrSession::syncActions(const char *action_set_name)
GHOST_XrActionSet *action_set = nullptr; GHOST_XrActionSet *action_set = nullptr;
if (action_set_name != nullptr) { if (action_set_name != nullptr) {
action_set = find_action_set(m_oxr.get(), action_set_name); action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return false; return false;
} }
@@ -842,12 +840,12 @@ bool GHOST_XrSession::syncActions(const char *action_set_name)
} }
sync_info.activeActionSets = active_action_sets.data(); sync_info.activeActionSets = active_action_sets.data();
CHECK_XR(xrSyncActions(m_oxr->session, &sync_info), "Failed to synchronize XR actions."); CHECK_XR(xrSyncActions(oxr_->session, &sync_info), "Failed to synchronize XR actions.");
/* Update action states (i.e. Blender custom data). */ /* Update action states (i.e. Blender custom data). */
XrSession session = m_oxr->session; XrSession session = oxr_->session;
XrSpace reference_space = m_oxr->reference_space; XrSpace reference_space = oxr_->reference_space;
const XrTime &predicted_display_time = m_draw_info->frame_state.predictedDisplayTime; const XrTime &predicted_display_time = draw_info_->frame_state.predictedDisplayTime;
if (action_set != nullptr) { if (action_set != nullptr) {
action_set->updateStates(session, reference_space, predicted_display_time); action_set->updateStates(session, reference_space, predicted_display_time);
@@ -868,7 +866,7 @@ bool GHOST_XrSession::applyHapticAction(const char *action_set_name,
const float &frequency, const float &frequency,
const float &amplitude) const float &amplitude)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return false; return false;
} }
@@ -879,7 +877,7 @@ bool GHOST_XrSession::applyHapticAction(const char *action_set_name,
} }
action->applyHapticFeedback( action->applyHapticFeedback(
m_oxr->session, action_name, subaction_path, duration, frequency, amplitude); oxr_->session, action_name, subaction_path, duration, frequency, amplitude);
return true; return true;
} }
@@ -888,7 +886,7 @@ void GHOST_XrSession::stopHapticAction(const char *action_set_name,
const char *action_name, const char *action_name,
const char *subaction_path) const char *subaction_path)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return; return;
} }
@@ -898,12 +896,12 @@ void GHOST_XrSession::stopHapticAction(const char *action_set_name,
return; return;
} }
action->stopHapticFeedback(m_oxr->session, action_name, subaction_path); action->stopHapticFeedback(oxr_->session, action_name, subaction_path);
} }
void *GHOST_XrSession::getActionSetCustomdata(const char *action_set_name) void *GHOST_XrSession::getActionSetCustomdata(const char *action_set_name)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return nullptr; return nullptr;
} }
@@ -913,7 +911,7 @@ void *GHOST_XrSession::getActionSetCustomdata(const char *action_set_name)
void *GHOST_XrSession::getActionCustomdata(const char *action_set_name, const char *action_name) void *GHOST_XrSession::getActionCustomdata(const char *action_set_name, const char *action_name)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return nullptr; return nullptr;
} }
@@ -928,7 +926,7 @@ void *GHOST_XrSession::getActionCustomdata(const char *action_set_name, const ch
uint32_t GHOST_XrSession::getActionCount(const char *action_set_name) uint32_t GHOST_XrSession::getActionCount(const char *action_set_name)
{ {
const GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); const GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return 0; return 0;
} }
@@ -939,7 +937,7 @@ uint32_t GHOST_XrSession::getActionCount(const char *action_set_name)
void GHOST_XrSession::getActionCustomdataArray(const char *action_set_name, void GHOST_XrSession::getActionCustomdataArray(const char *action_set_name,
void **r_customdata_array) void **r_customdata_array)
{ {
GHOST_XrActionSet *action_set = find_action_set(m_oxr.get(), action_set_name); GHOST_XrActionSet *action_set = find_action_set(oxr_.get(), action_set_name);
if (action_set == nullptr) { if (action_set == nullptr) {
return; return;
} }
@@ -956,17 +954,17 @@ void GHOST_XrSession::getActionCustomdataArray(const char *action_set_name,
bool GHOST_XrSession::loadControllerModel(const char *subaction_path) bool GHOST_XrSession::loadControllerModel(const char *subaction_path)
{ {
if (!m_context->isExtensionEnabled(XR_MSFT_CONTROLLER_MODEL_EXTENSION_NAME)) { if (!context_->isExtensionEnabled(XR_MSFT_CONTROLLER_MODEL_EXTENSION_NAME)) {
return false; return false;
} }
XrSession session = m_oxr->session; XrSession session = oxr_->session;
std::map<std::string, GHOST_XrControllerModel> &controller_models = m_oxr->controller_models; std::map<std::string, GHOST_XrControllerModel> &controller_models = oxr_->controller_models;
std::map<std::string, GHOST_XrControllerModel>::iterator it = controller_models.find( std::map<std::string, GHOST_XrControllerModel>::iterator it = controller_models.find(
subaction_path); subaction_path);
if (it == controller_models.end()) { if (it == controller_models.end()) {
XrInstance instance = m_context->getInstance(); XrInstance instance = context_->getInstance();
it = controller_models it = controller_models
.emplace(std::piecewise_construct, .emplace(std::piecewise_construct,
std::make_tuple(subaction_path), std::make_tuple(subaction_path),
@@ -981,17 +979,17 @@ bool GHOST_XrSession::loadControllerModel(const char *subaction_path)
void GHOST_XrSession::unloadControllerModel(const char *subaction_path) void GHOST_XrSession::unloadControllerModel(const char *subaction_path)
{ {
std::map<std::string, GHOST_XrControllerModel> &controller_models = m_oxr->controller_models; std::map<std::string, GHOST_XrControllerModel> &controller_models = oxr_->controller_models;
/* It's possible nothing is removed. */ /* It's possible nothing is removed. */
controller_models.erase(subaction_path); controller_models.erase(subaction_path);
} }
bool GHOST_XrSession::updateControllerModelComponents(const char *subaction_path) bool GHOST_XrSession::updateControllerModelComponents(const char *subaction_path)
{ {
XrSession session = m_oxr->session; XrSession session = oxr_->session;
std::map<std::string, GHOST_XrControllerModel>::iterator it = m_oxr->controller_models.find( std::map<std::string, GHOST_XrControllerModel>::iterator it = oxr_->controller_models.find(
subaction_path); subaction_path);
if (it == m_oxr->controller_models.end()) { if (it == oxr_->controller_models.end()) {
return false; return false;
} }
@@ -1003,9 +1001,9 @@ bool GHOST_XrSession::updateControllerModelComponents(const char *subaction_path
bool GHOST_XrSession::getControllerModelData(const char *subaction_path, bool GHOST_XrSession::getControllerModelData(const char *subaction_path,
GHOST_XrControllerModelData &r_data) GHOST_XrControllerModelData &r_data)
{ {
std::map<std::string, GHOST_XrControllerModel>::iterator it = m_oxr->controller_models.find( std::map<std::string, GHOST_XrControllerModel>::iterator it = oxr_->controller_models.find(
subaction_path); subaction_path);
if (it == m_oxr->controller_models.end()) { if (it == oxr_->controller_models.end()) {
return false; return false;
} }
@@ -1044,16 +1042,16 @@ static void init_passthrough_extension_functions(XrInstance instance)
void GHOST_XrSession::enablePassthrough() void GHOST_XrSession::enablePassthrough()
{ {
if (!m_context->isExtensionEnabled(XR_FB_PASSTHROUGH_EXTENSION_NAME)) { if (!context_->isExtensionEnabled(XR_FB_PASSTHROUGH_EXTENSION_NAME)) {
m_oxr->passthrough_supported = false; oxr_->passthrough_supported = false;
return; return;
} }
if (m_oxr->passthrough_layer.layerHandle != XR_NULL_HANDLE) { if (oxr_->passthrough_layer.layerHandle != XR_NULL_HANDLE) {
return; /* Already initialized */ return; /* Already initialized */
} }
init_passthrough_extension_functions(m_context->getInstance()); init_passthrough_extension_functions(context_->getInstance());
XrResult result; XrResult result;
@@ -1063,7 +1061,7 @@ void GHOST_XrSession::enablePassthrough()
passthrough_create_info.flags |= XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB; passthrough_create_info.flags |= XR_PASSTHROUGH_IS_RUNNING_AT_CREATION_BIT_FB;
XrPassthroughFB passthrough_handle; XrPassthroughFB passthrough_handle;
result = g_xrCreatePassthroughFB(m_oxr->session, &passthrough_create_info, &passthrough_handle); result = g_xrCreatePassthroughFB(oxr_->session, &passthrough_create_info, &passthrough_handle);
XrPassthroughLayerCreateInfoFB passthrough_layer_create_info; XrPassthroughLayerCreateInfoFB passthrough_layer_create_info;
passthrough_layer_create_info.type = XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB; passthrough_layer_create_info.type = XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB;
@@ -1074,18 +1072,18 @@ void GHOST_XrSession::enablePassthrough()
XrPassthroughLayerFB passthrough_layer_handle; XrPassthroughLayerFB passthrough_layer_handle;
result = g_xrCreatePassthroughLayerFB( result = g_xrCreatePassthroughLayerFB(
m_oxr->session, &passthrough_layer_create_info, &passthrough_layer_handle); oxr_->session, &passthrough_layer_create_info, &passthrough_layer_handle);
g_xrPassthroughStartFB(passthrough_handle); g_xrPassthroughStartFB(passthrough_handle);
g_xrPassthroughLayerResumeFB(passthrough_layer_handle); g_xrPassthroughLayerResumeFB(passthrough_layer_handle);
m_oxr->passthrough_layer.type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB; oxr_->passthrough_layer.type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB;
m_oxr->passthrough_layer.next = nullptr; oxr_->passthrough_layer.next = nullptr;
m_oxr->passthrough_layer.flags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT; oxr_->passthrough_layer.flags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
m_oxr->passthrough_layer.space = nullptr; oxr_->passthrough_layer.space = nullptr;
m_oxr->passthrough_layer.layerHandle = passthrough_layer_handle; oxr_->passthrough_layer.layerHandle = passthrough_layer_handle;
m_oxr->passthrough_supported = (result == XR_SUCCESS); oxr_->passthrough_supported = (result == XR_SUCCESS);
} }
/** \} */ /* Meta Quest Passthrough */ /** \} */ /* Meta Quest Passthrough */

View File

@@ -87,16 +87,16 @@ class GHOST_XrSession {
private: private:
/** Pointer back to context managing this session. Would be nice to avoid, but needed to access /** Pointer back to context managing this session. Would be nice to avoid, but needed to access
* custom callbacks set before session start. */ * custom callbacks set before session start. */
class GHOST_XrContext *m_context; class GHOST_XrContext *context_;
std::unique_ptr<OpenXRSessionData> m_oxr; /* Could use stack, but PImpl is preferable. */ std::unique_ptr<OpenXRSessionData> oxr_; /* Could use stack, but PImpl is preferable. */
/** Active Ghost graphic context. Owned by Blender, not GHOST. */ /** Active Ghost graphic context. Owned by Blender, not GHOST. */
class GHOST_Context *m_gpu_ctx = nullptr; class GHOST_Context *gpu_ctx_ = nullptr;
std::unique_ptr<class GHOST_IXrGraphicsBinding> m_gpu_binding; std::unique_ptr<class GHOST_IXrGraphicsBinding> gpu_binding_;
/** Rendering information. Set when drawing starts. */ /** Rendering information. Set when drawing starts. */
std::unique_ptr<GHOST_XrDrawInfo> m_draw_info; std::unique_ptr<GHOST_XrDrawInfo> draw_info_;
void initSystem(); void initSystem();
void beginSession(); void beginSession();

View File

@@ -42,7 +42,7 @@ static OpenXRSwapchainData::ImageVec swapchain_images_create(XrSwapchain swapcha
GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_IXrGraphicsBinding &gpu_binding, GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_IXrGraphicsBinding &gpu_binding,
const XrSession &session, const XrSession &session,
const XrViewConfigurationView &view_config) const XrViewConfigurationView &view_config)
: m_oxr(std::make_unique<OpenXRSwapchainData>()) : oxr_(std::make_unique<OpenXRSwapchainData>())
{ {
XrSwapchainCreateInfo create_info = {XR_TYPE_SWAPCHAIN_CREATE_INFO}; XrSwapchainCreateInfo create_info = {XR_TYPE_SWAPCHAIN_CREATE_INFO};
uint32_t format_count = 0; uint32_t format_count = 0;
@@ -56,7 +56,7 @@ GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_IXrGraphicsBinding &gpu_binding,
assert(swapchain_formats.size() == format_count); assert(swapchain_formats.size() == format_count);
std::optional chosen_format = gpu_binding.chooseSwapchainFormat( std::optional chosen_format = gpu_binding.chooseSwapchainFormat(
swapchain_formats, m_format, m_is_srgb_buffer); swapchain_formats, format_, is_srgb_buffer_);
if (!chosen_format) { if (!chosen_format) {
throw GHOST_XrException( throw GHOST_XrException(
"Error: No format matching OpenXR runtime supported swapchain formats found."); "Error: No format matching OpenXR runtime supported swapchain formats found.");
@@ -72,31 +72,31 @@ GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_IXrGraphicsBinding &gpu_binding,
create_info.arraySize = 1; create_info.arraySize = 1;
create_info.mipCount = 1; create_info.mipCount = 1;
CHECK_XR(xrCreateSwapchain(session, &create_info, &m_oxr->swapchain), CHECK_XR(xrCreateSwapchain(session, &create_info, &oxr_->swapchain),
"Failed to create OpenXR swapchain."); "Failed to create OpenXR swapchain.");
m_image_width = create_info.width; image_width_ = create_info.width;
m_image_height = create_info.height; image_height_ = create_info.height;
m_oxr->swapchain_images = swapchain_images_create(m_oxr->swapchain, gpu_binding); oxr_->swapchain_images = swapchain_images_create(oxr_->swapchain, gpu_binding);
} }
GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_XrSwapchain &&other) GHOST_XrSwapchain::GHOST_XrSwapchain(GHOST_XrSwapchain &&other)
: m_oxr(std::move(other.m_oxr)), : oxr_(std::move(other.oxr_)),
m_image_width(other.m_image_width), image_width_(other.image_width_),
m_image_height(other.m_image_height), image_height_(other.image_height_),
m_format(other.m_format), format_(other.format_),
m_is_srgb_buffer(other.m_is_srgb_buffer) is_srgb_buffer_(other.is_srgb_buffer_)
{ {
/* Prevent xrDestroySwapchain call for the moved out item. */ /* Prevent xrDestroySwapchain call for the moved out item. */
other.m_oxr = nullptr; other.oxr_ = nullptr;
} }
GHOST_XrSwapchain::~GHOST_XrSwapchain() GHOST_XrSwapchain::~GHOST_XrSwapchain()
{ {
/* m_oxr may be nullptr after move. */ /* oxr_ may be nullptr after move. */
if (m_oxr && m_oxr->swapchain != XR_NULL_HANDLE) { if (oxr_ && oxr_->swapchain != XR_NULL_HANDLE) {
CHECK_XR_ASSERT(xrDestroySwapchain(m_oxr->swapchain)); CHECK_XR_ASSERT(xrDestroySwapchain(oxr_->swapchain));
} }
} }
@@ -107,36 +107,36 @@ XrSwapchainImageBaseHeader *GHOST_XrSwapchain::acquireDrawableSwapchainImage()
XrSwapchainImageWaitInfo wait_info = {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; XrSwapchainImageWaitInfo wait_info = {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
uint32_t image_idx; uint32_t image_idx;
CHECK_XR(xrAcquireSwapchainImage(m_oxr->swapchain, &acquire_info, &image_idx), CHECK_XR(xrAcquireSwapchainImage(oxr_->swapchain, &acquire_info, &image_idx),
"Failed to acquire swapchain image for the VR session."); "Failed to acquire swapchain image for the VR session.");
wait_info.timeout = XR_INFINITE_DURATION; wait_info.timeout = XR_INFINITE_DURATION;
CHECK_XR(xrWaitSwapchainImage(m_oxr->swapchain, &wait_info), CHECK_XR(xrWaitSwapchainImage(oxr_->swapchain, &wait_info),
"Failed to acquire swapchain image for the VR session."); "Failed to acquire swapchain image for the VR session.");
return m_oxr->swapchain_images[image_idx]; return oxr_->swapchain_images[image_idx];
} }
void GHOST_XrSwapchain::updateCompositionLayerProjectViewSubImage(XrSwapchainSubImage &r_sub_image) void GHOST_XrSwapchain::updateCompositionLayerProjectViewSubImage(XrSwapchainSubImage &r_sub_image)
{ {
r_sub_image.swapchain = m_oxr->swapchain; r_sub_image.swapchain = oxr_->swapchain;
r_sub_image.imageRect.offset = {0, 0}; r_sub_image.imageRect.offset = {0, 0};
r_sub_image.imageRect.extent = {m_image_width, m_image_height}; r_sub_image.imageRect.extent = {image_width_, image_height_};
} }
GHOST_TXrSwapchainFormat GHOST_XrSwapchain::getFormat() const GHOST_TXrSwapchainFormat GHOST_XrSwapchain::getFormat() const
{ {
return m_format; return format_;
} }
bool GHOST_XrSwapchain::isBufferSRGB() const bool GHOST_XrSwapchain::isBufferSRGB() const
{ {
return m_is_srgb_buffer; return is_srgb_buffer_;
} }
void GHOST_XrSwapchain::releaseImage() void GHOST_XrSwapchain::releaseImage()
{ {
XrSwapchainImageReleaseInfo release_info = {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; XrSwapchainImageReleaseInfo release_info = {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
CHECK_XR(xrReleaseSwapchainImage(m_oxr->swapchain, &release_info), CHECK_XR(xrReleaseSwapchainImage(oxr_->swapchain, &release_info),
"Failed to release swapchain image used to submit VR session frame."); "Failed to release swapchain image used to submit VR session frame.");
} }

View File

@@ -29,8 +29,8 @@ class GHOST_XrSwapchain {
bool isBufferSRGB() const; bool isBufferSRGB() const;
private: private:
std::unique_ptr<OpenXRSwapchainData> m_oxr; /* Could use stack, but PImpl is preferable. */ std::unique_ptr<OpenXRSwapchainData> oxr_; /* Could use stack, but PImpl is preferable. */
int32_t m_image_width, m_image_height; int32_t image_width_, image_height_;
GHOST_TXrSwapchainFormat m_format; GHOST_TXrSwapchainFormat format_;
bool m_is_srgb_buffer = false; bool is_srgb_buffer_ = false;
}; };

View File

@@ -32,7 +32,7 @@
#endif /* defined(WIN32) || defined(__APPLE__) */ #endif /* defined(WIN32) || defined(__APPLE__) */
static void gearsTimerProc(GHOST_TimerTaskHandle task, uint64_t time); static void gearsTimerProc(GHOST_TimerTaskHandle task, uint64_t time);
bool processEvent(GHOST_EventHandle hEvent, GHOST_TUserDataPtr userData); bool processEvent(GHOST_EventHandle hEvent, GHOST_TUserDataPtr user_data);
static GLfloat view_rotx = 20.0, view_roty = 30.0, view_rotz = 0.0; static GLfloat view_rotx = 20.0, view_roty = 30.0, view_rotz = 0.0;
static GLfloat fAngle = 0.0; static GLfloat fAngle = 0.0;
@@ -269,7 +269,7 @@ static void setViewPortGL(GHOST_WindowHandle hWindow)
GHOST_DisposeRectangle(hRect); GHOST_DisposeRectangle(hRect);
} }
bool processEvent(GHOST_EventHandle hEvent, GHOST_TUserDataPtr userData) bool processEvent(GHOST_EventHandle hEvent, GHOST_TUserDataPtr user_data)
{ {
bool handled = true; bool handled = true;
int cursor; int cursor;
@@ -389,7 +389,7 @@ bool processEvent(GHOST_EventHandle hEvent, GHOST_TUserDataPtr userData)
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
char *title1 = "gears - main window"; char *title1 = "gears - main window";
char *title2 = "gears - secondary window"; char *title2 = "gears - secondary window";
GHOST_EventConsumerHandle consumer = GHOST_CreateEventConsumer(processEvent, NULL); GHOST_EventConsumerHandle consumer = GHOST_CreateEventConsumer(processEvent, NULL);
@@ -410,7 +410,7 @@ int main(int argc, char **argv)
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
GHOST_kDrawingContextTypeOpenGL, GHOST_kDrawingContextTypeOpenGL,
gpuSettings); gpu_settings);
if (!sMainWindow) { if (!sMainWindow) {
printf("could not create main window\n"); printf("could not create main window\n");
exit(-1); exit(-1);
@@ -427,7 +427,7 @@ int main(int argc, char **argv)
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
GHOST_kDrawingContextTypeOpenGL, GHOST_kDrawingContextTypeOpenGL,
gpuSettings); gpu_settings);
if (!sSecondaryWindow) { if (!sSecondaryWindow) {
printf("could not create secondary window\n"); printf("could not create secondary window\n");
exit(-1); exit(-1);

View File

@@ -385,59 +385,59 @@ class Application : public GHOST_IEventConsumer {
~Application(); ~Application();
virtual bool processEvent(GHOST_IEvent *event); virtual bool processEvent(GHOST_IEvent *event);
GHOST_ISystem *m_system; GHOST_ISystem *system_;
GHOST_IWindow *m_mainWindow; GHOST_IWindow *main_window_;
GHOST_IWindow *m_secondaryWindow; GHOST_IWindow *secondary_window_;
GHOST_ITimerTask *m_gearsTimer, *m_testTimer; GHOST_ITimerTask *gears_timer_, *test_timer_;
GHOST_TStandardCursor m_cursor; GHOST_TStandardCursor cursor_;
bool m_exitRequested; bool exit_requested_;
bool stereo; bool stereo;
}; };
Application::Application(GHOST_ISystem *system) Application::Application(GHOST_ISystem *system)
: m_system(system), : system_(system),
m_mainWindow(0), main_window_(0),
m_secondaryWindow(0), secondary_window_(0),
m_gearsTimer(0), gears_timer_(0),
m_testTimer(0), test_timer_(0),
m_cursor(GHOST_kStandardCursorFirstCursor), cursor_(GHOST_kStandardCursorFirstCursor),
m_exitRequested(false), exit_requested_(false),
stereo(false) stereo(false)
{ {
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
gpuSettings.context_type = GHOST_kDrawingContextTypeOpenGL; gpu_settings.context_type = GHOST_kDrawingContextTypeOpenGL;
fApp = this; fApp = this;
// Create the main window // Create the main window
m_mainWindow = system->createWindow( main_window_ = system->createWindow(
"gears - main window", 10, 64, 320, 200, GHOST_kWindowStateNormal, gpuSettings); "gears - main window", 10, 64, 320, 200, GHOST_kWindowStateNormal, gpu_settings);
if (!m_mainWindow) { if (!main_window_) {
std::cout << "could not create main window\n"; std::cout << "could not create main window\n";
exit(-1); exit(-1);
} }
// Create a secondary window // Create a secondary window
m_secondaryWindow = system->createWindow( secondary_window_ = system->createWindow(
"gears - secondary window", 340, 64, 320, 200, GHOST_kWindowStateNormal, gpuSettings); "gears - secondary window", 340, 64, 320, 200, GHOST_kWindowStateNormal, gpu_settings);
if (!m_secondaryWindow) { if (!secondary_window_) {
std::cout << "could not create secondary window\n"; std::cout << "could not create secondary window\n";
exit(-1); exit(-1);
} }
// Install a timer to have the gears running // Install a timer to have the gears running
m_gearsTimer = system->installTimer(0 /*delay*/, 20 /*interval*/, gearsTimerProc, m_mainWindow); gears_timer_ = system->installTimer(0 /*delay*/, 20 /*interval*/, gearsTimerProc, main_window_);
} }
Application::~Application() Application::~Application()
{ {
// Dispose windows // Dispose windows
if (m_system->validWindow(m_mainWindow)) { if (system_->validWindow(main_window_)) {
m_system->disposeWindow(m_mainWindow); system_->disposeWindow(main_window_);
} }
if (m_system->validWindow(m_secondaryWindow)) { if (system_->validWindow(secondary_window_)) {
m_system->disposeWindow(m_secondaryWindow); system_->disposeWindow(secondary_window_);
} }
} }
@@ -474,19 +474,19 @@ bool Application::processEvent(const GHOST_IEvent *event)
GHOST_TEventKeyData *keyData = (GHOST_TEventKeyData *)event->getData(); GHOST_TEventKeyData *keyData = (GHOST_TEventKeyData *)event->getData();
switch (keyData->key) { switch (keyData->key) {
case GHOST_kKeyC: { case GHOST_kKeyC: {
int cursor = m_cursor; int cursor = cursor_;
cursor++; cursor++;
if (cursor >= GHOST_kStandardCursorNumCursors) { if (cursor >= GHOST_kStandardCursorNumCursors) {
cursor = GHOST_kStandardCursorFirstCursor; cursor = GHOST_kStandardCursorFirstCursor;
} }
m_cursor = (GHOST_TStandardCursor)cursor; cursor_ = (GHOST_TStandardCursor)cursor;
window->setCursorShape(m_cursor); window->setCursorShape(cursor_);
break; break;
} }
case GHOST_kKeyE: { case GHOST_kKeyE: {
int x = 200, y = 200; int x = 200, y = 200;
m_system->setCursorPosition(x, y); system_->setCursorPosition(x, y);
break; break;
} }
@@ -496,27 +496,27 @@ bool Application::processEvent(const GHOST_IEvent *event)
case GHOST_kKeyM: { case GHOST_kKeyM: {
bool down = false; bool down = false;
m_system->getModifierKeyState(GHOST_kModifierKeyLeftShift, down); system_->getModifierKeyState(GHOST_kModifierKeyLeftShift, down);
if (down) { if (down) {
std::cout << "left shift down\n"; std::cout << "left shift down\n";
} }
m_system->getModifierKeyState(GHOST_kModifierKeyRightShift, down); system_->getModifierKeyState(GHOST_kModifierKeyRightShift, down);
if (down) { if (down) {
std::cout << "right shift down\n"; std::cout << "right shift down\n";
} }
m_system->getModifierKeyState(GHOST_kModifierKeyLeftAlt, down); system_->getModifierKeyState(GHOST_kModifierKeyLeftAlt, down);
if (down) { if (down) {
std::cout << "left Alt down\n"; std::cout << "left Alt down\n";
} }
m_system->getModifierKeyState(GHOST_kModifierKeyRightAlt, down); system_->getModifierKeyState(GHOST_kModifierKeyRightAlt, down);
if (down) { if (down) {
std::cout << "right Alt down\n"; std::cout << "right Alt down\n";
} }
m_system->getModifierKeyState(GHOST_kModifierKeyLeftControl, down); system_->getModifierKeyState(GHOST_kModifierKeyLeftControl, down);
if (down) { if (down) {
std::cout << "left control down\n"; std::cout << "left control down\n";
} }
m_system->getModifierKeyState(GHOST_kModifierKeyRightControl, down); system_->getModifierKeyState(GHOST_kModifierKeyRightControl, down);
if (down) { if (down) {
std::cout << "right control down\n"; std::cout << "right control down\n";
} }
@@ -524,7 +524,7 @@ bool Application::processEvent(const GHOST_IEvent *event)
} }
case GHOST_kKeyQ: case GHOST_kKeyQ:
m_exitRequested = true; exit_requested_ = true;
break; break;
case GHOST_kKeyS: // toggle mono and stereo case GHOST_kKeyS: // toggle mono and stereo
@@ -537,22 +537,22 @@ bool Application::processEvent(const GHOST_IEvent *event)
break; break;
case GHOST_kKeyT: case GHOST_kKeyT:
if (!m_testTimer) { if (!test_timer_) {
m_testTimer = m_system->installTimer(0, 1000, testTimerProc); test_timer_ = system_->installTimer(0, 1000, testTimerProc);
} }
else { else {
m_system->removeTimer(m_testTimer); system_->removeTimer(test_timer_);
m_testTimer = 0; test_timer_ = 0;
} }
break; break;
case GHOST_kKeyW: case GHOST_kKeyW:
if (m_mainWindow) { if (main_window_) {
std::string title = m_mainWindow->getTitle(); std::string title = main_window_->getTitle();
title += "-"; title += "-";
m_mainWindow->setTitle(title); main_window_->setTitle(title);
} }
break; break;
@@ -564,11 +564,11 @@ bool Application::processEvent(const GHOST_IEvent *event)
case GHOST_kEventWindowClose: { case GHOST_kEventWindowClose: {
GHOST_IWindow *window2 = event->getWindow(); GHOST_IWindow *window2 = event->getWindow();
if (window2 == m_mainWindow) { if (window2 == main_window_) {
m_exitRequested = true; exit_requested_ = true;
} }
else { else {
m_system->disposeWindow(window2); system_->disposeWindow(window2);
} }
break; break;
} }
@@ -583,7 +583,7 @@ bool Application::processEvent(const GHOST_IEvent *event)
case GHOST_kEventWindowUpdate: { case GHOST_kEventWindowUpdate: {
GHOST_IWindow *window2 = event->getWindow(); GHOST_IWindow *window2 = event->getWindow();
if (!m_system->validWindow(window2)) { if (!system_->validWindow(window2)) {
break; break;
} }
@@ -677,7 +677,7 @@ int main(int /*argc*/, char ** /*argv*/)
fSystem->addEventConsumer(&app); fSystem->addEventConsumer(&app);
// Enter main loop // Enter main loop
while (!app.m_exitRequested) { while (!app.exit_requested_) {
// printf("main: loop\n"); // printf("main: loop\n");
fSystem->processEvents(true); fSystem->processEvents(true);
fSystem->dispatchEvents(); fSystem->dispatchEvents();

View File

@@ -309,7 +309,7 @@ MainWindow *mainwindow_new(MultiTestApp *app)
{ {
GHOST_SystemHandle sys = multitestapp_get_system(app); GHOST_SystemHandle sys = multitestapp_get_system(app);
GHOST_WindowHandle win; GHOST_WindowHandle win;
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
win = GHOST_CreateWindow(sys, win = GHOST_CreateWindow(sys,
NULL, NULL,
@@ -321,7 +321,7 @@ MainWindow *mainwindow_new(MultiTestApp *app)
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
GHOST_kDrawingContextTypeOpenGL, GHOST_kDrawingContextTypeOpenGL,
gpuSettings); gpu_settings);
if (win) { if (win) {
MainWindow *mw = MEM_callocN(sizeof(*mw), "mainwindow_new"); MainWindow *mw = MEM_callocN(sizeof(*mw), "mainwindow_new");
@@ -561,7 +561,7 @@ static void loggerwindow_handle(void *priv, GHOST_EventHandle evt)
LoggerWindow *loggerwindow_new(MultiTestApp *app) LoggerWindow *loggerwindow_new(MultiTestApp *app)
{ {
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
GHOST_SystemHandle sys = multitestapp_get_system(app); GHOST_SystemHandle sys = multitestapp_get_system(app);
uint32_t screensize[2]; uint32_t screensize[2];
GHOST_WindowHandle win; GHOST_WindowHandle win;
@@ -582,7 +582,7 @@ LoggerWindow *loggerwindow_new(MultiTestApp *app)
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
GHOST_kDrawingContextTypeOpenGL, GHOST_kDrawingContextTypeOpenGL,
gpuSettings); gpu_settings);
if (win) { if (win) {
LoggerWindow *lw = MEM_callocN(sizeof(*lw), "loggerwindow_new"); LoggerWindow *lw = MEM_callocN(sizeof(*lw), "loggerwindow_new");
@@ -774,7 +774,7 @@ static void extrawindow_handle(void *priv, GHOST_EventHandle evt)
ExtraWindow *extrawindow_new(MultiTestApp *app) ExtraWindow *extrawindow_new(MultiTestApp *app)
{ {
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
GHOST_SystemHandle sys = multitestapp_get_system(app); GHOST_SystemHandle sys = multitestapp_get_system(app);
GHOST_WindowHandle win; GHOST_WindowHandle win;
@@ -788,7 +788,7 @@ ExtraWindow *extrawindow_new(MultiTestApp *app)
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
GHOST_kDrawingContextTypeOpenGL, GHOST_kDrawingContextTypeOpenGL,
gpuSettings); gpu_settings);
if (win) { if (win) {
ExtraWindow *ew = MEM_callocN(sizeof(*ew), "mainwindow_new"); ExtraWindow *ew = MEM_callocN(sizeof(*ew), "mainwindow_new");

View File

@@ -39,12 +39,12 @@ void GPUTest::SetUpTestSuite(GHOST_TDrawingContextType draw_context_type,
if (!GPU_backend_supported()) { if (!GPU_backend_supported()) {
GTEST_SKIP() << "GPU backend not supported"; GTEST_SKIP() << "GPU backend not supported";
} }
GHOST_GPUSettings gpuSettings = {}; GHOST_GPUSettings gpu_settings = {};
gpuSettings.context_type = draw_context_type; gpu_settings.context_type = draw_context_type;
gpuSettings.flags = GHOST_gpuDebugContext; gpu_settings.flags = GHOST_gpuDebugContext;
ghost_system_ = GHOST_CreateSystemBackground(); ghost_system_ = GHOST_CreateSystemBackground();
GPU_backend_ghost_system_set(ghost_system_); GPU_backend_ghost_system_set(ghost_system_);
ghost_context_ = GHOST_CreateGPUContext(ghost_system_, gpuSettings); ghost_context_ = GHOST_CreateGPUContext(ghost_system_, gpu_settings);
GHOST_ActivateGPUContext(ghost_context_); GHOST_ActivateGPUContext(ghost_context_);
context_ = GPU_context_create(nullptr, ghost_context_); context_ = GPU_context_create(nullptr, ghost_context_);
GPU_init(); GPU_init();

View File

@@ -1590,15 +1590,15 @@ static bool ghost_event_proc(GHOST_EventHandle ghost_event, GHOST_TUserDataPtr p
static GHOST_WindowHandle playanim_window_open( static GHOST_WindowHandle playanim_window_open(
GHOST_SystemHandle ghost_system, const char *title, int posx, int posy, int sizex, int sizey) GHOST_SystemHandle ghost_system, const char *title, int posx, int posy, int sizex, int sizey)
{ {
GHOST_GPUSettings gpusettings = {0}; GHOST_GPUSettings gpu_settings = {0};
const eGPUBackendType gpu_backend = GPU_backend_type_selection_get(); const eGPUBackendType gpu_backend = GPU_backend_type_selection_get();
gpusettings.context_type = wm_ghost_drawing_context_type(gpu_backend); gpu_settings.context_type = wm_ghost_drawing_context_type(gpu_backend);
gpusettings.preferred_device.index = U.gpu_preferred_index; gpu_settings.preferred_device.index = U.gpu_preferred_index;
gpusettings.preferred_device.vendor_id = U.gpu_preferred_vendor_id; gpu_settings.preferred_device.vendor_id = U.gpu_preferred_vendor_id;
gpusettings.preferred_device.device_id = U.gpu_preferred_device_id; gpu_settings.preferred_device.device_id = U.gpu_preferred_device_id;
if (GPU_backend_vsync_is_overridden()) { if (GPU_backend_vsync_is_overridden()) {
gpusettings.flags |= GHOST_gpuVSyncIsOverridden; gpu_settings.flags |= GHOST_gpuVSyncIsOverridden;
gpusettings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get()); gpu_settings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get());
} }
{ {
@@ -1654,7 +1654,7 @@ static GHOST_WindowHandle playanim_window_open(
/* Could optionally start full-screen. */ /* Could optionally start full-screen. */
GHOST_kWindowStateNormal, GHOST_kWindowStateNormal,
false, false,
gpusettings); gpu_settings);
} }
static void playanim_window_zoom(PlayState &ps, const float zoom_offset) static void playanim_window_zoom(PlayState &ps, const float zoom_offset)

View File

@@ -866,23 +866,23 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm,
bool is_dialog) bool is_dialog)
{ {
/* A new window is created when page-flip mode is required for a window. */ /* A new window is created when page-flip mode is required for a window. */
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
if (win->stereo3d_format->display_mode == S3D_DISPLAY_PAGEFLIP) { if (win->stereo3d_format->display_mode == S3D_DISPLAY_PAGEFLIP) {
gpuSettings.flags |= GHOST_gpuStereoVisual; gpu_settings.flags |= GHOST_gpuStereoVisual;
} }
if (G.debug & G_DEBUG_GPU) { if (G.debug & G_DEBUG_GPU) {
gpuSettings.flags |= GHOST_gpuDebugContext; gpu_settings.flags |= GHOST_gpuDebugContext;
} }
eGPUBackendType gpu_backend = GPU_backend_type_selection_get(); eGPUBackendType gpu_backend = GPU_backend_type_selection_get();
gpuSettings.context_type = wm_ghost_drawing_context_type(gpu_backend); gpu_settings.context_type = wm_ghost_drawing_context_type(gpu_backend);
gpuSettings.preferred_device.index = U.gpu_preferred_index; gpu_settings.preferred_device.index = U.gpu_preferred_index;
gpuSettings.preferred_device.vendor_id = U.gpu_preferred_vendor_id; gpu_settings.preferred_device.vendor_id = U.gpu_preferred_vendor_id;
gpuSettings.preferred_device.device_id = U.gpu_preferred_device_id; gpu_settings.preferred_device.device_id = U.gpu_preferred_device_id;
if (GPU_backend_vsync_is_overridden()) { if (GPU_backend_vsync_is_overridden()) {
gpuSettings.flags |= GHOST_gpuVSyncIsOverridden; gpu_settings.flags |= GHOST_gpuVSyncIsOverridden;
gpuSettings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get()); gpu_settings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get());
} }
int posx = 0; int posx = 0;
@@ -910,7 +910,7 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm,
win->sizey, win->sizey,
(GHOST_TWindowState)win->windowstate, (GHOST_TWindowState)win->windowstate,
is_dialog, is_dialog,
gpuSettings); gpu_settings);
if (ghostwin) { if (ghostwin) {
win->gpuctx = GPU_context_create(ghostwin, nullptr); win->gpuctx = GPU_context_create(ghostwin, nullptr);
@@ -3155,21 +3155,21 @@ void *WM_system_gpu_context_create()
BLI_assert(BLI_thread_is_main()); BLI_assert(BLI_thread_is_main());
BLI_assert(GPU_framebuffer_active_get() == GPU_framebuffer_back_get()); BLI_assert(GPU_framebuffer_active_get() == GPU_framebuffer_back_get());
GHOST_GPUSettings gpuSettings = {0}; GHOST_GPUSettings gpu_settings = {0};
const eGPUBackendType gpu_backend = GPU_backend_type_selection_get(); const eGPUBackendType gpu_backend = GPU_backend_type_selection_get();
gpuSettings.context_type = wm_ghost_drawing_context_type(gpu_backend); gpu_settings.context_type = wm_ghost_drawing_context_type(gpu_backend);
if (G.debug & G_DEBUG_GPU) { if (G.debug & G_DEBUG_GPU) {
gpuSettings.flags |= GHOST_gpuDebugContext; gpu_settings.flags |= GHOST_gpuDebugContext;
} }
gpuSettings.preferred_device.index = U.gpu_preferred_index; gpu_settings.preferred_device.index = U.gpu_preferred_index;
gpuSettings.preferred_device.vendor_id = U.gpu_preferred_vendor_id; gpu_settings.preferred_device.vendor_id = U.gpu_preferred_vendor_id;
gpuSettings.preferred_device.device_id = U.gpu_preferred_device_id; gpu_settings.preferred_device.device_id = U.gpu_preferred_device_id;
if (GPU_backend_vsync_is_overridden()) { if (GPU_backend_vsync_is_overridden()) {
gpuSettings.flags |= GHOST_gpuVSyncIsOverridden; gpu_settings.flags |= GHOST_gpuVSyncIsOverridden;
gpuSettings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get()); gpu_settings.vsync = GHOST_TVSyncModes(GPU_backend_vsync_get());
} }
return GHOST_CreateGPUContext(g_system, gpuSettings); return GHOST_CreateGPUContext(g_system, gpu_settings);
} }
void WM_system_gpu_context_dispose(void *context) void WM_system_gpu_context_dispose(void *context)