From f4b6db5def62b09d4ea6df41192de29212e531d7 Mon Sep 17 00:00:00 2001 From: Matt Hardcastle Date: Sun, 2 Dec 2018 17:08:27 -0800 Subject: [PATCH 01/50] Use QSaveFile when persisting domain settings to disk Prior to this change the `DomainServerSettingsManager::persistToFile()` method wrote directly to the settings file. It also did limited error checking. These limitations could lead to a situation where a crashed domain-server process, a file system backup, a settings file copy, or a hardware error could corrupt the setting file. This change swaps the `QFile` class for `QSaveFile` and uses its atomic saving features, which writes the changes to the settings file to a file in the same directory as the settings file and then does a rename to replace the original. If the rename, or any of the file operations, fail the original settings file remains in place. --- .../src/DomainServerSettingsManager.cpp | 57 ++++++++++++------- 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/domain-server/src/DomainServerSettingsManager.cpp b/domain-server/src/DomainServerSettingsManager.cpp index 780fad15f2..0f6807d5a0 100644 --- a/domain-server/src/DomainServerSettingsManager.cpp +++ b/domain-server/src/DomainServerSettingsManager.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -1714,28 +1715,44 @@ void DomainServerSettingsManager::sortPermissions() { } void DomainServerSettingsManager::persistToFile() { - sortPermissions(); - - // make sure we have the dir the settings file is supposed to live in - QFileInfo settingsFileInfo(_configMap.getUserConfigFilename()); - - if (!settingsFileInfo.dir().exists()) { - settingsFileInfo.dir().mkpath("."); - } - - QFile settingsFile(_configMap.getUserConfigFilename()); - - if (settingsFile.open(QIODevice::WriteOnly)) { - // take a read lock so we can grab the config and write it to file - QReadLocker locker(&_settingsLock); - settingsFile.write(QJsonDocument::fromVariant(_configMap.getConfig()).toJson()); - } else { - qCritical("Could not write to JSON settings file. Unable to persist settings."); - - // failed to write, reload whatever the current config state is - // with a write lock since we're about to overwrite the config map + QString settingsFilename = _configMap.getUserConfigFilename(); + QDir settingsDir = QFileInfo(settingsFilename).dir(); + if (!settingsDir.exists() && !settingsDir.mkpath(".")) { + // If the path already exists when the `mkpath` method is + // called, it will return true. It will only return false if the + // path doesn't exist after the call returns. + qCritical("Could not create the settings file parent directory. Unable to persist settings."); QWriteLocker locker(&_settingsLock); _configMap.loadConfig(); + return; + } + QSaveFile settingsFile(settingsFilename); + if (!settingsFile.open(QIODevice::WriteOnly)) { + qCritical("Could not open the JSON settings file. Unable to persist settings."); + QWriteLocker locker(&_settingsLock); + _configMap.loadConfig(); + return; + } + + sortPermissions(); + + QVariantMap conf; + { + QReadLocker locker(&_settingsLock); + conf = _configMap.getConfig(); + } + QByteArray json = QJsonDocument::fromVariant(conf).toJson(); + if (settingsFile.write(json) == -1) { + qCritical("Could not write to JSON settings file. Unable to persist settings."); + QWriteLocker locker(&_settingsLock); + _configMap.loadConfig(); + return; + } + if (!settingsFile.commit()) { + qCritical("Could not commit writes to JSON settings file. Unable to persist settings."); + QWriteLocker locker(&_settingsLock); + _configMap.loadConfig(); + return; // defend against future code } } From 0b472a9f0273d024162c64d8c3cb09c90e1ae09e Mon Sep 17 00:00:00 2001 From: Ken Cooke Date: Sat, 16 Feb 2019 11:19:18 -0800 Subject: [PATCH 02/50] Protect against lost counter underflow in networking stats --- libraries/networking/src/SequenceNumberStats.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/SequenceNumberStats.cpp b/libraries/networking/src/SequenceNumberStats.cpp index e11fcf22d4..a451701502 100644 --- a/libraries/networking/src/SequenceNumberStats.cpp +++ b/libraries/networking/src/SequenceNumberStats.cpp @@ -142,8 +142,10 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui if (wantExtraDebugging) { qCDebug(networking) << "found it in _missingSet"; } - _stats._lost--; - _stats._recovered++; + if (_stats._lost > 0) { + _stats._lost--; + _stats._recovered++; + } } else { // this late seq num is not in our missing set. it is possibly a duplicate, or possibly a late // packet that should have arrived before our first received packet. we'll count these From 7359d42b5c5f80478bf4bdfc857c999796f322e9 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 1 May 2019 08:17:27 +1200 Subject: [PATCH 03/50] Window JSDoc update --- .../src/scripting/WindowScriptingInterface.h | 149 ++++++++---------- .../src/material-networking/TextureCache.cpp | 26 +++ 2 files changed, 92 insertions(+), 83 deletions(-) diff --git a/interface/src/scripting/WindowScriptingInterface.h b/interface/src/scripting/WindowScriptingInterface.h index 77b586ec70..9a314cad6a 100644 --- a/interface/src/scripting/WindowScriptingInterface.h +++ b/interface/src/scripting/WindowScriptingInterface.h @@ -23,9 +23,9 @@ #include /**jsdoc - * The Window API provides various facilities not covered elsewhere: window dimensions, window focus, normal or entity camera - * view, clipboard, announcements, user connections, common dialog boxes, snapshots, file import, domain changes, domain - * physics. + * The Window API provides various facilities not covered elsewhere, including: window dimensions, window focus, + * camera view, announcements, user connections, common dialog boxes, snapshots, file import, domain navigation, domain changes, + * domain physics, OS clipboard, build number. * * @namespace Window * @@ -37,13 +37,13 @@ * chrome), in pixels. Read-only. * @property {number} innerHeight - The height of the drawable area of the Interface window (i.e., without borders or other * chrome), in pixels. Read-only. - * @property {object} location - Provides facilities for working with your current metaverse location. See {@link location}. * @property {number} x - The x display coordinate of the top left corner of the drawable area of the Interface window. * Read-only. * @property {number} y - The y display coordinate of the top left corner of the drawable area of the Interface window. * Read-only. - * @property {boolean} interstitialModeEnabled=true - true if the interstitial graphics are displayed when the + * @property {boolean} interstitialModeEnabled=false - true if the interstitial graphics are displayed when a * domain is loading, otherwise false. + * @property {location} location - Provides facilities for working with your current metaverse location. */ class WindowScriptingInterface : public QObject, public Dependency { @@ -65,27 +65,27 @@ public: public slots: /**jsdoc - * Check if the Interface window has focus. + * Checks whether the Interface window has focus. * @function Window.hasFocus - * @returns {boolean} true if the Interface window has focus, otherwise false. + * @returns {boolean} true if the Interface window has focus, false if it doesn't. */ QScriptValue hasFocus(); /**jsdoc - * Make the Interface window have focus. On Windows, if Interface doesn't already have focus, the task bar icon flashes to + * Makes the Interface window have focus. On Windows, if Interface doesn't already have focus, the task bar icon flashes to * indicate that Interface wants attention but focus isn't taken away from the application that the user is using. * @function Window.setFocus */ void setFocus(); /**jsdoc - * Raise the Interface window if it is minimized. If raised, the window gains focus. + * Raises the Interface window if it is minimized. If raised, the window gains focus. * @function Window.raise */ void raise(); /**jsdoc - * Display a dialog with the specified message and an "OK" button. The dialog is non-modal; the script continues without + * Displays a dialog with the specified message and an "OK" button. The dialog is non-modal; the script continues without * waiting for a user response. * @function Window.alert * @param {string} [message=""] - The message to display. @@ -96,8 +96,7 @@ public slots: void alert(const QString& message = ""); /**jsdoc - * Prompt the user to confirm something. Displays a modal dialog with a message plus "Yes" and "No" buttons. - * responds. + * Prompts the user to confirm something. Displays a modal dialog with a message plus "Yes" and "No" buttons. * @function Window.confirm * @param {string} [message=""] - The question to display. * @returns {boolean} true if the user selects "Yes", otherwise false. @@ -108,7 +107,7 @@ public slots: QScriptValue confirm(const QString& message = ""); /**jsdoc - * Prompt the user to enter some text. Displays a modal dialog with a message and a text box, plus "OK" and "Cancel" + * Prompts the user to enter some text. Displays a modal dialog with a message and a text box, plus "OK" and "Cancel" * buttons. * @function Window.prompt * @param {string} message - The question to display. @@ -125,7 +124,7 @@ public slots: QScriptValue prompt(const QString& message, const QString& defaultText); /**jsdoc - * Prompt the user to enter some text. Displays a non-modal dialog with a message and a text box, plus "OK" and "Cancel" + * Prompts the user to enter some text. Displays a non-modal dialog with a message and a text box, plus "OK" and "Cancel" * buttons. A {@link Window.promptTextChanged|promptTextChanged} signal is emitted when the user OKs the dialog; no signal * is emitted if the user cancels the dialog. * @function Window.promptAsync @@ -143,7 +142,7 @@ public slots: void promptAsync(const QString& message = "", const QString& defaultText = ""); /**jsdoc - * Prompt the user to choose a directory. Displays a modal dialog that navigates the directory tree. + * Prompts the user to choose a directory. Displays a modal dialog that navigates the directory tree. * @function Window.browseDir * @param {string} [title=""] - The title to display at the top of the dialog. * @param {string} [directory=""] - The initial directory to start browsing at. @@ -155,7 +154,7 @@ public slots: QScriptValue browseDir(const QString& title = "", const QString& directory = ""); /**jsdoc - * Prompt the user to choose a directory. Displays a non-modal dialog that navigates the directory tree. A + * Prompts the user to choose a directory. Displays a non-modal dialog that navigates the directory tree. A * {@link Window.browseDirChanged|browseDirChanged} signal is emitted when a directory is chosen; no signal is emitted if * the user cancels the dialog. * @function Window.browseDirAsync @@ -173,7 +172,7 @@ public slots: void browseDirAsync(const QString& title = "", const QString& directory = ""); /**jsdoc - * Prompt the user to choose a file. Displays a modal dialog that navigates the directory tree. + * Prompts the user to choose a file. Displays a modal dialog that navigates the directory tree. * @function Window.browse * @param {string} [title=""] - The title to display at the top of the dialog. * @param {string} [directory=""] - The initial directory to start browsing at. @@ -187,7 +186,7 @@ public slots: QScriptValue browse(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Prompt the user to choose a file. Displays a non-modal dialog that navigates the directory tree. A + * Prompts the user to choose a file. Displays a non-modal dialog that navigates the directory tree. A * {@link Window.browseChanged|browseChanged} signal is emitted when a file is chosen; no signal is emitted if the user * cancels the dialog. * @function Window.browseAsync @@ -207,7 +206,7 @@ public slots: void browseAsync(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Prompt the user to specify the path and name of a file to save to. Displays a model dialog that navigates the directory + * Prompts the user to specify the path and name of a file to save to. Displays a model dialog that navigates the directory * tree and allows the user to type in a file name. * @function Window.save * @param {string} [title=""] - The title to display at the top of the dialog. @@ -223,7 +222,7 @@ public slots: QScriptValue save(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Prompt the user to specify the path and name of a file to save to. Displays a non-model dialog that navigates the + * Prompts the user to specify the path and name of a file to save to. Displays a non-model dialog that navigates the * directory tree and allows the user to type in a file name. A {@link Window.saveFileChanged|saveFileChanged} signal is * emitted when a file is specified; no signal is emitted if the user cancels the dialog. * @function Window.saveAsync @@ -243,7 +242,7 @@ public slots: void saveAsync(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Prompt the user to choose an Asset Server item. Displays a modal dialog that navigates the tree of assets on the Asset + * Prompts the user to choose an Asset Server item. Displays a modal dialog that navigates the tree of assets on the Asset * Server. * @function Window.browseAssets * @param {string} [title=""] - The title to display at the top of the dialog. @@ -258,8 +257,8 @@ public slots: QScriptValue browseAssets(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Prompt the user to choose an Asset Server item. Displays a non-modal dialog that navigates the tree of assets on the - * Asset Server. A {@link Window.assetsDirChanged|assetsDirChanged} signal is emitted when an asset is chosen; no signal is + * Prompts the user to choose an Asset Server item. Displays a non-modal dialog that navigates the tree of assets on the + * Asset Server. An {@link Window.assetsDirChanged|assetsDirChanged} signal is emitted when an asset is chosen; no signal is * emitted if the user cancels the dialog. * @function Window.browseAssetsAsync * @param {string} [title=""] - The title to display at the top of the dialog. @@ -278,7 +277,7 @@ public slots: void browseAssetsAsync(const QString& title = "", const QString& directory = "", const QString& nameFilter = ""); /**jsdoc - * Open the Asset Browser dialog. If a file to upload is specified, the user is prompted to enter the folder and name to + * Opens the Asset Browser dialog. If a file to upload is specified, the user is prompted to enter the folder and name to * map the file to on the asset server. * @function Window.showAssetServer * @param {string} [uploadFile=""] - The path and name of a file to upload to the asset server. @@ -290,14 +289,14 @@ public slots: void showAssetServer(const QString& upload = ""); /**jsdoc - * Get Interface's build number. + * Gets Interface's build number. * @function Window.checkVersion * @returns {string} Interface's build number. */ QString checkVersion(); /**jsdoc - * Get the signature for Interface's protocol version. + * Gets the signature for Interface's protocol version. * @function Window.protocolSignature * @returns {string} A string uniquely identifying the version of the metaverse protocol that Interface is using. */ @@ -317,25 +316,19 @@ public slots: * are emitted. The path to store the snapshots and the length of the animated GIF to capture are specified in Settings > * General > Snapshots. * - * If user has supplied a specific filename for the snapshot: - * If the user's requested filename has a suffix that's contained within SUPPORTED_IMAGE_FORMATS, - * DON'T append ".jpg" to the filename. QT will save the image in the format associated with the - * filename's suffix. - * If you want lossless Snapshots, supply a `.png` filename. Otherwise, use `.jpeg` or `.jpg`. - * Otherwise, ".jpg" is appended to the user's requested filename so that the image is saved in JPG format. - * If the user hasn't supplied a specific filename for the snapshot: - * Save the snapshot in JPG format according to FILENAME_PATH_FORMAT * @function Window.takeSnapshot * @param {boolean} [notify=true] - This value is passed on through the {@link Window.stillSnapshotTaken|stillSnapshotTaken} * signal. * @param {boolean} [includeAnimated=false] - If true, a moving image is captured as an animated GIF in addition * to a still image. - * @param {number} [aspectRatio=0] - The width/height ratio of the snapshot required. If the value is 0 the + * @param {number} [aspectRatio=0] - The width/height ratio of the snapshot required. If the value is 0, the * full resolution is used (window dimensions in desktop mode; HMD display dimensions in HMD mode), otherwise one of the * dimensions is adjusted in order to match the aspect ratio. - * @param {string} [filename=""] - If this parameter is not given, the image will be saved as "hifi-snap-by-<user name>-YYYY-MM-DD_HH-MM-SS". - * If this parameter is "" then the image will be saved as ".jpg". - * Otherwise, the image will be saved to this filename, with an appended ".jpg". + * @param {string} [filename=""] - If a filename is not provided, the image is saved as "hifi-snap-by-<user + * name>-on-YYYY-MM-DD_HH-MM-SS".
+ * Still images are saved in JPEG or PNG format according to the extension provided — ".jpg", + * ".jpeg", or ".png" — or if not provided then in JPEG format with an extension of + * ".jpg". Animated images are saved in GIF format. * * @example Using the snapshot function and signals. * function onStillSnapshotTaken(path, notify) { @@ -368,9 +361,11 @@ public slots: * @function Window.takeSecondaryCameraSnapshot * @param {boolean} [notify=true] - This value is passed on through the {@link Window.stillSnapshotTaken|stillSnapshotTaken} * signal. - * @param {string} [filename=""] - If this parameter is not given, the image will be saved as "hifi-snap-by-<user name>-YYYY-MM-DD_HH-MM-SS". - * If this parameter is "" then the image will be saved as ".jpg". - * Otherwise, the image will be saved to this filename, with an appended ".jpg". + * @param {string} [filename=""] - If a filename is not provided, the image is saved as "hifi-snap-by-<user + * name>-on-YYYY-MM-DD_HH-MM-SS".
+ * Images are saved in JPEG or PNG format according to the extension provided — ".jpg", + * ".jpeg", or ".png" — or if not provided then in JPEG format with an extension of + * ".jpg". */ void takeSecondaryCameraSnapshot(const bool& notify = true, const QString& filename = QString()); @@ -380,17 +375,19 @@ public slots: * @function Window.takeSecondaryCamera360Snapshot * @param {Vec3} cameraPosition - The position of the camera for the snapshot. * @param {boolean} [cubemapOutputFormat=false] - If true then the snapshot is saved as a cube map image, - * otherwise is saved as an equirectangular image. + * otherwise it is saved as an equirectangular image. * @param {boolean} [notify=true] - This value is passed on through the {@link Window.stillSnapshotTaken|stillSnapshotTaken} * signal. - * @param {string} [filename=""] - If this parameter is not supplied, the image will be saved as "hifi-snap-by-<user name>-YYYY-MM-DD_HH-MM-SS". - * If this parameter is "" then the image will be saved as ".jpg". - * Otherwise, the image will be saved to this filename, with an appended ".jpg". + * @param {string} [filename=""] - If a filename is not provided, the image is saved as "hifi-snap-by-<user + * name>-on-YYYY-MM-DD_HH-MM-SS".
+ * Images are saved in JPEG or PNG format according to the extension provided — ".jpg", + * ".jpeg", or ".png" — or if not provided then in JPEG format with an extension of + * ".jpg". */ void takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition, const bool& cubemapOutputFormat = false, const bool& notify = true, const QString& filename = QString()); /**jsdoc - * Emit a {@link Window.connectionAdded|connectionAdded} or a {@link Window.connectionError|connectionError} signal that + * Emits a {@link Window.connectionAdded|connectionAdded} or a {@link Window.connectionError|connectionError} signal that * indicates whether or not a user connection was successfully made using the Web API. * @function Window.makeConnection * @param {boolean} success - If true then {@link Window.connectionAdded|connectionAdded} is emitted, otherwise @@ -400,7 +397,7 @@ public slots: void makeConnection(bool success, const QString& userNameOrError); /**jsdoc - * Display a notification message. Notifications are displayed in panels by the default script, nofications.js. An + * Displays a notification message. Notifications are displayed in panels by the default script, nofications.js. An * {@link Window.announcement|announcement} signal is emitted when this function is called. * @function Window.displayAnnouncement * @param {string} message - The announcement message. @@ -416,7 +413,7 @@ public slots: void displayAnnouncement(const QString& message); /**jsdoc - * Prepare a snapshot ready for sharing. A {@link Window.snapshotShared|snapshotShared} signal is emitted when the snapshot + * Prepares a snapshot ready for sharing. A {@link Window.snapshotShared|snapshotShared} signal is emitted when the snapshot * has been prepared. * @function Window.shareSnapshot * @param {string} path - The path and name of the image file to share. @@ -425,7 +422,7 @@ public slots: void shareSnapshot(const QString& path, const QUrl& href = QUrl("")); /**jsdoc - * Check to see if physics is active for you in the domain you're visiting - there is a delay between your arrival at a + * Checks to see if physics is active for you in the domain you're visiting - there is a delay between your arrival at a * domain and physics becoming active for you in that domain. * @function Window.isPhysicsEnabled * @returns {boolean} true if physics is currently active for you, otherwise false. @@ -448,39 +445,16 @@ public slots: bool isPhysicsEnabled(); /**jsdoc - * Set what to show on the PC display: normal view or entity camera view. The entity camera is configured using + * Sets what to show on the PC display. For entity camera view, the entity camera is configured using * {@link Camera.setCameraEntity} and {@link Camera|Camera.mode}. * @function Window.setDisplayTexture * @param {Window.DisplayTexture} texture - The view to display. * @returns {boolean} true if the display texture was successfully set, otherwise false. */ - // See spectatorCamera.js for Valid parameter values. - /**jsdoc - *

The views that may be displayed on the PC display.

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
ValueView Displayed
""Normal view.
"resource://spectatorCameraFrame"Entity camera view.
- * @typedef {string} Window.DisplayTexture - */ bool setDisplayTexture(const QString& name); /**jsdoc - * Check if a 2D point is within the desktop window if in desktop mode, or the drawable area of the HUD overlay if in HMD + * Checks if a 2D point is within the desktop window if in desktop mode, or the drawable area of the HUD overlay if in HMD * mode. * @function Window.isPointOnDesktopWindow * @param {Vec2} point - The point to check. @@ -489,7 +463,7 @@ public slots: bool isPointOnDesktopWindow(QVariant point); /**jsdoc - * Get the size of the drawable area of the Interface window if in desktop mode or the HMD rendering surface if in HMD mode. + * Gets the size of the drawable area of the Interface window if in desktop mode or the HMD rendering surface if in HMD mode. * @function Window.getDeviceSize * @returns {Vec2} The width and height of the Interface window or HMD rendering surface, in pixels. */ @@ -503,7 +477,7 @@ public slots: int getLastDomainConnectionError() const; /**jsdoc - * Open a non-modal message box that can have a variety of button combinations. See also, + * Opens a non-modal message box that can have a variety of button combinations. See also, * {@link Window.updateMessageBox|updateMessageBox} and {@link Window.closeMessageBox|closeMessageBox}. * @function Window.openMessageBox * @param {string} title - The title to display for the message box. @@ -535,17 +509,21 @@ public slots: int openMessageBox(QString title, QString text, int buttons, int defaultButton); /**jsdoc - * Open a URL in the Interface window or other application, depending on the URL's scheme. The following schemes are supported: - * hifi (navigate to the URL in Interface), hifiapp (open a system app in Interface). Other schemes will either be handled by the OS - * (e.g. http, https, mailto) or will create a confirmation dialog asking the user to confirm that they want to try to open - * the URL. + * Opens a URL in the Interface window or other application, depending on the URL's scheme. The following schemes are + * supported:
+ *
    + *
  • hifi: Navigate to the URL in Interface.
  • + *
  • hifiapp: Open a system app in Interface.
  • + *
+ * Other schemes will either be handled by the OS (e.g. http, https, or mailto) or + * will display a dialog asking the user to confirm that they want to try to open the URL. * @function Window.openUrl * @param {string} url - The URL to open. */ void openUrl(const QUrl& url); /**jsdoc - * Open an Android activity and optionally return back to the scene when the activity is completed. Android only. + * Opens an Android activity and optionally return back to the scene when the activity is completed. Android only. * @function Window.openAndroidActivity * @param {string} activityName - The name of the activity to open: one of "Home", "Login", or * "Privacy Policy". @@ -555,7 +533,7 @@ public slots: void openAndroidActivity(const QString& activityName, const bool backToScene); /**jsdoc - * Update the content of a message box that was opened with {@link Window.openMessageBox|openMessageBox}. + * Updates the content of a message box that was opened with {@link Window.openMessageBox|openMessageBox}. * @function Window.updateMessageBox * @param {number} id - The ID of the message box. * @param {string} title - The title to display for the message box. @@ -567,12 +545,17 @@ public slots: void updateMessageBox(int id, QString title, QString text, int buttons, int defaultButton); /**jsdoc - * Close a message box that was opened with {@link Window.openMessageBox|openMessageBox}. + * Closes a message box that was opened with {@link Window.openMessageBox|openMessageBox}. * @function Window.closeMessageBox * @param {number} id - The ID of the message box. */ void closeMessageBox(int id); + /**jsdoc + * @function Window.domainLoadingProgress + * @returns {number} Progress. + * @deprecated This function is deprecated and will be removed. + */ float domainLoadingProgress(); private slots: diff --git a/libraries/material-networking/src/material-networking/TextureCache.cpp b/libraries/material-networking/src/material-networking/TextureCache.cpp index b3192eac6e..d8ad362de1 100644 --- a/libraries/material-networking/src/material-networking/TextureCache.cpp +++ b/libraries/material-networking/src/material-networking/TextureCache.cpp @@ -64,6 +64,32 @@ const std::string TextureCache::KTX_DIRNAME{ "ktx_cache" }; #endif const std::string TextureCache::KTX_EXT { "ktx" }; +/**jsdoc + *

The views that may be displayed on the PC display.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ValueView Displayed
""Normal view.
"resource://hmdPreviewFrame"HMD preview.
"resource://spectatorCameraFrame"Entity camera view.
+ * @typedef {string} Window.DisplayTexture + */ static const QString RESOURCE_SCHEME = "resource"; static const QUrl SPECTATOR_CAMERA_FRAME_URL("resource://spectatorCameraFrame"); static const QUrl HMD_PREVIEW_FRAME_URL("resource://hmdPreviewFrame"); From 9df873cff5b201c45bdf99abbf630a0683714453 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 1 May 2019 08:17:43 +1200 Subject: [PATCH 04/50] location JSDoc update --- libraries/networking/src/AddressManager.h | 44 +++++++++++------------ 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/libraries/networking/src/AddressManager.h b/libraries/networking/src/AddressManager.h index 3b95923634..48a245538d 100644 --- a/libraries/networking/src/AddressManager.h +++ b/libraries/networking/src/AddressManager.h @@ -32,11 +32,11 @@ const QString INDEX_PATH = "/"; const QString GET_PLACE = "/api/v1/places/%1"; /**jsdoc - * The location API provides facilities related to your current location in the metaverse. + * The location API provides facilities related to your current location in the metaverse. * - *
Getter/Setter
+ *

Getter/Setter

*

You can get and set your current metaverse address by directly reading a string value from and writing a string value to - * the location object. This is an alternative to using the location.href property or this object's + * the location object. This is an alternative to using the location.href property or other object * functions.

* * @namespace location @@ -186,19 +186,19 @@ public: public slots: /**jsdoc - * Go to a specified metaverse address. + * Takes you to a specified metaverse address. * @function location.handleLookupString * @param {string} address - The address to go to: a "hifi://" address, an IP address (e.g., * "127.0.0.1" or "localhost"), a domain name, a named path on a domain (starts with * "/"), a position or position and orientation, or a user (starts with "@"). - * @param {boolean} fromSuggestions=false - Set to true if the address is obtained from the "Goto" dialog. + * @param {boolean} [fromSuggestions=false] - Set to true if the address is obtained from the "Goto" dialog. * Helps ensure that user's location history is correctly maintained. */ void handleLookupString(const QString& lookupString, bool fromSuggestions = false); /**jsdoc - * Go to a position and orientation resulting from a lookup for a named path in the domain (set in the domain server's - * settings). + * Takes you to a position and orientation resulting from a lookup for a named path in the domain (set in the domain + * server's settings). * @function location.goToViewpointForPath * @param {string} path - The position and orientation corresponding to the named path. * @param {string} namedPath - The named path that was looked up on the server. @@ -212,29 +212,29 @@ public slots: { return handleViewpoint(viewpointString, false, DomainPathResponse, false, pathString); } /**jsdoc - * Go back to the previous location in your navigation history, if there is one. + * Takes you back to the previous location in your navigation history, if there is one. * @function location.goBack */ void goBack(); /**jsdoc - * Go forward to the next location in your navigation history, if there is one. + * Takes you forward to the next location in your navigation history, if there is one. * @function location.goForward */ void goForward(); /**jsdoc - * Go to the local Sandbox server that's running on the same PC as Interface. + * Takes you to the local Sandbox server that's running on the same PC as Interface. * @function location.goToLocalSandbox - * @param {string} path="" - The position and orientation to go to (e.g., "/0,0,0"). - * @param {location.LookupTrigger} trigger=StartupFromSettings - The reason for the function call. Helps ensure that user's + * @param {string} [path=""] - The position and orientation to go to (e.g., "/0,0,0"). + * @param {location.LookupTrigger} [trigger=StartupFromSettings] - The reason for the function call. Helps ensure that user's * location history is correctly maintained. */ void goToLocalSandbox(QString path = "", LookupTrigger trigger = LookupTrigger::StartupFromSettings) { handleUrl(SANDBOX_HIFI_ADDRESS + path, trigger); } /**jsdoc - * Go to the default "welcome" metaverse address. + * Takes you to the default "welcome" metaverse address. * @function location.goToEntry * @param {location.LookupTrigger} trigger=StartupFromSettings - The reason for the function call. Helps ensure that user's * location history is correctly maintained. @@ -242,28 +242,28 @@ public slots: void goToEntry(LookupTrigger trigger = LookupTrigger::StartupFromSettings) { handleUrl(DEFAULT_HIFI_ADDRESS, trigger); } /**jsdoc - * Go to the specified user's location. + * Takes you to the specified user's location. * @function location.goToUser * @param {string} username - The user's username. - * @param {boolean} matchOrientation=true - If true then go to a location just in front of the user and turn to face + * @param {boolean} [matchOrientation=true] - If true then go to a location just in front of the user and turn to face * them, otherwise go to the user's exact location and orientation. */ void goToUser(const QString& username, bool shouldMatchOrientation = true); /**jsdoc - * Go to the last address tried. This will be the last URL tried from location.handleLookupString + * Takes you to the last address tried. This will be the last URL tried from location.handleLookupString * @function location.goToLastAddress */ void goToLastAddress() { handleUrl(_lastVisitedURL, LookupTrigger::AttemptedRefresh); } /**jsdoc - * Returns if going back is possible. + * Checks if going back is possible. * @function location.canGoBack */ bool canGoBack() const; /**jsdoc - * Refresh the current address, e.g., after connecting to a domain in order to position the user to the desired location. + * Refreshes the current address, e.g., after connecting to a domain in order to position the user to the desired location. * @function location.refreshPreviousLookup * @deprecated This function is deprecated and will be removed. */ @@ -272,27 +272,27 @@ public slots: void refreshPreviousLookup(); /**jsdoc - * Update your current metaverse location in Interface's {@link Settings} file as your last-known address. This can be used + * Updates your current metaverse location in Interface's {@link Settings} file as your last-known address. This can be used * to ensure that you start up at that address if you exit Interface without a later address automatically being saved. * @function location.storeCurrentAddress */ void storeCurrentAddress(); /**jsdoc - * Copy your current metaverse address (i.e., location.href property value) to the OS clipboard. + * Copies your current metaverse address (i.e., location.href property value) to the OS clipboard. * @function location.copyAddress */ void copyAddress(); /**jsdoc - * Copy your current metaverse location and orientation (i.e., location.pathname property value) to the OS + * Copies your current metaverse location and orientation (i.e., location.pathname property value) to the OS * clipboard. * @function location.copyPath */ void copyPath(); /**jsdoc - * Retrieve and remember the place name for the given domain ID if the place name is not already known. + * Retrieves and remembers the place name for the given domain ID if the place name is not already known. * @function location.lookupShareableNameForDomainID * @param {Uuid} domainID - The UUID of the domain. * @deprecated This function is deprecated and will be removed. From e3ff0bbcdf3873a7907b34ac10f27a79d6ea81d1 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 1 May 2019 08:18:00 +1200 Subject: [PATCH 05/50] PlatformInfo JSDoc --- .../PlatformInfoScriptingInterface.h | 85 ++++++++++++------- 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/interface/src/scripting/PlatformInfoScriptingInterface.h b/interface/src/scripting/PlatformInfoScriptingInterface.h index 31f0058585..f4d91d1230 100644 --- a/interface/src/scripting/PlatformInfoScriptingInterface.h +++ b/interface/src/scripting/PlatformInfoScriptingInterface.h @@ -13,69 +13,90 @@ class QScriptValue; +/**jsdoc + * The PlatformInfo API provides information about the computer and controllers being used. + * + * @namespace PlatformInfo + * + * @hifi-interface + * @hifi-client-entity + * @hifi-avatar + */ class PlatformInfoScriptingInterface : public QObject { Q_OBJECT public slots: + /**jsdoc + * @function PlatformInfo.getInstance + * @deprecated This function is deprecated and will be removed. + */ static PlatformInfoScriptingInterface* getInstance(); /**jsdoc - * Returns the Operating Sytem type - * @function Test.getOperatingSystemType - * @returns {string} "WINDOWS", "MACOS" or "UNKNOWN" - */ + * Gets the operating system type. + * @function PlatformInfo.getOperatingSystemType + * @returns {string} "WINDOWS", "MACOS", or "UNKNOWN". + */ QString getOperatingSystemType(); /**jsdoc - * Returns the CPU brand - *function PlatformInfo.getCPUBrand() - * @returns {string} brand of CPU - */ + * Gets information on the CPU. + * @function PlatformInfo.getCPUBrand + * @returns {string} Information on the CPU. + * @example Report the CPU being used. + * print("CPU: " + PlatformInfo.getCPUBrand()); + * // Example: Intel(R) Core(TM) i7-7820HK CPU @ 2.90GHz + */ QString getCPUBrand(); /**jsdoc - * Returns the number of logical CPU cores - *function PlatformInfo.getNumLogicalCores() - * @returns {int} number of logical CPU cores - */ + * Gets the number of logical CPU cores. + * @function PlatformInfo.getNumLogicalCores + * @returns {number} The number of logical CPU cores. + */ unsigned int getNumLogicalCores(); /**jsdoc - * Returns the total system memory in megabyte - *function PlatformInfo.getTotalSystemMemory() - * @returns {int} size of memory in megabytes - */ + * Returns the total system memory in megabytes. + * @function PlatformInfo.getTotalSystemMemoryMB + * @returns {number} the total system memory in megabytes. + */ int getTotalSystemMemoryMB(); /**jsdoc - * Returns the graphics card type - * @function Test.getGraphicsCardType - * @returns {string} graphics card type - */ + * Gets the graphics card type. + * @function PlatformInfo.getGraphicsCardType + * @returns {string} The graphics card type. + */ QString getGraphicsCardType(); /**jsdoc - * Returns true if Oculus Rift is connected (looks for hand controllers) - * @function Window.hasRift - * @returns {boolean} true if running on Windows, otherwise false.*/ + * Checks whether Oculus Touch controllers are connected. + * @function PlatformInfo.hasRiftControllers + * @returns {boolean} true if Oculus Touch controllers are connected, false if they aren't. + */ bool hasRiftControllers(); /**jsdoc - * Returns true if HTC Vive is connected (looks for hand controllers) - * @function Window.hasRift - * @returns {boolean} true if running on Windows, otherwise false.*/ + * Checks whether Vive controllers are connected. + * @function PlatformInfo.hasViveControllers + * @returns {boolean} true if Vive controllers are connected, false if they aren't. + */ bool hasViveControllers(); /**jsdoc - * Returns true if device supports 3d HTML - * @function Window.has3DHTML - * @returns {boolean} true if device supports 3d HTML, otherwise false.*/ + * Checks whether HTML on 3D surfaces (e.g., Web entities) is supported. + * @function PlatformInfo.has3DHTML + * @returns {boolean} true if the current display supports HTML on 3D surfaces, false if it + * doesn't. + */ bool has3DHTML(); /**jsdoc - * Returns true if device is standalone - * @function Window.hasRift - * @returns {boolean} true if device is a standalone device, otherwise false.*/ + * Checks whether Interface is running on a stand-alone HMD device (CPU incorporated into the HMD display). + * @function PlatformInfo.isStandalone + * @returns {boolean} true if Interface is running on a stand-alone device, false if it isn't. + */ bool isStandalone(); }; From d8f6e923c754aa90e748f78c1d7d8b30915b7364 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 1 May 2019 08:18:17 +1200 Subject: [PATCH 06/50] Paths JSDoc update --- libraries/shared/src/PathUtils.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/PathUtils.h b/libraries/shared/src/PathUtils.h index cac5c58ca4..4ab6a79e22 100644 --- a/libraries/shared/src/PathUtils.h +++ b/libraries/shared/src/PathUtils.h @@ -19,7 +19,7 @@ #include "DependencyManager.h" /**jsdoc - * The Paths API provides absolute paths to the scripts and resources directories. + * The Paths API provides absolute paths to the scripts and resources directories. * * @namespace Paths * From f09f6ebd0853e3e2fe4cc645d60f36e571f83beb Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Thu, 2 May 2019 15:50:35 -0700 Subject: [PATCH 07/50] initial interface setup for platform --- interface/CMakeLists.txt | 2 +- interface/src/Application.cpp | 1937 ++++++++++++------------ interface/src/Application.h | 3 + libraries/platform/CMakeLists.txt | 3 + libraries/platform/src/WINPlatform.cpp | 23 + libraries/platform/src/WINPlatform.h | 21 + libraries/platform/src/platform.cpp | 39 + libraries/platform/src/platform.h | 33 + 8 files changed, 1069 insertions(+), 992 deletions(-) create mode 100644 libraries/platform/CMakeLists.txt create mode 100644 libraries/platform/src/WINPlatform.cpp create mode 100644 libraries/platform/src/WINPlatform.h create mode 100644 libraries/platform/src/platform.cpp create mode 100644 libraries/platform/src/platform.h diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index bb8ebbd2a0..cd329e109a 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -209,7 +209,7 @@ link_hifi_libraries( model-networking model-baker entities avatars trackers audio audio-client animation script-engine physics render-utils entities-renderer avatars-renderer ui qml auto-updater midi - controllers plugins image trackers + controllers plugins image trackers platform ui-plugins display-plugins input-plugins # Platform specific GL libraries ${PLATFORM_GL_BACKEND} diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index dcc91a66fc..8f864cb88a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -9,7 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - #include "Application.h" #include @@ -51,7 +50,6 @@ #include #include - #include #include #include @@ -195,8 +193,6 @@ #include "scripting/KeyboardScriptingInterface.h" #include "scripting/RefreshRateScriptingInterface.h" - - #if defined(Q_OS_MAC) || defined(Q_OS_WIN) #include "SpeechRecognizer.h" #endif @@ -245,7 +241,7 @@ #include "webbrowser/WebBrowserSuggestionsEngine.h" #include - +#include #include "AboutUtil.h" #include @@ -267,7 +263,7 @@ // On Windows PC, NVidia Optimus laptop, we want to enable NVIDIA GPU // FIXME seems to be broken. extern "C" { - _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; +_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } #endif @@ -280,6 +276,8 @@ extern "C" { Q_LOGGING_CATEGORY(trace_app_input_mouse, "trace.app.input.mouse") +#define PLATFORM 1 + using namespace std; static QTimer locationUpdateTimer; @@ -336,9 +334,9 @@ static const float INITIAL_QUERY_RADIUS = 10.0f; // priority radius for entitie static const QString DESKTOP_LOCATION = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); -Setting::Handle maxOctreePacketsPerSecond{"maxOctreePPS", DEFAULT_MAX_OCTREE_PPS}; +Setting::Handle maxOctreePacketsPerSecond{ "maxOctreePPS", DEFAULT_MAX_OCTREE_PPS }; -Setting::Handle loginDialogPoppedUp{"loginDialogPoppedUp", false}; +Setting::Handle loginDialogPoppedUp{ "loginDialogPoppedUp", false }; static const QUrl AVATAR_INPUTS_BAR_QML = PathUtils::qmlUrl("AvatarInputsBar.qml"); static const QUrl MIC_BAR_APPLICATION_QML = PathUtils::qmlUrl("hifi/audio/MicBarApplication.qml"); @@ -349,7 +347,7 @@ static const QString NO_MOVEMENT_MAPPING_NAME = "Standard to Action (No Movement static const QString NO_MOVEMENT_MAPPING_JSON = PathUtils::resourcesPath() + "/controllers/standard_nomovement.json"; static const QString MARKETPLACE_CDN_HOSTNAME = "mpassets.highfidelity.com"; -static const int INTERVAL_TO_CHECK_HMD_WORN_STATUS = 500; // milliseconds +static const int INTERVAL_TO_CHECK_HMD_WORN_STATUS = 500; // milliseconds static const QString DESKTOP_DISPLAY_PLUGIN_NAME = "Desktop"; static const QString ACTIVE_DISPLAY_PLUGIN_SETTING_NAME = "activeDisplayPlugin"; static const QString SYSTEM_TABLET = "com.highfidelity.interface.tablet.system"; @@ -360,26 +358,25 @@ static const float FOCUS_HIGHLIGHT_EXPANSION_FACTOR = 1.05f; #if defined(Q_OS_ANDROID) static const QString TESTER_FILE = "/sdcard/_hifi_test_device.txt"; #endif -const std::vector> Application::_acceptedExtensions { - { SVO_EXTENSION, &Application::importSVOFromURL }, - { SVO_JSON_EXTENSION, &Application::importSVOFromURL }, - { AVA_JSON_EXTENSION, &Application::askToWearAvatarAttachmentUrl }, - { JSON_EXTENSION, &Application::importJSONFromURL }, - { JS_EXTENSION, &Application::askToLoadScript }, - { FST_EXTENSION, &Application::askToSetAvatarUrl }, - { JSON_GZ_EXTENSION, &Application::askToReplaceDomainContent }, - { CONTENT_ZIP_EXTENSION, &Application::askToReplaceDomainContent }, - { ZIP_EXTENSION, &Application::importFromZIP }, - { JPG_EXTENSION, &Application::importImage }, - { PNG_EXTENSION, &Application::importImage } -}; +const std::vector> + Application::_acceptedExtensions{ { SVO_EXTENSION, &Application::importSVOFromURL }, + { SVO_JSON_EXTENSION, &Application::importSVOFromURL }, + { AVA_JSON_EXTENSION, &Application::askToWearAvatarAttachmentUrl }, + { JSON_EXTENSION, &Application::importJSONFromURL }, + { JS_EXTENSION, &Application::askToLoadScript }, + { FST_EXTENSION, &Application::askToSetAvatarUrl }, + { JSON_GZ_EXTENSION, &Application::askToReplaceDomainContent }, + { CONTENT_ZIP_EXTENSION, &Application::askToReplaceDomainContent }, + { ZIP_EXTENSION, &Application::importFromZIP }, + { JPG_EXTENSION, &Application::importImage }, + { PNG_EXTENSION, &Application::importImage } }; class DeadlockWatchdogThread : public QThread { public: static const unsigned long HEARTBEAT_UPDATE_INTERVAL_SECS = 1; - static const unsigned long MAX_HEARTBEAT_AGE_USECS = 120 * USECS_PER_SECOND; // 2 mins with no checkin probably a deadlock - static const int WARNING_ELAPSED_HEARTBEAT = 500 * USECS_PER_MSEC; // warn if elapsed heartbeat average is large - static const int HEARTBEAT_SAMPLES = 100000; // ~5 seconds worth of samples + static const unsigned long MAX_HEARTBEAT_AGE_USECS = 120 * USECS_PER_SECOND; // 2 mins with no checkin probably a deadlock + static const int WARNING_ELAPSED_HEARTBEAT = 500 * USECS_PER_MSEC; // warn if elapsed heartbeat average is large + static const int HEARTBEAT_SAMPLES = 100000; // ~5 seconds worth of samples // Set the heartbeat on launch DeadlockWatchdogThread() { @@ -387,14 +384,10 @@ public: // Give the heartbeat an initial value _heartbeat = usecTimestampNow(); _paused = false; - connect(qApp, &QCoreApplication::aboutToQuit, [this] { - _quit = true; - }); + connect(qApp, &QCoreApplication::aboutToQuit, [this] { _quit = true; }); } - void setMainThreadID(Qt::HANDLE threadID) { - _mainThreadID = threadID; - } + void setMainThreadID(Qt::HANDLE threadID) { _mainThreadID = threadID; } static void updateHeartbeat() { auto now = usecTimestampNow(); @@ -415,9 +408,7 @@ public: lambda(); resume(); } - static void pause() { - _paused = true; - } + static void pause() { _paused = true; } static void resume() { // Update the heartbeat BEFORE resuming the checks @@ -432,55 +423,49 @@ public: if (_paused) { continue; } - uint64_t lastHeartbeat = _heartbeat; // sample atomic _heartbeat, because we could context switch away and have it updated on us + uint64_t lastHeartbeat = + _heartbeat; // sample atomic _heartbeat, because we could context switch away and have it updated on us uint64_t now = usecTimestampNow(); auto lastHeartbeatAge = (now > lastHeartbeat) ? now - lastHeartbeat : 0; auto elapsedMovingAverage = _movingAverage.getAverage(); if (elapsedMovingAverage > _maxElapsedAverage) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage - << "maxElapsed:" << _maxElapsed - << "PREVIOUS maxElapsedAverage:" << _maxElapsedAverage + qCDebug(interfaceapp_deadlock) + << "DEADLOCK WATCHDOG WARNING:" + << "lastHeartbeatAge:" << lastHeartbeatAge << "elapsedMovingAverage:" << elapsedMovingAverage + << "maxElapsed:" << _maxElapsed << "PREVIOUS maxElapsedAverage:" << _maxElapsedAverage << "NEW maxElapsedAverage:" << elapsedMovingAverage << "** NEW MAX ELAPSED AVERAGE **" << "samples:" << _movingAverage.getSamples(); _maxElapsedAverage = elapsedMovingAverage; } if (lastHeartbeatAge > _maxElapsed) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage - << "PREVIOUS maxElapsed:" << _maxElapsed - << "NEW maxElapsed:" << lastHeartbeatAge << "** NEW MAX ELAPSED **" - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + qCDebug(interfaceapp_deadlock) + << "DEADLOCK WATCHDOG WARNING:" + << "lastHeartbeatAge:" << lastHeartbeatAge << "elapsedMovingAverage:" << elapsedMovingAverage + << "PREVIOUS maxElapsed:" << _maxElapsed << "NEW maxElapsed:" << lastHeartbeatAge << "** NEW MAX ELAPSED **" + << "maxElapsedAverage:" << _maxElapsedAverage << "samples:" << _movingAverage.getSamples(); _maxElapsed = lastHeartbeatAge; } if (elapsedMovingAverage > WARNING_ELAPSED_HEARTBEAT) { qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage << "** OVER EXPECTED VALUE **" - << "maxElapsed:" << _maxElapsed - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + << "lastHeartbeatAge:" << lastHeartbeatAge + << "elapsedMovingAverage:" << elapsedMovingAverage << "** OVER EXPECTED VALUE **" + << "maxElapsed:" << _maxElapsed << "maxElapsedAverage:" << _maxElapsedAverage + << "samples:" << _movingAverage.getSamples(); } if (lastHeartbeatAge > MAX_HEARTBEAT_AGE_USECS) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK DETECTED -- " - << "lastHeartbeatAge:" << lastHeartbeatAge - << "[ lastHeartbeat :" << lastHeartbeat - << "now:" << now << " ]" - << "elapsedMovingAverage:" << elapsedMovingAverage - << "maxElapsed:" << _maxElapsed - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + qCDebug(interfaceapp_deadlock) + << "DEADLOCK DETECTED -- " + << "lastHeartbeatAge:" << lastHeartbeatAge << "[ lastHeartbeat :" << lastHeartbeat << "now:" << now << " ]" + << "elapsedMovingAverage:" << elapsedMovingAverage << "maxElapsed:" << _maxElapsed + << "maxElapsedAverage:" << _maxElapsedAverage << "samples:" << _movingAverage.getSamples(); - // Don't actually crash in debug builds, in case this apparent deadlock is simply from - // the developer actively debugging code - #ifdef NDEBUG +// Don't actually crash in debug builds, in case this apparent deadlock is simply from +// the developer actively debugging code +#ifdef NDEBUG deadlockDetectionCrash(); - #endif +#endif } } } @@ -491,7 +476,7 @@ public: static std::atomic _maxElapsedAverage; static ThreadSafeMovingAverage _movingAverage; - bool _quit { false }; + bool _quit{ false }; Qt::HANDLE _mainThreadID = nullptr; }; @@ -516,8 +501,7 @@ bool isDomainURL(QUrl url) { // url.scheme() != HIFI_URL_SCHEME_HTTPS return false; } - if (url.path().endsWith(".json", Qt::CaseInsensitive) || - url.path().endsWith(".json.gz", Qt::CaseInsensitive)) { + if (url.path().endsWith(".json", Qt::CaseInsensitive) || url.path().endsWith(".json.gz", Qt::CaseInsensitive)) { return true; } return false; @@ -531,7 +515,7 @@ public: return staticInstance; } - bool nativeEventFilter(const QByteArray &eventType, void* msg, long* result) Q_DECL_OVERRIDE { + bool nativeEventFilter(const QByteArray& eventType, void* msg, long* result) Q_DECL_OVERRIDE { if (eventType == "windows_generic_MSG") { MSG* message = (MSG*)msg; @@ -559,12 +543,12 @@ public: } if (message->message == WM_DEVICECHANGE) { - const float MIN_DELTA_SECONDS = 2.0f; // de-bounce signal + const float MIN_DELTA_SECONDS = 2.0f; // de-bounce signal static float lastTriggerTime = 0.0f; const float deltaSeconds = secTimestampNow() - lastTriggerTime; lastTriggerTime = secTimestampNow(); if (deltaSeconds > MIN_DELTA_SECONDS) { - Midi::USBchanged(); // re-scan the MIDI bus + Midi::USBchanged(); // re-scan the MIDI bus } } } @@ -575,38 +559,35 @@ public: class LambdaEvent : public QEvent { std::function _fun; + public: - LambdaEvent(const std::function & fun) : - QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) { - } - LambdaEvent(std::function && fun) : - QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) { - } + LambdaEvent(const std::function& fun) : QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) {} + LambdaEvent(std::function&& fun) : QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) {} void call() const { _fun(); } }; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { - QString logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message); + QString logMessage = LogHandler::getInstance().printMessage((LogMsgType)type, context, message); if (!logMessage.isEmpty()) { #ifdef Q_OS_ANDROID - const char * local=logMessage.toStdString().c_str(); + const char* local = logMessage.toStdString().c_str(); switch (type) { case QtDebugMsg: - __android_log_write(ANDROID_LOG_DEBUG,"Interface",local); + __android_log_write(ANDROID_LOG_DEBUG, "Interface", local); break; case QtInfoMsg: - __android_log_write(ANDROID_LOG_INFO,"Interface",local); + __android_log_write(ANDROID_LOG_INFO, "Interface", local); break; case QtWarningMsg: - __android_log_write(ANDROID_LOG_WARN,"Interface",local); + __android_log_write(ANDROID_LOG_WARN, "Interface", local); break; case QtCriticalMsg: - __android_log_write(ANDROID_LOG_ERROR,"Interface",local); + __android_log_write(ANDROID_LOG_ERROR, "Interface", local); break; case QtFatalMsg: default: - __android_log_write(ANDROID_LOG_FATAL,"Interface",local); + __android_log_write(ANDROID_LOG_FATAL, "Interface", local); abort(); } #else @@ -615,21 +596,21 @@ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QSt } } - -class ApplicationMeshProvider : public scriptable::ModelProviderFactory { +class ApplicationMeshProvider : public scriptable::ModelProviderFactory { public: virtual scriptable::ModelProviderPointer lookupModelProvider(const QUuid& uuid) override { bool success; if (auto nestable = DependencyManager::get()->find(uuid, success).lock()) { auto type = nestable->getNestableType(); #ifdef SCRIPTABLE_MESH_DEBUG - qCDebug(interfaceapp) << "ApplicationMeshProvider::lookupModelProvider" << uuid << SpatiallyNestable::nestableTypeToString(type); + qCDebug(interfaceapp) << "ApplicationMeshProvider::lookupModelProvider" << uuid + << SpatiallyNestable::nestableTypeToString(type); #endif switch (type) { - case NestableType::Entity: - return getEntityModelProvider(static_cast(uuid)); - case NestableType::Avatar: - return getAvatarModelProvider(uuid); + case NestableType::Entity: + return getEntityModelProvider(static_cast(uuid)); + case NestableType::Avatar: + return getAvatarModelProvider(uuid); } } return nullptr; @@ -726,7 +707,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { // HRS: I could not figure out how to move these any earlier in startup, so when using this option, be sure to also supply // --allowMultipleInstances - auto reportAndQuit = [&](const char* commandSwitch, std::function report) { + auto reportAndQuit = [&](const char* commandSwitch, std::function report) { const char* reportfile = getCmdOption(argc, constArgv, commandSwitch); // Reports to the specified file, because stdout is set up to be captured for logging. if (reportfile) { @@ -734,9 +715,9 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { if (fp) { report(fp); fclose(fp); - if (!runningMarkerExisted) { // don't leave ours around + if (!runningMarkerExisted) { // don't leave ours around RunningMarker runingMarker(RUNNING_MARKER_FILENAME); - runingMarker.deleteRunningMarkerFile(); // happens in deleter, but making the side-effect explicit. + runingMarker.deleteRunningMarkerFile(); // happens in deleter, but making the side-effect explicit. } _exit(0); } @@ -746,9 +727,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { auto version = protocolVersionsSignatureBase64(); fputs(version.toLatin1().data(), fp); }); - reportAndQuit("--version", [&](FILE* fp) { - fputs(BuildInfo::VERSION.toLatin1().data(), fp); - }); + reportAndQuit("--version", [&](FILE* fp) { fputs(BuildInfo::VERSION.toLatin1().data(), fp); }); const char* portStr = getCmdOption(argc, constArgv, "--listenPort"); const int listenPort = portStr ? atoi(portStr) : INVALID_PORT; @@ -767,7 +746,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { qApp->setProperty(hifi::properties::STANDALONE, isStandalone); // Ignore any previous crashes if running from command line with a test script. - bool inTestMode { false }; + bool inTestMode{ false }; for (int i = 0; i < argc; ++i) { QString parameter(argv[i]); if (parameter == TEST_SCRIPT_COMMAND) { @@ -776,7 +755,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { } } - bool previousSessionCrashed { false }; + bool previousSessionCrashed{ false }; if (!inTestMode) { previousSessionCrashed = CrashRecoveryHandler::checkForResetSettings(runningMarkerExisted, suppressPrompt); } @@ -822,7 +801,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { audioDLLPath += "/audioWin7"; } QCoreApplication::addLibraryPath(audioDLLPath); -#endif +#endif DependencyManager::registerInheritance(); DependencyManager::registerInheritance(); @@ -840,7 +819,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(); DependencyManager::set(); #if defined(Q_OS_ANDROID) - DependencyManager::set(); // use the default user agent getter + DependencyManager::set(); // use the default user agent getter #else DependencyManager::set(std::bind(&Application::getUserAgent, qApp)); #endif @@ -854,7 +833,8 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(NodeType::Agent, listenPort); DependencyManager::set(); DependencyManager::set(); - DependencyManager::set(); // ModelFormatRegistry must be defined before ModelCache. See the ModelCache constructor. + DependencyManager::set< + ModelFormatRegistry>(); // ModelFormatRegistry must be defined before ModelCache. See the ModelCache constructor. DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); @@ -906,10 +886,11 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); - controller::StateController::setStateVariables({ { STATE_IN_HMD, STATE_CAMERA_FULL_SCREEN_MIRROR, - STATE_CAMERA_FIRST_PERSON, STATE_CAMERA_THIRD_PERSON, STATE_CAMERA_ENTITY, STATE_CAMERA_INDEPENDENT, - STATE_SNAP_TURN, STATE_ADVANCED_MOVEMENT_CONTROLS, STATE_GROUNDED, STATE_NAV_FOCUSED, - STATE_PLATFORM_WINDOWS, STATE_PLATFORM_MAC, STATE_PLATFORM_ANDROID, STATE_LEFT_HAND_DOMINANT, STATE_RIGHT_HAND_DOMINANT, STATE_STRAFE_ENABLED } }); + controller::StateController::setStateVariables( + { { STATE_IN_HMD, STATE_CAMERA_FULL_SCREEN_MIRROR, STATE_CAMERA_FIRST_PERSON, STATE_CAMERA_THIRD_PERSON, + STATE_CAMERA_ENTITY, STATE_CAMERA_INDEPENDENT, STATE_SNAP_TURN, STATE_ADVANCED_MOVEMENT_CONTROLS, STATE_GROUNDED, + STATE_NAV_FOCUSED, STATE_PLATFORM_WINDOWS, STATE_PLATFORM_MAC, STATE_PLATFORM_ANDROID, STATE_LEFT_HAND_DOMINANT, + STATE_RIGHT_HAND_DOMINANT, STATE_STRAFE_ENABLED } }); DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); @@ -947,7 +928,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { // continuing to overburden Application.cpp QUuid _keyboardFocusHighlightID; -OffscreenGLCanvas* _qmlShareContext { nullptr }; +OffscreenGLCanvas* _qmlShareContext{ nullptr }; // FIXME hack access to the internal share context for the Chromium helper // Normally we'd want to use QWebEngine::initialize(), but we can't because @@ -957,11 +938,11 @@ OffscreenGLCanvas* _qmlShareContext { nullptr }; // So instead we create a new offscreen context to share with the QGLWidget, // and manually set THAT to be the shared context for the Chromium helper #if !defined(DISABLE_QML) -OffscreenGLCanvas* _chromiumShareContext { nullptr }; +OffscreenGLCanvas* _chromiumShareContext{ nullptr }; #endif -Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext *context); -Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context(); +Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext* context); +Q_GUI_EXPORT QOpenGLContext* qt_gl_global_share_context(); Setting::Handle sessionRunTime{ "sessionRunTime", 0 }; @@ -982,41 +963,35 @@ QSharedPointer getOffscreenUI() { #endif } +void Application::InitializePlatform() { + platform::create(); + + if (platform::enumerateProcessors()) { + std::string test = platform::getProcessor(0); + } +} + Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bool runningMarkerExisted) : - QApplication(argc, argv), - _window(new MainWindow(desktop())), - _sessionRunTimer(startupTimer), + QApplication(argc, argv), _window(new MainWindow(desktop())), _sessionRunTimer(startupTimer), #ifndef Q_OS_ANDROID _logger(new FileLogger(this)), #endif _previousSessionCrashed(setupEssentials(argc, argv, runningMarkerExisted)), - _entitySimulation(new PhysicalEntitySimulation()), - _physicsEngine(new PhysicsEngine(Vectors::ZERO)), - _entityClipboard(new EntityTree()), - _previousScriptLocation("LastScriptLocation", DESKTOP_LOCATION), + _entitySimulation(new PhysicalEntitySimulation()), _physicsEngine(new PhysicsEngine(Vectors::ZERO)), + _entityClipboard(new EntityTree()), _previousScriptLocation("LastScriptLocation", DESKTOP_LOCATION), _fieldOfView("fieldOfView", DEFAULT_FIELD_OF_VIEW_DEGREES), _hmdTabletScale("hmdTabletScale", DEFAULT_HMD_TABLET_SCALE_PERCENT), - _desktopTabletScale("desktopTabletScale", DEFAULT_DESKTOP_TABLET_SCALE_PERCENT), - _firstRun(Settings::firstRun, true), + _desktopTabletScale("desktopTabletScale", DEFAULT_DESKTOP_TABLET_SCALE_PERCENT), _firstRun(Settings::firstRun, true), _desktopTabletBecomesToolbarSetting("desktopTabletBecomesToolbar", DEFAULT_DESKTOP_TABLET_BECOMES_TOOLBAR), _hmdTabletBecomesToolbarSetting("hmdTabletBecomesToolbar", DEFAULT_HMD_TABLET_BECOMES_TOOLBAR), _preferStylusOverLaserSetting("preferStylusOverLaser", DEFAULT_PREFER_STYLUS_OVER_LASER), _preferAvatarFingerOverStylusSetting("preferAvatarFingerOverStylus", DEFAULT_PREFER_AVATAR_FINGER_OVER_STYLUS), _constrainToolbarPosition("toolbar/constrainToolbarToCenterX", true), _preferredCursor("preferredCursor", DEFAULT_CURSOR_NAME), - _miniTabletEnabledSetting("miniTabletEnabled", DEFAULT_MINI_TABLET_ENABLED), - _scaleMirror(1.0f), - _mirrorYawOffset(0.0f), - _raiseMirror(0.0f), - _enableProcessOctreeThread(true), - _lastNackTime(usecTimestampNow()), - _lastSendDownstreamAudioStats(usecTimestampNow()), - _notifiedPacketVersionMismatchThisDomain(false), - _maxOctreePPS(maxOctreePacketsPerSecond.get()), - _lastFaceTrackerUpdate(0), - _snapshotSound(nullptr), - _sampleSound(nullptr) -{ + _miniTabletEnabledSetting("miniTabletEnabled", DEFAULT_MINI_TABLET_ENABLED), _scaleMirror(1.0f), _mirrorYawOffset(0.0f), + _raiseMirror(0.0f), _enableProcessOctreeThread(true), _lastNackTime(usecTimestampNow()), + _lastSendDownstreamAudioStats(usecTimestampNow()), _notifiedPacketVersionMismatchThisDomain(false), + _maxOctreePPS(maxOctreePacketsPerSecond.get()), _lastFaceTrackerUpdate(0), _snapshotSound(nullptr), _sampleSound(nullptr) { auto steamClient = PluginManager::getInstance()->getSteamClientPlugin(); setProperty(hifi::properties::STEAM, (steamClient && steamClient->isRunning())); @@ -1033,7 +1008,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // This is done so as not break previous command line scripts if (testScriptPath.left(HIFI_URL_SCHEME_HTTP.length()) == HIFI_URL_SCHEME_HTTP || testScriptPath.left(HIFI_URL_SCHEME_FTP.length()) == HIFI_URL_SCHEME_FTP) { - setProperty(hifi::properties::TEST, QUrl::fromUserInput(testScriptPath)); } else if (QFileInfo(testScriptPath).exists()) { setProperty(hifi::properties::TEST, QUrl::fromLocalFile(testScriptPath)); @@ -1058,7 +1032,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // make sure the debug draw singleton is initialized on the main thread. DebugDraw::getInstance().removeMarker(""); - PluginContainer* pluginContainer = dynamic_cast(this); // set the container for any plugins that care + PluginContainer* pluginContainer = dynamic_cast(this); // set the container for any plugins that care PluginManager::getInstance()->setContainer(pluginContainer); QThreadPool::globalInstance()->setMaxThreadCount(MIN_PROCESSING_THREAD_POOL_SIZE); @@ -1069,12 +1043,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto controllerScriptingInterface = DependencyManager::get().data(); _controllerScriptingInterface = dynamic_cast(controllerScriptingInterface); - connect(PluginManager::getInstance().data(), &PluginManager::inputDeviceRunningChanged, - controllerScriptingInterface, &controller::ScriptingInterface::updateRunningInputDevices); + connect(PluginManager::getInstance().data(), &PluginManager::inputDeviceRunningChanged, controllerScriptingInterface, + &controller::ScriptingInterface::updateRunningInputDevices); - EntityTree::setEntityClicksCapturedOperator([this] { - return _controllerScriptingInterface->areEntityClicksCaptured(); - }); + EntityTree::setEntityClicksCapturedOperator([this] { return _controllerScriptingInterface->areEntityClicksCaptured(); }); _entityClipboard->createRootElement(); @@ -1082,6 +1054,11 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo installNativeEventFilter(&MyNativeEventFilter::getInstance()); #endif +#ifdef PLATFORM + InitializePlatform(); +#endif + + QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "styles/Inconsolata.otf"); QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "fonts/fontawesome-webfont.ttf"); QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "fonts/hifi-glyphs.ttf"); @@ -1096,7 +1073,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "fonts/Cairo-SemiBold.ttf"); _window->setWindowTitle("High Fidelity Interface"); - Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us + Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us auto nodeList = DependencyManager::get(); nodeList->startThread(); @@ -1152,7 +1129,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo bool isStore = property(hifi::properties::OCULUS_STORE).toBool(); - DependencyManager::get()->setLimitedCommerce(isStore); // Or we could make it a separate arg, or if either arg is set, etc. And should this instead by a hifi::properties? + DependencyManager::get()->setLimitedCommerce( + isStore); // Or we could make it a separate arg, or if either arg is set, etc. And should this instead by a hifi::properties? updateHeartbeat(); @@ -1186,14 +1164,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return myAvatar ? myAvatar->getOrientationForAudio() : Quaternions::IDENTITY; }); - recording::Frame::registerFrameHandler(AudioConstants::getAudioFrameName(), [&audioIO](recording::Frame::ConstPointer frame) { - audioIO->handleRecordedAudioInput(frame->data); - }); + recording::Frame::registerFrameHandler(AudioConstants::getAudioFrameName(), + [&audioIO](recording::Frame::ConstPointer frame) { + audioIO->handleRecordedAudioInput(frame->data); + }); connect(audioIO, &AudioClient::inputReceived, [](const QByteArray& audio) { static auto recorder = DependencyManager::get(); if (recorder->isRecording()) { - static const recording::FrameType AUDIO_FRAME_TYPE = recording::Frame::registerFrameType(AudioConstants::getAudioFrameName()); + static const recording::FrameType AUDIO_FRAME_TYPE = + recording::Frame::registerFrameType(AudioConstants::getAudioFrameName()); recorder->recordFrame(AUDIO_FRAME_TYPE, audio); } }); @@ -1210,9 +1190,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(&domainHandler, SIGNAL(domainURLChanged(QUrl)), SLOT(domainURLChanged(QUrl))); connect(&domainHandler, SIGNAL(redirectToErrorDomainURL(QUrl)), SLOT(goToErrorDomainURL(QUrl))); - connect(&domainHandler, &DomainHandler::domainURLChanged, [](QUrl domainURL){ - setCrashAnnotation("domain", domainURL.toString().toStdString()); - }); + connect(&domainHandler, &DomainHandler::domainURLChanged, + [](QUrl domainURL) { setCrashAnnotation("domain", domainURL.toString().toStdString()); }); connect(&domainHandler, SIGNAL(resetting()), SLOT(resettingDomain())); connect(&domainHandler, SIGNAL(connectedToDomain(QUrl)), SLOT(updateWindowTitle())); connect(&domainHandler, SIGNAL(disconnectedFromDomain()), SLOT(updateWindowTitle())); @@ -1240,20 +1219,21 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // We could clear ATP assets only when changing domains, but it's possible that the domain you are connected // to has gone down and switched to a new content set, so when you reconnect the cached ATP assets will no longer be valid. - connect(&domainHandler, &DomainHandler::disconnectedFromDomain, DependencyManager::get().data(), &ScriptCache::clearATPScriptsFromCache); + connect(&domainHandler, &DomainHandler::disconnectedFromDomain, DependencyManager::get().data(), + &ScriptCache::clearATPScriptsFromCache); // update our location every 5 seconds in the metaverse server, assuming that we are authenticated with one const qint64 DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS = 5 * MSECS_PER_SECOND; auto discoverabilityManager = DependencyManager::get(); connect(&locationUpdateTimer, &QTimer::timeout, discoverabilityManager.data(), &DiscoverabilityManager::updateLocation); - connect(&locationUpdateTimer, &QTimer::timeout, - DependencyManager::get().data(), &AddressManager::storeCurrentAddress); + connect(&locationUpdateTimer, &QTimer::timeout, DependencyManager::get().data(), + &AddressManager::storeCurrentAddress); locationUpdateTimer.start(DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS); // if we get a domain change, immediately attempt update location in metaverse server - connect(&nodeList->getDomainHandler(), &DomainHandler::connectedToDomain, - discoverabilityManager.data(), &DiscoverabilityManager::updateLocation); + connect(&nodeList->getDomainHandler(), &DomainHandler::connectedToDomain, discoverabilityManager.data(), + &DiscoverabilityManager::updateLocation); // send a location update immediately discoverabilityManager->updateLocation(); @@ -1266,8 +1246,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &Application::notifyPacketVersionMismatch); // you might think we could just do this in NodeList but we only want this connection for Interface - connect(&nodeList->getDomainHandler(), SIGNAL(limitOfSilentDomainCheckInsReached()), - nodeList.data(), SLOT(reset())); + connect(&nodeList->getDomainHandler(), SIGNAL(limitOfSilentDomainCheckInsReached()), nodeList.data(), SLOT(reset())); auto dialogsManager = DependencyManager::get(); #if defined(Q_OS_ANDROID) @@ -1285,21 +1264,21 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo accountManager->setAuthURL(NetworkingConstants::METAVERSE_SERVER_URL()); // use our MyAvatar position and quat for address manager path - addressManager->setPositionGetter([this]{ return getMyAvatar()->getWorldFeetPosition(); }); - addressManager->setOrientationGetter([this]{ return getMyAvatar()->getWorldOrientation(); }); + addressManager->setPositionGetter([this] { return getMyAvatar()->getWorldFeetPosition(); }); + addressManager->setOrientationGetter([this] { return getMyAvatar()->getWorldOrientation(); }); connect(addressManager.data(), &AddressManager::hostChanged, this, &Application::updateWindowTitle); connect(this, &QCoreApplication::aboutToQuit, addressManager.data(), &AddressManager::storeCurrentAddress); connect(this, &Application::activeDisplayPluginChanged, this, &Application::updateThreadPoolCount); - connect(this, &Application::activeDisplayPluginChanged, this, [](){ + connect(this, &Application::activeDisplayPluginChanged, this, []() { qApp->setProperty(hifi::properties::HMD, qApp->isHMDMode()); auto displayPlugin = qApp->getActiveDisplayPlugin(); setCrashAnnotation("display_plugin", displayPlugin->getName().toStdString()); setCrashAnnotation("hmd", displayPlugin->isHmd() ? "1" : "0"); }); connect(this, &Application::activeDisplayPluginChanged, this, &Application::updateSystemTabletMode); - connect(this, &Application::activeDisplayPluginChanged, this, [&](){ + connect(this, &Application::activeDisplayPluginChanged, this, [&]() { if (getLoginDialogPoppedUp()) { auto dialogsManager = DependencyManager::get(); auto keyboard = DependencyManager::get(); @@ -1322,10 +1301,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); // Save avatar location immediately after a teleport. - connect(myAvatar.get(), &MyAvatar::positionGoneTo, - DependencyManager::get().data(), &AddressManager::storeCurrentAddress); + connect(myAvatar.get(), &MyAvatar::positionGoneTo, DependencyManager::get().data(), + &AddressManager::storeCurrentAddress); - connect(myAvatar.get(), &MyAvatar::skeletonModelURLChanged, [](){ + connect(myAvatar.get(), &MyAvatar::skeletonModelURLChanged, []() { QUrl avatarURL = qApp->getMyAvatar()->getSkeletonModelURL(); setCrashAnnotation("avatar", avatarURL.toString().toStdString()); }); @@ -1335,26 +1314,30 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo { auto scriptEngines = DependencyManager::get().data(); - scriptEngines->registerScriptInitializer([this](ScriptEnginePointer engine) { - registerScriptEngineWithApplicationServices(engine); - }); + scriptEngines->registerScriptInitializer( + [this](ScriptEnginePointer engine) { registerScriptEngineWithApplicationServices(engine); }); - connect(scriptEngines, &ScriptEngines::scriptCountChanged, this, [this] { - auto scriptEngines = DependencyManager::get(); - if (scriptEngines->getRunningScripts().isEmpty()) { - getMyAvatar()->clearScriptableSettings(); - } - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptCountChanged, this, + [this] { + auto scriptEngines = DependencyManager::get(); + if (scriptEngines->getRunningScripts().isEmpty()) { + getMyAvatar()->clearScriptableSettings(); + } + }, + Qt::QueuedConnection); - connect(scriptEngines, &ScriptEngines::scriptsReloading, this, [this] { - getEntities()->reloadEntityScripts(); - loadAvatarScripts(getMyAvatar()->getScriptUrls()); - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptsReloading, this, + [this] { + getEntities()->reloadEntityScripts(); + loadAvatarScripts(getMyAvatar()->getScriptUrls()); + }, + Qt::QueuedConnection); - connect(scriptEngines, &ScriptEngines::scriptLoadError, - this, [](const QString& filename, const QString& error) { - OffscreenUi::asyncWarning(nullptr, "Error Loading Script", filename + " failed to load."); - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptLoadError, this, + [](const QString& filename, const QString& error) { + OffscreenUi::asyncWarning(nullptr, "Error Loading Script", filename + " failed to load."); + }, + Qt::QueuedConnection); } #ifdef _WIN32 @@ -1364,11 +1347,13 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // tell the NodeList instance who to tell the domain server we care about nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer - << NodeType::EntityServer << NodeType::AssetServer << NodeType::MessagesMixer << NodeType::EntityScriptServer); + << NodeType::EntityServer << NodeType::AssetServer + << NodeType::MessagesMixer << NodeType::EntityScriptServer); // connect to the packet sent signal of the _entityEditSender connect(&_entityEditSender, &EntityEditPacketSender::packetSent, this, &Application::packetSent); - connect(&_entityEditSender, &EntityEditPacketSender::addingEntityWithCertificate, this, &Application::addingEntityWithCertificate); + connect(&_entityEditSender, &EntityEditPacketSender::addingEntityWithCertificate, this, + &Application::addingEntityWithCertificate); QString concurrentDownloadsStr = getCmdOption(argc, constArgv, "--concurrent-downloads"); bool success; @@ -1430,7 +1415,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto audioScriptingInterface = DependencyManager::set(); auto audioIO = DependencyManager::get().data(); connect(audioIO, &AudioClient::mutedByMixer, audioScriptingInterface.data(), &AudioScriptingInterface::mutedByMixer); - connect(audioIO, &AudioClient::receivedFirstPacket, audioScriptingInterface.data(), &AudioScriptingInterface::receivedFirstPacket); + connect(audioIO, &AudioClient::receivedFirstPacket, audioScriptingInterface.data(), + &AudioScriptingInterface::receivedFirstPacket); connect(audioIO, &AudioClient::disconnected, audioScriptingInterface.data(), &AudioScriptingInterface::disconnected); connect(audioIO, &AudioClient::muteEnvironmentRequested, [](glm::vec3 position, float radius) { auto audioClient = DependencyManager::get(); @@ -1444,7 +1430,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo } }); connect(this, &Application::activeDisplayPluginChanged, - reinterpret_cast(audioScriptingInterface.data()), &scripting::Audio::onContextChanged); + reinterpret_cast(audioScriptingInterface.data()), &scripting::Audio::onContextChanged); } // Create the rendering engine. This can be slow on some machines due to lots of @@ -1453,7 +1439,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo qCDebug(interfaceapp, "Initialized Render Engine."); // Overlays need to exist before we set the ContextOverlayInterface dependency - _overlays.init(); // do this before scripts load + _overlays.init(); // do this before scripts load DependencyManager::set(); auto offscreenUi = getOffscreenUI(); @@ -1505,8 +1491,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo updateHeartbeat(); static const QString TESTER = "HIFI_TESTER"; - bool isTester = false; -#if defined (Q_OS_ANDROID) + bool isTester = false; +#if defined(Q_OS_ANDROID) // Since we cannot set environment variables in Android we use a file presence // to denote that this is a testing device QFileInfo check_tester_file(TESTER_FILE); @@ -1515,7 +1501,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo constexpr auto INSTALLER_INI_NAME = "installer.ini"; auto iniPath = QDir(applicationDirPath()).filePath(INSTALLER_INI_NAME); - QFile installerFile { iniPath }; + QFile installerFile{ iniPath }; std::unordered_map installerKeyValues; if (installerFile.open(QIODevice::ReadOnly)) { while (!installerFile.atEnd()) { @@ -1562,29 +1548,27 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo static const QString TESTER = "HIFI_TESTER"; auto gpuIdent = GPUIdent::getInstance(); auto glContextData = getGLContextData(); - QJsonObject properties = { - { "version", applicationVersion() }, - { "tester", QProcessEnvironment::systemEnvironment().contains(TESTER) || isTester }, - { "installer_campaign", installerCampaign }, - { "installer_type", installerType }, - { "build_type", BuildInfo::BUILD_TYPE_STRING }, - { "previousSessionCrashed", _previousSessionCrashed }, - { "previousSessionRuntime", sessionRunTime.get() }, - { "cpu_architecture", QSysInfo::currentCpuArchitecture() }, - { "kernel_type", QSysInfo::kernelType() }, - { "kernel_version", QSysInfo::kernelVersion() }, - { "os_type", QSysInfo::productType() }, - { "os_version", QSysInfo::productVersion() }, - { "gpu_name", gpuIdent->getName() }, - { "gpu_driver", gpuIdent->getDriver() }, - { "gpu_memory", static_cast(gpuIdent->getMemory()) }, - { "gl_version_int", glVersionToInteger(glContextData.value("version").toString()) }, - { "gl_version", glContextData["version"] }, - { "gl_vender", glContextData["vendor"] }, - { "gl_sl_version", glContextData["sl_version"] }, - { "gl_renderer", glContextData["renderer"] }, - { "ideal_thread_count", QThread::idealThreadCount() } - }; + QJsonObject properties = { { "version", applicationVersion() }, + { "tester", QProcessEnvironment::systemEnvironment().contains(TESTER) || isTester }, + { "installer_campaign", installerCampaign }, + { "installer_type", installerType }, + { "build_type", BuildInfo::BUILD_TYPE_STRING }, + { "previousSessionCrashed", _previousSessionCrashed }, + { "previousSessionRuntime", sessionRunTime.get() }, + { "cpu_architecture", QSysInfo::currentCpuArchitecture() }, + { "kernel_type", QSysInfo::kernelType() }, + { "kernel_version", QSysInfo::kernelVersion() }, + { "os_type", QSysInfo::productType() }, + { "os_version", QSysInfo::productVersion() }, + { "gpu_name", gpuIdent->getName() }, + { "gpu_driver", gpuIdent->getDriver() }, + { "gpu_memory", static_cast(gpuIdent->getMemory()) }, + { "gl_version_int", glVersionToInteger(glContextData.value("version").toString()) }, + { "gl_version", glContextData["version"] }, + { "gl_vender", glContextData["vendor"] }, + { "gl_sl_version", glContextData["sl_version"] }, + { "gl_renderer", glContextData["renderer"] }, + { "ideal_thread_count", QThread::idealThreadCount() } }; auto macVersion = QSysInfo::macVersion(); if (macVersion != QSysInfo::MV_None) { properties["os_osx_version"] = QSysInfo::macVersion(); @@ -1621,7 +1605,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // For now we're going to set the PPS for outbound packets to be super high, this is // probably not the right long term solution. But for now, we're going to do this to // allow you to move an entity around in your hand - _entityEditSender.setPacketsPerSecond(3000); // super high!! + _entityEditSender.setPacketsPerSecond(3000); // super high!! // Make sure we don't time out during slow operations at startup updateHeartbeat(); @@ -1629,15 +1613,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(this, SIGNAL(aboutToQuit()), this, SLOT(onAboutToQuit())); // FIXME -- I'm a little concerned about this. - connect(myAvatar->getSkeletonModel().get(), &SkeletonModel::skeletonLoaded, - this, &Application::checkSkeleton, Qt::QueuedConnection); + connect(myAvatar->getSkeletonModel().get(), &SkeletonModel::skeletonLoaded, this, &Application::checkSkeleton, + Qt::QueuedConnection); // Setup the userInputMapper with the actions auto userInputMapper = DependencyManager::get(); connect(userInputMapper.data(), &UserInputMapper::actionEvent, [this](int action, float state) { using namespace controller; auto tabletScriptingInterface = DependencyManager::get(); - auto audioScriptingInterface = reinterpret_cast(DependencyManager::get().data()); + auto audioScriptingInterface = + reinterpret_cast(DependencyManager::get().data()); { auto actionEnum = static_cast(action); int key = Qt::Key_unknown; @@ -1719,7 +1704,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo if (action == controller::toInt(controller::Action::RETICLE_CLICK)) { auto reticlePos = getApplicationCompositor().getReticlePosition(); - QPoint localPos(reticlePos.x, reticlePos.y); // both hmd and desktop already handle this in our coordinates. + QPoint localPos(reticlePos.x, reticlePos.y); // both hmd and desktop already handle this in our coordinates. if (state) { QMouseEvent mousePress(QEvent::MouseButtonPress, localPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); sendEvent(_glWidget, &mousePress); @@ -1729,7 +1714,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo sendEvent(_glWidget, &mouseRelease); _reticleClickPressed = false; } - return; // nothing else to do + return; // nothing else to do } if (state) { @@ -1754,9 +1739,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice = userInputMapper->getStateDevice(); - _applicationStateDevice->setInputVariant(STATE_IN_HMD, []() -> float { - return qApp->isHMDMode() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_IN_HMD, []() -> float { return qApp->isHMDMode() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_CAMERA_FULL_SCREEN_MIRROR, []() -> float { return qApp->getCamera().getMode() == CAMERA_MODE_MIRROR ? 1 : 0; }); @@ -1772,9 +1755,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice->setInputVariant(STATE_CAMERA_INDEPENDENT, []() -> float { return qApp->getCamera().getMode() == CAMERA_MODE_INDEPENDENT ? 1 : 0; }); - _applicationStateDevice->setInputVariant(STATE_SNAP_TURN, []() -> float { - return qApp->getMyAvatar()->getSnapTurn() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_SNAP_TURN, + []() -> float { return qApp->getMyAvatar()->getSnapTurn() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_ADVANCED_MOVEMENT_CONTROLS, []() -> float { return qApp->getMyAvatar()->useAdvancedMovementControls() ? 1 : 0; }); @@ -1784,9 +1766,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice->setInputVariant(STATE_RIGHT_HAND_DOMINANT, []() -> float { return qApp->getMyAvatar()->getDominantHand() == "right" ? 1 : 0; }); - _applicationStateDevice->setInputVariant(STATE_STRAFE_ENABLED, []() -> float { - return qApp->getMyAvatar()->getStrafeEnabled() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_STRAFE_ENABLED, + []() -> float { return qApp->getMyAvatar()->getStrafeEnabled() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_GROUNDED, []() -> float { return qApp->getMyAvatar()->getCharacterController()->onGround() ? 1 : 0; @@ -1811,13 +1792,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); _applicationStateDevice->setInputVariant(STATE_PLATFORM_ANDROID, []() -> float { #if defined(Q_OS_ANDROID) - return 1 ; + return 1; #else return 0; #endif }); - getRefreshRateManager().setRefreshRateRegime(RefreshRateManager::RefreshRateRegime::STARTUP); // Setup the _keyboardMouseDevice, _touchscreenDevice, _touchscreenVirtualPadDevice and the user input mapper with the default bindings @@ -1843,28 +1823,30 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Make sure we don't time out during slow operations at startup updateHeartbeat(); QTimer* settingsTimer = new QTimer(); - moveToNewNamedThread(settingsTimer, "Settings Thread", [this, settingsTimer]{ - // This needs to run on the settings thread, so we need to pass the `settingsTimer` as the - // receiver object, otherwise it will run on the application thread and trigger a warning - // about trying to kill the timer on the main thread. - connect(qApp, &Application::beforeAboutToQuit, settingsTimer, [this, settingsTimer]{ - // Disconnect the signal from the save settings - QObject::disconnect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); - // Stop the settings timer - settingsTimer->stop(); - // Delete it (this will trigger the thread destruction - settingsTimer->deleteLater(); - // Mark the settings thread as finished, so we know we can safely save in the main application - // shutdown code - _settingsGuard.trigger(); - }); + moveToNewNamedThread(settingsTimer, "Settings Thread", + [this, settingsTimer] { + // This needs to run on the settings thread, so we need to pass the `settingsTimer` as the + // receiver object, otherwise it will run on the application thread and trigger a warning + // about trying to kill the timer on the main thread. + connect(qApp, &Application::beforeAboutToQuit, settingsTimer, [this, settingsTimer] { + // Disconnect the signal from the save settings + QObject::disconnect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); + // Stop the settings timer + settingsTimer->stop(); + // Delete it (this will trigger the thread destruction + settingsTimer->deleteLater(); + // Mark the settings thread as finished, so we know we can safely save in the main application + // shutdown code + _settingsGuard.trigger(); + }); - int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now - settingsTimer->setSingleShot(false); - settingsTimer->setInterval(SAVE_SETTINGS_INTERVAL); // 10s, Qt::CoarseTimer acceptable - QObject::connect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); - settingsTimer->start(); - }, QThread::LowestPriority); + int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now + settingsTimer->setSingleShot(false); + settingsTimer->setInterval(SAVE_SETTINGS_INTERVAL); // 10s, Qt::CoarseTimer acceptable + QObject::connect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); + settingsTimer->start(); + }, + QThread::LowestPriority); if (Menu::getInstance()->isOptionChecked(MenuOption::FirstPerson)) { getMyAvatar()->setBoomLength(MyAvatar::ZOOM_MIN); // So that camera doesn't auto-switch to third person. @@ -1876,15 +1858,15 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo AudioInjector::setLocalAudioInterface(audioIO); auto audioScriptingInterface = DependencyManager::get(); audioScriptingInterface->setLocalAudioInterface(audioIO); - connect(audioIO, &AudioClient::noiseGateOpened, audioScriptingInterface.data(), &AudioScriptingInterface::noiseGateOpened); - connect(audioIO, &AudioClient::noiseGateClosed, audioScriptingInterface.data(), &AudioScriptingInterface::noiseGateClosed); + connect(audioIO, &AudioClient::noiseGateOpened, audioScriptingInterface.data(), + &AudioScriptingInterface::noiseGateOpened); + connect(audioIO, &AudioClient::noiseGateClosed, audioScriptingInterface.data(), + &AudioScriptingInterface::noiseGateClosed); connect(audioIO, &AudioClient::inputReceived, audioScriptingInterface.data(), &AudioScriptingInterface::inputReceived); } this->installEventFilter(this); - - #ifdef HAVE_DDE auto ddeTracker = DependencyManager::get(); ddeTracker->init(); @@ -1900,19 +1882,20 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // If launched from Steam, let it handle updates const QString HIFI_NO_UPDATER_COMMAND_LINE_KEY = "--no-updater"; bool noUpdater = arguments().indexOf(HIFI_NO_UPDATER_COMMAND_LINE_KEY) != -1; - bool buildCanUpdate = BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable - || BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Master; + bool buildCanUpdate = + BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable || BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Master; if (!noUpdater && buildCanUpdate) { constexpr auto INSTALLER_TYPE_CLIENT_ONLY = "client_only"; auto applicationUpdater = DependencyManager::set(); - AutoUpdater::InstallerType type = installerType == INSTALLER_TYPE_CLIENT_ONLY - ? AutoUpdater::InstallerType::CLIENT_ONLY : AutoUpdater::InstallerType::FULL; + AutoUpdater::InstallerType type = installerType == INSTALLER_TYPE_CLIENT_ONLY ? AutoUpdater::InstallerType::CLIENT_ONLY + : AutoUpdater::InstallerType::FULL; applicationUpdater->setInstallerType(type); applicationUpdater->setInstallerCampaign(installerCampaign); - connect(applicationUpdater.data(), &AutoUpdater::newVersionIsAvailable, dialogsManager.data(), &DialogsManager::showUpdateDialog); + connect(applicationUpdater.data(), &AutoUpdater::newVersionIsAvailable, dialogsManager.data(), + &DialogsManager::showUpdateDialog); applicationUpdater->checkForUpdate(); } @@ -1931,7 +1914,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto keyboard = DependencyManager::get(); if (getEntities()->wantsKeyboardFocus(id)) { setKeyboardFocusEntity(id); - } else if (!keyboard->containsID(id)) { // FIXME: this is a hack to make the keyboard work for now, since the keys would otherwise steal focus + } else if ( + !keyboard->containsID( + id)) { // FIXME: this is a hack to make the keyboard work for now, since the keys would otherwise steal focus setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); } } @@ -1940,57 +1925,63 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(pointerManager.data(), &PointerManager::triggerBeginOverlay, keyboardFocusOperator); auto entityScriptingInterface = DependencyManager::get(); - connect(entityScriptingInterface.data(), &EntityScriptingInterface::deletingEntity, this, [this](const EntityItemID& entityItemID) { - if (entityItemID == _keyboardFocusedEntity.get()) { - setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); - } - }, Qt::QueuedConnection); + connect(entityScriptingInterface.data(), &EntityScriptingInterface::deletingEntity, this, + [this](const EntityItemID& entityItemID) { + if (entityItemID == _keyboardFocusedEntity.get()) { + setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); + } + }, + Qt::QueuedConnection); + + EntityTreeRenderer::setAddMaterialToEntityOperator( + [this](const QUuid& entityID, graphics::MaterialLayer material, const std::string& parentMaterialName) { + if (_aboutToQuit) { + return false; + } + + auto renderable = getEntities()->renderableForEntityId(entityID); + if (renderable) { + renderable->addMaterial(material, parentMaterialName); + return true; + } - EntityTreeRenderer::setAddMaterialToEntityOperator([this](const QUuid& entityID, graphics::MaterialLayer material, const std::string& parentMaterialName) { - if (_aboutToQuit) { return false; - } + }); + EntityTreeRenderer::setRemoveMaterialFromEntityOperator( + [this](const QUuid& entityID, graphics::MaterialPointer material, const std::string& parentMaterialName) { + if (_aboutToQuit) { + return false; + } - auto renderable = getEntities()->renderableForEntityId(entityID); - if (renderable) { - renderable->addMaterial(material, parentMaterialName); - return true; - } + auto renderable = getEntities()->renderableForEntityId(entityID); + if (renderable) { + renderable->removeMaterial(material, parentMaterialName); + return true; + } - return false; - }); - EntityTreeRenderer::setRemoveMaterialFromEntityOperator([this](const QUuid& entityID, graphics::MaterialPointer material, const std::string& parentMaterialName) { - if (_aboutToQuit) { return false; - } + }); - auto renderable = getEntities()->renderableForEntityId(entityID); - if (renderable) { - renderable->removeMaterial(material, parentMaterialName); - return true; - } - - return false; - }); - - EntityTreeRenderer::setAddMaterialToAvatarOperator([](const QUuid& avatarID, graphics::MaterialLayer material, const std::string& parentMaterialName) { - auto avatarManager = DependencyManager::get(); - auto avatar = avatarManager->getAvatarBySessionID(avatarID); - if (avatar) { - avatar->addMaterial(material, parentMaterialName); - return true; - } - return false; - }); - EntityTreeRenderer::setRemoveMaterialFromAvatarOperator([](const QUuid& avatarID, graphics::MaterialPointer material, const std::string& parentMaterialName) { - auto avatarManager = DependencyManager::get(); - auto avatar = avatarManager->getAvatarBySessionID(avatarID); - if (avatar) { - avatar->removeMaterial(material, parentMaterialName); - return true; - } - return false; - }); + EntityTreeRenderer::setAddMaterialToAvatarOperator( + [](const QUuid& avatarID, graphics::MaterialLayer material, const std::string& parentMaterialName) { + auto avatarManager = DependencyManager::get(); + auto avatar = avatarManager->getAvatarBySessionID(avatarID); + if (avatar) { + avatar->addMaterial(material, parentMaterialName); + return true; + } + return false; + }); + EntityTreeRenderer::setRemoveMaterialFromAvatarOperator( + [](const QUuid& avatarID, graphics::MaterialPointer material, const std::string& parentMaterialName) { + auto avatarManager = DependencyManager::get(); + auto avatar = avatarManager->getAvatarBySessionID(avatarID); + if (avatar) { + avatar->removeMaterial(material, parentMaterialName); + return true; + } + return false; + }); EntityTree::setGetEntityObjectOperator([this](const QUuid& id) -> QObject* { auto entities = getEntities(); @@ -2017,9 +2008,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return QSizeF(0.0f, 0.0f); }); - connect(this, &Application::aboutToQuit, [this]() { - setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); - }); + connect(this, &Application::aboutToQuit, [this]() { setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); }); // Add periodic checks to send user activity data static int CHECK_NEARBY_AVATARS_INTERVAL_MS = 10000; @@ -2038,7 +2027,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QTimer* sendStatsTimer = new QTimer(this); sendStatsTimer->setInterval(SEND_STATS_INTERVAL_MS); // 10s, Qt::CoarseTimer acceptable connect(sendStatsTimer, &QTimer::timeout, this, [this]() { - QJsonObject properties = {}; MemoryInfo memInfo; if (getMemoryInfo(memInfo)) { @@ -2049,8 +2037,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // content location and build info - useful for filtering stats auto addressManager = DependencyManager::get(); - auto currentDomain = addressManager->currentShareableAddress(true).toString(); // domain only - auto currentPath = addressManager->currentPath(true); // with orientation + auto currentDomain = addressManager->currentShareableAddress(true).toString(); // domain only + auto currentPath = addressManager->currentPath(true); // with orientation properties["current_domain"] = currentDomain; properties["current_path"] = currentPath; properties["build_version"] = BuildInfo::VERSION; @@ -2114,24 +2102,24 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo startedRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_STARTED).toInt(); startedRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_STARTED).toInt(); startedRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_STARTED).toInt(); - startedRequests["total"] = startedRequests["atp"].toInt() + startedRequests["http"].toInt() - + startedRequests["file"].toInt(); + startedRequests["total"] = + startedRequests["atp"].toInt() + startedRequests["http"].toInt() + startedRequests["file"].toInt(); properties["started_requests"] = startedRequests; QJsonObject successfulRequests; successfulRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_SUCCESS).toInt(); successfulRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_SUCCESS).toInt(); successfulRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_SUCCESS).toInt(); - successfulRequests["total"] = successfulRequests["atp"].toInt() + successfulRequests["http"].toInt() - + successfulRequests["file"].toInt(); + successfulRequests["total"] = + successfulRequests["atp"].toInt() + successfulRequests["http"].toInt() + successfulRequests["file"].toInt(); properties["successful_requests"] = successfulRequests; QJsonObject failedRequests; failedRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_FAILED).toInt(); failedRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_FAILED).toInt(); failedRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_FAILED).toInt(); - failedRequests["total"] = failedRequests["atp"].toInt() + failedRequests["http"].toInt() - + failedRequests["file"].toInt(); + failedRequests["total"] = + failedRequests["atp"].toInt() + failedRequests["http"].toInt() + failedRequests["file"].toInt(); properties["failed_requests"] = failedRequests; QJsonObject cacheRequests; @@ -2176,21 +2164,18 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo totalServerOctreeElements += i->second.getTotalElements(); } - properties["local_octree_elements"] = (qint64) OctreeElement::getInternalNodeCount(); - properties["server_octree_elements"] = (qint64) totalServerOctreeElements; + properties["local_octree_elements"] = (qint64)OctreeElement::getInternalNodeCount(); + properties["server_octree_elements"] = (qint64)totalServerOctreeElements; properties["active_display_plugin"] = getActiveDisplayPlugin()->getName(); properties["using_hmd"] = isHMDMode(); _autoSwitchDisplayModeSupportedHMDPlugin = nullptr; - foreach(DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { - if (displayPlugin->isHmd() && - displayPlugin->getSupportsAutoSwitch()) { + foreach (DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { + if (displayPlugin->isHmd() && displayPlugin->getSupportsAutoSwitch()) { _autoSwitchDisplayModeSupportedHMDPlugin = displayPlugin; - _autoSwitchDisplayModeSupportedHMDPluginName = - _autoSwitchDisplayModeSupportedHMDPlugin->getName(); - _previousHMDWornStatus = - _autoSwitchDisplayModeSupportedHMDPlugin->isDisplayVisible(); + _autoSwitchDisplayModeSupportedHMDPluginName = _autoSwitchDisplayModeSupportedHMDPlugin->getName(); + _previousHMDWornStatus = _autoSwitchDisplayModeSupportedHMDPlugin->isDisplayVisible(); break; } } @@ -2198,7 +2183,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo if (_autoSwitchDisplayModeSupportedHMDPlugin) { if (getActiveDisplayPlugin() != _autoSwitchDisplayModeSupportedHMDPlugin && !_autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { - startHMDStandBySession(); + startHMDStandBySession(); } // Poll periodically to check whether the user has worn HMD or not. Switch Display mode accordingly. // If the user wears HMD then switch to VR mode. If the user removes HMD then switch to Desktop mode. @@ -2224,8 +2209,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // controller::Pose considers two poses to be different if either are invalid. In our case, we actually // want to consider the pose to be unchanged if it was invalid and still is invalid, so we check that first. properties["hand_pose_changed"] = - ((leftHandPose.valid || lastLeftHandPose.valid) && (leftHandPose != lastLeftHandPose)) - || ((rightHandPose.valid || lastRightHandPose.valid) && (rightHandPose != lastRightHandPose)); + ((leftHandPose.valid || lastLeftHandPose.valid) && (leftHandPose != lastLeftHandPose)) || + ((rightHandPose.valid || lastRightHandPose.valid) && (rightHandPose != lastRightHandPose)); lastLeftHandPose = leftHandPose; lastRightHandPose = rightHandPose; @@ -2236,11 +2221,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Periodically check for count of nearby avatars static int lastCountOfNearbyAvatars = -1; QTimer* checkNearbyAvatarsTimer = new QTimer(this); - checkNearbyAvatarsTimer->setInterval(CHECK_NEARBY_AVATARS_INTERVAL_MS); // 10 seconds, Qt::CoarseTimer ok + checkNearbyAvatarsTimer->setInterval(CHECK_NEARBY_AVATARS_INTERVAL_MS); // 10 seconds, Qt::CoarseTimer ok connect(checkNearbyAvatarsTimer, &QTimer::timeout, this, []() { auto avatarManager = DependencyManager::get(); int nearbyAvatars = avatarManager->numberOfAvatarsInRange(avatarManager->getMyAvatar()->getWorldPosition(), - NEARBY_AVATAR_RADIUS_METERS) - 1; + NEARBY_AVATAR_RADIUS_METERS) - + 1; if (nearbyAvatars != lastCountOfNearbyAvatars) { lastCountOfNearbyAvatars = nearbyAvatars; UserActivityLogger::getInstance().logAction("nearby_avatars", { { "count", nearbyAvatars } }); @@ -2249,9 +2235,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo checkNearbyAvatarsTimer->start(); // Track user activity event when we receive a mute packet - auto onMutedByMixer = []() { - UserActivityLogger::getInstance().logAction("received_mute_packet"); - }; + auto onMutedByMixer = []() { UserActivityLogger::getInstance().logAction("received_mute_packet"); }; connect(DependencyManager::get().data(), &AudioClient::mutedByMixer, this, onMutedByMixer); // Track when the address bar is opened @@ -2281,16 +2265,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Monitor model assets (e.g., from Clara.io) added to the world that may need resizing. static const int ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS = 1000; - _addAssetToWorldResizeTimer.setInterval(ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS); // 1s, Qt::CoarseTimer acceptable + _addAssetToWorldResizeTimer.setInterval(ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS); // 1s, Qt::CoarseTimer acceptable connect(&_addAssetToWorldResizeTimer, &QTimer::timeout, this, &Application::addAssetToWorldCheckModelSize); // Auto-update and close adding asset to world info message box. static const int ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS = 5000; - _addAssetToWorldInfoTimer.setInterval(ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS); // 5s, Qt::CoarseTimer acceptable + _addAssetToWorldInfoTimer.setInterval(ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS); // 5s, Qt::CoarseTimer acceptable _addAssetToWorldInfoTimer.setSingleShot(true); connect(&_addAssetToWorldInfoTimer, &QTimer::timeout, this, &Application::addAssetToWorldInfoTimeout); static const int ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS = 8000; - _addAssetToWorldErrorTimer.setInterval(ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS); // 8s, Qt::CoarseTimer acceptable + _addAssetToWorldErrorTimer.setInterval(ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS); // 8s, Qt::CoarseTimer acceptable _addAssetToWorldErrorTimer.setSingleShot(true); connect(&_addAssetToWorldErrorTimer, &QTimer::timeout, this, &Application::addAssetToWorldErrorTimeout); @@ -2302,7 +2286,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(&_myCamera, &Camera::modeUpdated, this, &Application::cameraModeChanged); - DependencyManager::get()->setShouldPickHUDOperator([]() { return DependencyManager::get()->isHMDMode(); }); + DependencyManager::get()->setShouldPickHUDOperator( + []() { return DependencyManager::get()->isHMDMode(); }); DependencyManager::get()->setCalculatePos2DFromHUDOperator([this](const glm::vec3& intersection) { const glm::vec2 MARGIN(25.0f); glm::vec2 maxPos = _controllerScriptingInterface->getViewportDimensions() - MARGIN; @@ -2312,7 +2297,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Setup the mouse ray pick and related operators { - auto mouseRayPick = std::make_shared(Vectors::ZERO, Vectors::UP, PickFilter(PickScriptingInterface::PICK_ENTITIES() | PickScriptingInterface::PICK_LOCAL_ENTITIES()), 0.0f, true); + auto mouseRayPick = std::make_shared(Vectors::ZERO, Vectors::UP, + PickFilter(PickScriptingInterface::PICK_ENTITIES() | + PickScriptingInterface::PICK_LOCAL_ENTITIES()), + 0.0f, true); mouseRayPick->parentTransform = std::make_shared(); mouseRayPick->setJointState(PickQuery::JOINT_STATE_MOUSE); auto mouseRayPickID = DependencyManager::get()->addPick(PickQuery::Ray, mouseRayPick); @@ -2338,7 +2326,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo DependencyManager::get()->setPrecisionPicking(rayPickID, value); }); - EntityItem::setBillboardRotationOperator([](const glm::vec3& position, const glm::quat& rotation, BillboardMode billboardMode, const glm::vec3& frustumPos) { + EntityItem::setBillboardRotationOperator([](const glm::vec3& position, const glm::quat& rotation, + BillboardMode billboardMode, const glm::vec3& frustumPos) { if (billboardMode == BillboardMode::YAW) { //rotate about vertical to face the camera glm::vec3 dPosition = frustumPos - position; @@ -2364,9 +2353,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return viewFrustum.getPosition(); }); - DependencyManager::get()->setKickConfirmationOperator([this] (const QUuid& nodeID) { userKickConfirmation(nodeID); }); + DependencyManager::get()->setKickConfirmationOperator( + [this](const QUuid& nodeID) { userKickConfirmation(nodeID); }); - render::entities::WebEntityRenderer::setAcquireWebSurfaceOperator([=](const QString& url, bool htmlContent, QSharedPointer& webSurface, bool& cachedWebSurface) { + render::entities::WebEntityRenderer::setAcquireWebSurfaceOperator([=](const QString& url, bool htmlContent, + QSharedPointer& webSurface, + bool& cachedWebSurface) { bool isTablet = url == TabletScriptingInterface::QML; if (htmlContent) { webSurface = DependencyManager::get()->acquire(render::entities::WebEntityRenderer::QML); @@ -2380,7 +2372,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QObject::connect(webSurface.data(), &hifi::qml::OffscreenSurface::rootContextCreated, rootItemLoadedFunctor); } auto surfaceContext = webSurface->getSurfaceContext(); - surfaceContext->setContextProperty("KeyboardScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("KeyboardScriptingInterface", + DependencyManager::get().data()); } else { // FIXME: the tablet should use the OffscreenQmlSurfaceCache webSurface = QSharedPointer(new OffscreenQmlSurface(), [](OffscreenQmlSurface* webSurface) { @@ -2391,8 +2384,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); }); auto rootItemLoadedFunctor = [webSurface, url, isTablet] { - Application::setupQmlSurface(webSurface->getSurfaceContext(), isTablet || url == LOGIN_DIALOG.toString() || url == AVATAR_INPUTS_BAR_QML.toString() || - url == BUBBLE_ICON_QML.toString()); + Application::setupQmlSurface(webSurface->getSurfaceContext(), isTablet || url == LOGIN_DIALOG.toString() || + url == AVATAR_INPUTS_BAR_QML.toString() || + url == BUBBLE_ICON_QML.toString()); }; if (webSurface->getRootItem()) { rootItemLoadedFunctor(); @@ -2406,7 +2400,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo const uint8_t TABLET_FPS = 90; webSurface->setMaxFps(isTablet ? TABLET_FPS : DEFAULT_MAX_FPS); }); - render::entities::WebEntityRenderer::setReleaseWebSurfaceOperator([=](QSharedPointer& webSurface, bool& cachedWebSurface, std::vector& connections) { + render::entities::WebEntityRenderer::setReleaseWebSurfaceOperator([=](QSharedPointer& webSurface, + bool& cachedWebSurface, + std::vector& connections) { QQuickItem* rootItem = webSurface->getRootItem(); // Fix for crash in QtWebEngineCore when rapidly switching domains @@ -2515,10 +2511,10 @@ QString Application::getUserAgent() { return userAgent; } - QString userAgent = "Mozilla/5.0 (HighFidelityInterface/" + BuildInfo::VERSION + "; " - + QSysInfo::productType() + " " + QSysInfo::productVersion() + ")"; + QString userAgent = "Mozilla/5.0 (HighFidelityInterface/" + BuildInfo::VERSION + "; " + QSysInfo::productType() + " " + + QSysInfo::productVersion() + ")"; - auto formatPluginName = [](QString name) -> QString { return name.trimmed().replace(" ", "-"); }; + auto formatPluginName = [](QString name) -> QString { return name.trimmed().replace(" ", "-"); }; // For each plugin, add to userAgent auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins(); @@ -2527,7 +2523,7 @@ QString Application::getUserAgent() { userAgent += " " + formatPluginName(dp->getName()); } } - auto inputPlugins= PluginManager::getInstance()->getInputPlugins(); + auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); for (auto& ip : inputPlugins) { if (ip->isActive()) { userAgent += " " + formatPluginName(ip->getName()); @@ -2561,7 +2557,7 @@ void Application::checkChangeCursor() { QMutexLocker locker(&_changeCursorLock); if (_cursorNeedsChanging) { #ifdef Q_OS_MAC - auto cursorTarget = _window; // OSX doesn't seem to provide for hiding the cursor only on the GL widget + auto cursorTarget = _window; // OSX doesn't seem to provide for hiding the cursor only on the GL widget #else // On windows and linux, hiding the top level cursor also means it's invisible when hovering over the // window menu, which is a pain, so only hide it for the GL surface @@ -2600,7 +2596,7 @@ void Application::onAboutToQuit() { _firstRun.set(false); } - foreach(auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { + foreach (auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { if (inputPlugin->isActive()) { inputPlugin->deactivate(); } @@ -2613,8 +2609,7 @@ void Application::onAboutToQuit() { loginDialogPoppedUp.set(false); getActiveDisplayPlugin()->deactivate(); - if (_autoSwitchDisplayModeSupportedHMDPlugin - && _autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { + if (_autoSwitchDisplayModeSupportedHMDPlugin && _autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { _autoSwitchDisplayModeSupportedHMDPlugin->endSession(); } // use the CloseEventSender via a QThread to send an event that says the user asked for the app to close @@ -2676,7 +2671,7 @@ void Application::cleanupBeforeQuit() { nodeList->getPacketReceiver().setShouldDropPackets(true); } - getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts + getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts // Clear any queued processing (I/O, FBX/OBJ/Texture parsing) QThreadPool::globalInstance()->clear(); @@ -2685,7 +2680,7 @@ void Application::cleanupBeforeQuit() { // FIXME: Something is still holding on to the ScriptEnginePointers contained in ScriptEngines, and they hold backpointers to ScriptEngines, // so this doesn't shut down properly - DependencyManager::get()->shutdownScripting(); // stop all currently running global scripts + DependencyManager::get()->shutdownScripting(); // stop all currently running global scripts // These classes hold ScriptEnginePointers, so they must be destroyed before ScriptEngines // Must be done after shutdownScripting in case any scripts try to access these things { @@ -2729,7 +2724,7 @@ void Application::cleanupBeforeQuit() { DependencyManager::destroy(); #endif - DependencyManager::destroy(); // Must be destroyed before TabletScriptingInterface + DependencyManager::destroy(); // Must be destroyed before TabletScriptingInterface // stop QML DependencyManager::destroy(); @@ -2770,14 +2765,14 @@ Application::~Application() { avatarManager->handleProcessedPhysicsTransaction(transaction); avatarManager->deleteAllAvatars(); - + auto myCharacterController = getMyAvatar()->getCharacterController(); myCharacterController->clearDetailedMotionStates(); - + myCharacterController->buildPhysicsTransaction(transaction); _physicsEngine->processTransaction(transaction); myCharacterController->handleProcessedPhysicsTransaction(transaction); - + _physicsEngine->setCharacterController(nullptr); // the _shapeManager should have zero references @@ -2807,7 +2802,7 @@ Application::~Application() { DependencyManager::destroy(); - DependencyManager::destroy(); // must be destroyed before the FramebufferCache + DependencyManager::destroy(); // must be destroyed before the FramebufferCache DependencyManager::destroy(); @@ -2881,7 +2876,7 @@ void Application::initializeGL() { if (!nsightActive()) { _chromiumShareContext = new OffscreenGLCanvas(); _chromiumShareContext->setObjectName("ChromiumShareContext"); - auto format =QSurfaceFormat::defaultFormat(); + auto format = QSurfaceFormat::defaultFormat(); #ifdef Q_OS_MAC // On mac, the primary shared OpenGL context must be a 3.2 core context, // or chromium flips out and spews error spam (but renders fine) @@ -2900,7 +2895,6 @@ void Application::initializeGL() { } #endif - _glWidget->createContext(globalShareContext); if (!_glWidget->makeCurrent()) { @@ -2909,7 +2903,7 @@ void Application::initializeGL() { #if !defined(DISABLE_QML) QStringList chromiumFlags; - // Bug 21993: disable microphone and camera input + // Bug 21993: disable microphone and camera input chromiumFlags << "--use-fake-device-for-media-stream"; // Disable signed distance field font rendering on ATI/AMD GPUs, due to // https://highfidelity.manuscript.com/f/cases/13677/Text-showing-up-white-on-Marketplace-app @@ -2946,7 +2940,6 @@ void Application::initializeGL() { } #endif - // Build an offscreen GL context for the main thread. _glWidget->makeCurrent(); glClearColor(0.2f, 0.2f, 0.2f, 1); @@ -2964,18 +2957,18 @@ void Application::initializeDisplayPlugins() { auto defaultDisplayPlugin = displayPlugins.at(0); // Once time initialization code DisplayPluginPointer targetDisplayPlugin; - foreach(auto displayPlugin, displayPlugins) { + foreach (auto displayPlugin, displayPlugins) { displayPlugin->setContext(_graphicsEngine.getGPUContext()); if (displayPlugin->getName() == lastActiveDisplayPluginName) { targetDisplayPlugin = displayPlugin; } QObject::connect(displayPlugin.get(), &DisplayPlugin::recommendedFramebufferSizeChanged, - [this](const QSize& size) { resizeGL(); }); + [this](const QSize& size) { resizeGL(); }); QObject::connect(displayPlugin.get(), &DisplayPlugin::resetSensorsRequested, this, &Application::requestReset); if (displayPlugin->isHmd()) { auto hmdDisplayPlugin = dynamic_cast(displayPlugin.get()); QObject::connect(hmdDisplayPlugin, &HmdDisplayPlugin::hmdMountedChanged, - DependencyManager::get().data(), &HMDScriptingInterface::mountedChanged); + DependencyManager::get().data(), &HMDScriptingInterface::mountedChanged); QObject::connect(hmdDisplayPlugin, &HmdDisplayPlugin::hmdVisibleChanged, this, &Application::hmdVisibleChanged); } } @@ -3012,7 +3005,8 @@ void Application::showLoginScreen() { auto dialogsManager = DependencyManager::get(); if (!accountManager->isLoggedIn()) { if (!isHMDMode()) { - auto toolbar = DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); + auto toolbar = + DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); toolbar->writeProperty("visible", false); } _loginDialogPoppedUp = true; @@ -3041,60 +3035,64 @@ void Application::initializeUi() { QmlContextCallback commerceCallback = [](QQmlContext* context) { context->setContextProperty("Commerce", DependencyManager::get().data()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/checkout/Checkout.qml" }, - QUrl{ "hifi/commerce/common/CommerceLightbox.qml" }, - QUrl{ "hifi/commerce/common/EmulatedMarketplaceHeader.qml" }, - QUrl{ "hifi/commerce/common/FirstUseTutorial.qml" }, - QUrl{ "hifi/commerce/common/sendAsset/SendAsset.qml" }, - QUrl{ "hifi/commerce/common/SortableListModel.qml" }, - QUrl{ "hifi/commerce/inspectionCertificate/InspectionCertificate.qml" }, - QUrl{ "hifi/commerce/marketplaceItemTester/MarketplaceItemTester.qml"}, - QUrl{ "hifi/commerce/purchases/PurchasedItem.qml" }, - QUrl{ "hifi/commerce/purchases/Purchases.qml" }, - QUrl{ "hifi/commerce/wallet/Help.qml" }, - QUrl{ "hifi/commerce/wallet/NeedsLogIn.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseChange.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseModal.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseSelection.qml" }, - QUrl{ "hifi/commerce/wallet/Wallet.qml" }, - QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, - QUrl{ "hifi/commerce/wallet/WalletSetup.qml" }, - QUrl{ "hifi/dialogs/security/Security.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageChange.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageModel.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageSelection.qml" }, - QUrl{ "hifi/tablet/TabletMenu.qml" }, - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - }, commerceCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/checkout/Checkout.qml" }, + QUrl{ "hifi/commerce/common/CommerceLightbox.qml" }, + QUrl{ "hifi/commerce/common/EmulatedMarketplaceHeader.qml" }, + QUrl{ "hifi/commerce/common/FirstUseTutorial.qml" }, + QUrl{ "hifi/commerce/common/sendAsset/SendAsset.qml" }, + QUrl{ "hifi/commerce/common/SortableListModel.qml" }, + QUrl{ "hifi/commerce/inspectionCertificate/InspectionCertificate.qml" }, + QUrl{ "hifi/commerce/marketplaceItemTester/MarketplaceItemTester.qml" }, + QUrl{ "hifi/commerce/purchases/PurchasedItem.qml" }, + QUrl{ "hifi/commerce/purchases/Purchases.qml" }, + QUrl{ "hifi/commerce/wallet/Help.qml" }, + QUrl{ "hifi/commerce/wallet/NeedsLogIn.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseChange.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseModal.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseSelection.qml" }, + QUrl{ "hifi/commerce/wallet/Wallet.qml" }, + QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, + QUrl{ "hifi/commerce/wallet/WalletSetup.qml" }, + QUrl{ "hifi/dialogs/security/Security.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageChange.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageModel.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageSelection.qml" }, + QUrl{ "hifi/tablet/TabletMenu.qml" }, + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + }, + commerceCallback); QmlContextCallback marketplaceCallback = [](QQmlContext* context) { context->setContextProperty("MarketplaceScriptingInterface", new QmlMarketplace()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - }, marketplaceCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + }, + marketplaceCallback); QmlContextCallback platformInfoCallback = [](QQmlContext* context) { context->setContextProperty("PlatformInfo", new PlatformInfoScriptingInterface()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - QUrl{ "hifi/commerce/purchases/Purchases.qml" }, - QUrl{ "hifi/commerce/wallet/Wallet.qml" }, - QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, - QUrl{ "hifi/tablet/TabletAddressDialog.qml" }, - QUrl{ "hifi/Card.qml" }, - QUrl{ "hifi/Pal.qml" }, - QUrl{ "hifi/NameCard.qml" }, - }, platformInfoCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + QUrl{ "hifi/commerce/purchases/Purchases.qml" }, + QUrl{ "hifi/commerce/wallet/Wallet.qml" }, + QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, + QUrl{ "hifi/tablet/TabletAddressDialog.qml" }, + QUrl{ "hifi/Card.qml" }, + QUrl{ "hifi/Pal.qml" }, + QUrl{ "hifi/NameCard.qml" }, + }, + platformInfoCallback); QmlContextCallback ttsCallback = [](QQmlContext* context) { context->setContextProperty("TextToSpeech", DependencyManager::get().data()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/tts/TTS.qml" } - }, ttsCallback); + OffscreenQmlSurface::addWhitelistContextHandler({ QUrl{ "hifi/tts/TTS.qml" } }, ttsCallback); qmlRegisterType("Hifi", 1, 0, "ResourceImageItem"); qmlRegisterType("Hifi", 1, 0, "Preference"); qmlRegisterType("HifiWeb", 1, 0, "WebBrowserSuggestionsEngine"); @@ -3105,18 +3103,15 @@ void Application::initializeUi() { } auto offscreenUi = getOffscreenUI(); - connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootContextCreated, - this, &Application::onDesktopRootContextCreated); - connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootItemCreated, - this, &Application::onDesktopRootItemCreated); + connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootContextCreated, this, + &Application::onDesktopRootContextCreated); + connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootItemCreated, this, &Application::onDesktopRootItemCreated); #if !defined(DISABLE_QML) offscreenUi->setProxyWindow(_window->windowHandle()); // OffscreenUi is a subclass of OffscreenQmlSurface specifically designed to // support the window management and scripting proxies for VR use - DeadlockWatchdogThread::withPause([&] { - offscreenUi->createDesktop(PathUtils::qmlUrl("hifi/Desktop.qml")); - }); + DeadlockWatchdogThread::withPause([&] { offscreenUi->createDesktop(PathUtils::qmlUrl("hifi/Desktop.qml")); }); // FIXME either expose so that dialogs can set this themselves or // do better detection in the offscreen UI of what has focus offscreenUi->setNavigationFocused(false); @@ -3140,7 +3135,7 @@ void Application::initializeUi() { }); offscreenUi->resume(); #endif - connect(_window, &MainWindow::windowGeometryChanged, [this](const QRect& r){ + connect(_window, &MainWindow::windowGeometryChanged, [this](const QRect& r) { resizeGL(); if (_touchscreenVirtualPadDevice) { _touchscreenVirtualPadDevice->resize(); @@ -3149,7 +3144,7 @@ void Application::initializeUi() { // This will set up the input plugins UI _activeInputPlugins.clear(); - foreach(auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { + foreach (auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { if (KeyboardMouseDevice::NAME == inputPlugin->getName()) { _keyboardMouseDevice = std::dynamic_pointer_cast(inputPlugin); } @@ -3160,10 +3155,8 @@ void Application::initializeUi() { _touchscreenVirtualPadDevice = std::dynamic_pointer_cast(inputPlugin); #if defined(ANDROID_APP_INTERFACE) auto& virtualPadManager = VirtualPad::Manager::instance(); - connect(&virtualPadManager, &VirtualPad::Manager::hapticFeedbackRequested, - this, [](int duration) { - AndroidHelper::instance().performHapticFeedback(duration); - }); + connect(&virtualPadManager, &VirtualPad::Manager::hapticFeedbackRequested, this, + [](int duration) { AndroidHelper::instance().performHapticFeedback(duration); }); #endif } } @@ -3171,10 +3164,9 @@ void Application::initializeUi() { auto compositorHelper = DependencyManager::get(); connect(compositorHelper.data(), &CompositorHelper::allowMouseCaptureChanged, this, [=] { if (isHMDMode()) { - auto compositorHelper = DependencyManager::get(); // don't capture outer smartpointer - showCursor(compositorHelper->getAllowMouseCapture() ? - Cursor::Manager::lookupIcon(_preferredCursor.get()) : - Cursor::Icon::SYSTEM); + auto compositorHelper = DependencyManager::get(); // don't capture outer smartpointer + showCursor(compositorHelper->getAllowMouseCapture() ? Cursor::Manager::lookupIcon(_preferredCursor.get()) + : Cursor::Icon::SYSTEM); } }); @@ -3185,8 +3177,10 @@ void Application::initializeUi() { if (rootObject == TabletScriptingInterface::QML) { // in Qt 5.10.0 there is already an "Audio" object in the QML context // though I failed to find it (from QtMultimedia??). So.. let it be "AudioScriptingInterface" - surfaceContext->setContextProperty("AudioScriptingInterface", DependencyManager::get().data()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("AudioScriptingInterface", + DependencyManager::get().data()); + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED } }); @@ -3202,10 +3196,12 @@ void Application::initializeUi() { auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins(); // first sort the plugins into groupings: standard, advanced, developer std::stable_sort(displayPlugins.begin(), displayPlugins.end(), - [](const DisplayPluginPointer& a, const DisplayPluginPointer& b) -> bool { return a->getGrouping() < b->getGrouping(); }); + [](const DisplayPluginPointer& a, const DisplayPluginPointer& b) -> bool { + return a->getGrouping() < b->getGrouping(); + }); int dpIndex = 1; // concatenate the groupings into a single list in the order: standard, advanced, developer - for(const auto& displayPlugin : displayPlugins) { + for (const auto& displayPlugin : displayPlugins) { addDisplayPluginToMenu(displayPlugin, dpIndex, _displayPlugin == displayPlugin); dpIndex++; } @@ -3216,18 +3212,15 @@ void Application::initializeUi() { } #endif - // The display plugins are created before the menu now, so we need to do this here to hide the menu bar // now that it exists if (_window && _window->isFullScreen()) { setFullscreen(nullptr, true); } - setIsInterstitialMode(true); } - void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { auto engine = surfaceContext->engine(); // in Qt 5.10.0 there is already an "Audio" object in the QML context @@ -3262,7 +3255,8 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("AvatarList", DependencyManager::get().data()); surfaceContext->setContextProperty("Users", DependencyManager::get().data()); - surfaceContext->setContextProperty("UserActivityLogger", DependencyManager::get().data()); + surfaceContext->setContextProperty("UserActivityLogger", + DependencyManager::get().data()); surfaceContext->setContextProperty("Camera", &_myCamera); @@ -3287,8 +3281,10 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("InputConfiguration", DependencyManager::get().data()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - surfaceContext->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED surfaceContext->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); surfaceContext->setContextProperty("DialogsManager", _dialogsManagerScriptingInterface); @@ -3346,12 +3342,10 @@ void Application::userKickConfirmation(const QUuid& nodeID) { } QString kickMessage = "Do you wish to kick " + userName + " from your domain"; - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Kick User", kickMessage, - QMessageBox::Yes | QMessageBox::No); + ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Kick User", kickMessage, QMessageBox::Yes | QMessageBox::No); if (dlg->getDialogItem()) { - - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); bool yes = (static_cast(answer.toInt()) == QMessageBox::Yes); @@ -3370,14 +3364,16 @@ void Application::userKickConfirmation(const QUuid& nodeID) { void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditionalContextProperties) { surfaceContext->setContextProperty("Users", DependencyManager::get().data()); surfaceContext->setContextProperty("HMD", DependencyManager::get().data()); - surfaceContext->setContextProperty("UserActivityLogger", DependencyManager::get().data()); + surfaceContext->setContextProperty("UserActivityLogger", + DependencyManager::get().data()); surfaceContext->setContextProperty("Preferences", DependencyManager::get().data()); surfaceContext->setContextProperty("Vec3", new Vec3()); surfaceContext->setContextProperty("Quat", new Quat()); surfaceContext->setContextProperty("MyAvatar", DependencyManager::get()->getMyAvatar().get()); surfaceContext->setContextProperty("Entities", DependencyManager::get().data()); surfaceContext->setContextProperty("Snapshot", DependencyManager::get().data()); - surfaceContext->setContextProperty("KeyboardScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("KeyboardScriptingInterface", + DependencyManager::get().data()); if (setAdditionalContextProperties) { auto tabletScriptingInterface = DependencyManager::get(); @@ -3390,8 +3386,10 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("MenuInterface", MenuScriptingInterface::getInstance()); surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - surfaceContext->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED surfaceContext->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); // in Qt 5.10.0 there is already an "Audio" object in the QML context @@ -3411,14 +3409,16 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("InputConfiguration", DependencyManager::get().data()); surfaceContext->setContextProperty("SoundCache", DependencyManager::get().data()); surfaceContext->setContextProperty("AvatarBookmarks", DependencyManager::get().data()); - surfaceContext->setContextProperty("Render", AbstractViewStateInterface::instance()->getRenderEngine()->getConfiguration().get()); + surfaceContext->setContextProperty("Render", + AbstractViewStateInterface::instance()->getRenderEngine()->getConfiguration().get()); surfaceContext->setContextProperty("Workload", qApp->getGameWorkload()._engine->getConfiguration().get()); surfaceContext->setContextProperty("Controller", DependencyManager::get().data()); surfaceContext->setContextProperty("Pointers", DependencyManager::get().data()); surfaceContext->setContextProperty("Window", DependencyManager::get().data()); surfaceContext->setContextProperty("Reticle", qApp->getApplicationCompositor().getReticleInterface()); surfaceContext->setContextProperty("HiFiAbout", AboutUtil::getInstance()); - surfaceContext->setContextProperty("WalletScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("WalletScriptingInterface", + DependencyManager::get().data()); surfaceContext->setContextProperty("ResourceRequestObserver", DependencyManager::get().data()); } } @@ -3438,20 +3438,17 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { // Using the latter will cause the camera to wobble with idle animations, // or with changes from the face tracker if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) { - _thirdPersonHMDCameraBoomValid= false; + _thirdPersonHMDCameraBoomValid = false; if (isHMDMode()) { mat4 camMat = myAvatar->getSensorToWorldMatrix() * myAvatar->getHMDSensorMatrix(); _myCamera.setPosition(extractTranslation(camMat)); _myCamera.setOrientation(glmExtractRotation(camMat)); - } - else { + } else { _myCamera.setPosition(myAvatar->getDefaultEyePosition()); _myCamera.setOrientation(myAvatar->getMyHead()->getHeadOrientation()); } - } - else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { + } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { if (isHMDMode()) { - if (!_thirdPersonHMDCameraBoomValid) { const glm::vec3 CAMERA_OFFSET = glm::vec3(0.0f, 0.0f, 0.7f); _thirdPersonHMDCameraBoom = cancelOutRollAndPitch(myAvatar->getHMDSensorOrientation()) * CAMERA_OFFSET; @@ -3460,32 +3457,29 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { glm::mat4 thirdPersonCameraSensorToWorldMatrix = myAvatar->getSensorToWorldMatrix(); - const glm::vec3 cameraPos = myAvatar->getHMDSensorPosition() + _thirdPersonHMDCameraBoom * myAvatar->getBoomLength(); + const glm::vec3 cameraPos = + myAvatar->getHMDSensorPosition() + _thirdPersonHMDCameraBoom * myAvatar->getBoomLength(); glm::mat4 sensorCameraMat = createMatFromQuatAndPos(myAvatar->getHMDSensorOrientation(), cameraPos); glm::mat4 worldCameraMat = thirdPersonCameraSensorToWorldMatrix * sensorCameraMat; _myCamera.setOrientation(glm::normalize(glmExtractRotation(worldCameraMat))); _myCamera.setPosition(extractTranslation(worldCameraMat)); - } - else { + } else { _thirdPersonHMDCameraBoomValid = false; _myCamera.setOrientation(myAvatar->getHead()->getOrientation()); if (isOptionChecked(MenuOption::CenterPlayerInView)) { - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + _myCamera.getOrientation() * boomOffset); - } - else { - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + myAvatar->getWorldOrientation() * boomOffset); + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + _myCamera.getOrientation() * boomOffset); + } else { + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + myAvatar->getWorldOrientation() * boomOffset); } } - } - else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) { - _thirdPersonHMDCameraBoomValid= false; + } else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) { + _thirdPersonHMDCameraBoomValid = false; if (isHMDMode()) { - auto mirrorBodyOrientation = myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f)); + auto mirrorBodyOrientation = + myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f)); glm::quat hmdRotation = extractRotation(myAvatar->getHMDSensorMatrix()); // Mirror HMD yaw and roll @@ -3502,26 +3496,24 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { // Mirror HMD lateral offsets hmdOffset.x = -hmdOffset.x; - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) - + mirrorBodyOrientation * glm::vec3(0.0f, 0.0f, 1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror - + mirrorBodyOrientation * hmdOffset); - } - else { + _myCamera.setPosition( + myAvatar->getDefaultEyePosition() + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) + + mirrorBodyOrientation * glm::vec3(0.0f, 0.0f, 1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror + + mirrorBodyOrientation * hmdOffset); + } else { auto userInputMapper = DependencyManager::get(); const float YAW_SPEED = TWO_PI / 5.0f; float deltaYaw = userInputMapper->getActionState(controller::Action::YAW) * YAW_SPEED * deltaTime; _mirrorYawOffset += deltaYaw; _myCamera.setOrientation(myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f))); - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) - + (myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, _mirrorYawOffset, 0.0f))) * - glm::vec3(0.0f, 0.0f, -1.0f) * myAvatar->getBoomLength() * _scaleMirror); + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) + + (myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, _mirrorYawOffset, 0.0f))) * + glm::vec3(0.0f, 0.0f, -1.0f) * myAvatar->getBoomLength() * _scaleMirror); } renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE; - } - else if (_myCamera.getMode() == CAMERA_MODE_ENTITY) { - _thirdPersonHMDCameraBoomValid= false; + } else if (_myCamera.getMode() == CAMERA_MODE_ENTITY) { + _thirdPersonHMDCameraBoomValid = false; EntityItemPointer cameraEntity = _myCamera.getCameraEntityPointer(); if (cameraEntity != nullptr) { if (isHMDMode()) { @@ -3529,8 +3521,7 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { _myCamera.setOrientation(cameraEntity->getWorldOrientation() * hmdRotation); glm::vec3 hmdOffset = extractTranslation(myAvatar->getHMDSensorMatrix()); _myCamera.setPosition(cameraEntity->getWorldPosition() + (hmdRotation * hmdOffset)); - } - else { + } else { _myCamera.setOrientation(cameraEntity->getWorldOrientation()); _myCamera.setPosition(cameraEntity->getWorldPosition()); } @@ -3550,7 +3541,6 @@ void Application::runTests() { } void Application::faceTrackerMuteToggled() { - QAction* muteAction = Menu::getInstance()->getActionForOption(MenuOption::MuteFaceTracking); Q_CHECK_PTR(muteAction); bool isMuted = getSelectedFaceTracker()->isMuted(); @@ -3597,9 +3587,8 @@ void Application::setPreferredCursor(const QString& cursorName) { if (_displayPlugin && _displayPlugin->isHmd()) { _preferredCursor.set(cursorName.isEmpty() ? DEFAULT_CURSOR_NAME : cursorName); - } - else { - _preferredCursor.set(cursorName.isEmpty() ? Cursor::Manager::getIconName(Cursor::Icon::SYSTEM) : cursorName); + } else { + _preferredCursor.set(cursorName.isEmpty() ? Cursor::Manager::getIconName(Cursor::Icon::SYSTEM) : cursorName); } showCursor(Cursor::Manager::lookupIcon(_preferredCursor.get())); @@ -3655,7 +3644,8 @@ void Application::showHelp() { QUrlQuery queryString; queryString.addQueryItem("handControllerName", handControllerName); queryString.addQueryItem("defaultTab", defaultTab); - TabletProxy* tablet = dynamic_cast(DependencyManager::get()->getTablet(SYSTEM_TABLET)); + TabletProxy* tablet = + dynamic_cast(DependencyManager::get()->getTablet(SYSTEM_TABLET)); tablet->gotoWebScreen(PathUtils::resourcesUrl() + INFO_HELP_PATH + "?" + queryString.toString()); DependencyManager::get()->openTablet(); //InfoView::show(INFO_HELP_PATH, false, queryString.toString()); @@ -3695,8 +3685,8 @@ void Application::resizeGL() { // FIXME the aspect ratio for stereo displays is incorrect based on this. float aspectRatio = displayPlugin->getRecommendedAspectRatio(); - _myCamera.setProjection(glm::perspective(glm::radians(_fieldOfView.get()), aspectRatio, - DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP)); + _myCamera.setProjection( + glm::perspective(glm::radians(_fieldOfView.get()), aspectRatio, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP)); // Possible change in aspect ratio { QMutexLocker viewLocker(&_viewMutex); @@ -3713,14 +3703,12 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { bool sandboxIsRunning = SandboxUtils::readStatus(reply->readAll()); - enum HandControllerType { + enum HandControllerType + { Vive, Oculus }; - static const std::map MIN_CONTENT_VERSION = { - { Vive, 1 }, - { Oculus, 27 } - }; + static const std::map MIN_CONTENT_VERSION = { { Vive, 1 }, { Oculus, 27 } }; // Get sandbox content set version auto acDirPath = PathUtils::getAppDataPath() + "../../" + BuildInfo::MODIFIED_ORGANIZATION + "/assignment-client/"; @@ -3730,7 +3718,7 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { QFile contentVersionFile(contentVersionPath); if (contentVersionFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QString line = contentVersionFile.readAll(); - contentVersion = line.toInt(); // returns 0 if conversion fails + contentVersion = line.toInt(); // returns 0 if conversion fails } // Get controller availability @@ -3748,7 +3736,8 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { bool isUsingHMD = _displayPlugin->isHmd(); bool isUsingHMDAndHandControllers = hasHMD && hasHandControllers && isUsingHMD; - qCDebug(interfaceapp) << "HMD:" << hasHMD << ", Hand Controllers: " << hasHandControllers << ", Using HMD: " << isUsingHMDAndHandControllers; + qCDebug(interfaceapp) << "HMD:" << hasHMD << ", Hand Controllers: " << hasHandControllers + << ", Using HMD: " << isUsingHMDAndHandControllers; // when --url in command line, teleport to location const QString HIFI_URL_COMMAND_LINE_KEY = "--url"; @@ -3770,8 +3759,8 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { // If this is a first run we short-circuit the address passed in if (_firstRun.get()) { - DependencyManager::get()->goToEntry(); - sentTo = SENT_TO_ENTRY; + DependencyManager::get()->goToEntry(); + sentTo = SENT_TO_ENTRY; _firstRun.set(false); } else { @@ -3790,22 +3779,21 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { sentTo = SENT_TO_PREVIOUS_LOCATION; } - UserActivityLogger::getInstance().logAction("startup_sent_to", { - { "sent_to", sentTo }, - { "sandbox_is_running", sandboxIsRunning }, - { "has_hmd", hasHMD }, - { "has_hand_controllers", hasHandControllers }, - { "is_using_hmd", isUsingHMD }, - { "is_using_hmd_and_hand_controllers", isUsingHMDAndHandControllers }, - { "content_version", contentVersion } - }); + UserActivityLogger::getInstance().logAction("startup_sent_to", + { { "sent_to", sentTo }, + { "sandbox_is_running", sandboxIsRunning }, + { "has_hmd", hasHMD }, + { "has_hand_controllers", hasHandControllers }, + { "is_using_hmd", isUsingHMD }, + { "is_using_hmd_and_hand_controllers", isUsingHMDAndHandControllers }, + { "content_version", contentVersion } }); _connectionMonitor.init(); } bool Application::importJSONFromURL(const QString& urlString) { // we only load files that terminate in just .json (not .svo.json and not .ava.json) - QUrl jsonURL { urlString }; + QUrl jsonURL{ urlString }; emit svoImportRequested(urlString); return true; @@ -3951,19 +3939,18 @@ bool Application::handleKeyEventForFocusedEntity(QEvent* event) { if (_keyboardFocusedEntity.get() != UNKNOWN_ENTITY_ID) { switch (event->type()) { case QEvent::KeyPress: - case QEvent::KeyRelease: - { - auto eventHandler = getEntities()->getEventHandler(_keyboardFocusedEntity.get()); - if (eventHandler) { - event->setAccepted(false); - QCoreApplication::sendEvent(eventHandler, event); - if (event->isAccepted()) { - _lastAcceptedKeyPress = usecTimestampNow(); - return true; - } + case QEvent::KeyRelease: { + auto eventHandler = getEntities()->getEventHandler(_keyboardFocusedEntity.get()); + if (eventHandler) { + event->setAccepted(false); + QCoreApplication::sendEvent(eventHandler, event); + if (event->isAccepted()) { + _lastAcceptedKeyPress = usecTimestampNow(); + return true; } - break; } + break; + } default: break; } @@ -3999,19 +3986,18 @@ static void dumpEventQueue(QThread* thread) { qDebug() << " " << type; } } -#endif // DEBUG_EVENT_QUEUE +#endif // DEBUG_EVENT_QUEUE -bool Application::notify(QObject * object, QEvent * event) { +bool Application::notify(QObject* object, QEvent* event) { if (thread() == QThread::currentThread()) { PROFILE_RANGE_IF_LONGER(app, "notify", 2) return QApplication::notify(object, event); - } - + } + return QApplication::notify(object, event); } bool Application::event(QEvent* event) { - if (_aboutToQuit) { return false; } @@ -4043,7 +4029,7 @@ bool Application::event(QEvent* event) { dumpEventQueue(QThread::currentThread()); } } -#endif // DEBUG_EVENT_QUEUE +#endif // DEBUG_EVENT_QUEUE _pendingIdleEvent.store(false); @@ -4107,7 +4093,6 @@ bool Application::event(QEvent* event) { } bool Application::eventFilter(QObject* object, QEvent* event) { - if (_aboutToQuit && event->type() != QEvent::DeferredDelete && event->type() != QEvent::Destroy) { return true; } @@ -4149,7 +4134,7 @@ void Application::keyPressEvent(QKeyEvent* event) { _keysPressed.insert(event->key(), *event); } - _controllerScriptingInterface->emitKeyPressEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitKeyPressEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isKeyCaptured(event) || isInterstitialMode()) { return; @@ -4239,9 +4224,10 @@ void Application::keyPressEvent(QKeyEvent* event) { case Qt::Key_G: if (isShifted && isMeta && Menu::getInstance() && Menu::getInstance()->getMenu("Developer")->isVisible()) { static const QString HIFI_FRAMES_FOLDER_VAR = "HIFI_FRAMES_FOLDER"; - static const QString GPU_FRAME_FOLDER = QProcessEnvironment::systemEnvironment().contains(HIFI_FRAMES_FOLDER_VAR) - ? QProcessEnvironment::systemEnvironment().value(HIFI_FRAMES_FOLDER_VAR) - : "hifiFrames"; + static const QString GPU_FRAME_FOLDER = + QProcessEnvironment::systemEnvironment().contains(HIFI_FRAMES_FOLDER_VAR) + ? QProcessEnvironment::systemEnvironment().value(HIFI_FRAMES_FOLDER_VAR) + : "hifiFrames"; static QString GPU_FRAME_TEMPLATE = GPU_FRAME_FOLDER + "/{DATE}_{TIME}"; QString fullPath = FileUtils::computeDocumentPath(FileUtils::replaceDateTimeTokens(GPU_FRAME_TEMPLATE)); if (FileUtils::canCreateFile(fullPath)) { @@ -4320,16 +4306,18 @@ void Application::keyPressEvent(QKeyEvent* event) { if (!isShifted && !isMeta && !isOption && !event->isAutoRepeat()) { AudioInjectorOptions options; options.localOnly = true; - options.positionSet = false; // system sound + options.positionSet = false; // system sound options.stereo = true; Setting::Handle notificationSounds{ MenuOption::NotificationSounds, true }; Setting::Handle notificationSoundSnapshot{ MenuOption::NotificationSoundsSnapshot, true }; if (notificationSounds.get() && notificationSoundSnapshot.get()) { if (_snapshotSoundInjector) { - DependencyManager::get()->setOptionsAndRestart(_snapshotSoundInjector, options); + DependencyManager::get()->setOptionsAndRestart(_snapshotSoundInjector, + options); } else { - _snapshotSoundInjector = DependencyManager::get()->playSound(_snapshotSound, options); + _snapshotSoundInjector = + DependencyManager::get()->playSound(_snapshotSound, options); } } takeSnapshot(true); @@ -4350,7 +4338,7 @@ void Application::keyPressEvent(QKeyEvent* event) { } else { showCursor(Cursor::Icon::DEFAULT); } - } else if (!event->isAutoRepeat()){ + } else if (!event->isAutoRepeat()) { resetSensors(true); } break; @@ -4410,7 +4398,7 @@ void Application::keyReleaseEvent(QKeyEvent* event) { AndroidHelper::instance().requestActivity("Home", false); } #endif - _controllerScriptingInterface->emitKeyReleaseEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitKeyReleaseEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isKeyCaptured(event)) { @@ -4420,7 +4408,6 @@ void Application::keyReleaseEvent(QKeyEvent* event) { if (_keyboardMouseDevice->isActive()) { _keyboardMouseDevice->keyReleaseEvent(event); } - } void Application::focusInEvent(QFocusEvent* event) { @@ -4429,10 +4416,9 @@ void Application::focusInEvent(QFocusEvent* event) { } } - void Application::focusOutEvent(QFocusEvent* event) { auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); - foreach(auto inputPlugin, inputPlugins) { + foreach (auto inputPlugin, inputPlugins) { if (inputPlugin->isActive()) { inputPlugin->pluginFocusOutEvent(); } @@ -4458,7 +4444,7 @@ void Application::synthesizeKeyReleasEvents() { QHash keysPressed; std::swap(keysPressed, _keysPressed); for (auto& ev : keysPressed) { - QKeyEvent synthesizedEvent { QKeyEvent::KeyRelease, ev.key(), Qt::NoModifier, ev.text() }; + QKeyEvent synthesizedEvent{ QKeyEvent::KeyRelease, ev.key(), Qt::NoModifier, ev.text() }; keyReleaseEvent(&synthesizedEvent); } } @@ -4475,7 +4461,7 @@ void Application::maybeToggleMenuVisible(QMouseEvent* event) const { if (event->pos().y() <= MENU_TOGGLE_AREA) { menuBar->setVisible(true); } - } else { + } else { if (event->pos().y() > MENU_TOGGLE_AREA) { menuBar->setVisible(false); } @@ -4495,7 +4481,7 @@ void Application::mouseMoveEvent(QMouseEvent* event) { // compositor reticle // handleRealMouseMoveEvent() will return true, if we shouldn't process the event further if (!compositor.fakeEventActive() && compositor.handleRealMouseMoveEvent()) { - return; // bail + return; // bail } #if !defined(DISABLE_QML) @@ -4515,17 +4501,14 @@ void Application::mouseMoveEvent(QMouseEvent* event) { buttons |= Qt::LeftButton; } - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), button, - buttons, event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), button, buttons, event->modifiers()); if (compositor.getReticleVisible() || !isHMDMode() || !compositor.getReticleOverDesktop() || getOverlays().getOverlayAtPoint(glm::vec2(transformedPos.x(), transformedPos.y())) != UNKNOWN_ENTITY_ID) { getEntities()->mouseMoveEvent(&mappedEvent); } - _controllerScriptingInterface->emitMouseMoveEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMouseMoveEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4555,11 +4538,12 @@ void Application::mousePressEvent(QMouseEvent* event) { QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); QUuid result = getEntities()->mousePressEvent(&mappedEvent); setKeyboardFocusEntity(getEntities()->wantsKeyboardFocus(result) ? result : UNKNOWN_ENTITY_ID); - _controllerScriptingInterface->emitMousePressEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMousePressEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4592,10 +4576,8 @@ void Application::mouseDoublePressEvent(QMouseEvent* event) { #else QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), event->button(), - event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); getEntities()->mouseDoublePressEvent(&mappedEvent); // if one of our scripts have asked to capture this event, then stop processing it @@ -4607,7 +4589,6 @@ void Application::mouseDoublePressEvent(QMouseEvent* event) { } void Application::mouseReleaseEvent(QMouseEvent* event) { - #if !defined(DISABLE_QML) auto offscreenUi = getOffscreenUI(); auto eventPosition = getApplicationCompositor().getMouseEventPosition(event); @@ -4615,14 +4596,12 @@ void Application::mouseReleaseEvent(QMouseEvent* event) { #else QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), event->button(), - event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); getEntities()->mouseReleaseEvent(&mappedEvent); - _controllerScriptingInterface->emitMouseReleaseEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMouseReleaseEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4641,7 +4620,7 @@ void Application::touchUpdateEvent(QTouchEvent* event) { if (event->type() == QEvent::TouchUpdate) { TouchEvent thisEvent(*event, _lastTouchEvent); - _controllerScriptingInterface->emitTouchUpdateEvent(thisEvent); // send events to any registered scripts + _controllerScriptingInterface->emitTouchUpdateEvent(thisEvent); // send events to any registered scripts _lastTouchEvent = thisEvent; } @@ -4663,10 +4642,10 @@ void Application::touchUpdateEvent(QTouchEvent* event) { void Application::touchBeginEvent(QTouchEvent* event) { _altPressed = false; - TouchEvent thisEvent(*event); // on touch begin, we don't compare to last event - _controllerScriptingInterface->emitTouchBeginEvent(thisEvent); // send events to any registered scripts + TouchEvent thisEvent(*event); // on touch begin, we don't compare to last event + _controllerScriptingInterface->emitTouchBeginEvent(thisEvent); // send events to any registered scripts - _lastTouchEvent = thisEvent; // and we reset our last event to this event before we call our update + _lastTouchEvent = thisEvent; // and we reset our last event to this event before we call our update touchUpdateEvent(event); // if one of our scripts have asked to capture this event, then stop processing it @@ -4683,13 +4662,12 @@ void Application::touchBeginEvent(QTouchEvent* event) { if (_touchscreenVirtualPadDevice && _touchscreenVirtualPadDevice->isActive()) { _touchscreenVirtualPadDevice->touchBeginEvent(event); } - } void Application::touchEndEvent(QTouchEvent* event) { _altPressed = false; TouchEvent thisEvent(*event, _lastTouchEvent); - _controllerScriptingInterface->emitTouchEndEvent(thisEvent); // send events to any registered scripts + _controllerScriptingInterface->emitTouchEndEvent(thisEvent); // send events to any registered scripts _lastTouchEvent = thisEvent; // if one of our scripts have asked to capture this event, then stop processing it @@ -4720,7 +4698,7 @@ void Application::touchGestureEvent(QGestureEvent* event) { void Application::wheelEvent(QWheelEvent* event) const { _altPressed = false; - _controllerScriptingInterface->emitWheelEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitWheelEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isWheelCaptured() || getLoginDialogPoppedUp()) { @@ -4732,7 +4710,7 @@ void Application::wheelEvent(QWheelEvent* event) const { } } -void Application::dropEvent(QDropEvent *event) { +void Application::dropEvent(QDropEvent* event) { const QMimeData* mimeData = event->mimeData(); for (auto& url : mimeData->urls()) { QString urlString = url.toString(); @@ -4758,8 +4736,8 @@ bool Application::acceptSnapshot(const QString& urlString) { DependencyManager::get()->handleLookupString(snapshotData->getURL().toString()); } } else { - OffscreenUi::asyncWarning("", "No location details were found in the file\n" + - snapshotPath + "\nTry dragging in an authentic Hifi snapshot."); + OffscreenUi::asyncWarning("", "No location details were found in the file\n" + snapshotPath + + "\nTry dragging in an authentic Hifi snapshot."); } return true; } @@ -4772,41 +4750,39 @@ bool Application::acceptSnapshot(const QString& urlString) { #pragma comment(lib, "ntdll.lib") extern "C" { - enum SYSTEM_INFORMATION_CLASS { - SystemBasicInformation = 0, - SystemProcessorPerformanceInformation = 8, - }; +enum SYSTEM_INFORMATION_CLASS +{ + SystemBasicInformation = 0, + SystemProcessorPerformanceInformation = 8, +}; - struct SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { - LARGE_INTEGER IdleTime; - LARGE_INTEGER KernelTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER DpcTime; - LARGE_INTEGER InterruptTime; - ULONG InterruptCount; - }; +struct SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { + LARGE_INTEGER IdleTime; + LARGE_INTEGER KernelTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER DpcTime; + LARGE_INTEGER InterruptTime; + ULONG InterruptCount; +}; - struct SYSTEM_BASIC_INFORMATION { - ULONG Reserved; - ULONG TimerResolution; - ULONG PageSize; - ULONG NumberOfPhysicalPages; - ULONG LowestPhysicalPageNumber; - ULONG HighestPhysicalPageNumber; - ULONG AllocationGranularity; - ULONG_PTR MinimumUserModeAddress; - ULONG_PTR MaximumUserModeAddress; - ULONG_PTR ActiveProcessorsAffinityMask; - CCHAR NumberOfProcessors; - }; - - NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformation( - _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, - _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation, - _In_ ULONG SystemInformationLength, - _Out_opt_ PULONG ReturnLength - ); +struct SYSTEM_BASIC_INFORMATION { + ULONG Reserved; + ULONG TimerResolution; + ULONG PageSize; + ULONG NumberOfPhysicalPages; + ULONG LowestPhysicalPageNumber; + ULONG HighestPhysicalPageNumber; + ULONG AllocationGranularity; + ULONG_PTR MinimumUserModeAddress; + ULONG_PTR MaximumUserModeAddress; + ULONG_PTR ActiveProcessorsAffinityMask; + CCHAR NumberOfProcessors; +}; +NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformation(_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, + _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation, + _In_ ULONG SystemInformationLength, + _Out_opt_ PULONG ReturnLength); } template NTSTATUS NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, T& t) { @@ -4818,7 +4794,6 @@ NTSTATUS NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClas return NtQuerySystemInformation(SystemInformationClass, t.data(), (ULONG)(sizeof(T) * t.size()), nullptr); } - template void updateValueAndDelta(std::pair& pair, T newValue) { auto& value = pair.first; @@ -4830,11 +4805,11 @@ void updateValueAndDelta(std::pair& pair, T newValue) { struct MyCpuInfo { using ValueAndDelta = std::pair; std::string name; - ValueAndDelta kernel { 0, 0 }; - ValueAndDelta user { 0, 0 }; - ValueAndDelta idle { 0, 0 }; - float kernelUsage { 0.0f }; - float userUsage { 0.0f }; + ValueAndDelta kernel{ 0, 0 }; + ValueAndDelta user{ 0, 0 }; + ValueAndDelta idle{ 0, 0 }; + float kernelUsage{ 0.0f }; + float userUsage{ 0.0f }; void update(const SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION& cpuInfo) { updateValueAndDelta(kernel, cpuInfo.KernelTime.QuadPart); @@ -4852,13 +4827,13 @@ struct MyCpuInfo { void updateCpuInformation() { static std::once_flag once; - static SYSTEM_BASIC_INFORMATION systemInfo {}; + static SYSTEM_BASIC_INFORMATION systemInfo{}; static SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION cpuTotals; static std::vector cpuInfos; static std::vector myCpuInfos; static MyCpuInfo myCpuTotals; std::call_once(once, [&] { - NtQuerySystemInformation( SystemBasicInformation, systemInfo); + NtQuerySystemInformation(SystemBasicInformation, systemInfo); cpuInfos.resize(systemInfo.NumberOfProcessors); myCpuInfos.resize(systemInfo.NumberOfProcessors); for (size_t i = 0; i < systemInfo.NumberOfProcessors; ++i) { @@ -4883,20 +4858,14 @@ void updateCpuInformation() { // Update friendly structure auto& myCpuInfo = myCpuInfos[i]; myCpuInfo.update(cpuInfo); - PROFILE_COUNTER(app, myCpuInfo.name.c_str(), { - { "kernel", myCpuInfo.kernelUsage }, - { "user", myCpuInfo.userUsage } - }); + PROFILE_COUNTER(app, myCpuInfo.name.c_str(), { { "kernel", myCpuInfo.kernelUsage }, { "user", myCpuInfo.userUsage } }); } myCpuTotals.update(cpuTotals); - PROFILE_COUNTER(app, myCpuTotals.name.c_str(), { - { "kernel", myCpuTotals.kernelUsage }, - { "user", myCpuTotals.userUsage } - }); + PROFILE_COUNTER(app, myCpuTotals.name.c_str(), + { { "kernel", myCpuTotals.kernelUsage }, { "user", myCpuTotals.userUsage } }); } - static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; @@ -5020,8 +4989,10 @@ void Application::idle() { PROFILE_COUNTER_IF_CHANGED(app, "renderLoopRate", float, getRenderLoopRate()); PROFILE_COUNTER_IF_CHANGED(app, "currentDownloads", uint32_t, ResourceCache::getLoadingRequests().length()); PROFILE_COUNTER_IF_CHANGED(app, "pendingDownloads", uint32_t, ResourceCache::getPendingRequestCount()); - PROFILE_COUNTER_IF_CHANGED(app, "currentProcessing", int, DependencyManager::get()->getStat("Processing").toInt()); - PROFILE_COUNTER_IF_CHANGED(app, "pendingProcessing", int, DependencyManager::get()->getStat("PendingProcessing").toInt()); + PROFILE_COUNTER_IF_CHANGED(app, "currentProcessing", int, + DependencyManager::get()->getStat("Processing").toInt()); + PROFILE_COUNTER_IF_CHANGED(app, "pendingProcessing", int, + DependencyManager::get()->getStat("PendingProcessing").toInt()); auto renderConfig = _graphicsEngine.getRenderEngine()->getConfiguration(); PROFILE_COUNTER_IF_CHANGED(render, "gpuTime", float, (float)_graphicsEngine.getGPUContext()->getFrameTimerGPUAverage()); @@ -5051,7 +5022,7 @@ void Application::idle() { } } #endif - + checkChangeCursor(); #if !defined(DISABLE_QML) @@ -5086,9 +5057,9 @@ void Application::idle() { update(glm::clamp(secondsSinceLastUpdate, 0.0f, BIGGEST_DELTA_TIME_SECS)); } - { // Update keyboard focus highlight + { // Update keyboard focus highlight if (!_keyboardFocusedEntity.get().isInvalidID()) { - const quint64 LOSE_FOCUS_AFTER_ELAPSED_TIME = 30 * USECS_PER_SECOND; // if idle for 30 seconds, drop focus + const quint64 LOSE_FOCUS_AFTER_ELAPSED_TIME = 30 * USECS_PER_SECOND; // if idle for 30 seconds, drop focus quint64 elapsedSinceAcceptedKeyPress = usecTimestampNow() - _lastAcceptedKeyPress; if (elapsedSinceAcceptedKeyPress > LOSE_FOCUS_AFTER_ELAPSED_TIME) { setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); @@ -5118,7 +5089,7 @@ void Application::idle() { PerformanceWarning warn(showWarnings, "Application::idle()... pluginIdle()"); getActiveDisplayPlugin()->idle(); auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); - foreach(auto inputPlugin, inputPlugins) { + foreach (auto inputPlugin, inputPlugins) { if (inputPlugin->isActive()) { inputPlugin->idle(); } @@ -5206,9 +5177,7 @@ void Application::calibrateEyeTracker5Points() { } #endif -bool Application::exportEntities(const QString& filename, - const QVector& entityIDs, - const glm::vec3* givenOffset) { +bool Application::exportEntities(const QString& filename, const QVector& entityIDs, const glm::vec3* givenOffset) { QHash entities; auto nodeList = DependencyManager::get(); @@ -5221,7 +5190,7 @@ bool Application::exportEntities(const QString& filename, glm::vec3 root(TREE_SCALE, TREE_SCALE, TREE_SCALE); bool success = true; entityTree->withReadLock([entityIDs, entityTree, givenOffset, myAvatarID, &root, &entities, &success, &exportTree] { - for (auto entityID : entityIDs) { // Gather entities and properties. + for (auto entityID : entityIDs) { // Gather entities and properties. auto entityItem = entityTree->findEntityByEntityItemID(entityID); if (!entityItem) { qCWarning(interfaceapp) << "Skipping export of" << entityID << "that is not in scene."; @@ -5231,8 +5200,7 @@ bool Application::exportEntities(const QString& filename, if (!givenOffset) { EntityItemID parentID = entityItem->getParentID(); bool parentIsAvatar = (parentID == AVATAR_SELF_ID || parentID == myAvatarID); - if (!parentIsAvatar && (parentID.isInvalidID() || - !entityIDs.contains(parentID) || + if (!parentIsAvatar && (parentID.isInvalidID() || !entityIDs.contains(parentID) || !entityTree->findEntityByEntityItemID(parentID))) { // If parent wasn't selected, we want absolute position, which isn't in properties. auto position = entityItem->getWorldPosition(); @@ -5263,7 +5231,7 @@ bool Application::exportEntities(const QString& filename, properties.setPosition(properties.getPosition() - root); } else if (!entities.contains(parentID)) { entityDatum->globalizeProperties(properties, "Parent %3 of %2 %1 is not selected for export.", -root); - } // else valid parent -- don't offset + } // else valid parent -- don't offset } exportTree->addEntity(entityDatum->getEntityItemID(), properties); } @@ -5284,15 +5252,12 @@ bool Application::exportEntities(const QString& filename, float x, float y, floa AACube boundingCube(minCorner, cubeSize); QVector entities; auto entityTree = getEntities()->getTree(); - entityTree->withReadLock([&] { - entityTree->evalEntitiesInCube(boundingCube, PickFilter(), entities); - }); + entityTree->withReadLock([&] { entityTree->evalEntitiesInCube(boundingCube, PickFilter(), entities); }); return exportEntities(filename, entities, ¢er); } void Application::loadSettings() { - - sessionRunTime.set(0); // Just clean living. We're about to saveSettings, which will update value. + sessionRunTime.set(0); // Just clean living. We're about to saveSettings, which will update value. DependencyManager::get()->loadSettings(); DependencyManager::get()->loadSettings(); @@ -5362,7 +5327,8 @@ void Application::loadSettings() { } } - auto audioScriptingInterface = reinterpret_cast(DependencyManager::get().data()); + auto audioScriptingInterface = + reinterpret_cast(DependencyManager::get().data()); audioScriptingInterface->loadData(); getMyAvatar()->loadData(); @@ -5374,7 +5340,8 @@ void Application::saveSettings() const { DependencyManager::get()->saveSettings(); DependencyManager::get()->saveSettings(); - auto audioScriptingInterface = reinterpret_cast(DependencyManager::get().data()); + auto audioScriptingInterface = + reinterpret_cast(DependencyManager::get().data()); audioScriptingInterface->saveData(); Menu::getInstance()->saveSettings(); @@ -5419,7 +5386,6 @@ void Application::init() { } } - qCDebug(interfaceapp) << "Loaded settings"; // fire off an immediate domain-server check in now that settings are loaded @@ -5454,23 +5420,27 @@ void Application::init() { auto entityScriptingInterface = DependencyManager::get(); // connect the _entityCollisionSystem to our EntityTreeRenderer since that's what handles running entity scripts - connect(_entitySimulation.get(), &PhysicalEntitySimulation::entityCollisionWithEntity, - getEntities().data(), &EntityTreeRenderer::entityCollisionWithEntity); + connect(_entitySimulation.get(), &PhysicalEntitySimulation::entityCollisionWithEntity, getEntities().data(), + &EntityTreeRenderer::entityCollisionWithEntity); // connect the _entities (EntityTreeRenderer) to our script engine's EntityScriptingInterface for firing // of events related clicking, hovering over, and entering entities getEntities()->connectSignalsToSlots(entityScriptingInterface.data()); // Make sure any new sounds are loaded as soon as know about them. - connect(tree.get(), &EntityTree::newCollisionSoundURL, this, [this](QUrl newURL, EntityItemID id) { - getEntities()->setCollisionSound(id, DependencyManager::get()->getSound(newURL)); - }, Qt::QueuedConnection); - connect(getMyAvatar().get(), &MyAvatar::newCollisionSoundURL, this, [this](QUrl newURL) { - if (auto avatar = getMyAvatar()) { - auto sound = DependencyManager::get()->getSound(newURL); - avatar->setCollisionSound(sound); - } - }, Qt::QueuedConnection); + connect(tree.get(), &EntityTree::newCollisionSoundURL, this, + [this](QUrl newURL, EntityItemID id) { + getEntities()->setCollisionSound(id, DependencyManager::get()->getSound(newURL)); + }, + Qt::QueuedConnection); + connect(getMyAvatar().get(), &MyAvatar::newCollisionSoundURL, this, + [this](QUrl newURL) { + if (auto avatar = getMyAvatar()) { + auto sound = DependencyManager::get()->getSound(newURL); + avatar->setCollisionSound(sound); + } + }, + Qt::QueuedConnection); _gameWorkload.startup(getEntities()->getWorkloadSpace(), _graphicsEngine.getRenderScene(), _entitySimulation); _entitySimulation->setWorkloadSpace(getEntities()->getWorkloadSpace()); @@ -5541,7 +5511,8 @@ void Application::resumeAfterLoginDialogActionTaken() { } if (!isHMDMode() && getDesktopTabletBecomesToolbarSetting()) { - auto toolbar = DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); + auto toolbar = + DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); toolbar->writeProperty("visible", true); } else { getApplicationCompositor().getReticleInterface()->setAllowMouseCapture(true); @@ -5687,8 +5658,8 @@ void Application::updateMyAvatarLookAtPosition() { glm::quat hmdRotation = glm::quat_cast(headPose); lookAtSpot = _myCamera.getPosition() + myAvatar->getWorldOrientation() * (hmdRotation * lookAtPosition); } else { - lookAtSpot = myAvatar->getHead()->getEyePosition() - + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * lookAtPosition); + lookAtSpot = myAvatar->getHead()->getEyePosition() + + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * lookAtPosition); } } else { AvatarSharedPointer lookingAt = myAvatar->getLookAtTargetAvatar().lock(); @@ -5702,14 +5673,14 @@ void Application::updateMyAvatarLookAtPosition() { const float MAXIMUM_FACE_ANGLE = 65.0f * RADIANS_PER_DEGREE; glm::vec3 lookingAtFaceOrientation = lookingAtHead->getFinalOrientationInWorldFrame() * IDENTITY_FORWARD; - glm::vec3 fromLookingAtToMe = glm::normalize(myAvatar->getHead()->getEyePosition() - - lookingAtHead->getEyePosition()); + glm::vec3 fromLookingAtToMe = + glm::normalize(myAvatar->getHead()->getEyePosition() - lookingAtHead->getEyePosition()); float faceAngle = glm::angle(lookingAtFaceOrientation, fromLookingAtToMe); if (faceAngle < MAXIMUM_FACE_ANGLE) { // Randomly look back and forth between look targets - eyeContactTarget target = Menu::getInstance()->isOptionChecked(MenuOption::FixGaze) ? - LEFT_EYE : myAvatar->getEyeContactTarget(); + eyeContactTarget target = + Menu::getInstance()->isOptionChecked(MenuOption::FixGaze) ? LEFT_EYE : myAvatar->getEyeContactTarget(); switch (target) { case LEFT_EYE: lookAtSpot = lookingAtHead->getLeftEyePosition(); @@ -5732,7 +5703,7 @@ void Application::updateMyAvatarLookAtPosition() { lookAtSpot = transformPoint(headPose.getMatrix(), glm::vec3(0.0f, 0.0f, TREE_SCALE)); } else { lookAtSpot = myAvatar->getHead()->getEyePosition() + - (myAvatar->getHead()->getFinalOrientationInWorldFrame() * glm::vec3(0.0f, 0.0f, -TREE_SCALE)); + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * glm::vec3(0.0f, 0.0f, -TREE_SCALE)); } } @@ -5746,9 +5717,9 @@ void Application::updateMyAvatarLookAtPosition() { if (isLookingAtSomeone) { deflection *= GAZE_DEFLECTION_REDUCTION_DURING_EYE_CONTACT; } - lookAtSpot = origin + _myCamera.getOrientation() * glm::quat(glm::radians(glm::vec3( - eyePitch * deflection, eyeYaw * deflection, 0.0f))) * - glm::inverse(_myCamera.getOrientation()) * (lookAtSpot - origin); + lookAtSpot = origin + _myCamera.getOrientation() * + glm::quat(glm::radians(glm::vec3(eyePitch * deflection, eyeYaw * deflection, 0.0f))) * + glm::inverse(_myCamera.getOrientation()) * (lookAtSpot - origin); } } @@ -5784,22 +5755,18 @@ void Application::centerUI() { void Application::cycleCamera() { auto menu = Menu::getInstance(); if (menu->isOptionChecked(MenuOption::FullscreenMirror)) { - menu->setIsOptionChecked(MenuOption::FullscreenMirror, false); menu->setIsOptionChecked(MenuOption::FirstPerson, true); } else if (menu->isOptionChecked(MenuOption::FirstPerson)) { - menu->setIsOptionChecked(MenuOption::FirstPerson, false); menu->setIsOptionChecked(MenuOption::ThirdPerson, true); } else if (menu->isOptionChecked(MenuOption::ThirdPerson)) { - menu->setIsOptionChecked(MenuOption::ThirdPerson, false); menu->setIsOptionChecked(MenuOption::FullscreenMirror, true); - } - cameraMenuChanged(); // handle the menu change + cameraMenuChanged(); // handle the menu change } void Application::cameraModeChanged() { @@ -5841,7 +5808,7 @@ void Application::cameraMenuChanged() { if (!isHMDMode() && _myCamera.getMode() != CAMERA_MODE_MIRROR) { _mirrorYawOffset = 0.0f; _myCamera.setMode(CAMERA_MODE_MIRROR); - getMyAvatar()->reset(false, false, false); // to reset any active MyAvatar::FollowHelpers + getMyAvatar()->reset(false, false, false); // to reset any active MyAvatar::FollowHelpers getMyAvatar()->setBoomLength(MyAvatar::ZOOM_DEFAULT); } } else if (menu->isOptionChecked(MenuOption::FirstPerson)) { @@ -5870,7 +5837,6 @@ void Application::resetPhysicsReadyInformation() { _octreeProcessor.startEntitySequence(); } - void Application::reloadResourceCaches() { resetPhysicsReadyInformation(); @@ -5980,7 +5946,7 @@ void Application::setKeyboardFocusEntity(const QUuid& id) { if (properties.getShowKeyboardFocusHighlight()) { if (auto entity = entities->getEntity(entityId)) { setKeyboardFocusHighlight(entity->getWorldPosition(), entity->getWorldOrientation(), - entity->getScaledDimensions() * FOCUS_HIGHLIGHT_EXPANSION_FACTOR); + entity->getScaledDimensions() * FOCUS_HIGHLIGHT_EXPANSION_FACTOR); return; } } @@ -6044,8 +6010,8 @@ void Application::updateSecondaryCameraViewFrustum() { glm::vec3 mainCameraPositionWorld = getCamera().getPosition(); glm::vec3 mainCameraPositionPortalEntrance = vec3(portalEntranceFromWorld * vec4(mainCameraPositionWorld, 1.0f)); - mainCameraPositionPortalEntrance = vec3(-mainCameraPositionPortalEntrance.x, mainCameraPositionPortalEntrance.y, - -mainCameraPositionPortalEntrance.z); + mainCameraPositionPortalEntrance = + vec3(-mainCameraPositionPortalEntrance.x, mainCameraPositionPortalEntrance.y, -mainCameraPositionPortalEntrance.z); glm::vec3 portalExitCameraPositionWorld = vec3(worldFromPortalExit * vec4(mainCameraPositionPortalEntrance, 1.0f)); secondaryViewFrustum.setPosition(portalExitCameraPositionWorld); @@ -6056,7 +6022,8 @@ void Application::updateSecondaryCameraViewFrustum() { // but the values are the same. glm::vec3 upperRight = halfPortalExitPropertiesDimensions - mainCameraPositionPortalEntrance; glm::vec3 bottomLeft = -halfPortalExitPropertiesDimensions - mainCameraPositionPortalEntrance; - glm::mat4 frustum = glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); + glm::mat4 frustum = + glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); secondaryViewFrustum.setProjection(frustum); } else if (camera->mirrorProjection && !camera->attachedEntityId.isNull()) { auto entityScriptingInterface = DependencyManager::get(); @@ -6076,8 +6043,8 @@ void Application::updateSecondaryCameraViewFrustum() { // get mirror camera position by reflecting main camera position's z coordinate in mirror space glm::vec3 mainCameraPositionWorld = getCamera().getPosition(); glm::vec3 mainCameraPositionMirror = vec3(mirrorFromWorld * vec4(mainCameraPositionWorld, 1.0f)); - glm::vec3 mirrorCameraPositionMirror = vec3(mainCameraPositionMirror.x, mainCameraPositionMirror.y, - -mainCameraPositionMirror.z); + glm::vec3 mirrorCameraPositionMirror = + vec3(mainCameraPositionMirror.x, mainCameraPositionMirror.y, -mainCameraPositionMirror.z); glm::vec3 mirrorCameraPositionWorld = vec3(worldFromMirror * vec4(mirrorCameraPositionMirror, 1.0f)); // set frustum position to be mirrored camera and set orientation to mirror's adjusted rotation @@ -6089,7 +6056,8 @@ void Application::updateSecondaryCameraViewFrustum() { float nearClip = mirrorCameraPositionMirror.z + mirrorPropertiesDimensions.z * 2.0f; glm::vec3 upperRight = halfMirrorPropertiesDimensions - mirrorCameraPositionMirror; glm::vec3 bottomLeft = -halfMirrorPropertiesDimensions - mirrorCameraPositionMirror; - glm::mat4 frustum = glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); + glm::mat4 frustum = + glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); secondaryViewFrustum.setProjection(frustum); } else { if (!camera->attachedEntityId.isNull()) { @@ -6103,10 +6071,8 @@ void Application::updateSecondaryCameraViewFrustum() { } float aspectRatio = (float)camera->textureWidth / (float)camera->textureHeight; - secondaryViewFrustum.setProjection(camera->vFoV, - aspectRatio, - camera->nearClipPlaneDistance, - camera->farClipPlaneDistance); + secondaryViewFrustum.setProjection(camera->vFoV, aspectRatio, camera->nearClipPlaneDistance, + camera->farClipPlaneDistance); } // Without calculating the bound planes, the secondary camera will use the same culling frustum as the main camera, // which is not what we want here. @@ -6124,7 +6090,6 @@ void Application::update(float deltaTime) { return; } - if (!_physicsEnabled) { if (!domainLoadingInProgress) { PROFILE_ASYNC_BEGIN(app, "Scene Loading", ""); @@ -6179,8 +6144,8 @@ void Application::update(float deltaTime) { Menu* menu = Menu::getInstance(); auto audioClient = DependencyManager::get(); if (menu->isOptionChecked(MenuOption::AutoMuteAudio) && !audioClient->isMuted()) { - if (_lastFaceTrackerUpdate > 0 - && ((usecTimestampNow() - _lastFaceTrackerUpdate) > MUTE_MICROPHONE_AFTER_USECS)) { + if (_lastFaceTrackerUpdate > 0 && + ((usecTimestampNow() - _lastFaceTrackerUpdate) > MUTE_MICROPHONE_AFTER_USECS)) { audioClient->setMuted(true); _lastFaceTrackerUpdate = 0; } @@ -6201,22 +6166,21 @@ void Application::update(float deltaTime) { hmdAvatarAlignmentType = controller::HmdAvatarAlignmentType::Head; } - controller::InputCalibrationData calibrationData = { - myAvatar->getSensorToWorldMatrix(), - createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()), - myAvatar->getHMDSensorMatrix(), - myAvatar->getCenterEyeCalibrationMat(), - myAvatar->getHeadCalibrationMat(), - myAvatar->getSpine2CalibrationMat(), - myAvatar->getHipsCalibrationMat(), - myAvatar->getLeftFootCalibrationMat(), - myAvatar->getRightFootCalibrationMat(), - myAvatar->getRightArmCalibrationMat(), - myAvatar->getLeftArmCalibrationMat(), - myAvatar->getRightHandCalibrationMat(), - myAvatar->getLeftHandCalibrationMat(), - hmdAvatarAlignmentType - }; + controller::InputCalibrationData calibrationData = + { myAvatar->getSensorToWorldMatrix(), + createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()), + myAvatar->getHMDSensorMatrix(), + myAvatar->getCenterEyeCalibrationMat(), + myAvatar->getHeadCalibrationMat(), + myAvatar->getSpine2CalibrationMat(), + myAvatar->getHipsCalibrationMat(), + myAvatar->getLeftFootCalibrationMat(), + myAvatar->getRightFootCalibrationMat(), + myAvatar->getRightArmCalibrationMat(), + myAvatar->getLeftArmCalibrationMat(), + myAvatar->getRightHandCalibrationMat(), + myAvatar->getLeftHandCalibrationMat(), + hmdAvatarAlignmentType }; InputPluginPointer keyboardMousePlugin; for (auto inputPlugin : PluginManager::getInstance()->getInputPlugins()) { @@ -6238,82 +6202,84 @@ void Application::update(float deltaTime) { myAvatar->clearDriveKeys(); if (_myCamera.getMode() != CAMERA_MODE_INDEPENDENT && !isInterstitialMode()) { if (!_controllerScriptingInterface->areActionsCaptured() && _myCamera.getMode() != CAMERA_MODE_MIRROR) { - myAvatar->setDriveKey(MyAvatar::TRANSLATE_Z, -1.0f * userInputMapper->getActionState(controller::Action::TRANSLATE_Z)); + myAvatar->setDriveKey(MyAvatar::TRANSLATE_Z, + -1.0f * userInputMapper->getActionState(controller::Action::TRANSLATE_Z)); myAvatar->setDriveKey(MyAvatar::TRANSLATE_Y, userInputMapper->getActionState(controller::Action::TRANSLATE_Y)); myAvatar->setDriveKey(MyAvatar::TRANSLATE_X, userInputMapper->getActionState(controller::Action::TRANSLATE_X)); if (deltaTime > FLT_EPSILON) { myAvatar->setDriveKey(MyAvatar::PITCH, -1.0f * userInputMapper->getActionState(controller::Action::PITCH)); myAvatar->setDriveKey(MyAvatar::YAW, -1.0f * userInputMapper->getActionState(controller::Action::YAW)); - myAvatar->setDriveKey(MyAvatar::DELTA_PITCH, -1.0f * userInputMapper->getActionState(controller::Action::DELTA_PITCH)); - myAvatar->setDriveKey(MyAvatar::DELTA_YAW, -1.0f * userInputMapper->getActionState(controller::Action::DELTA_YAW)); - myAvatar->setDriveKey(MyAvatar::STEP_YAW, -1.0f * userInputMapper->getActionState(controller::Action::STEP_YAW)); + myAvatar->setDriveKey(MyAvatar::DELTA_PITCH, + -1.0f * userInputMapper->getActionState(controller::Action::DELTA_PITCH)); + myAvatar->setDriveKey(MyAvatar::DELTA_YAW, + -1.0f * userInputMapper->getActionState(controller::Action::DELTA_YAW)); + myAvatar->setDriveKey(MyAvatar::STEP_YAW, + -1.0f * userInputMapper->getActionState(controller::Action::STEP_YAW)); } } myAvatar->setDriveKey(MyAvatar::ZOOM, userInputMapper->getActionState(controller::Action::TRANSLATE_CAMERA_Z)); } myAvatar->setSprintMode((bool)userInputMapper->getActionState(controller::Action::SPRINT)); - static const std::vector avatarControllerActions = { - controller::Action::LEFT_HAND, - controller::Action::RIGHT_HAND, - controller::Action::LEFT_FOOT, - controller::Action::RIGHT_FOOT, - controller::Action::HIPS, - controller::Action::SPINE2, - controller::Action::HEAD, - controller::Action::LEFT_HAND_THUMB1, - controller::Action::LEFT_HAND_THUMB2, - controller::Action::LEFT_HAND_THUMB3, - controller::Action::LEFT_HAND_THUMB4, - controller::Action::LEFT_HAND_INDEX1, - controller::Action::LEFT_HAND_INDEX2, - controller::Action::LEFT_HAND_INDEX3, - controller::Action::LEFT_HAND_INDEX4, - controller::Action::LEFT_HAND_MIDDLE1, - controller::Action::LEFT_HAND_MIDDLE2, - controller::Action::LEFT_HAND_MIDDLE3, - controller::Action::LEFT_HAND_MIDDLE4, - controller::Action::LEFT_HAND_RING1, - controller::Action::LEFT_HAND_RING2, - controller::Action::LEFT_HAND_RING3, - controller::Action::LEFT_HAND_RING4, - controller::Action::LEFT_HAND_PINKY1, - controller::Action::LEFT_HAND_PINKY2, - controller::Action::LEFT_HAND_PINKY3, - controller::Action::LEFT_HAND_PINKY4, - controller::Action::RIGHT_HAND_THUMB1, - controller::Action::RIGHT_HAND_THUMB2, - controller::Action::RIGHT_HAND_THUMB3, - controller::Action::RIGHT_HAND_THUMB4, - controller::Action::RIGHT_HAND_INDEX1, - controller::Action::RIGHT_HAND_INDEX2, - controller::Action::RIGHT_HAND_INDEX3, - controller::Action::RIGHT_HAND_INDEX4, - controller::Action::RIGHT_HAND_MIDDLE1, - controller::Action::RIGHT_HAND_MIDDLE2, - controller::Action::RIGHT_HAND_MIDDLE3, - controller::Action::RIGHT_HAND_MIDDLE4, - controller::Action::RIGHT_HAND_RING1, - controller::Action::RIGHT_HAND_RING2, - controller::Action::RIGHT_HAND_RING3, - controller::Action::RIGHT_HAND_RING4, - controller::Action::RIGHT_HAND_PINKY1, - controller::Action::RIGHT_HAND_PINKY2, - controller::Action::RIGHT_HAND_PINKY3, - controller::Action::RIGHT_HAND_PINKY4, - controller::Action::LEFT_ARM, - controller::Action::RIGHT_ARM, - controller::Action::LEFT_SHOULDER, - controller::Action::RIGHT_SHOULDER, - controller::Action::LEFT_FORE_ARM, - controller::Action::RIGHT_FORE_ARM, - controller::Action::LEFT_LEG, - controller::Action::RIGHT_LEG, - controller::Action::LEFT_UP_LEG, - controller::Action::RIGHT_UP_LEG, - controller::Action::LEFT_TOE_BASE, - controller::Action::RIGHT_TOE_BASE - }; + static const std::vector avatarControllerActions = { controller::Action::LEFT_HAND, + controller::Action::RIGHT_HAND, + controller::Action::LEFT_FOOT, + controller::Action::RIGHT_FOOT, + controller::Action::HIPS, + controller::Action::SPINE2, + controller::Action::HEAD, + controller::Action::LEFT_HAND_THUMB1, + controller::Action::LEFT_HAND_THUMB2, + controller::Action::LEFT_HAND_THUMB3, + controller::Action::LEFT_HAND_THUMB4, + controller::Action::LEFT_HAND_INDEX1, + controller::Action::LEFT_HAND_INDEX2, + controller::Action::LEFT_HAND_INDEX3, + controller::Action::LEFT_HAND_INDEX4, + controller::Action::LEFT_HAND_MIDDLE1, + controller::Action::LEFT_HAND_MIDDLE2, + controller::Action::LEFT_HAND_MIDDLE3, + controller::Action::LEFT_HAND_MIDDLE4, + controller::Action::LEFT_HAND_RING1, + controller::Action::LEFT_HAND_RING2, + controller::Action::LEFT_HAND_RING3, + controller::Action::LEFT_HAND_RING4, + controller::Action::LEFT_HAND_PINKY1, + controller::Action::LEFT_HAND_PINKY2, + controller::Action::LEFT_HAND_PINKY3, + controller::Action::LEFT_HAND_PINKY4, + controller::Action::RIGHT_HAND_THUMB1, + controller::Action::RIGHT_HAND_THUMB2, + controller::Action::RIGHT_HAND_THUMB3, + controller::Action::RIGHT_HAND_THUMB4, + controller::Action::RIGHT_HAND_INDEX1, + controller::Action::RIGHT_HAND_INDEX2, + controller::Action::RIGHT_HAND_INDEX3, + controller::Action::RIGHT_HAND_INDEX4, + controller::Action::RIGHT_HAND_MIDDLE1, + controller::Action::RIGHT_HAND_MIDDLE2, + controller::Action::RIGHT_HAND_MIDDLE3, + controller::Action::RIGHT_HAND_MIDDLE4, + controller::Action::RIGHT_HAND_RING1, + controller::Action::RIGHT_HAND_RING2, + controller::Action::RIGHT_HAND_RING3, + controller::Action::RIGHT_HAND_RING4, + controller::Action::RIGHT_HAND_PINKY1, + controller::Action::RIGHT_HAND_PINKY2, + controller::Action::RIGHT_HAND_PINKY3, + controller::Action::RIGHT_HAND_PINKY4, + controller::Action::LEFT_ARM, + controller::Action::RIGHT_ARM, + controller::Action::LEFT_SHOULDER, + controller::Action::RIGHT_SHOULDER, + controller::Action::LEFT_FORE_ARM, + controller::Action::RIGHT_FORE_ARM, + controller::Action::LEFT_LEG, + controller::Action::RIGHT_LEG, + controller::Action::LEFT_UP_LEG, + controller::Action::RIGHT_UP_LEG, + controller::Action::LEFT_TOE_BASE, + controller::Action::RIGHT_TOE_BASE }; // copy controller poses from userInputMapper to myAvatar. glm::mat4 myAvatarMatrix = createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()); @@ -6324,21 +6290,25 @@ void Application::update(float deltaTime) { myAvatar->setControllerPoseInSensorFrame(action, pose.transform(avatarToSensorMatrix)); } - static const std::vector trackedObjectStringLiterals = { - QStringLiteral("_TrackedObject00"), QStringLiteral("_TrackedObject01"), QStringLiteral("_TrackedObject02"), QStringLiteral("_TrackedObject03"), - QStringLiteral("_TrackedObject04"), QStringLiteral("_TrackedObject05"), QStringLiteral("_TrackedObject06"), QStringLiteral("_TrackedObject07"), - QStringLiteral("_TrackedObject08"), QStringLiteral("_TrackedObject09"), QStringLiteral("_TrackedObject10"), QStringLiteral("_TrackedObject11"), - QStringLiteral("_TrackedObject12"), QStringLiteral("_TrackedObject13"), QStringLiteral("_TrackedObject14"), QStringLiteral("_TrackedObject15") - }; + static const std::vector trackedObjectStringLiterals = + { QStringLiteral("_TrackedObject00"), QStringLiteral("_TrackedObject01"), QStringLiteral("_TrackedObject02"), + QStringLiteral("_TrackedObject03"), QStringLiteral("_TrackedObject04"), QStringLiteral("_TrackedObject05"), + QStringLiteral("_TrackedObject06"), QStringLiteral("_TrackedObject07"), QStringLiteral("_TrackedObject08"), + QStringLiteral("_TrackedObject09"), QStringLiteral("_TrackedObject10"), QStringLiteral("_TrackedObject11"), + QStringLiteral("_TrackedObject12"), QStringLiteral("_TrackedObject13"), QStringLiteral("_TrackedObject14"), + QStringLiteral("_TrackedObject15") }; // Controlled by the Developer > Avatar > Show Tracked Objects menu. if (_showTrackedObjects) { - static const std::vector trackedObjectActions = { - controller::Action::TRACKED_OBJECT_00, controller::Action::TRACKED_OBJECT_01, controller::Action::TRACKED_OBJECT_02, controller::Action::TRACKED_OBJECT_03, - controller::Action::TRACKED_OBJECT_04, controller::Action::TRACKED_OBJECT_05, controller::Action::TRACKED_OBJECT_06, controller::Action::TRACKED_OBJECT_07, - controller::Action::TRACKED_OBJECT_08, controller::Action::TRACKED_OBJECT_09, controller::Action::TRACKED_OBJECT_10, controller::Action::TRACKED_OBJECT_11, - controller::Action::TRACKED_OBJECT_12, controller::Action::TRACKED_OBJECT_13, controller::Action::TRACKED_OBJECT_14, controller::Action::TRACKED_OBJECT_15 - }; + static const std::vector trackedObjectActions = + { controller::Action::TRACKED_OBJECT_00, controller::Action::TRACKED_OBJECT_01, + controller::Action::TRACKED_OBJECT_02, controller::Action::TRACKED_OBJECT_03, + controller::Action::TRACKED_OBJECT_04, controller::Action::TRACKED_OBJECT_05, + controller::Action::TRACKED_OBJECT_06, controller::Action::TRACKED_OBJECT_07, + controller::Action::TRACKED_OBJECT_08, controller::Action::TRACKED_OBJECT_09, + controller::Action::TRACKED_OBJECT_10, controller::Action::TRACKED_OBJECT_11, + controller::Action::TRACKED_OBJECT_12, controller::Action::TRACKED_OBJECT_13, + controller::Action::TRACKED_OBJECT_14, controller::Action::TRACKED_OBJECT_15 }; int i = 0; glm::vec4 BLUE(0.0f, 0.0f, 1.0f, 1.0f); @@ -6361,8 +6331,8 @@ void Application::update(float deltaTime) { _prevShowTrackedObjects = _showTrackedObjects; } - updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process... - updateDialogs(deltaTime); // update various stats dialogs if present + updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process... + updateDialogs(deltaTime); // update various stats dialogs if present auto grabManager = DependencyManager::get(); grabManager->simulateGrabs(); @@ -6440,18 +6410,15 @@ void Application::update(float deltaTime) { { PROFILE_RANGE(simulation_physics, "PrepareActions"); - _physicsEngine->forEachDynamic([&](EntityDynamicPointer dynamic) { - dynamic->prepareForPhysicsSimulation(); - }); + _physicsEngine->forEachDynamic( + [&](EntityDynamicPointer dynamic) { dynamic->prepareForPhysicsSimulation(); }); } } auto t2 = std::chrono::high_resolution_clock::now(); { PROFILE_RANGE(simulation_physics, "StepPhysics"); PerformanceTimer perfTimer("stepPhysics"); - getEntities()->getTree()->withWriteLock([&] { - _physicsEngine->stepSimulation(); - }); + getEntities()->getTree()->withWriteLock([&] { _physicsEngine->stepSimulation(); }); } auto t3 = std::chrono::high_resolution_clock::now(); { @@ -6490,8 +6457,8 @@ void Application::update(float deltaTime) { } if (PerformanceTimer::isActive() && - Menu::getInstance()->isOptionChecked(MenuOption::DisplayDebugTimingDetails) && - Menu::getInstance()->isOptionChecked(MenuOption::ExpandPhysicsTiming)) { + Menu::getInstance()->isOptionChecked(MenuOption::DisplayDebugTimingDetails) && + Menu::getInstance()->isOptionChecked(MenuOption::ExpandPhysicsTiming)) { _physicsEngine->harvestPerformanceStats(); } // NOTE: the PhysicsEngine stats are written to stdout NOT to Qt log framework @@ -6501,17 +6468,17 @@ void Application::update(float deltaTime) { // NOTE: the getEntities()->update() call below will wait for lock // and will provide non-physical entity motion - getEntities()->update(true); // update the models... + getEntities()->update(true); // update the models... auto t5 = std::chrono::high_resolution_clock::now(); workload::Timings timings(6); - timings[0] = t1 - t0; // prePhysics entities - timings[1] = t2 - t1; // prePhysics avatars - timings[2] = t3 - t2; // stepPhysics - timings[3] = t4 - t3; // postPhysics - timings[4] = t5 - t4; // non-physical kinematics - timings[5] = workload::Timing_ns((int32_t)(NSECS_PER_SECOND * deltaTime)); // game loop duration + timings[0] = t1 - t0; // prePhysics entities + timings[1] = t2 - t1; // prePhysics avatars + timings[2] = t3 - t2; // stepPhysics + timings[3] = t4 - t3; // postPhysics + timings[4] = t5 - t4; // non-physical kinematics + timings[5] = workload::Timing_ns((int32_t)(NSECS_PER_SECOND * deltaTime)); // game loop duration _gameWorkload.updateSimulationTimings(timings); } } @@ -6595,9 +6562,8 @@ void Application::update(float deltaTime) { viewIsDifferentEnough = true; } - // if it's been a while since our last query or the view has significantly changed then send a query, otherwise suppress it - static const std::chrono::seconds MIN_PERIOD_BETWEEN_QUERIES { 3 }; + static const std::chrono::seconds MIN_PERIOD_BETWEEN_QUERIES{ 3 }; auto now = SteadyClock::now(); if (now > _queryExpiry || viewIsDifferentEnough) { if (DependencyManager::get()->shouldRenderEntities()) { @@ -6626,7 +6592,8 @@ void Application::update(float deltaTime) { if (sinceLastNack > TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS && !isInterstitialMode()) { _lastSendDownstreamAudioStats = now; - QMetaObject::invokeMethod(DependencyManager::get().data(), "sendDownstreamAudioStatsPacket", Qt::QueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "sendDownstreamAudioStatsPacket", + Qt::QueuedConnection); } } @@ -6645,7 +6612,6 @@ void Application::update(float deltaTime) { _postUpdateLambdas.clear(); } - updateRenderArgs(deltaTime); { @@ -6653,8 +6619,7 @@ void Application::update(float deltaTime) { AnimDebugDraw::getInstance().update(); } - - { // Game loop is done, mark the end of the frame for the scene transactions and the render loop to take over + { // Game loop is done, mark the end of the frame for the scene transactions and the render loop to take over PerformanceTimer perfTimer("enqueueFrame"); getMain3DScene()->enqueueFrame(); } @@ -6688,16 +6653,16 @@ void Application::updateRenderArgs(float deltaTime) { { QMutexLocker viewLocker(&_viewMutex); // adjust near clip plane to account for sensor scaling. - auto adjustedProjection = glm::perspective(glm::radians(_fieldOfView.get()), - getActiveDisplayPlugin()->getRecommendedAspectRatio(), - DEFAULT_NEAR_CLIP * sensorToWorldScale, - DEFAULT_FAR_CLIP); + auto adjustedProjection = + glm::perspective(glm::radians(_fieldOfView.get()), getActiveDisplayPlugin()->getRecommendedAspectRatio(), + DEFAULT_NEAR_CLIP * sensorToWorldScale, DEFAULT_FAR_CLIP); _viewFrustum.setProjection(adjustedProjection); _viewFrustum.calculate(); } - appRenderArgs._renderArgs = RenderArgs(_graphicsEngine.getGPUContext(), lodManager->getOctreeSizeScale(), - lodManager->getBoundaryLevelAdjust(), lodManager->getLODAngleHalfTan(), RenderArgs::DEFAULT_RENDER_MODE, - RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); + appRenderArgs._renderArgs = + RenderArgs(_graphicsEngine.getGPUContext(), lodManager->getOctreeSizeScale(), + lodManager->getBoundaryLevelAdjust(), lodManager->getLODAngleHalfTan(), + RenderArgs::DEFAULT_RENDER_MODE, RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); appRenderArgs._renderArgs._scene = getMain3DScene(); { @@ -6786,7 +6751,6 @@ void Application::updateRenderArgs(float deltaTime) { appRenderArgs._renderArgs.setViewFrustum(_displayViewFrustum); } - // HACK // load the view frustum // FIXME: This preDisplayRender call is temporary until we create a separate render::scene for the mirror rendering. @@ -6815,18 +6779,14 @@ void Application::queryAvatars() { } } - int Application::sendNackPackets() { - // iterates through all nodes in NodeList auto nodeList = DependencyManager::get(); int packetsSent = 0; - nodeList->eachNode([&](const SharedNodePointer& node){ - + nodeList->eachNode([&](const SharedNodePointer& node) { if (node->getActiveSocket() && node->getType() == NodeType::EntityServer) { - auto nackPacketList = NLPacketList::create(PacketType::OctreeDataNack); QUuid nodeUUID = node->getUUID(); @@ -6844,7 +6804,8 @@ int Application::sendNackPackets() { return; } // get sequence number stats of node, prune its missing set, and make a copy of the missing set - SequenceNumberStats& sequenceNumberStats = _octreeServerSceneStats[nodeUUID].getIncomingOctreeSequenceNumberStats(); + SequenceNumberStats& sequenceNumberStats = + _octreeServerSceneStats[nodeUUID].getIncomingOctreeSequenceNumberStats(); sequenceNumberStats.pruneMissingSet(); missingSequenceNumbers = sequenceNumberStats.getMissingSet(); }); @@ -6852,7 +6813,7 @@ int Application::sendNackPackets() { _isMissingSequenceNumbers = (missingSequenceNumbers.size() != 0); // construct nack packet(s) for this node - foreach(const OCTREE_PACKET_SEQUENCE& missingNumber, missingSequenceNumbers) { + foreach (const OCTREE_PACKET_SEQUENCE& missingNumber, missingSequenceNumbers) { nackPacketList->writePrimitive(missingNumber); } @@ -6869,9 +6830,8 @@ int Application::sendNackPackets() { } void Application::queryOctree(NodeType_t serverType, PacketType packetType) { - if (!_settingsLoaded) { - return; // bail early if settings are not loaded + return; // bail early if settings are not loaded } const bool isModifiedQuery = !_physicsEnabled; @@ -6901,7 +6861,6 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType) { } _octreeQuery.setReportInitialCompletion(isModifiedQuery); - auto nodeList = DependencyManager::get(); auto node = nodeList->soloNodeOfType(serverType); @@ -6920,7 +6879,6 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType) { } } - bool Application::isHMDMode() const { return getActiveDisplayPlugin()->isHmd(); } @@ -6929,7 +6887,9 @@ float Application::getNumCollisionObjects() const { return _physicsEngine ? _physicsEngine->getNumCollisionObjects() : 0; } -float Application::getTargetRenderFrameRate() const { return getActiveDisplayPlugin()->getTargetFrameRate(); } +float Application::getTargetRenderFrameRate() const { + return getActiveDisplayPlugin()->getTargetFrameRate(); +} QRect Application::getDesirableApplicationGeometry() const { QRect applicationGeometry = getWindow()->geometry(); @@ -6955,7 +6915,7 @@ QRect Application::getDesirableApplicationGeometry() const { } PickRay Application::computePickRay(float x, float y) const { - vec2 pickPoint { x, y }; + vec2 pickPoint{ x, y }; PickRay result; if (isHMDMode()) { getApplicationCompositor().computeHmdPickRay(pickPoint, result.origin, result.direction); @@ -7015,19 +6975,18 @@ void Application::hmdVisibleChanged(bool visible) { } void Application::updateWindowTitle() const { - auto nodeList = DependencyManager::get(); auto accountManager = DependencyManager::get(); auto isInErrorState = nodeList->getDomainHandler().isInErrorState(); - QString buildVersion = " - " - + (BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable ? QString("Version") : QString("Build")) - + " " + applicationVersion(); + QString buildVersion = " - " + + (BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable ? QString("Version") : QString("Build")) + + " " + applicationVersion(); QString loginStatus = accountManager->isLoggedIn() ? "" : " (NOT LOGGED IN)"; - QString connectionStatus = isInErrorState ? " (ERROR CONNECTING)" : - nodeList->getDomainHandler().isConnected() ? "" : " (NOT CONNECTED)"; + QString connectionStatus = + isInErrorState ? " (ERROR CONNECTING)" : nodeList->getDomainHandler().isConnected() ? "" : " (NOT CONNECTED)"; QString username = accountManager->getAccountInfo().getUsername(); setCrashAnnotation("username", username.toStdString()); @@ -7046,8 +7005,8 @@ void Application::updateWindowTitle() const { } } - QString title = QString() + (!username.isEmpty() ? username + " @ " : QString()) - + currentPlaceName + connectionStatus + loginStatus + buildVersion; + QString title = QString() + (!username.isEmpty() ? username + " @ " : QString()) + currentPlaceName + connectionStatus + + loginStatus + buildVersion; #ifndef WIN32 // crashes with vs2013/win32 @@ -7057,7 +7016,7 @@ void Application::updateWindowTitle() const { // updateTitleWindow gets called whenever there's a change regarding the domain, so rather // than placing this within domainURLChanged, it's placed here to cover the other potential cases. - DependencyManager::get< MessagesClient >()->sendLocalMessage("Toolbar-DomainChanged", ""); + DependencyManager::get()->sendLocalMessage("Toolbar-DomainChanged", ""); } void Application::clearDomainOctreeDetails(bool clearAll) { @@ -7071,9 +7030,7 @@ void Application::clearDomainOctreeDetails(bool clearAll) { resetPhysicsReadyInformation(); setIsInterstitialMode(true); - _octreeServerSceneStats.withWriteLock([&] { - _octreeServerSceneStats.clear(); - }); + _octreeServerSceneStats.withWriteLock([&] { _octreeServerSceneStats.clear(); }); // reset the model renderer clearAll ? getEntities()->clear() : getEntities()->clearDomainAndNonOwnedEntities(); @@ -7157,7 +7114,7 @@ void Application::nodeActivated(SharedNodePointer node) { _queryExpiry = SteadyClock::now(); _octreeQuery.incrementConnectionID(); - if (!_failedToConnectToEntityServer) { + if (!_failedToConnectToEntityServer) { _entityServerConnectionTimer.stop(); } } @@ -7283,7 +7240,6 @@ void Application::addingEntityWithCertificate(const QString& certificateID, cons } void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointer scriptEngine) { - scriptEngine->setEmitScriptUpdatesFunction([this]() { SharedNodePointer entityServerNode = DependencyManager::get()->soloNodeOfType(NodeType::EntityServer); return !entityServerNode || isPhysicsEnabled(); @@ -7327,13 +7283,13 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe #endif qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, wrapperFromScriptValue); - qScriptRegisterMetaType(scriptEngine.data(), - wrapperToScriptValue, wrapperFromScriptValue); + qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, + wrapperFromScriptValue); scriptEngine->registerGlobalObject("Toolbars", DependencyManager::get().data()); qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, wrapperFromScriptValue); - qScriptRegisterMetaType(scriptEngine.data(), - wrapperToScriptValue, wrapperFromScriptValue); + qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, + wrapperFromScriptValue); scriptEngine->registerGlobalObject("Tablet", DependencyManager::get().data()); // FIXME remove these deprecated names for the tablet scripting interface scriptEngine->registerGlobalObject("tabletInterface", DependencyManager::get().data()); @@ -7343,17 +7299,20 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("Window", DependencyManager::get().data()); scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter, - LocationScriptingInterface::locationSetter, "Window"); + LocationScriptingInterface::locationSetter, "Window"); // register `location` on the global object. scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter, LocationScriptingInterface::locationSetter); bool clientScript = scriptEngine->isClientScript(); - scriptEngine->registerFunction("OverlayWindow", clientScript ? QmlWindowClass::constructor : QmlWindowClass::restricted_constructor); + scriptEngine->registerFunction("OverlayWindow", + clientScript ? QmlWindowClass::constructor : QmlWindowClass::restricted_constructor); #if !defined(Q_OS_ANDROID) && !defined(DISABLE_QML) - scriptEngine->registerFunction("OverlayWebWindow", clientScript ? QmlWebWindowClass::constructor : QmlWebWindowClass::restricted_constructor); + scriptEngine->registerFunction("OverlayWebWindow", + clientScript ? QmlWebWindowClass::constructor : QmlWebWindowClass::restricted_constructor); #endif - scriptEngine->registerFunction("QmlFragment", clientScript ? QmlFragmentClass::constructor : QmlFragmentClass::restricted_constructor); + scriptEngine->registerFunction("QmlFragment", + clientScript ? QmlFragmentClass::constructor : QmlFragmentClass::restricted_constructor); scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("DesktopPreviewProvider", DependencyManager::get().data()); @@ -7380,8 +7339,10 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("DialogsManager", _dialogsManagerScriptingInterface); - scriptEngine->registerGlobalObject("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - scriptEngine->registerGlobalObject("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + scriptEngine->registerGlobalObject("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + scriptEngine->registerGlobalObject("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED scriptEngine->registerGlobalObject("AccountServices", AccountServicesScriptingInterface::getInstance()); qScriptRegisterMetaType(scriptEngine.data(), DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue); @@ -7410,7 +7371,8 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("ScriptDiscoveryService", DependencyManager::get().data()); scriptEngine->registerGlobalObject("Reticle", getApplicationCompositor().getReticleInterface()); - scriptEngine->registerGlobalObject("UserActivityLogger", DependencyManager::get().data()); + scriptEngine->registerGlobalObject("UserActivityLogger", + DependencyManager::get().data()); scriptEngine->registerGlobalObject("Users", DependencyManager::get().data()); scriptEngine->registerGlobalObject("GooglePoly", DependencyManager::get().data()); @@ -7447,7 +7409,6 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe connect(scriptEngine.data(), &ScriptEngine::warningMessage, scriptEngines, &ScriptEngines::onWarningMessage); connect(scriptEngine.data(), &ScriptEngine::infoMessage, scriptEngines, &ScriptEngines::onInfoMessage); connect(scriptEngine.data(), &ScriptEngine::clearDebugWindow, scriptEngines, &ScriptEngines::onClearDebugWindow); - } bool Application::canAcceptURL(const QString& urlString) const { @@ -7471,8 +7432,8 @@ bool Application::acceptURL(const QString& urlString, bool defaultUpload) { if (url.scheme() == URL_SCHEME_HIFI) { // this is a hifi URL - have the AddressManager handle it - QMetaObject::invokeMethod(DependencyManager::get().data(), "handleLookupString", - Qt::AutoConnection, Q_ARG(const QString&, urlString)); + QMetaObject::invokeMethod(DependencyManager::get().data(), "handleLookupString", Qt::AutoConnection, + Q_ARG(const QString&, urlString)); return true; } @@ -7509,13 +7470,13 @@ bool Application::askToSetAvatarUrl(const QString& url) { QString modelName = fstMapping["name"].toString(); QString modelLicense = fstMapping["license"].toString(); - bool agreeToLicense = true; // assume true + bool agreeToLicense = true; // assume true //create set avatar callback - auto setAvatar = [=] (QString url, QString modelName) { - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Set Avatar", - "Would you like to use '" + modelName + "' for your avatar?", - QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + auto setAvatar = [=](QString url, QString modelName) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Set Avatar", "Would you like to use '" + modelName + "' for your avatar?", + QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); bool ok = (QMessageBox::Ok == static_cast(answer.toInt())); @@ -7533,22 +7494,22 @@ bool Application::askToSetAvatarUrl(const QString& url) { const int MAX_CHARACTERS_PER_LINE = 90; modelLicense = simpleWordWrap(modelLicense, MAX_CHARACTERS_PER_LINE); - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Avatar Usage License", - modelLicense + "\nDo you agree to these terms?", - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - QObject::connect(dlg, &ModalDialogListener::response, this, [=, &agreeToLicense] (QVariant answer) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Avatar Usage License", modelLicense + "\nDo you agree to these terms?", + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + QObject::connect(dlg, &ModalDialogListener::response, this, [=, &agreeToLicense](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); agreeToLicense = (static_cast(answer.toInt()) == QMessageBox::Yes); if (agreeToLicense) { switch (modelType) { case FSTReader::HEAD_AND_BODY_MODEL: { - setAvatar(url, modelName); - break; - } - default: - OffscreenUi::asyncWarning("", modelName + "Does not support a head and body as required."); - break; + setAvatar(url, modelName); + break; + } + default: + OffscreenUi::asyncWarning("", modelName + "Does not support a head and body as required."); + break; } } else { qCDebug(interfaceapp) << "Declined to agree to avatar license"; @@ -7563,11 +7524,10 @@ bool Application::askToSetAvatarUrl(const QString& url) { return true; } - bool Application::askToLoadScript(const QString& scriptFilenameOrURL) { QString shortName = scriptFilenameOrURL; - QUrl scriptURL { scriptFilenameOrURL }; + QUrl scriptURL{ scriptFilenameOrURL }; if (scriptURL.host().endsWith(MARKETPLACE_CDN_HOSTNAME)) { int startIndex = shortName.lastIndexOf('/') + 1; @@ -7579,10 +7539,10 @@ bool Application::askToLoadScript(const QString& scriptFilenameOrURL) { DependencyManager::get()->loadScript(scriptFilenameOrURL); #else QString message = "Would you like to run this script:\n" + shortName; - ModalDialogListener* dlg = OffscreenUi::asyncQuestion(getWindow(), "Run Script", message, - QMessageBox::Yes | QMessageBox::No); + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion(getWindow(), "Run Script", message, QMessageBox::Yes | QMessageBox::No); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { const QString& fileName = scriptFilenameOrURL; if (static_cast(answer.toInt()) == QMessageBox::Yes) { qCDebug(interfaceapp) << "Chose to run the script: " << fileName; @@ -7604,7 +7564,6 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { QNetworkReply* reply = networkAccessManager.get(networkRequest); int requestNumber = ++_avatarAttachmentRequest; connect(reply, &QNetworkReply::finished, [this, reply, url, requestNumber]() { - if (requestNumber != _avatarAttachmentRequest) { // this request has been superseded by another more recent request reply->deleteLater(); @@ -7619,7 +7578,6 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { QJsonParseError jsonError; auto doc = QJsonDocument::fromJson(contents, &jsonError); if (jsonError.error == QJsonParseError::NoError) { - auto jsonObject = doc.object(); // retrieve optional name field from JSON @@ -7631,10 +7589,10 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { auto avatarAttachmentConfirmationTitle = tr("Avatar Attachment Confirmation"); auto avatarAttachmentConfirmationMessage = tr("Would you like to wear '%1' on your avatar?").arg(name); - ModalDialogListener* dlg = OffscreenUi::asyncQuestion(avatarAttachmentConfirmationTitle, - avatarAttachmentConfirmationMessage, - QMessageBox::Ok | QMessageBox::Cancel); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion(avatarAttachmentConfirmationTitle, avatarAttachmentConfirmationMessage, + QMessageBox::Ok | QMessageBox::Cancel); + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); if (static_cast(answer.toInt()) == QMessageBox::Yes) { // add attachment to avatar @@ -7685,18 +7643,23 @@ bool Application::askToReplaceDomainContent(const QString& url) { QString methodDetails; const int MAX_CHARACTERS_PER_LINE = 90; if (DependencyManager::get()->getThisNodeCanReplaceContent()) { - QUrl originURL { url }; + QUrl originURL{ url }; if (originURL.host().endsWith(MARKETPLACE_CDN_HOSTNAME)) { // Create a confirmation dialog when this call is made - static const QString infoText = simpleWordWrap("Your domain's content will be replaced with a new content set. " - "If you want to save what you have now, create a backup before proceeding. For more information about backing up " - "and restoring content, visit the documentation page at: ", MAX_CHARACTERS_PER_LINE) + + static const QString infoText = + simpleWordWrap( + "Your domain's content will be replaced with a new content set. " + "If you want to save what you have now, create a backup before proceeding. For more information about " + "backing up " + "and restoring content, visit the documentation page at: ", + MAX_CHARACTERS_PER_LINE) + "\nhttps://docs.highfidelity.com/create-and-explore/start-working-in-your-sandbox/restoring-sandbox-content"; - ModalDialogListener* dig = OffscreenUi::asyncQuestion("Are you sure you want to replace this domain's content set?", - infoText, QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + ModalDialogListener* dig = + OffscreenUi::asyncQuestion("Are you sure you want to replace this domain's content set?", infoText, + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - QObject::connect(dig, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dig, &ModalDialogListener::response, this, [=](QVariant answer) { QString details; if (static_cast(answer.toInt()) == QMessageBox::Yes) { // Given confirmation, send request to domain server to replace content @@ -7705,33 +7668,26 @@ bool Application::askToReplaceDomainContent(const QString& url) { } else { details = "UserDeclinedToReplaceContent"; } - QJsonObject messageProperties = { - { "status", details }, - { "content_set_url", url } - }; + QJsonObject messageProperties = { { "status", details }, { "content_set_url", url } }; UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); QObject::disconnect(dig, &ModalDialogListener::response, this, nullptr); }); } else { methodDetails = "ContentSetDidNotOriginateFromMarketplace"; - QJsonObject messageProperties = { - { "status", methodDetails }, - { "content_set_url", url } - }; + QJsonObject messageProperties = { { "status", methodDetails }, { "content_set_url", url } }; UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); } } else { - methodDetails = "UserDoesNotHavePermissionToReplaceContent"; - static const QString warningMessage = simpleWordWrap("The domain owner must enable 'Replace Content' " - "permissions for you in this domain's server settings before you can continue.", MAX_CHARACTERS_PER_LINE); - OffscreenUi::asyncWarning("You do not have permissions to replace domain content", warningMessage, - QMessageBox::Ok, QMessageBox::Ok); + methodDetails = "UserDoesNotHavePermissionToReplaceContent"; + static const QString warningMessage = simpleWordWrap( + "The domain owner must enable 'Replace Content' " + "permissions for you in this domain's server settings before you can continue.", + MAX_CHARACTERS_PER_LINE); + OffscreenUi::asyncWarning("You do not have permissions to replace domain content", warningMessage, QMessageBox::Ok, + QMessageBox::Ok); - QJsonObject messageProperties = { - { "status", methodDetails }, - { "content_set_url", url } - }; - UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); + QJsonObject messageProperties = { { "status", methodDetails }, { "content_set_url", url } }; + UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); } return true; } @@ -7768,9 +7724,9 @@ void Application::showAssetServerWidget(QString filePath) { if (!DependencyManager::get()->getThisNodeCanWriteAssets() || getLoginDialogPoppedUp()) { return; } - static const QUrl url { "hifi/AssetServer.qml" }; + static const QUrl url{ "hifi/AssetServer.qml" }; - auto startUpload = [=](QQmlContext* context, QObject* newObject){ + auto startUpload = [=](QQmlContext* context, QObject* newObject) { if (!filePath.isEmpty()) { emit uploadRequest(filePath); } @@ -7795,7 +7751,6 @@ void Application::showAssetServerWidget(QString filePath) { } void Application::addAssetToWorldFromURL(QString url) { - QString filename; if (url.contains("filename")) { filename = url.section("filename=", 1, 1); // Filename is in "?filename=" parameter at end of URL. @@ -7807,7 +7762,6 @@ void Application::addAssetToWorldFromURL(QString url) { } else { filename.remove(".zip"); } - } if (!DependencyManager::get()->getThisNodeCanWriteAssets()) { @@ -7819,8 +7773,8 @@ void Application::addAssetToWorldFromURL(QString url) { addAssetToWorldInfo(filename, "Downloading model file " + filename + "."); - auto request = DependencyManager::get()->createResourceRequest( - nullptr, QUrl(url), true, -1, "Application::addAssetToWorldFromURL"); + auto request = DependencyManager::get()->createResourceRequest(nullptr, QUrl(url), true, -1, + "Application::addAssetToWorldFromURL"); connect(request, &ResourceRequest::finished, this, &Application::addAssetToWorldFromURLRequestFinished); request->send(); } @@ -7877,7 +7831,6 @@ void Application::addAssetToWorldFromURLRequestFinished() { request->deleteLater(); } - QString filenameFromPath(QString filePath) { return filePath.right(filePath.length() - filePath.lastIndexOf("/") - 1); } @@ -7922,8 +7875,8 @@ void Application::addAssetToWorldWithNewMapping(QString filePath, QString mappin if (result == GetMappingRequest::NotFound) { addAssetToWorldUpload(filePath, mapping, isZip, isBlocks); } else if (result != GetMappingRequest::NoError) { - QString errorInfo = "Could not map asset name: " - + mapping.left(mapping.length() - QString::number(copy).length() - 1); + QString errorInfo = + "Could not map asset name: " + mapping.left(mapping.length() - QString::number(copy).length() - 1); qWarning(interfaceapp) << "Error downloading model: " + errorInfo; addAssetToWorldError(filenameFromPath(filePath), errorInfo); } else if (copy < MAX_COPY_COUNT - 1) { @@ -7934,8 +7887,8 @@ void Application::addAssetToWorldWithNewMapping(QString filePath, QString mappin mapping = mapping.insert(mapping.lastIndexOf("."), "-" + QString::number(copy)); addAssetToWorldWithNewMapping(filePath, mapping, copy, isZip, isBlocks); } else { - QString errorInfo = "Too many copies of asset name: " - + mapping.left(mapping.length() - QString::number(copy).length() - 1); + QString errorInfo = + "Too many copies of asset name: " + mapping.left(mapping.length() - QString::number(copy).length() - 1); qWarning(interfaceapp) << "Error downloading model: " + errorInfo; addAssetToWorldError(filenameFromPath(filePath), errorInfo); } @@ -7982,7 +7935,7 @@ void Application::addAssetToWorldSetMapping(QString filePath, QString mapping, Q // to prevent files that aren't models or texture files from being loaded into world automatically if ((filePath.toLower().endsWith(OBJ_EXTENSION) || filePath.toLower().endsWith(FBX_EXTENSION)) || ((filePath.toLower().endsWith(JPG_EXTENSION) || filePath.toLower().endsWith(PNG_EXTENSION)) && - ((!isBlocks) && (!isZip)))) { + ((!isBlocks) && (!isZip)))) { addAssetToWorldAddEntity(filePath, mapping); } else { qCDebug(interfaceapp) << "Zipped contents are not supported entity files"; @@ -8008,10 +7961,11 @@ void Application::addAssetToWorldAddEntity(QString filePath, QString mapping) { properties.setShapeType(SHAPE_TYPE_SIMPLE_COMPOUND); } properties.setCollisionless(true); // Temporarily set so that doesn't collide with avatar. - properties.setVisible(false); // Temporarily set so that don't see at large unresized dimensions. + properties.setVisible(false); // Temporarily set so that don't see at large unresized dimensions. bool grabbable = (Menu::getInstance()->isOptionChecked(MenuOption::CreateEntitiesGrabbable)); properties.setUserData(grabbable ? GRABBABLE_USER_DATA : NOT_GRABBABLE_USER_DATA); - glm::vec3 positionOffset = getMyAvatar()->getWorldOrientation() * (getMyAvatar()->getSensorToWorldScale() * glm::vec3(0.0f, 0.0f, -2.0f)); + glm::vec3 positionOffset = + getMyAvatar()->getWorldOrientation() * (getMyAvatar()->getSensorToWorldScale() * glm::vec3(0.0f, 0.0f, -2.0f)); properties.setPosition(getMyAvatar()->getWorldPosition() + positionOffset); properties.setRotation(getMyAvatar()->getWorldOrientation()); properties.setGravity(glm::vec3(0.0f, 0.0f, 0.0f)); @@ -8057,12 +8011,11 @@ void Application::addAssetToWorldCheckModelSize() { const glm::vec3 DEFAULT_DIMENSIONS = glm::vec3(0.1f, 0.1f, 0.1f); if (dimensions != DEFAULT_DIMENSIONS) { - // Scale model so that its maximum is exactly specific size. const float MAXIMUM_DIMENSION = getMyAvatar()->getSensorToWorldScale(); auto previousDimensions = dimensions; - auto scale = std::min(MAXIMUM_DIMENSION / dimensions.x, std::min(MAXIMUM_DIMENSION / dimensions.y, - MAXIMUM_DIMENSION / dimensions.z)); + auto scale = std::min(MAXIMUM_DIMENSION / dimensions.x, + std::min(MAXIMUM_DIMENSION / dimensions.y, MAXIMUM_DIMENSION / dimensions.z)); dimensions *= scale; qInfo(interfaceapp) << "Model" << name << "auto-resized from" << previousDimensions << " to " << dimensions; doResize = true; @@ -8109,7 +8062,6 @@ void Application::addAssetToWorldCheckModelSize() { } } - void Application::addAssetToWorldInfo(QString modelName, QString infoText) { // Displays the most recent info message, subject to being overridden by error messages. @@ -8134,8 +8086,8 @@ void Application::addAssetToWorldInfo(QString modelName, QString infoText) { if (!_addAssetToWorldErrorTimer.isActive()) { if (!_addAssetToWorldMessageBox) { - _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, - "Downloading Model", "", QMessageBox::NoButton, QMessageBox::NoButton); + _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, "Downloading Model", + "", QMessageBox::NoButton, QMessageBox::NoButton); connect(_addAssetToWorldMessageBox, SIGNAL(destroyed()), this, SLOT(onAssetToWorldMessageBoxClosed())); } @@ -8217,8 +8169,8 @@ void Application::addAssetToWorldError(QString modelName, QString errorText) { addAssetToWorldInfoClear(modelName); if (!_addAssetToWorldMessageBox) { - _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, - "Downloading Model", "", QMessageBox::NoButton, QMessageBox::NoButton); + _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, "Downloading Model", "", + QMessageBox::NoButton, QMessageBox::NoButton); connect(_addAssetToWorldMessageBox, SIGNAL(destroyed()), this, SLOT(onAssetToWorldMessageBoxClosed())); } @@ -8250,7 +8202,6 @@ void Application::addAssetToWorldErrorTimeout() { } } - void Application::addAssetToWorldMessageClose() { // Clear messages, e.g., if Interface is being closed or domain changes. @@ -8288,7 +8239,6 @@ void Application::onAssetToWorldMessageBoxClosed() { } } - void Application::handleUnzip(QString zipFile, QStringList unzipFile, bool autoAdd, bool isZip, bool isBlocks) { if (autoAdd) { if (!unzipFile.isEmpty()) { @@ -8311,10 +8261,9 @@ void Application::packageModel() { } void Application::loadDialog() { - ModalDialogListener* dlg = OffscreenUi::getOpenFileNameAsync(_glWidget, tr("Open Script"), - getPreviousScriptLocation(), + ModalDialogListener* dlg = OffscreenUi::getOpenFileNameAsync(_glWidget, tr("Open Script"), getPreviousScriptLocation(), tr("JavaScript Files (*.js)")); - connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { disconnect(dlg, &ModalDialogListener::response, this, nullptr); const QString& response = answer.toString(); if (!response.isEmpty() && QFile(response).exists()) { @@ -8335,7 +8284,7 @@ void Application::setPreviousScriptLocation(const QString& location) { void Application::loadScriptURLDialog() const { ModalDialogListener* dlg = OffscreenUi::getTextAsync(OffscreenUi::ICON_NONE, "Open and Run Script", "Script URL"); - connect(dlg, &ModalDialogListener::response, this, [=] (QVariant response) { + connect(dlg, &ModalDialogListener::response, this, [=](QVariant response) { disconnect(dlg, &ModalDialogListener::response, this, nullptr); const QString& newScript = response.toString(); if (QUrl(newScript).scheme() == "atp") { @@ -8388,9 +8337,8 @@ void Application::toggleLogDialog() { if (getLoginDialogPoppedUp()) { return; } - if (! _logDialog) { - - bool keepOnTop =_keepLogWindowOnTop.get(); + if (!_logDialog) { + bool keepOnTop = _keepLogWindowOnTop.get(); #ifdef Q_OS_WIN _logDialog = new LogDialog(keepOnTop ? qApp->getWindow() : nullptr, getLogger()); #elif !defined(Q_OS_ANDROID) @@ -8411,21 +8359,21 @@ void Application::toggleLogDialog() { #endif } - void Application::recreateLogWindow(int keepOnTop) { - _keepLogWindowOnTop.set(keepOnTop != 0); - if (_logDialog) { - bool toggle = _logDialog->isVisible(); - _logDialog->close(); - _logDialog = nullptr; +void Application::recreateLogWindow(int keepOnTop) { + _keepLogWindowOnTop.set(keepOnTop != 0); + if (_logDialog) { + bool toggle = _logDialog->isVisible(); + _logDialog->close(); + _logDialog = nullptr; - if (toggle) { - toggleLogDialog(); - } - } - } + if (toggle) { + toggleLogDialog(); + } + } +} void Application::toggleEntityScriptServerLogDialog() { - if (! _entityScriptServerLogDialog) { + if (!_entityScriptServerLogDialog) { _entityScriptServerLogDialog = new EntityScriptServerLogDialog(nullptr); } @@ -8441,11 +8389,13 @@ void Application::loadAddAvatarBookmarkDialog() const { } void Application::loadAvatarBrowser() const { - auto tablet = dynamic_cast(DependencyManager::get()->getTablet("com.highfidelity.interface.tablet.system")); + auto tablet = dynamic_cast( + DependencyManager::get()->getTablet("com.highfidelity.interface.tablet.system")); // construct the url to the marketplace item QString url = NetworkingConstants::METAVERSE_SERVER_URL().toString() + "/marketplace?category=avatars"; - QString MARKETPLACES_INJECT_SCRIPT_PATH = "file:///" + qApp->applicationDirPath() + "/scripts/system/html/js/marketplacesInject.js"; + QString MARKETPLACES_INJECT_SCRIPT_PATH = + "file:///" + qApp->applicationDirPath() + "/scripts/system/html/js/marketplacesInject.js"; tablet->gotoWebScreen(url, MARKETPLACES_INJECT_SCRIPT_PATH); DependencyManager::get()->openTablet(); } @@ -8465,33 +8415,45 @@ bool Application::takeSnapshotOperators(std::queue& snapshotOp } void Application::takeSnapshot(bool notify, bool includeAnimated, float aspectRatio, const QString& filename) { - addSnapshotOperator(std::make_tuple([notify, includeAnimated, aspectRatio, filename](const QImage& snapshot) { - QString path = DependencyManager::get()->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); + addSnapshotOperator(std::make_tuple( + [notify, includeAnimated, aspectRatio, filename](const QImage& snapshot) { + QString path = + DependencyManager::get() + ->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); - // If we're not doing an animated snapshot as well... - if (!includeAnimated) { - if (!path.isEmpty()) { - // Tell the dependency manager that the capture of the still snapshot has taken place. - emit DependencyManager::get()->stillSnapshotTaken(path, notify); + // If we're not doing an animated snapshot as well... + if (!includeAnimated) { + if (!path.isEmpty()) { + // Tell the dependency manager that the capture of the still snapshot has taken place. + emit DependencyManager::get()->stillSnapshotTaken(path, notify); + } + } else if (!SnapshotAnimated::isAlreadyTakingSnapshotAnimated()) { + qApp->postLambdaEvent([path, aspectRatio] { + // Get an animated GIF snapshot and save it + SnapshotAnimated::saveSnapshotAnimated(path, aspectRatio, + DependencyManager::get()); + }); } - } else if (!SnapshotAnimated::isAlreadyTakingSnapshotAnimated()) { - qApp->postLambdaEvent([path, aspectRatio] { - // Get an animated GIF snapshot and save it - SnapshotAnimated::saveSnapshotAnimated(path, aspectRatio, DependencyManager::get()); - }); - } - }, aspectRatio, true)); + }, + aspectRatio, true)); } void Application::takeSecondaryCameraSnapshot(const bool& notify, const QString& filename) { - addSnapshotOperator(std::make_tuple([notify, filename](const QImage& snapshot) { - QString snapshotPath = DependencyManager::get()->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); + addSnapshotOperator(std::make_tuple( + [notify, filename](const QImage& snapshot) { + QString snapshotPath = + DependencyManager::get() + ->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); - emit DependencyManager::get()->stillSnapshotTaken(snapshotPath, notify); - }, 0.0f, false)); + emit DependencyManager::get()->stillSnapshotTaken(snapshotPath, notify); + }, + 0.0f, false)); } -void Application::takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition, const bool& cubemapOutputFormat, const bool& notify, const QString& filename) { +void Application::takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition, + const bool& cubemapOutputFormat, + const bool& notify, + const QString& filename) { postLambdaEvent([notify, filename, cubemapOutputFormat, cameraPosition] { DependencyManager::get()->save360Snapshot(cameraPosition, cubemapOutputFormat, notify, filename); }); @@ -8568,7 +8530,8 @@ void Application::windowMinimizedChanged(bool minimized) { static std::once_flag once; std::call_once(once, [&] { connect(&_minimizedWindowTimer, &QTimer::timeout, this, [] { - QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(static_cast(Idle)), Qt::HighEventPriority); + QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(static_cast(Idle)), + Qt::HighEventPriority); }); }); @@ -8619,7 +8582,7 @@ void Application::initPlugins(const QStringList& arguments) { if (parser.isSet(disableDisplays)) { auto disabledDisplays = parser.value(disableDisplays).split(',', QString::SkipEmptyParts); - qInfo() << "Disabling following display plugins:" << disabledDisplays; + qInfo() << "Disabling following display plugins:" << disabledDisplays; PluginManager::getInstance()->disableDisplays(disabledDisplays); } @@ -8739,7 +8702,6 @@ DisplayPluginPointer Application::getActiveDisplayPlugin() const { return _displayPlugin; } - #if !defined(DISABLE_QML) static const char* EXCLUSION_GROUP_KEY = "exclusionGroup"; @@ -8747,7 +8709,7 @@ static void addDisplayPluginToMenu(const DisplayPluginPointer& displayPlugin, in auto menu = Menu::getInstance(); QString name = displayPlugin->getName(); auto grouping = displayPlugin->getGrouping(); - QString groupingMenu { "" }; + QString groupingMenu{ "" }; Q_ASSERT(!menu->menuItemExists(MenuOption::OutputMenu, name)); // assign the meny grouping based on plugin grouping @@ -8769,10 +8731,9 @@ static void addDisplayPluginToMenu(const DisplayPluginPointer& displayPlugin, in displayPluginGroup->setExclusive(true); } auto parent = menu->getMenu(MenuOption::OutputMenu); - auto action = menu->addActionToQMenuAndActionHash(parent, - name, QKeySequence(Qt::CTRL + (Qt::Key_0 + index)), qApp, - SLOT(updateDisplayMode()), - QAction::NoRole, Menu::UNSPECIFIED_POSITION, groupingMenu); + auto action = menu->addActionToQMenuAndActionHash(parent, name, QKeySequence(Qt::CTRL + (Qt::Key_0 + index)), qApp, + SLOT(updateDisplayMode()), QAction::NoRole, Menu::UNSPECIFIED_POSITION, + groupingMenu); action->setCheckable(true); action->setChecked(active); @@ -8797,7 +8758,7 @@ void Application::updateDisplayMode() { DisplayPluginPointer newDisplayPlugin = displayPlugins.at(0); auto menu = getPrimaryMenu(); if (menu) { - foreach(DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { + foreach (DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { QString name = displayPlugin->getName(); QAction* action = menu->getActionForOption(name); // Menu might have been removed if the display plugin lost @@ -8887,8 +8848,7 @@ void Application::setDisplayPlugin(DisplayPluginPointer newDisplayPlugin) { RefreshRateManager& refreshRateManager = getRefreshRateManager(); refreshRateManager.setRefreshRateOperator(OpenGLDisplayPlugin::getRefreshRateOperator()); bool isHmd = newDisplayPlugin->isHmd(); - RefreshRateManager::UXMode uxMode = isHmd ? RefreshRateManager::UXMode::HMD : - RefreshRateManager::UXMode::DESKTOP; + RefreshRateManager::UXMode uxMode = isHmd ? RefreshRateManager::UXMode::HMD : RefreshRateManager::UXMode::DESKTOP; refreshRateManager.setUXMode(uxMode); } @@ -8897,11 +8857,10 @@ void Application::setDisplayPlugin(DisplayPluginPointer newDisplayPlugin) { qCDebug(interfaceapp) << "Entering into" << (isHmd ? "HMD" : "Desktop") << "Mode"; // Only log/emit after a successful change - UserActivityLogger::getInstance().logAction("changed_display_mode", { - { "previous_display_mode", _displayPlugin ? _displayPlugin->getName() : "" }, - { "display_mode", newDisplayPlugin ? newDisplayPlugin->getName() : "" }, - { "hmd", isHmd } - }); + UserActivityLogger::getInstance().logAction("changed_display_mode", + { { "previous_display_mode", _displayPlugin ? _displayPlugin->getName() : "" }, + { "display_mode", newDisplayPlugin ? newDisplayPlugin->getName() : "" }, + { "hmd", isHmd } }); emit activeDisplayPluginChanged(); // reset the avatar, to set head and hand palms back to a reasonable default pose. @@ -8968,7 +8927,7 @@ void Application::setShowBulletConstraintLimits(bool value) { } void Application::createLoginDialog() { - const glm::vec3 LOGIN_DIMENSIONS { 0.89f, 0.5f, 0.01f }; + const glm::vec3 LOGIN_DIMENSIONS{ 0.89f, 0.5f, 0.01f }; const auto OFFSET = glm::vec2(0.7f, -0.1f); auto cameraPosition = _myCamera.getPosition(); auto cameraOrientation = _myCamera.getOrientation(); @@ -9045,7 +9004,8 @@ void Application::updateLoginDialogPosition() { } { - glm::vec3 keyboardLocalOffset = cameraOrientation * glm::vec3(-0.4f * getMyAvatar()->getSensorToWorldScale(), -0.3f, 0.2f); + glm::vec3 keyboardLocalOffset = + cameraOrientation * glm::vec3(-0.4f * getMyAvatar()->getSensorToWorldScale(), -0.3f, 0.2f); glm::quat keyboardOrientation = cameraOrientation * glm::quat(glm::radians(glm::vec3(-30.0f, 180.0f, 0.0f))); EntityItemProperties properties; @@ -9057,7 +9017,7 @@ void Application::updateLoginDialogPosition() { } void Application::createAvatarInputsBar() { - const glm::vec3 LOCAL_POSITION { 0.0, 0.0, -1.0 }; + const glm::vec3 LOCAL_POSITION{ 0.0, 0.0, -1.0 }; // DEFAULT_DPI / tablet scale percentage const float DPI = 31.0f / (75.0f / 100.0f); @@ -9211,7 +9171,6 @@ CompositorHelper& Application::getApplicationCompositor() const { return *DependencyManager::get(); } - // virtual functions required for PluginContainer ui::Menu* Application::getPrimaryMenu() { auto appMenu = _window->menuBar(); @@ -9343,7 +9302,9 @@ void Application::showUrlHandler(const QUrl& url) { return; } - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Confirm openUrl", "Do you recognize this path or code and want to open or execute it: " + url.toDisplayString()); + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Confirm openUrl", "Do you recognize this path or code and want to open or execute it: " + + url.toDisplayString()); QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); if (QMessageBox::Yes == static_cast(answer.toInt())) { @@ -9363,11 +9324,8 @@ void Application::beforeEnterBackground() { clearDomainOctreeDetails(); } - - void Application::enterBackground() { - QMetaObject::invokeMethod(DependencyManager::get().data(), - "stop", Qt::BlockingQueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "stop", Qt::BlockingQueuedConnection); // Quest only supports one plugin which can't be deactivated currently #if !defined(ANDROID_APP_QUEST_INTERFACE) if (getActiveDisplayPlugin()->isActive()) { @@ -9377,8 +9335,7 @@ void Application::enterBackground() { } void Application::enterForeground() { - QMetaObject::invokeMethod(DependencyManager::get().data(), - "start", Qt::BlockingQueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "start", Qt::BlockingQueuedConnection); // Quest only supports one plugin which can't be deactivated currently #if !defined(ANDROID_APP_QUEST_INTERFACE) if (!getActiveDisplayPlugin() || getActiveDisplayPlugin()->isActive() || !getActiveDisplayPlugin()->activate()) { @@ -9389,11 +9346,9 @@ void Application::enterForeground() { nodeList->setSendDomainServerCheckInEnabled(true); } - -void Application::toggleAwayMode(){ - QKeyEvent event = QKeyEvent (QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); - QCoreApplication::sendEvent (this, &event); +void Application::toggleAwayMode() { + QKeyEvent event = QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); + QCoreApplication::sendEvent(this, &event); } - #endif diff --git a/interface/src/Application.h b/interface/src/Application.h index 300769b349..6a1b483ea4 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -79,6 +79,8 @@ #include "Sound.h" + + class GLCanvas; class FaceTracker; class MainWindow; @@ -172,6 +174,7 @@ public: void raise(); void showCursor(const Cursor::Icon& cursor); + void InitializePlatform(); bool isThrottleRendering() const; diff --git a/libraries/platform/CMakeLists.txt b/libraries/platform/CMakeLists.txt new file mode 100644 index 0000000000..9caca0635c --- /dev/null +++ b/libraries/platform/CMakeLists.txt @@ -0,0 +1,3 @@ +set(TARGET_NAME platform) +setup_hifi_library() +link_hifi_libraries(shared) \ No newline at end of file diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp new file mode 100644 index 0000000000..492726705b --- /dev/null +++ b/libraries/platform/src/WINPlatform.cpp @@ -0,0 +1,23 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "WINPlatform.h" + +using namespace platform; + +bool WINInstance::enumerateProcessors() { + return true; + +} + +std::string WINInstance::getProcessor(int index) { + + return "Fake processor"; +} + + diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h new file mode 100644 index 0000000000..8380b5864a --- /dev/null +++ b/libraries/platform/src/WINPlatform.h @@ -0,0 +1,21 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#pragma once +#include "platform.h" + +namespace platform { + + class WINInstance : public Instance { + + public: + bool enumerateProcessors(); + std::string getProcessor(int index); + }; + +} // namespace platform \ No newline at end of file diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp new file mode 100644 index 0000000000..a04ced06d8 --- /dev/null +++ b/libraries/platform/src/platform.cpp @@ -0,0 +1,39 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "platform.h" +#include + +#ifdef Q_OS_WIN +#include "WINPlatform.h" +#endif + +#ifdef Q_OS_MACOS +#include "MACPlatform.h" +#endif + +#ifdef Q_OS_LINUX +#endif + +using namespace platform; + +void platform::create() { + + #ifdef Q_OS_WIN + _instance =new WINInstance(); + #elif Q_OS_MAC + #endif +} + +std::string platform::getProcessor(int index) { + return _instance->getProcessor(index); +} + +bool platform::enumerateProcessors() { + return _instance->enumerateProcessors(); +} \ No newline at end of file diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h new file mode 100644 index 0000000000..6a474989a4 --- /dev/null +++ b/libraries/platform/src/platform.h @@ -0,0 +1,33 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + + +#pragma once +#include +#include + +namespace platform { + + class Instance { + + public: + std::string virtual getProcessor(int index) = 0; + bool virtual enumerateProcessors() = 0; + + private: + + std::vector _processors; + }; + + + static Instance *_instance; + + void create(); + std::string getProcessor(int index); + bool enumerateProcessors(); +} \ No newline at end of file From 527cf8b3d339395dd5bed71f0947a8648dd7d889 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 3 May 2019 15:57:45 -0700 Subject: [PATCH 08/50] adding cpu and memory as well as json serialization with the 3rd party library --- interface/src/Application.cpp | 1950 ++++++++++++------------ interface/src/Application.h | 4 +- libraries/platform/CMakeLists.txt | 4 +- libraries/platform/src/WINPlatform.cpp | 74 +- libraries/platform/src/WINPlatform.h | 19 +- libraries/platform/src/platform.cpp | 8 + libraries/platform/src/platform.h | 48 +- 7 files changed, 1082 insertions(+), 1025 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4fce236e31..ee1ea1dc7d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -9,7 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - #include "Application.h" #include @@ -51,7 +50,6 @@ #include #include - #include #include #include @@ -157,6 +155,7 @@ #include #include #include +#include #include "recording/ClipCache.h" #include "AudioClient.h" @@ -195,8 +194,6 @@ #include "scripting/KeyboardScriptingInterface.h" #include "scripting/RefreshRateScriptingInterface.h" - - #if defined(Q_OS_MAC) || defined(Q_OS_WIN) #include "SpeechRecognizer.h" #endif @@ -245,7 +242,6 @@ #include "webbrowser/WebBrowserSuggestionsEngine.h" #include - #include "AboutUtil.h" #include @@ -267,7 +263,7 @@ // On Windows PC, NVidia Optimus laptop, we want to enable NVIDIA GPU // FIXME seems to be broken. extern "C" { - _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; +_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } #endif @@ -336,9 +332,9 @@ static const float INITIAL_QUERY_RADIUS = 10.0f; // priority radius for entitie static const QString DESKTOP_LOCATION = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); -Setting::Handle maxOctreePacketsPerSecond{"maxOctreePPS", DEFAULT_MAX_OCTREE_PPS}; +Setting::Handle maxOctreePacketsPerSecond{ "maxOctreePPS", DEFAULT_MAX_OCTREE_PPS }; -Setting::Handle loginDialogPoppedUp{"loginDialogPoppedUp", false}; +Setting::Handle loginDialogPoppedUp{ "loginDialogPoppedUp", false }; static const QUrl AVATAR_INPUTS_BAR_QML = PathUtils::qmlUrl("AvatarInputsBar.qml"); static const QUrl MIC_BAR_APPLICATION_QML = PathUtils::qmlUrl("hifi/audio/MicBarApplication.qml"); @@ -349,7 +345,7 @@ static const QString NO_MOVEMENT_MAPPING_NAME = "Standard to Action (No Movement static const QString NO_MOVEMENT_MAPPING_JSON = PathUtils::resourcesPath() + "/controllers/standard_nomovement.json"; static const QString MARKETPLACE_CDN_HOSTNAME = "mpassets.highfidelity.com"; -static const int INTERVAL_TO_CHECK_HMD_WORN_STATUS = 500; // milliseconds +static const int INTERVAL_TO_CHECK_HMD_WORN_STATUS = 500; // milliseconds static const QString DESKTOP_DISPLAY_PLUGIN_NAME = "Desktop"; static const QString ACTIVE_DISPLAY_PLUGIN_SETTING_NAME = "activeDisplayPlugin"; static const QString SYSTEM_TABLET = "com.highfidelity.interface.tablet.system"; @@ -360,26 +356,25 @@ static const float FOCUS_HIGHLIGHT_EXPANSION_FACTOR = 1.05f; #if defined(Q_OS_ANDROID) static const QString TESTER_FILE = "/sdcard/_hifi_test_device.txt"; #endif -const std::vector> Application::_acceptedExtensions { - { SVO_EXTENSION, &Application::importSVOFromURL }, - { SVO_JSON_EXTENSION, &Application::importSVOFromURL }, - { AVA_JSON_EXTENSION, &Application::askToWearAvatarAttachmentUrl }, - { JSON_EXTENSION, &Application::importJSONFromURL }, - { JS_EXTENSION, &Application::askToLoadScript }, - { FST_EXTENSION, &Application::askToSetAvatarUrl }, - { JSON_GZ_EXTENSION, &Application::askToReplaceDomainContent }, - { CONTENT_ZIP_EXTENSION, &Application::askToReplaceDomainContent }, - { ZIP_EXTENSION, &Application::importFromZIP }, - { JPG_EXTENSION, &Application::importImage }, - { PNG_EXTENSION, &Application::importImage } -}; +const std::vector> + Application::_acceptedExtensions{ { SVO_EXTENSION, &Application::importSVOFromURL }, + { SVO_JSON_EXTENSION, &Application::importSVOFromURL }, + { AVA_JSON_EXTENSION, &Application::askToWearAvatarAttachmentUrl }, + { JSON_EXTENSION, &Application::importJSONFromURL }, + { JS_EXTENSION, &Application::askToLoadScript }, + { FST_EXTENSION, &Application::askToSetAvatarUrl }, + { JSON_GZ_EXTENSION, &Application::askToReplaceDomainContent }, + { CONTENT_ZIP_EXTENSION, &Application::askToReplaceDomainContent }, + { ZIP_EXTENSION, &Application::importFromZIP }, + { JPG_EXTENSION, &Application::importImage }, + { PNG_EXTENSION, &Application::importImage } }; class DeadlockWatchdogThread : public QThread { public: static const unsigned long HEARTBEAT_UPDATE_INTERVAL_SECS = 1; - static const unsigned long MAX_HEARTBEAT_AGE_USECS = 120 * USECS_PER_SECOND; // 2 mins with no checkin probably a deadlock - static const int WARNING_ELAPSED_HEARTBEAT = 500 * USECS_PER_MSEC; // warn if elapsed heartbeat average is large - static const int HEARTBEAT_SAMPLES = 100000; // ~5 seconds worth of samples + static const unsigned long MAX_HEARTBEAT_AGE_USECS = 120 * USECS_PER_SECOND; // 2 mins with no checkin probably a deadlock + static const int WARNING_ELAPSED_HEARTBEAT = 500 * USECS_PER_MSEC; // warn if elapsed heartbeat average is large + static const int HEARTBEAT_SAMPLES = 100000; // ~5 seconds worth of samples // Set the heartbeat on launch DeadlockWatchdogThread() { @@ -387,14 +382,10 @@ public: // Give the heartbeat an initial value _heartbeat = usecTimestampNow(); _paused = false; - connect(qApp, &QCoreApplication::aboutToQuit, [this] { - _quit = true; - }); + connect(qApp, &QCoreApplication::aboutToQuit, [this] { _quit = true; }); } - void setMainThreadID(Qt::HANDLE threadID) { - _mainThreadID = threadID; - } + void setMainThreadID(Qt::HANDLE threadID) { _mainThreadID = threadID; } static void updateHeartbeat() { auto now = usecTimestampNow(); @@ -415,9 +406,7 @@ public: lambda(); resume(); } - static void pause() { - _paused = true; - } + static void pause() { _paused = true; } static void resume() { // Update the heartbeat BEFORE resuming the checks @@ -432,55 +421,49 @@ public: if (_paused) { continue; } - uint64_t lastHeartbeat = _heartbeat; // sample atomic _heartbeat, because we could context switch away and have it updated on us + uint64_t lastHeartbeat = + _heartbeat; // sample atomic _heartbeat, because we could context switch away and have it updated on us uint64_t now = usecTimestampNow(); auto lastHeartbeatAge = (now > lastHeartbeat) ? now - lastHeartbeat : 0; auto elapsedMovingAverage = _movingAverage.getAverage(); if (elapsedMovingAverage > _maxElapsedAverage) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage - << "maxElapsed:" << _maxElapsed - << "PREVIOUS maxElapsedAverage:" << _maxElapsedAverage + qCDebug(interfaceapp_deadlock) + << "DEADLOCK WATCHDOG WARNING:" + << "lastHeartbeatAge:" << lastHeartbeatAge << "elapsedMovingAverage:" << elapsedMovingAverage + << "maxElapsed:" << _maxElapsed << "PREVIOUS maxElapsedAverage:" << _maxElapsedAverage << "NEW maxElapsedAverage:" << elapsedMovingAverage << "** NEW MAX ELAPSED AVERAGE **" << "samples:" << _movingAverage.getSamples(); _maxElapsedAverage = elapsedMovingAverage; } if (lastHeartbeatAge > _maxElapsed) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage - << "PREVIOUS maxElapsed:" << _maxElapsed - << "NEW maxElapsed:" << lastHeartbeatAge << "** NEW MAX ELAPSED **" - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + qCDebug(interfaceapp_deadlock) + << "DEADLOCK WATCHDOG WARNING:" + << "lastHeartbeatAge:" << lastHeartbeatAge << "elapsedMovingAverage:" << elapsedMovingAverage + << "PREVIOUS maxElapsed:" << _maxElapsed << "NEW maxElapsed:" << lastHeartbeatAge << "** NEW MAX ELAPSED **" + << "maxElapsedAverage:" << _maxElapsedAverage << "samples:" << _movingAverage.getSamples(); _maxElapsed = lastHeartbeatAge; } if (elapsedMovingAverage > WARNING_ELAPSED_HEARTBEAT) { qCDebug(interfaceapp_deadlock) << "DEADLOCK WATCHDOG WARNING:" - << "lastHeartbeatAge:" << lastHeartbeatAge - << "elapsedMovingAverage:" << elapsedMovingAverage << "** OVER EXPECTED VALUE **" - << "maxElapsed:" << _maxElapsed - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + << "lastHeartbeatAge:" << lastHeartbeatAge + << "elapsedMovingAverage:" << elapsedMovingAverage << "** OVER EXPECTED VALUE **" + << "maxElapsed:" << _maxElapsed << "maxElapsedAverage:" << _maxElapsedAverage + << "samples:" << _movingAverage.getSamples(); } if (lastHeartbeatAge > MAX_HEARTBEAT_AGE_USECS) { - qCDebug(interfaceapp_deadlock) << "DEADLOCK DETECTED -- " - << "lastHeartbeatAge:" << lastHeartbeatAge - << "[ lastHeartbeat :" << lastHeartbeat - << "now:" << now << " ]" - << "elapsedMovingAverage:" << elapsedMovingAverage - << "maxElapsed:" << _maxElapsed - << "maxElapsedAverage:" << _maxElapsedAverage - << "samples:" << _movingAverage.getSamples(); + qCDebug(interfaceapp_deadlock) + << "DEADLOCK DETECTED -- " + << "lastHeartbeatAge:" << lastHeartbeatAge << "[ lastHeartbeat :" << lastHeartbeat << "now:" << now << " ]" + << "elapsedMovingAverage:" << elapsedMovingAverage << "maxElapsed:" << _maxElapsed + << "maxElapsedAverage:" << _maxElapsedAverage << "samples:" << _movingAverage.getSamples(); - // Don't actually crash in debug builds, in case this apparent deadlock is simply from - // the developer actively debugging code - #ifdef NDEBUG +// Don't actually crash in debug builds, in case this apparent deadlock is simply from +// the developer actively debugging code +#ifdef NDEBUG deadlockDetectionCrash(); - #endif +#endif } } } @@ -491,7 +474,7 @@ public: static std::atomic _maxElapsedAverage; static ThreadSafeMovingAverage _movingAverage; - bool _quit { false }; + bool _quit{ false }; Qt::HANDLE _mainThreadID = nullptr; }; @@ -516,8 +499,7 @@ bool isDomainURL(QUrl url) { // url.scheme() != HIFI_URL_SCHEME_HTTPS return false; } - if (url.path().endsWith(".json", Qt::CaseInsensitive) || - url.path().endsWith(".json.gz", Qt::CaseInsensitive)) { + if (url.path().endsWith(".json", Qt::CaseInsensitive) || url.path().endsWith(".json.gz", Qt::CaseInsensitive)) { return true; } return false; @@ -531,7 +513,7 @@ public: return staticInstance; } - bool nativeEventFilter(const QByteArray &eventType, void* msg, long* result) Q_DECL_OVERRIDE { + bool nativeEventFilter(const QByteArray& eventType, void* msg, long* result) Q_DECL_OVERRIDE { if (eventType == "windows_generic_MSG") { MSG* message = (MSG*)msg; @@ -559,12 +541,12 @@ public: } if (message->message == WM_DEVICECHANGE) { - const float MIN_DELTA_SECONDS = 2.0f; // de-bounce signal + const float MIN_DELTA_SECONDS = 2.0f; // de-bounce signal static float lastTriggerTime = 0.0f; const float deltaSeconds = secTimestampNow() - lastTriggerTime; lastTriggerTime = secTimestampNow(); if (deltaSeconds > MIN_DELTA_SECONDS) { - Midi::USBchanged(); // re-scan the MIDI bus + Midi::USBchanged(); // re-scan the MIDI bus } } } @@ -575,38 +557,35 @@ public: class LambdaEvent : public QEvent { std::function _fun; + public: - LambdaEvent(const std::function & fun) : - QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) { - } - LambdaEvent(std::function && fun) : - QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) { - } + LambdaEvent(const std::function& fun) : QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) {} + LambdaEvent(std::function&& fun) : QEvent(static_cast(ApplicationEvent::Lambda)), _fun(fun) {} void call() const { _fun(); } }; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { - QString logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message); + QString logMessage = LogHandler::getInstance().printMessage((LogMsgType)type, context, message); if (!logMessage.isEmpty()) { #ifdef Q_OS_ANDROID - const char * local=logMessage.toStdString().c_str(); + const char* local = logMessage.toStdString().c_str(); switch (type) { case QtDebugMsg: - __android_log_write(ANDROID_LOG_DEBUG,"Interface",local); + __android_log_write(ANDROID_LOG_DEBUG, "Interface", local); break; case QtInfoMsg: - __android_log_write(ANDROID_LOG_INFO,"Interface",local); + __android_log_write(ANDROID_LOG_INFO, "Interface", local); break; case QtWarningMsg: - __android_log_write(ANDROID_LOG_WARN,"Interface",local); + __android_log_write(ANDROID_LOG_WARN, "Interface", local); break; case QtCriticalMsg: - __android_log_write(ANDROID_LOG_ERROR,"Interface",local); + __android_log_write(ANDROID_LOG_ERROR, "Interface", local); break; case QtFatalMsg: default: - __android_log_write(ANDROID_LOG_FATAL,"Interface",local); + __android_log_write(ANDROID_LOG_FATAL, "Interface", local); abort(); } #else @@ -615,21 +594,21 @@ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QSt } } - -class ApplicationMeshProvider : public scriptable::ModelProviderFactory { +class ApplicationMeshProvider : public scriptable::ModelProviderFactory { public: virtual scriptable::ModelProviderPointer lookupModelProvider(const QUuid& uuid) override { bool success; if (auto nestable = DependencyManager::get()->find(uuid, success).lock()) { auto type = nestable->getNestableType(); #ifdef SCRIPTABLE_MESH_DEBUG - qCDebug(interfaceapp) << "ApplicationMeshProvider::lookupModelProvider" << uuid << SpatiallyNestable::nestableTypeToString(type); + qCDebug(interfaceapp) << "ApplicationMeshProvider::lookupModelProvider" << uuid + << SpatiallyNestable::nestableTypeToString(type); #endif switch (type) { - case NestableType::Entity: - return getEntityModelProvider(static_cast(uuid)); - case NestableType::Avatar: - return getAvatarModelProvider(uuid); + case NestableType::Entity: + return getEntityModelProvider(static_cast(uuid)); + case NestableType::Avatar: + return getAvatarModelProvider(uuid); } } return nullptr; @@ -731,7 +710,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { // HRS: I could not figure out how to move these any earlier in startup, so when using this option, be sure to also supply // --allowMultipleInstances - auto reportAndQuit = [&](const char* commandSwitch, std::function report) { + auto reportAndQuit = [&](const char* commandSwitch, std::function report) { const char* reportfile = getCmdOption(argc, constArgv, commandSwitch); // Reports to the specified file, because stdout is set up to be captured for logging. if (reportfile) { @@ -739,9 +718,9 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { if (fp) { report(fp); fclose(fp); - if (!runningMarkerExisted) { // don't leave ours around + if (!runningMarkerExisted) { // don't leave ours around RunningMarker runingMarker(RUNNING_MARKER_FILENAME); - runingMarker.deleteRunningMarkerFile(); // happens in deleter, but making the side-effect explicit. + runingMarker.deleteRunningMarkerFile(); // happens in deleter, but making the side-effect explicit. } _exit(0); } @@ -751,9 +730,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { auto version = protocolVersionsSignatureBase64(); fputs(version.toLatin1().data(), fp); }); - reportAndQuit("--version", [&](FILE* fp) { - fputs(BuildInfo::VERSION.toLatin1().data(), fp); - }); + reportAndQuit("--version", [&](FILE* fp) { fputs(BuildInfo::VERSION.toLatin1().data(), fp); }); const char* portStr = getCmdOption(argc, constArgv, "--listenPort"); const int listenPort = portStr ? atoi(portStr) : INVALID_PORT; @@ -772,7 +749,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { qApp->setProperty(hifi::properties::STANDALONE, isStandalone); // Ignore any previous crashes if running from command line with a test script. - bool inTestMode { false }; + bool inTestMode{ false }; for (int i = 0; i < argc; ++i) { QString parameter(argv[i]); if (parameter == TEST_SCRIPT_COMMAND) { @@ -781,7 +758,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { } } - bool previousSessionCrashed { false }; + bool previousSessionCrashed{ false }; if (!inTestMode) { previousSessionCrashed = CrashRecoveryHandler::checkForResetSettings(runningMarkerExisted, suppressPrompt); } @@ -827,7 +804,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { audioDLLPath += "/audioWin7"; } QCoreApplication::addLibraryPath(audioDLLPath); -#endif +#endif DependencyManager::registerInheritance(); DependencyManager::registerInheritance(); @@ -845,7 +822,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(); DependencyManager::set(); #if defined(Q_OS_ANDROID) - DependencyManager::set(); // use the default user agent getter + DependencyManager::set(); // use the default user agent getter #else DependencyManager::set(std::bind(&Application::getUserAgent, qApp)); #endif @@ -859,7 +836,8 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(NodeType::Agent, listenPort); DependencyManager::set(); DependencyManager::set(); - DependencyManager::set(); // ModelFormatRegistry must be defined before ModelCache. See the ModelCache constructor. + DependencyManager::set< + ModelFormatRegistry>(); // ModelFormatRegistry must be defined before ModelCache. See the ModelCache constructor. DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); @@ -911,10 +889,11 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); - controller::StateController::setStateVariables({ { STATE_IN_HMD, STATE_CAMERA_FULL_SCREEN_MIRROR, - STATE_CAMERA_FIRST_PERSON, STATE_CAMERA_THIRD_PERSON, STATE_CAMERA_ENTITY, STATE_CAMERA_INDEPENDENT, - STATE_SNAP_TURN, STATE_ADVANCED_MOVEMENT_CONTROLS, STATE_GROUNDED, STATE_NAV_FOCUSED, - STATE_PLATFORM_WINDOWS, STATE_PLATFORM_MAC, STATE_PLATFORM_ANDROID, STATE_LEFT_HAND_DOMINANT, STATE_RIGHT_HAND_DOMINANT, STATE_STRAFE_ENABLED } }); + controller::StateController::setStateVariables( + { { STATE_IN_HMD, STATE_CAMERA_FULL_SCREEN_MIRROR, STATE_CAMERA_FIRST_PERSON, STATE_CAMERA_THIRD_PERSON, + STATE_CAMERA_ENTITY, STATE_CAMERA_INDEPENDENT, STATE_SNAP_TURN, STATE_ADVANCED_MOVEMENT_CONTROLS, STATE_GROUNDED, + STATE_NAV_FOCUSED, STATE_PLATFORM_WINDOWS, STATE_PLATFORM_MAC, STATE_PLATFORM_ANDROID, STATE_LEFT_HAND_DOMINANT, + STATE_RIGHT_HAND_DOMINANT, STATE_STRAFE_ENABLED } }); DependencyManager::set(); DependencyManager::set(); DependencyManager::set(); @@ -952,7 +931,7 @@ bool setupEssentials(int& argc, char** argv, bool runningMarkerExisted) { // continuing to overburden Application.cpp QUuid _keyboardFocusHighlightID; -OffscreenGLCanvas* _qmlShareContext { nullptr }; +OffscreenGLCanvas* _qmlShareContext{ nullptr }; // FIXME hack access to the internal share context for the Chromium helper // Normally we'd want to use QWebEngine::initialize(), but we can't because @@ -962,11 +941,11 @@ OffscreenGLCanvas* _qmlShareContext { nullptr }; // So instead we create a new offscreen context to share with the QGLWidget, // and manually set THAT to be the shared context for the Chromium helper #if !defined(DISABLE_QML) -OffscreenGLCanvas* _chromiumShareContext { nullptr }; +OffscreenGLCanvas* _chromiumShareContext{ nullptr }; #endif -Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext *context); -Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context(); +Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext* context); +Q_GUI_EXPORT QOpenGLContext* qt_gl_global_share_context(); Setting::Handle sessionRunTime{ "sessionRunTime", 0 }; @@ -988,46 +967,32 @@ QSharedPointer getOffscreenUI() { } Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bool runningMarkerExisted) : - QApplication(argc, argv), - _window(new MainWindow(desktop())), - _sessionRunTimer(startupTimer), + QApplication(argc, argv), _window(new MainWindow(desktop())), _sessionRunTimer(startupTimer), #ifndef Q_OS_ANDROID _logger(new FileLogger(this)), #endif _previousSessionCrashed(setupEssentials(argc, argv, runningMarkerExisted)), - _entitySimulation(new PhysicalEntitySimulation()), - _physicsEngine(new PhysicsEngine(Vectors::ZERO)), - _entityClipboard(new EntityTree()), - _previousScriptLocation("LastScriptLocation", DESKTOP_LOCATION), + _entitySimulation(new PhysicalEntitySimulation()), _physicsEngine(new PhysicsEngine(Vectors::ZERO)), + _entityClipboard(new EntityTree()), _previousScriptLocation("LastScriptLocation", DESKTOP_LOCATION), _fieldOfView("fieldOfView", DEFAULT_FIELD_OF_VIEW_DEGREES), _hmdTabletScale("hmdTabletScale", DEFAULT_HMD_TABLET_SCALE_PERCENT), - _desktopTabletScale("desktopTabletScale", DEFAULT_DESKTOP_TABLET_SCALE_PERCENT), - _firstRun(Settings::firstRun, true), + _desktopTabletScale("desktopTabletScale", DEFAULT_DESKTOP_TABLET_SCALE_PERCENT), _firstRun(Settings::firstRun, true), _desktopTabletBecomesToolbarSetting("desktopTabletBecomesToolbar", DEFAULT_DESKTOP_TABLET_BECOMES_TOOLBAR), _hmdTabletBecomesToolbarSetting("hmdTabletBecomesToolbar", DEFAULT_HMD_TABLET_BECOMES_TOOLBAR), _preferStylusOverLaserSetting("preferStylusOverLaser", DEFAULT_PREFER_STYLUS_OVER_LASER), _preferAvatarFingerOverStylusSetting("preferAvatarFingerOverStylus", DEFAULT_PREFER_AVATAR_FINGER_OVER_STYLUS), _constrainToolbarPosition("toolbar/constrainToolbarToCenterX", true), _preferredCursor("preferredCursor", DEFAULT_CURSOR_NAME), - _miniTabletEnabledSetting("miniTabletEnabled", DEFAULT_MINI_TABLET_ENABLED), - _scaleMirror(1.0f), - _mirrorYawOffset(0.0f), - _raiseMirror(0.0f), - _enableProcessOctreeThread(true), - _lastNackTime(usecTimestampNow()), - _lastSendDownstreamAudioStats(usecTimestampNow()), - _notifiedPacketVersionMismatchThisDomain(false), - _maxOctreePPS(maxOctreePacketsPerSecond.get()), - _lastFaceTrackerUpdate(0), - _snapshotSound(nullptr), - _sampleSound(nullptr) -{ - + _miniTabletEnabledSetting("miniTabletEnabled", DEFAULT_MINI_TABLET_ENABLED), _scaleMirror(1.0f), _mirrorYawOffset(0.0f), + _raiseMirror(0.0f), _enableProcessOctreeThread(true), _lastNackTime(usecTimestampNow()), + _lastSendDownstreamAudioStats(usecTimestampNow()), _notifiedPacketVersionMismatchThisDomain(false), + _maxOctreePPS(maxOctreePacketsPerSecond.get()), _lastFaceTrackerUpdate(0), _snapshotSound(nullptr), _sampleSound(nullptr) { auto steamClient = PluginManager::getInstance()->getSteamClientPlugin(); setProperty(hifi::properties::STEAM, (steamClient && steamClient->isRunning())); setProperty(hifi::properties::CRASHED, _previousSessionCrashed); { + initializePlatform(); //testing const QStringList args = arguments(); for (int i = 0; i < args.size() - 1; ++i) { @@ -1038,7 +1003,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // This is done so as not break previous command line scripts if (testScriptPath.left(HIFI_URL_SCHEME_HTTP.length()) == HIFI_URL_SCHEME_HTTP || testScriptPath.left(HIFI_URL_SCHEME_FTP.length()) == HIFI_URL_SCHEME_FTP) { - setProperty(hifi::properties::TEST, QUrl::fromUserInput(testScriptPath)); } else if (QFileInfo(testScriptPath).exists()) { setProperty(hifi::properties::TEST, QUrl::fromLocalFile(testScriptPath)); @@ -1063,7 +1027,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // make sure the debug draw singleton is initialized on the main thread. DebugDraw::getInstance().removeMarker(""); - PluginContainer* pluginContainer = dynamic_cast(this); // set the container for any plugins that care + PluginContainer* pluginContainer = dynamic_cast(this); // set the container for any plugins that care PluginManager::getInstance()->setContainer(pluginContainer); QThreadPool::globalInstance()->setMaxThreadCount(MIN_PROCESSING_THREAD_POOL_SIZE); @@ -1074,12 +1038,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto controllerScriptingInterface = DependencyManager::get().data(); _controllerScriptingInterface = dynamic_cast(controllerScriptingInterface); - connect(PluginManager::getInstance().data(), &PluginManager::inputDeviceRunningChanged, - controllerScriptingInterface, &controller::ScriptingInterface::updateRunningInputDevices); + connect(PluginManager::getInstance().data(), &PluginManager::inputDeviceRunningChanged, controllerScriptingInterface, + &controller::ScriptingInterface::updateRunningInputDevices); - EntityTree::setEntityClicksCapturedOperator([this] { - return _controllerScriptingInterface->areEntityClicksCaptured(); - }); + EntityTree::setEntityClicksCapturedOperator([this] { return _controllerScriptingInterface->areEntityClicksCaptured(); }); _entityClipboard->createRootElement(); @@ -1101,7 +1063,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "fonts/Cairo-SemiBold.ttf"); _window->setWindowTitle("High Fidelity Interface"); - Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us + Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us auto nodeList = DependencyManager::get(); nodeList->startThread(); @@ -1157,7 +1119,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo bool isStore = property(hifi::properties::OCULUS_STORE).toBool(); - DependencyManager::get()->setLimitedCommerce(isStore); // Or we could make it a separate arg, or if either arg is set, etc. And should this instead by a hifi::properties? + DependencyManager::get()->setLimitedCommerce( + isStore); // Or we could make it a separate arg, or if either arg is set, etc. And should this instead by a hifi::properties? updateHeartbeat(); @@ -1191,14 +1154,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return myAvatar ? myAvatar->getOrientationForAudio() : Quaternions::IDENTITY; }); - recording::Frame::registerFrameHandler(AudioConstants::getAudioFrameName(), [&audioIO](recording::Frame::ConstPointer frame) { - audioIO->handleRecordedAudioInput(frame->data); - }); + recording::Frame::registerFrameHandler(AudioConstants::getAudioFrameName(), + [&audioIO](recording::Frame::ConstPointer frame) { + audioIO->handleRecordedAudioInput(frame->data); + }); connect(audioIO, &AudioClient::inputReceived, [](const QByteArray& audio) { static auto recorder = DependencyManager::get(); if (recorder->isRecording()) { - static const recording::FrameType AUDIO_FRAME_TYPE = recording::Frame::registerFrameType(AudioConstants::getAudioFrameName()); + static const recording::FrameType AUDIO_FRAME_TYPE = + recording::Frame::registerFrameType(AudioConstants::getAudioFrameName()); recorder->recordFrame(AUDIO_FRAME_TYPE, audio); } }); @@ -1215,9 +1180,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(&domainHandler, SIGNAL(domainURLChanged(QUrl)), SLOT(domainURLChanged(QUrl))); connect(&domainHandler, SIGNAL(redirectToErrorDomainURL(QUrl)), SLOT(goToErrorDomainURL(QUrl))); - connect(&domainHandler, &DomainHandler::domainURLChanged, [](QUrl domainURL){ - setCrashAnnotation("domain", domainURL.toString().toStdString()); - }); + connect(&domainHandler, &DomainHandler::domainURLChanged, + [](QUrl domainURL) { setCrashAnnotation("domain", domainURL.toString().toStdString()); }); connect(&domainHandler, SIGNAL(resetting()), SLOT(resettingDomain())); connect(&domainHandler, SIGNAL(connectedToDomain(QUrl)), SLOT(updateWindowTitle())); connect(&domainHandler, SIGNAL(disconnectedFromDomain()), SLOT(updateWindowTitle())); @@ -1245,20 +1209,21 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // We could clear ATP assets only when changing domains, but it's possible that the domain you are connected // to has gone down and switched to a new content set, so when you reconnect the cached ATP assets will no longer be valid. - connect(&domainHandler, &DomainHandler::disconnectedFromDomain, DependencyManager::get().data(), &ScriptCache::clearATPScriptsFromCache); + connect(&domainHandler, &DomainHandler::disconnectedFromDomain, DependencyManager::get().data(), + &ScriptCache::clearATPScriptsFromCache); // update our location every 5 seconds in the metaverse server, assuming that we are authenticated with one const qint64 DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS = 5 * MSECS_PER_SECOND; auto discoverabilityManager = DependencyManager::get(); connect(&locationUpdateTimer, &QTimer::timeout, discoverabilityManager.data(), &DiscoverabilityManager::updateLocation); - connect(&locationUpdateTimer, &QTimer::timeout, - DependencyManager::get().data(), &AddressManager::storeCurrentAddress); + connect(&locationUpdateTimer, &QTimer::timeout, DependencyManager::get().data(), + &AddressManager::storeCurrentAddress); locationUpdateTimer.start(DATA_SERVER_LOCATION_CHANGE_UPDATE_MSECS); // if we get a domain change, immediately attempt update location in metaverse server - connect(&nodeList->getDomainHandler(), &DomainHandler::connectedToDomain, - discoverabilityManager.data(), &DiscoverabilityManager::updateLocation); + connect(&nodeList->getDomainHandler(), &DomainHandler::connectedToDomain, discoverabilityManager.data(), + &DiscoverabilityManager::updateLocation); // send a location update immediately discoverabilityManager->updateLocation(); @@ -1271,8 +1236,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &Application::notifyPacketVersionMismatch); // you might think we could just do this in NodeList but we only want this connection for Interface - connect(&nodeList->getDomainHandler(), SIGNAL(limitOfSilentDomainCheckInsReached()), - nodeList.data(), SLOT(reset())); + connect(&nodeList->getDomainHandler(), SIGNAL(limitOfSilentDomainCheckInsReached()), nodeList.data(), SLOT(reset())); auto dialogsManager = DependencyManager::get(); #if defined(Q_OS_ANDROID) @@ -1290,21 +1254,21 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo accountManager->setAuthURL(NetworkingConstants::METAVERSE_SERVER_URL()); // use our MyAvatar position and quat for address manager path - addressManager->setPositionGetter([this]{ return getMyAvatar()->getWorldFeetPosition(); }); - addressManager->setOrientationGetter([this]{ return getMyAvatar()->getWorldOrientation(); }); + addressManager->setPositionGetter([this] { return getMyAvatar()->getWorldFeetPosition(); }); + addressManager->setOrientationGetter([this] { return getMyAvatar()->getWorldOrientation(); }); connect(addressManager.data(), &AddressManager::hostChanged, this, &Application::updateWindowTitle); connect(this, &QCoreApplication::aboutToQuit, addressManager.data(), &AddressManager::storeCurrentAddress); connect(this, &Application::activeDisplayPluginChanged, this, &Application::updateThreadPoolCount); - connect(this, &Application::activeDisplayPluginChanged, this, [](){ + connect(this, &Application::activeDisplayPluginChanged, this, []() { qApp->setProperty(hifi::properties::HMD, qApp->isHMDMode()); auto displayPlugin = qApp->getActiveDisplayPlugin(); setCrashAnnotation("display_plugin", displayPlugin->getName().toStdString()); setCrashAnnotation("hmd", displayPlugin->isHmd() ? "1" : "0"); }); connect(this, &Application::activeDisplayPluginChanged, this, &Application::updateSystemTabletMode); - connect(this, &Application::activeDisplayPluginChanged, this, [&](){ + connect(this, &Application::activeDisplayPluginChanged, this, [&]() { if (getLoginDialogPoppedUp()) { auto dialogsManager = DependencyManager::get(); auto keyboard = DependencyManager::get(); @@ -1327,10 +1291,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); // Save avatar location immediately after a teleport. - connect(myAvatar.get(), &MyAvatar::positionGoneTo, - DependencyManager::get().data(), &AddressManager::storeCurrentAddress); + connect(myAvatar.get(), &MyAvatar::positionGoneTo, DependencyManager::get().data(), + &AddressManager::storeCurrentAddress); - connect(myAvatar.get(), &MyAvatar::skeletonModelURLChanged, [](){ + connect(myAvatar.get(), &MyAvatar::skeletonModelURLChanged, []() { QUrl avatarURL = qApp->getMyAvatar()->getSkeletonModelURL(); setCrashAnnotation("avatar", avatarURL.toString().toStdString()); }); @@ -1340,26 +1304,30 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo { auto scriptEngines = DependencyManager::get().data(); - scriptEngines->registerScriptInitializer([this](ScriptEnginePointer engine) { - registerScriptEngineWithApplicationServices(engine); - }); + scriptEngines->registerScriptInitializer( + [this](ScriptEnginePointer engine) { registerScriptEngineWithApplicationServices(engine); }); - connect(scriptEngines, &ScriptEngines::scriptCountChanged, this, [this] { - auto scriptEngines = DependencyManager::get(); - if (scriptEngines->getRunningScripts().isEmpty()) { - getMyAvatar()->clearScriptableSettings(); - } - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptCountChanged, this, + [this] { + auto scriptEngines = DependencyManager::get(); + if (scriptEngines->getRunningScripts().isEmpty()) { + getMyAvatar()->clearScriptableSettings(); + } + }, + Qt::QueuedConnection); - connect(scriptEngines, &ScriptEngines::scriptsReloading, this, [this] { - getEntities()->reloadEntityScripts(); - loadAvatarScripts(getMyAvatar()->getScriptUrls()); - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptsReloading, this, + [this] { + getEntities()->reloadEntityScripts(); + loadAvatarScripts(getMyAvatar()->getScriptUrls()); + }, + Qt::QueuedConnection); - connect(scriptEngines, &ScriptEngines::scriptLoadError, - this, [](const QString& filename, const QString& error) { - OffscreenUi::asyncWarning(nullptr, "Error Loading Script", filename + " failed to load."); - }, Qt::QueuedConnection); + connect(scriptEngines, &ScriptEngines::scriptLoadError, this, + [](const QString& filename, const QString& error) { + OffscreenUi::asyncWarning(nullptr, "Error Loading Script", filename + " failed to load."); + }, + Qt::QueuedConnection); } #ifdef _WIN32 @@ -1369,11 +1337,13 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // tell the NodeList instance who to tell the domain server we care about nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer - << NodeType::EntityServer << NodeType::AssetServer << NodeType::MessagesMixer << NodeType::EntityScriptServer); + << NodeType::EntityServer << NodeType::AssetServer + << NodeType::MessagesMixer << NodeType::EntityScriptServer); // connect to the packet sent signal of the _entityEditSender connect(&_entityEditSender, &EntityEditPacketSender::packetSent, this, &Application::packetSent); - connect(&_entityEditSender, &EntityEditPacketSender::addingEntityWithCertificate, this, &Application::addingEntityWithCertificate); + connect(&_entityEditSender, &EntityEditPacketSender::addingEntityWithCertificate, this, + &Application::addingEntityWithCertificate); QString concurrentDownloadsStr = getCmdOption(argc, constArgv, "--concurrent-downloads"); bool success; @@ -1435,7 +1405,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto audioScriptingInterface = DependencyManager::set(); auto audioIO = DependencyManager::get().data(); connect(audioIO, &AudioClient::mutedByMixer, audioScriptingInterface.data(), &AudioScriptingInterface::mutedByMixer); - connect(audioIO, &AudioClient::receivedFirstPacket, audioScriptingInterface.data(), &AudioScriptingInterface::receivedFirstPacket); + connect(audioIO, &AudioClient::receivedFirstPacket, audioScriptingInterface.data(), + &AudioScriptingInterface::receivedFirstPacket); connect(audioIO, &AudioClient::disconnected, audioScriptingInterface.data(), &AudioScriptingInterface::disconnected); connect(audioIO, &AudioClient::muteEnvironmentRequested, [](glm::vec3 position, float radius) { auto audioClient = DependencyManager::get(); @@ -1448,10 +1419,11 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo audioScriptingInterface->environmentMuted(); } }); - QSharedPointer scriptingAudioSharedPointer = qSharedPointerDynamicCast(DependencyManager::get()); + QSharedPointer scriptingAudioSharedPointer = + qSharedPointerDynamicCast(DependencyManager::get()); if (scriptingAudioSharedPointer) { - connect(this, &Application::activeDisplayPluginChanged, - scriptingAudioSharedPointer.data(), &scripting::Audio::onContextChanged); + connect(this, &Application::activeDisplayPluginChanged, scriptingAudioSharedPointer.data(), + &scripting::Audio::onContextChanged); } } @@ -1461,7 +1433,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo qCDebug(interfaceapp, "Initialized Render Engine."); // Overlays need to exist before we set the ContextOverlayInterface dependency - _overlays.init(); // do this before scripts load + _overlays.init(); // do this before scripts load DependencyManager::set(); auto offscreenUi = getOffscreenUI(); @@ -1513,8 +1485,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo updateHeartbeat(); static const QString TESTER = "HIFI_TESTER"; - bool isTester = false; -#if defined (Q_OS_ANDROID) + bool isTester = false; +#if defined(Q_OS_ANDROID) // Since we cannot set environment variables in Android we use a file presence // to denote that this is a testing device QFileInfo check_tester_file(TESTER_FILE); @@ -1523,7 +1495,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo constexpr auto INSTALLER_INI_NAME = "installer.ini"; auto iniPath = QDir(applicationDirPath()).filePath(INSTALLER_INI_NAME); - QFile installerFile { iniPath }; + QFile installerFile{ iniPath }; std::unordered_map installerKeyValues; if (installerFile.open(QIODevice::ReadOnly)) { while (!installerFile.atEnd()) { @@ -1570,29 +1542,27 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo static const QString TESTER = "HIFI_TESTER"; auto gpuIdent = GPUIdent::getInstance(); auto glContextData = getGLContextData(); - QJsonObject properties = { - { "version", applicationVersion() }, - { "tester", QProcessEnvironment::systemEnvironment().contains(TESTER) || isTester }, - { "installer_campaign", installerCampaign }, - { "installer_type", installerType }, - { "build_type", BuildInfo::BUILD_TYPE_STRING }, - { "previousSessionCrashed", _previousSessionCrashed }, - { "previousSessionRuntime", sessionRunTime.get() }, - { "cpu_architecture", QSysInfo::currentCpuArchitecture() }, - { "kernel_type", QSysInfo::kernelType() }, - { "kernel_version", QSysInfo::kernelVersion() }, - { "os_type", QSysInfo::productType() }, - { "os_version", QSysInfo::productVersion() }, - { "gpu_name", gpuIdent->getName() }, - { "gpu_driver", gpuIdent->getDriver() }, - { "gpu_memory", static_cast(gpuIdent->getMemory()) }, - { "gl_version_int", glVersionToInteger(glContextData.value("version").toString()) }, - { "gl_version", glContextData["version"] }, - { "gl_vender", glContextData["vendor"] }, - { "gl_sl_version", glContextData["sl_version"] }, - { "gl_renderer", glContextData["renderer"] }, - { "ideal_thread_count", QThread::idealThreadCount() } - }; + QJsonObject properties = { { "version", applicationVersion() }, + { "tester", QProcessEnvironment::systemEnvironment().contains(TESTER) || isTester }, + { "installer_campaign", installerCampaign }, + { "installer_type", installerType }, + { "build_type", BuildInfo::BUILD_TYPE_STRING }, + { "previousSessionCrashed", _previousSessionCrashed }, + { "previousSessionRuntime", sessionRunTime.get() }, + { "cpu_architecture", QSysInfo::currentCpuArchitecture() }, + { "kernel_type", QSysInfo::kernelType() }, + { "kernel_version", QSysInfo::kernelVersion() }, + { "os_type", QSysInfo::productType() }, + { "os_version", QSysInfo::productVersion() }, + { "gpu_name", gpuIdent->getName() }, + { "gpu_driver", gpuIdent->getDriver() }, + { "gpu_memory", static_cast(gpuIdent->getMemory()) }, + { "gl_version_int", glVersionToInteger(glContextData.value("version").toString()) }, + { "gl_version", glContextData["version"] }, + { "gl_vender", glContextData["vendor"] }, + { "gl_sl_version", glContextData["sl_version"] }, + { "gl_renderer", glContextData["renderer"] }, + { "ideal_thread_count", QThread::idealThreadCount() } }; auto macVersion = QSysInfo::macVersion(); if (macVersion != QSysInfo::MV_None) { properties["os_osx_version"] = QSysInfo::macVersion(); @@ -1629,7 +1599,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // For now we're going to set the PPS for outbound packets to be super high, this is // probably not the right long term solution. But for now, we're going to do this to // allow you to move an entity around in your hand - _entityEditSender.setPacketsPerSecond(3000); // super high!! + _entityEditSender.setPacketsPerSecond(3000); // super high!! // Make sure we don't time out during slow operations at startup updateHeartbeat(); @@ -1637,15 +1607,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(this, SIGNAL(aboutToQuit()), this, SLOT(onAboutToQuit())); // FIXME -- I'm a little concerned about this. - connect(myAvatar->getSkeletonModel().get(), &SkeletonModel::skeletonLoaded, - this, &Application::checkSkeleton, Qt::QueuedConnection); + connect(myAvatar->getSkeletonModel().get(), &SkeletonModel::skeletonLoaded, this, &Application::checkSkeleton, + Qt::QueuedConnection); // Setup the userInputMapper with the actions auto userInputMapper = DependencyManager::get(); connect(userInputMapper.data(), &UserInputMapper::actionEvent, [this](int action, float state) { using namespace controller; auto tabletScriptingInterface = DependencyManager::get(); - QSharedPointer audioScriptingInterface = qSharedPointerDynamicCast(DependencyManager::get()); + QSharedPointer audioScriptingInterface = + qSharedPointerDynamicCast(DependencyManager::get()); { auto actionEnum = static_cast(action); int key = Qt::Key_unknown; @@ -1729,7 +1700,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo if (action == controller::toInt(controller::Action::RETICLE_CLICK)) { auto reticlePos = getApplicationCompositor().getReticlePosition(); - QPoint localPos(reticlePos.x, reticlePos.y); // both hmd and desktop already handle this in our coordinates. + QPoint localPos(reticlePos.x, reticlePos.y); // both hmd and desktop already handle this in our coordinates. if (state) { QMouseEvent mousePress(QEvent::MouseButtonPress, localPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); sendEvent(_glWidget, &mousePress); @@ -1739,7 +1710,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo sendEvent(_glWidget, &mouseRelease); _reticleClickPressed = false; } - return; // nothing else to do + return; // nothing else to do } if (state) { @@ -1764,9 +1735,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice = userInputMapper->getStateDevice(); - _applicationStateDevice->setInputVariant(STATE_IN_HMD, []() -> float { - return qApp->isHMDMode() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_IN_HMD, []() -> float { return qApp->isHMDMode() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_CAMERA_FULL_SCREEN_MIRROR, []() -> float { return qApp->getCamera().getMode() == CAMERA_MODE_MIRROR ? 1 : 0; }); @@ -1782,9 +1751,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice->setInputVariant(STATE_CAMERA_INDEPENDENT, []() -> float { return qApp->getCamera().getMode() == CAMERA_MODE_INDEPENDENT ? 1 : 0; }); - _applicationStateDevice->setInputVariant(STATE_SNAP_TURN, []() -> float { - return qApp->getMyAvatar()->getSnapTurn() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_SNAP_TURN, + []() -> float { return qApp->getMyAvatar()->getSnapTurn() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_ADVANCED_MOVEMENT_CONTROLS, []() -> float { return qApp->getMyAvatar()->useAdvancedMovementControls() ? 1 : 0; }); @@ -1794,9 +1762,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _applicationStateDevice->setInputVariant(STATE_RIGHT_HAND_DOMINANT, []() -> float { return qApp->getMyAvatar()->getDominantHand() == "right" ? 1 : 0; }); - _applicationStateDevice->setInputVariant(STATE_STRAFE_ENABLED, []() -> float { - return qApp->getMyAvatar()->getStrafeEnabled() ? 1 : 0; - }); + _applicationStateDevice->setInputVariant(STATE_STRAFE_ENABLED, + []() -> float { return qApp->getMyAvatar()->getStrafeEnabled() ? 1 : 0; }); _applicationStateDevice->setInputVariant(STATE_GROUNDED, []() -> float { return qApp->getMyAvatar()->getCharacterController()->onGround() ? 1 : 0; @@ -1821,13 +1788,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); _applicationStateDevice->setInputVariant(STATE_PLATFORM_ANDROID, []() -> float { #if defined(Q_OS_ANDROID) - return 1 ; + return 1; #else return 0; #endif }); - getRefreshRateManager().setRefreshRateRegime(RefreshRateManager::RefreshRateRegime::STARTUP); // Setup the _keyboardMouseDevice, _touchscreenDevice, _touchscreenVirtualPadDevice and the user input mapper with the default bindings @@ -1853,28 +1819,30 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Make sure we don't time out during slow operations at startup updateHeartbeat(); QTimer* settingsTimer = new QTimer(); - moveToNewNamedThread(settingsTimer, "Settings Thread", [this, settingsTimer]{ - // This needs to run on the settings thread, so we need to pass the `settingsTimer` as the - // receiver object, otherwise it will run on the application thread and trigger a warning - // about trying to kill the timer on the main thread. - connect(qApp, &Application::beforeAboutToQuit, settingsTimer, [this, settingsTimer]{ - // Disconnect the signal from the save settings - QObject::disconnect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); - // Stop the settings timer - settingsTimer->stop(); - // Delete it (this will trigger the thread destruction - settingsTimer->deleteLater(); - // Mark the settings thread as finished, so we know we can safely save in the main application - // shutdown code - _settingsGuard.trigger(); - }); + moveToNewNamedThread(settingsTimer, "Settings Thread", + [this, settingsTimer] { + // This needs to run on the settings thread, so we need to pass the `settingsTimer` as the + // receiver object, otherwise it will run on the application thread and trigger a warning + // about trying to kill the timer on the main thread. + connect(qApp, &Application::beforeAboutToQuit, settingsTimer, [this, settingsTimer] { + // Disconnect the signal from the save settings + QObject::disconnect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); + // Stop the settings timer + settingsTimer->stop(); + // Delete it (this will trigger the thread destruction + settingsTimer->deleteLater(); + // Mark the settings thread as finished, so we know we can safely save in the main application + // shutdown code + _settingsGuard.trigger(); + }); - int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now - settingsTimer->setSingleShot(false); - settingsTimer->setInterval(SAVE_SETTINGS_INTERVAL); // 10s, Qt::CoarseTimer acceptable - QObject::connect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); - settingsTimer->start(); - }, QThread::LowestPriority); + int SAVE_SETTINGS_INTERVAL = 10 * MSECS_PER_SECOND; // Let's save every seconds for now + settingsTimer->setSingleShot(false); + settingsTimer->setInterval(SAVE_SETTINGS_INTERVAL); // 10s, Qt::CoarseTimer acceptable + QObject::connect(settingsTimer, &QTimer::timeout, this, &Application::saveSettings); + settingsTimer->start(); + }, + QThread::LowestPriority); if (Menu::getInstance()->isOptionChecked(MenuOption::FirstPerson)) { getMyAvatar()->setBoomLength(MyAvatar::ZOOM_MIN); // So that camera doesn't auto-switch to third person. @@ -1886,15 +1854,15 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo AudioInjector::setLocalAudioInterface(audioIO); auto audioScriptingInterface = DependencyManager::get(); audioScriptingInterface->setLocalAudioInterface(audioIO); - connect(audioIO, &AudioClient::noiseGateOpened, audioScriptingInterface.data(), &AudioScriptingInterface::noiseGateOpened); - connect(audioIO, &AudioClient::noiseGateClosed, audioScriptingInterface.data(), &AudioScriptingInterface::noiseGateClosed); + connect(audioIO, &AudioClient::noiseGateOpened, audioScriptingInterface.data(), + &AudioScriptingInterface::noiseGateOpened); + connect(audioIO, &AudioClient::noiseGateClosed, audioScriptingInterface.data(), + &AudioScriptingInterface::noiseGateClosed); connect(audioIO, &AudioClient::inputReceived, audioScriptingInterface.data(), &AudioScriptingInterface::inputReceived); } this->installEventFilter(this); - - #ifdef HAVE_DDE auto ddeTracker = DependencyManager::get(); ddeTracker->init(); @@ -1910,19 +1878,20 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // If launched from Steam, let it handle updates const QString HIFI_NO_UPDATER_COMMAND_LINE_KEY = "--no-updater"; bool noUpdater = arguments().indexOf(HIFI_NO_UPDATER_COMMAND_LINE_KEY) != -1; - bool buildCanUpdate = BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable - || BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Master; + bool buildCanUpdate = + BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable || BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Master; if (!noUpdater && buildCanUpdate) { constexpr auto INSTALLER_TYPE_CLIENT_ONLY = "client_only"; auto applicationUpdater = DependencyManager::set(); - AutoUpdater::InstallerType type = installerType == INSTALLER_TYPE_CLIENT_ONLY - ? AutoUpdater::InstallerType::CLIENT_ONLY : AutoUpdater::InstallerType::FULL; + AutoUpdater::InstallerType type = installerType == INSTALLER_TYPE_CLIENT_ONLY ? AutoUpdater::InstallerType::CLIENT_ONLY + : AutoUpdater::InstallerType::FULL; applicationUpdater->setInstallerType(type); applicationUpdater->setInstallerCampaign(installerCampaign); - connect(applicationUpdater.data(), &AutoUpdater::newVersionIsAvailable, dialogsManager.data(), &DialogsManager::showUpdateDialog); + connect(applicationUpdater.data(), &AutoUpdater::newVersionIsAvailable, dialogsManager.data(), + &DialogsManager::showUpdateDialog); applicationUpdater->checkForUpdate(); } @@ -1941,7 +1910,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo auto keyboard = DependencyManager::get(); if (getEntities()->wantsKeyboardFocus(id)) { setKeyboardFocusEntity(id); - } else if (!keyboard->containsID(id)) { // FIXME: this is a hack to make the keyboard work for now, since the keys would otherwise steal focus + } else if ( + !keyboard->containsID( + id)) { // FIXME: this is a hack to make the keyboard work for now, since the keys would otherwise steal focus setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); } } @@ -1950,57 +1921,63 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(pointerManager.data(), &PointerManager::triggerBeginOverlay, keyboardFocusOperator); auto entityScriptingInterface = DependencyManager::get(); - connect(entityScriptingInterface.data(), &EntityScriptingInterface::deletingEntity, this, [this](const EntityItemID& entityItemID) { - if (entityItemID == _keyboardFocusedEntity.get()) { - setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); - } - }, Qt::QueuedConnection); + connect(entityScriptingInterface.data(), &EntityScriptingInterface::deletingEntity, this, + [this](const EntityItemID& entityItemID) { + if (entityItemID == _keyboardFocusedEntity.get()) { + setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); + } + }, + Qt::QueuedConnection); + + EntityTreeRenderer::setAddMaterialToEntityOperator( + [this](const QUuid& entityID, graphics::MaterialLayer material, const std::string& parentMaterialName) { + if (_aboutToQuit) { + return false; + } + + auto renderable = getEntities()->renderableForEntityId(entityID); + if (renderable) { + renderable->addMaterial(material, parentMaterialName); + return true; + } - EntityTreeRenderer::setAddMaterialToEntityOperator([this](const QUuid& entityID, graphics::MaterialLayer material, const std::string& parentMaterialName) { - if (_aboutToQuit) { return false; - } + }); + EntityTreeRenderer::setRemoveMaterialFromEntityOperator( + [this](const QUuid& entityID, graphics::MaterialPointer material, const std::string& parentMaterialName) { + if (_aboutToQuit) { + return false; + } - auto renderable = getEntities()->renderableForEntityId(entityID); - if (renderable) { - renderable->addMaterial(material, parentMaterialName); - return true; - } + auto renderable = getEntities()->renderableForEntityId(entityID); + if (renderable) { + renderable->removeMaterial(material, parentMaterialName); + return true; + } - return false; - }); - EntityTreeRenderer::setRemoveMaterialFromEntityOperator([this](const QUuid& entityID, graphics::MaterialPointer material, const std::string& parentMaterialName) { - if (_aboutToQuit) { return false; - } + }); - auto renderable = getEntities()->renderableForEntityId(entityID); - if (renderable) { - renderable->removeMaterial(material, parentMaterialName); - return true; - } - - return false; - }); - - EntityTreeRenderer::setAddMaterialToAvatarOperator([](const QUuid& avatarID, graphics::MaterialLayer material, const std::string& parentMaterialName) { - auto avatarManager = DependencyManager::get(); - auto avatar = avatarManager->getAvatarBySessionID(avatarID); - if (avatar) { - avatar->addMaterial(material, parentMaterialName); - return true; - } - return false; - }); - EntityTreeRenderer::setRemoveMaterialFromAvatarOperator([](const QUuid& avatarID, graphics::MaterialPointer material, const std::string& parentMaterialName) { - auto avatarManager = DependencyManager::get(); - auto avatar = avatarManager->getAvatarBySessionID(avatarID); - if (avatar) { - avatar->removeMaterial(material, parentMaterialName); - return true; - } - return false; - }); + EntityTreeRenderer::setAddMaterialToAvatarOperator( + [](const QUuid& avatarID, graphics::MaterialLayer material, const std::string& parentMaterialName) { + auto avatarManager = DependencyManager::get(); + auto avatar = avatarManager->getAvatarBySessionID(avatarID); + if (avatar) { + avatar->addMaterial(material, parentMaterialName); + return true; + } + return false; + }); + EntityTreeRenderer::setRemoveMaterialFromAvatarOperator( + [](const QUuid& avatarID, graphics::MaterialPointer material, const std::string& parentMaterialName) { + auto avatarManager = DependencyManager::get(); + auto avatar = avatarManager->getAvatarBySessionID(avatarID); + if (avatar) { + avatar->removeMaterial(material, parentMaterialName); + return true; + } + return false; + }); EntityTree::setGetEntityObjectOperator([this](const QUuid& id) -> QObject* { auto entities = getEntities(); @@ -2027,9 +2004,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return QSizeF(0.0f, 0.0f); }); - connect(this, &Application::aboutToQuit, [this]() { - setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); - }); + connect(this, &Application::aboutToQuit, [this]() { setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); }); // Add periodic checks to send user activity data static int CHECK_NEARBY_AVATARS_INTERVAL_MS = 10000; @@ -2048,7 +2023,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QTimer* sendStatsTimer = new QTimer(this); sendStatsTimer->setInterval(SEND_STATS_INTERVAL_MS); // 10s, Qt::CoarseTimer acceptable connect(sendStatsTimer, &QTimer::timeout, this, [this]() { - QJsonObject properties = {}; MemoryInfo memInfo; if (getMemoryInfo(memInfo)) { @@ -2059,8 +2033,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // content location and build info - useful for filtering stats auto addressManager = DependencyManager::get(); - auto currentDomain = addressManager->currentShareableAddress(true).toString(); // domain only - auto currentPath = addressManager->currentPath(true); // with orientation + auto currentDomain = addressManager->currentShareableAddress(true).toString(); // domain only + auto currentPath = addressManager->currentPath(true); // with orientation properties["current_domain"] = currentDomain; properties["current_path"] = currentPath; properties["build_version"] = BuildInfo::VERSION; @@ -2124,24 +2098,24 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo startedRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_STARTED).toInt(); startedRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_STARTED).toInt(); startedRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_STARTED).toInt(); - startedRequests["total"] = startedRequests["atp"].toInt() + startedRequests["http"].toInt() - + startedRequests["file"].toInt(); + startedRequests["total"] = + startedRequests["atp"].toInt() + startedRequests["http"].toInt() + startedRequests["file"].toInt(); properties["started_requests"] = startedRequests; QJsonObject successfulRequests; successfulRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_SUCCESS).toInt(); successfulRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_SUCCESS).toInt(); successfulRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_SUCCESS).toInt(); - successfulRequests["total"] = successfulRequests["atp"].toInt() + successfulRequests["http"].toInt() - + successfulRequests["file"].toInt(); + successfulRequests["total"] = + successfulRequests["atp"].toInt() + successfulRequests["http"].toInt() + successfulRequests["file"].toInt(); properties["successful_requests"] = successfulRequests; QJsonObject failedRequests; failedRequests["atp"] = statTracker->getStat(STAT_ATP_REQUEST_FAILED).toInt(); failedRequests["http"] = statTracker->getStat(STAT_HTTP_REQUEST_FAILED).toInt(); failedRequests["file"] = statTracker->getStat(STAT_FILE_REQUEST_FAILED).toInt(); - failedRequests["total"] = failedRequests["atp"].toInt() + failedRequests["http"].toInt() - + failedRequests["file"].toInt(); + failedRequests["total"] = + failedRequests["atp"].toInt() + failedRequests["http"].toInt() + failedRequests["file"].toInt(); properties["failed_requests"] = failedRequests; QJsonObject cacheRequests; @@ -2186,21 +2160,18 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo totalServerOctreeElements += i->second.getTotalElements(); } - properties["local_octree_elements"] = (qint64) OctreeElement::getInternalNodeCount(); - properties["server_octree_elements"] = (qint64) totalServerOctreeElements; + properties["local_octree_elements"] = (qint64)OctreeElement::getInternalNodeCount(); + properties["server_octree_elements"] = (qint64)totalServerOctreeElements; properties["active_display_plugin"] = getActiveDisplayPlugin()->getName(); properties["using_hmd"] = isHMDMode(); _autoSwitchDisplayModeSupportedHMDPlugin = nullptr; - foreach(DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { - if (displayPlugin->isHmd() && - displayPlugin->getSupportsAutoSwitch()) { + foreach (DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { + if (displayPlugin->isHmd() && displayPlugin->getSupportsAutoSwitch()) { _autoSwitchDisplayModeSupportedHMDPlugin = displayPlugin; - _autoSwitchDisplayModeSupportedHMDPluginName = - _autoSwitchDisplayModeSupportedHMDPlugin->getName(); - _previousHMDWornStatus = - _autoSwitchDisplayModeSupportedHMDPlugin->isDisplayVisible(); + _autoSwitchDisplayModeSupportedHMDPluginName = _autoSwitchDisplayModeSupportedHMDPlugin->getName(); + _previousHMDWornStatus = _autoSwitchDisplayModeSupportedHMDPlugin->isDisplayVisible(); break; } } @@ -2208,7 +2179,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo if (_autoSwitchDisplayModeSupportedHMDPlugin) { if (getActiveDisplayPlugin() != _autoSwitchDisplayModeSupportedHMDPlugin && !_autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { - startHMDStandBySession(); + startHMDStandBySession(); } // Poll periodically to check whether the user has worn HMD or not. Switch Display mode accordingly. // If the user wears HMD then switch to VR mode. If the user removes HMD then switch to Desktop mode. @@ -2234,8 +2205,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // controller::Pose considers two poses to be different if either are invalid. In our case, we actually // want to consider the pose to be unchanged if it was invalid and still is invalid, so we check that first. properties["hand_pose_changed"] = - ((leftHandPose.valid || lastLeftHandPose.valid) && (leftHandPose != lastLeftHandPose)) - || ((rightHandPose.valid || lastRightHandPose.valid) && (rightHandPose != lastRightHandPose)); + ((leftHandPose.valid || lastLeftHandPose.valid) && (leftHandPose != lastLeftHandPose)) || + ((rightHandPose.valid || lastRightHandPose.valid) && (rightHandPose != lastRightHandPose)); lastLeftHandPose = leftHandPose; lastRightHandPose = rightHandPose; @@ -2246,11 +2217,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Periodically check for count of nearby avatars static int lastCountOfNearbyAvatars = -1; QTimer* checkNearbyAvatarsTimer = new QTimer(this); - checkNearbyAvatarsTimer->setInterval(CHECK_NEARBY_AVATARS_INTERVAL_MS); // 10 seconds, Qt::CoarseTimer ok + checkNearbyAvatarsTimer->setInterval(CHECK_NEARBY_AVATARS_INTERVAL_MS); // 10 seconds, Qt::CoarseTimer ok connect(checkNearbyAvatarsTimer, &QTimer::timeout, this, []() { auto avatarManager = DependencyManager::get(); int nearbyAvatars = avatarManager->numberOfAvatarsInRange(avatarManager->getMyAvatar()->getWorldPosition(), - NEARBY_AVATAR_RADIUS_METERS) - 1; + NEARBY_AVATAR_RADIUS_METERS) - + 1; if (nearbyAvatars != lastCountOfNearbyAvatars) { lastCountOfNearbyAvatars = nearbyAvatars; UserActivityLogger::getInstance().logAction("nearby_avatars", { { "count", nearbyAvatars } }); @@ -2259,9 +2231,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo checkNearbyAvatarsTimer->start(); // Track user activity event when we receive a mute packet - auto onMutedByMixer = []() { - UserActivityLogger::getInstance().logAction("received_mute_packet"); - }; + auto onMutedByMixer = []() { UserActivityLogger::getInstance().logAction("received_mute_packet"); }; connect(DependencyManager::get().data(), &AudioClient::mutedByMixer, this, onMutedByMixer); // Track when the address bar is opened @@ -2291,16 +2261,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Monitor model assets (e.g., from Clara.io) added to the world that may need resizing. static const int ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS = 1000; - _addAssetToWorldResizeTimer.setInterval(ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS); // 1s, Qt::CoarseTimer acceptable + _addAssetToWorldResizeTimer.setInterval(ADD_ASSET_TO_WORLD_TIMER_INTERVAL_MS); // 1s, Qt::CoarseTimer acceptable connect(&_addAssetToWorldResizeTimer, &QTimer::timeout, this, &Application::addAssetToWorldCheckModelSize); // Auto-update and close adding asset to world info message box. static const int ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS = 5000; - _addAssetToWorldInfoTimer.setInterval(ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS); // 5s, Qt::CoarseTimer acceptable + _addAssetToWorldInfoTimer.setInterval(ADD_ASSET_TO_WORLD_INFO_TIMEOUT_MS); // 5s, Qt::CoarseTimer acceptable _addAssetToWorldInfoTimer.setSingleShot(true); connect(&_addAssetToWorldInfoTimer, &QTimer::timeout, this, &Application::addAssetToWorldInfoTimeout); static const int ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS = 8000; - _addAssetToWorldErrorTimer.setInterval(ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS); // 8s, Qt::CoarseTimer acceptable + _addAssetToWorldErrorTimer.setInterval(ADD_ASSET_TO_WORLD_ERROR_TIMEOUT_MS); // 8s, Qt::CoarseTimer acceptable _addAssetToWorldErrorTimer.setSingleShot(true); connect(&_addAssetToWorldErrorTimer, &QTimer::timeout, this, &Application::addAssetToWorldErrorTimeout); @@ -2312,7 +2282,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo connect(&_myCamera, &Camera::modeUpdated, this, &Application::cameraModeChanged); - DependencyManager::get()->setShouldPickHUDOperator([]() { return DependencyManager::get()->isHMDMode(); }); + DependencyManager::get()->setShouldPickHUDOperator( + []() { return DependencyManager::get()->isHMDMode(); }); DependencyManager::get()->setCalculatePos2DFromHUDOperator([this](const glm::vec3& intersection) { const glm::vec2 MARGIN(25.0f); glm::vec2 maxPos = _controllerScriptingInterface->getViewportDimensions() - MARGIN; @@ -2322,7 +2293,10 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo // Setup the mouse ray pick and related operators { - auto mouseRayPick = std::make_shared(Vectors::ZERO, Vectors::UP, PickFilter(PickScriptingInterface::PICK_ENTITIES() | PickScriptingInterface::PICK_LOCAL_ENTITIES()), 0.0f, true); + auto mouseRayPick = std::make_shared(Vectors::ZERO, Vectors::UP, + PickFilter(PickScriptingInterface::PICK_ENTITIES() | + PickScriptingInterface::PICK_LOCAL_ENTITIES()), + 0.0f, true); mouseRayPick->parentTransform = std::make_shared(); mouseRayPick->setJointState(PickQuery::JOINT_STATE_MOUSE); auto mouseRayPickID = DependencyManager::get()->addPick(PickQuery::Ray, mouseRayPick); @@ -2348,7 +2322,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo DependencyManager::get()->setPrecisionPicking(rayPickID, value); }); - EntityItem::setBillboardRotationOperator([](const glm::vec3& position, const glm::quat& rotation, BillboardMode billboardMode, const glm::vec3& frustumPos) { + EntityItem::setBillboardRotationOperator([](const glm::vec3& position, const glm::quat& rotation, + BillboardMode billboardMode, const glm::vec3& frustumPos) { if (billboardMode == BillboardMode::YAW) { //rotate about vertical to face the camera glm::vec3 dPosition = frustumPos - position; @@ -2374,9 +2349,12 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo return viewFrustum.getPosition(); }); - DependencyManager::get()->setKickConfirmationOperator([this] (const QUuid& nodeID) { userKickConfirmation(nodeID); }); + DependencyManager::get()->setKickConfirmationOperator( + [this](const QUuid& nodeID) { userKickConfirmation(nodeID); }); - render::entities::WebEntityRenderer::setAcquireWebSurfaceOperator([=](const QString& url, bool htmlContent, QSharedPointer& webSurface, bool& cachedWebSurface) { + render::entities::WebEntityRenderer::setAcquireWebSurfaceOperator([=](const QString& url, bool htmlContent, + QSharedPointer& webSurface, + bool& cachedWebSurface) { bool isTablet = url == TabletScriptingInterface::QML; if (htmlContent) { webSurface = DependencyManager::get()->acquire(render::entities::WebEntityRenderer::QML); @@ -2390,7 +2368,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo QObject::connect(webSurface.data(), &hifi::qml::OffscreenSurface::rootContextCreated, rootItemLoadedFunctor); } auto surfaceContext = webSurface->getSurfaceContext(); - surfaceContext->setContextProperty("KeyboardScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("KeyboardScriptingInterface", + DependencyManager::get().data()); } else { // FIXME: the tablet should use the OffscreenQmlSurfaceCache webSurface = QSharedPointer(new OffscreenQmlSurface(), [](OffscreenQmlSurface* webSurface) { @@ -2401,8 +2380,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo }); }); auto rootItemLoadedFunctor = [webSurface, url, isTablet] { - Application::setupQmlSurface(webSurface->getSurfaceContext(), isTablet || url == LOGIN_DIALOG.toString() || url == AVATAR_INPUTS_BAR_QML.toString() || - url == BUBBLE_ICON_QML.toString()); + Application::setupQmlSurface(webSurface->getSurfaceContext(), isTablet || url == LOGIN_DIALOG.toString() || + url == AVATAR_INPUTS_BAR_QML.toString() || + url == BUBBLE_ICON_QML.toString()); }; if (webSurface->getRootItem()) { rootItemLoadedFunctor(); @@ -2416,7 +2396,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo const uint8_t TABLET_FPS = 90; webSurface->setMaxFps(isTablet ? TABLET_FPS : DEFAULT_MAX_FPS); }); - render::entities::WebEntityRenderer::setReleaseWebSurfaceOperator([=](QSharedPointer& webSurface, bool& cachedWebSurface, std::vector& connections) { + render::entities::WebEntityRenderer::setReleaseWebSurfaceOperator([=](QSharedPointer& webSurface, + bool& cachedWebSurface, + std::vector& connections) { QQuickItem* rootItem = webSurface->getRootItem(); // Fix for crash in QtWebEngineCore when rapidly switching domains @@ -2477,6 +2459,19 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo pauseUntilLoginDetermined(); } +///Platform test function not staying for final code +void Application::initializePlatform() { + //init the platform + platform::create(); + + //run the enumeration + if (platform::enumerateProcessors()) { + for (int i = 0; i < platform::getProcessorCount(); i++) { + std::string myPlat = platform::getProcessor(0); + } + } +} + void Application::updateVerboseLogging() { auto menu = Menu::getInstance(); if (!menu) { @@ -2525,10 +2520,10 @@ QString Application::getUserAgent() { return userAgent; } - QString userAgent = "Mozilla/5.0 (HighFidelityInterface/" + BuildInfo::VERSION + "; " - + QSysInfo::productType() + " " + QSysInfo::productVersion() + ")"; + QString userAgent = "Mozilla/5.0 (HighFidelityInterface/" + BuildInfo::VERSION + "; " + QSysInfo::productType() + " " + + QSysInfo::productVersion() + ")"; - auto formatPluginName = [](QString name) -> QString { return name.trimmed().replace(" ", "-"); }; + auto formatPluginName = [](QString name) -> QString { return name.trimmed().replace(" ", "-"); }; // For each plugin, add to userAgent auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins(); @@ -2537,7 +2532,7 @@ QString Application::getUserAgent() { userAgent += " " + formatPluginName(dp->getName()); } } - auto inputPlugins= PluginManager::getInstance()->getInputPlugins(); + auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); for (auto& ip : inputPlugins) { if (ip->isActive()) { userAgent += " " + formatPluginName(ip->getName()); @@ -2571,7 +2566,7 @@ void Application::checkChangeCursor() { QMutexLocker locker(&_changeCursorLock); if (_cursorNeedsChanging) { #ifdef Q_OS_MAC - auto cursorTarget = _window; // OSX doesn't seem to provide for hiding the cursor only on the GL widget + auto cursorTarget = _window; // OSX doesn't seem to provide for hiding the cursor only on the GL widget #else // On windows and linux, hiding the top level cursor also means it's invisible when hovering over the // window menu, which is a pain, so only hide it for the GL surface @@ -2610,7 +2605,7 @@ void Application::onAboutToQuit() { _firstRun.set(false); } - foreach(auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { + foreach (auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { if (inputPlugin->isActive()) { inputPlugin->deactivate(); } @@ -2623,8 +2618,7 @@ void Application::onAboutToQuit() { loginDialogPoppedUp.set(false); getActiveDisplayPlugin()->deactivate(); - if (_autoSwitchDisplayModeSupportedHMDPlugin - && _autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { + if (_autoSwitchDisplayModeSupportedHMDPlugin && _autoSwitchDisplayModeSupportedHMDPlugin->isSessionActive()) { _autoSwitchDisplayModeSupportedHMDPlugin->endSession(); } // use the CloseEventSender via a QThread to send an event that says the user asked for the app to close @@ -2686,7 +2680,7 @@ void Application::cleanupBeforeQuit() { nodeList->getPacketReceiver().setShouldDropPackets(true); } - getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts + getEntities()->shutdown(); // tell the entities system we're shutting down, so it will stop running scripts // Clear any queued processing (I/O, FBX/OBJ/Texture parsing) QThreadPool::globalInstance()->clear(); @@ -2695,7 +2689,7 @@ void Application::cleanupBeforeQuit() { // FIXME: Something is still holding on to the ScriptEnginePointers contained in ScriptEngines, and they hold backpointers to ScriptEngines, // so this doesn't shut down properly - DependencyManager::get()->shutdownScripting(); // stop all currently running global scripts + DependencyManager::get()->shutdownScripting(); // stop all currently running global scripts // These classes hold ScriptEnginePointers, so they must be destroyed before ScriptEngines // Must be done after shutdownScripting in case any scripts try to access these things { @@ -2739,7 +2733,7 @@ void Application::cleanupBeforeQuit() { DependencyManager::destroy(); #endif - DependencyManager::destroy(); // Must be destroyed before TabletScriptingInterface + DependencyManager::destroy(); // Must be destroyed before TabletScriptingInterface // stop QML DependencyManager::destroy(); @@ -2780,14 +2774,14 @@ Application::~Application() { avatarManager->handleProcessedPhysicsTransaction(transaction); avatarManager->deleteAllAvatars(); - + auto myCharacterController = getMyAvatar()->getCharacterController(); myCharacterController->clearDetailedMotionStates(); - + myCharacterController->buildPhysicsTransaction(transaction); _physicsEngine->processTransaction(transaction); myCharacterController->handleProcessedPhysicsTransaction(transaction); - + _physicsEngine->setCharacterController(nullptr); // the _shapeManager should have zero references @@ -2817,7 +2811,7 @@ Application::~Application() { DependencyManager::destroy(); - DependencyManager::destroy(); // must be destroyed before the FramebufferCache + DependencyManager::destroy(); // must be destroyed before the FramebufferCache DependencyManager::destroy(); @@ -2891,7 +2885,7 @@ void Application::initializeGL() { if (!nsightActive()) { _chromiumShareContext = new OffscreenGLCanvas(); _chromiumShareContext->setObjectName("ChromiumShareContext"); - auto format =QSurfaceFormat::defaultFormat(); + auto format = QSurfaceFormat::defaultFormat(); #ifdef Q_OS_MAC // On mac, the primary shared OpenGL context must be a 3.2 core context, // or chromium flips out and spews error spam (but renders fine) @@ -2910,7 +2904,6 @@ void Application::initializeGL() { } #endif - _glWidget->createContext(globalShareContext); if (!_glWidget->makeCurrent()) { @@ -2919,7 +2912,7 @@ void Application::initializeGL() { #if !defined(DISABLE_QML) QStringList chromiumFlags; - // Bug 21993: disable microphone and camera input + // Bug 21993: disable microphone and camera input chromiumFlags << "--use-fake-device-for-media-stream"; // Disable signed distance field font rendering on ATI/AMD GPUs, due to // https://highfidelity.manuscript.com/f/cases/13677/Text-showing-up-white-on-Marketplace-app @@ -2956,7 +2949,6 @@ void Application::initializeGL() { } #endif - // Build an offscreen GL context for the main thread. _glWidget->makeCurrent(); glClearColor(0.2f, 0.2f, 0.2f, 1); @@ -2974,18 +2966,18 @@ void Application::initializeDisplayPlugins() { auto defaultDisplayPlugin = displayPlugins.at(0); // Once time initialization code DisplayPluginPointer targetDisplayPlugin; - foreach(auto displayPlugin, displayPlugins) { + foreach (auto displayPlugin, displayPlugins) { displayPlugin->setContext(_graphicsEngine.getGPUContext()); if (displayPlugin->getName() == lastActiveDisplayPluginName) { targetDisplayPlugin = displayPlugin; } QObject::connect(displayPlugin.get(), &DisplayPlugin::recommendedFramebufferSizeChanged, - [this](const QSize& size) { resizeGL(); }); + [this](const QSize& size) { resizeGL(); }); QObject::connect(displayPlugin.get(), &DisplayPlugin::resetSensorsRequested, this, &Application::requestReset); if (displayPlugin->isHmd()) { auto hmdDisplayPlugin = dynamic_cast(displayPlugin.get()); QObject::connect(hmdDisplayPlugin, &HmdDisplayPlugin::hmdMountedChanged, - DependencyManager::get().data(), &HMDScriptingInterface::mountedChanged); + DependencyManager::get().data(), &HMDScriptingInterface::mountedChanged); QObject::connect(hmdDisplayPlugin, &HmdDisplayPlugin::hmdVisibleChanged, this, &Application::hmdVisibleChanged); } } @@ -3022,7 +3014,8 @@ void Application::showLoginScreen() { auto dialogsManager = DependencyManager::get(); if (!accountManager->isLoggedIn()) { if (!isHMDMode()) { - auto toolbar = DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); + auto toolbar = + DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); toolbar->writeProperty("visible", false); } _loginDialogPoppedUp = true; @@ -3051,60 +3044,64 @@ void Application::initializeUi() { QmlContextCallback commerceCallback = [](QQmlContext* context) { context->setContextProperty("Commerce", DependencyManager::get().data()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/checkout/Checkout.qml" }, - QUrl{ "hifi/commerce/common/CommerceLightbox.qml" }, - QUrl{ "hifi/commerce/common/EmulatedMarketplaceHeader.qml" }, - QUrl{ "hifi/commerce/common/FirstUseTutorial.qml" }, - QUrl{ "hifi/commerce/common/sendAsset/SendAsset.qml" }, - QUrl{ "hifi/commerce/common/SortableListModel.qml" }, - QUrl{ "hifi/commerce/inspectionCertificate/InspectionCertificate.qml" }, - QUrl{ "hifi/commerce/marketplaceItemTester/MarketplaceItemTester.qml"}, - QUrl{ "hifi/commerce/purchases/PurchasedItem.qml" }, - QUrl{ "hifi/commerce/purchases/Purchases.qml" }, - QUrl{ "hifi/commerce/wallet/Help.qml" }, - QUrl{ "hifi/commerce/wallet/NeedsLogIn.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseChange.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseModal.qml" }, - QUrl{ "hifi/commerce/wallet/PassphraseSelection.qml" }, - QUrl{ "hifi/commerce/wallet/Wallet.qml" }, - QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, - QUrl{ "hifi/commerce/wallet/WalletSetup.qml" }, - QUrl{ "hifi/dialogs/security/Security.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageChange.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageModel.qml" }, - QUrl{ "hifi/dialogs/security/SecurityImageSelection.qml" }, - QUrl{ "hifi/tablet/TabletMenu.qml" }, - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - }, commerceCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/checkout/Checkout.qml" }, + QUrl{ "hifi/commerce/common/CommerceLightbox.qml" }, + QUrl{ "hifi/commerce/common/EmulatedMarketplaceHeader.qml" }, + QUrl{ "hifi/commerce/common/FirstUseTutorial.qml" }, + QUrl{ "hifi/commerce/common/sendAsset/SendAsset.qml" }, + QUrl{ "hifi/commerce/common/SortableListModel.qml" }, + QUrl{ "hifi/commerce/inspectionCertificate/InspectionCertificate.qml" }, + QUrl{ "hifi/commerce/marketplaceItemTester/MarketplaceItemTester.qml" }, + QUrl{ "hifi/commerce/purchases/PurchasedItem.qml" }, + QUrl{ "hifi/commerce/purchases/Purchases.qml" }, + QUrl{ "hifi/commerce/wallet/Help.qml" }, + QUrl{ "hifi/commerce/wallet/NeedsLogIn.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseChange.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseModal.qml" }, + QUrl{ "hifi/commerce/wallet/PassphraseSelection.qml" }, + QUrl{ "hifi/commerce/wallet/Wallet.qml" }, + QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, + QUrl{ "hifi/commerce/wallet/WalletSetup.qml" }, + QUrl{ "hifi/dialogs/security/Security.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageChange.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageModel.qml" }, + QUrl{ "hifi/dialogs/security/SecurityImageSelection.qml" }, + QUrl{ "hifi/tablet/TabletMenu.qml" }, + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + }, + commerceCallback); QmlContextCallback marketplaceCallback = [](QQmlContext* context) { context->setContextProperty("MarketplaceScriptingInterface", new QmlMarketplace()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - }, marketplaceCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + }, + marketplaceCallback); QmlContextCallback platformInfoCallback = [](QQmlContext* context) { context->setContextProperty("PlatformInfo", new PlatformInfoScriptingInterface()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, - QUrl{ "hifi/commerce/purchases/Purchases.qml" }, - QUrl{ "hifi/commerce/wallet/Wallet.qml" }, - QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, - QUrl{ "hifi/tablet/TabletAddressDialog.qml" }, - QUrl{ "hifi/Card.qml" }, - QUrl{ "hifi/Pal.qml" }, - QUrl{ "hifi/NameCard.qml" }, - }, platformInfoCallback); + OffscreenQmlSurface::addWhitelistContextHandler( + { + QUrl{ "hifi/commerce/marketplace/Marketplace.qml" }, + QUrl{ "hifi/commerce/purchases/Purchases.qml" }, + QUrl{ "hifi/commerce/wallet/Wallet.qml" }, + QUrl{ "hifi/commerce/wallet/WalletHome.qml" }, + QUrl{ "hifi/tablet/TabletAddressDialog.qml" }, + QUrl{ "hifi/Card.qml" }, + QUrl{ "hifi/Pal.qml" }, + QUrl{ "hifi/NameCard.qml" }, + }, + platformInfoCallback); QmlContextCallback ttsCallback = [](QQmlContext* context) { context->setContextProperty("TextToSpeech", DependencyManager::get().data()); }; - OffscreenQmlSurface::addWhitelistContextHandler({ - QUrl{ "hifi/tts/TTS.qml" } - }, ttsCallback); + OffscreenQmlSurface::addWhitelistContextHandler({ QUrl{ "hifi/tts/TTS.qml" } }, ttsCallback); qmlRegisterType("Hifi", 1, 0, "ResourceImageItem"); qmlRegisterType("Hifi", 1, 0, "Preference"); qmlRegisterType("HifiWeb", 1, 0, "WebBrowserSuggestionsEngine"); @@ -3115,18 +3112,15 @@ void Application::initializeUi() { } auto offscreenUi = getOffscreenUI(); - connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootContextCreated, - this, &Application::onDesktopRootContextCreated); - connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootItemCreated, - this, &Application::onDesktopRootItemCreated); + connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootContextCreated, this, + &Application::onDesktopRootContextCreated); + connect(offscreenUi.data(), &hifi::qml::OffscreenSurface::rootItemCreated, this, &Application::onDesktopRootItemCreated); #if !defined(DISABLE_QML) offscreenUi->setProxyWindow(_window->windowHandle()); // OffscreenUi is a subclass of OffscreenQmlSurface specifically designed to // support the window management and scripting proxies for VR use - DeadlockWatchdogThread::withPause([&] { - offscreenUi->createDesktop(PathUtils::qmlUrl("hifi/Desktop.qml")); - }); + DeadlockWatchdogThread::withPause([&] { offscreenUi->createDesktop(PathUtils::qmlUrl("hifi/Desktop.qml")); }); // FIXME either expose so that dialogs can set this themselves or // do better detection in the offscreen UI of what has focus offscreenUi->setNavigationFocused(false); @@ -3150,7 +3144,7 @@ void Application::initializeUi() { }); offscreenUi->resume(); #endif - connect(_window, &MainWindow::windowGeometryChanged, [this](const QRect& r){ + connect(_window, &MainWindow::windowGeometryChanged, [this](const QRect& r) { resizeGL(); if (_touchscreenVirtualPadDevice) { _touchscreenVirtualPadDevice->resize(); @@ -3159,7 +3153,7 @@ void Application::initializeUi() { // This will set up the input plugins UI _activeInputPlugins.clear(); - foreach(auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { + foreach (auto inputPlugin, PluginManager::getInstance()->getInputPlugins()) { if (KeyboardMouseDevice::NAME == inputPlugin->getName()) { _keyboardMouseDevice = std::dynamic_pointer_cast(inputPlugin); } @@ -3170,10 +3164,8 @@ void Application::initializeUi() { _touchscreenVirtualPadDevice = std::dynamic_pointer_cast(inputPlugin); #if defined(ANDROID_APP_INTERFACE) auto& virtualPadManager = VirtualPad::Manager::instance(); - connect(&virtualPadManager, &VirtualPad::Manager::hapticFeedbackRequested, - this, [](int duration) { - AndroidHelper::instance().performHapticFeedback(duration); - }); + connect(&virtualPadManager, &VirtualPad::Manager::hapticFeedbackRequested, this, + [](int duration) { AndroidHelper::instance().performHapticFeedback(duration); }); #endif } } @@ -3181,10 +3173,9 @@ void Application::initializeUi() { auto compositorHelper = DependencyManager::get(); connect(compositorHelper.data(), &CompositorHelper::allowMouseCaptureChanged, this, [=] { if (isHMDMode()) { - auto compositorHelper = DependencyManager::get(); // don't capture outer smartpointer - showCursor(compositorHelper->getAllowMouseCapture() ? - Cursor::Manager::lookupIcon(_preferredCursor.get()) : - Cursor::Icon::SYSTEM); + auto compositorHelper = DependencyManager::get(); // don't capture outer smartpointer + showCursor(compositorHelper->getAllowMouseCapture() ? Cursor::Manager::lookupIcon(_preferredCursor.get()) + : Cursor::Icon::SYSTEM); } }); @@ -3195,8 +3186,10 @@ void Application::initializeUi() { if (rootObject == TabletScriptingInterface::QML) { // in Qt 5.10.0 there is already an "Audio" object in the QML context // though I failed to find it (from QtMultimedia??). So.. let it be "AudioScriptingInterface" - surfaceContext->setContextProperty("AudioScriptingInterface", DependencyManager::get().data()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("AudioScriptingInterface", + DependencyManager::get().data()); + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED } }); @@ -3212,10 +3205,12 @@ void Application::initializeUi() { auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins(); // first sort the plugins into groupings: standard, advanced, developer std::stable_sort(displayPlugins.begin(), displayPlugins.end(), - [](const DisplayPluginPointer& a, const DisplayPluginPointer& b) -> bool { return a->getGrouping() < b->getGrouping(); }); + [](const DisplayPluginPointer& a, const DisplayPluginPointer& b) -> bool { + return a->getGrouping() < b->getGrouping(); + }); int dpIndex = 1; // concatenate the groupings into a single list in the order: standard, advanced, developer - for(const auto& displayPlugin : displayPlugins) { + for (const auto& displayPlugin : displayPlugins) { addDisplayPluginToMenu(displayPlugin, dpIndex, _displayPlugin == displayPlugin); dpIndex++; } @@ -3226,18 +3221,15 @@ void Application::initializeUi() { } #endif - // The display plugins are created before the menu now, so we need to do this here to hide the menu bar // now that it exists if (_window && _window->isFullScreen()) { setFullscreen(nullptr, true); } - setIsInterstitialMode(true); } - void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { auto engine = surfaceContext->engine(); // in Qt 5.10.0 there is already an "Audio" object in the QML context @@ -3272,7 +3264,8 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("AvatarList", DependencyManager::get().data()); surfaceContext->setContextProperty("Users", DependencyManager::get().data()); - surfaceContext->setContextProperty("UserActivityLogger", DependencyManager::get().data()); + surfaceContext->setContextProperty("UserActivityLogger", + DependencyManager::get().data()); surfaceContext->setContextProperty("Camera", &_myCamera); @@ -3297,8 +3290,10 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("InputConfiguration", DependencyManager::get().data()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - surfaceContext->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED surfaceContext->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); surfaceContext->setContextProperty("DialogsManager", _dialogsManagerScriptingInterface); @@ -3356,12 +3351,10 @@ void Application::userKickConfirmation(const QUuid& nodeID) { } QString kickMessage = "Do you wish to kick " + userName + " from your domain"; - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Kick User", kickMessage, - QMessageBox::Yes | QMessageBox::No); + ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Kick User", kickMessage, QMessageBox::Yes | QMessageBox::No); if (dlg->getDialogItem()) { - - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); bool yes = (static_cast(answer.toInt()) == QMessageBox::Yes); @@ -3380,14 +3373,16 @@ void Application::userKickConfirmation(const QUuid& nodeID) { void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditionalContextProperties) { surfaceContext->setContextProperty("Users", DependencyManager::get().data()); surfaceContext->setContextProperty("HMD", DependencyManager::get().data()); - surfaceContext->setContextProperty("UserActivityLogger", DependencyManager::get().data()); + surfaceContext->setContextProperty("UserActivityLogger", + DependencyManager::get().data()); surfaceContext->setContextProperty("Preferences", DependencyManager::get().data()); surfaceContext->setContextProperty("Vec3", new Vec3()); surfaceContext->setContextProperty("Quat", new Quat()); surfaceContext->setContextProperty("MyAvatar", DependencyManager::get()->getMyAvatar().get()); surfaceContext->setContextProperty("Entities", DependencyManager::get().data()); surfaceContext->setContextProperty("Snapshot", DependencyManager::get().data()); - surfaceContext->setContextProperty("KeyboardScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("KeyboardScriptingInterface", + DependencyManager::get().data()); if (setAdditionalContextProperties) { auto tabletScriptingInterface = DependencyManager::get(); @@ -3400,8 +3395,10 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("MenuInterface", MenuScriptingInterface::getInstance()); surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); - surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - surfaceContext->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + surfaceContext->setContextProperty("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED surfaceContext->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); // in Qt 5.10.0 there is already an "Audio" object in the QML context @@ -3421,14 +3418,16 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("InputConfiguration", DependencyManager::get().data()); surfaceContext->setContextProperty("SoundCache", DependencyManager::get().data()); surfaceContext->setContextProperty("AvatarBookmarks", DependencyManager::get().data()); - surfaceContext->setContextProperty("Render", AbstractViewStateInterface::instance()->getRenderEngine()->getConfiguration().get()); + surfaceContext->setContextProperty("Render", + AbstractViewStateInterface::instance()->getRenderEngine()->getConfiguration().get()); surfaceContext->setContextProperty("Workload", qApp->getGameWorkload()._engine->getConfiguration().get()); surfaceContext->setContextProperty("Controller", DependencyManager::get().data()); surfaceContext->setContextProperty("Pointers", DependencyManager::get().data()); surfaceContext->setContextProperty("Window", DependencyManager::get().data()); surfaceContext->setContextProperty("Reticle", qApp->getApplicationCompositor().getReticleInterface()); surfaceContext->setContextProperty("HiFiAbout", AboutUtil::getInstance()); - surfaceContext->setContextProperty("WalletScriptingInterface", DependencyManager::get().data()); + surfaceContext->setContextProperty("WalletScriptingInterface", + DependencyManager::get().data()); surfaceContext->setContextProperty("ResourceRequestObserver", DependencyManager::get().data()); } } @@ -3448,20 +3447,17 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { // Using the latter will cause the camera to wobble with idle animations, // or with changes from the face tracker if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) { - _thirdPersonHMDCameraBoomValid= false; + _thirdPersonHMDCameraBoomValid = false; if (isHMDMode()) { mat4 camMat = myAvatar->getSensorToWorldMatrix() * myAvatar->getHMDSensorMatrix(); _myCamera.setPosition(extractTranslation(camMat)); _myCamera.setOrientation(glmExtractRotation(camMat)); - } - else { + } else { _myCamera.setPosition(myAvatar->getDefaultEyePosition()); _myCamera.setOrientation(myAvatar->getMyHead()->getHeadOrientation()); } - } - else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { + } else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) { if (isHMDMode()) { - if (!_thirdPersonHMDCameraBoomValid) { const glm::vec3 CAMERA_OFFSET = glm::vec3(0.0f, 0.0f, 0.7f); _thirdPersonHMDCameraBoom = cancelOutRollAndPitch(myAvatar->getHMDSensorOrientation()) * CAMERA_OFFSET; @@ -3470,32 +3466,29 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { glm::mat4 thirdPersonCameraSensorToWorldMatrix = myAvatar->getSensorToWorldMatrix(); - const glm::vec3 cameraPos = myAvatar->getHMDSensorPosition() + _thirdPersonHMDCameraBoom * myAvatar->getBoomLength(); + const glm::vec3 cameraPos = + myAvatar->getHMDSensorPosition() + _thirdPersonHMDCameraBoom * myAvatar->getBoomLength(); glm::mat4 sensorCameraMat = createMatFromQuatAndPos(myAvatar->getHMDSensorOrientation(), cameraPos); glm::mat4 worldCameraMat = thirdPersonCameraSensorToWorldMatrix * sensorCameraMat; _myCamera.setOrientation(glm::normalize(glmExtractRotation(worldCameraMat))); _myCamera.setPosition(extractTranslation(worldCameraMat)); - } - else { + } else { _thirdPersonHMDCameraBoomValid = false; _myCamera.setOrientation(myAvatar->getHead()->getOrientation()); if (isOptionChecked(MenuOption::CenterPlayerInView)) { - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + _myCamera.getOrientation() * boomOffset); - } - else { - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + myAvatar->getWorldOrientation() * boomOffset); + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + _myCamera.getOrientation() * boomOffset); + } else { + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + myAvatar->getWorldOrientation() * boomOffset); } } - } - else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) { - _thirdPersonHMDCameraBoomValid= false; + } else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) { + _thirdPersonHMDCameraBoomValid = false; if (isHMDMode()) { - auto mirrorBodyOrientation = myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f)); + auto mirrorBodyOrientation = + myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f)); glm::quat hmdRotation = extractRotation(myAvatar->getHMDSensorMatrix()); // Mirror HMD yaw and roll @@ -3512,26 +3505,24 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { // Mirror HMD lateral offsets hmdOffset.x = -hmdOffset.x; - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) - + mirrorBodyOrientation * glm::vec3(0.0f, 0.0f, 1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror - + mirrorBodyOrientation * hmdOffset); - } - else { + _myCamera.setPosition( + myAvatar->getDefaultEyePosition() + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) + + mirrorBodyOrientation * glm::vec3(0.0f, 0.0f, 1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror + + mirrorBodyOrientation * hmdOffset); + } else { auto userInputMapper = DependencyManager::get(); const float YAW_SPEED = TWO_PI / 5.0f; float deltaYaw = userInputMapper->getActionState(controller::Action::YAW) * YAW_SPEED * deltaTime; _mirrorYawOffset += deltaYaw; _myCamera.setOrientation(myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, PI + _mirrorYawOffset, 0.0f))); - _myCamera.setPosition(myAvatar->getDefaultEyePosition() - + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) - + (myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, _mirrorYawOffset, 0.0f))) * - glm::vec3(0.0f, 0.0f, -1.0f) * myAvatar->getBoomLength() * _scaleMirror); + _myCamera.setPosition(myAvatar->getDefaultEyePosition() + + glm::vec3(0, _raiseMirror * myAvatar->getModelScale(), 0) + + (myAvatar->getWorldOrientation() * glm::quat(glm::vec3(0.0f, _mirrorYawOffset, 0.0f))) * + glm::vec3(0.0f, 0.0f, -1.0f) * myAvatar->getBoomLength() * _scaleMirror); } renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE; - } - else if (_myCamera.getMode() == CAMERA_MODE_ENTITY) { - _thirdPersonHMDCameraBoomValid= false; + } else if (_myCamera.getMode() == CAMERA_MODE_ENTITY) { + _thirdPersonHMDCameraBoomValid = false; EntityItemPointer cameraEntity = _myCamera.getCameraEntityPointer(); if (cameraEntity != nullptr) { if (isHMDMode()) { @@ -3539,8 +3530,7 @@ void Application::updateCamera(RenderArgs& renderArgs, float deltaTime) { _myCamera.setOrientation(cameraEntity->getWorldOrientation() * hmdRotation); glm::vec3 hmdOffset = extractTranslation(myAvatar->getHMDSensorMatrix()); _myCamera.setPosition(cameraEntity->getWorldPosition() + (hmdRotation * hmdOffset)); - } - else { + } else { _myCamera.setOrientation(cameraEntity->getWorldOrientation()); _myCamera.setPosition(cameraEntity->getWorldPosition()); } @@ -3560,7 +3550,6 @@ void Application::runTests() { } void Application::faceTrackerMuteToggled() { - QAction* muteAction = Menu::getInstance()->getActionForOption(MenuOption::MuteFaceTracking); Q_CHECK_PTR(muteAction); bool isMuted = getSelectedFaceTracker()->isMuted(); @@ -3607,9 +3596,8 @@ void Application::setPreferredCursor(const QString& cursorName) { if (_displayPlugin && _displayPlugin->isHmd()) { _preferredCursor.set(cursorName.isEmpty() ? DEFAULT_CURSOR_NAME : cursorName); - } - else { - _preferredCursor.set(cursorName.isEmpty() ? Cursor::Manager::getIconName(Cursor::Icon::SYSTEM) : cursorName); + } else { + _preferredCursor.set(cursorName.isEmpty() ? Cursor::Manager::getIconName(Cursor::Icon::SYSTEM) : cursorName); } showCursor(Cursor::Manager::lookupIcon(_preferredCursor.get())); @@ -3665,7 +3653,8 @@ void Application::showHelp() { QUrlQuery queryString; queryString.addQueryItem("handControllerName", handControllerName); queryString.addQueryItem("defaultTab", defaultTab); - TabletProxy* tablet = dynamic_cast(DependencyManager::get()->getTablet(SYSTEM_TABLET)); + TabletProxy* tablet = + dynamic_cast(DependencyManager::get()->getTablet(SYSTEM_TABLET)); tablet->gotoWebScreen(PathUtils::resourcesUrl() + INFO_HELP_PATH + "?" + queryString.toString()); DependencyManager::get()->openTablet(); //InfoView::show(INFO_HELP_PATH, false, queryString.toString()); @@ -3705,8 +3694,8 @@ void Application::resizeGL() { // FIXME the aspect ratio for stereo displays is incorrect based on this. float aspectRatio = displayPlugin->getRecommendedAspectRatio(); - _myCamera.setProjection(glm::perspective(glm::radians(_fieldOfView.get()), aspectRatio, - DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP)); + _myCamera.setProjection( + glm::perspective(glm::radians(_fieldOfView.get()), aspectRatio, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP)); // Possible change in aspect ratio { QMutexLocker viewLocker(&_viewMutex); @@ -3723,14 +3712,12 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { bool sandboxIsRunning = SandboxUtils::readStatus(reply->readAll()); - enum HandControllerType { + enum HandControllerType + { Vive, Oculus }; - static const std::map MIN_CONTENT_VERSION = { - { Vive, 1 }, - { Oculus, 27 } - }; + static const std::map MIN_CONTENT_VERSION = { { Vive, 1 }, { Oculus, 27 } }; // Get sandbox content set version auto acDirPath = PathUtils::getAppDataPath() + "../../" + BuildInfo::MODIFIED_ORGANIZATION + "/assignment-client/"; @@ -3740,7 +3727,7 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { QFile contentVersionFile(contentVersionPath); if (contentVersionFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QString line = contentVersionFile.readAll(); - contentVersion = line.toInt(); // returns 0 if conversion fails + contentVersion = line.toInt(); // returns 0 if conversion fails } // Get controller availability @@ -3758,7 +3745,8 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { bool isUsingHMD = _displayPlugin->isHmd(); bool isUsingHMDAndHandControllers = hasHMD && hasHandControllers && isUsingHMD; - qCDebug(interfaceapp) << "HMD:" << hasHMD << ", Hand Controllers: " << hasHandControllers << ", Using HMD: " << isUsingHMDAndHandControllers; + qCDebug(interfaceapp) << "HMD:" << hasHMD << ", Hand Controllers: " << hasHandControllers + << ", Using HMD: " << isUsingHMDAndHandControllers; // when --url in command line, teleport to location const QString HIFI_URL_COMMAND_LINE_KEY = "--url"; @@ -3780,8 +3768,8 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { // If this is a first run we short-circuit the address passed in if (_firstRun.get()) { - DependencyManager::get()->goToEntry(); - sentTo = SENT_TO_ENTRY; + DependencyManager::get()->goToEntry(); + sentTo = SENT_TO_ENTRY; _firstRun.set(false); } else { @@ -3800,22 +3788,21 @@ void Application::handleSandboxStatus(QNetworkReply* reply) { sentTo = SENT_TO_PREVIOUS_LOCATION; } - UserActivityLogger::getInstance().logAction("startup_sent_to", { - { "sent_to", sentTo }, - { "sandbox_is_running", sandboxIsRunning }, - { "has_hmd", hasHMD }, - { "has_hand_controllers", hasHandControllers }, - { "is_using_hmd", isUsingHMD }, - { "is_using_hmd_and_hand_controllers", isUsingHMDAndHandControllers }, - { "content_version", contentVersion } - }); + UserActivityLogger::getInstance().logAction("startup_sent_to", + { { "sent_to", sentTo }, + { "sandbox_is_running", sandboxIsRunning }, + { "has_hmd", hasHMD }, + { "has_hand_controllers", hasHandControllers }, + { "is_using_hmd", isUsingHMD }, + { "is_using_hmd_and_hand_controllers", isUsingHMDAndHandControllers }, + { "content_version", contentVersion } }); _connectionMonitor.init(); } bool Application::importJSONFromURL(const QString& urlString) { // we only load files that terminate in just .json (not .svo.json and not .ava.json) - QUrl jsonURL { urlString }; + QUrl jsonURL{ urlString }; emit svoImportRequested(urlString); return true; @@ -3961,19 +3948,18 @@ bool Application::handleKeyEventForFocusedEntity(QEvent* event) { if (_keyboardFocusedEntity.get() != UNKNOWN_ENTITY_ID) { switch (event->type()) { case QEvent::KeyPress: - case QEvent::KeyRelease: - { - auto eventHandler = getEntities()->getEventHandler(_keyboardFocusedEntity.get()); - if (eventHandler) { - event->setAccepted(false); - QCoreApplication::sendEvent(eventHandler, event); - if (event->isAccepted()) { - _lastAcceptedKeyPress = usecTimestampNow(); - return true; - } + case QEvent::KeyRelease: { + auto eventHandler = getEntities()->getEventHandler(_keyboardFocusedEntity.get()); + if (eventHandler) { + event->setAccepted(false); + QCoreApplication::sendEvent(eventHandler, event); + if (event->isAccepted()) { + _lastAcceptedKeyPress = usecTimestampNow(); + return true; } - break; } + break; + } default: break; } @@ -4009,19 +3995,18 @@ static void dumpEventQueue(QThread* thread) { qDebug() << " " << type; } } -#endif // DEBUG_EVENT_QUEUE +#endif // DEBUG_EVENT_QUEUE -bool Application::notify(QObject * object, QEvent * event) { +bool Application::notify(QObject* object, QEvent* event) { if (thread() == QThread::currentThread()) { PROFILE_RANGE_IF_LONGER(app, "notify", 2) return QApplication::notify(object, event); - } - + } + return QApplication::notify(object, event); } bool Application::event(QEvent* event) { - if (_aboutToQuit) { return false; } @@ -4053,7 +4038,7 @@ bool Application::event(QEvent* event) { dumpEventQueue(QThread::currentThread()); } } -#endif // DEBUG_EVENT_QUEUE +#endif // DEBUG_EVENT_QUEUE _pendingIdleEvent.store(false); @@ -4114,7 +4099,6 @@ bool Application::event(QEvent* event) { } bool Application::eventFilter(QObject* object, QEvent* event) { - if (_aboutToQuit && event->type() != QEvent::DeferredDelete && event->type() != QEvent::Destroy) { return true; } @@ -4161,7 +4145,7 @@ void Application::keyPressEvent(QKeyEvent* event) { _keysPressed.insert(event->key(), *event); } - _controllerScriptingInterface->emitKeyPressEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitKeyPressEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isKeyCaptured(event) || isInterstitialMode()) { return; @@ -4251,9 +4235,10 @@ void Application::keyPressEvent(QKeyEvent* event) { case Qt::Key_G: if (isShifted && isMeta && Menu::getInstance() && Menu::getInstance()->getMenu("Developer")->isVisible()) { static const QString HIFI_FRAMES_FOLDER_VAR = "HIFI_FRAMES_FOLDER"; - static const QString GPU_FRAME_FOLDER = QProcessEnvironment::systemEnvironment().contains(HIFI_FRAMES_FOLDER_VAR) - ? QProcessEnvironment::systemEnvironment().value(HIFI_FRAMES_FOLDER_VAR) - : "hifiFrames"; + static const QString GPU_FRAME_FOLDER = + QProcessEnvironment::systemEnvironment().contains(HIFI_FRAMES_FOLDER_VAR) + ? QProcessEnvironment::systemEnvironment().value(HIFI_FRAMES_FOLDER_VAR) + : "hifiFrames"; static QString GPU_FRAME_TEMPLATE = GPU_FRAME_FOLDER + "/{DATE}_{TIME}"; QString fullPath = FileUtils::computeDocumentPath(FileUtils::replaceDateTimeTokens(GPU_FRAME_TEMPLATE)); if (FileUtils::canCreateFile(fullPath)) { @@ -4313,9 +4298,10 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isMeta) { auto audioClient = DependencyManager::get(); audioClient->setMuted(!audioClient->isMuted()); - QSharedPointer audioScriptingInterface = qSharedPointerDynamicCast(DependencyManager::get()); + QSharedPointer audioScriptingInterface = + qSharedPointerDynamicCast(DependencyManager::get()); if (audioScriptingInterface && audioScriptingInterface->getPTT()) { - audioScriptingInterface->setPushingToTalk(!audioClient->isMuted()); + audioScriptingInterface->setPushingToTalk(!audioClient->isMuted()); } } break; @@ -4336,16 +4322,18 @@ void Application::keyPressEvent(QKeyEvent* event) { if (!isShifted && !isMeta && !isOption && !event->isAutoRepeat()) { AudioInjectorOptions options; options.localOnly = true; - options.positionSet = false; // system sound + options.positionSet = false; // system sound options.stereo = true; Setting::Handle notificationSounds{ MenuOption::NotificationSounds, true }; Setting::Handle notificationSoundSnapshot{ MenuOption::NotificationSoundsSnapshot, true }; if (notificationSounds.get() && notificationSoundSnapshot.get()) { if (_snapshotSoundInjector) { - DependencyManager::get()->setOptionsAndRestart(_snapshotSoundInjector, options); + DependencyManager::get()->setOptionsAndRestart(_snapshotSoundInjector, + options); } else { - _snapshotSoundInjector = DependencyManager::get()->playSound(_snapshotSound, options); + _snapshotSoundInjector = + DependencyManager::get()->playSound(_snapshotSound, options); } } takeSnapshot(true); @@ -4366,7 +4354,7 @@ void Application::keyPressEvent(QKeyEvent* event) { } else { showCursor(Cursor::Icon::DEFAULT); } - } else if (!event->isAutoRepeat()){ + } else if (!event->isAutoRepeat()) { resetSensors(true); } break; @@ -4426,7 +4414,7 @@ void Application::keyReleaseEvent(QKeyEvent* event) { AndroidHelper::instance().requestActivity("Home", false); } #endif - _controllerScriptingInterface->emitKeyReleaseEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitKeyReleaseEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isKeyCaptured(event)) { @@ -4436,12 +4424,11 @@ void Application::keyReleaseEvent(QKeyEvent* event) { if (_keyboardMouseDevice->isActive()) { _keyboardMouseDevice->keyReleaseEvent(event); } - } void Application::focusOutEvent(QFocusEvent* event) { auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); - foreach(auto inputPlugin, inputPlugins) { + foreach (auto inputPlugin, inputPlugins) { if (inputPlugin->isActive()) { inputPlugin->pluginFocusOutEvent(); } @@ -4463,7 +4450,7 @@ void Application::synthesizeKeyReleasEvents() { QHash keysPressed; std::swap(keysPressed, _keysPressed); for (auto& ev : keysPressed) { - QKeyEvent synthesizedEvent { QKeyEvent::KeyRelease, ev.key(), Qt::NoModifier, ev.text() }; + QKeyEvent synthesizedEvent{ QKeyEvent::KeyRelease, ev.key(), Qt::NoModifier, ev.text() }; keyReleaseEvent(&synthesizedEvent); } } @@ -4480,7 +4467,7 @@ void Application::maybeToggleMenuVisible(QMouseEvent* event) const { if (event->pos().y() <= MENU_TOGGLE_AREA) { menuBar->setVisible(true); } - } else { + } else { if (event->pos().y() > MENU_TOGGLE_AREA) { menuBar->setVisible(false); } @@ -4500,7 +4487,7 @@ void Application::mouseMoveEvent(QMouseEvent* event) { // compositor reticle // handleRealMouseMoveEvent() will return true, if we shouldn't process the event further if (!compositor.fakeEventActive() && compositor.handleRealMouseMoveEvent()) { - return; // bail + return; // bail } #if !defined(DISABLE_QML) @@ -4520,17 +4507,14 @@ void Application::mouseMoveEvent(QMouseEvent* event) { buttons |= Qt::LeftButton; } - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), button, - buttons, event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), button, buttons, event->modifiers()); if (compositor.getReticleVisible() || !isHMDMode() || !compositor.getReticleOverDesktop() || getOverlays().getOverlayAtPoint(glm::vec2(transformedPos.x(), transformedPos.y())) != UNKNOWN_ENTITY_ID) { getEntities()->mouseMoveEvent(&mappedEvent); } - _controllerScriptingInterface->emitMouseMoveEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMouseMoveEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4560,11 +4544,12 @@ void Application::mousePressEvent(QMouseEvent* event) { QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); QUuid result = getEntities()->mousePressEvent(&mappedEvent); setKeyboardFocusEntity(getEntities()->wantsKeyboardFocus(result) ? result : UNKNOWN_ENTITY_ID); - _controllerScriptingInterface->emitMousePressEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMousePressEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4597,10 +4582,8 @@ void Application::mouseDoublePressEvent(QMouseEvent* event) { #else QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), event->button(), - event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); getEntities()->mouseDoublePressEvent(&mappedEvent); // if one of our scripts have asked to capture this event, then stop processing it @@ -4612,7 +4595,6 @@ void Application::mouseDoublePressEvent(QMouseEvent* event) { } void Application::mouseReleaseEvent(QMouseEvent* event) { - #if !defined(DISABLE_QML) auto offscreenUi = getOffscreenUI(); auto eventPosition = getApplicationCompositor().getMouseEventPosition(event); @@ -4620,14 +4602,12 @@ void Application::mouseReleaseEvent(QMouseEvent* event) { #else QPointF transformedPos; #endif - QMouseEvent mappedEvent(event->type(), - transformedPos, - event->screenPos(), event->button(), - event->buttons(), event->modifiers()); + QMouseEvent mappedEvent(event->type(), transformedPos, event->screenPos(), event->button(), event->buttons(), + event->modifiers()); getEntities()->mouseReleaseEvent(&mappedEvent); - _controllerScriptingInterface->emitMouseReleaseEvent(&mappedEvent); // send events to any registered scripts + _controllerScriptingInterface->emitMouseReleaseEvent(&mappedEvent); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isMouseCaptured()) { @@ -4646,7 +4626,7 @@ void Application::touchUpdateEvent(QTouchEvent* event) { if (event->type() == QEvent::TouchUpdate) { TouchEvent thisEvent(*event, _lastTouchEvent); - _controllerScriptingInterface->emitTouchUpdateEvent(thisEvent); // send events to any registered scripts + _controllerScriptingInterface->emitTouchUpdateEvent(thisEvent); // send events to any registered scripts _lastTouchEvent = thisEvent; } @@ -4668,10 +4648,10 @@ void Application::touchUpdateEvent(QTouchEvent* event) { void Application::touchBeginEvent(QTouchEvent* event) { _altPressed = false; - TouchEvent thisEvent(*event); // on touch begin, we don't compare to last event - _controllerScriptingInterface->emitTouchBeginEvent(thisEvent); // send events to any registered scripts + TouchEvent thisEvent(*event); // on touch begin, we don't compare to last event + _controllerScriptingInterface->emitTouchBeginEvent(thisEvent); // send events to any registered scripts - _lastTouchEvent = thisEvent; // and we reset our last event to this event before we call our update + _lastTouchEvent = thisEvent; // and we reset our last event to this event before we call our update touchUpdateEvent(event); // if one of our scripts have asked to capture this event, then stop processing it @@ -4688,13 +4668,12 @@ void Application::touchBeginEvent(QTouchEvent* event) { if (_touchscreenVirtualPadDevice && _touchscreenVirtualPadDevice->isActive()) { _touchscreenVirtualPadDevice->touchBeginEvent(event); } - } void Application::touchEndEvent(QTouchEvent* event) { _altPressed = false; TouchEvent thisEvent(*event, _lastTouchEvent); - _controllerScriptingInterface->emitTouchEndEvent(thisEvent); // send events to any registered scripts + _controllerScriptingInterface->emitTouchEndEvent(thisEvent); // send events to any registered scripts _lastTouchEvent = thisEvent; // if one of our scripts have asked to capture this event, then stop processing it @@ -4725,7 +4704,7 @@ void Application::touchGestureEvent(QGestureEvent* event) { void Application::wheelEvent(QWheelEvent* event) const { _altPressed = false; - _controllerScriptingInterface->emitWheelEvent(event); // send events to any registered scripts + _controllerScriptingInterface->emitWheelEvent(event); // send events to any registered scripts // if one of our scripts have asked to capture this event, then stop processing it if (_controllerScriptingInterface->isWheelCaptured() || getLoginDialogPoppedUp()) { @@ -4737,7 +4716,7 @@ void Application::wheelEvent(QWheelEvent* event) const { } } -void Application::dropEvent(QDropEvent *event) { +void Application::dropEvent(QDropEvent* event) { const QMimeData* mimeData = event->mimeData(); for (auto& url : mimeData->urls()) { QString urlString = url.toString(); @@ -4763,8 +4742,8 @@ bool Application::acceptSnapshot(const QString& urlString) { DependencyManager::get()->handleLookupString(snapshotData->getURL().toString()); } } else { - OffscreenUi::asyncWarning("", "No location details were found in the file\n" + - snapshotPath + "\nTry dragging in an authentic Hifi snapshot."); + OffscreenUi::asyncWarning("", "No location details were found in the file\n" + snapshotPath + + "\nTry dragging in an authentic Hifi snapshot."); } return true; } @@ -4777,41 +4756,39 @@ bool Application::acceptSnapshot(const QString& urlString) { #pragma comment(lib, "ntdll.lib") extern "C" { - enum SYSTEM_INFORMATION_CLASS { - SystemBasicInformation = 0, - SystemProcessorPerformanceInformation = 8, - }; +enum SYSTEM_INFORMATION_CLASS +{ + SystemBasicInformation = 0, + SystemProcessorPerformanceInformation = 8, +}; - struct SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { - LARGE_INTEGER IdleTime; - LARGE_INTEGER KernelTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER DpcTime; - LARGE_INTEGER InterruptTime; - ULONG InterruptCount; - }; +struct SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { + LARGE_INTEGER IdleTime; + LARGE_INTEGER KernelTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER DpcTime; + LARGE_INTEGER InterruptTime; + ULONG InterruptCount; +}; - struct SYSTEM_BASIC_INFORMATION { - ULONG Reserved; - ULONG TimerResolution; - ULONG PageSize; - ULONG NumberOfPhysicalPages; - ULONG LowestPhysicalPageNumber; - ULONG HighestPhysicalPageNumber; - ULONG AllocationGranularity; - ULONG_PTR MinimumUserModeAddress; - ULONG_PTR MaximumUserModeAddress; - ULONG_PTR ActiveProcessorsAffinityMask; - CCHAR NumberOfProcessors; - }; - - NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformation( - _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, - _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation, - _In_ ULONG SystemInformationLength, - _Out_opt_ PULONG ReturnLength - ); +struct SYSTEM_BASIC_INFORMATION { + ULONG Reserved; + ULONG TimerResolution; + ULONG PageSize; + ULONG NumberOfPhysicalPages; + ULONG LowestPhysicalPageNumber; + ULONG HighestPhysicalPageNumber; + ULONG AllocationGranularity; + ULONG_PTR MinimumUserModeAddress; + ULONG_PTR MaximumUserModeAddress; + ULONG_PTR ActiveProcessorsAffinityMask; + CCHAR NumberOfProcessors; +}; +NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformation(_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, + _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation, + _In_ ULONG SystemInformationLength, + _Out_opt_ PULONG ReturnLength); } template NTSTATUS NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, T& t) { @@ -4823,7 +4800,6 @@ NTSTATUS NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClas return NtQuerySystemInformation(SystemInformationClass, t.data(), (ULONG)(sizeof(T) * t.size()), nullptr); } - template void updateValueAndDelta(std::pair& pair, T newValue) { auto& value = pair.first; @@ -4835,11 +4811,11 @@ void updateValueAndDelta(std::pair& pair, T newValue) { struct MyCpuInfo { using ValueAndDelta = std::pair; std::string name; - ValueAndDelta kernel { 0, 0 }; - ValueAndDelta user { 0, 0 }; - ValueAndDelta idle { 0, 0 }; - float kernelUsage { 0.0f }; - float userUsage { 0.0f }; + ValueAndDelta kernel{ 0, 0 }; + ValueAndDelta user{ 0, 0 }; + ValueAndDelta idle{ 0, 0 }; + float kernelUsage{ 0.0f }; + float userUsage{ 0.0f }; void update(const SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION& cpuInfo) { updateValueAndDelta(kernel, cpuInfo.KernelTime.QuadPart); @@ -4857,13 +4833,13 @@ struct MyCpuInfo { void updateCpuInformation() { static std::once_flag once; - static SYSTEM_BASIC_INFORMATION systemInfo {}; + static SYSTEM_BASIC_INFORMATION systemInfo{}; static SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION cpuTotals; static std::vector cpuInfos; static std::vector myCpuInfos; static MyCpuInfo myCpuTotals; std::call_once(once, [&] { - NtQuerySystemInformation( SystemBasicInformation, systemInfo); + NtQuerySystemInformation(SystemBasicInformation, systemInfo); cpuInfos.resize(systemInfo.NumberOfProcessors); myCpuInfos.resize(systemInfo.NumberOfProcessors); for (size_t i = 0; i < systemInfo.NumberOfProcessors; ++i) { @@ -4888,20 +4864,14 @@ void updateCpuInformation() { // Update friendly structure auto& myCpuInfo = myCpuInfos[i]; myCpuInfo.update(cpuInfo); - PROFILE_COUNTER(app, myCpuInfo.name.c_str(), { - { "kernel", myCpuInfo.kernelUsage }, - { "user", myCpuInfo.userUsage } - }); + PROFILE_COUNTER(app, myCpuInfo.name.c_str(), { { "kernel", myCpuInfo.kernelUsage }, { "user", myCpuInfo.userUsage } }); } myCpuTotals.update(cpuTotals); - PROFILE_COUNTER(app, myCpuTotals.name.c_str(), { - { "kernel", myCpuTotals.kernelUsage }, - { "user", myCpuTotals.userUsage } - }); + PROFILE_COUNTER(app, myCpuTotals.name.c_str(), + { { "kernel", myCpuTotals.kernelUsage }, { "user", myCpuTotals.userUsage } }); } - static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; @@ -5025,8 +4995,10 @@ void Application::idle() { PROFILE_COUNTER_IF_CHANGED(app, "renderLoopRate", float, getRenderLoopRate()); PROFILE_COUNTER_IF_CHANGED(app, "currentDownloads", uint32_t, ResourceCache::getLoadingRequests().length()); PROFILE_COUNTER_IF_CHANGED(app, "pendingDownloads", uint32_t, ResourceCache::getPendingRequestCount()); - PROFILE_COUNTER_IF_CHANGED(app, "currentProcessing", int, DependencyManager::get()->getStat("Processing").toInt()); - PROFILE_COUNTER_IF_CHANGED(app, "pendingProcessing", int, DependencyManager::get()->getStat("PendingProcessing").toInt()); + PROFILE_COUNTER_IF_CHANGED(app, "currentProcessing", int, + DependencyManager::get()->getStat("Processing").toInt()); + PROFILE_COUNTER_IF_CHANGED(app, "pendingProcessing", int, + DependencyManager::get()->getStat("PendingProcessing").toInt()); auto renderConfig = _graphicsEngine.getRenderEngine()->getConfiguration(); PROFILE_COUNTER_IF_CHANGED(render, "gpuTime", float, (float)_graphicsEngine.getGPUContext()->getFrameTimerGPUAverage()); @@ -5056,7 +5028,7 @@ void Application::idle() { } } #endif - + checkChangeCursor(); #if !defined(DISABLE_QML) @@ -5091,9 +5063,9 @@ void Application::idle() { update(glm::clamp(secondsSinceLastUpdate, 0.0f, BIGGEST_DELTA_TIME_SECS)); } - { // Update keyboard focus highlight + { // Update keyboard focus highlight if (!_keyboardFocusedEntity.get().isInvalidID()) { - const quint64 LOSE_FOCUS_AFTER_ELAPSED_TIME = 30 * USECS_PER_SECOND; // if idle for 30 seconds, drop focus + const quint64 LOSE_FOCUS_AFTER_ELAPSED_TIME = 30 * USECS_PER_SECOND; // if idle for 30 seconds, drop focus quint64 elapsedSinceAcceptedKeyPress = usecTimestampNow() - _lastAcceptedKeyPress; if (elapsedSinceAcceptedKeyPress > LOSE_FOCUS_AFTER_ELAPSED_TIME) { setKeyboardFocusEntity(UNKNOWN_ENTITY_ID); @@ -5123,7 +5095,7 @@ void Application::idle() { PerformanceWarning warn(showWarnings, "Application::idle()... pluginIdle()"); getActiveDisplayPlugin()->idle(); auto inputPlugins = PluginManager::getInstance()->getInputPlugins(); - foreach(auto inputPlugin, inputPlugins) { + foreach (auto inputPlugin, inputPlugins) { if (inputPlugin->isActive()) { inputPlugin->idle(); } @@ -5211,9 +5183,7 @@ void Application::calibrateEyeTracker5Points() { } #endif -bool Application::exportEntities(const QString& filename, - const QVector& entityIDs, - const glm::vec3* givenOffset) { +bool Application::exportEntities(const QString& filename, const QVector& entityIDs, const glm::vec3* givenOffset) { QHash entities; auto nodeList = DependencyManager::get(); @@ -5226,7 +5196,7 @@ bool Application::exportEntities(const QString& filename, glm::vec3 root(TREE_SCALE, TREE_SCALE, TREE_SCALE); bool success = true; entityTree->withReadLock([entityIDs, entityTree, givenOffset, myAvatarID, &root, &entities, &success, &exportTree] { - for (auto entityID : entityIDs) { // Gather entities and properties. + for (auto entityID : entityIDs) { // Gather entities and properties. auto entityItem = entityTree->findEntityByEntityItemID(entityID); if (!entityItem) { qCWarning(interfaceapp) << "Skipping export of" << entityID << "that is not in scene."; @@ -5236,8 +5206,7 @@ bool Application::exportEntities(const QString& filename, if (!givenOffset) { EntityItemID parentID = entityItem->getParentID(); bool parentIsAvatar = (parentID == AVATAR_SELF_ID || parentID == myAvatarID); - if (!parentIsAvatar && (parentID.isInvalidID() || - !entityIDs.contains(parentID) || + if (!parentIsAvatar && (parentID.isInvalidID() || !entityIDs.contains(parentID) || !entityTree->findEntityByEntityItemID(parentID))) { // If parent wasn't selected, we want absolute position, which isn't in properties. auto position = entityItem->getWorldPosition(); @@ -5268,7 +5237,7 @@ bool Application::exportEntities(const QString& filename, properties.setPosition(properties.getPosition() - root); } else if (!entities.contains(parentID)) { entityDatum->globalizeProperties(properties, "Parent %3 of %2 %1 is not selected for export.", -root); - } // else valid parent -- don't offset + } // else valid parent -- don't offset } exportTree->addEntity(entityDatum->getEntityItemID(), properties); } @@ -5289,15 +5258,12 @@ bool Application::exportEntities(const QString& filename, float x, float y, floa AACube boundingCube(minCorner, cubeSize); QVector entities; auto entityTree = getEntities()->getTree(); - entityTree->withReadLock([&] { - entityTree->evalEntitiesInCube(boundingCube, PickFilter(), entities); - }); + entityTree->withReadLock([&] { entityTree->evalEntitiesInCube(boundingCube, PickFilter(), entities); }); return exportEntities(filename, entities, ¢er); } void Application::loadSettings() { - - sessionRunTime.set(0); // Just clean living. We're about to saveSettings, which will update value. + sessionRunTime.set(0); // Just clean living. We're about to saveSettings, which will update value. DependencyManager::get()->loadSettings(); DependencyManager::get()->loadSettings(); @@ -5367,7 +5333,8 @@ void Application::loadSettings() { } } - QSharedPointer audioScriptingInterface = qSharedPointerDynamicCast(DependencyManager::get()); + QSharedPointer audioScriptingInterface = + qSharedPointerDynamicCast(DependencyManager::get()); if (audioScriptingInterface) { audioScriptingInterface->loadData(); } @@ -5381,7 +5348,8 @@ void Application::saveSettings() const { DependencyManager::get()->saveSettings(); DependencyManager::get()->saveSettings(); - QSharedPointer audioScriptingInterface = qSharedPointerDynamicCast(DependencyManager::get()); + QSharedPointer audioScriptingInterface = + qSharedPointerDynamicCast(DependencyManager::get()); if (audioScriptingInterface) { audioScriptingInterface->saveData(); } @@ -5428,7 +5396,6 @@ void Application::init() { } } - qCDebug(interfaceapp) << "Loaded settings"; // fire off an immediate domain-server check in now that settings are loaded @@ -5463,23 +5430,27 @@ void Application::init() { auto entityScriptingInterface = DependencyManager::get(); // connect the _entityCollisionSystem to our EntityTreeRenderer since that's what handles running entity scripts - connect(_entitySimulation.get(), &PhysicalEntitySimulation::entityCollisionWithEntity, - getEntities().data(), &EntityTreeRenderer::entityCollisionWithEntity); + connect(_entitySimulation.get(), &PhysicalEntitySimulation::entityCollisionWithEntity, getEntities().data(), + &EntityTreeRenderer::entityCollisionWithEntity); // connect the _entities (EntityTreeRenderer) to our script engine's EntityScriptingInterface for firing // of events related clicking, hovering over, and entering entities getEntities()->connectSignalsToSlots(entityScriptingInterface.data()); // Make sure any new sounds are loaded as soon as know about them. - connect(tree.get(), &EntityTree::newCollisionSoundURL, this, [this](QUrl newURL, EntityItemID id) { - getEntities()->setCollisionSound(id, DependencyManager::get()->getSound(newURL)); - }, Qt::QueuedConnection); - connect(getMyAvatar().get(), &MyAvatar::newCollisionSoundURL, this, [this](QUrl newURL) { - if (auto avatar = getMyAvatar()) { - auto sound = DependencyManager::get()->getSound(newURL); - avatar->setCollisionSound(sound); - } - }, Qt::QueuedConnection); + connect(tree.get(), &EntityTree::newCollisionSoundURL, this, + [this](QUrl newURL, EntityItemID id) { + getEntities()->setCollisionSound(id, DependencyManager::get()->getSound(newURL)); + }, + Qt::QueuedConnection); + connect(getMyAvatar().get(), &MyAvatar::newCollisionSoundURL, this, + [this](QUrl newURL) { + if (auto avatar = getMyAvatar()) { + auto sound = DependencyManager::get()->getSound(newURL); + avatar->setCollisionSound(sound); + } + }, + Qt::QueuedConnection); _gameWorkload.startup(getEntities()->getWorkloadSpace(), _graphicsEngine.getRenderScene(), _entitySimulation); _entitySimulation->setWorkloadSpace(getEntities()->getWorkloadSpace()); @@ -5550,7 +5521,8 @@ void Application::resumeAfterLoginDialogActionTaken() { } if (!isHMDMode() && getDesktopTabletBecomesToolbarSetting()) { - auto toolbar = DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); + auto toolbar = + DependencyManager::get()->getToolbar("com.highfidelity.interface.toolbar.system"); toolbar->writeProperty("visible", true); } else { getApplicationCompositor().getReticleInterface()->setAllowMouseCapture(true); @@ -5696,8 +5668,8 @@ void Application::updateMyAvatarLookAtPosition() { glm::quat hmdRotation = glm::quat_cast(headPose); lookAtSpot = _myCamera.getPosition() + myAvatar->getWorldOrientation() * (hmdRotation * lookAtPosition); } else { - lookAtSpot = myAvatar->getHead()->getEyePosition() - + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * lookAtPosition); + lookAtSpot = myAvatar->getHead()->getEyePosition() + + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * lookAtPosition); } } else { AvatarSharedPointer lookingAt = myAvatar->getLookAtTargetAvatar().lock(); @@ -5711,14 +5683,14 @@ void Application::updateMyAvatarLookAtPosition() { const float MAXIMUM_FACE_ANGLE = 65.0f * RADIANS_PER_DEGREE; glm::vec3 lookingAtFaceOrientation = lookingAtHead->getFinalOrientationInWorldFrame() * IDENTITY_FORWARD; - glm::vec3 fromLookingAtToMe = glm::normalize(myAvatar->getHead()->getEyePosition() - - lookingAtHead->getEyePosition()); + glm::vec3 fromLookingAtToMe = + glm::normalize(myAvatar->getHead()->getEyePosition() - lookingAtHead->getEyePosition()); float faceAngle = glm::angle(lookingAtFaceOrientation, fromLookingAtToMe); if (faceAngle < MAXIMUM_FACE_ANGLE) { // Randomly look back and forth between look targets - eyeContactTarget target = Menu::getInstance()->isOptionChecked(MenuOption::FixGaze) ? - LEFT_EYE : myAvatar->getEyeContactTarget(); + eyeContactTarget target = + Menu::getInstance()->isOptionChecked(MenuOption::FixGaze) ? LEFT_EYE : myAvatar->getEyeContactTarget(); switch (target) { case LEFT_EYE: lookAtSpot = lookingAtHead->getLeftEyePosition(); @@ -5741,7 +5713,7 @@ void Application::updateMyAvatarLookAtPosition() { lookAtSpot = transformPoint(headPose.getMatrix(), glm::vec3(0.0f, 0.0f, TREE_SCALE)); } else { lookAtSpot = myAvatar->getHead()->getEyePosition() + - (myAvatar->getHead()->getFinalOrientationInWorldFrame() * glm::vec3(0.0f, 0.0f, -TREE_SCALE)); + (myAvatar->getHead()->getFinalOrientationInWorldFrame() * glm::vec3(0.0f, 0.0f, -TREE_SCALE)); } } @@ -5755,9 +5727,9 @@ void Application::updateMyAvatarLookAtPosition() { if (isLookingAtSomeone) { deflection *= GAZE_DEFLECTION_REDUCTION_DURING_EYE_CONTACT; } - lookAtSpot = origin + _myCamera.getOrientation() * glm::quat(glm::radians(glm::vec3( - eyePitch * deflection, eyeYaw * deflection, 0.0f))) * - glm::inverse(_myCamera.getOrientation()) * (lookAtSpot - origin); + lookAtSpot = origin + _myCamera.getOrientation() * + glm::quat(glm::radians(glm::vec3(eyePitch * deflection, eyeYaw * deflection, 0.0f))) * + glm::inverse(_myCamera.getOrientation()) * (lookAtSpot - origin); } } @@ -5793,22 +5765,18 @@ void Application::centerUI() { void Application::cycleCamera() { auto menu = Menu::getInstance(); if (menu->isOptionChecked(MenuOption::FullscreenMirror)) { - menu->setIsOptionChecked(MenuOption::FullscreenMirror, false); menu->setIsOptionChecked(MenuOption::FirstPerson, true); } else if (menu->isOptionChecked(MenuOption::FirstPerson)) { - menu->setIsOptionChecked(MenuOption::FirstPerson, false); menu->setIsOptionChecked(MenuOption::ThirdPerson, true); } else if (menu->isOptionChecked(MenuOption::ThirdPerson)) { - menu->setIsOptionChecked(MenuOption::ThirdPerson, false); menu->setIsOptionChecked(MenuOption::FullscreenMirror, true); - } - cameraMenuChanged(); // handle the menu change + cameraMenuChanged(); // handle the menu change } void Application::cameraModeChanged() { @@ -5850,7 +5818,7 @@ void Application::cameraMenuChanged() { if (!isHMDMode() && _myCamera.getMode() != CAMERA_MODE_MIRROR) { _mirrorYawOffset = 0.0f; _myCamera.setMode(CAMERA_MODE_MIRROR); - getMyAvatar()->reset(false, false, false); // to reset any active MyAvatar::FollowHelpers + getMyAvatar()->reset(false, false, false); // to reset any active MyAvatar::FollowHelpers getMyAvatar()->setBoomLength(MyAvatar::ZOOM_DEFAULT); } } else if (menu->isOptionChecked(MenuOption::FirstPerson)) { @@ -5879,7 +5847,6 @@ void Application::resetPhysicsReadyInformation() { _octreeProcessor.startEntitySequence(); } - void Application::reloadResourceCaches() { resetPhysicsReadyInformation(); @@ -5989,7 +5956,7 @@ void Application::setKeyboardFocusEntity(const QUuid& id) { if (properties.getShowKeyboardFocusHighlight()) { if (auto entity = entities->getEntity(entityId)) { setKeyboardFocusHighlight(entity->getWorldPosition(), entity->getWorldOrientation(), - entity->getScaledDimensions() * FOCUS_HIGHLIGHT_EXPANSION_FACTOR); + entity->getScaledDimensions() * FOCUS_HIGHLIGHT_EXPANSION_FACTOR); return; } } @@ -6053,8 +6020,8 @@ void Application::updateSecondaryCameraViewFrustum() { glm::vec3 mainCameraPositionWorld = getCamera().getPosition(); glm::vec3 mainCameraPositionPortalEntrance = vec3(portalEntranceFromWorld * vec4(mainCameraPositionWorld, 1.0f)); - mainCameraPositionPortalEntrance = vec3(-mainCameraPositionPortalEntrance.x, mainCameraPositionPortalEntrance.y, - -mainCameraPositionPortalEntrance.z); + mainCameraPositionPortalEntrance = + vec3(-mainCameraPositionPortalEntrance.x, mainCameraPositionPortalEntrance.y, -mainCameraPositionPortalEntrance.z); glm::vec3 portalExitCameraPositionWorld = vec3(worldFromPortalExit * vec4(mainCameraPositionPortalEntrance, 1.0f)); secondaryViewFrustum.setPosition(portalExitCameraPositionWorld); @@ -6065,7 +6032,8 @@ void Application::updateSecondaryCameraViewFrustum() { // but the values are the same. glm::vec3 upperRight = halfPortalExitPropertiesDimensions - mainCameraPositionPortalEntrance; glm::vec3 bottomLeft = -halfPortalExitPropertiesDimensions - mainCameraPositionPortalEntrance; - glm::mat4 frustum = glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); + glm::mat4 frustum = + glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); secondaryViewFrustum.setProjection(frustum); } else if (camera->mirrorProjection && !camera->attachedEntityId.isNull()) { auto entityScriptingInterface = DependencyManager::get(); @@ -6085,8 +6053,8 @@ void Application::updateSecondaryCameraViewFrustum() { // get mirror camera position by reflecting main camera position's z coordinate in mirror space glm::vec3 mainCameraPositionWorld = getCamera().getPosition(); glm::vec3 mainCameraPositionMirror = vec3(mirrorFromWorld * vec4(mainCameraPositionWorld, 1.0f)); - glm::vec3 mirrorCameraPositionMirror = vec3(mainCameraPositionMirror.x, mainCameraPositionMirror.y, - -mainCameraPositionMirror.z); + glm::vec3 mirrorCameraPositionMirror = + vec3(mainCameraPositionMirror.x, mainCameraPositionMirror.y, -mainCameraPositionMirror.z); glm::vec3 mirrorCameraPositionWorld = vec3(worldFromMirror * vec4(mirrorCameraPositionMirror, 1.0f)); // set frustum position to be mirrored camera and set orientation to mirror's adjusted rotation @@ -6098,7 +6066,8 @@ void Application::updateSecondaryCameraViewFrustum() { float nearClip = mirrorCameraPositionMirror.z + mirrorPropertiesDimensions.z * 2.0f; glm::vec3 upperRight = halfMirrorPropertiesDimensions - mirrorCameraPositionMirror; glm::vec3 bottomLeft = -halfMirrorPropertiesDimensions - mirrorCameraPositionMirror; - glm::mat4 frustum = glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); + glm::mat4 frustum = + glm::frustum(bottomLeft.x, upperRight.x, bottomLeft.y, upperRight.y, nearClip, camera->farClipPlaneDistance); secondaryViewFrustum.setProjection(frustum); } else { if (!camera->attachedEntityId.isNull()) { @@ -6112,10 +6081,8 @@ void Application::updateSecondaryCameraViewFrustum() { } float aspectRatio = (float)camera->textureWidth / (float)camera->textureHeight; - secondaryViewFrustum.setProjection(camera->vFoV, - aspectRatio, - camera->nearClipPlaneDistance, - camera->farClipPlaneDistance); + secondaryViewFrustum.setProjection(camera->vFoV, aspectRatio, camera->nearClipPlaneDistance, + camera->farClipPlaneDistance); } // Without calculating the bound planes, the secondary camera will use the same culling frustum as the main camera, // which is not what we want here. @@ -6133,7 +6100,6 @@ void Application::update(float deltaTime) { return; } - if (!_physicsEnabled) { if (!domainLoadingInProgress) { PROFILE_ASYNC_BEGIN(app, "Scene Loading", ""); @@ -6188,8 +6154,8 @@ void Application::update(float deltaTime) { Menu* menu = Menu::getInstance(); auto audioClient = DependencyManager::get(); if (menu->isOptionChecked(MenuOption::AutoMuteAudio) && !audioClient->isMuted()) { - if (_lastFaceTrackerUpdate > 0 - && ((usecTimestampNow() - _lastFaceTrackerUpdate) > MUTE_MICROPHONE_AFTER_USECS)) { + if (_lastFaceTrackerUpdate > 0 && + ((usecTimestampNow() - _lastFaceTrackerUpdate) > MUTE_MICROPHONE_AFTER_USECS)) { audioClient->setMuted(true); _lastFaceTrackerUpdate = 0; } @@ -6210,22 +6176,21 @@ void Application::update(float deltaTime) { hmdAvatarAlignmentType = controller::HmdAvatarAlignmentType::Head; } - controller::InputCalibrationData calibrationData = { - myAvatar->getSensorToWorldMatrix(), - createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()), - myAvatar->getHMDSensorMatrix(), - myAvatar->getCenterEyeCalibrationMat(), - myAvatar->getHeadCalibrationMat(), - myAvatar->getSpine2CalibrationMat(), - myAvatar->getHipsCalibrationMat(), - myAvatar->getLeftFootCalibrationMat(), - myAvatar->getRightFootCalibrationMat(), - myAvatar->getRightArmCalibrationMat(), - myAvatar->getLeftArmCalibrationMat(), - myAvatar->getRightHandCalibrationMat(), - myAvatar->getLeftHandCalibrationMat(), - hmdAvatarAlignmentType - }; + controller::InputCalibrationData calibrationData = + { myAvatar->getSensorToWorldMatrix(), + createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()), + myAvatar->getHMDSensorMatrix(), + myAvatar->getCenterEyeCalibrationMat(), + myAvatar->getHeadCalibrationMat(), + myAvatar->getSpine2CalibrationMat(), + myAvatar->getHipsCalibrationMat(), + myAvatar->getLeftFootCalibrationMat(), + myAvatar->getRightFootCalibrationMat(), + myAvatar->getRightArmCalibrationMat(), + myAvatar->getLeftArmCalibrationMat(), + myAvatar->getRightHandCalibrationMat(), + myAvatar->getLeftHandCalibrationMat(), + hmdAvatarAlignmentType }; InputPluginPointer keyboardMousePlugin; for (auto inputPlugin : PluginManager::getInstance()->getInputPlugins()) { @@ -6247,82 +6212,84 @@ void Application::update(float deltaTime) { myAvatar->clearDriveKeys(); if (_myCamera.getMode() != CAMERA_MODE_INDEPENDENT && !isInterstitialMode()) { if (!_controllerScriptingInterface->areActionsCaptured() && _myCamera.getMode() != CAMERA_MODE_MIRROR) { - myAvatar->setDriveKey(MyAvatar::TRANSLATE_Z, -1.0f * userInputMapper->getActionState(controller::Action::TRANSLATE_Z)); + myAvatar->setDriveKey(MyAvatar::TRANSLATE_Z, + -1.0f * userInputMapper->getActionState(controller::Action::TRANSLATE_Z)); myAvatar->setDriveKey(MyAvatar::TRANSLATE_Y, userInputMapper->getActionState(controller::Action::TRANSLATE_Y)); myAvatar->setDriveKey(MyAvatar::TRANSLATE_X, userInputMapper->getActionState(controller::Action::TRANSLATE_X)); if (deltaTime > FLT_EPSILON) { myAvatar->setDriveKey(MyAvatar::PITCH, -1.0f * userInputMapper->getActionState(controller::Action::PITCH)); myAvatar->setDriveKey(MyAvatar::YAW, -1.0f * userInputMapper->getActionState(controller::Action::YAW)); - myAvatar->setDriveKey(MyAvatar::DELTA_PITCH, -1.0f * userInputMapper->getActionState(controller::Action::DELTA_PITCH)); - myAvatar->setDriveKey(MyAvatar::DELTA_YAW, -1.0f * userInputMapper->getActionState(controller::Action::DELTA_YAW)); - myAvatar->setDriveKey(MyAvatar::STEP_YAW, -1.0f * userInputMapper->getActionState(controller::Action::STEP_YAW)); + myAvatar->setDriveKey(MyAvatar::DELTA_PITCH, + -1.0f * userInputMapper->getActionState(controller::Action::DELTA_PITCH)); + myAvatar->setDriveKey(MyAvatar::DELTA_YAW, + -1.0f * userInputMapper->getActionState(controller::Action::DELTA_YAW)); + myAvatar->setDriveKey(MyAvatar::STEP_YAW, + -1.0f * userInputMapper->getActionState(controller::Action::STEP_YAW)); } } myAvatar->setDriveKey(MyAvatar::ZOOM, userInputMapper->getActionState(controller::Action::TRANSLATE_CAMERA_Z)); } myAvatar->setSprintMode((bool)userInputMapper->getActionState(controller::Action::SPRINT)); - static const std::vector avatarControllerActions = { - controller::Action::LEFT_HAND, - controller::Action::RIGHT_HAND, - controller::Action::LEFT_FOOT, - controller::Action::RIGHT_FOOT, - controller::Action::HIPS, - controller::Action::SPINE2, - controller::Action::HEAD, - controller::Action::LEFT_HAND_THUMB1, - controller::Action::LEFT_HAND_THUMB2, - controller::Action::LEFT_HAND_THUMB3, - controller::Action::LEFT_HAND_THUMB4, - controller::Action::LEFT_HAND_INDEX1, - controller::Action::LEFT_HAND_INDEX2, - controller::Action::LEFT_HAND_INDEX3, - controller::Action::LEFT_HAND_INDEX4, - controller::Action::LEFT_HAND_MIDDLE1, - controller::Action::LEFT_HAND_MIDDLE2, - controller::Action::LEFT_HAND_MIDDLE3, - controller::Action::LEFT_HAND_MIDDLE4, - controller::Action::LEFT_HAND_RING1, - controller::Action::LEFT_HAND_RING2, - controller::Action::LEFT_HAND_RING3, - controller::Action::LEFT_HAND_RING4, - controller::Action::LEFT_HAND_PINKY1, - controller::Action::LEFT_HAND_PINKY2, - controller::Action::LEFT_HAND_PINKY3, - controller::Action::LEFT_HAND_PINKY4, - controller::Action::RIGHT_HAND_THUMB1, - controller::Action::RIGHT_HAND_THUMB2, - controller::Action::RIGHT_HAND_THUMB3, - controller::Action::RIGHT_HAND_THUMB4, - controller::Action::RIGHT_HAND_INDEX1, - controller::Action::RIGHT_HAND_INDEX2, - controller::Action::RIGHT_HAND_INDEX3, - controller::Action::RIGHT_HAND_INDEX4, - controller::Action::RIGHT_HAND_MIDDLE1, - controller::Action::RIGHT_HAND_MIDDLE2, - controller::Action::RIGHT_HAND_MIDDLE3, - controller::Action::RIGHT_HAND_MIDDLE4, - controller::Action::RIGHT_HAND_RING1, - controller::Action::RIGHT_HAND_RING2, - controller::Action::RIGHT_HAND_RING3, - controller::Action::RIGHT_HAND_RING4, - controller::Action::RIGHT_HAND_PINKY1, - controller::Action::RIGHT_HAND_PINKY2, - controller::Action::RIGHT_HAND_PINKY3, - controller::Action::RIGHT_HAND_PINKY4, - controller::Action::LEFT_ARM, - controller::Action::RIGHT_ARM, - controller::Action::LEFT_SHOULDER, - controller::Action::RIGHT_SHOULDER, - controller::Action::LEFT_FORE_ARM, - controller::Action::RIGHT_FORE_ARM, - controller::Action::LEFT_LEG, - controller::Action::RIGHT_LEG, - controller::Action::LEFT_UP_LEG, - controller::Action::RIGHT_UP_LEG, - controller::Action::LEFT_TOE_BASE, - controller::Action::RIGHT_TOE_BASE - }; + static const std::vector avatarControllerActions = { controller::Action::LEFT_HAND, + controller::Action::RIGHT_HAND, + controller::Action::LEFT_FOOT, + controller::Action::RIGHT_FOOT, + controller::Action::HIPS, + controller::Action::SPINE2, + controller::Action::HEAD, + controller::Action::LEFT_HAND_THUMB1, + controller::Action::LEFT_HAND_THUMB2, + controller::Action::LEFT_HAND_THUMB3, + controller::Action::LEFT_HAND_THUMB4, + controller::Action::LEFT_HAND_INDEX1, + controller::Action::LEFT_HAND_INDEX2, + controller::Action::LEFT_HAND_INDEX3, + controller::Action::LEFT_HAND_INDEX4, + controller::Action::LEFT_HAND_MIDDLE1, + controller::Action::LEFT_HAND_MIDDLE2, + controller::Action::LEFT_HAND_MIDDLE3, + controller::Action::LEFT_HAND_MIDDLE4, + controller::Action::LEFT_HAND_RING1, + controller::Action::LEFT_HAND_RING2, + controller::Action::LEFT_HAND_RING3, + controller::Action::LEFT_HAND_RING4, + controller::Action::LEFT_HAND_PINKY1, + controller::Action::LEFT_HAND_PINKY2, + controller::Action::LEFT_HAND_PINKY3, + controller::Action::LEFT_HAND_PINKY4, + controller::Action::RIGHT_HAND_THUMB1, + controller::Action::RIGHT_HAND_THUMB2, + controller::Action::RIGHT_HAND_THUMB3, + controller::Action::RIGHT_HAND_THUMB4, + controller::Action::RIGHT_HAND_INDEX1, + controller::Action::RIGHT_HAND_INDEX2, + controller::Action::RIGHT_HAND_INDEX3, + controller::Action::RIGHT_HAND_INDEX4, + controller::Action::RIGHT_HAND_MIDDLE1, + controller::Action::RIGHT_HAND_MIDDLE2, + controller::Action::RIGHT_HAND_MIDDLE3, + controller::Action::RIGHT_HAND_MIDDLE4, + controller::Action::RIGHT_HAND_RING1, + controller::Action::RIGHT_HAND_RING2, + controller::Action::RIGHT_HAND_RING3, + controller::Action::RIGHT_HAND_RING4, + controller::Action::RIGHT_HAND_PINKY1, + controller::Action::RIGHT_HAND_PINKY2, + controller::Action::RIGHT_HAND_PINKY3, + controller::Action::RIGHT_HAND_PINKY4, + controller::Action::LEFT_ARM, + controller::Action::RIGHT_ARM, + controller::Action::LEFT_SHOULDER, + controller::Action::RIGHT_SHOULDER, + controller::Action::LEFT_FORE_ARM, + controller::Action::RIGHT_FORE_ARM, + controller::Action::LEFT_LEG, + controller::Action::RIGHT_LEG, + controller::Action::LEFT_UP_LEG, + controller::Action::RIGHT_UP_LEG, + controller::Action::LEFT_TOE_BASE, + controller::Action::RIGHT_TOE_BASE }; // copy controller poses from userInputMapper to myAvatar. glm::mat4 myAvatarMatrix = createMatFromQuatAndPos(myAvatar->getWorldOrientation(), myAvatar->getWorldPosition()); @@ -6333,21 +6300,25 @@ void Application::update(float deltaTime) { myAvatar->setControllerPoseInSensorFrame(action, pose.transform(avatarToSensorMatrix)); } - static const std::vector trackedObjectStringLiterals = { - QStringLiteral("_TrackedObject00"), QStringLiteral("_TrackedObject01"), QStringLiteral("_TrackedObject02"), QStringLiteral("_TrackedObject03"), - QStringLiteral("_TrackedObject04"), QStringLiteral("_TrackedObject05"), QStringLiteral("_TrackedObject06"), QStringLiteral("_TrackedObject07"), - QStringLiteral("_TrackedObject08"), QStringLiteral("_TrackedObject09"), QStringLiteral("_TrackedObject10"), QStringLiteral("_TrackedObject11"), - QStringLiteral("_TrackedObject12"), QStringLiteral("_TrackedObject13"), QStringLiteral("_TrackedObject14"), QStringLiteral("_TrackedObject15") - }; + static const std::vector trackedObjectStringLiterals = + { QStringLiteral("_TrackedObject00"), QStringLiteral("_TrackedObject01"), QStringLiteral("_TrackedObject02"), + QStringLiteral("_TrackedObject03"), QStringLiteral("_TrackedObject04"), QStringLiteral("_TrackedObject05"), + QStringLiteral("_TrackedObject06"), QStringLiteral("_TrackedObject07"), QStringLiteral("_TrackedObject08"), + QStringLiteral("_TrackedObject09"), QStringLiteral("_TrackedObject10"), QStringLiteral("_TrackedObject11"), + QStringLiteral("_TrackedObject12"), QStringLiteral("_TrackedObject13"), QStringLiteral("_TrackedObject14"), + QStringLiteral("_TrackedObject15") }; // Controlled by the Developer > Avatar > Show Tracked Objects menu. if (_showTrackedObjects) { - static const std::vector trackedObjectActions = { - controller::Action::TRACKED_OBJECT_00, controller::Action::TRACKED_OBJECT_01, controller::Action::TRACKED_OBJECT_02, controller::Action::TRACKED_OBJECT_03, - controller::Action::TRACKED_OBJECT_04, controller::Action::TRACKED_OBJECT_05, controller::Action::TRACKED_OBJECT_06, controller::Action::TRACKED_OBJECT_07, - controller::Action::TRACKED_OBJECT_08, controller::Action::TRACKED_OBJECT_09, controller::Action::TRACKED_OBJECT_10, controller::Action::TRACKED_OBJECT_11, - controller::Action::TRACKED_OBJECT_12, controller::Action::TRACKED_OBJECT_13, controller::Action::TRACKED_OBJECT_14, controller::Action::TRACKED_OBJECT_15 - }; + static const std::vector trackedObjectActions = + { controller::Action::TRACKED_OBJECT_00, controller::Action::TRACKED_OBJECT_01, + controller::Action::TRACKED_OBJECT_02, controller::Action::TRACKED_OBJECT_03, + controller::Action::TRACKED_OBJECT_04, controller::Action::TRACKED_OBJECT_05, + controller::Action::TRACKED_OBJECT_06, controller::Action::TRACKED_OBJECT_07, + controller::Action::TRACKED_OBJECT_08, controller::Action::TRACKED_OBJECT_09, + controller::Action::TRACKED_OBJECT_10, controller::Action::TRACKED_OBJECT_11, + controller::Action::TRACKED_OBJECT_12, controller::Action::TRACKED_OBJECT_13, + controller::Action::TRACKED_OBJECT_14, controller::Action::TRACKED_OBJECT_15 }; int i = 0; glm::vec4 BLUE(0.0f, 0.0f, 1.0f, 1.0f); @@ -6370,8 +6341,8 @@ void Application::update(float deltaTime) { _prevShowTrackedObjects = _showTrackedObjects; } - updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process... - updateDialogs(deltaTime); // update various stats dialogs if present + updateThreads(deltaTime); // If running non-threaded, then give the threads some time to process... + updateDialogs(deltaTime); // update various stats dialogs if present auto grabManager = DependencyManager::get(); grabManager->simulateGrabs(); @@ -6449,18 +6420,15 @@ void Application::update(float deltaTime) { { PROFILE_RANGE(simulation_physics, "PrepareActions"); - _physicsEngine->forEachDynamic([&](EntityDynamicPointer dynamic) { - dynamic->prepareForPhysicsSimulation(); - }); + _physicsEngine->forEachDynamic( + [&](EntityDynamicPointer dynamic) { dynamic->prepareForPhysicsSimulation(); }); } } auto t2 = std::chrono::high_resolution_clock::now(); { PROFILE_RANGE(simulation_physics, "StepPhysics"); PerformanceTimer perfTimer("stepPhysics"); - getEntities()->getTree()->withWriteLock([&] { - _physicsEngine->stepSimulation(); - }); + getEntities()->getTree()->withWriteLock([&] { _physicsEngine->stepSimulation(); }); } auto t3 = std::chrono::high_resolution_clock::now(); { @@ -6499,8 +6467,8 @@ void Application::update(float deltaTime) { } if (PerformanceTimer::isActive() && - Menu::getInstance()->isOptionChecked(MenuOption::DisplayDebugTimingDetails) && - Menu::getInstance()->isOptionChecked(MenuOption::ExpandPhysicsTiming)) { + Menu::getInstance()->isOptionChecked(MenuOption::DisplayDebugTimingDetails) && + Menu::getInstance()->isOptionChecked(MenuOption::ExpandPhysicsTiming)) { _physicsEngine->harvestPerformanceStats(); } // NOTE: the PhysicsEngine stats are written to stdout NOT to Qt log framework @@ -6510,17 +6478,17 @@ void Application::update(float deltaTime) { // NOTE: the getEntities()->update() call below will wait for lock // and will provide non-physical entity motion - getEntities()->update(true); // update the models... + getEntities()->update(true); // update the models... auto t5 = std::chrono::high_resolution_clock::now(); workload::Timings timings(6); - timings[0] = t1 - t0; // prePhysics entities - timings[1] = t2 - t1; // prePhysics avatars - timings[2] = t3 - t2; // stepPhysics - timings[3] = t4 - t3; // postPhysics - timings[4] = t5 - t4; // non-physical kinematics - timings[5] = workload::Timing_ns((int32_t)(NSECS_PER_SECOND * deltaTime)); // game loop duration + timings[0] = t1 - t0; // prePhysics entities + timings[1] = t2 - t1; // prePhysics avatars + timings[2] = t3 - t2; // stepPhysics + timings[3] = t4 - t3; // postPhysics + timings[4] = t5 - t4; // non-physical kinematics + timings[5] = workload::Timing_ns((int32_t)(NSECS_PER_SECOND * deltaTime)); // game loop duration _gameWorkload.updateSimulationTimings(timings); } } @@ -6604,9 +6572,8 @@ void Application::update(float deltaTime) { viewIsDifferentEnough = true; } - // if it's been a while since our last query or the view has significantly changed then send a query, otherwise suppress it - static const std::chrono::seconds MIN_PERIOD_BETWEEN_QUERIES { 3 }; + static const std::chrono::seconds MIN_PERIOD_BETWEEN_QUERIES{ 3 }; auto now = SteadyClock::now(); if (now > _queryExpiry || viewIsDifferentEnough) { if (DependencyManager::get()->shouldRenderEntities()) { @@ -6635,7 +6602,8 @@ void Application::update(float deltaTime) { if (sinceLastNack > TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS && !isInterstitialMode()) { _lastSendDownstreamAudioStats = now; - QMetaObject::invokeMethod(DependencyManager::get().data(), "sendDownstreamAudioStatsPacket", Qt::QueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "sendDownstreamAudioStatsPacket", + Qt::QueuedConnection); } } @@ -6654,7 +6622,6 @@ void Application::update(float deltaTime) { _postUpdateLambdas.clear(); } - updateRenderArgs(deltaTime); { @@ -6662,8 +6629,7 @@ void Application::update(float deltaTime) { AnimDebugDraw::getInstance().update(); } - - { // Game loop is done, mark the end of the frame for the scene transactions and the render loop to take over + { // Game loop is done, mark the end of the frame for the scene transactions and the render loop to take over PerformanceTimer perfTimer("enqueueFrame"); getMain3DScene()->enqueueFrame(); } @@ -6697,16 +6663,16 @@ void Application::updateRenderArgs(float deltaTime) { { QMutexLocker viewLocker(&_viewMutex); // adjust near clip plane to account for sensor scaling. - auto adjustedProjection = glm::perspective(glm::radians(_fieldOfView.get()), - getActiveDisplayPlugin()->getRecommendedAspectRatio(), - DEFAULT_NEAR_CLIP * sensorToWorldScale, - DEFAULT_FAR_CLIP); + auto adjustedProjection = + glm::perspective(glm::radians(_fieldOfView.get()), getActiveDisplayPlugin()->getRecommendedAspectRatio(), + DEFAULT_NEAR_CLIP * sensorToWorldScale, DEFAULT_FAR_CLIP); _viewFrustum.setProjection(adjustedProjection); _viewFrustum.calculate(); } - appRenderArgs._renderArgs = RenderArgs(_graphicsEngine.getGPUContext(), lodManager->getOctreeSizeScale(), - lodManager->getBoundaryLevelAdjust(), lodManager->getLODAngleHalfTan(), RenderArgs::DEFAULT_RENDER_MODE, - RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); + appRenderArgs._renderArgs = + RenderArgs(_graphicsEngine.getGPUContext(), lodManager->getOctreeSizeScale(), + lodManager->getBoundaryLevelAdjust(), lodManager->getLODAngleHalfTan(), + RenderArgs::DEFAULT_RENDER_MODE, RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE); appRenderArgs._renderArgs._scene = getMain3DScene(); { @@ -6795,7 +6761,6 @@ void Application::updateRenderArgs(float deltaTime) { appRenderArgs._renderArgs.setViewFrustum(_displayViewFrustum); } - // HACK // load the view frustum // FIXME: This preDisplayRender call is temporary until we create a separate render::scene for the mirror rendering. @@ -6824,18 +6789,14 @@ void Application::queryAvatars() { } } - int Application::sendNackPackets() { - // iterates through all nodes in NodeList auto nodeList = DependencyManager::get(); int packetsSent = 0; - nodeList->eachNode([&](const SharedNodePointer& node){ - + nodeList->eachNode([&](const SharedNodePointer& node) { if (node->getActiveSocket() && node->getType() == NodeType::EntityServer) { - auto nackPacketList = NLPacketList::create(PacketType::OctreeDataNack); QUuid nodeUUID = node->getUUID(); @@ -6853,7 +6814,8 @@ int Application::sendNackPackets() { return; } // get sequence number stats of node, prune its missing set, and make a copy of the missing set - SequenceNumberStats& sequenceNumberStats = _octreeServerSceneStats[nodeUUID].getIncomingOctreeSequenceNumberStats(); + SequenceNumberStats& sequenceNumberStats = + _octreeServerSceneStats[nodeUUID].getIncomingOctreeSequenceNumberStats(); sequenceNumberStats.pruneMissingSet(); missingSequenceNumbers = sequenceNumberStats.getMissingSet(); }); @@ -6861,7 +6823,7 @@ int Application::sendNackPackets() { _isMissingSequenceNumbers = (missingSequenceNumbers.size() != 0); // construct nack packet(s) for this node - foreach(const OCTREE_PACKET_SEQUENCE& missingNumber, missingSequenceNumbers) { + foreach (const OCTREE_PACKET_SEQUENCE& missingNumber, missingSequenceNumbers) { nackPacketList->writePrimitive(missingNumber); } @@ -6878,9 +6840,8 @@ int Application::sendNackPackets() { } void Application::queryOctree(NodeType_t serverType, PacketType packetType) { - if (!_settingsLoaded) { - return; // bail early if settings are not loaded + return; // bail early if settings are not loaded } const bool isModifiedQuery = !_physicsEnabled; @@ -6910,7 +6871,6 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType) { } _octreeQuery.setReportInitialCompletion(isModifiedQuery); - auto nodeList = DependencyManager::get(); auto node = nodeList->soloNodeOfType(serverType); @@ -6929,7 +6889,6 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType) { } } - bool Application::isHMDMode() const { return getActiveDisplayPlugin()->isHmd(); } @@ -6938,7 +6897,9 @@ float Application::getNumCollisionObjects() const { return _physicsEngine ? _physicsEngine->getNumCollisionObjects() : 0; } -float Application::getTargetRenderFrameRate() const { return getActiveDisplayPlugin()->getTargetFrameRate(); } +float Application::getTargetRenderFrameRate() const { + return getActiveDisplayPlugin()->getTargetFrameRate(); +} QRect Application::getDesirableApplicationGeometry() const { QRect applicationGeometry = getWindow()->geometry(); @@ -6964,7 +6925,7 @@ QRect Application::getDesirableApplicationGeometry() const { } PickRay Application::computePickRay(float x, float y) const { - vec2 pickPoint { x, y }; + vec2 pickPoint{ x, y }; PickRay result; if (isHMDMode()) { getApplicationCompositor().computeHmdPickRay(pickPoint, result.origin, result.direction); @@ -7024,19 +6985,18 @@ void Application::hmdVisibleChanged(bool visible) { } void Application::updateWindowTitle() const { - auto nodeList = DependencyManager::get(); auto accountManager = DependencyManager::get(); auto isInErrorState = nodeList->getDomainHandler().isInErrorState(); - QString buildVersion = " - " - + (BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable ? QString("Version") : QString("Build")) - + " " + applicationVersion(); + QString buildVersion = " - " + + (BuildInfo::BUILD_TYPE == BuildInfo::BuildType::Stable ? QString("Version") : QString("Build")) + + " " + applicationVersion(); QString loginStatus = accountManager->isLoggedIn() ? "" : " (NOT LOGGED IN)"; - QString connectionStatus = isInErrorState ? " (ERROR CONNECTING)" : - nodeList->getDomainHandler().isConnected() ? "" : " (NOT CONNECTED)"; + QString connectionStatus = + isInErrorState ? " (ERROR CONNECTING)" : nodeList->getDomainHandler().isConnected() ? "" : " (NOT CONNECTED)"; QString username = accountManager->getAccountInfo().getUsername(); setCrashAnnotation("username", username.toStdString()); @@ -7055,8 +7015,8 @@ void Application::updateWindowTitle() const { } } - QString title = QString() + (!username.isEmpty() ? username + " @ " : QString()) - + currentPlaceName + connectionStatus + loginStatus + buildVersion; + QString title = QString() + (!username.isEmpty() ? username + " @ " : QString()) + currentPlaceName + connectionStatus + + loginStatus + buildVersion; #ifndef WIN32 // crashes with vs2013/win32 @@ -7066,7 +7026,7 @@ void Application::updateWindowTitle() const { // updateTitleWindow gets called whenever there's a change regarding the domain, so rather // than placing this within domainURLChanged, it's placed here to cover the other potential cases. - DependencyManager::get< MessagesClient >()->sendLocalMessage("Toolbar-DomainChanged", ""); + DependencyManager::get()->sendLocalMessage("Toolbar-DomainChanged", ""); } void Application::clearDomainOctreeDetails(bool clearAll) { @@ -7080,9 +7040,7 @@ void Application::clearDomainOctreeDetails(bool clearAll) { resetPhysicsReadyInformation(); setIsInterstitialMode(true); - _octreeServerSceneStats.withWriteLock([&] { - _octreeServerSceneStats.clear(); - }); + _octreeServerSceneStats.withWriteLock([&] { _octreeServerSceneStats.clear(); }); // reset the model renderer clearAll ? getEntities()->clear() : getEntities()->clearDomainAndNonOwnedEntities(); @@ -7166,7 +7124,7 @@ void Application::nodeActivated(SharedNodePointer node) { _queryExpiry = SteadyClock::now(); _octreeQuery.incrementConnectionID(); - if (!_failedToConnectToEntityServer) { + if (!_failedToConnectToEntityServer) { _entityServerConnectionTimer.stop(); } } @@ -7292,7 +7250,6 @@ void Application::addingEntityWithCertificate(const QString& certificateID, cons } void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointer scriptEngine) { - scriptEngine->setEmitScriptUpdatesFunction([this]() { SharedNodePointer entityServerNode = DependencyManager::get()->soloNodeOfType(NodeType::EntityServer); return !entityServerNode || isPhysicsEnabled(); @@ -7336,13 +7293,13 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe #endif qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, wrapperFromScriptValue); - qScriptRegisterMetaType(scriptEngine.data(), - wrapperToScriptValue, wrapperFromScriptValue); + qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, + wrapperFromScriptValue); scriptEngine->registerGlobalObject("Toolbars", DependencyManager::get().data()); qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, wrapperFromScriptValue); - qScriptRegisterMetaType(scriptEngine.data(), - wrapperToScriptValue, wrapperFromScriptValue); + qScriptRegisterMetaType(scriptEngine.data(), wrapperToScriptValue, + wrapperFromScriptValue); scriptEngine->registerGlobalObject("Tablet", DependencyManager::get().data()); // FIXME remove these deprecated names for the tablet scripting interface scriptEngine->registerGlobalObject("tabletInterface", DependencyManager::get().data()); @@ -7352,17 +7309,20 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("Window", DependencyManager::get().data()); scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter, - LocationScriptingInterface::locationSetter, "Window"); + LocationScriptingInterface::locationSetter, "Window"); // register `location` on the global object. scriptEngine->registerGetterSetter("location", LocationScriptingInterface::locationGetter, LocationScriptingInterface::locationSetter); bool clientScript = scriptEngine->isClientScript(); - scriptEngine->registerFunction("OverlayWindow", clientScript ? QmlWindowClass::constructor : QmlWindowClass::restricted_constructor); + scriptEngine->registerFunction("OverlayWindow", + clientScript ? QmlWindowClass::constructor : QmlWindowClass::restricted_constructor); #if !defined(Q_OS_ANDROID) && !defined(DISABLE_QML) - scriptEngine->registerFunction("OverlayWebWindow", clientScript ? QmlWebWindowClass::constructor : QmlWebWindowClass::restricted_constructor); + scriptEngine->registerFunction("OverlayWebWindow", + clientScript ? QmlWebWindowClass::constructor : QmlWebWindowClass::restricted_constructor); #endif - scriptEngine->registerFunction("QmlFragment", clientScript ? QmlFragmentClass::constructor : QmlFragmentClass::restricted_constructor); + scriptEngine->registerFunction("QmlFragment", + clientScript ? QmlFragmentClass::constructor : QmlFragmentClass::restricted_constructor); scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("DesktopPreviewProvider", DependencyManager::get().data()); @@ -7389,8 +7349,10 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("DialogsManager", _dialogsManagerScriptingInterface); - scriptEngine->registerGlobalObject("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED - scriptEngine->registerGlobalObject("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + scriptEngine->registerGlobalObject("Account", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED + scriptEngine->registerGlobalObject("GlobalServices", + AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED scriptEngine->registerGlobalObject("AccountServices", AccountServicesScriptingInterface::getInstance()); qScriptRegisterMetaType(scriptEngine.data(), DownloadInfoResultToScriptValue, DownloadInfoResultFromScriptValue); @@ -7419,7 +7381,8 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("ScriptDiscoveryService", DependencyManager::get().data()); scriptEngine->registerGlobalObject("Reticle", getApplicationCompositor().getReticleInterface()); - scriptEngine->registerGlobalObject("UserActivityLogger", DependencyManager::get().data()); + scriptEngine->registerGlobalObject("UserActivityLogger", + DependencyManager::get().data()); scriptEngine->registerGlobalObject("Users", DependencyManager::get().data()); scriptEngine->registerGlobalObject("GooglePoly", DependencyManager::get().data()); @@ -7456,7 +7419,6 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe connect(scriptEngine.data(), &ScriptEngine::warningMessage, scriptEngines, &ScriptEngines::onWarningMessage); connect(scriptEngine.data(), &ScriptEngine::infoMessage, scriptEngines, &ScriptEngines::onInfoMessage); connect(scriptEngine.data(), &ScriptEngine::clearDebugWindow, scriptEngines, &ScriptEngines::onClearDebugWindow); - } bool Application::canAcceptURL(const QString& urlString) const { @@ -7480,8 +7442,8 @@ bool Application::acceptURL(const QString& urlString, bool defaultUpload) { if (url.scheme() == URL_SCHEME_HIFI) { // this is a hifi URL - have the AddressManager handle it - QMetaObject::invokeMethod(DependencyManager::get().data(), "handleLookupString", - Qt::AutoConnection, Q_ARG(const QString&, urlString)); + QMetaObject::invokeMethod(DependencyManager::get().data(), "handleLookupString", Qt::AutoConnection, + Q_ARG(const QString&, urlString)); return true; } @@ -7518,13 +7480,13 @@ bool Application::askToSetAvatarUrl(const QString& url) { QString modelName = fstMapping["name"].toString(); QString modelLicense = fstMapping["license"].toString(); - bool agreeToLicense = true; // assume true + bool agreeToLicense = true; // assume true //create set avatar callback - auto setAvatar = [=] (QString url, QString modelName) { - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Set Avatar", - "Would you like to use '" + modelName + "' for your avatar?", - QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + auto setAvatar = [=](QString url, QString modelName) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Set Avatar", "Would you like to use '" + modelName + "' for your avatar?", + QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); bool ok = (QMessageBox::Ok == static_cast(answer.toInt())); @@ -7542,22 +7504,22 @@ bool Application::askToSetAvatarUrl(const QString& url) { const int MAX_CHARACTERS_PER_LINE = 90; modelLicense = simpleWordWrap(modelLicense, MAX_CHARACTERS_PER_LINE); - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Avatar Usage License", - modelLicense + "\nDo you agree to these terms?", - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - QObject::connect(dlg, &ModalDialogListener::response, this, [=, &agreeToLicense] (QVariant answer) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Avatar Usage License", modelLicense + "\nDo you agree to these terms?", + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + QObject::connect(dlg, &ModalDialogListener::response, this, [=, &agreeToLicense](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); agreeToLicense = (static_cast(answer.toInt()) == QMessageBox::Yes); if (agreeToLicense) { switch (modelType) { case FSTReader::HEAD_AND_BODY_MODEL: { - setAvatar(url, modelName); - break; - } - default: - OffscreenUi::asyncWarning("", modelName + "Does not support a head and body as required."); - break; + setAvatar(url, modelName); + break; + } + default: + OffscreenUi::asyncWarning("", modelName + "Does not support a head and body as required."); + break; } } else { qCDebug(interfaceapp) << "Declined to agree to avatar license"; @@ -7572,11 +7534,10 @@ bool Application::askToSetAvatarUrl(const QString& url) { return true; } - bool Application::askToLoadScript(const QString& scriptFilenameOrURL) { QString shortName = scriptFilenameOrURL; - QUrl scriptURL { scriptFilenameOrURL }; + QUrl scriptURL{ scriptFilenameOrURL }; if (scriptURL.host().endsWith(MARKETPLACE_CDN_HOSTNAME)) { int startIndex = shortName.lastIndexOf('/') + 1; @@ -7588,10 +7549,10 @@ bool Application::askToLoadScript(const QString& scriptFilenameOrURL) { DependencyManager::get()->loadScript(scriptFilenameOrURL); #else QString message = "Would you like to run this script:\n" + shortName; - ModalDialogListener* dlg = OffscreenUi::asyncQuestion(getWindow(), "Run Script", message, - QMessageBox::Yes | QMessageBox::No); + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion(getWindow(), "Run Script", message, QMessageBox::Yes | QMessageBox::No); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { const QString& fileName = scriptFilenameOrURL; if (static_cast(answer.toInt()) == QMessageBox::Yes) { qCDebug(interfaceapp) << "Chose to run the script: " << fileName; @@ -7613,7 +7574,6 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { QNetworkReply* reply = networkAccessManager.get(networkRequest); int requestNumber = ++_avatarAttachmentRequest; connect(reply, &QNetworkReply::finished, [this, reply, url, requestNumber]() { - if (requestNumber != _avatarAttachmentRequest) { // this request has been superseded by another more recent request reply->deleteLater(); @@ -7628,7 +7588,6 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { QJsonParseError jsonError; auto doc = QJsonDocument::fromJson(contents, &jsonError); if (jsonError.error == QJsonParseError::NoError) { - auto jsonObject = doc.object(); // retrieve optional name field from JSON @@ -7640,10 +7599,10 @@ bool Application::askToWearAvatarAttachmentUrl(const QString& url) { auto avatarAttachmentConfirmationTitle = tr("Avatar Attachment Confirmation"); auto avatarAttachmentConfirmationMessage = tr("Would you like to wear '%1' on your avatar?").arg(name); - ModalDialogListener* dlg = OffscreenUi::asyncQuestion(avatarAttachmentConfirmationTitle, - avatarAttachmentConfirmationMessage, - QMessageBox::Ok | QMessageBox::Cancel); - QObject::connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion(avatarAttachmentConfirmationTitle, avatarAttachmentConfirmationMessage, + QMessageBox::Ok | QMessageBox::Cancel); + QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); if (static_cast(answer.toInt()) == QMessageBox::Yes) { // add attachment to avatar @@ -7694,18 +7653,23 @@ bool Application::askToReplaceDomainContent(const QString& url) { QString methodDetails; const int MAX_CHARACTERS_PER_LINE = 90; if (DependencyManager::get()->getThisNodeCanReplaceContent()) { - QUrl originURL { url }; + QUrl originURL{ url }; if (originURL.host().endsWith(MARKETPLACE_CDN_HOSTNAME)) { // Create a confirmation dialog when this call is made - static const QString infoText = simpleWordWrap("Your domain's content will be replaced with a new content set. " - "If you want to save what you have now, create a backup before proceeding. For more information about backing up " - "and restoring content, visit the documentation page at: ", MAX_CHARACTERS_PER_LINE) + + static const QString infoText = + simpleWordWrap( + "Your domain's content will be replaced with a new content set. " + "If you want to save what you have now, create a backup before proceeding. For more information about " + "backing up " + "and restoring content, visit the documentation page at: ", + MAX_CHARACTERS_PER_LINE) + "\nhttps://docs.highfidelity.com/create-and-explore/start-working-in-your-sandbox/restoring-sandbox-content"; - ModalDialogListener* dig = OffscreenUi::asyncQuestion("Are you sure you want to replace this domain's content set?", - infoText, QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + ModalDialogListener* dig = + OffscreenUi::asyncQuestion("Are you sure you want to replace this domain's content set?", infoText, + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - QObject::connect(dig, &ModalDialogListener::response, this, [=] (QVariant answer) { + QObject::connect(dig, &ModalDialogListener::response, this, [=](QVariant answer) { QString details; if (static_cast(answer.toInt()) == QMessageBox::Yes) { // Given confirmation, send request to domain server to replace content @@ -7714,33 +7678,26 @@ bool Application::askToReplaceDomainContent(const QString& url) { } else { details = "UserDeclinedToReplaceContent"; } - QJsonObject messageProperties = { - { "status", details }, - { "content_set_url", url } - }; + QJsonObject messageProperties = { { "status", details }, { "content_set_url", url } }; UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); QObject::disconnect(dig, &ModalDialogListener::response, this, nullptr); }); } else { methodDetails = "ContentSetDidNotOriginateFromMarketplace"; - QJsonObject messageProperties = { - { "status", methodDetails }, - { "content_set_url", url } - }; + QJsonObject messageProperties = { { "status", methodDetails }, { "content_set_url", url } }; UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); } } else { - methodDetails = "UserDoesNotHavePermissionToReplaceContent"; - static const QString warningMessage = simpleWordWrap("The domain owner must enable 'Replace Content' " - "permissions for you in this domain's server settings before you can continue.", MAX_CHARACTERS_PER_LINE); - OffscreenUi::asyncWarning("You do not have permissions to replace domain content", warningMessage, - QMessageBox::Ok, QMessageBox::Ok); + methodDetails = "UserDoesNotHavePermissionToReplaceContent"; + static const QString warningMessage = simpleWordWrap( + "The domain owner must enable 'Replace Content' " + "permissions for you in this domain's server settings before you can continue.", + MAX_CHARACTERS_PER_LINE); + OffscreenUi::asyncWarning("You do not have permissions to replace domain content", warningMessage, QMessageBox::Ok, + QMessageBox::Ok); - QJsonObject messageProperties = { - { "status", methodDetails }, - { "content_set_url", url } - }; - UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); + QJsonObject messageProperties = { { "status", methodDetails }, { "content_set_url", url } }; + UserActivityLogger::getInstance().logAction("replace_domain_content", messageProperties); } return true; } @@ -7777,9 +7734,9 @@ void Application::showAssetServerWidget(QString filePath) { if (!DependencyManager::get()->getThisNodeCanWriteAssets() || getLoginDialogPoppedUp()) { return; } - static const QUrl url { "hifi/AssetServer.qml" }; + static const QUrl url{ "hifi/AssetServer.qml" }; - auto startUpload = [=](QQmlContext* context, QObject* newObject){ + auto startUpload = [=](QQmlContext* context, QObject* newObject) { if (!filePath.isEmpty()) { emit uploadRequest(filePath); } @@ -7804,7 +7761,6 @@ void Application::showAssetServerWidget(QString filePath) { } void Application::addAssetToWorldFromURL(QString url) { - QString filename; if (url.contains("filename")) { filename = url.section("filename=", 1, 1); // Filename is in "?filename=" parameter at end of URL. @@ -7816,7 +7772,6 @@ void Application::addAssetToWorldFromURL(QString url) { } else { filename.remove(".zip"); } - } if (!DependencyManager::get()->getThisNodeCanWriteAssets()) { @@ -7828,8 +7783,8 @@ void Application::addAssetToWorldFromURL(QString url) { addAssetToWorldInfo(filename, "Downloading model file " + filename + "."); - auto request = DependencyManager::get()->createResourceRequest( - nullptr, QUrl(url), true, -1, "Application::addAssetToWorldFromURL"); + auto request = DependencyManager::get()->createResourceRequest(nullptr, QUrl(url), true, -1, + "Application::addAssetToWorldFromURL"); connect(request, &ResourceRequest::finished, this, &Application::addAssetToWorldFromURLRequestFinished); request->send(); } @@ -7886,7 +7841,6 @@ void Application::addAssetToWorldFromURLRequestFinished() { request->deleteLater(); } - QString filenameFromPath(QString filePath) { return filePath.right(filePath.length() - filePath.lastIndexOf("/") - 1); } @@ -7931,8 +7885,8 @@ void Application::addAssetToWorldWithNewMapping(QString filePath, QString mappin if (result == GetMappingRequest::NotFound) { addAssetToWorldUpload(filePath, mapping, isZip, isBlocks); } else if (result != GetMappingRequest::NoError) { - QString errorInfo = "Could not map asset name: " - + mapping.left(mapping.length() - QString::number(copy).length() - 1); + QString errorInfo = + "Could not map asset name: " + mapping.left(mapping.length() - QString::number(copy).length() - 1); qWarning(interfaceapp) << "Error downloading model: " + errorInfo; addAssetToWorldError(filenameFromPath(filePath), errorInfo); } else if (copy < MAX_COPY_COUNT - 1) { @@ -7943,8 +7897,8 @@ void Application::addAssetToWorldWithNewMapping(QString filePath, QString mappin mapping = mapping.insert(mapping.lastIndexOf("."), "-" + QString::number(copy)); addAssetToWorldWithNewMapping(filePath, mapping, copy, isZip, isBlocks); } else { - QString errorInfo = "Too many copies of asset name: " - + mapping.left(mapping.length() - QString::number(copy).length() - 1); + QString errorInfo = + "Too many copies of asset name: " + mapping.left(mapping.length() - QString::number(copy).length() - 1); qWarning(interfaceapp) << "Error downloading model: " + errorInfo; addAssetToWorldError(filenameFromPath(filePath), errorInfo); } @@ -7991,7 +7945,7 @@ void Application::addAssetToWorldSetMapping(QString filePath, QString mapping, Q // to prevent files that aren't models or texture files from being loaded into world automatically if ((filePath.toLower().endsWith(OBJ_EXTENSION) || filePath.toLower().endsWith(FBX_EXTENSION)) || ((filePath.toLower().endsWith(JPG_EXTENSION) || filePath.toLower().endsWith(PNG_EXTENSION)) && - ((!isBlocks) && (!isZip)))) { + ((!isBlocks) && (!isZip)))) { addAssetToWorldAddEntity(filePath, mapping); } else { qCDebug(interfaceapp) << "Zipped contents are not supported entity files"; @@ -8017,10 +7971,11 @@ void Application::addAssetToWorldAddEntity(QString filePath, QString mapping) { properties.setShapeType(SHAPE_TYPE_SIMPLE_COMPOUND); } properties.setCollisionless(true); // Temporarily set so that doesn't collide with avatar. - properties.setVisible(false); // Temporarily set so that don't see at large unresized dimensions. + properties.setVisible(false); // Temporarily set so that don't see at large unresized dimensions. bool grabbable = (Menu::getInstance()->isOptionChecked(MenuOption::CreateEntitiesGrabbable)); properties.setUserData(grabbable ? GRABBABLE_USER_DATA : NOT_GRABBABLE_USER_DATA); - glm::vec3 positionOffset = getMyAvatar()->getWorldOrientation() * (getMyAvatar()->getSensorToWorldScale() * glm::vec3(0.0f, 0.0f, -2.0f)); + glm::vec3 positionOffset = + getMyAvatar()->getWorldOrientation() * (getMyAvatar()->getSensorToWorldScale() * glm::vec3(0.0f, 0.0f, -2.0f)); properties.setPosition(getMyAvatar()->getWorldPosition() + positionOffset); properties.setRotation(getMyAvatar()->getWorldOrientation()); properties.setGravity(glm::vec3(0.0f, 0.0f, 0.0f)); @@ -8066,12 +8021,11 @@ void Application::addAssetToWorldCheckModelSize() { const glm::vec3 DEFAULT_DIMENSIONS = glm::vec3(0.1f, 0.1f, 0.1f); if (dimensions != DEFAULT_DIMENSIONS) { - // Scale model so that its maximum is exactly specific size. const float MAXIMUM_DIMENSION = getMyAvatar()->getSensorToWorldScale(); auto previousDimensions = dimensions; - auto scale = std::min(MAXIMUM_DIMENSION / dimensions.x, std::min(MAXIMUM_DIMENSION / dimensions.y, - MAXIMUM_DIMENSION / dimensions.z)); + auto scale = std::min(MAXIMUM_DIMENSION / dimensions.x, + std::min(MAXIMUM_DIMENSION / dimensions.y, MAXIMUM_DIMENSION / dimensions.z)); dimensions *= scale; qInfo(interfaceapp) << "Model" << name << "auto-resized from" << previousDimensions << " to " << dimensions; doResize = true; @@ -8118,7 +8072,6 @@ void Application::addAssetToWorldCheckModelSize() { } } - void Application::addAssetToWorldInfo(QString modelName, QString infoText) { // Displays the most recent info message, subject to being overridden by error messages. @@ -8143,8 +8096,8 @@ void Application::addAssetToWorldInfo(QString modelName, QString infoText) { if (!_addAssetToWorldErrorTimer.isActive()) { if (!_addAssetToWorldMessageBox) { - _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, - "Downloading Model", "", QMessageBox::NoButton, QMessageBox::NoButton); + _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, "Downloading Model", + "", QMessageBox::NoButton, QMessageBox::NoButton); connect(_addAssetToWorldMessageBox, SIGNAL(destroyed()), this, SLOT(onAssetToWorldMessageBoxClosed())); } @@ -8226,8 +8179,8 @@ void Application::addAssetToWorldError(QString modelName, QString errorText) { addAssetToWorldInfoClear(modelName); if (!_addAssetToWorldMessageBox) { - _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, - "Downloading Model", "", QMessageBox::NoButton, QMessageBox::NoButton); + _addAssetToWorldMessageBox = getOffscreenUI()->createMessageBox(OffscreenUi::ICON_INFORMATION, "Downloading Model", "", + QMessageBox::NoButton, QMessageBox::NoButton); connect(_addAssetToWorldMessageBox, SIGNAL(destroyed()), this, SLOT(onAssetToWorldMessageBoxClosed())); } @@ -8259,7 +8212,6 @@ void Application::addAssetToWorldErrorTimeout() { } } - void Application::addAssetToWorldMessageClose() { // Clear messages, e.g., if Interface is being closed or domain changes. @@ -8297,7 +8249,6 @@ void Application::onAssetToWorldMessageBoxClosed() { } } - void Application::handleUnzip(QString zipFile, QStringList unzipFile, bool autoAdd, bool isZip, bool isBlocks) { if (autoAdd) { if (!unzipFile.isEmpty()) { @@ -8320,10 +8271,9 @@ void Application::packageModel() { } void Application::loadDialog() { - ModalDialogListener* dlg = OffscreenUi::getOpenFileNameAsync(_glWidget, tr("Open Script"), - getPreviousScriptLocation(), + ModalDialogListener* dlg = OffscreenUi::getOpenFileNameAsync(_glWidget, tr("Open Script"), getPreviousScriptLocation(), tr("JavaScript Files (*.js)")); - connect(dlg, &ModalDialogListener::response, this, [=] (QVariant answer) { + connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { disconnect(dlg, &ModalDialogListener::response, this, nullptr); const QString& response = answer.toString(); if (!response.isEmpty() && QFile(response).exists()) { @@ -8344,7 +8294,7 @@ void Application::setPreviousScriptLocation(const QString& location) { void Application::loadScriptURLDialog() const { ModalDialogListener* dlg = OffscreenUi::getTextAsync(OffscreenUi::ICON_NONE, "Open and Run Script", "Script URL"); - connect(dlg, &ModalDialogListener::response, this, [=] (QVariant response) { + connect(dlg, &ModalDialogListener::response, this, [=](QVariant response) { disconnect(dlg, &ModalDialogListener::response, this, nullptr); const QString& newScript = response.toString(); if (QUrl(newScript).scheme() == "atp") { @@ -8397,9 +8347,8 @@ void Application::toggleLogDialog() { if (getLoginDialogPoppedUp()) { return; } - if (! _logDialog) { - - bool keepOnTop =_keepLogWindowOnTop.get(); + if (!_logDialog) { + bool keepOnTop = _keepLogWindowOnTop.get(); #ifdef Q_OS_WIN _logDialog = new LogDialog(keepOnTop ? qApp->getWindow() : nullptr, getLogger()); #elif !defined(Q_OS_ANDROID) @@ -8420,21 +8369,21 @@ void Application::toggleLogDialog() { #endif } - void Application::recreateLogWindow(int keepOnTop) { - _keepLogWindowOnTop.set(keepOnTop != 0); - if (_logDialog) { - bool toggle = _logDialog->isVisible(); - _logDialog->close(); - _logDialog = nullptr; +void Application::recreateLogWindow(int keepOnTop) { + _keepLogWindowOnTop.set(keepOnTop != 0); + if (_logDialog) { + bool toggle = _logDialog->isVisible(); + _logDialog->close(); + _logDialog = nullptr; - if (toggle) { - toggleLogDialog(); - } - } - } + if (toggle) { + toggleLogDialog(); + } + } +} void Application::toggleEntityScriptServerLogDialog() { - if (! _entityScriptServerLogDialog) { + if (!_entityScriptServerLogDialog) { _entityScriptServerLogDialog = new EntityScriptServerLogDialog(nullptr); } @@ -8450,11 +8399,13 @@ void Application::loadAddAvatarBookmarkDialog() const { } void Application::loadAvatarBrowser() const { - auto tablet = dynamic_cast(DependencyManager::get()->getTablet("com.highfidelity.interface.tablet.system")); + auto tablet = dynamic_cast( + DependencyManager::get()->getTablet("com.highfidelity.interface.tablet.system")); // construct the url to the marketplace item QString url = NetworkingConstants::METAVERSE_SERVER_URL().toString() + "/marketplace?category=avatars"; - QString MARKETPLACES_INJECT_SCRIPT_PATH = "file:///" + qApp->applicationDirPath() + "/scripts/system/html/js/marketplacesInject.js"; + QString MARKETPLACES_INJECT_SCRIPT_PATH = + "file:///" + qApp->applicationDirPath() + "/scripts/system/html/js/marketplacesInject.js"; tablet->gotoWebScreen(url, MARKETPLACES_INJECT_SCRIPT_PATH); DependencyManager::get()->openTablet(); } @@ -8474,35 +8425,47 @@ bool Application::takeSnapshotOperators(std::queue& snapshotOp } void Application::takeSnapshot(bool notify, bool includeAnimated, float aspectRatio, const QString& filename) { - addSnapshotOperator(std::make_tuple([notify, includeAnimated, aspectRatio, filename](const QImage& snapshot) { - qApp->postLambdaEvent([snapshot, notify, includeAnimated, aspectRatio, filename] { - QString path = DependencyManager::get()->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); + addSnapshotOperator(std::make_tuple( + [notify, includeAnimated, aspectRatio, filename](const QImage& snapshot) { + qApp->postLambdaEvent([snapshot, notify, includeAnimated, aspectRatio, filename] { + QString path = + DependencyManager::get() + ->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); - // If we're not doing an animated snapshot as well... - if (!includeAnimated) { - if (!path.isEmpty()) { - // Tell the dependency manager that the capture of the still snapshot has taken place. - emit DependencyManager::get()->stillSnapshotTaken(path, notify); + // If we're not doing an animated snapshot as well... + if (!includeAnimated) { + if (!path.isEmpty()) { + // Tell the dependency manager that the capture of the still snapshot has taken place. + emit DependencyManager::get()->stillSnapshotTaken(path, notify); + } + } else if (!SnapshotAnimated::isAlreadyTakingSnapshotAnimated()) { + // Get an animated GIF snapshot and save it + SnapshotAnimated::saveSnapshotAnimated(path, aspectRatio, + DependencyManager::get()); } - } else if (!SnapshotAnimated::isAlreadyTakingSnapshotAnimated()) { - // Get an animated GIF snapshot and save it - SnapshotAnimated::saveSnapshotAnimated(path, aspectRatio, DependencyManager::get()); - } - }); - }, aspectRatio, true)); + }); + }, + aspectRatio, true)); } void Application::takeSecondaryCameraSnapshot(const bool& notify, const QString& filename) { - addSnapshotOperator(std::make_tuple([notify, filename](const QImage& snapshot) { - qApp->postLambdaEvent([snapshot, notify, filename] { - QString snapshotPath = DependencyManager::get()->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); + addSnapshotOperator(std::make_tuple( + [notify, filename](const QImage& snapshot) { + qApp->postLambdaEvent([snapshot, notify, filename] { + QString snapshotPath = + DependencyManager::get() + ->saveSnapshot(snapshot, filename, TestScriptingInterface::getInstance()->getTestResultsLocation()); - emit DependencyManager::get()->stillSnapshotTaken(snapshotPath, notify); - }); - }, 0.0f, false)); + emit DependencyManager::get()->stillSnapshotTaken(snapshotPath, notify); + }); + }, + 0.0f, false)); } -void Application::takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition, const bool& cubemapOutputFormat, const bool& notify, const QString& filename) { +void Application::takeSecondaryCamera360Snapshot(const glm::vec3& cameraPosition, + const bool& cubemapOutputFormat, + const bool& notify, + const QString& filename) { postLambdaEvent([notify, filename, cubemapOutputFormat, cameraPosition] { DependencyManager::get()->save360Snapshot(cameraPosition, cubemapOutputFormat, notify, filename); }); @@ -8588,7 +8551,8 @@ void Application::windowMinimizedChanged(bool minimized) { static std::once_flag once; std::call_once(once, [&] { connect(&_minimizedWindowTimer, &QTimer::timeout, this, [] { - QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(static_cast(Idle)), Qt::HighEventPriority); + QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(static_cast(Idle)), + Qt::HighEventPriority); }); }); @@ -8639,7 +8603,7 @@ void Application::initPlugins(const QStringList& arguments) { if (parser.isSet(disableDisplays)) { auto disabledDisplays = parser.value(disableDisplays).split(',', QString::SkipEmptyParts); - qInfo() << "Disabling following display plugins:" << disabledDisplays; + qInfo() << "Disabling following display plugins:" << disabledDisplays; PluginManager::getInstance()->disableDisplays(disabledDisplays); } @@ -8759,7 +8723,6 @@ DisplayPluginPointer Application::getActiveDisplayPlugin() const { return _displayPlugin; } - #if !defined(DISABLE_QML) static const char* EXCLUSION_GROUP_KEY = "exclusionGroup"; @@ -8767,7 +8730,7 @@ static void addDisplayPluginToMenu(const DisplayPluginPointer& displayPlugin, in auto menu = Menu::getInstance(); QString name = displayPlugin->getName(); auto grouping = displayPlugin->getGrouping(); - QString groupingMenu { "" }; + QString groupingMenu{ "" }; Q_ASSERT(!menu->menuItemExists(MenuOption::OutputMenu, name)); // assign the meny grouping based on plugin grouping @@ -8789,10 +8752,9 @@ static void addDisplayPluginToMenu(const DisplayPluginPointer& displayPlugin, in displayPluginGroup->setExclusive(true); } auto parent = menu->getMenu(MenuOption::OutputMenu); - auto action = menu->addActionToQMenuAndActionHash(parent, - name, QKeySequence(Qt::CTRL + (Qt::Key_0 + index)), qApp, - SLOT(updateDisplayMode()), - QAction::NoRole, Menu::UNSPECIFIED_POSITION, groupingMenu); + auto action = menu->addActionToQMenuAndActionHash(parent, name, QKeySequence(Qt::CTRL + (Qt::Key_0 + index)), qApp, + SLOT(updateDisplayMode()), QAction::NoRole, Menu::UNSPECIFIED_POSITION, + groupingMenu); action->setCheckable(true); action->setChecked(active); @@ -8817,7 +8779,7 @@ void Application::updateDisplayMode() { DisplayPluginPointer newDisplayPlugin = displayPlugins.at(0); auto menu = getPrimaryMenu(); if (menu) { - foreach(DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { + foreach (DisplayPluginPointer displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { QString name = displayPlugin->getName(); QAction* action = menu->getActionForOption(name); // Menu might have been removed if the display plugin lost @@ -8907,8 +8869,7 @@ void Application::setDisplayPlugin(DisplayPluginPointer newDisplayPlugin) { RefreshRateManager& refreshRateManager = getRefreshRateManager(); refreshRateManager.setRefreshRateOperator(OpenGLDisplayPlugin::getRefreshRateOperator()); bool isHmd = newDisplayPlugin->isHmd(); - RefreshRateManager::UXMode uxMode = isHmd ? RefreshRateManager::UXMode::VR : - RefreshRateManager::UXMode::DESKTOP; + RefreshRateManager::UXMode uxMode = isHmd ? RefreshRateManager::UXMode::VR : RefreshRateManager::UXMode::DESKTOP; refreshRateManager.setUXMode(uxMode); } @@ -8917,11 +8878,10 @@ void Application::setDisplayPlugin(DisplayPluginPointer newDisplayPlugin) { qCDebug(interfaceapp) << "Entering into" << (isHmd ? "HMD" : "Desktop") << "Mode"; // Only log/emit after a successful change - UserActivityLogger::getInstance().logAction("changed_display_mode", { - { "previous_display_mode", _displayPlugin ? _displayPlugin->getName() : "" }, - { "display_mode", newDisplayPlugin ? newDisplayPlugin->getName() : "" }, - { "hmd", isHmd } - }); + UserActivityLogger::getInstance().logAction("changed_display_mode", + { { "previous_display_mode", _displayPlugin ? _displayPlugin->getName() : "" }, + { "display_mode", newDisplayPlugin ? newDisplayPlugin->getName() : "" }, + { "hmd", isHmd } }); emit activeDisplayPluginChanged(); // reset the avatar, to set head and hand palms back to a reasonable default pose. @@ -8988,7 +8948,7 @@ void Application::setShowBulletConstraintLimits(bool value) { } void Application::createLoginDialog() { - const glm::vec3 LOGIN_DIMENSIONS { 0.89f, 0.5f, 0.01f }; + const glm::vec3 LOGIN_DIMENSIONS{ 0.89f, 0.5f, 0.01f }; const auto OFFSET = glm::vec2(0.7f, -0.1f); auto cameraPosition = _myCamera.getPosition(); auto cameraOrientation = _myCamera.getOrientation(); @@ -9065,7 +9025,8 @@ void Application::updateLoginDialogPosition() { } { - glm::vec3 keyboardLocalOffset = cameraOrientation * glm::vec3(-0.4f * getMyAvatar()->getSensorToWorldScale(), -0.3f, 0.2f); + glm::vec3 keyboardLocalOffset = + cameraOrientation * glm::vec3(-0.4f * getMyAvatar()->getSensorToWorldScale(), -0.3f, 0.2f); glm::quat keyboardOrientation = cameraOrientation * glm::quat(glm::radians(glm::vec3(-30.0f, 180.0f, 0.0f))); EntityItemProperties properties; @@ -9077,7 +9038,7 @@ void Application::updateLoginDialogPosition() { } void Application::createAvatarInputsBar() { - const glm::vec3 LOCAL_POSITION { 0.0, 0.0, -1.0 }; + const glm::vec3 LOCAL_POSITION{ 0.0, 0.0, -1.0 }; // DEFAULT_DPI / tablet scale percentage const float DPI = 31.0f / (75.0f / 100.0f); @@ -9231,7 +9192,6 @@ CompositorHelper& Application::getApplicationCompositor() const { return *DependencyManager::get(); } - // virtual functions required for PluginContainer ui::Menu* Application::getPrimaryMenu() { auto appMenu = _window->menuBar(); @@ -9363,7 +9323,9 @@ void Application::showUrlHandler(const QUrl& url) { return; } - ModalDialogListener* dlg = OffscreenUi::asyncQuestion("Confirm openUrl", "Do you recognize this path or code and want to open or execute it: " + url.toDisplayString()); + ModalDialogListener* dlg = + OffscreenUi::asyncQuestion("Confirm openUrl", "Do you recognize this path or code and want to open or execute it: " + + url.toDisplayString()); QObject::connect(dlg, &ModalDialogListener::response, this, [=](QVariant answer) { QObject::disconnect(dlg, &ModalDialogListener::response, this, nullptr); if (QMessageBox::Yes == static_cast(answer.toInt())) { @@ -9383,11 +9345,8 @@ void Application::beforeEnterBackground() { clearDomainOctreeDetails(); } - - void Application::enterBackground() { - QMetaObject::invokeMethod(DependencyManager::get().data(), - "stop", Qt::BlockingQueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "stop", Qt::BlockingQueuedConnection); // Quest only supports one plugin which can't be deactivated currently #if !defined(ANDROID_APP_QUEST_INTERFACE) if (getActiveDisplayPlugin()->isActive()) { @@ -9397,8 +9356,7 @@ void Application::enterBackground() { } void Application::enterForeground() { - QMetaObject::invokeMethod(DependencyManager::get().data(), - "start", Qt::BlockingQueuedConnection); + QMetaObject::invokeMethod(DependencyManager::get().data(), "start", Qt::BlockingQueuedConnection); // Quest only supports one plugin which can't be deactivated currently #if !defined(ANDROID_APP_QUEST_INTERFACE) if (!getActiveDisplayPlugin() || getActiveDisplayPlugin()->isActive() || !getActiveDisplayPlugin()->activate()) { @@ -9409,11 +9367,9 @@ void Application::enterForeground() { nodeList->setSendDomainServerCheckInEnabled(true); } - -void Application::toggleAwayMode(){ - QKeyEvent event = QKeyEvent (QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); - QCoreApplication::sendEvent (this, &event); +void Application::toggleAwayMode() { + QKeyEvent event = QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); + QCoreApplication::sendEvent(this, &event); } - #endif diff --git a/interface/src/Application.h b/interface/src/Application.h index 6a1b483ea4..94e983290e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -48,7 +48,6 @@ #include #include #include - #include #include "avatar/MyAvatar.h" @@ -148,7 +147,7 @@ public: // Return an HTTP User-Agent string with OS and device information. Q_INVOKABLE QString getUserAgent(); - + void initializePlatform(); void initializeGL(); void initializeDisplayPlugins(); void initializeRenderEngine(); @@ -174,7 +173,6 @@ public: void raise(); void showCursor(const Cursor::Icon& cursor); - void InitializePlatform(); bool isThrottleRendering() const; diff --git a/libraries/platform/CMakeLists.txt b/libraries/platform/CMakeLists.txt index 9caca0635c..d5b617a146 100644 --- a/libraries/platform/CMakeLists.txt +++ b/libraries/platform/CMakeLists.txt @@ -1,3 +1,5 @@ set(TARGET_NAME platform) setup_hifi_library() -link_hifi_libraries(shared) \ No newline at end of file + +link_hifi_libraries(shared) +target_json() \ No newline at end of file diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 492726705b..d1fa0c0d25 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -7,17 +7,87 @@ // #include "WINPlatform.h" +#include +#include +#include using namespace platform; - +using namespace nlohmann; + bool WINInstance::enumerateProcessors() { + + cpu cpu; + + getCpuDetails(cpu); + + cpu.numberOfCores = getNumLogicalCores(); + + _processors.push_back(cpu); + + _memory.totalMb = getTotalSystemRamMb(); + return true; +} + +void WINInstance::getCpuDetails(cpu &cpu) { + int CPUInfo[4] = { -1 }; + unsigned nExIds; + unsigned int i = 0; + char CPUBrandString[16]; + char CPUModelString[16]; + char CPUClockString[16]; + // Get the information associated with each extended ID. + __cpuid(CPUInfo, 0x80000000); + nExIds = CPUInfo[0]; + + for (i = 0x80000000; i <= nExIds; ++i) { + __cpuid(CPUInfo, i); + // Interpret CPU brand string + if (i == 0x80000002) { + memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); + } else if (i == 0x80000003) { + memcpy(CPUModelString, CPUInfo, sizeof(CPUInfo)); + } else if (i == 0x80000004) { + memcpy(CPUClockString, CPUInfo, sizeof(CPUInfo)); + } + } + + cpu.brand = CPUBrandString; + cpu.model = CPUModelString; + cpu.clockSpeed = CPUClockString; +} + +unsigned int WINInstance::getNumLogicalCores() { + return std::thread::hardware_concurrency(); +} + +int WINInstance::getTotalSystemRamMb() { + MEMORYSTATUSEX statex; + statex.dwLength = sizeof(statex); + GlobalMemoryStatusEx(&statex); + return statex.ullTotalPhys / 1024 / 1024; } std::string WINInstance::getProcessor(int index) { + + std::string result; + if (index >= _processors.size()) + return result; - return "Fake processor"; + json j; + to_Json(j, _processors.at(index)); + + //serialize this + return j.dump(); +} + +void WINInstance::to_Json(json& result, const cpu& cpu) { + + result["cpuBrand"] = cpu.brand; + result["cpuModel"] = cpu.model; + result["cpuClockSpeed"] = cpu.clockSpeed; + result["cpuNumberOfCores"] = cpu.numberOfCores; } diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 8380b5864a..9fbdcd6da4 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -8,14 +8,23 @@ #pragma once #include "platform.h" +#include namespace platform { + using namespace nlohmann; + class WINInstance : public Instance { - - public: - bool enumerateProcessors(); - std::string getProcessor(int index); - }; + + public: + bool enumerateProcessors(); + std::string getProcessor(int index); + + private: + unsigned int getNumLogicalCores(); + void getCpuDetails(cpu& cpu); + int getTotalSystemRamMb(); + void to_Json(nlohmann::json& result, const cpu& cpu); +}; } // namespace platform \ No newline at end of file diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index a04ced06d8..c581387909 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -36,4 +36,12 @@ std::string platform::getProcessor(int index) { bool platform::enumerateProcessors() { return _instance->enumerateProcessors(); +} + +int platform::getTotalSystemRamMb() { + return _instance->getTotalSystemRamMb(); +} + +int platform::getProcessorCount() { + return _instance->getProcessorCount(); } \ No newline at end of file diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 6a474989a4..2d1c29a187 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -6,28 +6,42 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - #pragma once #include #include namespace platform { - - class Instance { - - public: - std::string virtual getProcessor(int index) = 0; - bool virtual enumerateProcessors() = 0; - private: - - std::vector _processors; - }; +struct cpu { + std::string brand; + std::string model; + int numberOfCores; + std::string clockSpeed; +}; - - static Instance *_instance; +struct memory { + int totalMb; +}; - void create(); - std::string getProcessor(int index); - bool enumerateProcessors(); -} \ No newline at end of file +class Instance { +public: + std::string virtual getProcessor(int index) = 0; + bool virtual enumerateProcessors() = 0; + int virtual getTotalSystemRamMb() = 0; + int getProcessorCount() {return _processors.size(); } + +protected: + std::vector _processors; + struct memory _memory; +}; + +static Instance* _instance; + +//Platform level functions +void create(); +std::string getProcessor(int index); +int getProcessorCount(); +bool enumerateProcessors(); +int getTotalSystemRamMb(); + +} // namespace platform \ No newline at end of file From 7183d108790f68edea01fe7af51e212a140775a2 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Mon, 6 May 2019 10:26:16 +1200 Subject: [PATCH 09/50] Desktop JSDoc --- .../scripting/DesktopScriptingInterface.cpp | 7 +++ .../src/scripting/DesktopScriptingInterface.h | 51 +++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/interface/src/scripting/DesktopScriptingInterface.cpp b/interface/src/scripting/DesktopScriptingInterface.cpp index bda06cda48..f6c089b17c 100644 --- a/interface/src/scripting/DesktopScriptingInterface.cpp +++ b/interface/src/scripting/DesktopScriptingInterface.cpp @@ -31,6 +31,13 @@ int DesktopScriptingInterface::getHeight() { return size.height(); } +/**jsdoc + * The presentation mode specifies how an {@link InteractiveWindow} is displayed. + * @typedef {object} InteractiveWindow.PresentationMode + * @property {number} VIRTUAL - The window is displayed inside Interface: in the desktop window in desktop mode or on the HUD + * surface in HMD mode. + * @property {number} NATIVE - The window is displayed separately from the Interface window, as its own separate window. + */ QVariantMap DesktopScriptingInterface::getPresentationMode() { static QVariantMap presentationModes { { "VIRTUAL", Virtual }, diff --git a/interface/src/scripting/DesktopScriptingInterface.h b/interface/src/scripting/DesktopScriptingInterface.h index c8e251eb3e..2711447b45 100644 --- a/interface/src/scripting/DesktopScriptingInterface.h +++ b/interface/src/scripting/DesktopScriptingInterface.h @@ -20,16 +20,25 @@ #include "InteractiveWindow.h" /**jsdoc + * The Desktop API provides the dimensions of the computer screen, sets the opacity of the HUD surface, and + * enables QML and HTML windows to be shown inside or outside of Interface. + * * @namespace Desktop * * @hifi-interface * @hifi-client-entity * @hifi-avatar * - * @property {number} width - * @property {number} height - * @property {number} ALWAYS_ON_TOP - InteractiveWindow flag for always showing a window on top - * @property {number} CLOSE_BUTTON_HIDES - InteractiveWindow flag for hiding the window instead of closing on window close by user + * @property {number} width - The width of the computer screen including task bar and system menu, in pixels. + * Read-only. + * @property {number} height - The height of the computer screen including task bar and system menu, in pixels. + * Read-only. + * @property {InteractiveWindow.Flags} ALWAYS_ON_TOP - A flag value that makes an {@link InteractiveWindow} always display on + * top. Read-only. + * @property {InteractiveWindow.Flags} CLOSE_BUTTON_HIDES - A flag value that makes an {@link InteractiveWindow} hide instead + * of closing when the user clicks the "close" button. Read-only. + * @property {InteractiveWindow.PresentationMode} PresentationMode - The different display options for an + * {@link InteractiveWindow}: display inside Interface or in a separate desktop window. Read-only. */ class DesktopScriptingInterface : public QObject, public Dependency { Q_OBJECT @@ -41,9 +50,43 @@ class DesktopScriptingInterface : public QObject, public Dependency { Q_PROPERTY(int CLOSE_BUTTON_HIDES READ flagCloseButtonHides CONSTANT FINAL) public: + /**jsdoc + * Sets the opacity of the HUD surface. + * @function Desktop.setHUDAlpha + * @param {number} alpha - The opacity, 0.0 – 1.0. + */ Q_INVOKABLE void setHUDAlpha(float alpha); + + /**jsdoc + * Opens a QML window within Interface: in the Interface window in desktop mode or on the HUD surface in HMD mode. If a + * window of the specified name already exists, it is shown, otherwise a new window is created from the QML. + * @function Desktop.show + * @param {string} url - The QML file that specifies the window content + * @param {string} name - A unique name for the window. + * @example Open the general settings dialog. + * Desktop.show("hifi/dialogs/GeneralPreferencesDialog.qml", "GeneralPreferencesDialog"); + */ Q_INVOKABLE void show(const QString& path, const QString& title); + /**jsdoc + * Creates a new window that can be displayed either within Interface or as a separate desktop window. + * @function Desktop.createWindow + * @param {string} url - The QML file that specifies the window content. The QML file can use a WebView + * control (defined by "WebView.qml" included in the Interface install) to embed an HTML Web page (complete with + * EventBridge object). + * @param {InteractiveWindow.Properties} [properties] - Initial window properties. + * @returns {InteractiveWindow} A new window object. + * @example Open a dialog in its own window separate from Interface. + * var nativeWindow = Desktop.createWindow(Script.resourcesPath() + 'qml/OverlayWindowTest.qml', { + * title: "Native Window", + * presentationMode: Desktop.PresentationMode.NATIVE, + * size: { x: 500, y: 400 } + * }); + * + * Script.scriptEnding.connect(function () { + * nativeWindow.close(); + * }); + */ Q_INVOKABLE InteractiveWindowPointer createWindow(const QString& sourceUrl, const QVariantMap& properties = QVariantMap()); int getWidth(); From 2d5bf4f9407bba5236776e1f3a781e7c43bd13a1 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Mon, 6 May 2019 10:27:24 +1200 Subject: [PATCH 10/50] InteractiveWindow JSDoc --- libraries/ui/src/InteractiveWindow.cpp | 14 +++++ libraries/ui/src/InteractiveWindow.h | 71 +++++++++++++++++++++----- 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/libraries/ui/src/InteractiveWindow.cpp b/libraries/ui/src/InteractiveWindow.cpp index 5f7999f826..45a996b111 100644 --- a/libraries/ui/src/InteractiveWindow.cpp +++ b/libraries/ui/src/InteractiveWindow.cpp @@ -57,6 +57,20 @@ void interactiveWindowPointerFromScriptValue(const QScriptValue& object, Interac } } +/**jsdoc + * A set of properties used when creating an InteractiveWindow. + * @typedef {object} InteractiveWindow.Properties + * @property {string} [title="InteractiveWindow] - The title of the window. + * @property {Vec2} [position] - The initial position of the window, in pixels. + * @property {Vec2} [size] - The initial size of the window, in pixels + * @property {boolean} [visible=true] - true to make the window visible when created, false to make + * it invisible. + * @property {InteractiveWindow.PresentationMode} [presentationMode=Desktop.PresentationMode.VIRTUAL] - + * Desktop.PresentationMode.VIRTUAL to display the window inside Interface, .NATIVE to display it + * as its own separate window. + * @property {InteractiveWindow.Flags} [flags=0] - Window behavior flags, set at window creation. Possible flag values are + * provided as {@link Desktop|Desktop.ALWAYS_ON_TOP} and {@link Desktop|Desktop.CLOSE_BUTTON_HIDES}. + */ InteractiveWindow::InteractiveWindow(const QString& sourceUrl, const QVariantMap& properties) { auto offscreenUi = DependencyManager::get(); diff --git a/libraries/ui/src/InteractiveWindow.h b/libraries/ui/src/InteractiveWindow.h index 22a3df7530..06712965e1 100644 --- a/libraries/ui/src/InteractiveWindow.h +++ b/libraries/ui/src/InteractiveWindow.h @@ -25,6 +25,21 @@ namespace InteractiveWindowEnums { Q_NAMESPACE + /**jsdoc + * A set of flags controlling InteractiveWindow behavior. The value is constructed by using the + * | (bitwise OR) operator on the individual flag values.
+ * + * + * + * + * + * + * + * + *
Flag NameValueDescription
ALWAYS_ON_TOP1The window always displays on top.
CLOSE_BUTTON_HIDES2The window hides instead of closing when the user clicks + * the "close" button.
+ * @typedef {number} InteractiveWindow.Flags + */ enum InteractiveWindowFlags : uint8_t { AlwaysOnTop = 1 << 0, CloseButtonHides = 1 << 1 @@ -41,18 +56,25 @@ namespace InteractiveWindowEnums { using namespace InteractiveWindowEnums; /**jsdoc + * An InteractiveWindow can display either inside Interface or in its own window separate from the Interface + * window. The window content is defined by a QML file, which can optionally include a WebView control that embeds + * an HTML Web page. (The WebView control is defined by a "WebView.qml" file included in the Interface install.) + * + *

Create using {@link Desktop.createWindow}.

+ * * @class InteractiveWindow * * @hifi-interface * @hifi-client-entity * @hifi-avatar * - * @property {string} title - * @property {Vec2} position - * @property {Vec2} size - * @property {boolean} visible - * @property {Desktop.PresentationMode} presentationMode - * + * @property {string} title - The title of the window. + * @property {Vec2} position - The position of the window, in pixels. + * @property {Vec2} size - The size of the window, in pixels. + * @property {boolean} visible - true if the window is visible, false if it isn't. + * @property {InteractiveWindow.PresentationMode} presentationMode - The presentation mode of the window: + * Desktop.PresentationMode.VIRTUAL to display the window inside Interface, .NATIVE to display it + * as its own separate window. */ class InteractiveWindow : public QObject { Q_OBJECT @@ -90,36 +112,49 @@ private: public slots: /**jsdoc + * Sends a message to the QML page. To receive the message, the QML page must implement a function: + *
function fromScript(message) {
+     *   ...
+     * }
* @function InteractiveWindow.sendToQml - * @param {object} message + * @param {string|object} message - The message to send to the QML page. */ // Scripts can use this to send a message to the QML object void sendToQml(const QVariant& message); /**jsdoc + * Sends a message to an embedded HTML Web page. To receive the message, the HTML page's script must connect to the + * EventBridge that is automatically provided to the script: + *
EventBridge.scriptEventReceived.connect(function(message) {
+     *     ...
+     * });
* @function InteractiveWindow.emitScriptEvent - * @param {object} message + * @param {string|object} message - The message to send to the embedded HTML Web page. */ // QmlWindow content may include WebView requiring EventBridge. void emitScriptEvent(const QVariant& scriptMessage); /**jsdoc * @function InteractiveWindow.emitWebEvent - * @param {object} message + * @param {object|string} message - The message. + * @deprecated This function is deprecated and will be removed from the API. */ void emitWebEvent(const QVariant& webMessage); /**jsdoc + * Closes the window. It can then no longer be used. * @function InteractiveWindow.close */ Q_INVOKABLE void close(); /**jsdoc + * Makes the window visible and raises it to the top. * @function InteractiveWindow.show */ Q_INVOKABLE void show(); /**jsdoc + * Raises the window to the top. * @function InteractiveWindow.raise */ Q_INVOKABLE void raise(); @@ -127,44 +162,52 @@ public slots: signals: /**jsdoc + * Triggered when the window is made visible or invisible, or is closed. * @function InteractiveWindow.visibleChanged * @returns {Signal} */ void visibleChanged(); /**jsdoc + * Triggered when the window's position changes. * @function InteractiveWindow.positionChanged * @returns {Signal} */ void positionChanged(); /**jsdoc + * Triggered when the window's' size changes. * @function InteractiveWindow.sizeChanged * @returns {Signal} */ void sizeChanged(); /**jsdoc + * Triggered when the window's presentation mode changes. * @function InteractiveWindow.presentationModeChanged * @returns {Signal} */ void presentationModeChanged(); /**jsdoc + * Triggered when window's title changes. * @function InteractiveWindow.titleChanged * @returns {Signal} */ void titleChanged(); /**jsdoc + * Triggered when the window is closed. * @function InteractiveWindow.closed * @returns {Signal} */ void closed(); /**jsdoc + * Triggered when a message from the QML page is received. The QML page can send a message (string or object) by calling: + *
sendToScript(message);
* @function InteractiveWindow.fromQml - * @param {object} message + * @param {string|object} message - The message received. * @returns {Signal} */ // Scripts can connect to this signal to receive messages from the QML object @@ -172,15 +215,18 @@ signals: /**jsdoc * @function InteractiveWindow.scriptEventReceived - * @param {object} message + * @param {object} message - The message. * @returns {Signal} + * @deprecated This signal is deprecated and will be removed from the API. */ // InteractiveWindow content may include WebView requiring EventBridge. void scriptEventReceived(const QVariant& message); /**jsdoc + * Trigged when a message from an embedded HTML Web page is received. The HTML Web page can send a message by calling: + *
EventBridge.emitWebEvent(message);
* @function InteractiveWindow.webEventReceived - * @param {object} message + * @param {string|object} message - The message received. * @returns {Signal} */ void webEventReceived(const QVariant& message); @@ -190,6 +236,7 @@ protected slots: * @function InteractiveWindow.qmlToScript * @param {object} message * @returns {Signal} + * @deprecated This signal is deprecated and will be removed from the API. */ void qmlToScript(const QVariant& message); From dfa5d2ddf1a9e9b3b610f2b17f48e54120bad935 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Mon, 6 May 2019 11:23:30 +1200 Subject: [PATCH 11/50] InteractiveWindow QML messaging example --- libraries/ui/src/InteractiveWindow.h | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/libraries/ui/src/InteractiveWindow.h b/libraries/ui/src/InteractiveWindow.h index 06712965e1..aee185fd4a 100644 --- a/libraries/ui/src/InteractiveWindow.h +++ b/libraries/ui/src/InteractiveWindow.h @@ -118,6 +118,44 @@ public slots: * }
* @function InteractiveWindow.sendToQml * @param {string|object} message - The message to send to the QML page. + * @example Send and receive messages with a QML window. + * // JavaScript file. + * + * var qmlWindow = Desktop.createWindow(Script.resolvePath("QMLWindow.qml"), { + * title: "QML Window", + * size: { x: 400, y: 300 } + * }); + * + * qmlWindow.fromQml.connect(function (message) { + * print("Message received: " + message); + * }); + * + * Script.setTimeout(function () { + * qmlWindow.sendToQml("Hello world!"); + * }, 2000); + * + * Script.scriptEnding.connect(function () { + * qmlWindow.close(); + * }); + * @example + * // QML file, "QMLWindow.qml". + * + * import QtQuick 2.5 + * import QtQuick.Controls 1.4 + * + * Rectangle { + * + * function fromScript(message) { + * text.text = message; + * sendToScript("Hello back!"); + * } + * + * Label { + * id: text + * anchors.centerIn: parent + * text: "..." + * } + * } */ // Scripts can use this to send a message to the QML object void sendToQml(const QVariant& message); From 8273e5b666def4389ce75a52a5de857ac693a988 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Mon, 6 May 2019 12:27:46 -0700 Subject: [PATCH 12/50] fixing stuff based on comments and feedback from Sam. willc reate template for some of the getters since its the same old --- interface/src/Application.cpp | 4 +- libraries/platform/src/WINPlatform.cpp | 42 +++++++------------- libraries/platform/src/WINPlatform.h | 6 +-- libraries/platform/src/platform.cpp | 55 +++++++++++++++++++++++--- libraries/platform/src/platform.h | 41 +++++++++---------- 5 files changed, 86 insertions(+), 62 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b5970fad49..6e3711d60a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2466,8 +2466,8 @@ void Application::initializePlatform() { //run the enumeration if (platform::enumerateProcessors()) { - for (int i = 0; i < platform::getProcessorCount(); i++) { - std::string myPlat = platform::getProcessor(0); + for (int i = 0; i < platform::getNumProcessor(); i++) { + platform::getProcessor(i); } } } diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index d1fa0c0d25..c335e3745e 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -16,20 +16,24 @@ using namespace nlohmann; bool WINInstance::enumerateProcessors() { - cpu cpu; + + json cpu; getCpuDetails(cpu); - cpu.numberOfCores = getNumLogicalCores(); + cpu["numCores"] = getNumLogicalCores(); _processors.push_back(cpu); - _memory.totalMb = getTotalSystemRamMb(); + json mem; + mem["totalRam"] = getTotalSystemRam(); + + _memory.push_back(mem); return true; } -void WINInstance::getCpuDetails(cpu &cpu) { +void WINInstance::getCpuDetails(json &cpu) { int CPUInfo[4] = { -1 }; unsigned nExIds; unsigned int i = 0; @@ -53,41 +57,23 @@ void WINInstance::getCpuDetails(cpu &cpu) { } } - cpu.brand = CPUBrandString; - cpu.model = CPUModelString; - cpu.clockSpeed = CPUClockString; + cpu["brand"] = CPUBrandString; + cpu["model"] = CPUModelString; + cpu["clockSpeed"] = CPUClockString; } unsigned int WINInstance::getNumLogicalCores() { return std::thread::hardware_concurrency(); } -int WINInstance::getTotalSystemRamMb() { +int WINInstance::getTotalSystemRam() { MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); return statex.ullTotalPhys / 1024 / 1024; } -std::string WINInstance::getProcessor(int index) { - - std::string result; - if (index >= _processors.size()) - return result; - - json j; - to_Json(j, _processors.at(index)); - - //serialize this - return j.dump(); -} - -void WINInstance::to_Json(json& result, const cpu& cpu) { - - result["cpuBrand"] = cpu.brand; - result["cpuModel"] = cpu.model; - result["cpuClockSpeed"] = cpu.clockSpeed; - result["cpuNumberOfCores"] = cpu.numberOfCores; -} + + diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 9fbdcd6da4..f03fb2c95a 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -18,13 +18,11 @@ namespace platform { public: bool enumerateProcessors(); - std::string getProcessor(int index); private: unsigned int getNumLogicalCores(); - void getCpuDetails(cpu& cpu); - int getTotalSystemRamMb(); - void to_Json(nlohmann::json& result, const cpu& cpu); + void getCpuDetails(nlohmann::json& cpu); + int getTotalSystemRam(); }; } // namespace platform \ No newline at end of file diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index c581387909..5ab2e7fbc2 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -6,7 +6,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // + #include "platform.h" + #include #ifdef Q_OS_WIN @@ -21,6 +23,9 @@ #endif using namespace platform; +using namespace nlohmann; + +Instance* _instance; void platform::create() { @@ -30,18 +35,56 @@ void platform::create() { #endif } -std::string platform::getProcessor(int index) { - return _instance->getProcessor(index); +json Instance::getProcessor(int index) { + assert(index < _processor.size()); + + json result; + if (index >= _processors.size()) + return result; + + return _processors.at(index); } + +//These are ripe for template.. will work on that next +json Instance::getSystemRam(int index) { + + assert(index < _memory.size()); + + json result; + if(index>= _memory.size()) + return result; + + return _memory.at(index); +} + +json Instance::getGPU(int index) { + assert(index < _gpu.size()); + + json result; + if (index >= _gpu.size()) + return result; + + return _gpu.at(index); +} + + bool platform::enumerateProcessors() { return _instance->enumerateProcessors(); } -int platform::getTotalSystemRamMb() { - return _instance->getTotalSystemRamMb(); +json platform::getProcessor(int index) { + return _instance->getProcessor(index); } -int platform::getProcessorCount() { - return _instance->getProcessorCount(); +json platform::getSystemRam(int index) { + return _instance->getSystemRam(index); +} + +int platform::getNumMemory() { + return _instance->getNumMemory(); +} + +int platform::getNumProcessor() { + return _instance->getNumProcessor(); } \ No newline at end of file diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 2d1c29a187..3dfb2f2b14 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -9,39 +9,36 @@ #pragma once #include #include - +#include namespace platform { -struct cpu { - std::string brand; - std::string model; - int numberOfCores; - std::string clockSpeed; -}; - -struct memory { - int totalMb; -}; - class Instance { public: - std::string virtual getProcessor(int index) = 0; bool virtual enumerateProcessors() = 0; - int virtual getTotalSystemRamMb() = 0; - int getProcessorCount() {return _processors.size(); } + + int getNumProcessor() { return _processors.size(); } + nlohmann::json getProcessor(int index); + + int getNumMemory() { return _memory.size(); } + nlohmann::json getSystemRam(int index); + + int getNumGPU() { return _gpu.size(); } + nlohmann::json getGPU(int index); + protected: - std::vector _processors; - struct memory _memory; + std::vector _processors; + std::vector _memory; + std::vector _gpu; }; -static Instance* _instance; - //Platform level functions void create(); -std::string getProcessor(int index); -int getProcessorCount(); + bool enumerateProcessors(); -int getTotalSystemRamMb(); +int getNumProcessor(); +nlohmann::json getProcessor(int index); +int getNumMemory(); +nlohmann::json getSystemRam(int index); } // namespace platform \ No newline at end of file From 26b38f5950a203530584b45b9d87b3726537d114 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Mon, 6 May 2019 13:51:52 -0700 Subject: [PATCH 13/50] ifndef protection for headers --- interface/src/Application.cpp | 8 +++++--- libraries/platform/src/WINPlatform.h | 8 ++++++-- libraries/platform/src/platform.h | 8 ++++++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6e3711d60a..de1e72bfc7 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2461,13 +2461,15 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo ///Platform test function not staying for final code void Application::initializePlatform() { - //init the platform + //init the platform platform::create(); - //run the enumeration + //run the enumeration if (platform::enumerateProcessors()) { for (int i = 0; i < platform::getNumProcessor(); i++) { - platform::getProcessor(i); + std::string test = platform::getProcessor(i).dump(); + + qDebug() << test.c_str(); } } } diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index f03fb2c95a..1579767b60 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -6,7 +6,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#pragma once +#ifndef hifi_WinPlatform_h +#define hifi_WinPlatform_h + #include "platform.h" #include @@ -25,4 +27,6 @@ namespace platform { int getTotalSystemRam(); }; -} // namespace platform \ No newline at end of file +} // namespace platform + +#endif //hifi_winplatform_h \ No newline at end of file diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 3dfb2f2b14..d539db4387 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -6,7 +6,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#pragma once +#ifndef hifi_Platform_h +#define hifi_Platform_h + #include #include #include @@ -41,4 +43,6 @@ nlohmann::json getProcessor(int index); int getNumMemory(); nlohmann::json getSystemRam(int index); -} // namespace platform \ No newline at end of file +} // namespace platform + +#endif // hifi_platform_h \ No newline at end of file From f557e58224d1f9be39f916c3a80761df3358b6c6 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Mon, 6 May 2019 16:16:20 -0700 Subject: [PATCH 14/50] working on dxgi gpu info stuff --- libraries/platform/src/WINPlatform.cpp | 100 +++++++++++++++++++------ libraries/platform/src/WINPlatform.h | 7 +- libraries/platform/src/platform.cpp | 31 ++++++++ libraries/platform/src/platform.h | 3 +- 4 files changed, 113 insertions(+), 28 deletions(-) diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index c335e3745e..c29f29483e 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -11,36 +11,33 @@ #include #include + + +#ifdef Q_OS_WINDOWS +#include +#include +#endif + using namespace platform; using namespace nlohmann; bool WINInstance::enumerateProcessors() { - - - json cpu; - - getCpuDetails(cpu); - - cpu["numCores"] = getNumLogicalCores(); - - _processors.push_back(cpu); - - json mem; - mem["totalRam"] = getTotalSystemRam(); - - _memory.push_back(mem); + enumerateCpu(); + enumerateGpu(); + enumerateRam(); return true; } -void WINInstance::getCpuDetails(json &cpu) { +void WINInstance::enumerateCpu() { + json cpu; int CPUInfo[4] = { -1 }; unsigned nExIds; unsigned int i = 0; char CPUBrandString[16]; char CPUModelString[16]; char CPUClockString[16]; - + // Get the information associated with each extended ID. __cpuid(CPUInfo, 0x80000000); nExIds = CPUInfo[0]; @@ -56,24 +53,79 @@ void WINInstance::getCpuDetails(json &cpu) { memcpy(CPUClockString, CPUInfo, sizeof(CPUInfo)); } } - + cpu["brand"] = CPUBrandString; cpu["model"] = CPUModelString; cpu["clockSpeed"] = CPUClockString; + cpu["numCores"] = getNumLogicalCores(); + + _processors.push_back(cpu); } unsigned int WINInstance::getNumLogicalCores() { return std::thread::hardware_concurrency(); } -int WINInstance::getTotalSystemRam() { +void WINInstance::enumerateGpu() { +#ifdef Q_OS_WINDOWS + IDXGIAdapter* adapter; + std::vector adapters; + IDXGIFactory* factory = NULL; + + HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); + _gpu.clear(); + if (SUCCEEDED(hr)) { + for (UINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { + DXGI_ADAPTER_DESC* desc; + + if (SUCCEEDED(adapter->GetDesc(desc))) { + json* gpu = new json(); + + (*gpu)["BrandModel"] = desc->Description; + (*gpu)["DedicatedRam"] = desc->DedicatedVideoMemory/1024/1024; + (*gpu)["SharedRam"] = desc->SharedSystemMemory / 1024 / 1024; + + UINT numModes = 0; + DXGI_MODE_DESC* displayModes = NULL; + DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT; + IDXGIOutput* output = NULL; + + if (SUCCEEDED(adapter->EnumOutputs(0, &output))) { + output->GetDisplayModeList(format, 0, &numModes, displayModes); + + DXGI_OUTPUT_DESC* desc; + + output->GetDesc(desc); + + //auto a = desc->Monitor; + //auto b = desc->DeviceName; + //figure out monitor info here + + } + + _gpu.push_back(gpu); + + } + } + } + + if (adapter) { + adapter->Release(); + } + if (factory) { + factory->Release(); + } + + +#endif +} + +void WINInstance::enumerateRam() { + json ram; MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); - return statex.ullTotalPhys / 1024 / 1024; + int totalRam = statex.ullTotalPhys / 1024 / 1024; + ram["totalMem"] = totalRam; + _memory.push_back(ram); } - - - - - diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 1579767b60..542bebb5de 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -23,9 +23,10 @@ namespace platform { private: unsigned int getNumLogicalCores(); - void getCpuDetails(nlohmann::json& cpu); - int getTotalSystemRam(); -}; + void enumerateCpu(); + void enumerateRam(); + void enumerateGpu(); + }; } // namespace platform diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index 5ab2e7fbc2..c71b62bbd8 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -69,6 +69,37 @@ json Instance::getGPU(int index) { } +Instance::~Instance() { + //if (_processors.size() > 0) { + + // for (std::vector::iterator it = _processors.begin(); it != _processors.end(); ++it) { + // delete (*it); + // } + // + // _processors.clear(); + // + // } + // + // if (_memory.size() > 0) { + // for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { + // delete (*it); + // } + // + // _memory.clear(); + // } + + + if (_gpu.size() > 0) { + for (std::vector::iterator it = _gpu.begin(); it != _gpu.end(); ++it) { + delete (*it); + } + + _gpu.clear(); + } + + +} + bool platform::enumerateProcessors() { return _instance->enumerateProcessors(); } diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index d539db4387..b14421ffff 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -27,11 +27,12 @@ public: int getNumGPU() { return _gpu.size(); } nlohmann::json getGPU(int index); + ~Instance(); protected: std::vector _processors; std::vector _memory; - std::vector _gpu; + std::vector _gpu; }; //Platform level functions From 302e876857358d9bb32f827675d23f7c4fba3f18 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 9 May 2019 10:26:16 +1200 Subject: [PATCH 15/50] Update InteractiveWindow JSDoc per changes in master --- .../scripting/DesktopScriptingInterface.cpp | 49 +++++++++++++++++-- .../src/scripting/DesktopScriptingInterface.h | 5 +- interface/src/ui/InteractiveWindow.cpp | 8 +++ 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/interface/src/scripting/DesktopScriptingInterface.cpp b/interface/src/scripting/DesktopScriptingInterface.cpp index 093678c474..8a34c8f2ba 100644 --- a/interface/src/scripting/DesktopScriptingInterface.cpp +++ b/interface/src/scripting/DesktopScriptingInterface.cpp @@ -22,6 +22,29 @@ #include #include +/**jsdoc + * The possible docking locations of an InteractiveWindow. + * @typedef {object} InteractiveWindow.DockAreas + * @property {InteractiveWindow.DockArea} TOP - Dock to the top edge of the Interface window. + * @property {InteractiveWindow.DockArea} BOTTOM - Dock to the bottom edge of the Interface window. + * @property {InteractiveWindow.DockArea} LEFT - Dock to the left edge of the Interface window. + * @property {InteractiveWindow.DockArea} RIGHT - Dock to the right edge of the Interface window. + */ +/**jsdoc + * A docking location of an InteractiveWindow. + * + * + * + * + * + * + * + * + * + * + *
ValueName

Description
0TOPDock to the top edge of the Interface window.
1BOTTOMDock to the bottom edge of the Interface window.
2LEFTDock to the left edge of the Interface window.
3RIGHTDock to the right edge of the Interface window.
+ * @typedef {number} InteractiveWindow.DockArea + */ static const QVariantMap DOCK_AREA { { "TOP", DockArea::TOP }, { "BOTTOM", DockArea::BOTTOM }, @@ -39,11 +62,27 @@ int DesktopScriptingInterface::getHeight() { } /**jsdoc - * The presentation mode specifies how an {@link InteractiveWindow} is displayed. - * @typedef {object} InteractiveWindow.PresentationMode - * @property {number} VIRTUAL - The window is displayed inside Interface: in the desktop window in desktop mode or on the HUD - * surface in HMD mode. - * @property {number} NATIVE - The window is displayed separately from the Interface window, as its own separate window. + * The possible display modes for an InteractiveWindow. + * @typedef {object} InteractiveWindow.PresentationModes + * @property {InteractiveWindow.PresentationMode} VIRTUAL - The window is displayed inside Interface: in the desktop window in + * desktop mode or on the HUD surface in HMD mode. + * @property {InteractiveWindow.PresentationMode} NATIVE - The window is displayed separately from the Interface window, as its + * own separate window. + */ +/**jsdoc + * A display mode for an InteractiveWindow. + * + * + * + * + * + * + * + * + *
ValueName

Description
0VIRTUALThe window is displayed inside Interface: in the desktop window in + * desktop mode or on the HUD surface in HMD mode.
1NATIVEThe window is displayed separately from the Interface window, as its + * own separate window.
+ * @typedef {number} InteractiveWindow.PresentationMode */ QVariantMap DesktopScriptingInterface::getPresentationMode() { static QVariantMap presentationModes { diff --git a/interface/src/scripting/DesktopScriptingInterface.h b/interface/src/scripting/DesktopScriptingInterface.h index 895594a264..5cd264606e 100644 --- a/interface/src/scripting/DesktopScriptingInterface.h +++ b/interface/src/scripting/DesktopScriptingInterface.h @@ -37,8 +37,11 @@ * top. Read-only. * @property {InteractiveWindow.Flags} CLOSE_BUTTON_HIDES - A flag value that makes an {@link InteractiveWindow} hide instead * of closing when the user clicks the "close" button. Read-only. - * @property {InteractiveWindow.PresentationMode} PresentationMode - The different display options for an + * @property {InteractiveWindow.PresentationModes} PresentationMode - The possible display options for an * {@link InteractiveWindow}: display inside Interface or in a separate desktop window. Read-only. + * @property {InteractiveWindow.DockAreas} DockArea - The possible docking locations of an {@link InteractiveWindow}: top, + * bottom, left, or right of the Interface window. + * Read-only. */ class DesktopScriptingInterface : public QObject, public Dependency { Q_OBJECT diff --git a/interface/src/ui/InteractiveWindow.cpp b/interface/src/ui/InteractiveWindow.cpp index a850c14b6f..72714ea8e8 100644 --- a/interface/src/ui/InteractiveWindow.cpp +++ b/interface/src/ui/InteractiveWindow.cpp @@ -79,6 +79,9 @@ void interactiveWindowPointerFromScriptValue(const QScriptValue& object, Interac * @property {InteractiveWindow.PresentationMode} [presentationMode=Desktop.PresentationMode.VIRTUAL] - * Desktop.PresentationMode.VIRTUAL to display the window inside Interface, .NATIVE to display it * as its own separate window. + * @property {InteractiveWindow.PresentationWindowInfo} [presentationWindowInfo] - Controls how a NATIVE window is + * displayed. If used, the window is docked to the specified edge of the Interface window, otherwise the window is + * displayed as its own separate window. * @property {InteractiveWindow.Flags} [flags=0] - Window behavior flags, set at window creation. Possible flag values are * provided as {@link Desktop|Desktop.ALWAYS_ON_TOP} and {@link Desktop|Desktop.CLOSE_BUTTON_HIDES}. */ @@ -107,6 +110,11 @@ InteractiveWindow::InteractiveWindow(const QString& sourceUrl, const QVariantMap auto mainWindow = qApp->getWindow(); _dockWidget = std::shared_ptr(new DockWidget(title, mainWindow), dockWidgetDeleter); + /**jsdoc + * Configures how a NATIVE window is displayed. + * @typedef {object} InteractiveWindow.PresentationWindowInfo + * @property {InteractiveWindow.DockArea} dockArea - The edge of the Interface window to dock to. + */ if (nativeWindowInfo.contains(DOCK_AREA_PROPERTY)) { DockArea dockedArea = (DockArea) nativeWindowInfo[DOCK_AREA_PROPERTY].toInt(); switch (dockedArea) { From 0d97543ece6212f6fc386fc8faf1d9cd0e406bed Mon Sep 17 00:00:00 2001 From: amerhifi Date: Thu, 9 May 2019 12:04:41 -0700 Subject: [PATCH 16/50] code cleanup based on discussion with Sam. Adding implementation for graphics and display info from gpuiden. removed dxgi references in platform --- interface/CMakeLists.txt | 1 + interface/src/Application.cpp | 17 ++++- interface/src/Application.h | 3 + libraries/platform/src/WINPlatform.cpp | 86 ++++++------------------ libraries/platform/src/WINPlatform.h | 2 +- libraries/platform/src/platform.cpp | 92 ++++++++++++++++++-------- libraries/platform/src/platform.h | 36 +++++++--- libraries/shared/CMakeLists.txt | 1 + libraries/shared/src/GPUIdent.cpp | 21 ++++++ libraries/shared/src/GPUIdent.h | 8 ++- 10 files changed, 161 insertions(+), 106 deletions(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index cd329e109a..b022984bb7 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -228,6 +228,7 @@ target_bullet() target_opengl() add_crashpad() target_breakpad() +target_json() # perform standard include and linking for found externals foreach(EXTERNAL ${OPTIONAL_EXTERNALS}) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index b13fd3dda9..48c3ae594a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -196,6 +196,8 @@ #include "scripting/RefreshRateScriptingInterface.h" +#include +#include #if defined(Q_OS_MAC) || defined(Q_OS_WIN) #include "SpeechRecognizer.h" @@ -245,7 +247,7 @@ #include "webbrowser/WebBrowserSuggestionsEngine.h" #include - +#include #include "AboutUtil.h" #include @@ -1032,6 +1034,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo _sampleSound(nullptr) { + initPlatform(); auto steamClient = PluginManager::getInstance()->getSteamClientPlugin(); setProperty(hifi::properties::STEAM, (steamClient && steamClient->isRunning())); setProperty(hifi::properties::CRASHED, _previousSessionCrashed); @@ -2486,6 +2489,18 @@ Application::Application(int& argc, char** argv, QElapsedTimer& startupTimer, bo pauseUntilLoginDetermined(); } +void Application::initPlatform() { + + platform::create(); + + platform::enumeratePlatform(); + + nlohmann::json test = platform::getGraphics(0); + nlohmann::json test1 = platform::getProcessor(0); + nlohmann::json test2 = platform::getMemory(0); + nlohmann::json test3 = platform::getDisplay(0); +} + void Application::updateVerboseLogging() { auto menu = Menu::getInstance(); if (!menu) { diff --git a/interface/src/Application.h b/interface/src/Application.h index 94e983290e..69db555d56 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -130,6 +130,9 @@ public: virtual bool makeRenderingContextCurrent() override; virtual bool isForeground() const override; + //test + void initPlatform(); + virtual DisplayPluginPointer getActiveDisplayPlugin() const override; // FIXME? Empty methods, do we still need them? diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index c29f29483e..21997a6fbe 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -10,27 +10,22 @@ #include #include #include +#include +#include - -#ifdef Q_OS_WINDOWS -#include -#include -#endif - using namespace platform; using namespace nlohmann; -bool WINInstance::enumerateProcessors() { +bool WINInstance::enumeratePlatform() { enumerateCpu(); enumerateGpu(); enumerateRam(); - return true; } void WINInstance::enumerateCpu() { - json cpu; + json *cpu= new json(); int CPUInfo[4] = { -1 }; unsigned nExIds; unsigned int i = 0; @@ -54,12 +49,12 @@ void WINInstance::enumerateCpu() { } } - cpu["brand"] = CPUBrandString; - cpu["model"] = CPUModelString; - cpu["clockSpeed"] = CPUClockString; - cpu["numCores"] = getNumLogicalCores(); + (*cpu)["brand"] = CPUBrandString; + (*cpu)["model"] = CPUModelString; + (*cpu)["clockSpeed"] = CPUClockString; + (*cpu)["numCores"] = getNumLogicalCores(); - _processors.push_back(cpu); + _cpu.push_back(cpu); } unsigned int WINInstance::getNumLogicalCores() { @@ -67,65 +62,26 @@ unsigned int WINInstance::getNumLogicalCores() { } void WINInstance::enumerateGpu() { -#ifdef Q_OS_WINDOWS - IDXGIAdapter* adapter; - std::vector adapters; - IDXGIFactory* factory = NULL; - HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); - _gpu.clear(); - if (SUCCEEDED(hr)) { - for (UINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { - DXGI_ADAPTER_DESC* desc; + GPUIdent* ident = GPUIdent::getInstance(); + + json *gpu = new json(); + (*gpu)["name"] = ident->getName().toUtf8().constData(); + (*gpu)["memory"] = ident->getMemory(); + (*gpu)["driver"] = ident->getDriver().toUtf8().constData(); - if (SUCCEEDED(adapter->GetDesc(desc))) { - json* gpu = new json(); - - (*gpu)["BrandModel"] = desc->Description; - (*gpu)["DedicatedRam"] = desc->DedicatedVideoMemory/1024/1024; - (*gpu)["SharedRam"] = desc->SharedSystemMemory / 1024 / 1024; - - UINT numModes = 0; - DXGI_MODE_DESC* displayModes = NULL; - DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT; - IDXGIOutput* output = NULL; - - if (SUCCEEDED(adapter->EnumOutputs(0, &output))) { - output->GetDisplayModeList(format, 0, &numModes, displayModes); - - DXGI_OUTPUT_DESC* desc; - - output->GetDesc(desc); - - //auto a = desc->Monitor; - //auto b = desc->DeviceName; - //figure out monitor info here - - } - - _gpu.push_back(gpu); - - } - } - } - - if (adapter) { - adapter->Release(); - } - if (factory) { - factory->Release(); - } - - -#endif + _gpu.push_back(gpu); + _display = ident->getOutput(); } void WINInstance::enumerateRam() { - json ram; + json* ram = new json(); + MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); int totalRam = statex.ullTotalPhys / 1024 / 1024; - ram["totalMem"] = totalRam; + (*ram)["totalMem"] = totalRam; + _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 542bebb5de..198fad5b77 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -19,7 +19,7 @@ namespace platform { class WINInstance : public Instance { public: - bool enumerateProcessors(); + bool enumeratePlatform(); private: unsigned int getNumLogicalCores(); diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index c71b62bbd8..a6ae58e305 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -35,19 +35,23 @@ void platform::create() { #endif } -json Instance::getProcessor(int index) { +void platform::destroy() { + delete _instance; +} + +json Instance::getCPU(int index) { assert(index < _processor.size()); json result; - if (index >= _processors.size()) + if (index >= _cpu.size()) return result; - return _processors.at(index); + return _cpu.at(index); } //These are ripe for template.. will work on that next -json Instance::getSystemRam(int index) { +json Instance::getMemory(int index) { assert(index < _memory.size()); @@ -68,25 +72,34 @@ json Instance::getGPU(int index) { return _gpu.at(index); } +json Instance::getDisplay(int index) { + assert(index < _display.size()); + + json result; + if (index >= _display.size()) + return result; + + return _display.at(index); +} Instance::~Instance() { - //if (_processors.size() > 0) { + if (_cpu.size() > 0) { - // for (std::vector::iterator it = _processors.begin(); it != _processors.end(); ++it) { - // delete (*it); - // } - // - // _processors.clear(); - // - // } - // - // if (_memory.size() > 0) { - // for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { - // delete (*it); - // } - // - // _memory.clear(); - // } + for (std::vector::iterator it = _cpu.begin(); it != _cpu.end(); ++it) { + delete (*it); + } + + _cpu.clear(); + + } + + if (_memory.size() > 0) { + for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { + delete (*it); + } + + _memory.clear(); + } if (_gpu.size() > 0) { @@ -97,25 +110,48 @@ Instance::~Instance() { _gpu.clear(); } + if (_display.size() > 0) { + for (std::vector::iterator it = _display.begin(); it != _display.end(); ++it) { + delete (*it); + } + _display.clear(); + } } -bool platform::enumerateProcessors() { - return _instance->enumerateProcessors(); +bool platform::enumeratePlatform() { + return _instance->enumeratePlatform(); +} + +int platform::getNumProcessor() { + return _instance->getNumCPU(); } json platform::getProcessor(int index) { - return _instance->getProcessor(index); + return _instance->getCPU(index); } -json platform::getSystemRam(int index) { - return _instance->getSystemRam(index); +int platform::getNumGraphics() { + return _instance->getNumGPU(); +} + +nlohmann::json platform::getGraphics(int index) { + return _instance->getGPU(index); +} + +int platform::getNumDisplay() { + return _instance->getNumDisplay(); +} + +nlohmann::json platform::getDisplay(int index) { + return _instance->getDisplay(index); +} + +json platform::getMemory(int index) { + return _instance->getMemory(index); } int platform::getNumMemory() { return _instance->getNumMemory(); } -int platform::getNumProcessor() { - return _instance->getNumProcessor(); -} \ No newline at end of file diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index b14421ffff..db78502fa4 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -12,37 +12,53 @@ #include #include #include + + namespace platform { class Instance { public: - bool virtual enumerateProcessors() = 0; + bool virtual enumeratePlatform() = 0; - int getNumProcessor() { return _processors.size(); } - nlohmann::json getProcessor(int index); - - int getNumMemory() { return _memory.size(); } - nlohmann::json getSystemRam(int index); + int getNumCPU() { return _cpu.size(); } + nlohmann::json getCPU(int index); int getNumGPU() { return _gpu.size(); } nlohmann::json getGPU(int index); + int getNumMemory() { return _memory.size(); } + nlohmann::json getMemory(int index); + + int getNumDisplay() { return _display.size(); } + nlohmann::json getDisplay(int index); + ~Instance(); protected: - std::vector _processors; - std::vector _memory; + std::vector _cpu; + std::vector _memory; std::vector _gpu; + std::vector _display; + }; //Platform level functions void create(); +void destroy(); + +bool enumeratePlatform(); -bool enumerateProcessors(); int getNumProcessor(); nlohmann::json getProcessor(int index); + +int getNumGraphics(); +nlohmann::json getGraphics(int index); + +int getNumDisplay(); +nlohmann::json getDisplay(int index); + int getNumMemory(); -nlohmann::json getSystemRam(int index); +nlohmann::json getMemory(int index); } // namespace platform diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 713501aa77..81e85c0d85 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -13,3 +13,4 @@ endif() target_zlib() target_nsight() +target_json() diff --git a/libraries/shared/src/GPUIdent.cpp b/libraries/shared/src/GPUIdent.cpp index 3b7a6cee40..2fc29e0d19 100644 --- a/libraries/shared/src/GPUIdent.cpp +++ b/libraries/shared/src/GPUIdent.cpp @@ -12,6 +12,7 @@ #ifdef Q_OS_WIN #include +#include //#include //#include @@ -250,6 +251,26 @@ GPUIdent* GPUIdent::ensureQuery(const QString& vendor, const QString& renderer) */ if (!validAdapterList.empty()) { + + for (auto outy = adapterToOutputs.begin(); outy != adapterToOutputs.end(); outy++) { + + AdapterEntry entry = *outy; + + entry.first.first.Description; + for (auto test = entry.second.begin(); test != entry.second.end(); test++) { + nlohmann::json* output = new nlohmann::json(); + (*output)["description"] = entry.first.first.Description; + (*output)["deviceName"]= test->DeviceName; + (*output)["coordinatesleft"] = test->DesktopCoordinates.left; + (*output)["coordinatesright"] = test->DesktopCoordinates.right; + (*output)["coordinatestop"] = test->DesktopCoordinates.top; + (*output)["coordinatesbottom"] = test->DesktopCoordinates.bottom; + _output.push_back(output); + + } + + } + auto& adapterEntry = adapterToOutputs[validAdapterList.front()]; std::wstring wDescription(adapterEntry.first.first.Description); diff --git a/libraries/shared/src/GPUIdent.h b/libraries/shared/src/GPUIdent.h index f780a4ddbd..8bb3a33d44 100644 --- a/libraries/shared/src/GPUIdent.h +++ b/libraries/shared/src/GPUIdent.h @@ -15,19 +15,25 @@ #define hifi_GPUIdent_h #include - #include +#include +#include +#include class GPUIdent { + public: uint64_t getMemory() { return _dedicatedMemoryMB; } QString getName() { return _name; } QString getDriver() { return _driver; } bool isValid() { return _isValid; } + std::vector getOutput() { return _output; } + // E.g., GPUIdent::getInstance()->getMemory(); static GPUIdent* getInstance(const QString& vendor = "", const QString& renderer = "") { return _instance.ensureQuery(vendor, renderer); } private: + std::vector _output; uint64_t _dedicatedMemoryMB { 0 }; QString _name { "" }; QString _driver { "" }; From 8b1cdb03cce38cc752b8c0bb16bc6e0affd0f3fe Mon Sep 17 00:00:00 2001 From: amerhifi Date: Thu, 9 May 2019 14:35:05 -0700 Subject: [PATCH 17/50] new mac os stubs --- libraries/platform/src/MACOSPlatform.cpp | 86 ++++++++++++++++++++++++ libraries/platform/src/MACOSPlatform.h | 33 +++++++++ 2 files changed, 119 insertions(+) create mode 100644 libraries/platform/src/MACOSPlatform.cpp create mode 100644 libraries/platform/src/MACOSPlatform.h diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp new file mode 100644 index 0000000000..775d996c39 --- /dev/null +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -0,0 +1,86 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "MACOSPlatform.h" +#include +#include +#include +#include + + +using namespace platform; +using namespace nlohmann; + +bool MACOSInstance::enumeratePlatform() { + enumerateCpu(); + enumerateGpu(); + enumerateRam(); + return true; +} + +void WINInstance::enumerateCpu() { + json *cpu= new json(); + int CPUInfo[4] = { -1 }; + unsigned nExIds; + unsigned int i = 0; + char CPUBrandString[16]; + char CPUModelString[16]; + char CPUClockString[16]; + + // Get the information associated with each extended ID. + __cpuid(CPUInfo, 0x80000000); + nExIds = CPUInfo[0]; + + for (i = 0x80000000; i <= nExIds; ++i) { + __cpuid(CPUInfo, i); + // Interpret CPU brand string + if (i == 0x80000002) { + memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); + } else if (i == 0x80000003) { + memcpy(CPUModelString, CPUInfo, sizeof(CPUInfo)); + } else if (i == 0x80000004) { + memcpy(CPUClockString, CPUInfo, sizeof(CPUInfo)); + } + } + + (*cpu)["brand"] = CPUBrandString; + (*cpu)["model"] = CPUModelString; + (*cpu)["clockSpeed"] = CPUClockString; + (*cpu)["numCores"] = getNumLogicalCores(); + + _cpu.push_back(cpu); +} + +unsigned int WINInstance::getNumLogicalCores() { + return std::thread::hardware_concurrency(); +} + +void WINInstance::enumerateGpu() { + + GPUIdent* ident = GPUIdent::getInstance(); + + json *gpu = new json(); + (*gpu)["name"] = ident->getName().toUtf8().constData(); + (*gpu)["memory"] = ident->getMemory(); + (*gpu)["driver"] = ident->getDriver().toUtf8().constData(); + + _gpu.push_back(gpu); + _display = ident->getOutput(); +} + +void WINInstance::enumerateRam() { + json* ram = new json(); + + MEMORYSTATUSEX statex; + statex.dwLength = sizeof(statex); + GlobalMemoryStatusEx(&statex); + int totalRam = statex.ullTotalPhys / 1024 / 1024; + (*ram)["totalMem"] = totalRam; + + _memory.push_back(ram); +} diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h new file mode 100644 index 0000000000..66b74f2122 --- /dev/null +++ b/libraries/platform/src/MACOSPlatform.h @@ -0,0 +1,33 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_WinPlatform_h +#define hifi_WinPlatform_h + +#include "platform.h" +#include + +namespace platform { + + using namespace nlohmann; + + class MACOSInstance : public Instance { + + public: + bool enumeratePlatform(); + + private: + unsigned int getNumLogicalCores(); + void enumerateCpu(); + void enumerateRam(); + void enumerateGpu(); + }; + +} // namespace platform + +#endif //hifi_winplatform_h \ No newline at end of file From b998008f0119aab30ad385dd28aaa37e02cb47ea Mon Sep 17 00:00:00 2001 From: amerhifi Date: Thu, 9 May 2019 14:43:27 -0700 Subject: [PATCH 18/50] fixed typo --- libraries/platform/src/platform.cpp | 58 ++++++++++++++--------------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index a6ae58e305..f0ff3a988a 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -40,7 +40,7 @@ void platform::destroy() { } json Instance::getCPU(int index) { - assert(index < _processor.size()); + assert(index < _cpu.size()); json result; if (index >= _cpu.size()) @@ -83,40 +83,36 @@ json Instance::getDisplay(int index) { } Instance::~Instance() { - if (_cpu.size() > 0) { - - for (std::vector::iterator it = _cpu.begin(); it != _cpu.end(); ++it) { - delete (*it); - } - - _cpu.clear(); - - } - - if (_memory.size() > 0) { - for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { - delete (*it); - } - - _memory.clear(); - } + if (_cpu.size() > 0) { + + for (std::vector::iterator it = _cpu.begin(); it != _cpu.end(); ++it) { + delete (*it); + } + _cpu.clear(); + } + + if (_memory.size() > 0) { + for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { + delete (*it); + } + _memory.clear(); + } - if (_gpu.size() > 0) { - for (std::vector::iterator it = _gpu.begin(); it != _gpu.end(); ++it) { - delete (*it); - } + if (_gpu.size() > 0) { + for (std::vector::iterator it = _gpu.begin(); it != _gpu.end(); ++it) { + delete (*it); + } + _gpu.clear(); + } - _gpu.clear(); - } + if (_display.size() > 0) { + for (std::vector::iterator it = _display.begin(); it != _display.end(); ++it) { + delete (*it); + } - if (_display.size() > 0) { - for (std::vector::iterator it = _display.begin(); it != _display.end(); ++it) { - delete (*it); - } - - _display.clear(); - } + _display.clear(); + } } bool platform::enumeratePlatform() { From edb3206a24e71a47fe994dce3569649356eec055 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 09:55:26 -0700 Subject: [PATCH 19/50] adding macos platform. Misisng display and cpu info --- interface/src/Application.cpp | 8 +-- libraries/platform/src/MACOSPlatform.cpp | 56 +++++++------------- libraries/platform/src/MACOSPlatform.h | 6 +-- libraries/platform/src/WINPlatform.cpp | 9 ++-- libraries/platform/src/platform.cpp | 65 +++++++++++------------- libraries/platform/src/platform.h | 20 ++++---- libraries/shared/src/GPUIdent.h | 2 +- 7 files changed, 73 insertions(+), 93 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 48c3ae594a..14a92adc7a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2495,10 +2495,10 @@ void Application::initPlatform() { platform::enumeratePlatform(); - nlohmann::json test = platform::getGraphics(0); - nlohmann::json test1 = platform::getProcessor(0); - nlohmann::json test2 = platform::getMemory(0); - nlohmann::json test3 = platform::getDisplay(0); + const nlohmann::json* test = platform::getGraphics(0); + const nlohmann::json* test1 = platform::getProcessor(0); + const nlohmann::json* test2 = platform::getMemory(0); + //const nlohmann::json* test3 = platform::getDisplay(0); } void Application::updateVerboseLogging() { diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index 775d996c39..fb83de1951 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -7,11 +7,11 @@ // #include "MACOSPlatform.h" -#include + #include #include #include - +#include using namespace platform; using namespace nlohmann; @@ -23,44 +23,26 @@ bool MACOSInstance::enumeratePlatform() { return true; } -void WINInstance::enumerateCpu() { +void MACOSInstance::enumerateCpu() { json *cpu= new json(); - int CPUInfo[4] = { -1 }; - unsigned nExIds; - unsigned int i = 0; - char CPUBrandString[16]; - char CPUModelString[16]; - char CPUClockString[16]; + - // Get the information associated with each extended ID. - __cpuid(CPUInfo, 0x80000000); - nExIds = CPUInfo[0]; - - for (i = 0x80000000; i <= nExIds; ++i) { - __cpuid(CPUInfo, i); - // Interpret CPU brand string - if (i == 0x80000002) { - memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo)); - } else if (i == 0x80000003) { - memcpy(CPUModelString, CPUInfo, sizeof(CPUInfo)); - } else if (i == 0x80000004) { - memcpy(CPUClockString, CPUInfo, sizeof(CPUInfo)); - } - } - - (*cpu)["brand"] = CPUBrandString; - (*cpu)["model"] = CPUModelString; - (*cpu)["clockSpeed"] = CPUClockString; - (*cpu)["numCores"] = getNumLogicalCores(); + + // (*cpu)["brand"] = ident->getName(); + // (*cpu)["model"] = CPUModelString; + // (*cpu)["clockSpeed"] = CPUClockString; + // (*cpu)["numCores"] = getNumLogicalCores(); _cpu.push_back(cpu); } -unsigned int WINInstance::getNumLogicalCores() { + + +unsigned int MACOSInstance::getNumLogicalCores() { return std::thread::hardware_concurrency(); } -void WINInstance::enumerateGpu() { +void MACOSInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); @@ -73,14 +55,12 @@ void WINInstance::enumerateGpu() { _display = ident->getOutput(); } -void WINInstance::enumerateRam() { +void MACOSInstance::enumerateRam() { json* ram = new json(); - - MEMORYSTATUSEX statex; - statex.dwLength = sizeof(statex); - GlobalMemoryStatusEx(&statex); - int totalRam = statex.ullTotalPhys / 1024 / 1024; - (*ram)["totalMem"] = totalRam; + long pages = sysconf(_SC_PHYS_PAGES); + long page_size = sysconf(_SC_PAGE_SIZE); + + (*ram)["totalMem"] = pages * page_size;; _memory.push_back(ram); } diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h index 66b74f2122..ff1a4818be 100644 --- a/libraries/platform/src/MACOSPlatform.h +++ b/libraries/platform/src/MACOSPlatform.h @@ -6,8 +6,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef hifi_WinPlatform_h -#define hifi_WinPlatform_h +#ifndef hifi_MACOSPlatform_h +#define hifi_MACOSPlatform_h #include "platform.h" #include @@ -30,4 +30,4 @@ namespace platform { } // namespace platform -#endif //hifi_winplatform_h \ No newline at end of file +#endif //hifi_winplatform_h diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 21997a6fbe..0c7f3db9f6 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -7,8 +7,10 @@ // #include "WINPlatform.h" +#ifdef Q_OS_WINDOWS #include #include +#endif #include #include #include @@ -33,6 +35,7 @@ void WINInstance::enumerateCpu() { char CPUModelString[16]; char CPUClockString[16]; +#ifdef Q_OS_WINDOWS // Get the information associated with each extended ID. __cpuid(CPUInfo, 0x80000000); nExIds = CPUInfo[0]; @@ -53,7 +56,7 @@ void WINInstance::enumerateCpu() { (*cpu)["model"] = CPUModelString; (*cpu)["clockSpeed"] = CPUClockString; (*cpu)["numCores"] = getNumLogicalCores(); - +#endif _cpu.push_back(cpu); } @@ -76,12 +79,12 @@ void WINInstance::enumerateGpu() { void WINInstance::enumerateRam() { json* ram = new json(); - +#ifdef Q_OS_WINDOWS MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); int totalRam = statex.ullTotalPhys / 1024 / 1024; (*ram)["totalMem"] = totalRam; - +#endif _memory.push_back(ram); } diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index f0ff3a988a..7fd8e4f8ad 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -16,7 +16,7 @@ #endif #ifdef Q_OS_MACOS -#include "MACPlatform.h" +#include "MACOSPlatform.h" #endif #ifdef Q_OS_LINUX @@ -31,7 +31,10 @@ void platform::create() { #ifdef Q_OS_WIN _instance =new WINInstance(); - #elif Q_OS_MAC + #endif + + #ifdef Q_OS_MAC + _instance = new MACOSInstance(); #endif } @@ -39,45 +42,37 @@ void platform::destroy() { delete _instance; } -json Instance::getCPU(int index) { - assert(index < _cpu.size()); - - json result; - if (index >= _cpu.size()) - return result; + json* Instance::getCPU(int index) { + assert(index <(int) _cpu.size()); + if (index >= (int)_cpu.size()) + return nullptr; return _cpu.at(index); } //These are ripe for template.. will work on that next -json Instance::getMemory(int index) { - - assert(index < _memory.size()); - - json result; - if(index>= _memory.size()) - return result; +json* Instance::getMemory(int index) { + assert(index <(int) _memory.size()); + if(index >= (int)_memory.size()) + return nullptr; return _memory.at(index); } -json Instance::getGPU(int index) { - assert(index < _gpu.size()); - - json result; - if (index >= _gpu.size()) - return result; +json* Instance::getGPU(int index) { + assert(index <(int) _gpu.size()); + if (index >=(int) _gpu.size()) + return nullptr; return _gpu.at(index); } -json Instance::getDisplay(int index) { - assert(index < _display.size()); - - json result; - if (index >= _display.size()) - return result; +json* Instance::getDisplay(int index) { + assert(index <(int) _display.size()); + + if (index >=(int) _display.size()) + return nullptr; return _display.at(index); } @@ -123,7 +118,7 @@ int platform::getNumProcessor() { return _instance->getNumCPU(); } -json platform::getProcessor(int index) { +const json* platform::getProcessor(int index) { return _instance->getCPU(index); } @@ -131,7 +126,7 @@ int platform::getNumGraphics() { return _instance->getNumGPU(); } -nlohmann::json platform::getGraphics(int index) { +const json* platform::getGraphics(int index) { return _instance->getGPU(index); } @@ -139,15 +134,17 @@ int platform::getNumDisplay() { return _instance->getNumDisplay(); } -nlohmann::json platform::getDisplay(int index) { +const json* platform::getDisplay(int index) { return _instance->getDisplay(index); } -json platform::getMemory(int index) { - return _instance->getMemory(index); -} - int platform::getNumMemory() { return _instance->getNumMemory(); } +const json* platform::getMemory(int index) { + return _instance->getMemory(index); +} + + + diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index db78502fa4..9a5267211a 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -21,18 +21,18 @@ public: bool virtual enumeratePlatform() = 0; int getNumCPU() { return _cpu.size(); } - nlohmann::json getCPU(int index); + nlohmann::json* getCPU(int index); int getNumGPU() { return _gpu.size(); } - nlohmann::json getGPU(int index); + nlohmann::json* getGPU(int index); int getNumMemory() { return _memory.size(); } - nlohmann::json getMemory(int index); + nlohmann::json* getMemory(int index); int getNumDisplay() { return _display.size(); } - nlohmann::json getDisplay(int index); + nlohmann::json* getDisplay(int index); - ~Instance(); + virtual ~Instance(); protected: std::vector _cpu; @@ -49,17 +49,17 @@ void destroy(); bool enumeratePlatform(); int getNumProcessor(); -nlohmann::json getProcessor(int index); +const nlohmann::json* getProcessor(int index); int getNumGraphics(); -nlohmann::json getGraphics(int index); +const nlohmann::json* getGraphics(int index); int getNumDisplay(); -nlohmann::json getDisplay(int index); +const nlohmann::json* getDisplay(int index); int getNumMemory(); -nlohmann::json getMemory(int index); +const nlohmann::json* getMemory(int index); } // namespace platform -#endif // hifi_platform_h \ No newline at end of file +#endif // hifi_platform_h diff --git a/libraries/shared/src/GPUIdent.h b/libraries/shared/src/GPUIdent.h index 8bb3a33d44..eff215ca25 100644 --- a/libraries/shared/src/GPUIdent.h +++ b/libraries/shared/src/GPUIdent.h @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include class GPUIdent From ba69f0c962882bd5c534173e3e8f3f15cb8233d8 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 12:21:40 -0700 Subject: [PATCH 20/50] cleaned up references and added json alias. Unfortuantely this library isn't easy to forward declare so leaving the header include --- libraries/platform/src/MACOSPlatform.cpp | 5 ----- libraries/platform/src/MACOSPlatform.h | 1 - libraries/platform/src/WINPlatform.cpp | 3 ++- libraries/platform/src/WINPlatform.h | 3 +-- libraries/platform/src/platform.cpp | 1 - libraries/platform/src/platform.h | 28 ++++++++++++------------ 6 files changed, 17 insertions(+), 24 deletions(-) diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index fb83de1951..034849817c 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -14,7 +14,6 @@ #include using namespace platform; -using namespace nlohmann; bool MACOSInstance::enumeratePlatform() { enumerateCpu(); @@ -26,8 +25,6 @@ bool MACOSInstance::enumeratePlatform() { void MACOSInstance::enumerateCpu() { json *cpu= new json(); - - // (*cpu)["brand"] = ident->getName(); // (*cpu)["model"] = CPUModelString; // (*cpu)["clockSpeed"] = CPUClockString; @@ -36,8 +33,6 @@ void MACOSInstance::enumerateCpu() { _cpu.push_back(cpu); } - - unsigned int MACOSInstance::getNumLogicalCores() { return std::thread::hardware_concurrency(); } diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h index ff1a4818be..71953d1d1a 100644 --- a/libraries/platform/src/MACOSPlatform.h +++ b/libraries/platform/src/MACOSPlatform.h @@ -10,7 +10,6 @@ #define hifi_MACOSPlatform_h #include "platform.h" -#include namespace platform { diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 0c7f3db9f6..1e5e05df42 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -7,17 +7,18 @@ // #include "WINPlatform.h" + #ifdef Q_OS_WINDOWS #include #include #endif + #include #include #include using namespace platform; -using namespace nlohmann; bool WINInstance::enumeratePlatform() { enumerateCpu(); diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 198fad5b77..35ad2bf964 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -10,7 +10,6 @@ #define hifi_WinPlatform_h #include "platform.h" -#include namespace platform { @@ -30,4 +29,4 @@ namespace platform { } // namespace platform -#endif //hifi_winplatform_h \ No newline at end of file +#endif //hifi_winplatform_h diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index 7fd8e4f8ad..b51a3907bb 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -23,7 +23,6 @@ #endif using namespace platform; -using namespace nlohmann; Instance* _instance; diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 9a5267211a..3c28836a7f 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -9,36 +9,36 @@ #ifndef hifi_Platform_h #define hifi_Platform_h -#include #include #include namespace platform { - + using json = nlohmann::json; + class Instance { public: bool virtual enumeratePlatform() = 0; int getNumCPU() { return _cpu.size(); } - nlohmann::json* getCPU(int index); + json* getCPU(int index); int getNumGPU() { return _gpu.size(); } - nlohmann::json* getGPU(int index); + json* getGPU(int index); int getNumMemory() { return _memory.size(); } - nlohmann::json* getMemory(int index); + json* getMemory(int index); int getNumDisplay() { return _display.size(); } - nlohmann::json* getDisplay(int index); + json* getDisplay(int index); virtual ~Instance(); protected: - std::vector _cpu; - std::vector _memory; - std::vector _gpu; - std::vector _display; + std::vector _cpu; + std::vector _memory; + std::vector _gpu; + std::vector _display; }; @@ -49,16 +49,16 @@ void destroy(); bool enumeratePlatform(); int getNumProcessor(); -const nlohmann::json* getProcessor(int index); +const json* getProcessor(int index); int getNumGraphics(); -const nlohmann::json* getGraphics(int index); +const json* getGraphics(int index); int getNumDisplay(); -const nlohmann::json* getDisplay(int index); +const json* getDisplay(int index); int getNumMemory(); -const nlohmann::json* getMemory(int index); +const json* getMemory(int index); } // namespace platform From 0e6fcf0fe6cdc91d37fd88ca1510c0b4474a6cbe Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 12:24:41 -0700 Subject: [PATCH 21/50] removed unecessary using --- libraries/platform/src/MACOSPlatform.h | 3 --- libraries/platform/src/WINPlatform.h | 3 --- libraries/platform/src/platform.h | 3 +-- 3 files changed, 1 insertion(+), 8 deletions(-) diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h index 71953d1d1a..44861eba41 100644 --- a/libraries/platform/src/MACOSPlatform.h +++ b/libraries/platform/src/MACOSPlatform.h @@ -12,9 +12,6 @@ #include "platform.h" namespace platform { - - using namespace nlohmann; - class MACOSInstance : public Instance { public: diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 35ad2bf964..20efe63bad 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -12,9 +12,6 @@ #include "platform.h" namespace platform { - - using namespace nlohmann; - class WINInstance : public Instance { public: diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 3c28836a7f..8ad68e2019 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -12,7 +12,6 @@ #include #include - namespace platform { using json = nlohmann::json; @@ -39,7 +38,6 @@ protected: std::vector _memory; std::vector _gpu; std::vector _display; - }; //Platform level functions @@ -56,6 +54,7 @@ const json* getGraphics(int index); int getNumDisplay(); const json* getDisplay(int index); + int getNumMemory(); const json* getMemory(int index); From 684d71fc5b8dd6bf50c7f2edc9b4b1ca9d7d1d28 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 12:27:10 -0700 Subject: [PATCH 22/50] more clean up --- libraries/platform/src/platform.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index b51a3907bb..5ee157f76c 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -38,7 +38,8 @@ void platform::create() { } void platform::destroy() { - delete _instance; + if(_instance) + delete _instance; } json* Instance::getCPU(int index) { @@ -97,14 +98,13 @@ Instance::~Instance() { for (std::vector::iterator it = _gpu.begin(); it != _gpu.end(); ++it) { delete (*it); } - _gpu.clear(); + _gpu.clear(); } if (_display.size() > 0) { for (std::vector::iterator it = _display.begin(); it != _display.end(); ++it) { delete (*it); } - _display.clear(); } } From 81c0d195e3a0d5c37d1ca4a9a34a87b83e0f5f28 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 15:17:33 -0700 Subject: [PATCH 23/50] added ability to extract cpu info on osx --- libraries/platform/src/MACOSPlatform.cpp | 42 +++++++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index 034849817c..9ea2daca52 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -12,6 +12,7 @@ #include #include #include +#include using namespace platform; @@ -22,13 +23,44 @@ bool MACOSInstance::enumeratePlatform() { return true; } +static void getCpuId( uint32_t* p, uint32_t ax ) +{ + __asm __volatile + ( "movl %%ebx, %%esi\n\t" + "cpuid\n\t" + "xchgl %%ebx, %%esi" + : "=a" (p[0]), "=S" (p[1]), + "=c" (p[2]), "=d" (p[3]) + : "0" (ax) + ); +} + void MACOSInstance::enumerateCpu() { json *cpu= new json(); - - // (*cpu)["brand"] = ident->getName(); - // (*cpu)["model"] = CPUModelString; - // (*cpu)["clockSpeed"] = CPUClockString; - // (*cpu)["numCores"] = getNumLogicalCores(); + uint32_t cpuInfo[4]={0,0,0,0}; + char CPUBrandString[16]; + char CPUModelString[16]; + char CPUClockString[16]; + uint32_t nExIds; + getCpuId(cpuInfo, 0x80000000); + nExIds = cpuInfo[0]; + + for (uint32_t i = 0x80000000; i <= nExIds; ++i) { + getCpuId(cpuInfo, i); + // Interpret CPU brand string + if (i == 0x80000002) { + memcpy(CPUBrandString, cpuInfo, sizeof(cpuInfo)); + } else if (i == 0x80000003) { + memcpy(CPUModelString, cpuInfo, sizeof(cpuInfo)); + } else if (i == 0x80000004) { + memcpy(CPUClockString, cpuInfo, sizeof(cpuInfo)); + } + } + + (*cpu)["brand"] = ident->getName(); + (*cpu)["model"] = CPUModelString; + (*cpu)["clockSpeed"] = CPUClockString; + (*cpu)["numCores"] = getNumLogicalCores(); _cpu.push_back(cpu); } From d019dc7d547c20a862d066e036cf8f34a0acf9ee Mon Sep 17 00:00:00 2001 From: amerhifi Date: Fri, 10 May 2019 15:31:11 -0700 Subject: [PATCH 24/50] typo --- libraries/platform/src/MACOSPlatform.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index 9ea2daca52..115d7cb4bd 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -57,7 +57,7 @@ void MACOSInstance::enumerateCpu() { } } - (*cpu)["brand"] = ident->getName(); + (*cpu)["brand"] = CPUBrandString; (*cpu)["model"] = CPUModelString; (*cpu)["clockSpeed"] = CPUClockString; (*cpu)["numCores"] = getNumLogicalCores(); From 13c9bb078c582bcaac2e6bd93de25754c40c045f Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 06:50:08 -0700 Subject: [PATCH 25/50] cleaned up pointers from the platform. Relized that having to manage them outisde of the platform will cause other issues. --- interface/src/Application.cpp | 6 ++-- libraries/platform/src/MACOSPlatform.cpp | 34 ++++++++++++--------- libraries/platform/src/WINPlatform.cpp | 22 +++++++------- libraries/platform/src/platform.cpp | 38 ++++++++---------------- libraries/platform/src/platform.h | 24 +++++++-------- libraries/shared/src/GPUIdent.cpp | 17 +++++------ libraries/shared/src/GPUIdent.h | 4 +-- 7 files changed, 69 insertions(+), 76 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 14a92adc7a..e34730e4d6 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2495,9 +2495,9 @@ void Application::initPlatform() { platform::enumeratePlatform(); - const nlohmann::json* test = platform::getGraphics(0); - const nlohmann::json* test1 = platform::getProcessor(0); - const nlohmann::json* test2 = platform::getMemory(0); + const nlohmann::json test = platform::getGraphics(0); + const nlohmann::json test1 = platform::getProcessor(0); + const nlohmann::json test2 = platform::getMemory(0); //const nlohmann::json* test3 = platform::getDisplay(0); } diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index 115d7cb4bd..d9c17ddfa2 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -11,8 +11,11 @@ #include #include #include + +#ifdef Q_MAC_OS #include #include +#endif using namespace platform; @@ -25,18 +28,20 @@ bool MACOSInstance::enumeratePlatform() { static void getCpuId( uint32_t* p, uint32_t ax ) { +#ifdef Q_OS_MAC __asm __volatile - ( "movl %%ebx, %%esi\n\t" + ( "movl %%ebx, %%esi\n\t" "cpuid\n\t" "xchgl %%ebx, %%esi" : "=a" (p[0]), "=S" (p[1]), "=c" (p[2]), "=d" (p[3]) : "0" (ax) ); +#endif } void MACOSInstance::enumerateCpu() { - json *cpu= new json(); + json cpu = {}; uint32_t cpuInfo[4]={0,0,0,0}; char CPUBrandString[16]; char CPUModelString[16]; @@ -57,10 +62,10 @@ void MACOSInstance::enumerateCpu() { } } - (*cpu)["brand"] = CPUBrandString; - (*cpu)["model"] = CPUModelString; - (*cpu)["clockSpeed"] = CPUClockString; - (*cpu)["numCores"] = getNumLogicalCores(); + cpu["brand"] = CPUBrandString; + cpu["model"] = CPUModelString; + cpu["clockSpeed"] = CPUClockString; + cpu["numCores"] = getNumLogicalCores(); _cpu.push_back(cpu); } @@ -73,21 +78,22 @@ void MACOSInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); - json *gpu = new json(); - (*gpu)["name"] = ident->getName().toUtf8().constData(); - (*gpu)["memory"] = ident->getMemory(); - (*gpu)["driver"] = ident->getDriver().toUtf8().constData(); + json gpu = {}; + gpu["name"] = ident->getName().toUtf8().constData(); + gpu["memory"] = ident->getMemory(); + gpu["driver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); } void MACOSInstance::enumerateRam() { - json* ram = new json(); - long pages = sysconf(_SC_PHYS_PAGES); + json ram = {}; +#ifdef Q_OS_MAC + long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); - (*ram)["totalMem"] = pages * page_size;; - + ram["totalMem"] = pages * page_size;; +#endif _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 1e5e05df42..5ff782893b 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -28,7 +28,7 @@ bool WINInstance::enumeratePlatform() { } void WINInstance::enumerateCpu() { - json *cpu= new json(); + json cpu = {}; int CPUInfo[4] = { -1 }; unsigned nExIds; unsigned int i = 0; @@ -53,10 +53,10 @@ void WINInstance::enumerateCpu() { } } - (*cpu)["brand"] = CPUBrandString; - (*cpu)["model"] = CPUModelString; - (*cpu)["clockSpeed"] = CPUClockString; - (*cpu)["numCores"] = getNumLogicalCores(); + cpu["brand"] = CPUBrandString; + cpu["model"] = CPUModelString; + cpu["clockSpeed"] = CPUClockString; + cpu["numCores"] = getNumLogicalCores(); #endif _cpu.push_back(cpu); } @@ -69,23 +69,23 @@ void WINInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); - json *gpu = new json(); - (*gpu)["name"] = ident->getName().toUtf8().constData(); - (*gpu)["memory"] = ident->getMemory(); - (*gpu)["driver"] = ident->getDriver().toUtf8().constData(); + json gpu = {}; + gpu["name"] = ident->getName().toUtf8().constData(); + gpu["memory"] = ident->getMemory(); + gpu["driver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); } void WINInstance::enumerateRam() { - json* ram = new json(); + json ram = {}; #ifdef Q_OS_WINDOWS MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); int totalRam = statex.ullTotalPhys / 1024 / 1024; - (*ram)["totalMem"] = totalRam; + ram["totalMem"] = totalRam; #endif _memory.push_back(ram); } diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index 5ee157f76c..e017bcc99d 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -24,7 +24,7 @@ using namespace platform; -Instance* _instance; +Instance *_instance; void platform::create() { @@ -42,37 +42,37 @@ void platform::destroy() { delete _instance; } - json* Instance::getCPU(int index) { + json Instance::getCPU(int index) { assert(index <(int) _cpu.size()); if (index >= (int)_cpu.size()) - return nullptr; + return NULL; return _cpu.at(index); } //These are ripe for template.. will work on that next -json* Instance::getMemory(int index) { +json Instance::getMemory(int index) { assert(index <(int) _memory.size()); if(index >= (int)_memory.size()) - return nullptr; + return NULL; return _memory.at(index); } -json* Instance::getGPU(int index) { +json Instance::getGPU(int index) { assert(index <(int) _gpu.size()); if (index >=(int) _gpu.size()) - return nullptr; + return NULL; return _gpu.at(index); } -json* Instance::getDisplay(int index) { +json Instance::getDisplay(int index) { assert(index <(int) _display.size()); if (index >=(int) _display.size()) - return nullptr; + return NULL; return _display.at(index); } @@ -80,31 +80,19 @@ json* Instance::getDisplay(int index) { Instance::~Instance() { if (_cpu.size() > 0) { - for (std::vector::iterator it = _cpu.begin(); it != _cpu.end(); ++it) { - delete (*it); - } _cpu.clear(); } if (_memory.size() > 0) { - for (std::vector::iterator it = _memory.begin(); it != _memory.end(); ++it) { - delete (*it); - } _memory.clear(); } if (_gpu.size() > 0) { - for (std::vector::iterator it = _gpu.begin(); it != _gpu.end(); ++it) { - delete (*it); - } _gpu.clear(); } if (_display.size() > 0) { - for (std::vector::iterator it = _display.begin(); it != _display.end(); ++it) { - delete (*it); - } _display.clear(); } } @@ -117,7 +105,7 @@ int platform::getNumProcessor() { return _instance->getNumCPU(); } -const json* platform::getProcessor(int index) { +json platform::getProcessor(int index) { return _instance->getCPU(index); } @@ -125,7 +113,7 @@ int platform::getNumGraphics() { return _instance->getNumGPU(); } -const json* platform::getGraphics(int index) { +json platform::getGraphics(int index) { return _instance->getGPU(index); } @@ -133,7 +121,7 @@ int platform::getNumDisplay() { return _instance->getNumDisplay(); } -const json* platform::getDisplay(int index) { +json platform::getDisplay(int index) { return _instance->getDisplay(index); } @@ -141,7 +129,7 @@ int platform::getNumMemory() { return _instance->getNumMemory(); } -const json* platform::getMemory(int index) { +json platform::getMemory(int index) { return _instance->getMemory(index); } diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 8ad68e2019..920caa5419 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -20,24 +20,24 @@ public: bool virtual enumeratePlatform() = 0; int getNumCPU() { return _cpu.size(); } - json* getCPU(int index); + json getCPU(int index); int getNumGPU() { return _gpu.size(); } - json* getGPU(int index); + json getGPU(int index); int getNumMemory() { return _memory.size(); } - json* getMemory(int index); + json getMemory(int index); int getNumDisplay() { return _display.size(); } - json* getDisplay(int index); + json getDisplay(int index); virtual ~Instance(); protected: - std::vector _cpu; - std::vector _memory; - std::vector _gpu; - std::vector _display; + std::vector _cpu; + std::vector _memory; + std::vector _gpu; + std::vector _display; }; //Platform level functions @@ -47,17 +47,17 @@ void destroy(); bool enumeratePlatform(); int getNumProcessor(); -const json* getProcessor(int index); +json getProcessor(int index); int getNumGraphics(); -const json* getGraphics(int index); +json getGraphics(int index); int getNumDisplay(); -const json* getDisplay(int index); +json getDisplay(int index); int getNumMemory(); -const json* getMemory(int index); +json getMemory(int index); } // namespace platform diff --git a/libraries/shared/src/GPUIdent.cpp b/libraries/shared/src/GPUIdent.cpp index 2fc29e0d19..6cf094aa09 100644 --- a/libraries/shared/src/GPUIdent.cpp +++ b/libraries/shared/src/GPUIdent.cpp @@ -258,17 +258,16 @@ GPUIdent* GPUIdent::ensureQuery(const QString& vendor, const QString& renderer) entry.first.first.Description; for (auto test = entry.second.begin(); test != entry.second.end(); test++) { - nlohmann::json* output = new nlohmann::json(); - (*output)["description"] = entry.first.first.Description; - (*output)["deviceName"]= test->DeviceName; - (*output)["coordinatesleft"] = test->DesktopCoordinates.left; - (*output)["coordinatesright"] = test->DesktopCoordinates.right; - (*output)["coordinatestop"] = test->DesktopCoordinates.top; - (*output)["coordinatesbottom"] = test->DesktopCoordinates.bottom; + nlohmann::json output = {}; + + output["description"] = entry.first.first.Description; + output["deviceName"]= test->DeviceName; + output["coordinatesleft"] = test->DesktopCoordinates.left; + output["coordinatesright"] = test->DesktopCoordinates.right; + output["coordinatestop"] = test->DesktopCoordinates.top; + output["coordinatesbottom"] = test->DesktopCoordinates.bottom; _output.push_back(output); - } - } auto& adapterEntry = adapterToOutputs[validAdapterList.front()]; diff --git a/libraries/shared/src/GPUIdent.h b/libraries/shared/src/GPUIdent.h index eff215ca25..e720fc5811 100644 --- a/libraries/shared/src/GPUIdent.h +++ b/libraries/shared/src/GPUIdent.h @@ -28,12 +28,12 @@ public: QString getName() { return _name; } QString getDriver() { return _driver; } bool isValid() { return _isValid; } - std::vector getOutput() { return _output; } + std::vector getOutput() { return _output; } // E.g., GPUIdent::getInstance()->getMemory(); static GPUIdent* getInstance(const QString& vendor = "", const QString& renderer = "") { return _instance.ensureQuery(vendor, renderer); } private: - std::vector _output; + std::vector _output; uint64_t _dedicatedMemoryMB { 0 }; QString _name { "" }; QString _driver { "" }; From cbd751df89b01a936a25abee93d9de2d8a6e3867 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 08:37:05 -0700 Subject: [PATCH 26/50] fixing mac typo --- libraries/platform/src/MACOSPlatform.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index d9c17ddfa2..e701f5afbc 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -12,7 +12,7 @@ #include #include -#ifdef Q_MAC_OS +#ifdef Q_OS_MAC #include #include #endif From 541aef5e90db404e580ac94dd4661d908c4c752f Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 09:56:10 -0700 Subject: [PATCH 27/50] fixing warnings --- libraries/platform/src/WINPlatform.cpp | 5 +++-- libraries/platform/src/platform.h | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 5ff782893b..26106bb207 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -29,14 +29,15 @@ bool WINInstance::enumeratePlatform() { void WINInstance::enumerateCpu() { json cpu = {}; + + +#ifdef Q_OS_WINDOWS int CPUInfo[4] = { -1 }; unsigned nExIds; unsigned int i = 0; char CPUBrandString[16]; char CPUModelString[16]; char CPUClockString[16]; - -#ifdef Q_OS_WINDOWS // Get the information associated with each extended ID. __cpuid(CPUInfo, 0x80000000); nExIds = CPUInfo[0]; diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 920caa5419..1a885982bb 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -19,16 +19,16 @@ class Instance { public: bool virtual enumeratePlatform() = 0; - int getNumCPU() { return _cpu.size(); } + int getNumCPU() { return (int)_cpu.size(); } json getCPU(int index); - int getNumGPU() { return _gpu.size(); } + int getNumGPU() { return (int)_gpu.size(); } json getGPU(int index); - int getNumMemory() { return _memory.size(); } + int getNumMemory() { return (int)_memory.size(); } json getMemory(int index); - int getNumDisplay() { return _display.size(); } + int getNumDisplay() { return (int)_display.size(); } json getDisplay(int index); virtual ~Instance(); From 8759f028f8adc1a3bcfae97658b9f17a9fadeacd Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 11:41:30 -0700 Subject: [PATCH 28/50] fixing Linux warnings --- libraries/platform/src/MACOSPlatform.h | 2 +- libraries/platform/src/WINPlatform.h | 2 +- libraries/platform/src/platform.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h index 44861eba41..8008a6faee 100644 --- a/libraries/platform/src/MACOSPlatform.h +++ b/libraries/platform/src/MACOSPlatform.h @@ -15,7 +15,7 @@ namespace platform { class MACOSInstance : public Instance { public: - bool enumeratePlatform(); + bool enumeratePlatform() override; private: unsigned int getNumLogicalCores(); diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 20efe63bad..7af2f9602f 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -15,7 +15,7 @@ namespace platform { class WINInstance : public Instance { public: - bool enumeratePlatform(); + bool enumeratePlatform() override; private: unsigned int getNumLogicalCores(); diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index 1a885982bb..d726a41d8d 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -36,7 +36,7 @@ public: protected: std::vector _cpu; std::vector _memory; - std::vector _gpu; + std::vector _gpu; std::vector _display; }; From 8623c3d74f523d6dc21779e2702f6963e1feb2be Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 12:14:48 -0700 Subject: [PATCH 29/50] removing testing function declared in app.h --- interface/src/Application.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index bb4e5e48a7..87b0ae7656 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -130,9 +130,6 @@ public: virtual bool makeRenderingContextCurrent() override; virtual bool isForeground() const override; - //test - void initPlatform(); - virtual DisplayPluginPointer getActiveDisplayPlugin() const override; // FIXME? Empty methods, do we still need them? From 270d7feb7f5c557ae09ed08370d43f0893537eb9 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 12:20:22 -0700 Subject: [PATCH 30/50] removed the duplicate function declaration --- interface/src/Application.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index 87b0ae7656..d3f0fd501a 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -147,7 +147,7 @@ public: // Return an HTTP User-Agent string with OS and device information. Q_INVOKABLE QString getUserAgent(); - void initializePlatform(); + void initializeGL(); void initializeDisplayPlugins(); void initializeRenderEngine(); From 804d1711027d7381319e42e9845fc3fdf9fa02f2 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 16:38:11 -0700 Subject: [PATCH 31/50] fixed a bunch of pr comments --- libraries/platform/src/MACOSPlatform.cpp | 14 +++--- libraries/platform/src/WINPlatform.cpp | 11 +++-- libraries/platform/src/WINPlatform.h | 1 - libraries/platform/src/platform.cpp | 63 +++++++++++------------- libraries/platform/src/platform.h | 11 ++--- libraries/shared/src/GPUIdent.cpp | 15 +++--- libraries/shared/src/GPUIdent.h | 2 +- 7 files changed, 54 insertions(+), 63 deletions(-) diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index e701f5afbc..adaabc1d8d 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -41,7 +41,7 @@ static void getCpuId( uint32_t* p, uint32_t ax ) } void MACOSInstance::enumerateCpu() { - json cpu = {}; + json cpu = {}; uint32_t cpuInfo[4]={0,0,0,0}; char CPUBrandString[16]; char CPUModelString[16]; @@ -75,10 +75,8 @@ unsigned int MACOSInstance::getNumLogicalCores() { } void MACOSInstance::enumerateGpu() { - - GPUIdent* ident = GPUIdent::getInstance(); - - json gpu = {}; + GPUIdent* ident = GPUIdent::getInstance(); + json gpu = {}; gpu["name"] = ident->getName().toUtf8().constData(); gpu["memory"] = ident->getMemory(); gpu["driver"] = ident->getDriver().toUtf8().constData(); @@ -88,11 +86,11 @@ void MACOSInstance::enumerateGpu() { } void MACOSInstance::enumerateRam() { - json ram = {}; + json ram = {}; + #ifdef Q_OS_MAC - long pages = sysconf(_SC_PHYS_PAGES); + long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); - ram["totalMem"] = pages * page_size;; #endif _memory.push_back(ram); diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index 26106bb207..ca99facbf9 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -28,8 +28,7 @@ bool WINInstance::enumeratePlatform() { } void WINInstance::enumerateCpu() { - json cpu = {}; - + json cpu = {}; #ifdef Q_OS_WINDOWS int CPUInfo[4] = { -1 }; @@ -59,6 +58,7 @@ void WINInstance::enumerateCpu() { cpu["clockSpeed"] = CPUClockString; cpu["numCores"] = getNumLogicalCores(); #endif + _cpu.push_back(cpu); } @@ -68,9 +68,9 @@ unsigned int WINInstance::getNumLogicalCores() { void WINInstance::enumerateGpu() { - GPUIdent* ident = GPUIdent::getInstance(); + GPUIdent* ident = GPUIdent::getInstance(); - json gpu = {}; + json gpu = {}; gpu["name"] = ident->getName().toUtf8().constData(); gpu["memory"] = ident->getMemory(); gpu["driver"] = ident->getDriver().toUtf8().constData(); @@ -80,7 +80,7 @@ void WINInstance::enumerateGpu() { } void WINInstance::enumerateRam() { - json ram = {}; + json ram = {}; #ifdef Q_OS_WINDOWS MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); @@ -88,5 +88,6 @@ void WINInstance::enumerateRam() { int totalRam = statex.ullTotalPhys / 1024 / 1024; ram["totalMem"] = totalRam; #endif + _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 7af2f9602f..06af4c2982 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -23,7 +23,6 @@ namespace platform { void enumerateRam(); void enumerateGpu(); }; - } // namespace platform #endif //hifi_winplatform_h diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index e017bcc99d..c98e74c1c5 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -42,10 +42,10 @@ void platform::destroy() { delete _instance; } - json Instance::getCPU(int index) { +json Instance::getCPU(int index) { assert(index <(int) _cpu.size()); if (index >= (int)_cpu.size()) - return NULL; + return json(); return _cpu.at(index); } @@ -55,74 +55,74 @@ void platform::destroy() { json Instance::getMemory(int index) { assert(index <(int) _memory.size()); if(index >= (int)_memory.size()) - return NULL; + return json(); return _memory.at(index); } json Instance::getGPU(int index) { assert(index <(int) _gpu.size()); - if (index >=(int) _gpu.size()) - return NULL; + if (index >=(int) _gpu.size()) + return json(); + return _gpu.at(index); } json Instance::getDisplay(int index) { - assert(index <(int) _display.size()); + assert(index <(int) _display.size()); - if (index >=(int) _display.size()) - return NULL; + if (index >=(int) _display.size()) + return json(); - return _display.at(index); + return _display.at(index); } Instance::~Instance() { - if (_cpu.size() > 0) { + if (_cpu.size() > 0) { + _cpu.clear(); + } - _cpu.clear(); - } - - if (_memory.size() > 0) { - _memory.clear(); - } + if (_memory.size() > 0) { + _memory.clear(); + } - if (_gpu.size() > 0) { + if (_gpu.size() > 0) { _gpu.clear(); - } + } - if (_display.size() > 0) { - _display.clear(); - } + if (_display.size() > 0) { + _display.clear(); + } } bool platform::enumeratePlatform() { return _instance->enumeratePlatform(); } -int platform::getNumProcessor() { - return _instance->getNumCPU(); +int platform::getNumCPU() { + return _instance->getNumCPU(); } -json platform::getProcessor(int index) { +json platform::getCPU(int index) { return _instance->getCPU(index); } -int platform::getNumGraphics() { - return _instance->getNumGPU(); +int platform::getNumGPU() { + return _instance->getNumGPU(); } -json platform::getGraphics(int index) { - return _instance->getGPU(index); +json platform::getGPU(int index) { + return _instance->getGPU(index); } int platform::getNumDisplay() { - return _instance->getNumDisplay(); + return _instance->getNumDisplay(); } json platform::getDisplay(int index) { - return _instance->getDisplay(index); + return _instance->getDisplay(index); } int platform::getNumMemory() { @@ -132,6 +132,3 @@ int platform::getNumMemory() { json platform::getMemory(int index) { return _instance->getMemory(index); } - - - diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index d726a41d8d..c535520300 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -37,7 +37,7 @@ protected: std::vector _cpu; std::vector _memory; std::vector _gpu; - std::vector _display; + std::vector _display; }; //Platform level functions @@ -46,16 +46,15 @@ void destroy(); bool enumeratePlatform(); -int getNumProcessor(); -json getProcessor(int index); +int getNumCPU(); +json getCPU(int index); -int getNumGraphics(); -json getGraphics(int index); +int getNumGPU(); +json getGPU(int index); int getNumDisplay(); json getDisplay(int index); - int getNumMemory(); json getMemory(int index); diff --git a/libraries/shared/src/GPUIdent.cpp b/libraries/shared/src/GPUIdent.cpp index 6cf094aa09..6bb445e15a 100644 --- a/libraries/shared/src/GPUIdent.cpp +++ b/libraries/shared/src/GPUIdent.cpp @@ -251,15 +251,12 @@ GPUIdent* GPUIdent::ensureQuery(const QString& vendor, const QString& renderer) */ if (!validAdapterList.empty()) { + for (auto outy = adapterToOutputs.begin(); outy != adapterToOutputs.end(); outy++) { - for (auto outy = adapterToOutputs.begin(); outy != adapterToOutputs.end(); outy++) { - AdapterEntry entry = *outy; - - entry.first.first.Description; - for (auto test = entry.second.begin(); test != entry.second.end(); test++) { - nlohmann::json output = {}; - + for (auto test = entry.second.begin(); test != entry.second.end(); ++test) { + + nlohmann::json output = {}; output["description"] = entry.first.first.Description; output["deviceName"]= test->DeviceName; output["coordinatesleft"] = test->DesktopCoordinates.left; @@ -267,8 +264,8 @@ GPUIdent* GPUIdent::ensureQuery(const QString& vendor, const QString& renderer) output["coordinatestop"] = test->DesktopCoordinates.top; output["coordinatesbottom"] = test->DesktopCoordinates.bottom; _output.push_back(output); - } - } + } + } auto& adapterEntry = adapterToOutputs[validAdapterList.front()]; diff --git a/libraries/shared/src/GPUIdent.h b/libraries/shared/src/GPUIdent.h index e720fc5811..3d47ef8a33 100644 --- a/libraries/shared/src/GPUIdent.h +++ b/libraries/shared/src/GPUIdent.h @@ -28,7 +28,7 @@ public: QString getName() { return _name; } QString getDriver() { return _driver; } bool isValid() { return _isValid; } - std::vector getOutput() { return _output; } + const std::vector& getOutput() { return _output; } // E.g., GPUIdent::getInstance()->getMemory(); static GPUIdent* getInstance(const QString& vendor = "", const QString& renderer = "") { return _instance.ensureQuery(vendor, renderer); } From 95e3eede5fa7ae1f38ae3bad3a9d719f78587dab Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 17:07:25 -0700 Subject: [PATCH 32/50] moved instance to own file. moved functions based on comments in pr --- libraries/platform/src/MACOSPlatform.cpp | 15 +--- libraries/platform/src/MACOSPlatform.h | 14 ++-- libraries/platform/src/WINPlatform.cpp | 17 +--- libraries/platform/src/WINPlatform.h | 11 +-- libraries/platform/src/platform.cpp | 66 +--------------- libraries/platform/src/platform.h | 28 +------ libraries/platform/src/platformInstance.cpp | 86 +++++++++++++++++++++ libraries/platform/src/platformInstance.h | 49 ++++++++++++ 8 files changed, 154 insertions(+), 132 deletions(-) create mode 100644 libraries/platform/src/platformInstance.cpp create mode 100644 libraries/platform/src/platformInstance.h diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index adaabc1d8d..90df303a4e 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -19,13 +19,6 @@ using namespace platform; -bool MACOSInstance::enumeratePlatform() { - enumerateCpu(); - enumerateGpu(); - enumerateRam(); - return true; -} - static void getCpuId( uint32_t* p, uint32_t ax ) { #ifdef Q_OS_MAC @@ -65,15 +58,11 @@ void MACOSInstance::enumerateCpu() { cpu["brand"] = CPUBrandString; cpu["model"] = CPUModelString; cpu["clockSpeed"] = CPUClockString; - cpu["numCores"] = getNumLogicalCores(); + cpu["numCores"] = std::thread::hardware_concurrency(); _cpu.push_back(cpu); } -unsigned int MACOSInstance::getNumLogicalCores() { - return std::thread::hardware_concurrency(); -} - void MACOSInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; @@ -85,7 +74,7 @@ void MACOSInstance::enumerateGpu() { _display = ident->getOutput(); } -void MACOSInstance::enumerateRam() { +void MACOSInstance::enumerateMemory() { json ram = {}; #ifdef Q_OS_MAC diff --git a/libraries/platform/src/MACOSPlatform.h b/libraries/platform/src/MACOSPlatform.h index 8008a6faee..287e0c0ed7 100644 --- a/libraries/platform/src/MACOSPlatform.h +++ b/libraries/platform/src/MACOSPlatform.h @@ -9,19 +9,15 @@ #ifndef hifi_MACOSPlatform_h #define hifi_MACOSPlatform_h -#include "platform.h" +#include "platformInstance.h" namespace platform { class MACOSInstance : public Instance { - - public: - bool enumeratePlatform() override; - private: - unsigned int getNumLogicalCores(); - void enumerateCpu(); - void enumerateRam(); - void enumerateGpu(); + public: + void enumerateCpu() override; + void enumerateMemory() override; + void enumerateGpu() override; }; } // namespace platform diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index ca99facbf9..f78b0d6e17 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -20,13 +20,6 @@ using namespace platform; -bool WINInstance::enumeratePlatform() { - enumerateCpu(); - enumerateGpu(); - enumerateRam(); - return true; -} - void WINInstance::enumerateCpu() { json cpu = {}; @@ -56,16 +49,12 @@ void WINInstance::enumerateCpu() { cpu["brand"] = CPUBrandString; cpu["model"] = CPUModelString; cpu["clockSpeed"] = CPUClockString; - cpu["numCores"] = getNumLogicalCores(); + cpu["numCores"] = std::thread::hardware_concurrency(); #endif _cpu.push_back(cpu); } -unsigned int WINInstance::getNumLogicalCores() { - return std::thread::hardware_concurrency(); -} - void WINInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); @@ -79,8 +68,9 @@ void WINInstance::enumerateGpu() { _display = ident->getOutput(); } -void WINInstance::enumerateRam() { +void WINInstance::enumerateMemory() { json ram = {}; + #ifdef Q_OS_WINDOWS MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); @@ -88,6 +78,5 @@ void WINInstance::enumerateRam() { int totalRam = statex.ullTotalPhys / 1024 / 1024; ram["totalMem"] = totalRam; #endif - _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.h b/libraries/platform/src/WINPlatform.h index 06af4c2982..4d466a9b7e 100644 --- a/libraries/platform/src/WINPlatform.h +++ b/libraries/platform/src/WINPlatform.h @@ -9,19 +9,16 @@ #ifndef hifi_WinPlatform_h #define hifi_WinPlatform_h -#include "platform.h" +#include "platformInstance.h" namespace platform { class WINInstance : public Instance { public: - bool enumeratePlatform() override; + void enumerateCpu() override; + void enumerateMemory() override; + void enumerateGpu() override; - private: - unsigned int getNumLogicalCores(); - void enumerateCpu(); - void enumerateRam(); - void enumerateGpu(); }; } // namespace platform diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index c98e74c1c5..e9084d9bc1 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -27,14 +27,11 @@ using namespace platform; Instance *_instance; void platform::create() { - - #ifdef Q_OS_WIN - _instance =new WINInstance(); - #endif - - #ifdef Q_OS_MAC +#ifdef Q_OS_WIN + _instance =new WINInstance(); +#elseif defined(Q_OS_MAC) _instance = new MACOSInstance(); - #endif +#endif } void platform::destroy() { @@ -42,61 +39,6 @@ void platform::destroy() { delete _instance; } -json Instance::getCPU(int index) { - assert(index <(int) _cpu.size()); - if (index >= (int)_cpu.size()) - return json(); - - return _cpu.at(index); -} - - -//These are ripe for template.. will work on that next -json Instance::getMemory(int index) { - assert(index <(int) _memory.size()); - if(index >= (int)_memory.size()) - return json(); - - return _memory.at(index); -} - -json Instance::getGPU(int index) { - assert(index <(int) _gpu.size()); - - if (index >=(int) _gpu.size()) - return json(); - - return _gpu.at(index); -} - -json Instance::getDisplay(int index) { - assert(index <(int) _display.size()); - - if (index >=(int) _display.size()) - return json(); - - return _display.at(index); -} - -Instance::~Instance() { - if (_cpu.size() > 0) { - _cpu.clear(); - } - - if (_memory.size() > 0) { - _memory.clear(); - } - - - if (_gpu.size() > 0) { - _gpu.clear(); - } - - if (_display.size() > 0) { - _display.clear(); - } -} - bool platform::enumeratePlatform() { return _instance->enumeratePlatform(); } diff --git a/libraries/platform/src/platform.h b/libraries/platform/src/platform.h index c535520300..895114ba6d 100644 --- a/libraries/platform/src/platform.h +++ b/libraries/platform/src/platform.h @@ -9,41 +9,15 @@ #ifndef hifi_Platform_h #define hifi_Platform_h +#include "platformInstance.h" #include #include namespace platform { using json = nlohmann::json; -class Instance { -public: - bool virtual enumeratePlatform() = 0; - - int getNumCPU() { return (int)_cpu.size(); } - json getCPU(int index); - - int getNumGPU() { return (int)_gpu.size(); } - json getGPU(int index); - - int getNumMemory() { return (int)_memory.size(); } - json getMemory(int index); - - int getNumDisplay() { return (int)_display.size(); } - json getDisplay(int index); - - virtual ~Instance(); - -protected: - std::vector _cpu; - std::vector _memory; - std::vector _gpu; - std::vector _display; -}; - -//Platform level functions void create(); void destroy(); - bool enumeratePlatform(); int getNumCPU(); diff --git a/libraries/platform/src/platformInstance.cpp b/libraries/platform/src/platformInstance.cpp new file mode 100644 index 0000000000..705f5bd358 --- /dev/null +++ b/libraries/platform/src/platformInstance.cpp @@ -0,0 +1,86 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + + +#include "platform.h" + +#include + +#ifdef Q_OS_WIN +#include "WINPlatform.h" +#endif + +#ifdef Q_OS_MACOS +#include "MACOSPlatform.h" +#endif + +#ifdef Q_OS_LINUX +#endif + +using namespace platform; + +bool Instance::enumeratePlatform() { + enumerateCpu(); + enumerateGpu(); + enumerateMemory(); + return true; +} + +json Instance::getCPU(int index) { + assert(index <(int) _cpu.size()); + if (index >= (int)_cpu.size()) + return json(); + + return _cpu.at(index); +} + +//These are ripe for template.. will work on that next +json Instance::getMemory(int index) { + assert(index <(int) _memory.size()); + if(index >= (int)_memory.size()) + return json(); + + return _memory.at(index); +} + +json Instance::getGPU(int index) { + assert(index <(int) _gpu.size()); + + if (index >=(int) _gpu.size()) + return json(); + + return _gpu.at(index); +} + +json Instance::getDisplay(int index) { + assert(index <(int) _display.size()); + + if (index >=(int) _display.size()) + return json(); + + return _display.at(index); +} + +Instance::~Instance() { + if (_cpu.size() > 0) { + _cpu.clear(); + } + + if (_memory.size() > 0) { + _memory.clear(); + } + + + if (_gpu.size() > 0) { + _gpu.clear(); + } + + if (_display.size() > 0) { + _display.clear(); + } +} diff --git a/libraries/platform/src/platformInstance.h b/libraries/platform/src/platformInstance.h new file mode 100644 index 0000000000..739b70e318 --- /dev/null +++ b/libraries/platform/src/platformInstance.h @@ -0,0 +1,49 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_PlatformInstance_h +#define hifi_PlatformInstance_h + +#include +#include + +namespace platform { + using json = nlohmann::json; + +class Instance { +public: + bool virtual enumeratePlatform(); + + int getNumCPU() { return (int)_cpu.size(); } + json getCPU(int index); + + int getNumGPU() { return (int)_gpu.size(); } + json getGPU(int index); + + int getNumMemory() { return (int)_memory.size(); } + json getMemory(int index); + + int getNumDisplay() { return (int)_display.size(); } + json getDisplay(int index); + + void virtual enumerateCpu()=0; + void virtual enumerateMemory()=0; + void virtual enumerateGpu()=0; + + virtual ~Instance(); + +protected: + std::vector _cpu; + std::vector _memory; + std::vector _gpu; + std::vector _display; +}; + +} // namespace platform + +#endif // hifi_platform_h From 830f3dc9762a30cbb4747692df74f235884f0653 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 17:45:57 -0700 Subject: [PATCH 33/50] moved all hard coded json keys to platform::jsonkeys namespace and file --- libraries/platform/src/MACOSPlatform.cpp | 18 ++++++------- libraries/platform/src/WINPlatform.cpp | 20 +++++++------- libraries/platform/src/platformInstance.h | 2 +- libraries/platform/src/platformJsonKeys.h | 32 +++++++++++++++++++++++ 4 files changed, 52 insertions(+), 20 deletions(-) create mode 100644 libraries/platform/src/platformJsonKeys.h diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index 90df303a4e..a215f46335 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -7,7 +7,7 @@ // #include "MACOSPlatform.h" - +#include "platformJsonKeys.h" #include #include #include @@ -55,10 +55,10 @@ void MACOSInstance::enumerateCpu() { } } - cpu["brand"] = CPUBrandString; - cpu["model"] = CPUModelString; - cpu["clockSpeed"] = CPUClockString; - cpu["numCores"] = std::thread::hardware_concurrency(); + cpu[jsonKeys::cpuBrand] = CPUBrandString; + cpu[jsonKeys::cpuModel] = CPUModelString; + cpu[jsonKeys::cpuClockSpeed] = CPUClockString; + cpu[jsonKeys::cpuNumCores] = std::thread::hardware_concurrency(); _cpu.push_back(cpu); } @@ -66,9 +66,9 @@ void MACOSInstance::enumerateCpu() { void MACOSInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu["name"] = ident->getName().toUtf8().constData(); - gpu["memory"] = ident->getMemory(); - gpu["driver"] = ident->getDriver().toUtf8().constData(); + gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); + gpu[jsonKeys::gpuMemory] = ident->getMemory(); + gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); @@ -80,7 +80,7 @@ void MACOSInstance::enumerateMemory() { #ifdef Q_OS_MAC long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); - ram["totalMem"] = pages * page_size;; + ram[jsonKeys::totalMemory] = pages * page_size;; #endif _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index f78b0d6e17..b8748f3a4b 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -7,7 +7,7 @@ // #include "WINPlatform.h" - +#include "platformJsonKeys.h" #ifdef Q_OS_WINDOWS #include #include @@ -22,7 +22,7 @@ using namespace platform; void WINInstance::enumerateCpu() { json cpu = {}; - + #ifdef Q_OS_WINDOWS int CPUInfo[4] = { -1 }; unsigned nExIds; @@ -46,10 +46,10 @@ void WINInstance::enumerateCpu() { } } - cpu["brand"] = CPUBrandString; - cpu["model"] = CPUModelString; - cpu["clockSpeed"] = CPUClockString; - cpu["numCores"] = std::thread::hardware_concurrency(); + cpu[jsonKeys::cpuBrand] = CPUBrandString; + cpu[jsonKeys::cpuModel] = CPUModelString; + cpu[jsonKeys::cpuClockSpeed] = CPUClockString; + cpu[jsonKeys::cpuNumCores] = std::thread::hardware_concurrency(); #endif _cpu.push_back(cpu); @@ -60,9 +60,9 @@ void WINInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu["name"] = ident->getName().toUtf8().constData(); - gpu["memory"] = ident->getMemory(); - gpu["driver"] = ident->getDriver().toUtf8().constData(); + gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); + gpu[jsonKeys::gpuMemory] = ident->getMemory(); + gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); @@ -76,7 +76,7 @@ void WINInstance::enumerateMemory() { statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); int totalRam = statex.ullTotalPhys / 1024 / 1024; - ram["totalMem"] = totalRam; + ram[jsonKeys::totalMemory] = totalRam; #endif _memory.push_back(ram); } diff --git a/libraries/platform/src/platformInstance.h b/libraries/platform/src/platformInstance.h index 739b70e318..4770200f07 100644 --- a/libraries/platform/src/platformInstance.h +++ b/libraries/platform/src/platformInstance.h @@ -46,4 +46,4 @@ protected: } // namespace platform -#endif // hifi_platform_h +#endif // hifi_platformInstance_h diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h new file mode 100644 index 0000000000..f2d5d35af4 --- /dev/null +++ b/libraries/platform/src/platformJsonKeys.h @@ -0,0 +1,32 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_PlatformJsonKeys_h +#define hifi_PlatformJsonKeys_h + + +namespace platform { + namespace jsonKeys{ + static const char* cpuBrand= "cpuBrand"; + static const char* cpuModel = "cpuModel"; + static const char* cpuClockSpeed = "clockSpeed"; + static const char* cpuNumCores = "numCores"; + static const char* gpuName = "GpuName"; + static const char* gpuMemory = "gpuMemory"; + static const char* gpuDriver = "gpuDriver"; + static const char* totalMemory = "totalMem"; + static const char* displayDescription = "description"; + static const char* displayName = "deviceName"; + static const char* displayCoordsLeft = "coordinatesleft"; + static const char* displayCoordsRight = "coordinatesright"; + static const char* displayCoordsTop = "coordinatestop"; + static const char* displayCoordsBottom = "coordinatesbottom"; + } +} // namespace platform + +#endif From dc139dc04d6c9e62afa51ac447cb6fb6877f9171 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 17:47:12 -0700 Subject: [PATCH 34/50] added missing eof --- libraries/platform/CMakeLists.txt | 2 +- libraries/shared/CMakeLists.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/platform/CMakeLists.txt b/libraries/platform/CMakeLists.txt index d5b617a146..2d71babe6f 100644 --- a/libraries/platform/CMakeLists.txt +++ b/libraries/platform/CMakeLists.txt @@ -2,4 +2,4 @@ set(TARGET_NAME platform) setup_hifi_library() link_hifi_libraries(shared) -target_json() \ No newline at end of file +target_json() diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 81e85c0d85..061e7947cb 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -14,3 +14,4 @@ endif() target_zlib() target_nsight() target_json() + From fe6b2fceed572e127b722dc93a16f5a97d9af960 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 09:39:44 -0700 Subject: [PATCH 35/50] addressing comment in pr. removing extra space added in previous checkin --- interface/src/Application.h | 4 +--- libraries/shared/src/GPUIdent.cpp | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index 72f7d1f189..34a5ba1d0c 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -1,4 +1,4 @@ -// +// // Application.h // interface/src // @@ -78,8 +78,6 @@ #include "Sound.h" - - class GLCanvas; class FaceTracker; class MainWindow; diff --git a/libraries/shared/src/GPUIdent.cpp b/libraries/shared/src/GPUIdent.cpp index 6bb445e15a..a78ded483b 100644 --- a/libraries/shared/src/GPUIdent.cpp +++ b/libraries/shared/src/GPUIdent.cpp @@ -251,7 +251,7 @@ GPUIdent* GPUIdent::ensureQuery(const QString& vendor, const QString& renderer) */ if (!validAdapterList.empty()) { - for (auto outy = adapterToOutputs.begin(); outy != adapterToOutputs.end(); outy++) { + for (auto outy = adapterToOutputs.begin(); outy != adapterToOutputs.end(); ++outy) { AdapterEntry entry = *outy; for (auto test = entry.second.begin(); test != entry.second.end(); ++test) { From 18fe18ee12a96c09a5cd0da2c5961ef78f9a2e86 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 12:07:59 -0700 Subject: [PATCH 36/50] elseif typo --- libraries/platform/src/platform.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index e9084d9bc1..496dd164be 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -29,7 +29,7 @@ Instance *_instance; void platform::create() { #ifdef Q_OS_WIN _instance =new WINInstance(); -#elseif defined(Q_OS_MAC) +#elif defined(Q_OS_MAC) _instance = new MACOSInstance(); #endif } From d5bb7f25e1b740c6ea4ece90a926f6c48918d887 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Wed, 15 May 2019 07:56:55 +1200 Subject: [PATCH 37/50] Doc review --- .../src/scripting/DesktopScriptingInterface.h | 4 ++-- .../scripting/PlatformInfoScriptingInterface.h | 2 +- interface/src/ui/InteractiveWindow.h | 10 +++++----- .../src/material-networking/TextureCache.cpp | 2 +- libraries/networking/src/AddressManager.h | 17 +++++++++-------- 5 files changed, 18 insertions(+), 17 deletions(-) diff --git a/interface/src/scripting/DesktopScriptingInterface.h b/interface/src/scripting/DesktopScriptingInterface.h index 5cd264606e..b4ff159176 100644 --- a/interface/src/scripting/DesktopScriptingInterface.h +++ b/interface/src/scripting/DesktopScriptingInterface.h @@ -65,7 +65,7 @@ public: * Opens a QML window within Interface: in the Interface window in desktop mode or on the HUD surface in HMD mode. If a * window of the specified name already exists, it is shown, otherwise a new window is created from the QML. * @function Desktop.show - * @param {string} url - The QML file that specifies the window content + * @param {string} url - The QML file that specifies the window content. * @param {string} name - A unique name for the window. * @example Open the general settings dialog. * Desktop.show("hifi/dialogs/GeneralPreferencesDialog.qml", "GeneralPreferencesDialog"); @@ -76,7 +76,7 @@ public: * Creates a new window that can be displayed either within Interface or as a separate desktop window. * @function Desktop.createWindow * @param {string} url - The QML file that specifies the window content. The QML file can use a WebView - * control (defined by "WebView.qml" included in the Interface install) to embed an HTML Web page (complete with + * control (defined by "WebView.qml" included in the Interface install) to embed an HTML web page (complete with * EventBridge object). * @param {InteractiveWindow.Properties} [properties] - Initial window properties. * @returns {InteractiveWindow} A new window object. diff --git a/interface/src/scripting/PlatformInfoScriptingInterface.h b/interface/src/scripting/PlatformInfoScriptingInterface.h index f4d91d1230..c065f849f2 100644 --- a/interface/src/scripting/PlatformInfoScriptingInterface.h +++ b/interface/src/scripting/PlatformInfoScriptingInterface.h @@ -59,7 +59,7 @@ public slots: /**jsdoc * Returns the total system memory in megabytes. * @function PlatformInfo.getTotalSystemMemoryMB - * @returns {number} the total system memory in megabytes. + * @returns {number} The total system memory in megabytes. */ int getTotalSystemMemoryMB(); diff --git a/interface/src/ui/InteractiveWindow.h b/interface/src/ui/InteractiveWindow.h index a691e692e8..22127479d2 100644 --- a/interface/src/ui/InteractiveWindow.h +++ b/interface/src/ui/InteractiveWindow.h @@ -66,7 +66,7 @@ using namespace InteractiveWindowEnums; /**jsdoc * An InteractiveWindow can display either inside Interface or in its own window separate from the Interface * window. The window content is defined by a QML file, which can optionally include a WebView control that embeds - * an HTML Web page. (The WebView control is defined by a "WebView.qml" file included in the Interface install.) + * an HTML web page. (The WebView control is defined by a "WebView.qml" file included in the Interface install.) * *

Create using {@link Desktop.createWindow}.

* @@ -170,13 +170,13 @@ public slots: void sendToQml(const QVariant& message); /**jsdoc - * Sends a message to an embedded HTML Web page. To receive the message, the HTML page's script must connect to the + * Sends a message to an embedded HTML web page. To receive the message, the HTML page's script must connect to the * EventBridge that is automatically provided to the script: *
EventBridge.scriptEventReceived.connect(function(message) {
      *     ...
      * });
* @function InteractiveWindow.emitScriptEvent - * @param {string|object} message - The message to send to the embedded HTML Web page. + * @param {string|object} message - The message to send to the embedded HTML web page. */ // QmlWindow content may include WebView requiring EventBridge. void emitScriptEvent(const QVariant& scriptMessage); @@ -223,7 +223,7 @@ signals: void positionChanged(); /**jsdoc - * Triggered when the window's' size changes. + * Triggered when the window's size changes. * @function InteractiveWindow.sizeChanged * @returns {Signal} */ @@ -270,7 +270,7 @@ signals: void scriptEventReceived(const QVariant& message); /**jsdoc - * Trigged when a message from an embedded HTML Web page is received. The HTML Web page can send a message by calling: + * Triggered when a message from an embedded HTML web page is received. The HTML web page can send a message by calling: *
EventBridge.emitWebEvent(message);
* @function InteractiveWindow.webEventReceived * @param {string|object} message - The message received. diff --git a/libraries/material-networking/src/material-networking/TextureCache.cpp b/libraries/material-networking/src/material-networking/TextureCache.cpp index d8ad362de1..8ffcad0c69 100644 --- a/libraries/material-networking/src/material-networking/TextureCache.cpp +++ b/libraries/material-networking/src/material-networking/TextureCache.cpp @@ -65,7 +65,7 @@ const std::string TextureCache::KTX_DIRNAME{ "ktx_cache" }; const std::string TextureCache::KTX_EXT { "ktx" }; /**jsdoc - *

The views that may be displayed on the PC display.

+ *

The views that may be visible on the PC display.

* * * diff --git a/libraries/networking/src/AddressManager.h b/libraries/networking/src/AddressManager.h index 48a245538d..3cf5637c5f 100644 --- a/libraries/networking/src/AddressManager.h +++ b/libraries/networking/src/AddressManager.h @@ -245,21 +245,22 @@ public slots: * Takes you to the specified user's location. * @function location.goToUser * @param {string} username - The user's username. - * @param {boolean} [matchOrientation=true] - If true then go to a location just in front of the user and turn to face - * them, otherwise go to the user's exact location and orientation. + * @param {boolean} [matchOrientation=true] - If true then go to a location just in front of the user and turn + * to face them, otherwise go to the user's exact location and orientation. */ void goToUser(const QString& username, bool shouldMatchOrientation = true); /**jsdoc - * Takes you to the last address tried. This will be the last URL tried from location.handleLookupString - * @function location.goToLastAddress - */ + * Takes you to the last address tried. This will be the last URL tried from location.handleLookupString. + * @function location.goToLastAddress + */ void goToLastAddress() { handleUrl(_lastVisitedURL, LookupTrigger::AttemptedRefresh); } /**jsdoc - * Checks if going back is possible. - * @function location.canGoBack - */ + * Checks if going back to the previous location is possible. + * @function location.canGoBack + * @returns true if going back is possible, false if it isn't. + */ bool canGoBack() const; /**jsdoc From a12685c74b0f7251243dc10d21f38da895b58f4e Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 13:01:15 -0700 Subject: [PATCH 38/50] hiding json keys from ubuntu so that we can build for now until Linux implementation is done --- libraries/platform/src/platformJsonKeys.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index f2d5d35af4..cd818baa31 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,6 +12,7 @@ namespace platform { namespace jsonKeys{ +#ifndef Q_OS_LINUX static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; @@ -26,7 +27,9 @@ namespace platform { static const char* displayCoordsRight = "coordinatesright"; static const char* displayCoordsTop = "coordinatestop"; static const char* displayCoordsBottom = "coordinatesbottom"; - } +#endif + } + } // namespace platform #endif From 549b1ec73296ace7a9eef7b91edf35f03a446d58 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 13:04:25 -0700 Subject: [PATCH 39/50] VS didn't save the comment addition --- libraries/platform/src/platformJsonKeys.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index cd818baa31..a597d887f7 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,7 +12,7 @@ namespace platform { namespace jsonKeys{ -#ifndef Q_OS_LINUX +#ifndef Q_OS_LINUX //hiding from linux at the moment due to unused variables warning static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; From 3975525b36341105c1e01c939bf20e33b9b87bb9 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 14:50:32 -0700 Subject: [PATCH 40/50] trying a different method since ubuntu is still seeing them as unused --- libraries/platform/src/platformJsonKeys.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index a597d887f7..221a0180fe 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,7 +12,7 @@ namespace platform { namespace jsonKeys{ -#ifndef Q_OS_LINUX //hiding from linux at the moment due to unused variables warning +#if !defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; From 7ab9c482c20bca31cd61193ddff3f51622f96093 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 15:50:12 -0700 Subject: [PATCH 41/50] trying an alternative method for jumping over linux for now --- libraries/platform/src/platformJsonKeys.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index 221a0180fe..8d656e84c5 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,7 +12,8 @@ namespace platform { namespace jsonKeys{ -#if !defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning +#if defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning +#else static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; From 5e62e6b719cec72ec4de542dcdc19ff8167eee6b Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 19:29:17 -0700 Subject: [PATCH 42/50] Sam for the win. Qtglobal missing --- libraries/platform/src/platformJsonKeys.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index 8d656e84c5..5f06e97b09 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -8,12 +8,11 @@ #ifndef hifi_PlatformJsonKeys_h #define hifi_PlatformJsonKeys_h - +#include namespace platform { namespace jsonKeys{ -#if defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning -#else +#if !defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; From 19a848d481818a3828d92bfc99bab11c988d19fd Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 08:53:05 -0700 Subject: [PATCH 43/50] adding android until the stub is checked in --- libraries/platform/src/platformJsonKeys.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index 5f06e97b09..ea185433f6 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,7 +12,7 @@ namespace platform { namespace jsonKeys{ -#if !defined(Q_OS_LINUX) //hiding from linux at the moment due to unused variables warning +#if !defined(Q_OS_LINUX) || !defined(Q_OS_ANDROID) //hiding from linux at the moment due to unused variables warning static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; From c43d3de213e8d2b64f946ac7fda43c749d6b83e4 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 10:18:59 -0700 Subject: [PATCH 44/50] added linux and android stubs to help with the linux and android warnings --- android/settings.gradle | 16 ++++----- libraries/platform/src/AndroidPlatform.cpp | 40 +++++++++++++++++++++ libraries/platform/src/AndroidPlatform.h | 25 +++++++++++++ libraries/platform/src/LinuxPlatform.cpp | 42 ++++++++++++++++++++++ libraries/platform/src/LinuxPlatform.h | 25 +++++++++++++ libraries/platform/src/platform.cpp | 9 +++++ libraries/platform/src/platformJsonKeys.h | 4 +-- 7 files changed, 150 insertions(+), 11 deletions(-) create mode 100644 libraries/platform/src/AndroidPlatform.cpp create mode 100644 libraries/platform/src/AndroidPlatform.h create mode 100644 libraries/platform/src/LinuxPlatform.cpp create mode 100644 libraries/platform/src/LinuxPlatform.h diff --git a/android/settings.gradle b/android/settings.gradle index c7b70cfde2..8079cb79fd 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -2,8 +2,8 @@ // Libraries // -include ':oculus' -project(':oculus').projectDir = new File(settingsDir, 'libraries/oculus') +//include ':oculus' +//project(':oculus').projectDir = new File(settingsDir, 'libraries/oculus') include ':qt' project(':qt').projectDir = new File(settingsDir, 'libraries/qt') @@ -18,8 +18,8 @@ if (!getSettings().hasProperty("SUPPRESS_INTERFACE")) { } if (!getSettings().hasProperty("SUPPRESS_QUEST_INTERFACE")) { - include ':questInterface' - project(':questInterface').projectDir = new File(settingsDir, 'apps/questInterface') + // include ':questInterface' + // project(':questInterface').projectDir = new File(settingsDir, 'apps/questInterface') } // @@ -27,11 +27,11 @@ if (!getSettings().hasProperty("SUPPRESS_QUEST_INTERFACE")) { // if (!getSettings().hasProperty("SUPPRESS_FRAME_PLAYER")) { - include ':framePlayer' - project(':framePlayer').projectDir = new File(settingsDir, 'apps/framePlayer') + // include ':framePlayer' + // project(':framePlayer').projectDir = new File(settingsDir, 'apps/framePlayer') } if (!getSettings().hasProperty("SUPPRESS_QUEST_FRAME_PLAYER")) { - include ':questFramePlayer' - project(':questFramePlayer').projectDir = new File(settingsDir, 'apps/questFramePlayer') + //include ':questFramePlayer' + // project(':questFramePlayer').projectDir = new File(settingsDir, 'apps/questFramePlayer') } diff --git a/libraries/platform/src/AndroidPlatform.cpp b/libraries/platform/src/AndroidPlatform.cpp new file mode 100644 index 0000000000..e0a24d365a --- /dev/null +++ b/libraries/platform/src/AndroidPlatform.cpp @@ -0,0 +1,40 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "AndroidPlatform.h" +#include "platformJsonKeys.h" + +#include +#include +using namespace platform; + +void AndroidInstance::enumerateCpu() { + json cpu; + cpu[jsonKeys::cpuBrand] = ""; + cpu[jsonKeys::cpuModel] = ""; + cpu[jsonKeys::cpuClockSpeed] = ""; + cpu[jsonKeys::cpuNumCores] = ""; + _cpu.push_back(cpu); +} + +void AndroidInstance::enumerateGpu() { + GPUIdent* ident = GPUIdent::getInstance(); + json gpu = {}; + gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); + gpu[jsonKeys::gpuMemory] = ident->getMemory(); + gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + + _gpu.push_back(gpu); + _display = ident->getOutput(); +} + +void AndroidInstance::enumerateMemory() { + json ram = {}; + + _memory.push_back(ram); +} diff --git a/libraries/platform/src/AndroidPlatform.h b/libraries/platform/src/AndroidPlatform.h new file mode 100644 index 0000000000..17efbb45e3 --- /dev/null +++ b/libraries/platform/src/AndroidPlatform.h @@ -0,0 +1,25 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_AndroidPlatform_h +#define hifi_AndroidPlatform_h + +#include "platformInstance.h" + +namespace platform { + class AndroidInstance : public Instance { + + public: + void enumerateCpu() override; + void enumerateMemory() override; + void enumerateGpu() override; + }; + +} // namespace platform + +#endif //hifi_androidplatform_h diff --git a/libraries/platform/src/LinuxPlatform.cpp b/libraries/platform/src/LinuxPlatform.cpp new file mode 100644 index 0000000000..35ee2b1f0f --- /dev/null +++ b/libraries/platform/src/LinuxPlatform.cpp @@ -0,0 +1,42 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "LinuxPlatform.h" +#include "platformJsonKeys.h" +#include +#include + +using namespace platform; +void LinuxInstance::enumerateCpu() { + json cpu = {}; + + cpu[jsonKeys::cpuBrand] = ""; + cpu[jsonKeys::cpuModel] = ""; + cpu[jsonKeys::cpuClockSpeed] = ""; + cpu[jsonKeys::cpuNumCores] = ""; + + _cpu.push_back(cpu); +} + +void LinuxInstance::enumerateGpu() { + GPUIdent* ident = GPUIdent::getInstance(); + json gpu = {}; + gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); + gpu[jsonKeys::gpuMemory] = ident->getMemory(); + gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + + _gpu.push_back(gpu); + _display = ident->getOutput(); +} + +void LinuxInstance::enumerateMemory() { + json ram = {}; + + + _memory.push_back(ram); +} diff --git a/libraries/platform/src/LinuxPlatform.h b/libraries/platform/src/LinuxPlatform.h new file mode 100644 index 0000000000..1af4ce7444 --- /dev/null +++ b/libraries/platform/src/LinuxPlatform.h @@ -0,0 +1,25 @@ +// +// Created by Amer Cerkic 05/02/2019 +// Copyright 2019 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_LinuxPlatform_h +#define hifi_LinuxPlatform_h + +#include "platformInstance.h" + +namespace platform { + class LinuxInstance : public Instance { + + public: + void enumerateCpu() override; + void enumerateMemory() override; + void enumerateGpu() override; + }; + +} // namespace platform + +#endif //hifi_linuxPlaform_h diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index 496dd164be..f1bcf112fb 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -19,7 +19,12 @@ #include "MACOSPlatform.h" #endif +#ifdef Q_OS_ANDROID +#include "AndroidPlatform.h" +#endif + #ifdef Q_OS_LINUX +#include "LinuxPlatform.h" #endif using namespace platform; @@ -31,6 +36,10 @@ void platform::create() { _instance =new WINInstance(); #elif defined(Q_OS_MAC) _instance = new MACOSInstance(); +#elif defined(Q_OS_ANDROID) + _instance= new AndroidInstance(); +#elif defined(Q_OS_LINUX) + _instance= new LinuxInstance(); #endif } diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index ea185433f6..b947c3cc06 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -12,7 +12,6 @@ namespace platform { namespace jsonKeys{ -#if !defined(Q_OS_LINUX) || !defined(Q_OS_ANDROID) //hiding from linux at the moment due to unused variables warning static const char* cpuBrand= "cpuBrand"; static const char* cpuModel = "cpuModel"; static const char* cpuClockSpeed = "clockSpeed"; @@ -27,9 +26,8 @@ namespace platform { static const char* displayCoordsRight = "coordinatesright"; static const char* displayCoordsTop = "coordinatestop"; static const char* displayCoordsBottom = "coordinatesbottom"; -#endif } } // namespace platform -#endif +#endif From 89279e0d46e9d9cac950c54d4efe530ca314ce2f Mon Sep 17 00:00:00 2001 From: Amer <43353902+amerhifi@users.noreply.github.com> Date: Wed, 15 May 2019 10:27:14 -0700 Subject: [PATCH 45/50] undoing grade changes from Android build test --- android/settings.gradle | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/android/settings.gradle b/android/settings.gradle index 8079cb79fd..babe8cce92 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -18,8 +18,8 @@ if (!getSettings().hasProperty("SUPPRESS_INTERFACE")) { } if (!getSettings().hasProperty("SUPPRESS_QUEST_INTERFACE")) { - // include ':questInterface' - // project(':questInterface').projectDir = new File(settingsDir, 'apps/questInterface') + include ':questInterface' + project(':questInterface').projectDir = new File(settingsDir, 'apps/questInterface') } // @@ -27,11 +27,11 @@ if (!getSettings().hasProperty("SUPPRESS_QUEST_INTERFACE")) { // if (!getSettings().hasProperty("SUPPRESS_FRAME_PLAYER")) { - // include ':framePlayer' - // project(':framePlayer').projectDir = new File(settingsDir, 'apps/framePlayer') + include ':framePlayer' + project(':framePlayer').projectDir = new File(settingsDir, 'apps/framePlayer') } if (!getSettings().hasProperty("SUPPRESS_QUEST_FRAME_PLAYER")) { - //include ':questFramePlayer' - // project(':questFramePlayer').projectDir = new File(settingsDir, 'apps/questFramePlayer') + include ':questFramePlayer' + project(':questFramePlayer').projectDir = new File(settingsDir, 'apps/questFramePlayer') } From f1a90597cc40c55b96194934fa98d30e1ee2e3c6 Mon Sep 17 00:00:00 2001 From: Amer <43353902+amerhifi@users.noreply.github.com> Date: Wed, 15 May 2019 10:27:50 -0700 Subject: [PATCH 46/50] undo of gradle change --- android/settings.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/android/settings.gradle b/android/settings.gradle index babe8cce92..c7b70cfde2 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -2,8 +2,8 @@ // Libraries // -//include ':oculus' -//project(':oculus').projectDir = new File(settingsDir, 'libraries/oculus') +include ':oculus' +project(':oculus').projectDir = new File(settingsDir, 'libraries/oculus') include ':qt' project(':qt').projectDir = new File(settingsDir, 'libraries/qt') From a779fb54ff6626e6883a7e28672db6a43050d19d Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 11:53:40 -0700 Subject: [PATCH 47/50] testing a change to hopefully fix gcc warnings --- libraries/platform/src/platform.cpp | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/libraries/platform/src/platform.cpp b/libraries/platform/src/platform.cpp index f1bcf112fb..27e773d435 100644 --- a/libraries/platform/src/platform.cpp +++ b/libraries/platform/src/platform.cpp @@ -9,21 +9,15 @@ #include "platform.h" -#include +#include -#ifdef Q_OS_WIN +#if defined(Q_OS_WIN) #include "WINPlatform.h" -#endif - -#ifdef Q_OS_MACOS +#elif defined(Q_OS_MAC) #include "MACOSPlatform.h" -#endif - -#ifdef Q_OS_ANDROID +#elif defined(Q_OS_ANDROID) #include "AndroidPlatform.h" -#endif - -#ifdef Q_OS_LINUX +#elif defined(Q_OS_LINUX) #include "LinuxPlatform.h" #endif @@ -32,7 +26,7 @@ using namespace platform; Instance *_instance; void platform::create() { -#ifdef Q_OS_WIN +#if defined(Q_OS_WIN) _instance =new WINInstance(); #elif defined(Q_OS_MAC) _instance = new MACOSInstance(); From 803631a8212e68273385e6f6cf06ad9f0fbf7653 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 11:58:41 -0700 Subject: [PATCH 48/50] adding pragma once to see if it will help with gcc warnings. Its complaining that every file that includes the platformkeys is not using the variables --- libraries/platform/src/platformJsonKeys.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index b947c3cc06..c591f7ae5c 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -5,7 +5,7 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // - +#pragma once #ifndef hifi_PlatformJsonKeys_h #define hifi_PlatformJsonKeys_h #include From ff742ecd97cb4b1d524dfaa11f4a64942373a357 Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 12:13:30 -0700 Subject: [PATCH 49/50] removed qtglobal from keys. cleanup --- libraries/platform/src/platformJsonKeys.h | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index c591f7ae5c..e0ba136be1 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -8,7 +8,6 @@ #pragma once #ifndef hifi_PlatformJsonKeys_h #define hifi_PlatformJsonKeys_h -#include namespace platform { namespace jsonKeys{ From 1da5298086c7574fab3499cc345c8d563a4f627c Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 13:13:43 -0700 Subject: [PATCH 50/50] bypassing the static keys for now so that the pr can get build and go in --- libraries/platform/src/AndroidPlatform.cpp | 14 +++++----- libraries/platform/src/LinuxPlatform.cpp | 14 +++++----- libraries/platform/src/MACOSPlatform.cpp | 16 +++++------ libraries/platform/src/WINPlatform.cpp | 14 +++++----- libraries/platform/src/platformJsonKeys.h | 32 ++++++++++++---------- 5 files changed, 46 insertions(+), 44 deletions(-) diff --git a/libraries/platform/src/AndroidPlatform.cpp b/libraries/platform/src/AndroidPlatform.cpp index e0a24d365a..e998f6f938 100644 --- a/libraries/platform/src/AndroidPlatform.cpp +++ b/libraries/platform/src/AndroidPlatform.cpp @@ -15,19 +15,19 @@ using namespace platform; void AndroidInstance::enumerateCpu() { json cpu; - cpu[jsonKeys::cpuBrand] = ""; - cpu[jsonKeys::cpuModel] = ""; - cpu[jsonKeys::cpuClockSpeed] = ""; - cpu[jsonKeys::cpuNumCores] = ""; + cpu["cpuBrand"] = ""; + cpu["cpuModel"] = ""; + cpu["cpuClockSpeed"] = ""; + cpu["cpuNumCores"] = ""; _cpu.push_back(cpu); } void AndroidInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); - gpu[jsonKeys::gpuMemory] = ident->getMemory(); - gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + gpu["gpuName"] = ident->getName().toUtf8().constData(); + gpu["gpuMemory"] = ident->getMemory(); + gpu["gpuDriver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); diff --git a/libraries/platform/src/LinuxPlatform.cpp b/libraries/platform/src/LinuxPlatform.cpp index 35ee2b1f0f..96c105826f 100644 --- a/libraries/platform/src/LinuxPlatform.cpp +++ b/libraries/platform/src/LinuxPlatform.cpp @@ -15,10 +15,10 @@ using namespace platform; void LinuxInstance::enumerateCpu() { json cpu = {}; - cpu[jsonKeys::cpuBrand] = ""; - cpu[jsonKeys::cpuModel] = ""; - cpu[jsonKeys::cpuClockSpeed] = ""; - cpu[jsonKeys::cpuNumCores] = ""; + cpu["cpuBrand"] = ""; + cpu["cpuModel"] = ""; + cpu["cpuClockSpeed"] = ""; + cpu["cpuNumCores"] = ""; _cpu.push_back(cpu); } @@ -26,9 +26,9 @@ void LinuxInstance::enumerateCpu() { void LinuxInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); - gpu[jsonKeys::gpuMemory] = ident->getMemory(); - gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + gpu["gpuName"] = ident->getName().toUtf8().constData(); + gpu["gpuMemory"] = ident->getMemory(); + gpu["gpuDriver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); diff --git a/libraries/platform/src/MACOSPlatform.cpp b/libraries/platform/src/MACOSPlatform.cpp index a215f46335..172cd642aa 100644 --- a/libraries/platform/src/MACOSPlatform.cpp +++ b/libraries/platform/src/MACOSPlatform.cpp @@ -55,10 +55,10 @@ void MACOSInstance::enumerateCpu() { } } - cpu[jsonKeys::cpuBrand] = CPUBrandString; - cpu[jsonKeys::cpuModel] = CPUModelString; - cpu[jsonKeys::cpuClockSpeed] = CPUClockString; - cpu[jsonKeys::cpuNumCores] = std::thread::hardware_concurrency(); + cpu["cpuBrand"] = CPUBrandString; + cpu["cpuModel"] = CPUModelString; + cpu["cpuClockSpeed"] = CPUClockString; + cpu["cpuNumCores"] = std::thread::hardware_concurrency(); _cpu.push_back(cpu); } @@ -66,9 +66,9 @@ void MACOSInstance::enumerateCpu() { void MACOSInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); - gpu[jsonKeys::gpuMemory] = ident->getMemory(); - gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + gpu["gpuName"] = ident->getName().toUtf8().constData(); + gpu["gpuMemory"] = ident->getMemory(); + gpu["gpuDriver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); @@ -80,7 +80,7 @@ void MACOSInstance::enumerateMemory() { #ifdef Q_OS_MAC long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); - ram[jsonKeys::totalMemory] = pages * page_size;; + ram["totalMemory"] = pages * page_size;; #endif _memory.push_back(ram); } diff --git a/libraries/platform/src/WINPlatform.cpp b/libraries/platform/src/WINPlatform.cpp index b8748f3a4b..601a9d7290 100644 --- a/libraries/platform/src/WINPlatform.cpp +++ b/libraries/platform/src/WINPlatform.cpp @@ -46,10 +46,10 @@ void WINInstance::enumerateCpu() { } } - cpu[jsonKeys::cpuBrand] = CPUBrandString; - cpu[jsonKeys::cpuModel] = CPUModelString; - cpu[jsonKeys::cpuClockSpeed] = CPUClockString; - cpu[jsonKeys::cpuNumCores] = std::thread::hardware_concurrency(); + cpu["cpuBrand"] = CPUBrandString; + cpu["cpuModel"] = CPUModelString; + cpu["cpuClockSpeed"] = CPUClockString; + cpu["cpuNumCores"] = std::thread::hardware_concurrency(); #endif _cpu.push_back(cpu); @@ -60,9 +60,9 @@ void WINInstance::enumerateGpu() { GPUIdent* ident = GPUIdent::getInstance(); json gpu = {}; - gpu[jsonKeys::gpuName] = ident->getName().toUtf8().constData(); - gpu[jsonKeys::gpuMemory] = ident->getMemory(); - gpu[jsonKeys::gpuDriver] = ident->getDriver().toUtf8().constData(); + gpu["gpuName"] = ident->getName().toUtf8().constData(); + gpu["gpuMemory"] = ident->getMemory(); + gpu["gpuDriver"] = ident->getDriver().toUtf8().constData(); _gpu.push_back(gpu); _display = ident->getOutput(); diff --git a/libraries/platform/src/platformJsonKeys.h b/libraries/platform/src/platformJsonKeys.h index e0ba136be1..633add2b7e 100644 --- a/libraries/platform/src/platformJsonKeys.h +++ b/libraries/platform/src/platformJsonKeys.h @@ -11,21 +11,23 @@ namespace platform { namespace jsonKeys{ - static const char* cpuBrand= "cpuBrand"; - static const char* cpuModel = "cpuModel"; - static const char* cpuClockSpeed = "clockSpeed"; - static const char* cpuNumCores = "numCores"; - static const char* gpuName = "GpuName"; - static const char* gpuMemory = "gpuMemory"; - static const char* gpuDriver = "gpuDriver"; - static const char* totalMemory = "totalMem"; - static const char* displayDescription = "description"; - static const char* displayName = "deviceName"; - static const char* displayCoordsLeft = "coordinatesleft"; - static const char* displayCoordsRight = "coordinatesright"; - static const char* displayCoordsTop = "coordinatestop"; - static const char* displayCoordsBottom = "coordinatesbottom"; - } +#if 0 + static const char* cpuBrand { "cpuBrand"}; + static const char* cpuModel {"cpuModel"}; + static const char* cpuClockSpeed {"clockSpeed"}; + static const char* cpuNumCores { "numCores"}; + static const char* gpuName {"GpuName"}; + static const char* gpuMemory {"gpuMemory"}; + static const char* gpuDriver {"gpuDriver"}; + static const char* totalMemory {"totalMem"}; + static const char* displayDescription { "description"}; + static const char* displayName {"deviceName"}; + static const char* displayCoordsLeft {"coordinatesleft"}; + static const char* displayCoordsRight { "coordinatesright"}; + static const char* displayCoordsTop { "coordinatestop"}; + static const char* displayCoordsBottom { "coordinatesbottom"}; +#endif + } } // namespace platform