Overte C++ Documentation
Application.h
1 //
2 // Application.h
3 // interface/src
4 //
5 // Created by Andrzej Kapolka on 5/10/13.
6 // Copyright 2013 High Fidelity, Inc.
7 // Copyright 2020 Vircadia contributors.
8 // Copyright 2022-2023 Overte e.V.
9 //
10 // Distributed under the Apache License, Version 2.0.
11 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
12 // SPDX-License-Identifier: Apache-2.0
13 //
14 
15 #ifndef hifi_Application_h
16 #define hifi_Application_h
17 
18 #include <functional>
19 #include <memory>
20 
21 #include <QtCore/QCommandLineParser>
22 #include <QtCore/QHash>
23 #include <QtCore/QPointer>
24 #include <QtCore/QSet>
25 #include <QtCore/QSharedPointer>
26 #include <QtCore/QStringList>
27 #include <QtQuick/QQuickItem>
28 #include <QtCore/QSharedPointer>
29 
30 #include <QtGui/QImage>
31 
32 #include <QtWidgets/QApplication>
33 
34 #include <AvatarHashMap.h>
35 #include <ThreadHelpers.h>
36 #include <AbstractScriptingServicesInterface.h>
37 #include <AbstractViewStateInterface.h>
38 #include <EntityEditPacketSender.h>
39 #include <EntityTreeRenderer.h>
40 #include "ArchiveDownloadInterface.h"
41 #include <input-plugins/KeyboardMouseDevice.h>
42 #include <input-plugins/TouchscreenDevice.h>
43 #include <input-plugins/TouchscreenVirtualPadDevice.h>
44 #include <OctreeQuery.h>
45 #include <PhysicalEntitySimulation.h>
46 #include <PhysicsEngine.h>
47 #include <plugins/Forward.h>
48 #include <ui-plugins/PluginContainer.h>
49 #include <ShapeManager.h>
50 #include <SimpleMovingAverage.h>
51 #include <StDev.h>
52 #include <ViewFrustum.h>
53 #include <AbstractUriHandler.h>
54 #include <shared/RateCounter.h>
55 #include <ThreadSafeValueCache.h>
56 #include <shared/ConicalViewFrustum.h>
57 #include <shared/FileLogger.h>
58 #include <RunningMarker.h>
59 #include <ModerationFlags.h>
60 #include <OffscreenUi.h>
61 
62 #include "avatar/MyAvatar.h"
63 #include "FancyCamera.h"
64 #include "ConnectionMonitor.h"
65 #include "CursorManager.h"
66 #include "gpu/Context.h"
67 #include "LoginStateManager.h"
68 #include "Menu.h"
69 #include "PerformanceManager.h"
70 #include "RefreshRateManager.h"
71 #include "octree/OctreePacketProcessor.h"
72 #include "render/Engine.h"
73 #include "scripting/ControllerScriptingInterface.h"
74 #include "scripting/DialogsManagerScriptingInterface.h"
75 #include "ui/ApplicationOverlay.h"
76 #include "ui/EntityScriptServerLogDialog.h"
77 #include "ui/LodToolsDialog.h"
78 #include "ui/LogDialog.h"
79 #include "ui/OctreeStatsDialog.h"
80 #include "ui/OverlayConductor.h"
81 #include "ui/overlays/Overlays.h"
82 #include "DiscordRichPresence.h"
83 
84 #include "workload/GameWorkload.h"
85 #include "graphics/GraphicsEngine.h"
86 
87 #include <graphics/Skybox.h>
88 #include <ModelScriptingInterface.h>
89 
90 #include "Sound.h"
91 #include "VisionSqueeze.h"
92 
93 class GLCanvas;
94 class MainWindow;
95 class AssetUpload;
96 class CompositorHelper;
97 class AudioInjector;
98 class ScriptEngine;
99 using ScriptEnginePointer = std::shared_ptr<ScriptEngine>;
100 
101 namespace controller {
102  class StateController;
103 }
104 
105 
106 static const QString RUNNING_MARKER_FILENAME = "Interface.running";
107 
108 class Application;
109 #if defined(qApp)
110 #undef qApp
111 #endif
112 #define qApp (static_cast<Application*>(QCoreApplication::instance()))
113 
114 class Application : public QApplication,
117  public AbstractUriHandler,
118  public PluginContainer
119 {
120  Q_OBJECT
121 
122  // TODO? Get rid of those
123  friend class OctreePacketProcessor;
124 
125 public:
126 
136  void initializePluginManager(const QCommandLineParser& parser);
137 
147  void initialize(const QCommandLineParser &parser);
148 
149  void setPreviousSessionCrashed(bool value) { _previousSessionCrashed = value; }
150 
151  // virtual functions required for PluginContainer
152  virtual ui::Menu* getPrimaryMenu() override;
153  virtual void requestReset() override { resetSensors(false); }
154  virtual void showDisplayPluginsTools(bool show) override;
155  virtual GLWidget* getPrimaryWidget() override;
156  virtual MainWindow* getPrimaryWindow() override;
157  virtual QOpenGLContext* getPrimaryContext() override;
158  virtual bool makeRenderingContextCurrent() override;
159  virtual bool isForeground() const override;
160 
161  virtual DisplayPluginPointer getActiveDisplayPlugin() const override;
162 
163  static void shutdownPlugins();
164 
165  Application(
166  int& argc, char** argv,
167  const QCommandLineParser& parser,
168  QElapsedTimer& startup_time
169  );
170  ~Application();
171 
172  void postLambdaEvent(const std::function<void()>& f) override;
173  void sendLambdaEvent(const std::function<void()>& f) override;
174 
175  QString getPreviousScriptLocation();
176  void setPreviousScriptLocation(const QString& previousScriptLocation);
177 
178  // Return an HTTP User-Agent string with OS and device information.
179  Q_INVOKABLE QString getUserAgent();
180 
181  void initializeGL();
182  void initializeDisplayPlugins();
183  void initializeRenderEngine();
184  void initializeUi();
185 
186  void updateSecondaryCameraViewFrustum();
187 
188  void updateCamera(RenderArgs& renderArgs, float deltaTime);
189  void resizeGL();
190 
191  bool notify(QObject *, QEvent *) override;
192  bool event(QEvent* event) override;
193  bool eventFilter(QObject* object, QEvent* event) override;
194 
195  glm::uvec2 getCanvasSize() const;
196  QRect getRenderingGeometry() const;
197 
198  glm::uvec2 getUiSize() const;
199  QRect getRecommendedHUDRect() const;
200  glm::vec2 getDeviceSize() const;
201  bool hasFocus() const;
202  void setFocus();
203  void raise();
204 
205  void showCursor(const Cursor::Icon& cursor);
206 
207  bool isThrottleRendering() const;
208 
209  Camera& getCamera() { return _myCamera; }
210  const Camera& getCamera() const { return _myCamera; }
211  // Represents the current view frustum of the avatar.
212  void copyViewFrustum(ViewFrustum& viewOut) const;
213  // Represents the view frustum of the current rendering pass,
214  // which might be different from the viewFrustum, i.e. shadowmap
215  // passes, mirror window passes, etc
216  void copyDisplayViewFrustum(ViewFrustum& viewOut) const;
217 
218  bool isMissingSequenceNumbers() { return _isMissingSequenceNumbers; }
219 
220  const ConicalViewFrustums& getConicalViews() const override { return _conicalViews; }
221 
222  const OctreePacketProcessor& getOctreePacketProcessor() const { return *_octreeProcessor; }
223  QSharedPointer<EntityTreeRenderer> getEntities() const { return DependencyManager::get<EntityTreeRenderer>(); }
224  MainWindow* getWindow() const { return _window; }
225  EntityTreePointer getEntityClipboard() const { return _entityClipboard; }
226  std::shared_ptr<EntityEditPacketSender> getEntityEditPacketSender() { return _entityEditSender; }
227 
228  ivec2 getMouse() const;
229 
230  ApplicationOverlay& getApplicationOverlay() { return *_applicationOverlay; }
231  const ApplicationOverlay& getApplicationOverlay() const { return *_applicationOverlay; }
232  CompositorHelper& getApplicationCompositor() const;
233 
234  Overlays& getOverlays() { return _overlays; }
235 
236  PerformanceManager& getPerformanceManager() { return _performanceManager; }
237  RefreshRateManager& getRefreshRateManager() { return _refreshRateManager; }
238 
239  size_t getRenderFrameCount() const { return _graphicsEngine->getRenderFrameCount(); }
240  float getRenderLoopRate() const { return _graphicsEngine->getRenderLoopRate(); }
241  float getNumCollisionObjects() const;
242  float getTargetRenderFrameRate() const; // frames/second
243 
244  static void setupQmlSurface(QQmlContext* surfaceContext, bool setAdditionalContextProperties);
245 
246  float getFieldOfView() { return _fieldOfView.get(); }
247  void setFieldOfView(float fov);
248 
249  float getHMDTabletScale() { return _hmdTabletScale.get(); }
250  void setHMDTabletScale(float hmdTabletScale);
251  float getDesktopTabletScale() { return _desktopTabletScale.get(); }
252  void setDesktopTabletScale(float desktopTabletScale);
253 
254  bool getDesktopTabletBecomesToolbarSetting() { return _desktopTabletBecomesToolbarSetting.get(); }
255  bool getLogWindowOnTopSetting() { return _keepLogWindowOnTop.get(); }
256  void setLogWindowOnTopSetting(bool keepOnTop) { _keepLogWindowOnTop.set(keepOnTop); }
257  void setDesktopTabletBecomesToolbarSetting(bool value);
258  bool getHmdTabletBecomesToolbarSetting() { return _hmdTabletBecomesToolbarSetting.get(); }
259  void setHmdTabletBecomesToolbarSetting(bool value);
260  bool getPreferStylusOverLaser() { return _preferStylusOverLaserSetting.get(); }
261  void setPreferStylusOverLaser(bool value);
262 
263  bool getPreferAvatarFingerOverStylus() { return _preferAvatarFingerOverStylusSetting.get(); }
264  void setPreferAvatarFingerOverStylus(bool value);
265 
266  bool getMiniTabletEnabled() { return _miniTabletEnabledSetting.get(); }
267  void setMiniTabletEnabled(bool enabled);
268 
269  float getSettingConstrainToolbarPosition() { return _constrainToolbarPosition.get(); }
270  void setSettingConstrainToolbarPosition(bool setting);
271 
272  float getAwayStateWhenFocusLostInVREnabled() { return _awayStateWhenFocusLostInVREnabled.get(); }
273  void setAwayStateWhenFocusLostInVREnabled(bool setting);
274 
275  Q_INVOKABLE void setMinimumGPUTextureMemStabilityCount(int stabilityCount) { _minimumGPUTextureMemSizeStabilityCount = stabilityCount; }
276 
277  NodeToOctreeSceneStats* getOcteeSceneStats() { return &_octreeServerSceneStats; }
278 
279  virtual controller::ScriptingInterface* getControllerScriptingInterface() { return _controllerScriptingInterface; }
280  virtual void registerScriptEngineWithApplicationServices(ScriptManagerPointer& scriptManager) override;
281 
282  virtual void copyCurrentViewFrustum(ViewFrustum& viewOut) const override { copyDisplayViewFrustum(viewOut); }
283  virtual QThread* getMainThread() override { return thread(); }
284  virtual PickRay computePickRay(float x, float y) const override;
285  virtual glm::vec3 getAvatarPosition() const override;
286  virtual qreal getDevicePixelRatio() override;
287 
288  void setActiveDisplayPlugin(const QString& pluginName);
289 
290 #ifndef Q_OS_ANDROID
291  FileLogger* getLogger() const { return _logger; }
292 #endif
293 
294  float getRenderResolutionScale() const;
295 
296  qint64 getCurrentSessionRuntime() const { return _sessionRunTimer.elapsed(); }
297 
298  bool isAboutToQuit() const { return _aboutToQuit; }
299  bool isPhysicsEnabled() const { return _physicsEnabled; }
300  PhysicsEnginePointer getPhysicsEngine() { return _physicsEngine; }
301 
302  // the isHMDMode is true whenever we use the interface from an HMD and not a standard flat display
303  // rendering of several elements depend on that
304  // TODO: carry that information on the Camera as a setting
305  virtual bool isHMDMode() const override;
306  glm::mat4 getHMDSensorPose() const;
307  glm::mat4 getEyeOffset(int eye) const;
308  glm::mat4 getEyeProjection(int eye) const;
309 
310  QRect getDesirableApplicationGeometry() const;
311 
312  virtual bool canAcceptURL(const QString& url) const override;
313  virtual bool acceptURL(const QString& url, bool defaultUpload = false) override;
314 
315  void setMaxOctreePacketsPerSecond(int maxOctreePPS);
316  int getMaxOctreePacketsPerSecond() const;
317 
318  render::ScenePointer getMain3DScene() override { return _graphicsEngine->getRenderScene(); }
319  render::EnginePointer getRenderEngine() override { return _graphicsEngine->getRenderEngine(); }
320  gpu::ContextPointer getGPUContext() const { return _graphicsEngine->getGPUContext(); }
321 
322  const GameWorkload& getGameWorkload() const { return _gameWorkload; }
323 
324  virtual void pushPostUpdateLambda(void* key, const std::function<void()>& func) override;
325 
326  void updateMyAvatarLookAtPosition(float deltaTime);
327 
328  float getGameLoopRate() const { return _gameLoopCounter.rate(); }
329 
330  void takeSnapshot(bool notify, bool includeAnimated = false, float aspectRatio = 0.0f, const QString& filename = QString());
331  void takeSecondaryCameraSnapshot(const bool& notify, const QString& filename = QString());
332  void takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition,
333  const bool& cubemapOutputFormat,
334  const bool& notify,
335  const QString& filename = QString());
336 
337  void shareSnapshot(const QString& filename, const QUrl& href = QUrl(""));
338 
339  QUuid getTabletScreenID() const;
340  QUuid getTabletHomeButtonID() const;
341  QUuid getTabletFrameID() const;
342  QVector<QUuid> getTabletIDs() const;
343 
344  void setAvatarOverrideUrl(const QUrl& url, bool save);
345  void clearAvatarOverrideUrl() { _avatarOverrideUrl = QUrl(); _saveAvatarOverrideUrl = false; }
346  QUrl getAvatarOverrideUrl() { return _avatarOverrideUrl; }
347  bool getSaveAvatarOverrideUrl() { return _saveAvatarOverrideUrl; }
348  void saveNextPhysicsStats(QString filename);
349 
350  bool isServerlessMode() const;
351  bool isInterstitialMode() const { return _interstitialMode; }
352  bool failedToConnectToEntityServer() const { return _failedToConnectToEntityServer; }
353 
354  void replaceDomainContent(const QString& url, const QString& itemName);
355 
356  void loadAvatarScripts(const QVector<QString>& urls);
357  void unloadAvatarScripts();
358 
359  Q_INVOKABLE void copyToClipboard(const QString& text);
360 
361  int getOtherAvatarsReplicaCount() { return DependencyManager::get<AvatarHashMap>()->getReplicaCount(); }
362  void setOtherAvatarsReplicaCount(int count) { DependencyManager::get<AvatarHashMap>()->setReplicaCount(count); }
363 
364  void confirmConnectWithoutAvatarEntities();
365 
366  bool getLoginDialogPoppedUp() const { return _loginDialogPoppedUp; }
367  void createLoginDialog();
368  void updateLoginDialogPosition();
369 
370  void createAvatarInputsBar();
371  void destroyAvatarInputsBar();
372 
373  // Check if a headset is connected
374  bool hasRiftControllers();
375  bool hasViveControllers();
376 
377 #if defined(Q_OS_ANDROID)
378  void beforeEnterBackground();
379  void enterBackground();
380  void enterForeground();
381  void toggleAwayMode();
382  #endif
383 
384  using SnapshotOperator = std::tuple<std::function<void(const QImage&)>, float, bool>;
385  void addSnapshotOperator(const SnapshotOperator& snapshotOperator);
386  bool takeSnapshotOperators(std::queue<SnapshotOperator>& snapshotOperators);
387 
388  void openDirectory(const QString& path);
389 
390  void overrideEntry();
391  void forceDisplayName(const QString& displayName);
392  void forceLoginWithTokens(const QString& tokens);
393  void setConfigFileURL(const QString& fileUrl);
394 
395  // used by preferences and HMDScriptingInterface...
396  VisionSqueeze& getVisionSqueeze() { return _visionSqueeze; }
397 
398 signals:
399  void svoImportRequested(const QString& url);
400 
401  void fullAvatarURLChanged(const QString& newValue, const QString& modelName);
402 
403  void beforeAboutToQuit();
404  void activeDisplayPluginChanged();
405 
406  void uploadRequest(QString path);
407 
408  void interstitialModeChanged(bool isInInterstitialMode);
409 
410  void loginDialogFocusEnabled();
411  void loginDialogFocusDisabled();
412 
413  void miniTabletEnabledChanged(bool enabled);
414  void awayStateWhenFocusLostInVRChanged(bool enabled);
415 
416 public slots:
417  QVector<EntityItemID> pasteEntities(const QString& entityHostType, float x, float y, float z);
418  bool exportEntities(const QString& filename, const QVector<QUuid>& entityIDs, const glm::vec3* givenOffset = nullptr);
419  bool exportEntities(const QString& filename, float x, float y, float z, float scale);
420  bool importEntities(const QString& url, const bool isObservable = true, const qint64 callerId = -1);
421  void updateThreadPoolCount() const;
422  void updateSystemTabletMode();
423  void goToErrorDomainURL(QUrl errorDomainURL);
424 
425  Q_INVOKABLE void loadDialog();
426  Q_INVOKABLE void loadScriptURLDialog() const;
427  void toggleLogDialog();
428  void recreateLogWindow(int);
429  void toggleEntityScriptServerLogDialog();
430  Q_INVOKABLE void showAssetServerWidget(QString filePath = "");
431  Q_INVOKABLE void loadAddAvatarBookmarkDialog() const;
432  Q_INVOKABLE void loadAvatarBrowser() const;
433  Q_INVOKABLE SharedSoundPointer getSampleSound() const;
434 
435  void showDialog(const QUrl& widgetUrl, const QUrl& tabletUrl, const QString& name) const;
436 
437  void showLoginScreen();
438 
439  // FIXME: Move addAssetToWorld* methods to own class?
440  void addAssetToWorldFromURL(QString url);
441  void addAssetToWorldFromURLRequestFinished();
442  void addAssetToWorld(QString filePath, QString zipFile, bool isZip = false, bool isBlocks = false);
443  void addAssetToWorldUnzipFailure(QString filePath);
444  void addAssetToWorldWithNewMapping(QString filePath, QString mapping, int copy, bool isZip = false, bool isBlocks = false);
445  void addAssetToWorldUpload(QString filePath, QString mapping, bool isZip = false, bool isBlocks = false);
446  void addAssetToWorldSetMapping(QString filePath, QString mapping, QString hash, bool isZip = false, bool isBlocks = false);
447  void addAssetToWorldAddEntity(QString filePath, QString mapping);
448 
449  void handleUnzip(QString sourceFile, QStringList destinationFile, bool autoAdd, bool isZip, bool isBlocks);
450 
451  ArchiveDownloadInterface* getFileDownloadInterface() { return _fileDownload; }
452 
453  void handleLocalServerConnection() const;
454  void readArgumentsFromLocalSocket() const;
455 
456  static void packageModel();
457 
458  void resetSensors(bool andReload = false);
459 
460  void hmdVisibleChanged(bool visible);
461 
462 #if (PR_BUILD || DEV_BUILD)
463  void sendWrongProtocolVersionsSignature(bool checked) { ::sendWrongProtocolVersionsSignature(checked); }
464 #endif
465 
466  static void showHelp();
467  static void gotoTutorial();
468 
469  void cycleCamera();
470  void cameraModeChanged();
471  void cameraMenuChanged();
472  void captureMouseChanged(bool captureMouse);
473  void toggleOverlays();
474  void setOverlaysVisible(bool visible);
475  Q_INVOKABLE void centerUI();
476 
477  void resetPhysicsReadyInformation();
478 
479  void reloadResourceCaches();
480 
481  void updateHeartbeat() const;
482 
483  static void deadlockApplication();
484  static void unresponsiveApplication(); // cause main thread to be unresponsive for 35 seconds
485 
486  void rotationModeChanged() const;
487 
488  static void runTests();
489 
490  void setKeyboardFocusHighlight(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& dimensions);
491 
492  QUuid getKeyboardFocusEntity() const; // thread-safe
493  void setKeyboardFocusEntity(const QUuid& id);
494 
495  void addAssetToWorldMessageClose();
496 
497  void loadLODToolsDialog();
498  void loadEntityStatisticsDialog();
499  void loadDomainConnectionDialog();
500  void showScriptLogs();
501 
502  const QString getPreferredCursor() const { return _preferredCursor.get(); }
503  void setPreferredCursor(const QString& cursor);
504 
505  void setIsServerlessMode(bool serverlessDomain);
506  std::map<QString, QString> prepareServerlessDomainContents(QUrl domainURL, QByteArray data);
507 
508  void loadServerlessDomain(QUrl domainURL);
509  void loadErrorDomain(QUrl domainURL);
510  void setIsInterstitialMode(bool interstitialMode);
511 
512  void updateVerboseLogging();
513 
514  void setCachebustRequire();
515 
516  void changeViewAsNeeded(float boomLength);
517 
518  QString getGraphicsCardType();
519 
520  bool gpuTextureMemSizeStable();
521  void showUrlHandler(const QUrl& url);
522 
523  // used to test "shutdown" crash annotation.
524  void crashOnShutdown();
525 
526 private slots:
527  void onDesktopRootItemCreated(QQuickItem* qmlContext);
528  void onDesktopRootContextCreated(QQmlContext* qmlContext);
529  void showDesktop();
530  void clearDomainOctreeDetails(bool clearAll = true);
531  void onAboutToQuit();
532  void onPresent(quint32 frameCount);
533 
534  void resettingDomain();
535 
536  void activeChanged(Qt::ApplicationState state);
537  void windowMinimizedChanged(bool minimized);
538 
539  void notifyPacketVersionMismatch();
540 
541  void loadSettings(const QCommandLineParser& parser);
542  void saveSettings() const;
543  void setFailedToConnectToEntityServer();
544 
545  bool acceptSnapshot(const QString& urlString);
546  bool askToSetAvatarUrl(const QString& url);
547  bool askToLoadScript(const QString& scriptFilenameOrURL);
548 
549  bool askToWearAvatarAttachmentUrl(const QString& url);
550  void displayAvatarAttachmentWarning(const QString& message) const;
551 
552  bool askToReplaceDomainContent(const QString& url);
553 
554  void setSessionUUID(const QUuid& sessionUUID) const;
555 
556  void domainURLChanged(QUrl domainURL);
557  void updateWindowTitle() const;
558  void nodeAdded(SharedNodePointer node);
559  void nodeActivated(SharedNodePointer node);
560  void nodeKilled(SharedNodePointer node);
561  void updateDisplayMode();
562  void setDisplayPlugin(DisplayPluginPointer newPlugin);
563  void domainConnectionRefused(const QString& reasonMessage, int reason, const QString& extraInfo);
564 
565  void addAssetToWorldCheckModelSize();
566 
567  void onAssetToWorldMessageBoxClosed();
568  void addAssetToWorldInfoTimeout();
569  void addAssetToWorldErrorTimeout();
570 
571  void handleSandboxStatus(QNetworkReply* reply);
572  void switchDisplayMode();
573 
574  void setShowBulletWireframe(bool value);
575  void setShowBulletAABBs(bool value);
576  void setShowBulletContactPoints(bool value);
577  void setShowBulletConstraints(bool value);
578  void setShowBulletConstraintLimits(bool value);
579 
580  void onDismissedLoginDialog();
581 
582  void setShowTrackedObjects(bool value);
583 
584 private:
585  void init();
586  bool initMenu();
587  void pauseUntilLoginDetermined();
588  void resumeAfterLoginDialogActionTaken();
589  bool handleInputMethodEventForFocusedEntity(QEvent* event);
590  bool handleKeyEventForFocusedEntity(QEvent* event);
591  bool handleFileOpenEvent(QFileOpenEvent* event);
592  void cleanupBeforeQuit();
593 
594  void idle();
595  void tryToEnablePhysics();
596  void update(float deltaTime);
597 
598  // Various helper functions called during update()
599  void updateLOD(float deltaTime) const;
600  void updateThreads(float deltaTime);
601  void updateDialogs(float deltaTime) const;
602 
603  void queryOctree(NodeType_t serverType, PacketType packetType);
604  void queryAvatars();
605 
606  int sendNackPackets();
607 
608  std::shared_ptr<MyAvatar> getMyAvatar() const;
609 
610  void checkSkeleton() const;
611 
612  void initializeAcceptedFiles();
613 
614  bool importJSONFromURL(const QString& urlString);
615  bool importSVOFromURL(const QString& urlString);
616  bool importFromZIP(const QString& filePath);
617  bool importImage(const QString& urlString);
618 
619  int processOctreeStats(ReceivedMessage& message, SharedNodePointer sendingNode);
620  void trackIncomingOctreePacket(ReceivedMessage& message, SharedNodePointer sendingNode, bool wasStatsPacket);
621 
622  void resizeEvent(QResizeEvent* size);
623 
624  void keyPressEvent(QKeyEvent* event);
625  void keyReleaseEvent(QKeyEvent* event);
626 
627  void focusOutEvent(QFocusEvent* event);
628  void synthesizeKeyReleasEvents();
629  void focusInEvent(QFocusEvent* event);
630 
631  void mouseMoveEvent(QMouseEvent* event);
632  void mousePressEvent(QMouseEvent* event);
633  void mouseDoublePressEvent(QMouseEvent* event);
634  void mouseReleaseEvent(QMouseEvent* event);
635 
636  void touchBeginEvent(QTouchEvent* event);
637  void touchEndEvent(QTouchEvent* event);
638  void touchUpdateEvent(QTouchEvent* event);
639  void touchGestureEvent(QGestureEvent* event);
640 
641  void wheelEvent(QWheelEvent* event) const;
642  void dropEvent(QDropEvent* event);
643  static void dragEnterEvent(QDragEnterEvent* event);
644 
645  void maybeToggleMenuVisible(QMouseEvent* event) const;
646  void toggleTabletUI(bool shouldOpen = false) const;
647  bool shouldCaptureMouse() const;
648 
649  void userKickConfirmation(const QUuid& nodeID, unsigned int banFlags = ModerationFlags::getDefaultBanFlags());
650 
651  MainWindow* _window;
652 
653  // _isMenuInitialized: used to initialize menu early enough before it's needed by other
654  // initializers. Fixes a deadlock issue with recent Qt versions.
655  bool _isMenuInitialized;
656  QElapsedTimer& _sessionRunTimer;
657 
658  bool _aboutToQuit { false };
659 
660 #ifndef Q_OS_ANDROID
661  FileLogger* _logger { nullptr };
662 #endif
663 
664  bool _previousSessionCrashed;
665 
666  DisplayPluginPointer _displayPlugin;
667  QMetaObject::Connection _displayPluginPresentConnection;
668  mutable std::mutex _displayPluginLock;
669  InputPluginList _activeInputPlugins;
670 
671  bool _activatingDisplayPlugin { false };
672 
673  // Frame Rate Measurement
674  RateCounter<500> _gameLoopCounter;
675 
676  QTimer _minimizedWindowTimer;
677  QElapsedTimer _timerStart;
678  QElapsedTimer _lastTimeUpdated;
679 
680  int _minimumGPUTextureMemSizeStabilityCount { 30 };
681 
682  ShapeManager _shapeManager;
683  PhysicalEntitySimulationPointer _entitySimulation;
684  PhysicsEnginePointer _physicsEngine;
685 
686  EntityTreePointer _entityClipboard;
687 
688  mutable QRecursiveMutex _viewMutex;
689  ViewFrustum _viewFrustum; // current state of view frustum, perspective, orientation, etc.
690  ViewFrustum _displayViewFrustum;
691 
692  ConicalViewFrustums _conicalViews;
693  ConicalViewFrustums _lastQueriedViews; // last views used to query servers
694 
695  using SteadyClock = std::chrono::steady_clock;
696  using TimePoint = SteadyClock::time_point;
697  TimePoint _queryExpiry;
698 
699  OctreeQuery _octreeQuery { true }; // NodeData derived class for querying octee cells from octree servers
700 
701  std::shared_ptr<controller::StateController> _applicationStateDevice; // Default ApplicationDevice reflecting the state of different properties of the session
702  std::shared_ptr<KeyboardMouseDevice> _keyboardMouseDevice; // Default input device, the good old keyboard mouse and maybe touchpad
703  std::shared_ptr<TouchscreenDevice> _touchscreenDevice; // the good old touchscreen
704  std::shared_ptr<TouchscreenVirtualPadDevice> _touchscreenVirtualPadDevice;
705  SimpleMovingAverage _avatarSimsPerSecond {10};
706  int _avatarSimsPerSecondReport {0};
707  quint64 _lastAvatarSimsPerSecondUpdate {0};
708  FancyCamera _myCamera; // My view onto the world
709 
710  Setting::Handle<QString> _previousScriptLocation;
711  Setting::Handle<float> _fieldOfView;
712  Setting::Handle<float> _hmdTabletScale;
713  Setting::Handle<float> _desktopTabletScale;
714  Setting::Handle<bool> _firstRun;
715  Setting::Handle<bool> _desktopTabletBecomesToolbarSetting;
716  Setting::Handle<bool> _hmdTabletBecomesToolbarSetting;
717  Setting::Handle<bool> _preferStylusOverLaserSetting;
718  Setting::Handle<bool> _preferAvatarFingerOverStylusSetting;
719  Setting::Handle<bool> _constrainToolbarPosition;
720  Setting::Handle<bool> _awayStateWhenFocusLostInVREnabled;
721  Setting::Handle<QString> _preferredCursor;
722  Setting::Handle<bool> _miniTabletEnabledSetting;
723  Setting::Handle<bool> _keepLogWindowOnTop { "keepLogWindowOnTop", false };
724 
725  float _scaleMirror;
726  float _mirrorYawOffset;
727  float _raiseMirror;
728 
729  QHash<int, QKeyEvent> _keysPressed;
730 
731  bool _enableProcessOctreeThread;
732  bool _interstitialMode { false };
733 
734  std::shared_ptr<OctreePacketProcessor> _octreeProcessor;
735  std::shared_ptr<EntityEditPacketSender> _entityEditSender;
736 
737  StDev _idleLoopStdev;
738  float _idleLoopMeasuredJitter;
739 
740  NodeToOctreeSceneStats _octreeServerSceneStats;
741  ControllerScriptingInterface* _controllerScriptingInterface{ nullptr };
742  QPointer<LogDialog> _logDialog;
743  QPointer<EntityScriptServerLogDialog> _entityScriptServerLogDialog;
744  QDir _defaultScriptsLocation;
745  // If above is only set by parameter, below is unnecessary.
746  bool _overrideDefaultScriptsLocation;
747 
748  TouchEvent _lastTouchEvent;
749 
750  quint64 _lastNackTime;
751  quint64 _lastSendDownstreamAudioStats;
752 
753  bool _notifiedPacketVersionMismatchThisDomain;
754 
755  GLCanvas* _glWidget{ nullptr };
756 
757  typedef bool (Application::* AcceptURLMethod)(const QString &);
758  static const std::vector<std::pair<QString, Application::AcceptURLMethod>> _acceptedExtensions;
759 
760  glm::uvec2 _renderResolution;
761 
762  int _maxOctreePPS = DEFAULT_MAX_OCTREE_PPS;
763  bool _interstitialModeEnabled{ false };
764 
765  bool _loginDialogPoppedUp{ false };
766  bool _desktopRootItemCreated{ false };
767 
768  ModalDialogListener* _confirmConnectWithoutAvatarEntitiesDialog { nullptr };
769 
770  bool _developerMenuVisible{ false };
771  QString _previousAvatarSkeletonModel;
772  float _previousAvatarTargetScale;
773  CameraMode _previousCameraMode;
774  QUuid _loginDialogID;
775  QUuid _avatarInputsBarID;
776  LoginStateManager _loginStateManager;
777  PerformanceManager _performanceManager;
778  RefreshRateManager _refreshRateManager;
779 
780  GameWorkload _gameWorkload;
781 
782  std::shared_ptr<GraphicsEngine> _graphicsEngine;
783  void updateRenderArgs(float deltaTime);
784 
785  bool _disableLoginScreen { true };
786 
787  Overlays _overlays;
788  std::shared_ptr<ApplicationOverlay> _applicationOverlay;
789  OverlayConductor _overlayConductor;
790 
791  DialogsManagerScriptingInterface* _dialogsManagerScriptingInterface = new DialogsManagerScriptingInterface();
792 
793  ThreadSafeValueCache<EntityItemID> _keyboardFocusedEntity;
794  quint64 _lastAcceptedKeyPress = 0;
795  bool _isForeground = true; // starts out assumed to be in foreground
796  bool _isGLInitialized { false };
797  bool _physicsEnabled { false };
798  bool _failedToConnectToEntityServer { false };
799 
800  bool _reticleClickPressed { false };
801  bool _keyboardFocusWaitingOnRenderable { false };
802 
803  int _avatarAttachmentRequest = 0;
804 
805  bool _settingsLoaded { false };
806 
807  bool _captureMouse { false };
808  bool _ignoreMouseMove { false };
809  QPointF _mouseCaptureTarget { NAN, NAN };
810 
811  bool _isMissingSequenceNumbers { false };
812 
813  void checkChangeCursor();
814  mutable QRecursiveMutex _changeCursorLock;
815  Qt::CursorShape _desiredCursor{ Qt::BlankCursor };
816  bool _cursorNeedsChanging { false };
817 
818  std::map<void*, std::function<void()>> _postUpdateLambdas;
819  std::mutex _postUpdateLambdasLock;
820 
821  std::atomic<uint32_t> _fullSceneReceivedCounter { 0 }; // how many times have we received a full-scene octree stats packet
822  uint32_t _fullSceneCounterAtLastPhysicsCheck { 0 }; // _fullSceneReceivedCounter last time we checked physics ready
823 
824  qint64 _gpuTextureMemSizeStabilityCount { 0 };
825  qint64 _gpuTextureMemSizeAtLastCheck { 0 };
826 
827  bool _keyboardDeviceHasFocus { true };
828 
829  ConnectionMonitor _connectionMonitor;
830 
831  QTimer _addAssetToWorldResizeTimer;
832  QHash<QUuid, int> _addAssetToWorldResizeList;
833 
834  void addAssetToWorldInfo(QString modelName, QString infoText);
835  void addAssetToWorldInfoClear(QString modelName);
836  void addAssetToWorldInfoDone(QString modelName);
837  void addAssetToWorldError(QString modelName, QString errorText);
838 
839  QQuickItem* _addAssetToWorldMessageBox{ nullptr };
840  QStringList _addAssetToWorldInfoKeys; // Model name
841  QStringList _addAssetToWorldInfoMessages; // Info message
842  QTimer _addAssetToWorldInfoTimer;
843  QTimer _addAssetToWorldErrorTimer;
844  mutable QTimer _entityServerConnectionTimer;
845 
846  ArchiveDownloadInterface* _fileDownload;
847  AudioInjectorPointer _snapshotSoundInjector;
848  SharedSoundPointer _snapshotSound;
849  SharedSoundPointer _sampleSound;
850  std::mutex _snapshotMutex;
851  std::queue<SnapshotOperator> _snapshotOperators;
852  bool _hasPrimarySnapshot { false };
853 
854  DisplayPluginPointer _autoSwitchDisplayModeSupportedHMDPlugin { nullptr };
855  QString _autoSwitchDisplayModeSupportedHMDPluginName;
856  bool _previousHMDWornStatus;
857  void startHMDStandBySession();
858  void endHMDSession();
859 
860  glm::vec3 _thirdPersonHMDCameraBoom { 0.0f, 0.0f, -1.0f };
861  bool _thirdPersonHMDCameraBoomValid { true };
862 
863  QUrl _avatarOverrideUrl;
864  bool _saveAvatarOverrideUrl { false };
865 
866  std::atomic<bool> _pendingIdleEvent { true };
867 
868  bool quitWhenFinished { false };
869 
870  QUrl _urlParam;
871 
872  bool _showTrackedObjects { false };
873  bool _prevShowTrackedObjects { false };
874 
875  bool _resumeAfterLoginDialogActionTaken_WasPostponed { false };
876  bool _resumeAfterLoginDialogActionTaken_SafeToRun { false };
877  bool _startUpFinished { false };
878  bool _overrideEntry { false };
879 
880  VisionSqueeze _visionSqueeze;
881 
882  bool _crashOnShutdown { false };
883 
884  DiscordPresence* _discordPresence{ nullptr };
885 
886  bool _profilingInitialized { false };
887 };
888 #endif // hifi_Application_h
quint8 NodeType_t
An 8-bit value identifying the type of a node - domain server, audio mixer, etc.
Definition: NodeType.h:22
Interface provided by Application to other objects that need access to scripting services of the appl...
Definition: AbstractScriptingServicesInterface.h:26
virtual void registerScriptEngineWithApplicationServices(ScriptManagerPointer &scriptEngine)=0
Registers application specific services with a script engine.
Interface provided by Application to other objects that need access to the current view state details...
Definition: AbstractViewStateInterface.h:31
virtual void copyCurrentViewFrustum(ViewFrustum &viewOut) const =0
copies the current view frustum for rendering the view state
The ArchiveDownloadInterface API provides some facilities for working with the file system.
Definition: ArchiveDownloadInterface.h:27
customized canvas that simply forwards requests/events to the singleton application
Definition: GLCanvas.h:18
customized canvas that simply forwards requests/events to the singleton application
Definition: GLWidget.h:22
void initialize(bool isThreaded=true, QThread::Priority priority=QThread::NormalPriority)
Definition: GenericThread.cpp:33
Definition: OctreeSceneStats.h:274
Definition: OctreePacketProcessor.h:24
Provides an engine-independent interface for a scripting engine.
Definition: ScriptEngine.h:93
Represents a display or device event to the scripting engine. Exposed as TouchEvent
Definition: TouchEvent.h:30