-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwindow_ctx.cpp
More file actions
473 lines (406 loc) · 15.1 KB
/
window_ctx.cpp
File metadata and controls
473 lines (406 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#include "./window_ctx.hpp"
#include "./stat_panel.hpp"
#include "./xr_renderer.hpp"
namespace jsar::example
{
#ifdef __APPLE__
// Forward declare the macOS window customization function (implemented in macos_window.mm)
extern "C" void customizeMacOSWindow(GLFWwindow *window);
extern "C" void startWindowDragging(GLFWwindow *window);
extern "C" void updateWindowDragging(GLFWwindow *window);
extern "C" void stopWindowDragging(GLFWwindow *window);
extern "C" bool isMouseInDragRegion(GLFWwindow *window, double xpos, double ypos, int dragRegionHeight);
#endif
void onFramebufferSizeChanged(GLFWwindow *window, int width, int height)
{
WindowContext *ctx = reinterpret_cast<WindowContext *>(glfwGetWindowUserPointer(window));
float xScale, yScale;
glfwGetWindowContentScale(window, &xScale, &yScale);
ctx->contentScaling[0] = xScale;
ctx->contentScaling[1] = yScale;
ctx->width = width / ctx->contentScaling[0];
ctx->height = height / ctx->contentScaling[1];
ctx->aspect = (float)width / (float)height;
if (ctx->statPanel != nullptr)
ctx->statPanel->resetCanvas();
glfwSetWindowTitle(window, ctx->title().c_str());
}
WindowContext::WindowContext(GLFWmonitor *monitor)
{
// Initialize animation state
targetHorizontalRotation = 0.0f;
currentHorizontalRotation = 0.0f;
targetViewerPosition = glm::vec3(0.0f, 0.0f, 0.35f);
currentViewerPosition = targetViewerPosition;
lastFrameTime = 0.0;
// Initialize throttling state
lastScrollTime = 0.0;
lastMouseMoveTime = 0.0;
// Initialize dragging state
isDraggingWindow = false;
leftMousePressed = false;
dragRegionHeight = 25; // Default to 25 pixels
if (monitor == nullptr)
{
terminate();
return;
}
const GLFWvidmode *mode = glfwGetVideoMode(monitor);
width = mode->width;
height = mode->height;
aspect = (float)width / (float)height;
initWindow(monitor);
/** glfw will ignore x/y/w/h when monitor is not null. */
glfwSetWindowMonitor(window, monitor, 0, 0, width, height, mode->refreshRate);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
WindowContext::WindowContext(int width, int height)
: width(width)
, height(height)
{
// Initialize animation state
targetHorizontalRotation = 0.0f;
currentHorizontalRotation = 0.0f;
targetViewerPosition = glm::vec3(0.0f, 0.0f, 0.35f);
currentViewerPosition = targetViewerPosition;
lastFrameTime = 0.0;
// Initialize throttling state
lastScrollTime = 0.0;
lastMouseMoveTime = 0.0;
// Initialize dragging state
isDraggingWindow = false;
leftMousePressed = false;
dragRegionHeight = 25; // Default to 25 pixels
aspect = (float)width / (float)height;
initWindow(nullptr);
}
void WindowContext::shutdown()
{
if (terminated)
return;
glfwSetCursorPosCallback(window, nullptr);
glfwSetScrollCallback(window, nullptr);
glfwSetMouseButtonCallback(window, nullptr);
glfwSetKeyCallback(window, nullptr);
glfwSetCharCallback(window, nullptr);
glfwDestroyWindow(window);
terminated = true;
window = nullptr;
}
TrViewport WindowContext::drawingViewport()
{
return TrViewport(width * contentScaling[0], height * contentScaling[1]);
}
std::string WindowContext::title()
{
std::string baseTitle = "JSAR Browser";
return baseTitle + " (" + std::to_string(width) + "x" + std::to_string(height) + ")";
}
StatPanel *WindowContext::createStatPanel()
{
return new StatPanel(this);
}
inline WindowContext *GetContextAndExecute(GLFWwindow *window,
std::function<void(WindowContext *)> callback = nullptr)
{
assert(window != nullptr && "Window is not initialized.");
WindowContext *ctx = reinterpret_cast<WindowContext *>(glfwGetWindowUserPointer(window));
assert(ctx != nullptr && "Failed to retrieve user pointer.");
if (callback)
{
callback(ctx);
}
return ctx;
}
XRStereoscopicRenderer *WindowContext::createXrRenderer(bool monoMode)
{
assert(window != nullptr && "Window is not initialized.");
xrRenderer = new XRStereoscopicRenderer(this, monoMode);
// Initialize animation state with current viewer position
targetViewerPosition = xrRenderer->viewerPosition();
currentViewerPosition = targetViewerPosition;
targetHorizontalRotation = 0.0f;
currentHorizontalRotation = 0.0f;
lastFrameTime = 0.0;
glfwSetCursorPosCallback(window, [](GLFWwindow *window, double xpos, double ypos)
{ GetContextAndExecute(window)->handleCursorMove(xpos, ypos); });
glfwSetScrollCallback(window, [](GLFWwindow *window, double xoffset, double yoffset)
{ GetContextAndExecute(window)->handleScroll(xoffset, yoffset); });
glfwSetMouseButtonCallback(window, [](GLFWwindow *window, int button, int action, int mods)
{ GetContextAndExecute(window)->handleMouseButton(button, action, mods); });
// Set up key and character input callbacks for UI components
glfwSetKeyCallback(window, [](GLFWwindow *window, int key, int scancode, int action, int mods)
{ GetContextAndExecute(window)->handleKeyInput(key, scancode, action, mods); });
glfwSetCharCallback(window, [](GLFWwindow *window, unsigned int codepoint)
{ GetContextAndExecute(window)->handleCharInput(codepoint); });
return xrRenderer;
}
void WindowContext::handleScroll(double xoffset, double yoffset)
{
assert(xrRenderer != nullptr);
// Throttle scroll events to prevent overly sensitive scrolling
double currentTime = glfwGetTime();
if (currentTime - lastScrollTime < SCROLL_THROTTLE_INTERVAL)
{
return; // Skip this scroll event due to throttling
}
lastScrollTime = currentTime;
// Handle distance limits for forward/backward movement
if (yoffset != 0)
{
// Calculate new target position
float deltaZ = yoffset * 0.1f;
float newTargetZ = targetViewerPosition.z + deltaZ;
// Apply near/far limits (assuming initial position around 0.35f)
float minDistance = 0.1f; // Near limit
float maxDistance = 1.0f; // Far limit
// Clamp the target position within limits
// if (newTargetZ >= minDistance && newTargetZ <= maxDistance)
{
targetViewerPosition.z = newTargetZ;
}
}
if (xoffset != 0)
xrRenderer->rotateViewerByAxisY(xoffset * 0.1);
}
void WindowContext::handleCursorMove(double xoffset, double yoffset)
{
// Handle window dragging on macOS - prioritize dragging and skip bounds checking
#ifdef __APPLE__
if (isDraggingWindow)
{
updateWindowDragging(window);
return; // Skip normal cursor handling when dragging window
}
#endif
if (xoffset < 0 || yoffset < 0 || xoffset > width || yoffset > height)
return;
if (xrRenderer == nullptr)
return;
// Throttle mouse move events to prevent overly sensitive mouse movement
double currentTime = glfwGetTime();
if (currentTime - lastMouseMoveTime < MOUSE_THROTTLE_INTERVAL)
{
return; // Skip this mouse move event due to throttling
}
lastMouseMoveTime = currentTime;
// Handle middle mouse horizontal rotation
if (middleMousePressed)
{
double deltaX = xoffset - lastMouseX;
// Convert mouse movement to rotation (sensitivity factor)
float rotationSensitivity = 0.1f;
float deltaRotation = static_cast<float>(deltaX) * rotationSensitivity;
// Update target horizontal rotation with limits (+/- 30 degrees)
targetHorizontalRotation += deltaRotation;
if (targetHorizontalRotation > 30.0f)
targetHorizontalRotation = 30.0f;
else if (targetHorizontalRotation < -30.0f)
targetHorizontalRotation = -30.0f;
lastMouseX = xoffset;
lastMouseY = yoffset;
return; // Skip normal cursor handling when middle mouse is pressed
}
int viewIndex = 0;
float viewportWidth = width;
// In stereo mode, determine which eye is being interacted with
if (!xrRenderer->isMonoMode())
{
auto halfWidth = width / 2;
if (xoffset > halfWidth)
{
xoffset -= halfWidth;
viewIndex = 1;
}
viewportWidth = halfWidth;
}
glm::vec4 viewport(0, 0, viewportWidth, height);
glm::vec3 screenCoord(xoffset, viewport.w - yoffset, 0.2f);
GLfloat depth;
glReadPixels(screenCoord.x * contentScaling[0],
screenCoord.y * contentScaling[1],
1,
1,
GL_DEPTH_COMPONENT,
GL_FLOAT,
&depth);
screenCoord.z = depth;
// Update the main input source's target ray
glm::vec3 origin = xrRenderer->viewerPosition() + glm::vec3(0, -0.01f, 0); // Slightly lower than eye level
if (depth < 1.0f && depth > 0.0f)
{
glm::vec3 xyz = glm::unProject(screenCoord,
xrRenderer->getViewMatrixForEye(viewIndex),
xrRenderer->getProjectionMatrix(),
viewport);
glm::vec3 direction = glm::normalize(xyz - origin);
xrRenderer->updateMainInputSourceTargetRay(origin, direction);
}
else
{
glm::vec3 direction = glm::vec3(0, 1, 0); // Default direction if depth is invalid
xrRenderer->updateMainInputSourceTargetRay(origin, direction);
}
}
void WindowContext::handleMouseButton(int button, int action, int mods)
{
// First, check if we have a UI component handler and call it
if (uiMouseButtonHandler_)
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
uiMouseButtonHandler_(button, action, xpos, ypos);
}
if (xrRenderer == nullptr)
return;
if (button == GLFW_MOUSE_BUTTON_LEFT)
{
if (action == GLFW_PRESS)
{
leftMousePressed = true;
#ifdef __APPLE__
// Check if mouse is in the drag region (configurable height) on macOS
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
if (isMouseInDragRegion(window, xpos, ypos, dragRegionHeight))
{
isDraggingWindow = true;
startWindowDragging(window);
return; // Don't process as normal UI interaction
}
#endif
}
else if (action == GLFW_RELEASE)
{
leftMousePressed = false;
#ifdef __APPLE__
if (isDraggingWindow)
{
stopWindowDragging(window);
isDraggingWindow = false;
return; // Don't process as normal UI interaction
}
#endif
}
// Only update primary action if we're not dragging the window
if (!isDraggingWindow)
xrRenderer->updateMainInputSourcePrimaryAction(action == GLFW_PRESS);
}
else if (button == GLFW_MOUSE_BUTTON_MIDDLE)
{
if (action == GLFW_PRESS)
{
middleMousePressed = true;
glfwGetCursorPos(window, &lastMouseX, &lastMouseY);
}
else if (action == GLFW_RELEASE)
{
middleMousePressed = false;
}
}
}
void WindowContext::handleKeyInput(int key, int scancode, int action, int mods)
{
// First check if we have a UI component handler registered
if (keyInputHandler_)
{
keyInputHandler_(key, scancode, action, mods);
}
// Handle any window-level key events here if needed
// For now, we'll just pass through to the UI handler
}
void WindowContext::handleCharInput(unsigned int codepoint)
{
// First check if we have a UI component handler registered
if (charInputHandler_)
{
charInputHandler_(codepoint);
}
}
void WindowContext::setKeyInputHandler(std::function<void(int, int, int, int)> handler)
{
keyInputHandler_ = handler;
}
void WindowContext::setCharInputHandler(std::function<void(unsigned int)> handler)
{
charInputHandler_ = handler;
}
void WindowContext::setUIMouseButtonHandler(std::function<void(int, int, double, double)> handler)
{
uiMouseButtonHandler_ = handler;
}
void WindowContext::updateAnimation()
{
if (xrRenderer == nullptr)
return;
// Get current time for delta time calculation
double currentTime = glfwGetTime();
if (lastFrameTime == 0.0)
lastFrameTime = currentTime;
double deltaTime = currentTime - lastFrameTime;
lastFrameTime = currentTime;
// Improved smooth damping animation with cubic easing
// Using exponential decay with cubic easing for smoother approach to target
float rotationDampingFactor = 12.0f; // Higher damping for smoother animation
float positionDampingFactor = 8.0f;
// Smooth horizontal rotation animation with cubic easing
float rotationDifference = targetHorizontalRotation - currentHorizontalRotation;
if (std::abs(rotationDifference) > 0.001f) // Lower threshold for smoother ending
{
// Cubic easing out for smoother deceleration
float t = std::min(1.0f, rotationDampingFactor * static_cast<float>(deltaTime));
float easeOut = 1.0f - std::pow(1.0f - t, 3.0f); // Cubic ease-out
float rotationStep = rotationDifference * easeOut;
currentHorizontalRotation += rotationStep;
// Keep the original horizontalRotation variable in sync
horizontalRotation = currentHorizontalRotation;
// Apply the rotation difference to XR renderer
xrRenderer->rotateViewerByAxisY(rotationStep * (M_PI / 180.0f)); // Convert to radians
}
// Smooth position animation with cubic easing
glm::vec3 currentViewerPos = xrRenderer->viewerPosition();
glm::vec3 positionDifference = targetViewerPosition - currentViewerPos;
if (glm::length(positionDifference) > 0.0001f) // Lower threshold for smoother ending
{
// Cubic easing out for smoother deceleration
float t = std::min(1.0f, positionDampingFactor * static_cast<float>(deltaTime));
float easeOut = 1.0f - std::pow(1.0f - t, 3.0f); // Cubic ease-out
glm::vec3 positionStep = positionDifference * easeOut;
// Apply only the Z-axis movement (forward/backward)
if (std::abs(positionStep.z) > 0.0001f)
{
xrRenderer->moveViewerForward(positionStep.z);
// Update our target position tracking
currentViewerPosition = xrRenderer->viewerPosition();
}
}
}
void WindowContext::initWindow(GLFWmonitor *monitor)
{
window = glfwCreateWindow(width, height, title().c_str(), monitor, NULL);
if (!window)
{
terminate();
}
else
{
glfwGetWindowContentScale(window, &contentScaling[0], &contentScaling[1]);
glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, onFramebufferSizeChanged);
#ifdef __APPLE__
// On macOS, customize window to hide title bar but keep system buttons and rounded corners
customizeMacOSWindow(window);
#else
// On other platforms, use GLFW's decorated setting as fallback
glfwSetWindowAttrib(window, GLFW_DECORATED, GLFW_FALSE);
#endif
}
}
void WindowContext::setDragRegionHeight(int height)
{
if (height >= 0)
{
dragRegionHeight = height;
}
}
}