From f4b6db5def62b09d4ea6df41192de29212e531d7 Mon Sep 17 00:00:00 2001 From: Matt Hardcastle Date: Sun, 2 Dec 2018 17:08:27 -0800 Subject: [PATCH 01/58] 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 471baf83c69eab1589ec2085b1a43dc52612f88f Mon Sep 17 00:00:00 2001 From: Saracen Date: Tue, 25 Sep 2018 07:56:44 +0100 Subject: [PATCH 02/58] Support vertex colours and multiple unnamed mesh materials. # Conflicts: # libraries/fbx/src/GLTFSerializer.cpp --- libraries/fbx/src/GLTFSerializer.cpp | 167 ++++++++++++++++++--------- libraries/fbx/src/GLTFSerializer.h | 55 ++++++++- 2 files changed, 166 insertions(+), 56 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 622fb92ce7..ff2ab8a6d4 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -261,6 +261,41 @@ bool GLTFSerializer::setAsset(const QJsonObject& object) { return isAssetDefined; } +GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseIndices GLTFSerializer::createAccessorSparseIndices(const QJsonObject& object) { + GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseIndices accessorSparseIndices; + + getIntVal(object, "bufferView", accessorSparseIndices.bufferView, accessorSparseIndices.defined); + getIntVal(object, "byteOffset", accessorSparseIndices.byteOffset, accessorSparseIndices.defined); + getIntVal(object, "componentType", accessorSparseIndices.componentType, accessorSparseIndices.defined); + + return accessorSparseIndices; +} + +GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseValues GLTFSerializer::createAccessorSparseValues(const QJsonObject& object) { + GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseValues accessorSparseValues; + + getIntVal(object, "bufferView", accessorSparseValues.bufferView, accessorSparseValues.defined); + getIntVal(object, "byteOffset", accessorSparseValues.byteOffset, accessorSparseValues.defined); + + return accessorSparseValues; +} + +GLTFAccessor::GLTFAccessorSparse GLTFSerializer::createAccessorSparse(const QJsonObject& object) { + GLTFAccessor::GLTFAccessorSparse accessorSparse; + + getIntVal(object, "count", accessorSparse.count, accessorSparse.defined); + QJsonObject sparseIndicesObject; + if (getObjectVal(object, "indices", sparseIndicesObject, accessorSparse.defined)) { + accessorSparse.indices = createAccessorSparseIndices(sparseIndicesObject); + } + QJsonObject sparseValuesObject; + if (getObjectVal(object, "values", sparseValuesObject, accessorSparse.defined)) { + accessorSparse.values = createAccessorSparseValues(sparseValuesObject); + } + + return accessorSparse; +} + bool GLTFSerializer::addAccessor(const QJsonObject& object) { GLTFAccessor accessor; @@ -273,6 +308,12 @@ bool GLTFSerializer::addAccessor(const QJsonObject& object) { if (getStringVal(object, "type", type, accessor.defined)) { accessor.type = getAccessorType(type); } + + QJsonObject sparseObject; + if (getObjectVal(object, "sparse", sparseObject, accessor.defined)) { + accessor.sparse = createAccessorSparse(sparseObject); + } + getDoubleArrayVal(object, "max", accessor.max, accessor.defined); getDoubleArrayVal(object, "min", accessor.min, accessor.defined); @@ -783,7 +824,7 @@ void GLTFSerializer::generateTargetData(int index, float weight, QVector parents; QVector sortedNodes; parents.fill(-1, numNodes); @@ -802,18 +843,18 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& nodecount = 0; foreach(auto &node, _file.nodes) { // collect node transform - _file.nodes[nodecount].transforms.push_back(getModelTransform(node)); + _file.nodes[nodecount].transforms.push_back(getModelTransform(node)); int parentIndex = parents[nodecount]; while (parentIndex != -1) { const auto& parentNode = _file.nodes[parentIndex]; // collect transforms for a node's parents, grandparents, etc. _file.nodes[nodecount].transforms.push_back(getModelTransform(parentNode)); parentIndex = parents[parentIndex]; - } + } nodecount++; } - + // since parent indices must exist in the sorted list before any of their children, sortedNodes might not be initialized in the correct order // therefore we need to re-initialize the order in which nodes will be parsed QVector hasBeenSorted; @@ -837,10 +878,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& sortedNodes[j] = currentNode; i++; currentNode = sortedNodes[i]; - } + } j++; - } - } + } + } } @@ -868,7 +909,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& joint.translation = extractTranslation(joint.transform); joint.rotation = glmExtractRotation(joint.transform); glm::vec3 scale = extractScale(joint.transform); - joint.postTransform = glm::scale(glm::mat4(), scale); + joint.postTransform = glm::scale(glm::mat4(), scale); joint.name = node.name; joint.isSkeletonJoint = false; @@ -914,12 +955,18 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } - // Build materials + //Build materials QVector materialIDs; QString unknown = "Default"; int ukcount = 0; foreach(auto material, _file.materials) { - QString mid = (material.defined["name"]) ? material.name : unknown + ukcount++; + if (!(material.defined["name"])) { + QString name = unknown + QString::number(ukcount++); + material.name = name; + material.defined.insert("name", true); + } + + QString mid = material.name; materialIDs.push_back(mid); } @@ -928,6 +975,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hfmModel.materials[matid] = HFMMaterial(); HFMMaterial& hfmMaterial = hfmModel.materials[matid]; hfmMaterial._material = std::make_shared(); + hfmMaterial.name = hfmMaterial.materialID = matid; setHFMMaterial(hfmMaterial, _file.materials[i]); } @@ -938,30 +986,31 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& auto& node = _file.nodes[nodeIndex]; if (node.defined["mesh"]) { - foreach(auto &primitive, _file.meshes[node.mesh].primitives) { - hfmModel.meshes.append(HFMMesh()); - HFMMesh& mesh = hfmModel.meshes[hfmModel.meshes.size() - 1]; - if (!hfmModel.hasSkeletonJoints) { - HFMCluster cluster; - cluster.jointIndex = nodecount; - cluster.inverseBindMatrix = glm::mat4(); - cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); - mesh.clusters.append(cluster); + + hfmModel.meshes.append(HFMMesh()); + HFMMesh& mesh = hfmModel.meshes[hfmModel.meshes.size() - 1]; + if (!hfmModel.hasSkeletonJoints) { + HFMCluster cluster; + cluster.jointIndex = nodecount; + cluster.inverseBindMatrix = glm::mat4(); + cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); + mesh.clusters.append(cluster); } else { // skinned model for (int j = 0; j < numNodes; j++) { - HFMCluster cluster; - cluster.jointIndex = j; - cluster.inverseBindMatrix = jointInverseBindTransforms[j]; - cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); - mesh.clusters.append(cluster); - } + HFMCluster cluster; + cluster.jointIndex = j; + cluster.inverseBindMatrix = jointInverseBindTransforms[j]; + cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); + mesh.clusters.append(cluster); } - HFMCluster root; - root.jointIndex = 0; - root.inverseBindMatrix = jointInverseBindTransforms[root.jointIndex]; - root.inverseBindTransform = Transform(root.inverseBindMatrix); - mesh.clusters.append(root); + } + HFMCluster root; + root.jointIndex = 0; + root.inverseBindMatrix = jointInverseBindTransforms[root.jointIndex]; + root.inverseBindTransform = Transform(root.inverseBindMatrix); + mesh.clusters.append(root); + foreach(auto &primitive, _file.meshes[node.mesh].primitives) { HFMMeshPart part = HFMMeshPart(); int indicesAccessorIdx = primitive.indices; @@ -972,10 +1021,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int indicesAccBoffset = indicesAccessor.defined["byteOffset"] ? indicesAccessor.byteOffset : 0; - QVector raw_indices; - QVector raw_vertices; - QVector raw_normals; - bool success = addArrayOfType(indicesBuffer.blob, indicesBufferview.byteOffset + indicesAccBoffset, indicesAccessor.count, @@ -988,6 +1033,14 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } + // Increment the triangle indices by the current mesh vertex count so each mesh part can all reference the same buffers within the mesh + int prevMeshVerticesCount = mesh.vertices.count(); + if (prevMeshVerticesCount > 0) { + for (int i = 0; i < part.triangleIndices.count(); i++) { + part.triangleIndices[i] += prevMeshVerticesCount; + } + } + QList keys = primitive.attributes.values.keys(); QVector clusterJoints; QVector clusterWeights; @@ -1029,22 +1082,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& for (int n = 0; n < normals.size(); n = n + 3) { mesh.normals.push_back(glm::vec3(normals[n], normals[n + 1], normals[n + 2])); } - } else if (key == "COLOR_0") { - QVector colors; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - colors, - accessor.type, - accessor.componentType); - if (!success) { - qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; - continue; - } - int stride = (accessor.type == GLTFAccessorType::VEC4) ? 4 : 3; - for (int n = 0; n < colors.size() - 3; n += stride) { - mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); - } } else if (key == "TANGENT") { QVector tangents; success = addArrayOfType(buffer.blob, @@ -1093,7 +1130,23 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& for (int n = 0; n < texcoords.size(); n = n + 2) { mesh.texCoords1.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); } - } else if (key == "JOINTS_0") { + } else if (key == "COLOR_0") { + QVector colors; + success = addArrayOfType(buffer.blob, + bufferview.byteOffset + accBoffset, + accessor.count, + colors, + accessor.type, + accessor.componentType); + if (!success) { + qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; + continue; + } + int stride = (accessor.type == GLTFAccessorType::VEC4) ? 4 : 3; + for (int n = 0; n < colors.size() - 3; n += stride) { + mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); + } + } else if (key == "JOINTS_0") { QVector joints; success = addArrayOfType(buffer.blob, bufferview.byteOffset + accBoffset, @@ -1251,6 +1304,14 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.meshIndex = hfmModel.meshes.size(); } + + mesh.meshExtents.reset(); + foreach(const glm::vec3& vertex, mesh.vertices) { + mesh.meshExtents.addPoint(vertex); + hfmModel.meshExtents.addPoint(vertex); + } + + mesh.meshIndex = hfmModel.meshes.size(); } nodecount++; } @@ -1404,10 +1465,6 @@ HFMTexture GLTFSerializer::getHFMTexture(const GLTFTexture& texture) { void GLTFSerializer::setHFMMaterial(HFMMaterial& fbxmat, const GLTFMaterial& material) { - if (material.defined["name"]) { - fbxmat.name = fbxmat.materialID = material.name; - } - if (material.defined["emissiveFactor"] && material.emissiveFactor.size() == 3) { glm::vec3 emissive = glm::vec3(material.emissiveFactor[0], material.emissiveFactor[1], diff --git a/libraries/fbx/src/GLTFSerializer.h b/libraries/fbx/src/GLTFSerializer.h index b1c1bc4e44..fa5a640fca 100755 --- a/libraries/fbx/src/GLTFSerializer.h +++ b/libraries/fbx/src/GLTFSerializer.h @@ -481,6 +481,49 @@ namespace GLTFAccessorComponentType { }; } struct GLTFAccessor { + struct GLTFAccessorSparse { + struct GLTFAccessorSparseIndices { + int bufferView; + int byteOffset{ 0 }; + int componentType; + + QMap defined; + void dump() { + if (defined["bufferView"]) { + qCDebug(modelformat) << "bufferView: " << bufferView; + } + if (defined["byteOffset"]) { + qCDebug(modelformat) << "byteOffset: " << byteOffset; + } + if (defined["componentType"]) { + qCDebug(modelformat) << "componentType: " << componentType; + } + } + }; + struct GLTFAccessorSparseValues { + int bufferView; + int byteOffset{ 0 }; + + QMap defined; + void dump() { + if (defined["bufferView"]) { + qCDebug(modelformat) << "bufferView: " << bufferView; + } + if (defined["byteOffset"]) { + qCDebug(modelformat) << "byteOffset: " << byteOffset; + } + } + }; + + int count; + GLTFAccessorSparseIndices indices; + GLTFAccessorSparseValues values; + + QMap defined; + void dump() { + + } + }; int bufferView; int byteOffset { 0 }; int componentType; //required @@ -489,6 +532,7 @@ struct GLTFAccessor { bool normalized{ false }; QVector max; QVector min; + GLTFAccessorSparse sparse; QMap defined; void dump() { if (defined["bufferView"]) { @@ -521,6 +565,10 @@ struct GLTFAccessor { qCDebug(modelformat) << m; } } + if (defined["sparse"]) { + qCDebug(modelformat) << "sparse: "; + sparse.dump(); + } } }; @@ -763,6 +811,11 @@ private: int& outidx, QMap& defined); bool setAsset(const QJsonObject& object); + + GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseIndices createAccessorSparseIndices(const QJsonObject& object); + GLTFAccessor::GLTFAccessorSparse::GLTFAccessorSparseValues createAccessorSparseValues(const QJsonObject& object); + GLTFAccessor::GLTFAccessorSparse createAccessorSparse(const QJsonObject& object); + bool addAccessor(const QJsonObject& object); bool addAnimation(const QJsonObject& object); bool addBufferView(const QJsonObject& object); @@ -782,7 +835,7 @@ private: template bool readArray(const hifi::ByteArray& bin, int byteOffset, int count, QVector& outarray, int accessorType); - + template bool addArrayOfType(const hifi::ByteArray& bin, int byteOffset, int count, QVector& outarray, int accessorType, int componentType); From a4b3f02139b09d319833616a85acf860255e5047 Mon Sep 17 00:00:00 2001 From: Saracen Date: Wed, 7 Nov 2018 20:43:42 +0000 Subject: [PATCH 03/58] Added support for automatic normals generation, sparse accessors, extra threshold for thin bounding boxes, and general refactoring. # Conflicts: # libraries/fbx/src/GLTFSerializer.cpp --- libraries/fbx/src/GLTFSerializer.cpp | 440 +++++++++++++++++++++------ libraries/fbx/src/GLTFSerializer.h | 3 + 2 files changed, 348 insertions(+), 95 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index ff2ab8a6d4..78569fa78f 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -37,6 +37,28 @@ #include "FBXSerializer.h" +#define GLTF_GET_INDICIES(acc_count) int index1 = (indices[n + 0] * acc_count); int index2 = (indices[n + 1] * acc_count); int index3 = (indices[n + 2] * acc_count); + +#define GLTF_APPEND_ARRAY_1(new_array, old_array) GLTF_GET_INDICIES(1) \ +new_array.append(old_array[index1]); \ +new_array.append(old_array[index2]); \ +new_array.append(old_array[index3]); + +#define GLTF_APPEND_ARRAY_2(new_array, old_array) GLTF_GET_INDICIES(2) \ +new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); \ +new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); \ +new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); + +#define GLTF_APPEND_ARRAY_3(new_array, old_array) GLTF_GET_INDICIES(3) \ +new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); new_array.append(old_array[index1 + 2]); \ +new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); new_array.append(old_array[index2 + 2]); \ +new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); new_array.append(old_array[index3 + 2]); + +#define GLTF_APPEND_ARRAY_4(new_array, old_array) GLTF_GET_INDICIES(4) \ +new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); new_array.append(old_array[index1 + 2]); new_array.append(old_array[index1 + 3]); \ +new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); new_array.append(old_array[index2 + 2]); new_array.append(old_array[index2 + 3]); \ +new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); new_array.append(old_array[index3 + 2]); new_array.append(old_array[index3 + 3]); + bool GLTFSerializer::getStringVal(const QJsonObject& object, const QString& fieldname, QString& value, QMap& defined) { bool _defined = (object.contains(fieldname) && object[fieldname].isString()); @@ -1016,17 +1038,23 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int indicesAccessorIdx = primitive.indices; GLTFAccessor& indicesAccessor = _file.accessors[indicesAccessorIdx]; - GLTFBufferView& indicesBufferview = _file.bufferviews[indicesAccessor.bufferView]; - GLTFBuffer& indicesBuffer = _file.buffers[indicesBufferview.buffer]; - int indicesAccBoffset = indicesAccessor.defined["byteOffset"] ? indicesAccessor.byteOffset : 0; + // Buffers + QVector indices; + QVector vertices; + QVector normals; + QVector tangents; + int tangent_stride = 0; + QVector texcoords; + QVector texcoords2; + QVector colors; + int color_stride = 0; + QVector joints; + int joint_stride = 0; + QVector weights; + int weight_stride = 0; - bool success = addArrayOfType(indicesBuffer.blob, - indicesBufferview.byteOffset + indicesAccBoffset, - indicesAccessor.count, - part.triangleIndices, - indicesAccessor.type, - indicesAccessor.componentType); + bool success = addArrayOfFromAccessor(indicesAccessor, indices); if (!success) { qWarning(modelformat) << "There was a problem reading glTF INDICES data for model " << _url; @@ -1035,11 +1063,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Increment the triangle indices by the current mesh vertex count so each mesh part can all reference the same buffers within the mesh int prevMeshVerticesCount = mesh.vertices.count(); - if (prevMeshVerticesCount > 0) { - for (int i = 0; i < part.triangleIndices.count(); i++) { - part.triangleIndices[i] += prevMeshVerticesCount; - } - } QList keys = primitive.attributes.values.keys(); QVector clusterJoints; @@ -1049,136 +1072,290 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& int accessorIdx = primitive.attributes.values[key]; GLTFAccessor& accessor = _file.accessors[accessorIdx]; - GLTFBufferView& bufferview = _file.bufferviews[accessor.bufferView]; - GLTFBuffer& buffer = _file.buffers[bufferview.buffer]; int accBoffset = accessor.defined["byteOffset"] ? accessor.byteOffset : 0; if (key == "POSITION") { - QVector vertices; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, vertices, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, vertices); if (!success) { qWarning(modelformat) << "There was a problem reading glTF POSITION data for model " << _url; continue; } - for (int n = 0; n < vertices.size(); n = n + 3) { - mesh.vertices.push_back(glm::vec3(vertices[n], vertices[n + 1], vertices[n + 2])); + + if (accessor.type != GLTFAccessorType::VEC3) { + qWarning(modelformat) << "Invalid accessor type on glTF POSITION data for model " << _url; + continue; } } else if (key == "NORMAL") { - QVector normals; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - normals, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, normals); if (!success) { qWarning(modelformat) << "There was a problem reading glTF NORMAL data for model " << _url; continue; } - for (int n = 0; n < normals.size(); n = n + 3) { - mesh.normals.push_back(glm::vec3(normals[n], normals[n + 1], normals[n + 2])); + + if (accessor.type != GLTFAccessorType::VEC3) { + qWarning(modelformat) << "Invalid accessor type on glTF NORMAL data for model " << _url; + continue; } } else if (key == "TANGENT") { - QVector tangents; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - tangents, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, tangents); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TANGENT data for model " << _url; continue; } - // tangents can be a vec3 or a vec4 which includes a w component (of -1 or 1) - int stride = (accessor.type == GLTFAccessorType::VEC4) ? 4 : 3; - for (int n = 0; n < tangents.size() - 3; n += stride) { - float tanW = stride == 4 ? tangents[n + 3] : 1; - mesh.tangents.push_back(glm::vec3(tanW * tangents[n], tangents[n + 1], tanW * tangents[n + 2])); + + if (accessor.type == GLTFAccessorType::VEC4) { + tangent_stride = 4; + } else if (accessor.type == GLTFAccessorType::VEC3) { + tangent_stride = 3; + } else { + qWarning(modelformat) << "Invalid accessor type on glTF TANGENT data for model " << _url; + continue; } } else if (key == "TEXCOORD_0") { - QVector texcoords; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - texcoords, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, texcoords); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TEXCOORD_0 data for model " << _url; continue; } - for (int n = 0; n < texcoords.size(); n = n + 2) { - mesh.texCoords.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); + + if (accessor.type != GLTFAccessorType::VEC2) { + qWarning(modelformat) << "Invalid accessor type on glTF TEXCOORD_0 data for model " << _url; + continue; } } else if (key == "TEXCOORD_1") { - QVector texcoords; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - texcoords, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, texcoords2); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TEXCOORD_1 data for model " << _url; continue; } - for (int n = 0; n < texcoords.size(); n = n + 2) { - mesh.texCoords1.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); + + if (accessor.type != GLTFAccessorType::VEC2) { + qWarning(modelformat) << "Invalid accessor type on glTF TEXCOORD_1 data for model " << _url; + continue; } } else if (key == "COLOR_0") { - QVector colors; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - colors, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, colors); if (!success) { qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; continue; } - int stride = (accessor.type == GLTFAccessorType::VEC4) ? 4 : 3; - for (int n = 0; n < colors.size() - 3; n += stride) { - mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); + + if (accessor.type == GLTFAccessorType::VEC4) { + color_stride = 4; + } else if (accessor.type == GLTFAccessorType::VEC3) { + color_stride = 3; + } else { + qWarning(modelformat) << "Invalid accessor type on glTF COLOR_0 data for model " << _url; + continue; } - } else if (key == "JOINTS_0") { - QVector joints; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - joints, - accessor.type, - accessor.componentType); + } else if (key == "JOINTS_0") { + success = addArrayOfFromAccessor(accessor, joints); if (!success) { qWarning(modelformat) << "There was a problem reading glTF JOINTS_0 data for model " << _url; continue; } - for (int n = 0; n < joints.size(); n++) { - clusterJoints.push_back(joints[n]); + + if (accessor.type == GLTFAccessorType::VEC4) { + joint_stride = 4; + } else if (accessor.type == GLTFAccessorType::VEC3) { + joint_stride = 3; + } else if (accessor.type == GLTFAccessorType::VEC2) { + joint_stride = 2; + } else if (accessor.type == GLTFAccessorType::SCALAR) { + joint_stride = 1; + } else { + qWarning(modelformat) << "Invalid accessor type on glTF JOINTS_0 data for model " << _url; + continue; } } else if (key == "WEIGHTS_0") { - QVector weights; - success = addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - weights, - accessor.type, - accessor.componentType); + success = addArrayOfFromAccessor(accessor, weights); if (!success) { qWarning(modelformat) << "There was a problem reading glTF WEIGHTS_0 data for model " << _url; continue; } - for (int n = 0; n < weights.size(); n++) { - clusterWeights.push_back(weights[n]); + + if (accessor.type == GLTFAccessorType::VEC4) { + weight_stride = 4; + } else if (accessor.type == GLTFAccessorType::VEC3) { + weight_stride = 3; + } else if (accessor.type == GLTFAccessorType::VEC2) { + weight_stride = 2; + } else if (accessor.type == GLTFAccessorType::SCALAR) { + weight_stride = 1; + } else { + qWarning(modelformat) << "Invalid accessor type on glTF WEIGHTS_0 data for model " << _url; + continue; } } } - + + // generate the normals if they don't exist + if (normals.size() == 0) { + QVector new_indices; + QVector new_vertices; + QVector new_normals; + QVector new_tangents; + QVector new_texcoords; + QVector new_texcoords2; + QVector new_colors; + QVector new_joints; + QVector new_weights; + + for (int n = 0; n < indices.size(); n = n + 3) { + int v1_index = (indices[n + 0] * 3); + int v2_index = (indices[n + 1] * 3); + int v3_index = (indices[n + 2] * 3); + + glm::vec3 v1 = glm::vec3(vertices[v1_index], vertices[v1_index + 1], vertices[v1_index + 2]); + glm::vec3 v2 = glm::vec3(vertices[v2_index], vertices[v2_index + 1], vertices[v2_index + 2]); + glm::vec3 v3 = glm::vec3(vertices[v3_index], vertices[v3_index + 1], vertices[v3_index + 2]); + + new_vertices.append(v1.x); new_vertices.append(v1.y); new_vertices.append(v1.z); + new_vertices.append(v2.x); new_vertices.append(v2.y); new_vertices.append(v2.z); + new_vertices.append(v3.x); new_vertices.append(v3.y); new_vertices.append(v3.z); + + glm::vec3 norm = glm::normalize(glm::cross(v2 - v1, v3 - v1)); + + new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); + new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); + new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); + + if (tangents.size() > 0) { + if (tangent_stride == 4) { + GLTF_APPEND_ARRAY_4(new_tangents, tangents) + } else { + GLTF_APPEND_ARRAY_3(new_tangents, tangents) + } + } + + if (texcoords.size() > 0) { + GLTF_APPEND_ARRAY_2(new_texcoords, texcoords) + } + + if (texcoords2.size() > 0) { + GLTF_APPEND_ARRAY_2(new_texcoords2, texcoords2) + } + + if (colors.size() > 0) { + if (color_stride == 4) { + GLTF_APPEND_ARRAY_4(new_colors, colors) + } else { + GLTF_APPEND_ARRAY_3(new_colors, colors) + } + } + + if (joints.size() > 0) { + if (joint_stride == 4) { + GLTF_APPEND_ARRAY_4(new_joints, joints) + } else if (joint_stride == 3) { + GLTF_APPEND_ARRAY_3(new_joints, joints) + } else if (joint_stride == 2) { + GLTF_APPEND_ARRAY_2(new_joints, joints) + } else { + GLTF_APPEND_ARRAY_1(new_joints, joints) + } + } + + if (weights.size() > 0) { + if (weight_stride == 4) { + GLTF_APPEND_ARRAY_4(new_weights, weights) + } else if (weight_stride == 3) { + GLTF_APPEND_ARRAY_3(new_weights, weights) + } else if (weight_stride == 2) { + GLTF_APPEND_ARRAY_2(new_weights, weights) + } else { + GLTF_APPEND_ARRAY_1(new_weights, weights) + } + } + + new_indices.append(n); + new_indices.append(n + 1); + new_indices.append(n + 2); + } + + vertices = new_vertices; + normals = new_normals; + tangents = new_tangents; + indices = new_indices; + texcoords = new_texcoords; + texcoords2 = new_texcoords2; + colors = new_colors; + joints = new_joints; + weights = new_weights; + } + + for (int n = 0; n < indices.count(); n++) { + part.triangleIndices.push_back(indices[n] + prevMeshVerticesCount); + } + + for (int n = 0; n < vertices.size(); n = n + 3) { + mesh.vertices.push_back(glm::vec3(vertices[n], vertices[n + 1], vertices[n + 2])); + } + + for (int n = 0; n < normals.size(); n = n + 3) { + mesh.normals.push_back(glm::vec3(normals[n], normals[n + 1], normals[n + 2])); + } + + for (int n = 0; n < tangents.size(); n += tangent_stride) { + float tanW = tangent_stride == 4 ? tangents[n + 3] : 1; + mesh.tangents.push_back(glm::vec3(tanW * tangents[n], tangents[n + 1], tanW * tangents[n + 2])); + } + + for (int n = 0; n < texcoords.size(); n = n + 2) { + mesh.texCoords.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); + } + for (int n = 0; n < texcoords2.size(); n = n + 2) { + mesh.texCoords1.push_back(glm::vec2(texcoords2[n], texcoords2[n + 1])); + } + + for (int n = 0; n < colors.size(); n += color_stride) { + mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); + } + + for (int n = 0; n < joints.size(); n += joint_stride) { + clusterJoints.push_back(joints[n]); + if (joint_stride > 1) { + clusterJoints.push_back(joints[n + 1]); + if (joint_stride > 2) { + clusterJoints.push_back(joints[n + 2]); + if (joint_stride > 3) { + clusterJoints.push_back(joints[n + 3]); + } else { + clusterJoints.push_back(0); + } + } else { + clusterJoints.push_back(0); + clusterJoints.push_back(0); + } + } else { + clusterJoints.push_back(0); + clusterJoints.push_back(0); + clusterJoints.push_back(0); + } + } + + for (int n = 0; n < weights.size(); n += weight_stride) { + clusterWeights.push_back(weights[n]); + if (weight_stride > 1) { + clusterWeights.push_back(weights[n + 1]); + if (weight_stride > 2) { + clusterWeights.push_back(weights[n + 2]); + if (weight_stride > 3) { + clusterWeights.push_back(weights[n + 3]); + } else { + clusterWeights.push_back(0); + } + } else { + clusterWeights.push_back(0); + clusterWeights.push_back(0); + } + } else { + clusterWeights.push_back(0); + clusterWeights.push_back(0); + clusterWeights.push_back(0); + } + } + // Build weights (adapted from FBXSerializer.cpp) if (hfmModel.hasSkeletonJoints) { int numClusterIndices = clusterJoints.size(); @@ -1310,6 +1487,12 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.meshExtents.addPoint(vertex); hfmModel.meshExtents.addPoint(vertex); } + + // Add epsilon to mesh extents to compensate for planar meshes + mesh.meshExtents.minimum -= glm::vec3(EPSILON, EPSILON, EPSILON); + mesh.meshExtents.maximum += glm::vec3(EPSILON, EPSILON, EPSILON); + hfmModel.meshExtents.minimum -= glm::vec3(EPSILON, EPSILON, EPSILON); + hfmModel.meshExtents.maximum += glm::vec3(EPSILON, EPSILON, EPSILON); mesh.meshIndex = hfmModel.meshes.size(); } @@ -1601,7 +1784,74 @@ bool GLTFSerializer::addArrayOfType(const hifi::ByteArray& bin, int byteOffset, return false; } -void GLTFSerializer::retriangulate(const QVector& inIndices, const QVector& in_vertices, +template +bool GLTFSerializer::addArrayOfFromAccessor(GLTFAccessor& accessor, QVector& outarray) { + bool success = true; + + if (accessor.defined["bufferView"]) { + GLTFBufferView& bufferview = _file.bufferviews[accessor.bufferView]; + GLTFBuffer& buffer = _file.buffers[bufferview.buffer]; + + int accBoffset = accessor.defined["byteOffset"] ? accessor.byteOffset : 0; + + success = addArrayOfType(buffer.blob, bufferview.byteOffset + accBoffset, accessor.count, outarray, accessor.type, + accessor.componentType); + } else { + for (int i = 0; i < accessor.count; i++) { + T value; + memset(&value, 0, sizeof(T)); // Make sure the dummy array is initalised to zero. + outarray.push_back(value); + } + } + + if (success) { + if (accessor.defined["sparse"]) { + QVector out_sparse_indices_array; + + GLTFBufferView& sparseIndicesBufferview = _file.bufferviews[accessor.sparse.indices.bufferView]; + GLTFBuffer& sparseIndicesBuffer = _file.buffers[sparseIndicesBufferview.buffer]; + + int accSIBoffset = accessor.sparse.indices.defined["byteOffset"] ? accessor.sparse.indices.byteOffset : 0; + + success = addArrayOfType(sparseIndicesBuffer.blob, sparseIndicesBufferview.byteOffset + accSIBoffset, + accessor.sparse.count, out_sparse_indices_array, GLTFAccessorType::SCALAR, + accessor.sparse.indices.componentType); + if (success) { + QVector out_sparse_values_array; + + GLTFBufferView& sparseValuesBufferview = _file.bufferviews[accessor.sparse.values.bufferView]; + GLTFBuffer& sparseValuesBuffer = _file.buffers[sparseValuesBufferview.buffer]; + + int accSVBoffset = accessor.sparse.values.defined["byteOffset"] ? accessor.sparse.values.byteOffset : 0; + + success = addArrayOfType(sparseValuesBuffer.blob, sparseValuesBufferview.byteOffset + accSVBoffset, + accessor.sparse.count, out_sparse_values_array, accessor.type, accessor.componentType); + + if (success) { + for (int i = 0; i < accessor.sparse.count; i++) { + if ((i * 3) + 2 < out_sparse_values_array.size()) { + if ((out_sparse_indices_array[i] * 3) + 2 < outarray.length()) { + for (int j = 0; j < 3; j++) { + outarray[(out_sparse_indices_array[i] * 3) + j] = out_sparse_values_array[(i * 3) + j]; + } + } else { + success = false; + break; + } + } else { + success = false; + break; + } + } + } + } + } + } + + return success; +} + +void GLTFSerializer::retriangulate(const QVector& inIndices, const QVector& in_vertices, const QVector& in_normals, QVector& outIndices, QVector& out_vertices, QVector& out_normals) { for (int i = 0; i < inIndices.size(); i = i + 3) { @@ -1766,7 +2016,7 @@ void GLTFSerializer::hfmDebugDump(const HFMModel& hfmModel) { qCDebug(modelformat) << "---------------- Joints ----------------"; - foreach(HFMJoint joint, hfmModel.joints) { + foreach (HFMJoint joint, hfmModel.joints) { qCDebug(modelformat) << "\n"; qCDebug(modelformat) << " shapeInfo.avgPoint =" << joint.shapeInfo.avgPoint; qCDebug(modelformat) << " shapeInfo.debugLines =" << joint.shapeInfo.debugLines; diff --git a/libraries/fbx/src/GLTFSerializer.h b/libraries/fbx/src/GLTFSerializer.h index fa5a640fca..e7dc76e084 100755 --- a/libraries/fbx/src/GLTFSerializer.h +++ b/libraries/fbx/src/GLTFSerializer.h @@ -840,6 +840,9 @@ private: bool addArrayOfType(const hifi::ByteArray& bin, int byteOffset, int count, QVector& outarray, int accessorType, int componentType); + template + bool addArrayOfFromAccessor(GLTFAccessor& accessor, QVector& outarray); + void retriangulate(const QVector& in_indices, const QVector& in_vertices, const QVector& in_normals, QVector& out_indices, QVector& out_vertices, QVector& out_normals); From b00e0640c5169efacdef4e230fc0271deaa0d745 Mon Sep 17 00:00:00 2001 From: Saracen Date: Thu, 11 Apr 2019 22:09:36 +0100 Subject: [PATCH 04/58] Convert to camel case, removed unused variable, replace tabs with spaces, remove deprecated normals generation. --- libraries/fbx/src/GLTFSerializer.cpp | 186 +++++++-------------------- 1 file changed, 45 insertions(+), 141 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 78569fa78f..e7b9dd79f7 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -37,27 +37,27 @@ #include "FBXSerializer.h" -#define GLTF_GET_INDICIES(acc_count) int index1 = (indices[n + 0] * acc_count); int index2 = (indices[n + 1] * acc_count); int index3 = (indices[n + 2] * acc_count); +#define GLTF_GET_INDICIES(accCount) int index1 = (indices[n + 0] * accCount); int index2 = (indices[n + 1] * accCount); int index3 = (indices[n + 2] * accCount); -#define GLTF_APPEND_ARRAY_1(new_array, old_array) GLTF_GET_INDICIES(1) \ -new_array.append(old_array[index1]); \ -new_array.append(old_array[index2]); \ -new_array.append(old_array[index3]); +#define GLTF_APPEND_ARRAY_1(newArray, oldArray) GLTF_GET_INDICIES(1) \ +newArray.append(oldArray[index1]); \ +newArray.append(oldArray[index2]); \ +newArray.append(oldArray[index3]); -#define GLTF_APPEND_ARRAY_2(new_array, old_array) GLTF_GET_INDICIES(2) \ -new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); \ -new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); \ -new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); +#define GLTF_APPEND_ARRAY_2(newArray, oldArray) GLTF_GET_INDICIES(2) \ +newArray.append(oldArray[index1]); newArray.append(oldArray[index1 + 1]); \ +newArray.append(oldArray[index2]); newArray.append(oldArray[index2 + 1]); \ +newArray.append(oldArray[index3]); newArray.append(oldArray[index3 + 1]); -#define GLTF_APPEND_ARRAY_3(new_array, old_array) GLTF_GET_INDICIES(3) \ -new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); new_array.append(old_array[index1 + 2]); \ -new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); new_array.append(old_array[index2 + 2]); \ -new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); new_array.append(old_array[index3 + 2]); +#define GLTF_APPEND_ARRAY_3(newArray, oldArray) GLTF_GET_INDICIES(3) \ +newArray.append(oldArray[index1]); newArray.append(oldArray[index1 + 1]); newArray.append(oldArray[index1 + 2]); \ +newArray.append(oldArray[index2]); newArray.append(oldArray[index2 + 1]); newArray.append(oldArray[index2 + 2]); \ +newArray.append(oldArray[index3]); newArray.append(oldArray[index3 + 1]); newArray.append(oldArray[index3 + 2]); -#define GLTF_APPEND_ARRAY_4(new_array, old_array) GLTF_GET_INDICIES(4) \ -new_array.append(old_array[index1]); new_array.append(old_array[index1 + 1]); new_array.append(old_array[index1 + 2]); new_array.append(old_array[index1 + 3]); \ -new_array.append(old_array[index2]); new_array.append(old_array[index2 + 1]); new_array.append(old_array[index2 + 2]); new_array.append(old_array[index2 + 3]); \ -new_array.append(old_array[index3]); new_array.append(old_array[index3 + 1]); new_array.append(old_array[index3 + 2]); new_array.append(old_array[index3 + 3]); +#define GLTF_APPEND_ARRAY_4(newArray, oldArray) GLTF_GET_INDICIES(4) \ +newArray.append(oldArray[index1]); newArray.append(oldArray[index1 + 1]); newArray.append(oldArray[index1 + 2]); newArray.append(oldArray[index1 + 3]); \ +newArray.append(oldArray[index2]); newArray.append(oldArray[index2 + 1]); newArray.append(oldArray[index2 + 2]); newArray.append(oldArray[index2 + 3]); \ +newArray.append(oldArray[index3]); newArray.append(oldArray[index3 + 1]); newArray.append(oldArray[index3 + 2]); newArray.append(oldArray[index3 + 3]); bool GLTFSerializer::getStringVal(const QJsonObject& object, const QString& fieldname, QString& value, QMap& defined) { @@ -997,7 +997,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& hfmModel.materials[matid] = HFMMaterial(); HFMMaterial& hfmMaterial = hfmModel.materials[matid]; hfmMaterial._material = std::make_shared(); - hfmMaterial.name = hfmMaterial.materialID = matid; + hfmMaterial.name = hfmMaterial.materialID = matid; setHFMMaterial(hfmMaterial, _file.materials[i]); } @@ -1044,15 +1044,15 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& QVector vertices; QVector normals; QVector tangents; - int tangent_stride = 0; + int tangentStride = 0; QVector texcoords; QVector texcoords2; QVector colors; - int color_stride = 0; + int colorStride = 0; QVector joints; - int joint_stride = 0; + int jointStride = 0; QVector weights; - int weight_stride = 0; + int weightStride = 0; bool success = addArrayOfFromAccessor(indicesAccessor, indices); @@ -1073,7 +1073,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& GLTFAccessor& accessor = _file.accessors[accessorIdx]; - int accBoffset = accessor.defined["byteOffset"] ? accessor.byteOffset : 0; if (key == "POSITION") { success = addArrayOfFromAccessor(accessor, vertices); if (!success) { @@ -1104,9 +1103,9 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } if (accessor.type == GLTFAccessorType::VEC4) { - tangent_stride = 4; + tangentStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { - tangent_stride = 3; + tangentStride = 3; } else { qWarning(modelformat) << "Invalid accessor type on glTF TANGENT data for model " << _url; continue; @@ -1141,9 +1140,9 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } if (accessor.type == GLTFAccessorType::VEC4) { - color_stride = 4; + colorStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { - color_stride = 3; + colorStride = 3; } else { qWarning(modelformat) << "Invalid accessor type on glTF COLOR_0 data for model " << _url; continue; @@ -1156,13 +1155,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } if (accessor.type == GLTFAccessorType::VEC4) { - joint_stride = 4; + jointStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { - joint_stride = 3; + jointStride = 3; } else if (accessor.type == GLTFAccessorType::VEC2) { - joint_stride = 2; + jointStride = 2; } else if (accessor.type == GLTFAccessorType::SCALAR) { - joint_stride = 1; + jointStride = 1; } else { qWarning(modelformat) << "Invalid accessor type on glTF JOINTS_0 data for model " << _url; continue; @@ -1175,13 +1174,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } if (accessor.type == GLTFAccessorType::VEC4) { - weight_stride = 4; + weightStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { - weight_stride = 3; + weightStride = 3; } else if (accessor.type == GLTFAccessorType::VEC2) { - weight_stride = 2; + weightStride = 2; } else if (accessor.type == GLTFAccessorType::SCALAR) { - weight_stride = 1; + weightStride = 1; } else { qWarning(modelformat) << "Invalid accessor type on glTF WEIGHTS_0 data for model " << _url; continue; @@ -1189,101 +1188,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } - // generate the normals if they don't exist - if (normals.size() == 0) { - QVector new_indices; - QVector new_vertices; - QVector new_normals; - QVector new_tangents; - QVector new_texcoords; - QVector new_texcoords2; - QVector new_colors; - QVector new_joints; - QVector new_weights; - - for (int n = 0; n < indices.size(); n = n + 3) { - int v1_index = (indices[n + 0] * 3); - int v2_index = (indices[n + 1] * 3); - int v3_index = (indices[n + 2] * 3); - - glm::vec3 v1 = glm::vec3(vertices[v1_index], vertices[v1_index + 1], vertices[v1_index + 2]); - glm::vec3 v2 = glm::vec3(vertices[v2_index], vertices[v2_index + 1], vertices[v2_index + 2]); - glm::vec3 v3 = glm::vec3(vertices[v3_index], vertices[v3_index + 1], vertices[v3_index + 2]); - - new_vertices.append(v1.x); new_vertices.append(v1.y); new_vertices.append(v1.z); - new_vertices.append(v2.x); new_vertices.append(v2.y); new_vertices.append(v2.z); - new_vertices.append(v3.x); new_vertices.append(v3.y); new_vertices.append(v3.z); - - glm::vec3 norm = glm::normalize(glm::cross(v2 - v1, v3 - v1)); - - new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); - new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); - new_normals.append(norm.x); new_normals.append(norm.y); new_normals.append(norm.z); - - if (tangents.size() > 0) { - if (tangent_stride == 4) { - GLTF_APPEND_ARRAY_4(new_tangents, tangents) - } else { - GLTF_APPEND_ARRAY_3(new_tangents, tangents) - } - } - - if (texcoords.size() > 0) { - GLTF_APPEND_ARRAY_2(new_texcoords, texcoords) - } - - if (texcoords2.size() > 0) { - GLTF_APPEND_ARRAY_2(new_texcoords2, texcoords2) - } - - if (colors.size() > 0) { - if (color_stride == 4) { - GLTF_APPEND_ARRAY_4(new_colors, colors) - } else { - GLTF_APPEND_ARRAY_3(new_colors, colors) - } - } - - if (joints.size() > 0) { - if (joint_stride == 4) { - GLTF_APPEND_ARRAY_4(new_joints, joints) - } else if (joint_stride == 3) { - GLTF_APPEND_ARRAY_3(new_joints, joints) - } else if (joint_stride == 2) { - GLTF_APPEND_ARRAY_2(new_joints, joints) - } else { - GLTF_APPEND_ARRAY_1(new_joints, joints) - } - } - - if (weights.size() > 0) { - if (weight_stride == 4) { - GLTF_APPEND_ARRAY_4(new_weights, weights) - } else if (weight_stride == 3) { - GLTF_APPEND_ARRAY_3(new_weights, weights) - } else if (weight_stride == 2) { - GLTF_APPEND_ARRAY_2(new_weights, weights) - } else { - GLTF_APPEND_ARRAY_1(new_weights, weights) - } - } - - new_indices.append(n); - new_indices.append(n + 1); - new_indices.append(n + 2); - } - - vertices = new_vertices; - normals = new_normals; - tangents = new_tangents; - indices = new_indices; - texcoords = new_texcoords; - texcoords2 = new_texcoords2; - colors = new_colors; - joints = new_joints; - weights = new_weights; - } - for (int n = 0; n < indices.count(); n++) { part.triangleIndices.push_back(indices[n] + prevMeshVerticesCount); } @@ -1296,8 +1200,8 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.normals.push_back(glm::vec3(normals[n], normals[n + 1], normals[n + 2])); } - for (int n = 0; n < tangents.size(); n += tangent_stride) { - float tanW = tangent_stride == 4 ? tangents[n + 3] : 1; + for (int n = 0; n < tangents.size(); n += tangentStride) { + float tanW = tangentStride == 4 ? tangents[n + 3] : 1; mesh.tangents.push_back(glm::vec3(tanW * tangents[n], tangents[n + 1], tanW * tangents[n + 2])); } @@ -1308,17 +1212,17 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.texCoords1.push_back(glm::vec2(texcoords2[n], texcoords2[n + 1])); } - for (int n = 0; n < colors.size(); n += color_stride) { + for (int n = 0; n < colors.size(); n += colorStride) { mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); } - for (int n = 0; n < joints.size(); n += joint_stride) { + for (int n = 0; n < joints.size(); n += jointStride) { clusterJoints.push_back(joints[n]); - if (joint_stride > 1) { + if (jointStride > 1) { clusterJoints.push_back(joints[n + 1]); - if (joint_stride > 2) { + if (jointStride > 2) { clusterJoints.push_back(joints[n + 2]); - if (joint_stride > 3) { + if (jointStride > 3) { clusterJoints.push_back(joints[n + 3]); } else { clusterJoints.push_back(0); @@ -1334,13 +1238,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } - for (int n = 0; n < weights.size(); n += weight_stride) { + for (int n = 0; n < weights.size(); n += weightStride) { clusterWeights.push_back(weights[n]); - if (weight_stride > 1) { + if (weightStride > 1) { clusterWeights.push_back(weights[n + 1]); - if (weight_stride > 2) { + if (weightStride > 2) { clusterWeights.push_back(weights[n + 2]); - if (weight_stride > 3) { + if (weightStride > 3) { clusterWeights.push_back(weights[n + 3]); } else { clusterWeights.push_back(0); From a1279fa0b16b1b608450aec074477e69b0ccf492 Mon Sep 17 00:00:00 2001 From: Saracen Date: Mon, 22 Apr 2019 21:10:12 +0100 Subject: [PATCH 05/58] Fixed requested indentation issues. # Conflicts: # libraries/fbx/src/GLTFSerializer.cpp --- libraries/fbx/src/GLTFSerializer.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index e7b9dd79f7..3f569a3c3e 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -872,7 +872,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // collect transforms for a node's parents, grandparents, etc. _file.nodes[nodecount].transforms.push_back(getModelTransform(parentNode)); parentIndex = parents[parentIndex]; - } + } nodecount++; } @@ -900,10 +900,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& sortedNodes[j] = currentNode; i++; currentNode = sortedNodes[i]; - } + } j++; - } - } + } + } } @@ -931,7 +931,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& joint.translation = extractTranslation(joint.transform); joint.rotation = glmExtractRotation(joint.transform); glm::vec3 scale = extractScale(joint.transform); - joint.postTransform = glm::scale(glm::mat4(), scale); + joint.postTransform = glm::scale(glm::mat4(), scale); joint.name = node.name; joint.isSkeletonJoint = false; @@ -982,7 +982,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& QString unknown = "Default"; int ukcount = 0; foreach(auto material, _file.materials) { - if (!(material.defined["name"])) { + if (!material.defined["name"]) { QString name = unknown + QString::number(ukcount++); material.name = name; material.defined.insert("name", true); @@ -1017,8 +1017,8 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& cluster.inverseBindMatrix = glm::mat4(); cluster.inverseBindTransform = Transform(cluster.inverseBindMatrix); mesh.clusters.append(cluster); - } else { // skinned model - for (int j = 0; j < numNodes; j++) { + } else { // skinned model + for (int j = 0; j < numNodes; j++) { HFMCluster cluster; cluster.jointIndex = j; cluster.inverseBindMatrix = jointInverseBindTransforms[j]; @@ -1026,7 +1026,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& mesh.clusters.append(cluster); } } - HFMCluster root; + HFMCluster root; root.jointIndex = 0; root.inverseBindMatrix = jointInverseBindTransforms[root.jointIndex]; root.inverseBindTransform = Transform(root.inverseBindMatrix); From 9b7df26d9195ff00b5fb7dd6b961284e6ea594ba Mon Sep 17 00:00:00 2001 From: Saracen Date: Sat, 27 Apr 2019 11:20:09 +0100 Subject: [PATCH 06/58] Fixed cluster weighting regression. --- libraries/fbx/src/GLTFSerializer.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 3f569a3c3e..7c13d58968 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -1262,15 +1262,20 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Build weights (adapted from FBXSerializer.cpp) if (hfmModel.hasSkeletonJoints) { - int numClusterIndices = clusterJoints.size(); + int prevMeshClusterIndexCount = mesh.clusterIndices.count(); + int prevMeshClusterWeightCount = mesh.clusterWeights.count(); const int WEIGHTS_PER_VERTEX = 4; const float ALMOST_HALF = 0.499f; - int numVertices = mesh.vertices.size(); - mesh.clusterIndices.fill(mesh.clusters.size() - 1, numClusterIndices); - mesh.clusterWeights.fill(0, numClusterIndices); + int numVertices = mesh.vertices.size() - prevMeshVerticesCount; + + // Append new cluster indices and weights for this mesh part + for (int i = 0; i < numVertices * WEIGHTS_PER_VERTEX; i++) { + mesh.clusterIndices.push_back(mesh.clusters.size() - 1); + mesh.clusterWeights.push_back(0); + } for (int c = 0; c < clusterJoints.size(); c++) { - mesh.clusterIndices[c] = originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; + mesh.clusterIndices[prevMeshClusterIndexCount+c] = originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; } // normalize and compress to 16-bits @@ -1284,10 +1289,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& if (totalWeight > 0.0f) { float weightScalingFactor = (float)(UINT16_MAX) / totalWeight; for (int k = j; k < j + WEIGHTS_PER_VERTEX; ++k) { - mesh.clusterWeights[k] = (uint16_t)(weightScalingFactor * clusterWeights[k] + ALMOST_HALF); + mesh.clusterWeights[prevMeshClusterWeightCount+k] = (uint16_t)(weightScalingFactor * clusterWeights[k] + ALMOST_HALF); } } else { - mesh.clusterWeights[j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); + mesh.clusterWeights[prevMeshClusterWeightCount+j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); } } } From 0bf216ab730c91fcc98bd02cf5e0db9f6aec11dc Mon Sep 17 00:00:00 2001 From: Saracen Date: Sat, 27 Apr 2019 12:42:37 +0100 Subject: [PATCH 07/58] Sparse accessors support for skin inverse bind matrices and shapekey target data. --- libraries/fbx/src/GLTFSerializer.cpp | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 7c13d58968..f5cc9ff03c 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -812,32 +812,16 @@ glm::mat4 GLTFSerializer::getModelTransform(const GLTFNode& node) { void GLTFSerializer::getSkinInverseBindMatrices(std::vector>& inverseBindMatrixValues) { for (auto &skin : _file.skins) { GLTFAccessor& indicesAccessor = _file.accessors[skin.inverseBindMatrices]; - GLTFBufferView& indicesBufferview = _file.bufferviews[indicesAccessor.bufferView]; - GLTFBuffer& indicesBuffer = _file.buffers[indicesBufferview.buffer]; - int accBoffset = indicesAccessor.defined["byteOffset"] ? indicesAccessor.byteOffset : 0; QVector matrices; - addArrayOfType(indicesBuffer.blob, - indicesBufferview.byteOffset + accBoffset, - indicesAccessor.count, - matrices, - indicesAccessor.type, - indicesAccessor.componentType); + addArrayOfFromAccessor(indicesAccessor, matrices); inverseBindMatrixValues.push_back(matrices.toStdVector()); } } void GLTFSerializer::generateTargetData(int index, float weight, QVector& returnVector) { GLTFAccessor& accessor = _file.accessors[index]; - GLTFBufferView& bufferview = _file.bufferviews[accessor.bufferView]; - GLTFBuffer& buffer = _file.buffers[bufferview.buffer]; - int accBoffset = accessor.defined["byteOffset"] ? accessor.byteOffset : 0; QVector storedValues; - addArrayOfType(buffer.blob, - bufferview.byteOffset + accBoffset, - accessor.count, - storedValues, - accessor.type, - accessor.componentType); + addArrayOfFromAccessor(accessor, storedValues); for (int n = 0; n < storedValues.size(); n = n + 3) { returnVector.push_back(glm::vec3(weight * storedValues[n], weight * storedValues[n + 1], weight * storedValues[n + 2])); } From 95ec51e37bb27b6d273433bb32f149285ac150d1 Mon Sep 17 00:00:00 2001 From: Saracen Date: Mon, 29 Apr 2019 20:35:38 +0100 Subject: [PATCH 08/58] Formatting and naming changes. Tweak to structure of skinning code. --- libraries/fbx/src/GLTFSerializer.cpp | 49 ++++++++++++++-------------- libraries/fbx/src/GLTFSerializer.h | 2 +- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index f5cc9ff03c..99211fb6fa 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -813,7 +813,7 @@ void GLTFSerializer::getSkinInverseBindMatrices(std::vector>& for (auto &skin : _file.skins) { GLTFAccessor& indicesAccessor = _file.accessors[skin.inverseBindMatrices]; QVector matrices; - addArrayOfFromAccessor(indicesAccessor, matrices); + addArrayFromAccessor(indicesAccessor, matrices); inverseBindMatrixValues.push_back(matrices.toStdVector()); } } @@ -821,7 +821,7 @@ void GLTFSerializer::getSkinInverseBindMatrices(std::vector>& void GLTFSerializer::generateTargetData(int index, float weight, QVector& returnVector) { GLTFAccessor& accessor = _file.accessors[index]; QVector storedValues; - addArrayOfFromAccessor(accessor, storedValues); + addArrayFromAccessor(accessor, storedValues); for (int n = 0; n < storedValues.size(); n = n + 3) { returnVector.push_back(glm::vec3(weight * storedValues[n], weight * storedValues[n + 1], weight * storedValues[n + 2])); } @@ -849,7 +849,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& nodecount = 0; foreach(auto &node, _file.nodes) { // collect node transform - _file.nodes[nodecount].transforms.push_back(getModelTransform(node)); + _file.nodes[nodecount].transforms.push_back(getModelTransform(node)); int parentIndex = parents[nodecount]; while (parentIndex != -1) { const auto& parentNode = _file.nodes[parentIndex]; @@ -1038,7 +1038,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& QVector weights; int weightStride = 0; - bool success = addArrayOfFromAccessor(indicesAccessor, indices); + bool success = addArrayFromAccessor(indicesAccessor, indices); if (!success) { qWarning(modelformat) << "There was a problem reading glTF INDICES data for model " << _url; @@ -1058,7 +1058,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& GLTFAccessor& accessor = _file.accessors[accessorIdx]; if (key == "POSITION") { - success = addArrayOfFromAccessor(accessor, vertices); + success = addArrayFromAccessor(accessor, vertices); if (!success) { qWarning(modelformat) << "There was a problem reading glTF POSITION data for model " << _url; continue; @@ -1069,7 +1069,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "NORMAL") { - success = addArrayOfFromAccessor(accessor, normals); + success = addArrayFromAccessor(accessor, normals); if (!success) { qWarning(modelformat) << "There was a problem reading glTF NORMAL data for model " << _url; continue; @@ -1080,7 +1080,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "TANGENT") { - success = addArrayOfFromAccessor(accessor, tangents); + success = addArrayFromAccessor(accessor, tangents); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TANGENT data for model " << _url; continue; @@ -1095,7 +1095,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "TEXCOORD_0") { - success = addArrayOfFromAccessor(accessor, texcoords); + success = addArrayFromAccessor(accessor, texcoords); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TEXCOORD_0 data for model " << _url; continue; @@ -1106,7 +1106,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "TEXCOORD_1") { - success = addArrayOfFromAccessor(accessor, texcoords2); + success = addArrayFromAccessor(accessor, texcoords2); if (!success) { qWarning(modelformat) << "There was a problem reading glTF TEXCOORD_1 data for model " << _url; continue; @@ -1117,7 +1117,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "COLOR_0") { - success = addArrayOfFromAccessor(accessor, colors); + success = addArrayFromAccessor(accessor, colors); if (!success) { qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; continue; @@ -1132,7 +1132,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "JOINTS_0") { - success = addArrayOfFromAccessor(accessor, joints); + success = addArrayFromAccessor(accessor, joints); if (!success) { qWarning(modelformat) << "There was a problem reading glTF JOINTS_0 data for model " << _url; continue; @@ -1151,7 +1151,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "WEIGHTS_0") { - success = addArrayOfFromAccessor(accessor, weights); + success = addArrayFromAccessor(accessor, weights); if (!success) { qWarning(modelformat) << "There was a problem reading glTF WEIGHTS_0 data for model " << _url; continue; @@ -1252,15 +1252,10 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& const float ALMOST_HALF = 0.499f; int numVertices = mesh.vertices.size() - prevMeshVerticesCount; - // Append new cluster indices and weights for this mesh part - for (int i = 0; i < numVertices * WEIGHTS_PER_VERTEX; i++) { - mesh.clusterIndices.push_back(mesh.clusters.size() - 1); - mesh.clusterWeights.push_back(0); - } - - for (int c = 0; c < clusterJoints.size(); c++) { - mesh.clusterIndices[prevMeshClusterIndexCount+c] = originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; - } + mesh.clusterIndices.resize(mesh.clusterIndices.size() + + numVertices * WEIGHTS_PER_VERTEX); + mesh.clusterWeights.resize(mesh.clusterWeights.size() + + numVertices * WEIGHTS_PER_VERTEX); // normalize and compress to 16-bits for (int i = 0; i < numVertices; ++i) { @@ -1268,15 +1263,21 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& float totalWeight = 0.0f; for (int k = j; k < j + WEIGHTS_PER_VERTEX; ++k) { + mesh.clusterIndices[prevMeshClusterIndexCount + k] = + originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[k]]]; + totalWeight += clusterWeights[k]; } if (totalWeight > 0.0f) { float weightScalingFactor = (float)(UINT16_MAX) / totalWeight; for (int k = j; k < j + WEIGHTS_PER_VERTEX; ++k) { - mesh.clusterWeights[prevMeshClusterWeightCount+k] = (uint16_t)(weightScalingFactor * clusterWeights[k] + ALMOST_HALF); + mesh.clusterWeights[prevMeshClusterWeightCount + k] = (uint16_t)(weightScalingFactor * clusterWeights[k] + ALMOST_HALF); } } else { - mesh.clusterWeights[prevMeshClusterWeightCount+j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); + mesh.clusterWeights[prevMeshClusterWeightCount + j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); + for (int k = j + 1; k < j + WEIGHTS_PER_VERTEX; ++k) { + mesh.clusterWeights[prevMeshClusterWeightCount + k] = 0; + } } } } @@ -1678,7 +1679,7 @@ bool GLTFSerializer::addArrayOfType(const hifi::ByteArray& bin, int byteOffset, } template -bool GLTFSerializer::addArrayOfFromAccessor(GLTFAccessor& accessor, QVector& outarray) { +bool GLTFSerializer::addArrayFromAccessor(GLTFAccessor& accessor, QVector& outarray) { bool success = true; if (accessor.defined["bufferView"]) { diff --git a/libraries/fbx/src/GLTFSerializer.h b/libraries/fbx/src/GLTFSerializer.h index e7dc76e084..4d72805863 100755 --- a/libraries/fbx/src/GLTFSerializer.h +++ b/libraries/fbx/src/GLTFSerializer.h @@ -841,7 +841,7 @@ private: QVector& outarray, int accessorType, int componentType); template - bool addArrayOfFromAccessor(GLTFAccessor& accessor, QVector& outarray); + bool addArrayFromAccessor(GLTFAccessor& accessor, QVector& outarray); void retriangulate(const QVector& in_indices, const QVector& in_vertices, const QVector& in_normals, QVector& out_indices, From a07507430335e47755dc5c1919350eb66f02c5ba Mon Sep 17 00:00:00 2001 From: Saracen Date: Mon, 29 Apr 2019 21:26:13 +0100 Subject: [PATCH 09/58] Revert to previous clusterIndices and clusterWeight expansion implementation. --- libraries/fbx/src/GLTFSerializer.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 99211fb6fa..85e55f226b 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -1252,10 +1252,16 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& const float ALMOST_HALF = 0.499f; int numVertices = mesh.vertices.size() - prevMeshVerticesCount; - mesh.clusterIndices.resize(mesh.clusterIndices.size() - + numVertices * WEIGHTS_PER_VERTEX); - mesh.clusterWeights.resize(mesh.clusterWeights.size() - + numVertices * WEIGHTS_PER_VERTEX); + // Append new cluster indices and weights for this mesh part + for (int i = 0; i < numVertices * WEIGHTS_PER_VERTEX; i++) { + mesh.clusterIndices.push_back(mesh.clusters.size() - 1); + mesh.clusterWeights.push_back(0); + } + + for (int c = 0; c < clusterJoints.size(); c++) { + mesh.clusterIndices[prevMeshClusterIndexCount + c] = + originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[c]]]; + } // normalize and compress to 16-bits for (int i = 0; i < numVertices; ++i) { @@ -1263,9 +1269,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& float totalWeight = 0.0f; for (int k = j; k < j + WEIGHTS_PER_VERTEX; ++k) { - mesh.clusterIndices[prevMeshClusterIndexCount + k] = - originalToNewNodeIndexMap[_file.skins[node.skin].joints[clusterJoints[k]]]; - totalWeight += clusterWeights[k]; } if (totalWeight > 0.0f) { @@ -1275,9 +1278,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } else { mesh.clusterWeights[prevMeshClusterWeightCount + j] = (uint16_t)((float)(UINT16_MAX) + ALMOST_HALF); - for (int k = j + 1; k < j + WEIGHTS_PER_VERTEX; ++k) { - mesh.clusterWeights[prevMeshClusterWeightCount + k] = 0; - } } } } From f09f6ebd0853e3e2fe4cc645d60f36e571f83beb Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Thu, 2 May 2019 15:50:35 -0700 Subject: [PATCH 10/58] 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 11/58] 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 8273e5b666def4389ce75a52a5de857ac693a988 Mon Sep 17 00:00:00 2001 From: amer cerkic Date: Mon, 6 May 2019 12:27:46 -0700 Subject: [PATCH 12/58] 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/58] 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/58] 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 0d97543ece6212f6fc386fc8faf1d9cd0e406bed Mon Sep 17 00:00:00 2001 From: amerhifi Date: Thu, 9 May 2019 12:04:41 -0700 Subject: [PATCH 15/58] 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 16/58] 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 17/58] 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 18/58] 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 19/58] 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 20/58] 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 21/58] 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 22/58] 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 23/58] 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 7987ed14b09bf219f692e4677ccd2208c58ec26d Mon Sep 17 00:00:00 2001 From: Saracen Date: Sat, 11 May 2019 04:30:14 +0100 Subject: [PATCH 24/58] Fix mismatched meshpart attributes (generates dummy buffers), re-added normals generation routine, buffer size checks, detect out-of-range indices, --- libraries/fbx/src/GLTFSerializer.cpp | 340 +++++++++++++++++++++------ 1 file changed, 267 insertions(+), 73 deletions(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index 85e55f226b..b06b8f1822 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -1016,6 +1016,16 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& root.inverseBindTransform = Transform(root.inverseBindMatrix); mesh.clusters.append(root); + QList meshAttributes; + foreach(auto &primitive, _file.meshes[node.mesh].primitives) { + QList keys = primitive.attributes.values.keys(); + foreach (auto &key, keys) { + if (!meshAttributes.contains(key)) { + meshAttributes.push_back(key); + } + } + } + foreach(auto &primitive, _file.meshes[node.mesh].primitives) { HFMMeshPart part = HFMMeshPart(); @@ -1026,17 +1036,21 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& // Buffers QVector indices; QVector vertices; + int verticesStride = 3; QVector normals; + int normalStride = 3; QVector tangents; - int tangentStride = 0; + int tangentStride = 4; QVector texcoords; + int texCoordStride = 2; QVector texcoords2; + int texCoord2Stride = 2; QVector colors; - int colorStride = 0; + int colorStride = 3; QVector joints; - int jointStride = 0; + int jointStride = 4; QVector weights; - int weightStride = 0; + int weightStride = 4; bool success = addArrayFromAccessor(indicesAccessor, indices); @@ -1058,34 +1072,28 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& GLTFAccessor& accessor = _file.accessors[accessorIdx]; if (key == "POSITION") { + if (accessor.type != GLTFAccessorType::VEC3) { + qWarning(modelformat) << "Invalid accessor type on glTF POSITION data for model " << _url; + continue; + } + success = addArrayFromAccessor(accessor, vertices); if (!success) { qWarning(modelformat) << "There was a problem reading glTF POSITION data for model " << _url; continue; } - + } else if (key == "NORMAL") { if (accessor.type != GLTFAccessorType::VEC3) { - qWarning(modelformat) << "Invalid accessor type on glTF POSITION data for model " << _url; + qWarning(modelformat) << "Invalid accessor type on glTF NORMAL data for model " << _url; continue; } - } else if (key == "NORMAL") { + success = addArrayFromAccessor(accessor, normals); if (!success) { qWarning(modelformat) << "There was a problem reading glTF NORMAL data for model " << _url; continue; } - - if (accessor.type != GLTFAccessorType::VEC3) { - qWarning(modelformat) << "Invalid accessor type on glTF NORMAL data for model " << _url; - continue; - } } else if (key == "TANGENT") { - success = addArrayFromAccessor(accessor, tangents); - if (!success) { - qWarning(modelformat) << "There was a problem reading glTF TANGENT data for model " << _url; - continue; - } - if (accessor.type == GLTFAccessorType::VEC4) { tangentStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { @@ -1094,6 +1102,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "Invalid accessor type on glTF TANGENT data for model " << _url; continue; } + + success = addArrayFromAccessor(accessor, tangents); + if (!success) { + qWarning(modelformat) << "There was a problem reading glTF TANGENT data for model " << _url; + tangentStride = 0; + continue; + } } else if (key == "TEXCOORD_0") { success = addArrayFromAccessor(accessor, texcoords); if (!success) { @@ -1117,12 +1132,6 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& continue; } } else if (key == "COLOR_0") { - success = addArrayFromAccessor(accessor, colors); - if (!success) { - qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; - continue; - } - if (accessor.type == GLTFAccessorType::VEC4) { colorStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { @@ -1131,13 +1140,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "Invalid accessor type on glTF COLOR_0 data for model " << _url; continue; } - } else if (key == "JOINTS_0") { - success = addArrayFromAccessor(accessor, joints); + + success = addArrayFromAccessor(accessor, colors); if (!success) { - qWarning(modelformat) << "There was a problem reading glTF JOINTS_0 data for model " << _url; + qWarning(modelformat) << "There was a problem reading glTF COLOR_0 data for model " << _url; continue; } - + } else if (key == "JOINTS_0") { if (accessor.type == GLTFAccessorType::VEC4) { jointStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { @@ -1150,13 +1159,13 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "Invalid accessor type on glTF JOINTS_0 data for model " << _url; continue; } - } else if (key == "WEIGHTS_0") { - success = addArrayFromAccessor(accessor, weights); + + success = addArrayFromAccessor(accessor, joints); if (!success) { - qWarning(modelformat) << "There was a problem reading glTF WEIGHTS_0 data for model " << _url; + qWarning(modelformat) << "There was a problem reading glTF JOINTS_0 data for model " << _url; continue; } - + } else if (key == "WEIGHTS_0") { if (accessor.type == GLTFAccessorType::VEC4) { weightStride = 4; } else if (accessor.type == GLTFAccessorType::VEC3) { @@ -1169,78 +1178,263 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& qWarning(modelformat) << "Invalid accessor type on glTF WEIGHTS_0 data for model " << _url; continue; } + + success = addArrayFromAccessor(accessor, weights); + if (!success) { + qWarning(modelformat) << "There was a problem reading glTF WEIGHTS_0 data for model " << _url; + continue; + } } } - for (int n = 0; n < indices.count(); n++) { - part.triangleIndices.push_back(indices[n] + prevMeshVerticesCount); + // Validation stage + if (indices.count() == 0) { + qWarning(modelformat) << "Missing indices for model " << _url; + continue; + } + if (vertices.count() == 0) { + qWarning(modelformat) << "Missing vertices for model " << _url; + continue; } - for (int n = 0; n < vertices.size(); n = n + 3) { + int partVerticesCount = vertices.size() / 3; + + // generate the normals if they don't exist + if (normals.size() == 0) { + QVector newIndices; + QVector newVertices; + QVector newNormals; + QVector newTexcoords; + QVector newTexcoords2; + QVector newColors; + QVector newJoints; + QVector newWeights; + + for (int n = 0; n < indices.size(); n = n + 3) { + int v1_index = (indices[n + 0] * 3); + int v2_index = (indices[n + 1] * 3); + int v3_index = (indices[n + 2] * 3); + + glm::vec3 v1 = glm::vec3(vertices[v1_index], vertices[v1_index + 1], vertices[v1_index + 2]); + glm::vec3 v2 = glm::vec3(vertices[v2_index], vertices[v2_index + 1], vertices[v2_index + 2]); + glm::vec3 v3 = glm::vec3(vertices[v3_index], vertices[v3_index + 1], vertices[v3_index + 2]); + + newVertices.append(v1.x); + newVertices.append(v1.y); + newVertices.append(v1.z); + newVertices.append(v2.x); + newVertices.append(v2.y); + newVertices.append(v2.z); + newVertices.append(v3.x); + newVertices.append(v3.y); + newVertices.append(v3.z); + + glm::vec3 norm = glm::normalize(glm::cross(v2 - v1, v3 - v1)); + + newNormals.append(norm.x); + newNormals.append(norm.y); + newNormals.append(norm.z); + newNormals.append(norm.x); + newNormals.append(norm.y); + newNormals.append(norm.z); + newNormals.append(norm.x); + newNormals.append(norm.y); + newNormals.append(norm.z); + + if (texcoords.size() == partVerticesCount * texCoordStride) { + GLTF_APPEND_ARRAY_2(newTexcoords, texcoords) + } + + if (texcoords2.size() == partVerticesCount * texCoord2Stride) { + GLTF_APPEND_ARRAY_2(newTexcoords2, texcoords2) + } + + if (colors.size() == partVerticesCount * colorStride) { + if (colorStride == 4) { + GLTF_APPEND_ARRAY_4(newColors, colors) + } else { + GLTF_APPEND_ARRAY_3(newColors, colors) + } + } + + if (joints.size() == partVerticesCount * jointStride) { + if (jointStride == 4) { + GLTF_APPEND_ARRAY_4(newJoints, joints) + } else if (jointStride == 3) { + GLTF_APPEND_ARRAY_3(newJoints, joints) + } else if (jointStride == 2) { + GLTF_APPEND_ARRAY_2(newJoints, joints) + } else { + GLTF_APPEND_ARRAY_1(newJoints, joints) + } + } + + if (weights.size() == partVerticesCount * weightStride) { + if (weightStride == 4) { + GLTF_APPEND_ARRAY_4(newWeights, weights) + } else if (weightStride == 3) { + GLTF_APPEND_ARRAY_3(newWeights, weights) + } else if (weightStride == 2) { + GLTF_APPEND_ARRAY_2(newWeights, weights) + } else { + GLTF_APPEND_ARRAY_1(newWeights, weights) + } + } + newIndices.append(n); + newIndices.append(n + 1); + newIndices.append(n + 2); + } + + vertices = newVertices; + normals = newNormals; + tangents = QVector(); + texcoords = newTexcoords; + texcoords2 = newTexcoords2; + colors = newColors; + joints = newJoints; + weights = newWeights; + indices = newIndices; + + partVerticesCount = vertices.size() / 3; + } + + QVector validatedIndices; + for (int n = 0; n < indices.count(); n++) { + if (indices[n] < partVerticesCount) { + validatedIndices.push_back(indices[n] + prevMeshVerticesCount); + } else { + validatedIndices = QVector(); + break; + } + } + + if (validatedIndices.size() == 0) { + qWarning(modelformat) << "Indices out of range for model " << _url; + continue; + } + + part.triangleIndices.append(validatedIndices); + + for (int n = 0; n < vertices.size(); n = n + verticesStride) { mesh.vertices.push_back(glm::vec3(vertices[n], vertices[n + 1], vertices[n + 2])); } - for (int n = 0; n < normals.size(); n = n + 3) { + for (int n = 0; n < normals.size(); n = n + normalStride) { mesh.normals.push_back(glm::vec3(normals[n], normals[n + 1], normals[n + 2])); } - for (int n = 0; n < tangents.size(); n += tangentStride) { - float tanW = tangentStride == 4 ? tangents[n + 3] : 1; - mesh.tangents.push_back(glm::vec3(tanW * tangents[n], tangents[n + 1], tanW * tangents[n + 2])); + // TODO: add correct tangent generation + if (tangents.size() == partVerticesCount * tangentStride) { + for (int n = 0; n < tangents.size(); n += tangentStride) { + float tanW = tangentStride == 4 ? tangents[n + 3] : 1; + mesh.tangents.push_back(glm::vec3(tanW * tangents[n], tangents[n + 1], tanW * tangents[n + 2])); + } + } else { + if (meshAttributes.contains("TANGENT")) { + for (int i = 0; i < partVerticesCount; i++) { + mesh.tangents.push_back(glm::vec3(0.0f, 0.0f, 0.0f)); + } + } } - for (int n = 0; n < texcoords.size(); n = n + 2) { - mesh.texCoords.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); - } - for (int n = 0; n < texcoords2.size(); n = n + 2) { - mesh.texCoords1.push_back(glm::vec2(texcoords2[n], texcoords2[n + 1])); + if (texcoords.size() == partVerticesCount * texCoordStride) { + for (int n = 0; n < texcoords.size(); n = n + 2) { + mesh.texCoords.push_back(glm::vec2(texcoords[n], texcoords[n + 1])); + } + } else { + if (meshAttributes.contains("TEXCOORD_0")) { + for (int i = 0; i < partVerticesCount; i++) { + mesh.texCoords.push_back(glm::vec2(0.0f, 0.0f)); + } + } } - for (int n = 0; n < colors.size(); n += colorStride) { - mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); + if (texcoords.size() == partVerticesCount * texCoord2Stride) { + for (int n = 0; n < texcoords2.size(); n = n + 2) { + mesh.texCoords1.push_back(glm::vec2(texcoords2[n], texcoords2[n + 1])); + } + } else { + if (meshAttributes.contains("TEXCOORD_1")) { + for (int i = 0; i < partVerticesCount; i++) { + mesh.texCoords1.push_back(glm::vec2(0.0f, 0.0f)); + } + } } - for (int n = 0; n < joints.size(); n += jointStride) { - clusterJoints.push_back(joints[n]); - if (jointStride > 1) { - clusterJoints.push_back(joints[n + 1]); - if (jointStride > 2) { - clusterJoints.push_back(joints[n + 2]); - if (jointStride > 3) { - clusterJoints.push_back(joints[n + 3]); + if (colors.size() == partVerticesCount * colorStride) { + for (int n = 0; n < colors.size(); n += colorStride) { + mesh.colors.push_back(glm::vec3(colors[n], colors[n + 1], colors[n + 2])); + } + } else { + if (meshAttributes.contains("COLOR_0")) { + for (int i = 0; i < partVerticesCount; i++) { + mesh.colors.push_back(glm::vec3(1.0f, 1.0f, 1.0f)); + } + } + } + + if (joints.size() == partVerticesCount * jointStride) { + for (int n = 0; n < joints.size(); n += jointStride) { + clusterJoints.push_back(joints[n]); + if (jointStride > 1) { + clusterJoints.push_back(joints[n + 1]); + if (jointStride > 2) { + clusterJoints.push_back(joints[n + 2]); + if (jointStride > 3) { + clusterJoints.push_back(joints[n + 3]); + } else { + clusterJoints.push_back(0); + } } else { clusterJoints.push_back(0); + clusterJoints.push_back(0); } } else { clusterJoints.push_back(0); clusterJoints.push_back(0); + clusterJoints.push_back(0); + } + } + } else { + if (meshAttributes.contains("JOINTS_0")) { + for (int i = 0; i < partVerticesCount; i++) { + for (int j = 0; j < 4; j++) { + clusterJoints.push_back(0); + } } - } else { - clusterJoints.push_back(0); - clusterJoints.push_back(0); - clusterJoints.push_back(0); } } - for (int n = 0; n < weights.size(); n += weightStride) { - clusterWeights.push_back(weights[n]); - if (weightStride > 1) { - clusterWeights.push_back(weights[n + 1]); - if (weightStride > 2) { - clusterWeights.push_back(weights[n + 2]); - if (weightStride > 3) { - clusterWeights.push_back(weights[n + 3]); + if (weights.size() == partVerticesCount * weightStride) { + for (int n = 0; n < weights.size(); n += weightStride) { + clusterWeights.push_back(weights[n]); + if (weightStride > 1) { + clusterWeights.push_back(weights[n + 1]); + if (weightStride > 2) { + clusterWeights.push_back(weights[n + 2]); + if (weightStride > 3) { + clusterWeights.push_back(weights[n + 3]); + } else { + clusterWeights.push_back(0.0f); + } } else { - clusterWeights.push_back(0); + clusterWeights.push_back(0.0f); + clusterWeights.push_back(0.0f); } } else { - clusterWeights.push_back(0); - clusterWeights.push_back(0); + clusterWeights.push_back(0.0f); + clusterWeights.push_back(0.0f); + clusterWeights.push_back(0.0f); + } + } + } else { + if (meshAttributes.contains("WEIGHTS_0")) { + for (int i = 0; i < partVerticesCount; i++) { + clusterWeights.push_back(1.0f); + for (int j = 1; j < 4; j++) { + clusterWeights.push_back(0.0f); + } } - } else { - clusterWeights.push_back(0); - clusterWeights.push_back(0); - clusterWeights.push_back(0); } } From 13c9bb078c582bcaac2e6bd93de25754c40c045f Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 06:50:08 -0700 Subject: [PATCH 25/58] 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/58] 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/58] 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 9aadea81b3419dc6590ab8ad74e6f6ac39364e06 Mon Sep 17 00:00:00 2001 From: Saracen Date: Mon, 13 May 2019 19:13:24 +0100 Subject: [PATCH 28/58] Fix to use correct texcoord2 array. --- libraries/fbx/src/GLTFSerializer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/fbx/src/GLTFSerializer.cpp b/libraries/fbx/src/GLTFSerializer.cpp index b06b8f1822..7650cf04f6 100755 --- a/libraries/fbx/src/GLTFSerializer.cpp +++ b/libraries/fbx/src/GLTFSerializer.cpp @@ -1349,7 +1349,7 @@ bool GLTFSerializer::buildGeometry(HFMModel& hfmModel, const hifi::VariantHash& } } - if (texcoords.size() == partVerticesCount * texCoord2Stride) { + if (texcoords2.size() == partVerticesCount * texCoord2Stride) { for (int n = 0; n < texcoords2.size(); n = n + 2) { mesh.texCoords1.push_back(glm::vec2(texcoords2[n], texcoords2[n + 1])); } From 8759f028f8adc1a3bcfae97658b9f17a9fadeacd Mon Sep 17 00:00:00 2001 From: amerhifi Date: Mon, 13 May 2019 11:41:30 -0700 Subject: [PATCH 29/58] 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 30/58] 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 31/58] 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 32/58] 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 33/58] 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 34/58] 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 35/58] 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 36/58] 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 37/58] 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 a12685c74b0f7251243dc10d21f38da895b58f4e Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 13:01:15 -0700 Subject: [PATCH 38/58] 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/58] 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/58] 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/58] 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 2f380b3669a70dce58e3b35b029aa7258465e479 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 14 May 2019 17:58:32 -0700 Subject: [PATCH 42/58] Detailing the info from the refresh rate --- .../src/display-plugins/RefreshRateController.cpp | 4 +++- .../src/display-plugins/RefreshRateController.h | 2 +- libraries/plugins/src/plugins/DisplayPlugin.h | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/display-plugins/src/display-plugins/RefreshRateController.cpp b/libraries/display-plugins/src/display-plugins/RefreshRateController.cpp index 2d9b553163..369c3cdb26 100644 --- a/libraries/display-plugins/src/display-plugins/RefreshRateController.cpp +++ b/libraries/display-plugins/src/display-plugins/RefreshRateController.cpp @@ -30,7 +30,7 @@ int RefreshRateController::getRefreshRateLimitPeriod() const { return durationNanosecondsToHz(_refreshRateLimitPeriod); } -void RefreshRateController::sleepThreadIfNeeded(QThread* thread, bool isHmd) { +std::chrono::nanoseconds RefreshRateController::sleepThreadIfNeeded(QThread* thread, bool isHmd) { if (!isHmd) { static const std::chrono::nanoseconds EPSILON = std::chrono::milliseconds(1); auto duration = std::chrono::duration_cast(_endTime - _startTime); @@ -39,5 +39,7 @@ void RefreshRateController::sleepThreadIfNeeded(QThread* thread, bool isHmd) { if (sleepDuration.count() > 0) { thread->msleep(std::chrono::duration_cast(sleepDuration).count()); } + return sleepDuration; } + return std::chrono::nanoseconds(0); } diff --git a/libraries/display-plugins/src/display-plugins/RefreshRateController.h b/libraries/display-plugins/src/display-plugins/RefreshRateController.h index 15adee3d3d..3cb563377f 100644 --- a/libraries/display-plugins/src/display-plugins/RefreshRateController.h +++ b/libraries/display-plugins/src/display-plugins/RefreshRateController.h @@ -29,7 +29,7 @@ public: void clockStartTime() { _startTime = std::chrono::high_resolution_clock::now(); } void clockEndTime() { _endTime = std::chrono::high_resolution_clock::now(); } - void sleepThreadIfNeeded(QThread* thread, bool isHmd); + std::chrono::nanoseconds sleepThreadIfNeeded(QThread* thread, bool isHmd); private: std::chrono::time_point _startTime { std::chrono::high_resolution_clock::now() }; std::chrono::time_point _endTime { std::chrono::high_resolution_clock::now() }; diff --git a/libraries/plugins/src/plugins/DisplayPlugin.h b/libraries/plugins/src/plugins/DisplayPlugin.h index a07e6cea04..9dc1d7002d 100644 --- a/libraries/plugins/src/plugins/DisplayPlugin.h +++ b/libraries/plugins/src/plugins/DisplayPlugin.h @@ -211,7 +211,7 @@ public: virtual void cycleDebugOutput() {} void waitForPresent(); - float getAveragePresentTime() { return _movingAveragePresent.average / (float)USECS_PER_MSEC; } // in msec + float getAveragePresentTime() { return _movingAveragePresent.average / (float)USECS_PER_MSEC; } // in msec std::function getHUDOperator(); From 5e62e6b719cec72ec4de542dcdc19ff8167eee6b Mon Sep 17 00:00:00 2001 From: amerhifi Date: Tue, 14 May 2019 19:29:17 -0700 Subject: [PATCH 43/58] 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 44/58] 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 45/58] 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 46/58] 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 47/58] 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 48/58] 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 49/58] 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 50/58] 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 5db78ef2e15ea1ee05c817074517c55e6fc396ac Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Wed, 15 May 2019 12:55:25 -0700 Subject: [PATCH 51/58] Add scripting to set the refresh rate --- interface/src/Application.cpp | 6 ++- interface/src/RefreshRateManager.cpp | 5 --- interface/src/RefreshRateManager.h | 1 + .../PerformanceScriptingInterface.cpp | 28 ++++++++++++ .../scripting/PerformanceScriptingInterface.h | 43 +++++++++++++++++++ 5 files changed, 77 insertions(+), 6 deletions(-) create mode 100644 interface/src/scripting/PerformanceScriptingInterface.cpp create mode 100644 interface/src/scripting/PerformanceScriptingInterface.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d8df9ea62d..7f429d9765 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -193,6 +193,7 @@ #include "scripting/TTSScriptingInterface.h" #include "scripting/KeyboardScriptingInterface.h" #include "scripting/RefreshRateScriptingInterface.h" +#include "scripting/PerformanceScriptingInterface.h" @@ -3280,6 +3281,7 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("Controller", DependencyManager::get().data()); surfaceContext->setContextProperty("Entities", DependencyManager::get().data()); surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); + surfaceContext->setContextProperty("Performance", new PerformanceScriptingInterface()); _fileDownload = new FileScriptingInterface(engine); surfaceContext->setContextProperty("File", _fileDownload); connect(_fileDownload, &FileScriptingInterface::unzipResult, this, &Application::handleUnzip); @@ -3430,6 +3432,7 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("Settings", SettingsScriptingInterface::getInstance()); surfaceContext->setContextProperty("MenuInterface", MenuScriptingInterface::getInstance()); surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); + surfaceContext->setContextProperty("Performance", new PerformanceScriptingInterface()); surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED surfaceContext->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED @@ -7413,7 +7416,8 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("LODManager", DependencyManager::get().data()); scriptEngine->registerGlobalObject("Keyboard", DependencyManager::get().data()); - scriptEngine->registerGlobalObject("RefreshRate", new RefreshRateScriptingInterface); + scriptEngine->registerGlobalObject("RefreshRate", new RefreshRateScriptingInterface()); + scriptEngine->registerGlobalObject("Performance", new PerformanceScriptingInterface()); scriptEngine->registerGlobalObject("Paths", DependencyManager::get().data()); diff --git a/interface/src/RefreshRateManager.cpp b/interface/src/RefreshRateManager.cpp index 0c5bcd405e..f2033b9491 100644 --- a/interface/src/RefreshRateManager.cpp +++ b/interface/src/RefreshRateManager.cpp @@ -13,13 +13,8 @@ #include "RefreshRateManager.h" #include -#include -#include - -#include - static const int VR_TARGET_RATE = 90; static const std::array REFRESH_RATE_PROFILE_TO_STRING = diff --git a/interface/src/RefreshRateManager.h b/interface/src/RefreshRateManager.h index 6ded8c8869..6316de3bfb 100644 --- a/interface/src/RefreshRateManager.h +++ b/interface/src/RefreshRateManager.h @@ -14,6 +14,7 @@ #include #include +#include #include diff --git a/interface/src/scripting/PerformanceScriptingInterface.cpp b/interface/src/scripting/PerformanceScriptingInterface.cpp new file mode 100644 index 0000000000..53529beeef --- /dev/null +++ b/interface/src/scripting/PerformanceScriptingInterface.cpp @@ -0,0 +1,28 @@ +// +// Created by Bradley Austin Davis on 2019/05/14 +// Copyright 2013-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 "PerformanceScriptingInterface.h" + +#include "../Application.h" + +std::once_flag PerformanceScriptingInterface::registry_flag; + +PerformanceScriptingInterface::PerformanceScriptingInterface() { + std::call_once(registry_flag, [] { + qmlRegisterType("PerformanceEnums", 1, 0, "RefreshRate"); + }); +} + +void PerformanceScriptingInterface::setRefreshRateProfile(RefreshRateProfile refreshRateProfile) { + qApp->getRefreshRateManager().setRefreshRateProfile((RefreshRateManager::RefreshRateProfile)refreshRateProfile); +} + +PerformanceScriptingInterface::RefreshRateProfile PerformanceScriptingInterface::getRefreshRateProfile() const { + return (PerformanceScriptingInterface::RefreshRateProfile)qApp->getRefreshRateManager().getRefreshRateProfile(); +} diff --git a/interface/src/scripting/PerformanceScriptingInterface.h b/interface/src/scripting/PerformanceScriptingInterface.h new file mode 100644 index 0000000000..266fa7229f --- /dev/null +++ b/interface/src/scripting/PerformanceScriptingInterface.h @@ -0,0 +1,43 @@ +// +// Created by Bradley Austin Davis on 2019/05/14 +// Copyright 2013-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 +#ifndef hifi_PerformanceScriptingInterface_h +#define hifi_PerformanceScriptingInterface_h + +#include + +#include + +#include "../RefreshRateManager.h" + + +class PerformanceScriptingInterface : public QObject { + Q_OBJECT +public: + // Must match RefreshRateManager enums + enum RefreshRateProfile { + ECO = RefreshRateManager::RefreshRateProfile::ECO, + INTERACTIVE = RefreshRateManager::RefreshRateProfile::INTERACTIVE, + REALTIME = RefreshRateManager::RefreshRateProfile::REALTIME, + }; + Q_ENUM(RefreshRateProfile) + + + PerformanceScriptingInterface(); + ~PerformanceScriptingInterface() = default; + +public slots: + void setRefreshRateProfile(RefreshRateProfile refreshRateProfile); + RefreshRateProfile getRefreshRateProfile() const; + +private: + static std::once_flag registry_flag; +}; + +#endif // header guard From 8c375db90f3185263c4180db78cc495d4968f199 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Wed, 15 May 2019 12:55:47 -0700 Subject: [PATCH 52/58] Add display plugin introspection to the window scripting interface --- .../scripting/WindowScriptingInterface.cpp | 33 ++++++++++++++++ .../src/scripting/WindowScriptingInterface.h | 38 +++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index 2c1311924f..e1272d68a7 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include "AndroidHelper.h" @@ -609,3 +610,35 @@ void WindowScriptingInterface::onMessageBoxSelected(int button) { float WindowScriptingInterface::domainLoadingProgress() { return qApp->getOctreePacketProcessor().domainLoadingProgress(); } + +const DisplayPluginList& getDisplayPlugins() { + static const auto& list = PluginManager::getInstance()->getDisplayPlugins(); + return list; +} + +int WindowScriptingInterface::getDisplayPluginCount() { + return getDisplayPlugins().size(); +} + +QString WindowScriptingInterface::getDisplayPluginName(int index) { + return getDisplayPlugins().at(index)->getName(); +} + +bool WindowScriptingInterface::isDisplayPluginHmd(int index) { + return getDisplayPlugins().at(index)->isHmd(); +} + +int WindowScriptingInterface::getActiveDisplayPlugin() { + auto active = qApp->getActiveDisplayPlugin(); + auto size = getDisplayPluginCount(); + for (int i = 0; i < size; ++i) { + if (getDisplayPlugins().at(i) == active) { + return i; + } + } + return -1; +} + +void WindowScriptingInterface::setActiveDisplayPlugin(int index) { + qApp->setActiveDisplayPlugin(getDisplayPlugins().at(index)->getName()); +} diff --git a/interface/src/scripting/WindowScriptingInterface.h b/interface/src/scripting/WindowScriptingInterface.h index 77b586ec70..c165e5474e 100644 --- a/interface/src/scripting/WindowScriptingInterface.h +++ b/interface/src/scripting/WindowScriptingInterface.h @@ -575,6 +575,44 @@ public slots: float domainLoadingProgress(); + /**jsdoc + * Return the number of display plugins currently available + * @function Window.getDisplayPluginCount + * @returns {int} The number of currently available display plugins + */ + int getDisplayPluginCount(); + + /**jsdoc + * Return the human readable name of a display plugin + * @function Window.getDisplayPluginName + * @param {int} index - The index of the display plugin. Must be less than the value returned by {@link Window.getDisplayPluginCount|getDisplayPluginCount}. + * @returns {string} The name of the specified display plugin + */ + QString getDisplayPluginName(int index); + + /**jsdoc + * Return whether a given display plugin is an HMD + * @function Window.isDisplayPluginHmd + * @param {int} index - The index of the display plugin. Must be less than the value returned by {@link Window.getDisplayPluginCount|getDisplayPluginCount}. + * @returns {bool} True if the specified display plugin is a HMD + */ + bool isDisplayPluginHmd(int index); + + /**jsdoc + * Return the currently active display plugin + * @function Window.getActiveDisplayPlugin + * @returns {int} The index of the currently active display plugin + */ + int getActiveDisplayPlugin(); + + /**jsdoc + * Return the currently active display plugin + * @function Window.setActiveDisplayPlugin + * @param {int} index - The index of the display plugin. Must be less than the value returned by {@link Window.getDisplayPluginCount|getDisplayPluginCount}. + */ + void setActiveDisplayPlugin(int index); + + private slots: void onWindowGeometryChanged(const QRect& geometry); void onMessageBoxSelected(int button); From 1da5298086c7574fab3499cc345c8d563a4f627c Mon Sep 17 00:00:00 2001 From: amerhifi Date: Wed, 15 May 2019 13:13:43 -0700 Subject: [PATCH 53/58] 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 From 4e1b01177f516e86cd1580f23300c4eb4f5bce8e Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Wed, 15 May 2019 15:01:13 -0700 Subject: [PATCH 54/58] Capping the LOD MAnager target FPS by the refresh rate current rate --- interface/src/LODManager.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/interface/src/LODManager.cpp b/interface/src/LODManager.cpp index b6fffbb4bd..b0b919fb0f 100644 --- a/interface/src/LODManager.cpp +++ b/interface/src/LODManager.cpp @@ -351,10 +351,18 @@ float LODManager::getHMDLODTargetFPS() const { } float LODManager::getLODTargetFPS() const { + auto refreshRateFPS = qApp->getRefreshRateManager().getActiveRefreshRate(); + auto lodTargetFPS = getDesktopLODTargetFPS(); if (qApp->isHMDMode()) { - return getHMDLODTargetFPS(); + lodTargetFPS = getHMDLODTargetFPS(); + } + + // if RefreshRate is slower than LOD target then it becomes the true LOD target + if (lodTargetFPS > refreshRateFPS) { + return refreshRateFPS; + } else { + return lodTargetFPS; } - return getDesktopLODTargetFPS(); } void LODManager::setWorldDetailQuality(float quality) { From 0400bc6da0073ea72e4ee4261cd821fce60a7c3d Mon Sep 17 00:00:00 2001 From: Zach Fox Date: Wed, 15 May 2019 15:36:28 -0700 Subject: [PATCH 55/58] Fix JS to QML event bridge messages with Docked Windows --- interface/src/ui/InteractiveWindow.cpp | 7 +++---- interface/src/ui/InteractiveWindow.h | 1 - 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/interface/src/ui/InteractiveWindow.cpp b/interface/src/ui/InteractiveWindow.cpp index 810d85fa89..4bf4481c60 100644 --- a/interface/src/ui/InteractiveWindow.cpp +++ b/interface/src/ui/InteractiveWindow.cpp @@ -69,7 +69,6 @@ void interactiveWindowPointerFromScriptValue(const QScriptValue& object, Interac } InteractiveWindow::InteractiveWindow(const QString& sourceUrl, const QVariantMap& properties) { - bool docked = false; InteractiveWindowPresentationMode presentationMode = InteractiveWindowPresentationMode::Native; if (properties.contains(PRESENTATION_MODE_PROPERTY)) { @@ -124,12 +123,12 @@ InteractiveWindow::InteractiveWindow(const QString& sourceUrl, const QVariantMap QObject::connect(quickView.get(), &QQuickView::statusChanged, [&, this] (QQuickView::Status status) { if (status == QQuickView::Ready) { QQuickItem* rootItem = _dockWidget->getRootItem(); + _dockWidget->getQuickView()->rootContext()->setContextProperty(EVENT_BRIDGE_PROPERTY, this); QObject::connect(rootItem, SIGNAL(sendToScript(QVariant)), this, SLOT(qmlToScript(const QVariant&)), Qt::QueuedConnection); } }); _dockWidget->setSource(QUrl(sourceUrl)); mainWindow->addDockWidget(dockArea, _dockWidget.get()); - _dockedWindow = docked; } else { auto offscreenUi = DependencyManager::get(); // Build the event bridge and wrapper on the main thread @@ -188,10 +187,10 @@ InteractiveWindow::~InteractiveWindow() { void InteractiveWindow::sendToQml(const QVariant& message) { // Forward messages received from the script on to QML - if (_dockedWindow) { + if (_dockWidget) { QQuickItem* rootItem = _dockWidget->getRootItem(); if (rootItem) { - QMetaObject::invokeMethod(_qmlWindow, "fromScript", Qt::QueuedConnection, Q_ARG(QVariant, message)); + QMetaObject::invokeMethod(rootItem, "fromScript", Qt::QueuedConnection, Q_ARG(QVariant, message)); } } else { QMetaObject::invokeMethod(_qmlWindow, "fromScript", Qt::QueuedConnection, Q_ARG(QVariant, message)); diff --git a/interface/src/ui/InteractiveWindow.h b/interface/src/ui/InteractiveWindow.h index 816babc56a..fc6f6c55ab 100644 --- a/interface/src/ui/InteractiveWindow.h +++ b/interface/src/ui/InteractiveWindow.h @@ -203,7 +203,6 @@ protected slots: void qmlToScript(const QVariant& message); private: - bool _dockedWindow { false }; QPointer _qmlWindow; std::shared_ptr _dockWidget { nullptr }; }; From edbd354760824a443f1b0405a044cef92d69a106 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Wed, 15 May 2019 17:57:53 -0700 Subject: [PATCH 56/58] Instead of returning the main window dimension (modulo the height of the menu bar) let s return the size of the actual 3d viewport widget --- interface/src/scripting/WindowScriptingInterface.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index 2c1311924f..954c3e4590 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -414,11 +414,11 @@ QString WindowScriptingInterface::protocolSignature() { } int WindowScriptingInterface::getInnerWidth() { - return qApp->getWindow()->geometry().width(); + return qApp->getPrimaryWidget()->geometry().width(); } int WindowScriptingInterface::getInnerHeight() { - return qApp->getWindow()->geometry().height() - qApp->getPrimaryMenu()->geometry().height(); + return qApp->getPrimaryWidget()->geometry().height(); } glm::vec2 WindowScriptingInterface::getDeviceSize() const { From 9bcc23f0c48445b9dfa0da1c9cb716308ee0b381 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Thu, 16 May 2019 09:40:22 -0700 Subject: [PATCH 57/58] PR comments --- interface/src/Application.cpp | 4 -- .../PerformanceScriptingInterface.cpp | 12 +++++ .../scripting/PerformanceScriptingInterface.h | 5 ++ .../scripting/RefreshRateScriptingInterface.h | 46 ------------------- 4 files changed, 17 insertions(+), 50 deletions(-) delete mode 100644 interface/src/scripting/RefreshRateScriptingInterface.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 7f429d9765..3d6c2218ce 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -192,7 +192,6 @@ #include "scripting/WalletScriptingInterface.h" #include "scripting/TTSScriptingInterface.h" #include "scripting/KeyboardScriptingInterface.h" -#include "scripting/RefreshRateScriptingInterface.h" #include "scripting/PerformanceScriptingInterface.h" @@ -3280,7 +3279,6 @@ void Application::onDesktopRootContextCreated(QQmlContext* surfaceContext) { surfaceContext->setContextProperty("Controller", DependencyManager::get().data()); surfaceContext->setContextProperty("Entities", DependencyManager::get().data()); - surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); surfaceContext->setContextProperty("Performance", new PerformanceScriptingInterface()); _fileDownload = new FileScriptingInterface(engine); surfaceContext->setContextProperty("File", _fileDownload); @@ -3431,7 +3429,6 @@ void Application::setupQmlSurface(QQmlContext* surfaceContext, bool setAdditiona surfaceContext->setContextProperty("Settings", SettingsScriptingInterface::getInstance()); surfaceContext->setContextProperty("MenuInterface", MenuScriptingInterface::getInstance()); - surfaceContext->setContextProperty("RefreshRate", new RefreshRateScriptingInterface()); surfaceContext->setContextProperty("Performance", new PerformanceScriptingInterface()); surfaceContext->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED @@ -7416,7 +7413,6 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEnginePointe scriptEngine->registerGlobalObject("LODManager", DependencyManager::get().data()); scriptEngine->registerGlobalObject("Keyboard", DependencyManager::get().data()); - scriptEngine->registerGlobalObject("RefreshRate", new RefreshRateScriptingInterface()); scriptEngine->registerGlobalObject("Performance", new PerformanceScriptingInterface()); scriptEngine->registerGlobalObject("Paths", DependencyManager::get().data()); diff --git a/interface/src/scripting/PerformanceScriptingInterface.cpp b/interface/src/scripting/PerformanceScriptingInterface.cpp index 53529beeef..b1b4e62dca 100644 --- a/interface/src/scripting/PerformanceScriptingInterface.cpp +++ b/interface/src/scripting/PerformanceScriptingInterface.cpp @@ -26,3 +26,15 @@ void PerformanceScriptingInterface::setRefreshRateProfile(RefreshRateProfile ref PerformanceScriptingInterface::RefreshRateProfile PerformanceScriptingInterface::getRefreshRateProfile() const { return (PerformanceScriptingInterface::RefreshRateProfile)qApp->getRefreshRateManager().getRefreshRateProfile(); } + +int PerformanceScriptingInterface::getActiveRefreshRate() const { + return qApp->getRefreshRateManager().getActiveRefreshRate(); +} + +RefreshRateManager::UXMode PerformanceScriptingInterface::getUXMode() const { + return qApp->getRefreshRateManager().getUXMode(); +} + +RefreshRateManager::RefreshRateRegime PerformanceScriptingInterface::getRefreshRateRegime() const { + return qApp->getRefreshRateManager().getRefreshRateRegime(); +} diff --git a/interface/src/scripting/PerformanceScriptingInterface.h b/interface/src/scripting/PerformanceScriptingInterface.h index 266fa7229f..90b51d173c 100644 --- a/interface/src/scripting/PerformanceScriptingInterface.h +++ b/interface/src/scripting/PerformanceScriptingInterface.h @@ -36,6 +36,11 @@ public slots: void setRefreshRateProfile(RefreshRateProfile refreshRateProfile); RefreshRateProfile getRefreshRateProfile() const; + int getActiveRefreshRate() const; + RefreshRateManager::UXMode getUXMode() const; + RefreshRateManager::RefreshRateRegime getRefreshRateRegime() const; + + private: static std::once_flag registry_flag; }; diff --git a/interface/src/scripting/RefreshRateScriptingInterface.h b/interface/src/scripting/RefreshRateScriptingInterface.h deleted file mode 100644 index 697141583f..0000000000 --- a/interface/src/scripting/RefreshRateScriptingInterface.h +++ /dev/null @@ -1,46 +0,0 @@ -// -// RefreshRateScriptingInterface.h -// interface/src/scrfipting -// -// Created by Dante Ruiz on 2019-04-15. -// 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_RefreshRateScriptingInterface_h -#define hifi_RefreshRateScriptingInterface_h - -#include - -#include - -class RefreshRateScriptingInterface : public QObject { - Q_OBJECT -public: - RefreshRateScriptingInterface() = default; - ~RefreshRateScriptingInterface() = default; - -public: - Q_INVOKABLE QString getRefreshRateProfile() { - RefreshRateManager& refreshRateManager = qApp->getRefreshRateManager(); - return QString::fromStdString(RefreshRateManager::refreshRateProfileToString(refreshRateManager.getRefreshRateProfile())); - } - - Q_INVOKABLE QString getRefreshRateRegime() { - RefreshRateManager& refreshRateManager = qApp->getRefreshRateManager(); - return QString::fromStdString(RefreshRateManager::refreshRateRegimeToString(refreshRateManager.getRefreshRateRegime())); - } - - Q_INVOKABLE QString getUXMode() { - RefreshRateManager& refreshRateManager = qApp->getRefreshRateManager(); - return QString::fromStdString(RefreshRateManager::uxModeToString(refreshRateManager.getUXMode())); - } - - Q_INVOKABLE int getActiveRefreshRate() { - return qApp->getRefreshRateManager().getActiveRefreshRate(); - } -}; - -#endif From 6a0b479041f1f96356f1a7ab260b47211627ca0d Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Thu, 16 May 2019 10:48:18 -0700 Subject: [PATCH 58/58] Fix warning and build failures --- .../src/scripting/WindowScriptingInterface.cpp | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index e1272d68a7..3194fa24eb 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -611,28 +611,23 @@ float WindowScriptingInterface::domainLoadingProgress() { return qApp->getOctreePacketProcessor().domainLoadingProgress(); } -const DisplayPluginList& getDisplayPlugins() { - static const auto& list = PluginManager::getInstance()->getDisplayPlugins(); - return list; -} - int WindowScriptingInterface::getDisplayPluginCount() { - return getDisplayPlugins().size(); + return (int)PluginManager::getInstance()->getDisplayPlugins().size(); } QString WindowScriptingInterface::getDisplayPluginName(int index) { - return getDisplayPlugins().at(index)->getName(); + return PluginManager::getInstance()->getDisplayPlugins().at(index)->getName(); } bool WindowScriptingInterface::isDisplayPluginHmd(int index) { - return getDisplayPlugins().at(index)->isHmd(); + return PluginManager::getInstance()->getDisplayPlugins().at(index)->isHmd(); } int WindowScriptingInterface::getActiveDisplayPlugin() { auto active = qApp->getActiveDisplayPlugin(); auto size = getDisplayPluginCount(); for (int i = 0; i < size; ++i) { - if (getDisplayPlugins().at(i) == active) { + if (PluginManager::getInstance()->getDisplayPlugins().at(i) == active) { return i; } } @@ -640,5 +635,6 @@ int WindowScriptingInterface::getActiveDisplayPlugin() { } void WindowScriptingInterface::setActiveDisplayPlugin(int index) { - qApp->setActiveDisplayPlugin(getDisplayPlugins().at(index)->getName()); + auto name = PluginManager::getInstance()->getDisplayPlugins().at(index)->getName(); + qApp->setActiveDisplayPlugin(name); }