diff --git a/native/.clang-format b/native/.clang-format index 0d68186e73..ed084d9cff 100644 --- a/native/.clang-format +++ b/native/.clang-format @@ -4,8 +4,6 @@ BasedOnStyle: Google AccessModifierOffset: -4 AlignConsecutiveMacros: true -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true AllowShortCaseLabelsOnASingleLine: true ColumnLimit: 0 ConstructorInitializerIndentWidth: 0 @@ -19,6 +17,4 @@ ObjCSpaceAfterProperty: true --- Language: Cpp -# Force pointers to the type for C++. -DerivePointerAlignment: false -PointerAlignment: Right \ No newline at end of file +DerivePointerAlignment: true \ No newline at end of file diff --git a/native/cocos/3d/assets/Mesh.cpp b/native/cocos/3d/assets/Mesh.cpp index 27d0698a30..5c6a9bfe00 100644 --- a/native/cocos/3d/assets/Mesh.cpp +++ b/native/cocos/3d/assets/Mesh.cpp @@ -56,7 +56,7 @@ uint32_t getComponentByteLength(gfx::Format format) { using DataReaderCallback = std::function; DataReaderCallback getReader(const DataView &dataView, gfx::Format format) { - const auto & info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; const uint32_t stride = info.size / info.count; switch (info.type) { @@ -113,7 +113,7 @@ DataReaderCallback getReader(const DataView &dataView, gfx::Format format) { using DataWritterCallback = std::function; DataWritterCallback getWriter(DataView &dataView, gfx::Format format) { - const auto & info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; const uint32_t stride = info.size / info.count; switch (info.type) { @@ -225,7 +225,7 @@ void Mesh::initialize() { _initialized = true; if (_struct.dynamic.has_value()) { - auto * device = gfx::Device::getInstance(); + auto *device = gfx::Device::getInstance(); gfx::BufferList vertexBuffers; for (const auto &vertexBundle : _struct.vertexBundles) { @@ -237,8 +237,8 @@ void Mesh::initialize() { } for (auto i = 0U; i < _struct.primitives.size(); i++) { - const auto & primitive = _struct.primitives[i]; - const auto & indexView = primitive.indexView; + const auto &primitive = _struct.primitives[i]; + const auto &indexView = primitive.indexView; gfx::Buffer *indexBuffer = nullptr; if (indexView.has_value()) { @@ -274,10 +274,10 @@ void Mesh::initialize() { return; } - auto & buffer = _data; - gfx::Device * gfxDevice = gfx::Device::getInstance(); - auto vertexBuffers = createVertexBuffers(gfxDevice, buffer.buffer()); - gfx::BufferList indexBuffers; + auto &buffer = _data; + gfx::Device *gfxDevice = gfx::Device::getInstance(); + auto vertexBuffers = createVertexBuffers(gfxDevice, buffer.buffer()); + gfx::BufferList indexBuffers; ccstd::vector> subMeshes; for (size_t i = 0; i < _struct.primitives.size(); i++) { @@ -291,7 +291,7 @@ void Mesh::initialize() { const auto &idxView = prim.indexView.value(); uint32_t dstStride = idxView.stride; - uint32_t dstSize = idxView.length; + uint32_t dstSize = idxView.length; if (dstStride == 4 && !gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) { uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count; if (vertexCount >= 65536) { @@ -328,9 +328,9 @@ void Mesh::initialize() { gfx::AttributeList gfxAttributes; if (!prim.vertexBundelIndices.empty()) { - uint32_t idx = prim.vertexBundelIndices[0]; - const IVertexBundle & vertexBundle = _struct.vertexBundles[idx]; - const gfx::AttributeList &attrs = vertexBundle.attributes; + uint32_t idx = prim.vertexBundelIndices[0]; + const IVertexBundle &vertexBundle = _struct.vertexBundles[idx]; + const gfx::AttributeList &attrs = vertexBundle.attributes; gfxAttributes.resize(attrs.size()); for (size_t j = 0; j < attrs.size(); ++j) { const auto &attr = attrs[j]; @@ -370,8 +370,8 @@ void Mesh::assign(const IStruct &structInfo, const Uint8Array &data) { void Mesh::reset(ICreateInfo &&info) { destroyRenderingMesh(); _struct = std::move(info.structInfo); - _data = std::move(info.data); - _hash = 0; + _data = std::move(info.data); + _hash = 0; } Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) { @@ -379,10 +379,10 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) { if (iter != _boneSpaceBounds.end()) { return iter->second; } - Vec3 v32; - BoneSpaceBounds & bounds = _boneSpaceBounds[skeleton->getHash()]; + Vec3 v32; + BoneSpaceBounds &bounds = _boneSpaceBounds[skeleton->getHash()]; ccstd::vector valid; - const auto & bindposes = skeleton->getBindposes(); + const auto &bindposes = skeleton->getBindposes(); valid.reserve(bindposes.size()); for (size_t i = 0; i < bindposes.size(); i++) { bounds.emplace_back(ccnew geometry::AABB{ @@ -392,8 +392,8 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) { } const auto &primitives = _struct.primitives; for (index_t p = 0; p < primitives.size(); p++) { - const auto joints = readAttribute(p, gfx::ATTR_NAME_JOINTS); - const auto weights = readAttribute(p, gfx::ATTR_NAME_WEIGHTS); + const auto joints = readAttribute(p, gfx::ATTR_NAME_JOINTS); + const auto weights = readAttribute(p, gfx::ATTR_NAME_WEIGHTS); const auto positions = readAttribute(p, gfx::ATTR_NAME_POSITION); if (joints.index() == 0 || weights.index() == 0 || positions.index() == 0) { continue; @@ -409,8 +409,8 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) { getTypedArrayValue(positions, 3 * i + 2)}; for (uint32_t j = 0; j < 4; ++j) { - const uint32_t idx = 4 * i + j; - const auto joint = getTypedArrayValue(joints, idx); + const uint32_t idx = 4 * i + j; + const auto joint = getTypedArrayValue(joints, idx); if (std::fabs(getTypedArrayValue(weights, idx)) < FLT_EPSILON || joint >= bindposes.size()) { continue; @@ -418,7 +418,7 @@ Mesh::BoneSpaceBounds Mesh::getBoneSpaceBounds(Skeleton *skeleton) { Vec3::transformMat4(v31, bindposes[joint], &v32); valid[joint] = true; - auto &b = bounds[joint]; + auto &b = bounds[joint]; Vec3::min(b->center, v32, &b->center); Vec3::max(b->halfExtents, v32, &b->halfExtents); } @@ -442,14 +442,14 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid } } - Vec3 vec3Temp; - Quaternion rotate; + Vec3 vec3Temp; + Quaternion rotate; geometry::AABB boundingBox; if (worldMatrix != nullptr) { worldMatrix->getRotation(&rotate); } if (!_initialized) { - auto structInfo = mesh->_struct; //NOTE: Need copy struct, so don't use referece + auto structInfo = mesh->_struct; //NOTE: Need copy struct, so don't use referece Uint8Array data{mesh->_data.slice()}; if (worldMatrix != nullptr) { if (structInfo.maxPosition.has_value() && structInfo.minPosition.has_value()) { @@ -481,7 +481,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid const uint32_t vertexCount = vtxBdl.view.count; - const uint32_t vertexStride = vtxBdl.view.stride; + const uint32_t vertexStride = vtxBdl.view.stride; const uint32_t attrComponentByteLength = getComponentByteLength(format); for (uint32_t vtxIdx = 0; vtxIdx < vertexCount; vtxIdx++) { const uint32_t xOffset = vtxIdx * vertexStride; @@ -516,15 +516,15 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid BufferBlob bufferBlob; // merge vertex buffer - uint32_t vertCount = 0; + uint32_t vertCount = 0; uint32_t vertStride = 0; - uint32_t srcOffset = 0; - uint32_t dstOffset = 0; + uint32_t srcOffset = 0; + uint32_t dstOffset = 0; uint32_t srcAttrOffset = 0; - uint32_t srcVBOffset = 0; - uint32_t dstVBOffset = 0; - uint32_t attrSize = 0; + uint32_t srcVBOffset = 0; + uint32_t dstVBOffset = 0; + uint32_t attrSize = 0; bool hasAttr = false; @@ -534,15 +534,15 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid for (size_t i = 0; i < _struct.vertexBundles.size(); ++i) { Uint8Array dstAttrView; - const auto &bundle = _struct.vertexBundles[i]; - auto & dstBundle = mesh->_struct.vertexBundles[i]; + const auto &bundle = _struct.vertexBundles[i]; + auto &dstBundle = mesh->_struct.vertexBundles[i]; - srcOffset = bundle.view.offset; - dstOffset = dstBundle.view.offset; + srcOffset = bundle.view.offset; + dstOffset = dstBundle.view.offset; vertStride = bundle.view.stride; - vertCount = bundle.view.count + dstBundle.view.count; + vertCount = bundle.view.count + dstBundle.view.count; - auto * vb = ccnew ArrayBuffer(vertCount * vertStride); + auto *vb = ccnew ArrayBuffer(vertCount * vertStride); Uint8Array vbView(vb); Uint8Array srcVBView = _data.subarray(srcOffset, srcOffset + bundle.view.length); @@ -555,7 +555,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid srcAttrOffset = 0; for (const auto &attr : bundle.attributes) { dstVBOffset = 0; - hasAttr = false; + hasAttr = false; for (const auto &dstAttr : dstBundle.attributes) { if (attr.name == dstAttr.name && attr.format == dstAttr.format) { hasAttr = true; @@ -564,7 +564,7 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid dstVBOffset += gfx::GFX_FORMAT_INFOS[static_cast(dstAttr.format)].size; } if (hasAttr) { - attrSize = gfx::GFX_FORMAT_INFOS[static_cast(attr.format)].size; + attrSize = gfx::GFX_FORMAT_INFOS[static_cast(attr.format)].size; srcVBOffset = bundle.view.length + srcAttrOffset; for (uint32_t v = 0; v < dstBundle.view.count; ++v) { dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize); @@ -589,29 +589,29 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid srcAttrOffset += gfx::GFX_FORMAT_INFOS[static_cast(attr.format)].size; } - auto &vertexBundle = vertexBundles[i]; - vertexBundle.attributes = bundle.attributes, + auto &vertexBundle = vertexBundles[i]; + vertexBundle.attributes = bundle.attributes, vertexBundle.view.offset = bufferBlob.getLength(); vertexBundle.view.length = vb->byteLength(); - vertexBundle.view.count = vertCount; + vertexBundle.view.count = vertCount; vertexBundle.view.stride = vertStride; bufferBlob.addBuffer(vb); } // merge index buffer - uint32_t idxCount = 0; - uint32_t idxStride = 2; + uint32_t idxCount = 0; + uint32_t idxStride = 2; uint32_t vertBatchCount = 0; ccstd::vector primitives; primitives.resize(_struct.primitives.size()); for (size_t i = 0; i < _struct.primitives.size(); ++i) { - const auto &prim = _struct.primitives[i]; - auto & dstPrim = mesh->_struct.primitives[i]; + const auto &prim = _struct.primitives[i]; + auto &dstPrim = mesh->_struct.primitives[i]; - primitives[i].primitiveMode = prim.primitiveMode; + primitives[i].primitiveMode = prim.primitiveMode; primitives[i].vertexBundelIndices = prim.vertexBundelIndices; for (const uint32_t bundleIdx : prim.vertexBundelIndices) { @@ -705,10 +705,10 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid dstOffset += dstPrim.indexView.value().length; IBufferView indexView; - indexView.offset = bufferBlob.getLength(); - indexView.length = ib->byteLength(); - indexView.count = idxCount; - indexView.stride = idxStride; + indexView.offset = bufferBlob.getLength(); + indexView.length = ib->byteLength(); + indexView.count = idxCount; + indexView.stride = idxStride; primitives[i].indexView = indexView; bufferBlob.setNextAlignment(idxStride); @@ -719,9 +719,9 @@ bool Mesh::merge(Mesh *mesh, const Mat4 *worldMatrix /* = nullptr */, bool valid // Create mesh struct. Mesh::IStruct meshStruct; meshStruct.vertexBundles = vertexBundles; - meshStruct.primitives = primitives; - meshStruct.minPosition = _struct.minPosition; - meshStruct.maxPosition = _struct.maxPosition; + meshStruct.primitives = primitives; + meshStruct.minPosition = _struct.minPosition; + meshStruct.maxPosition = _struct.maxPosition; if (meshStruct.minPosition && mesh->_struct.minPosition && meshStruct.maxPosition && mesh->_struct.maxPosition) { if (worldMatrix != nullptr) { @@ -764,8 +764,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) { } for (size_t i = 0; i < _struct.vertexBundles.size(); ++i) { - const auto &bundle = _struct.vertexBundles[i]; - auto & dstBundle = mesh->_struct.vertexBundles[i]; + const auto &bundle = _struct.vertexBundles[i]; + auto &dstBundle = mesh->_struct.vertexBundles[i]; if (bundle.attributes.size() != dstBundle.attributes.size()) { return false; @@ -782,8 +782,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) { return false; } for (size_t i = 0; i < _struct.primitives.size(); ++i) { - const auto &prim = _struct.primitives[i]; - auto & dstPrim = mesh->_struct.primitives[i]; + const auto &prim = _struct.primitives[i]; + auto &dstPrim = mesh->_struct.primitives[i]; if (prim.vertexBundelIndices.size() != dstPrim.vertexBundelIndices.size()) { return false; } @@ -811,8 +811,8 @@ bool Mesh::validateMergingMesh(Mesh *mesh) { TypedArray Mesh::readAttribute(index_t primitiveIndex, const char *attributeName) { TypedArray result; accessAttribute(primitiveIndex, attributeName, [&](const IVertexBundle &vertexBundle, uint32_t iAttribute) { - const uint32_t vertexCount = vertexBundle.view.count; - const gfx::Format format = vertexBundle.attributes[iAttribute].format; + const uint32_t vertexCount = vertexBundle.view.count; + const gfx::Format format = vertexBundle.attributes[iAttribute].format; if (vertexCount == 0) { return; } @@ -827,8 +827,8 @@ TypedArray Mesh::readAttribute(index_t primitiveIndex, const char *attributeName } const uint32_t componentCount = formatInfo.count; - result = createTypedArrayWithGFXFormat(format, vertexCount * componentCount); - const uint32_t inputStride = vertexBundle.view.stride; + result = createTypedArrayWithGFXFormat(format, vertexCount * componentCount); + const uint32_t inputStride = vertexBundle.view.stride; for (uint32_t iVertex = 0; iVertex < vertexCount; ++iVertex) { for (uint32_t iComponent = 0; iComponent < componentCount; ++iComponent) { TypedArrayElementType element = reader(inputStride * iVertex + getTypedArrayBytesPerElement(result) * iComponent); @@ -867,13 +867,13 @@ bool Mesh::copyAttribute(index_t primitiveIndex, const char *attributeName, Arra const uint32_t componentCount = formatInfo.count; - const uint32_t inputStride = vertexBundle.view.stride; - const uint32_t inputComponentByteLength = getComponentByteLength(format); - const uint32_t outputStride = stride; + const uint32_t inputStride = vertexBundle.view.stride; + const uint32_t inputComponentByteLength = getComponentByteLength(format); + const uint32_t outputStride = stride; const uint32_t outputComponentByteLength = inputComponentByteLength; for (uint32_t iVertex = 0; iVertex < vertexCount; ++iVertex) { for (uint32_t iComponent = 0; iComponent < componentCount; ++iComponent) { - const uint32_t inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent; + const uint32_t inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent; const uint32_t outputOffset = outputStride * iVertex + outputComponentByteLength * iComponent; writer(outputOffset, reader(inputOffset)); } @@ -891,10 +891,10 @@ IBArray Mesh::readIndices(index_t primitiveIndex) { if (!primitive.indexView.has_value()) { return {}; } - const uint32_t stride = primitive.indexView.value().stride; - const uint32_t count = primitive.indexView.value().count; + const uint32_t stride = primitive.indexView.value().stride; + const uint32_t count = primitive.indexView.value().count; const uint32_t byteOffset = primitive.indexView.value().offset; - IBArray ret; + IBArray ret; if (stride == 1) { ret = Uint8Array(_data.buffer(), byteOffset, count); } else if (stride == 2) { @@ -915,12 +915,12 @@ bool Mesh::copyIndices(index_t primitiveIndex, TypedArray &outputArray) { return false; } - const uint32_t indexCount = primitive.indexView.value().count; + const uint32_t indexCount = primitive.indexView.value().count; const gfx::Format indexFormat = primitive.indexView.value().stride == 1 ? gfx::Format::R8UI : (primitive.indexView.value().stride == 2 ? gfx::Format::R16UI : gfx::Format::R32UI); - DataView view(_data.buffer()); - auto reader = getReader(view, indexFormat); + DataView view(_data.buffer()); + auto reader = getReader(view, indexFormat); for (uint32_t i = 0; i < indexCount; ++i) { TypedArrayElementType element = reader(primitive.indexView.value().offset + gfx::GFX_FORMAT_INFOS[static_cast(indexFormat)].size * i); setTypedArrayValue(outputArray, i, element); @@ -964,22 +964,22 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr } } - auto &dynamic = _struct.dynamic.value(); - auto &info = dynamic.info; + auto &dynamic = _struct.dynamic.value(); + auto &info = dynamic.info; auto &primitive = _struct.primitives[primitiveIndex]; - auto &subMesh = _renderingSubMeshes[primitiveIndex]; - auto &drawInfo = subMesh->getDrawInfo().value(); + auto &subMesh = _renderingSubMeshes[primitiveIndex]; + auto &drawInfo = subMesh->getDrawInfo().value(); // update _data & buffer for (auto index = 0U; index < buffers.size(); index++) { - const auto &vertices = *buffers[index]; - auto & bundle = _struct.vertexBundles[primitive.vertexBundelIndices[index]]; - const auto stride = bundle.view.stride; - const auto vertexCount = vertices.byteLength() / stride; - const auto updateSize = vertices.byteLength(); - auto * dstBuffer = _data.buffer()->getData() + bundle.view.offset; - const auto *srcBuffer = vertices.buffer()->getData() + vertices.byteOffset(); - auto * vertexBuffer = subMesh->getVertexBuffers()[index]; + const auto &vertices = *buffers[index]; + auto &bundle = _struct.vertexBundles[primitive.vertexBundelIndices[index]]; + const auto stride = bundle.view.stride; + const auto vertexCount = vertices.byteLength() / stride; + const auto updateSize = vertices.byteLength(); + auto *dstBuffer = _data.buffer()->getData() + bundle.view.offset; + const auto *srcBuffer = vertices.buffer()->getData() + vertices.byteOffset(); + auto *vertexBuffer = subMesh->getVertexBuffers()[index]; CC_ASSERT(vertexCount <= info.maxSubMeshVertices); if (updateSize > 0U) { @@ -987,19 +987,19 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr vertexBuffer->update(srcBuffer, updateSize); } - bundle.view.count = vertexCount; + bundle.view.count = vertexCount; drawInfo.vertexCount = vertexCount; } if (primitive.indexView.has_value()) { - auto & indexView = primitive.indexView.value(); - const auto &stride = indexView.stride; - const auto indexCount = (stride == sizeof(uint16_t)) ? geometry.indices16.value().length() : geometry.indices32.value().length(); - const auto updateSize = indexCount * stride; - auto * dstBuffer = _data.buffer()->getData() + indexView.offset; - const auto *srcBuffer = (stride == sizeof(uint16_t)) ? geometry.indices16.value().buffer()->getData() + geometry.indices16.value().byteOffset() - : geometry.indices32.value().buffer()->getData() + geometry.indices32.value().byteOffset(); - auto * indexBuffer = subMesh->getIndexBuffer(); + auto &indexView = primitive.indexView.value(); + const auto &stride = indexView.stride; + const auto indexCount = (stride == sizeof(uint16_t)) ? geometry.indices16.value().length() : geometry.indices32.value().length(); + const auto updateSize = indexCount * stride; + auto *dstBuffer = _data.buffer()->getData() + indexView.offset; + const auto *srcBuffer = (stride == sizeof(uint16_t)) ? geometry.indices16.value().buffer()->getData() + geometry.indices16.value().byteOffset() + : geometry.indices32.value().buffer()->getData() + geometry.indices32.value().byteOffset(); + auto *indexBuffer = subMesh->getIndexBuffer(); CC_ASSERT(indexCount <= info.maxSubMeshIndices); if (updateSize > 0U) { @@ -1007,7 +1007,7 @@ void Mesh::updateSubMesh(index_t primitiveIndex, const IDynamicGeometry &geometr indexBuffer->update(srcBuffer, updateSize); } - indexView.count = indexCount; + indexView.count = indexCount; drawInfo.indexCount = indexCount; } @@ -1045,7 +1045,7 @@ void Mesh::accessAttribute(index_t primitiveIndex, const char *attributeName, co auto &primitive = _struct.primitives[primitiveIndex]; for (const auto &vertexBundleIndex : primitive.vertexBundelIndices) { const auto &vertexBundle = _struct.vertexBundles[vertexBundleIndex]; - auto iter = std::find_if(vertexBundle.attributes.begin(), vertexBundle.attributes.end(), [&](const auto &a) -> bool { return a.name == attributeName; }); + auto iter = std::find_if(vertexBundle.attributes.begin(), vertexBundle.attributes.end(), [&](const auto &a) -> bool { return a.name == attributeName; }); if (iter == vertexBundle.attributes.end()) { continue; } @@ -1079,7 +1079,7 @@ bool Mesh::validate() const { } TypedArray Mesh::createTypedArrayWithGFXFormat(gfx::Format format, uint32_t count) { - const auto & info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; const uint32_t stride = info.size / info.count; switch (info.type) { diff --git a/native/cocos/3d/assets/Mesh.h b/native/cocos/3d/assets/Mesh.h index bfcb8581e5..6b25b1a7a9 100644 --- a/native/cocos/3d/assets/Mesh.h +++ b/native/cocos/3d/assets/Mesh.h @@ -205,7 +205,7 @@ public: ~Mesh() override; cc::any getNativeAsset() const override; - void setNativeAsset(const cc::any &obj) override; + void setNativeAsset(const cc::any &obj) override; void setAssetData(cc::ArrayBuffer *data) { _data = Uint8Array(data); @@ -431,8 +431,8 @@ public: IntrusivePtr morphRendering; private: - IStruct _struct; - uint64_t _hash{0}; + IStruct _struct; + uint64_t _hash{0}; Uint8Array _data; bool _initialized{false}; diff --git a/native/cocos/3d/assets/Morph.h b/native/cocos/3d/assets/Morph.h index 165d848960..b690fa4f50 100644 --- a/native/cocos/3d/assets/Morph.h +++ b/native/cocos/3d/assets/Morph.h @@ -48,7 +48,7 @@ MorphRendering *createMorphRendering(Mesh *mesh, gfx::Device *gfxDevice); */ class MorphRendering : public RefCounted { public: - ~MorphRendering() override = default; + ~MorphRendering() override = default; virtual MorphRenderingInstance *createInstance() = 0; }; diff --git a/native/cocos/3d/assets/MorphRendering.cpp b/native/cocos/3d/assets/MorphRendering.cpp index e7fa4ebfb4..88bc79263c 100644 --- a/native/cocos/3d/assets/MorphRendering.cpp +++ b/native/cocos/3d/assets/MorphRendering.cpp @@ -132,9 +132,9 @@ public: void initialize(gfx::Device *gfxDevice, uint32_t width, uint32_t height, uint32_t pixelBytes, bool /*useFloat32Array*/, PixelFormat pixelFormat) { _arrayBuffer = ccnew ArrayBuffer(width * height * pixelBytes); - _valueView = Float32Array(_arrayBuffer); + _valueView = Float32Array(_arrayBuffer); - auto * imageAsset = ccnew ImageAsset(); + auto *imageAsset = ccnew ImageAsset(); IMemoryImageSource source{_arrayBuffer, false, width, height, pixelFormat}; imageAsset->setNativeAsset(source); @@ -152,15 +152,15 @@ public: private: IntrusivePtr _textureAsset; - gfx::Sampler * _sampler{nullptr}; - ArrayBuffer::Ptr _arrayBuffer; - Float32Array _valueView; + gfx::Sampler *_sampler{nullptr}; + ArrayBuffer::Ptr _arrayBuffer; + Float32Array _valueView; CC_DISALLOW_COPY_MOVE_ASSIGN(MorphTexture); }; struct GpuMorphAttribute { - ccstd::string attributeName; + ccstd::string attributeName; IntrusivePtr morphTexture; }; @@ -171,13 +171,13 @@ struct CpuMorphAttributeTarget { using CpuMorphAttributeTargetList = ccstd::vector; struct CpuMorphAttribute { - ccstd::string name; + ccstd::string name; CpuMorphAttributeTargetList targets; }; struct Vec4TextureFactory { - uint32_t width{0}; - uint32_t height{0}; + uint32_t width{0}; + uint32_t height{0}; std::function create{nullptr}; }; @@ -205,11 +205,11 @@ bool bestSizeToHavePixels(uint32_t nPixels, uint32_t *pWidth, uint32_t *pHeight) nPixels = 5; } const uint32_t aligned = pipeline::nextPow2(nPixels); - const auto epxSum = static_cast(std::log2(aligned)); - const uint32_t h = epxSum >> 1; - const uint32_t w = (epxSum & 1) ? (h + 1) : h; + const auto epxSum = static_cast(std::log2(aligned)); + const uint32_t h = epxSum >> 1; + const uint32_t w = (epxSum & 1) ? (h + 1) : h; - *pWidth = 1 << w; + *pWidth = 1 << w; *pHeight = 1 << h; return true; @@ -235,29 +235,29 @@ void enableVertexId(Mesh *mesh, uint32_t subMeshIndex, gfx::Device *gfxDevice) { Vec4TextureFactory createVec4TextureFactory(gfx::Device *gfxDevice, uint32_t vec4Capacity) { bool hasFeatureFloatTexture = static_cast(gfxDevice->getFormatFeatures(gfx::Format::RGBA32F) & gfx::FormatFeature::SAMPLED_TEXTURE) != 0; - uint32_t pixelRequired = 0; - PixelFormat pixelFormat = PixelFormat::RGBA8888; - uint32_t pixelBytes = 4; - bool useFloat32Array = false; + uint32_t pixelRequired = 0; + PixelFormat pixelFormat = PixelFormat::RGBA8888; + uint32_t pixelBytes = 4; + bool useFloat32Array = false; if (hasFeatureFloatTexture) { - pixelRequired = vec4Capacity; - pixelBytes = 16; - pixelFormat = Texture2D::PixelFormat::RGBA32F; + pixelRequired = vec4Capacity; + pixelBytes = 16; + pixelFormat = Texture2D::PixelFormat::RGBA32F; useFloat32Array = true; } else { - pixelRequired = 4 * vec4Capacity; - pixelBytes = 4; - pixelFormat = Texture2D::PixelFormat::RGBA8888; + pixelRequired = 4 * vec4Capacity; + pixelBytes = 4; + pixelFormat = Texture2D::PixelFormat::RGBA8888; useFloat32Array = false; } - uint32_t width = 0; + uint32_t width = 0; uint32_t height = 0; bestSizeToHavePixels(pixelRequired, &width, &height); CC_ASSERT(width * height >= pixelRequired); Vec4TextureFactory ret; - ret.width = width; + ret.width = width; ret.height = height; ret.create = [=]() -> MorphTexture * { auto *texture = ccnew MorphTexture(); // texture will be held by IntrusivePtr in GpuMorphAttribute @@ -319,8 +319,8 @@ public: } private: - uint32_t _targetCount{0}; - DataView * _localBuffer{nullptr}; + uint32_t _targetCount{0}; + DataView *_localBuffer{nullptr}; IntrusivePtr _remoteBuffer; }; @@ -328,12 +328,12 @@ class CpuComputing final : public SubMeshMorphRendering { public: explicit CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice); - SubMeshMorphRenderingInstance * createInstance() override; + SubMeshMorphRenderingInstance *createInstance() override; const ccstd::vector &getData() const; private: ccstd::vector _attributes; - gfx::Device * _gfxDevice{nullptr}; + gfx::Device *_gfxDevice{nullptr}; }; class GpuComputing final : public SubMeshMorphRendering { @@ -344,12 +344,12 @@ public: void destroy(); private: - gfx::Device * _gfxDevice{nullptr}; - const SubMeshMorph * _subMeshMorph{nullptr}; - uint32_t _textureWidth{0}; - uint32_t _textureHeight{0}; + gfx::Device *_gfxDevice{nullptr}; + const SubMeshMorph *_subMeshMorph{nullptr}; + uint32_t _textureWidth{0}; + uint32_t _textureHeight{0}; ccstd::vector _attributes; - uint32_t _verticesCount{0}; + uint32_t _verticesCount{0}; friend class GpuComputingRenderingInstance; }; @@ -357,7 +357,7 @@ private: class CpuComputingRenderingInstance final : public SubMeshMorphRenderingInstance { public: explicit CpuComputingRenderingInstance(CpuComputing *owner, uint32_t nVertices, gfx::Device *gfxDevice) { - _owner = owner; //NOTE: release by mesh`s destroy, it`ll call current instance`s destroy method + _owner = owner; //NOTE: release by mesh`s destroy, it`ll call current instance`s destroy method _morphUniforms = ccnew MorphUniforms(gfxDevice, 0 /* TODO? */); auto vec4TextureFactory = createVec4TextureFactory(gfxDevice, nVertices); @@ -371,14 +371,14 @@ public: void setWeights(const ccstd::vector &weights) override { for (size_t iAttribute = 0; iAttribute < _attributes.size(); ++iAttribute) { - const auto & myAttribute = _attributes[iAttribute]; - Float32Array &valueView = myAttribute.morphTexture->getValueView(); - const auto & attributeMorph = _owner->getData()[iAttribute]; + const auto &myAttribute = _attributes[iAttribute]; + Float32Array &valueView = myAttribute.morphTexture->getValueView(); + const auto &attributeMorph = _owner->getData()[iAttribute]; CC_ASSERT(weights.size() == attributeMorph.targets.size()); for (size_t iTarget = 0; iTarget < attributeMorph.targets.size(); ++iTarget) { - const auto & targetDisplacements = attributeMorph.targets[iTarget].displacements; - const float weight = weights[iTarget]; - const uint32_t nVertices = targetDisplacements.length() / 3; + const auto &targetDisplacements = attributeMorph.targets[iTarget].displacements; + const float weight = weights[iTarget]; + const uint32_t nVertices = targetDisplacements.length() / 3; if (iTarget == 0) { for (uint32_t iVertex = 0; iVertex < nVertices; ++iVertex) { valueView[4 * iVertex + 0] = targetDisplacements[3 * iVertex + 0] * weight; @@ -407,7 +407,7 @@ public: void adaptPipelineState(gfx::DescriptorSet *descriptorSet) override { for (const auto &attribute : _attributes) { - const auto & attributeName = attribute.attributeName; + const auto &attributeName = attribute.attributeName; cc::optional binding; if (attributeName == gfx::ATTR_NAME_POSITION) { binding = uint32_t{pipeline::POSITIONMORPH::BINDING}; @@ -437,14 +437,14 @@ public: private: ccstd::vector _attributes; - IntrusivePtr _owner; - IntrusivePtr _morphUniforms; + IntrusivePtr _owner; + IntrusivePtr _morphUniforms; }; class GpuComputingRenderingInstance final : public SubMeshMorphRenderingInstance { public: explicit GpuComputingRenderingInstance(GpuComputing *owner, gfx::Device *gfxDevice) { - _owner = owner; + _owner = owner; _morphUniforms = ccnew MorphUniforms(gfxDevice, static_cast(_owner->_subMeshMorph->targets.size())); _morphUniforms->setMorphTextureInfo(static_cast(_owner->_textureWidth), static_cast(_owner->_textureHeight)); _morphUniforms->setVerticesCount(_owner->_verticesCount); @@ -465,7 +465,7 @@ public: void adaptPipelineState(gfx::DescriptorSet *descriptorSet) override { for (const auto &attribute : *_attributes) { - const auto & attributeName = attribute.attributeName; + const auto &attributeName = attribute.attributeName; cc::optional binding; if (attributeName == gfx::ATTR_NAME_POSITION) { binding = uint32_t{pipeline::POSITIONMORPH::BINDING}; @@ -491,12 +491,12 @@ public: private: ccstd::vector *_attributes{nullptr}; - IntrusivePtr _owner; - IntrusivePtr _morphUniforms; + IntrusivePtr _owner; + IntrusivePtr _morphUniforms; }; CpuComputing::CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice) { - _gfxDevice = gfxDevice; + _gfxDevice = gfxDevice; const auto &subMeshMorph = morph->subMeshMorphs[subMeshIndex].value(); enableVertexId(mesh, subMeshIndex, gfxDevice); @@ -510,7 +510,7 @@ CpuComputing::CpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph uint32_t i = 0; for (const auto &attributeDisplacement : subMeshMorph.targets) { const Mesh::IBufferView &displacementsView = attributeDisplacement.displacements[attributeIndex]; - attr.targets[i].displacements = Float32Array(mesh->getData().buffer(), + attr.targets[i].displacements = Float32Array(mesh->getData().buffer(), mesh->getData().byteOffset() + displacementsView.offset, attributeDisplacement.displacements[attributeIndex].count); @@ -533,7 +533,7 @@ const ccstd::vector &CpuComputing::getData() const { } GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph, gfx::Device *gfxDevice) { - _gfxDevice = gfxDevice; + _gfxDevice = gfxDevice; const auto &subMeshMorph = morph->subMeshMorphs[subMeshIndex].value(); _subMeshMorph = &subMeshMorph; @@ -541,20 +541,20 @@ GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph enableVertexId(mesh, subMeshIndex, gfxDevice); - uint32_t nVertices = mesh->getStruct().vertexBundles[mesh->getStruct().primitives[subMeshIndex].vertexBundelIndices[0]].view.count; - _verticesCount = nVertices; - auto nTargets = static_cast(subMeshMorph.targets.size()); + uint32_t nVertices = mesh->getStruct().vertexBundles[mesh->getStruct().primitives[subMeshIndex].vertexBundelIndices[0]].view.count; + _verticesCount = nVertices; + auto nTargets = static_cast(subMeshMorph.targets.size()); uint32_t vec4Required = nVertices * nTargets; auto vec4TextureFactory = createVec4TextureFactory(gfxDevice, vec4Required); - _textureWidth = vec4TextureFactory.width; - _textureHeight = vec4TextureFactory.height; + _textureWidth = vec4TextureFactory.width; + _textureHeight = vec4TextureFactory.height; // Creates texture for each attribute. uint32_t attributeIndex = 0; _attributes.reserve(subMeshMorph.attributes.size()); for (const auto &attributeName : subMeshMorph.attributes) { - auto * vec4Tex = vec4TextureFactory.create(); + auto *vec4Tex = vec4TextureFactory.create(); Float32Array &valueView = vec4Tex->getValueView(); // if (DEV) { // Make it easy to view texture in profilers... // for (let i = 0; i < valueView.length / 4; ++i) { @@ -564,8 +564,8 @@ GpuComputing::GpuComputing(Mesh *mesh, uint32_t subMeshIndex, const Morph *morph uint32_t morphTargetIndex = 0; for (const auto &morphTarget : subMeshMorph.targets) { - const auto & displacementsView = morphTarget.displacements[attributeIndex]; - Float32Array displacements(mesh->getData().buffer(), + const auto &displacementsView = morphTarget.displacements[attributeIndex]; + Float32Array displacements(mesh->getData().buffer(), mesh->getData().byteOffset() + displacementsView.offset, displacementsView.count); const uint32_t displacementsOffset = (nVertices * morphTargetIndex) * 4; @@ -601,7 +601,7 @@ void GpuComputing::destroy() { class StdMorphRenderingInstance : public MorphRenderingInstance { public: explicit StdMorphRenderingInstance(StdMorphRendering *owner) { - _owner = owner; + _owner = owner; size_t nSubMeshes = _owner->_mesh->getStruct().primitives.size(); _subMeshInstances.resize(nSubMeshes, nullptr); @@ -628,8 +628,8 @@ public: ccstd::vector requiredPatches(index_t subMeshIndex) override { CC_ASSERT(_owner->_mesh->getStruct().morph.has_value()); - const auto &subMeshMorphOpt = _owner->_mesh->getStruct().morph.value().subMeshMorphs[subMeshIndex]; - auto * subMeshRenderingInstance = _subMeshInstances[subMeshIndex].get(); + const auto &subMeshMorphOpt = _owner->_mesh->getStruct().morph.value().subMeshMorphs[subMeshIndex]; + auto *subMeshRenderingInstance = _subMeshInstances[subMeshIndex].get(); if (subMeshRenderingInstance == nullptr || !subMeshMorphOpt.has_value()) { return {}; } @@ -680,12 +680,12 @@ public: } private: - IntrusivePtr _owner; + IntrusivePtr _owner; ccstd::vector> _subMeshInstances; }; StdMorphRendering::StdMorphRendering(Mesh *mesh, gfx::Device *gfxDevice) { - _mesh = mesh; + _mesh = mesh; const auto &structInfo = _mesh->getStruct(); if (!structInfo.morph.has_value()) { return; diff --git a/native/cocos/3d/assets/MorphRendering.h b/native/cocos/3d/assets/MorphRendering.h index 6507b8d3bf..23f71c6c58 100644 --- a/native/cocos/3d/assets/MorphRendering.h +++ b/native/cocos/3d/assets/MorphRendering.h @@ -44,7 +44,7 @@ public: MorphRenderingInstance *createInstance() override; private: - Mesh * _mesh{nullptr}; + Mesh *_mesh{nullptr}; ccstd::vector> _subMeshRenderings; CC_DISALLOW_COPY_MOVE_ASSIGN(StdMorphRendering); diff --git a/native/cocos/3d/assets/Skeleton.cpp b/native/cocos/3d/assets/Skeleton.cpp index 03bff171db..b9801ed4c9 100644 --- a/native/cocos/3d/assets/Skeleton.cpp +++ b/native/cocos/3d/assets/Skeleton.cpp @@ -54,7 +54,7 @@ uint64_t Skeleton::getHash() { << ibm.m[12] << " " << ibm.m[13] << " " << ibm.m[14] << " " << ibm.m[15] << "\n"; } ccstd::string str{sstr.str()}; - std::size_t seed = 666; + std::size_t seed = 666; boost::hash_range(seed, str.begin(), str.end()); _hash = static_cast(seed); } diff --git a/native/cocos/3d/assets/Skeleton.h b/native/cocos/3d/assets/Skeleton.h index 18c93542e8..b9beb4f8ed 100644 --- a/native/cocos/3d/assets/Skeleton.h +++ b/native/cocos/3d/assets/Skeleton.h @@ -35,8 +35,8 @@ namespace cc { */ class Skeleton final : public Asset { public: - using Super = Asset; - Skeleton() = default; + using Super = Asset; + Skeleton() = default; ~Skeleton() override = default; /** * @en The path of all bones, the length always equals the length of [[bindposes]] @@ -73,7 +73,7 @@ public: * @zh 获取骨骼资源的哈希值 */ uint64_t getHash(); - void setHash(uint64_t hash) { _hash = hash; } + void setHash(uint64_t hash) { _hash = hash; } inline double getHashForJS() { return static_cast(getHash()); @@ -83,10 +83,10 @@ public: bool validate() const override; private: - ccstd::vector _joints; - ccstd::vector _bindposes; + ccstd::vector _joints; + ccstd::vector _bindposes; cc::optional> _invBindposes; - uint64_t _hash{0}; + uint64_t _hash{0}; }; } // namespace cc diff --git a/native/cocos/3d/misc/Buffer.cpp b/native/cocos/3d/misc/Buffer.cpp index 165b9f4c56..ee6840049d 100644 --- a/native/cocos/3d/misc/Buffer.cpp +++ b/native/cocos/3d/misc/Buffer.cpp @@ -40,7 +40,7 @@ Record typeMap{ ccstd::string getDataViewType(const gfx::FormatInfo &info) { ccstd::string type; - auto iter = typeMap.find(info.type); + auto iter = typeMap.find(info.type); if (iter != typeMap.end()) { type = iter->second; } else { @@ -53,20 +53,20 @@ ccstd::string getDataViewType(const gfx::FormatInfo &info) { } // namespace -using DataVariant = cc::variant; +using DataVariant = cc::variant; using MapBufferCallback = std::function; -DataView mapBuffer(DataView & target, - const MapBufferCallback & callback, +DataView mapBuffer(DataView &target, + const MapBufferCallback &callback, cc::optional aFormat, - cc::optional aOffset, - cc::optional aLength, - cc::optional aStride, - DataView * out) { + cc::optional aOffset, + cc::optional aLength, + cc::optional aStride, + DataView *out) { gfx::Format format = aFormat.has_value() ? aFormat.value() : gfx::Format::R32F; - uint32_t offset = aOffset.has_value() ? aOffset.value() : 0; - uint32_t length = aLength.has_value() ? aLength.value() : target.byteLength() - offset; - uint32_t stride = aStride.has_value() ? aStride.value() : 0; + uint32_t offset = aOffset.has_value() ? aOffset.value() : 0; + uint32_t length = aLength.has_value() ? aLength.value() : target.byteLength() - offset; + uint32_t stride = aStride.has_value() ? aStride.value() : 0; DataView dataView; if (out == nullptr) { @@ -82,7 +82,7 @@ DataView mapBuffer(DataView & target, static const ccstd::string SET_PREFIX{"set"}; static const ccstd::string GET_PREFIX{"get"}; - bool isFloat = info.type == gfx::FormatType::FLOAT || info.type == gfx::FormatType::UFLOAT; + bool isFloat = info.type == gfx::FormatType::FLOAT || info.type == gfx::FormatType::UFLOAT; DataView::IntWritter intWritter = nullptr; if (!isFloat) { intWritter = DataView::intWritterMap[SET_PREFIX + getDataViewType(info)]; @@ -94,7 +94,7 @@ DataView mapBuffer(DataView & target, } const uint32_t componentBytesLength = info.size / info.count; - const uint32_t nSeg = floor(length / stride); + const uint32_t nSeg = floor(length / stride); for (uint32_t iSeg = 0; iSeg < nSeg; ++iSeg) { const uint32_t x = offset + stride * iSeg; diff --git a/native/cocos/3d/misc/Buffer.h b/native/cocos/3d/misc/Buffer.h index d0b1358780..35228644a9 100644 --- a/native/cocos/3d/misc/Buffer.h +++ b/native/cocos/3d/misc/Buffer.h @@ -33,17 +33,17 @@ namespace cc { // default params behaviors just like on an plain, compact Float32Array template -void writeBuffer(DataView & target, +void writeBuffer(DataView &target, const ccstd::vector &data, - const gfx::Format & format = gfx::Format::R32F, - uint32_t offset = 0, - uint32_t stride = 0) { + const gfx::Format &format = gfx::Format::R32F, + uint32_t offset = 0, + uint32_t stride = 0) { const gfx::FormatInfo &info = gfx::GFX_FORMAT_INFOS[static_cast(format)]; if (stride == 0) { stride = info.size; } const uint32_t componentBytesLength = info.size / info.count; - const auto nSeg = static_cast(floor(data.size() / info.count)); + const auto nSeg = static_cast(floor(data.size() / info.count)); const uint32_t bytes = info.size / info.count * 8; @@ -112,15 +112,15 @@ void writeBuffer(DataView & target, } } -using DataVariant = cc::variant; +using DataVariant = cc::variant; using MapBufferCallback = std::function; -DataView mapBuffer(DataView & target, - const MapBufferCallback & callback, +DataView mapBuffer(DataView &target, + const MapBufferCallback &callback, cc::optional aFormat, - cc::optional aOffset, - cc::optional aLength, - cc::optional aStride, - DataView * out); + cc::optional aOffset, + cc::optional aLength, + cc::optional aStride, + DataView *out); } // namespace cc diff --git a/native/cocos/3d/misc/BufferBlob.cpp b/native/cocos/3d/misc/BufferBlob.cpp index 202b872975..cbdb945dbf 100644 --- a/native/cocos/3d/misc/BufferBlob.cpp +++ b/native/cocos/3d/misc/BufferBlob.cpp @@ -47,7 +47,7 @@ uint32_t BufferBlob::addBuffer(ArrayBuffer *arrayBuffer) { ArrayBuffer::Ptr BufferBlob::getCombined() { Int8Array result(_length); - uint32_t counter = 0; + uint32_t counter = 0; for (const auto &arrayBufferOrPadding : _arrayBufferOrPaddings) { if (const auto *p = cc::get_if(&arrayBufferOrPadding)) { diff --git a/native/cocos/3d/misc/BufferBlob.h b/native/cocos/3d/misc/BufferBlob.h index c69f85dfa8..efa1a7275e 100644 --- a/native/cocos/3d/misc/BufferBlob.h +++ b/native/cocos/3d/misc/BufferBlob.h @@ -42,7 +42,7 @@ public: private: ccstd::vector> _arrayBufferOrPaddings; - uint32_t _length{0}; + uint32_t _length{0}; }; } // namespace cc diff --git a/native/cocos/3d/misc/CreateMesh.cpp b/native/cocos/3d/misc/CreateMesh.cpp index d94b451386..009938252a 100644 --- a/native/cocos/3d/misc/CreateMesh.cpp +++ b/native/cocos/3d/misc/CreateMesh.cpp @@ -30,14 +30,14 @@ Mesh *MeshUtils::createMesh(const IGeometry &geometry, Mesh *out /*= nullptr*/, Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICreateMeshOptions &options /* = {}*/) { // Collect attributes and calculate length of result vertex buffer. gfx::AttributeList attributes; - uint32_t stride = 0; + uint32_t stride = 0; struct Channel { - uint32_t offset{0}; + uint32_t offset{0}; ccstd::vector data; // float? - gfx::Attribute attribute; + gfx::Attribute attribute; }; ccstd::vector channels; - uint32_t vertCount = 0; + uint32_t vertCount = 0; const gfx::Attribute *attr = nullptr; @@ -60,7 +60,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr attributes.emplace_back(*attr); const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attr->format)]; - vertCount = std::max(vertCount, static_cast(std::floor(positions.size() / info.count))); + vertCount = std::max(vertCount, static_cast(std::floor(positions.size() / info.count))); channels.emplace_back(Channel{stride, positions, *attr}); stride += info.size; } @@ -82,7 +82,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr attributes.emplace_back(*attr); const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attr->format)]; - vertCount = std::max(vertCount, static_cast(std::floor(geometry.normals->size() / info.count))); + vertCount = std::max(vertCount, static_cast(std::floor(geometry.normals->size() / info.count))); channels.emplace_back(Channel{stride, geometry.normals.value(), *attr}); stride += info.size; } @@ -104,7 +104,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr attributes.emplace_back(*attr); const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attr->format)]; - vertCount = std::max(vertCount, static_cast(std::floor(geometry.uvs->size() / info.count))); + vertCount = std::max(vertCount, static_cast(std::floor(geometry.uvs->size() / info.count))); channels.emplace_back(Channel{stride, geometry.uvs.value(), *attr}); stride += info.size; } @@ -126,7 +126,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr attributes.emplace_back(*attr); const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attr->format)]; - vertCount = std::max(vertCount, static_cast(std::floor(geometry.tangents->size() / info.count))); + vertCount = std::max(vertCount, static_cast(std::floor(geometry.tangents->size() / info.count))); channels.emplace_back(Channel{stride, geometry.tangents.value(), *attr}); stride += info.size; } @@ -148,7 +148,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr attributes.emplace_back(*attr); const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attr->format)]; - vertCount = std::max(vertCount, static_cast(std::floor(geometry.colors->size() / info.count))); + vertCount = std::max(vertCount, static_cast(std::floor(geometry.colors->size() / info.count))); channels.emplace_back(Channel{stride, geometry.colors.value(), *attr}); stride += info.size; } @@ -167,32 +167,32 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr BufferBlob bufferBlob; // Fill vertex buffer. - auto * vertexBuffer = ccnew ArrayBuffer(vertCount * stride); + auto *vertexBuffer = ccnew ArrayBuffer(vertCount * stride); DataView vertexBufferView(vertexBuffer); for (const auto &channel : channels) { writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride); } bufferBlob.setNextAlignment(0); Mesh::IVertexBundle vertexBundle; - Mesh::IBufferView buffferView; + Mesh::IBufferView buffferView; - buffferView.offset = bufferBlob.getLength(); - buffferView.length = static_cast(vertexBuffer->byteLength()); - buffferView.count = vertCount; - buffferView.stride = stride; + buffferView.offset = bufferBlob.getLength(); + buffferView.length = static_cast(vertexBuffer->byteLength()); + buffferView.count = vertCount; + buffferView.stride = stride; vertexBundle.attributes = attributes; - vertexBundle.view = buffferView; + vertexBundle.view = buffferView; bufferBlob.addBuffer(vertexBuffer); // Fill index buffer. ArrayBuffer::Ptr indexBuffer; - uint32_t idxCount = 0; - const uint32_t idxStride = 2; + uint32_t idxCount = 0; + const uint32_t idxStride = 2; if (geometry.indices.has_value()) { const ccstd::vector &indices = geometry.indices.value(); - idxCount = static_cast(indices.size()); - indexBuffer = ccnew ArrayBuffer(idxStride * idxCount); + idxCount = static_cast(indices.size()); + indexBuffer = ccnew ArrayBuffer(idxStride * idxCount); DataView indexBufferView(indexBuffer); writeBuffer(indexBufferView, indices, gfx::Format::R16UI); } @@ -200,15 +200,15 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr // Create primitive. Mesh::ISubMesh primitive; primitive.vertexBundelIndices = {0}; - primitive.primitiveMode = geometry.primitiveMode.has_value() ? geometry.primitiveMode.value() : gfx::PrimitiveMode::TRIANGLE_LIST; + primitive.primitiveMode = geometry.primitiveMode.has_value() ? geometry.primitiveMode.value() : gfx::PrimitiveMode::TRIANGLE_LIST; if (indexBuffer) { bufferBlob.setNextAlignment(idxStride); Mesh::IBufferView bufferView; - bufferView.offset = bufferBlob.getLength(); - bufferView.length = indexBuffer->byteLength(); - bufferView.count = idxCount; - bufferView.stride = idxStride; + bufferView.offset = bufferBlob.getLength(); + bufferView.length = indexBuffer->byteLength(); + bufferView.count = idxCount; + bufferView.stride = idxStride; primitive.indexView = bufferView; bufferBlob.addBuffer(indexBuffer); } @@ -232,7 +232,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr // Create mesh struct Mesh::IStruct meshStruct; meshStruct.vertexBundles = {vertexBundle}; - meshStruct.primitives = {primitive}; + meshStruct.primitives = {primitive}; if (minPosition.has_value()) { meshStruct.minPosition = minPosition.value(); @@ -243,7 +243,7 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ICr Mesh::ICreateInfo createInfo; createInfo.structInfo = std::move(meshStruct); - createInfo.data = Uint8Array(bufferBlob.getCombined()); + createInfo.data = Uint8Array(bufferBlob.getCombined()); return createInfo; } @@ -273,7 +273,7 @@ Mesh *MeshUtils::createDynamicMesh(index_t primitiveIndex, const IDynamicGeometr Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geometry, const ICreateDynamicMeshOptions &options /* = {}*/) { gfx::AttributeList attributes; - uint32_t stream = 0U; + uint32_t stream = 0U; if (!geometry.positions.empty()) { attributes.push_back({gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F, false, stream++, false, 0U}); @@ -297,15 +297,15 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome if (geometry.customAttributes.has_value()) { for (const auto &ca : geometry.customAttributes.value()) { - auto attr = ca.attr; + auto attr = ca.attr; attr.stream = stream++; attributes.emplace_back(attr); } } ccstd::vector vertexBundles; - ccstd::vector primitives; - uint32_t dataSize = 0U; + ccstd::vector primitives; + uint32_t dataSize = 0U; for (auto i = 0U; i < options.maxSubMeshes; i++) { Mesh::ISubMesh primitive; @@ -313,8 +313,8 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome // add vertex buffers for (const auto &attr : attributes) { - const auto &formatInfo = gfx::GFX_FORMAT_INFOS[static_cast(attr.format)]; - uint32_t vertexBufferSize = options.maxSubMeshVertices * formatInfo.size; + const auto &formatInfo = gfx::GFX_FORMAT_INFOS[static_cast(attr.format)]; + uint32_t vertexBufferSize = options.maxSubMeshVertices * formatInfo.size; Mesh::IBufferView vertexView = { dataSize, @@ -371,12 +371,12 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome Mesh::IStruct meshStruct; meshStruct.vertexBundles = vertexBundles; - meshStruct.primitives = primitives; - meshStruct.dynamic = std::move(dynamicStruct); + meshStruct.primitives = primitives; + meshStruct.dynamic = std::move(dynamicStruct); Mesh::ICreateInfo createInfo; createInfo.structInfo = std::move(meshStruct); - createInfo.data = Uint8Array(dataSize); + createInfo.data = Uint8Array(dataSize); return createInfo; } diff --git a/native/cocos/3d/models/BakedSkinningModel.cpp b/native/cocos/3d/models/BakedSkinningModel.cpp index 874241db30..bcbd1a817d 100644 --- a/native/cocos/3d/models/BakedSkinningModel.cpp +++ b/native/cocos/3d/models/BakedSkinningModel.cpp @@ -72,7 +72,7 @@ void BakedSkinningModel::destroy() { void BakedSkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh) { _skeleton = skeleton; - _mesh = mesh; + _mesh = mesh; if (skeleton == nullptr || skinningRoot == nullptr || mesh == nullptr) return; setTransform(skinningRoot); @@ -94,9 +94,9 @@ void BakedSkinningModel::updateTransform(uint32_t stamp) { if (!_isUploadedAnim) { return; } - IAnimInfo & animInfo = _jointMedium.animInfo; + IAnimInfo &animInfo = _jointMedium.animInfo; geometry::AABB *skelBound = nullptr; - const float * curFrame = animInfo.curFrame; + const float *curFrame = animInfo.curFrame; // float curFrame = info.data[0]; auto index = static_cast(std::roundf(*curFrame)); if (!_jointMedium.boundsInfo.empty() && index < _jointMedium.boundsInfo.size()) { @@ -112,10 +112,10 @@ void BakedSkinningModel::updateTransform(uint32_t stamp) { void BakedSkinningModel::updateUBOs(uint32_t stamp) { Super::updateUBOs(stamp); - IAnimInfo & info = _jointMedium.animInfo; - int idx = _instAnimInfoIdx; - const float *curFrame = info.curFrame; - uint32_t frameDataBytes = info.frameDataBytes; + IAnimInfo &info = _jointMedium.animInfo; + int idx = _instAnimInfoIdx; + const float *curFrame = info.curFrame; + uint32_t frameDataBytes = info.frameDataBytes; // float curFrame = info.data[0]; // uint32_t curFrameDataBytes = info.data.byteLength(); if (idx >= 0) { @@ -136,13 +136,13 @@ void BakedSkinningModel::applyJointTexture(const cc::optional(textureHandle->handle.texture->getWidth()); - jointTextureInfo[1] = static_cast(_skeleton->getJoints().size()); - jointTextureInfo[2] = static_cast(textureHandle->pixelOffset) + 0.1F; // guard against floor() underflow - jointTextureInfo[3] = 1 / jointTextureInfo[0]; + jointTextureInfo[0] = static_cast(textureHandle->handle.texture->getWidth()); + jointTextureInfo[1] = static_cast(_skeleton->getJoints().size()); + jointTextureInfo[2] = static_cast(textureHandle->pixelOffset) + 0.1F; // guard against floor() underflow + jointTextureInfo[3] = 1 / jointTextureInfo[0]; updateInstancedJointTextureInfo(); if (buffer != nullptr) { buffer->update(&jointTextureInfo[0], jointTextureInfo.byteLength()); @@ -164,8 +164,8 @@ ccstd::vector BakedSkinningModel::getMacroPatches(index_t su void BakedSkinningModel::updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) { Super::updateLocalDescriptors(subModelIndex, descriptorSet); - gfx::Buffer * buffer = _jointMedium.buffer; - auto & texture = _jointMedium.texture; + gfx::Buffer *buffer = _jointMedium.buffer; + auto &texture = _jointMedium.texture; const IAnimInfo &animInfo = _jointMedium.animInfo; descriptorSet->bindBuffer(pipeline::UBOSkinningTexture::BINDING, buffer); descriptorSet->bindBuffer(pipeline::UBOSkinningAnimation::BINDING, animInfo.buffer); @@ -183,9 +183,9 @@ void BakedSkinningModel::updateInstancedAttributes(const ccstd::vector= 0) { auto &view = getInstancedAttributeBlock()->views[idx]; setTypedArrayValue(view, 0, *animInfo.curFrame); //NOTE: curFrame is only used in JSB. @@ -195,20 +195,20 @@ void BakedSkinningModel::updateInstancedJointTextureInfo() { } void BakedSkinningModel::syncAnimInfoForJS(gfx::Buffer *buffer, const Float32Array &data, Uint8Array &dirty) { - _jointMedium.animInfo.buffer = buffer; - _jointMedium.animInfo.curFrame = &data[0]; + _jointMedium.animInfo.buffer = buffer; + _jointMedium.animInfo.curFrame = &data[0]; _jointMedium.animInfo.frameDataBytes = data.byteLength(); - _jointMedium.animInfo.dirtyForJSB = &dirty[0]; + _jointMedium.animInfo.dirtyForJSB = &dirty[0]; } void BakedSkinningModel::syncDataForJS(const ccstd::vector> &boundsInfo, - const cc::optional & modelBound, - float jointTextureInfo0, - float jointTextureInfo1, - float jointTextureInfo2, - float jointTextureInfo3, - gfx::Texture * tex, - const Float32Array & animInfoData) { + const cc::optional &modelBound, + float jointTextureInfo0, + float jointTextureInfo1, + float jointTextureInfo2, + float jointTextureInfo3, + gfx::Texture *tex, + const Float32Array &animInfoData) { _jointMedium.boundsInfo = boundsInfo; if (modelBound.has_value()) { @@ -223,11 +223,11 @@ void BakedSkinningModel::syncDataForJS(const ccstd::vectorhandle.texture = tex; - _jointMedium.texture = textureInfo; + IJointTextureHandle *textureInfo = IJointTextureHandle::createJoinTextureHandle(); + textureInfo->handle.texture = tex; + _jointMedium.texture = textureInfo; updateInstancedJointTextureInfo(); diff --git a/native/cocos/3d/models/BakedSkinningModel.h b/native/cocos/3d/models/BakedSkinningModel.h index b89c5bb149..9f1ccddb30 100644 --- a/native/cocos/3d/models/BakedSkinningModel.h +++ b/native/cocos/3d/models/BakedSkinningModel.h @@ -41,10 +41,10 @@ class Texture; class DataPoolManager; struct BakedJointInfo { - IntrusivePtr buffer; - Float32Array jointTextureInfo; - cc::optional texture; - IAnimInfo animInfo; + IntrusivePtr buffer; + Float32Array jointTextureInfo; + cc::optional texture; + IAnimInfo animInfo; ccstd::vector> boundsInfo; }; @@ -56,12 +56,12 @@ public: void destroy() override; - ccstd::vector getMacroPatches(index_t subModelIndex) override; - void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) override; - void updateTransform(uint32_t stamp) override; - void updateUBOs(uint32_t stamp) override; - void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; - void updateInstancedJointTextureInfo(); + ccstd::vector getMacroPatches(index_t subModelIndex) override; + void updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) override; + void updateTransform(uint32_t stamp) override; + void updateUBOs(uint32_t stamp) override; + void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; + void updateInstancedJointTextureInfo(); // void uploadAnimation(AnimationClip *anim); // TODO(xwx): AnimationClip not define void bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh); @@ -76,13 +76,13 @@ public: void syncAnimInfoForJS(gfx::Buffer *buffer, const Float32Array &data, Uint8Array &dirty); void syncDataForJS(const ccstd::vector> &boundsInfo, - const cc::optional & modelBound, - float jointTextureInfo0, - float jointTextureInfo1, - float jointTextureInfo2, - float jointTextureInfo3, - gfx::Texture * tex, - const Float32Array & animInfoData); + const cc::optional &modelBound, + float jointTextureInfo0, + float jointTextureInfo1, + float jointTextureInfo2, + float jointTextureInfo3, + gfx::Texture *tex, + const Float32Array &animInfoData); void setUploadedAnimForJS(bool value) { _isUploadedAnim = value; } @@ -91,10 +91,10 @@ protected: private: BakedJointInfo _jointMedium; - index_t _instAnimInfoIdx{CC_INVALID_INDEX}; + index_t _instAnimInfoIdx{CC_INVALID_INDEX}; // IntrusivePtr _dataPoolManager; IntrusivePtr _skeleton; - IntrusivePtr _mesh; + IntrusivePtr _mesh; // AnimationClip* uploadedAnim; bool _isUploadedAnim{false}; diff --git a/native/cocos/3d/models/MorphModel.h b/native/cocos/3d/models/MorphModel.h index 93ec52f98c..bcaf13dcfd 100644 --- a/native/cocos/3d/models/MorphModel.h +++ b/native/cocos/3d/models/MorphModel.h @@ -35,14 +35,14 @@ class MorphModel : public scene::Model { public: using Super = scene::Model; - MorphModel() = default; + MorphModel() = default; ~MorphModel() override = default; CC_DISALLOW_COPY_MOVE_ASSIGN(MorphModel); - ccstd::vector getMacroPatches(index_t subModelIndex) override; - void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override; - void destroy() override; - void setSubModelMaterial(index_t idx, Material *mat) override; + ccstd::vector getMacroPatches(index_t subModelIndex) override; + void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override; + void destroy() override; + void setSubModelMaterial(index_t idx, Material *mat) override; inline void setMorphRendering(MorphRenderingInstance *morphRendering) { _morphRenderingInstance = morphRendering; } diff --git a/native/cocos/3d/models/SkinningModel.cpp b/native/cocos/3d/models/SkinningModel.cpp index d9d8a5cbf0..e6be5add19 100644 --- a/native/cocos/3d/models/SkinningModel.cpp +++ b/native/cocos/3d/models/SkinningModel.cpp @@ -85,18 +85,18 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m if (!skeleton || !skinningRoot || !mesh) return; setTransform(skinningRoot); - auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton); - const auto &jointMaps = mesh->getStruct().jointMaps; + auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton); + const auto &jointMaps = mesh->getStruct().jointMaps; ensureEnoughBuffers((jointMaps.has_value() && !jointMaps->empty()) ? static_cast(jointMaps->size()) : 1); _bufferIndices = mesh->getJointBufferIndices(); for (index_t index = 0; index < skeleton->getJoints().size(); ++index) { - geometry::AABB *bound = boneSpaceBounds[index]; - auto * target = skinningRoot->getChildByPath(skeleton->getJoints()[index]); + geometry::AABB *bound = boneSpaceBounds[index]; + auto *target = skinningRoot->getChildByPath(skeleton->getJoints()[index]); if (!bound || !target) continue; - auto * transform = cc::getTransform(target, skinningRoot); - const Mat4 & bindPose = skeleton->getBindposes()[index]; + auto *transform = cc::getTransform(target, skinningRoot); + const Mat4 &bindPose = skeleton->getBindposes()[index]; ccstd::vector indices; ccstd::vector buffers; if (!jointMaps.has_value()) { @@ -107,12 +107,12 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m } JointInfo jointInfo; - jointInfo.bound = bound; - jointInfo.target = target; - jointInfo.bindpose = bindPose; + jointInfo.bound = bound; + jointInfo.target = target; + jointInfo.bindpose = bindPose; jointInfo.transform = transform; - jointInfo.buffers = std::move(buffers); - jointInfo.indices = std::move(indices); + jointInfo.buffers = std::move(buffers); + jointInfo.indices = std::move(indices); _joints.emplace_back(std::move(jointInfo)); } } @@ -123,15 +123,15 @@ void SkinningModel::updateTransform(uint32_t stamp) { root->updateWorldTransform(); _localDataUpdated = true; } - Vec3 v3Min{INFINITY, INFINITY, INFINITY}; - Vec3 v3Max{-INFINITY, -INFINITY, -INFINITY}; + Vec3 v3Min{INFINITY, INFINITY, INFINITY}; + Vec3 v3Max{-INFINITY, -INFINITY, -INFINITY}; geometry::AABB ab1; - Vec3 v31; - Vec3 v32; + Vec3 v31; + Vec3 v32; for (JointInfo &jointInfo : _joints) { - const auto *bound = jointInfo.bound; - auto * transform = jointInfo.transform; - Mat4 worldMatrix = cc::getWorldMatrix(transform, static_cast(stamp)); + const auto *bound = jointInfo.bound; + auto *transform = jointInfo.transform; + Mat4 worldMatrix = cc::getWorldMatrix(transform, static_cast(stamp)); jointInfo.bound->transform(worldMatrix, &ab1); ab1.getBoundary(&v31, &v32); Vec3::min(v3Min, v31, &v3Min); @@ -146,7 +146,7 @@ void SkinningModel::updateTransform(uint32_t stamp) { void SkinningModel::updateUBOs(uint32_t stamp) { Super::updateUBOs(stamp); uint32_t bIdx = 0; - Mat4 mat4; + Mat4 mat4; for (const JointInfo &jointInfo : _joints) { Mat4::multiply(jointInfo.transform->world, jointInfo.bindpose, &mat4); for (uint32_t buffer : jointInfo.buffers) { @@ -164,7 +164,7 @@ void SkinningModel::updateUBOs(uint32_t stamp) { void SkinningModel::initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) { const auto &original = subMeshData->getVertexBuffers(); - auto & iaInfo = subMeshData->getIaInfo(); + auto &iaInfo = subMeshData->getIaInfo(); iaInfo.vertexBuffers = subMeshData->getJointMappedBuffers(); Super::initSubModel(idx, subMeshData, mat); iaInfo.vertexBuffers = original; @@ -177,14 +177,14 @@ ccstd::vector SkinningModel::getMacroPatches(index_t subMode patches.insert(std::begin(patches), std::begin(myPatches), std::end(myPatches)); return patches; } - + return myPatches; } void SkinningModel::uploadJointData(uint32_t base, const Mat4 &mat, float *dst) { memcpy(reinterpret_cast(dst + base), mat.m, sizeof(float) * 12); - dst[base + 3] = mat.m[12]; - dst[base + 7] = mat.m[13]; + dst[base + 3] = mat.m[12]; + dst[base + 7] = mat.m[13]; dst[base + 11] = mat.m[14]; } diff --git a/native/cocos/3d/models/SkinningModel.h b/native/cocos/3d/models/SkinningModel.h index 86f9e5c63e..7eaf3b6de1 100644 --- a/native/cocos/3d/models/SkinningModel.h +++ b/native/cocos/3d/models/SkinningModel.h @@ -40,10 +40,10 @@ class AABB; } struct JointInfo { - geometry::AABB * bound{nullptr}; - Node * target{nullptr}; - Mat4 bindpose; - IJointTransform * transform{nullptr}; + geometry::AABB *bound{nullptr}; + Node *target{nullptr}; + Mat4 bindpose; + IJointTransform *transform{nullptr}; ccstd::vector buffers; ccstd::vector indices; }; @@ -59,19 +59,19 @@ public: void updateUBOs(uint32_t stamp) override; void destroy() override; - void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override; - ccstd::vector getMacroPatches(index_t subModelIndex) override; - void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; + void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat) override; + ccstd::vector getMacroPatches(index_t subModelIndex) override; + void updateInstancedAttributes(const ccstd::vector &attributes, scene::Pass *pass) override; void bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *mesh); private: static void uploadJointData(uint32_t base, const Mat4 &mat, float *dst); - void ensureEnoughBuffers(index_t count); + void ensureEnoughBuffers(index_t count); - ccstd::vector _bufferIndices; - ccstd::vector> _buffers; - ccstd::vector _joints; + ccstd::vector _bufferIndices; + ccstd::vector> _buffers; + ccstd::vector _joints; ccstd::vector *> _dataArray; CC_DISALLOW_COPY_MOVE_ASSIGN(SkinningModel); diff --git a/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.cpp b/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.cpp index 335da50766..e5091613f7 100644 --- a/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.cpp +++ b/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.cpp @@ -40,25 +40,25 @@ cc::gfx::Format selectJointsMediumFormat(cc::gfx::Device *device) { // Linear Blending Skinning void uploadJointDataLBS(cc::Float32Array out, uint32_t base, const cc::Mat4 &mat, bool /*firstBone*/) { - out[base + 0] = mat.m[0]; - out[base + 1] = mat.m[1]; - out[base + 2] = mat.m[2]; - out[base + 3] = mat.m[12]; - out[base + 4] = mat.m[4]; - out[base + 5] = mat.m[5]; - out[base + 6] = mat.m[6]; - out[base + 7] = mat.m[13]; - out[base + 8] = mat.m[8]; - out[base + 9] = mat.m[9]; + out[base + 0] = mat.m[0]; + out[base + 1] = mat.m[1]; + out[base + 2] = mat.m[2]; + out[base + 3] = mat.m[12]; + out[base + 4] = mat.m[4]; + out[base + 5] = mat.m[5]; + out[base + 6] = mat.m[6]; + out[base + 7] = mat.m[13]; + out[base + 8] = mat.m[8]; + out[base + 9] = mat.m[9]; out[base + 10] = mat.m[10]; out[base + 11] = mat.m[14]; } cc::Quaternion dq0; cc::Quaternion dq1; -cc::Vec3 v31; +cc::Vec3 v31; cc::Quaternion qt1; -cc::Vec3 v32; +cc::Vec3 v32; float dot(const cc::Quaternion &a, const cc::Quaternion &b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; @@ -87,16 +87,16 @@ void uploadJointDataDQS(cc::Float32Array out, uint32_t base, cc::Mat4 &mat, bool dq1.w = 0; multiplyScalar(dq1 * qt1, 0.5, &dq1); // upload - out[base + 0] = qt1.x; - out[base + 1] = qt1.y; - out[base + 2] = qt1.z; - out[base + 3] = qt1.w; - out[base + 4] = dq1.x; - out[base + 5] = dq1.y; - out[base + 6] = dq1.z; - out[base + 7] = dq1.w; - out[base + 8] = v32.x; - out[base + 9] = v32.y; + out[base + 0] = qt1.x; + out[base + 1] = qt1.y; + out[base + 2] = qt1.z; + out[base + 3] = qt1.w; + out[base + 4] = dq1.x; + out[base + 5] = dq1.y; + out[base + 6] = dq1.z; + out[base + 7] = dq1.w; + out[base + 8] = v32.x; + out[base + 9] = v32.y; out[base + 10] = v32.z; } @@ -136,18 +136,18 @@ cc::Mat4 *getWorldTransformUntilRoot(cc::Node *target, cc::Node *root, cc::Mat4 } // namespace namespace cc { JointTexturePool::JointTexturePool(gfx::Device *device) { - _device = device; + _device = device; const auto &format = selectJointsMediumFormat(_device); - _formatSize = gfx::GFX_FORMAT_INFOS[static_cast(format)].size; - _pixelsPerJoint = 48 / _formatSize; - _pool = ccnew TextureBufferPool(device); + _formatSize = gfx::GFX_FORMAT_INFOS[static_cast(format)].size; + _pixelsPerJoint = 48 / _formatSize; + _pool = ccnew TextureBufferPool(device); ITextureBufferPoolInfo poolInfo; - poolInfo.format = format; + poolInfo.format = format; poolInfo.roundUpFn = roundUpType{roundUpTextureSize}; _pool->initialize(poolInfo); _customPool = ccnew TextureBufferPool(device); ITextureBufferPoolInfo customPoolInfo; - customPoolInfo.format = format; + customPoolInfo.format = format; customPoolInfo.roundUpFn = roundUpType{roundUpTextureSize}; _customPool->initialize(customPoolInfo); } @@ -161,7 +161,7 @@ void JointTexturePool::registerCustomTextureLayouts(const ccstd::vector(_customPool->createChunk(layout.textureLength)); for (const auto &content : layout.contents) { - auto skeleton = content.skeleton; + auto skeleton = content.skeleton; _chunkIdxMap[skeleton] = chunkIdx; // include default pose too for (const auto &clip : content.clips) { _chunkIdxMap[skeleton ^ clip] = chunkIdx; @@ -171,19 +171,19 @@ void JointTexturePool::registerCustomTextureLayouts(const ccstd::vector JointTexturePool::getDefaultPoseTexture(Skeleton *skeleton, Mesh *mesh, Node *skinningRoot) { - uint64_t hash = skeleton->getHash() ^ 0; // may not equal to skeleton.hash + uint64_t hash = skeleton->getHash() ^ 0; // may not equal to skeleton.hash cc::optional texture; if (_textureBuffers.find(hash) != _textureBuffers.end()) { texture = _textureBuffers[hash]; } - const ccstd::vector &joints = skeleton->getJoints(); - const ccstd::vector & bindPoses = skeleton->getBindposes(); - Float32Array textureBuffer; - bool buildTexture = false; - auto jointCount = static_cast(joints.size()); + const ccstd::vector &joints = skeleton->getJoints(); + const ccstd::vector &bindPoses = skeleton->getBindposes(); + Float32Array textureBuffer; + bool buildTexture = false; + auto jointCount = static_cast(joints.size()); if (!texture.has_value()) { - uint32_t bufSize = jointCount * 12; + uint32_t bufSize = jointCount * 12; ITextureBufferHandle handle; if (_chunkIdxMap.find(hash) != _chunkIdxMap.end()) { handle = _customPool->alloc(bufSize * Float32Array::BYTES_PER_ELEMENT, _chunkIdxMap[hash]); @@ -192,29 +192,29 @@ cc::optional JointTexturePool::getDefaultPoseTexture(Skel return texture; } IJointTextureHandle *textureHandle = IJointTextureHandle::createJoinTextureHandle(); - textureHandle->pixelOffset = handle.start / _formatSize; - textureHandle->refCount = 1; - textureHandle->clipHash = 0; - textureHandle->skeletonHash = skeleton->getHash(); - textureHandle->readyToBeDeleted = false; - textureHandle->handle = handle; - texture = textureHandle; - textureBuffer = Float32Array(bufSize); - buildTexture = true; + textureHandle->pixelOffset = handle.start / _formatSize; + textureHandle->refCount = 1; + textureHandle->clipHash = 0; + textureHandle->skeletonHash = skeleton->getHash(); + textureHandle->readyToBeDeleted = false; + textureHandle->handle = handle; + texture = textureHandle; + textureBuffer = Float32Array(bufSize); + buildTexture = true; } else { texture.value()->refCount++; } geometry::AABB ab1; - Mat4 mat4; - Vec3 v34; - Vec3 v33; - Vec3 v3Min(-INF, -INF, -INF); - Vec3 v3Max(-INF, -INF, -INF); - auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton); + Mat4 mat4; + Vec3 v34; + Vec3 v33; + Vec3 v3Min(-INF, -INF, -INF); + Vec3 v3Max(-INF, -INF, -INF); + auto boneSpaceBounds = mesh->getBoneSpaceBounds(skeleton); for (uint32_t j = 0, offset = 0; j < jointCount; ++j, offset += 12) { auto *node = skinningRoot->getChildByPath(joints[j]); - Mat4 mat = node ? *getWorldTransformUntilRoot(node, skinningRoot, &mat4) : skeleton->getInverseBindposes()[j]; + Mat4 mat = node ? *getWorldTransformUntilRoot(node, skinningRoot, &mat4) : skeleton->getInverseBindposes()[j]; if (j < boneSpaceBounds.size()) { auto *bound = boneSpaceBounds[j].get(); bound->transform(mat, &ab1); @@ -474,9 +474,9 @@ IAnimInfo JointAnimationInfo::getData(const ccstd::string &nodeID) { Float32Array data; buffer->update(data.buffer()->getData()); IAnimInfo info; - info.buffer = buffer; - info.data = data; - info.dirty = false; + info.buffer = buffer; + info.data = data; + info.dirty = false; _pool[nodeID] = info; return info; diff --git a/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.h b/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.h index 3e83830ad9..80882bbaab 100644 --- a/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.h +++ b/native/cocos/3d/skeletal-animation/SkeletalAnimationUtils.h @@ -42,32 +42,32 @@ class Mesh; // _chunkIdxMap[key] = skeleton ^ clips[i] struct IChunkContent { - uint64_t skeleton{0}; + uint64_t skeleton{0}; ccstd::vector clips; }; struct ICustomJointTextureLayout { - uint32_t textureLength{0}; + uint32_t textureLength{0}; ccstd::vector contents; }; struct IInternalJointAnimInfo { - cc::optional downstream; // downstream default pose, if present - cc::optional> curveData; // the nearest animation curve, if present - index_t bindposeIdx{0}; // index of the actual bindpose to use - cc::optional bindposeCorrection; // correction factor from the original bindpose + cc::optional downstream; // downstream default pose, if present + cc::optional> curveData; // the nearest animation curve, if present + index_t bindposeIdx{0}; // index of the actual bindpose to use + cc::optional bindposeCorrection; // correction factor from the original bindpose }; class IJointTextureHandle { public: - uint32_t pixelOffset{0}; - uint32_t refCount{0}; - uint64_t clipHash{0}; - uint64_t skeletonHash{0}; - bool readyToBeDeleted{false}; - ITextureBufferHandle handle; + uint32_t pixelOffset{0}; + uint32_t refCount{0}; + uint64_t clipHash{0}; + uint64_t skeletonHash{0}; + bool readyToBeDeleted{false}; + ITextureBufferHandle handle; ccstd::unordered_map> bounds; - cc::optional> animInfos; + cc::optional> animInfos; static IJointTextureHandle *createJoinTextureHandle() { return ccnew IJointTextureHandle(); @@ -114,13 +114,13 @@ public: private: // const IInternalJointAnimInfo &createAnimInfos(Skeleton *skeleton, AnimationClip *clip, Node *skinningRoot); // TODO(xwx): AnimationClip not define - gfx::Device * _device{nullptr}; - IntrusivePtr _pool; + gfx::Device *_device{nullptr}; + IntrusivePtr _pool; ccstd::unordered_map _textureBuffers; - uint32_t _formatSize{0}; - uint32_t _pixelsPerJoint{0}; - IntrusivePtr _customPool; - ccstd::unordered_map _chunkIdxMap; // hash -> chunkIdx + uint32_t _formatSize{0}; + uint32_t _pixelsPerJoint{0}; + IntrusivePtr _customPool; + ccstd::unordered_map _chunkIdxMap; // hash -> chunkIdx CC_DISALLOW_COPY_MOVE_ASSIGN(JointTexturePool); }; @@ -128,10 +128,10 @@ private: struct IAnimInfo { gfx::Buffer *buffer{nullptr}; Float32Array data; - const float *curFrame{nullptr}; // Only used in JSB - uint32_t frameDataBytes{0}; // Only used in JSB - uint8_t * dirtyForJSB{nullptr}; // Only used in JSB - bool dirty{false}; + const float *curFrame{nullptr}; // Only used in JSB + uint32_t frameDataBytes{0}; // Only used in JSB + uint8_t *dirtyForJSB{nullptr}; // Only used in JSB + bool dirty{false}; }; class JointAnimationInfo : public RefCounted { @@ -140,14 +140,14 @@ public: explicit JointAnimationInfo(gfx::Device *device); ~JointAnimationInfo() override = default; - IAnimInfo getData(const ccstd::string &nodeID = "-1"); - void destroy(const ccstd::string &nodeID); + IAnimInfo getData(const ccstd::string &nodeID = "-1"); + void destroy(const ccstd::string &nodeID); static const IAnimInfo &switchClip(IAnimInfo &info /*, AnimationClip *clip */); - void clear(); + void clear(); private: ccstd::unordered_map _pool; // pre node - gfx::Device * _device{nullptr}; + gfx::Device *_device{nullptr}; CC_DISALLOW_COPY_MOVE_ASSIGN(JointAnimationInfo); }; diff --git a/native/cocos/application/ApplicationManager.h b/native/cocos/application/ApplicationManager.h index 7a12ed4e5e..26b475c5f3 100644 --- a/native/cocos/application/ApplicationManager.h +++ b/native/cocos/application/ApplicationManager.h @@ -32,7 +32,7 @@ namespace cc { class CC_DLL ApplicationManager { public: - static ApplicationManager *getInstance(); + static ApplicationManager* getInstance(); using ApplicationPtr = std::shared_ptr; @@ -64,7 +64,7 @@ public: private: std::weak_ptr _currentApp; - ccstd::vector _apps; + ccstd::vector _apps; }; } // namespace cc diff --git a/native/cocos/application/BaseApplication.h b/native/cocos/application/BaseApplication.h index 07b8fe99d9..3b35b13013 100644 --- a/native/cocos/application/BaseApplication.h +++ b/native/cocos/application/BaseApplication.h @@ -40,7 +40,7 @@ public: /** * @brief Application main business logic. */ - virtual int32_t run(int argc, + virtual int32_t run(int argc, const char **argv) = 0; /** * @brief Pause the application. diff --git a/native/cocos/application/BaseGame.h b/native/cocos/application/BaseGame.h index 42ba258b55..4e65ea740e 100644 --- a/native/cocos/application/BaseGame.h +++ b/native/cocos/application/BaseGame.h @@ -30,18 +30,18 @@ namespace cc { class BaseGame : public CocosApplication { public: struct DebuggerInfo { - bool enabled{true}; - int32_t port{6086}; + bool enabled{true}; + int32_t port{6086}; std::string address{"0.0.0.0"}; - bool pauseOnStart{false}; + bool pauseOnStart{false}; }; struct WindowInfo { std::string title; - int32_t x{-1}; - int32_t y{-1}; - int32_t width{-1}; - int32_t height{-1}; - int32_t flags{-1}; + int32_t x{-1}; + int32_t y{-1}; + int32_t width{-1}; + int32_t height{-1}; + int32_t flags{-1}; }; BaseGame() = default; @@ -51,9 +51,9 @@ public: // override default value //_windowInfo.x = _windowInfo.x == -1 ? 0 : _windowInfo.x; //_windowInfo.y = _windowInfo.y == -1 ? 0 : _windowInfo.y; - _windowInfo.width = _windowInfo.width == -1 ? 800 : _windowInfo.width; + _windowInfo.width = _windowInfo.width == -1 ? 800 : _windowInfo.width; _windowInfo.height = _windowInfo.height == -1 ? 600 : _windowInfo.height; - _windowInfo.flags = _windowInfo.flags == -1 ? cc::ISystemWindow::CC_WINDOW_SHOWN | + _windowInfo.flags = _windowInfo.flags == -1 ? cc::ISystemWindow::CC_WINDOW_SHOWN | cc::ISystemWindow::CC_WINDOW_RESIZABLE | cc::ISystemWindow::CC_WINDOW_INPUT_FOCUS : _windowInfo.flags; @@ -82,8 +82,8 @@ public: } protected: - std::string _xxteaKey; + std::string _xxteaKey; DebuggerInfo _debuggerInfo; - WindowInfo _windowInfo; + WindowInfo _windowInfo; }; } // namespace cc diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp index afe3c9e57d..abc4b579b3 100644 --- a/native/cocos/application/CocosApplication.cpp +++ b/native/cocos/application/CocosApplication.cpp @@ -39,7 +39,7 @@ namespace cc { CocosApplication::CocosApplication() { - _engine = BaseEngine::createEngine(); + _engine = BaseEngine::createEngine(); _systemWidow = _engine->getInterface(); CC_ASSERT(_systemWidow != nullptr); } @@ -78,9 +78,9 @@ int CocosApplication::init() { se->start(); #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - auto logicSize = _systemWidow->getViewSize(); - IScreen *screen = _engine->getInterface(); - float pixelRatio = screen->getDevicePixelRatio(); + auto logicSize = _systemWidow->getViewSize(); + IScreen *screen = _engine->getInterface(); + float pixelRatio = screen->getDevicePixelRatio(); cc::EventDispatcher::dispatchResizeEvent(logicSize.x * pixelRatio, logicSize.y * pixelRatio); #endif return 0; diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h index 8bae8eb18f..100441ed00 100644 --- a/native/cocos/application/CocosApplication.h +++ b/native/cocos/application/CocosApplication.h @@ -98,7 +98,7 @@ public: * @param h: Window height * @param flags: Window flag */ - virtual void createWindow(const char* title, int32_t w, + virtual void createWindow(const char *title, int32_t w, int32_t h, int32_t flags); #endif /** @@ -107,12 +107,12 @@ public: * @param port:Server port. * @param isWaitForConnect:Is Wait for connect. */ - virtual void setDebugIpAndPort(const ccstd::string& serverAddr, uint32_t port, bool isWaitForConnect); + virtual void setDebugIpAndPort(const ccstd::string &serverAddr, uint32_t port, bool isWaitForConnect); /** * @brief Run the script file * @param filePath:script path. */ - virtual void runScript(const ccstd::string& filePath); + virtual void runScript(const ccstd::string &filePath); /** * @brief Script exception handling * @param location,Exception location @@ -123,7 +123,7 @@ public: virtual void setXXTeaKey(const ccstd::string &key); private: - ISystemWindow* _systemWidow{nullptr}; + ISystemWindow *_systemWidow{nullptr}; BaseEngine::Ptr _engine{nullptr}; }; } // namespace cc diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index 6e12b5b0c7..1ecfddd06d 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -56,25 +56,25 @@ using namespace cc; //NOLINT -const int AudioEngine::INVALID_AUDIO_ID = -1; -const float AudioEngine::TIME_UNKNOWN = -1.0F; +const int AudioEngine::INVALID_AUDIO_ID = -1; +const float AudioEngine::TIME_UNKNOWN = -1.0F; //audio file path,audio IDs ccstd::unordered_map> AudioEngine::sAudioPathIDMap; //profileName,ProfileHelper ccstd::unordered_map AudioEngine::sAudioPathProfileHelperMap; -unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES; -AudioEngine::ProfileHelper * AudioEngine::sDefaultProfileHelper = nullptr; -ccstd::unordered_map AudioEngine::sAudioIDInfoMap; -AudioEngineImpl * AudioEngine::sAudioEngineImpl = nullptr; +unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES; +AudioEngine::ProfileHelper *AudioEngine::sDefaultProfileHelper = nullptr; +ccstd::unordered_map AudioEngine::sAudioIDInfoMap; +AudioEngineImpl *AudioEngine::sAudioEngineImpl = nullptr; -float AudioEngine::sVolumeFactor = 1.0F; -uint32_t AudioEngine::sOnPauseListenerID = 0; -uint32_t AudioEngine::sOnResumeListenerID = 0; +float AudioEngine::sVolumeFactor = 1.0F; +uint32_t AudioEngine::sOnPauseListenerID = 0; +uint32_t AudioEngine::sOnResumeListenerID = 0; ccstd::vector AudioEngine::sBreakAudioID; AudioEngine::AudioEngineThreadPool *AudioEngine::sThreadPool = nullptr; -bool AudioEngine::sIsEnabled = true; +bool AudioEngine::sIsEnabled = true; AudioEngine::AudioInfo::AudioInfo() : filePath(nullptr), @@ -135,12 +135,12 @@ private: } } - ccstd::vector _workers; + ccstd::vector _workers; ccstd::queue> _taskQueue; - std::mutex _queueMutex; + std::mutex _queueMutex; std::condition_variable _taskCondition; - bool _stop{}; + bool _stop{}; }; void AudioEngine::end() { @@ -176,7 +176,7 @@ bool AudioEngine::lazyInit() { sAudioEngineImpl = nullptr; return false; } - sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground); + sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground); sOnResumeListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_FOREGROUND, AudioEngine::onEnterForeground); } @@ -208,7 +208,7 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume, auto *profileHelper = sDefaultProfileHelper; if (profile && profile != &profileHelper->profile) { CC_ASSERT(!profile->name.empty()); - profileHelper = &sAudioPathProfileHelperMap[profile->name]; + profileHelper = &sAudioPathProfileHelperMap[profile->name]; profileHelper->profile = *profile; } @@ -223,7 +223,7 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume, } if (profileHelper->profile.minDelay > TIME_DELAY_PRECISION) { auto currTime = std::chrono::high_resolution_clock::now(); - auto delay = static_cast(std::chrono::duration_cast(currTime - profileHelper->lastPlayTime).count()) / 1000000.0; + auto delay = static_cast(std::chrono::duration_cast(currTime - profileHelper->lastPlayTime).count()) / 1000000.0; if (profileHelper->lastPlayTime.time_since_epoch().count() != 0 && delay <= profileHelper->profile.minDelay) { CC_LOG_INFO("Fail to play %s cause by limited minimum delay", filePath.c_str()); break; @@ -242,9 +242,9 @@ int AudioEngine::play2d(const ccstd::string &filePath, bool loop, float volume, sAudioPathIDMap[filePath].push_back(ret); auto it = sAudioPathIDMap.find(filePath); - auto &audioRef = sAudioIDInfoMap[ret]; - audioRef.volume = volume; - audioRef.loop = loop; + auto &audioRef = sAudioIDInfoMap[ret]; + audioRef.volume = volume; + audioRef.loop = loop; audioRef.filePath = &it->first; if (profileHelper) { diff --git a/native/cocos/audio/android/AudioDecoder.cpp b/native/cocos/audio/android/AudioDecoder.cpp index 771af88faa..05fc925467 100644 --- a/native/cocos/audio/android/AudioDecoder.cpp +++ b/native/cocos/audio/android/AudioDecoder.cpp @@ -34,8 +34,8 @@ THE SOFTWARE. namespace cc { size_t AudioDecoder::fileRead(void *ptr, size_t size, size_t nmemb, void *datasource) { - AudioDecoder *thiz = (AudioDecoder *)datasource; - ssize_t toReadBytes = std::min((ssize_t)(thiz->_fileData.getSize() - thiz->_fileCurrPos), (ssize_t)(nmemb * size)); + AudioDecoder *thiz = (AudioDecoder *)datasource; + ssize_t toReadBytes = std::min((ssize_t)(thiz->_fileData.getSize() - thiz->_fileCurrPos), (ssize_t)(nmemb * size)); if (toReadBytes > 0) { memcpy(ptr, (unsigned char *)thiz->_fileData.getBytes() + thiz->_fileCurrPos, toReadBytes); thiz->_fileCurrPos += toReadBytes; @@ -76,7 +76,7 @@ AudioDecoder::~AudioDecoder() { } bool AudioDecoder::init(const ccstd::string &url, int sampleRate) { - _url = url; + _url = url; _sampleRate = sampleRate; return true; } @@ -130,16 +130,16 @@ bool AudioDecoder::resample() { ALOGV("Resample: %d --> %d", _result.sampleRate, _sampleRate); - auto r = _result; + auto r = _result; PcmBufferProvider provider; provider.init(r.pcmBuffer->data(), r.numFrames, r.pcmBuffer->size() / r.numFrames); - const int outFrameRate = _sampleRate; - int outputChannels = 2; - size_t outputFrameSize = outputChannels * sizeof(int32_t); - auto outputFrames = static_cast(((int64_t)r.numFrames * outFrameRate) / r.sampleRate); - size_t outputSize = outputFrames * outputFrameSize; - void * outputVAddr = malloc(outputSize); + const int outFrameRate = _sampleRate; + int outputChannels = 2; + size_t outputFrameSize = outputChannels * sizeof(int32_t); + auto outputFrames = static_cast(((int64_t)r.numFrames * outFrameRate) / r.sampleRate); + size_t outputSize = outputFrames * outputFrameSize; + void *outputVAddr = malloc(outputSize); auto resampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT, r.numChannels, outFrameRate, AudioResampler::MED_QUALITY); @@ -181,9 +181,9 @@ bool AudioDecoder::resample() { // mono takes left channel only (out of stereo output pair) // stereo and multichannel preserve all channels. - int channels = r.numChannels; - int32_t *out = (int32_t *)outputVAddr; - int16_t *convert = (int16_t *)malloc(outputFrames * channels * sizeof(int16_t)); + int channels = r.numChannels; + int32_t *out = (int32_t *)outputVAddr; + int16_t *convert = (int16_t *)malloc(outputFrames * channels * sizeof(int16_t)); const int volumeShift = 12; // shift requirement for Q4.27 to Q.15 // round to half towards zero and saturate at int16 (non-dithered) @@ -208,7 +208,7 @@ bool AudioDecoder::resample() { } // Reset result - _result.numFrames = static_cast(outputFrames); + _result.numFrames = static_cast(outputFrames); _result.sampleRate = outFrameRate; auto buffer = std::make_shared>(); @@ -232,7 +232,7 @@ bool AudioDecoder::interleave() { } else if (_result.numChannels == 1) { // If it's a mono audio, try to compose a fake stereo buffer size_t newBufferSize = _result.pcmBuffer->size() * 2; - auto newBuffer = std::make_shared>(); + auto newBuffer = std::make_shared>(); newBuffer->reserve(newBufferSize); size_t totalFrameSizeInBytes = (size_t)(_result.numFrames * _result.bitsPerSample / 8); @@ -249,7 +249,7 @@ bool AudioDecoder::interleave() { } _result.numChannels = 2; _result.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - _result.pcmBuffer = newBuffer; + _result.pcmBuffer = newBuffer; return true; } diff --git a/native/cocos/audio/android/AudioDecoder.h b/native/cocos/audio/android/AudioDecoder.h index d8ba5f8594..2712745d02 100644 --- a/native/cocos/audio/android/AudioDecoder.h +++ b/native/cocos/audio/android/AudioDecoder.h @@ -43,19 +43,19 @@ public: protected: virtual bool decodeToPcm() = 0; - bool resample(); - bool interleave(); + bool resample(); + bool interleave(); static size_t fileRead(void *ptr, size_t size, size_t nmemb, void *datasource); - static int fileSeek(void *datasource, int64_t offset, int whence); - static int fileClose(void *datasource); - static long fileTell(void *datasource); + static int fileSeek(void *datasource, int64_t offset, int whence); + static int fileClose(void *datasource); + static long fileTell(void *datasource); ccstd::string _url; - PcmData _result; - int _sampleRate; - Data _fileData; - size_t _fileCurrPos; + PcmData _result; + int _sampleRate; + Data _fileData; + size_t _fileCurrPos; }; } // namespace cc diff --git a/native/cocos/audio/android/AudioDecoderMp3.cpp b/native/cocos/audio/android/AudioDecoderMp3.cpp index e18e2b69a2..b41ad9c13c 100644 --- a/native/cocos/audio/android/AudioDecoderMp3.cpp +++ b/native/cocos/audio/android/AudioDecoderMp3.cpp @@ -44,24 +44,24 @@ bool AudioDecoderMp3::decodeToPcm() { } mp3_callbacks callbacks; - callbacks.read = AudioDecoder::fileRead; - callbacks.seek = AudioDecoder::fileSeek; + callbacks.read = AudioDecoder::fileRead; + callbacks.seek = AudioDecoder::fileSeek; callbacks.close = AudioDecoder::fileClose; - callbacks.tell = AudioDecoder::fileTell; + callbacks.tell = AudioDecoder::fileTell; int numChannels = 0; - int sampleRate = 0; - int numFrames = 0; + int sampleRate = 0; + int numFrames = 0; if (EXIT_SUCCESS == decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames) && numChannels > 0 && sampleRate > 0 && numFrames > 0) { - _result.numChannels = numChannels; - _result.sampleRate = sampleRate; + _result.numChannels = numChannels; + _result.sampleRate = sampleRate; _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = numFrames; - _result.duration = 1.0f * numFrames / sampleRate; + _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = numFrames; + _result.duration = 1.0f * numFrames / sampleRate; ccstd::string info = _result.toString(); ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); diff --git a/native/cocos/audio/android/AudioDecoderProvider.cpp b/native/cocos/audio/android/AudioDecoderProvider.cpp index 58d11124c4..ad4ce2eaa3 100644 --- a/native/cocos/audio/android/AudioDecoderProvider.cpp +++ b/native/cocos/audio/android/AudioDecoderProvider.cpp @@ -36,7 +36,7 @@ namespace cc { AudioDecoder *AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) { - AudioDecoder *decoder = nullptr; + AudioDecoder *decoder = nullptr; ccstd::string extension = FileUtils::getInstance()->getFileExtension(url); ALOGV("url:%s, extension:%s", url.c_str(), extension.c_str()); if (extension == ".ogg") { diff --git a/native/cocos/audio/android/AudioDecoderProvider.h b/native/cocos/audio/android/AudioDecoderProvider.h index bff43d7af4..e525fed75a 100644 --- a/native/cocos/audio/android/AudioDecoderProvider.h +++ b/native/cocos/audio/android/AudioDecoderProvider.h @@ -34,7 +34,7 @@ class AudioDecoder; class AudioDecoderProvider { public: static AudioDecoder *createAudioDecoder(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); - static void destroyAudioDecoder(AudioDecoder **decoder); + static void destroyAudioDecoder(AudioDecoder **decoder); }; } // namespace cc \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderSLES.cpp b/native/cocos/audio/android/AudioDecoderSLES.cpp index c7c81e031b..756c154efc 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.cpp +++ b/native/cocos/audio/android/AudioDecoderSLES.cpp @@ -111,12 +111,12 @@ AudioDecoderSLES::~AudioDecoderSLES() { bool AudioDecoderSLES::init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) { if (AudioDecoder::init(url, sampleRate)) { - _engineItf = engineItf; + _engineItf = engineItf; _bufferSizeInFrames = bufferSizeInFrames; - _fdGetterCallback = fdGetterCallback; + _fdGetterCallback = fdGetterCallback; BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2); - _pcmData = (char *)malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); + _pcmData = (char *)malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); memset(_pcmData, 0x00, NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); return true; } @@ -132,23 +132,23 @@ bool AudioDecoderSLES::decodeToPcm() { /* Interfaces for the audio player */ SLAndroidSimpleBufferQueueItf decBuffQueueItf; - SLPrefetchStatusItf prefetchItf; - SLPlayItf playItf; - SLMetadataExtractionItf mdExtrItf; + SLPrefetchStatusItf prefetchItf; + SLPlayItf playItf; + SLMetadataExtractionItf mdExtrItf; /* Source of audio data for the decoding */ SLDataSource decSource; // decUri & locFd should be defined here - SLDataLocator_URI decUri; + SLDataLocator_URI decUri; SLDataLocator_AndroidFD locFd; /* Data sink for decoded audio */ - SLDataSink decDest; + SLDataSink decDest; SLDataLocator_AndroidSimpleBufferQueue decBuffQueue; - SLDataFormat_PCM pcm; + SLDataFormat_PCM pcm; - SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; + SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; /* Initialize arrays required[] and iidArray[] */ @@ -171,12 +171,12 @@ bool AudioDecoderSLES::decodeToPcm() { iidArray[2] = SL_IID_METADATAEXTRACTION; SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED}; - decSource.pFormat = &formatMime; + decSource.pFormat = &formatMime; if (_url[0] != '/') { - off_t start = 0, length = 0; + off_t start = 0, length = 0; ccstd::string relativePath; - size_t position = _url.find("@assets/"); + size_t position = _url.find("@assets/"); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it @@ -197,25 +197,25 @@ bool AudioDecoderSLES::decodeToPcm() { decSource.pLocator = &locFd; } else { - decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()}; + decUri = {SL_DATALOCATOR_URI, (SLchar *)_url.c_str()}; decSource.pLocator = &decUri; } /* Setup the data sink */ decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE; + decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE; /* set up the format of the data in the buffer queue */ pcm.formatType = SL_DATAFORMAT_PCM; // IDEA: valid value required but currently ignored - pcm.numChannels = 2; + pcm.numChannels = 2; pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; + pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; decDest.pLocator = (void *)&decBuffQueue; - decDest.pFormat = (void *)&pcm; + decDest.pFormat = (void *)&pcm; { std::lock_guard lk(__SLPlayerMutex); @@ -264,11 +264,11 @@ bool AudioDecoderSLES::decodeToPcm() { /* ------------------------------------------------------ */ /* Initialize the callback and its context for the decoding buffer queue */ - _decContext.playItf = playItf; - _decContext.metaItf = mdExtrItf; + _decContext.playItf = playItf; + _decContext.metaItf = mdExtrItf; _decContext.pDataBase = (int8_t *)_pcmData; - _decContext.pData = _decContext.pDataBase; - _decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES; + _decContext.pData = _decContext.pDataBase; + _decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES; result = (*decBuffQueueItf)->RegisterCallback(decBuffQueueItf, SLAudioDecoderCallbackProxy::decPlayCallback, this); SL_RETURN_VAL_IF_FAILED(result, false, "decBuffQueueItf RegisterCallback failed"); @@ -299,7 +299,7 @@ bool AudioDecoderSLES::decodeToPcm() { /* 2/ block until data has been prefetched */ SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW; - SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s + SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) && !_prefetchError) { std::this_thread::sleep_for(std::chrono::milliseconds(2)); @@ -315,7 +315,7 @@ bool AudioDecoderSLES::decodeToPcm() { /* ------------------------------------------------------ */ /* Display duration */ SLmillisecond durationInMsec = SL_TIME_UNKNOWN; - result = (*playItf)->GetDuration(playItf, &durationInMsec); + result = (*playItf)->GetDuration(playItf, &durationInMsec); SL_RETURN_VAL_IF_FAILED(result, false, "GetDuration failed"); if (durationInMsec == SL_TIME_UNKNOWN) { @@ -331,14 +331,14 @@ bool AudioDecoderSLES::decodeToPcm() { // can make assumptions about the size of the keys and their matching values (all SLuint32) SLuint32 itemCount; result = (*mdExtrItf)->GetItemCount(mdExtrItf, &itemCount); - SLuint32 i, keySize, valueSize; + SLuint32 i, keySize, valueSize; SLMetadataInfo *keyInfo, *value; for (i = 0; i < itemCount; i++) { - keyInfo = nullptr; - keySize = 0; - value = nullptr; + keyInfo = nullptr; + keySize = 0; + value = nullptr; valueSize = 0; - result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize); + result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize); SL_RETURN_VAL_IF_FAILED(result, false, "GetKeySize(%d) failed", (int)i); result = (*mdExtrItf)->GetValueSize(mdExtrItf, i, &valueSize); @@ -433,7 +433,7 @@ void AudioDecoderSLES::queryAudioInfo() { SLresult result; /* Get duration in callback where we use the callback context for the SLPlayItf*/ SLmillisecond durationInMsec = SL_TIME_UNKNOWN; - result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec); + result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec); SL_RETURN_IF_FAILED(result, "decodeProgressCallback,GetDuration failed"); if (durationInMsec == SL_TIME_UNKNOWN) { @@ -455,7 +455,7 @@ void AudioDecoderSLES::queryAudioInfo() { // but the call was successful for the PCM format keys, so those conditions are implied _result.sampleRate = *((SLuint32 *)pcmMetaData.data); - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, PCM_METADATA_VALUE_SIZE, &pcmMetaData); SL_RETURN_IF_FAILED(result, "%s GetValue _numChannelsKeyIndex failed", __FUNCTION__); _result.numChannels = *((SLuint32 *)pcmMetaData.data); @@ -481,7 +481,7 @@ void AudioDecoderSLES::queryAudioInfo() { void AudioDecoderSLES::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event) { SLpermille level = 0; - SLresult result; + SLresult result; result = (*caller)->GetFillLevel(caller, &level); SL_RETURN_IF_FAILED(result, "GetFillLevel failed"); diff --git a/native/cocos/audio/android/AudioDecoderSLES.h b/native/cocos/audio/android/AudioDecoderSLES.h index bcf1d3d59c..2e48108a80 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.h +++ b/native/cocos/audio/android/AudioDecoderSLES.h @@ -36,7 +36,7 @@ protected: AudioDecoderSLES(); virtual ~AudioDecoderSLES(); - bool init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); + bool init(SLEngineItf engineItf, const ccstd::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); virtual bool decodeToPcm() override; private: @@ -69,24 +69,24 @@ private: int _endiannessKeyIndex; /* to signal to the test app the end of the stream to decode has been reached */ - bool _eos; - std::mutex _eosLock; + bool _eos; + std::mutex _eosLock; std::condition_variable _eosCondition; /* Structure for passing information to callback function */ typedef struct CallbackCntxt_ { - SLPlayItf playItf; + SLPlayItf playItf; SLMetadataExtractionItf metaItf; - SLuint32 size; - SLint8 * pDataBase; // Base address of local audio data storage - SLint8 * pData; // Current address of local audio data storage + SLuint32 size; + SLint8 *pDataBase; // Base address of local audio data storage + SLint8 *pData; // Current address of local audio data storage } CallbackCntxt; - CallbackCntxt _decContext; - int _bufferSizeInFrames; - int _assetFd; + CallbackCntxt _decContext; + int _bufferSizeInFrames; + int _assetFd; FdGetterCallback _fdGetterCallback; - bool _isDecodingCallbackInvoked; + bool _isDecodingCallbackInvoked; friend class SLAudioDecoderCallbackProxy; friend class AudioDecoderProvider; diff --git a/native/cocos/audio/android/AudioDecoderWav.cpp b/native/cocos/audio/android/AudioDecoderWav.cpp index 693819882d..fc76af5b8f 100644 --- a/native/cocos/audio/android/AudioDecoderWav.cpp +++ b/native/cocos/audio/android/AudioDecoderWav.cpp @@ -58,14 +58,14 @@ bool AudioDecoderWav::decodeToPcm() { SF_INFO info; snd_callbacks cb; - cb.open = onWavOpen; - cb.read = AudioDecoder::fileRead; - cb.seek = onWavSeek; + cb.open = onWavOpen; + cb.read = AudioDecoder::fileRead; + cb.seek = onWavSeek; cb.close = onWavClose; - cb.tell = AudioDecoder::fileTell; + cb.tell = AudioDecoder::fileTell; SNDFILE *handle = nullptr; - bool ret = false; + bool ret = false; do { handle = sf_open_read(_url.c_str(), &info, &cb, this); if (handle == nullptr) { @@ -77,20 +77,20 @@ bool AudioDecoderWav::decodeToPcm() { } ALOGD("wav info: frames: %d, samplerate: %d, channels: %d, format: %d", info.frames, info.samplerate, info.channels, info.format); - size_t bufSize = sizeof(int16_t) * info.frames * info.channels; - auto * buf = static_cast(malloc(bufSize)); + size_t bufSize = sizeof(int16_t) * info.frames * info.channels; + auto *buf = static_cast(malloc(bufSize)); sf_count_t readFrames = sf_readf_short(handle, reinterpret_cast(buf), info.frames); CC_ASSERT(readFrames == info.frames); _result.pcmBuffer->insert(_result.pcmBuffer->end(), buf, buf + bufSize); - _result.numChannels = info.channels; - _result.sampleRate = info.samplerate; + _result.numChannels = info.channels; + _result.sampleRate = info.samplerate; _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - _result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); - _result.endianness = SL_BYTEORDER_LITTLEENDIAN; - _result.numFrames = info.frames; - _result.duration = static_cast(1.0F * info.frames / _result.sampleRate); //NOLINT + _result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = info.frames; + _result.duration = static_cast(1.0F * info.frames / _result.sampleRate); //NOLINT free(buf); ret = true; diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index 0b09b31684..6662661740 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -58,17 +58,17 @@ using namespace cc; //NOLINT // Audio focus values synchronized with which in cocos/platform/android/java/src/com/cocos/lib/CocosNativeActivity.java namespace { -AudioEngineImpl *gAudioImpl = nullptr; -int outputSampleRate = 44100; -int bufferSizeInFrames = 192; +AudioEngineImpl *gAudioImpl = nullptr; +int outputSampleRate = 44100; +int bufferSizeInFrames = 192; void getAudioInfo() { - JNIEnv * env = JniHelper::getEnv(); - jclass audioSystem = env->FindClass("android/media/AudioSystem"); - jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); - outputSampleRate = env->CallStaticIntMethod(audioSystem, method); - method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); - bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); + JNIEnv *env = JniHelper::getEnv(); + jclass audioSystem = env->FindClass("android/media/AudioSystem"); + jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); + outputSampleRate = env->CallStaticIntMethod(audioSystem, method); + method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); + bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); } } // namespace @@ -97,8 +97,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) { if (cc::FileUtilsAndroid::getObbFile() != nullptr) { int64_t startV; int64_t lenV; - fd = getObbAssetFileDescriptorJNI(url, &startV, &lenV); - *start = static_cast(startV); + fd = getObbAssetFileDescriptorJNI(url, &startV, &lenV); + *start = static_cast(startV); *length = static_cast(lenV); } if (fd <= 0) { @@ -170,8 +170,8 @@ bool AudioEngineImpl::init() { // create output mix const SLInterfaceID outputMixIIDs[] = {}; - const SLboolean outputMixReqs[] = {}; - result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); + const SLboolean outputMixReqs[] = {}; + result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); if (SL_RESULT_SUCCESS != result) { CC_LOG_ERROR("create output mix fail"); break; diff --git a/native/cocos/audio/android/AudioEngine-inl.h b/native/cocos/audio/android/AudioEngine-inl.h index 98851f5dc5..87fac288a9 100644 --- a/native/cocos/audio/android/AudioEngine-inl.h +++ b/native/cocos/audio/android/AudioEngine-inl.h @@ -50,19 +50,19 @@ public: AudioEngineImpl(); ~AudioEngineImpl() override; - bool init(); - int play2d(const ccstd::string &filePath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - void pause(int audioID); - void resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const ccstd::string &filePath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + void pause(int audioID); + void resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); float getDurationFromFile(const ccstd::string &filePath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); void uncache(const ccstd::string &filePath); void uncacheAll(); @@ -82,7 +82,7 @@ private: SLObjectItf _outputMixObject; //audioID,AudioInfo - ccstd::unordered_map _audioPlayers; + ccstd::unordered_map _audioPlayers; ccstd::unordered_map> _callbackMap; // UrlAudioPlayers which need to resumed while entering foreground diff --git a/native/cocos/audio/android/AudioMixer.cpp b/native/cocos/audio/android/AudioMixer.cpp index c784f91d34..60216be9e6 100644 --- a/native/cocos/audio/android/AudioMixer.cpp +++ b/native/cocos/audio/android/AudioMixer.cpp @@ -527,8 +527,9 @@ static inline bool setVolumeRampVariables(float newVolume, int32_t ramp, if (ramp != 0) { // when the ramp completes, *pPrevVolume is set to *pSetVolume, so there // is no computational mismatch; hence equality is checked here. - ALOGD_IF(*pPrevVolume != *pSetVolume, "previous float ramp hasn't finished," - " prev:%f set_to:%f", + ALOGD_IF(*pPrevVolume != *pSetVolume, + "previous float ramp hasn't finished," + " prev:%f set_to:%f", *pPrevVolume, *pSetVolume); const float inc = (newVolume - *pPrevVolume) / ramp; // could be inf, nan, subnormal const float maxv = max(newVolume, *pPrevVolume); // could be inf, cannot be nan, subnormal @@ -558,8 +559,9 @@ static inline bool setVolumeRampVariables(float newVolume, int32_t ramp, // integer volume is U4.12 (to use 16 bit multiplies), but ramping uses U4.28. // when the ramp completes, *pIntPrevVolume is set to *pIntSetVolume << 16, so there // is no computational mismatch; hence equality is checked here. - ALOGD_IF(*pIntPrevVolume != *pIntSetVolume << 16, "previous int ramp hasn't finished," - " prev:%d set_to:%d", + ALOGD_IF(*pIntPrevVolume != *pIntSetVolume << 16, + "previous int ramp hasn't finished," + " prev:%d set_to:%d", *pIntPrevVolume, *pIntSetVolume << 16); const int32_t inc = ((intVolume << 16) - *pIntPrevVolume) / ramp; @@ -591,7 +593,6 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { int32_t *valueBuf = reinterpret_cast(value); switch (target) { - case TRACK: switch (param) { case CHANNEL_MASK: { @@ -715,12 +716,13 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { "bad parameters speed %f, pitch %f", playbackRate->mSpeed, playbackRate->mPitch); if (track.setPlaybackRate(*playbackRate)) { - ALOGV("setParameter(TIMESTRETCH, PLAYBACK_RATE, STRETCH_MODE, FALLBACK_MODE " - "%f %f %d %d", - playbackRate->mSpeed, - playbackRate->mPitch, - playbackRate->mStretchMode, - playbackRate->mFallbackMode); + ALOGV( + "setParameter(TIMESTRETCH, PLAYBACK_RATE, STRETCH_MODE, FALLBACK_MODE " + "%f %f %d %d", + playbackRate->mSpeed, + playbackRate->mPitch, + playbackRate->mStretchMode, + playbackRate->mFallbackMode); // invalidateState(1 << name); } } break; @@ -757,9 +759,10 @@ bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSam const int resamplerChannelCount = false /*downmixerBufferProvider != NULL*/ ? mMixerChannelCount : channelCount; - ALOGVV("Creating resampler:" - " format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n", - mMixerInFormat, resamplerChannelCount, devSampleRate, quality); + ALOGVV( + "Creating resampler:" + " format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n", + mMixerInFormat, resamplerChannelCount, devSampleRate, quality); resampler = AudioResampler::create( mMixerInFormat, resamplerChannelCount, @@ -1008,10 +1011,11 @@ void AudioMixer::process__validate(state_t *state, int64_t pts) { } } - ALOGV("mixer configuration change: %d activeTracks (%08x) " - "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d", - countActiveTracks, state->enabledTracks, - all16BitsStereoNoResample, resampling, volumeRamp); + ALOGV( + "mixer configuration change: %d activeTracks (%08x) " + "all16BitsStereoNoResample=%d, resampling=%d, volumeRamp=%d", + countActiveTracks, state->enabledTracks, + all16BitsStereoNoResample, resampling, volumeRamp); state->hook(state, pts); @@ -1521,7 +1525,6 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { t.resampler->setPTS(pts); t.hook(&t, outTemp, numFrames, state->resampleTemp, aux); } else { - size_t outFrames = 0; while (outFrames < numFrames) { @@ -1808,8 +1811,9 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { // been enabled for mixing. if (in == NULL || (((uintptr_t)in) & 3)) { memset(out, 0, numFrames * channels * audio_bytes_per_sample(t->mMixerFormat)); - ALOGE_IF((((uintptr_t)in) & 3), "process_NoResampleOneTrack: bus error: " - "buffer %p track %p, channels %d, needs %#x", + ALOGE_IF((((uintptr_t)in) & 3), + "process_NoResampleOneTrack: bus error: " + "buffer %p track %p, channels %d, needs %#x", in, t, t->channelCount, t->needs); return; } diff --git a/native/cocos/audio/android/AudioMixerController.cpp b/native/cocos/audio/android/AudioMixerController.cpp index 64b61a74db..07a7daa7df 100644 --- a/native/cocos/audio/android/AudioMixerController.cpp +++ b/native/cocos/audio/android/AudioMixerController.cpp @@ -89,7 +89,7 @@ void AudioMixerController::initTrack(Track *track, ccstd::vector &track return; uint32_t channelMask = audio_channel_out_mask_from_count(2); - int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT, + int32_t name = _mixer->getTrackName(channelMask, AUDIO_FORMAT_PCM_16_BIT, AUDIO_SESSION_OUTPUT_MIX); if (name < 0) { // If we could not get the track name, it means that there're MAX_NUM_TRACKS tracks @@ -124,9 +124,9 @@ void AudioMixerController::initTrack(Track *track, ccstd::vector &track _mixer->enable(name); std::lock_guard lk(track->_volumeDirtyMutex); - gain_minifloat_packed_t volume = track->getVolumeLR(); - float lVolume = float_from_gain(gain_minifloat_unpack_left(volume)); - float rVolume = float_from_gain(gain_minifloat_unpack_right(volume)); + gain_minifloat_packed_t volume = track->getVolumeLR(); + float lVolume = float_from_gain(gain_minifloat_unpack_left(volume)); + float rVolume = float_from_gain(gain_minifloat_unpack_right(volume)); _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &lVolume); _mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &rVolume); @@ -185,9 +185,9 @@ void AudioMixerController::mixOneFrame() { std::lock_guard lk(track->_volumeDirtyMutex); if (track->isVolumeDirty()) { - gain_minifloat_packed_t volume = track->getVolumeLR(); - float lVolume = float_from_gain(gain_minifloat_unpack_left(volume)); - float rVolume = float_from_gain(gain_minifloat_unpack_right(volume)); + gain_minifloat_packed_t volume = track->getVolumeLR(); + float lVolume = float_from_gain(gain_minifloat_unpack_left(volume)); + float rVolume = float_from_gain(gain_minifloat_unpack_right(volume)); ALOGV("Track (name: %d)'s volume is dirty, update volume to L: %f, R: %f", name, lVolume, rVolume); @@ -256,7 +256,7 @@ void AudioMixerController::mixOneFrame() { _activeTracksMutex.unlock(); - auto mixEnd = clockNow(); + auto mixEnd = clockNow(); float mixInterval = intervalInMS(mixStart, mixEnd); ALOGV_IF(mixInterval > 1.0f, "Mix a frame waste: %fms", mixInterval); diff --git a/native/cocos/audio/android/AudioMixerController.h b/native/cocos/audio/android/AudioMixerController.h index 53ab38a3b4..1d2b2367f5 100644 --- a/native/cocos/audio/android/AudioMixerController.h +++ b/native/cocos/audio/android/AudioMixerController.h @@ -40,7 +40,7 @@ class AudioMixer; class AudioMixerController { public: struct OutputBuffer { - void * buf; + void *buf; size_t size; }; @@ -53,8 +53,8 @@ public: bool addTrack(Track *track); bool hasPlayingTacks(); - void pause(); - void resume(); + void pause(); + void resume(); inline bool isPaused() const { return _isPaused; }; void mixOneFrame(); @@ -72,7 +72,7 @@ private: AudioMixer *_mixer; - std::mutex _activeTracksMutex; + std::mutex _activeTracksMutex; ccstd::vector _activeTracks; OutputBuffer _mixingBuffer; diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 50439fb953..a41a2c87ff 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -61,7 +61,7 @@ static int getSystemAPILevel() { struct AudioFileIndicator { ccstd::string extension; - int smallSizeIndicator; + int smallSizeIndicator; }; static AudioFileIndicator gAudioFileIndicator[] = { @@ -73,7 +73,7 @@ static AudioFileIndicator gAudioFileIndicator[] = { AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject, int deviceSampleRate, int bufferSizeInFrames, const FdGetterCallback &fdGetterCallback, //NOLINT(modernize-pass-by-value) - ICallerThreadUtils * callerThreadUtils) + ICallerThreadUtils *callerThreadUtils) : _engineItf(engineItf), _outputMixObject(outputMixObject), _deviceSampleRate(deviceSampleRate), _bufferSizeInFrames(bufferSizeInFrames), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) { ALOGI("deviceSampleRate: %d, bufferSizeInFrames: %d", _deviceSampleRate, _bufferSizeInFrames); if (getSystemAPILevel() >= 17) { @@ -124,22 +124,22 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const ccstd::string &audioFile if (info.isValid()) { if (isSmallFile(info)) { // Put an empty lambda to preloadEffect since we only want the future object to get PcmData - auto pcmData = std::make_shared(); - auto isSucceed = std::make_shared(false); + auto pcmData = std::make_shared(); + auto isSucceed = std::make_shared(false); auto isReturnFromCache = std::make_shared(false); auto isPreloadFinished = std::make_shared(false); std::thread::id threadId = std::this_thread::get_id(); - void * infoPtr = &info; - ccstd::string url = info.url; + void *infoPtr = &info; + ccstd::string url = info.url; preloadEffect( info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data) { // If the callback is in the same thread as caller's, it means that we found it // in the cache *isReturnFromCache = std::this_thread::get_id() == threadId; - *pcmData = std::move(data); - *isSucceed = succeed; + *pcmData = std::move(data); + *isSucceed = succeed; *isPreloadFinished = true; ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str()); }, @@ -236,7 +236,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload if (preloadIter != _preloadCallbackMap.end()) { ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str()); PreloadCallbackParam param; - param.callback = cb; + param.callback = cb; param.isPreloadInPlay2d = isPreloadInPlay2d; preloadIter->second.push_back(std::move(param)); return; @@ -255,7 +255,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _pcmCacheMutex.unlock(); PreloadCallbackParam param; - param.callback = cb; + param.callback = cb; param.isPreloadInPlay2d = isPreloadInPlay2d; ccstd::vector callbacks; callbacks.push_back(std::move(param)); @@ -264,9 +264,9 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _threadPool->pushTask([this, audioFilePath](int /*tid*/) { ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str()); - PcmData d; + PcmData d; AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); - bool ret = decoder != nullptr && decoder->start(); + bool ret = decoder != nullptr && decoder->start(); if (ret) { d = decoder->getResult(); std::lock_guard lk(_pcmCacheMutex); @@ -278,7 +278,7 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload ALOGV("decode %s", (ret ? "succeed" : "failed")); std::lock_guard lk(_preloadCallbackMutex); - auto && preloadIter = _preloadCallbackMap.find(audioFilePath); + auto &&preloadIter = _preloadCallbackMap.find(audioFilePath); if (preloadIter != _preloadCallbackMap.end()) { auto &¶ms = preloadIter->second; ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), (int)params.size()); @@ -303,14 +303,14 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( const ccstd::string &audioFilePath) { AudioFileInfo info; - long fileSize = 0; //NOLINT(google-runtime-int) - off_t start = 0; - off_t length = 0; - int assetFd = -1; + long fileSize = 0; //NOLINT(google-runtime-int) + off_t start = 0; + off_t length = 0; + int assetFd = -1; if (audioFilePath[0] != '/') { ccstd::string relativePath; - size_t position = audioFilePath.find("@assets/"); + size_t position = audioFilePath.find("@assets/"); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it @@ -338,10 +338,10 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( } } - info.url = audioFilePath; + info.url = audioFilePath; info.assetFd = std::make_shared(assetFd); - info.start = start; - info.length = fileSize; + info.start = start; + info.length = fileSize; ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize); @@ -350,9 +350,9 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(readability-convert-member-functions-to-static) //REFINE: If file size is smaller than 100k, we think it's a small file. This value should be set by developers. - auto & audioFileInfo = const_cast(info); - size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); - size_t pos = audioFileInfo.url.rfind('.'); + auto &audioFileInfo = const_cast(info); + size_t judgeCount = sizeof(gAudioFileIndicator) / sizeof(gAudioFileIndicator[0]); + size_t pos = audioFileInfo.url.rfind('.'); ccstd::string extension; if (pos != ccstd::string::npos) { extension = audioFileInfo.url.substr(pos); @@ -373,7 +373,7 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read float AudioPlayerProvider::getDurationFromFile(const ccstd::string &filePath) { std::lock_guard lk(_pcmCacheMutex); - auto iter = _pcmCache.find(filePath); + auto iter = _pcmCache.find(filePath); if (iter != _pcmCache.end()) { return iter->second.duration; } @@ -382,7 +382,7 @@ float AudioPlayerProvider::getDurationFromFile(const ccstd::string &filePath) { void AudioPlayerProvider::clearPcmCache(const ccstd::string &audioFilePath) { std::lock_guard lk(_pcmCacheMutex); - auto iter = _pcmCache.find(audioFilePath); + auto iter = _pcmCache.find(audioFilePath); if (iter != _pcmCache.end()) { ALOGV("clear pcm cache: (%s)", audioFilePath.c_str()); _pcmCache.erase(iter); @@ -397,7 +397,7 @@ void AudioPlayerProvider::clearAllPcmCaches() { } PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const ccstd::string &url, - const PcmData & pcmData) { + const PcmData &pcmData) { PcmAudioPlayer *pcmPlayer = nullptr; if (pcmData.isValid()) { pcmPlayer = ccnew PcmAudioPlayer(_mixController, _callerThreadUtils); @@ -418,8 +418,8 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( } SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI; - auto urlPlayer = ccnew UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); - bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); + auto urlPlayer = ccnew UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); + bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); if (!ret) { SL_SAFE_DELETE(urlPlayer); } diff --git a/native/cocos/audio/android/AudioPlayerProvider.h b/native/cocos/audio/android/AudioPlayerProvider.h index ddf06e05fb..58b9d49c61 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.h +++ b/native/cocos/audio/android/AudioPlayerProvider.h @@ -58,7 +58,7 @@ public: void preloadEffect(const ccstd::string &audioFilePath, const PreloadCallback &cb); float getDurationFromFile(const ccstd::string &filePath); - void clearPcmCache(const ccstd::string &audioFilePath); + void clearPcmCache(const ccstd::string &audioFilePath); void clearAllPcmCaches(); @@ -68,10 +68,10 @@ public: private: struct AudioFileInfo { - ccstd::string url; + ccstd::string url; std::shared_ptr assetFd; - off_t start{}; - off_t length; + off_t start{}; + off_t length; AudioFileInfo() : assetFd(nullptr) {} @@ -92,28 +92,28 @@ private: bool isSmallFile(const AudioFileInfo &info); private: - SLEngineItf _engineItf; - SLObjectItf _outputMixObject; - int _deviceSampleRate; - int _bufferSizeInFrames; - FdGetterCallback _fdGetterCallback; + SLEngineItf _engineItf; + SLObjectItf _outputMixObject; + int _deviceSampleRate; + int _bufferSizeInFrames; + FdGetterCallback _fdGetterCallback; ICallerThreadUtils *_callerThreadUtils; ccstd::unordered_map _pcmCache; - std::mutex _pcmCacheMutex; + std::mutex _pcmCacheMutex; struct PreloadCallbackParam { PreloadCallback callback; - bool isPreloadInPlay2d; + bool isPreloadInPlay2d; }; ccstd::unordered_map> _preloadCallbackMap; - std::mutex _preloadCallbackMutex; + std::mutex _preloadCallbackMutex; - std::mutex _preloadWaitMutex; + std::mutex _preloadWaitMutex; std::condition_variable _preloadWaitCond; - PcmAudioService * _pcmAudioService; + PcmAudioService *_pcmAudioService; AudioMixerController *_mixController; LegacyThreadPool *_threadPool; diff --git a/native/cocos/audio/android/AudioResampler.cpp b/native/cocos/audio/android/AudioResampler.cpp index 7165ca043f..93272512dc 100644 --- a/native/cocos/audio/android/AudioResampler.cpp +++ b/native/cocos/audio/android/AudioResampler.cpp @@ -140,7 +140,6 @@ static uint32_t currentMHz = 0; AudioResampler *AudioResampler::create(audio_format_t format, int inChannelCount, int32_t sampleRate, src_quality quality) { - bool atFinalQuality; if (quality == DEFAULT_QUALITY) { // read the resampler default quality property the first time it is needed @@ -247,7 +246,6 @@ AudioResampler::AudioResampler(int inChannelCount, mLocalTimeFreq(0), mPTS(AudioBufferProvider::kInvalidPTS), mQuality(quality) { - const int maxChannels = 2; //cjh quality < DYN_LOW_QUALITY ? 2 : 8; if (inChannelCount < 1 || inChannelCount > maxChannels) { LOG_ALWAYS_FATAL("Unsupported sample format %d quality %d channels", @@ -296,7 +294,6 @@ void AudioResampler::setPTS(int64_t pts) { } int64_t AudioResampler::calculateOutputPTS(int outputFrameIndex) { - if (mPTS == AudioBufferProvider::kInvalidPTS) { return AudioBufferProvider::kInvalidPTS; } else { @@ -314,7 +311,6 @@ void AudioResampler::reset() { size_t AudioResamplerOrder1::resample(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - // should never happen, but we overflow if it does // ALOG_ASSERT(outFrameCount < 32767); @@ -332,7 +328,6 @@ size_t AudioResamplerOrder1::resample(int32_t *out, size_t outFrameCount, size_t AudioResamplerOrder1::resampleStereo16(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - int32_t vl = mVolume[0]; int32_t vr = mVolume[1]; @@ -347,7 +342,6 @@ size_t AudioResamplerOrder1::resampleStereo16(int32_t *out, size_t outFrameCount // outFrameCount, inputIndex, phaseFraction, phaseIncrement); while (outputIndex < outputSampleCount) { - // buffer is empty, fetch a new one while (mBuffer.frameCount == 0) { mBuffer.frameCount = inFrameCount; @@ -431,7 +425,6 @@ resampleStereo16_exit: size_t AudioResamplerOrder1::resampleMono16(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - int32_t vl = mVolume[0]; int32_t vr = mVolume[1]; @@ -566,17 +559,24 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmMono16Loop(int16_t *in, asm( "stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n" // get parameters - " ldr r6, [sp, #" MO_PARAM5 " + 20]\n" // &phaseFraction - " ldr r6, [r6]\n" // phaseFraction - " ldr r7, [sp, #" MO_PARAM5 " + 8]\n" // &inputIndex - " ldr r7, [r7]\n" // inputIndex - " ldr r8, [sp, #" MO_PARAM5 " + 4]\n" // out - " ldr r0, [sp, #" MO_PARAM5 " + 0]\n" // &outputIndex - " ldr r0, [r0]\n" // outputIndex - " add r8, r8, r0, asl #2\n" // curOut - " ldr r9, [sp, #" MO_PARAM5 " + 24]\n" // phaseIncrement - " ldr r10, [sp, #" MO_PARAM5 " + 12]\n" // vl - " ldr r11, [sp, #" MO_PARAM5 " + 16]\n" // vr + " ldr r6, [sp, #" MO_PARAM5 + " + 20]\n" // &phaseFraction + " ldr r6, [r6]\n" // phaseFraction + " ldr r7, [sp, #" MO_PARAM5 + " + 8]\n" // &inputIndex + " ldr r7, [r7]\n" // inputIndex + " ldr r8, [sp, #" MO_PARAM5 + " + 4]\n" // out + " ldr r0, [sp, #" MO_PARAM5 + " + 0]\n" // &outputIndex + " ldr r0, [r0]\n" // outputIndex + " add r8, r8, r0, asl #2\n" // curOut + " ldr r9, [sp, #" MO_PARAM5 + " + 24]\n" // phaseIncrement + " ldr r10, [sp, #" MO_PARAM5 + " + 12]\n" // vl + " ldr r11, [sp, #" MO_PARAM5 + " + 16]\n" // vr // r0 pin, x0, Samp @@ -632,15 +632,19 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmMono16Loop(int16_t *in, " bic r6, r6, #0xC0000000\n" // phaseFraction & ... // save modified values - " ldr r0, [sp, #" MO_PARAM5 " + 20]\n" // &phaseFraction - " str r6, [r0]\n" // phaseFraction - " ldr r0, [sp, #" MO_PARAM5 " + 8]\n" // &inputIndex - " str r7, [r0]\n" // inputIndex - " ldr r0, [sp, #" MO_PARAM5 " + 4]\n" // out - " sub r8, r0\n" // curOut - out - " asr r8, #2\n" // new outputIndex - " ldr r0, [sp, #" MO_PARAM5 " + 0]\n" // &outputIndex - " str r8, [r0]\n" // save outputIndex + " ldr r0, [sp, #" MO_PARAM5 + " + 20]\n" // &phaseFraction + " str r6, [r0]\n" // phaseFraction + " ldr r0, [sp, #" MO_PARAM5 + " + 8]\n" // &inputIndex + " str r7, [r0]\n" // inputIndex + " ldr r0, [sp, #" MO_PARAM5 + " + 4]\n" // out + " sub r8, r0\n" // curOut - out + " asr r8, #2\n" // new outputIndex + " ldr r0, [sp, #" MO_PARAM5 + " + 0]\n" // &outputIndex + " str r8, [r0]\n" // save outputIndex " ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc}\n"); } @@ -683,17 +687,24 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmStereo16Loop(int16_t *in asm( "stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r12, lr}\n" // get parameters - " ldr r6, [sp, #" ST_PARAM5 " + 20]\n" // &phaseFraction - " ldr r6, [r6]\n" // phaseFraction - " ldr r7, [sp, #" ST_PARAM5 " + 8]\n" // &inputIndex - " ldr r7, [r7]\n" // inputIndex - " ldr r8, [sp, #" ST_PARAM5 " + 4]\n" // out - " ldr r0, [sp, #" ST_PARAM5 " + 0]\n" // &outputIndex - " ldr r0, [r0]\n" // outputIndex - " add r8, r8, r0, asl #2\n" // curOut - " ldr r9, [sp, #" ST_PARAM5 " + 24]\n" // phaseIncrement - " ldr r10, [sp, #" ST_PARAM5 " + 12]\n" // vl - " ldr r11, [sp, #" ST_PARAM5 " + 16]\n" // vr + " ldr r6, [sp, #" ST_PARAM5 + " + 20]\n" // &phaseFraction + " ldr r6, [r6]\n" // phaseFraction + " ldr r7, [sp, #" ST_PARAM5 + " + 8]\n" // &inputIndex + " ldr r7, [r7]\n" // inputIndex + " ldr r8, [sp, #" ST_PARAM5 + " + 4]\n" // out + " ldr r0, [sp, #" ST_PARAM5 + " + 0]\n" // &outputIndex + " ldr r0, [r0]\n" // outputIndex + " add r8, r8, r0, asl #2\n" // curOut + " ldr r9, [sp, #" ST_PARAM5 + " + 24]\n" // phaseIncrement + " ldr r10, [sp, #" ST_PARAM5 + " + 12]\n" // vl + " ldr r11, [sp, #" ST_PARAM5 + " + 16]\n" // vr // r0 pin, x0, Samp @@ -757,15 +768,19 @@ __attribute__((noinline)) void AudioResamplerOrder1::AsmStereo16Loop(int16_t *in " bic r6, r6, #0xC0000000\n" // phaseFraction & ... // save modified values - " ldr r0, [sp, #" ST_PARAM5 " + 20]\n" // &phaseFraction - " str r6, [r0]\n" // phaseFraction - " ldr r0, [sp, #" ST_PARAM5 " + 8]\n" // &inputIndex - " str r7, [r0]\n" // inputIndex - " ldr r0, [sp, #" ST_PARAM5 " + 4]\n" // out - " sub r8, r0\n" // curOut - out - " asr r8, #2\n" // new outputIndex - " ldr r0, [sp, #" ST_PARAM5 " + 0]\n" // &outputIndex - " str r8, [r0]\n" // save outputIndex + " ldr r0, [sp, #" ST_PARAM5 + " + 20]\n" // &phaseFraction + " str r6, [r0]\n" // phaseFraction + " ldr r0, [sp, #" ST_PARAM5 + " + 8]\n" // &inputIndex + " str r7, [r0]\n" // inputIndex + " ldr r0, [sp, #" ST_PARAM5 + " + 4]\n" // out + " sub r8, r0\n" // curOut - out + " asr r8, #2\n" // new outputIndex + " ldr r0, [sp, #" ST_PARAM5 + " + 0]\n" // &outputIndex + " str r8, [r0]\n" // save outputIndex " ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r12, pc}\n"); } diff --git a/native/cocos/audio/android/AudioResampler.h b/native/cocos/audio/android/AudioResampler.h index c073eaab6d..171846f7c0 100644 --- a/native/cocos/audio/android/AudioResampler.h +++ b/native/cocos/audio/android/AudioResampler.h @@ -43,10 +43,10 @@ public: // certain fixed rate conversions. Sample rate cannot be // changed dynamically. enum src_quality { - DEFAULT_QUALITY = 0, - LOW_QUALITY = 1, - MED_QUALITY = 2, - HIGH_QUALITY = 3, + DEFAULT_QUALITY = 0, + LOW_QUALITY = 1, + MED_QUALITY = 2, + HIGH_QUALITY = 3, VERY_HIGH_QUALITY = 4, }; @@ -82,7 +82,7 @@ public: virtual size_t resample(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) = 0; - virtual void reset(); + virtual void reset(); virtual size_t getUnreleasedFrames() const { return mInputIndex; } // called from destructor, so must not be virtual @@ -106,20 +106,20 @@ protected: int64_t calculateOutputPTS(int outputFrameIndex); - const int32_t mChannelCount; - const int32_t mSampleRate; - int32_t mInSampleRate; + const int32_t mChannelCount; + const int32_t mSampleRate; + int32_t mInSampleRate; AudioBufferProvider::Buffer mBuffer; union { - int16_t mVolume[2]; + int16_t mVolume[2]; uint32_t mVolumeRL; }; - int16_t mTargetVolume[2]; - size_t mInputIndex; - int32_t mPhaseIncrement; + int16_t mTargetVolume[2]; + size_t mInputIndex; + int32_t mPhaseIncrement; uint32_t mPhaseFraction; uint64_t mLocalTimeFreq; - int64_t mPTS; + int64_t mPTS; // returns the inFrameCount required to generate outFrameCount frames. // diff --git a/native/cocos/audio/android/AudioResamplerCubic.cpp b/native/cocos/audio/android/AudioResamplerCubic.cpp index 97d14f82ca..474a3a5b91 100644 --- a/native/cocos/audio/android/AudioResamplerCubic.cpp +++ b/native/cocos/audio/android/AudioResamplerCubic.cpp @@ -34,7 +34,6 @@ void AudioResamplerCubic::init() { size_t AudioResamplerCubic::resample(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - // should never happen, but we overflow if it does // ALOG_ASSERT(outFrameCount < 32767); @@ -52,7 +51,6 @@ size_t AudioResamplerCubic::resample(int32_t *out, size_t outFrameCount, size_t AudioResamplerCubic::resampleStereo16(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - int32_t vl = mVolume[0]; int32_t vr = mVolume[1]; @@ -91,7 +89,6 @@ size_t AudioResamplerCubic::resampleStereo16(int32_t *out, size_t outFrameCount, // time to fetch another sample while (indexIncrement--) { - inputIndex++; if (inputIndex == mBuffer.frameCount) { inputIndex = 0; @@ -121,7 +118,6 @@ save_state: size_t AudioResamplerCubic::resampleMono16(int32_t *out, size_t outFrameCount, AudioBufferProvider *provider) { - int32_t vl = mVolume[0]; int32_t vr = mVolume[1]; @@ -160,7 +156,6 @@ size_t AudioResamplerCubic::resampleMono16(int32_t *out, size_t outFrameCount, // time to fetch another sample while (indexIncrement--) { - inputIndex++; if (inputIndex == mBuffer.frameCount) { inputIndex = 0; diff --git a/native/cocos/audio/android/AudioResamplerPublic.h b/native/cocos/audio/android/AudioResamplerPublic.h index 2e8c58a682..9753ab0fe6 100644 --- a/native/cocos/audio/android/AudioResamplerPublic.h +++ b/native/cocos/audio/android/AudioResamplerPublic.h @@ -63,7 +63,7 @@ namespace cc { //Determines the current algorithm used for stretching enum AudioTimestretchStretchMode : int32_t { AUDIO_TIMESTRETCH_STRETCH_DEFAULT = 0, - AUDIO_TIMESTRETCH_STRETCH_SPEECH = 1, + AUDIO_TIMESTRETCH_STRETCH_SPEECH = 1, //REFINE: add more stretch modes/algorithms }; @@ -79,15 +79,15 @@ enum AudioTimestretchStretchMode : int32_t { // FALLBACK_FAIL: will stop program execution and log a fatal error enum AudioTimestretchFallbackMode : int32_t { AUDIO_TIMESTRETCH_FALLBACK_CUT_REPEAT = -1, - AUDIO_TIMESTRETCH_FALLBACK_DEFAULT = 0, - AUDIO_TIMESTRETCH_FALLBACK_MUTE = 1, - AUDIO_TIMESTRETCH_FALLBACK_FAIL = 2, + AUDIO_TIMESTRETCH_FALLBACK_DEFAULT = 0, + AUDIO_TIMESTRETCH_FALLBACK_MUTE = 1, + AUDIO_TIMESTRETCH_FALLBACK_FAIL = 2, }; struct AudioPlaybackRate { - float mSpeed; - float mPitch; - enum AudioTimestretchStretchMode mStretchMode; + float mSpeed; + float mPitch; + enum AudioTimestretchStretchMode mStretchMode; enum AudioTimestretchFallbackMode mFallbackMode; }; diff --git a/native/cocos/audio/android/PcmAudioPlayer.cpp b/native/cocos/audio/android/PcmAudioPlayer.cpp index 054b50b734..a4d5ee2a04 100644 --- a/native/cocos/audio/android/PcmAudioPlayer.cpp +++ b/native/cocos/audio/android/PcmAudioPlayer.cpp @@ -44,7 +44,7 @@ PcmAudioPlayer::~PcmAudioPlayer() { } bool PcmAudioPlayer::prepare(const ccstd::string &url, const PcmData &decResult) { - _url = url; + _url = url; _decResult = decResult; _track = ccnew Track(_decResult); @@ -64,7 +64,7 @@ bool PcmAudioPlayer::prepare(const ccstd::string &url, const PcmData &decResult) _track->onStateChanged = [this, callerThreadId](Track::State state) { // It maybe in sub thread Track::State prevState = _track->getPrevState(); - auto func = [this, state, prevState]() { + auto func = [this, state, prevState]() { // It's in caller's thread if (state == Track::State::OVER && prevState != Track::State::STOPPED) { if (_playEventCallback != nullptr) { diff --git a/native/cocos/audio/android/PcmAudioPlayer.h b/native/cocos/audio/android/PcmAudioPlayer.h index e2444082a9..8ba5e62372 100644 --- a/native/cocos/audio/android/PcmAudioPlayer.h +++ b/native/cocos/audio/android/PcmAudioPlayer.h @@ -82,13 +82,13 @@ private: virtual ~PcmAudioPlayer(); private: - int _id; - ccstd::string _url; - PcmData _decResult; - Track * _track; - PlayEventCallback _playEventCallback; + int _id; + ccstd::string _url; + PcmData _decResult; + Track *_track; + PlayEventCallback _playEventCallback; AudioMixerController *_controller; - ICallerThreadUtils * _callerThreadUtils; + ICallerThreadUtils *_callerThreadUtils; friend class AudioPlayerProvider; }; diff --git a/native/cocos/audio/android/PcmAudioService.cpp b/native/cocos/audio/android/PcmAudioService.cpp index ea24320973..8749615651 100644 --- a/native/cocos/audio/android/PcmAudioService.cpp +++ b/native/cocos/audio/android/PcmAudioService.cpp @@ -80,9 +80,9 @@ void PcmAudioService::bqFetchBufferCallback(SLAndroidSimpleBufferQueueItf bq) { } bool PcmAudioService::init(AudioMixerController *controller, int numChannels, int sampleRate, int bufferSizeInBytes) { - _controller = controller; - _numChannels = numChannels; - _sampleRate = sampleRate; + _controller = controller; + _numChannels = numChannels; + _sampleRate = sampleRate; _bufferSizeInBytes = bufferSizeInBytes; SLuint32 channelMask = SL_SPEAKER_FRONT_CENTER; diff --git a/native/cocos/audio/android/PcmBufferProvider.cpp b/native/cocos/audio/android/PcmBufferProvider.cpp index be5aeaa0b5..5fdcdb2513 100644 --- a/native/cocos/audio/android/PcmBufferProvider.cpp +++ b/native/cocos/audio/android/PcmBufferProvider.cpp @@ -60,9 +60,10 @@ status_t PcmBufferProvider::getNextBuffer(Buffer *buffer, buffer->frameCount = _numFrames - _nextFrame; } - ALOGVV("getNextBuffer() requested %zu frames out of %zu frames available," - " and returned %zu frames", - requestedFrames, (size_t)(_numFrames - _nextFrame), buffer->frameCount); + ALOGVV( + "getNextBuffer() requested %zu frames out of %zu frames available," + " and returned %zu frames", + requestedFrames, (size_t)(_numFrames - _nextFrame), buffer->frameCount); _unrel = buffer->frameCount; if (buffer->frameCount > 0) { @@ -76,15 +77,17 @@ status_t PcmBufferProvider::getNextBuffer(Buffer *buffer, void PcmBufferProvider::releaseBuffer(Buffer *buffer) { if (buffer->frameCount > _unrel) { - ALOGVV("ERROR releaseBuffer() released %zu frames but only %zu available " - "to release", - buffer->frameCount, _unrel); + ALOGVV( + "ERROR releaseBuffer() released %zu frames but only %zu available " + "to release", + buffer->frameCount, _unrel); _nextFrame += _unrel; _unrel = 0; } else { - ALOGVV("releaseBuffer() released %zu frames out of %zu frames available " - "to release", - buffer->frameCount, _unrel); + ALOGVV( + "releaseBuffer() released %zu frames out of %zu frames available " + "to release", + buffer->frameCount, _unrel); _nextFrame += buffer->frameCount; _unrel -= buffer->frameCount; } diff --git a/native/cocos/audio/android/PcmData.cpp b/native/cocos/audio/android/PcmData.cpp index fe5b11fc57..83bed91c72 100644 --- a/native/cocos/audio/android/PcmData.cpp +++ b/native/cocos/audio/android/PcmData.cpp @@ -41,70 +41,70 @@ PcmData::~PcmData() { PcmData::PcmData(const PcmData &o) { // ALOGV("In the copy constructor of PcmData (%p)", this); - numChannels = o.numChannels; - sampleRate = o.sampleRate; + numChannels = o.numChannels; + sampleRate = o.sampleRate; bitsPerSample = o.bitsPerSample; containerSize = o.containerSize; - channelMask = o.channelMask; - endianness = o.endianness; - numFrames = o.numFrames; - duration = o.duration; - pcmBuffer = std::move(o.pcmBuffer); + channelMask = o.channelMask; + endianness = o.endianness; + numFrames = o.numFrames; + duration = o.duration; + pcmBuffer = std::move(o.pcmBuffer); } PcmData::PcmData(PcmData &&o) { // ALOGV("In the move constructor of PcmData (%p)", this); - numChannels = o.numChannels; - sampleRate = o.sampleRate; + numChannels = o.numChannels; + sampleRate = o.sampleRate; bitsPerSample = o.bitsPerSample; containerSize = o.containerSize; - channelMask = o.channelMask; - endianness = o.endianness; - numFrames = o.numFrames; - duration = o.duration; - pcmBuffer = std::move(o.pcmBuffer); + channelMask = o.channelMask; + endianness = o.endianness; + numFrames = o.numFrames; + duration = o.duration; + pcmBuffer = std::move(o.pcmBuffer); o.reset(); } PcmData &PcmData::operator=(const PcmData &o) { // ALOGV("In the copy assignment of PcmData"); - numChannels = o.numChannels; - sampleRate = o.sampleRate; + numChannels = o.numChannels; + sampleRate = o.sampleRate; bitsPerSample = o.bitsPerSample; containerSize = o.containerSize; - channelMask = o.channelMask; - endianness = o.endianness; - numFrames = o.numFrames; - duration = o.duration; - pcmBuffer = o.pcmBuffer; + channelMask = o.channelMask; + endianness = o.endianness; + numFrames = o.numFrames; + duration = o.duration; + pcmBuffer = o.pcmBuffer; return *this; } PcmData &PcmData::operator=(PcmData &&o) { // ALOGV("In the move assignment of PcmData"); - numChannels = o.numChannels; - sampleRate = o.sampleRate; + numChannels = o.numChannels; + sampleRate = o.sampleRate; bitsPerSample = o.bitsPerSample; containerSize = o.containerSize; - channelMask = o.channelMask; - endianness = o.endianness; - numFrames = o.numFrames; - duration = o.duration; - pcmBuffer = std::move(o.pcmBuffer); + channelMask = o.channelMask; + endianness = o.endianness; + numFrames = o.numFrames; + duration = o.duration; + pcmBuffer = std::move(o.pcmBuffer); o.reset(); return *this; } void PcmData::reset() { - numChannels = -1; - sampleRate = -1; + numChannels = -1; + sampleRate = -1; bitsPerSample = -1; containerSize = -1; - channelMask = -1; - endianness = -1; - numFrames = -1; - duration = -1.0f; - pcmBuffer = nullptr; + channelMask = -1; + endianness = -1; + numFrames = -1; + duration = -1.0f; + pcmBuffer = nullptr; } bool PcmData::isValid() const { @@ -113,7 +113,7 @@ bool PcmData::isValid() const { ccstd::string PcmData::toString() const { ccstd::string ret; - char buf[256] = {0}; + char buf[256] = {0}; snprintf(buf, sizeof(buf), "numChannels: %d, sampleRate: %d, bitPerSample: %d, containerSize: %d, " diff --git a/native/cocos/audio/android/PcmData.h b/native/cocos/audio/android/PcmData.h index adc489402a..214b665949 100644 --- a/native/cocos/audio/android/PcmData.h +++ b/native/cocos/audio/android/PcmData.h @@ -34,14 +34,14 @@ namespace cc { struct PcmData { std::shared_ptr> pcmBuffer; - int numChannels; - int sampleRate; - int bitsPerSample; - int containerSize; - int channelMask; - int endianness; - int numFrames; - float duration; // in seconds + int numChannels; + int sampleRate; + int bitsPerSample; + int containerSize; + int channelMask; + int endianness; + int numFrames; + float duration; // in seconds PcmData(); diff --git a/native/cocos/audio/android/UrlAudioPlayer.cpp b/native/cocos/audio/android/UrlAudioPlayer.cpp index 47cf632531..228e375356 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.cpp +++ b/native/cocos/audio/android/UrlAudioPlayer.cpp @@ -34,9 +34,9 @@ THE SOFTWARE. namespace { -std::mutex __playerContainerMutex; +std::mutex __playerContainerMutex; ccstd::vector __playerContainer; -std::once_flag __onceFlag; +std::once_flag __onceFlag; } // namespace @@ -48,7 +48,7 @@ public: UrlAudioPlayer *thiz = (UrlAudioPlayer *)context; // We must use a mutex for the whole block of the following function invocation. std::lock_guard lk(__playerContainerMutex); - auto iter = std::find(__playerContainer.begin(), __playerContainer.end(), thiz); + auto iter = std::find(__playerContainer.begin(), __playerContainer.end(), thiz); if (iter != __playerContainer.end()) { thiz->playEventCallback(caller, playEvent); } @@ -200,7 +200,7 @@ float UrlAudioPlayer::getVolume() const { void UrlAudioPlayer::setAudioFocus(bool isFocus) { _isAudioFocus = isFocus; - float volume = _isAudioFocus ? _volume : 0.0f; + float volume = _isAudioFocus ? _volume : 0.0f; setVolumeToSLPlayer(volume); } @@ -210,7 +210,7 @@ float UrlAudioPlayer::getDuration() const { } SLmillisecond duration; - SLresult r = (*_playItf)->GetDuration(_playItf, &duration); + SLresult r = (*_playItf)->GetDuration(_playItf, &duration); SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getDuration failed"); if (duration == SL_TIME_UNKNOWN) { @@ -227,21 +227,21 @@ float UrlAudioPlayer::getDuration() const { float UrlAudioPlayer::getPosition() const { SLmillisecond millisecond; - SLresult r = (*_playItf)->GetPosition(_playItf, &millisecond); + SLresult r = (*_playItf)->GetPosition(_playItf, &millisecond); SL_RETURN_VAL_IF_FAILED(r, 0.0f, "UrlAudioPlayer::getPosition failed"); return millisecond / 1000.0f; } bool UrlAudioPlayer::setPosition(float pos) { SLmillisecond millisecond = 1000.0f * pos; - SLresult r = (*_seekItf)->SetPosition(_seekItf, millisecond, SL_SEEKMODE_ACCURATE); + SLresult r = (*_seekItf)->SetPosition(_seekItf, millisecond, SL_SEEKMODE_ACCURATE); SL_RETURN_VAL_IF_FAILED(r, false, "UrlAudioPlayer::setPosition %f failed", pos); return true; } bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std::shared_ptr assetFd, int start, int length) { - _url = url; + _url = url; _assetFd = assetFd; const char *locatorTypeStr = "UNKNOWN"; @@ -259,7 +259,7 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std SLDataSource audioSrc; SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED}; - audioSrc.pFormat = &formatMime; + audioSrc.pFormat = &formatMime; //Note: locFd & locUri should be outside of the following if/else block // Although locFd & locUri are only used inside if/else block, its lifecycle @@ -268,24 +268,24 @@ bool UrlAudioPlayer::prepare(const ccstd::string &url, SLuint32 locatorType, std // while invoking Engine::createAudioPlayer interface. So be care of change the position // of these two variables. SLDataLocator_AndroidFD locFd; - SLDataLocator_URI locUri; + SLDataLocator_URI locUri; if (locatorType == SL_DATALOCATOR_ANDROIDFD) { - locFd = {locatorType, _assetFd->getFd(), start, length}; + locFd = {locatorType, _assetFd->getFd(), start, length}; audioSrc.pLocator = &locFd; } else if (locatorType == SL_DATALOCATOR_URI) { - locUri = {locatorType, (SLchar *)_url.c_str()}; + locUri = {locatorType, (SLchar *)_url.c_str()}; audioSrc.pLocator = &locUri; ALOGV("locUri: locatorType: %d", (int)locUri.locatorType); } // configure audio sink SLDataLocator_OutputMix locOutmix = {SL_DATALOCATOR_OUTPUTMIX, _outputMixObj}; - SLDataSink audioSnk = {&locOutmix, nullptr}; + SLDataSink audioSnk = {&locOutmix, nullptr}; // create audio player const SLInterfaceID ids[3] = {SL_IID_SEEK, SL_IID_PREFETCHSTATUS, SL_IID_VOLUME}; - const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; + const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; SLresult result = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &audioSrc, &audioSnk, 3, ids, req); SL_RETURN_VAL_IF_FAILED(result, false, "CreateAudioPlayer failed"); @@ -328,7 +328,7 @@ void UrlAudioPlayer::setLoop(bool isLoop) { _isLoop = isLoop; SLboolean loopEnable = _isLoop ? SL_BOOLEAN_TRUE : SL_BOOLEAN_FALSE; - SLresult r = (*_seekItf)->SetLoop(_seekItf, loopEnable, 0, SL_TIME_UNKNOWN); + SLresult r = (*_seekItf)->SetLoop(_seekItf, loopEnable, 0, SL_TIME_UNKNOWN); SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setLoop %d failed", _isLoop ? 1 : 0); } diff --git a/native/cocos/audio/android/UrlAudioPlayer.h b/native/cocos/audio/android/UrlAudioPlayer.h index 21a325809a..9084f5e754 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.h +++ b/native/cocos/audio/android/UrlAudioPlayer.h @@ -95,29 +95,29 @@ private: void setVolumeToSLPlayer(float volume); private: - SLEngineItf _engineItf; - SLObjectItf _outputMixObj; + SLEngineItf _engineItf; + SLObjectItf _outputMixObj; ICallerThreadUtils *_callerThreadUtils; - int _id; + int _id; ccstd::string _url; std::shared_ptr _assetFd; SLObjectItf _playObj; - SLPlayItf _playItf; - SLSeekItf _seekItf; + SLPlayItf _playItf; + SLSeekItf _seekItf; SLVolumeItf _volumeItf; float _volume; float _duration; - bool _isLoop; - bool _isAudioFocus; + bool _isLoop; + bool _isAudioFocus; State _state; PlayEventCallback _playEventCallback; - std::thread::id _callerThreadId; + std::thread::id _callerThreadId; std::shared_ptr _isDestroyed; friend class SLUrlAudioPlayerCallbackProxy; diff --git a/native/cocos/audio/android/audio_utils/include/audio_utils/primitives.h b/native/cocos/audio/android/audio_utils/include/audio_utils/primitives.h index 75eaf89cc0..9058219e80 100644 --- a/native/cocos/audio/android/audio_utils/include/audio_utils/primitives.h +++ b/native/cocos/audio/android/audio_utils/include/audio_utils/primitives.h @@ -528,7 +528,7 @@ static inline int16_t clamp16_from_float(float f) { static const int32_t limpos = (0x10f << 22) /*zero*/ + 32767; /* 0x43c07fff */ union { - float f; + float f; int32_t i; } u; @@ -566,7 +566,7 @@ static inline uint8_t clamp8_from_float(float f) { static const int32_t limpos = (0x11f << 22) /*zero*/ + 255; /* 0x47c000ff */ union { - float f; + float f; int32_t i; } u; @@ -591,7 +591,7 @@ static inline uint8_t clamp8_from_float(float f) { * depending on hardware and future implementation of this function. */ static inline int32_t clamp24_from_float(float f) { - static const float scale = (float)(1 << 23); + static const float scale = (float)(1 << 23); static const float limpos = 0x7fffff / (float)(1 << 23); static const float limneg = -0x800000 / (float)(1 << 23); @@ -632,7 +632,7 @@ static inline int32_t clamp24_from_q8_23(int32_t ival) { * depending on hardware and future implementation of this function. */ static inline int32_t clampq4_27_from_float(float f) { - static const float scale = (float)(1UL << 27); + static const float scale = (float)(1UL << 27); static const float limpos = 16.; static const float limneg = -16.; @@ -656,7 +656,7 @@ static inline int32_t clampq4_27_from_float(float f) { * depending on hardware and future implementation of this function. */ static inline int32_t clamp32_from_float(float f) { - static const float scale = (float)(1UL << 31); + static const float scale = (float)(1UL << 31); static const float limpos = 1.; static const float limneg = -1.; @@ -727,7 +727,7 @@ static inline float float_from_u4_12(uint16_t uval) { * depending on hardware and future implementation of this function. */ static inline uint32_t u4_28_from_float(float f) { - static const float scale = (float)(1 << 28); + static const float scale = (float)(1 << 28); static const float limpos = 16.0f; if (f <= 0.) { @@ -749,7 +749,7 @@ static inline uint32_t u4_28_from_float(float f) { * depending on hardware and future implementation of this function. */ static inline uint16_t u4_12_from_float(float f) { - static const float scale = (float)(1 << 12); + static const float scale = (float)(1 << 12); static const float limpos = 0xffff / (float)(1 << 12); if (f <= 0.) { @@ -849,8 +849,8 @@ static inline int32_t mulAdd(int16_t in, int16_t v, int32_t a) { #if defined(__arm__) && !defined(__thumb__) int32_t out; asm("smlabb %[out], %[in], %[v], %[a] \n" - : [out] "=r"(out) - : [in] "%r"(in), [v] "r"(v), [a] "r"(a) + : [ out ] "=r"(out) + : [ in ] "%r"(in), [ v ] "r"(v), [ a ] "r"(a) :); return out; #else @@ -865,8 +865,8 @@ static inline int32_t mul(int16_t in, int16_t v) { #if defined(__arm__) && !defined(__thumb__) int32_t out; asm("smulbb %[out], %[in], %[v] \n" - : [out] "=r"(out) - : [in] "%r"(in), [v] "r"(v) + : [ out ] "=r"(out) + : [ in ] "%r"(in), [ v ] "r"(v) :); return out; #else @@ -882,13 +882,13 @@ static inline int32_t mulAddRL(int left, uint32_t inRL, uint32_t vRL, int32_t a) int32_t out; if (left) { asm("smlabb %[out], %[inRL], %[vRL], %[a] \n" - : [out] "=r"(out) - : [inRL] "%r"(inRL), [vRL] "r"(vRL), [a] "r"(a) + : [ out ] "=r"(out) + : [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL), [ a ] "r"(a) :); } else { asm("smlatt %[out], %[inRL], %[vRL], %[a] \n" - : [out] "=r"(out) - : [inRL] "%r"(inRL), [vRL] "r"(vRL), [a] "r"(a) + : [ out ] "=r"(out) + : [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL), [ a ] "r"(a) :); } return out; @@ -909,13 +909,13 @@ static inline int32_t mulRL(int left, uint32_t inRL, uint32_t vRL) { int32_t out; if (left) { asm("smulbb %[out], %[inRL], %[vRL] \n" - : [out] "=r"(out) - : [inRL] "%r"(inRL), [vRL] "r"(vRL) + : [ out ] "=r"(out) + : [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL) :); } else { asm("smultt %[out], %[inRL], %[vRL] \n" - : [out] "=r"(out) - : [inRL] "%r"(inRL), [vRL] "r"(vRL) + : [ out ] "=r"(out) + : [ inRL ] "%r"(inRL), [ vRL ] "r"(vRL) :); } return out; diff --git a/native/cocos/audio/android/mp3reader.cpp b/native/cocos/audio/android/mp3reader.cpp index ea95c9bd09..c84b37733b 100644 --- a/native/cocos/audio/android/mp3reader.cpp +++ b/native/cocos/audio/android/mp3reader.cpp @@ -204,7 +204,6 @@ static ssize_t sourceReadAt(mp3_callbacks *callback, void *source, off64_t offse static bool resync( mp3_callbacks *callback, void *source, uint32_t match_header, off64_t *inout_pos, uint32_t *out_header) { - if (*inout_pos == 0) { // Skip an optional ID3 header if syncing at the very beginning // of the datasource. @@ -359,7 +358,6 @@ Mp3Reader::Mp3Reader() : mSource(NULL), mCallback(NULL) { // Initialize the MP3 reader. bool Mp3Reader::init(mp3_callbacks *callback, void *source) { - mSource = source; mCallback = callback; // Open the file. @@ -385,7 +383,6 @@ bool Mp3Reader::init(mp3_callbacks *callback, void *source) { // Get the next valid MP3 frame. bool Mp3Reader::getFrame(void *buffer, uint32_t *size) { - size_t frame_size; uint32_t bitrate; uint32_t num_samples; diff --git a/native/cocos/audio/android/tinysndfile.cpp b/native/cocos/audio/android/tinysndfile.cpp index 6c6ecd759f..3e8eb9deaa 100644 --- a/native/cocos/audio/android/tinysndfile.cpp +++ b/native/cocos/audio/android/tinysndfile.cpp @@ -38,14 +38,14 @@ #define WAVE_FORMAT_EXTENSIBLE 0xFFFE static snd_callbacks sDefaultCallback; -static int sInited = 0; +static int sInited = 0; struct SNDFILE_ { - uint8_t * temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping - void * stream; - size_t bytesPerFrame; - size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE - SF_INFO info; + uint8_t *temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping + void *stream; + size_t bytesPerFrame; + size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE + SF_INFO info; snd_callbacks callback; }; @@ -93,12 +93,12 @@ static long tell_func(void *datasource) { //NOLINT(google-runtime-int,readabilit static void lazyInit() { if (sInited == 0) { - sDefaultCallback.open = open_func; - sDefaultCallback.read = read_func; - sDefaultCallback.seek = seek_func; + sDefaultCallback.open = open_func; + sDefaultCallback.read = read_func; + sDefaultCallback.seek = seek_func; sDefaultCallback.close = close_func; - sDefaultCallback.tell = tell_func; - sInited = 1; + sDefaultCallback.tell = tell_func; + sInited = 1; } } @@ -134,12 +134,12 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * // don't attempt to parse all valid forms, just the most common ones unsigned char wav[12]; - size_t actual; - unsigned riffSize; - size_t remaining; - int hadFmt = 0; - int hadData = 0; - long dataTell = 0L; //NOLINT(google-runtime-int) + size_t actual; + unsigned riffSize; + size_t remaining; + int hadFmt = 0; + int hadData = 0; + long dataTell = 0L; //NOLINT(google-runtime-int) actual = handle->callback.read(wav, sizeof(char), sizeof(wav), stream); if (actual < 12) { @@ -207,8 +207,8 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * #endif goto close; } - unsigned format = little2u(&fmt[0]); - size_t minSize = 0; + unsigned format = little2u(&fmt[0]); + size_t minSize = 0; switch (format) { case WAVE_FORMAT_PCM: case WAVE_FORMAT_IEEE_FLOAT: @@ -264,10 +264,10 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * #endif goto close; } - unsigned bytesPerFrame = (bitsPerSample >> 3) * channels; - handle->bytesPerFrame = bytesPerFrame; + unsigned bytesPerFrame = (bitsPerSample >> 3) * channels; + handle->bytesPerFrame = bytesPerFrame; handle->info.samplerate = static_cast(samplerate); - handle->info.channels = static_cast(channels); + handle->info.channels = static_cast(channels); switch (bitsPerSample) { case 8: handle->info.format |= SF_FORMAT_PCM_U8; @@ -300,9 +300,9 @@ SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks *cb, void * #endif goto close; } - handle->remaining = chunkSize / handle->bytesPerFrame; + handle->remaining = chunkSize / handle->bytesPerFrame; handle->info.frames = handle->remaining; - dataTell = handle->callback.tell(stream); + dataTell = handle->callback.tell(stream); if (chunkSize > 0) { handle->callback.seek(stream, static_cast(chunkSize), SEEK_CUR); //NOLINT(google-runtime-int) } @@ -384,12 +384,12 @@ sf_count_t sf_readf_short(SNDFILE *handle, int16_t *ptr, sf_count_t desiredFrame desiredFrames = handle->remaining; } // does not check for numeric overflow - size_t desiredBytes = desiredFrames * handle->bytesPerFrame; - size_t actualBytes; - void * temp = nullptr; + size_t desiredBytes = desiredFrames * handle->bytesPerFrame; + size_t actualBytes; + void *temp = nullptr; unsigned format = handle->info.format & SF_FORMAT_SUBMASK; if (format == SF_FORMAT_PCM_32 || format == SF_FORMAT_FLOAT || format == SF_FORMAT_PCM_24) { - temp = malloc(desiredBytes); + temp = malloc(desiredBytes); actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream); } else { actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream); diff --git a/native/cocos/audio/android/tinysndfile.h b/native/cocos/audio/android/tinysndfile.h index 4651350bd3..30379107c0 100644 --- a/native/cocos/audio/android/tinysndfile.h +++ b/native/cocos/audio/android/tinysndfile.h @@ -32,9 +32,9 @@ using sf_count_t = int; using SF_INFO = struct { sf_count_t frames; - int samplerate; - int channels; - int format; + int samplerate; + int channels; + int format; }; // opaque to clients diff --git a/native/cocos/audio/apple/AudioCache.h b/native/cocos/audio/apple/AudioCache.h index ba471af319..2895bb11d9 100644 --- a/native/cocos/audio/apple/AudioCache.h +++ b/native/cocos/audio/apple/AudioCache.h @@ -64,9 +64,9 @@ protected: void invokingLoadCallbacks(); //pcm data related stuff - ALenum _format; - ALsizei _sampleRate; - float _duration; + ALenum _format; + ALsizei _sampleRate; + float _duration; uint32_t _totalFrames; uint32_t _framesRead; @@ -74,16 +74,16 @@ protected: * Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE */ ALuint _alBufferId; - char * _pcmData; + char *_pcmData; /*Queue buffer related stuff * Streaming in openal when sizeInBytes greater then PCMDATA_CACHEMAXSIZE */ - char * _queBuffers[QUEUEBUFFER_NUM]; - ALsizei _queBufferSize[QUEUEBUFFER_NUM]; + char *_queBuffers[QUEUEBUFFER_NUM]; + ALsizei _queBufferSize[QUEUEBUFFER_NUM]; uint32_t _queBufferFrames; - std::mutex _playCallbackMutex; + std::mutex _playCallbackMutex; ccstd::vector> _playCallbacks; // loadCallbacks doesn't need mutex since it's invoked only in Cocos thread. @@ -94,10 +94,10 @@ protected: State _state; std::shared_ptr _isDestroyed; - ccstd::string _fileFullPath; - unsigned int _id; - bool _isLoadingFinished; - bool _isSkipReadDataTask; + ccstd::string _fileFullPath; + unsigned int _id; + bool _isLoadingFinished; + bool _isSkipReadDataTask; friend class AudioEngineImpl; friend class AudioPlayer; diff --git a/native/cocos/audio/apple/AudioDecoder.h b/native/cocos/audio/apple/AudioDecoder.h index 5c1f866160..94a7adc898 100644 --- a/native/cocos/audio/apple/AudioDecoder.h +++ b/native/cocos/audio/apple/AudioDecoder.h @@ -107,12 +107,12 @@ public: uint32_t getChannelCount() const; private: - bool _isOpened; + bool _isOpened; ExtAudioFileRef _extRef; - uint32_t _totalFrames; - uint32_t _bytesPerFrame; - uint32_t _sampleRate; - uint32_t _channelCount; + uint32_t _totalFrames; + uint32_t _bytesPerFrame; + uint32_t _sampleRate; + uint32_t _channelCount; AudioStreamBasicDescription _outputFormat; }; diff --git a/native/cocos/audio/apple/AudioEngine-inl.h b/native/cocos/audio/apple/AudioEngine-inl.h index 403cf80998..56ceb689df 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.h +++ b/native/cocos/audio/apple/AudioEngine-inl.h @@ -42,28 +42,28 @@ public: AudioEngineImpl(); ~AudioEngineImpl(); - bool init(); - int play2d(const ccstd::string &fileFullPath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - bool pause(int audioID); - bool resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const ccstd::string &fileFullPath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + bool pause(int audioID); + bool resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); float getDurationFromFile(const ccstd::string &fileFullPath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); - void uncache(const ccstd::string &filePath); - void uncacheAll(); + void uncache(const ccstd::string &filePath); + void uncacheAll(); AudioCache *preload(const ccstd::string &filePath, std::function callback); - void update(float dt); + void update(float dt); private: - bool checkAudioIdValid(int audioID); - void play2dImpl(AudioCache *cache, int audioID); + bool checkAudioIdValid(int audioID); + void play2dImpl(AudioCache *cache, int audioID); ALuint findValidSource(); static ALvoid myAlSourceNotificationCallback(ALuint sid, ALuint notificationID, ALvoid *userData); @@ -78,11 +78,11 @@ private: //audioID,AudioInfo ccstd::unordered_map _audioPlayers; - std::mutex _threadMutex; + std::mutex _threadMutex; bool _lazyInitLoop; - int _currentAudioID; + int _currentAudioID; std::weak_ptr _scheduler; }; } // namespace cc diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index b08c8cacbf..c09f9cbbd0 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -159,8 +159,7 @@ void AudioEngineInterruptionListenerCallback(void *user_data, UInt32 interruptio } [[AVAudioSession sharedInstance] setActive:YES error:&error]; alcMakeContextCurrent(s_ALContext); - } - else if (isAudioSessionInterrupted) { + } else if (isAudioSessionInterrupted) { isAudioSessionInterrupted = false; ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)"); NSError *error = nil; @@ -635,7 +634,6 @@ void AudioEngineImpl::update(float dt) { delete player; _unusedSourcesPool.push_back(alSource); } else if (player->_ready && sourceState == AL_STOPPED) { - ccstd::string filePath; if (player->_finishCallbak) { auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID]; diff --git a/native/cocos/audio/apple/AudioPlayer.h b/native/cocos/audio/apple/AudioPlayer.h index 5ed93a21b8..8b28297d64 100644 --- a/native/cocos/audio/apple/AudioPlayer.h +++ b/native/cocos/audio/apple/AudioPlayer.h @@ -47,9 +47,9 @@ public: void destroy(); //queue buffer related stuff - bool setTime(float time); + bool setTime(float time); float getTime() { return _currTime; } - bool setLoop(bool loop); + bool setLoop(bool loop); protected: void setCache(AudioCache *cache); @@ -59,25 +59,25 @@ protected: AudioCache *_audioCache; - float _volume; - bool _loop; + float _volume; + bool _loop; std::function _finishCallbak; - bool _isDestroyed; - bool _removeByAudioEngine; - bool _ready; + bool _isDestroyed; + bool _removeByAudioEngine; + bool _ready; ALuint _alSource; //play by circular buffer - float _currTime; - bool _streamingSource; - ALuint _bufferIds[QUEUEBUFFER_NUM]; - std::thread * _rotateBufferThread; + float _currTime; + bool _streamingSource; + ALuint _bufferIds[QUEUEBUFFER_NUM]; + std::thread *_rotateBufferThread; std::condition_variable _sleepCondition; - std::mutex _sleepMutex; - bool _timeDirty; - bool _isRotateThreadExited; - std::atomic_bool _needWakeupRotateThread; + std::mutex _sleepMutex; + bool _timeDirty; + bool _isRotateThreadExited; + std::atomic_bool _needWakeupRotateThread; std::mutex _play2dMutex; diff --git a/native/cocos/audio/apple/AudioPlayer.mm b/native/cocos/audio/apple/AudioPlayer.mm index f04d79cf21..57d9db845a 100644 --- a/native/cocos/audio/apple/AudioPlayer.mm +++ b/native/cocos/audio/apple/AudioPlayer.mm @@ -112,7 +112,8 @@ void AudioPlayer::destroy() { std::this_thread::sleep_for(std::chrono::milliseconds(2)); alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed); } - alSourceUnqueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); CHECK_AL_ERROR_DEBUG(); + alSourceUnqueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); + CHECK_AL_ERROR_DEBUG(); } ALOGVV("UnqueueBuffers Before alSourceStop"); #endif @@ -328,7 +329,6 @@ bool AudioPlayer::setLoop(bool loop) { bool AudioPlayer::setTime(float time) { if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) { - _currTime = time; _timeDirty = true; diff --git a/native/cocos/audio/include/AudioEngine.h b/native/cocos/audio/include/AudioEngine.h index 7154898201..58cdf5bac6 100644 --- a/native/cocos/audio/include/AudioEngine.h +++ b/native/cocos/audio/include/AudioEngine.h @@ -334,11 +334,11 @@ protected: struct AudioInfo { const ccstd::string *filePath; - ProfileHelper * profileHelper; + ProfileHelper *profileHelper; - float volume; - bool loop; - float duration; + float volume; + bool loop; + float duration; AudioState state; AudioInfo(); @@ -372,9 +372,9 @@ protected: static bool sIsEnabled; private: - static float sVolumeFactor; - static uint32_t sOnPauseListenerID; - static uint32_t sOnResumeListenerID; + static float sVolumeFactor; + static uint32_t sOnPauseListenerID; + static uint32_t sOnResumeListenerID; static ccstd::vector sBreakAudioID; static void onEnterBackground(const CustomEvent &); diff --git a/native/cocos/audio/oalsoft/AudioCache.cpp b/native/cocos/audio/oalsoft/AudioCache.cpp index d241982522..174e586417 100644 --- a/native/cocos/audio/oalsoft/AudioCache.cpp +++ b/native/cocos/audio/oalsoft/AudioCache.cpp @@ -57,7 +57,7 @@ AudioCache::AudioCache() : _format(-1), _sampleRate(0), _duration(0.0F), _totalFrames(0), _framesRead(0), _alBufferId(INVALID_AL_BUFFER_ID), _pcmData(nullptr), _queBufferFrames(0), _state(State::INITIAL), _isDestroyed(std::make_shared(false)), _id(++gIdIndex), _isLoadingFinished(false), _isSkipReadDataTask(false) { ALOGVV("AudioCache() %p, id=%u", this, _id); for (int i = 0; i < QUEUEBUFFER_NUM; ++i) { - _queBuffers[i] = nullptr; + _queBuffers[i] = nullptr; _queBufferSize[i] = 0; } } @@ -113,22 +113,22 @@ void AudioCache::readDataTask(unsigned int selfId) { } const uint32_t originalTotalFrames = decoder->getTotalFrames(); - const uint32_t bytesPerFrame = decoder->getBytesPerFrame(); - const uint32_t sampleRate = decoder->getSampleRate(); - const uint32_t channelCount = decoder->getChannelCount(); + const uint32_t bytesPerFrame = decoder->getBytesPerFrame(); + const uint32_t sampleRate = decoder->getSampleRate(); + const uint32_t channelCount = decoder->getChannelCount(); - uint32_t totalFrames = originalTotalFrames; - uint32_t dataSize = totalFrames * bytesPerFrame; + uint32_t totalFrames = originalTotalFrames; + uint32_t dataSize = totalFrames * bytesPerFrame; uint32_t remainingFrames = totalFrames; - uint32_t adjustFrames = 0; + uint32_t adjustFrames = 0; - _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; - _sampleRate = static_cast(sampleRate); - _duration = 1.0F * totalFrames / sampleRate; + _format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16; + _sampleRate = static_cast(sampleRate); + _duration = 1.0F * totalFrames / sampleRate; _totalFrames = totalFrames; if (dataSize <= PCMDATA_CACHEMAXSIZE) { - uint32_t framesRead = 0; + uint32_t framesRead = 0; const uint32_t framesToReadOnce = std::min(totalFrames, static_cast(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM)); ccstd::vector adjustFrameBuf; @@ -225,7 +225,7 @@ void AudioCache::readDataTask(unsigned int selfId) { const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame; for (int index = 0; index < QUEUEBUFFER_NUM; ++index) { - _queBuffers[index] = static_cast(malloc(queBufferBytes)); + _queBuffers[index] = static_cast(malloc(queBufferBytes)); _queBufferSize[index] = queBufferBytes; decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]); diff --git a/native/cocos/audio/oalsoft/AudioCache.h b/native/cocos/audio/oalsoft/AudioCache.h index 2de51a7f4b..9e2e78944d 100644 --- a/native/cocos/audio/oalsoft/AudioCache.h +++ b/native/cocos/audio/oalsoft/AudioCache.h @@ -72,9 +72,9 @@ protected: void invokingLoadCallbacks(); //pcm data related stuff - ALenum _format; - ALsizei _sampleRate; - float _duration; + ALenum _format; + ALsizei _sampleRate; + float _duration; uint32_t _totalFrames; uint32_t _framesRead; @@ -82,16 +82,16 @@ protected: * Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE */ ALuint _alBufferId; - char * _pcmData; + char *_pcmData; /*Queue buffer related stuff * Streaming in OpenAL when sizeInBytes greater then PCMDATA_CACHEMAXSIZE */ - char * _queBuffers[QUEUEBUFFER_NUM]; - ALsizei _queBufferSize[QUEUEBUFFER_NUM]; + char *_queBuffers[QUEUEBUFFER_NUM]; + ALsizei _queBufferSize[QUEUEBUFFER_NUM]; uint32_t _queBufferFrames; - std::mutex _playCallbackMutex; + std::mutex _playCallbackMutex; ccstd::vector> _playCallbacks; // loadCallbacks doesn't need mutex since it's invoked only in Cocos thread. @@ -102,10 +102,10 @@ protected: State _state; std::shared_ptr _isDestroyed; - ccstd::string _fileFullPath; - unsigned int _id; - bool _isLoadingFinished; - bool _isSkipReadDataTask; + ccstd::string _fileFullPath; + unsigned int _id; + bool _isLoadingFinished; + bool _isSkipReadDataTask; friend class AudioEngineImpl; friend class AudioPlayer; diff --git a/native/cocos/audio/oalsoft/AudioDecoder.cpp b/native/cocos/audio/oalsoft/AudioDecoder.cpp index 033c4e0d66..27de942543 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoder.cpp @@ -52,7 +52,7 @@ bool AudioDecoder::isOpened() const { } uint32_t AudioDecoder::readFixedFrames(uint32_t framesToRead, char *pcmBuf) { - uint32_t framesRead = 0; + uint32_t framesRead = 0; uint32_t framesReadOnce = 0; do { framesReadOnce = read(framesToRead - framesRead, pcmBuf + framesRead * _bytesPerFrame); diff --git a/native/cocos/audio/oalsoft/AudioDecoder.h b/native/cocos/audio/oalsoft/AudioDecoder.h index f757f0d8af..b6cf654e1d 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.h +++ b/native/cocos/audio/oalsoft/AudioDecoder.h @@ -114,7 +114,7 @@ protected: AudioDecoder(); virtual ~AudioDecoder(); - bool _isOpened; + bool _isOpened; uint32_t _totalFrames; uint32_t _bytesPerFrame; uint32_t _sampleRate; diff --git a/native/cocos/audio/oalsoft/AudioDecoderManager.h b/native/cocos/audio/oalsoft/AudioDecoderManager.h index 08dcb726c8..1465fbfe26 100644 --- a/native/cocos/audio/oalsoft/AudioDecoderManager.h +++ b/native/cocos/audio/oalsoft/AudioDecoderManager.h @@ -32,10 +32,10 @@ class AudioDecoder; class AudioDecoderManager { public: - static bool init(); - static void destroy(); + static bool init(); + static void destroy(); static AudioDecoder *createDecoder(const char *path); - static void destroyDecoder(AudioDecoder *decoder); + static void destroyDecoder(AudioDecoder *decoder); }; } // namespace cc diff --git a/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp index dc788e9691..1fc5426b31 100644 --- a/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderMp3.cpp @@ -80,10 +80,10 @@ AudioDecoderMp3::~AudioDecoderMp3() { bool AudioDecoderMp3::open(const char *path) { ccstd::string fullPath = FileUtils::getInstance()->fullPathForFilename(path); - long rate = 0; //NOLINT(google-runtime-int) - int error = MPG123_OK; - int mp3Encoding = 0; - int channel = 0; + long rate = 0; //NOLINT(google-runtime-int) + int error = MPG123_OK; + int mp3Encoding = 0; + int channel = 0; do { _mpg123handle = mpg123_new(nullptr, &error); if (nullptr == _mpg123handle) { @@ -91,7 +91,7 @@ bool AudioDecoderMp3::open(const char *path) { break; } #if CC_PLATFORM_OHOS == CC_PLATFORM - auto *fu = static_cast(FileUtils::getInstance()); + auto *fu = static_cast(FileUtils::getInstance()); _fdAndDeleter = fu->getFd(fullPath); if (mpg123_open_fd(_mpg123handle, _fdAndDeleter.first) != MPG123_OK || mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK) { #else @@ -102,7 +102,7 @@ bool AudioDecoderMp3::open(const char *path) { } _channelCount = channel; - _sampleRate = rate; + _sampleRate = rate; if (mp3Encoding == MPG123_ENC_SIGNED_16) { _bytesPerFrame = 2 * _channelCount; @@ -152,8 +152,8 @@ void AudioDecoderMp3::close() { uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char *pcmBuf) { size_t bytesToRead = framesToRead * _bytesPerFrame; - size_t bytesRead = 0; - int err = mpg123_read(_mpg123handle, reinterpret_cast(pcmBuf), bytesToRead, &bytesRead); + size_t bytesRead = 0; + int err = mpg123_read(_mpg123handle, reinterpret_cast(pcmBuf), bytesToRead, &bytesRead); if (err == MPG123_ERR) { ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle)); return 0; diff --git a/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp index c558f6e72a..c032bcf650 100644 --- a/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp +++ b/native/cocos/audio/oalsoft/AudioDecoderOgg.cpp @@ -68,11 +68,11 @@ bool AudioDecoderOgg::open(const char *path) { #endif // header vorbis_info *vi = ov_info(&_vf, -1); - _sampleRate = static_cast(vi->rate); - _channelCount = vi->channels; - _bytesPerFrame = vi->channels * sizeof(int16_t); - _totalFrames = static_cast(ov_pcm_total(&_vf, -1)); - _isOpened = true; + _sampleRate = static_cast(vi->rate); + _channelCount = vi->channels; + _bytesPerFrame = vi->channels * sizeof(int16_t); + _totalFrames = static_cast(ov_pcm_total(&_vf, -1)); + _isOpened = true; return true; } return false; @@ -86,12 +86,12 @@ void AudioDecoderOgg::close() { } uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char *pcmBuf) { - int currentSection = 0; - auto bytesToRead = framesToRead * _bytesPerFrame; + int currentSection = 0; + auto bytesToRead = framesToRead * _bytesPerFrame; #if CC_PLATFORM == CC_PLATFORM_WINDOWS auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); #elif CC_PLATFORM == CC_PLATFORM_OHOS - int bitstream = 0; + int bitstream = 0; auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, &bitstream); #elif CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX auto bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection); diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp index cdbd041ec0..c5f294c40a 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -57,8 +57,8 @@ //IDEA: Move _winLog, winLog to a separated file static void _winLog(const char *format, va_list args) { static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char * buf = nullptr; + int bufferSize = MAX_LOG_LENGTH; + char *buf = nullptr; do { buf = ccnew char[bufferSize]; @@ -77,10 +77,10 @@ static void _winLog(const char *format, va_list args) { strcat(buf, "\n"); - int pos = 0; - auto len = static_cast(strlen(buf)); - char tempBuf[MAX_LOG_LENGTH + 1] = {0}; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; + int pos = 0; + auto len = static_cast(strlen(buf)); + char tempBuf[MAX_LOG_LENGTH + 1] = {0}; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; do { std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); @@ -114,7 +114,7 @@ void audioLog(const char *format, ...) { using namespace cc; //NOLINT -static ALCdevice * sALDevice = nullptr; +static ALCdevice *sALDevice = nullptr; static ALCcontext *sALContext = nullptr; AudioEngineImpl::AudioEngineImpl() @@ -167,7 +167,7 @@ bool AudioEngineImpl::init() { } _scheduler = CC_CURRENT_ENGINE()->getScheduler(); - ret = AudioDecoderManager::init(); + ret = AudioDecoderManager::init(); CC_LOG_DEBUG("OpenAL was initialized successfully!"); } } while (false); @@ -180,10 +180,10 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, const std::f auto it = _audioCaches.find(filePath); if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; - audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - unsigned int cacheId = audioCache->_id; - auto isCacheDestroyed = audioCache->_isDestroyed; + audioCache = &_audioCaches[filePath]; + audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); + unsigned int cacheId = audioCache->_id; + auto isCacheDestroyed = audioCache->_isDestroyed; AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed]() { if (*isCacheDestroyed) { ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId); @@ -207,8 +207,8 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu return AudioEngine::INVALID_AUDIO_ID; } - bool sourceFlag = false; - ALuint alSource = 0; + bool sourceFlag = false; + ALuint alSource = 0; for (unsigned int src : _alSources) { alSource = src; @@ -227,8 +227,8 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu } player->_alSource = alSource; - player->_loop = loop; - player->_volume = volume; + player->_loop = loop; + player->_volume = volume; auto audioCache = preload(filePath, nullptr); if (audioCache == nullptr) { @@ -283,7 +283,7 @@ void AudioEngineImpl::setVolume(int audioID, float volume) { if (!checkAudioIdValid(audioID)) { return; } - auto player = _audioPlayers[audioID]; + auto player = _audioPlayers[audioID]; player->_volume = volume; if (player->_ready) { @@ -408,8 +408,8 @@ float AudioEngineImpl::getCurrentTime(int audioID) { if (!checkAudioIdValid(audioID)) { return 0.0F; } - float ret = 0.0F; - auto player = _audioPlayers[audioID]; + float ret = 0.0F; + auto player = _audioPlayers[audioID]; if (player->_ready) { if (player->_streamingSource) { ret = player->getTime(); @@ -430,7 +430,7 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time) { if (!checkAudioIdValid(audioID)) { return false; } - bool ret = false; + bool ret = false; auto player = _audioPlayers[audioID]; do { @@ -470,16 +470,16 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::functionfirst; - player = it->second; + audioID = it->first; + player = it->second; alSource = player->_alSource; alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState); @@ -494,7 +494,7 @@ void AudioEngineImpl::update(float /*dt*/) { ccstd::string filePath; if (player->_finishCallbak) { auto &audioInfo = AudioEngine::sAudioIDInfoMap[audioID]; - filePath = *audioInfo.filePath; + filePath = *audioInfo.filePath; } AudioEngine::remove(audioID); diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.h b/native/cocos/audio/oalsoft/AudioEngine-soft.h index cb01946f62..2145a3612e 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.h +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.h @@ -42,24 +42,24 @@ public: AudioEngineImpl(); ~AudioEngineImpl() override; - bool init(); - int play2d(const ccstd::string &filePath, bool loop, float volume); - void setVolume(int audioID, float volume); - void setLoop(int audioID, bool loop); - bool pause(int audioID); - bool resume(int audioID); - void stop(int audioID); - void stopAll(); + bool init(); + int play2d(const ccstd::string &filePath, bool loop, float volume); + void setVolume(int audioID, float volume); + void setLoop(int audioID, bool loop); + bool pause(int audioID); + bool resume(int audioID); + void stop(int audioID); + void stopAll(); float getDuration(int audioID); float getDurationFromFile(const ccstd::string &filePath); float getCurrentTime(int audioID); - bool setCurrentTime(int audioID, float time); - void setFinishCallback(int audioID, const std::function &callback); + bool setCurrentTime(int audioID, float time); + void setFinishCallback(int audioID, const std::function &callback); - void uncache(const ccstd::string &filePath); - void uncacheAll(); + void uncache(const ccstd::string &filePath); + void uncacheAll(); AudioCache *preload(const ccstd::string &filePath, const std::function &callback); - void update(float dt); + void update(float dt); private: bool checkAudioIdValid(int audioID); @@ -75,11 +75,11 @@ private: //audioID,AudioInfo ccstd::unordered_map _audioPlayers; - std::mutex _threadMutex; + std::mutex _threadMutex; bool _lazyInitLoop; - int _currentAudioID; + int _currentAudioID; std::weak_ptr _scheduler; }; } // namespace cc diff --git a/native/cocos/audio/oalsoft/AudioPlayer.cpp b/native/cocos/audio/oalsoft/AudioPlayer.cpp index 7c4f060320..0333b1d8f3 100644 --- a/native/cocos/audio/oalsoft/AudioPlayer.cpp +++ b/native/cocos/audio/oalsoft/AudioPlayer.cpp @@ -180,7 +180,7 @@ bool AudioPlayer::play2d() { alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds); CHECK_AL_ERROR_DEBUG(); _rotateBufferThread = ccnew std::thread(&AudioPlayer::rotateBufferThread, this, - _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); + _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1); } else { alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId); CHECK_AL_ERROR_DEBUG(); @@ -204,7 +204,7 @@ bool AudioPlayer::play2d() { break; } _ready = true; - ret = true; + ret = true; } while (false); if (!ret) { @@ -216,15 +216,15 @@ bool AudioPlayer::play2d() { } void AudioPlayer::rotateBufferThread(int offsetFrame) { - char * tmpBuffer = nullptr; - AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str()); + char *tmpBuffer = nullptr; + AudioDecoder *decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str()); do { BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str())); - uint32_t framesRead = 0; + uint32_t framesRead = 0; const uint32_t framesToRead = _audioCache->_queBufferFrames; - const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame(); - tmpBuffer = static_cast(malloc(bufferSize)); + const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame(); + tmpBuffer = static_cast(malloc(bufferSize)); memset(tmpBuffer, 0, bufferSize); if (offsetFrame != 0) { @@ -232,8 +232,8 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { } ALint sourceState; - ALint bufferProcessed = 0; - bool needToExitThread = false; + ALint bufferProcessed = 0; + bool needToExitThread = false; while (!_isDestroyed) { alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState); @@ -242,7 +242,7 @@ void AudioPlayer::rotateBufferThread(int offsetFrame) { while (bufferProcessed > 0) { bufferProcessed--; if (_timeDirty) { - _timeDirty = false; + _timeDirty = false; offsetFrame = static_cast(_currTime * decoder->getSampleRate()); decoder->seek(offsetFrame); } else { @@ -307,7 +307,7 @@ bool AudioPlayer::setLoop(bool loop) { bool AudioPlayer::setTime(float time) { if (!_isDestroyed && time >= 0.0F && time < _audioCache->_duration) { - _currTime = time; + _currTime = time; _timeDirty = true; return true; diff --git a/native/cocos/audio/oalsoft/AudioPlayer.h b/native/cocos/audio/oalsoft/AudioPlayer.h index b41fda1f36..2483209a39 100644 --- a/native/cocos/audio/oalsoft/AudioPlayer.h +++ b/native/cocos/audio/oalsoft/AudioPlayer.h @@ -55,9 +55,9 @@ public: void destroy(); //queue buffer related stuff - bool setTime(float time); + bool setTime(float time); float getTime() { return _currTime; } - bool setLoop(bool loop); + bool setLoop(bool loop); protected: void setCache(AudioCache *cache); @@ -66,24 +66,24 @@ protected: AudioCache *_audioCache; - float _volume; - bool _loop; + float _volume; + bool _loop; std::function _finishCallbak; - bool _isDestroyed; - bool _removeByAudioEngine; - bool _ready; + bool _isDestroyed; + bool _removeByAudioEngine; + bool _ready; ALuint _alSource; //play by circular buffer - float _currTime; - bool _streamingSource; - ALuint _bufferIds[3]; - std::thread * _rotateBufferThread; + float _currTime; + bool _streamingSource; + ALuint _bufferIds[3]; + std::thread *_rotateBufferThread; std::condition_variable _sleepCondition; - std::mutex _sleepMutex; - bool _timeDirty; - bool _isRotateThreadExited; + std::mutex _sleepMutex; + bool _timeDirty; + bool _isRotateThreadExited; std::mutex _play2dMutex; diff --git a/native/cocos/audio/ohos/AudioDecoderWav.cpp b/native/cocos/audio/ohos/AudioDecoderWav.cpp index 94f20d35b8..58a02825d2 100644 --- a/native/cocos/audio/ohos/AudioDecoderWav.cpp +++ b/native/cocos/audio/ohos/AudioDecoderWav.cpp @@ -32,11 +32,11 @@ namespace { snd_callbacks wavCallbacks = { - .open = cc::ohosOpen, - .read = cc::ohosRead, - .seek = cc::ohosSeek, + .open = cc::ohosOpen, + .read = cc::ohosRead, + .seek = cc::ohosSeek, .close = cc::ohosClose, - .tell = cc::ohosTell, + .tell = cc::ohosTell, }; } @@ -52,13 +52,13 @@ AudioDecoderWav::~AudioDecoderWav() { bool AudioDecoderWav::open(const char *path) { _sndHandle = sf_open_read(path, &_sndInfo, &wavCallbacks, this); - _isOpened = (_sndHandle != nullptr) && _sndInfo.frames > 0; + _isOpened = (_sndHandle != nullptr) && _sndInfo.frames > 0; if (!_isOpened) return false; - _channelCount = _sndInfo.channels; - _sampleRate = _sndInfo.samplerate; + _channelCount = _sndInfo.channels; + _sampleRate = _sndInfo.samplerate; _bytesPerFrame = 2 * _channelCount; // short - _totalFrames = _sndInfo.frames; + _totalFrames = _sndInfo.frames; return true; } @@ -71,8 +71,8 @@ void AudioDecoderWav::close() { } uint32_t AudioDecoderWav::read(uint32_t framesToRead, char *pcmBuf) { - auto *output = reinterpret_cast(pcmBuf); - auto actualFrames = sf_readf_short(_sndHandle, output, framesToRead); + auto *output = reinterpret_cast(pcmBuf); + auto actualFrames = sf_readf_short(_sndHandle, output, framesToRead); return actualFrames; } diff --git a/native/cocos/audio/ohos/AudioDecoderWav.h b/native/cocos/audio/ohos/AudioDecoderWav.h index 4102f32d46..1652d5a77f 100644 --- a/native/cocos/audio/ohos/AudioDecoderWav.h +++ b/native/cocos/audio/ohos/AudioDecoderWav.h @@ -36,14 +36,14 @@ public: AudioDecoderWav(); ~AudioDecoderWav() override; - bool open(const char *path) override; - void close() override; + bool open(const char *path) override; + void close() override; uint32_t read(uint32_t framesToRead, char *pcmBuf) override; - bool seek(uint32_t frameOffset) override; + bool seek(uint32_t frameOffset) override; uint32_t tell() const override; private: - SF_INFO _sndInfo; + SF_INFO _sndInfo; SNDFILE *_sndHandle{}; }; diff --git a/native/cocos/audio/ohos/FsCallback.cpp b/native/cocos/audio/ohos/FsCallback.cpp index 559191a173..5c5c8b11a7 100644 --- a/native/cocos/audio/ohos/FsCallback.cpp +++ b/native/cocos/audio/ohos/FsCallback.cpp @@ -37,25 +37,25 @@ inline cc::FileUtilsOHOS *getFU() { struct FatFd { union { - FILE * fp; + FILE *fp; RawFile *rf; } file; void *user; - bool isRawFile; + bool isRawFile; }; } // namespace namespace cc { void *ohosOpen(const char *path, void *user) { - bool isRawfile = false; - const auto newPath = getFU()->expandPath(path, &isRawfile); - auto * ret = ccnew FatFd(); + bool isRawfile = false; + const auto newPath = getFU()->expandPath(path, &isRawfile); + auto *ret = ccnew FatFd(); if (isRawfile) { ret->file.rf = OpenRawFile(cc::FileUtilsOHOS::getResourceManager(), newPath.c_str()); } else { ret->file.fp = fopen(newPath.c_str(), "rb"); } - ret->user = user; + ret->user = user; ret->isRawFile = isRawfile; return ret; } @@ -78,7 +78,7 @@ int ohosSeek(void *datasource, long offset, int whence) { //NOLINT(google-runtim int ohosClose(void *datasource) { auto *fatFd = static_cast(datasource); - int code = 0; + int code = 0; if (fatFd->isRawFile) { CloseRawFile(fatFd->file.rf); code = 0; diff --git a/native/cocos/base/CachedArray.h b/native/cocos/base/CachedArray.h index ba9ce19885..e973731ed5 100644 --- a/native/cocos/base/CachedArray.h +++ b/native/cocos/base/CachedArray.h @@ -37,9 +37,9 @@ template class CachedArray final { public: explicit CachedArray(uint size = 1U) { - _size = 0; + _size = 0; _capacity = std::max(size, 1U); - _array = ccnew T[_capacity]; + _array = ccnew T[_capacity]; } // The rule of five applies here @@ -55,29 +55,29 @@ public: CachedArray &operator=(const CachedArray &other) { if (this != &other) { delete[] _array; - _size = other._size; + _size = other._size; _capacity = other._capacity; - _array = ccnew T[_capacity]; + _array = ccnew T[_capacity]; memcpy(_array, other._array, _size * sizeof(T)); } return *this; } CachedArray(CachedArray &&other) noexcept : _size(other._size), _capacity(other._capacity), _array(other._array) { - other._size = 0; + other._size = 0; other._capacity = 0; - other._array = nullptr; + other._array = nullptr; } CachedArray &operator=(CachedArray &&other) noexcept { if (this != &other) { delete[] _array; - _size = other._size; - _capacity = other._capacity; - _array = other._array; - other._size = 0; + _size = other._size; + _capacity = other._capacity; + _array = other._array; + other._size = 0; other._capacity = 0; - other._array = nullptr; + other._array = nullptr; } return *this; } @@ -93,12 +93,12 @@ public: inline void clear() { _size = 0; } inline uint size() const { return _size; } - inline T pop() { return _array[--_size]; } + inline T pop() { return _array[--_size]; } void reserve(uint size) { if (size > _capacity) { T *temp = _array; - _array = ccnew T[size]; + _array = ccnew T[size]; memcpy(_array, temp, _capacity * sizeof(T)); _capacity = size; delete[] temp; @@ -108,7 +108,7 @@ public: void push(T item) { if (_size >= _capacity) { T *temp = _array; - _array = ccnew T[_capacity * 2]; + _array = ccnew T[_capacity * 2]; memcpy(_array, temp, _capacity * sizeof(T)); _capacity *= 2; delete[] temp; @@ -118,9 +118,9 @@ public: void concat(const CachedArray &array) { if (_size + array._size > _capacity) { - T * temp = _array; + T *temp = _array; uint size = std::max(_capacity * 2, _size + array._size); - _array = ccnew T[size]; + _array = ccnew T[size]; memcpy(_array, temp, _size * sizeof(T)); _capacity = size; delete[] temp; @@ -131,9 +131,9 @@ public: void concat(T *array, uint count) { if (_size + count > _capacity) { - T * temp = _array; + T *temp = _array; uint size = std::max(_capacity * 2, _size + count); - _array = ccnew T[size]; + _array = ccnew T[size]; memcpy(_array, temp, _size * sizeof(T)); _capacity = size; delete[] temp; @@ -159,9 +159,9 @@ public: } private: - uint _size = 0; + uint _size = 0; uint _capacity = 0; - T * _array = nullptr; + T *_array = nullptr; }; } // namespace cc diff --git a/native/cocos/base/Data.cpp b/native/cocos/base/Data.cpp index 1487ade351..b0dd78b260 100644 --- a/native/cocos/base/Data.cpp +++ b/native/cocos/base/Data.cpp @@ -68,10 +68,10 @@ void Data::move(Data &other) { clear(); _bytes = other._bytes; - _size = other._size; + _size = other._size; other._bytes = nullptr; - other._size = 0; + other._size = 0; } bool Data::isNull() const { @@ -90,7 +90,7 @@ void Data::copy(const unsigned char *bytes, uint32_t size) { clear(); if (size > 0) { - _size = size; + _size = size; _bytes = static_cast(malloc(sizeof(unsigned char) * _size)); memcpy(_bytes, bytes, _size); } @@ -99,7 +99,7 @@ void Data::copy(const unsigned char *bytes, uint32_t size) { void Data::fastSet(unsigned char *bytes, uint32_t size) { free(_bytes); _bytes = bytes; - _size = size; + _size = size; } void Data::resize(uint32_t size) { @@ -107,14 +107,14 @@ void Data::resize(uint32_t size) { if (_size == size) { return; } - _size = size; + _size = size; _bytes = static_cast(realloc(_bytes, sizeof(unsigned char) * _size)); } void Data::clear() { free(_bytes); _bytes = nullptr; - _size = 0; + _size = 0; } uint8_t *Data::takeBuffer(uint32_t *size) { @@ -124,7 +124,7 @@ uint8_t *Data::takeBuffer(uint32_t *size) { } _bytes = nullptr; - _size = 0; + _size = 0; return buffer; } diff --git a/native/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index f03336a7a8..a4ab8f445b 100644 --- a/native/cocos/base/IndexHandle.h +++ b/native/cocos/base/IndexHandle.h @@ -49,7 +49,7 @@ public: inline bool operator<(IndexHandle const &rhs) const noexcept; inline bool operator==(IndexHandle const &rhs) const noexcept; inline bool operator!=(IndexHandle const &rhs) const noexcept; - inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicitly + inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicitly static IndexType constexpr UNINITIALIZED{std::numeric_limits::max()}; diff --git a/native/cocos/base/Locked.h b/native/cocos/base/Locked.h index a5f4c74eb5..7e1f0fb8c2 100644 --- a/native/cocos/base/Locked.h +++ b/native/cocos/base/Locked.h @@ -36,17 +36,17 @@ public: _mtx->lock(); } UniqueLockedRef(UniqueLockedRef &&t) noexcept { - _data = t._data; - _mtx = t._mtx; + _data = t._data; + _mtx = t._mtx; t._data = nullptr; - t._mtx = nullptr; + t._mtx = nullptr; } UniqueLockedRef &operator=(UniqueLockedRef &&t) noexcept { - _data = t._data; - _mtx = t._mtx; + _data = t._data; + _mtx = t._mtx; t._data = nullptr; - t._mtx = nullptr; + t._mtx = nullptr; return *this; } @@ -67,18 +67,18 @@ public: } private: - T * _data{}; + T *_data{}; LK *_mtx{}; }; template class Locked { public: - Locked() = default; - Locked(const Locked &) = delete; - Locked(Locked &&) = delete; - Locked & operator=(const Locked &) = delete; - Locked & operator=(Locked &&) = delete; + Locked() = default; + Locked(const Locked &) = delete; + Locked(Locked &&) = delete; + Locked &operator=(const Locked &) = delete; + Locked &operator=(Locked &&) = delete; UniqueLockedRef lock() { UniqueLockedRef ref(&_data, &_mutex); return std::move(ref); @@ -86,7 +86,7 @@ public: private: LK _mutex{}; - T _data{}; + T _data{}; }; } // namespace cc \ No newline at end of file diff --git a/native/cocos/base/Log.cpp b/native/cocos/base/Log.cpp index 3c0d7369b0..508ba37ffd 100644 --- a/native/cocos/base/Log.cpp +++ b/native/cocos/base/Log.cpp @@ -60,7 +60,7 @@ LogLevel Log::slogLevel = LogLevel::LEVEL_DEBUG; LogLevel Log::slogLevel = LogLevel::INFO; #endif -FILE * Log::slogFile = nullptr; +FILE *Log::slogFile = nullptr; const ccstd::vector LOG_LEVEL_DESCS{"FATAL", "ERROR", "WARN", "INFO", "DEBUG"}; void Log::setLogFile(const ccstd::string &filename) { @@ -76,9 +76,9 @@ void Log::setLogFile(const ccstd::string &filename) { msg += "------------------------------------------------------\n"; struct tm *tm_time; - time_t ct_time; + time_t ct_time; time(&ct_time); - tm_time = localtime(&ct_time); + tm_time = localtime(&ct_time); char dateBuffer[256] = {0}; snprintf(dateBuffer, sizeof(dateBuffer), "LOG DATE: %04d-%02d-%02d %02d:%02d:%02d\n", tm_time->tm_year + 1900, @@ -106,13 +106,13 @@ void Log::close() { } void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { - char buff[4096]; - char *p = buff; + char buff[4096]; + char *p = buff; char *last = buff + sizeof(buff) - 3; #if defined(LOG_USE_TIMESTAMP) struct tm *tmTime; - time_t ctTime; + time_t ctTime; time(&ctTime); tmTime = localtime(&ctTime); @@ -126,7 +126,7 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { // p += StringUtil::vprintf(p, last, formats, args); std::ptrdiff_t count = (last - p); - int ret = vsnprintf(p, count, formats, args); + int ret = vsnprintf(p, count, formats, args); if (ret >= count - 1) { p += (count - 1); } else if (ret >= 0) { @@ -136,7 +136,7 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { va_end(args); *p++ = '\n'; - *p = 0; + *p = 0; if (slogFile) { fputs(buff, slogFile); diff --git a/native/cocos/base/Log.h b/native/cocos/base/Log.h index 0b1ede3edf..57c86cdaa2 100644 --- a/native/cocos/base/Log.h +++ b/native/cocos/base/Log.h @@ -49,11 +49,11 @@ class CC_DLL Log { public: static LogLevel slogLevel; // for read only - static inline void setLogLevel(LogLevel level) { slogLevel = level; } + static inline void setLogLevel(LogLevel level) { slogLevel = level; } static inline FILE *getLogFile() { return slogFile; } - static void setLogFile(const ccstd::string &filename); - static void close(); - static void logMessage(LogType type, LogLevel level, const char *formats, ...); + static void setLogFile(const ccstd::string &filename); + static void close(); + static void logMessage(LogType type, LogLevel level, const char *formats, ...); private: static FILE *slogFile; diff --git a/native/cocos/base/Macros.h b/native/cocos/base/Macros.h index 0538acd903..c14e370bdd 100644 --- a/native/cocos/base/Macros.h +++ b/native/cocos/base/Macros.h @@ -218,7 +218,7 @@ It should work same as apples CFSwapInt32LittleToHost(..) #define CC_DISALLOW_COPY_MOVE_ASSIGN(TypeName) \ TypeName(const TypeName &) = delete; \ - TypeName(TypeName &&) = delete; \ + TypeName(TypeName &&) = delete; \ CC_DISALLOW_ASSIGN(TypeName) #if (CC_COMPILER == CC_COMPILER_MSVC) diff --git a/native/cocos/base/Ptr.h b/native/cocos/base/Ptr.h index 3f2b5f196f..b869a90acd 100644 --- a/native/cocos/base/Ptr.h +++ b/native/cocos/base/Ptr.h @@ -123,7 +123,7 @@ public: } T *get() const { return _ptr; } - operator T *() const { return _ptr; } // NOLINT + operator T *() const { return _ptr; } // NOLINT T &operator*() const { return *_ptr; } T *operator->() const { return _ptr; } @@ -180,7 +180,7 @@ public: void swap(T **pp) noexcept { T *p = _ptr; _ptr = *pp; - *pp = p; + *pp = p; } void swap(IntrusivePtr &r) noexcept { swap(&r._ptr); } @@ -193,7 +193,7 @@ private: // calling Release() once on the object when no longer using it. T *release() { T *retVal = _ptr; - _ptr = nullptr; + _ptr = nullptr; return retVal; } diff --git a/native/cocos/base/Random.h b/native/cocos/base/Random.h index a039373787..623f83ef0c 100644 --- a/native/cocos/base/Random.h +++ b/native/cocos/base/Random.h @@ -43,21 +43,21 @@ public: template static inline T randomReal(T min, T max) { std::uniform_real_distribution dist(min, max); - auto & mt = RandomHelper::getEngine(); + auto &mt = RandomHelper::getEngine(); return dist(mt); } template static inline T randomInt(T min, T max) { std::uniform_int_distribution dist(min, max); - auto & mt = RandomHelper::getEngine(); + auto &mt = RandomHelper::getEngine(); return dist(mt); } private: static inline std::mt19937 &getEngine() { static std::random_device seedGen; - static std::mt19937 engine(seedGen()); + static std::mt19937 engine(seedGen()); return engine; } }; diff --git a/native/cocos/base/RefMap.h b/native/cocos/base/RefMap.h index 1d7f689182..282e159c2a 100644 --- a/native/cocos/base/RefMap.h +++ b/native/cocos/base/RefMap.h @@ -269,7 +269,7 @@ public: */ V getRandomObject() const { if (!_data.empty()) { - auto randIdx = RandomHelper::randomInt(0, static_cast(_data.size()) - 1); + auto randIdx = RandomHelper::randomInt(0, static_cast(_data.size()) - 1); const_iterator randIter = _data.begin(); std::advance(randIter, randIdx); return randIter->second; diff --git a/native/cocos/base/Scheduler.cpp b/native/cocos/base/Scheduler.cpp index 7cdd6f530f..40e7b8caed 100644 --- a/native/cocos/base/Scheduler.cpp +++ b/native/cocos/base/Scheduler.cpp @@ -37,25 +37,25 @@ namespace { constexpr unsigned CC_REPEAT_FOREVER{UINT_MAX - 1}; -constexpr int MAX_FUNC_TO_PERFORM{30}; -constexpr int INITIAL_TIMER_COUND{10}; +constexpr int MAX_FUNC_TO_PERFORM{30}; +constexpr int INITIAL_TIMER_COUND{10}; } // namespace namespace cc { // implementation Timer void Timer::setupTimerWithInterval(float seconds, unsigned int repeat, float delay) { - _elapsed = -1; - _interval = seconds; - _delay = delay; - _useDelay = _delay > 0.0F; - _repeat = repeat; + _elapsed = -1; + _interval = seconds; + _delay = delay; + _useDelay = _delay > 0.0F; + _repeat = repeat; _runForever = _repeat == CC_REPEAT_FOREVER; } void Timer::update(float dt) { if (_elapsed == -1) { - _elapsed = 0; + _elapsed = 0; _timesExecuted = 0; return; } @@ -105,9 +105,9 @@ void Timer::update(float dt) { bool TimerTargetCallback::initWithCallback(Scheduler *scheduler, const ccSchedulerFunc &callback, void *target, const ccstd::string &key, float seconds, unsigned int repeat, float delay) { _scheduler = scheduler; - _target = target; - _callback = callback; - _key = key; + _target = target; + _callback = callback; + _key = key; setupTimerWithInterval(seconds, repeat, delay); return true; } @@ -153,10 +153,10 @@ void Scheduler::schedule(const ccSchedulerFunc &callback, void *target, float in CC_ASSERT(target); CC_ASSERT(!key.empty()); - auto iter = _hashForTimers.find(target); + auto iter = _hashForTimers.find(target); HashTimerEntry *element = nullptr; if (iter == _hashForTimers.end()) { - element = ccnew HashTimerEntry(); + element = ccnew HashTimerEntry(); element->target = target; _hashForTimers[target] = element; @@ -196,8 +196,8 @@ void Scheduler::unschedule(const ccstd::string &key, void *target) { auto iter = _hashForTimers.find(target); if (iter != _hashForTimers.end()) { HashTimerEntry *element = iter->second; - int i = 0; - auto & timers = element->timers; + int i = 0; + auto &timers = element->timers; for (auto *t : timers) { auto *timer = dynamic_cast(t); @@ -270,7 +270,7 @@ void Scheduler::unscheduleAllForTarget(void *target) { auto iter = _hashForTimers.find(target); if (iter != _hashForTimers.end()) { HashTimerEntry *element = iter->second; - auto & timers = element->timers; + auto &timers = element->timers; if (std::find(timers.begin(), timers.end(), element->currentTimer) != timers.end() && (!element->currentTimerSalvaged)) { element->currentTimer->addRef(); @@ -340,14 +340,14 @@ void Scheduler::update(float dt) { // Iterate over all the custom selectors HashTimerEntry *elt = nullptr; for (auto iter = _hashForTimers.begin(); iter != _hashForTimers.end();) { - elt = iter->second; - _currentTarget = elt; + elt = iter->second; + _currentTarget = elt; _currentTargetSalvaged = false; if (!_currentTarget->paused) { // The 'timers' array may change while inside this loop for (elt->timerIndex = 0; elt->timerIndex < static_cast(elt->timers.size()); ++(elt->timerIndex)) { - elt->currentTimer = elt->timers.at(elt->timerIndex); + elt->currentTimer = elt->timers.at(elt->timerIndex); elt->currentTimerSalvaged = false; elt->currentTimer->update(dt); @@ -376,7 +376,7 @@ void Scheduler::update(float dt) { } _updateHashLocked = false; - _currentTarget = nullptr; + _currentTarget = nullptr; // // Functions allocated from another thread diff --git a/native/cocos/base/Scheduler.h b/native/cocos/base/Scheduler.h index be75a37152..0b8a651be5 100644 --- a/native/cocos/base/Scheduler.h +++ b/native/cocos/base/Scheduler.h @@ -57,7 +57,7 @@ public: void setupTimerWithInterval(float seconds, unsigned int repeat, float delay); virtual void trigger(float dt) = 0; - virtual void cancel() = 0; + virtual void cancel() = 0; /** triggers the timer */ void update(float dt); @@ -65,14 +65,14 @@ public: protected: Timer() = default; - Scheduler * _scheduler = nullptr; - float _elapsed = 0.F; - bool _runForever = false; - bool _useDelay = false; + Scheduler *_scheduler = nullptr; + float _elapsed = 0.F; + bool _runForever = false; + bool _useDelay = false; unsigned int _timesExecuted = 0; - unsigned int _repeat = 0; //0 = once, 1 is 2 x executed - float _delay = 0.F; - float _interval = 0.F; + unsigned int _repeat = 0; //0 = once, 1 is 2 x executed + float _delay = 0.F; + float _interval = 0.F; }; class CC_DLL TimerTargetCallback final : public Timer { @@ -83,15 +83,15 @@ public: bool initWithCallback(Scheduler *scheduler, const ccSchedulerFunc &callback, void *target, const ccstd::string &key, float seconds, unsigned int repeat, float delay); inline const ccSchedulerFunc &getCallback() const { return _callback; }; - inline const ccstd::string & getKey() const { return _key; }; + inline const ccstd::string &getKey() const { return _key; }; void trigger(float dt) override; void cancel() override; private: - void * _target = nullptr; + void *_target = nullptr; ccSchedulerFunc _callback = nullptr; - ccstd::string _key; + ccstd::string _key; }; /** @@ -276,11 +276,11 @@ private: // Hash Element used for "selectors with interval" struct HashTimerEntry { ccstd::vector timers; - void * target; - int timerIndex; - Timer * currentTimer; - bool currentTimerSalvaged; - bool paused; + void *target; + int timerIndex; + Timer *currentTimer; + bool currentTimerSalvaged; + bool paused; }; void removeHashElement(struct HashTimerEntry *element); @@ -290,14 +290,14 @@ private: // Used for "selectors with interval" ccstd::unordered_map _hashForTimers; - struct HashTimerEntry * _currentTarget = nullptr; - bool _currentTargetSalvaged = false; + struct HashTimerEntry *_currentTarget = nullptr; + bool _currentTargetSalvaged = false; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. bool _updateHashLocked = false; // Used for "perform Function" ccstd::vector> _functionsToPerform; - std::mutex _performMutex; + std::mutex _performMutex; }; // end of base group diff --git a/native/cocos/base/StringPool.h b/native/cocos/base/StringPool.h index f234141e90..f6af829a7a 100644 --- a/native/cocos/base/StringPool.h +++ b/native/cocos/base/StringPool.h @@ -58,22 +58,22 @@ public: StringPool() = default; ~StringPool(); StringPool(const StringPool &) = delete; - StringPool(StringPool &&) = delete; + StringPool(StringPool &&) = delete; StringPool &operator=(const StringPool &) = delete; StringPool &operator=(StringPool &&) = delete; StringHandle stringToHandle(const char *str) noexcept; - char const * handleToString(const StringHandle &handle) const noexcept; + char const *handleToString(const StringHandle &handle) const noexcept; StringHandle find(const char *str) const noexcept; private: StringHandle doStringToHandle(const char *str) noexcept; - char const * doHandleToString(const StringHandle &handle) const noexcept; + char const *doHandleToString(const StringHandle &handle) const noexcept; StringHandle doFind(const char *str) const noexcept; ccstd::unordered_map _stringToHandles{}; - ccstd::vector _handleToStrings{}; - mutable ReadWriteLock _readWriteLock{}; + ccstd::vector _handleToStrings{}; + mutable ReadWriteLock _readWriteLock{}; }; using ThreadSafeStringPool = StringPool; @@ -121,7 +121,7 @@ inline StringHandle StringPool::doStringToHandle(const char *str) no if (it == _stringToHandles.end()) { size_t const strLength = strlen(str) + 1; - char *const strCache = ccnew char[strLength]; + char *const strCache = ccnew char[strLength]; strcpy(strCache, str); StringHandle name(static_cast(_handleToStrings.size()), strCache); _handleToStrings.emplace_back(strCache); diff --git a/native/cocos/base/StringUtil.cpp b/native/cocos/base/StringUtil.cpp index add065ddfa..a2c7208a7f 100644 --- a/native/cocos/base/StringUtil.cpp +++ b/native/cocos/base/StringUtil.cpp @@ -47,7 +47,7 @@ int StringUtil::vprintf(char *buf, const char *last, const char *fmt, va_list ar if (last <= buf) return 0; int count = (int)(last - buf); - int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args); + int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args); if (ret < 0) { if (errno == 0) { return count - 1; @@ -65,7 +65,7 @@ int StringUtil::vprintf(char *buf, const char *last, const char *fmt, va_list ar } auto count = static_cast(last - buf); - int ret = vsnprintf(buf, count, fmt, args); + int ret = vsnprintf(buf, count, fmt, args); if (ret >= count - 1) { return count - 1; } @@ -85,7 +85,7 @@ int StringUtil::printf(char *buf, const char *last, const char *fmt, ...) { } ccstd::string StringUtil::format(const char *fmt, ...) { - char sz[4096]; + char sz[4096]; va_list args; va_start(args, fmt); vprintf(sz, sz + sizeof(sz) - 1, fmt, args); @@ -164,11 +164,11 @@ ccstd::string &StringUtil::toupper(ccstd::string &str) { } ccstd::string GzipedString::value() const { // NOLINT(readability-convert-member-functions-to-static) - uint8_t * outGzip{nullptr}; - uint8_t * outBase64{nullptr}; - auto * input = reinterpret_cast(const_cast(_str.c_str())); - auto lenOfBase64 = base64Decode(input, static_cast(_str.size()), &outBase64); - auto lenofUnzip = ZipUtils::inflateMemory(outBase64, static_cast(lenOfBase64), &outGzip); + uint8_t *outGzip{nullptr}; + uint8_t *outBase64{nullptr}; + auto *input = reinterpret_cast(const_cast(_str.c_str())); + auto lenOfBase64 = base64Decode(input, static_cast(_str.size()), &outBase64); + auto lenofUnzip = ZipUtils::inflateMemory(outBase64, static_cast(lenOfBase64), &outGzip); ccstd::string ret(outGzip, outGzip + lenofUnzip); free(outGzip); free(outBase64); diff --git a/native/cocos/base/StringUtil.h b/native/cocos/base/StringUtil.h index 9649c4fb78..515f39b6c9 100644 --- a/native/cocos/base/StringUtil.h +++ b/native/cocos/base/StringUtil.h @@ -36,14 +36,14 @@ namespace cc { class CC_DLL StringUtil { public: - static int vprintf(char *buf, const char *last, const char *fmt, va_list args); - static int printf(char *buf, const char *last, const char *fmt, ...); - static ccstd::string format(const char *fmt, ...); + static int vprintf(char *buf, const char *last, const char *fmt, va_list args); + static int printf(char *buf, const char *last, const char *fmt, ...); + static ccstd::string format(const char *fmt, ...); static ccstd::vector split(const ccstd::string &str, const ccstd::string &delims, uint maxSplits = 0); - static ccstd::string & replace(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr); - static ccstd::string & replaceAll(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr); - static ccstd::string & tolower(ccstd::string &str); - static ccstd::string & toupper(ccstd::string &str); + static ccstd::string &replace(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr); + static ccstd::string &replaceAll(ccstd::string &str, const ccstd::string &findStr, const ccstd::string &replaceStr); + static ccstd::string &tolower(ccstd::string &str); + static ccstd::string &toupper(ccstd::string &str); }; /** diff --git a/native/cocos/base/ThreadPool.cpp b/native/cocos/base/ThreadPool.cpp index ecc7f63aec..5ac46f241e 100644 --- a/native/cocos/base/ThreadPool.cpp +++ b/native/cocos/base/ThreadPool.cpp @@ -108,7 +108,7 @@ LegacyThreadPool::~LegacyThreadPool() { // number of idle threads int LegacyThreadPool::getIdleThreadNum() const { - auto * thiz = const_cast(this); + auto *thiz = const_cast(this); std::lock_guard lk(thiz->_idleThreadNumMutex); return _idleThreadNum; } @@ -131,7 +131,7 @@ void LegacyThreadPool::init() { _initedFlags[i] = std::make_shared>(true); ++_initedThreadNum; } else { - _abortFlags[i] = std::make_shared>(true); + _abortFlags[i] = std::make_shared>(true); _initedFlags[i] = std::make_shared>(false); } } @@ -143,7 +143,7 @@ bool LegacyThreadPool::tryShrinkPool() { auto before = std::chrono::high_resolution_clock::now(); ccstd::vector threadIDsToJoin; - int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep); + int maxThreadNumToJoin = std::min(_initedThreadNum - _minThreadNum, _shrinkStep); for (int i = 0; i < _maxThreadNum; ++i) { if ((int)threadIDsToJoin.size() >= maxThreadNumToJoin) { @@ -201,7 +201,7 @@ void LegacyThreadPool::stretchPool(int count) { } if (newThreadCount > 0) { - auto after = std::chrono::high_resolution_clock::now(); + auto after = std::chrono::high_resolution_clock::now(); float seconds = TIME_MINUS(after, before); LOGD("stretch pool from %d to %d, waste %f seconds\n", oldThreadCount, _initedThreadNum, @@ -210,7 +210,7 @@ void LegacyThreadPool::stretchPool(int count) { } void LegacyThreadPool::pushTask(const std::function &runnable, - TaskType type /* = DEFAULT*/) { + TaskType type /* = DEFAULT*/) { if (!_isFixedSize) { _idleThreadNumMutex.lock(); int idleNum = _idleThreadNum; @@ -218,7 +218,7 @@ void LegacyThreadPool::pushTask(const std::function &runnable, if (idleNum > _minThreadNum) { if (_taskQueue.empty()) { - auto now = std::chrono::high_resolution_clock::now(); + auto now = std::chrono::high_resolution_clock::now(); float seconds = TIME_MINUS(now, _lastShrinkTime); if (seconds > _shrinkInterval) { tryShrinkPool(); @@ -235,7 +235,7 @@ void LegacyThreadPool::pushTask(const std::function &runnable, }); Task task; - task.type = type; + task.type = type; task.callback = callback; _taskQueue.push(task); @@ -340,8 +340,8 @@ void LegacyThreadPool::setThread(int tid) { _abortFlags[tid]); // a copy of the shared ptr to the flag auto f = [this, tid, abortPtr /* a copy of the shared ptr to the abort */]() { std::atomic &abort = *abortPtr; - Task task; - bool isPop = _taskQueue.pop(task); + Task task; + bool isPop = _taskQueue.pop(task); while (true) { while (isPop) { // if there is anything in the queue std::unique_ptr> func( diff --git a/native/cocos/base/ThreadPool.h b/native/cocos/base/ThreadPool.h index 5389f2abdf..6236d1dd10 100644 --- a/native/cocos/base/ThreadPool.h +++ b/native/cocos/base/ThreadPool.h @@ -143,7 +143,7 @@ private: void stretchPool(int count); - ccstd::vector> _threads; + ccstd::vector> _threads; ccstd::vector>> _abortFlags; ccstd::vector>> _idleFlags; ccstd::vector>> _initedFlags; @@ -168,39 +168,39 @@ private: } bool empty() const { - auto thiz = const_cast(this); + auto thiz = const_cast(this); std::unique_lock lock(thiz->mutex); return this->q.empty(); } size_t size() const { - auto thiz = const_cast(this); + auto thiz = const_cast(this); std::unique_lock lock(thiz->mutex); return this->q.size(); } private: ccstd::queue q; - std::mutex mutex; + std::mutex mutex; }; struct Task { - TaskType type; + TaskType type; std::function *callback; }; static LegacyThreadPool *_instance; ThreadSafeQueue _taskQueue; - std::atomic _isDone{false}; - std::atomic _isStop{false}; + std::atomic _isDone{false}; + std::atomic _isStop{false}; //IDEA: std::atomic isn't supported by ndk-r10e while compiling with `armeabi` arch. // So using a mutex here instead. - int _idleThreadNum{0}; // how many threads are waiting + int _idleThreadNum{0}; // how many threads are waiting std::mutex _idleThreadNumMutex; - std::mutex _mutex; + std::mutex _mutex; std::condition_variable _cv; int _minThreadNum{0}; @@ -208,10 +208,10 @@ private: int _initedThreadNum{0}; std::chrono::time_point _lastShrinkTime; - float _shrinkInterval{5}; - int _shrinkStep{2}; - int _stretchStep{2}; - bool _isFixedSize{false}; + float _shrinkInterval{5}; + int _shrinkStep{2}; + int _stretchStep{2}; + bool _isFixedSize{false}; }; } // namespace cc diff --git a/native/cocos/base/Timer.cpp b/native/cocos/base/Timer.cpp index 90f2fdba84..37cb30dc85 100644 --- a/native/cocos/base/Timer.cpp +++ b/native/cocos/base/Timer.cpp @@ -40,7 +40,7 @@ void Timer::reset() { int64_t Timer::getMicroseconds() const { auto currentTime = Clock::now(); - auto duration = std::chrono::duration_cast(currentTime - _startTime).count(); + auto duration = std::chrono::duration_cast(currentTime - _startTime).count(); if (duration < 0) { duration = 0; } @@ -50,7 +50,7 @@ int64_t Timer::getMicroseconds() const { int64_t Timer::getMilliseconds() const { auto currentTime = Clock::now(); - auto duration = std::chrono::duration_cast(currentTime - _startTime).count(); + auto duration = std::chrono::duration_cast(currentTime - _startTime).count(); if (duration < 0) { duration = 0; } diff --git a/native/cocos/base/Timer.h b/native/cocos/base/Timer.h index 29b8443a07..5dfef95d33 100644 --- a/native/cocos/base/Timer.h +++ b/native/cocos/base/Timer.h @@ -34,15 +34,15 @@ namespace utils { class CC_DLL Timer { public: - using Clock = std::chrono::high_resolution_clock; + using Clock = std::chrono::high_resolution_clock; using TimePoint = Clock::time_point; explicit Timer(bool doReset = true); - void reset(); + void reset(); int64_t getMicroseconds() const; int64_t getMilliseconds() const; - float getSeconds(bool highPrecision = false) const; + float getSeconds(bool highPrecision = false) const; private: TimePoint _startTime; diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index d934ca739c..7ac43b46c2 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -29,7 +29,7 @@ #include "base/Macros.h" #include "base/std/container/unordered_map.h" -using uint = std::uint32_t; +using uint = std::uint32_t; using ushort = std::uint16_t; #if (CC_PLATFORM != CC_PLATFORM_LINUX && CC_PLATFORM != CC_PLATFORM_QNX) // linux has typedef ulong @@ -45,38 +45,38 @@ using index_t = int32_t; #define CC_ENUM_CONVERSION_OPERATOR(T) \ inline std::underlying_type::type toNumber(const T v) { return static_cast::type>(v); } -#define CC_ENUM_BITWISE_OPERATORS(T) \ - inline bool operator!(const T v) { return !static_cast::type>(v); } \ - inline T operator~(const T v) { return static_cast(~static_cast::type>(v)); } \ - inline bool operator||(const T lhs, const T rhs) { return (static_cast::type>(lhs) || static_cast::type>(rhs)); } \ - inline bool operator&&(const T lhs, const T rhs) { return (static_cast::type>(lhs) && static_cast::type>(rhs)); } \ - inline T operator|(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) | static_cast::type>(rhs)); } \ - inline T operator&(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) & static_cast::type>(rhs)); } \ - inline T operator^(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) ^ static_cast::type>(rhs)); } \ - inline T operator+(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) + static_cast::type>(rhs)); } \ - inline T operator+(const T lhs, bool rhs) { return static_cast(static_cast::type>(lhs) + rhs); } \ - inline void operator|=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) | static_cast::type>(rhs)); } \ - inline void operator&=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) & static_cast::type>(rhs)); } \ - inline void operator^=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) ^ static_cast::type>(rhs)); } \ - inline bool hasFlag(const T flags, const T flagToTest) { \ - using ValueType = std::underlying_type::type; \ - CC_ASSERT((static_cast(flagToTest) & (static_cast(flagToTest) - 1)) == 0); \ - return (static_cast(flags) & static_cast(flagToTest)) != 0; \ - } \ - inline bool hasAnyFlags(const T flags, const T flagsToTest) { \ - using ValueType = std::underlying_type::type; \ - return (static_cast(flags) & static_cast(flagsToTest)) != 0; \ - } \ - inline bool hasAllFlags(const T flags, const T flagsToTest) { \ - using ValueType = std::underlying_type::type; \ - return (static_cast(flags) & static_cast(flagsToTest)) == static_cast(flagsToTest); \ - } \ - inline T addFlags(T &flags, const T flagsToAdd) { \ - flags |= flagsToAdd; \ - return flags; \ - } \ - inline T removeFlags(T &flags, const T flagsToRemove) { \ - flags &= ~flagsToRemove; \ - return flags; \ - } \ +#define CC_ENUM_BITWISE_OPERATORS(T) \ + inline bool operator!(const T v) { return !static_cast::type>(v); } \ + inline T operator~(const T v) { return static_cast(~static_cast::type>(v)); } \ + inline bool operator||(const T lhs, const T rhs) { return (static_cast::type>(lhs) || static_cast::type>(rhs)); } \ + inline bool operator&&(const T lhs, const T rhs) { return (static_cast::type>(lhs) && static_cast::type>(rhs)); } \ + inline T operator|(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) | static_cast::type>(rhs)); } \ + inline T operator&(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) & static_cast::type>(rhs)); } \ + inline T operator^(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) ^ static_cast::type>(rhs)); } \ + inline T operator+(const T lhs, const T rhs) { return static_cast(static_cast::type>(lhs) + static_cast::type>(rhs)); } \ + inline T operator+(const T lhs, bool rhs) { return static_cast(static_cast::type>(lhs) + rhs); } \ + inline void operator|=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) | static_cast::type>(rhs)); } \ + inline void operator&=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) & static_cast::type>(rhs)); } \ + inline void operator^=(T &lhs, const T rhs) { lhs = static_cast(static_cast::type>(lhs) ^ static_cast::type>(rhs)); } \ + inline bool hasFlag(const T flags, const T flagToTest) { \ + using ValueType = std::underlying_type::type; \ + CC_ASSERT((static_cast(flagToTest) & (static_cast(flagToTest) - 1)) == 0); \ + return (static_cast(flags) & static_cast(flagToTest)) != 0; \ + } \ + inline bool hasAnyFlags(const T flags, const T flagsToTest) { \ + using ValueType = std::underlying_type::type; \ + return (static_cast(flags) & static_cast(flagsToTest)) != 0; \ + } \ + inline bool hasAllFlags(const T flags, const T flagsToTest) { \ + using ValueType = std::underlying_type::type; \ + return (static_cast(flags) & static_cast(flagsToTest)) == static_cast(flagsToTest); \ + } \ + inline T addFlags(T &flags, const T flagsToAdd) { \ + flags |= flagsToAdd; \ + return flags; \ + } \ + inline T removeFlags(T &flags, const T flagsToRemove) { \ + flags &= ~flagsToRemove; \ + return flags; \ + } \ CC_ENUM_CONVERSION_OPERATOR(T) diff --git a/native/cocos/base/UTF8.cpp b/native/cocos/base/UTF8.cpp index ede81e78b2..6b0cd0f366 100644 --- a/native/cocos/base/UTF8.cpp +++ b/native/cocos/base/UTF8.cpp @@ -174,7 +174,7 @@ bool utfConvert( constexpr int mostBytesPerCharacter = 4; const size_t maxNumberOfChars = from.length(); // all UTFs at most one element represents one character. - const size_t numberOfOut = maxNumberOfChars * mostBytesPerCharacter / sizeof(To); + const size_t numberOfOut = maxNumberOfChars * mostBytesPerCharacter / sizeof(To); std::basic_string working(numberOfOut, 0); @@ -183,7 +183,7 @@ bool utfConvert( auto outbeg = reinterpret_cast(&working[0]); auto outend = outbeg + working.length(); - auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion); + auto r = cvtfunc(&inbeg, inend, &outbeg, outend, strictConversion); if (r != conversionOK) { return false; } @@ -195,9 +195,9 @@ bool utfConvert( }; CC_DLL void UTF8LooseFix(const ccstd::string &in, ccstd::string &out) { //NOLINT - const auto *p = reinterpret_cast(in.c_str()); - const auto *end = reinterpret_cast(in.c_str() + in.size()); - unsigned ucharLen = 0; + const auto *p = reinterpret_cast(in.c_str()); + const auto *end = reinterpret_cast(in.c_str() + in.size()); + unsigned ucharLen = 0; while (p < end) { ucharLen = getNumBytesForUTF8(*p); if (isLegalUTF8Sequence(p, p + ucharLen)) { @@ -237,11 +237,11 @@ bool UTF32ToUTF16(const std::u32string &utf32, std::u16string &outUtf16) { //NOL #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) ccstd::string getStringUTFCharsJNI(JNIEnv *env, jstring srcjStr, bool *ret) { - ccstd::string utf8Str; - auto * unicodeChar = static_cast(env->GetStringChars(srcjStr, nullptr)); - size_t unicodeCharLength = env->GetStringLength(srcjStr); + ccstd::string utf8Str; + auto *unicodeChar = static_cast(env->GetStringChars(srcjStr, nullptr)); + size_t unicodeCharLength = env->GetStringLength(srcjStr); const std::u16string unicodeStr(reinterpret_cast(unicodeChar), unicodeCharLength); - bool flag = UTF16ToUTF8(unicodeStr, utf8Str); + bool flag = UTF16ToUTF8(unicodeStr, utf8Str); if (ret) { *ret = flag; @@ -256,7 +256,7 @@ ccstd::string getStringUTFCharsJNI(JNIEnv *env, jstring srcjStr, bool *ret) { jstring newStringUTFJNI(JNIEnv *env, const ccstd::string &utf8Str, bool *ret) { std::u16string utf16Str; - bool flag = cc::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); + bool flag = cc::StringUtils::UTF8ToUTF16(utf8Str, utf16Str); if (ret) { *ret = flag; diff --git a/native/cocos/base/UTF8.h b/native/cocos/base/UTF8.h index 18edbcf3df..8379bc0cf6 100644 --- a/native/cocos/base/UTF8.h +++ b/native/cocos/base/UTF8.h @@ -189,7 +189,7 @@ class CC_DLL StringUTF8 { public: struct CharUTF8 { ccstd::string _char; - bool isAnsi() { return _char.size() == 1; } + bool isAnsi() { return _char.size() == 1; } }; using CharUTF8Store = ccstd::vector; @@ -198,7 +198,7 @@ public: ~StringUTF8() = default; std::size_t length() const; - void replace(const ccstd::string &newStr); + void replace(const ccstd::string &newStr); ccstd::string getAsCharSequence() const; diff --git a/native/cocos/base/Value.cpp b/native/cocos/base/Value.cpp index 634ed5385c..35c4e82e38 100644 --- a/native/cocos/base/Value.cpp +++ b/native/cocos/base/Value.cpp @@ -39,8 +39,8 @@ namespace cc { -const ValueVector VALUE_VECTOR_NULL; -const ValueMap VALUE_MAP_NULL = {}; +const ValueVector VALUE_VECTOR_NULL; +const ValueMap VALUE_MAP_NULL = {}; const ValueMapIntKey VALUE_MAP_INT_KEY_NULL = {}; const Value Value::VALUE_NULL; @@ -90,43 +90,43 @@ Value::Value(const char *v) Value::Value(const ccstd::string &v) : _type(Type::STRING) { - _field.strVal = ccnew ccstd::string(); + _field.strVal = ccnew ccstd::string(); *_field.strVal = v; } Value::Value(const ValueVector &v) : _type(Type::VECTOR) { - _field.vectorVal = ccnew ValueVector(); + _field.vectorVal = ccnew ValueVector(); *_field.vectorVal = v; } Value::Value(ValueVector &&v) : _type(Type::VECTOR) { - _field.vectorVal = ccnew ValueVector(); + _field.vectorVal = ccnew ValueVector(); *_field.vectorVal = std::move(v); } Value::Value(const ValueMap &v) : _type(Type::MAP) { - _field.mapVal = ccnew ValueMap(); + _field.mapVal = ccnew ValueMap(); *_field.mapVal = v; } Value::Value(ValueMap &&v) : _type(Type::MAP) { - _field.mapVal = ccnew ValueMap(); + _field.mapVal = ccnew ValueMap(); *_field.mapVal = std::move(v); } Value::Value(const ValueMapIntKey &v) : _type(Type::INT_KEY_MAP) { - _field.intKeyMapVal = ccnew ValueMapIntKey(); + _field.intKeyMapVal = ccnew ValueMapIntKey(); *_field.intKeyMapVal = v; } Value::Value(ValueMapIntKey &&v) : _type(Type::INT_KEY_MAP) { - _field.intKeyMapVal = ccnew ValueMapIntKey(); + _field.intKeyMapVal = ccnew ValueMapIntKey(); *_field.intKeyMapVal = std::move(v); } @@ -181,7 +181,7 @@ Value &Value::operator=(const Value &other) { //NOLINT(misc-no-recursion) break; case Type::MAP: if (_field.mapVal == nullptr) { - _field.mapVal = ccnew ValueMap(); + _field.mapVal = ccnew ValueMap(); } *_field.mapVal = *other._field.mapVal; break; @@ -361,9 +361,9 @@ bool Value::operator==(const Value &v) const { //NOLINT(misc-no-recursion) case Type::FLOAT: return std::abs(v._field.floatVal - this->_field.floatVal) <= FLT_EPSILON; case Type::DOUBLE: return std::abs(v._field.doubleVal - this->_field.doubleVal) <= DBL_EPSILON; case Type::VECTOR: { - const auto &v1 = *(this->_field.vectorVal); - const auto &v2 = *(v._field.vectorVal); - const auto size = v1.size(); + const auto &v1 = *(this->_field.vectorVal); + const auto &v2 = *(v._field.vectorVal); + const auto size = v1.size(); if (size == v2.size()) { for (size_t i = 0; i < size; i++) { if (v1[i] != v2[i]) { diff --git a/native/cocos/base/Value.h b/native/cocos/base/Value.h index f0856808c8..fdfbeadc8a 100644 --- a/native/cocos/base/Value.h +++ b/native/cocos/base/Value.h @@ -35,12 +35,12 @@ namespace cc { class Value; -using ValueVector = ccstd::vector; -using ValueMap = ccstd::unordered_map; +using ValueVector = ccstd::vector; +using ValueMap = ccstd::unordered_map; using ValueMapIntKey = ccstd::unordered_map; -CC_DLL extern const ValueVector VALUE_VECTOR_NULL; -CC_DLL extern const ValueMap VALUE_MAP_NULL; +CC_DLL extern const ValueVector VALUE_VECTOR_NULL; +CC_DLL extern const ValueMap VALUE_MAP_NULL; CC_DLL extern const ValueMapIntKey VALUE_MAP_INT_KEY_NULL; /* @@ -221,15 +221,15 @@ private: union { unsigned char byteVal; - int intVal; - unsigned int unsignedVal; - float floatVal; - double doubleVal; - bool boolVal; + int intVal; + unsigned int unsignedVal; + float floatVal; + double doubleVal; + bool boolVal; - ccstd::string * strVal; - ValueVector * vectorVal; - ValueMap * mapVal; + ccstd::string *strVal; + ValueVector *vectorVal; + ValueMap *mapVal; ValueMapIntKey *intKeyMapVal; } _field; diff --git a/native/cocos/base/ZipUtils.cpp b/native/cocos/base/ZipUtils.cpp index ff850cf468..8b5c200fd2 100644 --- a/native/cocos/base/ZipUtils.cpp +++ b/native/cocos/base/ZipUtils.cpp @@ -56,14 +56,14 @@ namespace cc { unsigned int ZipUtils::encryptedPvrKeyParts[4] = {0, 0, 0, 0}; unsigned int ZipUtils::encryptionKey[1024]; -bool ZipUtils::encryptionKeyIsValid = false; +bool ZipUtils::encryptionKeyIsValid = false; // --------------------- ZipUtils --------------------- inline void ZipUtils::decodeEncodedPvr(unsigned int *data, uint32_t len) { - const int enclen = 1024; + const int enclen = 1024; const int securelen = 512; - const int distance = 64; + const int distance = 64; // check if key was set // make sure to call caw_setkey_part() for all 4 key parts @@ -78,8 +78,8 @@ inline void ZipUtils::decodeEncodedPvr(unsigned int *data, uint32_t len) { unsigned int p{0}; unsigned int e{0}; unsigned int rounds = 6; - unsigned int sum = 0; - unsigned int z = ZipUtils::encryptionKey[enclen - 1]; + unsigned int sum = 0; + unsigned int z = ZipUtils::encryptionKey[enclen - 1]; do { #define DELTA 0x9e3779b9 @@ -124,8 +124,8 @@ inline void ZipUtils::decodeEncodedPvr(unsigned int *data, uint32_t len) { } inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, uint32_t len) { - unsigned int cs = 0; - const int cslen = 128; + unsigned int cs = 0; + const int cslen = 128; len = (len < cslen) ? len : cslen; @@ -142,18 +142,18 @@ inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, uint32_t len int ZipUtils::inflateMemoryWithHint(unsigned char *in, uint32_t inLength, unsigned char **out, uint32_t *outLength, uint32_t outLengthHint) { /* ret value */ - int err = Z_OK; + int err = Z_OK; uint32_t bufferSize = outLengthHint; - *out = static_cast(malloc(bufferSize)); + *out = static_cast(malloc(bufferSize)); z_stream descompressionStream; /* decompression stream */ descompressionStream.zalloc = static_cast(nullptr); - descompressionStream.zfree = static_cast(nullptr); + descompressionStream.zfree = static_cast(nullptr); descompressionStream.opaque = static_cast(nullptr); - descompressionStream.next_in = in; - descompressionStream.avail_in = inLength; - descompressionStream.next_out = *out; + descompressionStream.next_in = in; + descompressionStream.avail_in = inLength; + descompressionStream.next_out = *out; descompressionStream.avail_out = bufferSize; /* window size to hold 256k */ @@ -188,20 +188,20 @@ int ZipUtils::inflateMemoryWithHint(unsigned char *in, uint32_t inLength, unsign return Z_MEM_ERROR; } - descompressionStream.next_out = *out + bufferSize; + descompressionStream.next_out = *out + bufferSize; descompressionStream.avail_out = static_cast(bufferSize); bufferSize *= BUFFER_INC_FACTOR; } } *outLength = bufferSize - descompressionStream.avail_out; - err = inflateEnd(&descompressionStream); + err = inflateEnd(&descompressionStream); return err; } uint32_t ZipUtils::inflateMemoryWithHint(unsigned char *in, uint32_t inLength, unsigned char **out, uint32_t outLengthHint) { uint32_t outLength = 0; - int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); + int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint); if (err != Z_OK || *out == nullptr) { if (err == Z_MEM_ERROR) { @@ -243,7 +243,7 @@ int ZipUtils::inflateGZipFile(const char *path, unsigned char **out) { } /* 512k initial decompress buffer */ - unsigned int bufferSize = 512 * 1024; + unsigned int bufferSize = 512 * 1024; unsigned int totalBufferSize = bufferSize; *out = static_cast(malloc(bufferSize)); @@ -369,13 +369,13 @@ int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, uint32_t bufferLen, #if CC_DEBUG > 0 // decrypt - auto * ints = reinterpret_cast(const_cast(buffer) + 12); + auto *ints = reinterpret_cast(const_cast(buffer) + 12); uint32_t enclen = (bufferLen - 12) / 4; decodeEncodedPvr(ints, enclen); // verify checksum in debug mode unsigned int calculated = checksumPvr(ints, enclen); - unsigned int required = CC_SWAP_INT32_BIG_TO_HOST(header->reserved); + unsigned int required = CC_SWAP_INT32_BIG_TO_HOST(header->reserved); if (calculated != required) { CC_LOG_DEBUG("Can't decrypt image file. Is the decryption key valid?"); @@ -395,9 +395,9 @@ int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, uint32_t bufferLen, return -1; } - uLongf destlen = len; - const auto *source = reinterpret_cast(buffer + sizeof(*header)); - int ret = uncompress(*out, &destlen, source, static_cast(bufferLen - sizeof(*header))); + uLongf destlen = len; + const auto *source = reinterpret_cast(buffer + sizeof(*header)); + int ret = uncompress(*out, &destlen, source, static_cast(bufferLen - sizeof(*header))); if (ret != Z_OK) { CC_LOG_DEBUG("CCZ: Failed to uncompress data"); @@ -429,7 +429,7 @@ void ZipUtils::setPvrEncryptionKeyPart(int index, unsigned int value) { if (ZipUtils::encryptedPvrKeyParts[index] != value) { ZipUtils::encryptedPvrKeyParts[index] = value; - ZipUtils::encryptionKeyIsValid = false; + ZipUtils::encryptionKeyIsValid = false; } } @@ -448,13 +448,13 @@ static const ccstd::string EMPTY_FILE_NAME; struct ZipEntryInfo { unz_file_pos pos; - uLong uncompressed_size; + uLong uncompressed_size; }; class ZipFilePrivate { public: Locked zipFile; - std::unique_ptr memfs; + std::unique_ptr memfs; // ccstd::unordered_map is faster if available on the platform using FileListContainer = ccstd::unordered_map; @@ -473,13 +473,13 @@ ZipFile *ZipFile::createWithBuffer(const void *buffer, uint32_t size) { ZipFile::ZipFile() : _data(ccnew ZipFilePrivate) { auto zipFile = _data->zipFile.lock(); - *zipFile = nullptr; + *zipFile = nullptr; } ZipFile::ZipFile(const ccstd::string &zipFile, const ccstd::string &filter) : _data(ccnew ZipFilePrivate) { auto zipFileL = _data->zipFile.lock(); - *zipFileL = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFile).c_str()); + *zipFileL = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFile).c_str()); setFilter(filter); } @@ -505,7 +505,7 @@ bool ZipFile::setFilter(const ccstd::string &filter) { _data->fileList.clear(); // UNZ_MAXFILENAMEINZIP + 1 - it is done so in unzLocateFile - char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1]; + char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1]; unz_file_info64 fileInfo; // go through all files and store position information about the required files @@ -513,14 +513,14 @@ bool ZipFile::setFilter(const ccstd::string &filter) { szCurrentFileName, sizeof(szCurrentFileName) - 1); while (err == UNZ_OK) { unz_file_pos posInfo; - int posErr = unzGetFilePos(*zipFile, &posInfo); + int posErr = unzGetFilePos(*zipFile, &posInfo); if (posErr == UNZ_OK) { ccstd::string currentFileName = szCurrentFileName; // cache info about filtered files only (like 'assets/') if (filter.empty() || currentFileName.substr(0, filter.length()) == filter) { ZipEntryInfo entry; - entry.pos = posInfo; - entry.uncompressed_size = static_cast(fileInfo.uncompressed_size); + entry.pos = posInfo; + entry.uncompressed_size = static_cast(fileInfo.uncompressed_size); _data->fileList[currentFileName] = entry; } } @@ -568,7 +568,7 @@ unsigned char *ZipFile::getFileData(const ccstd::string &fileName, uint32_t *siz nRet = unzOpenCurrentFile(*zipFile); CC_BREAK_IF(UNZ_OK != nRet); - buffer = static_cast(malloc(fileInfo.uncompressed_size)); + buffer = static_cast(malloc(fileInfo.uncompressed_size)); int CC_UNUSED nSize = unzReadCurrentFile(*zipFile, buffer, static_cast(fileInfo.uncompressed_size)); CC_ASSERT(nSize == 0 || nSize == (int)fileInfo.uncompressed_size); @@ -630,7 +630,7 @@ ccstd::string ZipFile::getNextFilename() { int ZipFile::getCurrentFileInfo(ccstd::string *filename, unz_file_info *info) { char path[FILENAME_MAX + 1]; auto zipFile = _data->zipFile.lock(); - int ret = unzGetCurrentFileInfo(*zipFile, info, path, sizeof(path), nullptr, 0, nullptr, 0); + int ret = unzGetCurrentFileInfo(*zipFile, info, path, sizeof(path), nullptr, 0, nullptr, 0); if (ret != UNZ_OK) { *filename = EMPTY_FILE_NAME; } else { @@ -641,7 +641,7 @@ int ZipFile::getCurrentFileInfo(ccstd::string *filename, unz_file_info *info) { bool ZipFile::initWithBuffer(const void *buffer, uint32_t size) { if (!buffer || size == 0) return false; - auto zipFile = _data->zipFile.lock(); + auto zipFile = _data->zipFile.lock(); zlib_filefunc_def memoryFile = {nullptr}; std::unique_ptr memfs(ccnew ourmemory_t{static_cast(const_cast(buffer)), static_cast(size), 0, 0, 0}); diff --git a/native/cocos/base/ZipUtils.h b/native/cocos/base/ZipUtils.h index 8b7716e5f1..3936d53597 100644 --- a/native/cocos/base/ZipUtils.h +++ b/native/cocos/base/ZipUtils.h @@ -41,11 +41,11 @@ using unz_file_info = struct unz_file_info_s; #endif struct CCZHeader { - unsigned char sig[4]; /** Signature. Should be 'CCZ!' 4 bytes. */ - uint16_t compression_type; /** Should be 0. */ - uint16_t version; /** Should be 2 (although version type==1 is also supported). */ - unsigned int reserved; /** Reserved for users. */ - unsigned int len; /** Size of the uncompressed file. */ + unsigned char sig[4]; /** Signature. Should be 'CCZ!' 4 bytes. */ + uint16_t compression_type; /** Should be 0. */ + uint16_t version; /** Should be 2 (although version type==1 is also supported). */ + unsigned int reserved; /** Reserved for users. */ + unsigned int len; /** Size of the uncompressed file. */ }; enum { @@ -184,13 +184,13 @@ public: static void setPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4); private: - static int inflateMemoryWithHint(unsigned char *in, uint32_t inLength, unsigned char **out, uint32_t *outLength, uint32_t outLengthHint); - static inline void decodeEncodedPvr(unsigned int *data, uint32_t len); + static int inflateMemoryWithHint(unsigned char *in, uint32_t inLength, unsigned char **out, uint32_t *outLength, uint32_t outLengthHint); + static inline void decodeEncodedPvr(unsigned int *data, uint32_t len); static inline unsigned int checksumPvr(const unsigned int *data, uint32_t len); static unsigned int encryptedPvrKeyParts[4]; static unsigned int encryptionKey[1024]; - static bool encryptionKeyIsValid; + static bool encryptionKeyIsValid; }; // forward declaration @@ -269,7 +269,7 @@ private: ZipFile(); bool initWithBuffer(const void *buffer, uint32_t size); - int getCurrentFileInfo(ccstd::string *filename, unz_file_info *info); + int getCurrentFileInfo(ccstd::string *filename, unz_file_info *info); /** Internal data like zip file pointer / file list array and so on */ ZipFilePrivate *_data{nullptr}; diff --git a/native/cocos/base/astc.cpp b/native/cocos/base/astc.cpp index a1bb5bf3d6..de0226a9c2 100644 --- a/native/cocos/base/astc.cpp +++ b/native/cocos/base/astc.cpp @@ -28,9 +28,9 @@ #include "base/astc.h" #include "platform/Image.h" -static const unsigned int MAGIC = 0x5CA1AB13; -static const astc_byte ASTC_HEADER_SIZE_X_BEGIN = 7; -static const astc_byte ASTC_HEADER_SIZE_Y_BEGIN = 10; +static const unsigned int MAGIC = 0x5CA1AB13; +static const astc_byte ASTC_HEADER_SIZE_X_BEGIN = 7; +static const astc_byte ASTC_HEADER_SIZE_Y_BEGIN = 10; bool astcIsValid(const astc_byte *pHeader) { uint32_t magicval = static_cast(pHeader[0]) + @@ -59,4 +59,3 @@ int astcGetHeight(const astc_byte *pHeader) { int ysize = pHeader[ASTC_HEADER_SIZE_Y_BEGIN] + (pHeader[ASTC_HEADER_SIZE_Y_BEGIN + 1] * 256) + (pHeader[ASTC_HEADER_SIZE_Y_BEGIN + 2] * 65536); return ysize; } - diff --git a/native/cocos/base/astc.h b/native/cocos/base/astc.h index 7fd9ab1c48..88feb709dc 100644 --- a/native/cocos/base/astc.h +++ b/native/cocos/base/astc.h @@ -29,7 +29,7 @@ #pragma once -using astc_byte = unsigned char; +using astc_byte = unsigned char; using astc_uint32 = unsigned int; // Size of a ASTC header diff --git a/native/cocos/base/base64.cpp b/native/cocos/base/base64.cpp index bf7c17bcef..f4fd0f8132 100644 --- a/native/cocos/base/base64.cpp +++ b/native/cocos/base/base64.cpp @@ -39,21 +39,21 @@ ccstd::string alphabet{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123 int doBase64Decode(const unsigned char *input, unsigned int inputLen, unsigned char *output, unsigned int *outputLen) { static ccstd::vector inalphabet(256); static ccstd::vector decoder(256); - int i; - int bits; - int c = 0; - int charCount; - int errors = 0; - unsigned int inputIdx = 0; - unsigned int outputIdx = 0; - int length = static_cast(alphabet.length()); + int i; + int bits; + int c = 0; + int charCount; + int errors = 0; + unsigned int inputIdx = 0; + unsigned int outputIdx = 0; + int length = static_cast(alphabet.length()); for (i = length - 1; i >= 0; i--) { inalphabet[alphabet[i]] = 1; - decoder[alphabet[i]] = i; + decoder[alphabet[i]] = i; } charCount = 0; - bits = 0; + bits = 0; for (inputIdx = 0; inputIdx < inputLen; inputIdx++) { c = input[inputIdx]; if (c == '=') { @@ -70,8 +70,8 @@ int doBase64Decode(const unsigned char *input, unsigned int inputLen, unsigned c output[outputIdx++] = (bits >> 16); output[outputIdx++] = ((bits >> 8) & 0xff); output[outputIdx++] = (bits & 0xff); - bits = 0; - charCount = 0; + bits = 0; + charCount = 0; } else { bits <<= 6; } @@ -110,11 +110,11 @@ int doBase64Decode(const unsigned char *input, unsigned int inputLen, unsigned c void doBase64Encode(const unsigned char *input, unsigned int inputLen, char *output) { unsigned int charCount; unsigned int bits; - unsigned int inputIdx = 0; + unsigned int inputIdx = 0; unsigned int outputIdx = 0; charCount = 0; - bits = 0; + bits = 0; for (inputIdx = 0; inputIdx < inputLen; inputIdx++) { bits |= input[inputIdx]; @@ -124,8 +124,8 @@ void doBase64Encode(const unsigned char *input, unsigned int inputLen, char *out output[outputIdx++] = alphabet[(bits >> 12) & 0x3f]; output[outputIdx++] = alphabet[(bits >> 6) & 0x3f]; output[outputIdx++] = alphabet[bits & 0x3f]; - bits = 0; - charCount = 0; + bits = 0; + charCount = 0; } else { bits <<= 8; } @@ -159,7 +159,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char * if (ret > 0) { free(*out); - *out = nullptr; + *out = nullptr; outLength = 0; } } diff --git a/native/cocos/base/csscolorparser.cpp b/native/cocos/base/csscolorparser.cpp index d29a93dc04..08f146ce86 100644 --- a/native/cocos/base/csscolorparser.cpp +++ b/native/cocos/base/csscolorparser.cpp @@ -60,7 +60,7 @@ namespace CSSColorParser { // http://www.w3.org/TR/css3-color/ struct NamedColor { const char *name; - Color color; + Color color; }; const ccstd::vector NAMED_COLORS = { @@ -216,14 +216,12 @@ const ccstd::vector NAMED_COLORS = { template uint8_t clampCssByte(T i) { // Clamp to integer 0 .. 255. i = static_cast(::round(i)); // Seems to be what Chrome does (vs truncation). - return static_cast(i < 0 ? 0 : i > 255 ? 255 - : i); + return static_cast(i < 0 ? 0 : i > 255 ? 255 : i); } template float clampCssFloat(T f) { // Clamp to float 0.0 .. 1.0. - return f < 0 ? 0 : f > 1 ? 1 - : float(f); + return f < 0 ? 0 : f > 1 ? 1 : float(f); } float parseFloat(const ccstd::string &str) { @@ -269,8 +267,8 @@ float cssHueToRgb(float m1, float m2, float h) { ccstd::vector split(const ccstd::string &s, char delim) { ccstd::vector elems; - std::stringstream ss(s); - ccstd::string item; + std::stringstream ss(s); + ccstd::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } @@ -324,7 +322,7 @@ Color parse(const ccstd::string &cssStr) { size_t op = str.find_first_of('('); size_t ep = str.find_first_of(')'); if (op != ccstd::string::npos && ep + 1 == str.length()) { - const ccstd::string fname = str.substr(0, op); + const ccstd::string fname = str.substr(0, op); const ccstd::vector params = split(str.substr(op + 1, ep - (op + 1)), ','); diff --git a/native/cocos/base/csscolorparser.h b/native/cocos/base/csscolorparser.h index 9b4e81a178..a782060cab 100644 --- a/native/cocos/base/csscolorparser.h +++ b/native/cocos/base/csscolorparser.h @@ -57,11 +57,10 @@ namespace CSSColorParser { struct Color { inline Color() = default; inline Color(unsigned char red, unsigned char green, unsigned char blue, float alpha) - : r(red), g(green), b(blue), a(alpha > 1 ? 1 : alpha < 0 ? 0 - : alpha) { + : r(red), g(green), b(blue), a(alpha > 1 ? 1 : alpha < 0 ? 0 : alpha) { } unsigned char r = 0, g = 0, b = 0; - float a = 1.0f; + float a = 1.0f; }; inline bool operator==(const Color &lhs, const Color &rhs) { diff --git a/native/cocos/base/etc1.cpp b/native/cocos/base/etc1.cpp index 16af2b5af8..68f4570b40 100644 --- a/native/cocos/base/etc1.cpp +++ b/native/cocos/base/etc1.cpp @@ -43,11 +43,11 @@ static const char kMagic[] = {'P', 'K', 'M', ' ', '1', '0'}; -static const etc1_uint32 ETC1_PKM_FORMAT_OFFSET = 6; -static const etc1_uint32 ETC1_PKM_ENCODED_WIDTH_OFFSET = 8; +static const etc1_uint32 ETC1_PKM_FORMAT_OFFSET = 6; +static const etc1_uint32 ETC1_PKM_ENCODED_WIDTH_OFFSET = 8; static const etc1_uint32 ETC1_PKM_ENCODED_HEIGHT_OFFSET = 10; -static const etc1_uint32 ETC1_PKM_WIDTH_OFFSET = 12; -static const etc1_uint32 ETC1_PKM_HEIGHT_OFFSET = 14; +static const etc1_uint32 ETC1_PKM_WIDTH_OFFSET = 12; +static const etc1_uint32 ETC1_PKM_HEIGHT_OFFSET = 14; static const etc1_uint32 ETC1_RGB_NO_MIPMAPS = 0; @@ -61,11 +61,11 @@ etc1_bool etc1_pkm_is_valid(const etc1_byte *pHeader) { if (memcmp(pHeader, kMagic, sizeof(kMagic))) { return false; } - etc1_uint32 format = readBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET); - etc1_uint32 encodedWidth = readBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET); + etc1_uint32 format = readBEUint16(pHeader + ETC1_PKM_FORMAT_OFFSET); + etc1_uint32 encodedWidth = readBEUint16(pHeader + ETC1_PKM_ENCODED_WIDTH_OFFSET); etc1_uint32 encodedHeight = readBEUint16(pHeader + ETC1_PKM_ENCODED_HEIGHT_OFFSET); - etc1_uint32 width = readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); - etc1_uint32 height = readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); + etc1_uint32 width = readBEUint16(pHeader + ETC1_PKM_WIDTH_OFFSET); + etc1_uint32 height = readBEUint16(pHeader + ETC1_PKM_HEIGHT_OFFSET); return format == ETC1_RGB_NO_MIPMAPS && encodedWidth >= width && encodedWidth - width < 4 && encodedHeight >= height && encodedHeight - height < 4; diff --git a/native/cocos/base/etc1.h b/native/cocos/base/etc1.h index a18a7986f4..829e2d4e73 100644 --- a/native/cocos/base/etc1.h +++ b/native/cocos/base/etc1.h @@ -49,8 +49,8 @@ #endif typedef unsigned char etc1_byte; -typedef int etc1_bool; -typedef unsigned int etc1_uint32; +typedef int etc1_bool; +typedef unsigned int etc1_uint32; #ifdef __cplusplus extern "C" { diff --git a/native/cocos/base/etc2.cpp b/native/cocos/base/etc2.cpp index 27cdafd768..4a0d1bc435 100644 --- a/native/cocos/base/etc2.cpp +++ b/native/cocos/base/etc2.cpp @@ -31,11 +31,11 @@ static const char kMagic[] = {'P', 'K', 'M', ' ', '2', '0'}; -static const etc2_uint32 ETC2_PKM_FORMAT_OFFSET = 6; -static const etc2_uint32 ETC2_PKM_ENCODED_WIDTH_OFFSET = 8; +static const etc2_uint32 ETC2_PKM_FORMAT_OFFSET = 6; +static const etc2_uint32 ETC2_PKM_ENCODED_WIDTH_OFFSET = 8; static const etc2_uint32 ETC2_PKM_ENCODED_HEIGHT_OFFSET = 10; -static const etc2_uint32 ETC2_PKM_WIDTH_OFFSET = 12; -static const etc2_uint32 ETC2_PKM_HEIGHT_OFFSET = 14; +static const etc2_uint32 ETC2_PKM_WIDTH_OFFSET = 12; +static const etc2_uint32 ETC2_PKM_HEIGHT_OFFSET = 14; static etc2_uint32 readBEUint16(const etc2_byte *pIn) { return (pIn[0] << 8) | pIn[1]; @@ -47,11 +47,11 @@ etc2_bool etc2_pkm_is_valid(const etc2_byte *pHeader) { if (memcmp(pHeader, kMagic, sizeof(kMagic))) { return false; } - etc2_uint32 format = readBEUint16(pHeader + ETC2_PKM_FORMAT_OFFSET); - etc2_uint32 encodedWidth = readBEUint16(pHeader + ETC2_PKM_ENCODED_WIDTH_OFFSET); + etc2_uint32 format = readBEUint16(pHeader + ETC2_PKM_FORMAT_OFFSET); + etc2_uint32 encodedWidth = readBEUint16(pHeader + ETC2_PKM_ENCODED_WIDTH_OFFSET); etc2_uint32 encodedHeight = readBEUint16(pHeader + ETC2_PKM_ENCODED_HEIGHT_OFFSET); - etc2_uint32 width = readBEUint16(pHeader + ETC2_PKM_WIDTH_OFFSET); - etc2_uint32 height = readBEUint16(pHeader + ETC2_PKM_HEIGHT_OFFSET); + etc2_uint32 width = readBEUint16(pHeader + ETC2_PKM_WIDTH_OFFSET); + etc2_uint32 height = readBEUint16(pHeader + ETC2_PKM_HEIGHT_OFFSET); return (format == ETC2_RGB_NO_MIPMAPS || format == ETC2_RGBA_NO_MIPMAPS) && encodedWidth >= width && encodedWidth - width < 4 && encodedHeight >= height && encodedHeight - height < 4; diff --git a/native/cocos/base/etc2.h b/native/cocos/base/etc2.h index 6b388dce76..52bb509f90 100644 --- a/native/cocos/base/etc2.h +++ b/native/cocos/base/etc2.h @@ -30,8 +30,8 @@ /// @cond DO_NOT_SHOW typedef unsigned char etc2_byte; -typedef int etc2_bool; -typedef unsigned int etc2_uint32; +typedef int etc2_bool; +typedef unsigned int etc2_uint32; #ifndef GL_COMPRESSED_RGB8_ETC2 #define GL_COMPRESSED_RGB8_ETC2 0x9274 diff --git a/native/cocos/base/job-system/JobSystem.h b/native/cocos/base/job-system/JobSystem.h index 43a42e666c..3a4def2c0e 100644 --- a/native/cocos/base/job-system/JobSystem.h +++ b/native/cocos/base/job-system/JobSystem.h @@ -27,24 +27,24 @@ #include "job-system-taskflow/TFJobGraph.h" #include "job-system-taskflow/TFJobSystem.h" namespace cc { -using JobToken = TFJobToken; -using JobGraph = TFJobGraph; +using JobToken = TFJobToken; +using JobGraph = TFJobGraph; using JobSystem = TFJobSystem; } // namespace cc #elif CC_USE_JOB_SYSTEM_TBB #include "job-system-tbb/TBBJobGraph.h" #include "job-system-tbb/TBBJobSystem.h" namespace cc { -using JobToken = TBBJobToken; -using JobGraph = TBBJobGraph; +using JobToken = TBBJobToken; +using JobGraph = TBBJobGraph; using JobSystem = TBBJobSystem; } // namespace cc #else #include "job-system-dummy/DummyJobGraph.h" #include "job-system-dummy/DummyJobSystem.h" namespace cc { -using JobToken = DummyJobToken; -using JobGraph = DummyJobGraph; +using JobToken = DummyJobToken; +using JobGraph = DummyJobGraph; using JobSystem = DummyJobSystem; } // namespace cc #endif diff --git a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.cpp b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.cpp index f143589cf0..53f509ca51 100644 --- a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.cpp +++ b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.cpp @@ -31,7 +31,7 @@ namespace cc { namespace { -DummyGraphNode * freeList{nullptr}; +DummyGraphNode *freeList{nullptr}; ccstd::vector allocatedChunks; } // namespace @@ -72,7 +72,7 @@ DummyGraphNode *DummyGraphNode::alloc() { if (freeList == nullptr) { DummyGraphNode::allocChunk(); } - auto *p = freeList; + auto *p = freeList; freeList = freeList->_next; p->reset(); return p; @@ -80,7 +80,7 @@ DummyGraphNode *DummyGraphNode::alloc() { void DummyGraphNode::free(DummyGraphNode *node) { node->_next = freeList; - freeList = node; + freeList = node; } void DummyGraphNode::freeAll() { diff --git a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h index f891141b81..9bbd57dc7c 100644 --- a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h +++ b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h @@ -38,9 +38,9 @@ class DummyJobSystem; class DummyGraphNode; class DummyGraph final { public: - DummyGraph() = default; + DummyGraph() = default; DummyGraph(const DummyGraph &) = delete; - DummyGraph(DummyGraph &&) = delete; + DummyGraph(DummyGraph &&) = delete; DummyGraph &operator=(const DummyGraph &) = delete; DummyGraph &operator=(DummyGraph &&) = delete; ~DummyGraph(); @@ -56,14 +56,14 @@ public: private: bool excuted(DummyGraphNode *n) const; - int _generation{0}; + int _generation{0}; ccstd::vector _nodes; }; class DummyGraphNodeTaskItf { public: virtual ~DummyGraphNodeTaskItf() = default; - virtual void execute() = 0; + virtual void execute() = 0; }; template @@ -71,10 +71,10 @@ class DummyGraphNodeTaskImpl final : public DummyGraphNodeTaskItf { public: explicit DummyGraphNodeTaskImpl(Fn &&t) noexcept; DummyGraphNodeTaskImpl(const DummyGraphNodeTaskImpl &) = delete; - DummyGraphNodeTaskImpl(DummyGraphNodeTaskImpl &&) = delete; + DummyGraphNodeTaskImpl(DummyGraphNodeTaskImpl &&) = delete; DummyGraphNodeTaskImpl &operator=(const DummyGraphNodeTaskImpl &) = delete; DummyGraphNodeTaskImpl &operator=(DummyGraphNodeTaskImpl &&) = delete; - ~DummyGraphNodeTaskImpl() override = default; + ~DummyGraphNodeTaskImpl() override = default; inline void execute() override { _task(); } private: @@ -83,28 +83,28 @@ private: class DummyGraphNode final { public: - DummyGraphNode() = default; + DummyGraphNode() = default; DummyGraphNode(const DummyGraphNode &) = delete; - DummyGraphNode(DummyGraphNode &&) = delete; + DummyGraphNode(DummyGraphNode &&) = delete; DummyGraphNode &operator=(const DummyGraphNode &) = delete; DummyGraphNode &operator=(DummyGraphNode &&) = delete; ~DummyGraphNode(); private: - static void allocChunk(); + static void allocChunk(); static DummyGraphNode *alloc(); - static void free(DummyGraphNode *n); - static void freeAll(); + static void free(DummyGraphNode *n); + static void freeAll(); void succeed(DummyGraphNode *other); void precede(DummyGraphNode *other); void reset(); - DummyGraphNodeTaskItf * _callback{nullptr}; + DummyGraphNodeTaskItf *_callback{nullptr}; ccstd::unordered_set _successors{}; ccstd::unordered_set _predecessors{}; - DummyGraphNode * _next{nullptr}; - int _generation{0}; + DummyGraphNode *_next{nullptr}; + int _generation{0}; friend class DummyGraph; }; @@ -114,8 +114,8 @@ DummyGraphNodeTaskImpl::DummyGraphNodeTaskImpl(Fn &&t) noexcept : _task(t) { template size_t DummyGraph::addNode(Fn &&fn) { DummyGraphNode *n = DummyGraphNode::alloc(); - n->_callback = ccnew DummyGraphNodeTaskImpl(std::forward(fn)); - n->_generation = _generation; + n->_callback = ccnew DummyGraphNodeTaskImpl(std::forward(fn)); + n->_generation = _generation; _nodes.emplace_back(n); return _nodes.size() - 1; } @@ -126,10 +126,10 @@ class DummyJobGraph final { public: explicit DummyJobGraph(DummyJobSystem * /*system*/) noexcept {} DummyJobGraph(const DummyJobGraph &) = delete; - DummyJobGraph(DummyJobGraph &&) = delete; + DummyJobGraph(DummyJobGraph &&) = delete; DummyJobGraph &operator=(const DummyJobGraph &) = delete; DummyJobGraph &operator=(DummyJobGraph &&) = delete; - ~DummyJobGraph() noexcept = default; + ~DummyJobGraph() noexcept = default; template uint createJob(Function &&func) noexcept; diff --git a/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.cpp b/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.cpp index 8b336226a0..ec167e736e 100644 --- a/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.cpp +++ b/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.cpp @@ -34,7 +34,7 @@ void TFJobGraph::makeEdge(uint j1, uint j2) noexcept { void TFJobGraph::run() noexcept { if (_pending) return; - _future = _executor->run(_flow); + _future = _executor->run(_flow); _pending = true; } diff --git a/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.h b/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.h index 61e6e57644..68568ab793 100644 --- a/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.h +++ b/native/cocos/base/job-system/job-system-taskflow/TFJobGraph.h @@ -57,11 +57,11 @@ public: private: tf::Executor *_executor = nullptr; - tf::Taskflow _flow; + tf::Taskflow _flow; ccstd::deque _tasks; // existing tasks cannot be invalidated std::future _future; - bool _pending = false; + bool _pending = false; }; template diff --git a/native/cocos/base/job-system/job-system-tbb/TBBJobGraph.h b/native/cocos/base/job-system/job-system-tbb/TBBJobGraph.h index 34fe998007..6fa9a0850e 100644 --- a/native/cocos/base/job-system/job-system-tbb/TBBJobGraph.h +++ b/native/cocos/base/job-system/job-system-tbb/TBBJobGraph.h @@ -70,7 +70,7 @@ private: struct TBBParallelJob { uint predecessor = 0u; - uint successor = 0u; + uint successor = 0u; }; ccstd::vector _parallelJobs; @@ -87,14 +87,14 @@ uint TBBJobGraph::createJob(Function &&func) noexcept { template uint TBBJobGraph::createForEachIndexJob(uint begin, uint end, uint step, Function &&func) noexcept { _nodes.emplace_back(_graph, [](TBBJobToken t) {}); - uint predecessorIdx = static_cast(_nodes.size() - 1u); - TBBJobNode &predecessor = _nodes.back(); + uint predecessorIdx = static_cast(_nodes.size() - 1u); + TBBJobNode &predecessor = _nodes.back(); tbb::flow::make_edge(_nodes.front(), predecessor); _nodes.emplace_back(_graph, [](TBBJobToken t) {}); - uint successorIdx = static_cast(_nodes.size() - 1u); - TBBJobNode &successor = _nodes.back(); + uint successorIdx = static_cast(_nodes.size() - 1u); + TBBJobNode &successor = _nodes.back(); for (uint i = begin; i < end; i += step) { _nodes.emplace_back(_graph, [i, &func](TBBJobToken t) { func(i); }); diff --git a/native/cocos/base/job-system/job-system-tbb/TBBJobSystem.h b/native/cocos/base/job-system/job-system-tbb/TBBJobSystem.h index 6a8803dd2e..4839e4b70a 100644 --- a/native/cocos/base/job-system/job-system-tbb/TBBJobSystem.h +++ b/native/cocos/base/job-system/job-system-tbb/TBBJobSystem.h @@ -57,7 +57,7 @@ private: static TBBJobSystem *_instance; tbb::global_control _control; - uint _threadCount = 0u; + uint _threadCount = 0u; }; } // namespace cc diff --git a/native/cocos/base/memory/CallStack.cpp b/native/cocos/base/memory/CallStack.cpp index 918026b5b7..9846c86cb8 100644 --- a/native/cocos/base/memory/CallStack.cpp +++ b/native/cocos/base/memory/CallStack.cpp @@ -77,14 +77,14 @@ ccstd::string StackFrame::toString() { struct ThreadStack { void *stack[MAX_STACK_FRAMES]; - int current; - int overflow; + int current; + int overflow; }; extern "C" { -static pthread_once_t s_once = PTHREAD_ONCE_INIT; -static pthread_key_t s_threadStackKey = 0; +static pthread_once_t s_once = PTHREAD_ONCE_INIT; +static pthread_key_t s_threadStackKey = 0; static void __attribute__((no_instrument_function)) init_once(void) { @@ -98,8 +98,8 @@ getThreadStack() { return ptr; } - ptr = (ThreadStack *)calloc(1, sizeof(ThreadStack)); - ptr->current = 0; + ptr = (ThreadStack *)calloc(1, sizeof(ThreadStack)); + ptr->current = 0; ptr->overflow = 0; pthread_setspecific(s_threadStackKey, ptr); return ptr; @@ -111,7 +111,7 @@ __cyg_profile_func_enter(void *this_fn, void *call_site) { ThreadStack *ptr = getThreadStack(); if (ptr->current < MAX_STACK_FRAMES) { ptr->stack[ptr->current++] = this_fn; - ptr->overflow = 0; + ptr->overflow = 0; } else { ptr->overflow++; } @@ -162,7 +162,7 @@ ccstd::vector CallStack::backtrace() { callstack.reserve(MAX_STACK_FRAMES); void *array[MAX_STACK_FRAMES]; - int count = ::backtrace(array, MAX_STACK_FRAMES); + int count = ::backtrace(array, MAX_STACK_FRAMES); for (auto i = 0; i < count; i++) { callstack.push_back(array[i]); } @@ -173,7 +173,7 @@ ccstd::vector CallStack::backtrace() { callstack.reserve(MAX_STACK_FRAMES); void *array[MAX_STACK_FRAMES]; - int count = CaptureStackBackTrace(0, MAX_STACK_FRAMES, array, NULL); + int count = CaptureStackBackTrace(0, MAX_STACK_FRAMES, array, NULL); for (auto i = 0; i < count; i++) { callstack.push_back(array[i]); } @@ -187,9 +187,9 @@ ccstd::vector CallStack::backtrace() { ccstd::vector CallStack::backtraceSymbols(const ccstd::vector &callstack) { #if CC_PLATFORM == CC_PLATFORM_ANDROID ccstd::vector frames; - size_t size = callstack.size(); + size_t size = callstack.size(); for (size_t i = 0; i < size; i++) { - Dl_info info; + Dl_info info; StackFrame frame; if (dladdr(callstack[i], &info)) { if (info.dli_fname && strlen(info.dli_fname) > 0) { @@ -218,7 +218,7 @@ ccstd::vector CallStack::backtraceSymbols(const ccstd::vector frames; - char ** strs = ::backtrace_symbols(&callstack[0], size); + char **strs = ::backtrace_symbols(&callstack[0], size); for (size_t i = 0; i < size; i++) { StackFrame frame; frame.file = strs[i]; @@ -239,9 +239,9 @@ ccstd::vector CallStack::backtraceSymbols(const ccstd::vector(callstack[i]); + PTR_DWORD address = reinterpret_cast(callstack[i]); - char moduelName[MAX_PATH]; + char moduelName[MAX_PATH]; #if _WIN64 PTR_DWORD moduleBase = SymGetModuleBase64(_process, address); #else @@ -251,11 +251,11 @@ ccstd::vector CallStack::backtraceSymbols(const ccstd::vectorSizeOfStruct = sizeof(SYMBOL_INFO); - symbol->MaxNameLen = MAX_SYMBOL_LENGTH - 1; + DWORD64 offset = 0; + char symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_LENGTH] = {0}; + PSYMBOL_INFO symbol = (PSYMBOL_INFO)symbolBuffer; + symbol->SizeOfStruct = sizeof(SYMBOL_INFO); + symbol->MaxNameLen = MAX_SYMBOL_LENGTH - 1; if (SymFromAddr(_process, address, &offset, symbol)) { frame.function = symbol->Name; @@ -263,7 +263,7 @@ ccstd::vector CallStack::backtraceSymbols(const ccstd::vector backtrace(); + static ccstd::vector backtrace(); static ccstd::vector backtraceSymbols(const ccstd::vector &callstack); #if CC_PLATFORM == CC_PLATFORM_WINDOWS diff --git a/native/cocos/base/memory/Memory.h b/native/cocos/base/memory/Memory.h index 8fb815bf8b..bd1799b051 100644 --- a/native/cocos/base/memory/Memory.h +++ b/native/cocos/base/memory/Memory.h @@ -64,8 +64,8 @@ public: }; } // namespace cc -#define ccnew new (std::nothrow) -#define ccnew_placement(...) new (__VA_ARGS__) +#define ccnew new (std::nothrow) +#define ccnew_placement(...) new (__VA_ARGS__) #define CC_SAFE_DELETE(ptr) \ if (ptr) { \ diff --git a/native/cocos/base/memory/MemoryHook.cpp b/native/cocos/base/memory/MemoryHook.cpp index 0aa280b237..d2c589cca1 100644 --- a/native/cocos/base/memory/MemoryHook.cpp +++ b/native/cocos/base/memory/MemoryHook.cpp @@ -33,13 +33,13 @@ #define __GNU_SOURCE #include -static NewHookType g_new_hooker = nullptr; +static NewHookType g_new_hooker = nullptr; static DeleteHookType g_delete_hooker = nullptr; extern "C" { void *malloc(size_t size) __attribute__((weak)); -void free(void *ptr) __attribute__((weak)); +void free(void *ptr) __attribute__((weak)); // Use strong symbol to overwrite the weak one. void *malloc(size_t size) { @@ -70,17 +70,17 @@ void free(void *ptr) { } #elif CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_MAC_OSX -typedef void malloc_logger_t(uint32_t aType, +typedef void malloc_logger_t(uint32_t aType, uintptr_t aArg1, uintptr_t aArg2, uintptr_t aArg3, uintptr_t aResult, uint32_t aNumHotFramesToSkip); extern malloc_logger_t *malloc_logger; static malloc_logger_t *g_system_malloc_logger = nullptr; -static NewHookType g_new_hooker = nullptr; -static DeleteHookType g_delete_hooker = nullptr; +static NewHookType g_new_hooker = nullptr; +static DeleteHookType g_delete_hooker = nullptr; static void -cc_malloc_logger(uint32_t aType, +cc_malloc_logger(uint32_t aType, uintptr_t aArg1, uintptr_t aArg2, uintptr_t aArg3, uintptr_t aResult, uint32_t aNumHotFramesToSkip) { if (aResult != 0) { @@ -99,8 +99,8 @@ cc_malloc_logger(uint32_t aType, } else { // malloc/calloc/valloc if (CC_PREDICT_TRUE(g_new_hooker != nullptr)) { - const void *ptr = reinterpret_cast(aResult); - size_t size = reinterpret_cast(aArg2); + const void *ptr = reinterpret_cast(aResult); + size_t size = reinterpret_cast(aArg2); g_new_hooker(ptr, size); } } @@ -160,8 +160,8 @@ void MemoryHook::addRecord(uint64_t address, size_t size) { // {} is necessary here to make variables being destroyed before _hooking = false { MemoryRecord record; - record.address = address; - record.size = size; + record.address = address; + record.size = size; record.callstack = CallStack::backtrace(); _records.insert({address, record}); _totalSize += size; @@ -243,12 +243,12 @@ void MemoryHook::dumpMemoryLeak() { log(stream.str()); } - uint32_t i = 0; - size_t skipSize = 0; + uint32_t i = 0; + size_t skipSize = 0; uint32_t skipCount = 0; for (const auto &iter : _records) { - bool skip = false; + bool skip = false; auto frames = CallStack::backtraceSymbols(iter.second.callstack); for (auto &frame : frames) { if (isIgnored(frame)) { @@ -264,7 +264,7 @@ void MemoryHook::dumpMemoryLeak() { } std::stringstream stream; - int k = 0; + int k = 0; stream << std::endl; stream << "<" << ++i << ">:" @@ -305,14 +305,14 @@ void MemoryHook::log(const ccstd::string &msg) { void MemoryHook::registerAll() { #if CC_PLATFORM == CC_PLATFORM_ANDROID - g_new_hooker = newHook; + g_new_hooker = newHook; g_delete_hooker = deleteHook; free(malloc(1)); // force to init system_malloc/system_free #elif CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_MAC_OSX g_system_malloc_logger = malloc_logger; - malloc_logger = cc_malloc_logger; - g_new_hooker = newHook; - g_delete_hooker = deleteHook; + malloc_logger = cc_malloc_logger; + g_new_hooker = newHook; + g_delete_hooker = deleteHook; #elif CC_PLATFORM == CC_PLATFORM_WINDOWS MallocHook_AddNewHook(&newHook); MallocHook_AddDeleteHook(&deleteHook); @@ -321,12 +321,12 @@ void MemoryHook::registerAll() { void MemoryHook::unRegisterAll() { #if CC_PLATFORM == CC_PLATFORM_ANDROID - g_new_hooker = nullptr; + g_new_hooker = nullptr; g_delete_hooker = nullptr; #elif CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_MAC_OSX - malloc_logger = g_system_malloc_logger; - g_new_hooker = nullptr; - g_delete_hooker = nullptr; + malloc_logger = g_system_malloc_logger; + g_new_hooker = nullptr; + g_delete_hooker = nullptr; #elif CC_PLATFORM == CC_PLATFORM_WINDOWS MallocHook_RemoveNewHook(&newHook); MallocHook_RemoveDeleteHook(&deleteHook); diff --git a/native/cocos/base/memory/MemoryHook.h b/native/cocos/base/memory/MemoryHook.h index 4b1f715b47..8cd36d655c 100644 --- a/native/cocos/base/memory/MemoryHook.h +++ b/native/cocos/base/memory/MemoryHook.h @@ -43,8 +43,8 @@ typedef void (*DeleteHookType)(const void *ptr); namespace cc { struct CC_DLL MemoryRecord { - uint64_t address{0}; - size_t size{0}; + uint64_t address{0}; + size_t size{0}; ccstd::vector callstack; }; @@ -58,8 +58,8 @@ public: */ using RecordMap = ccstd::unordered_map; - void addRecord(uint64_t address, size_t size); - void removeRecord(uint64_t address); + void addRecord(uint64_t address, size_t size); + void removeRecord(uint64_t address); inline size_t getTotalSize() const { return _totalSize; } private: @@ -82,9 +82,9 @@ private: private: std::recursive_mutex _mutex; - bool _hooking{false}; - RecordMap _records; - size_t _totalSize{0U}; + bool _hooking{false}; + RecordMap _records; + size_t _totalSize{0U}; }; extern MemoryHook GMemoryHook; diff --git a/native/cocos/base/std/container/unordered_set.h b/native/cocos/base/std/container/unordered_set.h index 0c087b35e9..bc076c94ad 100644 --- a/native/cocos/base/std/container/unordered_set.h +++ b/native/cocos/base/std/container/unordered_set.h @@ -9,7 +9,7 @@ using std::unordered_set; namespace pmr { template < class Key, - class Hash = std::hash, + class Hash = std::hash, class KeyEqual = std::equal_to> using unordered_set = std::unordered_set>; } diff --git a/native/cocos/base/threading/AutoReleasePool.cpp b/native/cocos/base/threading/AutoReleasePool.cpp index 051a6de7de..baac3cd69a 100644 --- a/native/cocos/base/threading/AutoReleasePool.cpp +++ b/native/cocos/base/threading/AutoReleasePool.cpp @@ -27,7 +27,7 @@ namespace cc { -AutoReleasePool::AutoReleasePool() = default; +AutoReleasePool::AutoReleasePool() = default; AutoReleasePool::~AutoReleasePool() = default; void AutoReleasePool::drain() { diff --git a/native/cocos/base/threading/AutoReleasePool.h b/native/cocos/base/threading/AutoReleasePool.h index 383bc603d9..ed104dbe6a 100644 --- a/native/cocos/base/threading/AutoReleasePool.h +++ b/native/cocos/base/threading/AutoReleasePool.h @@ -31,7 +31,7 @@ class AutoReleasePool final { public: AutoReleasePool(); AutoReleasePool(const AutoReleasePool &) = delete; - AutoReleasePool(AutoReleasePool &&) = delete; + AutoReleasePool(AutoReleasePool &&) = delete; ~AutoReleasePool(); AutoReleasePool &operator=(const AutoReleasePool &) = delete; AutoReleasePool &operator=(AutoReleasePool &&) = delete; diff --git a/native/cocos/base/threading/ConditionVariable.h b/native/cocos/base/threading/ConditionVariable.h index e1cbbcc9c3..d2256b6839 100644 --- a/native/cocos/base/threading/ConditionVariable.h +++ b/native/cocos/base/threading/ConditionVariable.h @@ -36,18 +36,18 @@ class ConditionVariable final { public: void wait() noexcept; template - void wait(Function &&func, Args &&...args) noexcept; + void wait(Function &&func, Args &&... args) noexcept; void signal() noexcept; void signalAll() noexcept; private: - std::mutex _mutex; + std::mutex _mutex; std::condition_variable _condVar; }; // DO NOT MANIPULATE ANY SYCHRONIZATION PRIMITIVES INSIDE THE CALLBACK template -void ConditionVariable::wait(Function &&func, Args &&...args) noexcept { +void ConditionVariable::wait(Function &&func, Args &&... args) noexcept { std::unique_lock lock(_mutex); _condVar.wait(lock, std::bind(std::forward(func), std::forward(args)...)); } diff --git a/native/cocos/base/threading/Event.h b/native/cocos/base/threading/Event.h index 0f41c935cc..4b0d829387 100644 --- a/native/cocos/base/threading/Event.h +++ b/native/cocos/base/threading/Event.h @@ -41,7 +41,7 @@ private: T _syncObject{}; }; -using EventCV = Event; +using EventCV = Event; using EventSem = Event; } // namespace cc diff --git a/native/cocos/base/threading/MessageQueue.cpp b/native/cocos/base/threading/MessageQueue.cpp index b083235376..0363a97dc9 100644 --- a/native/cocos/base/threading/MessageQueue.cpp +++ b/native/cocos/base/threading/MessageQueue.cpp @@ -30,7 +30,7 @@ namespace cc { namespace { -uint32_t constexpr MEMORY_CHUNK_POOL_CAPACITY = 64; +uint32_t constexpr MEMORY_CHUNK_POOL_CAPACITY = 64; uint32_t constexpr SWITCH_CHUNK_MEMORY_REQUIREMENT = sizeof(MemoryChunkSwitchMessage) + utils::ALIGN_TO; } // namespace @@ -105,7 +105,7 @@ void MessageQueue::kick() noexcept { } void MessageQueue::kickAndWait() noexcept { - EventSem event; + EventSem event; EventSem *const pEvent = &event; ENQUEUE_MESSAGE_1(this, WaitUntilFinish, @@ -122,7 +122,7 @@ void MessageQueue::runConsumerThread() noexcept { if (_immediateMode || _workerAttached) return; _reader.terminateConsumerThread = false; - _reader.flushingFinished = false; + _reader.flushingFinished = false; std::thread consumerThread(&MessageQueue::consumerThreadLoop, this); consumerThread.detach(); @@ -132,12 +132,12 @@ void MessageQueue::runConsumerThread() noexcept { void MessageQueue::terminateConsumerThread() noexcept { if (_immediateMode || !_workerAttached) return; - EventSem event; + EventSem event; EventSem *const pEvent = &event; ReaderContext *const pR = &_reader; - ccnew_placement (allocate(1)) TerminateConsumerThreadMessage(pEvent, pR); + ccnew_placement(allocate(1)) TerminateConsumerThreadMessage(pEvent, pR); kick(); event.wait(); @@ -175,20 +175,20 @@ uint8_t *MessageQueue::allocateImpl(uint32_t allocatedSize, uint32_t const reque // newOffset contains the DummyMessage if (newOffset + sizeof(MemoryChunkSwitchMessage) <= MEMORY_CHUNK_SIZE) { uint8_t *const allocatedMemory = _writer.currentMemoryChunk + _writer.offset; - _writer.offset = newOffset; + _writer.offset = newOffset; return allocatedMemory; } - uint8_t *const newChunk = MessageQueue::MemoryAllocator::getInstance().request(); - auto *const switchMessage = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); - ccnew_placement (switchMessage) MemoryChunkSwitchMessage(this, newChunk, _writer.currentMemoryChunk); + uint8_t *const newChunk = MessageQueue::MemoryAllocator::getInstance().request(); + auto *const switchMessage = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); + ccnew_placement(switchMessage) MemoryChunkSwitchMessage(this, newChunk, _writer.currentMemoryChunk); switchMessage->_next = reinterpret_cast(newChunk); // point to start position - _writer.lastMessage = switchMessage; + _writer.lastMessage = switchMessage; ++_writer.pendingMessageCount; _writer.currentMemoryChunk = newChunk; - _writer.offset = 0; + _writer.offset = 0; DummyMessage *const head = allocate(1); - ccnew_placement (head) DummyMessage; + ccnew_placement(head) DummyMessage; if (_immediateMode) { pushMessages(); @@ -241,7 +241,7 @@ Message *MessageQueue::readMessage() noexcept { } } - Message *const msg = _reader.lastMessage->getNext(); + Message *const msg = _reader.lastMessage->getNext(); _reader.lastMessage = msg; --_reader.newMessageCount; CC_ASSERT(msg); @@ -287,7 +287,7 @@ TerminateConsumerThreadMessage::TerminateConsumerThreadMessage(EventSem *const p void TerminateConsumerThreadMessage::execute() noexcept { _reader->terminateConsumerThread = true; - _reader->flushingFinished = true; + _reader->flushingFinished = true; _event->signal(); } diff --git a/native/cocos/base/threading/MessageQueue.h b/native/cocos/base/threading/MessageQueue.h index 38e3bca993..5606c5c45e 100644 --- a/native/cocos/base/threading/MessageQueue.h +++ b/native/cocos/base/threading/MessageQueue.h @@ -49,16 +49,16 @@ inline uint32_t constexpr align(uint32_t const val, uint32_t const alignment) no class Message { public: - Message() = default; - virtual ~Message() = default; + Message() = default; + virtual ~Message() = default; Message(Message const &) = delete; - Message(Message &&) = delete; + Message(Message &&) = delete; Message &operator=(Message const &) = delete; Message &operator=(Message &&) = delete; - virtual void execute() = 0; + virtual void execute() = 0; virtual char const *getName() const noexcept = 0; - inline Message * getNext() const noexcept { return _next; } + inline Message *getNext() const noexcept { return _next; } private: Message *_next; // explicitly assigned beforehand, don't init the member here @@ -72,10 +72,10 @@ private: #endif struct ALIGNAS(64) WriterContext final { - uint8_t * currentMemoryChunk{nullptr}; - Message * lastMessage{nullptr}; - uint32_t offset{0}; - uint32_t pendingMessageCount{0}; + uint8_t *currentMemoryChunk{nullptr}; + Message *lastMessage{nullptr}; + uint32_t offset{0}; + uint32_t pendingMessageCount{0}; std::atomic writtenMessageCount{0}; }; @@ -85,8 +85,8 @@ struct ALIGNAS(64) ReaderContext final { uint32_t offset{0}; uint32_t writtenMessageCountSnap{0}; uint32_t newMessageCount{0}; - bool terminateConsumerThread{false}; - bool flushingFinished{false}; + bool terminateConsumerThread{false}; + bool flushingFinished{false}; }; // A single-producer single-consumer circular buffer queue. @@ -96,9 +96,9 @@ public: static constexpr uint32_t MEMORY_CHUNK_SIZE = 4096 * 16; MessageQueue(); - ~MessageQueue() = default; + ~MessageQueue() = default; MessageQueue(MessageQueue const &) = delete; - MessageQueue(MessageQueue &&) = delete; + MessageQueue(MessageQueue &&) = delete; MessageQueue &operator=(MessageQueue const &) = delete; MessageQueue &operator=(MessageQueue &&) = delete; @@ -129,7 +129,7 @@ public: inline bool isImmediateMode() const noexcept { return _immediateMode; } - void recycleMemoryChunk(uint8_t *chunk) const noexcept; + void recycleMemoryChunk(uint8_t *chunk) const noexcept; static void freeChunksInFreeQueue(MessageQueue *mainMessageQueue) noexcept; inline void setImmediateMode(bool immediateMode) noexcept { _immediateMode = immediateMode; } @@ -137,25 +137,25 @@ public: private: class ALIGNAS(64) MemoryAllocator final { public: - MemoryAllocator() = default; - ~MemoryAllocator() = default; + MemoryAllocator() = default; + ~MemoryAllocator() = default; MemoryAllocator(MemoryAllocator const &) = delete; - MemoryAllocator(MemoryAllocator &&) = delete; + MemoryAllocator(MemoryAllocator &&) = delete; MemoryAllocator &operator=(MemoryAllocator const &) = delete; MemoryAllocator &operator=(MemoryAllocator &&) = delete; static MemoryAllocator &getInstance() noexcept; - uint8_t * request() noexcept; - void recycle(uint8_t *chunk, bool freeByUser) noexcept; - void freeByUser(MessageQueue *mainMessageQueue) noexcept; + uint8_t *request() noexcept; + void recycle(uint8_t *chunk, bool freeByUser) noexcept; + void freeByUser(MessageQueue *mainMessageQueue) noexcept; private: using ChunkQueue = moodycamel::ConcurrentQueue; - void free(uint8_t *chunk) noexcept; + void free(uint8_t *chunk) noexcept; std::atomic _chunkCount{0}; - ChunkQueue _chunkPool{}; - ChunkQueue _chunkFreeQueue{}; + ChunkQueue _chunkPool{}; + ChunkQueue _chunkFreeQueue{}; }; // structs may be padded @@ -164,28 +164,28 @@ private: #endif uint8_t *allocateImpl(uint32_t allocatedSize, uint32_t requestSize) noexcept; - void pushMessages() noexcept; + void pushMessages() noexcept; // consumer thread specifics - void pullMessages() noexcept; - void executeMessages() noexcept; - Message * readMessage() noexcept; + void pullMessages() noexcept; + void executeMessages() noexcept; + Message *readMessage() noexcept; inline bool hasNewMessage() const noexcept { return _reader.newMessageCount > 0 && !_reader.flushingFinished; } - void consumerThreadLoop() noexcept; + void consumerThreadLoop() noexcept; WriterContext _writer; ReaderContext _reader; - EventCV _event; - bool _immediateMode{true}; - bool _workerAttached{false}; - bool _freeChunksByUser{true}; // recycled chunks will be stashed until explicit free instruction + EventCV _event; + bool _immediateMode{true}; + bool _workerAttached{false}; + bool _freeChunksByUser{true}; // recycled chunks will be stashed until explicit free instruction friend class MemoryChunkSwitchMessage; }; class DummyMessage final : public Message { public: - void execute() noexcept override {} + void execute() noexcept override {} char const *getName() const noexcept override; }; @@ -194,24 +194,24 @@ public: MemoryChunkSwitchMessage(MessageQueue *queue, uint8_t *newChunk, uint8_t *oldChunk) noexcept; ~MemoryChunkSwitchMessage() override; - void execute() noexcept override; + void execute() noexcept override; char const *getName() const noexcept override; private: MessageQueue *_messageQueue{nullptr}; - uint8_t * _newChunk{nullptr}; - uint8_t * _oldChunk{nullptr}; + uint8_t *_newChunk{nullptr}; + uint8_t *_oldChunk{nullptr}; }; class TerminateConsumerThreadMessage final : public Message { public: TerminateConsumerThreadMessage(EventSem *pEvent, ReaderContext *pR) noexcept; - void execute() noexcept override; + void execute() noexcept override; char const *getName() const noexcept override; private: - EventSem * _event{nullptr}; + EventSem *_event{nullptr}; ReaderContext *_reader{nullptr}; }; @@ -219,8 +219,8 @@ template std::enable_if_t::value, T *> MessageQueue::allocate(uint32_t const /*count*/) noexcept { uint32_t allocatedSize = 0; - T *const msg = reinterpret_cast(allocateImpl(allocatedSize, sizeof(T))); - msg->_next = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); + T *const msg = reinterpret_cast(allocateImpl(allocatedSize, sizeof(T))); + msg->_next = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); ++_writer.pendingMessageCount; _writer.lastMessage = msg; return msg; @@ -231,9 +231,9 @@ std::enable_if_t::value, T *> MessageQueue::allocate(uint32_t const count) noexcept { uint32_t const requestSize = sizeof(T) * count; CC_ASSERT(requestSize); - uint32_t allocatedSize = 0; + uint32_t allocatedSize = 0; uint8_t *const allocatedMemory = allocateImpl(allocatedSize, requestSize); - _writer.lastMessage->_next = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); + _writer.lastMessage->_next = reinterpret_cast(_writer.currentMemoryChunk + _writer.offset); return reinterpret_cast(allocatedMemory); } diff --git a/native/cocos/base/threading/ReadWriteLock.h b/native/cocos/base/threading/ReadWriteLock.h index 6bc58d9120..4569d21a15 100644 --- a/native/cocos/base/threading/ReadWriteLock.h +++ b/native/cocos/base/threading/ReadWriteLock.h @@ -44,10 +44,10 @@ public: } template - auto lockRead(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)); + auto lockRead(Function &&func, Args &&... args) noexcept -> decltype(func(std::forward(args)...)); template - auto lockWrite(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)); + auto lockWrite(Function &&func, Args &&... args) noexcept -> decltype(func(std::forward(args)...)); private: uv_rwlock_t _lock; @@ -62,7 +62,7 @@ private: }; template -auto ReadWriteLock::lockRead(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)) { +auto ReadWriteLock::lockRead(Function &&func, Args &&... args) noexcept -> decltype(func(std::forward(args)...)) { uv_rwlock_rdlock(&_lock); auto defer = Defer([&]() { uv_rwlock_rdunlock(&_lock); @@ -71,7 +71,7 @@ auto ReadWriteLock::lockRead(Function &&func, Args &&...args) noexcept -> declty } template -auto ReadWriteLock::lockWrite(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)) { +auto ReadWriteLock::lockWrite(Function &&func, Args &&... args) noexcept -> decltype(func(std::forward(args)...)) { uv_rwlock_wrlock(&_lock); auto defer = Defer([&]() { uv_rwlock_wrunlock(&_lock); diff --git a/native/cocos/base/threading/ThreadPool.cpp b/native/cocos/base/threading/ThreadPool.cpp index 08f789bc9f..5d6b1428ac 100644 --- a/native/cocos/base/threading/ThreadPool.cpp +++ b/native/cocos/base/threading/ThreadPool.cpp @@ -27,7 +27,7 @@ namespace cc { -uint8_t const ThreadPool::CPU_CORE_COUNT = std::thread::hardware_concurrency(); +uint8_t const ThreadPool::CPU_CORE_COUNT = std::thread::hardware_concurrency(); uint8_t const ThreadPool::MAX_THREAD_COUNT = CPU_CORE_COUNT - 1; void ThreadPool::start() { diff --git a/native/cocos/base/threading/ThreadPool.h b/native/cocos/base/threading/ThreadPool.h index d24606eb27..10f650a274 100644 --- a/native/cocos/base/threading/ThreadPool.h +++ b/native/cocos/base/threading/ThreadPool.h @@ -39,21 +39,21 @@ namespace cc { class ThreadPool final { public: - using Task = std::function; + using Task = std::function; using TaskQueue = moodycamel::ConcurrentQueue; static uint8_t const CPU_CORE_COUNT; static uint8_t const MAX_THREAD_COUNT; - ThreadPool() = default; - ~ThreadPool() = default; - ThreadPool(ThreadPool const &) = delete; + ThreadPool() = default; + ~ThreadPool() = default; + ThreadPool(ThreadPool const &) = delete; ThreadPool(ThreadPool &&) noexcept = delete; ThreadPool &operator=(ThreadPool const &) = delete; ThreadPool &operator=(ThreadPool &&) noexcept = delete; template - auto dispatchTask(Function &&func, Args &&...args) -> std::future(args)...))>; + auto dispatchTask(Function &&func, Args &&... args) -> std::future(args)...))>; void start(); void stop(); @@ -62,19 +62,19 @@ private: void addThread(); - TaskQueue _tasks{}; + TaskQueue _tasks{}; ccstd::list _workers{}; - Event _event{}; - std::atomic _running{false}; - uint8_t _workerCount{MAX_THREAD_COUNT}; + Event _event{}; + std::atomic _running{false}; + uint8_t _workerCount{MAX_THREAD_COUNT}; }; template -auto ThreadPool::dispatchTask(Function &&func, Args &&...args) -> std::future(args)...))> { +auto ThreadPool::dispatchTask(Function &&func, Args &&... args) -> std::future(args)...))> { CC_ASSERT(_running); - using ReturnType = decltype(func(std::forward(args)...)); - auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...)); + using ReturnType = decltype(func(std::forward(args)...)); + auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...)); bool const succeed = _tasks.enqueue([task]() { (*task)(); }); diff --git a/native/cocos/base/threading/ThreadSafeCounter.h b/native/cocos/base/threading/ThreadSafeCounter.h index 4179882f35..86edff7fe2 100644 --- a/native/cocos/base/threading/ThreadSafeCounter.h +++ b/native/cocos/base/threading/ThreadSafeCounter.h @@ -33,12 +33,12 @@ namespace cc { template ::value>> class ThreadSafeCounter final { public: - inline T increment() noexcept { return add(1); } - inline T add(T const v) noexcept { return _counter.fetch_add(v, std::memory_order_relaxed); } - inline T decrement() noexcept { return subtract(1); } - inline T subtract(T const v) noexcept { return _counter.fetch_sub(v, std::memory_order_relaxed); } + inline T increment() noexcept { return add(1); } + inline T add(T const v) noexcept { return _counter.fetch_add(v, std::memory_order_relaxed); } + inline T decrement() noexcept { return subtract(1); } + inline T subtract(T const v) noexcept { return _counter.fetch_sub(v, std::memory_order_relaxed); } inline void set(T const v) noexcept { _counter.store(v, std::memory_order_relaxed); } - inline T get() const noexcept { return _counter.load(std::memory_order_relaxed); } + inline T get() const noexcept { return _counter.load(std::memory_order_relaxed); } inline void reset() noexcept { set(0); } private: diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp index 60a1b95b63..00f2167ab0 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp @@ -52,14 +52,14 @@ void *ThreadSafeLinearAllocator::doAllocate(size_t size, size_t alignment) noexc return nullptr; } - void * allocatedMemory = nullptr; - size_t oldUsedSize = 0; - uint64_t newUsedSize = 0; // force 64-bit here to correctly detect overflows + void *allocatedMemory = nullptr; + size_t oldUsedSize = 0; + uint64_t newUsedSize = 0; // force 64-bit here to correctly detect overflows do { - oldUsedSize = getUsedSize(); + oldUsedSize = getUsedSize(); allocatedMemory = acl::align_to(acl::add_offset_to_ptr(_buffer, oldUsedSize), alignment); - newUsedSize = reinterpret_cast(allocatedMemory) - reinterpret_cast(_buffer) + size; + newUsedSize = reinterpret_cast(allocatedMemory) - reinterpret_cast(_buffer) + size; if (newUsedSize > _capacity) { return nullptr; // overflows diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.h b/native/cocos/base/threading/ThreadSafeLinearAllocator.h index 9eae396be1..5f6f3638dd 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.h +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.h @@ -42,7 +42,7 @@ public: explicit ThreadSafeLinearAllocator(size_t size, size_t alignment = 1) noexcept; ~ThreadSafeLinearAllocator(); ThreadSafeLinearAllocator(ThreadSafeLinearAllocator const &) = delete; - ThreadSafeLinearAllocator(ThreadSafeLinearAllocator &&) = delete; + ThreadSafeLinearAllocator(ThreadSafeLinearAllocator &&) = delete; ThreadSafeLinearAllocator &operator=(ThreadSafeLinearAllocator const &) = delete; ThreadSafeLinearAllocator &operator=(ThreadSafeLinearAllocator &&) = delete; @@ -55,7 +55,7 @@ public: return reinterpret_cast(doAllocate(size, alignment)) - reinterpret_cast(_buffer); } - inline void * getBuffer() const noexcept { return _buffer; } + inline void *getBuffer() const noexcept { return _buffer; } inline size_t getCapacity() const noexcept { return _capacity; } inline size_t getUsedSize() const noexcept { return _usedSize.load(std::memory_order_relaxed); } inline size_t getBalance() const noexcept { return getCapacity() - getUsedSize(); } @@ -65,9 +65,9 @@ public: private: void *doAllocate(size_t size, size_t alignment) noexcept; - void * _buffer{nullptr}; - size_t _capacity{0}; - size_t _alignment{1}; + void *_buffer{nullptr}; + size_t _capacity{0}; + size_t _alignment{1}; std::atomic _usedSize{0}; }; diff --git a/native/cocos/bindings/dop/BufferAllocator.cpp b/native/cocos/bindings/dop/BufferAllocator.cpp index 7d04655991..d664fe1939 100644 --- a/native/cocos/bindings/dop/BufferAllocator.cpp +++ b/native/cocos/bindings/dop/BufferAllocator.cpp @@ -50,7 +50,7 @@ se::Object *BufferAllocator::alloc(uint index, uint bytes) { _buffers[index] = obj; uint8_t *ret = nullptr; - size_t len; + size_t len; obj->getArrayBufferData(static_cast(&ret), &len); return obj; diff --git a/native/cocos/bindings/dop/BufferAllocator.h b/native/cocos/bindings/dop/BufferAllocator.h index 10dadf5639..df62c45aa1 100644 --- a/native/cocos/bindings/dop/BufferAllocator.h +++ b/native/cocos/bindings/dop/BufferAllocator.h @@ -40,13 +40,13 @@ public: ~BufferAllocator() override; se::Object *alloc(uint index, uint bytes); - void free(uint index); + void free(uint index); private: static constexpr uint BUFFER_MASK = ~(1 << 30); ccstd::unordered_map _buffers; - PoolType _type = PoolType::UNKNOWN; + PoolType _type = PoolType::UNKNOWN; }; } // namespace se diff --git a/native/cocos/bindings/dop/BufferPool.cpp b/native/cocos/bindings/dop/BufferPool.cpp index b41f7de171..b9ce862b16 100644 --- a/native/cocos/bindings/dop/BufferPool.cpp +++ b/native/cocos/bindings/dop/BufferPool.cpp @@ -35,8 +35,8 @@ BufferPool::BufferPool(PoolType type, uint entryBits, uint bytesPerEntry) _bytesPerEntry(bytesPerEntry), _type(type) { _entriesPerChunk = 1 << entryBits; - _entryMask = _entriesPerChunk - 1; - _chunkMask = 0xffffffff & ~(_entryMask | POOL_FLAG); + _entryMask = _entriesPerChunk - 1; + _chunkMask = 0xffffffff & ~(_entryMask | POOL_FLAG); _bytesPerChunk = _bytesPerEntry * _entriesPerChunk; } @@ -47,7 +47,7 @@ se::Object *BufferPool::allocateNewChunk() { se::Object *jsObj = _allocator.alloc(static_cast(_chunks.size()), _bytesPerChunk); uint8_t *realPtr = nullptr; - size_t len = 0; + size_t len = 0; jsObj->getArrayBufferData(&realPtr, &len); _chunks.push_back(realPtr); diff --git a/native/cocos/bindings/dop/BufferPool.h b/native/cocos/bindings/dop/BufferPool.h index 9790894f5e..73918631ab 100644 --- a/native/cocos/bindings/dop/BufferPool.h +++ b/native/cocos/bindings/dop/BufferPool.h @@ -57,15 +57,15 @@ public: private: static constexpr uint POOL_FLAG = 1 << 30; - BufferAllocator _allocator; + BufferAllocator _allocator; ccstd::vector _chunks; - uint _entryBits = 1 << 8; - uint _chunkMask = 0; - uint _entryMask = 0; - uint _bytesPerChunk = 0; - uint _entriesPerChunk = 0; - uint _bytesPerEntry = 0; - PoolType _type = PoolType::UNKNOWN; + uint _entryBits = 1 << 8; + uint _chunkMask = 0; + uint _entryMask = 0; + uint _bytesPerChunk = 0; + uint _entriesPerChunk = 0; + uint _bytesPerEntry = 0; + PoolType _type = PoolType::UNKNOWN; }; } // namespace se diff --git a/native/cocos/bindings/dop/jsb_dop.cpp b/native/cocos/bindings/dop/jsb_dop.cpp index c784d1560a..f901011c0d 100644 --- a/native/cocos/bindings/dop/jsb_dop.cpp +++ b/native/cocos/bindings/dop/jsb_dop.cpp @@ -48,10 +48,10 @@ SE_DECLARE_FINALIZE_FUNC(jsb_BufferPool_finalize) static bool jsb_BufferPool_constructor(se::State &s) { // NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 3) { - uint poolType = 0; - uint entryBits = 0; + uint poolType = 0; + uint entryBits = 0; uint bytesPerEntry = 0; bool ok = true; @@ -100,7 +100,7 @@ SE_DECLARE_FINALIZE_FUNC(jsb_BufferAllocator_finalize) static bool jsb_BufferAllocator_constructor(se::State &s) { // NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { uint type = 0; @@ -124,7 +124,7 @@ static bool jsb_BufferAllocator_alloc(se::State &s) { // NOLINT SE_PRECONDITION2(bufferAllocator, false, "jsb_Array_alloc : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { uint index = 0; sevalue_to_native(args[0], &index); @@ -144,7 +144,7 @@ static bool jsb_BufferAllocator_free(se::State &s) { // NOLINT SE_PRECONDITION2(bufferAllocator, false, "jsb_Array_alloc : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { uint index = 0; sevalue_to_native(args[0], &index); diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index c29eadf6fd..5bf3656795 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -31,21 +31,21 @@ #include "cocos/platform/interfaces/modules/ISystemWindow.h" namespace { -se::Value tickVal; -se::ValueArray tickArgsValArr(1); +se::Value tickVal; +se::ValueArray tickArgsValArr(1); ccstd::vector jsTouchObjPool; -se::Object * jsTouchObjArray = nullptr; -se::Object * jsMouseEventObj = nullptr; -se::Object * jsKeyboardEventObj = nullptr; -se::Object * jsResizeEventObj = nullptr; -se::Object * jsOrientationEventObj = nullptr; -bool inited = false; +se::Object *jsTouchObjArray = nullptr; +se::Object *jsMouseEventObj = nullptr; +se::Object *jsKeyboardEventObj = nullptr; +se::Object *jsResizeEventObj = nullptr; +se::Object *jsOrientationEventObj = nullptr; +bool inited = false; } // namespace namespace cc { ccstd::unordered_map EventDispatcher::listeners; -uint32_t EventDispatcher::hashListenerId = 1; +uint32_t EventDispatcher::hashListenerId = 1; bool EventDispatcher::initialized() { return inited && se::ScriptEngine::getInstance()->isValid(); @@ -110,7 +110,7 @@ void EventDispatcher::dispatchTouchEvent(const TouchEvent &touchEvent) { } uint32_t touchIndex = 0; - int poolIndex = 0; + int poolIndex = 0; for (const auto &touch : touchEvent.touches) { se::Object *jsTouch = jsTouchObjPool.at(poolIndex++); jsTouch->setProperty("identifier", se::Value(touch.index)); @@ -154,8 +154,8 @@ void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { jsMouseEventObj->root(); } - const auto & xVal = se::Value(mouseEvent.x); - const auto & yVal = se::Value(mouseEvent.y); + const auto &xVal = se::Value(mouseEvent.x); + const auto &yVal = se::Value(mouseEvent.y); const MouseEvent::Type type = mouseEvent.type; if (type == MouseEvent::Type::WHEEL) { @@ -169,23 +169,23 @@ void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { jsMouseEventObj->setProperty("y", yVal); } - const char *eventName = nullptr; + const char *eventName = nullptr; const char *jsFunctionName = nullptr; switch (type) { case MouseEvent::Type::DOWN: - eventName = EVENT_MOUSE_DOWN; + eventName = EVENT_MOUSE_DOWN; jsFunctionName = "onMouseDown"; break; case MouseEvent::Type::MOVE: - eventName = EVENT_MOUSE_MOVE; + eventName = EVENT_MOUSE_MOVE; jsFunctionName = "onMouseMove"; break; case MouseEvent::Type::UP: - eventName = EVENT_MOUSE_UP; + eventName = EVENT_MOUSE_UP; jsFunctionName = "onMouseUp"; break; case MouseEvent::Type::WHEEL: - eventName = EVENT_MOUSE_WHEEL; + eventName = EVENT_MOUSE_WHEEL; jsFunctionName = "onMouseWheel"; break; default: @@ -347,10 +347,10 @@ void EventDispatcher::doDispatchEvent(const char *eventName, const char *jsFunct } uint32_t EventDispatcher::addCustomEventListener(const ccstd::string &eventName, const CustomEventListener &listener) { - Node *newNode = ccnew Node(); - newNode->listener = listener; + Node *newNode = ccnew Node(); + newNode->listener = listener; newNode->listenerID = hashListenerId; - newNode->next = nullptr; + newNode->next = nullptr; auto iter = listeners.find(eventName); if (iter == listeners.end()) { diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index 72c2a96191..4cb8e8217e 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -38,13 +38,13 @@ namespace cc { enum class OSEventType { KEYBOARD_OSEVENT = 0, - TOUCH_OSEVENT = 1, - MOUSE_OSEVENT = 2, - CUSTOM_OSEVENT = 3, - DEVICE_OSEVENT = 4, - WINDOW_OSEVENT = 5, - APP_OSEVENT = 6, - UNKNOWN_OSEVENT = 7 + TOUCH_OSEVENT = 1, + MOUSE_OSEVENT = 2, + CUSTOM_OSEVENT = 3, + DEVICE_OSEVENT = 4, + WINDOW_OSEVENT = 5, + APP_OSEVENT = 6, + UNKNOWN_OSEVENT = 7 }; class OSEvent { @@ -68,7 +68,6 @@ private: #define CONSTRUCT_EVENT(name, type) \ name() : OSEvent(type) {} - class WindowEvent : public OSEvent { public: CONSTRUCT_EVENT(WindowEvent, OSEventType::WINDOW_OSEVENT) @@ -83,17 +82,17 @@ public: CLOSE, UNKNOWN, }; - Type type = Type::UNKNOWN; - int width = 0; - int height = 0; + Type type = Type::UNKNOWN; + int width = 0; + int height = 0; }; // Touch event related class TouchInfo { public: - float x = 0; - float y = 0; - int index = 0; + float x = 0; + float y = 0; + int index = 0; TouchInfo(float x, float y, int index) : x(x), @@ -113,7 +112,7 @@ public: }; ccstd::vector touches; - Type type = Type::UNKNOWN; + Type type = Type::UNKNOWN; }; class MouseEvent : public OSEvent { @@ -132,7 +131,7 @@ public: // The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. // For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left. uint16_t button = 0; - Type type = Type::UNKNOWN; + Type type = Type::UNKNOWN; }; enum class KeyCode { @@ -140,67 +139,67 @@ enum class KeyCode { * @en The back key on mobile phone * @zh 移动端返回键 */ - MOBILE_BACK = 6, - BACKSPACE = 8, - TAB = 9, - NUM_LOCK = 12, - NUMPAD_ENTER = 20013, - ENTER = 13, - SHIFT_RIGHT = 20016, - SHIFT_LEFT = 16, - CONTROL_LEFT = 17, - CONTROL_RIGHT = 20017, - ALT_RIGHT = 20018, - ALT_LEFT = 18, - PAUSE = 19, - CAPS_LOCK = 20, - ESCAPE = 27, - SPACE = 32, - PAGE_UP = 33, - PAGE_DOWN = 34, - END = 35, - HOME = 36, - ARROW_LEFT = 37, - ARROW_UP = 38, - ARROW_RIGHT = 39, - ARROW_DOWN = 40, - INSERT = 45, - DELETE_KEY = 46, //DELETE has conflict - META_LEFT = 91, - CONTEXT_MENU = 20093, - PRINT_SCREEN = 20094, - META_RIGHT = 93, + MOBILE_BACK = 6, + BACKSPACE = 8, + TAB = 9, + NUM_LOCK = 12, + NUMPAD_ENTER = 20013, + ENTER = 13, + SHIFT_RIGHT = 20016, + SHIFT_LEFT = 16, + CONTROL_LEFT = 17, + CONTROL_RIGHT = 20017, + ALT_RIGHT = 20018, + ALT_LEFT = 18, + PAUSE = 19, + CAPS_LOCK = 20, + ESCAPE = 27, + SPACE = 32, + PAGE_UP = 33, + PAGE_DOWN = 34, + END = 35, + HOME = 36, + ARROW_LEFT = 37, + ARROW_UP = 38, + ARROW_RIGHT = 39, + ARROW_DOWN = 40, + INSERT = 45, + DELETE_KEY = 46, //DELETE has conflict + META_LEFT = 91, + CONTEXT_MENU = 20093, + PRINT_SCREEN = 20094, + META_RIGHT = 93, NUMPAD_MULTIPLY = 106, - NUMPAD_PLUS = 107, - NUMPAD_MINUS = 109, - NUMPAD_DECIMAL = 110, - NUMPAD_DIVIDE = 111, - SCROLLLOCK = 145, - SEMICOLON = 186, - EQUAL = 187, - COMMA = 188, - MINUS = 189, - PERIOD = 190, - SLASH = 191, - BACKQUOTE = 192, - BRACKET_LEFT = 219, - BACKSLASH = 220, - BRACKET_RIGHT = 221, - QUOTE = 222, - NUMPAD_0 = 10048, - NUMPAD_1 = 10049, - NUMPAD_2 = 10050, - NUMPAD_3 = 10051, - NUMPAD_4 = 10052, - NUMPAD_5 = 10053, - NUMPAD_6 = 10054, - NUMPAD_7 = 10055, - NUMPAD_8 = 10056, - NUMPAD_9 = 10057, - DPAD_UP = 1003, - DPAD_LEFT = 1000, - DPAD_DOWN = 1004, - DPAD_RIGHT = 1001 + NUMPAD_PLUS = 107, + NUMPAD_MINUS = 109, + NUMPAD_DECIMAL = 110, + NUMPAD_DIVIDE = 111, + SCROLLLOCK = 145, + SEMICOLON = 186, + EQUAL = 187, + COMMA = 188, + MINUS = 189, + PERIOD = 190, + SLASH = 191, + BACKQUOTE = 192, + BRACKET_LEFT = 219, + BACKSLASH = 220, + BRACKET_RIGHT = 221, + QUOTE = 222, + NUMPAD_0 = 10048, + NUMPAD_1 = 10049, + NUMPAD_2 = 10050, + NUMPAD_3 = 10051, + NUMPAD_4 = 10052, + NUMPAD_5 = 10053, + NUMPAD_6 = 10054, + NUMPAD_7 = 10055, + NUMPAD_8 = 10056, + NUMPAD_9 = 10057, + DPAD_UP = 1003, + DPAD_LEFT = 1000, + DPAD_DOWN = 1004, + DPAD_RIGHT = 1001 }; class KeyboardEvent : public OSEvent { @@ -213,12 +212,12 @@ public: UNKNOWN }; - int key = -1; - Action action = Action::UNKNOWN; - bool altKeyActive = false; - bool ctrlKeyActive = false; - bool metaKeyActive = false; - bool shiftKeyActive = false; + int key = -1; + Action action = Action::UNKNOWN; + bool altKeyActive = false; + bool ctrlKeyActive = false; + bool metaKeyActive = false; + bool shiftKeyActive = false; // TODO(mingo): support caps lock? }; @@ -227,12 +226,12 @@ public: CONSTRUCT_EVENT(CustomEvent, OSEventType::CUSTOM_OSEVENT) ccstd::string name; union { - void * ptrVal; + void *ptrVal; int32_t longVal; - int intVal; + int intVal; int16_t shortVal; - char charVal; - bool boolVal; + char charVal; + bool boolVal; } args[10] = {}; virtual ~CustomEvent() = default; // NOLINT(modernize-use-nullptr) @@ -247,12 +246,12 @@ public: UNKNOWN }; union { - void * ptrVal; + void *ptrVal; int32_t longVal; - int intVal; + int intVal; int16_t shortVal; - char charVal; - bool boolVal; + char charVal; + bool boolVal; } args[3] = {}; Type type{Type::DEVICE_MEMORY}; // NOLINT(modernize-use-nullptr) }; @@ -279,21 +278,21 @@ public: using CustomEventListener = std::function; static uint32_t addCustomEventListener(const ccstd::string &eventName, const CustomEventListener &listener); - static void removeCustomEventListener(const ccstd::string &eventName, uint32_t listenerID); - static void removeAllCustomEventListeners(const ccstd::string &eventName); - static void removeAllEventListeners(); - static void dispatchCustomEvent(const CustomEvent &event); + static void removeCustomEventListener(const ccstd::string &eventName, uint32_t listenerID); + static void removeAllCustomEventListeners(const ccstd::string &eventName); + static void removeAllEventListeners(); + static void dispatchCustomEvent(const CustomEvent &event); private: static void doDispatchEvent(const char *eventName, const char *jsFunctionName, const ccstd::vector &args); struct Node { CustomEventListener listener; - uint32_t listenerID; - struct Node * next = nullptr; + uint32_t listenerID; + struct Node *next = nullptr; }; static ccstd::unordered_map listeners; - static uint32_t hashListenerId; //simple increment hash + static uint32_t hashListenerId; //simple increment hash }; } // end of namespace cc diff --git a/native/cocos/bindings/jswrapper/HandleObject.h b/native/cocos/bindings/jswrapper/HandleObject.h index cf764897aa..f55148f5c4 100644 --- a/native/cocos/bindings/jswrapper/HandleObject.h +++ b/native/cocos/bindings/jswrapper/HandleObject.h @@ -98,11 +98,11 @@ public: private: HandleObject(const HandleObject &) = delete; void operator=(const HandleObject &) = delete; - HandleObject(HandleObject &&) = delete; + HandleObject(HandleObject &&) = delete; void operator=(HandleObject &&) = delete; - void *operator new(size_t size) = delete; - void operator delete(void *, size_t) = delete; + void *operator new(size_t size) = delete; + void operator delete(void *, size_t) = delete; Object *_obj; friend class Object; diff --git a/native/cocos/bindings/jswrapper/MappingUtils.h b/native/cocos/bindings/jswrapper/MappingUtils.h index 163971dab5..13d3b67e1c 100644 --- a/native/cocos/bindings/jswrapper/MappingUtils.h +++ b/native/cocos/bindings/jswrapper/MappingUtils.h @@ -42,9 +42,9 @@ public: static Map::iterator find(void *nativeObj); static Map::iterator erase(Map::iterator iter); - static void erase(void *nativeObj); - static void clear(); - static size_t size(); + static void erase(void *nativeObj); + static void clear(); + static size_t size(); static const Map &instance(); diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index ac90b735f3..45a11ca3a4 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -55,8 +55,8 @@ public: return reinterpret_cast *>(this); } virtual const char *getName() const = 0; - virtual void * getRaw() const = 0; - virtual void allowDestroyInGC() const { + virtual void *getRaw() const = 0; + virtual void allowDestroyInGC() const { CC_ASSERT(false); } virtual void tryAllowDestroyInGC() const {} @@ -72,9 +72,9 @@ public: template class TypedPrivateObject : public PrivateObjectBase { public: - inline std::shared_ptr share(); + inline std::shared_ptr share(); inline cc::IntrusivePtr &ccShared(); - inline const char * getName() const override { + inline const char *getName() const override { static_assert(!std::is_base_of::value, ""); // NOLINT // remove after using c++17 return typeid(T).name(); } @@ -175,9 +175,9 @@ inline cc::IntrusivePtr &TypedPrivateObject::ccShared() { #if CC_DEBUG inline void inHeap(void *ptr) { constexpr size_t r = 4 * 1024; // 4K - char a; - auto anchor = reinterpret_cast(&a); - auto p = reinterpret_cast(ptr); + char a; + auto anchor = reinterpret_cast(&a); + auto p = reinterpret_cast(ptr); // must be in heaps CC_ASSERT(abs(anchor - p) > r); } diff --git a/native/cocos/bindings/jswrapper/State.h b/native/cocos/bindings/jswrapper/State.h index df338c642f..6d66a7831f 100644 --- a/native/cocos/bindings/jswrapper/State.h +++ b/native/cocos/bindings/jswrapper/State.h @@ -97,8 +97,8 @@ private: State &operator=(State &&) noexcept; PrivateObjectBase *_privateObject{nullptr}; - Object * _thisObject{nullptr}; //weak ref - const ValueArray * _args{nullptr}; //weak ref - Value _retVal; //weak ref + Object *_thisObject{nullptr}; //weak ref + const ValueArray *_args{nullptr}; //weak ref + Value _retVal; //weak ref }; } // namespace se diff --git a/native/cocos/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index 2cfbefd8ef..4a9a637fc2 100644 --- a/native/cocos/bindings/jswrapper/Value.cpp +++ b/native/cocos/bindings/jswrapper/Value.cpp @@ -60,7 +60,7 @@ inline ValueArray EmptyValueArray; // NOLINT(readability-identifier-naming) -Value Value::Null = Value(Type::Null); //NOLINT(readability-identifier-naming) +Value Value::Null = Value(Type::Null); //NOLINT(readability-identifier-naming) Value Value::Undefined = Value(Type::Undefined); //NOLINT(readability-identifier-naming) Value::Value() @@ -244,9 +244,9 @@ Value &Value::operator=(Value &&v) noexcept { } _u._object->decRef(); } - _u._object = v._u._object; - _autoRootUnroot = v._autoRootUnroot; - v._u._object = nullptr; // Reset to nullptr here to avoid 'release' operation in v.reset(Type::Undefined) since it's a move operation here. + _u._object = v._u._object; + _autoRootUnroot = v._autoRootUnroot; + v._u._object = nullptr; // Reset to nullptr here to avoid 'release' operation in v.reset(Type::Undefined) since it's a move operation here. v._autoRootUnroot = false; } break; default: @@ -390,7 +390,7 @@ void Value::setObject(Object *object, bool autoRootUnroot /* = false*/) { } _u._object->decRef(); } - _u._object = object; + _u._object = object; _autoRootUnroot = autoRootUnroot; } else { _autoRootUnroot = autoRootUnroot; diff --git a/native/cocos/bindings/jswrapper/Value.h b/native/cocos/bindings/jswrapper/Value.h index 7e3ba27867..941a43fd23 100644 --- a/native/cocos/bindings/jswrapper/Value.h +++ b/native/cocos/bindings/jswrapper/Value.h @@ -473,11 +473,11 @@ private: void reset(Type type); union { - bool _boolean; - double _number; + bool _boolean; + double _number; ccstd::string *_string; - Object * _object; - int64_t _bigint; + Object *_object; + int64_t _bigint; } _u; Type _type; diff --git a/native/cocos/bindings/jswrapper/ValueArrayPool.cpp b/native/cocos/bindings/jswrapper/ValueArrayPool.cpp index f819470bd1..752a2bccff 100644 --- a/native/cocos/bindings/jswrapper/ValueArrayPool.cpp +++ b/native/cocos/bindings/jswrapper/ValueArrayPool.cpp @@ -56,8 +56,8 @@ ValueArray &ValueArrayPool::get(uint32_t argc) { } void ValueArrayPool::initPool(uint32_t index) { - auto & pool = _pools[index]; - uint32_t i = 0; + auto &pool = _pools[index]; + uint32_t i = 0; for (auto &arr : pool) { arr.resize(i); ++i; diff --git a/native/cocos/bindings/jswrapper/ValueArrayPool.h b/native/cocos/bindings/jswrapper/ValueArrayPool.h index edc865d805..066ee0aff3 100644 --- a/native/cocos/bindings/jswrapper/ValueArrayPool.h +++ b/native/cocos/bindings/jswrapper/ValueArrayPool.h @@ -47,7 +47,7 @@ public: private: ValueArray &_arr; - uint32_t & _depth; + uint32_t &_depth; }; class ValueArrayPool final { @@ -61,7 +61,7 @@ public: uint32_t _depth{0}; private: - void initPool(uint32_t index); + void initPool(uint32_t index); ccstd::vector> _pools; }; diff --git a/native/cocos/bindings/jswrapper/config.cpp b/native/cocos/bindings/jswrapper/config.cpp index a314d9ddfe..6e5f186022 100644 --- a/native/cocos/bindings/jswrapper/config.cpp +++ b/native/cocos/bindings/jswrapper/config.cpp @@ -34,8 +34,8 @@ static void _winLog(FILE *fp, const char *format, va_list args) { static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char * buf = nullptr; + int bufferSize = MAX_LOG_LENGTH; + char *buf = nullptr; do { buf = ccnew char[bufferSize]; @@ -52,10 +52,10 @@ static void _winLog(FILE *fp, const char *format, va_list args) { } while (true); - int pos = 0; - auto len = static_cast(strlen(buf)); - char tempBuf[MAX_LOG_LENGTH + 1] = {0}; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; + int pos = 0; + auto len = static_cast(strlen(buf)); + char tempBuf[MAX_LOG_LENGTH + 1] = {0}; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; do { std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); diff --git a/native/cocos/bindings/jswrapper/sm/Class.cpp b/native/cocos/bindings/jswrapper/sm/Class.cpp index 33c894a5bb..6b7da1d110 100644 --- a/native/cocos/bindings/jswrapper/sm/Class.cpp +++ b/native/cocos/bindings/jswrapper/sm/Class.cpp @@ -74,8 +74,8 @@ Class *Class::create(const char *className, Object *obj, Object *parentProto, JS Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSNative ctor) { se::AutoHandleScope scope; - se::Object * currentParent = parent; - se::Value tmp; + se::Object *currentParent = parent; + se::Value tmp; for (auto i = 0; i < classPath.size() - 1; i++) { bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp); CC_ASSERT(ok); // class or namespace in path is not defined @@ -123,7 +123,7 @@ bool Class::install() { // // __clsMap.emplace(_name, this); - _jsCls.name = _name; + _jsCls.name = _name; _jsCls.flags = JSCLASS_USERBIT1 | JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_FOREGROUND_FINALIZE; //IDEA: Use JSCLASS_BACKGROUND_FINALIZE to improve GC performance if (_finalizeOp != nullptr) { _classOps.finalize = _finalizeOp; @@ -135,7 +135,7 @@ bool Class::install() { _jsCls.cOps = &_classOps; - JSObject * parentObj = _parentProto != nullptr ? _parentProto->_getJSObject() : nullptr; + JSObject *parentObj = _parentProto != nullptr ? _parentProto->_getJSObject() : nullptr; JS::RootedObject parentProto(__cx, parentObj); JS::RootedObject parent(__cx, _parent->_getJSObject()); @@ -208,7 +208,7 @@ bool Class::defineFinalizeFunction(JSFinalizeOp func) { // } void Class::_createJSObjectWithClass(Class *cls, JS::MutableHandleObject outObj) { - JSObject * proto = cls->_proto != nullptr ? cls->_proto->_getJSObject() : nullptr; + JSObject *proto = cls->_proto != nullptr ? cls->_proto->_getJSObject() : nullptr; JS::RootedObject jsProto(__cx, proto); outObj.set(JS_NewObjectWithGivenProto(__cx, &cls->_jsCls, jsProto)); } diff --git a/native/cocos/bindings/jswrapper/sm/Class.h b/native/cocos/bindings/jswrapper/sm/Class.h index fbdd0b5c2c..109e180df5 100644 --- a/native/cocos/bindings/jswrapper/sm/Class.h +++ b/native/cocos/bindings/jswrapper/sm/Class.h @@ -134,20 +134,20 @@ private: static void onTraceCallback(JSTracer *trc, JSObject *obj); const char *_name; - Object * _parent; - Object * _proto; - Object * _parentProto; + Object *_parent; + Object *_proto; + Object *_parentProto; JSNative _ctor; - JSClass _jsCls; + JSClass _jsCls; JSClassOps _classOps; ccstd::vector _funcs; ccstd::vector _staticFuncs; ccstd::vector _properties; ccstd::vector _staticProperties; - JSFinalizeOp _finalizeOp; + JSFinalizeOp _finalizeOp; friend class ScriptEngine; friend class Object; diff --git a/native/cocos/bindings/jswrapper/sm/HelperMacros.cpp b/native/cocos/bindings/jswrapper/sm/HelperMacros.cpp index 2db92b6682..e10dc43248 100644 --- a/native/cocos/bindings/jswrapper/sm/HelperMacros.cpp +++ b/native/cocos/bindings/jswrapper/sm/HelperMacros.cpp @@ -31,7 +31,7 @@ namespace { bool cmp(const std::pair> &a, const std::pair> &b) { return std::get<1>(a.second) > std::get<1>(b.second); } -unsigned int __jsbInvocationCount; // NOLINT(readability-identifier-naming) +unsigned int __jsbInvocationCount; // NOLINT(readability-identifier-naming) ccstd::unordered_map> __jsbFunctionInvokedRecords; // NOLINT(readability-identifier-naming) } // namespace diff --git a/native/cocos/bindings/jswrapper/sm/HelperMacros.h b/native/cocos/bindings/jswrapper/sm/HelperMacros.h index 5800d5f433..fe414ad79b 100644 --- a/native/cocos/bindings/jswrapper/sm/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/sm/HelperMacros.h @@ -35,29 +35,28 @@ #undef RECORD_JSB_INVOKING #endif - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM -#if defined(RECORD_JSB_INVOKING) + #if defined(RECORD_JSB_INVOKING) - class JsbInvokeScopeT { - public: - JsbInvokeScopeT(const char *functionName); - ~JsbInvokeScopeT(); +class JsbInvokeScopeT { +public: + JsbInvokeScopeT(const char *functionName); + ~JsbInvokeScopeT(); - private: - const char * _functionName; - std::chrono::time_point _start; - }; - #define JsbInvokeScope(arg) JsbInvokeScopeT invokeScope(arg); // NOLINT(readability-identifier-naming) +private: + const char *_functionName; + std::chrono::time_point _start; +}; + #define JsbInvokeScope(arg) JsbInvokeScopeT invokeScope(arg); // NOLINT(readability-identifier-naming) -#else - // NOLINTNEXTLINE(readability-identifier-naming) - #define JsbInvokeScope(arg) \ - do { \ - } while (0) + #else + // NOLINTNEXTLINE(readability-identifier-naming) + #define JsbInvokeScope(arg) \ + do { \ + } while (0) -#endif + #endif template constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-naming) @@ -80,7 +79,6 @@ void printJSBInvoke(); void printJSBInvokeAtFrame(int n); - #define SAFE_INC_REF(obj) \ if (obj != nullptr) obj->incRef() #define SAFE_DEC_REF(obj) \ @@ -94,82 +92,81 @@ void printJSBInvokeAtFrame(int n); #define SE_DECLARE_FUNC(funcName) \ bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) - #define SE_BIND_FUNC(funcName) \ - bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ - JsbInvokeScope(#funcName); \ - bool ret = false; \ - JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ - JS::RootedObject _thizObj(_cx); \ - _argv.computeThis(_cx, &_thizObj); \ - se::ValueArray & args = se::gValueArrayPool.get(argc); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ - se::internal::jsToSeArgs(_cx, argc, _argv, args); \ - se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ - se::Object * thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ - se::State state(thisObject, privateObject, args); \ - ret = funcName(state); \ - if (!ret) { \ - SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ - } \ - se::internal::setReturnValue(_cx, state.rval(), _argv); \ - return ret; \ + #define SE_BIND_FUNC(funcName) \ + bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ + JsbInvokeScope(#funcName); \ + bool ret = false; \ + JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ + JS::RootedObject _thizObj(_cx); \ + _argv.computeThis(_cx, &_thizObj); \ + se::ValueArray &args = se::gValueArrayPool.get(argc); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + se::internal::jsToSeArgs(_cx, argc, _argv, args); \ + se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ + se::State state(thisObject, privateObject, args); \ + ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ + se::internal::setReturnValue(_cx, state.rval(), _argv); \ + return ret; \ } -#define SE_BIND_FUNC_FAST(funcName) \ - bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ - JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ - JS::RootedObject _thizObj(_cx); \ - _argv.computeThis(_cx, &_thizObj); \ - auto *privateObject = static_cast(se::internal::SE_JS_GetPrivate(_thizObj, 0)); \ - funcName(privateObject->getRaw()); \ - _argv.rval().setUndefined(); \ - return true; \ - } + #define SE_BIND_FUNC_FAST(funcName) \ + bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ + JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ + JS::RootedObject _thizObj(_cx); \ + _argv.computeThis(_cx, &_thizObj); \ + auto *privateObject = static_cast(se::internal::SE_JS_GetPrivate(_thizObj, 0)); \ + funcName(privateObject->getRaw()); \ + _argv.rval().setUndefined(); \ + return true; \ + } #define SE_DECLARE_FINALIZE_FUNC(funcName) \ void funcName##Registry(JSFreeOp *_fop, JSObject *_obj); - #define SE_BIND_FINALIZE_FUNC(funcName) \ - void funcName##Registry(JSFreeOp *_fop, JSObject *_obj) { \ - JsbInvokeScope(#funcName); \ - se::PrivateObjectBase* privateObject = static_cast(se::internal::SE_JS_GetPrivate(_obj, 0)); \ - se::Object* seObj = static_cast(se::internal::SE_JS_GetPrivate(_obj, 1)); \ - bool ret = false; \ - if (privateObject == nullptr) \ - return; \ - se::State state(privateObject); \ - ret = funcName(state); \ - if (!ret) { \ - SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ - } \ - if (seObj->isClearMappingInFinalizer() && privateObject!= nullptr) { \ - void *nativeObj = privateObject->getRaw(); \ - auto iter = se::NativePtrToObjectMap::find(nativeObj); \ - if (iter != se::NativePtrToObjectMap::end()) { \ - se::NativePtrToObjectMap::erase(iter); \ - } \ - } \ - seObj->decRef(); \ + #define SE_BIND_FINALIZE_FUNC(funcName) \ + void funcName##Registry(JSFreeOp *_fop, JSObject *_obj) { \ + JsbInvokeScope(#funcName); \ + se::PrivateObjectBase *privateObject = static_cast(se::internal::SE_JS_GetPrivate(_obj, 0)); \ + se::Object *seObj = static_cast(se::internal::SE_JS_GetPrivate(_obj, 1)); \ + bool ret = false; \ + if (privateObject == nullptr) \ + return; \ + se::State state(privateObject); \ + ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ + if (seObj->isClearMappingInFinalizer() && privateObject != nullptr) { \ + void *nativeObj = privateObject->getRaw(); \ + auto iter = se::NativePtrToObjectMap::find(nativeObj); \ + if (iter != se::NativePtrToObjectMap::end()) { \ + se::NativePtrToObjectMap::erase(iter); \ + } \ + } \ + seObj->decRef(); \ } - #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ JsbInvokeScope(#funcName); \ - bool ret = false; \ - JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ - se::ValueArray & args = se::gValueArrayPool.get(argc); \ + bool ret = false; \ + JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ + se::ValueArray &args = se::gValueArrayPool.get(argc); \ se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ - se::internal::jsToSeArgs(_cx, argc, _argv, args); \ - se::Object *thisObject = se::Object::_createJSObjectForConstructor(cls, _argv); \ - thisObject->_setFinalizeCallback(finalizeCb##Registry); \ + se::internal::jsToSeArgs(_cx, argc, _argv, args); \ + se::Object *thisObject = se::Object::_createJSObjectForConstructor(cls, _argv); \ + thisObject->_setFinalizeCallback(finalizeCb##Registry); \ _argv.rval().setObject(*thisObject->_getJSObject()); \ se::State state(thisObject, args); \ ret = funcName(state); \ if (ret) { \ se::Value _property; \ - bool _found = false; \ - _found = thisObject->getProperty("_ctor", &_property); \ + bool _found = false; \ + _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } else { \ SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ @@ -177,46 +174,46 @@ void printJSBInvokeAtFrame(int n); return ret; \ } - #define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ - bool funcName##postFix##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ - JsbInvokeScope(#funcName); \ - bool ret = false; \ - JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ - JS::RootedObject _thizObj(_cx); \ - _argv.computeThis(_cx, &_thizObj); \ - se::PrivateObjectBase * privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ - se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ - se::State state(thisObject, privateObject); \ - ret = funcName(state); \ - if (!ret) { \ - SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ - } \ - se::internal::setReturnValue(_cx, state.rval(), _argv); \ - return ret; \ + #define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ + bool funcName##postFix##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \ + JsbInvokeScope(#funcName); \ + bool ret = false; \ + JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \ + JS::RootedObject _thizObj(_cx); \ + _argv.computeThis(_cx, &_thizObj); \ + se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ + se::State state(thisObject, privateObject); \ + ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ + se::internal::setReturnValue(_cx, state.rval(), _argv); \ + return ret; \ } #define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, ) #define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter) - #define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ - bool funcName##postFix##Registry(JSContext *_cx, unsigned _argc, JS::Value *_vp) { \ - JsbInvokeScope(#funcName); \ - bool ret = false; \ - JS::CallArgs _argv = JS::CallArgsFromVp(_argc, _vp); \ - JS::RootedObject _thizObj(_cx); \ - _argv.computeThis(_cx, &_thizObj); \ - se::PrivateObjectBase * privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ - se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ - se::ValueArray & args = se::gValueArrayPool.get(1); \ - se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ - se::Value& data{args[0]}; \ - se::internal::jsToSeValue(_cx, _argv[0], &data); \ - se::State state(thisObject, privateObject, args); \ - ret = funcName(state); \ - if (!ret) { \ - SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ - } \ - return ret; \ + #define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ + bool funcName##postFix##Registry(JSContext *_cx, unsigned _argc, JS::Value *_vp) { \ + JsbInvokeScope(#funcName); \ + bool ret = false; \ + JS::CallArgs _argv = JS::CallArgsFromVp(_argc, _vp); \ + JS::RootedObject _thizObj(_cx); \ + _argv.computeThis(_cx, &_thizObj); \ + se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_cx, _thizObj, 0)); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_cx, _thizObj, 1)); \ + se::ValueArray &args = se::gValueArrayPool.get(1); \ + se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ + se::Value &data{args[0]}; \ + se::internal::jsToSeValue(_cx, _argv[0], &data); \ + se::State state(thisObject, privateObject, args); \ + ret = funcName(state); \ + if (!ret) { \ + SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ + } \ + return ret; \ } #define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, ) diff --git a/native/cocos/bindings/jswrapper/sm/Object.cpp b/native/cocos/bindings/jswrapper/sm/Object.cpp index 8418b9bf5b..c333fd033f 100644 --- a/native/cocos/bindings/jswrapper/sm/Object.cpp +++ b/native/cocos/bindings/jswrapper/sm/Object.cpp @@ -65,7 +65,7 @@ Object::~Object() { } bool Object::init(Class *cls, JSObject *obj) { - _cls = cls; + _cls = cls; _heap = obj; assert(__objectMap.find(this) == __objectMap.end()); @@ -89,7 +89,7 @@ Object *Object::_createJSObject(Class *cls, JSObject *obj) { } Object *Object::_createJSObjectForConstructor(Class *cls, const JS::CallArgs &args) { - Object * ret = ccnew Object(); + Object *ret = ccnew Object(); JS::RootedObject obj(__cx, JS_NewObjectForConstructor(__cx, &cls->_jsCls, args)); if (!ret->init(cls, obj)) { delete ret; @@ -111,8 +111,8 @@ Object *Object::createObjectWithClass(Class *cls) { } Object *Object::getObjectWithPtr(void *ptr) { - Object *obj = nullptr; - auto iter = NativePtrToObjectMap::find(ptr); + Object *obj = nullptr; + auto iter = NativePtrToObjectMap::find(ptr); if (iter != NativePtrToObjectMap::end()) { obj = iter->second; obj->incRef(); @@ -122,7 +122,7 @@ Object *Object::getObjectWithPtr(void *ptr) { Object *Object::createArrayObject(size_t length) { JS::RootedObject jsobj(__cx, JS::NewArrayObject(__cx, length)); - Object * obj = Object::_createJSObject(nullptr, jsobj); + Object *obj = Object::_createJSObject(nullptr, jsobj); return obj; } @@ -158,16 +158,16 @@ Object *Object::createArrayBufferObject(const void *data, size_t byteLength) { Object *Object::createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData /* = nullptr*/) { struct BackingStoreUserData { BufferContentsFreeFunc freeFunc; - void * freeUserData; - size_t byteLength; + void *freeUserData; + size_t byteLength; }; - auto *userData = ccnew BackingStoreUserData(); - userData->freeFunc = freeFunc; + auto *userData = ccnew BackingStoreUserData(); + userData->freeFunc = freeFunc; userData->freeUserData = freeUserData; - userData->byteLength = byteLength; + userData->byteLength = byteLength; - Object * obj = nullptr; + Object *obj = nullptr; JS::RootedObject jsobj(__cx, JS::NewExternalArrayBuffer( __cx, byteLength, contents, [](void *data, void *deleterData) { @@ -195,9 +195,9 @@ Object *Object::createTypedArray(TypedArrayType type, const void *data, size_t b #define CREATE_TYPEDARRAY(_type_, _data, _byteLength, count) \ { \ - void * tmpData = nullptr; \ + void *tmpData = nullptr; \ JS::RootedObject arr(__cx, JS_New##_type_##Array(__cx, (uint32_t)(count))); \ - bool isShared = false; \ + bool isShared = false; \ if (_data != nullptr) { \ JS::AutoCheckCannotGC nogc; \ tmpData = JS_Get##_type_##ArrayData(arr, &isShared, nogc); \ @@ -240,7 +240,7 @@ Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *ob /* static */ Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) { - size_t byteLength{0}; + size_t byteLength{0}; uint8_t *skip{nullptr}; obj->getTypedArrayData(&skip, &byteLength); return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset); @@ -307,12 +307,12 @@ Object *Object::createUint8TypedArray(uint8_t *data, size_t dataCount) { } Object *Object::createJSONObject(const std::string &jsonStr) { - Value strVal(jsonStr); + Value strVal(jsonStr); JS::RootedValue jsStr(__cx); internal::seToJsValue(__cx, strVal, &jsStr); - JS::RootedValue jsObj(__cx); + JS::RootedValue jsObj(__cx); JS::RootedString rootedStr(__cx, jsStr.toString()); - Object * obj = nullptr; + Object *obj = nullptr; if (JS_ParseJSON(__cx, rootedStr, &jsObj)) { obj = Object::_createJSObject(nullptr, jsObj.toObjectOrNull()); } @@ -334,7 +334,7 @@ bool Object::getProperty(const char *name, Value *data, bool cachePropertyName) JS::RootedObject object(__cx, jsobj); bool found = false; - bool ok = JS_HasProperty(__cx, object, name, &found); + bool ok = JS_HasProperty(__cx, object, name, &found); if (!ok || !found) { return false; @@ -365,7 +365,7 @@ bool Object::defineProperty(const char *name, JSNative getter, JSNative setter) bool Object::defineOwnProperty(const char *name, const se::Value &value, bool writable, bool enumerable, bool configurable) { JS::RootedObject jsObj(__cx, _getJSObject()); - JS::RootedValue jsVal(__cx); + JS::RootedValue jsVal(__cx); internal::seToJsValue(__cx, value, &jsVal); unsigned attrs = 0; @@ -394,12 +394,12 @@ bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = n contextObject.set(thisObject->_getJSObject()); } - JSObject * funcObj = _getJSObject(); + JSObject *funcObj = _getJSObject(); JS::RootedValue func(__cx, JS::ObjectValue(*funcObj)); JS::RootedValue rcValue(__cx); JSAutoRealm autoRealm(__cx, func.toObjectOrNull()); - bool ok = JS_CallFunctionValue(__cx, contextObject, func, jsarr, &rcValue); + bool ok = JS_CallFunctionValue(__cx, contextObject, func, jsarr, &rcValue); if (ok) { if (rval != nullptr) @@ -413,7 +413,7 @@ bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = n bool Object::defineFunction(const char *funcName, JSNative func) { JS::RootedObject object(__cx, _getJSObject()); - JSFunction * jsFunc = JS_DefineFunction(__cx, object, funcName, func, 0, JSPROP_ENUMERATE); + JSFunction *jsFunc = JS_DefineFunction(__cx, object, funcName, func, 0, JSPROP_ENUMERATE); return jsFunc != nullptr; } @@ -436,7 +436,7 @@ bool Object::getArrayElement(uint32_t index, Value *data) const { return false; JS::RootedObject object(__cx, _getJSObject()); - JS::RootedValue rcValue(__cx); + JS::RootedValue rcValue(__cx); if (JS_GetElement(__cx, object, index, &rcValue)) { internal::jsToSeValue(__cx, rcValue, data); return true; @@ -471,7 +471,7 @@ bool Object::isTypedArray() const { Object::TypedArrayType Object::getTypedArrayType() const { TypedArrayType ret = TypedArrayType::NONE; - JSObject * obj = _getJSObject(); + JSObject *obj = _getJSObject(); if (JS_IsInt8Array(obj)) ret = TypedArrayType::INT8; else if (JS_IsInt16Array(obj)) @@ -511,7 +511,7 @@ bool Object::getTypedArrayData(uint8_t **ptr, size_t *length) const { bool Object::isArray() const { JS::RootedValue value(__cx, JS::ObjectValue(*_getJSObject())); - bool isArray = false; + bool isArray = false; return JS::IsArrayObject(__cx, value, &isArray) && isArray; } @@ -522,7 +522,7 @@ bool Object::isArrayBuffer() const { bool Object::getArrayBufferData(uint8_t **ptr, size_t *length) const { assert(isArrayBuffer()); - bool isShared = false; + bool isShared = false; JS::AutoCheckCannotGC nogc; if (ptr != nullptr) { *ptr = (uint8_t *)JS::GetArrayBufferData(_getJSObject(), &isShared, nogc); @@ -536,14 +536,14 @@ bool Object::getArrayBufferData(uint8_t **ptr, size_t *length) const { bool Object::getAllKeys(ccstd::vector *allKeys) const { assert(allKeys != nullptr); - JS::RootedObject jsobj(__cx, _getJSObject()); + JS::RootedObject jsobj(__cx, _getJSObject()); JS::Rooted props(__cx, JS::IdVector(__cx)); if (!JS_Enumerate(__cx, jsobj, &props)) return false; ccstd::vector keys; for (size_t i = 0, length = props.length(); i < length; ++i) { - JS::RootedId id(__cx, props[i]); + JS::RootedId id(__cx, props[i]); JS::RootedValue keyVal(__cx); JS_IdToValue(__cx, id, &keyVal); @@ -685,8 +685,8 @@ void Object::trace(JSTracer *tracer) { * finalized. If the object was finalized, returns true. */ bool Object::updateAfterGC(JSTracer *trc, void *data) { assert(!isRooted()); - bool isGarbageCollected = false; - internal::PrivateData *internalData = nullptr; + bool isGarbageCollected = false; + internal::PrivateData *internalData = nullptr; JSObject *oldPtr = _heap.unbarrieredGet(); if (_heap.unbarrieredGet() != nullptr) @@ -710,7 +710,7 @@ bool Object::isRooted() const { } bool Object::strictEquals(Object *o) const { - JSObject *thisObj = _getJSObject(); + JSObject *thisObj = _getJSObject(); JSObject *oThisObj = o->_getJSObject(); if ((thisObj == nullptr || oThisObj == nullptr) && thisObj != oThisObj) return false; @@ -719,8 +719,8 @@ bool Object::strictEquals(Object *o) const { assert(oThisObj); JS::RootedValue v1(__cx, JS::ObjectValue(*_getJSObject())); JS::RootedValue v2(__cx, JS::ObjectValue(*o->_getJSObject())); - bool same = false; - bool ok = JS::SameValue(__cx, v1, v2, &same); + bool same = false; + bool ok = JS::SameValue(__cx, v1, v2, &same); return ok && same; } @@ -728,7 +728,7 @@ bool Object::attachObject(Object *obj) { assert(obj); Object *global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) return false; Object *jsbObj = jsbVal.toObject(); @@ -748,7 +748,7 @@ bool Object::attachObject(Object *obj) { bool Object::detachObject(Object *obj) { assert(obj); Object *global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) return false; Object *jsbObj = jsbVal.toObject(); diff --git a/native/cocos/bindings/jswrapper/sm/Object.h b/native/cocos/bindings/jswrapper/sm/Object.h index e48fb7897d..69fe58902c 100644 --- a/native/cocos/bindings/jswrapper/sm/Object.h +++ b/native/cocos/bindings/jswrapper/sm/Object.h @@ -277,7 +277,7 @@ public: */ bool getAllKeys(ccstd::vector *allKeys) const; - void setPrivateObject(PrivateObjectBase *data); + void setPrivateObject(PrivateObjectBase *data); PrivateObjectBase *getPrivateObject() const; /** @@ -412,10 +412,10 @@ public: // Private API used in wrapper static Object *_createJSObject(Class *cls, JSObject *obj); static Object *_createJSObjectForConstructor(Class *cls, const JS::CallArgs &args); - void _setFinalizeCallback(JSFinalizeOp finalizeCb); - bool _isNativeFunction(JSNative func) const; - JSObject * _getJSObject() const; - Class * _getClass() const { return _cls; } + void _setFinalizeCallback(JSFinalizeOp finalizeCb); + bool _isNativeFunction(JSNative func) const; + JSObject *_getJSObject() const; + Class *_getClass() const { return _cls; } // private: @@ -434,13 +434,13 @@ private: void unprotect(); void reset(); - JS::Heap _heap; /* should be untouched if in rooted mode */ + JS::Heap _heap; /* should be untouched if in rooted mode */ JS::PersistentRootedObject _root; /* should be null if not in rooted mode */ - PrivateObjectBase * _privateObject{nullptr}; + PrivateObjectBase *_privateObject{nullptr}; internal::PrivateData *_internalData{nullptr}; - Class * _cls{nullptr}; + Class *_cls{nullptr}; JSFinalizeOp _finalizeCb{nullptr}; uint32_t _rootCount{0}; diff --git a/native/cocos/bindings/jswrapper/sm/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/sm/ScriptEngine.cpp index 46877c1858..0dde4221cd 100644 --- a/native/cocos/bindings/jswrapper/sm/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/sm/ScriptEngine.cpp @@ -108,7 +108,7 @@ bool __log(JSContext *cx, uint32_t argc, JS::Value *vp) { JSString *string = JS::ToString(cx, args[0]); if (string) { JS::RootedString jsstr(cx, string); - JS::UniqueChars buffer = JS_EncodeStringToUTF8(cx, jsstr); + JS::UniqueChars buffer = JS_EncodeStringToUTF8(cx, jsstr); SE_LOGD("JS: %s\n", buffer.get()); } @@ -175,13 +175,13 @@ bool JSB_console_format_log(State &s, const char *prefix, int msgIndex = 0) { return false; const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { std::string msg = args[msgIndex].toStringForce(); - size_t pos; + size_t pos; for (int i = (msgIndex + 1); i < argc; ++i) { pos = msg.find("%"); if (pos != std::string::npos && pos != (msg.length() - 1) && (msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) { @@ -293,24 +293,24 @@ void ScriptEngine::onWeakPointerCompartmentCallback(JSTracer *trc, JS::Compartme /* static */ void ScriptEngine::onWeakPointerZoneGroupCallback(JSTracer *trc, void *data) { - bool isInCleanup = getInstance()->isInCleanup(); - bool isIterUpdated = false; - Object *obj = nullptr; - auto iter = NativePtrToObjectMap::begin(); + bool isInCleanup = getInstance()->isInCleanup(); + bool isIterUpdated = false; + Object *obj = nullptr; + auto iter = NativePtrToObjectMap::begin(); while (iter != NativePtrToObjectMap::end()) { - obj = iter->second; + obj = iter->second; isIterUpdated = false; if (!obj->isRooted()) { if (obj->updateAfterGC(trc, data)) { obj->decRef(); - iter = NativePtrToObjectMap::erase(iter); + iter = NativePtrToObjectMap::erase(iter); isIterUpdated = true; } } else if (isInCleanup) // Rooted and in cleanup step { obj->unprotect(); obj->decRef(); - iter = NativePtrToObjectMap::erase(iter); + iter = NativePtrToObjectMap::erase(iter); isIterUpdated = true; } @@ -401,7 +401,7 @@ bool ScriptEngine::init() { // SpiderMonkey isn't shipped with a console variable. Make a fake one. Value consoleVal; - bool hasConsole = _globalObj->getProperty("console", &consoleVal) && consoleVal.isObject(); + bool hasConsole = _globalObj->getProperty("console", &consoleVal) && consoleVal.isObject(); assert(!hasConsole); HandleObject consoleObj(Object::createPlainObject()); @@ -457,10 +457,10 @@ void ScriptEngine::cleanup() { JS_DestroyContext(_cx); - _cx = nullptr; - _globalObj = nullptr; + _cx = nullptr; + _globalObj = nullptr; _oldCompartment = nullptr; - _isValid = false; + _isValid = false; _registerCallbackArray.clear(); @@ -516,13 +516,13 @@ void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { #pragma mark - Debug -static std::string inData; -static std::string outData; +static std::string inData; +static std::string outData; static ccstd::vector g_queue; -static std::mutex g_qMutex; -static std::mutex g_rwMutex; -static int clientSocket = -1; -static uint32_t s_nestedLoopLevel = 0; +static std::mutex g_qMutex; +static std::mutex g_rwMutex; +static int clientSocket = -1; +static uint32_t s_nestedLoopLevel = 0; static void cc_closesocket(int fd) { #ifdef _WIN32 @@ -534,7 +534,7 @@ static void cc_closesocket(int fd) { void ScriptEngine::_debugProcessInput(const std::string &str) { JS::RootedObject debugGlobal(_cx, _debugGlobalObj->_getJSObject()); - JS::Realm * globalCpt = JS::EnterRealm(_cx, debugGlobal); + JS::Realm *globalCpt = JS::EnterRealm(_cx, debugGlobal); Value func; if (_debugGlobalObj->getProperty("processInput", &func) && func.isObject() && func.toObject()->isFunction()) { @@ -548,13 +548,13 @@ void ScriptEngine::_debugProcessInput(const std::string &str) { static bool NS_ProcessNextEvent() { std::string message; - size_t messageCount = 0; + size_t messageCount = 0; while (true) { g_qMutex.lock(); messageCount = g_queue.size(); if (messageCount > 0) { auto first = g_queue.begin(); - message = *first; + message = *first; g_queue.erase(first); --messageCount; } @@ -640,11 +640,11 @@ static void clearBuffers() { static void serverEntryPoint(uint32_t port) { // start a server, accept the connection and keep reading data from it struct addrinfo hints, *result = nullptr, *rp = nullptr; - int s = 0; + int s = 0; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; + hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; // TCP stream sockets - hints.ai_flags = AI_PASSIVE; // fill in my IP for me + hints.ai_flags = AI_PASSIVE; // fill in my IP for me std::stringstream portstr; portstr << port; @@ -698,7 +698,7 @@ static void serverEntryPoint(uint32_t port) { #define BUF_SIZE MAX_RECEIVED_SIZE + 1 char buf[BUF_SIZE] = {0}; - int readBytes = 0; + int readBytes = 0; while (true) { clientSocket = accept(s, NULL, NULL); @@ -733,7 +733,7 @@ static void serverEntryPoint(uint32_t port) { static bool JSBDebug_require(State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc >= 1) { ScriptEngine::getInstance()->runScript(args[0].toString()); @@ -747,7 +747,7 @@ SE_BIND_FUNC(JSBDebug_require) static bool JSBDebug_BufferWrite(State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 1) { // this is safe because we're already inside a lock (from clearBuffers) outData.append(args[0].toString()); @@ -802,7 +802,7 @@ bool ScriptEngine::start() { JS::LeaveRealm(_cx, globalCpt); } - bool ok = false; + bool ok = false; _startTime = std::chrono::steady_clock::now(); for (auto cb : _permRegisterCallbackArray) { @@ -827,7 +827,7 @@ bool ScriptEngine::start() { bool ScriptEngine::getScript(const std::string &path, JS::MutableHandleScript script) { std::string fullPath = _fileOperationDelegate.onGetFullPath(path); - auto iter = _filenameScriptMap.find(fullPath); + auto iter = _filenameScriptMap.find(fullPath); if (iter != _filenameScriptMap.end()) { JS::PersistentRootedScript *rootedScript = iter->second; script.set(rootedScript->get()); @@ -901,7 +901,7 @@ bool ScriptEngine::compileScript(const std::string &path, JS::MutableHandleScrip op.setFileAndLine(path.c_str(), 1); JS::SourceText srcBuf; - bool succeed = srcBuf.init(_cx, jsFileContent.c_str(), jsFileContent.length(), + bool succeed = srcBuf.init(_cx, jsFileContent.c_str(), jsFileContent.length(), JS::SourceOwnership::Borrowed); assert(succeed); @@ -909,7 +909,7 @@ bool ScriptEngine::compileScript(const std::string &path, JS::MutableHandleScrip if (compiledScript != nullptr) { compileSucceed = true; script.set(compiledScript); - std::string fullPath = _fileOperationDelegate.onGetFullPath(path); + std::string fullPath = _fileOperationDelegate.onGetFullPath(path); _filenameScriptMap[fullPath] = ccnew JS::PersistentRootedScript(_cx, script.get()); } assert(compileSucceed); @@ -940,7 +940,7 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val JS::RootedValue rval(_cx); JS::SourceText srcBuf; - bool succeed = srcBuf.init(_cx, script, length, JS::SourceOwnership::Borrowed); + bool succeed = srcBuf.init(_cx, script, length, JS::SourceOwnership::Borrowed); assert(succeed); bool ok = JS::Evaluate(_cx, options, srcBuf, &rval); @@ -971,7 +971,7 @@ bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */ assert(_fileOperationDelegate.isValid()); JS::RootedScript script(_cx); - bool ok = compileScript(path, &script); + bool ok = compileScript(path, &script); if (ok) { JS::RootedValue rval(_cx); ok = JS_ExecuteScript(_cx, script, &rval); @@ -998,11 +998,11 @@ void ScriptEngine::clearException() { JS_ClearPendingException(_cx); assert(exceptionValue.isObject()); - JS::RootedObject exceptionObj(_cx, exceptionValue.toObjectOrNull()); - JSErrorReport * report = JS_ErrorFromException(_cx, exceptionObj); - const char * message = report->message().c_str(); + JS::RootedObject exceptionObj(_cx, exceptionValue.toObjectOrNull()); + JSErrorReport *report = JS_ErrorFromException(_cx, exceptionObj); + const char *message = report->message().c_str(); const std::string filePath = report->filename != nullptr ? report->filename : "(no filename)"; - char line[50] = {0}; + char line[50] = {0}; snprintf(line, sizeof(line), "%u", report->lineno); char column[50] = {0}; snprintf(column, sizeof(column), "%u", report->column); @@ -1075,13 +1075,13 @@ void ScriptEngine::mainLoopUpdate() { return; } std::string message; - size_t messageCount = 0; + size_t messageCount = 0; while (true) { g_qMutex.lock(); messageCount = g_queue.size(); if (messageCount > 0) { auto first = g_queue.begin(); - message = *first; + message = *first; g_queue.erase(first); --messageCount; } @@ -1115,7 +1115,7 @@ bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_ } bool found = false; - bool ok = JS_HasProperty(_cx, contextObject, funcName, &found); + bool ok = JS_HasProperty(_cx, contextObject, funcName, &found); if (!ok || !found) { return false; @@ -1129,7 +1129,7 @@ bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_ } JS::RootedValue rcValue(_cx); - JSAutoRealm autoRealm(_cx, funcValue.toObjectOrNull()); + JSAutoRealm autoRealm(_cx, funcValue.toObjectOrNull()); ok = JS_CallFunctionValue(_cx, contextObject, funcValue, jsarr, &rcValue); if (ok) { diff --git a/native/cocos/bindings/jswrapper/sm/ScriptEngine.h b/native/cocos/bindings/jswrapper/sm/ScriptEngine.h index 3684408c90..49a43c71df 100644 --- a/native/cocos/bindings/jswrapper/sm/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/sm/ScriptEngine.h @@ -297,8 +297,8 @@ public: // Private API used in wrapper JSContext *_getContext() { return _cx; } - void _setGarbageCollecting(bool isGarbageCollecting); - void _debugProcessInput(const std::string &str); + void _setGarbageCollecting(bool isGarbageCollecting); + void _debugProcessInput(const std::string &str); // private: ScriptEngine(); @@ -318,8 +318,8 @@ private: FileOperationDelegate _fileOperationDelegate; - ccstd::vector _registerCallbackArray; - ccstd::vector _permRegisterCallbackArray; + ccstd::vector _registerCallbackArray; + ccstd::vector _permRegisterCallbackArray; std::chrono::steady_clock::time_point _startTime; ccstd::vector> _beforeInitHookArray; @@ -333,7 +333,7 @@ private: std::unordered_map _filenameScriptMap; std::string _debuggerServerAddr; - uint32_t _debuggerServerPort; + uint32_t _debuggerServerPort; uint32_t _vmId; diff --git a/native/cocos/bindings/jswrapper/sm/Utils.cpp b/native/cocos/bindings/jswrapper/sm/Utils.cpp index 50de4cc62f..5d00a5c2ee 100644 --- a/native/cocos/bindings/jswrapper/sm/Utils.cpp +++ b/native/cocos/bindings/jswrapper/sm/Utils.cpp @@ -36,19 +36,19 @@ namespace se { namespace internal { -void* SE_JS_GetPrivate(JSObject* obj, uint32_t slot) { +void *SE_JS_GetPrivate(JSObject *obj, uint32_t slot) { assert(slot >= 0 && slot < 2); - const auto& v = JS::GetReservedSlot(obj, slot); + const auto &v = JS::GetReservedSlot(obj, slot); return v.isNullOrUndefined() ? nullptr : v.toPrivate(); } -void SE_JS_SetPrivate(JSObject* obj, uint32_t slot, void* data) { +void SE_JS_SetPrivate(JSObject *obj, uint32_t slot, void *data) { assert(slot >= 0 && slot < 2); JS::SetReservedSlot(obj, slot, JS::PrivateValue(data)); } -bool isJSBClass(JSObject* obj) { - const JSClass *cls = JS::GetClass(obj); +bool isJSBClass(JSObject *obj) { + const JSClass *cls = JS::GetClass(obj); return (cls->flags & (JSCLASS_HAS_RESERVED_SLOTS(2)) && (cls->flags & JSCLASS_USERBIT1)); } @@ -87,8 +87,8 @@ void seToJsValue(JSContext *cx, const Value &arg, JS::MutableHandleValue outVal) } break; case Value::Type::String: { - JS::UTF8Chars utf8Str(arg.toString().c_str(), arg.toString().length()); - JSString * string = JS_NewStringCopyUTF8N(cx, utf8Str); + JS::UTF8Chars utf8Str(arg.toString().c_str(), arg.toString().length()); + JSString *string = JS_NewStringCopyUTF8N(cx, utf8Str); JS::RootedValue value(cx); value.setString(string); outVal.set(value); @@ -118,10 +118,9 @@ void seToJsValue(JSContext *cx, const Value &arg, JS::MutableHandleValue outVal) } break; case Value::Type::BigInt: { JS::RootedValue value(cx); - JS::BigInt* bi = JS::NumberToBigInt(cx, arg.toUint64()); + JS::BigInt *bi = JS::NumberToBigInt(cx, arg.toUint64()); outVal.setBigInt(bi); - } - break; + } break; default: assert(false); break; diff --git a/native/cocos/bindings/jswrapper/sm/Utils.h b/native/cocos/bindings/jswrapper/sm/Utils.h index 6801205235..876f6006c1 100644 --- a/native/cocos/bindings/jswrapper/sm/Utils.h +++ b/native/cocos/bindings/jswrapper/sm/Utils.h @@ -40,13 +40,13 @@ class Class; namespace internal { - struct PrivateData { +struct PrivateData { PrivateObjectBase *data{nullptr}; - Object * seObj{nullptr}; + Object *seObj{nullptr}; JSFinalizeOp finalizeCb{nullptr}; }; -void forceConvertJsValueToStdString(JSContext *cx, JS::HandleValue jsval, std::string *ret); +void forceConvertJsValueToStdString(JSContext *cx, JS::HandleValue jsval, std::string *ret); std::string jsToStdString(JSContext *cx, JS::HandleString jsStr); void jsToSeArgs(JSContext *cx, int argc, const JS::CallArgs &argv, ValueArray &outArr); @@ -56,13 +56,13 @@ void seToJsValue(JSContext *cx, const Value &v, JS::MutableHandleValue outVal); void setReturnValue(JSContext *cx, const Value &data, const JS::CallArgs &argv); -bool hasPrivate(JSContext *cx, JS::HandleObject obj); +bool hasPrivate(JSContext *cx, JS::HandleObject obj); void *getPrivate(JSContext *cx, JS::HandleObject obj, uint32_t slot); -void setPrivate(JSContext *cx, JS::HandleObject obj, PrivateObjectBase *data, Object *seObj, PrivateData **outInternalData, JSFinalizeOp finalizeCb); -void clearPrivate(JSContext *cx, JS::HandleObject obj); +void setPrivate(JSContext *cx, JS::HandleObject obj, PrivateObjectBase *data, Object *seObj, PrivateData **outInternalData, JSFinalizeOp finalizeCb); +void clearPrivate(JSContext *cx, JS::HandleObject obj); -void* SE_JS_GetPrivate(JSObject* obj, uint32_t slot); -void SE_JS_SetPrivate(JSObject* obj, uint32_t slot, void* data); +void *SE_JS_GetPrivate(JSObject *obj, uint32_t slot); +void SE_JS_SetPrivate(JSObject *obj, uint32_t slot, void *data); } // namespace internal diff --git a/native/cocos/bindings/jswrapper/v8/Class.cpp b/native/cocos/bindings/jswrapper/v8/Class.cpp index f7d2e4d60a..8436d8ea46 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.cpp +++ b/native/cocos/bindings/jswrapper/v8/Class.cpp @@ -41,11 +41,11 @@ namespace se { namespace { // ccstd::unordered_map __clsMap; -v8::Isolate * __isolate = nullptr; // NOLINT -ccstd::vector __allClasses; // NOLINT +v8::Isolate *__isolate = nullptr; // NOLINT +ccstd::vector __allClasses; // NOLINT void invalidConstructor(const v8::FunctionCallbackInfo &args) { - v8::Local thisObj = args.This(); + v8::Local thisObj = args.This(); v8::Local constructorName = thisObj->GetConstructorName(); v8::String::Utf8Value strConstructorName{args.GetIsolate(), constructorName}; SE_ASSERT(false, "%s 's constructor is not public!", *strConstructorName); // NOLINT(misc-static-assert) @@ -77,8 +77,8 @@ Class *Class::create(const ccstd::string &clsName, se::Object *parent, Object *p Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, v8::FunctionCallback ctor) { se::AutoHandleScope scope; - se::Object * currentParent = parent; - se::Value tmp; + se::Object *currentParent = parent; + se::Value tmp; for (auto i = 0; i < classPath.size() - 1; i++) { bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp); CC_ASSERT(ok); // class or namespace in path is not defined @@ -149,14 +149,14 @@ bool Class::install() { _ctorTemplate.Get(__isolate)->Inherit(_parentProto->_getClass()->_ctorTemplate.Get(__isolate)); } - v8::Local context = __isolate->GetCurrentContext(); - v8::MaybeLocal ctor = _ctorTemplate.Get(__isolate)->GetFunction(context); + v8::Local context = __isolate->GetCurrentContext(); + v8::MaybeLocal ctor = _ctorTemplate.Get(__isolate)->GetFunction(context); if (ctor.IsEmpty()) { return false; } - v8::Local ctorChecked = ctor.ToLocalChecked(); - v8::MaybeLocal name = v8::String::NewFromUtf8(__isolate, _name.c_str(), v8::NewStringType::kNormal); + v8::Local ctorChecked = ctor.ToLocalChecked(); + v8::MaybeLocal name = v8::String::NewFromUtf8(__isolate, _name.c_str(), v8::NewStringType::kNormal); if (name.IsEmpty()) { return false; } diff --git a/native/cocos/bindings/jswrapper/v8/Class.h b/native/cocos/bindings/jswrapper/v8/Class.h index c8c6f49a1c..bac410c9f6 100644 --- a/native/cocos/bindings/jswrapper/v8/Class.h +++ b/native/cocos/bindings/jswrapper/v8/Class.h @@ -132,17 +132,17 @@ private: static void cleanup(); // static v8::Local _createJSObject(const ccstd::string &clsName, Class** outCls); static v8::Local _createJSObjectWithClass(Class *cls); // NOLINT(readability-identifier-naming) - static void setIsolate(v8::Isolate *isolate); + static void setIsolate(v8::Isolate *isolate); ccstd::string _name; - Object * _parent; - Object * _parentProto; - Object * _proto; + Object *_parent; + Object *_parentProto; + Object *_proto; - v8::FunctionCallback _ctor; + v8::FunctionCallback _ctor; v8::UniquePersistent _ctorTemplate; - V8FinalizeFunc _finalizeFunc; - bool _createProto; + V8FinalizeFunc _finalizeFunc; + bool _createProto; friend class ScriptEngine; friend class Object; diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp b/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp index 240b6614c7..892b3e8ce3 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.cpp @@ -31,7 +31,7 @@ namespace { bool cmp(const std::pair> &a, const std::pair> &b) { return std::get<1>(a.second) > std::get<1>(b.second); } -unsigned int __jsbInvocationCount; // NOLINT(readability-identifier-naming) +unsigned int __jsbInvocationCount; // NOLINT(readability-identifier-naming) ccstd::unordered_map> __jsbFunctionInvokedRecords; // NOLINT(readability-identifier-naming) } // namespace diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.h b/native/cocos/bindings/jswrapper/v8/HelperMacros.h index 0eac8285f8..1e82dc4a45 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.h @@ -54,7 +54,7 @@ public: ~JsbInvokeScopeT(); private: - const char * _functionName; + const char *_functionName; std::chrono::time_point _start; }; #define JsbInvokeScope(arg) JsbInvokeScopeT invokeScope(arg); // NOLINT(readability-identifier-naming) @@ -109,15 +109,15 @@ void printJSBInvokeAtFrame(int n); #define SE_BIND_FUNC(funcName) \ void funcName##Registry(const v8::FunctionCallbackInfo &_v8args) { \ JsbInvokeScope(#funcName); \ - bool ret = false; \ - v8::Isolate * _isolate = _v8args.GetIsolate(); \ - v8::HandleScope _hs(_isolate); \ - se::ValueArray & args = se::gValueArrayPool.get(_v8args.Length()); \ + bool ret = false; \ + v8::Isolate *_isolate = _v8args.GetIsolate(); \ + v8::HandleScope _hs(_isolate); \ + se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length()); \ se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ se::internal::jsToSeArgs(_v8args, args); \ se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_isolate, _v8args.This(), 0)); \ - se::Object * thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ - se::State state(thisObject, privateObject, args); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ + se::State state(thisObject, privateObject, args); \ ret = funcName(state); \ if (!ret) { \ SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ @@ -139,7 +139,7 @@ void printJSBInvokeAtFrame(int n); auto se = se::ScriptEngine::getInstance(); \ se->_setGarbageCollecting(true); \ se::State state(privateObject); \ - bool ret = funcName(state); \ + bool ret = funcName(state); \ if (!ret) { \ SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ } \ @@ -153,10 +153,10 @@ void printJSBInvokeAtFrame(int n); #define SE_BIND_CTOR(funcName, cls, finalizeCb) \ void funcName##Registry(const v8::FunctionCallbackInfo &_v8args) { \ JsbInvokeScope(#funcName); \ - v8::Isolate * _isolate = _v8args.GetIsolate(); \ - v8::HandleScope _hs(_isolate); \ - bool ret = true; \ - se::ValueArray & args = se::gValueArrayPool.get(_v8args.Length()); \ + v8::Isolate *_isolate = _v8args.GetIsolate(); \ + v8::HandleScope _hs(_isolate); \ + bool ret = true; \ + se::ValueArray &args = se::gValueArrayPool.get(_v8args.Length()); \ se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ se::internal::jsToSeArgs(_v8args, args); \ se::Object *thisObject = se::Object::_createJSObject(cls, _v8args.This()); \ @@ -167,20 +167,20 @@ void printJSBInvokeAtFrame(int n); SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ } \ se::Value _property; \ - bool _found = false; \ - _found = thisObject->getProperty("_ctor", &_property); \ + bool _found = false; \ + _found = thisObject->getProperty("_ctor", &_property); \ if (_found) _property.toObject()->call(args, thisObject); \ } #define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ void funcName##postFix##Registry(v8::Local /*_property*/, const v8::PropertyCallbackInfo &_v8args) { \ JsbInvokeScope(#funcName); \ - v8::Isolate * _isolate = _v8args.GetIsolate(); \ - v8::HandleScope _hs(_isolate); \ - bool ret = true; \ + v8::Isolate *_isolate = _v8args.GetIsolate(); \ + v8::HandleScope _hs(_isolate); \ + bool ret = true; \ se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_isolate, _v8args.This(), 0)); \ - se::Object * thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ - se::State state(thisObject, privateObject); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ + se::State state(thisObject, privateObject); \ ret = funcName(state); \ if (!ret) { \ SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \ @@ -194,14 +194,14 @@ void printJSBInvokeAtFrame(int n); #define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ void funcName##postFix##Registry(v8::Local /*_property*/, v8::Local _value, const v8::PropertyCallbackInfo &_v8args) { \ JsbInvokeScope(#funcName); \ - v8::Isolate * _isolate = _v8args.GetIsolate(); \ - v8::HandleScope _hs(_isolate); \ - bool ret = true; \ + v8::Isolate *_isolate = _v8args.GetIsolate(); \ + v8::HandleScope _hs(_isolate); \ + bool ret = true; \ se::PrivateObjectBase *privateObject = static_cast(se::internal::getPrivate(_isolate, _v8args.This(), 0)); \ - se::Object * thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ - se::ValueArray & args = se::gValueArrayPool.get(1); \ + se::Object *thisObject = reinterpret_cast(se::internal::getPrivate(_isolate, _v8args.This(), 1)); \ + se::ValueArray &args = se::gValueArrayPool.get(1); \ se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \ - se::Value & data{args[0]}; \ + se::Value &data{args[0]}; \ se::internal::jsToSeValue(_isolate, _value, &data); \ se::State state(thisObject, privateObject, args); \ ret = funcName(state); \ diff --git a/native/cocos/bindings/jswrapper/v8/Object.cpp b/native/cocos/bindings/jswrapper/v8/Object.cpp index 178e0202b1..f707cfb719 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/bindings/jswrapper/v8/Object.cpp @@ -77,7 +77,7 @@ void Object::nativeObjectFinalizeHook(Object *seObj) { if (seObj->_clearMappingInFinalizer && seObj->_privateObject != nullptr) { void *nativeObj = seObj->_privateObject->getRaw(); - auto iter = NativePtrToObjectMap::find(nativeObj); + auto iter = NativePtrToObjectMap::find(nativeObj); if (iter != NativePtrToObjectMap::end()) { NativePtrToObjectMap::erase(iter); } @@ -103,14 +103,14 @@ void Object::setup() { } void Object::cleanup() { - void * nativeObj = nullptr; - Object *obj = nullptr; - Class * cls = nullptr; + void *nativeObj = nullptr; + Object *obj = nullptr; + Class *cls = nullptr; const auto &nativePtrToObjectMap = NativePtrToObjectMap::instance(); for (const auto &e : nativePtrToObjectMap) { - nativeObj = e.first; - obj = e.second; + nativeObj = e.first; + obj = e.second; PrivateObjectBase *privateObject = obj->getPrivateObject(); if (obj->_finalizeCb != nullptr) { obj->_finalizeCb(privateObject); @@ -154,13 +154,13 @@ void Object::cleanup() { Object *Object::createPlainObject() { v8::Local jsobj = v8::Object::New(__isolate); - Object * obj = _createJSObject(nullptr, jsobj); + Object *obj = _createJSObject(nullptr, jsobj); return obj; } Object *Object::getObjectWithPtr(void *ptr) { - Object *obj = nullptr; - auto iter = NativePtrToObjectMap::find(ptr); + Object *obj = nullptr; + auto iter = NativePtrToObjectMap::find(ptr); if (iter != NativePtrToObjectMap::end()) { obj = iter->second; obj->incRef(); @@ -179,13 +179,13 @@ Object *Object::_createJSObject(Class *cls, v8::Local obj) { // NOLI Object *Object::createObjectWithClass(Class *cls) { v8::Local jsobj = Class::_createJSObjectWithClass(cls); - Object * obj = Object::_createJSObject(cls, jsobj); + Object *obj = Object::_createJSObject(cls, jsobj); return obj; } Object *Object::createArrayObject(size_t length) { v8::Local jsobj = v8::Array::New(__isolate, static_cast(length)); - Object * obj = Object::_createJSObject(nullptr, jsobj); + Object *obj = Object::_createJSObject(nullptr, jsobj); return obj; } @@ -203,8 +203,8 @@ Object *Object::createArrayBufferObject(const void *data, size_t byteLength) { /* static */ Object *Object::createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData /* = nullptr*/) { std::shared_ptr backingStore = v8::ArrayBuffer::NewBackingStore(contents, byteLength, freeFunc, freeUserData); - Object * obj = nullptr; - v8::Local jsobj = v8::ArrayBuffer::New(__isolate, backingStore); + Object *obj = nullptr; + v8::Local jsobj = v8::ArrayBuffer::New(__isolate, backingStore); if (!jsobj.IsEmpty()) { obj = Object::_createJSObject(nullptr, jsobj); } @@ -270,7 +270,7 @@ Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *ob } Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) { - size_t byteLength{0}; + size_t byteLength{0}; uint8_t *skip{nullptr}; obj->getTypedArrayData(&skip, &byteLength); return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset); @@ -329,11 +329,11 @@ Object *Object::createUint8TypedArray(uint8_t *bytes, size_t byteLength) { Object *Object::createJSONObject(const ccstd::string &jsonStr) { v8::Local context = __isolate->GetCurrentContext(); - Value strVal(jsonStr); - v8::Local jsStr; + Value strVal(jsonStr); + v8::Local jsStr; internal::seToJsValue(__isolate, strVal, &jsStr); - v8::Local v8Str = v8::Local::Cast(jsStr); - v8::MaybeLocal ret = v8::JSON::Parse(context, v8Str); + v8::Local v8Str = v8::Local::Cast(jsStr); + v8::MaybeLocal ret = v8::JSON::Parse(context, v8Str); if (ret.IsEmpty()) { return nullptr; } @@ -384,10 +384,10 @@ bool Object::getProperty(const char *name, Value *data, bool cachePropertyName) return false; } - v8::Local nameValToLocal = nameValue.ToLocalChecked(); - v8::Local context = __isolate->GetCurrentContext(); - v8::Local localObj = _obj.handle(__isolate); - v8::Maybe maybeExist = localObj->Has(context, nameValToLocal); + v8::Local nameValToLocal = nameValue.ToLocalChecked(); + v8::Local context = __isolate->GetCurrentContext(); + v8::Local localObj = _obj.handle(__isolate); + v8::Maybe maybeExist = localObj->Has(context, nameValToLocal); if (maybeExist.IsNothing()) { return false; } @@ -418,9 +418,9 @@ bool Object::deleteProperty(const char *name) { return false; } - v8::Local nameValToLocal = nameValue.ToLocalChecked(); - v8::Local context = __isolate->GetCurrentContext(); - v8::Maybe maybeExist = _obj.handle(__isolate)->Delete(context, nameValToLocal); + v8::Local nameValToLocal = nameValue.ToLocalChecked(); + v8::Local context = __isolate->GetCurrentContext(); + v8::Maybe maybeExist = _obj.handle(__isolate)->Delete(context, nameValToLocal); if (maybeExist.IsNothing()) { return false; } @@ -455,8 +455,8 @@ bool Object::defineProperty(const char *name, v8::AccessorNameGetterCallback get } v8::Local nameValChecked = nameValue.ToLocalChecked(); - v8::Local jsName = v8::Local::Cast(nameValChecked); - v8::Maybe ret = _obj.handle(__isolate)->SetAccessor(__isolate->GetCurrentContext(), jsName, getter, setter); + v8::Local jsName = v8::Local::Cast(nameValChecked); + v8::Maybe ret = _obj.handle(__isolate)->SetAccessor(__isolate->GetCurrentContext(), jsName, getter, setter); return ret.IsJust() && ret.FromJust(); } @@ -481,8 +481,8 @@ bool Object::defineOwnProperty(const char *name, const se::Value &value, bool wr internal::seToJsValue(__isolate, value, &v8Value); v8::Local nameValChecked = nameValue.ToLocalChecked(); - v8::Local jsName = v8::Local::Cast(nameValChecked); - v8::Maybe ret = _obj.handle(__isolate)->DefineOwnProperty(__isolate->GetCurrentContext(), jsName, v8Value, static_cast(flag)); + v8::Local jsName = v8::Local::Cast(nameValChecked); + v8::Maybe ret = _obj.handle(__isolate)->DefineOwnProperty(__isolate->GetCurrentContext(), jsName, v8Value, static_cast(flag)); return ret.IsJust() && ret.FromJust(); } @@ -506,7 +506,7 @@ bool Object::isTypedArray() const { Object::TypedArrayType Object::getTypedArrayType() const { v8::Local value = const_cast(this)->_obj.handle(__isolate); - TypedArrayType ret = TypedArrayType::NONE; + TypedArrayType ret = TypedArrayType::NONE; if (value->IsInt8Array()) { ret = TypedArrayType::INT8; } else if (value->IsInt16Array()) { @@ -532,10 +532,10 @@ Object::TypedArrayType Object::getTypedArrayType() const { bool Object::getTypedArrayData(uint8_t **ptr, size_t *length) const { CC_ASSERT(isTypedArray()); - v8::Local obj = const_cast(this)->_obj.handle(__isolate); - v8::Local arr = v8::Local::Cast(obj); - const auto & backingStore = arr->Buffer()->GetBackingStore(); - *ptr = static_cast(backingStore->Data()) + arr->ByteOffset(); + v8::Local obj = const_cast(this)->_obj.handle(__isolate); + v8::Local arr = v8::Local::Cast(obj); + const auto &backingStore = arr->Buffer()->GetBackingStore(); + *ptr = static_cast(backingStore->Data()) + arr->ByteOffset(); if (length) { *length = arr->ByteLength(); } @@ -549,10 +549,10 @@ bool Object::isArrayBuffer() const { bool Object::getArrayBufferData(uint8_t **ptr, size_t *length) const { CC_ASSERT(isArrayBuffer()); - v8::Local obj = const_cast(this)->_obj.handle(__isolate); - v8::Local arrBuf = v8::Local::Cast(obj); - const auto & backingStore = arrBuf->GetBackingStore(); - *ptr = static_cast(backingStore->Data()); + v8::Local obj = const_cast(this)->_obj.handle(__isolate); + v8::Local arrBuf = v8::Local::Cast(obj); + const auto &backingStore = arrBuf->GetBackingStore(); + *ptr = static_cast(backingStore->Data()); if (length) { *length = backingStore->ByteLength(); } @@ -620,8 +620,8 @@ bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = n size_t argc = args.size(); ccstd::array, JSB_FUNC_DEFAULT_MAX_ARG_COUNT> argv; - std::unique_ptr>> vecArgs; - v8::Local * pArgv = argv.data(); + std::unique_ptr>> vecArgs; + v8::Local *pArgv = argv.data(); if (argc > JSB_FUNC_DEFAULT_MAX_ARG_COUNT) { vecArgs = std::make_unique>>(); @@ -680,7 +680,7 @@ bool Object::defineFunction(const char *funcName, void (*func)(const v8::Functio return false; } - v8::Local context = __isolate->GetCurrentContext(); + v8::Local context = __isolate->GetCurrentContext(); v8::MaybeLocal maybeFunc = v8::FunctionTemplate::New(__isolate, func)->GetFunction(context); if (maybeFunc.IsEmpty()) { return false; @@ -731,7 +731,7 @@ bool Object::getArrayLength(uint32_t *length) const { bool Object::getArrayElement(uint32_t index, Value *data) const { CC_ASSERT(isArray()); CC_ASSERT(data != nullptr); - auto * thiz = const_cast(this); + auto *thiz = const_cast(this); v8::MaybeLocal result = thiz->_obj.handle(__isolate)->Get(__isolate->GetCurrentContext(), index); if (result.IsEmpty()) { @@ -754,15 +754,15 @@ bool Object::setArrayElement(uint32_t index, const Value &data) { bool Object::getAllKeys(ccstd::vector *allKeys) const { CC_ASSERT(allKeys != nullptr); - auto * thiz = const_cast(this); - v8::Local context = __isolate->GetCurrentContext(); - v8::MaybeLocal keys = thiz->_obj.handle(__isolate)->GetOwnPropertyNames(context); + auto *thiz = const_cast(this); + v8::Local context = __isolate->GetCurrentContext(); + v8::MaybeLocal keys = thiz->_obj.handle(__isolate)->GetOwnPropertyNames(context); if (keys.IsEmpty()) { return false; } v8::Local keysChecked = keys.ToLocalChecked(); - Value keyVal; + Value keyVal; for (uint32_t i = 0, len = keysChecked->Length(); i < len; ++i) { v8::MaybeLocal key = keysChecked->Get(context, i); if (key.IsEmpty()) { @@ -821,7 +821,7 @@ bool Object::attachObject(Object *obj) { CC_ASSERT(obj); Object *global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) { return false; } @@ -844,7 +844,7 @@ bool Object::detachObject(Object *obj) { CC_ASSERT(obj); Object *global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) { return false; } diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index d5c3c4b56a..05e4b5e1d3 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -296,7 +296,7 @@ public: */ bool getAllKeys(ccstd::vector *allKeys) const; - void setPrivateObject(PrivateObjectBase *data); + void setPrivateObject(PrivateObjectBase *data); PrivateObjectBase *getPrivateObject() const; /** @@ -430,10 +430,10 @@ public: ccstd::string toStringExt() const; // Private API used in wrapper - static Object * _createJSObject(Class *cls, v8::Local obj); // NOLINT(readability-identifier-naming) - v8::Local _getJSObject() const; // NOLINT(readability-identifier-naming) - ObjectWrap & _getWrap(); // NOLINT(readability-identifier-naming) - Class * _getClass() const; // NOLINT(readability-identifier-naming) + static Object *_createJSObject(Class *cls, v8::Local obj); // NOLINT(readability-identifier-naming) + v8::Local _getJSObject() const; // NOLINT(readability-identifier-naming) + ObjectWrap &_getWrap(); // NOLINT(readability-identifier-naming) + Class *_getClass() const; // NOLINT(readability-identifier-naming) void _setFinalizeCallback(V8FinalizeFunc finalizeCb); // NOLINT(readability-identifier-naming) bool _isNativeFunction() const; // NOLINT(readability-identifier-naming) @@ -454,14 +454,14 @@ private: bool init(Class *cls, v8::Local obj); - Class * _cls{nullptr}; + Class *_cls{nullptr}; ObjectWrap _obj; - uint32_t _rootCount{0}; + uint32_t _rootCount{0}; - PrivateObjectBase * _privateObject{nullptr}; - V8FinalizeFunc _finalizeCb{nullptr}; + PrivateObjectBase *_privateObject{nullptr}; + V8FinalizeFunc _finalizeCb{nullptr}; internal::PrivateData *_internalData{nullptr}; - bool _clearMappingInFinalizer{true}; + bool _clearMappingInFinalizer{true}; #if CC_DEBUG && CC_DEBUG_JS_OBJECT_ID uint32_t _objectId = 0; diff --git a/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp b/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp index 9a0fb784fc..3ffb6b1e05 100644 --- a/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp +++ b/native/cocos/bindings/jswrapper/v8/ObjectWrap.cpp @@ -136,7 +136,7 @@ void ObjectWrap::unref() { /*static*/ void ObjectWrap::weakCallback(const v8::WeakCallbackInfo &data) { Object *seObj = data.GetParameter(); - ObjectWrap *wrap = &seObj->_getWrap(); + ObjectWrap *wrap = &seObj->_getWrap(); CC_ASSERT(wrap->_refs == 0); wrap->_handle.Reset(); diff --git a/native/cocos/bindings/jswrapper/v8/ObjectWrap.h b/native/cocos/bindings/jswrapper/v8/ObjectWrap.h index cd9b15ec77..057730c183 100644 --- a/native/cocos/bindings/jswrapper/v8/ObjectWrap.h +++ b/native/cocos/bindings/jswrapper/v8/ObjectWrap.h @@ -64,11 +64,11 @@ public: using FinalizeFunc = void (*)(Object *seObj); void setFinalizeCallback(FinalizeFunc finalizeCb); - v8::Local handle(); - v8::Local handle(v8::Isolate *isolate); + v8::Local handle(); + v8::Local handle(v8::Isolate *isolate); v8::Persistent &persistent(); - void wrap(void *nativeObj, uint32_t fieldIndex); + void wrap(void *nativeObj, uint32_t fieldIndex); static void *unwrap(v8::Local handle, uint32_t fieldIndex); /* Ref() marks the object as being attached to an event loop. * Refed objects will not be garbage collected, even if @@ -92,10 +92,10 @@ private: void makeWeak(); - int _refs{0}; // ro + int _refs{0}; // ro v8::Persistent _handle; - FinalizeFunc _finalizeCb{nullptr}; - Object * _parent{nullptr}; + FinalizeFunc _finalizeCb{nullptr}; + Object *_parent{nullptr}; bool _registerWeak{false}; }; diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 02c90a1b31..23d944cf03 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -52,7 +52,7 @@ const unsigned int JSB_STACK_FRAME_LIMIT = 20; #ifdef CC_DEBUG -unsigned int jsbInvocationCount = 0; +unsigned int jsbInvocationCount = 0; ccstd::unordered_map jsbFunctionInvokedRecords; #endif @@ -83,15 +83,15 @@ ccstd::string stackTraceToString(v8::Local stack) { char tmp[100] = {0}; for (int i = 0, e = stack->GetFrameCount(); i < e; ++i) { - v8::Local frame = stack->GetFrame(v8::Isolate::GetCurrent(), i); - v8::Local script = frame->GetScriptName(); - ccstd::string scriptName; + v8::Local frame = stack->GetFrame(v8::Isolate::GetCurrent(), i); + v8::Local script = frame->GetScriptName(); + ccstd::string scriptName; if (!script.IsEmpty()) { scriptName = *v8::String::Utf8Value(v8::Isolate::GetCurrent(), script); } v8::Local func = frame->GetFunctionName(); - ccstd::string funcName; + ccstd::string funcName; if (!func.IsEmpty()) { funcName = *v8::String::Utf8Value(v8::Isolate::GetCurrent(), func); } @@ -128,13 +128,13 @@ bool jsbConsoleFormatLog(State &state, const char *prefix, int msgIndex = 0) { } const auto &args = state.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if ((argc - msgIndex) == 1) { ccstd::string msg = args[msgIndex].toStringForce(); SE_LOGD("JS: %s%s\n", prefix, msg.c_str()); } else if (argc > 1) { ccstd::string msg = args[msgIndex].toStringForce(); - size_t pos; + size_t pos; for (int i = (msgIndex + 1); i < argc; ++i) { pos = msg.find('%'); if (pos != ccstd::string::npos && pos != (msg.length() - 1) && (msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) { @@ -271,13 +271,13 @@ void ScriptEngine::onOOMErrorCallback(const char *location, bool isHeapOom) { } void ScriptEngine::onMessageCallback(v8::Local message, v8::Local /*data*/) { - ScriptEngine * thiz = getInstance(); - v8::Local msg = message->Get(); - Value msgVal; + ScriptEngine *thiz = getInstance(); + v8::Local msg = message->Get(); + Value msgVal; internal::jsToSeValue(v8::Isolate::GetCurrent(), msg, &msgVal); CC_ASSERT(msgVal.isString()); v8::ScriptOrigin origin = message->GetScriptOrigin(); - Value resouceNameVal; + Value resouceNameVal; internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceName(), &resouceNameVal); Value line(origin.LineOffset()); Value column(origin.ColumnOffset()); @@ -367,22 +367,22 @@ void ScriptEngine::handlePromiseExceptions() { void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) { /* Reject message contains different types, yet not every type will lead to the exception in the end. * A detection is needed: if the reject handler is added after the promise is triggered, it's actually valid.*/ - v8::Isolate * isolate = getInstance()->_isolate; - v8::HandleScope scope(isolate); + v8::Isolate *isolate = getInstance()->_isolate; + v8::HandleScope scope(isolate); std::stringstream ss; - auto event = msg.GetEvent(); - auto value = msg.GetValue(); - auto promiseName = msg.GetPromise()->GetConstructorName(); + auto event = msg.GetEvent(); + auto value = msg.GetValue(); + auto promiseName = msg.GetPromise()->GetConstructorName(); if (!value.IsEmpty()) { // prepend error object to stack message v8::MaybeLocal maybeStr = value->ToString(isolate->GetCurrentContext()); - v8::Local str = maybeStr.IsEmpty() ? v8::String::NewFromUtf8(isolate, "[empty string]").ToLocalChecked() : maybeStr.ToLocalChecked(); - v8::String::Utf8Value valueUtf8(isolate, str); - auto * strp = *valueUtf8; + v8::Local str = maybeStr.IsEmpty() ? v8::String::NewFromUtf8(isolate, "[empty string]").ToLocalChecked() : maybeStr.ToLocalChecked(); + v8::String::Utf8Value valueUtf8(isolate, str); + auto *strp = *valueUtf8; if (strp == nullptr) { ss << "value: null" << std::endl; - auto tn = value->TypeOf(isolate); + auto tn = value->TypeOf(isolate); v8::String::Utf8Value tnUtf8(isolate, tn); strp = *tnUtf8; if (strp) { @@ -399,14 +399,14 @@ void ScriptEngine::onPromiseRejectCallback(v8::PromiseRejectMessage msg) { ss << " obj: null" << std::endl; } } else { - v8::Local obj = value->ToObject(isolate->GetCurrentContext()).ToLocalChecked(); - v8::Local attrNames = obj->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocalChecked(); + v8::Local obj = value->ToObject(isolate->GetCurrentContext()).ToLocalChecked(); + v8::Local attrNames = obj->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocalChecked(); if (!attrNames.IsEmpty()) { uint32_t size = attrNames->Length(); for (uint32_t i = 0; i < size; i++) { - se::Value e; + se::Value e; v8::Local attrName = attrNames->Get(isolate->GetCurrentContext(), i) .ToLocalChecked() ->ToString(isolate->GetCurrentContext()) @@ -596,14 +596,14 @@ bool ScriptEngine::init(v8::Isolate *isolate) { _beforeInitHookArray.clear(); if (isolate != nullptr) { - _isolate = isolate; + _isolate = isolate; v8::Local context = _isolate->GetCurrentContext(); _context.Reset(_isolate, context); _context.Get(isolate)->Enter(); } else { v8::Isolate::CreateParams createParams; createParams.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); - _isolate = v8::Isolate::New(createParams); + _isolate = v8::Isolate::New(createParams); v8::HandleScope hs(_isolate); _context.Reset(_isolate, v8::Context::New(_isolate)); _context.Get(_isolate)->Enter(); @@ -666,9 +666,9 @@ void ScriptEngine::cleanup() { } _isolate->Dispose(); - _isolate = nullptr; + _isolate = nullptr; _globalObj = nullptr; - _isValid = false; + _isValid = false; _registerCallbackArray.clear(); @@ -716,8 +716,8 @@ void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) { bool ScriptEngine::callRegisteredCallback() { se::AutoHandleScope hs; - bool ok = false; - _startTime = std::chrono::steady_clock::now(); + bool ok = false; + _startTime = std::chrono::steady_clock::now(); for (auto cb : _permRegisterCallbackArray) { ok = cb(_globalObj); @@ -751,7 +751,7 @@ bool ScriptEngine::start() { #if SE_ENABLE_INSPECTOR && !CC_EDITOR // V8 inspector stuff, most code are taken from NodeJS. _isolateData = node::CreateIsolateData(_isolate, uv_default_loop()); - _env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr); + _env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr); node::DebugOptions options; options.set_wait_for_connect(_isWaitForConnect); // the program will be hung up until debug attach if _isWaitForConnect = true @@ -810,9 +810,9 @@ bool ScriptEngine::evalString(const char *script, uint32_t length /* = 0 */, Val } // Fix the source url is too long displayed in Chrome debugger. - ccstd::string sourceUrl = fileName; + ccstd::string sourceUrl = fileName; static const ccstd::string PREFIX_KEY = "/temp/quick-scripts/"; - size_t prefixPos = sourceUrl.find(PREFIX_KEY); + size_t prefixPos = sourceUrl.find(PREFIX_KEY); if (prefixPos != ccstd::string::npos) { sourceUrl = sourceUrl.substr(prefixPos + PREFIX_KEY.length()); } @@ -820,7 +820,7 @@ bool ScriptEngine::evalString(const char *script, uint32_t length /* = 0 */, Val // It is needed, or will crash if invoked from non C++ context, such as invoked from objective-c context(for example, handler of UIKit). v8::HandleScope handleScope(_isolate); - ccstd::string scriptStr(script, length); + ccstd::string scriptStr(script, length); v8::MaybeLocal source = v8::String::NewFromUtf8(_isolate, scriptStr.c_str(), v8::NewStringType::kNormal); if (source.IsEmpty()) { return false; @@ -831,7 +831,7 @@ bool ScriptEngine::evalString(const char *script, uint32_t length /* = 0 */, Val return false; } - v8::ScriptOrigin origin(_isolate, originStr.ToLocalChecked()); + v8::ScriptOrigin origin(_isolate, originStr.ToLocalChecked()); v8::MaybeLocal maybeScript = v8::Script::Compile(_context.Get(_isolate), source.ToLocalChecked(), &origin); bool success = false; @@ -839,7 +839,7 @@ bool ScriptEngine::evalString(const char *script, uint32_t length /* = 0 */, Val if (!maybeScript.IsEmpty()) { v8::TryCatch block(_isolate); - v8::Local v8Script = maybeScript.ToLocalChecked(); + v8::Local v8Script = maybeScript.ToLocalChecked(); v8::MaybeLocal maybeResult = v8Script->Run(_context.Get(_isolate)); if (!maybeResult.IsEmpty()) { @@ -870,7 +870,7 @@ ccstd::string ScriptEngine::getCurrentStackTrace() { return ccstd::string(); } - v8::HandleScope hs(_isolate); + v8::HandleScope hs(_isolate); v8::Local stack = v8::StackTrace::CurrentStackTrace(_isolate, JSB_STACK_FRAME_LIMIT, v8::StackTrace::kOverview); return stackTraceToString(stack); } @@ -884,8 +884,8 @@ const ScriptEngine::FileOperationDelegate &ScriptEngine::getFileOperationDelegat } bool ScriptEngine::saveByteCodeToFile(const ccstd::string &path, const ccstd::string &pathBc) { - bool success = false; - auto *fu = cc::FileUtils::getInstance(); + bool success = false; + auto *fu = cc::FileUtils::getInstance(); if (pathBc.length() > 3 && pathBc.substr(pathBc.length() - 3) != ".bc") { SE_LOGE("ScriptEngine::generateByteCode bytecode file path should endwith \".bc\"\n"); @@ -909,7 +909,7 @@ bool ScriptEngine::saveByteCodeToFile(const ccstd::string &path, const ccstd::st return false; } ccstd::string pathBcDir = pathBc.substr(0, lastSep); - success = fu->createDirectory(pathBcDir); + success = fu->createDirectory(pathBcDir); if (!success) { SE_LOGE("ScriptEngine::generateByteCode failed to create bytecode for %s\n", path.c_str()); return success; @@ -917,15 +917,15 @@ bool ScriptEngine::saveByteCodeToFile(const ccstd::string &path, const ccstd::st } // load script file - ccstd::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path); - v8::Local code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, static_cast(scriptBuffer.length())).ToLocalChecked(); - v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, path.data(), v8::NewStringType::kNormal).ToLocalChecked(); + ccstd::string scriptBuffer = _fileOperationDelegate.onGetStringFromFile(path); + v8::Local code = v8::String::NewFromUtf8(_isolate, scriptBuffer.c_str(), v8::NewStringType::kNormal, static_cast(scriptBuffer.length())).ToLocalChecked(); + v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, path.data(), v8::NewStringType::kNormal).ToLocalChecked(); // create unbound script - v8::ScriptOrigin origin(_isolate, scriptPath); - v8::ScriptCompiler::Source source(code, origin); - v8::Local parsingContext = v8::Local::New(_isolate, _context); - v8::Context::Scope parsingScope(parsingContext); - v8::TryCatch tryCatch(_isolate); + v8::ScriptOrigin origin(_isolate, scriptPath); + v8::ScriptCompiler::Source source(code, origin); + v8::Local parsingContext = v8::Local::New(_isolate, _context); + v8::Context::Scope parsingScope(parsingContext); + v8::TryCatch tryCatch(_isolate); v8::Local v8Script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kEagerCompile) .ToLocalChecked(); // create CachedData @@ -947,26 +947,26 @@ bool ScriptEngine::runByteCodeFile(const ccstd::string &pathBc, Value *ret /* = fu->getContents(pathBc, &cachedData); // read origin source file length from .bc file - uint8_t *p = cachedData.getBytes() + 8; - int filesize = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24); + uint8_t *p = cachedData.getBytes() + 8; + int filesize = p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24); { // fix bytecode - v8::HandleScope scope(_isolate); - v8::Local dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked(); - v8::ScriptCompiler::Source dummySource(dummyBytecodeSource); - v8::Local dummyFunction = v8::ScriptCompiler::CompileUnboundScript(_isolate, &dummySource, v8::ScriptCompiler::kEagerCompile).ToLocalChecked(); - v8::ScriptCompiler::CachedData *dummyData = v8::ScriptCompiler::CreateCodeCache(dummyFunction); + v8::HandleScope scope(_isolate); + v8::Local dummyBytecodeSource = v8::String::NewFromUtf8(_isolate, "\" \"", v8::NewStringType::kNormal).ToLocalChecked(); + v8::ScriptCompiler::Source dummySource(dummyBytecodeSource); + v8::Local dummyFunction = v8::ScriptCompiler::CompileUnboundScript(_isolate, &dummySource, v8::ScriptCompiler::kEagerCompile).ToLocalChecked(); + v8::ScriptCompiler::CachedData *dummyData = v8::ScriptCompiler::CreateCodeCache(dummyFunction); memcpy(p + 4, dummyData->data + 12, 4); // delete dummyData; //NOTE: managed by v8 } // setup ScriptOrigin v8::Local scriptPath = v8::String::NewFromUtf8(_isolate, pathBc.data(), v8::NewStringType::kNormal).ToLocalChecked(); - v8::ScriptOrigin origin(_isolate, scriptPath, 0, 0, true); + v8::ScriptOrigin origin(_isolate, scriptPath, 0, 0, true); // restore CacheData - auto * v8CacheData = ccnew v8::ScriptCompiler::CachedData(cachedData.getBytes(), static_cast(cachedData.getSize())); + auto *v8CacheData = ccnew v8::ScriptCompiler::CachedData(cachedData.getBytes(), static_cast(cachedData.getSize())); v8::Local dummyCode; // generate dummy code @@ -974,10 +974,10 @@ bool ScriptEngine::runByteCodeFile(const ccstd::string &pathBc, Value *ret /* = ccstd::vector codeBuffer; codeBuffer.resize(filesize + 1); std::fill(codeBuffer.begin(), codeBuffer.end(), ' '); - codeBuffer[0] = '\"'; + codeBuffer[0] = '\"'; codeBuffer[filesize - 1] = '\"'; - codeBuffer[filesize] = '\0'; - dummyCode = v8::String::NewFromUtf8(_isolate, codeBuffer.data(), v8::NewStringType::kNormal, filesize).ToLocalChecked(); + codeBuffer[filesize] = '\0'; + dummyCode = v8::String::NewFromUtf8(_isolate, codeBuffer.data(), v8::NewStringType::kNormal, filesize).ToLocalChecked(); CC_ASSERT(dummyCode->Length() == filesize); } @@ -989,7 +989,7 @@ bool ScriptEngine::runByteCodeFile(const ccstd::string &pathBc, Value *ret /* = return false; } - v8::TryCatch tryCatch(_isolate); + v8::TryCatch tryCatch(_isolate); v8::Local v8Script = v8::ScriptCompiler::CompileUnboundScript(_isolate, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); @@ -1003,8 +1003,8 @@ bool ScriptEngine::runByteCodeFile(const ccstd::string &pathBc, Value *ret /* = return false; } - v8::Local runnableScript = v8Script->BindToCurrentContext(); - v8::MaybeLocal result = runnableScript->Run(_context.Get(_isolate)); + v8::Local runnableScript = v8Script->BindToCurrentContext(); + v8::MaybeLocal result = runnableScript->Run(_context.Get(_isolate)); if (result.IsEmpty()) { SE_LOGE("ScriptEngine::runByteCodeFile script %s, failed!\n", pathBc.c_str()); @@ -1051,9 +1051,9 @@ void ScriptEngine::clearException() { } void ScriptEngine::throwException(const ccstd::string &errorMessage) { - v8::HandleScope scope(_isolate); + v8::HandleScope scope(_isolate); v8::Local message = v8::String::NewFromUtf8(_isolate, errorMessage.data()).ToLocalChecked(); - v8::Local error = v8::Exception::Error(message); + v8::Local error = v8::Exception::Error(message); _isolate->ThrowException(error); } @@ -1072,7 +1072,7 @@ v8::Local ScriptEngine::_getContext() const { //NOLINT(readability- void ScriptEngine::enableDebugger(const ccstd::string &serverAddr, uint32_t port, bool isWait) { _debuggerServerAddr = serverAddr; _debuggerServerPort = port; - _isWaitForConnect = isWait; + _isWaitForConnect = isWait; } bool ScriptEngine::isDebuggerEnabled() const { @@ -1095,9 +1095,9 @@ bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_ return false; } - v8::Local nameValToLocal = nameValue.ToLocalChecked(); - v8::Local context = _isolate->GetCurrentContext(); - v8::Local localObj = targetObj->_obj.handle(_isolate); + v8::Local nameValToLocal = nameValue.ToLocalChecked(); + v8::Local context = _isolate->GetCurrentContext(); + v8::Local localObj = targetObj->_obj.handle(_isolate); v8::MaybeLocal funcVal = localObj->Get(context, nameValToLocal); if (funcVal.IsEmpty()) { @@ -1126,7 +1126,7 @@ bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_ } v8::MaybeLocal funcObj = funcVal.ToLocalChecked()->ToObject(context); - v8::MaybeLocal result = funcObj.ToLocalChecked()->CallAsFunction(_getContext(), localObj, argc, argv.data()); + v8::MaybeLocal result = funcObj.ToLocalChecked()->CallAsFunction(_getContext(), localObj, argc, argv.data()); #if CC_DEBUG if (tryCatch.HasCaught()) { @@ -1155,7 +1155,7 @@ ScriptEngine::VMStringPool::~VMStringPool() = default; v8::MaybeLocal ScriptEngine::VMStringPool::get(v8::Isolate *isolate, const char *name) { v8::Local ret; - auto iter = _vmStringPoolMap.find(name); + auto iter = _vmStringPoolMap.find(name); if (iter == _vmStringPoolMap.end()) { v8::MaybeLocal nameValue = v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kNormal); if (!nameValue.IsEmpty()) { diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.h b/native/cocos/bindings/jswrapper/v8/ScriptEngine.h index f5e091fcda..c1f804df66 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.h @@ -332,17 +332,17 @@ public: VMStringPool(); ~VMStringPool(); v8::MaybeLocal get(v8::Isolate *isolate, const char *name); - void clear(); + void clear(); private: ccstd::unordered_map *> _vmStringPoolMap; }; - inline VMStringPool & _getStringPool() { return _stringPool; } // NOLINT(readability-identifier-naming) - void _retainScriptObject(void *owner, void *target); // NOLINT(readability-identifier-naming) - void _releaseScriptObject(void *owner, void *target); // NOLINT(readability-identifier-naming) - v8::Local _getContext() const; // NOLINT(readability-identifier-naming) - void _setGarbageCollecting(bool isGarbageCollecting); // NOLINT(readability-identifier-naming) + inline VMStringPool &_getStringPool() { return _stringPool; } // NOLINT(readability-identifier-naming) + void _retainScriptObject(void *owner, void *target); // NOLINT(readability-identifier-naming) + void _releaseScriptObject(void *owner, void *target); // NOLINT(readability-identifier-naming) + v8::Local _getContext() const; // NOLINT(readability-identifier-naming) + void _setGarbageCollecting(bool isGarbageCollecting); // NOLINT(readability-identifier-naming) // private: @@ -375,24 +375,24 @@ private: ccstd::vector>, ccstd::vector>> _promiseArray; std::chrono::steady_clock::time_point _startTime; - ccstd::vector _registerCallbackArray; - ccstd::vector _permRegisterCallbackArray; - ccstd::vector> _beforeInitHookArray; - ccstd::vector> _afterInitHookArray; - ccstd::vector> _beforeCleanupHookArray; - ccstd::vector> _afterCleanupHookArray; + ccstd::vector _registerCallbackArray; + ccstd::vector _permRegisterCallbackArray; + ccstd::vector> _beforeInitHookArray; + ccstd::vector> _afterInitHookArray; + ccstd::vector> _beforeCleanupHookArray; + ccstd::vector> _afterCleanupHookArray; v8::Persistent _context; - v8::Isolate * _isolate; + v8::Isolate *_isolate; v8::HandleScope *_handleScope; - Object * _globalObj; - Value _gcFuncValue; - Object * _gcFunc = nullptr; + Object *_globalObj; + Value _gcFuncValue; + Object *_gcFunc = nullptr; FileOperationDelegate _fileOperationDelegate; - ExceptionCallback _nativeExceptionCallback = nullptr; - ExceptionCallback _jsExceptionCallback = nullptr; + ExceptionCallback _nativeExceptionCallback = nullptr; + ExceptionCallback _jsExceptionCallback = nullptr; #if SE_ENABLE_INSPECTOR node::Environment *_env; @@ -401,10 +401,10 @@ private: VMStringPool _stringPool; std::thread::id _engineThreadId; - ccstd::string _lastStackTrace; - ccstd::string _debuggerServerAddr; - uint32_t _debuggerServerPort; - bool _isWaitForConnect; + ccstd::string _lastStackTrace; + ccstd::string _debuggerServerAddr; + uint32_t _debuggerServerPort; + bool _isWaitForConnect; uint32_t _vmId; diff --git a/native/cocos/bindings/jswrapper/v8/Utils.cpp b/native/cocos/bindings/jswrapper/v8/Utils.cpp index 79cc410a03..eefa0c6704 100644 --- a/native/cocos/bindings/jswrapper/v8/Utils.cpp +++ b/native/cocos/bindings/jswrapper/v8/Utils.cpp @@ -125,8 +125,8 @@ void jsToSeValue(v8::Isolate *isolate, v8::Local jsval, Value *v) { v8::MaybeLocal jsObj = jsval->ToObject(isolate->GetCurrentContext()); if (!jsObj.IsEmpty()) { PrivateObjectBase *privateObject = static_cast(internal::getPrivate(isolate, jsObj.ToLocalChecked(), 0)); - void * nativePtr = privateObject ? privateObject->getRaw() : nullptr; - Object * obj = nullptr; + void *nativePtr = privateObject ? privateObject->getRaw() : nullptr; + Object *obj = nullptr; if (nativePtr != nullptr) { obj = Object::getObjectWithPtr(nativePtr); } @@ -180,7 +180,7 @@ bool hasPrivate(v8::Isolate * /*isolate*/, v8::Local value) { void setPrivate(v8::Isolate *isolate, ObjectWrap &wrap, PrivateObjectBase *data, Object *thizObj, PrivateData **outInternalData) { v8::Local obj = wrap.handle(isolate); - int c = obj->InternalFieldCount(); + int c = obj->InternalFieldCount(); CC_ASSERT(c > 1); if (c > 1) { wrap.wrap(data, 0); @@ -193,8 +193,8 @@ void setPrivate(v8::Isolate *isolate, ObjectWrap &wrap, PrivateObjectBase *data, } void *getPrivate(v8::Isolate *isolate, v8::Local value, uint32_t index /* = 0*/) { - v8::Local context = isolate->GetCurrentContext(); - v8::MaybeLocal obj = value->ToObject(context); + v8::Local context = isolate->GetCurrentContext(); + v8::MaybeLocal obj = value->ToObject(context); if (obj.IsEmpty()) { return nullptr; } @@ -205,7 +205,7 @@ void *getPrivate(v8::Isolate *isolate, v8::Local value, uint32_t inde } v8::Local objChecked = obj.ToLocalChecked(); - int c = objChecked->InternalFieldCount(); + int c = objChecked->InternalFieldCount(); if (c > 1) { void *nativeObj = nullptr; if (index >= 0 && index < 2) { @@ -220,7 +220,7 @@ void *getPrivate(v8::Isolate *isolate, v8::Local value, uint32_t inde void clearPrivate(v8::Isolate *isolate, ObjectWrap &wrap) { v8::Local obj = wrap.handle(isolate); - int c = obj->InternalFieldCount(); + int c = obj->InternalFieldCount(); if (c > 1) { wrap.wrap(nullptr, 0); wrap.wrap(nullptr, 1); diff --git a/native/cocos/bindings/jswrapper/v8/Utils.h b/native/cocos/bindings/jswrapper/v8/Utils.h index b36548f8d8..de328e01bc 100644 --- a/native/cocos/bindings/jswrapper/v8/Utils.h +++ b/native/cocos/bindings/jswrapper/v8/Utils.h @@ -40,7 +40,7 @@ namespace internal { struct PrivateData { PrivateObjectBase *data{nullptr}; - Object * seObj{nullptr}; + Object *seObj{nullptr}; }; void jsToSeArgs(const v8::FunctionCallbackInfo &_v8args, ValueArray &outArr); @@ -51,10 +51,10 @@ void seToJsValue(v8::Isolate *isolate, const Value &v, v8::Local *out void setReturnValue(const Value &data, const v8::FunctionCallbackInfo &argv); void setReturnValue(const Value &data, const v8::PropertyCallbackInfo &argv); -bool hasPrivate(v8::Isolate *isolate, v8::Local value); -void setPrivate(v8::Isolate *isolate, ObjectWrap &wrap, PrivateObjectBase *data, Object *obj, PrivateData **outInternalData); +bool hasPrivate(v8::Isolate *isolate, v8::Local value); +void setPrivate(v8::Isolate *isolate, ObjectWrap &wrap, PrivateObjectBase *data, Object *obj, PrivateData **outInternalData); void *getPrivate(v8::Isolate *isolate, v8::Local value, uint32_t index = 0); -void clearPrivate(v8::Isolate *isolate, ObjectWrap &wrap); +void clearPrivate(v8::Isolate *isolate, ObjectWrap &wrap); } // namespace internal } // namespace se diff --git a/native/cocos/bindings/jswrapper/v8/debugger/base64.h b/native/cocos/bindings/jswrapper/v8/debugger/base64.h index 929a3a6dba..37753d8286 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/base64.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/base64.h @@ -56,7 +56,7 @@ bool base64_decode_group_slow(char *const dst, const size_t dstlen, #define V(expr) \ for (;;) { \ const uint8_t c = src[*i]; \ - lo = unbase64(c); \ + lo = unbase64(c); \ *i += 1; \ if (lo < 64) \ break; /* Legal character. */ \ @@ -82,10 +82,10 @@ size_t base64_decode_fast(char *const dst, const size_t dstlen, const TypeName *const src, const size_t srclen, const size_t decoded_size) { const size_t available = dstlen < decoded_size ? dstlen : decoded_size; - const size_t max_k = available / 3 * 3; - size_t max_i = srclen / 4 * 4; - size_t i = 0; - size_t k = 0; + const size_t max_k = available / 3 * 3; + size_t max_i = srclen / 4 * 4; + size_t i = 0; + size_t k = 0; while (i < max_i && k < max_k) { const uint32_t v = unbase64(src[i + 0]) << 24 | @@ -119,9 +119,9 @@ size_t base64_decode(char *const dst, const size_t dstlen, } static size_t base64_encode(const char *src, - size_t slen, - char * dst, - size_t dlen) { + size_t slen, + char *dst, + size_t dlen) { // We know how much we'll write, just make sure that there's space. CHECK(dlen >= base64_encoded_size(slen) && "not enough space provided for base64 encode"); @@ -161,7 +161,7 @@ static size_t base64_encode(const char *src, if (n != slen) { switch (slen - n) { case 1: - a = src[i + 0] & 0xff; + a = src[i + 0] & 0xff; dst[k + 0] = table[a >> 2]; dst[k + 1] = table[(a & 3) << 4]; dst[k + 2] = '='; @@ -169,8 +169,8 @@ static size_t base64_encode(const char *src, break; case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; dst[k + 0] = table[a >> 2]; dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; dst[k + 2] = table[(b & 0x0f) << 2]; diff --git a/native/cocos/bindings/jswrapper/v8/debugger/env.h b/native/cocos/bindings/jswrapper/v8/debugger/env.h index a39d890f42..0ee5e0df23 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/env.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/env.h @@ -406,7 +406,6 @@ private: inline IsolateData::IsolateData(v8::Isolate *isolate, uv_loop_t *event_loop, uint32_t *zero_fill_field) : - // Create string and private symbol properties as internalized one byte strings. // // Internalized because it makes property lookups a little faster and because diff --git a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp index 422e4aae5e..b1ccaa2f42 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.cpp @@ -614,20 +614,20 @@ parse_url_char(enum state s, const char ch) { //NOLINT return s_dead; } //NOLINTNEXTLINE -size_t http_parser_execute(http_parser * parser, +size_t http_parser_execute(http_parser *parser, const http_parser_settings *settings, - const char * data, - size_t len) { - char c, ch; //NOLINT - int8_t unhex_val; //NOLINT - const char * p = data; - const char * header_field_mark = nullptr; - const char * header_value_mark = nullptr; - const char * url_mark = nullptr; - const char * body_mark = nullptr; - const char * status_mark = nullptr; - auto p_state = static_cast(parser->state); - const unsigned int lenient = parser->lenient_http_headers; + const char *data, + size_t len) { + char c, ch; //NOLINT + int8_t unhex_val; //NOLINT + const char *p = data; + const char *header_field_mark = nullptr; + const char *header_value_mark = nullptr; + const char *url_mark = nullptr; + const char *body_mark = nullptr; + const char *status_mark = nullptr; + auto p_state = static_cast(parser->state); + const unsigned int lenient = parser->lenient_http_headers; /* We're in an error state. Don't bother doing anything. */ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { @@ -706,7 +706,7 @@ size_t http_parser_execute(http_parser * parser, if (ch == CR || ch == LF) { break; } - parser->flags = 0; + parser->flags = 0; parser->content_length = ULLONG_MAX; if (ch == 'H') { @@ -732,15 +732,15 @@ size_t http_parser_execute(http_parser * parser, goto error; } - parser->type = HTTP_REQUEST; + parser->type = HTTP_REQUEST; parser->method = HTTP_HEAD; - parser->index = 2; + parser->index = 2; UPDATE_STATE(s_req_method); } break; case s_start_res: { - parser->flags = 0; + parser->flags = 0; parser->content_length = ULLONG_MAX; switch (ch) { @@ -933,7 +933,7 @@ size_t http_parser_execute(http_parser * parser, if (ch == CR || ch == LF) { break; } - parser->flags = 0; + parser->flags = 0; parser->content_length = ULLONG_MAX; if (UNLIKELY(!IS_ALPHA(ch))) { @@ -942,7 +942,7 @@ size_t http_parser_execute(http_parser * parser, } parser->method = static_cast(0); - parser->index = 1; + parser->index = 1; switch (ch) { case 'A': parser->method = HTTP_ACL; break; case 'B': parser->method = HTTP_BIND; break; @@ -1280,7 +1280,7 @@ size_t http_parser_execute(http_parser * parser, const char *start = p; for (; p != data + len; p++) { ch = *p; - c = TOKEN(ch); + c = TOKEN(ch); if (!c) { break; @@ -1478,8 +1478,8 @@ size_t http_parser_execute(http_parser * parser, } case s_header_value: { - const char *start = p; - auto hState = static_cast(parser->header_state); + const char *start = p; + auto hState = static_cast(parser->header_state); for (; p != data + len; p++) { ch = *p; if (ch == CR) { @@ -1508,7 +1508,7 @@ size_t http_parser_execute(http_parser * parser, case h_general: { const char *pCr; const char *pLf; - size_t limit = data + len - p; + size_t limit = data + len - p; limit = MIN(limit, HTTP_MAX_HEADER_SIZE); @@ -1622,7 +1622,7 @@ size_t http_parser_execute(http_parser * parser, case h_matching_connection_token: if (ch == ',') { - hState = h_matching_connection_token_start; + hState = h_matching_connection_token_start; parser->index = 0; } break; @@ -1642,7 +1642,7 @@ size_t http_parser_execute(http_parser * parser, } else if (hState == h_connection_upgrade) { parser->flags |= F_CONNECTION_UPGRADE; } - hState = h_matching_connection_token_start; + hState = h_matching_connection_token_start; parser->index = 0; } else if (ch != ' ') { hState = h_matching_connection_token; @@ -2091,9 +2091,9 @@ http_method_str(enum http_method m) { //NOLINT void http_parser_init(http_parser *parser, enum http_parser_type t) { //NOLINT void *data = parser->data; /* preserve application data */ memset(parser, 0, sizeof(*parser)); - parser->data = data; - parser->type = t; - parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); + parser->data = data; + parser->type = t; + parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); parser->http_errno = HPE_OK; } @@ -2201,7 +2201,7 @@ http_parse_host(const char *buf, struct http_parser_url *u, int found_at) { //NO enum http_host_state s; const char *p; - size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; + size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; u->field_data[UF_HOST].len = 0; @@ -2282,14 +2282,14 @@ void http_parser_url_init(struct http_parser_url *u) { //NOLINT int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, //NOLINT struct http_parser_url *u) { - enum state s; - const char * p; - enum http_parser_url_fields uf, old_uf; //NOLINT - int found_at = 0; //NOLINT + enum state s; + const char *p; + enum http_parser_url_fields uf, old_uf; //NOLINT + int found_at = 0; //NOLINT u->port = u->field_set = 0; - s = is_connect ? s_req_server_start : s_req_spaces_before_url; - old_uf = UF_MAX; + s = is_connect ? s_req_server_start : s_req_spaces_before_url; + old_uf = UF_MAX; for (p = buf; p < buf + buflen; p++) { s = parse_url_char(s, *p); diff --git a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h index 14b908e84e..33cb4bd111 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/http_parser.h @@ -38,13 +38,13 @@ extern "C" { (!defined(_MSC_VER) || _MSC_VER < 1600) && !defined(__WINE__) #include #include -typedef __int8 int8_t; -typedef unsigned __int8 uint8_t; -typedef __int16 int16_t; +typedef __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef __int16 int16_t; typedef unsigned __int16 uint16_t; -typedef __int32 int32_t; +typedef __int32 int32_t; typedef unsigned __int32 uint32_t; -typedef __int64 int64_t; +typedef __int64 int64_t; typedef unsigned __int64 uint64_t; #else #include @@ -68,7 +68,7 @@ typedef unsigned __int64 uint64_t; #define HTTP_MAX_HEADER_SIZE (80 * 1024) #endif -using http_parser = struct http_parser; +using http_parser = struct http_parser; using http_parser_settings = struct http_parser_settings; /* Callbacks should return non-zero to indicate an error. The parser will @@ -90,7 +90,7 @@ using http_parser_settings = struct http_parser_settings; * each providing just a few characters more data. */ using http_data_cb = int (*)(http_parser *, const char *, size_t); -using http_cb = int (*)(http_parser *); +using http_cb = int (*)(http_parser *); /* Request Methods */ #define HTTP_METHOD_MAP(XX) \ @@ -146,14 +146,14 @@ enum http_parser_type { HTTP_REQUEST, //NOLINT(readability-identifier-naming) HTTP_BOTH }; /* Flag values for http_parser.flags field */ -enum flags { F_CHUNKED = 1 << 0, //NOLINT(readability-identifier-naming) +enum flags { F_CHUNKED = 1 << 0, //NOLINT(readability-identifier-naming) F_CONNECTION_KEEP_ALIVE = 1 << 1, - F_CONNECTION_CLOSE = 1 << 2, - F_CONNECTION_UPGRADE = 1 << 3, - F_TRAILING = 1 << 4, - F_UPGRADE = 1 << 5, - F_SKIPBODY = 1 << 6, - F_CONTENTLENGTH = 1 << 7 + F_CONNECTION_CLOSE = 1 << 2, + F_CONNECTION_UPGRADE = 1 << 3, + F_TRAILING = 1 << 4, + F_UPGRADE = 1 << 5, + F_SKIPBODY = 1 << 6, + F_CONTENTLENGTH = 1 << 7 }; /* Map for errno-related constants @@ -228,11 +228,11 @@ struct http_parser { uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ /** READ-ONLY **/ - unsigned short http_major; //NOLINT(google-runtime-int) - unsigned short http_minor; //NOLINT(google-runtime-int) - unsigned int status_code : 16; /* responses only */ - unsigned int method : 8; /* requests only */ - unsigned int http_errno : 7; + unsigned short http_major; //NOLINT(google-runtime-int) + unsigned short http_minor; //NOLINT(google-runtime-int) + unsigned int status_code : 16; /* responses only */ + unsigned int method : 8; /* requests only */ + unsigned int http_errno : 7; /* 1 = Upgrade header was present and the parser has exited because of that. * 0 = No upgrade header present. @@ -246,14 +246,14 @@ struct http_parser { }; struct http_parser_settings { - http_cb on_message_begin; + http_cb on_message_begin; http_data_cb on_url; http_data_cb on_status; http_data_cb on_header_field; http_data_cb on_header_value; - http_cb on_headers_complete; + http_cb on_headers_complete; http_data_cb on_body; - http_cb on_message_complete; + http_cb on_message_complete; /* When on_chunk_header is called, the current chunk length is stored * in parser->content_length. */ @@ -261,14 +261,14 @@ struct http_parser_settings { http_cb on_chunk_complete; }; -enum http_parser_url_fields { UF_SCHEMA = 0, //NOLINT(readability-identifier-naming) - UF_HOST = 1, - UF_PORT = 2, - UF_PATH = 3, - UF_QUERY = 4, +enum http_parser_url_fields { UF_SCHEMA = 0, //NOLINT(readability-identifier-naming) + UF_HOST = 1, + UF_PORT = 2, + UF_PATH = 3, + UF_QUERY = 4, UF_FRAGMENT = 5, UF_USERINFO = 6, - UF_MAX = 7 + UF_MAX = 7 }; /* Result structure for http_parser_parse_url(). @@ -308,10 +308,10 @@ void http_parser_settings_init(http_parser_settings *settings); //NOLINT(readabi /* Executes the parser. Returns number of parsed bytes. Sets * `parser->http_errno` on error. */ -size_t http_parser_execute(http_parser * parser, //NOLINT(readability-identifier-naming) +size_t http_parser_execute(http_parser *parser, //NOLINT(readability-identifier-naming) const http_parser_settings *settings, - const char * data, - size_t len); + const char *data, + size_t len); /* If http_should_keep_alive() in the on_headers_complete or * on_message_complete callback returns 0, then this should be @@ -334,8 +334,8 @@ const char *http_errno_description(enum http_errno err); //NOLINT(readability-id void http_parser_url_init(struct http_parser_url *u); //NOLINT(readability-identifier-naming) /* Parse a URL; return nonzero on failure */ -int http_parser_parse_url(const char *buf, size_t buflen, //NOLINT(readability-identifier-naming) - int is_connect, //NOLINT(readability-identifier-naming) +int http_parser_parse_url(const char *buf, size_t buflen, //NOLINT(readability-identifier-naming) + int is_connect, //NOLINT(readability-identifier-naming) struct http_parser_url *u); /* Pause or un-pause the parser; a nonzero value pauses */ diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp b/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp index fcf0c7caa1..942b212f9d 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp @@ -43,7 +43,7 @@ using v8_inspector::StringView; using v8_inspector::V8Inspector; using v8_inspector::V8InspectorClient; -static uv_sem_t start_io_thread_semaphore; +static uv_sem_t start_io_thread_semaphore; static uv_async_t start_io_thread_async; class StartIoTask : public v8::Task { @@ -58,7 +58,7 @@ private: Agent *agent; }; -std::unique_ptr ToProtocolString(Isolate * isolate, +std::unique_ptr ToProtocolString(Isolate *isolate, Local value) { TwoByteValue buffer(isolate, value); return StringBuffer::create(StringView(*buffer, buffer.length())); @@ -143,9 +143,9 @@ static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t *buf, } static int StartDebugSignalHandler() { - wchar_t mapping_name[32]; - HANDLE mapping_handle; - DWORD pid; + wchar_t mapping_name[32]; + HANDLE mapping_handle; + DWORD pid; LPTHREAD_START_ROUTINE *handler; pid = GetCurrentProcessId(); @@ -187,9 +187,9 @@ static int StartDebugSignalHandler() { class JsBindingsSessionDelegate : public InspectorSessionDelegate { public: - JsBindingsSessionDelegate(Environment * env, - Local session, - Local receiver, + JsBindingsSessionDelegate(Environment *env, + Local session, + Local receiver, Local callback) : env_(env), session_(env->isolate(), session), @@ -210,15 +210,15 @@ public: } void SendMessageToFrontend(const v8_inspector::StringView &message) override { - Isolate * isolate = env_->isolate(); - v8::HandleScope handle_scope(isolate); - Context::Scope context_scope(env_->context()); + Isolate *isolate = env_->isolate(); + v8::HandleScope handle_scope(isolate); + Context::Scope context_scope(env_->context()); MaybeLocal v8string = String::NewFromTwoByte(isolate, message.characters16(), NewStringType::kNormal, static_cast(message.length())); - Local argument = v8string.ToLocalChecked().As(); + Local argument = v8string.ToLocalChecked().As(); Local callback = callback_.Get(isolate); - Local receiver = receiver_.Get(isolate); + Local receiver = receiver_.Get(isolate); callback->Call(env_->context(), receiver, 1, &argument) .FromMaybe(Local()); } @@ -243,9 +243,9 @@ private: delete delegate; } - Environment * env_; - Persistent session_; - Persistent receiver_; + Environment *env_; + Persistent session_; + Persistent receiver_; Persistent callback_; }; @@ -258,8 +258,8 @@ void SetDelegate(Environment *env, Local inspector, Maybe GetDelegate( const FunctionCallbackInfo &info) { - Environment * env = Environment::GetCurrent(info); - Local delegate; + Environment *env = Environment::GetCurrent(info); + Local delegate; MaybeLocal maybe_delegate = info.This()->GetPrivate(env->context(), env->inspector_delegate_private_symbol()); @@ -290,7 +290,7 @@ void Dispatch(const FunctionCallbackInfo &info) { } void Disconnect(const FunctionCallbackInfo &info) { - Environment * env = Environment::GetCurrent(info); + Environment *env = Environment::GetCurrent(info); Maybe delegate = GetDelegate(info); if (delegate.IsNothing()) { return; @@ -324,8 +324,8 @@ void ConnectJSBindingsSession(const FunctionCallbackInfo &info) { } void InspectorConsoleCall(const v8::FunctionCallbackInfo &info) { - Isolate * isolate = info.GetIsolate(); - HandleScope handle_scope(isolate); + Isolate *isolate = info.GetIsolate(); + HandleScope handle_scope(isolate); Local context = isolate->GetCurrentContext(); CHECK_LT(2, info.Length()); std::vector> call_args; @@ -339,7 +339,7 @@ void InspectorConsoleCall(const v8::FunctionCallbackInfo &info) { Local config_value = info[2]; CHECK(config_value->IsObject()); Local config_object = config_value.As(); - Local in_call_key = FIXED_ONE_BYTE_STRING(isolate, "in_call"); + Local in_call_key = FIXED_ONE_BYTE_STRING(isolate, "in_call"); if (!config_object->Has(context, in_call_key).FromMaybe(false)) { CHECK(config_object->Set(context, in_call_key, @@ -383,12 +383,12 @@ void CallAndPauseOnStart( } // Used in NodeInspectorClient::currentTimeMS() below. -const int NANOS_PER_MSEC = 1000000; +const int NANOS_PER_MSEC = 1000000; const int CONTEXT_GROUP_ID = 1; class ChannelImpl final : public v8_inspector::V8Inspector::Channel { public: - explicit ChannelImpl(V8Inspector * inspector, + explicit ChannelImpl(V8Inspector *inspector, InspectorSessionDelegate *delegate) : delegate_(delegate) { session_ = inspector->connect(1, this, StringView()); @@ -415,7 +415,7 @@ public: private: void sendResponse( - int callId, + int callId, std::unique_ptr message) override { sendMessageToFrontend(message->string()); } @@ -431,16 +431,16 @@ private: delegate_->SendMessageToFrontend(message); } - InspectorSessionDelegate *const delegate_; + InspectorSessionDelegate *const delegate_; std::unique_ptr session_; }; class InspectorTimer { public: - InspectorTimer(uv_loop_t * loop, - double interval_s, + InspectorTimer(uv_loop_t *loop, + double interval_s, V8InspectorClient::TimerCallback callback, - void * data) : timer_(), + void *data) : timer_(), callback_(callback), data_(data) { uv_timer_init(loop, &timer_); @@ -470,9 +470,9 @@ private: ~InspectorTimer() {} - uv_timer_t timer_; + uv_timer_t timer_; V8InspectorClient::TimerCallback callback_; - void * data_; + void *data_; }; class InspectorTimerHandle { @@ -498,7 +498,7 @@ private: class NodeInspectorClient : public V8InspectorClient { public: NodeInspectorClient(node::Environment *env, - v8::Platform * platform) : env_(env), + v8::Platform *platform) : env_(env), platform_(platform), terminated_(false), running_nested_loop_(false) { @@ -509,13 +509,13 @@ public: CHECK_NE(channel_, nullptr); if (running_nested_loop_) return; - terminated_ = false; + terminated_ = false; running_nested_loop_ = true; while (!terminated_ && channel_->waitForFrontendMessage()) { while (v8::platform::PumpMessageLoop(platform_, env_->isolate())) { } } - terminated_ = false; + terminated_ = false; running_nested_loop_ = false; } @@ -525,7 +525,7 @@ public: void contextCreated(Local context, const std::string &name) { std::unique_ptr name_buffer = Utf8ToStringView(name); - v8_inspector::V8ContextInfo info(context, CONTEXT_GROUP_ID, + v8_inspector::V8ContextInfo info(context, CONTEXT_GROUP_ID, name_buffer->string()); client_->contextCreated(info); } @@ -592,9 +592,9 @@ public: return channel_.get(); } - void startRepeatingTimer(double interval_s, + void startRepeatingTimer(double interval_s, TimerCallback callback, - void * data) override { + void *data) override { timers_.emplace(std::piecewise_construct, std::make_tuple(data), std::make_tuple(env_->event_loop(), interval_s, callback, data)); @@ -605,12 +605,12 @@ public: } private: - node::Environment * env_; - v8::Platform * platform_; - bool terminated_; - bool running_nested_loop_; - std::unique_ptr client_; - std::unique_ptr channel_; + node::Environment *env_; + v8::Platform *platform_; + bool terminated_; + bool running_nested_loop_; + std::unique_ptr client_; + std::unique_ptr channel_; std::unordered_map timers_; }; @@ -626,7 +626,7 @@ Agent::~Agent() { bool Agent::Start(v8::Platform *platform, const char *path, const DebugOptions &options) { - path_ = path == nullptr ? "" : path; + path_ = path == nullptr ? "" : path; debug_options_ = options; client_ = std::unique_ptr( @@ -655,7 +655,7 @@ bool Agent::StartIoThread(bool wait_for_connect) { CHECK_NE(client_, nullptr); enabled_ = true; - io_ = std::unique_ptr( + io_ = std::unique_ptr( new InspectorIo(parent_env_, platform_, path_, debug_options_, wait_for_connect)); if (!io_->Start()) { @@ -666,9 +666,9 @@ bool Agent::StartIoThread(bool wait_for_connect) { v8::Isolate *isolate = parent_env_->isolate(); // Send message to enable debug in workers - HandleScope handle_scope(isolate); + HandleScope handle_scope(isolate); Local process_object = parent_env_->process_object(); - Local emit_fn = + Local emit_fn = process_object->Get(parent_env_->context(), FIXED_ONE_BYTE_STRING(isolate, "emit")).ToLocalChecked(); // In case the thread started early during the startup if (!emit_fn->IsFunction()) @@ -749,9 +749,9 @@ void Agent::PauseOnNextJavascriptStatement(const std::string &reason) { } void Open(const FunctionCallbackInfo &args) { - Environment * env = Environment::GetCurrent(args); - inspector::Agent *agent = env->inspector_agent(); - bool wait_for_connect = false; + Environment *env = Environment::GetCurrent(args); + inspector::Agent *agent = env->inspector_agent(); + bool wait_for_connect = false; if (args.Length() > 0 && args[0]->IsUint32()) { uint32_t port = args[0]->Uint32Value(env->context()).ToChecked(); @@ -771,9 +771,9 @@ void Open(const FunctionCallbackInfo &args) { } void Url(const FunctionCallbackInfo &args) { - Environment * env = Environment::GetCurrent(args); - inspector::Agent * agent = env->inspector_agent(); - inspector::InspectorIo *io = agent->io(); + Environment *env = Environment::GetCurrent(args); + inspector::Agent *agent = env->inspector_agent(); + inspector::InspectorIo *io = agent->io(); if (!io) return; @@ -788,8 +788,8 @@ void Url(const FunctionCallbackInfo &args) { // static void Agent::InitInspector(Local target, Local unused, Local context, void *priv) { - Environment *env = Environment::GetCurrent(context); - Agent * agent = env->inspector_agent(); + Environment *env = Environment::GetCurrent(context); + Agent *agent = env->inspector_agent(); env->SetMethod(target, "consoleCall", InspectorConsoleCall); if (agent->debug_options_.wait_for_connect()) env->SetMethod(target, "callAndPauseOnStart", CallAndPauseOnStart); diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket.cpp b/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket.cpp index 6ed5ed8e69..564e2b6c92 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket.cpp @@ -503,10 +503,11 @@ static int message_complete_cb(http_parser *parser) { state->path)) { char accept_string[ACCEPT_KEY_LENGTH]; generate_accept_string(state->ws_key, &accept_string); - const char accept_ws_prefix[] = "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "Sec-WebSocket-Accept: "; + const char accept_ws_prefix[] = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: "; const char accept_ws_suffix[] = "\r\n\r\n"; std::string reply(accept_ws_prefix, sizeof(accept_ws_prefix) - 1); reply.append(accept_string, sizeof(accept_string)); diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket_server.cpp b/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket_server.cpp index 5defee5b66..dfbeb7de1b 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket_server.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_socket_server.cpp @@ -18,9 +18,9 @@ namespace inspector { // depend on inspector_socket_server.h std::string FormatWsAddress(const std::string &host, int port, const std::string &target_id, - bool include_protocol) { + bool include_protocol) { // Host is valid (socket was bound) so colon means it's a v6 IP address - bool v6 = host.find(':') != std::string::npos; + bool v6 = host.find(':') != std::string::npos; std::ostringstream url; if (include_protocol) url << "ws://"; @@ -55,7 +55,7 @@ void Escape(std::string *string) { } std::string MapToString(const std::map &object) { - bool first = true; + bool first = true; std::ostringstream json; json << "{\n"; for (const auto &name_value : object) { @@ -71,7 +71,7 @@ std::string MapToString(const std::map &object) { std::string MapsToString( const std::vector> &array) { - bool first = true; + bool first = true; std::ostringstream json; json << "[ "; for (const auto &object : array) { @@ -95,13 +95,13 @@ const char *MatchPathSegment(const char *path, const char *expected) { void OnBufferAlloc(uv_handle_t *handle, size_t len, uv_buf_t *buf) { buf->base = new char[len]; - buf->len = len; + buf->len = len; } -void PrintDebuggerReadyMessage(const std::string & host, - int port, +void PrintDebuggerReadyMessage(const std::string &host, + int port, const std::vector &ids, - FILE * out) { + FILE *out) { if (out == NULL) { return; } @@ -109,9 +109,9 @@ void PrintDebuggerReadyMessage(const std::string & host, std::vector> ipList; { - char buf[512]; - uv_interface_address_t *info = nullptr; - int count = 0, i = 0; + char buf[512]; + uv_interface_address_t *info = nullptr; + int count = 0, i = 0; uv_interface_addresses(&info, &count); i = count; @@ -157,14 +157,14 @@ void SendHttpResponse(InspectorSocket *socket, const std::string &response) { "Content-Length: %zu\r\n" "\r\n"; char header[sizeof(HEADERS) + 20]; - int header_len = snprintf(header, sizeof(header), HEADERS, response.size()); + int header_len = snprintf(header, sizeof(header), HEADERS, response.size()); inspector_write(socket, header, header_len); inspector_write(socket, response.data(), response.size()); } void SendVersionResponse(InspectorSocket *socket) { std::map response; - response["Browser"] = "Cocos Games"; //cjh + response["Browser"] = "Cocos Games"; //cjh response["Protocol-Version"] = "1.1"; SendHttpResponse(socket, MapToString(response)); } @@ -172,17 +172,17 @@ void SendVersionResponse(InspectorSocket *socket) { void SendProtocolJson(InspectorSocket *socket) { z_stream strm; strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; + strm.zfree = Z_NULL; strm.opaque = Z_NULL; CHECK_EQ(Z_OK, inflateInit(&strm)); static const size_t kDecompressedSize = PROTOCOL_JSON[0] * 0x10000u + PROTOCOL_JSON[1] * 0x100u + PROTOCOL_JSON[2]; - strm.next_in = const_cast(PROTOCOL_JSON + 3); + strm.next_in = const_cast(PROTOCOL_JSON + 3); strm.avail_in = sizeof(PROTOCOL_JSON) - 3; std::string data(kDecompressedSize, '\0'); - strm.next_out = reinterpret_cast(&data[0]); + strm.next_out = reinterpret_cast(&data[0]); strm.avail_out = static_cast(data.size()); CHECK_EQ(Z_STREAM_END, inflate(&strm, Z_FINISH)); CHECK_EQ(0, strm.avail_out); @@ -191,20 +191,20 @@ void SendProtocolJson(InspectorSocket *socket) { } int GetSocketHost(uv_tcp_t *socket, std::string *out_host) { - char ip[INET6_ADDRSTRLEN]; + char ip[INET6_ADDRSTRLEN]; sockaddr_storage addr; - int len = sizeof(addr); - int err = uv_tcp_getsockname(socket, + int len = sizeof(addr); + int err = uv_tcp_getsockname(socket, reinterpret_cast(&addr), &len); if (err != 0) return err; if (addr.ss_family == AF_INET6) { const sockaddr_in6 *v6 = reinterpret_cast(&addr); - err = uv_ip6_name(v6, ip, sizeof(ip)); + err = uv_ip6_name(v6, ip, sizeof(ip)); } else { const sockaddr_in *v4 = reinterpret_cast(&addr); - err = uv_ip4_name(v4, ip, sizeof(ip)); + err = uv_ip4_name(v4, ip, sizeof(ip)); } if (err != 0) return err; @@ -245,19 +245,19 @@ public: } private: - InspectorSocketServer * server_; + InspectorSocketServer *server_; std::set callbacks_; - int close_count_; + int close_count_; }; class SocketSession { public: static int Accept(InspectorSocketServer *server, int server_port, uv_stream_t *server_socket); - void Send(const std::string &message); - void Close(); + void Send(const std::string &message); + void Close(); - int id() const { return id_; } + int id() const { return id_; } bool IsForTarget(const std::string &target_id) const { return target_id_ == target_id; } @@ -276,9 +276,9 @@ private: kClosing, kEOF, kDeclined }; - static bool HandshakeCallback(InspectorSocket * socket, + static bool HandshakeCallback(InspectorSocket *socket, enum inspector_handshake_event state, - const std::string & path); + const std::string &path); static void ReadCallback(uv_stream_t *stream, ssize_t read, const uv_buf_t *buf); static void CloseCallback(InspectorSocket *socket, int code); @@ -290,19 +290,19 @@ private: target_id_ = target_id; } - const int id_; - InspectorSocket socket_; + const int id_; + InspectorSocket socket_; InspectorSocketServer *server_; - std::string target_id_; - State state_; - const int server_port_; + std::string target_id_; + State state_; + const int server_port_; }; class ServerSocket { public: static int Listen(InspectorSocketServer *inspector_server, sockaddr *addr, uv_loop_t *loop); - void Close() { + void Close() { uv_close(reinterpret_cast(&tcp_socket_), SocketClosedCallback); } @@ -326,16 +326,16 @@ private: } int DetectPort(); - uv_tcp_t tcp_socket_; + uv_tcp_t tcp_socket_; InspectorSocketServer *server_; - int port_; + int port_; }; InspectorSocketServer::InspectorSocketServer(SocketServerDelegate *delegate, - uv_loop_t * loop, - const std::string & host, - int port, - FILE * out) : loop_(loop), + uv_loop_t *loop, + const std::string &host, + int port, + FILE *out) : loop_(loop), delegate_(delegate), host_(host), port_(port), @@ -345,7 +345,7 @@ InspectorSocketServer::InspectorSocketServer(SocketServerDelegate *delegate, state_ = ServerState::kNew; } -bool InspectorSocketServer::SessionStarted(SocketSession * session, +bool InspectorSocketServer::SessionStarted(SocketSession *session, const std::string &id) { if (TargetExists(id) && delegate_->StartSession(session->id(), id)) { connected_sessions_[session->id()] = session; @@ -372,7 +372,7 @@ void InspectorSocketServer::SessionTerminated(SocketSession *session) { delete session; } -bool InspectorSocketServer::HandleGetRequest(InspectorSocket * socket, +bool InspectorSocketServer::HandleGetRequest(InspectorSocket *socket, const std::string &path) { const char *command = MatchPathSegment(path.c_str(), "/json"); if (command == nullptr) @@ -402,10 +402,10 @@ void InspectorSocketServer::SendListResponse(InspectorSocket *socket) { for (const std::string &id : delegate_->GetTargetIds()) { response.push_back(std::map()); std::map &target_map = response.back(); - target_map["description"] = "node.js instance"; - target_map["faviconUrl"] = "https://nodejs.org/static/favicon.ico"; - target_map["id"] = id; - target_map["title"] = delegate_->GetTargetTitle(id); + target_map["description"] = "node.js instance"; + target_map["faviconUrl"] = "https://nodejs.org/static/favicon.ico"; + target_map["id"] = id; + target_map["title"] = delegate_->GetTargetTitle(id); Escape(&target_map["title"]); target_map["type"] = "node"; // This attribute value is a "best effort" URL that is passed as a JSON @@ -422,7 +422,7 @@ void InspectorSocketServer::SendListResponse(InspectorSocket *socket) { } if (!connected) { std::string host; - int port = SocketSession::ServerPortForClient(socket); + int port = SocketSession::ServerPortForClient(socket); GetSocketHost(&socket->tcp, &host); std::ostringstream frontend_url; frontend_url << "devtools://devtools/bundled"; @@ -440,11 +440,11 @@ bool InspectorSocketServer::Start() { CHECK_EQ(state_, ServerState::kNew); struct addrinfo hints; memset(&hints, 0, sizeof(hints)); - hints.ai_flags = AI_NUMERICSERV; + hints.ai_flags = AI_NUMERICSERV; hints.ai_socktype = SOCK_STREAM; - uv_getaddrinfo_t req; + uv_getaddrinfo_t req; const std::string port_string = to_string(port_); - int err = uv_getaddrinfo(loop_, &req, nullptr, host_.c_str(), + int err = uv_getaddrinfo(loop_, &req, nullptr, host_.c_str(), port_string.c_str(), &hints); if (err < 0) { SE_LOGE("Unable to resolve \"%s\": %s\n", host_.c_str(), @@ -452,7 +452,7 @@ bool InspectorSocketServer::Start() { return false; } for (addrinfo *address = req.addrinfo; address != nullptr; - address = address->ai_next) { + address = address->ai_next) { err = ServerSocket::Listen(this, address->ai_addr, loop_); } uv_freeaddrinfo(req.addrinfo); @@ -501,7 +501,7 @@ void InspectorSocketServer::TerminateConnections() { bool InspectorSocketServer::TargetExists(const std::string &id) { const std::vector &target_ids = delegate_->GetTargetIds(); - const auto & found = std::find(target_ids.begin(), target_ids.end(), id); + const auto &found = std::find(target_ids.begin(), target_ids.end(), id); return found != target_ids.end(); } @@ -559,7 +559,7 @@ int SocketSession::Accept(InspectorSocketServer *server, int server_port, uv_stream_t *server_socket) { // Memory is freed when the socket closes. SocketSession *session = new SocketSession(server, server_port); - int err = inspector_accept(server_socket, &session->socket_, + int err = inspector_accept(server_socket, &session->socket_, HandshakeCallback); if (err != 0) { delete session; @@ -568,12 +568,12 @@ int SocketSession::Accept(InspectorSocketServer *server, int server_port, } // static -bool SocketSession::HandshakeCallback(InspectorSocket * socket, +bool SocketSession::HandshakeCallback(InspectorSocket *socket, inspector_handshake_event event, - const std::string & path) { - SocketSession * session = SocketSession::From(socket); - InspectorSocketServer *server = session->server_; - const std::string & id = path.empty() ? path : path.substr(1); + const std::string &path) { + SocketSession *session = SocketSession::From(socket); + InspectorSocketServer *server = session->server_; + const std::string &id = path.empty() ? path : path.substr(1); switch (event) { case kInspectorHandshakeHttpGet: return server->HandleGetRequest(socket, path); @@ -613,8 +613,8 @@ void SocketSession::FrontendConnected() { // static void SocketSession::ReadCallback(uv_stream_t *stream, ssize_t read, const uv_buf_t *buf) { - InspectorSocket *socket = inspector_from_stream(stream); - SocketSession * session = SocketSession::From(socket); + InspectorSocket *socket = inspector_from_stream(stream); + SocketSession *session = SocketSession::From(socket); if (read > 0) { session->server_->MessageReceived(session->id_, std::string(buf->base, read)); @@ -632,8 +632,8 @@ void SocketSession::Send(const std::string &message) { // ServerSocket implementation int ServerSocket::DetectPort() { sockaddr_storage addr; - int len = sizeof(addr); - int err = uv_tcp_getsockname(&tcp_socket_, + int len = sizeof(addr); + int err = uv_tcp_getsockname(&tcp_socket_, reinterpret_cast(&addr), &len); if (err != 0) return err; @@ -650,7 +650,7 @@ int ServerSocket::DetectPort() { int ServerSocket::Listen(InspectorSocketServer *inspector_server, sockaddr *addr, uv_loop_t *loop) { ServerSocket *server_socket = new ServerSocket(inspector_server); - uv_tcp_t * server = &server_socket->tcp_socket_; + uv_tcp_t *server = &server_socket->tcp_socket_; CHECK_EQ(0, uv_tcp_init(loop, server)); int err = uv_tcp_bind(server, addr, 0); if (err == 0) { @@ -670,7 +670,7 @@ int ServerSocket::Listen(InspectorSocketServer *inspector_server, // static void ServerSocket::SocketConnectedCallback(uv_stream_t *tcp_socket, - int status) { + int status) { if (status == 0) { ServerSocket *server_socket = ServerSocket::FromTcpSocket(tcp_socket); // Memory is freed when the socket closes. diff --git a/native/cocos/bindings/jswrapper/v8/debugger/node.cpp b/native/cocos/bindings/jswrapper/v8/debugger/node.cpp index d6371a61a6..523519d0c7 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/node.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/node.cpp @@ -367,14 +367,14 @@ namespace node { static bool v8_is_profiling = false; -Local ErrnoException(Isolate * isolate, - int errorno, +Local ErrnoException(Isolate *isolate, + int errorno, const char *syscall, const char *msg, const char *path) { Environment *env = Environment::GetCurrent(isolate); - Local e; + Local e; Local estring = OneByteString(env->isolate(), errno_string(errorno)); if (msg == nullptr || msg[0] == '\0') { msg = strerror(errorno); @@ -426,16 +426,16 @@ static Local StringFromPath(Isolate *isolate, const char *path) { return String::NewFromUtf8(isolate, path, v8::NewStringType::kNormal).ToLocalChecked(); } -Local UVException(Isolate * isolate, - int errorno, +Local UVException(Isolate *isolate, + int errorno, const char *syscall, const char *msg, const char *path) { return UVException(isolate, errorno, syscall, msg, path, nullptr); } -Local UVException(Isolate * isolate, - int errorno, +Local UVException(Isolate *isolate, + int errorno, const char *syscall, const char *msg, const char *path, @@ -445,16 +445,16 @@ Local UVException(Isolate * isolate, if (!msg || !msg[0]) msg = uv_strerror(errorno); - Local js_code = OneByteString(isolate, uv_err_name(errorno)); + Local js_code = OneByteString(isolate, uv_err_name(errorno)); Local js_syscall = OneByteString(isolate, syscall); Local js_path; Local js_dest; Local js_msg = js_code; - js_msg = String::Concat(isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, ": ")); - js_msg = String::Concat(isolate, js_msg, OneByteString(isolate, msg)); - js_msg = String::Concat(isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, ", ")); - js_msg = String::Concat(isolate, js_msg, js_syscall); + js_msg = String::Concat(isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, ": ")); + js_msg = String::Concat(isolate, js_msg, OneByteString(isolate, msg)); + js_msg = String::Concat(isolate, js_msg, FIXED_ONE_BYTE_STRING(isolate, ", ")); + js_msg = String::Concat(isolate, js_msg, js_syscall); if (path != nullptr) { js_path = StringFromPath(isolate, path); @@ -485,12 +485,12 @@ Local UVException(Isolate * isolate, return e; } -MaybeLocal MakeCallback(Environment * env, - Local recv, +MaybeLocal MakeCallback(Environment *env, + Local recv, const Local callback, - int argc, - Local argv[], - async_context asyncContext) { + int argc, + Local argv[], + async_context asyncContext) { // If you hit this assertion, you forgot to enter the v8::Context first. CHECK_EQ(env->context(), env->isolate()->GetCurrentContext()); @@ -571,11 +571,11 @@ MaybeLocal MakeCallback(Environment * env, // Public MakeCallback()s -MaybeLocal MakeCallback(Isolate * isolate, +MaybeLocal MakeCallback(Isolate *isolate, Local recv, - const char * method, - int argc, - Local argv[], + const char *method, + int argc, + Local argv[], async_context asyncContext) { Local method_string = String::NewFromUtf8(isolate, method, v8::NewStringType::kNormal) @@ -583,11 +583,11 @@ MaybeLocal MakeCallback(Isolate * isolate, return MakeCallback(isolate, recv, method_string, argc, argv, asyncContext); } -MaybeLocal MakeCallback(Isolate * isolate, +MaybeLocal MakeCallback(Isolate *isolate, Local recv, Local symbol, - int argc, - Local argv[], + int argc, + Local argv[], async_context asyncContext) { Local callback_v = recv->Get(isolate->GetCurrentContext(), symbol).ToLocalChecked(); if (callback_v.IsEmpty()) return Local(); @@ -596,12 +596,12 @@ MaybeLocal MakeCallback(Isolate * isolate, return MakeCallback(isolate, recv, callback, argc, argv, asyncContext); } -MaybeLocal MakeCallback(Isolate * isolate, - Local recv, +MaybeLocal MakeCallback(Isolate *isolate, + Local recv, Local callback, - int argc, - Local argv[], - async_context asyncContext) { + int argc, + Local argv[], + async_context asyncContext) { // Observe the following two subtleties: // // 1. The environment is retrieved from the callback function's context. @@ -609,7 +609,7 @@ MaybeLocal MakeCallback(Isolate * isolate, // // Because of the AssignToContext() call in src/node_contextify.cc, // the two contexts need not be the same. - Environment * env = Environment::GetCurrent(callback->GetCreationContext().ToLocalChecked()); + Environment *env = Environment::GetCurrent(callback->GetCreationContext().ToLocalChecked()); Context::Scope context_scope(env->context()); return MakeCallback(env, recv.As(), callback, argc, argv, asyncContext); @@ -617,10 +617,10 @@ MaybeLocal MakeCallback(Isolate * isolate, // Legacy MakeCallback()s -Local MakeCallback(Isolate * isolate, +Local MakeCallback(Isolate *isolate, Local recv, - const char * method, - int argc, + const char *method, + int argc, Local *argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( @@ -628,10 +628,10 @@ Local MakeCallback(Isolate * isolate, .FromMaybe(Local())); } -Local MakeCallback(Isolate * isolate, +Local MakeCallback(Isolate *isolate, Local recv, Local symbol, - int argc, + int argc, Local *argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( @@ -639,11 +639,11 @@ Local MakeCallback(Isolate * isolate, .FromMaybe(Local())); } -Local MakeCallback(Isolate * isolate, - Local recv, +Local MakeCallback(Isolate *isolate, + Local recv, Local callback, - int argc, - Local * argv) { + int argc, + Local *argv) { EscapableHandleScope handle_scope(isolate); return handle_scope.Escape( MakeCallback(isolate, recv, callback, argc, argv, {0, 0}) @@ -658,16 +658,16 @@ void FreeIsolateData(IsolateData *isolate_data) { delete isolate_data; } -Environment *CreateEnvironment(IsolateData * isolate_data, - Local context, - int argc, +Environment *CreateEnvironment(IsolateData *isolate_data, + Local context, + int argc, const char *const *argv, - int exec_argc, + int exec_argc, const char *const *exec_argv) { - Isolate * isolate = context->GetIsolate(); - HandleScope handle_scope(isolate); + Isolate *isolate = context->GetIsolate(); + HandleScope handle_scope(isolate); Context::Scope context_scope(context); - auto env = new Environment(isolate_data, context); + auto env = new Environment(isolate_data, context); env->Start(argc, argv, exec_argc, exec_argv, v8_is_profiling); return env; } @@ -684,11 +684,11 @@ NO_RETURN void Abort() { NO_RETURN void Assert(const char *const (*args)[4]) { auto filename = (*args)[0]; - auto linenum = (*args)[1]; - auto message = (*args)[2]; + auto linenum = (*args)[1]; + auto message = (*args)[2]; auto function = (*args)[3]; - char exepath[256]; + char exepath[256]; size_t exepath_size = sizeof(exepath); if (uv_exepath(exepath, &exepath_size)) snprintf(exepath, sizeof(exepath), "node"); @@ -728,25 +728,25 @@ static void Abort(const FunctionCallbackInfo &args) { .FromJust(); \ } while (0) -static void ProcessTitleGetter(Local property, +static void ProcessTitleGetter(Local property, const PropertyCallbackInfo &info) { char buffer[512]; uv_get_process_title(buffer, sizeof(buffer)); info.GetReturnValue().Set(String::NewFromUtf8(info.GetIsolate(), buffer, v8::NewStringType::kNormal).ToLocalChecked()); } -static void ProcessTitleSetter(Local property, - Local value, +static void ProcessTitleSetter(Local property, + Local value, const PropertyCallbackInfo &info) { node::Utf8Value title(info.GetIsolate(), value); // REFINE(piscisaureus): protect with a lock uv_set_process_title(*title); } -void SetupProcessObject(Environment * env, - int argc, +void SetupProcessObject(Environment *env, + int argc, const char *const *argv, - int exec_argc, + int exec_argc, const char *const *exec_argv) { HandleScope scope(env->isolate()); diff --git a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp index 91ea0221d5..c8731769a6 100644 --- a/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptJavaBridge.cpp @@ -71,10 +71,10 @@ public: using ValueTypes = ccstd::vector; using ReturnValue = union { - int intValue; - int64_t longValue; - float floatValue; - int boolValue; + int intValue; + int64_t longValue; + float floatValue; + int boolValue; ccstd::string *stringValue; }; @@ -150,24 +150,24 @@ public: private: bool _mValid{false}; - int _mError{JSJ_ERR_OK}; + int _mError{JSJ_ERR_OK}; ccstd::string _mClassName; ccstd::string _mMethodName; ccstd::string _mMethodSig; - int _mArgumentsCount{0}; - ValueTypes _mArgumentsType; - ValueType _mReturnType{ValueType::VOID}; + int _mArgumentsCount{0}; + ValueTypes _mArgumentsType; + ValueType _mReturnType{ValueType::VOID}; ReturnValue _mRet; - jstring _mRetjstring{nullptr}; + jstring _mRetjstring{nullptr}; - JNIEnv * _mEnv{nullptr}; - jclass _mClassID{nullptr}; + JNIEnv *_mEnv{nullptr}; + jclass _mClassID{nullptr}; jmethodID _mMethodID{nullptr}; - bool validateMethodSig(); - bool getMethodInfo(); + bool validateMethodSig(); + bool getMethodInfo(); ValueType checkType(const ccstd::string &sig, size_t *pos); }; @@ -176,12 +176,12 @@ public: using JsCallback = std::function; class ScriptNativeBridge { public: - void callByNative(const ccstd::string &arg0, const ccstd::string &arg1); + void callByNative(const ccstd::string &arg0, const ccstd::string &arg1); inline void setCallback(const JsCallback &cb) { _callback = cb; } static ScriptNativeBridge *bridgeCxxInstance; - se::Value jsCb; + se::Value jsCb; private: JsCallback _callback{nullptr}; // NOLINT(readability-identifier-naming) @@ -195,8 +195,8 @@ JNIEXPORT jint JNICALL JNI_JSJAVABRIDGE(evalString)(JNIEnv *env, jclass /*cls*/, } se::AutoHandleScope hs; - bool strFlag = false; - ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, value, &strFlag); + bool strFlag = false; + ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, value, &strFlag); if (!strFlag) { CC_LOG_DEBUG("JavaScriptJavaBridge_evalString error, invalid string code"); return 0; @@ -251,7 +251,7 @@ bool JavaScriptJavaBridge::CallInfo::execute() { _mRetjstring = static_cast(_mEnv->CallStaticObjectMethod(_mClassID, _mMethodID)); if (_mRetjstring) { ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(_mEnv, _mRetjstring); - _mRet.stringValue = ccnew ccstd::string(strValue); + _mRet.stringValue = ccnew ccstd::string(strValue); } else { _mRet.stringValue = nullptr; } @@ -301,7 +301,7 @@ bool JavaScriptJavaBridge::CallInfo::executeWithArgs(jvalue *args) { _mRetjstring = static_cast(_mEnv->CallStaticObjectMethodA(_mClassID, _mMethodID, args)); if (_mRetjstring) { ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(_mEnv, _mRetjstring); - _mRet.stringValue = ccnew ccstd::string(strValue); + _mRet.stringValue = ccnew ccstd::string(strValue); } else { _mRet.stringValue = nullptr; } @@ -392,10 +392,10 @@ JavaScriptJavaBridge::ValueType JavaScriptJavaBridge::CallInfo::checkType(const bool JavaScriptJavaBridge::CallInfo::getMethodInfo() { _mMethodID = nullptr; - _mEnv = nullptr; + _mEnv = nullptr; JavaVM *jvm = cc::JniHelper::getJavaVM(); - jint ret = jvm->GetEnv(reinterpret_cast(&_mEnv), JNI_VERSION_1_4); + jint ret = jvm->GetEnv(reinterpret_cast(&_mEnv), JNI_VERSION_1_4); switch (ret) { case JNI_OK: break; @@ -419,7 +419,7 @@ bool JavaScriptJavaBridge::CallInfo::getMethodInfo() { return false; } jstring jstrClassName = _mEnv->NewStringUTF(_mClassName.c_str()); - _mClassID = static_cast(_mEnv->CallObjectMethod(cc::JniHelper::classloader, + _mClassID = static_cast(_mEnv->CallObjectMethod(cc::JniHelper::classloader, cc::JniHelper::loadclassMethodMethodId, jstrClassName)); @@ -492,10 +492,10 @@ SE_BIND_CTOR(JavaScriptJavaBridge_constructor, __jsb_JavaScriptJavaBridge_class, static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(readability-identifier-naming) const auto &args = s.args(); - auto argc = static_cast(args.size()); + auto argc = static_cast(args.size()); if (argc == 3) { - bool ok = false; + bool ok = false; ccstd::string clsName; ccstd::string methodName; ccstd::string methodSig; @@ -510,7 +510,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(reada JavaScriptJavaBridge::CallInfo call(clsName.c_str(), methodName.c_str(), methodSig.c_str()); if (call.isValid()) { - ok = call.execute(); + ok = call.execute(); int errorCode = call.getErrorCode(); if (!ok || errorCode < 0) { call.tryThrowJSException(); @@ -526,7 +526,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(reada } if (argc > 3) { - bool ok = false; + bool ok = false; ccstd::string clsName; ccstd::string methodName; ccstd::string methodSig; @@ -541,8 +541,8 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(reada JavaScriptJavaBridge::CallInfo call(clsName.c_str(), methodName.c_str(), methodSig.c_str()); if (call.isValid() && call.getArgumentsCount() == (argc - 3)) { - int count = argc - 3; - auto * jargs = ccnew jvalue[count]; + int count = argc - 3; + auto *jargs = ccnew jvalue[count]; ccstd::vector toReleaseObjects; for (int i = 0; i < count; ++i) { int index = i + 3; @@ -623,9 +623,9 @@ SE_BIND_PROP_GET(ScriptNativeBridge_getCallback) static bool ScriptNativeBridge_setCallback(se::State &s) { //NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); CC_ASSERT(cobj == ScriptNativeBridge::bridgeCxxInstance); - const auto &args = s.args(); - se::Value jsFunc = args[0]; - cobj->jsCb = jsFunc; + const auto &args = s.args(); + se::Value jsFunc = args[0]; + cobj->jsCb = jsFunc; if (jsFunc.isNullOrUndefined()) { cobj->setCallback(nullptr); } else { @@ -633,7 +633,7 @@ static bool ScriptNativeBridge_setCallback(se::State &s) { //NOLINT(readability- s.thisObject()->attachObject(jsFunc.toObject()); cobj->setCallback([jsFunc](const ccstd::string &arg0, const ccstd::string &arg1) { se::AutoHandleScope hs; - se::ValueArray args; + se::ValueArray args; args.push_back(se::Value(arg0)); if (!arg1.empty()) { args.push_back(se::Value(arg1)); @@ -647,9 +647,9 @@ SE_BIND_PROP_SET(ScriptNativeBridge_setCallback) static bool ScriptNativeBridge_sendToNative(se::State &s) { //NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc >= 1 && argc < 3) { - bool ok = false; + bool ok = false; ccstd::string arg0; ok = sevalue_to_native(args[0], &arg0); SE_PRECONDITION2(ok, false, "Converting arg0 failed!"); diff --git a/native/cocos/bindings/manual/JavaScriptObjCBridge.mm b/native/cocos/bindings/manual/JavaScriptObjCBridge.mm index f06494aa91..0f436a0ced 100644 --- a/native/cocos/bindings/manual/JavaScriptObjCBridge.mm +++ b/native/cocos/bindings/manual/JavaScriptObjCBridge.mm @@ -28,7 +28,6 @@ #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global.h" - #include "base/std/container/string.h" #include @@ -74,8 +73,8 @@ public: class CallInfo { public: CallInfo(const char *className, const char *methodName) - : _className(className), - _methodName(methodName) {} + : _className(className), + _methodName(methodName) {} ~CallInfo() {} @@ -84,6 +83,7 @@ public: } bool execute(const se::ValueArray &argv, se::Value &rval); + private: int _error{JSO_ERR_OK}; ccstd::string _className; @@ -91,22 +91,23 @@ public: }; }; -using JsCallback = std::function; +using JsCallback = std::function; -class ScriptNativeBridge{ +class ScriptNativeBridge { public: - void callByNative(const ccstd::string& arg0, const ccstd::string& arg1); - inline void setCallback(const JsCallback& cb){ + void callByNative(const ccstd::string &arg0, const ccstd::string &arg1); + inline void setCallback(const JsCallback &cb) { _callback = cb; } - static ScriptNativeBridge* bridgeCxxInstance; + static ScriptNativeBridge *bridgeCxxInstance; se::Value jsCb; + private: JsCallback _callback{nullptr}; // NOLINT(readability-identifier-naming) }; -ScriptNativeBridge* ScriptNativeBridge::bridgeCxxInstance{nullptr}; +ScriptNativeBridge *ScriptNativeBridge::bridgeCxxInstance{nullptr}; bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Value &rval) { - NSString *className = [NSString stringWithCString:_className.c_str() encoding:NSUTF8StringEncoding]; + NSString *className = [NSString stringWithCString:_className.c_str() encoding:NSUTF8StringEncoding]; NSString *methodName = [NSString stringWithCString:_methodName.c_str() encoding:NSUTF8StringEncoding]; if (!className || !methodName) { @@ -125,7 +126,7 @@ bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Val _error = JSO_ERR_METHOD_NOT_FOUND; return false; } - methodSel = NSSelectorFromString(methodName); + methodSel = NSSelectorFromString(methodName); NSMethodSignature *methodSig = [targetClass methodSignatureForSelector:(SEL)methodSel]; if (methodSig == nil) { _error = JSO_ERR_METHOD_NOT_FOUND; @@ -133,7 +134,7 @@ bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Val return false; } @try { - int argc = (int)argv.size(); + int argc = (int)argv.size(); NSUInteger argumentCount = [methodSig numberOfArguments]; if (argumentCount != argc) { _error = JSO_ERR_INVALID_ARGUMENTS; @@ -145,8 +146,8 @@ bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Val [invocation setSelector:methodSel]; for (int i = 2; i < argc; ++i) { - ccstd::string argumentType = [methodSig getArgumentTypeAtIndex:i]; - const se::Value &arg = argv[i]; + ccstd::string argumentType = [methodSig getArgumentTypeAtIndex:i]; + const se::Value &arg = argv[i]; /* - (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx; * @@ -219,8 +220,8 @@ bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Val } } - NSUInteger returnLength = [methodSig methodReturnLength]; - ccstd::string returnType = [methodSig methodReturnType]; + NSUInteger returnLength = [methodSig methodReturnLength]; + ccstd::string returnType = [methodSig methodReturnType]; [invocation invoke]; if (returnLength > 0) { @@ -287,8 +288,7 @@ bool JavaScriptObjCBridge::CallInfo::execute(const se::ValueArray &argv, se::Val return true; } - -void ScriptNativeBridge::callByNative(const ccstd::string& arg0, const ccstd::string& arg1){ +void ScriptNativeBridge::callByNative(const ccstd::string &arg0, const ccstd::string &arg1) { _callback(arg0, arg1); } @@ -308,10 +308,10 @@ SE_BIND_CTOR(JavaScriptObjCBridge_constructor, __jsb_JavaScriptObjCBridge_class, static bool JavaScriptObjCBridge_callStaticMethod(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc >= 2) { - bool ok = false; + bool ok = false; ccstd::string clsName, methodName; ok = sevalue_to_native(args[0], &clsName); SE_PRECONDITION2(ok, false, "Converting class name failed!"); @@ -334,7 +334,7 @@ static bool JavaScriptObjCBridge_callStaticMethod(se::State &s) { } SE_BIND_FUNC(JavaScriptObjCBridge_callStaticMethod) -static bool ScriptNativeBridge_getCallback(se::State &s){ +static bool ScriptNativeBridge_getCallback(se::State &s) { ScriptNativeBridge *cobj = (ScriptNativeBridge *)s.nativeThisObject(); CC_ASSERT(cobj == ScriptNativeBridge::bridgeCxxInstance); s.rval() = cobj->jsCb; @@ -343,37 +343,36 @@ static bool ScriptNativeBridge_getCallback(se::State &s){ } SE_BIND_PROP_GET(ScriptNativeBridge_getCallback) -static bool ScriptNativeBridge_setCallback(se::State &s){ //NOLINT(readability-identifier-naming) +static bool ScriptNativeBridge_setCallback(se::State &s) { //NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); CC_ASSERT(cobj == ScriptNativeBridge::bridgeCxxInstance); const auto &args = s.args(); se::Value jsFunc = args[0]; cobj->jsCb = jsFunc; - if(jsFunc.isNullOrUndefined()) - { + if (jsFunc.isNullOrUndefined()) { cobj->setCallback(nullptr); - } - else{ + } else { CC_ASSERT(jsFunc.isObject() && jsFunc.toObject()->isFunction()); s.thisObject()->attachObject(jsFunc.toObject()); - cobj->setCallback([jsFunc](const ccstd::string& arg0, const ccstd::string& arg1){ + cobj->setCallback([jsFunc](const ccstd::string &arg0, const ccstd::string &arg1) { se::AutoHandleScope hs; se::ValueArray args; args.push_back(se::Value(arg0)); - if(!arg1.empty()) { + if (!arg1.empty()) { args.push_back(se::Value(arg1)); } jsFunc.toObject()->call(args, nullptr); }); } return true; -}SE_BIND_PROP_SET(ScriptNativeBridge_setCallback) +} +SE_BIND_PROP_SET(ScriptNativeBridge_setCallback) static bool ScriptNativeBridge_sendToNative(se::State &s) { //NOLINT const auto &args = s.args(); int argc = (int)args.size(); if (argc >= 1 && argc < 3) { - bool ok = false; + bool ok = false; ccstd::string arg0; ok = sevalue_to_native(args[0], &arg0); SE_PRECONDITION2(ok, false, "Converting first argument failed!"); @@ -391,7 +390,6 @@ static bool ScriptNativeBridge_sendToNative(se::State &s) { //NOLINT } SE_BIND_FUNC(ScriptNativeBridge_sendToNative) - bool register_javascript_objc_bridge(se::Object *obj) { se::Class *cls = se::Class::create("JavaScriptObjCBridge", obj, nullptr, _SE(JavaScriptObjCBridge_constructor)); cls->defineFinalizeFunction(_SE(JavaScriptObjCBridge_finalize)); @@ -405,8 +403,6 @@ bool register_javascript_objc_bridge(se::Object *obj) { return true; } - - se::Class *__jsb_ScriptNativeBridge_class = nullptr; // NOLINT static bool ScriptNativeBridge_finalize(se::State &s) { //NOLINT(readability-identifier-naming) @@ -438,6 +434,6 @@ bool register_script_native_bridge(se::Object *obj) { //NOLINT(readability-ident return true; } -void callScript(const ccstd::string& arg0, const ccstd::string& arg1){ +void callScript(const ccstd::string &arg0, const ccstd::string &arg1) { ScriptNativeBridge::bridgeCxxInstance->callByNative(arg0, arg1); } diff --git a/native/cocos/bindings/manual/jsb_assets_manual.cpp b/native/cocos/bindings/manual/jsb_assets_manual.cpp index d5c8864c0b..9a5d1b9b3d 100644 --- a/native/cocos/bindings/manual/jsb_assets_manual.cpp +++ b/native/cocos/bindings/manual/jsb_assets_manual.cpp @@ -39,9 +39,9 @@ static bool js_assets_Asset_getNativeDep(se::State &s) // NOLINT(readability-ide { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_assets_Asset_getNativeDep : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { ok = nativevalue_to_se(cobj->getNativeDep(), s.rval()); SE_PRECONDITION2(ok, false, "js_assets_Asset_getNativeDep : Error processing arguments"); @@ -57,7 +57,7 @@ static bool js_assets_ImageAsset_setData(se::State &s) // NOLINT(readability-ide auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_assets_Asset_setData : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { uint8_t *data{nullptr}; if (args[0].isObject()) { @@ -80,14 +80,14 @@ static bool js_assets_SimpleTexture_registerListeners(se::State &s) // NOLINT(re auto *thisObj = s.thisObject(); cobj->on(cc::EventTypesToJS::SIMPLE_TEXTURE_GFX_TEXTURE_UPDATED, [thisObj](cc::gfx::Texture *texture) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(texture, arg0, nullptr); se::ScriptEngine::getInstance()->callFunction(thisObj, "_onGFXTextureUpdated", 1, &arg0); }); cobj->on(cc::EventTypesToJS::SIMPLE_TEXTURE_AFTER_ASSIGN_IMAGE, [thisObj](cc::ImageAsset *image) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(image, arg0, nullptr); se::ScriptEngine::getInstance()->callFunction(thisObj, "_onAfterAssignImage", 1, &arg0); }); @@ -103,7 +103,7 @@ static bool js_assets_TextureBase_registerGFXSamplerUpdatedListener(se::State &s auto *thisObj = s.thisObject(); cobj->on(cc::EventTypesToJS::TEXTURE_BASE_GFX_SAMPLER_UPDATED, [thisObj](cc::gfx::Sampler *sampler) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(sampler, arg0, nullptr); se::ScriptEngine::getInstance()->callFunction(thisObj, "_onGFXSamplerUpdated", 1, &arg0); }); diff --git a/native/cocos/bindings/manual/jsb_classtype.h b/native/cocos/bindings/manual/jsb_classtype.h index 46c16ef3ac..7a764f5c1e 100644 --- a/native/cocos/bindings/manual/jsb_classtype.h +++ b/native/cocos/bindings/manual/jsb_classtype.h @@ -40,12 +40,12 @@ public: template static se::Class *findClass(const T *nativeObj) { - bool found = false; + bool found = false; ccstd::string typeName = typeid(*nativeObj).name(); - auto iter = jsbClassTypeMap.find(typeName); + auto iter = jsbClassTypeMap.find(typeName); if (iter == jsbClassTypeMap.end()) { typeName = typeid(T).name(); - iter = jsbClassTypeMap.find(typeName); + iter = jsbClassTypeMap.find(typeName); if (iter != jsbClassTypeMap.end()) { found = true; } diff --git a/native/cocos/bindings/manual/jsb_cocos_manual.cpp b/native/cocos/bindings/manual/jsb_cocos_manual.cpp index 46d69231cd..86d4c9bf0d 100644 --- a/native/cocos/bindings/manual/jsb_cocos_manual.cpp +++ b/native/cocos/bindings/manual/jsb_cocos_manual.cpp @@ -64,14 +64,14 @@ public: private: cc::SAXParser _parser; ccstd::string _result; - bool _isStoringCharacters; + bool _isStoringCharacters; ccstd::string _currentValue; }; // cc.PlistParser.getInstance() static bool js_PlistParser_getInstance(se::State &s) { // NOLINT(readability-identifier-naming) JSPlistDelegator *delegator = JSPlistDelegator::getInstance(); - cc::SAXParser * parser = delegator->getParser(); + cc::SAXParser *parser = delegator->getParser(); if (parser) { native_ptr_to_seval(parser, __jsb_cc_SAXParser_class, &s.rval()); @@ -84,8 +84,8 @@ SE_BIND_FUNC(js_PlistParser_getInstance) // NOLINT(readability-identifier-naming // cc.PlistParser.getInstance().parse(text) static bool js_PlistParser_parse(se::State &s) { // NOLINT(readability-identifier-naming) - const auto & args = s.args(); - size_t argc = args.size(); + const auto &args = s.args(); + size_t argc = args.size(); JSPlistDelegator *delegator = JSPlistDelegator::getInstance(); bool ok = true; @@ -203,9 +203,9 @@ static bool register_plist_parser(se::Object * /*obj*/) { // NOLINT(readability- static bool JSB_localStorageGetItem(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { - bool ok = true; + bool ok = true; ccstd::string key; ok = sevalue_to_native(args[0], &key); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -227,9 +227,9 @@ SE_BIND_FUNC(JSB_localStorageGetItem) // NOLINT(readability-identifier-naming) static bool JSB_localStorageRemoveItem(const se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { - bool ok = true; + bool ok = true; ccstd::string key; ok = sevalue_to_native(args[0], &key); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -244,9 +244,9 @@ SE_BIND_FUNC(JSB_localStorageRemoveItem) // NOLINT(readability-identifier-naming static bool JSB_localStorageSetItem(const se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { - bool ok = true; + bool ok = true; ccstd::string key; ok = sevalue_to_native(args[0], &key); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -265,7 +265,7 @@ SE_BIND_FUNC(JSB_localStorageSetItem) // NOLINT(readability-identifier-naming) static bool JSB_localStorageClear(const se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { localStorageClear(); return true; @@ -278,11 +278,11 @@ SE_BIND_FUNC(JSB_localStorageClear) // NOLINT(readability-identifier-naming) static bool JSB_localStorageKey(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { - bool ok = true; - int nIndex = 0; - ok = sevalue_to_native(args[0], &nIndex); + bool ok = true; + int nIndex = 0; + ok = sevalue_to_native(args[0], &nIndex); SE_PRECONDITION2(ok, false, "Error processing arguments"); ccstd::string value; localStorageGetKey(nIndex, &value); @@ -297,7 +297,7 @@ SE_BIND_FUNC(JSB_localStorageKey) // NOLINT(readability-identifier-naming) static bool JSB_localStorage_getLength(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 0) { int nLength = 0; @@ -357,9 +357,9 @@ static bool register_sys_localStorage(se::Object *obj) { // NOLINT(readability-i static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { std::function arg0; do { @@ -368,7 +368,7 @@ static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); se::Object *thisObj = s.thisObject(); - auto lambda = [=](const cc::Data &larg0) -> void { + auto lambda = [=](const cc::Data &larg0) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; @@ -376,9 +376,9 @@ static bool js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback(se::State se::ValueArray args; args.resize(1); ok &= Data_to_seval(larg0, &args[0]); - se::Value rval; + se::Value rval; se::Object *funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } @@ -404,7 +404,7 @@ SE_BIND_FUNC(js_CanvasRenderingContext2D_setCanvasBufferUpdatedCallback) // NOLI static void setCanvasRenderingContext2DProps(cc::ICanvasRenderingContext2D *context, const se::Value &val) { se::Object *props = val.toObject(); - se::Value propVal; + se::Value propVal; props->getProperty("lineWidth", &propVal); if (!propVal.isUndefined()) context->setLineWidth(propVal.toFloat()); @@ -437,9 +437,9 @@ static void setCanvasRenderingContext2DProps(cc::ICanvasRenderingContext2D *cont static bool js_engine_CanvasRenderingContext2D_measureText(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_measureText : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { ccstd::string arg0; ok &= sevalue_to_native(args[0], &arg0); @@ -459,9 +459,9 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_measureText) // NOLINT(readabili static bool js_engine_CanvasRenderingContext2D_fillRect(const se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fillRect : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 5) { float arg0 = 0; float arg1 = 0; @@ -485,14 +485,14 @@ SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_fillRect) // NOLINT(readability- static bool js_engine_CanvasRenderingContext2D_fillText(const se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_fillText : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 5) { ccstd::string arg0; - float arg1 = 0; - float arg2 = 0; - float arg3 = 0; + float arg1 = 0; + float arg2 = 0; + float arg3 = 0; ok &= sevalue_to_native(args[0], &arg0); ok &= sevalue_to_native(args[1], &arg1); ok &= sevalue_to_native(args[2], &arg2); @@ -517,13 +517,13 @@ static bool js_engine_CanvasRenderingContext2D_strokeText(const se::State &s) { auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_CanvasRenderingContext2D_strokeText : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); - bool ok = true; + size_t argc = args.size(); + bool ok = true; if (argc == 5) { ccstd::string arg0; - float arg1 = 0; - float arg2 = 0; - float arg3 = 0; + float arg1 = 0; + float arg2 = 0; + float arg3 = 0; ok &= sevalue_to_native(args[0], &arg0); ok &= sevalue_to_native(args[1], &arg1); ok &= sevalue_to_native(args[2], &arg2); @@ -546,7 +546,7 @@ static bool js_engine_CanvasRenderingContext2D_strokeText(const se::State &s) { SE_BIND_FUNC(js_engine_CanvasRenderingContext2D_strokeText) // NOLINT(readability-identifier-naming) static se::Object *deviceMotionObject = nullptr; -static bool JSB_getDeviceMotionValue(se::State &s) { // NOLINT(readability-identifier-naming) +static bool JSB_getDeviceMotionValue(se::State &s) { // NOLINT(readability-identifier-naming) if (deviceMotionObject == nullptr) { deviceMotionObject = se::Object::createArrayObject(9); deviceMotionObject->root(); @@ -602,11 +602,11 @@ static bool register_canvas_context2d(se::Object * /*obj*/) { // NOLINT(readabil static bool js_engine_FileUtils_listFilesRecursively(const se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_engine_FileUtils_listFilesRecursively : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { - ccstd::string arg0; + ccstd::string arg0; ccstd::vector arg1; ok &= sevalue_to_native(args[0], &arg0); SE_PRECONDITION2(ok, false, "js_engine_FileUtils_listFilesRecursively : Error processing arguments"); @@ -644,7 +644,7 @@ static bool js_se_setExceptionCallback(se::State &s) { // NOLINT(readability-ide se::ScriptEngine::getInstance()->setJSExceptionCallback([objFunc](const char *location, const char *message, const char *stack) { se::AutoHandleScope scope; - se::ValueArray jsArgs; + se::ValueArray jsArgs; jsArgs.resize(3); jsArgs[0] = se::Value(location); jsArgs[1] = se::Value(message); @@ -678,12 +678,12 @@ static bool js_engine_Color_get_val(se::State &s) // NOLINT(readability-identifi SE_PRECONDITION2(cobj, false, "js_engine_Color_get_val : Invalid Native Object"); CC_UNUSED bool ok = true; - se::Value jsret; - auto r = static_cast(cobj->r); - auto g = static_cast(cobj->g); - auto b = static_cast(cobj->b); - auto a = static_cast(cobj->a); - uint32_t val = (a << 24) + (b << 16) + (g << 8) + r; + se::Value jsret; + auto r = static_cast(cobj->r); + auto g = static_cast(cobj->g); + auto b = static_cast(cobj->b); + auto a = static_cast(cobj->a); + uint32_t val = (a << 24) + (b << 16) + (g << 8) + r; ok &= nativevalue_to_se(val, jsret, s.thisObject() /*ctx*/); s.rval() = jsret; return true; @@ -693,11 +693,11 @@ SE_BIND_PROP_GET(js_engine_Color_get_val) static bool js_engine_Color_set_val(se::State &s) // NOLINT(readability-identifier-naming) { const auto &args = s.args(); - auto * cobj = SE_THIS_OBJECT(s); + auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_engine_Color_set_val : Invalid Native Object"); CC_UNUSED bool ok = true; - uint32_t val{0}; + uint32_t val{0}; ok &= sevalue_to_native(args[0], &val, s.thisObject()); cobj->r = val & 0x000000FF; cobj->g = (val & 0x0000FF00) >> 8; diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 4fad325a58..b3f7d9874f 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -172,7 +172,7 @@ seval_to_type(const se::Value &v, bool &ok) { // NOLINT(readability-identifier-n return T(); } T *nativeObj = static_cast(v.toObject()->getPrivateData()); - ok = true; + ok = true; return *nativeObj; } @@ -228,9 +228,9 @@ seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(reada se::Object *obj = v.toObject(); CC_ASSERT(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -248,7 +248,7 @@ seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(reada if (tmp.isObject()) { T nativeObj = static_cast(tmp.toObject()->getPrivateData()); - (*ret)[i] = nativeObj; + (*ret)[i] = nativeObj; } else if (tmp.isNullOrUndefined()) { (*ret)[i] = nullptr; } else { @@ -268,9 +268,9 @@ seval_to_std_vector(const se::Value &v, ccstd::vector *ret) { // NOLINT(reada se::Object *obj = v.toObject(); CC_ASSERT(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -301,7 +301,7 @@ bool seval_to_Map_string_key(const se::Value &v, cc::RefMap *r se::Object *obj = v.toObject(); ccstd::vector allKeys; - bool ok = obj->getAllKeys(&allKeys); + bool ok = obj->getAllKeys(&allKeys); if (!ok) { ret->clear(); return false; @@ -343,7 +343,7 @@ template typename std::enable_if::value, bool>::type native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullptr) { // NOLINT(readability-identifier-naming) using DecayT = typename std::decay::type>::type; - auto *v = const_cast(&v_ref); + auto *v = const_cast(&v_ref); CC_ASSERT(ret != nullptr); if (v == nullptr) { @@ -351,8 +351,8 @@ native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullpt return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: non-Ref type: (%s) isn't catched!", typeid(*v).name()); se::Class *cls = JSBClassType::findClass(v); @@ -384,8 +384,8 @@ bool native_ptr_to_rooted_seval( // NOLINT(readability-identifier-naming) return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(reinterpret_cast(v)); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(reinterpret_cast(v)); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt se::Class *cls = JSBClassType::findClass(v); CC_ASSERT(cls != nullptr); @@ -412,15 +412,15 @@ bool native_ptr_to_rooted_seval( // NOLINT(readability-identifier-naming) template bool native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr) { // NOLINT(readability-identifier-naming) using DecayT = typename std::decay::type>::type; - auto *v = const_cast(vp); + auto *v = const_cast(vp); CC_ASSERT(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); CC_ASSERT(cls != nullptr); @@ -444,15 +444,15 @@ bool native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCa template bool native_ptr_to_seval(T *vp, se::Value *ret, bool *isReturnCachedValue = nullptr) { // NOLINT(readability-identifier-naming) using DecayT = typename std::decay::type>::type; - auto *v = const_cast(vp); + auto *v = const_cast(vp); CC_ASSERT(ret != nullptr); if (v == nullptr) { ret->setNull(); return true; } - se::Object *obj = nullptr; - auto iter = se::NativePtrToObjectMap::find(v); + se::Object *obj = nullptr; + auto iter = se::NativePtrToObjectMap::find(v); if (iter == se::NativePtrToObjectMap::end()) { // If we couldn't find native object in map, then the native object is created from native code. e.g. TMXLayer::getTileAt // CC_LOG_DEBUGWARN("WARNING: Ref type: (%s) isn't catched!", typeid(*v).name()); se::Class *cls = JSBClassType::findClass(v); @@ -477,10 +477,10 @@ bool native_ptr_to_seval(T *vp, se::Value *ret, bool *isReturnCachedValue = null template bool std_vector_to_seval(const ccstd::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) CC_ASSERT(ret != nullptr); - bool ok = true; + bool ok = true; se::HandleObject obj(se::Object::createArrayObject(v.size())); - uint32_t i = 0; + uint32_t i = 0; se::Value tmp; for (const auto &e : v) { native_ptr_to_seval(e, &tmp); @@ -535,10 +535,10 @@ holder_convert_to(In &input) { // NOLINT(readability-identifier-naming) template struct HolderType { - using type = typename std::remove_const::type; + using type = typename std::remove_const::type; using local_type = typename std::conditional_t, std::add_pointer_t, type>; local_type data; - type * ptr = nullptr; + type *ptr = nullptr; struct alignas(T) EmbedField { uint8_t inlineObject[is_reference && is_jsb_object_v ? sizeof(T) : 1]; } inlineObject; @@ -557,30 +557,30 @@ struct HolderType { template <> struct HolderType { - using type = const char *; + using type = const char *; using local_type = ccstd::string; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type value() const { return data.c_str(); } + inline type value() const { return data.c_str(); } }; template <> struct HolderType { - using type = const char *; + using type = const char *; using local_type = ccstd::string; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type value() const { return data.c_str(); } + inline type value() const { return data.c_str(); } }; #define HOLD_UNBOUND_TYPE(FromType, IsReference) \ template <> \ struct HolderType { \ - using type = FromType; \ + using type = FromType; \ using local_type = typename std::remove_pointer::type; \ std::remove_const_t data; \ - std::remove_const_t * ptr = nullptr; \ - inline type value() { return &data; } \ + std::remove_const_t *ptr = nullptr; \ + inline type value() { return &data; } \ } HOLD_UNBOUND_TYPE(cc::Vec3 *, false); @@ -592,20 +592,20 @@ HOLD_UNBOUND_TYPE(cc::geometry::AABB *, false); template <> struct HolderType { - using type = cc::ArrayBuffer; + using type = cc::ArrayBuffer; using local_type = cc::ArrayBuffer; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type & value() { return data; } + inline type &value() { return data; } }; template struct HolderType, true> { - using type = std::function; + using type = std::function; using local_type = std::function; - local_type data; + local_type data; std::remove_const_t *ptr = nullptr; - inline type value() { return data; } + inline type value() { return data; } }; //template @@ -657,7 +657,7 @@ template inline typename std::enable_if_t::value, bool> sevalue_to_native(const se::Value &from, T *to, se::Object *ctx) { // NOLINT(readability-identifier-naming) typename std::underlying_type_t tmp; - bool ret = sevalue_to_native(from, &tmp, ctx); + bool ret = sevalue_to_native(from, &tmp, ctx); if (ret) *to = static_cast(tmp); return ret; } @@ -716,14 +716,14 @@ bool sevalue_to_native(const se::Value &from, ccstd::array *to, se CC_ASSERT(array->isArray() || array->isArrayBuffer() || array->isTypedArray()); if (array->isTypedArray()) { uint8_t *data = nullptr; - size_t size = 0; + size_t size = 0; array->getTypedArrayData(&data, &size); for (size_t i = 0; i < std::min(size, CNT); i++) { (*to)[i] = data[i]; } } else if (array->isArrayBuffer()) { uint8_t *data = nullptr; - size_t size = 0; + size_t size = 0; array->getArrayBufferData(&data, &size); for (size_t i = 0; i < std::min(size, CNT); i++) { (*to)[i] = data[i]; @@ -786,7 +786,7 @@ template typename std::enable_if_t::value && std::is_arithmetic::value, bool> sevalue_to_native(const se::Value &from, T **to, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) se::Object *data = from.toObject(); - uint8_t * tmp; + uint8_t *tmp; if (data->isArrayBuffer()) { data->getArrayBufferData(&tmp, nullptr); } else if (data->isTypedArray()) { @@ -839,8 +839,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * if (array->isTypedArray()) { CC_ASSERT(std::is_arithmetic::value); - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; array->getTypedArrayData(&data, &dataLen); to->assign(reinterpret_cast(data), reinterpret_cast(data + dataLen)); return true; @@ -859,13 +859,13 @@ inline bool sevalue_to_native(const se::Value &from, std::function * self->attachObject(callback); *func = [callback, self](Args... inargs) { se::AutoHandleScope hs; - bool ok = true; - se::ValueArray args; - int idx = 0; + bool ok = true; + se::ValueArray args; + int idx = 0; args.resize(sizeof...(Args)); nativevalue_to_se_args_v(args, inargs...); se::Value rval; - bool succeed = callback->call(args, self, &rval); + bool succeed = callback->call(args, self, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } @@ -900,7 +900,7 @@ inline bool sevalue_to_native(const se::Value &from, HolderType return true; } if CC_CONSTEXPR (std::is_constructible::value) { - holder->ptr = ccnew_placement (&holder->inlineObject) T; + holder->ptr = ccnew_placement(&holder->inlineObject) T; } else { CC_ASSERT(false); // default construtor not provided } @@ -928,7 +928,7 @@ inline typename std::enable_if, bool>::type sevalue_to_native return true; } else { // holder->ptr = ccnew T; - holder->ptr = ccnew_placement (&holder->inlineObject) T; + holder->ptr = ccnew_placement(&holder->inlineObject) T; return sevalue_to_native(from, holder->ptr, ctx); } } @@ -1032,9 +1032,9 @@ bool sevalue_to_native(const se::Value &from, cc::IntrusivePtr *to, se::Objec auto *privateObject = from.toObject()->getPrivateObject(); if (!privateObject) { - T * tmp = nullptr; - bool ok = sevalue_to_native(from, &tmp, ctx); - *to = tmp; + T *tmp = nullptr; + bool ok = sevalue_to_native(from, &tmp, ctx); + *to = tmp; return ok; } @@ -1061,7 +1061,7 @@ void se_for_each_tuple(Tuple &&tuple, F &&f) { // NOLINT(readability-identifier- template bool sevalue_to_native(const se::Value &from, std::tuple *to, se::Object *ctx) { // NOLINT constexpr size_t argsize = std::tuple_size>::value; - bool result = true; + bool result = true; se_for_each_tuple(*to, [&](auto i, auto ¶m) { se::Value tmp; from.toObject()->getArrayElement(static_cast(i), &tmp); @@ -1073,10 +1073,10 @@ bool sevalue_to_native(const se::Value &from, std::tuple *to, se::Objec ////////////// ccstd::unordered_map template bool sevalue_to_native(const se::Value &from, ccstd::unordered_map *to, se::Object *ctx) { //NOLINT - se::Object * jsmap = from.toObject(); + se::Object *jsmap = from.toObject(); ccstd::vector allKeys; jsmap->getAllKeys(&allKeys); - bool ret = true; + bool ret = true; se::Value property; for (auto &it : allKeys) { if (jsmap->getProperty(it.c_str(), &property)) { @@ -1095,7 +1095,7 @@ bool sevalue_to_native(const se::Value &from, cc::optional *to, se::Object *c to->reset(); return true; } - T tmp{}; + T tmp{}; bool ret = sevalue_to_native(from, &tmp, ctx); if CC_CONSTEXPR (std::is_move_assignable::value) { *to = std::move(tmp); @@ -1220,7 +1220,7 @@ inline bool nativevalue_to_se(const cc::TypedArrayTemp &typedArray, se::Value template inline bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::Object *ctx) { // NOLINT(readability-identifier-naming) se::HandleObject array(se::Object::createArrayObject(from.size())); - se::Value tmp; + se::Value tmp; for (size_t i = 0; i < from.size(); i++) { // If from[i] is on stack, then should create a new object, or // JS will hold a freed object. @@ -1229,11 +1229,10 @@ inline bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::O nativevalue_to_se(pFrom, tmp, ctx); tmp.toObject()->clearPrivateData(); tmp.toObject()->setPrivateData(pFrom); - } - else { + } else { nativevalue_to_se(from[i], tmp, ctx); } - + array->setArrayElement(static_cast(i), tmp); } to.setObject(array, true); @@ -1261,8 +1260,8 @@ typename std::enable_if::value, void>::ty template inline bool nativevalue_to_se(const ccstd::unordered_map &from, se::Value &to, se::Object *ctx) { // NOLINT se::Object *ret = se::Object::createPlainObject(); - se::Value value; - bool ok = true; + se::Value value; + bool ok = true; for (auto &it : from) { ok &= nativevalue_to_se(it.second, value, ctx); cc_tmp_set_property(ret, it.first, value); @@ -1275,7 +1274,7 @@ inline bool nativevalue_to_se(const ccstd::unordered_map &from, se::Value template inline bool nativevalue_to_se(const ccstd::array &from, se::Value &to, se::Object *ctx) { // NOLINT(readability-identifier-naming) se::Object *array = se::Object::createArrayObject(N); - se::Value tmp; + se::Value tmp; for (size_t i = 0; i < N; i++) { nativevalue_to_se(from[i], tmp, ctx); array->setArrayElement(static_cast(i), tmp); @@ -1322,12 +1321,12 @@ bool nativevalue_to_se_args(se::ValueArray &array, T &x) { // NOLINT(readability return nativevalue_to_se(x, array[i], nullptr); } template -bool nativevalue_to_se_args(se::ValueArray &array, T &x, Args &...args) { // NOLINT(readability-identifier-naming) +bool nativevalue_to_se_args(se::ValueArray &array, T &x, Args &... args) { // NOLINT(readability-identifier-naming) return nativevalue_to_se_args(array, x) && nativevalue_to_se_args(array, args...); } template -bool nativevalue_to_se_args_v(se::ValueArray &array, Args &...args) { // NOLINT(readability-identifier-naming) +bool nativevalue_to_se_args_v(se::ValueArray &array, Args &... args) { // NOLINT(readability-identifier-naming) return nativevalue_to_se_args<0, Args...>(array, args...); } @@ -1337,7 +1336,7 @@ bool nativevalue_to_se_args_v(se::ValueArray &array, Args &...args) { // NOLINT( template bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; spine::Vector tmpv = v; @@ -1362,7 +1361,7 @@ bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object * / template bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; spine::Vector tmpv = v; @@ -1388,9 +1387,9 @@ bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se::Object * se::Object *obj = v.toObject(); CC_ASSERT(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -1478,8 +1477,8 @@ inline bool nativevalue_to_se(const cc::IntrusivePtr &from, se::Value &to, se template bool nativevalue_to_se(const std::tuple &from, se::Value &to, se::Object *ctx) { // NOLINT(readability-identifier-naming) - bool ok = true; - se::Value tmp; + bool ok = true; + se::Value tmp; se::Object *array = se::Object::createArrayObject(sizeof...(ARGS)); se_for_each_tuple( from, [&](auto i, auto ¶m) { diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index 7bde1daa80..8edc656012 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -52,7 +52,7 @@ template struct overloaded : F0, overloaded { overloaded(F0 f0, Fs... rest) : F0(f0), overloaded(rest...) {} // NOLINT(google-explicit-constructor) - using F0:: operator(); + using F0::operator(); using overloaded::operator(); }; @@ -107,7 +107,7 @@ template bool std_vector_T_to_seval(const ccstd::vector &v, se::Value *ret) { // NOLINT(readability-identifier-naming) CC_ASSERT(ret != nullptr); se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; uint32_t i = 0; for (const auto &value : v) { @@ -221,8 +221,8 @@ bool Rect_to_seval(const cc::Rect &v, se::Value *ret) { // NOLINT(readability-id return true; } void toVec2(void *data, DataType type, se::Value *ret) { - auto * intptr = static_cast(data); - auto * floatptr = static_cast(data); + auto *intptr = static_cast(data); + auto *floatptr = static_cast(data); cc::Vec2 vec2; if (DataType::INT == type) { vec2.x = static_cast(intptr[0]); @@ -236,8 +236,8 @@ void toVec2(void *data, DataType type, se::Value *ret) { } void toVec3(void *data, DataType type, se::Value *ret) { - auto * intptr = static_cast(data); - auto * floatptr = static_cast(data); + auto *intptr = static_cast(data); + auto *floatptr = static_cast(data); cc::Vec3 vec3; if (DataType::INT == type) { vec3.x = static_cast(intptr[0]); @@ -253,8 +253,8 @@ void toVec3(void *data, DataType type, se::Value *ret) { } void toVec4(void *data, DataType type, se::Value *ret) { - auto * intptr = static_cast(data); - auto * floatptr = static_cast(data); + auto *intptr = static_cast(data); + auto *floatptr = static_cast(data); cc::Vec4 vec4; if (DataType::INT == type) { vec4.x = static_cast(intptr[0]); @@ -347,7 +347,7 @@ bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret) { // NOLINT ccstd::vector allKeys; SE_PRECONDITION3(obj->getAllKeys(&allKeys), false, ret->clear()); - bool ok = false; + bool ok = false; se::Value value; cc::Value ccvalue; for (const auto &key : allKeys) { @@ -378,7 +378,7 @@ bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret) { ccstd::vector allKeys; SE_PRECONDITION3(obj->getAllKeys(&allKeys), false, ret->clear()); - bool ok = false; + bool ok = false; se::Value value; cc::Value ccvalue; for (const auto &key : allKeys) { @@ -411,7 +411,7 @@ bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret) { // NOLIN uint32_t len = 0; obj->getArrayLength(&len); - bool ok = false; + bool ok = false; se::Value value; cc::Value ccvalue; for (uint32_t i = 0; i < len; ++i) { @@ -427,7 +427,7 @@ bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret) { // NOLIN // NOLINTNEXTLINE(readability-identifier-naming) bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVector *ret) { - bool ok = false; + bool ok = false; cc::Value ccvalue; for (const auto &arg : args) { @@ -443,9 +443,9 @@ bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVecto bool seval_to_Data(const se::Value &v, cc::Data *ret) { CC_ASSERT(ret != nullptr); SE_PRECONDITION2(v.isObject() && v.toObject()->isTypedArray(), false, "Convert parameter to Data failed!"); - uint8_t *ptr = nullptr; - size_t length = 0; - bool ok = v.toObject()->getTypedArrayData(&ptr, &length); + uint8_t *ptr = nullptr; + size_t length = 0; + bool ok = v.toObject()->getTypedArrayData(&ptr, &length); if (ok) { ret->copy(ptr, static_cast(length)); } else { @@ -460,9 +460,9 @@ bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints * const static cc::network::DownloaderHints ZERO{0, 0, ""}; CC_ASSERT(ret != nullptr); SE_PRECONDITION2(v.isObject(), false, "Convert parameter to DownloaderHints failed!"); - se::Value tmp; + se::Value tmp; se::Object *obj = v.toObject(); - bool ok = false; + bool ok = false; ok = obj->getProperty("countOfMaxProcessingTasks", &tmp); SE_PRECONDITION3(ok && tmp.isNumber(), false, *ret = ZERO); @@ -483,7 +483,7 @@ bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints * bool sevalue_to_native(const se::Value &from, cc::Vec4 *to, se::Object * /*unused*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec4 failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "x", &cc::Vec4::x, tmp); set_member_field(obj, to, "y", &cc::Vec4::y, tmp); set_member_field(obj, to, "z", &cc::Vec4::z, tmp); @@ -499,14 +499,14 @@ bool sevalue_to_native(const se::Value &from, cc::Mat3 *to, se::Object * /*unuse if (obj->isTypedArray()) { // typed array SE_PRECONDITION2(obj->isTypedArray(), false, "Convert parameter to Matrix3 failed!"); - size_t length = 0; - uint8_t *ptr = nullptr; + size_t length = 0; + uint8_t *ptr = nullptr; obj->getTypedArrayData(&ptr, &length); memcpy(to->m, ptr, length); } else { - bool ok = false; - se::Value tmp; + bool ok = false; + se::Value tmp; ccstd::string prefix = "m"; for (uint32_t i = 0; i < 9; ++i) { ccstd::string name; @@ -542,14 +542,14 @@ bool sevalue_to_native(const se::Value &from, cc::Mat4 *to, se::Object * /*unuse // typed array SE_PRECONDITION2(obj->isTypedArray(), false, "Convert parameter to Matrix4 failed!"); - size_t length = 0; - uint8_t *ptr = nullptr; + size_t length = 0; + uint8_t *ptr = nullptr; obj->getTypedArrayData(&ptr, &length); memcpy(to->m, ptr, length); } else { - bool ok = false; - se::Value tmp; + bool ok = false; + se::Value tmp; ccstd::string prefix = "m"; for (uint32_t i = 0; i < 16; ++i) { ccstd::string name; @@ -581,7 +581,7 @@ bool sevalue_to_native(const se::Value &from, cc::Vec3 *to, se::Object * /*unuse SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec3 failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "x", &cc::Vec3::x, tmp); set_member_field(obj, to, "y", &cc::Vec3::y, tmp); set_member_field(obj, to, "z", &cc::Vec3::z, tmp); @@ -593,7 +593,7 @@ bool sevalue_to_native(const se::Value &from, cc::Color *to, se::Object * /*unus SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Color failed!"); se::Object *obj = from.toObject(); - se::Value t; + se::Value t; set_member_field(obj, to, "r", &cc::Color::r, t); set_member_field(obj, to, "g", &cc::Color::g, t); set_member_field(obj, to, "b", &cc::Color::b, t); @@ -606,7 +606,7 @@ bool sevalue_to_native(const se::Value &from, cc::Vec2 *to, se::Object * /*unuse SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Vec2 failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "x", &cc::Vec2::x, tmp); set_member_field(obj, to, "y", &cc::Vec2::y, tmp); return true; @@ -617,7 +617,7 @@ bool sevalue_to_native(const se::Value &from, cc::Size *to, se::Object * /*unuse SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Size failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "width", &cc::Size::width, tmp); set_member_field(obj, to, "height", &cc::Size::height, tmp); return true; @@ -627,7 +627,7 @@ bool sevalue_to_native(const se::Value &from, cc::Size *to, se::Object * /*unuse bool sevalue_to_native(const se::Value &from, cc::Quaternion *to, se::Object * /*unused*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Quaternion failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "x", &cc::Quaternion::x, tmp); set_member_field(obj, to, "y", &cc::Quaternion::y, tmp); set_member_field(obj, to, "z", &cc::Quaternion::z, tmp); @@ -641,7 +641,7 @@ bool sevalue_to_native(const se::Value &from, cc::Quaternion *to, se::Object * / bool sevalue_to_native(const se::Value &from, cc::geometry::AABB *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to AABB failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "halfExtents", &cc::geometry::AABB::halfExtents, tmp); set_member_field(obj, to, "center", &cc::geometry::AABB::center, tmp); return true; @@ -651,7 +651,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::AABB *to, se::Object bool sevalue_to_native(const se::Value &from, cc::geometry::Capsule *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Capsule failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "radius", &cc::geometry::Capsule::radius, tmp); set_member_field(obj, to, "halfHeight", &cc::geometry::Capsule::halfHeight, tmp); set_member_field(obj, to, "axis", &cc::geometry::Capsule::axis, tmp); @@ -662,7 +662,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Capsule *to, se::Obj bool sevalue_to_native(const se::Value &from, cc::geometry::Line *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Line failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "s", &cc::geometry::Line::s, tmp); set_member_field(obj, to, "e", &cc::geometry::Line::e, tmp); return true; @@ -672,7 +672,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Line *to, se::Object bool sevalue_to_native(const se::Value &from, cc::geometry::Ray *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Sphere failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "o", &cc::geometry::Ray::o, tmp); set_member_field(obj, to, "d", &cc::geometry::Ray::d, tmp); return true; @@ -682,7 +682,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Ray *to, se::Object bool sevalue_to_native(const se::Value &from, cc::geometry::Sphere *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Sphere failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "radius", &cc::geometry::Sphere::setRadius, tmp); set_member_field(obj, to, "center", &cc::geometry::Sphere::setCenter, tmp); return true; @@ -692,7 +692,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Sphere *to, se::Obje bool sevalue_to_native(const se::Value &from, cc::geometry::Triangle *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Plane failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "a", &cc::geometry::Triangle::a, tmp); set_member_field(obj, to, "b", &cc::geometry::Triangle::b, tmp); set_member_field(obj, to, "c", &cc::geometry::Triangle::c, tmp); @@ -703,7 +703,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Triangle *to, se::Ob bool sevalue_to_native(const se::Value &from, cc::geometry::Plane *to, se::Object * /*unused*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Plane failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "n", &cc::geometry::Plane::n, tmp); set_member_field(obj, to, "d", &cc::geometry::Plane::d, tmp); return true; @@ -718,7 +718,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Plane **to, se::Obje bool sevalue_to_native(const se::Value &from, cc::geometry::Frustum *to, se::Object * /*unused*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Frustum failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "planes", &cc::geometry::Frustum::planes, tmp); set_member_field(obj, to, "vertices", &cc::geometry::Frustum::vertices, tmp); return true; @@ -728,7 +728,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Frustum *to, se::Obj bool sevalue_to_native(const se::Value &from, cc::geometry::Spline *to, se::Object * /*unused*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Spline failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "_mode", &cc::geometry::Spline::setMode, tmp); set_member_field>(obj, to, "_knots", &cc::geometry::Spline::setKnots, tmp); return true; @@ -740,7 +740,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Spline *to, se::Obje bool sevalue_to_native(const se::Value &from, cc::scene::FogInfo *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to FogInfo failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "type", &cc::scene::FogInfo::setType, tmp); set_member_field(obj, to, "fogColor", &cc::scene::FogInfo::setFogColor, tmp); set_member_field(obj, to, "enabled", &cc::scene::FogInfo::setEnabled, tmp); @@ -758,7 +758,7 @@ bool sevalue_to_native(const se::Value &from, cc::scene::FogInfo *to, se::Object bool sevalue_to_native(const se::Value &from, cc::scene::ShadowsInfo *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to ShadowInfo failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "type", &cc::scene::ShadowsInfo::setType, tmp); set_member_field(obj, to, "enabled", &cc::scene::ShadowsInfo::setEnabled, tmp); set_member_field(obj, to, "normal", &cc::scene::ShadowsInfo::setNormal, tmp); @@ -774,7 +774,7 @@ bool sevalue_to_native(const se::Value &from, cc::scene::ShadowsInfo *to, se::Ob bool sevalue_to_native(const se::Value &from, cc::scene::SkyboxInfo *to, se::Object * /*ctx*/) { SE_PRECONDITION2(from.isObject(), false, "Convert parameter to SkyboxInfo failed!"); se::Object *obj = from.toObject(); - se::Value tmp; + se::Value tmp; set_member_field(obj, to, "envmap", &cc::scene::SkyboxInfo::setEnvmap, tmp); set_member_field(obj, to, "diffuseMap", &cc::scene::SkyboxInfo::setDiffuseMap, tmp); set_member_field(obj, to, "enabled", &cc::scene::SkyboxInfo::setEnabled, tmp); @@ -810,7 +810,7 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to auto *fromObj = from.toObject(); CC_ASSERT(fromObj->isArray()); uint32_t len = 0; - bool ok = fromObj->getArrayLength(&len); + bool ok = fromObj->getArrayLength(&len); if (ok) { to->resize(len); se::Value arrElement; @@ -819,7 +819,7 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to if (!ok || !arrElement.isObject()) { continue; } - cc::MacroRecord macroRecord; + cc::MacroRecord macroRecord; ccstd::vector keys; ok = arrElement.toObject()->getAllKeys(&keys); if (ok) { @@ -858,16 +858,16 @@ bool sevalue_to_native(const se::Value &from, cc::MaterialProperty *to, se::Obje if (from.isObject()) { auto *obj = const_cast(from.toObject()); - bool hasX; - bool hasY; - bool hasZ; - bool hasW; - bool hasEuler; - bool hasM01; - bool hasM08; - bool hasM15; - bool hasAssetID; - bool hasColorVal; + bool hasX; + bool hasY; + bool hasZ; + bool hasW; + bool hasEuler; + bool hasM01; + bool hasM08; + bool hasM15; + bool hasAssetID; + bool hasColorVal; se::Value tmp0; se::Value tmp1; @@ -881,10 +881,10 @@ bool sevalue_to_native(const se::Value &from, cc::MaterialProperty *to, se::Obje return true; } - hasX = obj->getProperty("x", &tmp0, true); - hasY = hasX && obj->getProperty("y", &tmp1, true); - hasZ = hasY && obj->getProperty("z", &tmp2, true); - hasW = hasZ && obj->getProperty("w", &tmp3, true); + hasX = obj->getProperty("x", &tmp0, true); + hasY = hasX && obj->getProperty("y", &tmp1, true); + hasZ = hasY && obj->getProperty("z", &tmp2, true); + hasW = hasZ && obj->getProperty("w", &tmp3, true); hasEuler = hasW && obj->getProperty("getEulerAngles", &tmp4, true); if (hasW) { @@ -996,8 +996,8 @@ bool sevalue_to_native(const se::Value &from, cc::IPreCompileInfoValueType *to, // NOLINTNEXTLINE(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, cc::variant, ccstd::string> *to, se::Object * /*ctx*/) { if (from.isObject() && from.toObject()->isArray()) { - uint32_t len = 0; - bool ok = from.toObject()->getArrayLength(&len); + uint32_t len = 0; + bool ok = from.toObject()->getArrayLength(&len); ccstd::vector arr; arr.resize(len); for (uint32_t i = 0; i < len; ++i) { @@ -1061,8 +1061,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Objec } se::Object *arr = from.toObject(); - uint32_t size; - se::Value tmp; + uint32_t size; + se::Value tmp; arr->getArrayLength(&size); to->resize(size); for (uint32_t i = 0; i < size; i++) { @@ -1083,8 +1083,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object *in = from.toObject(); if (in->isTypedArray()) { - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; in->getTypedArrayData(&data, &dataLen); to->resize(dataLen); to->assign(data, data + dataLen); @@ -1092,8 +1092,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, } if (in->isArrayBuffer()) { - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; in->getArrayBufferData(&data, &dataLen); to->resize(dataLen); to->assign(data, data + dataLen); @@ -1185,9 +1185,9 @@ bool sevalue_to_native(const se::Value &v, spine::Vector *ret, se se::Object *obj = v.toObject(); CC_ASSERT(obj->isArray()); - bool ok = true; + bool ok = true; uint32_t len = 0; - ok = obj->getArrayLength(&len); + ok = obj->getArrayLength(&len); if (!ok) { ret->clear(); return false; @@ -1217,7 +1217,7 @@ bool seval_to_Map_string_key(const se::Value &v, cc::RefMap allKeys; - bool ok = obj->getAllKeys(&allKeys); + bool ok = obj->getAllKeys(&allKeys); if (!ok) { ret->clear(); return false; @@ -1297,10 +1297,10 @@ bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret) { // NOLINT CC_ASSERT(ret != nullptr); se::HandleObject obj(se::Object::createPlainObject()); - bool ok = true; + bool ok = true; for (const auto &e : v) { - const ccstd::string &key = e.first; - const cc::Value & value = e.second; + const ccstd::string &key = e.first; + const cc::Value &value = e.second; if (key.empty()) { continue; @@ -1327,11 +1327,11 @@ bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret) { // CC_ASSERT(ret != nullptr); se::HandleObject obj(se::Object::createPlainObject()); - bool ok = true; + bool ok = true; for (const auto &e : v) { std::stringstream keyss; keyss << e.first; - ccstd::string key = keyss.str(); + ccstd::string key = keyss.str(); const cc::Value &value = e.second; if (key.empty()) { @@ -1358,7 +1358,7 @@ bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret) { // bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret) { // NOLINT CC_ASSERT(ret != nullptr); se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; uint32_t i = 0; for (const auto &value : v) { @@ -1427,7 +1427,7 @@ bool nativevalue_to_se(const spine::String &obj, se::Value &val, se::Object * /* // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const spine::Vector &v, se::Value &ret, se::Object * /*unused*/) { se::HandleObject obj(se::Object::createArrayObject(v.size())); - bool ok = true; + bool ok = true; spine::Vector tmpv = v; for (uint32_t i = 0, count = static_cast(tmpv.size()); i < count; i++) { @@ -1527,7 +1527,7 @@ bool nativevalue_to_se(const cc::NativeDep &from, se::Value &to, se::Object * /* // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Mat3 &from, se::Value &to, se::Object * /*ctx*/) { se::HandleObject obj(se::Object::createPlainObject()); - char keybuf[8] = {0}; + char keybuf[8] = {0}; for (auto i = 0; i < 9; i++) { snprintf(keybuf, sizeof(keybuf), "m%02d", i); obj->setProperty(keybuf, se::Value(from.m[i])); @@ -1539,7 +1539,7 @@ bool nativevalue_to_se(const cc::Mat3 &from, se::Value &to, se::Object * /*ctx*/ // NOLINTNEXTLINE(readability-identifier-naming) bool nativevalue_to_se(const cc::Mat4 &from, se::Value &to, se::Object * /*ctx*/) { se::HandleObject obj(se::Object::createPlainObject()); - char keybuf[8] = {0}; + char keybuf[8] = {0}; for (auto i = 0; i < 16; i++) { snprintf(keybuf, sizeof(keybuf), "m%02d", i); obj->setProperty(keybuf, se::Value(from.m[i])); @@ -1563,10 +1563,10 @@ bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::Object * /*ctx*/) { - const auto contactCount = from.size(); + const auto contactCount = from.size(); se::HandleObject array(se::Object::createArrayObject(contactCount)); for (size_t i = 0; i < contactCount; i++) { - auto t = i * cc::physics::ContactPoint::COUNT; + auto t = i * cc::physics::ContactPoint::COUNT; uint32_t j = 0; array->setArrayElement(static_cast(t + j++), se::Value(from[i].position.x)); array->setArrayElement(static_cast(t + j++), se::Value(from[i].position.y)); @@ -1616,14 +1616,14 @@ bool nativevalue_to_se(const cc::physics::RaycastResult &from, se::Value &to, se bool sevalue_to_native(const se::Value &from, cc::physics::ConvexDesc *to, se::Object *ctx) { CC_ASSERT(from.isObject()); se::Object *json = from.toObject(); - auto * data = static_cast(json->getPrivateData()); + auto *data = static_cast(json->getPrivateData()); if (data) { *to = *data; return true; } se::Value field; - bool ok = true; + bool ok = true; json->getProperty("positionLength", &field); if (!field.isNullOrUndefined()) ok &= sevalue_to_native(field, &to->positionLength, ctx); @@ -1652,13 +1652,13 @@ bool sevalue_to_native(const se::Value &from, cc::physics::TrimeshDesc *to, se:: CC_ASSERT(from.isObject()); se::Object *json = from.toObject(); - auto * data = static_cast(json->getPrivateData()); + auto *data = static_cast(json->getPrivateData()); if (data) { *to = *data; return true; } se::Value field; - bool ok = true; + bool ok = true; json->getProperty("triangleLength", &field); if (!field.isNullOrUndefined()) ok &= sevalue_to_native(field, &(to->triangleLength), ctx); @@ -1687,14 +1687,14 @@ bool sevalue_to_native(const se::Value &from, cc::physics::TrimeshDesc *to, se:: bool sevalue_to_native(const se::Value &from, cc::physics::HeightFieldDesc *to, se::Object *ctx) { CC_ASSERT(from.isObject()); se::Object *json = from.toObject(); - auto * data = static_cast(json->getPrivateData()); + auto *data = static_cast(json->getPrivateData()); if (data) { *to = *data; return true; } se::Value field; - bool ok = true; + bool ok = true; json->getProperty("rows", &field); if (!field.isNullOrUndefined()) ok &= sevalue_to_native(field, &to->rows, ctx); @@ -1722,14 +1722,14 @@ bool sevalue_to_native(const se::Value &from, cc::physics::HeightFieldDesc *to, bool sevalue_to_native(const se::Value &from, cc::physics::RaycastOptions *to, se::Object *ctx) { CC_ASSERT(from.isObject()); se::Object *json = from.toObject(); - auto * data = static_cast(json->getPrivateData()); + auto *data = static_cast(json->getPrivateData()); if (data) { *to = *data; return true; } se::Value field; - bool ok = true; + bool ok = true; json->getProperty("origin", &field); if (!field.isNullOrUndefined()) ok &= sevalue_to_native(field, &to->origin, ctx); @@ -1751,7 +1751,7 @@ bool sevalue_to_native(const se::Value &from, cc::physics::RaycastOptions *to, s bool nativevalue_to_se(const cc::geometry::AABB &from, se::Value &to, se::Object *ctx) { se::HandleObject obj(se::Object::createPlainObject()); - se::Value tmp; + se::Value tmp; if (nativevalue_to_se(from.getCenter(), tmp, ctx)) obj->setProperty("center", tmp); if (nativevalue_to_se(from.getHalfExtents(), tmp, ctx)) obj->setProperty("halfExtents", tmp); to.setObject(obj); @@ -1760,7 +1760,7 @@ bool nativevalue_to_se(const cc::geometry::AABB &from, se::Value &to, se::Object bool nativevalue_to_se(const cc::geometry::Sphere &from, se::Value &to, se::Object *ctx) { se::HandleObject obj(se::Object::createPlainObject()); - se::Value tmp(from.getRadius()); + se::Value tmp(from.getRadius()); obj->setProperty("radius", tmp); if (nativevalue_to_se(from.getCenter(), tmp, ctx)) obj->setProperty("center", tmp); to.setObject(obj); diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index 3fe8392205..9743fe421b 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -334,9 +334,9 @@ inline bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Objec bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::variant, ccstd::string> *to, se::Object *ctx); // NOLINT(readability-identifier-naming) -inline bool sevalue_to_native(const se::Value & /*from*/, cc::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, cc::variant, ccstd::string> *to, se::Object *ctx); // NOLINT(readability-identifier-naming) +inline bool sevalue_to_native(const se::Value & /*from*/, cc::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) // nothing todo return false; } diff --git a/native/cocos/bindings/manual/jsb_dragonbones_manual.cpp b/native/cocos/bindings/manual/jsb_dragonbones_manual.cpp index 0302734d55..9440721564 100644 --- a/native/cocos/bindings/manual/jsb_dragonbones_manual.cpp +++ b/native/cocos/bindings/manual/jsb_dragonbones_manual.cpp @@ -38,9 +38,9 @@ using namespace cc; static bool js_cocos2dx_dragonbones_Slot_get_globalTransformMatrix(se::State &s) { dragonBones::Slot *cobj = (dragonBones::Slot *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Slot_get_globalTransformMatrix : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { dragonBones::Matrix *result = cobj->getGlobalTransformMatrix(); ok &= native_ptr_to_seval((dragonBones::Matrix *)result, &s.rval()); @@ -55,9 +55,9 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_Slot_get_globalTransformMatrix) // add by fins static bool js_cocos2dx_dragonbones_Animation_get_animations(se::State &s) { dragonBones::Animation *cobj = (dragonBones::Animation *)s.nativeThisObject(); - se::HandleObject retObj(se::Object::createPlainObject()); - bool ok = false; - se::Value tmp; + se::HandleObject retObj(se::Object::createPlainObject()); + bool ok = false; + se::Value tmp; for (const auto &e : cobj->getAnimations()) { if (!e.first.empty()) { ok = native_ptr_to_seval(e.second, __jsb_dragonBones_AnimationData_class, &tmp); @@ -72,8 +72,8 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_Animation_get_animations) static bool js_cocos2dx_dragonbones_Armature_getDisplay(se::State &s) { if (s.args().size() == 0) { - dragonBones::Armature * cobj = (dragonBones::Armature *)s.nativeThisObject(); - dragonBones::CCArmatureDisplay *ret = (dragonBones::CCArmatureDisplay *)(cobj->getDisplay()); + dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); + dragonBones::CCArmatureDisplay *ret = (dragonBones::CCArmatureDisplay *)(cobj->getDisplay()); if (ret != nullptr) { bool ok = native_ptr_to_seval(ret, __jsb_dragonBones_CCArmatureDisplay_class, &s.rval()); SE_PRECONDITION2(ok, false, "Convert dragonBones::Animation to se::Value failed!"); @@ -89,13 +89,13 @@ static bool js_cocos2dx_dragonbones_Armature_getDisplay(se::State &s) { SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getDisplay) static bool js_cocos2dx_dragonbones_Armature_getSlots(se::State &s) { - dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); - const auto & result = cobj->getSlots(); - se::HandleObject arr(se::Object::createArrayObject(result.size())); + dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); + const auto &result = cobj->getSlots(); + se::HandleObject arr(se::Object::createArrayObject(result.size())); - uint32_t i = 0; + uint32_t i = 0; se::Value tmp; - bool ok = true; + bool ok = true; for (const auto &slot : result) { if (!native_ptr_to_seval(slot, &tmp)) { ok = false; @@ -113,13 +113,13 @@ static bool js_cocos2dx_dragonbones_Armature_getSlots(se::State &s) { SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getSlots) static bool js_cocos2dx_dragonbones_Armature_getBones(se::State &s) { - dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); - const auto & result = cobj->getBones(); - se::HandleObject arr(se::Object::createArrayObject(result.size())); + dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); + const auto &result = cobj->getBones(); + se::HandleObject arr(se::Object::createArrayObject(result.size())); - uint32_t i = 0; + uint32_t i = 0; se::Value tmp; - bool ok = true; + bool ok = true; for (const auto &bone : result) { if (!native_ptr_to_seval(bone, &tmp)) { ok = false; @@ -139,12 +139,12 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getBones) static bool js_cocos2dx_dragonbones_Armature_getBoneByDisplay(se::State &s) { dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Armature_getBoneByDisplay : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { dragonBones::CCArmatureDisplay *display = nullptr; - ok = seval_to_native_ptr(args[0], &display); + ok = seval_to_native_ptr(args[0], &display); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Armature_getBoneByDisplay : Error processing arguments"); dragonBones::Bone *result = cobj->getBoneByDisplay(display); ok &= native_ptr_to_seval((dragonBones::Bone *)result, &s.rval()); @@ -159,12 +159,12 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getBoneByDisplay) static bool js_cocos2dx_dragonbones_Armature_getSlotByDisplay(se::State &s) { dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Armature_getSlotByDisplay : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { dragonBones::CCArmatureDisplay *display = nullptr; - ok = seval_to_native_ptr(args[0], &display); + ok = seval_to_native_ptr(args[0], &display); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Armature_getSlotByDisplay : Error processing arguments"); dragonBones::Slot *result = cobj->getSlotByDisplay(display); ok &= native_ptr_to_seval((dragonBones::Slot *)result, &s.rval()); @@ -179,12 +179,12 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getSlotByDisplay) static bool js_cocos2dx_dragonbones_Armature_setReplacedTexture(se::State &s) { dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Armature_setReplacedTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { middleware::Texture2D *texture = nullptr; - ok = seval_to_native_ptr(args[0], &texture); + ok = seval_to_native_ptr(args[0], &texture); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Armature_setReplacedTexture : Error processing arguments"); cobj->setReplacedTexture(texture); return true; @@ -197,12 +197,12 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_setReplacedTexture) static bool js_cocos2dx_dragonbones_Armature_getReplacedTexture(se::State &s) { dragonBones::Armature *cobj = (dragonBones::Armature *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Armature_getReplacedTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { middleware::Texture2D *result = (middleware::Texture2D *)cobj->getReplacedTexture(); - ok = native_ptr_to_seval(result, __jsb_cc_middleware_Texture2D_class, &s.rval()); + ok = native_ptr_to_seval(result, __jsb_cc_middleware_Texture2D_class, &s.rval()); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Armature_getReplacedTexture : Error processing arguments"); return true; } @@ -213,9 +213,9 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Armature_getReplacedTexture) static bool js_cocos2dx_dragonbones_ArmatureData_get_animations(se::State &s) { dragonBones::ArmatureData *cobj = (dragonBones::ArmatureData *)s.nativeThisObject(); - se::HandleObject retObj(se::Object::createPlainObject()); - bool ok = false; - se::Value tmp; + se::HandleObject retObj(se::Object::createPlainObject()); + bool ok = false; + se::Value tmp; for (const auto &e : cobj->animations) { if (!e.first.empty()) { ok = native_ptr_to_seval(e.second, __jsb_dragonBones_AnimationData_class, &tmp); @@ -230,9 +230,9 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_ArmatureData_get_animations) static bool js_cocos2dx_dragonbones_ArmatureData_get_bones(se::State &s) { dragonBones::ArmatureData *cobj = (dragonBones::ArmatureData *)s.nativeThisObject(); - se::HandleObject retObj(se::Object::createPlainObject()); - bool ok = false; - se::Value tmp; + se::HandleObject retObj(se::Object::createPlainObject()); + bool ok = false; + se::Value tmp; for (const auto &e : cobj->bones) { if (!e.first.empty()) { ok = native_ptr_to_seval(e.second, __jsb_dragonBones_BoneData_class, &tmp); @@ -247,9 +247,9 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_ArmatureData_get_bones) static bool js_cocos2dx_dragonbones_ArmatureData_get_skins(se::State &s) { dragonBones::ArmatureData *cobj = (dragonBones::ArmatureData *)s.nativeThisObject(); - se::HandleObject retObj(se::Object::createPlainObject()); - bool ok = false; - se::Value tmp; + se::HandleObject retObj(se::Object::createPlainObject()); + bool ok = false; + se::Value tmp; for (const auto &e : cobj->skins) { if (!e.first.empty()) { ok = native_ptr_to_seval(e.second, __jsb_dragonBones_SkinData_class, &tmp); @@ -264,9 +264,9 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_ArmatureData_get_skins) static bool js_cocos2dx_dragonbones_ArmatureData_get_slots(se::State &s) { dragonBones::ArmatureData *cobj = (dragonBones::ArmatureData *)s.nativeThisObject(); - se::HandleObject retObj(se::Object::createPlainObject()); - bool ok = false; - se::Value tmp; + se::HandleObject retObj(se::Object::createPlainObject()); + bool ok = false; + se::Value tmp; for (const auto &e : cobj->slots) { if (!e.first.empty()) { ok = native_ptr_to_seval(e.second, __jsb_dragonBones_SlotData_class, &tmp); @@ -283,28 +283,28 @@ static bool js_cocos2dx_dragonbones_DragonBonesData_get_armatureNames(se::State dragonBones::DragonBonesData *cobj = (dragonBones::DragonBonesData *)s.nativeThisObject(); const auto &ret = cobj->getArmatureNames(); - bool ok = nativevalue_to_se(ret, s.rval()); + bool ok = nativevalue_to_se(ret, s.rval()); SE_PRECONDITION2(ok, false, "Convert ArmatureNames to se::Value failed!"); return true; } SE_BIND_PROP_GET(js_cocos2dx_dragonbones_DragonBonesData_get_armatureNames) static bool js_cocos2dx_dragonbones_Slot_getDisplay(se::State &s) { - dragonBones::Slot * cobj = (dragonBones::Slot *)s.nativeThisObject(); - dragonBones::CCArmatureDisplay *ret = static_cast(cobj->getDisplay()); - bool ok = native_ptr_to_seval(ret, __jsb_dragonBones_CCArmatureDisplay_class, &s.rval()); + dragonBones::Slot *cobj = (dragonBones::Slot *)s.nativeThisObject(); + dragonBones::CCArmatureDisplay *ret = static_cast(cobj->getDisplay()); + bool ok = native_ptr_to_seval(ret, __jsb_dragonBones_CCArmatureDisplay_class, &s.rval()); SE_PRECONDITION2(ok, false, "Convert dragonBones::DBCCSprite to se::Value failed!"); return true; } SE_BIND_FUNC(js_cocos2dx_dragonbones_Slot_getDisplay) static bool js_cocos2dx_dragonbones_Slot_set_displayIndex(se::State &s) { - const auto & args = s.args(); + const auto &args = s.args(); dragonBones::Slot *cobj = (dragonBones::Slot *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Slot_set_displayIndex : Invalid Native Object"); CC_UNUSED bool ok = true; - int32_t arg0; + int32_t arg0; ok &= sevalue_to_native(args[0], &arg0); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Slot_set_displayIndex : Error processing new value"); cobj->setDisplayIndex(arg0); @@ -317,7 +317,7 @@ static bool js_cocos2dx_dragonbones_Slot_get_displayIndex(se::State &s) { SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_Slot_get_displayIndex : Invalid Native Object"); const int32_t ret = cobj->getDisplayIndex(); - bool ok = nativevalue_to_se(ret, s.rval()); + bool ok = nativevalue_to_se(ret, s.rval()); SE_PRECONDITION2(ok, false, "js_cocos2dx_dragonbones_Slot_get_displayIndex to se::Value failed!"); return true; } @@ -325,12 +325,12 @@ SE_BIND_PROP_GET(js_cocos2dx_dragonbones_Slot_get_displayIndex) static bool js_cocos2dx_dragonbones_Slot_setDisplay(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 2) { - dragonBones::Slot * cobj = (dragonBones::Slot *)s.nativeThisObject(); + dragonBones::Slot *cobj = (dragonBones::Slot *)s.nativeThisObject(); dragonBones::CCArmatureDisplay *dbSprite = nullptr; - bool ok = seval_to_native_ptr(args[0], &dbSprite); + bool ok = seval_to_native_ptr(args[0], &dbSprite); SE_PRECONDITION2(ok, false, "Convert se::Value to dragonBones::DBCCSprite failed!"); dragonBones::DisplayType type; ok = sevalue_to_native(args[1], (int32_t *)&type); @@ -347,12 +347,12 @@ SE_BIND_FUNC(js_cocos2dx_dragonbones_Slot_setDisplay) static bool js_cocos2dx_dragonbones_BaseFactory_parseTextureAtlasData(se::State &s) { dragonBones::BaseFactory *cobj = (dragonBones::BaseFactory *)s.nativeThisObject(); SE_PRECONDITION2(cobj, false, "js_cocos2dx_dragonbones_BaseFactory_parseTextureAtlasData : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { - const char * arg0 = nullptr; - void * arg1 = nullptr; + const char *arg0 = nullptr; + void *arg1 = nullptr; ccstd::string arg0_tmp; ok &= sevalue_to_native(args[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); @@ -364,8 +364,8 @@ static bool js_cocos2dx_dragonbones_BaseFactory_parseTextureAtlasData(se::State return true; } if (argc == 3) { - const char * arg0 = nullptr; - void * arg1 = nullptr; + const char *arg0 = nullptr; + void *arg1 = nullptr; ccstd::string arg2; ccstd::string arg0_tmp; ok &= sevalue_to_native(args[0], &arg0_tmp); @@ -380,10 +380,10 @@ static bool js_cocos2dx_dragonbones_BaseFactory_parseTextureAtlasData(se::State return true; } if (argc == 4) { - const char * arg0 = nullptr; - void * arg1 = nullptr; + const char *arg0 = nullptr; + void *arg1 = nullptr; ccstd::string arg2; - float arg3 = 0; + float arg3 = 0; ccstd::string arg0_tmp; ok &= sevalue_to_native(args[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); diff --git a/native/cocos/bindings/manual/jsb_gfx_manual.cpp b/native/cocos/bindings/manual/jsb_gfx_manual.cpp index f9cab5827a..30c0309356 100644 --- a/native/cocos/bindings/manual/jsb_gfx_manual.cpp +++ b/native/cocos/bindings/manual/jsb_gfx_manual.cpp @@ -36,12 +36,12 @@ bool js_gfx_Device_copyBuffersToTexture(se::State &s) { // NOLINT(readability-id auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Device_copyBuffersToTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture * arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture *arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); @@ -53,7 +53,7 @@ bool js_gfx_Device_copyBuffersToTexture(se::State &s) { // NOLINT(readability-id se::Value value; for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { - uint8_t * ptr = nullptr; + uint8_t *ptr = nullptr; CC_UNUSED size_t dataLength = 0; if (value.isObject()) { se::Object *obj = value.toObject(); @@ -90,12 +90,12 @@ bool js_gfx_Device_copyTextureToBuffers(se::State &s) { // NOLINT(readability-id auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Device_copyBuffersToTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::Texture * arg0 = nullptr; - ccstd::vector arg1; + cc::gfx::Texture *arg0 = nullptr; + ccstd::vector arg1; cc::gfx::BufferTextureCopyList arg2; if (args[1].isObject()) { se::Object *dataObj = args[1].toObject(); @@ -107,7 +107,7 @@ bool js_gfx_Device_copyTextureToBuffers(se::State &s) { // NOLINT(readability-id se::Value value; for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { - uint8_t * ptr = nullptr; + uint8_t *ptr = nullptr; CC_UNUSED size_t dataLength = 0; if (value.isObject()) { se::Object *obj = value.toObject(); @@ -144,14 +144,14 @@ bool js_gfx_Device_copyTexImagesToTexture(se::State &s) { // NOLINT(readability- auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Device_copyBuffersToTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture * arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture *arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; - CC_UNUSED size_t dataLength = 0; + CC_UNUSED size_t dataLength = 0; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); SE_PRECONDITION2(dataObj->isArray(), false, "Buffers must be an array!"); @@ -189,7 +189,7 @@ static bool js_gfx_Device_createBuffer(se::State &s) { // NOLINT(readability-ide auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Device_createBuffer : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { cc::gfx::Buffer *buffer = nullptr; @@ -221,11 +221,11 @@ static bool js_gfx_Device_createTexture(se::State &s) { // NOLINT(readability-id auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Device_createTexture : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { - cc::gfx::Texture *texture = nullptr; - bool createTextureView = false; + cc::gfx::Texture *texture = nullptr; + bool createTextureView = false; sevalue_to_native(args[1], &createTextureView); if (createTextureView) { cc::gfx::TextureViewInfo textureViewInfo; @@ -248,11 +248,11 @@ static bool js_gfx_Device_createTexture(se::State &s) { // NOLINT(readability-id SE_BIND_FUNC(js_gfx_Device_createTexture) static bool js_gfx_Buffer_initialize(se::State &s) { // NOLINT(readability-identifier-naming) - CC_UNUSED bool ok = true; - auto * cobj = static_cast(s.nativeThisObject()); + CC_UNUSED bool ok = true; + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Buffer_initialize : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { bool initWithBufferViewInfo = false; @@ -279,11 +279,11 @@ static bool js_gfx_Buffer_initialize(se::State &s) { // NOLINT(readability-ident SE_BIND_FUNC(js_gfx_Buffer_initialize) static bool js_gfx_Texture_initialize(se::State &s) { // NOLINT(readability-identifier-naming) - CC_UNUSED bool ok = true; - auto * cobj = static_cast(s.nativeThisObject()); + CC_UNUSED bool ok = true; + auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_Texture_initialize : Invalid Native Object"); const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { bool initWithTextureViewInfo = false; @@ -312,13 +312,13 @@ SE_BIND_FUNC(js_gfx_Texture_initialize) static bool js_gfx_GFXBuffer_update(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_GFXBuffer_update : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; - uint8_t * arg0 = nullptr; + uint8_t *arg0 = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object * obj = args[0].toObject(); + se::Object *obj = args[0].toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&arg0, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -349,12 +349,12 @@ SE_BIND_FUNC(js_gfx_GFXBuffer_update) static bool js_gfx_CommandBuffer_execute(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_execute : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { cc::gfx::CommandBufferList cmdBufs; - unsigned int count = 0; + unsigned int count = 0; ok &= sevalue_to_native(args[1], &count); se::Object *jsarr = args[0].toObject(); @@ -375,7 +375,7 @@ static bool js_gfx_CommandBuffer_execute(se::State &s) { // NOLINT(readability-i break; } auto *cmdBuf = static_cast(tmp.toObject()->getPrivateData()); - cmdBufs[i] = cmdBuf; + cmdBufs[i] = cmdBuf; } } @@ -392,17 +392,17 @@ static bool js_gfx_CommandBuffer_updateBuffer(se::State &s) { // NOLINT(readabil auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_updateBuffer : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; cc::gfx::Buffer *arg0 = nullptr; SE_PRECONDITION2(args[0].isObject(), false, "js_gfx_CommandBuffer_updateBuffer : Invalid Native Object"); arg0 = static_cast(args[0].toObject()->getPrivateData()); - uint8_t * arg1 = nullptr; + uint8_t *arg1 = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object * obj = args[1].toObject(); + se::Object *obj = args[1].toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&arg1, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -428,12 +428,12 @@ static bool js_gfx_CommandBuffer_copyBuffersToTexture(se::State &s) { // NOLINT( auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_gfx_CommandBuffer_copyBuffersToTexture : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 3) { - cc::gfx::BufferDataList arg0; - cc::gfx::Texture * arg1 = nullptr; + cc::gfx::BufferDataList arg0; + cc::gfx::Texture *arg1 = nullptr; cc::gfx::BufferTextureCopyList arg2; if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); @@ -445,9 +445,9 @@ static bool js_gfx_CommandBuffer_copyBuffersToTexture(se::State &s) { // NOLINT( se::Value value; for (uint32_t i = 0; i < length; ++i) { if (dataObj->getArrayElement(i, &value)) { - uint8_t * ptr = nullptr; + uint8_t *ptr = nullptr; CC_UNUSED size_t dataLength = 0; - se::Object * obj = value.toObject(); + se::Object *obj = value.toObject(); if (obj->isArrayBuffer()) { ok = obj->getArrayBufferData(&ptr, &dataLength); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index a4560afcf3..f8861866b5 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -51,14 +51,14 @@ using namespace cc; //NOLINT static LegacyThreadPool *gThreadPool = nullptr; -static std::shared_ptr gLocalDownloader = nullptr; +static std::shared_ptr gLocalDownloader = nullptr; static ccstd::unordered_map> gLocalDownloaderHandlers; -static uint64_t gLocalDownloaderTaskId = 1000000; +static uint64_t gLocalDownloaderTaskId = 1000000; static cc::network::Downloader *localDownloader() { if (!gLocalDownloader) { - gLocalDownloader = std::make_shared(); - gLocalDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task, + gLocalDownloader = std::make_shared(); + gLocalDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask &task, const ccstd::vector &data) { if (data.empty()) { SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); @@ -71,7 +71,7 @@ static cc::network::Downloader *localDownloader() { return; } size_t imageBytes = data.size(); - auto * imageData = static_cast(malloc(imageBytes)); + auto *imageData = static_cast(malloc(imageBytes)); memcpy(imageData, data.data(), imageBytes); (callback->second)("", imageData, static_cast(imageBytes)); @@ -79,9 +79,9 @@ static cc::network::Downloader *localDownloader() { gLocalDownloaderHandlers.erase(callback); }; gLocalDownloader->onTaskError = [=](const cc::network::DownloadTask &task, - int errorCode, //NOLINT - int errorCodeInternal, //NOLINT - const ccstd::string & errorStr) { //NOLINT + int errorCode, //NOLINT + int errorCodeInternal, //NOLINT + const ccstd::string &errorStr) { //NOLINT SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); gLocalDownloaderHandlers.erase(task.identifier); }; @@ -92,14 +92,14 @@ static cc::network::Downloader *localDownloader() { static void localDownloaderCreateTask(const ccstd::string &url, const std::function &callback) { std::stringstream ss; ss << "jsb_loadimage_" << (gLocalDownloaderTaskId++); - ccstd::string key = ss.str(); - auto task = localDownloader()->createDownloadDataTask(url, key); + ccstd::string key = ss.str(); + auto task = localDownloader()->createDownloadDataTask(url, key); gLocalDownloaderHandlers.emplace(std::make_pair(task->identifier, callback)); } bool jsb_set_extend_property(const char *ns, const char *clsName) { //NOLINT se::Object *globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); - se::Value nsVal; + se::Value nsVal; if (globalObj->getProperty(ns, &nsVal) && nsVal.isObject()) { se::Value ccVal; if (globalObj->getProperty("cc", &ccVal) && ccVal.isObject()) { @@ -124,7 +124,7 @@ ccstd::unordered_map gModuleCache; static bool require(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); CC_ASSERT(argc >= 1); CC_ASSERT(args[0].isString()); @@ -166,7 +166,7 @@ static bool doModuleRequire(const ccstd::string &path, se::Value *ret, const ccs } } - fullPath = fileOperationDelegate.onGetFullPath(secondPath); + fullPath = fileOperationDelegate.onGetFullPath(secondPath); scriptBuffer = fileOperationDelegate.onGetStringFromFile(fullPath); } else { fullPath = fileOperationDelegate.onGetFullPath(pathWithSuffix); @@ -182,7 +182,7 @@ static bool doModuleRequire(const ccstd::string &path, se::Value *ret, const ccs ccstd::string currentScriptFileDir = FileUtils::getInstance()->getFileDir(fullPath); // Add closure for evalutate the script - char prefix[] = "(function(currentScriptDir){ window.module = window.module || {}; var exports = window.module.exports = {}; "; + char prefix[] = "(function(currentScriptDir){ window.module = window.module || {}; var exports = window.module.exports = {}; "; char suffix[512] = {0}; snprintf(suffix, sizeof(suffix), "\nwindow.module.exports = window.module.exports || exports;\n})('%s'); ", currentScriptFileDir.c_str()); @@ -209,8 +209,8 @@ static bool doModuleRequire(const ccstd::string &path, se::Value *ret, const ccs const ccstd::string &reletivePath = fullPath; #endif - auto se = se::ScriptEngine::getInstance(); - bool succeed = se->evalString(scriptBuffer.c_str(), static_cast(scriptBuffer.length()), nullptr, reletivePath.c_str()); + auto se = se::ScriptEngine::getInstance(); + bool succeed = se->evalString(scriptBuffer.c_str(), static_cast(scriptBuffer.length()), nullptr, reletivePath.c_str()); se::Value moduleVal; if (succeed && se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject()) { se::Value exportsVal; @@ -238,7 +238,7 @@ static bool doModuleRequire(const ccstd::string &path, se::Value *ret, const ccs static bool moduleRequire(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); CC_ASSERT(argc >= 2); CC_ASSERT(args[0].isString()); CC_ASSERT(args[1].isString()); @@ -268,7 +268,7 @@ static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { //NOLINT struct NamePtrStruct { const char *name; - void * ptr; + void *ptr; }; ccstd::vector namePtrArray; @@ -278,12 +278,12 @@ static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { //NOLINT CC_ASSERT(jsobj->_getClass() != nullptr); NamePtrStruct tmp; tmp.name = jsobj->_getClass()->getName(); - tmp.ptr = e.first; + tmp.ptr = e.first; namePtrArray.push_back(tmp); } std::sort(namePtrArray.begin(), namePtrArray.end(), [](const NamePtrStruct &a, const NamePtrStruct &b) -> bool { - ccstd::string left = a.name; + ccstd::string left = a.name; ccstd::string right = b.name; for (ccstd::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit) { if (::tolower(*lit) < ::tolower(*rit)) { @@ -386,7 +386,7 @@ SE_BIND_FUNC(JSB_closeWindow) static bool JSB_isObjectValid(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 1) { void *nativePtr = nullptr; seval_to_native_ptr(args[0], &nativePtr); @@ -401,9 +401,9 @@ SE_BIND_FUNC(JSB_isObjectValid) static bool JSB_setCursorEnabled(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments"); - bool ok = true; + bool ok = true; bool value = true; ok &= sevalue_to_native(args[0], &value); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -417,9 +417,9 @@ SE_BIND_FUNC(JSB_setCursorEnabled) static bool JSB_saveByteCode(se::State &s) { //NOLINT const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments"); - bool ok = true; + bool ok = true; ccstd::string srcfile; ccstd::string dstfile; ok &= sevalue_to_native(args[0], &srcfile); @@ -448,7 +448,7 @@ static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::O } static bool js_performance_now(se::State &s) { //NOLINT - auto now = std::chrono::steady_clock::now(); + auto now = std::chrono::steady_clock::now(); auto micro = std::chrono::duration_cast(now - se::ScriptEngine::getInstance()->getStartTime()).count(); s.rval().setDouble(static_cast(micro) * 0.001); return true; @@ -457,19 +457,19 @@ SE_BIND_FUNC(js_performance_now) namespace { struct ImageInfo { - uint32_t length = 0; - uint32_t width = 0; - uint32_t height = 0; - uint8_t * data = nullptr; - cc::gfx::Format format = cc::gfx::Format::UNKNOWN; - bool hasAlpha = false; - bool compressed = false; + uint32_t length = 0; + uint32_t width = 0; + uint32_t height = 0; + uint8_t *data = nullptr; + cc::gfx::Format format = cc::gfx::Format::UNKNOWN; + bool hasAlpha = false; + bool compressed = false; }; uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src++; + dst[i] = *src++; dst[i + 1] = *src++; dst[i + 2] = *src++; dst[i + 3] = 255; @@ -480,7 +480,7 @@ uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src; + dst[i] = *src; dst[i + 1] = *src; dst[i + 2] = *src++; dst[i + 3] = *src++; @@ -491,7 +491,7 @@ uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src; + dst[i] = *src; dst[i + 1] = *src; dst[i + 2] = *src++; dst[i + 3] = 255; @@ -500,12 +500,12 @@ uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { } struct ImageInfo *createImageInfo(Image *img) { - auto *imgInfo = ccnew struct ImageInfo(); + auto *imgInfo = ccnew struct ImageInfo(); imgInfo->length = static_cast(img->getDataLen()); - imgInfo->width = img->getWidth(); + imgInfo->width = img->getWidth(); imgInfo->height = img->getHeight(); img->takeData(&imgInfo->data); - imgInfo->format = img->getRenderFormat(); + imgInfo->format = img->getRenderFormat(); imgInfo->compressed = img->isCompressed(); // Convert to RGBA888 because standard web api will return only RGBA888. @@ -515,9 +515,9 @@ struct ImageInfo *createImageInfo(Image *img) { // format, or it will cause 0x502 error on OpenGL ES 2. if (!imgInfo->compressed && imgInfo->format != cc::gfx::Format::RGBA8) { imgInfo->length = img->getWidth() * img->getHeight() * 4; - uint8_t *dst = nullptr; + uint8_t *dst = nullptr; uint32_t length = imgInfo->length; - uint8_t *src = imgInfo->data; + uint8_t *src = imgInfo->data; switch (imgInfo->format) { case cc::gfx::Format::A8: case cc::gfx::Format::LA8: @@ -537,7 +537,7 @@ struct ImageInfo *createImageInfo(Image *img) { } if (dst != imgInfo->data) free(imgInfo->data); - imgInfo->data = dst; + imgInfo->data = dst; imgInfo->hasAlpha = true; } @@ -578,8 +578,8 @@ bool jsb_global_load_image(const ccstd::string &path, const se::Value &callbackV CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { se::AutoHandleScope hs; - se::ValueArray seArgs; - se::Value dataVal; + se::ValueArray seArgs; + se::Value dataVal; if (loadSucceed) { se::HandleObject retObj(se::Object::createPlainObject()); @@ -604,12 +604,12 @@ bool jsb_global_load_image(const ccstd::string &path, const se::Value &callbackV localDownloaderCreateTask(path, initImageFunc); } else if (path.find("data:") == 0 && (pos = path.find("base64,")) != ccstd::string::npos) { - int imageBytes = 0; - unsigned char *imageData = nullptr; - size_t dataStartPos = pos + strlen("base64,"); - const char * base64Data = path.data() + dataStartPos; - size_t dataLen = path.length() - dataStartPos; - imageBytes = base64Decode(reinterpret_cast(base64Data), static_cast(dataLen), &imageData); + int imageBytes = 0; + unsigned char *imageData = nullptr; + size_t dataStartPos = pos + strlen("base64,"); + const char *base64Data = path.data() + dataStartPos; + size_t dataLen = path.length() - dataStartPos; + imageBytes = base64Decode(reinterpret_cast(base64Data), static_cast(dataLen), &imageData); if (imageBytes <= 0 || imageData == nullptr) { SE_REPORT_ERROR("Decode base64 image data failed!"); return false; @@ -631,9 +631,9 @@ bool jsb_global_load_image(const ccstd::string &path, const se::Value &callbackV } static bool js_loadImage(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { ccstd::string path; ok &= sevalue_to_native(args[0], &path); @@ -651,9 +651,9 @@ static bool js_loadImage(se::State &s) { //NOLINT SE_BIND_FUNC(js_loadImage) static bool js_destroyImage(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { auto *data = reinterpret_cast(args[0].asPtr()); SE_PRECONDITION2(ok, false, "js_destroyImage : Error processing arguments"); @@ -666,9 +666,9 @@ static bool js_destroyImage(se::State &s) { //NOLINT SE_BIND_FUNC(js_destroyImage) static bool JSB_openURL(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc > 0) { ccstd::string url; ok = sevalue_to_native(args[0], &url); @@ -685,9 +685,9 @@ static bool JSB_openURL(se::State &s) { //NOLINT SE_BIND_FUNC(JSB_openURL) static bool JSB_copyTextToClipboard(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc > 0) { ccstd::string text; ok = sevalue_to_native(args[0], &text); @@ -704,9 +704,9 @@ static bool JSB_copyTextToClipboard(se::State &s) { //NOLINT SE_BIND_FUNC(JSB_copyTextToClipboard) static bool JSB_setPreferredFramesPerSecond(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc > 0) { int32_t fps; ok = sevalue_to_native(args[0], &fps); @@ -724,10 +724,10 @@ SE_BIND_FUNC(JSB_setPreferredFramesPerSecond) #if CC_USE_EDITBOX static bool JSB_showInputBox(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { - bool ok; - se::Value tmp; + bool ok; + se::Value tmp; const auto &obj = args[0].toObject(); cc::EditBox::ShowInfo showInfo; @@ -864,9 +864,9 @@ SE_BIND_FUNC(JSB_hideInputBox) #endif static bool jsb_createExternalArrayBuffer(se::State &s) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { uint32_t byteLength{0}; ok &= sevalue_to_native(args[0], &byteLength, s.thisObject()); @@ -896,16 +896,16 @@ static bool jsb_createExternalArrayBuffer(se::State &s) { SE_BIND_FUNC(jsb_createExternalArrayBuffer) static bool JSB_zipUtils_inflateMemory(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc > 0) { unsigned char *arg0 = nullptr; - size_t arg1 = 0; + size_t arg1 = 0; if (args[0].isString()) { const ccstd::string &str = args[0].toString(); - arg0 = const_cast(reinterpret_cast(str.c_str())); - arg1 = str.size(); + arg0 = const_cast(reinterpret_cast(str.c_str())); + arg1 = str.size(); } else if (args[0].isObject()) { se::Object *obj = args[0].toObject(); if (obj->isArrayBuffer()) { @@ -922,7 +922,7 @@ static bool JSB_zipUtils_inflateMemory(se::State &s) { //NOLINT } SE_PRECONDITION2(ok, false, "args[0] is not in type of string | ArrayBuffer | TypedArray"); unsigned char *arg2 = nullptr; - int32_t len = 0; + int32_t len = 0; if (argc == 1) { len = ZipUtils::inflateMemory(arg0, static_cast(arg1), &arg2); } else if (argc == 2) { @@ -930,7 +930,7 @@ static bool JSB_zipUtils_inflateMemory(se::State &s) { //NOLINT uint32_t outLengthHint = 0; if (!args[1].isUndefined()) { outLengthHint = args[1].toUint32(); - len = ZipUtils::inflateMemoryWithHint(arg0, static_cast(arg1), &arg2, outLengthHint); + len = ZipUtils::inflateMemoryWithHint(arg0, static_cast(arg1), &arg2, outLengthHint); } else { ok = false; } @@ -954,12 +954,12 @@ SE_BIND_FUNC(JSB_zipUtils_inflateMemory) static bool JSB_zipUtils_inflateGZipFile(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { SE_PRECONDITION2(args[0].isString(), false, "path is invalid!"); - ccstd::string arg0 = args[0].toString(); - unsigned char * arg1 = nullptr; - int32_t len = ZipUtils::inflateGZipFile(arg0.c_str(), &arg1); + ccstd::string arg0 = args[0].toString(); + unsigned char *arg1 = nullptr; + int32_t len = ZipUtils::inflateGZipFile(arg0.c_str(), &arg1); se::HandleObject seObj(se::Object::createArrayBufferObject(arg1, len)); if (!seObj.isEmpty() && len > 0) { s.rval().setObject(seObj); @@ -976,11 +976,11 @@ SE_BIND_FUNC(JSB_zipUtils_inflateGZipFile) static bool JSB_zipUtils_isGZipFile(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { SE_PRECONDITION2(args[0].isString(), false, "path is invalid!"); ccstd::string arg0 = args[0].toString(); - bool flag = ZipUtils::isGZipFile(arg0.c_str()); + bool flag = ZipUtils::isGZipFile(arg0.c_str()); s.rval().setBoolean(flag); return true; } @@ -990,16 +990,16 @@ static bool JSB_zipUtils_isGZipFile(se::State &s) { //NOLINT SE_BIND_FUNC(JSB_zipUtils_isGZipFile) static bool JSB_zipUtils_isGZipBuffer(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { unsigned char *arg0 = nullptr; - size_t arg1 = 0; + size_t arg1 = 0; if (args[0].isString()) { const ccstd::string &str = args[0].toString(); - arg0 = const_cast(reinterpret_cast(str.c_str())); - arg1 = str.size(); + arg0 = const_cast(reinterpret_cast(str.c_str())); + arg1 = str.size(); } else if (args[0].isObject()) { se::Object *obj = args[0].toObject(); if (obj->isArrayBuffer()) { @@ -1026,12 +1026,12 @@ SE_BIND_FUNC(JSB_zipUtils_isGZipBuffer) static bool JSB_zipUtils_inflateCCZFile(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { SE_PRECONDITION2(args[0].isString(), false, "path is invalid!"); - ccstd::string arg0 = args[0].toString(); - unsigned char * arg1 = nullptr; - int32_t len = ZipUtils::inflateCCZFile(arg0.c_str(), &arg1); + ccstd::string arg0 = args[0].toString(); + unsigned char *arg1 = nullptr; + int32_t len = ZipUtils::inflateCCZFile(arg0.c_str(), &arg1); se::HandleObject seObj(se::Object::createArrayBufferObject(arg1, len)); if (!seObj.isEmpty() && len > 0) { s.rval().setObject(seObj); @@ -1047,16 +1047,16 @@ static bool JSB_zipUtils_inflateCCZFile(se::State &s) { //NOLINT SE_BIND_FUNC(JSB_zipUtils_inflateCCZFile) static bool JSB_zipUtils_inflateCCZBuffer(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { unsigned char *arg0 = nullptr; - size_t arg1 = 0; + size_t arg1 = 0; if (args[0].isString()) { const ccstd::string &str = args[0].toString(); - arg0 = const_cast(reinterpret_cast(str.c_str())); - arg1 = str.size(); + arg0 = const_cast(reinterpret_cast(str.c_str())); + arg1 = str.size(); } else if (args[0].isObject()) { se::Object *obj = args[0].toObject(); if (obj->isArrayBuffer()) { @@ -1072,8 +1072,8 @@ static bool JSB_zipUtils_inflateCCZBuffer(se::State &s) { //NOLINT ok = false; } SE_PRECONDITION2(ok, false, "args[0] is not in type of string | ArrayBuffer | TypedArray"); - unsigned char * arg2 = nullptr; - int32_t len = ZipUtils::inflateCCZBuffer(arg0, static_cast(arg1), &arg2); + unsigned char *arg2 = nullptr; + int32_t len = ZipUtils::inflateCCZBuffer(arg0, static_cast(arg1), &arg2); se::HandleObject seObj(se::Object::createArrayBufferObject(arg2, len)); if (!seObj.isEmpty() && len > 0) { s.rval().setObject(seObj); @@ -1090,11 +1090,11 @@ SE_BIND_FUNC(JSB_zipUtils_inflateCCZBuffer) static bool JSB_zipUtils_isCCZFile(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { ccstd::string arg0; SE_PRECONDITION2(args[0].isString(), false, "path is invalid!"); - arg0 = args[0].toString(); + arg0 = args[0].toString(); bool flag = ZipUtils::isCCZFile(arg0.c_str()); s.rval().setBoolean(flag); return true; @@ -1105,16 +1105,16 @@ static bool JSB_zipUtils_isCCZFile(se::State &s) { //NOLINT SE_BIND_FUNC(JSB_zipUtils_isCCZFile) static bool JSB_zipUtils_isCCZBuffer(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { unsigned char *arg0 = nullptr; - size_t arg1 = 0; + size_t arg1 = 0; if (args[0].isString()) { const ccstd::string &str = args[0].toString(); - arg0 = const_cast(reinterpret_cast(str.c_str())); - arg1 = str.size(); + arg0 = const_cast(reinterpret_cast(str.c_str())); + arg1 = str.size(); } else if (args[0].isObject()) { se::Object *obj = args[0].toObject(); if (obj->isArrayBuffer()) { @@ -1141,10 +1141,10 @@ SE_BIND_FUNC(JSB_zipUtils_isCCZBuffer) static bool JSB_zipUtils_setPvrEncryptionKeyPart(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 2) { SE_PRECONDITION2(args[0].isNumber() && args[1].isNumber(), false, "args is not as expected"); - int32_t arg0 = args[0].toInt32(); + int32_t arg0 = args[0].toInt32(); uint32_t arg1 = args[1].toUint32(); ZipUtils::setPvrEncryptionKeyPart(arg0, arg1); return true; @@ -1156,7 +1156,7 @@ SE_BIND_FUNC(JSB_zipUtils_setPvrEncryptionKeyPart) static bool JSB_zipUtils_setPvrEncryptionKey(se::State &s) { //NOLINT const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 4) { SE_PRECONDITION2(args[0].isNumber() && args[1].isNumber(), false, "args is not as expected"); uint32_t arg0 = args[0].toUint32(); @@ -1183,7 +1183,7 @@ SE_BIND_FINALIZE_FUNC(js_TextEncoder_finalize) static bool js_TextEncoder_constructor(se::State &s) // NOLINT(readability-identifier-naming) { const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc > 0) { if (args[0].isString() && args[0].toString() != "utf-8") { CC_LOG_WARNING("TextEncoder only supports utf-8"); @@ -1198,12 +1198,12 @@ SE_BIND_CTOR(js_TextEncoder_constructor, __jsb_TextEncoder_class, js_TextEncoder static bool js_TextEncoder_encode(se::State &s) // NOLINT(readability-identifier-naming) { const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { const auto &arg0 = args[0]; SE_PRECONDITION2(arg0.isString(), false, "js_TextEncoder_encode, arg0 is not a string"); - const auto & str = arg0.toString(); + const auto &str = arg0.toString(); se::HandleObject encodedUint8Array{ se::Object::createTypedArray(se::Object::TypedArrayType::UINT8, str.data(), str.length())}; @@ -1228,7 +1228,7 @@ SE_BIND_FINALIZE_FUNC(js_TextDecoder_finalize) static bool js_TextDecoder_constructor(se::State &s) // NOLINT(readability-identifier-naming) { const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc > 0) { if (args[0].isString() && args[0].toString() != "utf-8") { CC_LOG_WARNING("TextDecoder only supports utf-8"); @@ -1245,15 +1245,15 @@ SE_BIND_CTOR(js_TextDecoder_constructor, __jsb_TextDecoder_class, js_TextDecoder static bool js_TextDecoder_decode(se::State &s) // NOLINT(readability-identifier-naming) { const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 1) { const auto &arg0 = args[0]; SE_PRECONDITION2(arg0.isObject() && arg0.toObject()->isTypedArray(), false, "js_TextDecoder_decode, arg0 is not a Uint8Array"); - auto * uint8ArrayObj = arg0.toObject(); + auto *uint8ArrayObj = arg0.toObject(); uint8_t *uint8ArrayData = nullptr; - size_t length = 0; - bool ok = uint8ArrayObj->getTypedArrayData(&uint8ArrayData, &length); + size_t length = 0; + bool ok = uint8ArrayObj->getTypedArrayData(&uint8ArrayData, &length); SE_PRECONDITION2(ok, false, "js_TextDecoder_decode, get typedarray data failed!"); ccstd::string str{reinterpret_cast(uint8ArrayData), length}; diff --git a/native/cocos/bindings/manual/jsb_global.h b/native/cocos/bindings/manual/jsb_global.h index c9e5be4a7c..56fcc8ce44 100644 --- a/native/cocos/bindings/manual/jsb_global.h +++ b/native/cocos/bindings/manual/jsb_global.h @@ -29,7 +29,7 @@ #include "jsb_global_init.h" template -T *jsb_override_new(Args &&...args) { //NOLINT(readability-identifier-naming) +T *jsb_override_new(Args &&... args) { //NOLINT(readability-identifier-naming) //create object in the default way return ccnew T(std::forward(args)...); } @@ -42,14 +42,14 @@ void jsb_override_delete(T *arg) { //NOLINT(readability-identifier-naming) template typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object(ARGS &&...args) { //NOLINT(readability-identifier-naming) +jsb_make_private_object(ARGS &&... args) { //NOLINT(readability-identifier-naming) //return se::raw_private_data(ccnew T(std::forward(args)...)); return se::ccshared_private_object(ccnew T(std::forward(args)...)); } template typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object(ARGS &&...args) { //NOLINT(readability-identifier-naming) +jsb_make_private_object(ARGS &&... args) { //NOLINT(readability-identifier-naming) return se::shared_private_object(std::make_shared(std::forward(args)...)); } diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 01f223fa4d..21448333c7 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -48,7 +48,7 @@ using namespace cc; //NOLINT se::Object *__jsbObj = nullptr; //NOLINT -se::Object *__glObj = nullptr; //NOLINT +se::Object *__glObj = nullptr; //NOLINT static std::basic_string xxteaKey; @@ -68,10 +68,10 @@ static ccstd::string removeFileExt(const ccstd::string &filePath) { static int selectPort(int port) { struct sockaddr_in addr; - static uv_tcp_t server; - uv_loop_t loop; + static uv_tcp_t server; + uv_loop_t loop; uv_loop_init(&loop); - int tryTimes = 200; + int tryTimes = 200; int startPort = port; while (tryTimes-- > 0) { uv_tcp_init(&loop, &server); @@ -104,7 +104,7 @@ void jsb_init_file_operation_delegate() { //NOLINT fileData = FileUtils::getInstance()->getDataFromFile(byteCodePath); uint32_t dataLen = 0; - uint8_t *data = xxtea_decrypt(fileData.getBytes(), static_cast(fileData.getSize()), + uint8_t *data = xxtea_decrypt(fileData.getBytes(), static_cast(fileData.getSize()), const_cast(xxteaKey.data()), static_cast(xxteaKey.size()), reinterpret_cast(&dataLen)); diff --git a/native/cocos/bindings/manual/jsb_helper.cpp b/native/cocos/bindings/manual/jsb_helper.cpp index 36db2a4a50..c35efb2fd9 100644 --- a/native/cocos/bindings/manual/jsb_helper.cpp +++ b/native/cocos/bindings/manual/jsb_helper.cpp @@ -30,7 +30,7 @@ /* static */ void CleanupTask::pushTaskToAutoReleasePool(const std::function &cb) { auto *ret = ccnew CleanupTask; - ret->_cb = cb; + ret->_cb = cb; cc::DeferredReleasePool::add(ret); } diff --git a/native/cocos/bindings/manual/jsb_network_manual.cpp b/native/cocos/bindings/manual/jsb_network_manual.cpp index b2143969cc..eac164d8f7 100644 --- a/native/cocos/bindings/manual/jsb_network_manual.cpp +++ b/native/cocos/bindings/manual/jsb_network_manual.cpp @@ -34,9 +34,9 @@ static bool js_cocos2dx_network_Downloader_createDownloadFileTask(se::State &s) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_network_Downloader_createDownloadFileTask : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 2) { ccstd::string arg0; ccstd::string arg1; @@ -82,9 +82,9 @@ SE_BIND_FUNC(js_cocos2dx_network_Downloader_createDownloadFileTask) static bool js_network_Downloader_setOnFileTaskSuccess(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_network_Downloader_setOnFileTaskSuccess : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { std::function arg0; do { @@ -93,7 +93,7 @@ static bool js_network_Downloader_setOnFileTaskSuccess(se::State &s) { // NOLINT se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto *thisObj = s.thisObject(); - auto lambda = [=](const cc::network::DownloadTask &larg0) -> void { + auto lambda = [=](const cc::network::DownloadTask &larg0) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; @@ -101,9 +101,9 @@ static bool js_network_Downloader_setOnFileTaskSuccess(se::State &s) { // NOLINT se::ValueArray args; args.resize(1); ok &= DownloadTask_to_seval(larg0, &args[0]); - se::Value rval; + se::Value rval; se::Object *funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } @@ -128,9 +128,9 @@ SE_BIND_FUNC(js_network_Downloader_setOnFileTaskSuccess) // NOLINT(readability-i static bool js_network_Downloader_setOnTaskError(se::State &s) { // NOLINT(readability-identifier-naming) auto *cobj = static_cast(s.nativeThisObject()); SE_PRECONDITION2(cobj, false, "js_network_Downloader_setOnTaskError : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { std::function arg0; do { @@ -139,7 +139,7 @@ static bool js_network_Downloader_setOnTaskError(se::State &s) { // NOLINT(reada se::Value jsFunc(args[0]); jsThis.toObject()->attachObject(jsFunc.toObject()); auto *thisObj = s.thisObject(); - auto lambda = [=](const cc::network::DownloadTask &larg0, int larg1, int larg2, const ccstd::string &larg3) -> void { + auto lambda = [=](const cc::network::DownloadTask &larg0, int larg1, int larg2, const ccstd::string &larg3) -> void { se::ScriptEngine::getInstance()->clearException(); se::AutoHandleScope hs; @@ -150,9 +150,9 @@ static bool js_network_Downloader_setOnTaskError(se::State &s) { // NOLINT(reada ok &= nativevalue_to_se(larg1, args[1]); ok &= nativevalue_to_se(larg2, args[2]); ok &= nativevalue_to_se(larg3, args[3]); - se::Value rval; + se::Value rval; se::Object *funcObj = jsFunc.toObject(); - bool succeed = funcObj->call(args, thisObj, &rval); + bool succeed = funcObj->call(args, thisObj, &rval); if (!succeed) { se::ScriptEngine::getInstance()->clearException(); } diff --git a/native/cocos/bindings/manual/jsb_pipeline_manual.cpp b/native/cocos/bindings/manual/jsb_pipeline_manual.cpp index 6c6d76c9d1..f154a09894 100644 --- a/native/cocos/bindings/manual/jsb_pipeline_manual.cpp +++ b/native/cocos/bindings/manual/jsb_pipeline_manual.cpp @@ -35,13 +35,13 @@ static bool JSB_getOrCreatePipelineState(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc == 4) { - auto *pass = static_cast(args[0].toObject()->getPrivateData()); - auto *shader = static_cast(args[1].toObject()->getPrivateData()); - auto *renderPass = static_cast(args[2].toObject()->getPrivateData()); + auto *pass = static_cast(args[0].toObject()->getPrivateData()); + auto *shader = static_cast(args[1].toObject()->getPrivateData()); + auto *renderPass = static_cast(args[2].toObject()->getPrivateData()); auto *inputAssembler = static_cast(args[3].toObject()->getPrivateData()); - auto *pipelineState = cc::pipeline::PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); + auto *pipelineState = cc::pipeline::PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); native_ptr_to_seval(pipelineState, &s.rval()); return true; } @@ -60,7 +60,7 @@ bool register_all_pipeline_manual(se::Object *obj) { // NOLINT(readability-ident } se::Object *nr = nrVal.toObject(); - se::Value psmVal; + se::Value psmVal; se::HandleObject jsobj(se::Object::createPlainObject()); psmVal.setObject(jsobj); nr->setProperty("PipelineStateManager", psmVal); diff --git a/native/cocos/bindings/manual/jsb_platform.h b/native/cocos/bindings/manual/jsb_platform.h index 79e9ab4695..4181a9ae03 100644 --- a/native/cocos/bindings/manual/jsb_platform.h +++ b/native/cocos/bindings/manual/jsb_platform.h @@ -31,5 +31,5 @@ namespace se { class Object; } -bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifier-naming] +bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifier-naming] const ccstd::unordered_map &getFontFamilyNameMap(); diff --git a/native/cocos/bindings/manual/jsb_platform_android.cpp b/native/cocos/bindings/manual/jsb_platform_android.cpp index 7577911e4f..cb185e4fd1 100644 --- a/native/cocos/bindings/manual/jsb_platform_android.cpp +++ b/native/cocos/bindings/manual/jsb_platform_android.cpp @@ -46,9 +46,9 @@ const ccstd::unordered_map &getFontFamilyNameMap() } static bool JSB_loadFont(se::State &s) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); @@ -60,8 +60,8 @@ static bool JSB_loadFont(se::State &s) { ok &= sevalue_to_native(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - ccstd::string fontFilePath; - std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + ccstd::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); std::match_results results; if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); diff --git a/native/cocos/bindings/manual/jsb_platform_ohos.cpp b/native/cocos/bindings/manual/jsb_platform_ohos.cpp index 5249d4efce..2a836eb71c 100644 --- a/native/cocos/bindings/manual/jsb_platform_ohos.cpp +++ b/native/cocos/bindings/manual/jsb_platform_ohos.cpp @@ -46,9 +46,9 @@ const ccstd::unordered_map &getFontFamilyNameMap() } static bool JSB_loadFont(se::State &s) { //NOLINT - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); @@ -60,8 +60,8 @@ static bool JSB_loadFont(se::State &s) { //NOLINT ok &= sevalue_to_native(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - ccstd::string fontFilePath; - std::regex re(R"(url\(\s*'\s*(.*?)\s*'\s*\))"); + ccstd::string fontFilePath; + std::regex re(R"(url\(\s*'\s*(.*?)\s*'\s*\))"); std::match_results results; if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); diff --git a/native/cocos/bindings/manual/jsb_platfrom_linux.cpp b/native/cocos/bindings/manual/jsb_platfrom_linux.cpp index e416761785..4b44e54a50 100644 --- a/native/cocos/bindings/manual/jsb_platfrom_linux.cpp +++ b/native/cocos/bindings/manual/jsb_platfrom_linux.cpp @@ -41,9 +41,9 @@ const ccstd::unordered_map &getFontFamilyNameMap() } static bool JSB_loadFont(se::State &s) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); @@ -55,8 +55,8 @@ static bool JSB_loadFont(se::State &s) { ok &= sevalue_to_native(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - ccstd::string fontFilePath; - std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + ccstd::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); std::match_results results; if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); diff --git a/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp b/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp index 35df8751d8..7f7e62162d 100644 --- a/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp +++ b/native/cocos/bindings/manual/jsb_platfrom_qnx.cpp @@ -41,9 +41,9 @@ const ccstd::unordered_map &getFontFamilyNameMap() } static bool JSB_loadFont(se::State &s) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); @@ -55,8 +55,8 @@ static bool JSB_loadFont(se::State &s) { ok &= seval_to_std_string(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - ccstd::string fontFilePath; - std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + ccstd::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); std::match_results results; if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); diff --git a/native/cocos/bindings/manual/jsb_platfrom_win32.cpp b/native/cocos/bindings/manual/jsb_platfrom_win32.cpp index 49d7c232f8..c01327688d 100644 --- a/native/cocos/bindings/manual/jsb_platfrom_win32.cpp +++ b/native/cocos/bindings/manual/jsb_platfrom_win32.cpp @@ -41,9 +41,9 @@ const ccstd::unordered_map &getFontFamilyNameMap() } static bool JSB_loadFont(se::State &s) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); @@ -55,8 +55,8 @@ static bool JSB_loadFont(se::State &s) { ok &= sevalue_to_native(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - ccstd::string fontFilePath; - std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); + ccstd::string fontFilePath; + std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); std::match_results results; if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index b3106a1fec..fdb1ef350d 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -42,7 +42,7 @@ static se::Object *nodeVec3CacheObj{nullptr}; static se::Object *nodeQuatCacheObj{nullptr}; static se::Object *nodeMat4CacheObj{nullptr}; -static float * tempFloatArray{nullptr}; +static float *tempFloatArray{nullptr}; static bool js_root_registerListeners(se::State &s) // NOLINT(readability-identifier-naming) { @@ -52,8 +52,8 @@ static bool js_root_registerListeners(se::State &s) // NOLINT(readability-identi #define DISPATCH_EVENT_TO_JS_ARGS_0(eventType, jsFuncName) \ cobj->getEventProcessor()->on(eventType, [](cc::Root *rootObj) { \ se::AutoHandleScope hs; \ - se::Value rootVal; \ - bool ok = nativevalue_to_se(rootObj, rootVal); \ + se::Value rootVal; \ + bool ok = nativevalue_to_se(rootObj, rootVal); \ SE_PRECONDITION2_FUNCNAME_VOID(ok, #jsFuncName, "js_root_registerListeners : Error processing arguments"); \ if (rootVal.isObject()) { \ se::ScriptEngine::getInstance()->callFunction(rootVal.toObject(), #jsFuncName, 0, nullptr); \ @@ -75,7 +75,7 @@ static void registerOnTransformChanged(cc::Node *node, se::Object *jsObject) { cc::NodeEventType::TRANSFORM_CHANGED, [jsObject](cc::TransformBit transformBit) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(transformBit, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onTransformChanged", 1, &arg0); }); @@ -86,7 +86,7 @@ static void registerOnParentChanged(cc::Node *node, se::Object *jsObject) { cc::NodeEventType::PARENT_CHANGED, [jsObject](cc::Node *oldParent) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(oldParent, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onParentChanged", 1, &arg0); }); @@ -97,7 +97,7 @@ static void registerOnLayerChanged(cc::Node *node, se::Object *jsObject) { cc::NodeEventType::LAYER_CHANGED, [jsObject](uint32_t layer) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(layer, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLayerChanged", 1, &arg0); }); @@ -108,7 +108,7 @@ static void registerOnChildRemoved(cc::Node *node, se::Object *jsObject) { cc::NodeEventType::CHILD_REMOVED, [jsObject](cc::Node *child) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(child, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onChildRemoved", 1, &arg0); }); @@ -119,7 +119,7 @@ static void registerOnChildAdded(cc::Node *node, se::Object *jsObject) { cc::NodeEventType::CHILD_ADDED, [jsObject](cc::Node *child) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(child, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onChildAdded", 1, &arg0); }); @@ -140,7 +140,7 @@ static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { cc::EventTypesToJS::NODE_ACTIVE_NODE, [jsObject](bool shouldActiveNow) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(shouldActiveNow, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onActiveNode", 1, &arg0); }, @@ -153,7 +153,7 @@ static void registerOnBatchCreated(cc::Node *node, se::Object *jsObject) { cc::EventTypesToJS::NODE_ON_BATCH_CREATED, [jsObject](bool dontChildPrefab) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(dontChildPrefab, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onBatchCreated", 1, &arg0); }, @@ -169,37 +169,37 @@ static void registerOnUiTransformDirty(cc::Node *node, se::Object *jsObject) { SE_PRECONDITION2_VOID(uiTransformDirtyVal.isObject() && uiTransformDirtyVal.toObject()->isTypedArray() && uiTransformDirtyVal.toObject()->getTypedArrayType() == se::Object::TypedArrayType::UINT32, "_uiTransformDirtyVal is not a TypedArray"); uint8_t *pDirty{nullptr}; - size_t dirtyArrBytes{0}; - bool ok = uiTransformDirtyVal.toObject()->getTypedArrayData(&pDirty, &dirtyArrBytes); + size_t dirtyArrBytes{0}; + bool ok = uiTransformDirtyVal.toObject()->getTypedArrayData(&pDirty, &dirtyArrBytes); CC_ASSERT(ok && pDirty != nullptr && dirtyArrBytes == 4); node->setUIPropsTransformDirtyPtr(reinterpret_cast(pDirty)); } static void registerActiveInHierarchyArr(cc::Node *node, se::Object *jsObject) { se::Value activeInHierarchyArrVal; - bool ok = jsObject->getProperty("_activeInHierarchyArr", &activeInHierarchyArrVal); + bool ok = jsObject->getProperty("_activeInHierarchyArr", &activeInHierarchyArrVal); CC_ASSERT(ok && activeInHierarchyArrVal.isObject() && activeInHierarchyArrVal.toObject()->isTypedArray() && activeInHierarchyArrVal.toObject()->getTypedArrayType() == se::Object::TypedArrayType::UINT8); uint8_t *pActiveInHierarchyArrData = nullptr; - ok = activeInHierarchyArrVal.toObject()->getTypedArrayData(&pActiveInHierarchyArrData, nullptr); + ok = activeInHierarchyArrVal.toObject()->getTypedArrayData(&pActiveInHierarchyArrData, nullptr); CC_ASSERT(ok); node->setActiveInHierarchyPtr(pActiveInHierarchyArrData); } static void registerLayerArr(cc::Node *node, se::Object *jsObject) { se::Value layerArrVal; - bool ok = jsObject->getProperty("_layerArr", &layerArrVal); + bool ok = jsObject->getProperty("_layerArr", &layerArrVal); CC_ASSERT(ok && layerArrVal.isObject() && layerArrVal.toObject()->isTypedArray() && layerArrVal.toObject()->getTypedArrayType() == se::Object::TypedArrayType::UINT32); uint8_t *pLayerArrValData = nullptr; - ok = layerArrVal.toObject()->getTypedArrayData(&pLayerArrValData, nullptr); + ok = layerArrVal.toObject()->getTypedArrayData(&pLayerArrValData, nullptr); CC_ASSERT(ok); node->setLayerPtr(reinterpret_cast(pLayerArrValData)); } static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object *jsObject) { node->on(cc::EventTypesToJS::NODE_LOCAL_POSITION_UPDATED, [jsObject](float x, float y, float z) { - se::AutoHandleScope hs; + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); nativevalue_to_se(y, args[1]); @@ -208,7 +208,7 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object }); node->on(cc::EventTypesToJS::NODE_LOCAL_ROTATION_UPDATED, [jsObject](float x, float y, float z, float w) { - se::AutoHandleScope hs; + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); nativevalue_to_se(y, args[1]); @@ -218,7 +218,7 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object }); node->on(cc::EventTypesToJS::NODE_LOCAL_SCALE_UPDATED, [jsObject](float x, float y, float z) { - se::AutoHandleScope hs; + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); nativevalue_to_se(y, args[1]); @@ -227,7 +227,7 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object }); node->on(cc::EventTypesToJS::NODE_LOCAL_POSITION_ROTATION_SCALE_UPDATED, [jsObject](float px, float py, float pz, float rx, float ry, float rz, float rw, float sx, float sy, float sz) { - se::AutoHandleScope hs; + se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(px, args[0]); nativevalue_to_se(py, args[1]); @@ -276,28 +276,28 @@ static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability- cc::NodeEventType::NODE_DESTROYED, [](cc::Node *node) { se::AutoHandleScope hs; - se::Value nodeVal; + se::Value nodeVal; nativevalue_to_se(node, nodeVal); se::ScriptEngine::getInstance()->callFunction(nodeVal.toObject(), "_onNodeDestroyed", 1, &nodeVal); }); cobj->onSiblingIndexChanged = [jsObject](index_t newIndex) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(newIndex, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSiblingIndexChanged", 1, &arg0); }; cobj->on(cc::EventTypesToJS::NODE_SCENE_UPDATED, [jsObject](cc::Scene *scene) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(scene, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSceneUpdated", 1, &arg0); }); cobj->on(cc::EventTypesToJS::NODE_EDITOR_ATTACHED, [jsObject](bool attached) { se::AutoHandleScope hs; - se::Value arg0; + se::Value arg0; nativevalue_to_se(attached, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onEditorAttached", 1, &arg0); }); @@ -430,22 +430,22 @@ static bool scene_Mat4_to_seval(const cc::Mat4 &v, se::Value *ret) { // NOLINT(r static bool js_scene_Camera_screenPointToRay(void *nativeObject) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(nativeObject); - cc::geometry::Ray ray = cobj->screenPointToRay(tempFloatArray[0], tempFloatArray[1]); - tempFloatArray[0] = ray.o.x; - tempFloatArray[1] = ray.o.y; - tempFloatArray[2] = ray.o.z; - tempFloatArray[3] = ray.d.x; - tempFloatArray[4] = ray.d.y; - tempFloatArray[5] = ray.d.z; + auto *cobj = reinterpret_cast(nativeObject); + cc::geometry::Ray ray = cobj->screenPointToRay(tempFloatArray[0], tempFloatArray[1]); + tempFloatArray[0] = ray.o.x; + tempFloatArray[1] = ray.o.y; + tempFloatArray[2] = ray.o.z; + tempFloatArray[3] = ray.d.x; + tempFloatArray[4] = ray.d.y; + tempFloatArray[5] = ray.d.z; return true; } SE_BIND_FUNC_FAST(js_scene_Camera_screenPointToRay) static bool js_scene_Camera_screenToWorld(void *nativeObject) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(nativeObject); - cc::Vec3 ret = cobj->screenToWorld(cc::Vec3{tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]}); + auto *cobj = reinterpret_cast(nativeObject); + cc::Vec3 ret = cobj->screenToWorld(cc::Vec3{tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]}); tempFloatArray[0] = ret.x; tempFloatArray[1] = ret.y; tempFloatArray[2] = ret.z; @@ -455,8 +455,8 @@ SE_BIND_FUNC_FAST(js_scene_Camera_screenToWorld) static bool js_scene_Camera_worldToScreen(void *nativeObject) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(nativeObject); - cc::Vec3 ret = cobj->worldToScreen(cc::Vec3{tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]}); + auto *cobj = reinterpret_cast(nativeObject); + cc::Vec3 ret = cobj->worldToScreen(cc::Vec3{tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]}); tempFloatArray[0] = ret.x; tempFloatArray[1] = ret.y; tempFloatArray[2] = ret.z; @@ -478,20 +478,20 @@ SE_BIND_FUNC_FAST(js_scene_Camera_worldMatrixToScreen) static bool js_scene_Node_getPosition(void *nativeObj) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(nativeObj); + auto *cobj = reinterpret_cast(nativeObj); const cc::Vec3 &result = cobj->getPosition(); - tempFloatArray[0] = result.x; - tempFloatArray[1] = result.y; - tempFloatArray[2] = result.z; + tempFloatArray[0] = result.x; + tempFloatArray[1] = result.y; + tempFloatArray[2] = result.z; return true; } SE_BIND_FUNC_FAST(js_scene_Node_getPosition) static bool js_scene_Node_setTempFloatArray(se::State &s) // NOLINT(readability-identifier-naming) { - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 1) { uint8_t *buffer = nullptr; args[0].toObject()->getArrayBufferData(&buffer, nullptr); @@ -507,9 +507,9 @@ static bool js_scene_Node_getRight(se::State &s) // NOLINT(readability-identifie { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getRight : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::Vec3 result = cobj->getRight(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -526,9 +526,9 @@ static bool js_scene_Node_getRotation(se::State &s) // NOLINT(readability-identi { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getRotation : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Quaternion &result = cobj->getRotation(); ok &= scene_Quaternion_to_seval(result, &s.rval()); @@ -545,9 +545,9 @@ static bool js_scene_Node_getScale(se::State &s) // NOLINT(readability-identifie { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getScale : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Vec3 &result = cobj->getScale(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -563,7 +563,7 @@ SE_BIND_FUNC(js_scene_Node_getScale) static bool js_scene_Node_setPosition(void *s) // NOLINT(readability-identifier-naming) { auto *cobj = reinterpret_cast(s); - auto argc = static_cast(tempFloatArray[0]); + auto argc = static_cast(tempFloatArray[0]); if (argc == 2) { cobj->setPositionInternal(tempFloatArray[1], tempFloatArray[2], true); @@ -593,7 +593,7 @@ SE_BIND_FUNC_FAST(js_scene_Node_setRotationFromEuler) static bool js_scene_Node_setScale(void *s) // NOLINT(readability-identifier-naming) { auto *cobj = reinterpret_cast(s); - auto argc = static_cast(tempFloatArray[0]); + auto argc = static_cast(tempFloatArray[0]); if (argc == 2) { cobj->setScaleInternal(tempFloatArray[1], tempFloatArray[2], true); @@ -606,20 +606,20 @@ SE_BIND_FUNC_FAST(js_scene_Node_setScale) static bool js_scene_Node_setRTS(void *s) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(s); + auto *cobj = reinterpret_cast(s); cc::Quaternion qt; - auto rotSize = static_cast(tempFloatArray[0]); + auto rotSize = static_cast(tempFloatArray[0]); if (rotSize > 0) { qt.set(tempFloatArray[1], tempFloatArray[2], tempFloatArray[3], tempFloatArray[4]); } - auto posSize = static_cast(tempFloatArray[5]); + auto posSize = static_cast(tempFloatArray[5]); cc::Vec3 pos; if (posSize > 0) { pos.set(tempFloatArray[6], tempFloatArray[7], tempFloatArray[8]); } - auto scaleSize = static_cast(tempFloatArray[9]); + auto scaleSize = static_cast(tempFloatArray[9]); cc::Vec3 scale; if (scaleSize > 0) { scale.set(tempFloatArray[10], tempFloatArray[11], tempFloatArray[12]); @@ -632,7 +632,7 @@ SE_BIND_FUNC_FAST(js_scene_Node_setRTS) static bool js_scene_Node_rotateForJS(void *s) // NOLINT(readability-identifier-naming) { auto *cobj = reinterpret_cast(s); - auto argc = static_cast(tempFloatArray[0]); + auto argc = static_cast(tempFloatArray[0]); if (argc == 4) { cobj->rotateForJS(tempFloatArray[1], tempFloatArray[2], tempFloatArray[3], tempFloatArray[4]); } else { @@ -640,7 +640,7 @@ static bool js_scene_Node_rotateForJS(void *s) // NOLINT(readability-identifier- cobj->rotateForJS(tempFloatArray[1], tempFloatArray[2], tempFloatArray[3], tempFloatArray[4], size == 0 ? cc::NodeSpace::LOCAL : static_cast(static_cast(std::roundf(tempFloatArray[5])))); } - const auto &lrot = cobj->getRotation(); + const auto &lrot = cobj->getRotation(); tempFloatArray[0] = lrot.x; tempFloatArray[1] = lrot.y; tempFloatArray[2] = lrot.z; @@ -653,9 +653,9 @@ static bool js_scene_Node_getUp(se::State &s) // NOLINT(readability-identifier-n { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getUp : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::Vec3 result = cobj->getUp(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -670,7 +670,7 @@ SE_BIND_FUNC(js_scene_Node_getUp) static bool js_scene_Node_getWorldMatrix(void *nativeObject) // NOLINT(readability-identifier-naming) { - auto * cobj = reinterpret_cast(nativeObject); + auto *cobj = reinterpret_cast(nativeObject); const cc::Mat4 &result = cobj->getWorldMatrix(); memcpy(tempFloatArray, result.m, sizeof(result.m)); return true; @@ -681,9 +681,9 @@ static bool js_scene_Node_getWorldPosition(se::State &s) // NOLINT(readability-i { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getWorldPosition : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Vec3 &result = cobj->getWorldPosition(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -700,9 +700,9 @@ static bool js_scene_Node_getWorldRS(se::State &s) // NOLINT(readability-identif { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getWorldRS : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::Mat4 result = cobj->getWorldRS(); ok &= scene_Mat4_to_seval(result, &s.rval()); @@ -719,9 +719,9 @@ static bool js_scene_Node_getWorldRT(se::State &s) // NOLINT(readability-identif { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getWorldRT : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::Mat4 result = cobj->getWorldRT(); ok &= scene_Mat4_to_seval(result, &s.rval()); @@ -738,9 +738,9 @@ static bool js_scene_Node_getWorldRotation(se::State &s) // NOLINT(readability-i { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getWorldRotation : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Quaternion &result = cobj->getWorldRotation(); ok &= scene_Quaternion_to_seval(result, &s.rval()); @@ -757,9 +757,9 @@ static bool js_scene_Node_getWorldScale(se::State &s) // NOLINT(readability-iden { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getWorldScale : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Vec3 &result = cobj->getWorldScale(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -776,9 +776,9 @@ static bool js_scene_Node_getEulerAngles(se::State &s) // NOLINT(readability-ide { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getEulerAngles : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { const cc::Vec3 &result = cobj->getEulerAngles(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -795,9 +795,9 @@ static bool js_scene_Node_getForward(se::State &s) // NOLINT(readability-identif { auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "js_scene_Node_getForward : Invalid Native Object"); - const auto & args = s.args(); - size_t argc = args.size(); - CC_UNUSED bool ok = true; + const auto &args = s.args(); + size_t argc = args.size(); + CC_UNUSED bool ok = true; if (argc == 0) { cc::Vec3 result = cobj->getForward(); ok &= scene_Vec3_to_seval(result, &s.rval()); @@ -821,11 +821,11 @@ static bool js_scene_Pass_blocks_getter(se::State &s) { // NOLINT(readability-id return true; } - const auto & blocks = cobj->getBlocks(); + const auto &blocks = cobj->getBlocks(); const uint8_t *blockDataBase = cobj->getRootBlock()->getData(); se::HandleObject jsBlocks{se::Object::createArrayObject(blocks.size())}; - int32_t i = 0; + int32_t i = 0; for (const auto &block : blocks) { se::HandleObject jsBlock{ se::Object::createTypedArrayWithBuffer( @@ -858,7 +858,7 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident cobj->getEventProcessor().on(eventType, [=](uint32_t stamp) { \ cobj->setCalledFromJS(true); \ se::AutoHandleScope hs; \ - se::Value stampVal{stamp}; \ + se::Value stampVal{stamp}; \ se::ScriptEngine::getInstance()->callFunction(thiz, #jsFuncName, 1, &stampVal); \ }) @@ -891,7 +891,7 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident cobj->setCalledFromJS(true); se::AutoHandleScope hs; - se::Value rval; + se::Value rval; ccstd::array args; nativevalue_to_se(subModelIndex, args[0]); bool ok = se::ScriptEngine::getInstance()->callFunction(thiz, "getMacroPatches", static_cast(args.size()), args.data(), &rval); @@ -911,8 +911,8 @@ static bool js_assets_MaterialInstance_registerListeners(se::State &s) // NOLINT SE_PRECONDITION2(cobj, false, "js_assets_MaterialInstance_registerListeners : Invalid Native Object"); cobj->setRebuildPSOCallback([](index_t /*index*/, cc::Material *material) { se::AutoHandleScope hs; - se::Value matVal; - bool ok = nativevalue_to_se(material, matVal); + se::Value matVal; + bool ok = nativevalue_to_se(material, matVal); if (!ok) { return; } diff --git a/native/cocos/bindings/manual/jsb_socketio.cpp b/native/cocos/bindings/manual/jsb_socketio.cpp index c699daa159..35274142f0 100644 --- a/native/cocos/bindings/manual/jsb_socketio.cpp +++ b/native/cocos/bindings/manual/jsb_socketio.cpp @@ -108,7 +108,7 @@ public: const se::ValueArray &cbStruct = it->second; CC_ASSERT(cbStruct.size() == 2); const se::Value &callback = cbStruct[0]; - const se::Value &target = cbStruct[1]; + const se::Value &target = cbStruct[1]; if (callback.isObject() && callback.toObject()->isFunction() && target.isObject()) { se::ValueArray args; args.push_back(dataVal); @@ -164,12 +164,12 @@ SE_BIND_PROP_SET(SocketIO_prop_setTag) // NOLINT(readability-identifier-naming) static bool SocketIO_send(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); - auto * cobj = static_cast(s.nativeThisObject()); + int argc = static_cast(args.size()); + auto *cobj = static_cast(s.nativeThisObject()); if (argc == 1) { ccstd::string payload; - bool ok = sevalue_to_native(args[0], &payload); + bool ok = sevalue_to_native(args[0], &payload); SE_PRECONDITION2(ok, false, "Converting payload failed!"); cobj->send(payload); @@ -183,11 +183,11 @@ SE_BIND_FUNC(SocketIO_send) // NOLINT(readability-identifier-naming) static bool SocketIO_emit(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); - auto * cobj = static_cast(s.nativeThisObject()); + int argc = static_cast(args.size()); + auto *cobj = static_cast(s.nativeThisObject()); if (argc >= 1) { - bool ok = false; + bool ok = false; ccstd::string eventName; ok = sevalue_to_native(args[0], &eventName); SE_PRECONDITION2(ok, false, "Converting eventName failed!"); @@ -216,8 +216,8 @@ SE_BIND_FUNC(SocketIO_emit) // NOLINT(readability-identifier-naming) static bool SocketIO_disconnect(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); - auto * cobj = static_cast(s.nativeThisObject()); + int argc = static_cast(args.size()); + auto *cobj = static_cast(s.nativeThisObject()); if (argc == 0) { cobj->disconnect(); @@ -231,11 +231,11 @@ SE_BIND_FUNC(SocketIO_disconnect) // NOLINT(readability-identifier-naming) static bool SocketIO_on(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); - auto * cobj = static_cast(s.nativeThisObject()); + int argc = static_cast(args.size()); + auto *cobj = static_cast(s.nativeThisObject()); if (argc == 2) { - bool ok = false; + bool ok = false; ccstd::string eventName; ok = sevalue_to_native(args[0], &eventName); SE_PRECONDITION2(ok, false, "Converting eventName failed!"); @@ -254,13 +254,13 @@ SE_BIND_FUNC(SocketIO_on) // NOLINT(readability-identifier-naming) // static static bool SocketIO_connect(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); CC_LOG_DEBUG("JSB SocketIO.connect method called"); if (argc >= 1 && argc <= 3) { ccstd::string url; ccstd::string caFilePath; - bool ok = false; + bool ok = false; ok = sevalue_to_native(args[0], &url); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -313,7 +313,7 @@ SE_BIND_FUNC(SocketIO_connect) // NOLINT(readability-identifier-naming) // static static bool SocketIO_close(se::State &s) { // NOLINT(readability-identifier-naming) const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 0) { return true; } diff --git a/native/cocos/bindings/manual/jsb_spine_manual.cpp b/native/cocos/bindings/manual/jsb_spine_manual.cpp index ab46e72e76..6238d62707 100644 --- a/native/cocos/bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/bindings/manual/jsb_spine_manual.cpp @@ -41,9 +41,9 @@ using namespace cc; -static spine::Cocos2dTextureLoader textureLoader; +static spine::Cocos2dTextureLoader textureLoader; static cc::RefMap *_preloadedAtlasTextures = nullptr; -static middleware::Texture2D * _getPreloadedAtlasTexture(const char *path) { +static middleware::Texture2D *_getPreloadedAtlasTexture(const char *path) { CC_ASSERT(_preloadedAtlasTextures); auto it = _preloadedAtlasTextures->find(path); return it != _preloadedAtlasTextures->end() ? it->second : nullptr; @@ -51,7 +51,7 @@ static middleware::Texture2D * _getPreloadedAtlasTex static bool js_register_spine_initSkeletonData(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc != 5) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 5); return false; @@ -62,7 +62,7 @@ static bool js_register_spine_initSkeletonData(se::State &s) { ok = sevalue_to_native(args[0], &uuid); SE_PRECONDITION2(ok, false, "js_register_spine_initSkeletonData: Invalid uuid content!"); - auto mgr = spine::SkeletonDataMgr::getInstance(); + auto mgr = spine::SkeletonDataMgr::getInstance(); bool hasSkeletonData = mgr->hasSkeletonData(uuid); if (hasSkeletonData) { spine::SkeletonData *skeletonData = mgr->retainByUUID(uuid); @@ -83,7 +83,7 @@ static bool js_register_spine_initSkeletonData(se::State &s) { SE_PRECONDITION2(ok, false, "js_register_spine_initSkeletonData: Invalid textures!"); float scale = 1.0f; - ok = sevalue_to_native(args[4], &scale); + ok = sevalue_to_native(args[4], &scale); SE_PRECONDITION2(ok, false, "js_register_spine_initSkeletonData: Invalid scale!"); // create atlas from preloaded texture @@ -97,16 +97,16 @@ static bool js_register_spine_initSkeletonData(se::State &s) { spine::spAtlasPage_setCustomTextureLoader(nullptr); spine::AttachmentLoader *attachmentLoader = ccnew_placement(__FILE__, __LINE__) spine::Cocos2dAtlasAttachmentLoader(atlas); - spine::SkeletonData * skeletonData = nullptr; + spine::SkeletonData *skeletonData = nullptr; std::size_t length = skeletonDataFile.length(); - auto binPos = skeletonDataFile.find(".skel", length - 5); + auto binPos = skeletonDataFile.find(".skel", length - 5); if (binPos == ccstd::string::npos) binPos = skeletonDataFile.find(".bin", length - 4); if (binPos != ccstd::string::npos) { auto fileUtils = cc::FileUtils::getInstance(); if (fileUtils->isFileExist(skeletonDataFile)) { - cc::Data cocos2dData; + cc::Data cocos2dData; const auto fullpath = fileUtils->fullPathForFilename(skeletonDataFile); fileUtils->getContents(fullpath, &cocos2dData); @@ -145,7 +145,7 @@ SE_BIND_FUNC(js_register_spine_initSkeletonData) static bool js_register_spine_disposeSkeletonData(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 5); return false; @@ -156,7 +156,7 @@ static bool js_register_spine_disposeSkeletonData(se::State &s) { ok = sevalue_to_native(args[0], &uuid); SE_PRECONDITION2(ok, false, "js_register_spine_disposeSkeletonData: Invalid uuid content!"); - auto mgr = spine::SkeletonDataMgr::getInstance(); + auto mgr = spine::SkeletonDataMgr::getInstance(); bool hasSkeletonData = mgr->hasSkeletonData(uuid); if (!hasSkeletonData) return true; mgr->releaseByUUID(uuid); @@ -167,7 +167,7 @@ SE_BIND_FUNC(js_register_spine_disposeSkeletonData) static bool js_register_spine_initSkeletonRenderer(se::State &s) { // renderer, jsonPath, atlasText, textures, scale const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc != 2) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 5); return false; @@ -175,14 +175,14 @@ static bool js_register_spine_initSkeletonRenderer(se::State &s) { bool ok = false; spine::SkeletonRenderer *node = nullptr; - ok = seval_to_native_ptr(args[0], &node); + ok = seval_to_native_ptr(args[0], &node); SE_PRECONDITION2(ok, false, "js_register_spine_initSkeletonData: Converting SpineRenderer failed!"); ccstd::string uuid; ok = sevalue_to_native(args[1], &uuid); SE_PRECONDITION2(ok, false, "js_register_spine_initSkeletonData: Invalid uuid content!"); - auto mgr = spine::SkeletonDataMgr::getInstance(); + auto mgr = spine::SkeletonDataMgr::getInstance(); bool hasSkeletonData = mgr->hasSkeletonData(uuid); if (hasSkeletonData) { node->initWithUUID(uuid); @@ -193,7 +193,7 @@ SE_BIND_FUNC(js_register_spine_initSkeletonRenderer) static bool js_register_spine_retainSkeletonData(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); return false; @@ -204,7 +204,7 @@ static bool js_register_spine_retainSkeletonData(se::State &s) { ok = sevalue_to_native(args[0], &uuid); SE_PRECONDITION2(ok, false, "js_register_spine_hasSkeletonData: Invalid uuid content!"); - auto mgr = spine::SkeletonDataMgr::getInstance(); + auto mgr = spine::SkeletonDataMgr::getInstance(); bool hasSkeletonData = mgr->hasSkeletonData(uuid); if (hasSkeletonData) { spine::SkeletonData *skeletonData = mgr->retainByUUID(uuid); @@ -232,7 +232,7 @@ bool register_all_spine_manual(se::Object *obj) { spine::setSpineObjectDisposeCallback([](void *spineObj) { // Support Native Spine fo Creator V3.0 se::Object *seObj = nullptr; - auto iter = se::NativePtrToObjectMap::find(spineObj); + auto iter = se::NativePtrToObjectMap::find(spineObj); if (iter != se::NativePtrToObjectMap::end()) { // Save se::Object pointer for being used in cleanup method. seObj = iter->second; @@ -242,7 +242,7 @@ bool register_all_spine_manual(se::Object *obj) { // the same address. iter->second->setClearMappingInFinalizer(false); se::NativePtrToObjectMap::erase(iter); - } + } }); se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { diff --git a/native/cocos/bindings/manual/jsb_websocket.cpp b/native/cocos/bindings/manual/jsb_websocket.cpp index f7224623c2..b52fc92c7f 100644 --- a/native/cocos/bindings/manual/jsb_websocket.cpp +++ b/native/cocos/bindings/manual/jsb_websocket.cpp @@ -89,7 +89,7 @@ void JsbWebSocketDelegate::onOpen(cc::network::WebSocket *ws) { jsObj->setProperty("target", target); se::Value func; - bool ok = _JSDelegate.toObject()->getProperty("onopen", &func); + bool ok = _JSDelegate.toObject()->getProperty("onopen", &func); if (ok && func.isObject() && func.toObject()->isFunction()) { se::ValueArray args; args.push_back(se::Value(jsObj)); @@ -112,7 +112,7 @@ void JsbWebSocketDelegate::onMessage(cc::network::WebSocket *ws, const cc::netwo return; } - se::Object * wsObj = iter->second; + se::Object *wsObj = iter->second; se::HandleObject jsObj(se::Object::createPlainObject()); jsObj->setProperty("type", se::Value("message")); se::Value target; @@ -120,7 +120,7 @@ void JsbWebSocketDelegate::onMessage(cc::network::WebSocket *ws, const cc::netwo jsObj->setProperty("target", target); se::Value func; - bool ok = _JSDelegate.toObject()->getProperty("onmessage", &func); + bool ok = _JSDelegate.toObject()->getProperty("onmessage", &func); if (ok && func.isObject() && func.toObject()->isFunction()) { se::ValueArray args; args.push_back(se::Value(jsObj)); @@ -165,7 +165,7 @@ void JsbWebSocketDelegate::onClose(cc::network::WebSocket *ws) { break; } - se::Object * wsObj = iter->second; + se::Object *wsObj = iter->second; se::HandleObject jsObj(se::Object::createPlainObject()); jsObj->setProperty("type", se::Value("close")); se::Value target; @@ -173,7 +173,7 @@ void JsbWebSocketDelegate::onClose(cc::network::WebSocket *ws) { jsObj->setProperty("target", target); se::Value func; - bool ok = _JSDelegate.toObject()->getProperty("onclose", &func); + bool ok = _JSDelegate.toObject()->getProperty("onclose", &func); if (ok && func.isObject() && func.toObject()->isFunction()) { se::ValueArray args; args.push_back(se::Value(jsObj)); @@ -208,7 +208,7 @@ void JsbWebSocketDelegate::onError(cc::network::WebSocket *ws, const cc::network return; } - se::Object * wsObj = iter->second; + se::Object *wsObj = iter->second; se::HandleObject jsObj(se::Object::createPlainObject()); jsObj->setProperty("type", se::Value("error")); se::Value target; @@ -216,7 +216,7 @@ void JsbWebSocketDelegate::onError(cc::network::WebSocket *ws, const cc::network jsObj->setProperty("target", target); se::Value func; - bool ok = _JSDelegate.toObject()->getProperty("onerror", &func); + bool ok = _JSDelegate.toObject()->getProperty("onerror", &func); if (ok && func.isObject() && func.toObject()->isFunction()) { se::ValueArray args; args.push_back(se::Value(jsObj)); @@ -250,7 +250,7 @@ SE_BIND_FINALIZE_FUNC(webSocketFinalize) static bool webSocketConstructor(se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 1 || argc == 2 || argc == 3) { ccstd::string url; @@ -258,10 +258,10 @@ static bool webSocketConstructor(se::State &s) { bool ok = sevalue_to_native(args[0], &url); SE_PRECONDITION2(ok, false, "Error processing url argument"); - se::Object * obj = s.thisObject(); + se::Object *obj = s.thisObject(); cc::network::WebSocket *cobj = nullptr; if (argc >= 2) { - ccstd::string caFilePath; + ccstd::string caFilePath; ccstd::vector protocols; if (args[1].isString()) { @@ -271,8 +271,8 @@ static bool webSocketConstructor(se::State &s) { protocols.push_back(protocol); } else if (args[1].isObject() && args[1].toObject()->isArray()) { se::Object *protocolArr = args[1].toObject(); - uint32_t len = 0; - ok = protocolArr->getArrayLength(&len); + uint32_t len = 0; + ok = protocolArr->getArrayLength(&len); SE_PRECONDITION2(ok, false, "getArrayLength failed!"); se::Value tmp; @@ -293,7 +293,7 @@ static bool webSocketConstructor(se::State &s) { SE_PRECONDITION2(ok, false, "Error processing caFilePath"); } - cobj = ccnew cc::network::WebSocket(); + cobj = ccnew cc::network::WebSocket(); auto *delegate = ccnew JsbWebSocketDelegate(); delegate->addRef(); if (cobj->init(*delegate, url, &protocols, caFilePath)) { @@ -307,7 +307,7 @@ static bool webSocketConstructor(se::State &s) { return false; } } else { - cobj = ccnew cc::network::WebSocket(); + cobj = ccnew cc::network::WebSocket(); auto *delegate = ccnew JsbWebSocketDelegate(); delegate->addRef(); if (cobj->init(*delegate, url)) { @@ -344,11 +344,11 @@ SE_BIND_CTOR(webSocketConstructor, jsbWebSocketClass, webSocketFinalize) static bool webSocketSend(const se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 1) { auto *cobj = static_cast(s.nativeThisObject()); - bool ok = false; + bool ok = false; if (args[0].isString()) { ccstd::string data; ok = sevalue_to_native(args[0], &data); @@ -365,8 +365,8 @@ static bool webSocketSend(const se::State &s) { cobj->send(data); } else if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); - uint8_t * ptr = nullptr; - size_t length = 0; + uint8_t *ptr = nullptr; + size_t length = 0; if (dataObj->isArrayBuffer()) { ok = dataObj->getArrayBufferData(&ptr, &length); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -391,7 +391,7 @@ SE_BIND_FUNC(webSocketSend) static bool webSocketClose(se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); auto *cobj = static_cast(s.nativeThisObject()); if (argc == 0) { @@ -411,7 +411,7 @@ static bool webSocketClose(se::State &s) { } else if (argc == 2) { CC_ASSERT(args[0].isNumber()); CC_ASSERT(args[1].isString()); - int reasonCode{0}; + int reasonCode{0}; ccstd::string reasonString; sevalue_to_native(args[0], &reasonCode); sevalue_to_native(args[1], &reasonString); @@ -434,7 +434,7 @@ SE_BIND_FUNC(webSocketClose) static bool webSocketGetReadyState(se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 0) { auto *cobj = static_cast(s.nativeThisObject()); @@ -448,7 +448,7 @@ SE_BIND_PROP_GET(webSocketGetReadyState) static bool webSocketGetBufferedAmount(se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 0) { auto *cobj = static_cast(s.nativeThisObject()); @@ -462,7 +462,7 @@ SE_BIND_PROP_GET(webSocketGetBufferedAmount) static bool webSocketGetExtensions(se::State &s) { const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc == 0) { auto *cobj = static_cast(s.nativeThisObject()); @@ -477,7 +477,7 @@ SE_BIND_PROP_GET(webSocketGetExtensions) #define WEBSOCKET_DEFINE_READONLY_INT_FIELD(full_name, value) \ static bool full_name(se::State &s) { \ const auto &args = s.args(); \ - int argc = (int)args.size(); \ + int argc = (int)args.size(); \ if (argc == 0) { \ s.rval().setInt32(value); \ return true; \ diff --git a/native/cocos/bindings/manual/jsb_websocket.h b/native/cocos/bindings/manual/jsb_websocket.h index 94ae8ca32b..dab16cf0fd 100644 --- a/native/cocos/bindings/manual/jsb_websocket.h +++ b/native/cocos/bindings/manual/jsb_websocket.h @@ -39,12 +39,12 @@ public: void onOpen(cc::network::WebSocket *ws) override; - void onMessage(cc::network::WebSocket * ws, + void onMessage(cc::network::WebSocket *ws, const cc::network::WebSocket::Data &data) override; void onClose(cc::network::WebSocket *ws) override; - void onError(cc::network::WebSocket * ws, + void onError(cc::network::WebSocket *ws, const cc::network::WebSocket::ErrorCode &error) override; void setJSDelegate(const se::Value &jsDelegate); diff --git a/native/cocos/bindings/manual/jsb_websocket_server.cpp b/native/cocos/bindings/manual/jsb_websocket_server.cpp index 7504a8b398..241d985f78 100644 --- a/native/cocos/bindings/manual/jsb_websocket_server.cpp +++ b/native/cocos/bindings/manual/jsb_websocket_server.cpp @@ -37,10 +37,10 @@ using namespace cc; using namespace cc::network; -se::Class *__jsb_WebSocketServer_class = nullptr; +se::Class *__jsb_WebSocketServer_class = nullptr; se::Class *__jsb_WebSocketServer_Connection_class = nullptr; -typedef std::shared_ptr * WSSPTR; +typedef std::shared_ptr *WSSPTR; typedef std::shared_ptr *WSCONNPTR; static int __sendIndex = 1; @@ -60,10 +60,10 @@ SE_BIND_FINALIZE_FUNC(WebSocketServer_finalize) static bool WebSocketServer_constructor(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - se::Object *obj = s.thisObject(); - WSSPTR cobj = ccnew std::shared_ptr(ccnew WebSocketServer()); + se::Object *obj = s.thisObject(); + WSSPTR cobj = ccnew std::shared_ptr(ccnew WebSocketServer()); obj->setPrivateData(cobj); (*cobj)->setData(obj); @@ -85,15 +85,15 @@ SE_BIND_CTOR(WebSocketServer_constructor, __jsb_WebSocketServer_class, WebSocket static bool WebSocketServer_listen(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1,2,3", argc); return false; } - WSSPTR cobj = (WSSPTR)s.nativeThisObject(); - int arg_port = 0; - ccstd::string arg_host = ""; + WSSPTR cobj = (WSSPTR)s.nativeThisObject(); + int arg_port = 0; + ccstd::string arg_host = ""; std::function arg_callback; bool ok; @@ -118,7 +118,7 @@ static bool WebSocketServer_listen(se::State &s) { if (funObj) { s.thisObject()->setProperty("__onlisten", se::Value(funObj)); std::weak_ptr serverWeak = *cobj; - arg_callback = [serverWeak](const ccstd::string &err) { + arg_callback = [serverWeak](const ccstd::string &err) { se::AutoHandleScope hs; auto serverPtr = serverWeak.lock(); @@ -154,7 +154,7 @@ SE_BIND_FUNC(WebSocketServer_listen) static bool WebSocketServer_onconnection(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -182,7 +182,7 @@ static bool WebSocketServer_onconnection(se::State &s) { } se::Object *obj = se::Object::createObjectWithClass(__jsb_WebSocketServer_Connection_class); - WSCONNPTR prv = ccnew std::shared_ptr(conn); + WSCONNPTR prv = ccnew std::shared_ptr(conn); // a connection is dead only if no reference & closed! obj->root(); obj->setPrivateData(prv); @@ -211,7 +211,7 @@ SE_BIND_PROP_SET(WebSocketServer_onconnection) static bool WebSocketServer_onclose(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1", argc); return false; @@ -220,9 +220,9 @@ static bool WebSocketServer_onclose(se::State &s) { SE_REPORT_ERROR("argument type error, function expected!"); } - WSSPTR cobj = (WSSPTR)s.nativeThisObject(); + WSSPTR cobj = (WSSPTR)s.nativeThisObject(); std::function callback; - std::weak_ptr serverWeak = *cobj; + std::weak_ptr serverWeak = *cobj; s.thisObject()->setProperty("__onclose", args[0]); callback = [serverWeak](const ccstd::string &err) { @@ -259,13 +259,13 @@ SE_BIND_PROP_SET(WebSocketServer_onclose) static bool WebSocketServer_close(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc > 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 0, 1", argc); return false; } - WSSPTR cobj = (WSSPTR)s.nativeThisObject(); + WSSPTR cobj = (WSSPTR)s.nativeThisObject(); std::function callback; if (argc == 1) { @@ -314,15 +314,15 @@ SE_BIND_FUNC(WebSocketServer_close) static bool WebSocketServer_connections(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - WSSPTR cobj = (WSSPTR)s.nativeThisObject(); - auto conns = cobj->get()->getConnections(); - se::Object *ret = se::Object::createArrayObject(conns.size()); + WSSPTR cobj = (WSSPTR)s.nativeThisObject(); + auto conns = cobj->get()->getConnections(); + se::Object *ret = se::Object::createArrayObject(conns.size()); for (size_t i = 0; i < conns.size(); i++) { std::shared_ptr &con = conns[i]; - se::Object * obj = (se::Object *)con->getData(); + se::Object *obj = (se::Object *)con->getData(); ret->setArrayElement(i, se::Value(obj)); } s.rval().setObject(ret); @@ -342,7 +342,7 @@ SE_BIND_FINALIZE_FUNC(WebSocketServer_Connection_finalize) static bool WebSocketServer_Connection_constructor(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { se::Object *obj = s.thisObject(); //private data should be set when connected @@ -356,7 +356,7 @@ SE_BIND_CTOR(WebSocketServer_Connection_constructor, __jsb_WebSocketServer_Conne static bool WebSocketServer_Connection_send(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); @@ -374,7 +374,7 @@ static bool WebSocketServer_Connection_send(se::State &s) { callback = [callbackId, connWeak](const ccstd::string &err) { se::AutoHandleScope hs; - auto conn = connWeak.lock(); + auto conn = connWeak.lock(); if (!conn) { return; } @@ -407,8 +407,8 @@ static bool WebSocketServer_Connection_send(se::State &s) { (*cobj)->sendTextAsync(data, callback); } else if (args[0].isObject()) { se::Object *dataObj = args[0].toObject(); - uint8_t * ptr = nullptr; - size_t length = 0; + uint8_t *ptr = nullptr; + size_t length = 0; if (dataObj->isArrayBuffer()) { ok = dataObj->getArrayBufferData(&ptr, &length); SE_PRECONDITION2(ok, false, "getArrayBufferData failed!"); @@ -433,7 +433,7 @@ SE_BIND_FUNC(WebSocketServer_Connection_send) static bool WebSocketServer_Connection_close(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc > 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 0, 1", argc); return false; @@ -447,9 +447,9 @@ static bool WebSocketServer_Connection_close(se::State &s) { } std::function callback; - int arg_code = -1; - ccstd::string arg_reason; - bool ok; + int arg_code = -1; + ccstd::string arg_reason; + bool ok; if (argc >= 1) { ok = sevalue_to_native(args[0], &arg_code); @@ -474,7 +474,7 @@ SE_BIND_FUNC(WebSocketServer_Connection_close) static bool WebSocketServer_Connection_onconnect(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -492,7 +492,7 @@ static bool WebSocketServer_Connection_onconnect(se::State &s) { cobj->get()->setOnConnect([connWeak]() { se::AutoHandleScope hs; - auto conn = connWeak.lock(); + auto conn = connWeak.lock(); if (!conn) { return; } @@ -506,7 +506,7 @@ static bool WebSocketServer_Connection_onconnect(se::State &s) { return; } se::ValueArray args; - bool success = callback.toObject()->call(args, sobj, nullptr); + bool success = callback.toObject()->call(args, sobj, nullptr); ; if (!success) { se::ScriptEngine::getInstance()->clearException(); @@ -518,7 +518,7 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_onconnect) static bool WebSocketServer_Connection_onerror(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -535,7 +535,7 @@ static bool WebSocketServer_Connection_onerror(se::State &s) { cobj->get()->setOnError([connWeak](const ccstd::string &err) { se::AutoHandleScope hs; - auto conn = connWeak.lock(); + auto conn = connWeak.lock(); if (!conn) { return; } @@ -564,7 +564,7 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_onerror) static bool WebSocketServer_Connection_onclose(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -613,7 +613,7 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_onclose) static bool WebSocketServer_Connection_ontext(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -659,7 +659,7 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_ontext) static bool WebSocketServer_Connection_onbinary(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -676,7 +676,7 @@ static bool WebSocketServer_Connection_onbinary(se::State &s) { cobj->get()->setOnBinary([connWeak](const std::shared_ptr text) { se::AutoHandleScope hs; - auto conn = connWeak.lock(); + auto conn = connWeak.lock(); if (!conn) { return; } @@ -691,7 +691,7 @@ static bool WebSocketServer_Connection_onbinary(se::State &s) { } se::ValueArray args; - se::Object * buffer = se::Object::createArrayBufferObject(text->getData(), text->size()); + se::Object *buffer = se::Object::createArrayBufferObject(text->getData(), text->size()); args.push_back(se::Value(buffer)); bool success = callback.toObject()->call(args, sobj, nullptr); ; @@ -705,7 +705,7 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_onbinary) static bool WebSocketServer_Connection_ondata(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (!(argc == 1 && args[0].isObject() && args[0].toObject()->isFunction())) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting 1 & function", argc); return false; @@ -756,12 +756,12 @@ SE_BIND_PROP_SET(WebSocketServer_Connection_ondata) static bool WebSocketServer_Connection_headers(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); - auto headers = cobj->get()->getHeaders(); - se::Object *ret = se::Object::createPlainObject(); + WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); + auto headers = cobj->get()->getHeaders(); + se::Object *ret = se::Object::createPlainObject(); for (auto &itr : headers) { ret->setProperty(itr.first.c_str(), se::Value(itr.second)); } @@ -775,12 +775,12 @@ SE_BIND_PROP_GET(WebSocketServer_Connection_headers) static bool WebSocketServer_Connection_protocols(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); - auto protocols = cobj->get()->getProtocols(); - se::Object *ret = se::Object::createArrayObject(protocols.size()); + WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); + auto protocols = cobj->get()->getProtocols(); + se::Object *ret = se::Object::createArrayObject(protocols.size()); for (size_t i = 0; i < protocols.size(); i++) { ret->setArrayElement(i, se::Value(protocols[i])); } @@ -794,11 +794,11 @@ SE_BIND_PROP_GET(WebSocketServer_Connection_protocols) static bool WebSocketServer_Connection_protocol(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); - auto protocols = cobj->get()->getProtocols(); + WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); + auto protocols = cobj->get()->getProtocols(); if (protocols.size() > 0) { s.rval().setString(protocols[0]); } else { @@ -813,11 +813,11 @@ SE_BIND_PROP_GET(WebSocketServer_Connection_protocol) static bool WebSocketServer_Connection_readyState(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = (int)args.size(); if (argc == 0) { - WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); - auto state = cobj->get()->getReadyState(); + WSCONNPTR cobj = (WSCONNPTR)s.nativeThisObject(); + auto state = cobj->get()->getReadyState(); s.rval().setInt32(state); return true; } diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index 48d786f69d..3f03f89fbc 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -120,11 +120,11 @@ class XMLHttpRequest : public RefCounted { public: // Ready States: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState enum class ReadyState : char { - UNSENT = 0, // Client has been created. open() not called yet. - OPENED = 1, // open() has been called. + UNSENT = 0, // Client has been created. open() not called yet. + OPENED = 1, // open() has been called. HEADERS_RECEIVED = 2, // send() has been called, and headers and status are available. - LOADING = 3, // Downloading; responseText holds partial data. - DONE = 4 // The operation is complete. + LOADING = 3, // Downloading; responseText holds partial data. + DONE = 4 // The operation is complete. }; enum class ResponseType : char { @@ -150,22 +150,22 @@ public: void sendString(const ccstd::string &str); void sendBinary(const cc::Data &data); - void setRequestHeader(const ccstd::string &key, const ccstd::string &value); + void setRequestHeader(const ccstd::string &key, const ccstd::string &value); ccstd::string getAllResponseHeaders() const; ccstd::string getResponseHeader(const ccstd::string &key) const; - ReadyState getReadyState() const { return _readyState; } - uint16_t getStatus() const { return _status; } + ReadyState getReadyState() const { return _readyState; } + uint16_t getStatus() const { return _status; } const ccstd::string &getStatusText() const { return _statusText; } const ccstd::string &getResponseText() const { return _responseText; } - const cc::Data & getResponseData() const { return _responseData; } - ResponseType getResponseType() const { return _responseType; } - void setResponseType(ResponseType type) { _responseType = type; } + const cc::Data &getResponseData() const { return _responseData; } + ResponseType getResponseType() const { return _responseType; } + void setResponseType(ResponseType type) { _responseType = type; } - void overrideMimeType(const ccstd::string &mimeType); + void overrideMimeType(const ccstd::string &mimeType); ccstd::string getMimeType() const; - void setTimeout(uint32_t timeoutInMilliseconds); + void setTimeout(uint32_t timeoutInMilliseconds); uint32_t getTimeout() const; void abort(); @@ -202,7 +202,7 @@ private: uint16_t _status{}; ResponseType _responseType{}; - ReadyState _readyState{}; + ReadyState _readyState{}; bool _withCredentialsValue{false}; bool _errorFlag{false}; @@ -240,7 +240,7 @@ bool XMLHttpRequest::open(const ccstd::string &method, const ccstd::string &url) } _method = method; - _url = url; + _url = url; HttpRequest::Type requestType = HttpRequest::Type::UNKNOWN; @@ -261,7 +261,7 @@ bool XMLHttpRequest::open(const ccstd::string &method, const ccstd::string &url) _httpRequest->setRequestType(requestType); _httpRequest->setUrl(_url); - _status = 0; + _status = 0; _isAborted = false; _isTimeout = false; @@ -358,9 +358,9 @@ void XMLHttpRequest::getHeader(const ccstd::string &header) { // Get Header and Set StatusText // Split String into Tokens if (header.find("HTTP") == 0) { - int _v1; // NOLINT(readability-identifier-naming) - int _v2; // NOLINT(readability-identifier-naming) - int code = 0; + int _v1; // NOLINT(readability-identifier-naming) + int _v2; // NOLINT(readability-identifier-naming) + int code = 0; char statusText[64] = {0}; sscanf(header.c_str(), "HTTP/%d.%d %d %63[^\n]", &_v1, &_v2, &code, statusText); _statusText = statusText; @@ -397,7 +397,7 @@ void XMLHttpRequest::onResponse(HttpClient * /*client*/, HttpResponse *response) SE_LOGD("XMLHttpRequest::onResponse, %s completed\n", tag.c_str()); } - auto statusCode = response->getResponseCode(); + auto statusCode = response->getResponseCode(); char statusString[64] = {0}; sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, tag.c_str()); @@ -409,7 +409,7 @@ void XMLHttpRequest::onResponse(HttpClient * /*client*/, HttpResponse *response) SE_LOGD("Response failed, error buffer: %s\n", errorBuffer.c_str()); if (statusCode == 0 || statusCode == -1) { _errorFlag = true; - _status = 0; + _status = 0; _statusText.clear(); if (onerror != nullptr) { onerror(); @@ -429,7 +429,7 @@ void XMLHttpRequest::onResponse(HttpClient * /*client*/, HttpResponse *response) ccstd::string header(headers->begin(), headers->end()); std::istringstream stream(header); - ccstd::string line; + ccstd::string line; while (std::getline(stream, line)) { getHeader(line); } @@ -482,7 +482,7 @@ void XMLHttpRequest::sendRequest() { if (ontimeout != nullptr) { ontimeout(); } - _isTimeout = true; + _isTimeout = true; _readyState = ReadyState::UNSENT; }, this, static_cast(_timeoutInMilliseconds) / 1000.0F, 0, 0.0F, false, "XMLHttpRequest"); @@ -509,7 +509,7 @@ void XMLHttpRequest::setHttpRequestData(const char *data, size_t len) { void XMLHttpRequest::setRequestHeader(const ccstd::string &key, const ccstd::string &value) { std::stringstream header_s; // NOLINT(readability-identifier-naming) std::stringstream value_s; // NOLINT(readability-identifier-naming) - ccstd::string header; + ccstd::string header; auto iter = _requestHeader.find(key); @@ -525,7 +525,7 @@ void XMLHttpRequest::setRequestHeader(const ccstd::string &key, const ccstd::str ccstd::string XMLHttpRequest::getAllResponseHeaders() const { std::stringstream responseheaders; - ccstd::string responseheader; + ccstd::string responseheader; for (const auto &it : _httpHeader) { responseheaders << it.first << ": " << it.second << "\n"; @@ -551,10 +551,10 @@ void XMLHttpRequest::setHttpRequestHeader() { ccstd::vector header; for (auto &it : _requestHeader) { - const char *first = it.first.c_str(); + const char *first = it.first.c_str(); const char *second = it.second.c_str(); - size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); - char * test = static_cast(malloc(len)); + size_t len = sizeof(char) * (strlen(first) + 3 + strlen(second)); + char *test = static_cast(malloc(len)); memset(test, 0, len); strcpy(test, first); @@ -645,10 +645,10 @@ SE_BIND_CTOR(XMLHttpRequest_constructor, __jsb_XMLHttpRequest_class, XMLHttpRequ static bool XMLHttpRequest_open(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc >= 2) { - auto * request = static_cast(s.nativeThisObject()); - bool ok = false; + auto *request = static_cast(s.nativeThisObject()); + bool ok = false; ccstd::string method; ok = sevalue_to_native(args[0], &method); SE_PRECONDITION2(ok, false, "args[0] isn't a string."); @@ -673,9 +673,9 @@ static bool XMLHttpRequest_abort(se::State &s) { //NOLINT(readability-identifier SE_BIND_FUNC(XMLHttpRequest_abort) static bool XMLHttpRequest_send(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) - const auto &args = s.args(); - size_t argc = args.size(); - auto * request = static_cast(s.nativeThisObject()); + const auto &args = s.args(); + size_t argc = args.size(); + auto *request = static_cast(s.nativeThisObject()); if (argc == 0) { request->send(); @@ -690,7 +690,7 @@ static bool XMLHttpRequest_send(se::State &s) { //NOLINT(readability-identifier- if (obj->isTypedArray()) { uint8_t *ptr = nullptr; - size_t len = 0; + size_t len = 0; if (obj->getTypedArrayData(&ptr, &len)) { Data data; data.copy(ptr, static_cast(len)); @@ -701,7 +701,7 @@ static bool XMLHttpRequest_send(se::State &s) { //NOLINT(readability-identifier- } } else if (obj->isArrayBuffer()) { uint8_t *ptr = nullptr; - size_t len = 0; + size_t len = 0; if (obj->getArrayBufferData(&ptr, &len)) { Data data; data.copy(ptr, static_cast(len)); @@ -733,12 +733,12 @@ SE_BIND_FUNC(XMLHttpRequest_send) static bool XMLHttpRequest_setRequestHeader(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc >= 2) { - auto * xhr = static_cast(s.nativeThisObject()); + auto *xhr = static_cast(s.nativeThisObject()); ccstd::string key; - bool ok = sevalue_to_native(args[0], &key); + bool ok = sevalue_to_native(args[0], &key); SE_PRECONDITION2(ok, false, "args[0] couldn't be converted to string."); ccstd::string value; ok = sevalue_to_native(args[1], &value); @@ -753,7 +753,7 @@ static bool XMLHttpRequest_setRequestHeader(se::State &s) { //NOLINT(readability SE_BIND_FUNC(XMLHttpRequest_setRequestHeader) static bool XMLHttpRequest_getAllResponseHeaders(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) - auto * xhr = static_cast(s.nativeThisObject()); + auto *xhr = static_cast(s.nativeThisObject()); ccstd::string headers = xhr->getAllResponseHeaders(); s.rval().setString(headers); return true; @@ -762,11 +762,11 @@ SE_BIND_FUNC(XMLHttpRequest_getAllResponseHeaders) static bool XMLHttpRequest_getResonpseHeader(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc > 0) { - auto * xhr = static_cast(s.nativeThisObject()); + auto *xhr = static_cast(s.nativeThisObject()); ccstd::string key; - bool ok = sevalue_to_native(args[0], &key); + bool ok = sevalue_to_native(args[0], &key); SE_PRECONDITION2(ok, false, "args[0] couldn't be converted to string."); ccstd::string header = xhr->getResponseHeader(key); s.rval().setString(header); @@ -780,7 +780,7 @@ SE_BIND_FUNC(XMLHttpRequest_getResonpseHeader) static bool XMLHttpRequest_overrideMimeType(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc > 0 && args[0].isString()) { ccstd::string mimeType; sevalue_to_native(args[0], &mimeType); @@ -792,8 +792,8 @@ static bool XMLHttpRequest_overrideMimeType(se::State &s) { //NOLINT(readability SE_BIND_FUNC(XMLHttpRequest_overrideMimeType) static bool XMLHttpRequest_getMIMEType(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) - auto *xhr = static_cast(s.nativeThisObject()); - auto type = xhr->getMimeType(); + auto *xhr = static_cast(s.nativeThisObject()); + auto type = xhr->getMimeType(); s.rval().setString(type); return true; } @@ -848,14 +848,14 @@ static bool XMLHttpRequest_getResponse(se::State &s) { //NOLINT(readability-iden } else { if (xhr->getResponseType() == XMLHttpRequest::ResponseType::JSON) { const ccstd::string &jsonText = xhr->getResponseText(); - se::HandleObject seObj(se::Object::createJSONObject(jsonText)); + se::HandleObject seObj(se::Object::createJSONObject(jsonText)); if (!seObj.isEmpty()) { s.rval().setObject(seObj); } else { s.rval().setNull(); } } else if (xhr->getResponseType() == XMLHttpRequest::ResponseType::ARRAY_BUFFER) { - const Data & data = xhr->getResponseData(); + const Data &data = xhr->getResponseData(); se::HandleObject seObj(se::Object::createArrayBufferObject(data.getBytes(), data.getSize())); if (!seObj.isEmpty()) { s.rval().setObject(seObj); @@ -880,11 +880,11 @@ SE_BIND_PROP_GET(XMLHttpRequest_getTimeout) static bool XMLHttpRequest_setTimeout(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - int argc = static_cast(args.size()); + int argc = static_cast(args.size()); if (argc > 0) { - auto * cobj = static_cast(s.nativeThisObject()); + auto *cobj = static_cast(s.nativeThisObject()); uint32_t timeoutInMilliseconds = 0; - bool ok = sevalue_to_native(args[0], &timeoutInMilliseconds); + bool ok = sevalue_to_native(args[0], &timeoutInMilliseconds); SE_PRECONDITION2(ok, false, "args[0] isn't a number"); if (timeoutInMilliseconds < 50) { SE_LOGE("The timeout value (%u ms) is too small, please note that timeout unit is milliseconds!", timeoutInMilliseconds); @@ -919,11 +919,11 @@ SE_BIND_PROP_GET(XMLHttpRequest_getResponseType) static bool XMLHttpRequest_setResponseType(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) const auto &args = s.args(); - size_t argc = args.size(); + size_t argc = args.size(); if (argc > 0) { ccstd::string type; - bool ok = sevalue_to_native(args[0], &type); + bool ok = sevalue_to_native(args[0], &type); SE_PRECONDITION2(ok, false, "args[0] couldn't be converted to string!"); auto *xhr = static_cast(s.nativeThisObject()); diff --git a/native/cocos/core/ArrayBuffer.h b/native/cocos/core/ArrayBuffer.h index 4c7ed4daee..3df20e6a06 100644 --- a/native/cocos/core/ArrayBuffer.h +++ b/native/cocos/core/ArrayBuffer.h @@ -83,14 +83,14 @@ public: CC_ASSERT(begin < _byteLength); CC_ASSERT(end <= _byteLength); uint32_t newBufByteLength = (end - begin); - Ptr buffer = ccnew ArrayBuffer(newBufByteLength); + Ptr buffer = ccnew ArrayBuffer(newBufByteLength); memcpy(buffer->getData(), _data + begin, newBufByteLength); return buffer; } // Just use it to copy data. Use TypedArray to get/set data. inline const uint8_t *getData() const { return _data; } - inline uint8_t * getData() { return _data; } + inline uint8_t *getData() { return _data; } inline void reset(const uint8_t *data, uint32_t length) { if (_jsArrayBuffer != nullptr) { @@ -104,8 +104,8 @@ public: private: se::Object *_jsArrayBuffer{nullptr}; - uint8_t * _data{nullptr}; - uint32_t _byteLength{0}; + uint8_t *_data{nullptr}; + uint32_t _byteLength{0}; template friend class TypedArrayTemp; diff --git a/native/cocos/core/DataView.cpp b/native/cocos/core/DataView.cpp index 5a72f66871..3fb85bf21d 100644 --- a/native/cocos/core/DataView.cpp +++ b/native/cocos/core/DataView.cpp @@ -75,7 +75,7 @@ void DataView::assign(ArrayBuffer *buffer, uint32_t byteOffset) { void DataView::assign(ArrayBuffer *buffer, uint32_t byteOffset, uint32_t byteLength) { CC_ASSERT(buffer != nullptr); CC_ASSERT(byteLength > 0); - _buffer = buffer; + _buffer = buffer; _byteOffset = byteOffset; _byteEndPos = byteLength + byteOffset; CC_ASSERT(_byteEndPos <= buffer->_byteLength); diff --git a/native/cocos/core/DataView.h b/native/cocos/core/DataView.h index 5dcb28f3d1..04692cc1b0 100644 --- a/native/cocos/core/DataView.h +++ b/native/cocos/core/DataView.h @@ -44,13 +44,13 @@ public: void assign(ArrayBuffer *buffer, uint32_t byteOffset); void assign(ArrayBuffer *buffer, uint32_t byteOffset, uint32_t byteLength); - uint8_t getUint8(uint32_t offset) const; + uint8_t getUint8(uint32_t offset) const; uint16_t getUint16(uint32_t offset) const; uint32_t getUint32(uint32_t offset) const; - int8_t getInt8(uint32_t offset) const; - int16_t getInt16(uint32_t offset) const; - int32_t getInt32(uint32_t offset) const; - float getFloat32(uint32_t offset) const; + int8_t getInt8(uint32_t offset) const; + int16_t getInt16(uint32_t offset) const; + int32_t getInt32(uint32_t offset) const; + float getFloat32(uint32_t offset) const; void setUint8(uint32_t offset, uint8_t value); void setUint16(uint32_t offset, uint16_t value); @@ -61,30 +61,30 @@ public: void setFloat32(uint32_t offset, float value); inline const ArrayBuffer *buffer() const { return _buffer; } - inline ArrayBuffer * buffer() { return _buffer; } - inline uint32_t byteOffset() const { return _byteOffset; } - inline uint32_t byteLength() const { + inline ArrayBuffer *buffer() { return _buffer; } + inline uint32_t byteOffset() const { return _byteOffset; } + inline uint32_t byteLength() const { return _byteEndPos - _byteOffset; } - using Int32Reader = int32_t (DataView::*)(uint32_t) const; - using UInt32Reader = uint32_t (DataView::*)(uint32_t) const; - using Int16Reader = int16_t (DataView::*)(uint32_t) const; - using UInt16Reader = uint16_t (DataView::*)(uint32_t) const; - using Int8Reader = int8_t (DataView::*)(uint32_t) const; - using UInt8Reader = uint8_t (DataView::*)(uint32_t) const; + using Int32Reader = int32_t (DataView::*)(uint32_t) const; + using UInt32Reader = uint32_t (DataView::*)(uint32_t) const; + using Int16Reader = int16_t (DataView::*)(uint32_t) const; + using UInt16Reader = uint16_t (DataView::*)(uint32_t) const; + using Int8Reader = int8_t (DataView::*)(uint32_t) const; + using UInt8Reader = uint8_t (DataView::*)(uint32_t) const; using ReaderVariant = cc::variant; static ccstd::unordered_map intReaderMap; - int32_t readInt(ReaderVariant &readerVariant, uint32_t offset); + int32_t readInt(ReaderVariant &readerVariant, uint32_t offset); using IntWritter = void (DataView::*)(uint32_t, uint32_t); static ccstd::unordered_map intWritterMap; private: ArrayBuffer::Ptr _buffer; - uint8_t * _data{nullptr}; - uint32_t _byteOffset{0}; - uint32_t _byteEndPos{0}; + uint8_t *_data{nullptr}; + uint32_t _byteOffset{0}; + uint32_t _byteEndPos{0}; }; } // namespace cc diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 470c9e5221..287b10c8d0 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -52,7 +52,7 @@ Root *Root::getInstance() { Root::Root(gfx::Device *device) : _device(device) { - instance = this; + instance = this; _eventProcessor = new CallbacksInvoker(); // TODO(minggo): // this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device) as DataPoolManager; @@ -75,18 +75,18 @@ void Root::initialize(gfx::Swapchain *swapchain) { colorAttachment.format = swapchain->getColorTexture()->getFormat(); renderPassInfo.colorAttachments.emplace_back(colorAttachment); - auto &depthStencilAttachment = renderPassInfo.depthStencilAttachment; - depthStencilAttachment.format = swapchain->getDepthStencilTexture()->getFormat(); - depthStencilAttachment.depthStoreOp = gfx::StoreOp::DISCARD; + auto &depthStencilAttachment = renderPassInfo.depthStencilAttachment; + depthStencilAttachment.format = swapchain->getDepthStencilTexture()->getFormat(); + depthStencilAttachment.depthStoreOp = gfx::StoreOp::DISCARD; depthStencilAttachment.stencilStoreOp = gfx::StoreOp::DISCARD; scene::IRenderWindowInfo info; - info.title = ccstd::string{"rootMainWindow"}; - info.width = swapchain->getWidth(); - info.height = swapchain->getHeight(); + info.title = ccstd::string{"rootMainWindow"}; + info.width = swapchain->getWidth(); + info.height = swapchain->getHeight(); info.renderPassInfo = renderPassInfo; - info.swapchain = swapchain; - _mainWindow = createWindow(info); + info.swapchain = swapchain; + _mainWindow = createWindow(info); _curWindow = _mainWindow; @@ -191,7 +191,7 @@ bool Root::setRenderPipeline(pipeline::RenderPipeline *rppl /* = nullptr*/) { isCreateDefaultPipeline = true; } - _pipeline = rppl; + _pipeline = rppl; _pipelineRuntime = std::make_unique(rppl); // now cluster just enabled in deferred pipeline @@ -265,9 +265,9 @@ void Root::frameMove(float deltaTime, int32_t totalFrames) { _cumulativeTime += deltaTime; _fpsTime += deltaTime; if (_fpsTime > 1.0F) { - _fps = _frameCount; + _fps = _frameCount; _frameCount = 0; - _fpsTime = 0.0; + _fpsTime = 0.0; } for (const auto &scene : _scenes) { diff --git a/native/cocos/core/Root.h b/native/cocos/core/Root.h index d0295625aa..ebb96d25bd 100644 --- a/native/cocos/core/Root.h +++ b/native/cocos/core/Root.h @@ -155,7 +155,7 @@ public: * GFX 设备 */ inline gfx::Device *getDevice() const { return _device; } - inline void setDevice(gfx::Device *device) { _device = device; } + inline void setDevice(gfx::Device *device) { _device = device; } /** * @zh @@ -249,29 +249,29 @@ public: inline CallbacksInvoker *getEventProcessor() const { return _eventProcessor; } private: - gfx::Device * _device{nullptr}; - gfx::Swapchain * _swapchain{nullptr}; - IntrusivePtr _mainWindow; - IntrusivePtr _curWindow; - IntrusivePtr _tempWindow; + gfx::Device *_device{nullptr}; + gfx::Swapchain *_swapchain{nullptr}; + IntrusivePtr _mainWindow; + IntrusivePtr _curWindow; + IntrusivePtr _tempWindow; ccstd::vector> _windows; - IntrusivePtr _pipeline{nullptr}; - std::unique_ptr _pipelineRuntime; - scene::DrawBatch2D * _batcher2D{nullptr}; + IntrusivePtr _pipeline{nullptr}; + std::unique_ptr _pipelineRuntime; + scene::DrawBatch2D *_batcher2D{nullptr}; // IntrusivePtr _dataPoolMgr; ccstd::vector> _scenes; - float _cumulativeTime{0.F}; - float _frameTime{0.F}; - float _fpsTime{0.F}; - uint32_t _frameCount{0}; - uint32_t _fps{0}; - uint32_t _fixedFPS{0}; - bool _useDeferredPipeline{false}; - bool _usesCustomPipeline{false}; - CallbacksInvoker * _eventProcessor{nullptr}; + float _cumulativeTime{0.F}; + float _frameTime{0.F}; + float _fpsTime{0.F}; + uint32_t _frameCount{0}; + uint32_t _fps{0}; + uint32_t _fixedFPS{0}; + bool _useDeferredPipeline{false}; + bool _usesCustomPipeline{false}; + CallbacksInvoker *_eventProcessor{nullptr}; // Cache ccstd::vector to avoid allocate every frame in frameMove - ccstd::vector _cameraList; + ccstd::vector _cameraList; ccstd::vector _swapchains; // }; diff --git a/native/cocos/core/System.h b/native/cocos/core/System.h index 1a57142468..95ec1ac21e 100644 --- a/native/cocos/core/System.h +++ b/native/cocos/core/System.h @@ -37,9 +37,9 @@ struct ISchedulable { }; enum struct Priority : uint32_t { - LOW = 0, - MEDIUM = 100, - HIGH = 200, + LOW = 0, + MEDIUM = 100, + HIGH = 200, SCHEDULER = UINT32_MAX, }; @@ -48,7 +48,7 @@ private: /* data */ protected: Priority _priority{Priority::LOW}; - bool _executeInEditMode{false}; + bool _executeInEditMode{false}; public: /** @@ -63,14 +63,14 @@ public: return 0; } - System() = default; + System() = default; virtual ~System() = default; inline const ccstd::string &getId() { return id; } - inline void setId(ccstd::string &s) { id = s; } + inline void setId(ccstd::string &s) { id = s; } inline Priority getPriority() const { return _priority; } - inline void setPriority(Priority i) { _priority = i; } + inline void setPriority(Priority i) { _priority = i; } inline bool getExecuteInEditMode() const { return _executeInEditMode; } inline void setExecuteInEditMode(bool b) { _executeInEditMode = b; } diff --git a/native/cocos/core/TypedArray.h b/native/cocos/core/TypedArray.h index 3fe7972009..d633c67fcf 100644 --- a/native/cocos/core/TypedArray.h +++ b/native/cocos/core/TypedArray.h @@ -132,16 +132,16 @@ public: TypedArrayTemp &operator=(TypedArrayTemp &&o) noexcept { if (this != &o) { - _buffer = o._buffer; - _byteOffset = o._byteOffset; - _byteLength = o._byteLength; - _byteEndPos = o._byteEndPos; + _buffer = o._buffer; + _byteOffset = o._byteOffset; + _byteLength = o._byteLength; + _byteEndPos = o._byteEndPos; _jsTypedArray = o._jsTypedArray; - o._buffer = nullptr; - o._byteOffset = 0; - o._byteLength = 0; - o._byteEndPos = 0; + o._buffer = nullptr; + o._byteOffset = 0; + o._byteLength = 0; + o._byteEndPos = 0; o._jsTypedArray = nullptr; } return *this; @@ -178,7 +178,7 @@ public: CC_ASSERT(start < (_byteLength / BYTES_PER_ELEMENT)); CC_ASSERT(end <= (_byteLength / BYTES_PER_ELEMENT)); uint32_t newBufByteLength = (end - start) * BYTES_PER_ELEMENT; - auto * buffer = ccnew ArrayBuffer(newBufByteLength); + auto *buffer = ccnew ArrayBuffer(newBufByteLength); memcpy(buffer->getData(), _buffer->getData() + start * BYTES_PER_ELEMENT + _byteOffset, newBufByteLength); return TypedArrayTemp(buffer); } @@ -213,21 +213,21 @@ public: _jsTypedArray = nullptr; } const uint32_t byteLength = length * BYTES_PER_ELEMENT; - _buffer = ccnew ArrayBuffer(byteLength); - _byteLength = _buffer->byteLength(); - _byteOffset = 0; - _byteEndPos = byteLength; - _jsTypedArray = se::Object::createTypedArrayWithBuffer(toTypedArrayType(), _buffer->getJSArrayBuffer(), 0, byteLength); + _buffer = ccnew ArrayBuffer(byteLength); + _byteLength = _buffer->byteLength(); + _byteOffset = 0; + _byteEndPos = byteLength; + _jsTypedArray = se::Object::createTypedArrayWithBuffer(toTypedArrayType(), _buffer->getJSArrayBuffer(), 0, byteLength); _jsTypedArray->root(); } inline ArrayBuffer *buffer() const { return _buffer; } - inline uint32_t byteLength() const { return _byteLength; } - inline uint32_t length() const { return _byteLength / BYTES_PER_ELEMENT; } - inline uint32_t byteOffset() const { return _byteOffset; } - inline bool empty() const { return _byteLength == 0; } - inline se::Object * getJSTypedArray() const { return _jsTypedArray; } - inline void setJSTypedArray(se::Object *typedArray) { + inline uint32_t byteLength() const { return _byteLength; } + inline uint32_t length() const { return _byteLength / BYTES_PER_ELEMENT; } + inline uint32_t byteOffset() const { return _byteOffset; } + inline bool empty() const { return _byteLength == 0; } + inline se::Object *getJSTypedArray() const { return _jsTypedArray; } + inline void setJSTypedArray(se::Object *typedArray) { if (_jsTypedArray != nullptr) { _jsTypedArray->unroot(); _jsTypedArray->decRef(); @@ -256,7 +256,7 @@ public: _byteEndPos = _buffer->byteLength(); } else { - _buffer = nullptr; + _buffer = nullptr; _byteOffset = 0; _byteLength = 0; _byteEndPos = 0; @@ -265,10 +265,10 @@ public: private: ArrayBuffer::Ptr _buffer; - uint32_t _byteOffset{0}; - uint32_t _byteLength{0}; - uint32_t _byteEndPos{0}; - se::Object * _jsTypedArray{nullptr}; + uint32_t _byteOffset{0}; + uint32_t _byteLength{0}; + uint32_t _byteEndPos{0}; + se::Object *_jsTypedArray{nullptr}; }; template @@ -277,7 +277,7 @@ typename std::enable_if_t::value, void> TypedArrayTemp< CC_ASSERT(_buffer); uint32_t dstByteOffset = offset * BYTES_PER_ELEMENT; uint32_t srcByteOffset = array.byteOffset(); - uint32_t srcCount = array.length(); + uint32_t srcCount = array.length(); CC_ASSERT(dstByteOffset + srcCount * TypedArrayTemp::BYTES_PER_ELEMENT <= _byteEndPos); memcpy(_buffer->_data + dstByteOffset, array._buffer->_data + srcByteOffset, array.byteLength()); } @@ -288,23 +288,23 @@ typename std::enable_if_t::value, void> TypedArrayTemp CC_ASSERT(_buffer); uint32_t dstByteOffset = offset * BYTES_PER_ELEMENT; uint32_t srcByteOffset = array.byteOffset(); - uint32_t srcCount = array.length(); - uint32_t remainCount = (_byteEndPos - dstByteOffset) / BYTES_PER_ELEMENT; + uint32_t srcCount = array.length(); + uint32_t remainCount = (_byteEndPos - dstByteOffset) / BYTES_PER_ELEMENT; CC_ASSERT(srcCount <= remainCount); for (uint32_t i = 0; i < srcCount; ++i) { (*this)[offset + i] = reinterpret_cast(array[i]); } } -using Int8Array = TypedArrayTemp; -using Int16Array = TypedArrayTemp; -using Int32Array = TypedArrayTemp; -using Uint8Array = TypedArrayTemp; -using Uint16Array = TypedArrayTemp; -using Uint32Array = TypedArrayTemp; -using Float32Array = TypedArrayTemp; -using Float64Array = TypedArrayTemp; -using TypedArray = cc::variant; +using Int8Array = TypedArrayTemp; +using Int16Array = TypedArrayTemp; +using Int32Array = TypedArrayTemp; +using Uint8Array = TypedArrayTemp; +using Uint16Array = TypedArrayTemp; +using Uint32Array = TypedArrayTemp; +using Float32Array = TypedArrayTemp; +using Float64Array = TypedArrayTemp; +using TypedArray = cc::variant; using TypedArrayElementType = cc::variant; uint32_t getTypedArrayLength(const TypedArray &arr); diff --git a/native/cocos/core/Types.h b/native/cocos/core/Types.h index b3e909a61f..79a5734d59 100644 --- a/native/cocos/core/Types.h +++ b/native/cocos/core/Types.h @@ -57,7 +57,7 @@ struct VertexIdChannel { struct NativeDep { ccstd::string uuid; ccstd::string ext; - bool __isNative__{false}; // NOLINT(bugprone-reserved-identifier) + bool __isNative__{false}; // NOLINT(bugprone-reserved-identifier) explicit NativeDep() = default; diff --git a/native/cocos/core/animation/SkeletalAnimationUtils.cpp b/native/cocos/core/animation/SkeletalAnimationUtils.cpp index 2afe14e160..c35a961db2 100644 --- a/native/cocos/core/animation/SkeletalAnimationUtils.cpp +++ b/native/cocos/core/animation/SkeletalAnimationUtils.cpp @@ -29,27 +29,27 @@ namespace cc { namespace { -ccstd::vector stack; //cjh TODO: how to release ? +ccstd::vector stack; //cjh TODO: how to release ? ccstd::unordered_map pool; } // namespace Mat4 getWorldMatrix(IJointTransform *transform, int32_t stamp) { - uint32_t i = 0; - Mat4 * res = nullptr; + uint32_t i = 0; + Mat4 *res = nullptr; while (transform != nullptr) { if ((transform->stamp == stamp || transform->stamp + 1 == stamp) && !transform->node->getChangedFlags()) { - res = &transform->world; + res = &transform->world; transform->stamp = stamp; break; } transform->stamp = stamp; stack.resize(i + 1); stack[i++] = transform; - transform = transform->parent; + transform = transform->parent; } while (i > 0) { - transform = stack[--i]; - stack[i] = nullptr; + transform = stack[--i]; + stack[i] = nullptr; const auto *node = transform->node; CC_ASSERT(node != nullptr); Mat4::fromRTS(node->getRotation(), node->getPosition(), node->getScale(), &transform->local); @@ -65,10 +65,10 @@ Mat4 getWorldMatrix(IJointTransform *transform, int32_t stamp) { IJointTransform *getTransform(Node *node, Node *root) { IJointTransform *joint = nullptr; - uint32_t i = 0; + uint32_t i = 0; while (node != root) { - const ccstd::string &id = node->getUuid(); - auto iter = pool.find(id); + const ccstd::string &id = node->getUuid(); + auto iter = pool.find(id); if (iter != pool.end()) { joint = iter->second; break; @@ -83,22 +83,22 @@ IJointTransform *getTransform(Node *node, Node *root) { stack.resize(i + 1); stack[i++] = joint; - node = node->getParent(); - joint = nullptr; + node = node->getParent(); + joint = nullptr; } IJointTransform *child; while (i > 0) { - child = stack[--i]; - stack[i] = nullptr; + child = stack[--i]; + stack[i] = nullptr; child->parent = joint; - joint = child; + joint = child; } return joint; } void deleteTransform(Node *node) { IJointTransform *transform = nullptr; - auto iter = pool.find(node->getUuid()); + auto iter = pool.find(node->getUuid()); if (iter != pool.end()) { transform = iter->second; } diff --git a/native/cocos/core/animation/SkeletalAnimationUtils.h b/native/cocos/core/animation/SkeletalAnimationUtils.h index 32bd833962..f54d8c1654 100644 --- a/native/cocos/core/animation/SkeletalAnimationUtils.h +++ b/native/cocos/core/animation/SkeletalAnimationUtils.h @@ -32,10 +32,10 @@ namespace cc { class Node; struct IJointTransform { - Node * node{nullptr}; - Mat4 local; - Mat4 world; - int stamp{-1}; + Node *node{nullptr}; + Mat4 local; + Mat4 world; + int stamp{-1}; struct IJointTransform *parent{nullptr}; }; diff --git a/native/cocos/core/assets/Asset.cpp b/native/cocos/core/assets/Asset.cpp index 867326ffed..9b8335b19b 100644 --- a/native/cocos/core/assets/Asset.cpp +++ b/native/cocos/core/assets/Asset.cpp @@ -57,7 +57,7 @@ ccstd::string Asset::getNativeUrl() const { } return _nativeUrl; } -Asset::Asset() = default; +Asset::Asset() = default; Asset::~Asset() = default; NativeDep Asset::getNativeDep() const { diff --git a/native/cocos/core/assets/Asset.h b/native/cocos/core/assets/Asset.h index e5363081bf..2d6c52fae7 100644 --- a/native/cocos/core/assets/Asset.h +++ b/native/cocos/core/assets/Asset.h @@ -57,7 +57,7 @@ public: NativeDep getNativeDep() const; inline const ccstd::string &getUuid() const { return _uuid; } - inline void setUuid(const ccstd::string &uuid) { _uuid = uuid; } + inline void setUuid(const ccstd::string &uuid) { _uuid = uuid; } /** * @en @@ -93,8 +93,8 @@ public: */ virtual void createNode(const CreateNodeCallback &cb) {} - void addAssetRef(); - void decAssetRef(bool autoRelease = true); + void addAssetRef(); + void decAssetRef(bool autoRelease = true); inline uint32_t getAssetRefCount() const { return _assetRefCount; } virtual void onLoaded() {} @@ -146,7 +146,7 @@ public: protected: ccstd::string _uuid; - cc::any _file; + cc::any _file; uint32_t _assetRefCount{0}; bool _loaded{true}; diff --git a/native/cocos/core/assets/BitmapFont.cpp b/native/cocos/core/assets/BitmapFont.cpp index 2e0e5b24e3..2d821fd0b1 100644 --- a/native/cocos/core/assets/BitmapFont.cpp +++ b/native/cocos/core/assets/BitmapFont.cpp @@ -56,43 +56,43 @@ void BitmapFontFace::doInit(const FontFaceInfo & /*info*/) { auto *fontNode = doc.RootElement(); auto *infoNode = fontNode->FirstChildElement("info"); - _fontSize = infoNode->UnsignedAttribute("size"); + _fontSize = infoNode->UnsignedAttribute("size"); auto *commonNode = fontNode->FirstChildElement("common"); - _lineHeight = commonNode->UnsignedAttribute("lineHeight"); - _textureWidth = commonNode->UnsignedAttribute("scaleW"); - _textureHeight = commonNode->UnsignedAttribute("scaleH"); - uint32_t pages = commonNode->UnsignedAttribute("pages"); - int base = commonNode->IntAttribute("base"); + _lineHeight = commonNode->UnsignedAttribute("lineHeight"); + _textureWidth = commonNode->UnsignedAttribute("scaleW"); + _textureHeight = commonNode->UnsignedAttribute("scaleH"); + uint32_t pages = commonNode->UnsignedAttribute("pages"); + int base = commonNode->IntAttribute("base"); // load glyphs auto *charsNode = fontNode->FirstChildElement("chars"); - auto *charNode = charsNode->FirstChildElement("char"); + auto *charNode = charsNode->FirstChildElement("char"); while (charNode) { FontGlyph glyph; - uint32_t value{0U}; + uint32_t value{0U}; - uint32_t code = charNode->UnsignedAttribute("id"); - glyph.x = static_cast(charNode->IntAttribute("x")); - glyph.y = static_cast(charNode->IntAttribute("y")); - glyph.width = static_cast(charNode->UnsignedAttribute("width")); - glyph.height = static_cast(charNode->UnsignedAttribute("height")); + uint32_t code = charNode->UnsignedAttribute("id"); + glyph.x = static_cast(charNode->IntAttribute("x")); + glyph.y = static_cast(charNode->IntAttribute("y")); + glyph.width = static_cast(charNode->UnsignedAttribute("width")); + glyph.height = static_cast(charNode->UnsignedAttribute("height")); glyph.bearingX = static_cast(charNode->IntAttribute("xoffset")); glyph.bearingY = static_cast(base - charNode->IntAttribute("yoffset")); - glyph.advance = static_cast(charNode->IntAttribute("xadvance")); - glyph.page = charNode->UnsignedAttribute("page"); + glyph.advance = static_cast(charNode->IntAttribute("xadvance")); + glyph.page = charNode->UnsignedAttribute("page"); _glyphs[code] = glyph; - charNode = charNode->NextSiblingElement(); + charNode = charNode->NextSiblingElement(); } // load textures auto *pagesNode = fontNode->FirstChildElement("pages"); - auto *pageNode = pagesNode->FirstChildElement("page"); + auto *pageNode = pagesNode->FirstChildElement("page"); _textures.resize(pages, nullptr); ccstd::string path = fontPath; - auto pos = fontPath.rfind('/'); + auto pos = fontPath.rfind('/'); if (pos == ccstd::string::npos) { pos = fontPath.rfind('\\'); @@ -103,20 +103,20 @@ void BitmapFontFace::doInit(const FontFaceInfo & /*info*/) { } while (pageNode) { - uint32_t id = pageNode->UnsignedAttribute("id"); + uint32_t id = pageNode->UnsignedAttribute("id"); ccstd::string file = pageNode->Attribute("file"); - _textures[id] = loadTexture(path + file); + _textures[id] = loadTexture(path + file); pageNode = pageNode->NextSiblingElement(); } // load kernings auto *kerningsNode = fontNode->FirstChildElement("kernings"); - auto *kerningNode = kerningsNode->FirstChildElement("kerning"); + auto *kerningNode = kerningsNode->FirstChildElement("kerning"); while (kerningNode) { KerningPair pair; - pair.prevCode = kerningNode->UnsignedAttribute("first"); - pair.nextCode = kerningNode->UnsignedAttribute("second"); + pair.prevCode = kerningNode->UnsignedAttribute("first"); + pair.nextCode = kerningNode->UnsignedAttribute("second"); _kernings[pair] = static_cast(kerningNode->IntAttribute("amount")); kerningNode = kerningNode->NextSiblingElement(); @@ -148,8 +148,8 @@ float BitmapFontFace::getKerning(uint32_t prevCode, uint32_t nextCode) { } gfx::Texture *BitmapFontFace::loadTexture(const ccstd::string &path) { - auto *image = ccnew Image(); - bool success = image->initWithImageFile(path); + auto *image = ccnew Image(); + bool success = image->initWithImageFile(path); if (!success) { CC_LOG_WARNING("BitmapFontFace initWithImageFile failed, path: %s.", path.c_str()); delete image; @@ -162,17 +162,17 @@ gfx::Texture *BitmapFontFace::loadTexture(const ccstd::string &path) { return nullptr; } - auto width = static_cast(image->getWidth()); + auto width = static_cast(image->getWidth()); auto height = static_cast(image->getHeight()); - auto *device = gfx::Device::getInstance(); + auto *device = gfx::Device::getInstance(); auto *texture = device->createTexture({gfx::TextureType::TEX2D, gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_DST, gfx::Format::R8, width, height}); - gfx::BufferDataList buffers{image->getData()}; + gfx::BufferDataList buffers{image->getData()}; gfx::BufferTextureCopyList regions = {{0U, 0U, {0U, 0U, 0U}, @@ -197,7 +197,7 @@ FontFace *BitmapFont::createFace(const FontFaceInfo &info) { face->doInit(info); uint32_t fontSize = face->getFontSize(); - _faces[fontSize] = face; + _faces[fontSize] = face; return face; } diff --git a/native/cocos/core/assets/BitmapFont.h b/native/cocos/core/assets/BitmapFont.h index ec35a2fded..fa58e8d255 100644 --- a/native/cocos/core/assets/BitmapFont.h +++ b/native/cocos/core/assets/BitmapFont.h @@ -34,17 +34,17 @@ namespace cc { class BitmapFontFace : public FontFace { public: explicit BitmapFontFace(Font *font); - ~BitmapFontFace() override = default; + ~BitmapFontFace() override = default; BitmapFontFace(const BitmapFontFace &) = delete; - BitmapFontFace(BitmapFontFace &&) = delete; + BitmapFontFace(BitmapFontFace &&) = delete; BitmapFontFace &operator=(const BitmapFontFace &) = delete; BitmapFontFace &operator=(BitmapFontFace &&) = delete; const FontGlyph *getGlyph(uint32_t code) override; - float getKerning(uint32_t prevCode, uint32_t nextCode) override; + float getKerning(uint32_t prevCode, uint32_t nextCode) override; private: - void doInit(const FontFaceInfo &info) override; + void doInit(const FontFaceInfo &info) override; static gfx::Texture *loadTexture(const ccstd::string &path); friend class BitmapFont; @@ -56,9 +56,9 @@ private: class BitmapFont : public Font { public: explicit BitmapFont(const ccstd::string &path); - ~BitmapFont() override = default; + ~BitmapFont() override = default; BitmapFont(const BitmapFont &) = delete; - BitmapFont(BitmapFont &&) = delete; + BitmapFont(BitmapFont &&) = delete; BitmapFont &operator=(const BitmapFont &) = delete; BitmapFont &operator=(BitmapFont &&) = delete; diff --git a/native/cocos/core/assets/BufferAsset.h b/native/cocos/core/assets/BufferAsset.h index a3084b0c9f..fe4121a1ba 100644 --- a/native/cocos/core/assets/BufferAsset.h +++ b/native/cocos/core/assets/BufferAsset.h @@ -32,14 +32,14 @@ namespace cc { class BufferAsset final : public Asset { public: - BufferAsset() = default; + BufferAsset() = default; ~BufferAsset() override = default; inline ArrayBuffer *getBuffer() const { return _buffer; } cc::any getNativeAsset() const override; - void setNativeAsset(const cc::any &obj) override; - bool validate() const override { return _buffer != nullptr; } + void setNativeAsset(const cc::any &obj) override; + bool validate() const override { return _buffer != nullptr; } private: ArrayBuffer::Ptr _buffer; diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index a4278bc143..c6182553f5 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ - #include "cocos.h" #include "engine/BaseEngine.h" #include "core/assets/EffectAsset.h" @@ -37,14 +36,14 @@ IPassStates::IPassStates(const IPassInfoFull &o) { } IPassStates &IPassStates::operator=(const IPassInfoFull &o) { - priority = o.priority; - primitive = o.primitive; - stage = o.stage; - rasterizerState = o.rasterizerState; + priority = o.priority; + primitive = o.primitive; + stage = o.stage; + rasterizerState = o.rasterizerState; depthStencilState = o.depthStencilState; - blendState = o.blendState; - dynamicStates = o.dynamicStates; - phase = o.phase; + blendState = o.blendState; + dynamicStates = o.dynamicStates; + phase = o.phase; return *this; } @@ -156,10 +155,10 @@ bool EffectAsset::destroy() { void EffectAsset::initDefault(const cc::optional &uuid) { Super::initDefault(uuid); const auto *effect = EffectAsset::get("unlit"); - _name = "unlit"; - _shaders = effect->_shaders; - _combinations = effect->_combinations; - _techniques = effect->_techniques; //NOTE: it will copy effect->_techniques to _techniques and _techniques will kept by SE_HOLD_RETURN_VALUE + _name = "unlit"; + _shaders = effect->_shaders; + _combinations = effect->_combinations; + _techniques = effect->_techniques; //NOTE: it will copy effect->_techniques to _techniques and _techniques will kept by SE_HOLD_RETURN_VALUE } bool EffectAsset::validate() const { @@ -227,7 +226,7 @@ ccstd::vector EffectAsset::doCombine(const ccstd::vectorsecond; - const ccstd::string & key = iter->first; + const ccstd::string &key = iter->first; ccstd::vector records; if (cur.empty()) { @@ -267,26 +266,26 @@ ccstd::vector EffectAsset::generateRecords(const ccstd::string &key } ccstd::vector EffectAsset::insertInfoValue(const ccstd::vector &records, - const ccstd::string & key, - const IPreCompileInfoValueType & infoValue) { + const ccstd::string &key, + const IPreCompileInfoValueType &infoValue) { ccstd::vector ret; for (const auto &record : records) { if (const auto *boolValues = cc::get_if>(&infoValue)) { for (const bool value : *boolValues) { MacroRecord tmpRecord = record; - tmpRecord[key] = value; + tmpRecord[key] = value; ret.emplace_back(tmpRecord); } } else if (const auto *intValues = cc::get_if>(&infoValue)) { for (const int32_t value : *intValues) { MacroRecord tmpRecord = record; - tmpRecord[key] = value; + tmpRecord[key] = value; ret.emplace_back(tmpRecord); } } else if (const auto *stringValues = cc::get_if>(&infoValue)) { for (const ccstd::string &value : *stringValues) { MacroRecord tmpRecord = record; - tmpRecord[key] = value; + tmpRecord[key] = value; ret.emplace_back(tmpRecord); } } else { diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index 569ea81a1f..3450cbe861 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -45,11 +45,11 @@ using IPropertyHandleInfo = std::tuple; using IPropertyValue = cc::optional, ccstd::string>>; struct IPropertyInfo { - int32_t type; // auto-extracted from shader - cc::optional handleInfo; // auto-generated from 'target' - cc::optional samplerHash; // auto-generated from 'sampler' - IPropertyValue value; // default value - cc::optional linear; // whether to convert the input to linear space first before applying + int32_t type; // auto-extracted from shader + cc::optional handleInfo; // auto-generated from 'target' + cc::optional samplerHash; // auto-generated from 'sampler' + IPropertyValue value; // default value + cc::optional linear; // whether to convert the input to linear space first before applying }; struct IPassInfoFull; @@ -62,8 +62,8 @@ struct RasterizerStateInfo { cc::optional isMultisample; cc::optional polygonMode; - cc::optional shadeModel; - cc::optional cullMode; + cc::optional shadeModel; + cc::optional cullMode; cc::optional depthBias; cc::optional depthBiasClamp; @@ -71,20 +71,20 @@ struct RasterizerStateInfo { cc::optional lineWidth; void fromGFXRasterizerState(const gfx::RasterizerState &rs) { - isDiscard = rs.isDiscard; - isFrontFaceCCW = rs.isFrontFaceCCW; + isDiscard = rs.isDiscard; + isFrontFaceCCW = rs.isFrontFaceCCW; depthBiasEnabled = rs.depthBiasEnabled; - isDepthClip = rs.isDepthClip; - isMultisample = rs.isMultisample; + isDepthClip = rs.isDepthClip; + isMultisample = rs.isMultisample; polygonMode = rs.polygonMode; - shadeModel = rs.shadeModel; - cullMode = rs.cullMode; + shadeModel = rs.shadeModel; + cullMode = rs.cullMode; - depthBias = rs.depthBias; + depthBias = rs.depthBias; depthBiasClamp = rs.depthBiasClamp; - depthBiasSlop = rs.depthBiasSlop; - lineWidth = rs.lineWidth; + depthBiasSlop = rs.depthBiasSlop; + lineWidth = rs.lineWidth; } void assignToGFXRasterizerState(gfx::RasterizerState &rs) const { @@ -135,43 +135,43 @@ struct DepthStencilStateInfo { cc::optional depthFunc; cc::optional stencilFuncFront; - cc::optional stencilReadMaskFront; - cc::optional stencilWriteMaskFront; - cc::optional stencilFailOpFront; - cc::optional stencilZFailOpFront; - cc::optional stencilPassOpFront; - cc::optional stencilRefFront; + cc::optional stencilReadMaskFront; + cc::optional stencilWriteMaskFront; + cc::optional stencilFailOpFront; + cc::optional stencilZFailOpFront; + cc::optional stencilPassOpFront; + cc::optional stencilRefFront; cc::optional stencilFuncBack; - cc::optional stencilReadMaskBack; - cc::optional stencilWriteMaskBack; - cc::optional stencilFailOpBack; - cc::optional stencilZFailOpBack; - cc::optional stencilPassOpBack; - cc::optional stencilRefBack; + cc::optional stencilReadMaskBack; + cc::optional stencilWriteMaskBack; + cc::optional stencilFailOpBack; + cc::optional stencilZFailOpBack; + cc::optional stencilPassOpBack; + cc::optional stencilRefBack; void fromGFXDepthStencilState(const gfx::DepthStencilState &ds) { - depthTest = ds.depthTest; - depthWrite = ds.depthWrite; + depthTest = ds.depthTest; + depthWrite = ds.depthWrite; stencilTestFront = ds.stencilTestFront; - stencilTestBack = ds.stencilTestBack; + stencilTestBack = ds.stencilTestBack; - depthFunc = ds.depthFunc; - stencilFuncFront = ds.stencilFuncFront; - stencilReadMaskFront = ds.stencilReadMaskFront; + depthFunc = ds.depthFunc; + stencilFuncFront = ds.stencilFuncFront; + stencilReadMaskFront = ds.stencilReadMaskFront; stencilWriteMaskFront = ds.stencilWriteMaskFront; - stencilFailOpFront = ds.stencilFailOpFront; - stencilZFailOpFront = ds.stencilZFailOpFront; - stencilPassOpFront = ds.stencilPassOpFront; - stencilRefFront = ds.stencilRefFront; + stencilFailOpFront = ds.stencilFailOpFront; + stencilZFailOpFront = ds.stencilZFailOpFront; + stencilPassOpFront = ds.stencilPassOpFront; + stencilRefFront = ds.stencilRefFront; - stencilFuncBack = ds.stencilFuncBack; - stencilReadMaskBack = ds.stencilReadMaskBack; + stencilFuncBack = ds.stencilFuncBack; + stencilReadMaskBack = ds.stencilReadMaskBack; stencilWriteMaskBack = ds.stencilWriteMaskBack; - stencilFailOpBack = ds.stencilFailOpBack; - stencilZFailOpBack = ds.stencilZFailOpBack; - stencilPassOpBack = ds.stencilPassOpBack; - stencilRefBack = ds.stencilRefBack; + stencilFailOpBack = ds.stencilFailOpBack; + stencilZFailOpBack = ds.stencilZFailOpBack; + stencilPassOpBack = ds.stencilPassOpBack; + stencilRefBack = ds.stencilRefBack; } void assignToGFXDepthStencilState(gfx::DepthStencilState &ds) const { @@ -236,23 +236,23 @@ struct DepthStencilStateInfo { }; struct BlendTargetInfo { - cc::optional blend; + cc::optional blend; cc::optional blendSrc; cc::optional blendDst; - cc::optional blendEq; + cc::optional blendEq; cc::optional blendSrcAlpha; cc::optional blendDstAlpha; - cc::optional blendAlphaEq; - cc::optional blendColorMask; + cc::optional blendAlphaEq; + cc::optional blendColorMask; void fromGFXBlendTarget(const gfx::BlendTarget &target) { - blend = target.blend; - blendSrc = target.blendSrc; - blendDst = target.blendDst; - blendEq = target.blendEq; - blendSrcAlpha = target.blendSrcAlpha; - blendDstAlpha = target.blendDstAlpha; - blendAlphaEq = target.blendAlphaEq; + blend = target.blend; + blendSrc = target.blendSrc; + blendDst = target.blendDst; + blendEq = target.blendEq; + blendSrcAlpha = target.blendSrcAlpha; + blendDstAlpha = target.blendDstAlpha; + blendAlphaEq = target.blendAlphaEq; blendColorMask = target.blendColorMask; } @@ -287,13 +287,13 @@ struct BlendTargetInfo { using BlendTargetInfoList = ccstd::vector; struct BlendStateInfo { - cc::optional isA2C; - cc::optional isIndepend; - cc::optional blendColor; + cc::optional isA2C; + cc::optional isIndepend; + cc::optional blendColor; cc::optional targets; void fromGFXBlendState(const gfx::BlendState &bs) { - isA2C = bs.isA2C; + isA2C = bs.isA2C; isIndepend = bs.isIndepend; blendColor = bs.blendColor; size_t len = bs.targets.size(); @@ -331,19 +331,19 @@ struct BlendStateInfo { // Pass instance itself are compliant to IPassStates too struct IPassStates { - cc::optional priority; - cc::optional primitive; + cc::optional priority; + cc::optional primitive; cc::optional stage; - cc::optional rasterizerState; - cc::optional depthStencilState; - cc::optional blendState; - cc::optional dynamicStates; - cc::optional phase; + cc::optional rasterizerState; + cc::optional depthStencilState; + cc::optional blendState; + cc::optional dynamicStates; + cc::optional phase; IPassStates() = default; explicit IPassStates(const IPassInfoFull &o); IPassStates &operator=(const IPassInfoFull &o); - void overrides(const IPassInfoFull &o); + void overrides(const IPassInfoFull &o); }; using PassOverrides = IPassStates; @@ -351,25 +351,25 @@ using PassPropertyInfoMap = ccstd::unordered_map; struct IPassInfoFull final { //cjh } : public IPassInfo { // IPassStates - cc::optional priority; - cc::optional primitive; + cc::optional priority; + cc::optional primitive; cc::optional stage; - cc::optional rasterizerState; - cc::optional depthStencilState; - cc::optional blendState; - cc::optional dynamicStates; - cc::optional phase; + cc::optional rasterizerState; + cc::optional depthStencilState; + cc::optional blendState; + cc::optional dynamicStates; + cc::optional phase; // IPassInfo - ccstd::string program; // auto-generated from 'vert' and 'frag' - cc::optional embeddedMacros; - index_t propertyIndex{CC_INVALID_INDEX}; - cc::optional switch_; + ccstd::string program; // auto-generated from 'vert' and 'frag' + cc::optional embeddedMacros; + index_t propertyIndex{CC_INVALID_INDEX}; + cc::optional switch_; cc::optional properties; // IPassInfoFull // generated part - index_t passIndex{0}; - MacroRecord defines; + index_t passIndex{0}; + MacroRecord defines; cc::optional stateOverrides; IPassInfoFull() = default; @@ -377,14 +377,14 @@ struct IPassInfoFull final { //cjh } : public IPassInfo { *this = o; } IPassInfoFull &operator=(const IPassStates &o) { - priority = o.priority; - primitive = o.primitive; - stage = o.stage; - rasterizerState = o.rasterizerState; + priority = o.priority; + primitive = o.primitive; + stage = o.stage; + rasterizerState = o.rasterizerState; depthStencilState = o.depthStencilState; - blendState = o.blendState; - dynamicStates = o.dynamicStates; - phase = o.phase; + blendState = o.blendState; + dynamicStates = o.dynamicStates; + phase = o.phase; return *this; } }; @@ -393,86 +393,86 @@ using IPassInfo = IPassInfoFull; struct ITechniqueInfo { ccstd::vector passes; - cc::optional name; + cc::optional name; }; struct IBlockInfo { - int32_t binding{-1}; - ccstd::string name; + int32_t binding{-1}; + ccstd::string name; ccstd::vector members; - gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; + gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct ISamplerTextureInfo { - int32_t binding{-1}; - ccstd::string name; - gfx::Type type{gfx::Type::UNKNOWN}; - uint32_t count{0}; + int32_t binding{-1}; + ccstd::string name; + gfx::Type type{gfx::Type::UNKNOWN}; + uint32_t count{0}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct ITextureInfo { - uint32_t set{0}; - int32_t binding{-1}; - ccstd::string name; - gfx::Type type{gfx::Type::UNKNOWN}; - uint32_t count{0}; + uint32_t set{0}; + int32_t binding{-1}; + ccstd::string name; + gfx::Type type{gfx::Type::UNKNOWN}; + uint32_t count{0}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct ISamplerInfo { - uint32_t set{0}; - int32_t binding{-1}; - ccstd::string name; - uint32_t count{0}; + uint32_t set{0}; + int32_t binding{-1}; + ccstd::string name; + uint32_t count{0}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct IBufferInfo { - int32_t binding{-1}; - ccstd::string name; - gfx::MemoryAccess memoryAccess{gfx::MemoryAccess::NONE}; + int32_t binding{-1}; + ccstd::string name; + gfx::MemoryAccess memoryAccess{gfx::MemoryAccess::NONE}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct IImageInfo { - int32_t binding{-1}; - ccstd::string name; - gfx::Type type{gfx::Type::UNKNOWN}; - uint32_t count{0}; - gfx::MemoryAccess memoryAccess{gfx::MemoryAccess::NONE}; + int32_t binding{-1}; + ccstd::string name; + gfx::Type type{gfx::Type::UNKNOWN}; + uint32_t count{0}; + gfx::MemoryAccess memoryAccess{gfx::MemoryAccess::NONE}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct IInputAttachmentInfo { - uint32_t set{0}; - int32_t binding{-1}; - ccstd::string name; - uint32_t count{0}; + uint32_t set{0}; + int32_t binding{-1}; + ccstd::string name; + uint32_t count{0}; gfx::ShaderStageFlags stageFlags{gfx::ShaderStageFlags::NONE}; }; struct IAttributeInfo { ccstd::string name; - gfx::Format format{gfx::Format::UNKNOWN}; - bool isNormalized{false}; - uint32_t stream{0U}; - bool isInstanced{false}; - uint32_t location{0U}; + gfx::Format format{gfx::Format::UNKNOWN}; + bool isNormalized{false}; + uint32_t stream{0U}; + bool isInstanced{false}; + uint32_t location{0U}; ccstd::vector defines; }; struct IDefineInfo { - ccstd::string name; - ccstd::string type; - cc::optional> range; //cjh number is float? ?: number[]; + ccstd::string name; + ccstd::string type; + cc::optional> range; //cjh number is float? ?: number[]; cc::optional> options; - cc::optional defaultVal; + cc::optional defaultVal; }; struct IBuiltin { - ccstd::string name; + ccstd::string name; ccstd::vector defines; }; @@ -486,8 +486,8 @@ struct IBuiltinInfo { using BuiltinsStatisticsType = ccstd::unordered_map; struct IBuiltins { - IBuiltinInfo globals; - IBuiltinInfo locals; + IBuiltinInfo globals; + IBuiltinInfo locals; BuiltinsStatisticsType statistics; }; @@ -497,20 +497,20 @@ struct IShaderSource { }; struct IShaderInfo { - ccstd::string name; - uint64_t hash{0xFFFFFFFFFFFFFFFFULL}; //cjh hash is 64 bit? - IShaderSource glsl4; - IShaderSource glsl3; - IShaderSource glsl1; - IBuiltins builtins; - ccstd::vector defines; - ccstd::vector attributes; - ccstd::vector blocks; - ccstd::vector samplerTextures; - ccstd::vector samplers; - ccstd::vector textures; - ccstd::vector buffers; - ccstd::vector images; + ccstd::string name; + uint64_t hash{0xFFFFFFFFFFFFFFFFULL}; //cjh hash is 64 bit? + IShaderSource glsl4; + IShaderSource glsl3; + IShaderSource glsl1; + IBuiltins builtins; + ccstd::vector defines; + ccstd::vector attributes; + ccstd::vector blocks; + ccstd::vector samplerTextures; + ccstd::vector samplers; + ccstd::vector textures; + ccstd::vector buffers; + ccstd::vector images; ccstd::vector subpassInputs; const IShaderSource *getSource(const ccstd::string &version) const { @@ -522,13 +522,13 @@ struct IShaderInfo { }; using IPreCompileInfoValueType = cc::variant, ccstd::vector, ccstd::vector>; -using IPreCompileInfo = ccstd::unordered_map; +using IPreCompileInfo = ccstd::unordered_map; class EffectAsset final : public Asset { public: using Super = Asset; - EffectAsset() = default; + EffectAsset() = default; ~EffectAsset() override = default; /** * @en Register the effect asset to the static map @@ -560,8 +560,8 @@ public: inline void setShaders(const ccstd::vector &val) { _shaders = val; } inline void setCombinations(const ccstd::vector &val) { _combinations = val; } - inline const ccstd::vector & getTechniques() const { return _techniques; } - inline const ccstd::vector & getShaders() const { return _shaders; } + inline const ccstd::vector &getTechniques() const { return _techniques; } + inline const ccstd::vector &getShaders() const { return _shaders; } inline const ccstd::vector &getCombinations() const { return _combinations; } /* @@ -583,8 +583,8 @@ protected: static ccstd::vector doCombine(const ccstd::vector &cur, const IPreCompileInfo &info, IPreCompileInfo::iterator iter); static ccstd::vector generateRecords(const ccstd::string &key, const IPreCompileInfoValueType &value); static ccstd::vector insertInfoValue(const ccstd::vector &records, - const ccstd::string & key, - const IPreCompileInfoValueType & value); + const ccstd::string &key, + const IPreCompileInfoValueType &value); void precompile(); diff --git a/native/cocos/core/assets/Font.h b/native/cocos/core/assets/Font.h index 87ff0d5773..8c8effc102 100644 --- a/native/cocos/core/assets/Font.h +++ b/native/cocos/core/assets/Font.h @@ -37,8 +37,8 @@ class Texture; class Font; constexpr uint32_t DEFAULT_FREETYPE_TEXTURE_SIZE = 512U; -constexpr uint32_t MIN_FONT_SIZE = 1U; -constexpr uint32_t MAX_FONT_SIZE = 128U; +constexpr uint32_t MIN_FONT_SIZE = 1U; +constexpr uint32_t MAX_FONT_SIZE = 128U; enum class FontType { INVALID, @@ -47,13 +47,13 @@ enum class FontType { }; struct FontGlyph { - int16_t x{0}; - int16_t y{0}; + int16_t x{0}; + int16_t y{0}; uint16_t width{0U}; uint16_t height{0U}; - int16_t bearingX{0}; - int16_t bearingY{0}; - int32_t advance{0}; + int16_t bearingX{0}; + int16_t bearingY{0}; + int32_t advance{0}; uint32_t page{0U}; // index of textures }; @@ -83,9 +83,9 @@ struct FontFaceInfo { FontFaceInfo(uint32_t size, uint32_t width, uint32_t height, ccstd::vector chars); // only used in freetype, for bitmap font, fontSize is determined by file. - uint32_t fontSize{1U}; - uint32_t textureWidth{DEFAULT_FREETYPE_TEXTURE_SIZE}; - uint32_t textureHeight{DEFAULT_FREETYPE_TEXTURE_SIZE}; + uint32_t fontSize{1U}; + uint32_t textureWidth{DEFAULT_FREETYPE_TEXTURE_SIZE}; + uint32_t textureHeight{DEFAULT_FREETYPE_TEXTURE_SIZE}; ccstd::vector preLoadedCharacters; //~ }; @@ -98,32 +98,32 @@ public: explicit FontFace(Font *font); virtual ~FontFace(); FontFace(const FontFace &) = delete; - FontFace(FontFace &&) = delete; + FontFace(FontFace &&) = delete; FontFace &operator=(const FontFace &) = delete; FontFace &operator=(FontFace &&) = delete; - virtual const FontGlyph *getGlyph(uint32_t code) = 0; - virtual float getKerning(uint32_t prevCode, uint32_t nextCode) = 0; + virtual const FontGlyph *getGlyph(uint32_t code) = 0; + virtual float getKerning(uint32_t prevCode, uint32_t nextCode) = 0; - inline Font * getFont() const { return _font; } - inline uint32_t getFontSize() const { return _fontSize; } - inline uint32_t getLineHeight() const { return _lineHeight; } + inline Font *getFont() const { return _font; } + inline uint32_t getFontSize() const { return _fontSize; } + inline uint32_t getLineHeight() const { return _lineHeight; } inline const ccstd::vector &getTextures() const { return _textures; } - inline gfx::Texture * getTexture(uint32_t page) const { return _textures[page]; } - inline uint32_t getTextureWidth() const { return _textureWidth; } - inline uint32_t getTextureHeight() const { return _textureHeight; } + inline gfx::Texture *getTexture(uint32_t page) const { return _textures[page]; } + inline uint32_t getTextureWidth() const { return _textureWidth; } + inline uint32_t getTextureHeight() const { return _textureHeight; } protected: virtual void doInit(const FontFaceInfo &info) = 0; - Font * _font{nullptr}; - uint32_t _fontSize{1U}; - uint32_t _lineHeight{0U}; - ccstd::unordered_map _glyphs; + Font *_font{nullptr}; + uint32_t _fontSize{1U}; + uint32_t _lineHeight{0U}; + ccstd::unordered_map _glyphs; ccstd::unordered_map _kernings; - ccstd::vector _textures; - uint32_t _textureWidth{0U}; - uint32_t _textureHeight{0U}; + ccstd::vector _textures; + uint32_t _textureWidth{0U}; + uint32_t _textureHeight{0U}; }; /** @@ -134,24 +134,24 @@ public: Font(FontType type, const ccstd::string &path); ~Font() override; Font(const Font &) = delete; - Font(Font &&) = delete; + Font(Font &&) = delete; Font &operator=(const Font &) = delete; Font &operator=(Font &&) = delete; virtual FontFace *createFace(const FontFaceInfo &info) = 0; - inline FontType getType() const { return _type; } - inline const ccstd::string & getPath() const { return _path; } + inline FontType getType() const { return _type; } + inline const ccstd::string &getPath() const { return _path; } inline const ccstd::vector &getData() const { return _data; } - inline FontFace * getFace(uint32_t fontSize) { return _faces[fontSize]; } - void releaseFaces(); + inline FontFace *getFace(uint32_t fontSize) { return _faces[fontSize]; } + void releaseFaces(); protected: void load(const ccstd::string &path); - FontType _type{FontType::INVALID}; - ccstd::string _path; - ccstd::vector _data; + FontType _type{FontType::INVALID}; + ccstd::string _path; + ccstd::vector _data; ccstd::unordered_map _faces; }; diff --git a/native/cocos/core/assets/FreeTypeFont.cpp b/native/cocos/core/assets/FreeTypeFont.cpp index 8ca132e274..ec59e08e6a 100644 --- a/native/cocos/core/assets/FreeTypeFont.cpp +++ b/native/cocos/core/assets/FreeTypeFont.cpp @@ -87,8 +87,8 @@ public: : _maxWidth(maxWidth), _maxHeight(maxHeight) {} inline void reset() { - _nextX = 0U; - _nextY = 0U; + _nextX = 0U; + _nextY = 0U; _maxLineHeight = 0U; } @@ -110,8 +110,8 @@ public: x = 0U; y = nextY; - _nextX = width; - _nextY = nextY; + _nextX = width; + _nextY = nextY; _maxLineHeight = height; return true; @@ -151,12 +151,12 @@ void FreeTypeFontFace::doInit(const FontFaceInfo &info) { return; } - _fontSize = info.fontSize < MIN_FONT_SIZE ? MIN_FONT_SIZE : (info.fontSize > MAX_FONT_SIZE ? MAX_FONT_SIZE : info.fontSize); - _textureWidth = info.textureWidth; + _fontSize = info.fontSize < MIN_FONT_SIZE ? MIN_FONT_SIZE : (info.fontSize > MAX_FONT_SIZE ? MAX_FONT_SIZE : info.fontSize); + _textureWidth = info.textureWidth; _textureHeight = info.textureHeight; - _allocator = std::make_unique(_textureWidth, _textureHeight); + _allocator = std::make_unique(_textureWidth, _textureHeight); - FT_Face face{nullptr}; + FT_Face face{nullptr}; FT_Error error = FT_New_Memory_Face(library->lib, fontData.data(), static_cast(fontData.size()), 0, &face); if (error) { CC_LOG_ERROR("FT_New_Memory_Face failed, error code: %d.", error); @@ -169,7 +169,7 @@ void FreeTypeFontFace::doInit(const FontFaceInfo &info) { return; } - _face = std::make_unique(face); + _face = std::make_unique(face); _lineHeight = static_cast(face->size->metrics.height >> 6); for (const auto &code : info.preLoadedCharacters) { @@ -198,23 +198,23 @@ float FreeTypeFontFace::getKerning(uint32_t prevCode, uint32_t nextCode) { } FT_Vector kerning; - FT_UInt prevIndex = FT_Get_Char_Index(face, prevCode); - FT_UInt nextIndex = FT_Get_Char_Index(face, nextCode); - FT_Error error = FT_Get_Kerning(face, prevIndex, nextIndex, FT_KERNING_DEFAULT, &kerning); + FT_UInt prevIndex = FT_Get_Char_Index(face, prevCode); + FT_UInt nextIndex = FT_Get_Char_Index(face, nextCode); + FT_Error error = FT_Get_Kerning(face, prevIndex, nextIndex, FT_KERNING_DEFAULT, &kerning); if (error) { CC_LOG_WARNING("FT_Get_Kerning failed, error code: %d, prevCode: %d, nextCode: %d", error, prevCode, nextCode); return 0.0F; } - auto result = static_cast(kerning.x >> 6); + auto result = static_cast(kerning.x >> 6); _kernings[{prevCode, nextCode}] = result; return result; } const FontGlyph *FreeTypeFontFace::loadGlyph(uint32_t code) { - FT_Face face = _face->face; + FT_Face face = _face->face; FT_Error error = FT_Load_Char(face, code, FT_LOAD_RENDER); if (error) { CC_LOG_WARNING("FT_Load_Char failed, error code: %d, character: %u.", error, code); @@ -222,11 +222,11 @@ const FontGlyph *FreeTypeFontFace::loadGlyph(uint32_t code) { } FontGlyph glyph; - glyph.width = face->glyph->bitmap.width; - glyph.height = face->glyph->bitmap.rows; + glyph.width = face->glyph->bitmap.width; + glyph.height = face->glyph->bitmap.rows; glyph.bearingX = face->glyph->bitmap_left; glyph.bearingY = face->glyph->bitmap_top; - glyph.advance = static_cast(face->glyph->advance.x >> 6); // advance.x's unit is 1/64 pixels + glyph.advance = static_cast(face->glyph->advance.x >> 6); // advance.x's unit is 1/64 pixels uint32_t x = 0U; uint32_t y = 0U; @@ -251,8 +251,8 @@ const FontGlyph *FreeTypeFontFace::loadGlyph(uint32_t code) { auto page = static_cast(_textures.size() - 1); updateTexture(page, x, y, glyph.width, glyph.height, face->glyph->bitmap.buffer); - glyph.x = x; - glyph.y = y; + glyph.x = x; + glyph.y = y; glyph.page = page; } @@ -262,7 +262,7 @@ const FontGlyph *FreeTypeFontFace::loadGlyph(uint32_t code) { } void FreeTypeFontFace::createTexture(uint32_t width, uint32_t height) { - auto *device = gfx::Device::getInstance(); + auto *device = gfx::Device::getInstance(); auto *texture = device->createTexture({gfx::TextureType::TEX2D, gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_DST, gfx::Format::R8, @@ -272,13 +272,13 @@ void FreeTypeFontFace::createTexture(uint32_t width, uint32_t height) { _textures.push_back(texture); std::vector empty(width * height, 0); - auto page = static_cast(_textures.size() - 1); + auto page = static_cast(_textures.size() - 1); updateTexture(page, 0U, 0U, width, height, empty.data()); } void FreeTypeFontFace::updateTexture(uint32_t page, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const uint8_t *buffer) { - auto * texture = getTexture(page); - gfx::BufferDataList buffers{buffer}; + auto *texture = getTexture(page); + gfx::BufferDataList buffers{buffer}; gfx::BufferTextureCopyList regions = {{0U, 0U, {static_cast(x), static_cast(y), 0U}, @@ -308,7 +308,7 @@ FontFace *FreeTypeFont::createFace(const FontFaceInfo &info) { face->doInit(info); uint32_t fontSize = face->getFontSize(); - _faces[fontSize] = face; + _faces[fontSize] = face; return face; } diff --git a/native/cocos/core/assets/FreeTypeFont.h b/native/cocos/core/assets/FreeTypeFont.h index 9f5893e2ad..c847376a7f 100644 --- a/native/cocos/core/assets/FreeTypeFont.h +++ b/native/cocos/core/assets/FreeTypeFont.h @@ -43,25 +43,25 @@ class GlyphAllocator; class FreeTypeFontFace : public FontFace { public: explicit FreeTypeFontFace(Font *font); - ~FreeTypeFontFace() override = default; + ~FreeTypeFontFace() override = default; FreeTypeFontFace(const FreeTypeFontFace &) = delete; - FreeTypeFontFace(FreeTypeFontFace &&) = delete; + FreeTypeFontFace(FreeTypeFontFace &&) = delete; FreeTypeFontFace &operator=(const FreeTypeFontFace &) = delete; FreeTypeFontFace &operator=(FreeTypeFontFace &&) = delete; const FontGlyph *getGlyph(uint32_t code) override; - float getKerning(uint32_t prevCode, uint32_t nextCode) override; - static void destroyFreeType(); + float getKerning(uint32_t prevCode, uint32_t nextCode) override; + static void destroyFreeType(); private: - void doInit(const FontFaceInfo &info) override; + void doInit(const FontFaceInfo &info) override; const FontGlyph *loadGlyph(uint32_t code); - void createTexture(uint32_t width, uint32_t height); - void updateTexture(uint32_t page, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const uint8_t *buffer); + void createTexture(uint32_t width, uint32_t height); + void updateTexture(uint32_t page, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const uint8_t *buffer); std::unique_ptr _allocator{nullptr}; - std::unique_ptr _face; - static FTLibrary * library; + std::unique_ptr _face; + static FTLibrary *library; friend class FreeTypeFont; }; @@ -72,9 +72,9 @@ private: class FreeTypeFont : public Font { public: explicit FreeTypeFont(const ccstd::string &path); - ~FreeTypeFont() override = default; + ~FreeTypeFont() override = default; FreeTypeFont(const FreeTypeFont &) = delete; - FreeTypeFont(FreeTypeFont &&) = delete; + FreeTypeFont(FreeTypeFont &&) = delete; FreeTypeFont &operator=(const FreeTypeFont &) = delete; FreeTypeFont &operator=(FreeTypeFont &&) = delete; diff --git a/native/cocos/core/assets/ImageAsset.cpp b/native/cocos/core/assets/ImageAsset.cpp index f50c67284e..2b47564375 100644 --- a/native/cocos/core/assets/ImageAsset.cpp +++ b/native/cocos/core/assets/ImageAsset.cpp @@ -45,18 +45,18 @@ void ImageAsset::setNativeAsset(const cc::any &obj) { image->takeData(&_data); _needFreeData = true; - _width = image->getWidth(); + _width = image->getWidth(); _height = image->getHeight(); _format = static_cast(image->getRenderFormat()); - _url = image->getFilePath(); + _url = image->getFilePath(); } else { const auto *imageSource = cc::any_cast(&obj); if (imageSource != nullptr) { _arrayBuffer = imageSource->data; - _data = const_cast(_arrayBuffer->getData()); - _width = imageSource->width; - _height = imageSource->height; - _format = imageSource->format; + _data = const_cast(_arrayBuffer->getData()); + _width = imageSource->width; + _height = imageSource->height; + _format = imageSource->format; } else { CC_LOG_WARNING("ImageAsset::setNativeAsset, unknown type!"); } diff --git a/native/cocos/core/assets/ImageAsset.h b/native/cocos/core/assets/ImageAsset.h index 08350af45c..3bba586330 100644 --- a/native/cocos/core/assets/ImageAsset.h +++ b/native/cocos/core/assets/ImageAsset.h @@ -40,10 +40,10 @@ class Image; */ struct IMemoryImageSource { ArrayBuffer::Ptr data; - bool compressed{false}; - uint32_t width{0}; - uint32_t height{0}; - PixelFormat format{PixelFormat::RGBA8888}; + bool compressed{false}; + uint32_t width{0}; + uint32_t height{0}; + PixelFormat format{PixelFormat::RGBA8888}; }; /** @@ -106,13 +106,13 @@ public: inline void setUrl(const ccstd::string &url) { _url = url; } private: - uint32_t _width{0}; - uint32_t _height{0}; - PixelFormat _format{PixelFormat::RGBA8888}; - uint8_t * _data{nullptr}; - bool _needFreeData{false}; // Should free data if the data is assigned in C++. - ArrayBuffer::Ptr _arrayBuffer; //minggo: hold the data from ImageSource. - ccstd::string _url; + uint32_t _width{0}; + uint32_t _height{0}; + PixelFormat _format{PixelFormat::RGBA8888}; + uint8_t *_data{nullptr}; + bool _needFreeData{false}; // Should free data if the data is assigned in C++. + ArrayBuffer::Ptr _arrayBuffer; //minggo: hold the data from ImageSource. + ccstd::string _url; CC_DISALLOW_COPY_MOVE_ASSIGN(ImageAsset); }; diff --git a/native/cocos/core/assets/Material.cpp b/native/cocos/core/assets/Material.cpp index 38347febab..641dd940c2 100644 --- a/native/cocos/core/assets/Material.cpp +++ b/native/cocos/core/assets/Material.cpp @@ -42,7 +42,7 @@ uint64_t Material::getHashForMaterial(Material *material) { return 0; } - uint64_t hash = 0; + uint64_t hash = 0; const auto &passes = *material->_passes; for (const auto &pass : passes) { hash ^= pass->getHash(); @@ -131,15 +131,15 @@ void Material::resetUniforms(bool clearPasses /* = true */) { } void Material::setProperty(const ccstd::string &name, const MaterialPropertyVariant &val, index_t passIdx /* = CC_INVALID_INDEX */) { - const auto &passes = *_passes; - bool success = false; + const auto &passes = *_passes; + bool success = false; if (passIdx == CC_INVALID_INDEX) { // try set property for all applicable passes size_t len = passes.size(); for (size_t i = 0; i < len; i++) { const auto &pass = passes[i]; if (uploadProperty(pass, name, val)) { _props[pass->getPropertyIndex()][name] = val; - success = true; + success = true; } } } else { @@ -151,7 +151,7 @@ void Material::setProperty(const ccstd::string &name, const MaterialPropertyVari const auto &pass = passes[passIdx]; if (uploadProperty(pass, name, val)) { _props[pass->getPropertyIndex()][name] = val; - success = true; + success = true; } } @@ -206,10 +206,10 @@ CC_MATERIAL_SETPROPERTY_ARRAY_IMPL(GFXTexture, gfx::Texture *) const MaterialPropertyVariant *Material::getProperty(const ccstd::string &name, index_t passIdx) const { if (passIdx == CC_INVALID_INDEX) { // try get property in all possible passes const auto &propsArray = _props; - size_t len = propsArray.size(); + size_t len = propsArray.size(); for (size_t i = 0; i < len; i++) { const auto &props = propsArray[i]; - auto iter = props.find(name); + auto iter = props.find(name); if (iter != props.end()) { return &iter->second; } @@ -221,8 +221,8 @@ const MaterialPropertyVariant *Material::getProperty(const ccstd::string &name, } const auto &passes = *_passes; - const auto &props = _props[passes[passIdx]->getPropertyIndex()]; - auto iter = props.find(name); + const auto &props = _props[passes[passIdx]->getPropertyIndex()]; + auto iter = props.find(name); if (iter != props.end()) { return &iter->second; } @@ -311,7 +311,7 @@ void Material::update(bool keepProps /* = true*/) { ccstd::vector> Material::createPasses() { ccstd::vector> passes; - ITechniqueInfo * tech = nullptr; + ITechniqueInfo *tech = nullptr; if (_techIdx < _effectAsset->_techniques.size()) { tech = &_effectAsset->_techniques[_techIdx]; } @@ -322,14 +322,14 @@ ccstd::vector> Material::createPasses() { size_t passNum = tech->passes.size(); for (size_t k = 0; k < passNum; ++k) { - auto & passInfo = tech->passes[k]; + auto &passInfo = tech->passes[k]; index_t propIdx = passInfo.passIndex = static_cast(k); if (propIdx >= _defines.size()) { _defines.resize(propIdx + 1); } passInfo.defines = _defines[propIdx]; - auto &defines = passInfo.defines; + auto &defines = passInfo.defines; if (propIdx >= _states.size()) { _states.resize(propIdx + 1); @@ -367,11 +367,11 @@ bool Material::uploadProperty(scene::Pass *pass, const ccstd::string &name, cons pass->setUniformArray(handle, cc::get(val)); } else if (val.index() == MATERIAL_PROPERTY_INDEX_SINGLE) { const auto &passProps = pass->getProperties(); - auto iter = passProps.find(name); + auto iter = passProps.find(name); if (iter != passProps.end() && iter->second.linear.has_value()) { CC_ASSERT(cc::holds_alternative(val)); const auto &prop = cc::get(val); - Vec4 srgb; + Vec4 srgb; if (cc::holds_alternative(prop)) { srgb = cc::get(prop).toVec4(); } else if (cc::holds_alternative(prop)) { @@ -412,8 +412,8 @@ void Material::bindTexture(scene::Pass *pass, uint32_t handle, const MaterialPro if (const auto *pTexture = cc::get_if>(&val)) { pass->bindTexture(binding, const_cast(pTexture->get()), index); } else if (const auto *pTextureBase = cc::get_if>(&val)) { - auto * textureBase = pTextureBase->get(); - gfx::Texture *texture = nullptr; + auto *textureBase = pTextureBase->get(); + gfx::Texture *texture = nullptr; if (textureBase != nullptr) { texture = textureBase->getGFXTexture(); } @@ -434,10 +434,10 @@ void Material::bindTexture(scene::Pass *pass, uint32_t handle, const MaterialPro void Material::initDefault(const cc::optional &uuid) { Super::initDefault(uuid); - MacroRecord defines{{"USE_COLOR", true}}; + MacroRecord defines{{"USE_COLOR", true}}; IMaterialInfo info; info.effectName = ccstd::string{"unlit"}; - info.defines = IMaterialInfo::DefinesType{defines}; + info.defines = IMaterialInfo::DefinesType{defines}; initialize(info); setProperty("mainColor", Color{0xFF, 0x00, 0xFF, 0xFF}); } diff --git a/native/cocos/core/assets/Material.h b/native/cocos/core/assets/Material.h index 4f7562ad83..aba8ea4619 100644 --- a/native/cocos/core/assets/Material.h +++ b/native/cocos/core/assets/Material.h @@ -94,7 +94,7 @@ public: * @zh 获取一个材质的哈希值 * @param material */ - static uint64_t getHashForMaterial(Material *material); + static uint64_t getHashForMaterial(Material *material); inline static double getHashForMaterialForJS(Material *material) { return static_cast(getHashForMaterial(material)); } @@ -340,7 +340,7 @@ protected: auto *pPatchArray = cc::get_if>(&patch); if (pPatchArray != nullptr) { const auto &patchArray = *pPatchArray; - size_t len = patchArray.size(); + size_t len = patchArray.size(); cur.resize(len); for (size_t i = 0; i < len; ++i) { diff --git a/native/cocos/core/assets/RenderTexture.cpp b/native/cocos/core/assets/RenderTexture.cpp index 08090ec719..b4507ca5ab 100644 --- a/native/cocos/core/assets/RenderTexture.cpp +++ b/native/cocos/core/assets/RenderTexture.cpp @@ -50,12 +50,12 @@ gfx::RenderPassInfo getDefaultRenderPassInfo(gfx::Device *device) { } } // namespace -RenderTexture::RenderTexture() = default; +RenderTexture::RenderTexture() = default; RenderTexture::~RenderTexture() = default; void RenderTexture::initialize(const IRenderTextureCreateInfo &info) { - _name = info.name.has_value() ? info.name.value() : ""; - _width = info.width; + _name = info.name.has_value() ? info.name.value() : ""; + _width = info.width; _height = info.height; initWindow(info); } @@ -73,7 +73,7 @@ bool RenderTexture::destroy() { } void RenderTexture::resize(uint32_t width, uint32_t height) { - _width = std::floor(clampf(static_cast(width), 1.F, 2048.F)); + _width = std::floor(clampf(static_cast(width), 1.F, 2048.F)); _height = std::floor(clampf(static_cast(height), 1.F, 2048.F)); if (_window != nullptr) { _window->resize(_width, _height); @@ -93,9 +93,9 @@ void RenderTexture::initWindow() { auto *device{Root::getInstance()->getDevice()}; cc::scene::IRenderWindowInfo windowInfo; - windowInfo.title = _name; - windowInfo.width = _width; - windowInfo.height = _height; + windowInfo.title = _name; + windowInfo.width = _width; + windowInfo.height = _height; windowInfo.renderPassInfo = getDefaultRenderPassInfo(device); if (_window != nullptr) { @@ -110,8 +110,8 @@ void RenderTexture::initWindow(const IRenderTextureCreateInfo &info) { auto *device{Root::getInstance()->getDevice()}; cc::scene::IRenderWindowInfo windowInfo; - windowInfo.title = _name; - windowInfo.width = _width; + windowInfo.title = _name; + windowInfo.width = _width; windowInfo.height = _height; if (info.passInfo.has_value()) { windowInfo.renderPassInfo = info.passInfo.value(); @@ -129,7 +129,7 @@ void RenderTexture::initWindow(const IRenderTextureCreateInfo &info) { void RenderTexture::initDefault(const cc::optional &uuid) { Super::initDefault(uuid); - _width = 1; + _width = 1; _height = 1; initWindow(); } @@ -148,9 +148,9 @@ ccstd::vector RenderTexture::readPixels(uint32_t x, uint32_t y, uint32_ auto *gfxDevice = getGFXDevice(); gfx::BufferTextureCopy region0{}; - region0.texOffset.x = static_cast(x); - region0.texOffset.y = static_cast(y); - region0.texExtent.width = width; + region0.texOffset.x = static_cast(x); + region0.texOffset.y = static_cast(y); + region0.texExtent.width = width; region0.texExtent.height = height; ccstd::vector buffer; diff --git a/native/cocos/core/assets/RenderTexture.h b/native/cocos/core/assets/RenderTexture.h index fe916b95ca..d4612f9314 100644 --- a/native/cocos/core/assets/RenderTexture.h +++ b/native/cocos/core/assets/RenderTexture.h @@ -31,9 +31,9 @@ namespace cc { struct IRenderTextureCreateInfo { - cc::optional name; - uint32_t width; - uint32_t height; + cc::optional name; + uint32_t width; + uint32_t height; cc::optional passInfo; }; namespace scene { diff --git a/native/cocos/core/assets/RenderingSubMesh.cpp b/native/cocos/core/assets/RenderingSubMesh.cpp index 47decb0aca..770180f0fc 100644 --- a/native/cocos/core/assets/RenderingSubMesh.cpp +++ b/native/cocos/core/assets/RenderingSubMesh.cpp @@ -35,32 +35,32 @@ namespace cc { -RenderingSubMesh::RenderingSubMesh(const gfx::BufferList & vertexBuffers, +RenderingSubMesh::RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode) + gfx::PrimitiveMode primitiveMode) : RenderingSubMesh(vertexBuffers, attributes, primitiveMode, nullptr, nullptr) { } -RenderingSubMesh::RenderingSubMesh(const gfx::BufferList & vertexBuffers, +RenderingSubMesh::RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode, - gfx::Buffer * indexBuffer) + gfx::PrimitiveMode primitiveMode, + gfx::Buffer *indexBuffer) : RenderingSubMesh(vertexBuffers, attributes, primitiveMode, indexBuffer, nullptr) { } -RenderingSubMesh::RenderingSubMesh(const gfx::BufferList & vertexBuffers, +RenderingSubMesh::RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode, - gfx::Buffer * indexBuffer /* = nullptr*/, - gfx::Buffer * indirectBuffer /* = nullptr*/) + gfx::PrimitiveMode primitiveMode, + gfx::Buffer *indexBuffer /* = nullptr*/, + gfx::Buffer *indirectBuffer /* = nullptr*/) : _vertexBuffers(vertexBuffers), _attributes(attributes), _primitiveMode(primitiveMode), _indexBuffer(indexBuffer), _indirectBuffer(indirectBuffer) { - _iaInfo.attributes = attributes; - _iaInfo.vertexBuffers = vertexBuffers; - _iaInfo.indexBuffer = indexBuffer; + _iaInfo.attributes = attributes; + _iaInfo.vertexBuffers = vertexBuffers; + _iaInfo.indexBuffer = indexBuffer; _iaInfo.indirectBuffer = indirectBuffer; } @@ -85,9 +85,9 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() { auto index = static_cast(_subMeshIdx.value()); const auto &positionsVar = _mesh->readAttribute(index, gfx::ATTR_NAME_POSITION); - const auto *pPositions = cc::get_if(&positionsVar); + const auto *pPositions = cc::get_if(&positionsVar); if (pPositions != nullptr) { - const auto &positions = *pPositions; + const auto &positions = *pPositions; const auto &indicesVar = _mesh->readIndices(index); Vec3 max; @@ -97,7 +97,7 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() { return element.name == gfx::ATTR_NAME_POSITION; }); if (iter != _attributes.cend()) { - const auto & attri = *iter; + const auto &attri = *iter; const uint32_t count = gfx::GFX_FORMAT_INFOS[static_cast(attri.format)].count; if (count == 2) { max.set(positions[0], positions[1], 0); @@ -124,8 +124,8 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() { } IGeometricInfo info; - info.positions = positions; - info.indices = indicesVar; + info.positions = positions; + info.indices = indicesVar; info.boundingBox.max = max; info.boundingBox.min = min; @@ -142,19 +142,19 @@ void RenderingSubMesh::genFlatBuffers() { return; } - uint32_t idxCount = 0; - const auto &prim = _mesh->getStruct().primitives[_subMeshIdx.value()]; + uint32_t idxCount = 0; + const auto &prim = _mesh->getStruct().primitives[_subMeshIdx.value()]; if (prim.indexView.has_value()) { idxCount = prim.indexView.value().count; } for (size_t i = 0; i < prim.vertexBundelIndices.size(); i++) { - const uint32_t bundleIdx = prim.vertexBundelIndices[i]; + const uint32_t bundleIdx = prim.vertexBundelIndices[i]; const Mesh::IVertexBundle &vertexBundle = _mesh->getStruct().vertexBundles[bundleIdx]; - const uint32_t vbCount = prim.indexView.has_value() ? prim.indexView.value().count : vertexBundle.view.count; - const uint32_t vbStride = vertexBundle.view.stride; - const uint32_t vbSize = vbStride * vbCount; - Uint8Array view(_mesh->getData().buffer(), vertexBundle.view.offset, vertexBundle.view.length); - Uint8Array sharedView(prim.indexView.has_value() ? vbSize : vertexBundle.view.length); + const uint32_t vbCount = prim.indexView.has_value() ? prim.indexView.value().count : vertexBundle.view.count; + const uint32_t vbStride = vertexBundle.view.stride; + const uint32_t vbSize = vbStride * vbCount; + Uint8Array view(_mesh->getData().buffer(), vertexBundle.view.offset, vertexBundle.view.length); + Uint8Array sharedView(prim.indexView.has_value() ? vbSize : vertexBundle.view.length); if (!prim.indexView.has_value()) { sharedView.set(_mesh->getData().subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length)); @@ -165,8 +165,8 @@ void RenderingSubMesh::genFlatBuffers() { IBArray ibView = _mesh->readIndices(static_cast(_subMeshIdx.value())); // transform to flat buffer for (uint32_t n = 0; n < idxCount; ++n) { - auto idx = getIBArrayValue(ibView, static_cast(n)); - uint32_t offset = n * vbStride; + auto idx = getIBArrayValue(ibView, static_cast(n)); + uint32_t offset = n * vbStride; uint32_t srcOffset = idx * vbStride; for (uint32_t m = 0; m < vbStride; ++m) { sharedView[static_cast(offset + m)] = view[static_cast(srcOffset + m)]; @@ -181,14 +181,14 @@ void RenderingSubMesh::enableVertexIdChannel(gfx::Device *device) { return; } - const auto streamIndex = static_cast(_vertexBuffers.size()); + const auto streamIndex = static_cast(_vertexBuffers.size()); const auto attributeIndex = static_cast(_attributes.size()); gfx::Buffer *vertexIdBuffer = allocVertexIdBuffer(device); _vertexBuffers.pushBack(vertexIdBuffer); _attributes.push_back({"a_vertexId", gfx::Format::R32F, false, streamIndex, false, 0}); - _iaInfo.attributes = _attributes; + _iaInfo.attributes = _attributes; _iaInfo.vertexBuffers = _vertexBuffers.get(); _vertexIdChannel = VertexIdChannel{ @@ -231,18 +231,18 @@ const gfx::BufferList &RenderingSubMesh::getJointMappedBuffers() { } const auto &structInfo = _mesh->getStruct(); - const auto &prim = structInfo.primitives[_subMeshIdx.value()]; + const auto &prim = structInfo.primitives[_subMeshIdx.value()]; if (!structInfo.jointMaps.has_value() || !prim.jointMapIndex.has_value() || structInfo.jointMaps.value()[prim.jointMapIndex.value()].empty()) { _jointMappedBuffers = _vertexBuffers; return _jointMappedBuffers.get(); } - gfx::Format jointFormat = gfx::Format::UNKNOWN; - int32_t jointOffset = 0; - gfx::Device *device = gfx::Device::getInstance(); + gfx::Format jointFormat = gfx::Format::UNKNOWN; + int32_t jointOffset = 0; + gfx::Device *device = gfx::Device::getInstance(); for (size_t i = 0; i < prim.vertexBundelIndices.size(); i++) { const auto &bundle = structInfo.vertexBundles[prim.vertexBundelIndices[i]]; - jointOffset = 0; - jointFormat = gfx::Format::UNKNOWN; + jointOffset = 0; + jointFormat = gfx::Format::UNKNOWN; for (const auto &attr : bundle.attributes) { if (attr.name == gfx::ATTR_NAME_JOINTS) { jointFormat = attr.format; @@ -251,8 +251,8 @@ const gfx::BufferList &RenderingSubMesh::getJointMappedBuffers() { jointOffset += static_cast(gfx::GFX_FORMAT_INFOS[static_cast(attr.format)].size); } if (jointFormat != gfx::Format::UNKNOWN) { - Uint8Array data{_mesh->getData().buffer(), bundle.view.offset, bundle.view.length}; - DataView dataView(data.slice().buffer()); + Uint8Array data{_mesh->getData().buffer(), bundle.view.offset, bundle.view.length}; + DataView dataView(data.slice().buffer()); const auto &idxMap = structInfo.jointMaps.value()[prim.jointMapIndex.value()]; mapBuffer( @@ -299,8 +299,8 @@ gfx::Buffer *RenderingSubMesh::allocVertexIdBuffer(gfx::Device *device) { vertexIds[iVertex] = static_cast(iVertex) + 0.5F; } - uint32_t vertexIdxByteLength = sizeof(float) * vertexCount; - gfx::Buffer *vertexIdBuffer = device->createBuffer({ + uint32_t vertexIdxByteLength = sizeof(float) * vertexCount; + gfx::Buffer *vertexIdBuffer = device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, vertexIdxByteLength, diff --git a/native/cocos/core/assets/RenderingSubMesh.h b/native/cocos/core/assets/RenderingSubMesh.h index 6cd552621b..307cd47b77 100644 --- a/native/cocos/core/assets/RenderingSubMesh.h +++ b/native/cocos/core/assets/RenderingSubMesh.h @@ -71,8 +71,8 @@ struct IGeometricInfo { * @zh 扁平化顶点缓冲区 */ struct IFlatBuffer { - uint32_t stride{0}; - uint32_t count{0}; + uint32_t stride{0}; + uint32_t count{0}; Uint8Array buffer; }; @@ -85,20 +85,20 @@ class Buffer; */ class RenderingSubMesh final : public Asset { public: - RenderingSubMesh(const gfx::BufferList & vertexBuffers, + RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode); + gfx::PrimitiveMode primitiveMode); - RenderingSubMesh(const gfx::BufferList & vertexBuffers, + RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode, - gfx::Buffer * indexBuffer); + gfx::PrimitiveMode primitiveMode, + gfx::Buffer *indexBuffer); - RenderingSubMesh(const gfx::BufferList & vertexBuffers, + RenderingSubMesh(const gfx::BufferList &vertexBuffers, const gfx::AttributeList &attributes, - gfx::PrimitiveMode primitiveMode, - gfx::Buffer * indexBuffer, - gfx::Buffer * indirectBuffer); + gfx::PrimitiveMode primitiveMode, + gfx::Buffer *indexBuffer, + gfx::Buffer *indirectBuffer); ~RenderingSubMesh() override; @@ -149,14 +149,14 @@ public: * @zh 扁平化的顶点缓冲区。 */ inline const ccstd::vector &getFlatBuffers() const { return _flatBuffers; } - inline void setFlatBuffers(const ccstd::vector &flatBuffers) { _flatBuffers = flatBuffers; } + inline void setFlatBuffers(const ccstd::vector &flatBuffers) { _flatBuffers = flatBuffers; } void genFlatBuffers(); inline const gfx::InputAssemblerInfo &getIaInfo() const { return _iaInfo; } - inline gfx::InputAssemblerInfo & getIaInfo() { return _iaInfo; } + inline gfx::InputAssemblerInfo &getIaInfo() { return _iaInfo; } - inline void setDrawInfo(const gfx::DrawInfo &info) { _drawInfo = info; } + inline void setDrawInfo(const gfx::DrawInfo &info) { _drawInfo = info; } inline cc::optional &getDrawInfo() { return _drawInfo; } /** @@ -176,17 +176,17 @@ public: */ void enableVertexIdChannel(gfx::Device *device); - inline void setMesh(Mesh *mesh) { _mesh = mesh; } + inline void setMesh(Mesh *mesh) { _mesh = mesh; } inline Mesh *getMesh() const { return _mesh; } - inline void setSubMeshIdx(uint32_t idx) { _subMeshIdx = idx; } + inline void setSubMeshIdx(uint32_t idx) { _subMeshIdx = idx; } inline const cc::optional &getSubMeshIdx() const { return _subMeshIdx; } private: gfx::Buffer *allocVertexIdBuffer(gfx::Device *device); // Mesh will includes RenderingSubMesh, so use Mesh* here. - Mesh * _mesh{nullptr}; + Mesh *_mesh{nullptr}; cc::optional _subMeshIdx; ccstd::vector _flatBuffers; diff --git a/native/cocos/core/assets/SceneAsset.cpp b/native/cocos/core/assets/SceneAsset.cpp index 720534af80..3c7cb096d7 100644 --- a/native/cocos/core/assets/SceneAsset.cpp +++ b/native/cocos/core/assets/SceneAsset.cpp @@ -28,7 +28,7 @@ namespace cc { -SceneAsset::SceneAsset() = default; +SceneAsset::SceneAsset() = default; SceneAsset::~SceneAsset() = default; bool SceneAsset::validate() const { diff --git a/native/cocos/core/assets/SceneAsset.h b/native/cocos/core/assets/SceneAsset.h index 03740970e5..c295bf0b2c 100644 --- a/native/cocos/core/assets/SceneAsset.h +++ b/native/cocos/core/assets/SceneAsset.h @@ -43,7 +43,7 @@ public: bool validate() const override; inline Scene *getScene() const { return _scene.get(); } - void setScene(Scene *scene); + void setScene(Scene *scene); private: /** diff --git a/native/cocos/core/assets/SimpleTexture.cpp b/native/cocos/core/assets/SimpleTexture.cpp index 4a407b8cb3..aa9d3fe89a 100644 --- a/native/cocos/core/assets/SimpleTexture.cpp +++ b/native/cocos/core/assets/SimpleTexture.cpp @@ -35,7 +35,7 @@ namespace cc { namespace { uint32_t getMipLevel(uint32_t width, uint32_t height) { - uint32_t size = std::max(width, height); + uint32_t size = std::max(width, height); uint32_t level = 0; while (size) { size >>= 1; @@ -52,9 +52,8 @@ bool canGenerateMipmap(uint32_t w, uint32_t h) { } // namespace -SimpleTexture::SimpleTexture()= default; -SimpleTexture::~SimpleTexture()= default; - +SimpleTexture::SimpleTexture() = default; +SimpleTexture::~SimpleTexture() = default; bool SimpleTexture::destroy() { tryDestroyTextureView(); @@ -81,9 +80,9 @@ void SimpleTexture::uploadData(const uint8_t *source, uint32_t level /* = 0 */, } gfx::BufferTextureCopy region; - region.texExtent.width = _textureWidth >> level; - region.texExtent.height = _textureHeight >> level; - region.texSubres.mipLevel = level; + region.texExtent.width = _textureWidth >> level; + region.texExtent.height = _textureHeight >> level; + region.texSubres.mipLevel = level; region.texSubres.baseArrayLayer = arrayIndex; const uint8_t *buffers[1]{source}; @@ -137,7 +136,7 @@ void SimpleTexture::createTexture(gfx::Device *device) { auto flags = gfx::TextureFlagBit::NONE; if (_mipFilter != Filter::NONE && canGenerateMipmap(_width, _height)) { _mipmapLevel = getMipLevel(_width, _height); - flags = gfx::TextureFlagBit::GEN_MIPMAP; + flags = gfx::TextureFlagBit::GEN_MIPMAP; } auto textureCreateInfo = getGfxTextureCreateInfo( @@ -150,8 +149,8 @@ void SimpleTexture::createTexture(gfx::Device *device) { // return; // } - auto *texture = device->createTexture(textureCreateInfo); - _textureWidth = textureCreateInfo.width; + auto *texture = device->createTexture(textureCreateInfo); + _textureWidth = textureCreateInfo.width; _textureHeight = textureCreateInfo.height; _gfxTexture = texture; @@ -165,17 +164,16 @@ gfx::Texture *SimpleTexture::createTextureView(gfx::Device *device) { } const uint32_t maxLevel = _maxLevel < _mipmapLevel ? _maxLevel : _mipmapLevel - 1; auto textureViewCreateInfo = getGfxTextureViewCreateInfo( - _gfxTexture, - getGFXFormat(), - _baseLevel, - maxLevel - _baseLevel + 1 - ); + _gfxTexture, + getGFXFormat(), + _baseLevel, + maxLevel - _baseLevel + 1); //TODO(minggo) -// if (!textureViewCreateInfo) { -// return; -// } - + // if (!textureViewCreateInfo) { + // return; + // } + return device->createTexture(textureViewCreateInfo); } @@ -192,16 +190,16 @@ void SimpleTexture::tryDestroyTextureView() { if (_gfxTextureView != nullptr) { _gfxTextureView->destroy(); _gfxTextureView = nullptr; - + //TODO(minggo): should notify JS if the performance is low. } } void SimpleTexture::setMipRange(uint32_t baseLevel, uint32_t maxLevel) { debug::assertID(baseLevel <= maxLevel, 3124); - + setMipRangeInternal(baseLevel, maxLevel); - + auto *device = getGFXDevice(); if (!device) { return; @@ -213,10 +211,9 @@ void SimpleTexture::setMipRange(uint32_t baseLevel, uint32_t maxLevel) { _gfxTextureView = textureView; } - -void SimpleTexture::setMipRangeInternal(uint32_t baseLevel, uint32_t maxLevel){ +void SimpleTexture::setMipRangeInternal(uint32_t baseLevel, uint32_t maxLevel) { _baseLevel = baseLevel < 1 ? 0 : baseLevel; - _maxLevel = _maxLevel < 1 ? 0 : maxLevel; + _maxLevel = _maxLevel < 1 ? 0 : maxLevel; } void SimpleTexture::notifyTextureUpdated() { diff --git a/native/cocos/core/assets/SimpleTexture.h b/native/cocos/core/assets/SimpleTexture.h index 52c4678af2..c5e5b99604 100644 --- a/native/cocos/core/assets/SimpleTexture.h +++ b/native/cocos/core/assets/SimpleTexture.h @@ -136,7 +136,7 @@ protected: void tryReset(); - void createTexture(gfx::Device *device); + void createTexture(gfx::Device *device); gfx::Texture *createTextureView(gfx::Device *device); void tryDestroyTexture(); diff --git a/native/cocos/core/assets/TextAsset.h b/native/cocos/core/assets/TextAsset.h index 685c7ce704..46b828f213 100644 --- a/native/cocos/core/assets/TextAsset.h +++ b/native/cocos/core/assets/TextAsset.h @@ -35,7 +35,7 @@ namespace cc { */ class TextAsset final : public Asset { public: - explicit TextAsset() = default; + explicit TextAsset() = default; ~TextAsset() override = default; /** * @en The text content. diff --git a/native/cocos/core/assets/Texture2D.cpp b/native/cocos/core/assets/Texture2D.cpp index 44dcbb22db..d907f597ad 100644 --- a/native/cocos/core/assets/Texture2D.cpp +++ b/native/cocos/core/assets/Texture2D.cpp @@ -32,7 +32,7 @@ namespace cc { -Texture2D::Texture2D() = default; +Texture2D::Texture2D() = default; Texture2D::~Texture2D() = default; void Texture2D::syncMipmapsForJS(const ccstd::vector> &value) { @@ -43,14 +43,14 @@ void Texture2D::setMipmaps(const ccstd::vector> &value) _mipmaps = value; setMipmapLevel(static_cast(_mipmaps.size())); if (!_mipmaps.empty()) { - ImageAsset * imageAsset = _mipmaps[0]; + ImageAsset *imageAsset = _mipmaps[0]; ITexture2DCreateInfo info; - info.width = imageAsset->getWidth(); - info.height = imageAsset->getHeight(); - info.format = imageAsset->getFormat(); + info.width = imageAsset->getWidth(); + info.height = imageAsset->getHeight(); + info.format = imageAsset->getFormat(); info.mipmapLevel = static_cast(_mipmaps.size()); - info.baseLevel = _baseLevel; - info.maxLevel = _maxLevel; + info.baseLevel = _baseLevel; + info.maxLevel = _maxLevel; reset(info); for (size_t i = 0, len = _mipmaps.size(); i < len; ++i) { @@ -59,11 +59,11 @@ void Texture2D::setMipmaps(const ccstd::vector> &value) } else { ITexture2DCreateInfo info; - info.width = 0; - info.height = 0; + info.width = 0; + info.height = 0; info.mipmapLevel = static_cast(_mipmaps.size()); - info.baseLevel = _baseLevel; - info.maxLevel = _maxLevel; + info.baseLevel = _baseLevel; + info.maxLevel = _maxLevel; reset(info); } } @@ -77,10 +77,10 @@ void Texture2D::onLoaded() { } void Texture2D::reset(const ITexture2DCreateInfo &info) { - _width = info.width; + _width = info.width; _height = info.height; setGFXFormat(info.format); - + uint32_t mipLevels = info.mipmapLevel.has_value() ? info.mipmapLevel.value() : 1; setMipmapLevel(mipLevels); @@ -92,14 +92,12 @@ void Texture2D::reset(const ITexture2DCreateInfo &info) { } void Texture2D::create(uint32_t width, uint32_t height, PixelFormat format /* = PixelFormat::RGBA8888*/, uint32_t mipmapLevel /* = 1*/, uint32_t baseLevel, uint32_t maxLevel) { - reset({ - width, - height, - format, - mipmapLevel, - baseLevel, - maxLevel - }); + reset({width, + height, + format, + mipmapLevel, + baseLevel, + maxLevel}); } ccstd::string Texture2D::toString() const { @@ -136,7 +134,7 @@ bool Texture2D::destroy() { ccstd::string Texture2D::description() const { std::stringstream ret; - ccstd::string url; + ccstd::string url; if (!_mipmaps.empty()) { url = _mipmaps[0]->getUrl(); } @@ -189,13 +187,13 @@ void Texture2D::deserialize(const cc::any &serializedData, const cc::any &handle gfx::TextureInfo Texture2D::getGfxTextureCreateInfo(gfx::TextureUsageBit usage, gfx::Format format, uint32_t levelCount, gfx::TextureFlagBit flags) { gfx::TextureInfo texInfo; - texInfo.type = gfx::TextureType::TEX2D; - texInfo.width = _width; - texInfo.height = _height; - texInfo.usage = usage; - texInfo.format = format; + texInfo.type = gfx::TextureType::TEX2D; + texInfo.width = _width; + texInfo.height = _height; + texInfo.usage = usage; + texInfo.format = format; texInfo.levelCount = levelCount; - texInfo.flags = flags; + texInfo.flags = flags; return texInfo; } diff --git a/native/cocos/core/assets/Texture2D.h b/native/cocos/core/assets/Texture2D.h index ee7a3e10f7..0690f88a11 100644 --- a/native/cocos/core/assets/Texture2D.h +++ b/native/cocos/core/assets/Texture2D.h @@ -34,7 +34,7 @@ namespace cc { struct ITexture2DSerializeData { - ccstd::string base; + ccstd::string base; ccstd::vector mipmaps; }; @@ -68,21 +68,20 @@ struct ITexture2DCreateInfo { * @default 1 */ cc::optional mipmapLevel; - + /** * @en The selected base mipmap level * @zh 选择使用的最小 mipmap 层级。 * @default 1 */ cc::optional baseLevel; - + /** * @en The selected maximum mipmap level * @zh 选择使用的最大 mipmap 层级。 * @default 1 */ cc::optional maxLevel; - }; /** diff --git a/native/cocos/core/assets/TextureBase.cpp b/native/cocos/core/assets/TextureBase.cpp index 63e0349a26..9effbffb4b 100644 --- a/native/cocos/core/assets/TextureBase.cpp +++ b/native/cocos/core/assets/TextureBase.cpp @@ -42,8 +42,8 @@ IDGenerator idGenerator("Tex"); TextureBase::TextureBase() { // Id for generate hash in material - _id = idGenerator.getNewId(); - _gfxDevice = getGFXDevice(); + _id = idGenerator.getNewId(); + _gfxDevice = getGFXDevice(); std::size_t seed = 666; boost::hash_range(seed, _id.begin(), _id.end()); _textureHash = static_cast(seed); @@ -52,13 +52,13 @@ TextureBase::TextureBase() { TextureBase::~TextureBase() = default; void TextureBase::setWrapMode(WrapMode wrapS, WrapMode wrapT, WrapMode wrapR) { - _wrapS = wrapS; + _wrapS = wrapS; _samplerInfo.addressU = static_cast(wrapS), - _wrapT = wrapT; + _wrapT = wrapT; _samplerInfo.addressV = static_cast(wrapT), - _wrapR = wrapR; + _wrapR = wrapR; _samplerInfo.addressW = static_cast(wrapR); if (_gfxDevice != nullptr) { @@ -73,9 +73,9 @@ void TextureBase::setWrapMode(WrapMode wrapS, WrapMode wrapT) { } void TextureBase::setFilters(Filter minFilter, Filter magFilter) { - _minFilter = minFilter; + _minFilter = minFilter; _samplerInfo.minFilter = static_cast(minFilter); - _magFilter = magFilter; + _magFilter = magFilter; _samplerInfo.magFilter = static_cast(magFilter); if (_gfxDevice != nullptr) { @@ -86,7 +86,7 @@ void TextureBase::setFilters(Filter minFilter, Filter magFilter) { } void TextureBase::setMipFilter(Filter mipFilter) { - _mipFilter = mipFilter; + _mipFilter = mipFilter; _samplerInfo.mipFilter = static_cast(mipFilter); if (_gfxDevice != nullptr) { @@ -97,7 +97,7 @@ void TextureBase::setMipFilter(Filter mipFilter) { } void TextureBase::setAnisotropy(uint32_t anisotropy) { - _anisotropy = anisotropy; + _anisotropy = anisotropy; _samplerInfo.maxAnisotropy = anisotropy; if (_gfxDevice != nullptr) { @@ -140,8 +140,8 @@ void TextureBase::deserialize(const cc::any &serializedData, const cc::any & /*h if (pData == nullptr) { return; } - const ccstd::string &data = *pData; - auto fields = StringUtil::split(data, ","); + const ccstd::string &data = *pData; + auto fields = StringUtil::split(data, ","); fields.insert(fields.begin(), ""); if (fields.size() >= 5) { diff --git a/native/cocos/core/assets/TextureBase.h b/native/cocos/core/assets/TextureBase.h index da6d1f1fdc..84423db194 100644 --- a/native/cocos/core/assets/TextureBase.h +++ b/native/cocos/core/assets/TextureBase.h @@ -210,7 +210,7 @@ public: protected: static gfx::Device *getGFXDevice(); - static gfx::Format getGFXPixelFormat(PixelFormat format); + static gfx::Format getGFXPixelFormat(PixelFormat format); gfx::Format getGFXFormat() const; @@ -248,10 +248,10 @@ public: uint32_t _height{1}; protected: - ccstd::string _id; + ccstd::string _id; gfx::SamplerInfo _samplerInfo; - gfx::Sampler * _gfxSampler{nullptr}; - gfx::Device * _gfxDevice{nullptr}; + gfx::Sampler *_gfxSampler{nullptr}; + gfx::Device *_gfxDevice{nullptr}; uint32_t _textureHash{0}; diff --git a/native/cocos/core/assets/TextureCube.cpp b/native/cocos/core/assets/TextureCube.cpp index 4f57fcbb40..e577bc4fd6 100644 --- a/native/cocos/core/assets/TextureCube.cpp +++ b/native/cocos/core/assets/TextureCube.cpp @@ -50,18 +50,18 @@ void forEachFace(const ITextureCubeMipmap &mipmap, const ForEachFaceCallback &ca /* static */ TextureCube *TextureCube::fromTexture2DArray(const ccstd::vector &textures) { - size_t nMipmaps = textures.size() / 6; + size_t nMipmaps = textures.size() / 6; ccstd::vector mipmaps; mipmaps.reserve(nMipmaps); for (size_t i = 0; i < nMipmaps; i++) { size_t x = i * 6; ITextureCubeMipmap mipmap; - mipmap.front = textures[x + static_cast(FaceIndex::FRONT)]->getImage(), - mipmap.back = textures[x + static_cast(FaceIndex::BACK)]->getImage(), - mipmap.left = textures[x + static_cast(FaceIndex::LEFT)]->getImage(), - mipmap.right = textures[x + static_cast(FaceIndex::RIGHT)]->getImage(), - mipmap.top = textures[x + static_cast(FaceIndex::TOP)]->getImage(), + mipmap.front = textures[x + static_cast(FaceIndex::FRONT)]->getImage(), + mipmap.back = textures[x + static_cast(FaceIndex::BACK)]->getImage(), + mipmap.left = textures[x + static_cast(FaceIndex::LEFT)]->getImage(), + mipmap.right = textures[x + static_cast(FaceIndex::RIGHT)]->getImage(), + mipmap.top = textures[x + static_cast(FaceIndex::TOP)]->getImage(), mipmap.bottom = textures[x + static_cast(FaceIndex::BOTTOM)]->getImage(), mipmaps.emplace_back(mipmap); @@ -80,14 +80,12 @@ void TextureCube::setMipmaps(const ccstd::vector &value) { setMipmapLevel(static_cast(_mipmaps.size())); if (!_mipmaps.empty()) { ImageAsset *imageAsset = _mipmaps[0].front; - reset({ - imageAsset->getWidth(), - imageAsset->getHeight(), - imageAsset->getFormat(), - static_cast(_mipmaps.size()), - _baseLevel, - _maxLevel - }); + reset({imageAsset->getWidth(), + imageAsset->getHeight(), + imageAsset->getFormat(), + static_cast(_mipmaps.size()), + _baseLevel, + _maxLevel}); for (size_t level = 0, len = _mipmaps.size(); level < len; ++level) { forEachFace(_mipmaps[level], [this, level](ImageAsset *face, TextureCube::FaceIndex faceIndex) { @@ -96,14 +94,12 @@ void TextureCube::setMipmaps(const ccstd::vector &value) { } } else { - reset({ - 0, - 0, - cc::nullopt, - static_cast(_mipmaps.size()), - _baseLevel, - _maxLevel - }); + reset({0, + 0, + cc::nullopt, + static_cast(_mipmaps.size()), + _baseLevel, + _maxLevel}); } } @@ -116,13 +112,13 @@ void TextureCube::setImage(const ITextureCubeMipmap &value) { _mipmaps.emplace_back(value); } void TextureCube::reset(const ITextureCubeCreateInfo &info) { - _width = info.width; + _width = info.width; _height = info.height; setGFXFormat(info.format); - + uint32_t mipLevels = info.mipmapLevel.has_value() ? info.mipmapLevel.value() : 1; setMipmapLevel(mipLevels); - + uint32_t minLod = info.baseLevel.has_value() ? info.baseLevel.value() : 0; uint32_t maxLod = info.maxLevel.has_value() ? info.maxLevel.value() : 1000; setMipRange(minLod, maxLod); @@ -201,13 +197,13 @@ void TextureCube::deserialize(const cc::any &serializedData, const cc::any &hand for (size_t i = 0; i < data->mipmaps.size(); ++i) { // Prevent resource load failed ITextureCubeMipmap mipmap; - mipmap.front = ccnew ImageAsset(), - mipmap.back = ccnew ImageAsset(), - mipmap.left = ccnew ImageAsset(), - mipmap.right = ccnew ImageAsset(), - mipmap.top = ccnew ImageAsset(), + mipmap.front = ccnew ImageAsset(), + mipmap.back = ccnew ImageAsset(), + mipmap.left = ccnew ImageAsset(), + mipmap.right = ccnew ImageAsset(), + mipmap.top = ccnew ImageAsset(), mipmap.bottom = ccnew ImageAsset(); - _mipmaps[i] = mipmap; + _mipmaps[i] = mipmap; // auto* mipmap = data->mipmaps[i]; //cjh TODO: what's handle.result?? const imageAssetClassId = js._getClassId(ImageAsset); @@ -223,14 +219,14 @@ void TextureCube::deserialize(const cc::any &serializedData, const cc::any &hand gfx::TextureInfo TextureCube::getGfxTextureCreateInfo(gfx::TextureUsageBit usage, gfx::Format format, uint32_t levelCount, gfx::TextureFlagBit flags) { gfx::TextureInfo texInfo; - texInfo.type = gfx::TextureType::CUBE; - texInfo.width = _width; - texInfo.height = _height; + texInfo.type = gfx::TextureType::CUBE; + texInfo.width = _width; + texInfo.height = _height; texInfo.layerCount = 6; - texInfo.usage = usage; - texInfo.format = format; + texInfo.usage = usage; + texInfo.format = format; texInfo.levelCount = levelCount; - texInfo.flags = flags; + texInfo.flags = flags; return texInfo; } @@ -254,12 +250,12 @@ void TextureCube::initDefault(const cc::optional &uuid) { ITextureCubeMipmap mipmap; - mipmap.front = imageAsset; - mipmap.back = imageAsset; - mipmap.top = imageAsset; + mipmap.front = imageAsset; + mipmap.back = imageAsset; + mipmap.top = imageAsset; mipmap.bottom = imageAsset; - mipmap.left = imageAsset; - mipmap.right = imageAsset; + mipmap.left = imageAsset; + mipmap.right = imageAsset; setMipmaps({mipmap}); } diff --git a/native/cocos/core/assets/TextureCube.h b/native/cocos/core/assets/TextureCube.h index d47b3028cb..f4fa376085 100644 --- a/native/cocos/core/assets/TextureCube.h +++ b/native/cocos/core/assets/TextureCube.h @@ -59,8 +59,8 @@ struct ITextureCubeSerializeMipmapData { }; struct ITextureCubeSerializeData { - ccstd::string base; - bool rgbe{false}; + ccstd::string base; + bool rgbe{false}; ccstd::vector mipmaps; }; @@ -82,12 +82,12 @@ public: * @zh 立方体每个面的约定索引。 */ enum class FaceIndex { - RIGHT = 0, - LEFT = 1, - TOP = 2, + RIGHT = 0, + LEFT = 1, + TOP = 2, BOTTOM = 3, - FRONT = 4, - BACK = 5, + FRONT = 4, + BACK = 5, }; /** @@ -166,7 +166,7 @@ public: bool destroy() override; cc::any serialize(const cc::any &ctxForExporting) override; - void deserialize(const cc::any &serializedData, const cc::any &handle) override; + void deserialize(const cc::any &serializedData, const cc::any &handle) override; gfx::TextureInfo getGfxTextureCreateInfo(gfx::TextureUsageBit usage, gfx::Format format, uint32_t levelCount, gfx::TextureFlagBit flags) override; gfx::TextureViewInfo getGfxTextureViewCreateInfo(gfx::Texture *texture, gfx::Format format, uint32_t baseLevel, uint32_t levelCount) override; diff --git a/native/cocos/core/builtin/BuiltinResMgr.cpp b/native/cocos/core/builtin/BuiltinResMgr.cpp index 5060e026fa..d207319cbb 100644 --- a/native/cocos/core/builtin/BuiltinResMgr.cpp +++ b/native/cocos/core/builtin/BuiltinResMgr.cpp @@ -193,7 +193,7 @@ bool BuiltinResMgr::initBuiltinRes(gfx::Device *device) { } // const ShaderSource *shaderSources = nullptr; - const auto iter = ShaderSourceAssembly::get().find(shaderVersionKey); + const auto iter = ShaderSourceAssembly::get().find(shaderVersionKey); if (iter != ShaderSourceAssembly::get().cend()) { shaderSources = iter->second; } @@ -208,9 +208,9 @@ bool BuiltinResMgr::initBuiltinRes(gfx::Device *device) { rapidjson::Document doc; doc.Parse(BUILTIN_EFFECTS.value().c_str()); - index_t effectIndex = 0; - rapidjson::Type type = doc.GetType(); - auto assetDeserializer = AssetDeserializerFactory::createAssetDeserializer(DeserializeAssetType::EFFECT); + index_t effectIndex = 0; + rapidjson::Type type = doc.GetType(); + auto assetDeserializer = AssetDeserializerFactory::createAssetDeserializer(DeserializeAssetType::EFFECT); for (const auto &e : doc.GetArray()) { IntrusivePtr effect = ccnew EffectAsset(); assetDeserializer->deserialize(e, effect); @@ -257,10 +257,10 @@ void BuiltinResMgr::initMaterials() { _materialsToBeCompiled.emplace_back(standardMtl); // material indicating missing effect (yellow) - auto * missingEfxMtl = ccnew Material(); + auto *missingEfxMtl = ccnew Material(); IMaterialInfo missingEfxInfo; missingEfxInfo.effectName = ccstd::string{"unlit"}; - missingEfxInfo.defines = IMaterialInfo::DefinesType{ + missingEfxInfo.defines = IMaterialInfo::DefinesType{ MacroRecord{ {"USE_COLOR", true}}}; missingEfxMtl->setUuid("missing-effect-material"); @@ -270,10 +270,10 @@ void BuiltinResMgr::initMaterials() { _materialsToBeCompiled.emplace_back(missingEfxMtl); // material indicating missing material (purple) - auto * missingMtl = ccnew Material(); + auto *missingMtl = ccnew Material(); IMaterialInfo missingInfo; missingInfo.effectName = ccstd::string{"unlit"}, - missingInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ + missingInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ {"USE_COLOR", true}}}; missingMtl->setUuid("missing-material"); missingMtl->initialize(missingInfo); @@ -281,10 +281,10 @@ void BuiltinResMgr::initMaterials() { resources[missingMtl->getUuid()] = missingMtl; _materialsToBeCompiled.emplace_back(missingMtl); - auto * clearStencilMtl = ccnew Material(); + auto *clearStencilMtl = ccnew Material(); IMaterialInfo clearStencilInfo; clearStencilInfo.effectName = ccstd::string{"clear-stencil"}, - clearStencilInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ + clearStencilInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ {"USE_TEXTURE", false}}}; clearStencilMtl->setUuid("default-clear-stencil"); clearStencilMtl->initialize(clearStencilInfo); @@ -296,7 +296,7 @@ void BuiltinResMgr::initMaterials() { spriteMtl->setUuid("ui-base-material"); IMaterialInfo spriteInfo; spriteInfo.effectName = ccstd::string{"sprite"}, - spriteInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", false}}}; + spriteInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", false}}}; spriteMtl->initialize(spriteInfo); resources[spriteMtl->getUuid()] = spriteMtl; _materialsToBeCompiled.emplace_back(spriteMtl); @@ -306,16 +306,16 @@ void BuiltinResMgr::initMaterials() { spriteColorMtl->setUuid("ui-sprite-material"); IMaterialInfo spriteColorInfo; spriteColorInfo.effectName = ccstd::string{"sprite"}, - spriteColorInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", false}}}; + spriteColorInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", false}}}; spriteColorMtl->initialize(spriteColorInfo); resources[spriteColorMtl->getUuid()] = spriteColorMtl; _materialsToBeCompiled.emplace_back(spriteColorMtl); // sprite alpha test material - auto * alphaTestMaskMtl = ccnew Material(); + auto *alphaTestMaskMtl = ccnew Material(); IMaterialInfo alphaTestMaskInfo; alphaTestMaskInfo.effectName = ccstd::string{"sprite"}, - alphaTestMaskInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ + alphaTestMaskInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ {"USE_TEXTURE", true}, {"USE_ALPHA_TEST", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", false}}}; alphaTestMaskMtl->setUuid("ui-alpha-test-material"); alphaTestMaskMtl->initialize(alphaTestMaskInfo); @@ -327,7 +327,7 @@ void BuiltinResMgr::initMaterials() { spriteGrayMtl->setUuid("ui-sprite-gray-material"); IMaterialInfo spriteGrayInfo; spriteGrayInfo.effectName = ccstd::string{"sprite"}, - spriteGrayInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", true}}}; + spriteGrayInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", true}}}; spriteGrayMtl->initialize(spriteGrayInfo); resources[spriteGrayMtl->getUuid()] = spriteGrayMtl; _materialsToBeCompiled.emplace_back(spriteGrayMtl); @@ -337,16 +337,16 @@ void BuiltinResMgr::initMaterials() { spriteAlphaMtl->setUuid("ui-sprite-alpha-sep-material"); IMaterialInfo spriteAlphaInfo; spriteAlphaInfo.effectName = ccstd::string{"sprite"}, - spriteAlphaInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", true}, {"IS_GRAY", false}}}; + spriteAlphaInfo.defines = IMaterialInfo::DefinesType{MacroRecord{{"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", true}, {"IS_GRAY", false}}}; spriteAlphaMtl->initialize(spriteAlphaInfo); resources[spriteAlphaMtl->getUuid()] = spriteAlphaMtl; _materialsToBeCompiled.emplace_back(spriteAlphaMtl); // sprite alpha & gray material - auto * spriteAlphaGrayMtl = ccnew Material(); + auto *spriteAlphaGrayMtl = ccnew Material(); IMaterialInfo spriteAlphaGrayInfo; spriteAlphaGrayInfo.effectName = ccstd::string{"sprite"}, - spriteAlphaGrayInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ + spriteAlphaGrayInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ {"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", true}, {"IS_GRAY", true}}}; spriteAlphaGrayMtl->setUuid("ui-sprite-gray-alpha-sep-material"); spriteAlphaGrayMtl->initialize(spriteAlphaGrayInfo); @@ -403,7 +403,7 @@ void BuiltinResMgr::initMaterials() { spineTwoColorMtl->setUuid("default-spine-material"); IMaterialInfo spineTwoColorInfo; spineTwoColorInfo.effectName = ccstd::string{"spine"}, - spineTwoColorInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ + spineTwoColorInfo.defines = IMaterialInfo::DefinesType{MacroRecord{ {"USE_TEXTURE", true}, {"CC_USE_EMBEDDED_ALPHA", false}, {"IS_GRAY", false}, @@ -428,11 +428,11 @@ void BuiltinResMgr::tryCompileAllPasses() { void BuiltinResMgr::initTexture2DWithUuid(const ccstd::string &uuid, const uint8_t *data, size_t dataBytes, uint32_t width, uint32_t height) { IMemoryImageSource imageSource; - imageSource.width = width; - imageSource.height = height; - imageSource.data = ccnew ArrayBuffer(data, static_cast(dataBytes)); + imageSource.width = width; + imageSource.height = height; + imageSource.data = ccnew ArrayBuffer(data, static_cast(dataBytes)); imageSource.compressed = false; - imageSource.format = PixelFormat::RGBA8888; + imageSource.format = PixelFormat::RGBA8888; auto *texture = ccnew Texture2D(); if (texture) { @@ -449,11 +449,11 @@ void BuiltinResMgr::initTexture2DWithUuid(const ccstd::string &uuid, const uint8 void BuiltinResMgr::initTextureCubeWithUuid(const ccstd::string &uuid, const uint8_t *data, size_t dataBytes, uint32_t width, uint32_t height) { IMemoryImageSource imageSource; - imageSource.width = width; - imageSource.height = height; - imageSource.data = ccnew ArrayBuffer(data, static_cast(dataBytes)); + imageSource.width = width; + imageSource.height = height; + imageSource.data = ccnew ArrayBuffer(data, static_cast(dataBytes)); imageSource.compressed = false; - imageSource.format = PixelFormat::RGBA8888; + imageSource.format = PixelFormat::RGBA8888; auto *texture = ccnew TextureCube(); if (texture) { diff --git a/native/cocos/core/builtin/BuiltinResMgr.h b/native/cocos/core/builtin/BuiltinResMgr.h index 1be7c7c0c9..f282885554 100644 --- a/native/cocos/core/builtin/BuiltinResMgr.h +++ b/native/cocos/core/builtin/BuiltinResMgr.h @@ -42,12 +42,12 @@ class Asset; class BuiltinResMgr final : public RefCounted { public: static BuiltinResMgr *getInstance(); - static void destroyInstance(); + static void destroyInstance(); - bool initBuiltinRes(gfx::Device *device); + bool initBuiltinRes(gfx::Device *device); inline bool isInitialized() const { return _isInitialized; } - void addAsset(const ccstd::string &uuid, Asset *asset); + void addAsset(const ccstd::string &uuid, Asset *asset); Asset *getAsset(const ccstd::string &uuid); template ::value>> @@ -56,7 +56,7 @@ public: } private: - explicit BuiltinResMgr() = default; + explicit BuiltinResMgr() = default; ~BuiltinResMgr() override = default; void initMaterials(); @@ -66,10 +66,10 @@ private: static BuiltinResMgr *instance; - gfx::Device * _device{nullptr}; + gfx::Device *_device{nullptr}; Record> _resources; - ccstd::vector> _materialsToBeCompiled; - bool _isInitialized{false}; + ccstd::vector> _materialsToBeCompiled; + bool _isInitialized{false}; CC_DISALLOW_COPY_MOVE_ASSIGN(BuiltinResMgr); }; diff --git a/native/cocos/core/builtin/ShaderSourceAssembly.h b/native/cocos/core/builtin/ShaderSourceAssembly.h index 39fd55e0c2..569246d02d 100644 --- a/native/cocos/core/builtin/ShaderSourceAssembly.h +++ b/native/cocos/core/builtin/ShaderSourceAssembly.h @@ -31,8 +31,8 @@ #include "base/std/container/vector.h" namespace cc { -using ShaderInfo = ccstd::unordered_map; -using ShaderSource = ccstd::vector>; +using ShaderInfo = ccstd::unordered_map; +using ShaderSource = ccstd::vector>; using ShaderSourceMap = ccstd::unordered_map; class ShaderSourceAssembly final { diff --git a/native/cocos/core/data/Object.h b/native/cocos/core/data/Object.h index 203c598b2e..deae24f47f 100644 --- a/native/cocos/core/data/Object.h +++ b/native/cocos/core/data/Object.h @@ -44,10 +44,10 @@ class CCObject : public RefCounted /*cjh implements EditorExtendableObject*/ { public: // definitions for CCObject.Flags enum class Flags : FlagBits { - ZERO = 0, - DESTROYED = 1 << 0, + ZERO = 0, + DESTROYED = 1 << 0, REAL_DESTROYED = 1 << 1, - TO_DESTROY = 1 << 2, + TO_DESTROY = 1 << 2, /** * @en The object will not be saved. * @zh 该对象将不会被保存。 @@ -58,14 +58,14 @@ public: * @zh 构建项目时,该对象将不会被保存。 */ EDITOR_ONLY = 1 << 4, - DIRTY = 1 << 5, + DIRTY = 1 << 5, /** * @en Dont destroy automatically when loading a new scene. * @zh 加载一个新场景时,不自动删除该对象。 * @private */ DONT_DESTROY = 1 << 6, - DESTROYING = 1 << 7, + DESTROYING = 1 << 7, /** * @en The node is deactivating. * @zh 节点正在反激活的过程中。 @@ -84,21 +84,21 @@ public: */ HIDE_IN_HIERARCHY = 1 << 10, - IS_ON_ENABLE_CALLED = 1 << 11, + IS_ON_ENABLE_CALLED = 1 << 11, IS_EDITOR_ON_ENABLE_CALLED = 1 << 12, - IS_PRELOAD_STARTED = 1 << 13, - IS_ON_LOAD_CALLED = 1 << 14, - IS_ON_LOAD_STARTED = 1 << 15, - IS_START_CALLED = 1 << 16, + IS_PRELOAD_STARTED = 1 << 13, + IS_ON_LOAD_CALLED = 1 << 14, + IS_ON_LOAD_STARTED = 1 << 15, + IS_START_CALLED = 1 << 16, IS_ROTATION_LOCKED = 1 << 17, - IS_SCALE_LOCKED = 1 << 18, - IS_ANCHOR_LOCKED = 1 << 19, - IS_SIZE_LOCKED = 1 << 20, + IS_SCALE_LOCKED = 1 << 18, + IS_ANCHOR_LOCKED = 1 << 19, + IS_SIZE_LOCKED = 1 << 20, IS_POSITION_LOCKED = 1 << 21, // Distributed - IS_REPLICATED = 1 << 22, + IS_REPLICATED = 1 << 22, IS_CLIENT_LOAD = 1 << 23, // var Hide = HideInGame | HideInEditor; @@ -119,7 +119,7 @@ public: //cjh public declare [editorExtrasTag]: unknown; - Flags _objFlags{Flags::ZERO}; + Flags _objFlags{Flags::ZERO}; ccstd::string _name; protected: @@ -139,13 +139,13 @@ public: * ``` */ inline const ccstd::string &getName() const { return _name; } - inline void setName(const ccstd::string &value) { _name = value; } + inline void setName(const ccstd::string &value) { _name = value; } /** * @en After inheriting CCObject objects, control whether you need to hide, lock, serialize, and other functions. * @zh 在继承 CCObject 对象后,控制是否需要隐藏,锁定,序列化等功能。 */ - inline void setHideFlags(Flags hideFlags); + inline void setHideFlags(Flags hideFlags); inline Flags getHideFlags() const; inline void setReplicated(bool value); @@ -238,7 +238,7 @@ inline bool CCObject::isValid() const { inline void CCObject::setHideFlags(Flags hideFlags) { Flags flags = hideFlags & Flags::ALL_HIDE_MASKS; - _objFlags = (_objFlags & ~Flags::ALL_HIDE_MASKS) | flags; + _objFlags = (_objFlags & ~Flags::ALL_HIDE_MASKS) | flags; } inline CCObject::Flags CCObject::getHideFlags() const { diff --git a/native/cocos/core/data/deserializer/EffectAssetDeserializer.cpp b/native/cocos/core/data/deserializer/EffectAssetDeserializer.cpp index 0fe2b89c39..f5c3bf609b 100644 --- a/native/cocos/core/data/deserializer/EffectAssetDeserializer.cpp +++ b/native/cocos/core/data/deserializer/EffectAssetDeserializer.cpp @@ -71,7 +71,7 @@ static void deserializeArray(const rapidjson::Value &valArray, ccstd::vector static MacroRecord jsonToMacroRecord(const rapidjson::Value &embeddedMacrosVal) { MacroRecord cEmbeddedMacros; for (const auto ¯o : embeddedMacrosVal.GetObject()) { - const auto *name = macro.name.GetString(); + const auto *name = macro.name.GetString(); const auto &value = macro.value; // using MacroValue = cc::variant; @@ -100,9 +100,9 @@ static IPropertyHandleInfo jsonToPropertyHandleInfo(const rapidjson::Value &hand if (handleInfoVal.IsArray()) { // using IPropertyHandleInfo = std::tuple; ccstd::string t0; - uint32_t t1 = 0; - gfx::Type t2 = gfx::Type::UNKNOWN; - int32_t i = 0; + uint32_t t1 = 0; + gfx::Type t2 = gfx::Type::UNKNOWN; + int32_t i = 0; for (const auto &e : handleInfoVal.GetArray()) { switch (i) { @@ -169,7 +169,7 @@ static PassPropertyInfoMap jsonToPassPropertyInfoMap(const rapidjson::Value &pro PassPropertyInfoMap propertyInfoMap; for (const auto &propertyVal : propertyInfoMapVal.GetObject()) { - const auto *name = propertyVal.name.GetString(); + const auto *name = propertyVal.name.GetString(); const auto &value = propertyVal.value; propertyInfoMap.emplace(name, jsonToPropertyInfo(value)); } @@ -397,7 +397,7 @@ static BlendStateInfo jsonToBlendState(const rapidjson::Value &val) { if (val.HasMember("targets")) { if (val["targets"].IsArray()) { - const auto & targetsVal = val["targets"].GetArray(); + const auto &targetsVal = val["targets"].GetArray(); BlendTargetInfoList targets; targets.resize(targetsVal.Size()); int32_t i = 0; @@ -549,7 +549,7 @@ static void deserializeShaderDefine(const rapidjson::Value &defineVal, IDefineIn } if (defineVal.HasMember("range")) { - auto & cRange = cDefine.range; + auto &cRange = cDefine.range; const auto &rangeVal = defineVal["range"]; cRange = ccstd::vector{}; @@ -557,7 +557,7 @@ static void deserializeShaderDefine(const rapidjson::Value &defineVal, IDefineIn } if (defineVal.HasMember("options")) { - auto & cOptions = cDefine.options; + auto &cOptions = cDefine.options; const auto &optionsVal = defineVal["options"]; cOptions = ccstd::vector{}; diff --git a/native/cocos/core/data/deserializer/EffectAssetDeserializer.h b/native/cocos/core/data/deserializer/EffectAssetDeserializer.h index f53545f81d..3f9bac8128 100644 --- a/native/cocos/core/data/deserializer/EffectAssetDeserializer.h +++ b/native/cocos/core/data/deserializer/EffectAssetDeserializer.h @@ -33,7 +33,7 @@ class Asset; class EffectAssetDeserializer final : public IAssetDeserializer { public: - EffectAssetDeserializer() = default; + EffectAssetDeserializer() = default; ~EffectAssetDeserializer() override = default; void deserialize(const rapidjson::Value &serializedData, Asset *effectAsset) override; diff --git a/native/cocos/core/data/deserializer/IAssetDeserializer.h b/native/cocos/core/data/deserializer/IAssetDeserializer.h index ab9c229ab6..ee32369b83 100644 --- a/native/cocos/core/data/deserializer/IAssetDeserializer.h +++ b/native/cocos/core/data/deserializer/IAssetDeserializer.h @@ -33,7 +33,7 @@ class Asset; class IAssetDeserializer { public: - virtual ~IAssetDeserializer() = default; + virtual ~IAssetDeserializer() = default; virtual void deserialize(const rapidjson::Value &serializedData, Asset *asset) = 0; }; diff --git a/native/cocos/core/event/CallbacksInvoker.cpp b/native/cocos/core/event/CallbacksInvoker.cpp index 66a71f2421..cbbaf4497e 100644 --- a/native/cocos/core/event/CallbacksInvoker.cpp +++ b/native/cocos/core/event/CallbacksInvoker.cpp @@ -85,7 +85,7 @@ void CallbackList::purgeCanceled() { void CallbackList::clear() { cancelAll(); _callbackInfos.clear(); - _isInvoking = false; + _isInvoking = false; _containCanceled = false; } @@ -183,7 +183,7 @@ void CallbacksInvoker::offAll(const KeyType &key) { void CallbacksInvoker::offAll(void *target) { for (auto &e : _callbackTable) { - auto & list = e.second; + auto &list = e.second; const auto &infos = list._callbackInfos; if (list._isInvoking) { index_t i = 0; @@ -215,9 +215,9 @@ void CallbacksInvoker::offAll() { void CallbacksInvoker::off(const KeyType &key, CallbackInfoBase::ID cbID) { auto iter = _callbackTable.find(key); if (iter != _callbackTable.end()) { - auto & list = iter->second; + auto &list = iter->second; const auto &infos = list._callbackInfos; - index_t i = 0; + index_t i = 0; for (const auto &info : infos) { if (info != nullptr && info->_id == cbID) { list.cancel(i); @@ -231,9 +231,9 @@ void CallbacksInvoker::off(const KeyType &key, CallbackInfoBase::ID cbID) { void CallbacksInvoker::offAll(const KeyType &key, void *target) { auto iter = _callbackTable.find(key); if (iter != _callbackTable.end()) { - auto & list = iter->second; + auto &list = iter->second; const auto &infos = list._callbackInfos; - index_t i = 0; + index_t i = 0; if (list._isInvoking) { for (const auto &info : infos) { if (info != nullptr && info->_target == target) { @@ -249,9 +249,9 @@ void CallbacksInvoker::offAll(const KeyType &key, void *target) { void CallbacksInvoker::off(CallbackInfoBase::ID cbID) { for (auto &cbInfo : _callbackTable) { - auto & list = cbInfo.second; + auto &list = cbInfo.second; const auto &infos = list._callbackInfos; - index_t i = 0; + index_t i = 0; for (const auto &info : infos) { if (info != nullptr && info->_id == cbID) { list.cancel(i); diff --git a/native/cocos/core/event/CallbacksInvoker.h b/native/cocos/core/event/CallbacksInvoker.h index f51ef610b3..09127ecdad 100644 --- a/native/cocos/core/event/CallbacksInvoker.h +++ b/native/cocos/core/event/CallbacksInvoker.h @@ -44,20 +44,20 @@ namespace cc { #define CC_CALLBACK_INVOKE_3(__selector__, __target__, Arg0, Arg1, Arg2, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)), __target__ struct CallbackInfoBase { - using ID = uint32_t; + using ID = uint32_t; using FakeCallbackMemberFn = void (CCObject::*)(); - CallbackInfoBase() = default; + CallbackInfoBase() = default; virtual ~CallbackInfoBase() = default; - virtual bool check() const = 0; - virtual void reset() = 0; + virtual bool check() const = 0; + virtual void reset() = 0; virtual FakeCallbackMemberFn getMemberFn() const = 0; void *_target{nullptr}; - ID _id{0}; - bool _once{false}; - bool _isCCObject{false}; + ID _id{0}; + bool _once{false}; + bool _isCCObject{false}; #if CC_DEBUG ccstd::vector _argTypes; #endif @@ -65,17 +65,17 @@ struct CallbackInfoBase { template struct CallbackInfo final : public CallbackInfoBase { - using CallbackFn = std::function; + using CallbackFn = std::function; using CallbackMemberFn = void (CCObject::*)(Args...); - CallbackFn _callback{nullptr}; + CallbackFn _callback{nullptr}; CallbackMemberFn _memberFn{nullptr}; template void set(CallbackFn &&callback, Target *target, bool once) { - _callback = std::forward(callback); - _target = target; - _once = once; + _callback = std::forward(callback); + _target = target; + _once = once; _isCCObject = std::is_base_of::value; #if CC_DEBUG _argTypes = {(typeid(Args).name())...}; @@ -84,9 +84,9 @@ struct CallbackInfo final : public CallbackInfoBase { template ::value>> void set(CallbackMemberFn memberFn, Target *target, bool once) { - _memberFn = memberFn; - _target = target; - _once = once; + _memberFn = memberFn; + _target = target; + _once = once; _isCCObject = true; #if CC_DEBUG _argTypes = {(typeid(Args).name())...}; @@ -94,10 +94,10 @@ struct CallbackInfo final : public CallbackInfoBase { } void reset() override { - _callback = nullptr; - _memberFn = nullptr; - _target = nullptr; - _once = false; + _callback = nullptr; + _memberFn = nullptr; + _target = nullptr; + _once = false; _isCCObject = false; #if CC_DEBUG _argTypes.clear(); @@ -126,8 +126,8 @@ struct CallbackInfo final : public CallbackInfoBase { class CallbackList final { public: ccstd::vector> _callbackInfos; - bool _isInvoking{false}; - bool _containCanceled{false}; + bool _isInvoking{false}; + bool _containCanceled{false}; /** * @zh 从列表中移除与指定目标相同回调函数的事件。 @@ -177,8 +177,8 @@ public: */ class CallbacksInvoker { public: - using KeyType = uint32_t; - CallbacksInvoker() = default; + using KeyType = uint32_t; + CallbacksInvoker() = default; virtual ~CallbacksInvoker() = default; /** * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 @@ -262,7 +262,7 @@ public: * @param args - The arguments to be passed to the callback */ template - void emit(const KeyType &key, Args &&...args); + void emit(const KeyType &key, Args &&... args); template struct FunctionTraits @@ -286,16 +286,16 @@ public: private: ccstd::unordered_map _callbackTable; - static CallbackInfoBase::ID cbIDCounter; + static CallbackInfoBase::ID cbIDCounter; }; template void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once) { static_assert(std::is_base_of::value, "Target must be the subclass of CCObject"); - using CallbackInfoType = CallbackInfo; - auto &list = _callbackTable[key]; - auto info = std::make_shared(); - info->_id = ++cbIDCounter; + using CallbackInfoType = CallbackInfo; + auto &list = _callbackTable[key]; + auto info = std::make_shared(); + info->_id = ++cbIDCounter; CallbackInfoBase::ID cbID = info->_id; info->set(static_cast(memberFn), target, once); list._callbackInfos.emplace_back(std::move(info)); @@ -303,9 +303,9 @@ void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), template void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) { - auto &list = _callbackTable[key]; - auto info = std::make_shared>(); - info->_id = ++cbIDCounter; + auto &list = _callbackTable[key]; + auto info = std::make_shared>(); + info->_id = ++cbIDCounter; CallbackInfoBase::ID cbID = info->_id; info->set(std::forward>(callback), target, once); list._callbackInfos.emplace_back(std::move(info)); @@ -359,11 +359,11 @@ template void CallbacksInvoker::off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) { static_assert(std::is_base_of::value, "Target must be the subclass of CCObject"); using CallbackFn = void (CCObject::*)(Args...); - auto iter = _callbackTable.find(key); + auto iter = _callbackTable.find(key); if (iter != _callbackTable.end()) { - auto & list = iter->second; + auto &list = iter->second; const auto &infos = list._callbackInfos; - size_t i = 0; + size_t i = 0; for (const auto &info : infos) { if (info != nullptr && reinterpret_cast(info->getMemberFn()) == memberFn && info->_target == target) { list.cancel(static_cast(i)); @@ -375,15 +375,15 @@ void CallbacksInvoker::off(const KeyType &key, void (Target::*memberFn)(Args...) } template -void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { +void CallbacksInvoker::emit(const KeyType &key, Args &&... args) { #if CC_DEBUG ccstd::vector argTypes{(typeid(Args).name())...}; #endif auto iter = _callbackTable.find(key); if (iter != _callbackTable.end()) { - auto &list = iter->second; - bool rootInvoker = !list._isInvoking; - list._isInvoking = true; + auto &list = iter->second; + bool rootInvoker = !list._isInvoking; + list._isInvoking = true; auto &infos = list._callbackInfos; for (auto &i : infos) { @@ -402,11 +402,11 @@ void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { } #endif using CallbackInfoType = CallbackInfo; - auto info = std::static_pointer_cast(i); + auto info = std::static_pointer_cast(i); if (info != nullptr) { if (info->_memberFn != nullptr && info->_target != nullptr) { - auto memberFn = info->_memberFn; - auto *target = reinterpret_cast(info->_target); + auto memberFn = info->_memberFn; + auto *target = reinterpret_cast(info->_target); // Pre off once callbacks to avoid influence on logic in callback if (info->_once) { @@ -420,8 +420,8 @@ void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { (target->*memberFn)(std::forward(args)...); } } else { - const auto & callback = info->_callback; - CallbackInfoBase::ID cbID = info->_id; + const auto &callback = info->_callback; + CallbackInfoBase::ID cbID = info->_id; // Pre off once callbacks to avoid influence on logic in callback if (info->_once) { off(key, cbID); @@ -451,7 +451,7 @@ void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { template bool CallbacksInvoker::hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const { using CallbackFn = void (CCObject::*)(Args...); - auto iter = _callbackTable.find(key); + auto iter = _callbackTable.find(key); if (iter == _callbackTable.end()) { return false; } diff --git a/native/cocos/core/geometry/AABB.cpp b/native/cocos/core/geometry/AABB.cpp index 0a72c860b1..8a02638b83 100644 --- a/native/cocos/core/geometry/AABB.cpp +++ b/native/cocos/core/geometry/AABB.cpp @@ -123,7 +123,7 @@ int AABB::aabbPlane(const Plane &plane) const { bool AABB::aabbFrustum(const Frustum &frustum) const { const auto &planes = frustum.planes; - const auto *self = this; + const auto *self = this; return std::all_of(planes.begin(), planes.end(), // frustum plane normal points to the inside diff --git a/native/cocos/core/geometry/AABB.h b/native/cocos/core/geometry/AABB.h index d99bccd271..c7500f2693 100644 --- a/native/cocos/core/geometry/AABB.h +++ b/native/cocos/core/geometry/AABB.h @@ -108,7 +108,7 @@ public: static Sphere *toBoundingSphere(Sphere *out, const AABB &a); static AABB *fromPoints(const Vec3 &minPos, const Vec3 &maxPos, AABB *dst); - static void transformExtentM4(Vec3 *out, const Vec3 &extent, const Mat4 &m4); + static void transformExtentM4(Vec3 *out, const Vec3 &extent, const Mat4 &m4); AABB(float px, float py, float pz, float hw, float hh, float hl); AABB(); @@ -136,22 +136,22 @@ public: */ bool aabbFrustum(const Frustum &) const; - int aabbPlane(const Plane &) const; - void getBoundary(cc::Vec3 *minPos, cc::Vec3 *maxPos) const; - void merge(const AABB &aabb); - void merge(const cc::Vec3 &point); - void merge(const ccstd::vector &points); - void merge(const Frustum &frustum); - void set(const cc::Vec3 ¢erVal, const cc::Vec3 &halfExtentVal); - void transform(const Mat4 &m, AABB *out) const; - bool contain(const cc::Vec3 &point) const; - inline void setCenter(float x, float y, float z) { center.set(x, y, z); } - inline void setCenter(const Vec3 ¢er) { this->center.set(center); } - inline void setValid(bool isValid) { _isValid = isValid; } + int aabbPlane(const Plane &) const; + void getBoundary(cc::Vec3 *minPos, cc::Vec3 *maxPos) const; + void merge(const AABB &aabb); + void merge(const cc::Vec3 &point); + void merge(const ccstd::vector &points); + void merge(const Frustum &frustum); + void set(const cc::Vec3 ¢erVal, const cc::Vec3 &halfExtentVal); + void transform(const Mat4 &m, AABB *out) const; + bool contain(const cc::Vec3 &point) const; + inline void setCenter(float x, float y, float z) { center.set(x, y, z); } + inline void setCenter(const Vec3 ¢er) { this->center.set(center); } + inline void setValid(bool isValid) { _isValid = isValid; } inline const Vec3 &getCenter() const { return center; } - inline bool isValid() const { return _isValid; } - inline void setHalfExtents(float x, float y, float z) { halfExtents.set(x, y, z); } - inline void setHalfExtents(const Vec3 &halfExtents) { this->halfExtents.set(halfExtents); } + inline bool isValid() const { return _isValid; } + inline void setHalfExtents(float x, float y, float z) { halfExtents.set(x, y, z); } + inline void setHalfExtents(const Vec3 &halfExtents) { this->halfExtents.set(halfExtents); } inline const Vec3 &getHalfExtents() const { return halfExtents; } cc::Vec3 center; diff --git a/native/cocos/core/geometry/Capsule.cpp b/native/cocos/core/geometry/Capsule.cpp index 3bb344206b..482b4ae6ce 100644 --- a/native/cocos/core/geometry/Capsule.cpp +++ b/native/cocos/core/geometry/Capsule.cpp @@ -5,10 +5,10 @@ namespace geometry { void Capsule::transform(const Mat4 &m, const Vec3 & /*pos*/, const Quaternion &rot, const Vec3 &scale, Capsule *out) const { const auto maxComponent = mathutils::absMaxComponent(scale); - out->radius = this->radius * std::abs(maxComponent); + out->radius = this->radius * std::abs(maxComponent); const auto halfTotalWorldHeight = (this->halfHeight + this->radius) * std::abs(scale.y); - auto halfWorldHeight = halfTotalWorldHeight - out->radius; + auto halfWorldHeight = halfTotalWorldHeight - out->radius; if (halfWorldHeight < 0) halfWorldHeight = 0; out->halfHeight = halfWorldHeight; diff --git a/native/cocos/core/geometry/Capsule.h b/native/cocos/core/geometry/Capsule.h index cb94c42679..c63afbd11a 100644 --- a/native/cocos/core/geometry/Capsule.h +++ b/native/cocos/core/geometry/Capsule.h @@ -75,21 +75,21 @@ public: explicit Capsule(float radius = 0.5, float halfHeight = 0.5, CenterEnum axis = CenterEnum::Y) { this->setType(ShapeEnum::SHAPE_CAPSULE); - this->radius = radius; + this->radius = radius; this->halfHeight = halfHeight; - this->axis = axis; - this->center = {}; - this->rotation = {}; - ellipseCenter0 = {0, halfHeight, 0}; - ellipseCenter1 = {0, -halfHeight, 0}; + this->axis = axis; + this->center = {}; + this->rotation = {}; + ellipseCenter0 = {0, halfHeight, 0}; + ellipseCenter1 = {0, -halfHeight, 0}; updateCache(); } Capsule(const Capsule &other) = default; - Capsule(Capsule &&other) = default; + Capsule(Capsule &&other) = default; Capsule &operator=(const Capsule &other) = default; Capsule &operator=(Capsule &&other) = default; - ~Capsule() override = default; + ~Capsule() override = default; /** * @en diff --git a/native/cocos/core/geometry/Curve.h b/native/cocos/core/geometry/Curve.h index 0a1492ee26..1790343ef7 100644 --- a/native/cocos/core/geometry/Curve.h +++ b/native/cocos/core/geometry/Curve.h @@ -40,13 +40,13 @@ struct Keyframe { float evalOptCurve(float t, const ccstd::vector &coefs); struct OptimizedKey { - float index; - float time; - float endTime; + float index; + float time; + float endTime; ccstd::vector coefficient; OptimizedKey() { - index = -1; - time = 0; + index = -1; + time = 0; endTime = 0; coefficient.resize(4); } @@ -94,10 +94,10 @@ public: */ auto getKeyFrames() { return Array.from(this._curve.keyframes()).map(([ time, value ]) = > { - const legacyKeyframe = ccnew Keyframe(); - legacyKeyframe.time = time; - legacyKeyframe.value = value.value; - legacyKeyframe.inTangent = value.leftTangent; + const legacyKeyframe = ccnew Keyframe(); + legacyKeyframe.time = time; + legacyKeyframe.value = value.value; + legacyKeyframe.inTangent = value.leftTangent; legacyKeyframe.outTangent = value.rightTangent; return legacyKeyframe; }); @@ -155,9 +155,9 @@ private if (keyFrames instanceof RealCurve) { this._curve = keyFrames; } else { - const curve = ccnew RealCurve(); - this._curve = curve; - curve.preExtrapolation = ExtrapolationMode.LOOP; + const curve = ccnew RealCurve(); + this._curve = curve; + curve.preExtrapolation = ExtrapolationMode.LOOP; curve.postExtrapolation = ExtrapolationMode.CLAMP; if (!keyFrames) { curve.assignSorted([ @@ -219,12 +219,12 @@ public evaluate(time : number) { const {cachedKey, _curve : curve} = this; - const nKeyframes = curve.keyFramesCount; - const lastKeyframeIndex = nKeyframes - 1; - let wrappedTime = time; - const extrapolationMode = time < 0 ? curve.preExtrapolation : curve.postExtrapolation; - const startTime = curve.getKeyframeTime(0); - const endTime = curve.getKeyframeTime(lastKeyframeIndex); + const nKeyframes = curve.keyFramesCount; + const lastKeyframeIndex = nKeyframes - 1; + let wrappedTime = time; + const extrapolationMode = time < 0 ? curve.preExtrapolation : curve.postExtrapolation; + const startTime = curve.getKeyframeTime(0); + const endTime = curve.getKeyframeTime(lastKeyframeIndex); switch (extrapolationMode) { case ExtrapolationMode.LOOP: wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; @@ -240,7 +240,7 @@ public if (wrappedTime >= cachedKey.time && wrappedTime < cachedKey.endTime) { return cachedKey.evaluate(wrappedTime); } - const leftIndex = this.findIndex(cachedKey, wrappedTime); + const leftIndex = this.findIndex(cachedKey, wrappedTime); const rightIndex = Math.min(leftIndex + 1, lastKeyframeIndex); this.calcOptimizedKey(cachedKey, leftIndex, rightIndex); return cachedKey.evaluate(wrappedTime); @@ -257,19 +257,19 @@ public : OptimizedKey, leftIndex : number, rightIndex : number) { - const lhsTime = this._curve.getKeyframeTime(leftIndex); - const rhsTime = this._curve.getKeyframeTime(rightIndex); + const lhsTime = this._curve.getKeyframeTime(leftIndex); + const rhsTime = this._curve.getKeyframeTime(rightIndex); const {value : lhsValue, leftTangent : lhsOutTangent} = this._curve.getKeyframeValue(leftIndex); const {value : rhsValue, rightTangent : rhsInTangent} = this._curve.getKeyframeValue(rightIndex); - optKey.index = leftIndex; - optKey.time = lhsTime; - optKey.endTime = rhsTime; + optKey.index = leftIndex; + optKey.time = lhsTime; + optKey.endTime = rhsTime; - const dx = rhsTime - lhsTime; - const dy = rhsValue - lhsValue; + const dx = rhsTime - lhsTime; + const dy = rhsValue - lhsValue; const length = 1 / (dx * dx); - const d1 = lhsOutTangent * dx; - const d2 = rhsInTangent * dx; + const d1 = lhsOutTangent * dx; + const d2 = rhsInTangent * dx; optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx; optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length; @@ -287,8 +287,8 @@ private : OptimizedKey, t : number) { const {_curve : curve} = this; - const nKeyframes = curve.keyFramesCount; - const cachedIndex = optKey.index; + const nKeyframes = curve.keyFramesCount; + const cachedIndex = optKey.index; if (cachedIndex != = -1) { const cachedTime = curve.getKeyframeTime(cachedIndex); if (t > cachedTime) { @@ -307,7 +307,7 @@ private } } } - let left = 0; + let left = 0; let right = nKeyframes; let mid; while (right - left > 1) { @@ -358,5 +358,5 @@ export function constructLegacyCurveAndConvert() { return curve; } -} +} // namespace geometry } // namespace cc \ No newline at end of file diff --git a/native/cocos/core/geometry/Distance.cpp b/native/cocos/core/geometry/Distance.cpp index 4c911c3b6a..ef8c95d7a8 100644 --- a/native/cocos/core/geometry/Distance.cpp +++ b/native/cocos/core/geometry/Distance.cpp @@ -19,14 +19,14 @@ float pointPlane(const Vec3 &point, const Plane &plane) { Vec3 *ptPointPlane(Vec3 *out, const Vec3 &point, const Plane &plane) { auto t = pointPlane(point, plane); - *out = point - t * plane.n; + *out = point - t * plane.n; return out; } Vec3 *ptPointAabb(Vec3 *out, const Vec3 &point, const AABB &aabb) { auto min = aabb.getCenter() - aabb.getHalfExtents(); auto max = aabb.getCenter() + aabb.getHalfExtents(); - *out = {cc::mathutils::clamp(point.x, min.x, max.x), + *out = {cc::mathutils::clamp(point.x, min.x, max.x), cc::mathutils::clamp(point.y, min.y, max.y), cc::mathutils::clamp(point.z, min.z, max.z)}; return out; @@ -40,7 +40,7 @@ Vec3 *ptPointObb(Vec3 *out, const Vec3 &point, const OBB &obb) { }; ccstd::array e = {obb.halfExtents.x, obb.halfExtents.y, obb.halfExtents.z}; - auto d = point - obb.center; + auto d = point - obb.center; float dist = 0.0F; // Start result at center of obb; make steps from there @@ -61,7 +61,7 @@ Vec3 *ptPointObb(Vec3 *out, const Vec3 &point, const OBB &obb) { } Vec3 *ptPointLine(Vec3 *out, const Vec3 &point, const Vec3 &linePointA, const Vec3 &linePointB) { - auto dir = linePointA - linePointB; + auto dir = linePointA - linePointB; auto dirSquared = dir.lengthSquared(); if (dirSquared == 0.0F) { @@ -70,8 +70,8 @@ Vec3 *ptPointLine(Vec3 *out, const Vec3 &point, const Vec3 &linePointA, const Ve } else { // Calculate the projection of the point onto the line extending through the segment. auto ap = point - linePointA; - auto t = Vec3::dot(ap, dir) / dirSquared; - *out = linePointA + cc::mathutils::clamp(t, 0.0F, 1.0F) * dir; + auto t = Vec3::dot(ap, dir) / dirSquared; + *out = linePointA + cc::mathutils::clamp(t, 0.0F, 1.0F) * dir; } return out; } diff --git a/native/cocos/core/geometry/Enums.h b/native/cocos/core/geometry/Enums.h index fa173635f3..4fc7754ef9 100644 --- a/native/cocos/core/geometry/Enums.h +++ b/native/cocos/core/geometry/Enums.h @@ -7,18 +7,18 @@ namespace cc { namespace geometry { enum class ShapeEnum { - SHAPE_RAY = (1 << 0), - SHAPE_LINE = (1 << 1), - SHAPE_SPHERE = (1 << 2), - SHAPE_AABB = (1 << 3), - SHAPE_OBB = (1 << 4), - SHAPE_PLANE = (1 << 5), - SHAPE_TRIANGLE = (1 << 6), - SHAPE_FRUSTUM = (1 << 7), + SHAPE_RAY = (1 << 0), + SHAPE_LINE = (1 << 1), + SHAPE_SPHERE = (1 << 2), + SHAPE_AABB = (1 << 3), + SHAPE_OBB = (1 << 4), + SHAPE_PLANE = (1 << 5), + SHAPE_TRIANGLE = (1 << 6), + SHAPE_FRUSTUM = (1 << 7), SHAPE_FRUSTUM_ACCURATE = (1 << 8), - SHAPE_CAPSULE = (1 << 9), - SHAPE_SPLINE = (1 << 10), - SHAPE_BAD = (1 << 11), + SHAPE_CAPSULE = (1 << 9), + SHAPE_SPLINE = (1 << 10), + SHAPE_BAD = (1 << 11), }; class ShapeBase : public RefCounted { diff --git a/native/cocos/core/geometry/Frustum.cpp b/native/cocos/core/geometry/Frustum.cpp index d441058e54..f65560d1a2 100644 --- a/native/cocos/core/geometry/Frustum.cpp +++ b/native/cocos/core/geometry/Frustum.cpp @@ -44,11 +44,11 @@ const ccstd::vector VEC_VALS{ } // namespace void Frustum::createOrtho(Frustum *out, float width, - float height, - float near, - float far, + float height, + float near, + float far, const Mat4 &transform) { - auto halfWidth = width / 2.0F; + auto halfWidth = width / 2.0F; auto halfHeight = height / 2.0F; Vec3::transformMat4({halfWidth, halfHeight, -near}, transform, &out->vertices[0]); Vec3::transformMat4({-halfWidth, halfHeight, -near}, transform, &out->vertices[1]); @@ -92,11 +92,11 @@ Frustum *Frustum::createFromAABB(Frustum *out, const AABB &aabb) { Frustum *Frustum::split(Frustum *out, const scene::Camera &camera, const Mat4 &m, float start, float end) { // 0: cameraNear 1:cameraFar - auto h = static_cast(::tan(camera.getFov() * 0.5)); + auto h = static_cast(::tan(camera.getFov() * 0.5)); float w = h * camera.getAspect(); - Vec3 nearTemp{start * w, start * h, start}; - Vec3 farTemp{end * w, end * h, end}; - Vec3 v3Tmp; + Vec3 nearTemp{start * w, start * h, start}; + Vec3 farTemp{end * w, end * h, end}; + Vec3 v3Tmp; auto &vertexes = out->vertices; // startHalfWidth startHalfHeight @@ -181,8 +181,8 @@ void Frustum::createOrtho(const float width, const float height, const float nea void Frustum::split(float start, float end, float aspect, float fov, const Mat4 &transform) { const float h = tanf(fov * 0.5F); const float w = h * aspect; - const Vec3 nearTemp(start * w, start * h, start); - const Vec3 farTemp(end * w, end * h, end); + const Vec3 nearTemp(start * w, start * h, start); + const Vec3 farTemp(end * w, end * h, end); vertices[0].transformMat4(Vec3(nearTemp.x, nearTemp.y, nearTemp.z), transform); vertices[1].transformMat4(Vec3(-nearTemp.x, nearTemp.y, nearTemp.z), transform); diff --git a/native/cocos/core/geometry/Frustum.h b/native/cocos/core/geometry/Frustum.h index 583ed86f7f..06e4fd4fc8 100644 --- a/native/cocos/core/geometry/Frustum.h +++ b/native/cocos/core/geometry/Frustum.h @@ -55,9 +55,9 @@ public: * @return @en The out object @zh 返回正交视锥体. */ static void createOrtho(Frustum *out, float width, - float height, - float near, - float far, + float height, + float near, + float far, const Mat4 &transform); /** * @en Create a frustum from an AABB box. @@ -121,7 +121,7 @@ public: out->vertices = f.vertices; return out; } - + /** * @en * Set whether to use accurate intersection testing function on this frustum. @@ -155,12 +155,12 @@ public: */ void transform(const Mat4 &); - ccstd::array vertices; + ccstd::array vertices; ccstd::array planes; - void createOrtho(float width, float height, float near, float far, const Mat4 &transform); - void split(float start, float end, float aspect, float fov, const Mat4 &transform); - void updatePlanes(); - void update(const Mat4 &m, const Mat4 &inv); + void createOrtho(float width, float height, float near, float far, const Mat4 &transform); + void split(float start, float end, float aspect, float fov, const Mat4 &transform); + void updatePlanes(); + void update(const Mat4 &m, const Mat4 &inv); }; } // namespace geometry diff --git a/native/cocos/core/geometry/Intersect.cpp b/native/cocos/core/geometry/Intersect.cpp index ffbbab61d6..2153349d32 100644 --- a/native/cocos/core/geometry/Intersect.cpp +++ b/native/cocos/core/geometry/Intersect.cpp @@ -44,8 +44,8 @@ float rayTriangle(const Ray &ray, const Triangle &triangle, bool doubleSided) { return 0; } float invDet = 1.0F / det; - auto ao = ray.o - triangle.a; - auto u = Vec3::dot(ao, pvec) * invDet; + auto ao = ray.o - triangle.a; + auto u = Vec3::dot(ao, pvec) * invDet; if (u < 0 || u > 1) { return 0; } @@ -61,11 +61,11 @@ float rayTriangle(const Ray &ray, const Triangle &triangle, bool doubleSided) { float raySphere(const Ray &ray, const Sphere &sphere) { auto rSq = sphere.getRadius() * sphere.getRadius(); - auto e = sphere.getCenter() - ray.o; + auto e = sphere.getCenter() - ray.o; auto eSq = e.lengthSquared(); auto aLength = Vec3::dot(e, ray.d); // assume ray direction already normalized - auto fSq = rSq - (eSq - aLength * aLength); + auto fSq = rSq - (eSq - aLength * aLength); if (fSq < 0) { return 0; } @@ -76,19 +76,19 @@ float raySphere(const Ray &ray, const Sphere &sphere) { } float rayAABB2(const Ray &ray, const Vec3 &min, const Vec3 &max) { - const auto &o = ray.o; - auto d = ray.d; - auto ix = 1.0F / d.x; - auto iy = 1.0F / d.y; - auto iz = 1.0F / d.z; - auto tx1 = (min.x - o.x) * ix; - auto tx2 = (max.x - o.x) * ix; - auto ty1 = (min.y - o.y) * iy; - auto ty2 = (max.y - o.y) * iy; - auto tz1 = (min.z - o.z) * iz; - auto tz2 = (max.z - o.z) * iz; - auto tmin = std::max(std::max(std::min(tx1, tx2), std::min(ty1, ty2)), std::min(tz1, tz2)); - auto tmax = std::min(std::min(std::max(tx1, tx2), std::max(ty1, ty2)), std::max(tz1, tz2)); + const auto &o = ray.o; + auto d = ray.d; + auto ix = 1.0F / d.x; + auto iy = 1.0F / d.y; + auto iz = 1.0F / d.z; + auto tx1 = (min.x - o.x) * ix; + auto tx2 = (max.x - o.x) * ix; + auto ty1 = (min.y - o.y) * iy; + auto ty2 = (max.y - o.y) * iy; + auto tz1 = (min.z - o.z) * iz; + auto tz2 = (max.z - o.z) * iz; + auto tmin = std::max(std::max(std::min(tx1, tx2), std::min(ty1, ty2)), std::min(tz1, tz2)); + auto tmax = std::min(std::min(std::max(tx1, tx2), std::max(ty1, ty2)), std::max(tz1, tz2)); if (tmax < 0 || tmin > tmax) { return 0; } @@ -103,9 +103,9 @@ float rayAABB(const Ray &ray, const AABB &aabb) { float rayOBB(const Ray &ray, const OBB &obb) { ccstd::array t; - ccstd::array size = {obb.halfExtents.x, obb.halfExtents.y, obb.halfExtents.z}; - const auto & center = obb.center; - auto const & d = ray.d; + ccstd::array size = {obb.halfExtents.x, obb.halfExtents.y, obb.halfExtents.z}; + const auto ¢er = obb.center; + auto const &d = ray.d; Vec3 x = {obb.orientation.m[0], obb.orientation.m[1], obb.orientation.m[2]}; Vec3 y = {obb.orientation.m[3], obb.orientation.m[4], obb.orientation.m[5]}; @@ -141,11 +141,11 @@ float rayOBB(const Ray &ray, const OBB &obb) { float rayCapsule(const Ray &ray, const Capsule &capsule) { Sphere sphere; - auto radiusSqr = capsule.radius * capsule.radius; - auto vRayNorm = ray.d.getNormalized(); - auto aa = capsule.ellipseCenter0; - auto bb = capsule.ellipseCenter1; - auto ba = bb - aa; + auto radiusSqr = capsule.radius * capsule.radius; + auto vRayNorm = ray.d.getNormalized(); + auto aa = capsule.ellipseCenter0; + auto bb = capsule.ellipseCenter1; + auto ba = bb - aa; if (ba == Vec3::ZERO) { sphere.setRadius(capsule.radius); sphere.setCenter(capsule.ellipseCenter0); @@ -170,9 +170,9 @@ float rayCapsule(const Ray &ray, const Capsule &capsule) { Vec3 OAxBA; //NOLINT(readability-identifier-naming) Vec3::cross(oa, ba, &OAxBA); auto ab2 = ba.lengthSquared(); - auto b = 2.0F * Vec3::dot(VxBA, OAxBA); - auto c = OAxBA.lengthSquared() - (radiusSqr * ab2); - auto d = b * b - 4 * a * c; + auto b = 2.0F * Vec3::dot(VxBA, OAxBA); + auto c = OAxBA.lengthSquared() - (radiusSqr * ab2); + auto d = b * b - 4 * a * c; if (d < 0) { return 0; @@ -190,9 +190,9 @@ float rayCapsule(const Ray &ray, const Capsule &capsule) { return raySphere(ray, sphere); } // Limit intersection between the bounds of the cylinder's end caps. - auto iPos = ray.o + vRayNorm * t; + auto iPos = ray.o + vRayNorm * t; auto iPosLen = iPos - aa; - auto tLimit = Vec3::dot(iPosLen, ba) / ab2; + auto tLimit = Vec3::dot(iPosLen, ba) / ab2; if (tLimit >= 0 && tLimit <= 1) { return t; @@ -219,7 +219,7 @@ void fillResult(float *minDis, ERaycastMode m, float d, float i0, float i1, floa if (r->empty()) { r->emplace_back(IRaySubMeshResult{d, static_cast(i0 / 3), static_cast(i1 / 3), static_cast(i2 / 3)}); } else { - (*r)[0].distance = d; + (*r)[0].distance = d; (*r)[0].vertexIndex0 = static_cast(i0 / 3); (*r)[0].vertexIndex1 = static_cast(i1 / 3); (*r)[0].vertexIndex2 = static_cast(i2 / 3); @@ -234,33 +234,33 @@ void fillResult(float *minDis, ERaycastMode m, float d, float i0, float i1, floa float narrowphase(float *minDis, const Float32Array &vb, const IBArray &ib, gfx::PrimitiveMode pm, const Ray &ray, IRaySubMeshOptions *opt) { Triangle tri; - auto ibSize = cc::visit([](auto &arr) { return arr.length(); }, ib); + auto ibSize = cc::visit([](auto &arr) { return arr.length(); }, ib); return cc::visit([&](auto &ib) { if (pm == gfx::PrimitiveMode::TRIANGLE_LIST) { auto cnt = ibSize; for (auto j = 0; j < cnt; j += 3) { - auto i0 = ib[j] * 3; - auto i1 = ib[j + 1] * 3; - auto i2 = ib[j + 2] * 3; - tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; - tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; - tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; + auto i0 = ib[j] * 3; + auto i1 = ib[j + 1] * 3; + auto i2 = ib[j + 2] * 3; + tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; + tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; + tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; auto dist = rayTriangle(ray, tri, opt->doubleSided); if (dist == 0.0F || dist > opt->distance) continue; fillResult(minDis, opt->mode, dist, static_cast(i0), static_cast(i1), static_cast(i2), opt->result); if (opt->mode == ERaycastMode::ANY) return dist; } } else if (pm == gfx::PrimitiveMode::TRIANGLE_STRIP) { - auto cnt = ibSize - 2; + auto cnt = ibSize - 2; int32_t rev = 0; for (auto j = 0; j < cnt; j += 1) { - auto i0 = ib[j - rev] * 3; - auto i1 = ib[j + rev + 1] * 3; - auto i2 = ib[j + 2] * 3; - tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; - tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; - tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; - rev = ~rev; + auto i0 = ib[j - rev] * 3; + auto i1 = ib[j + rev + 1] * 3; + auto i2 = ib[j + 2] * 3; + tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; + tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; + tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; + rev = ~rev; auto dist = rayTriangle(ray, tri, opt->doubleSided); if (dist == 0.0F || dist > opt->distance) continue; fillResult(minDis, opt->mode, dist, static_cast(i0), static_cast(i1), static_cast(i2), opt->result); @@ -268,13 +268,13 @@ float narrowphase(float *minDis, const Float32Array &vb, const IBArray &ib, gfx: } } else if (pm == gfx::PrimitiveMode::TRIANGLE_FAN) { auto cnt = ibSize - 1; - auto i0 = ib[0] * 3; - tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; + auto i0 = ib[0] * 3; + tri.a = {vb[i0], vb[i0 + 1], vb[i0 + 2]}; for (auto j = 1; j < cnt; j += 1) { - auto i1 = ib[j] * 3; - auto i2 = ib[j + 1] * 3; - tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; - tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; + auto i1 = ib[j] * 3; + auto i2 = ib[j + 1] * 3; + tri.b = {vb[i1], vb[i1 + 1], vb[i1 + 2]}; + tri.c = {vb[i2], vb[i2 + 1], vb[i2 + 2]}; auto dist = rayTriangle(ray, tri, opt->doubleSided); if (dist == 0.0 || dist > opt->distance) continue; fillResult(minDis, opt->mode, dist, static_cast(i0), static_cast(i1), static_cast(i2), opt->result); @@ -288,19 +288,19 @@ float narrowphase(float *minDis, const Float32Array &vb, const IBArray &ib, gfx: } // namespace float raySubMesh(const Ray &ray, const RenderingSubMesh &submesh, IRaySubMeshOptions *options) { - Triangle tri; + Triangle tri; IRaySubMeshOptions deOpt; - deOpt.mode = ERaycastMode::ANY; - deOpt.distance = FLT_MAX; + deOpt.mode = ERaycastMode::ANY; + deOpt.distance = FLT_MAX; deOpt.doubleSided = false; - float minDis = 0.0F; - auto &mesh = const_cast(submesh); + float minDis = 0.0F; + auto &mesh = const_cast(submesh); if (mesh.getGeometricInfo().positions.empty()) return minDis; IRaySubMeshOptions *opt = options ? options : &deOpt; - auto min = mesh.getGeometricInfo().boundingBox.min; - auto max = mesh.getGeometricInfo().boundingBox.max; + auto min = mesh.getGeometricInfo().boundingBox.min; + auto max = mesh.getGeometricInfo().boundingBox.max; if (rayAABB2(ray, min, max) != 0.0F) { - const auto &pm = mesh.getPrimitiveMode(); + const auto &pm = mesh.getPrimitiveMode(); const auto &info = mesh.getGeometricInfo(); narrowphase(&minDis, info.positions, info.indices.value(), pm, ray, opt); } @@ -308,19 +308,19 @@ float raySubMesh(const Ray &ray, const RenderingSubMesh &submesh, IRaySubMeshOpt } float rayMesh(const Ray &ray, const Mesh &mesh, IRayMeshOptions *option) { - float minDis = 0.0F; + float minDis = 0.0F; IRayMeshOptions deOpt; - deOpt.distance = std::numeric_limits::max(); - deOpt.doubleSided = false; - deOpt.mode = ERaycastMode::ANY; - IRayMeshOptions *opt = option ? option : &deOpt; - auto length = mesh.getSubMeshCount(); - auto min = mesh.getStruct().minPosition; - auto max = mesh.getStruct().maxPosition; + deOpt.distance = std::numeric_limits::max(); + deOpt.doubleSided = false; + deOpt.mode = ERaycastMode::ANY; + IRayMeshOptions *opt = option ? option : &deOpt; + auto length = mesh.getSubMeshCount(); + auto min = mesh.getStruct().minPosition; + auto max = mesh.getStruct().maxPosition; if (min.has_value() && max.has_value() && rayAABB2(ray, min.value(), max.value()) == 0.0F) return minDis; for (uint32_t i = 0; i < length; i++) { - const auto &sm = const_cast(mesh).getRenderingSubMeshes()[i]; - float dis = raySubMesh(ray, *sm, opt); + const auto &sm = const_cast(mesh).getRenderingSubMeshes()[i]; + float dis = raySubMesh(ray, *sm, opt); if (dis != 0.0F) { if (opt->mode == ERaycastMode::CLOSEST) { if (minDis == 0.0F || minDis > dis) { @@ -352,14 +352,14 @@ float rayMesh(const Ray &ray, const Mesh &mesh, IRayMeshOptions *option) { } float rayModel(const Ray &ray, const scene::Model &model, IRayModelOptions *option) { - float minDis = 0.0F; + float minDis = 0.0F; IRayModelOptions deOpt; - deOpt.distance = std::numeric_limits::max(); + deOpt.distance = std::numeric_limits::max(); deOpt.doubleSided = false; - deOpt.mode = ERaycastMode::ANY; + deOpt.mode = ERaycastMode::ANY; IRayModelOptions *opt = option ? option : &deOpt; - const auto * wb = model.getWorldBounds(); + const auto *wb = model.getWorldBounds(); if (wb && rayAABB(ray, *wb) == 0.0F) { return minDis; } @@ -372,7 +372,7 @@ float rayModel(const Ray &ray, const scene::Model &model, IRayModelOptions *opti const auto &subModels = model.getSubModels(); for (auto i = 0; i < subModels.size(); i++) { const auto &subMesh = subModels[i]->getSubMesh(); - float dis = raySubMesh(modelRay, *subMesh, opt); + float dis = raySubMesh(modelRay, *subMesh, opt); if (dis != 0.0F) { if (opt->mode == ERaycastMode::CLOSEST) { if (minDis == 0.0F || minDis > dis) { @@ -405,7 +405,7 @@ float rayModel(const Ray &ray, const scene::Model &model, IRayModelOptions *opti float linePlane(const Line &line, const Plane &plane) { auto ab = line.e - line.s; - auto t = (plane.d - Vec3::dot(line.s, plane.n)) / Vec3::dot(ab, plane.n); + auto t = (plane.d - Vec3::dot(line.s, plane.n)) / Vec3::dot(ab, plane.n); return (t < 0 || t > 1) ? 0 : t; } @@ -424,7 +424,7 @@ int lineTriangle(const Line &line, const Triangle &triangle, Vec3 *outPt) { } auto ap = line.s - triangle.a; - auto t = Vec3::dot(ap, n); + auto t = Vec3::dot(ap, n); if (t < 0 || t > det) { return 0; } @@ -550,16 +550,16 @@ static Interval getInterval(const ccstd::array &vertices, const Vec3 &a auto max = std::numeric_limits::min(); for (auto i = 0; i < 8; ++i) { auto projection = Vec3::dot(axis, vertices[i]); - min = std::min(projection, min); - max = std::max(projection, max); + min = std::min(projection, min); + max = std::max(projection, max); } return Interval{min, max}; } int aabbWithOBB(const AABB &aabb, const OBB &obb) { ccstd::array test; - ccstd::array vertices; - ccstd::array vertices2; + ccstd::array vertices; + ccstd::array vertices2; test[0] = {1, 0, 0}; test[1] = {0, 1, 0}; test[2] = {0, 0, 1}; @@ -590,7 +590,7 @@ int aabbWithOBB(const AABB &aabb, const OBB &obb) { } int aabbPlane(const AABB &aabb, const Plane &plane) { - auto r = aabb.getHalfExtents().x * std::abs(plane.n.x) + aabb.getHalfExtents().y * std::abs(plane.n.y) + aabb.getHalfExtents().z * std::abs(plane.n.z); + auto r = aabb.getHalfExtents().x * std::abs(plane.n.x) + aabb.getHalfExtents().y * std::abs(plane.n.y) + aabb.getHalfExtents().z * std::abs(plane.n.z); auto dot = Vec3::dot(plane.n, aabb.getCenter()); if (dot + r < plane.d) { return -1; @@ -614,10 +614,10 @@ int aabbFrustum(const AABB &aabb, const Frustum &frustum) { // https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/ int aabbFrustumAccurate(const AABB &aabb, const Frustum &frustum) { ccstd::array tmp; - int out1 = 0; - int out2 = 0; - int result = 0; - bool intersects = false; + int out1 = 0; + int out2 = 0; + int result = 0; + bool intersects = false; // 1. aabb inside/outside frustum test for (const auto &plane : frustum.planes) { result = aabbPlane(aabb, *plane); @@ -719,14 +719,14 @@ int obbFrustum(const OBB &obb, const Frustum &frustum) { // https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/ int obbFrustumAccurate(const OBB &obb, const Frustum &frustum) { - ccstd::array tmp = {}; - float dist = 0.0F; - size_t out1 = 0; - size_t out2 = 0; - auto dot = [](const Vec3 &n, float x, float y, float z) -> float { + ccstd::array tmp = {}; + float dist = 0.0F; + size_t out1 = 0; + size_t out2 = 0; + auto dot = [](const Vec3 &n, float x, float y, float z) -> float { return n.x * x + n.y * y + n.z * z; }; - int result = 0; + int result = 0; auto intersects = false; // 1. obb inside/outside frustum test for (const auto &plane : frustum.planes) { @@ -790,8 +790,8 @@ int obbFrustumAccurate(const OBB &obb, const Frustum &frustum) { } int obbWithOBB(const OBB &obb1, const OBB &obb2) { - ccstd::array vertices; - ccstd::array vertices2; + ccstd::array vertices; + ccstd::array vertices2; ccstd::array test; test[0] = {obb1.orientation.m[0], obb1.orientation.m[1], obb1.orientation.m[2]}; @@ -822,10 +822,10 @@ int obbWithOBB(const OBB &obb1, const OBB &obb2) { // https://github.com/diku-dk/bvh-tvcg18/blob/1fd3348c17bc8cf3da0b4ae60fdb8f2aa90a6ff0/FOUNDATION/GEOMETRY/GEOMETRY/include/overlap/geometry_overlap_obb_capsule.h int obbCapsule(const OBB &obb, const Capsule &capsule) { - Sphere sphere{}; + Sphere sphere{}; ccstd::array v3Verts8{}; ccstd::array v3Axis8{}; - auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1); + auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1); if (h == 0.0F) { sphere.setRadius(capsule.radius); sphere.setCenter(capsule.ellipseCenter0); @@ -858,9 +858,9 @@ int obbCapsule(const OBB &obb, const Capsule &capsule) { Vec3::cross(a2, bb, &axes[7]); for (auto i = 0; i < 8; ++i) { - auto a = getInterval(v3Verts8, axes[i]); - auto d0 = Vec3::dot(axes[i], capsule.ellipseCenter0); - auto d1 = Vec3::dot(axes[i], capsule.ellipseCenter1); + auto a = getInterval(v3Verts8, axes[i]); + auto d0 = Vec3::dot(axes[i], capsule.ellipseCenter0); + auto d1 = Vec3::dot(axes[i], capsule.ellipseCenter1); auto dMin = std::min(d0, d1) - capsule.radius; auto dMax = std::max(d0, d1) + capsule.radius; if (dMin > a.max || a.min > dMax) { @@ -872,7 +872,7 @@ int obbCapsule(const OBB &obb, const Capsule &capsule) { int spherePlane(const Sphere &sphere, const Plane &plane) { auto dot = Vec3::dot(plane.n, sphere.getCenter()); - auto r = sphere.getRadius() * plane.n.length(); + auto r = sphere.getRadius() * plane.n.length(); if (dot + r < plane.d) { return -1; } @@ -896,11 +896,11 @@ int sphereFrustumAccurate(const Sphere &sphere, const Frustum &frustum) { const static ccstd::array MAP = {1, -1, 1, -1, 1, -1}; for (auto i = 0; i < 6; i++) { const auto &plane = frustum.planes[i]; - const auto &n = plane->n; - const auto &d = plane->d; - auto r = sphere.getRadius(); - const auto &c = sphere.getCenter(); - auto dot = Vec3::dot(n, c); + const auto &n = plane->n; + const auto &d = plane->d; + auto r = sphere.getRadius(); + const auto &c = sphere.getCenter(); + auto dot = Vec3::dot(n, c); // frustum plane normal points to the inside if (dot + r < d) { return 0; // completely outside @@ -942,15 +942,15 @@ bool sphereOBB(const Sphere &sphere, const OBB &obb) { } bool sphereCapsule(const Sphere &sphere, const Capsule &capsule) { - auto r = sphere.getRadius() + capsule.radius; + auto r = sphere.getRadius() + capsule.radius; auto squaredR = r * r; - auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1); + auto h = capsule.ellipseCenter0.distanceSquared(capsule.ellipseCenter1); if (h == 0.0F) { return sphere.getCenter().distanceSquared(capsule.center) < squaredR; } auto v3Tmp0 = sphere.getCenter() - capsule.ellipseCenter0; auto v3Tmp1 = capsule.ellipseCenter1 - capsule.ellipseCenter0; - auto t = Vec3::dot(v3Tmp0, v3Tmp1) / h; + auto t = Vec3::dot(v3Tmp0, v3Tmp1) / h; if (t < 0) { return sphere.getCenter().distanceSquared(capsule.ellipseCenter0) < squaredR; } @@ -962,15 +962,15 @@ bool sphereCapsule(const Sphere &sphere, const Capsule &capsule) { } bool capsuleWithCapsule(const Capsule &capsuleA, const Capsule &capsuleB) { - auto u = capsuleA.ellipseCenter1 - capsuleA.ellipseCenter0; - auto v = capsuleB.ellipseCenter1 - capsuleB.ellipseCenter0; - auto w = capsuleA.ellipseCenter0 - capsuleB.ellipseCenter0; - auto a = Vec3::dot(u, u); // always >= 0 - auto b = Vec3::dot(u, v); - auto c = Vec3::dot(v, v); // always >= 0 - auto d = Vec3::dot(u, w); - auto e = Vec3::dot(v, w); - auto dd = a * c - b * b; // always >= 0 + auto u = capsuleA.ellipseCenter1 - capsuleA.ellipseCenter0; + auto v = capsuleB.ellipseCenter1 - capsuleB.ellipseCenter0; + auto w = capsuleA.ellipseCenter0 - capsuleB.ellipseCenter0; + auto a = Vec3::dot(u, u); // always >= 0 + auto b = Vec3::dot(u, v); + auto c = Vec3::dot(v, v); // always >= 0 + auto d = Vec3::dot(u, w); + auto e = Vec3::dot(v, w); + auto dd = a * c - b * b; // always >= 0 float sN; float sD = dd; // sc = sN / sD, default sD = dd >= 0 float tN; @@ -1024,9 +1024,9 @@ bool capsuleWithCapsule(const Capsule &capsuleA, const Capsule &capsuleB) { auto tc = (std::abs(tN) < math::EPSILON ? 0.0F : tN / tD); // get the difference of the two closest points - auto dP = w; - dP = dP + u * sc; - dP = dP - v * tc; + auto dP = w; + dP = dP + u * sc; + dP = dP - v * tc; auto radius = capsuleA.radius + capsuleB.radius; return dP.lengthSquared() < radius * radius; } diff --git a/native/cocos/core/geometry/Line.h b/native/cocos/core/geometry/Line.h index f4c5317e8e..3b232e9be6 100644 --- a/native/cocos/core/geometry/Line.h +++ b/native/cocos/core/geometry/Line.h @@ -128,8 +128,8 @@ public: Line(const Line &) = default; Line &operator=(const Line &) = default; Line &operator=(Line &&) = default; - Line(Line &&) = default; - ~Line() override = default; + Line(Line &&) = default; + ~Line() override = default; /** * @zh diff --git a/native/cocos/core/geometry/Obb.cpp b/native/cocos/core/geometry/Obb.cpp index 87c0ad342e..1731dd3963 100644 --- a/native/cocos/core/geometry/Obb.cpp +++ b/native/cocos/core/geometry/Obb.cpp @@ -27,40 +27,40 @@ OBB *OBB::create( float oy1, float oy2, float oy3, float oz1, float oz2, float oz3) { return ccnew OBB(cx, cy, cz, hw, hh, hl, - ox1, ox2, ox3, - oy1, oy2, oy3, - oz1, oz2, oz3); + ox1, ox2, ox3, + oy1, oy2, oy3, + oz1, oz2, oz3); } OBB *OBB::clone(const OBB &a) { return ccnew OBB(a.center.x, a.center.y, a.center.z, - a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, - a.orientation.m[0], a.orientation.m[1], a.orientation.m[2], - a.orientation.m[3], a.orientation.m[4], a.orientation.m[5], - a.orientation.m[6], a.orientation.m[7], a.orientation.m[8]); + a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, + a.orientation.m[0], a.orientation.m[1], a.orientation.m[2], + a.orientation.m[3], a.orientation.m[4], a.orientation.m[5], + a.orientation.m[6], a.orientation.m[7], a.orientation.m[8]); } OBB *OBB::copy(OBB *out, const OBB &a) { - out->center = a.center; + out->center = a.center; out->halfExtents = a.halfExtents; out->orientation = a.orientation; return out; } OBB *OBB::fromPoints(OBB *out, const Vec3 &minPos, const Vec3 &maxPos) { - out->center = 0.5F * (minPos + maxPos); + out->center = 0.5F * (minPos + maxPos); out->halfExtents = 0.5F * (maxPos - minPos); Mat3::identity(out->orientation); return out; } -OBB *OBB::set(OBB * out, +OBB *OBB::set(OBB *out, float cx, float cy, float cz, float hw, float hh, float hl, float ox1, float ox2, float ox3, float oy1, float oy2, float oy3, float oz1, float oz2, float oz3) { - out->center = {cx, cy, cz}; + out->center = {cx, cy, cz}; out->halfExtents = {hw, hh, hl}; out->orientation = {ox1, ox2, ox3, oy1, oy2, oy3, oz1, oz2, oz3}; return out; @@ -72,7 +72,7 @@ OBB::OBB(float cx, float cy, float cz, float oy1, float oy2, float oy3, float oz1, float oz2, float oz3) { setType(ShapeEnum::SHAPE_OBB); - center = {cx, cy, cz}; + center = {cx, cy, cz}; halfExtents = {hw, hh, hl}; orientation = {ox1, ox2, ox3, oy1, oy2, oy3, oz1, oz2, oz3}; } diff --git a/native/cocos/core/geometry/Obb.h b/native/cocos/core/geometry/Obb.h index 84002a5093..d0d8660dd5 100644 --- a/native/cocos/core/geometry/Obb.h +++ b/native/cocos/core/geometry/Obb.h @@ -93,7 +93,7 @@ public: * @return {OBB} out */ - static OBB *set(OBB * out, + static OBB *set(OBB *out, float cx, float cy, float cz, float hw, float hh, float hl, float ox1, float ox2, float ox3, diff --git a/native/cocos/core/geometry/Plane.cpp b/native/cocos/core/geometry/Plane.cpp index 07b3288c07..22e3cd0923 100644 --- a/native/cocos/core/geometry/Plane.cpp +++ b/native/cocos/core/geometry/Plane.cpp @@ -17,7 +17,7 @@ Plane *Plane::copy(Plane *out, const Plane &p) { return out; } -Plane *Plane::fromPoints(Plane * out, +Plane *Plane::fromPoints(Plane *out, const Vec3 &a, const Vec3 &b, const Vec3 &c) { @@ -35,7 +35,7 @@ Plane *Plane::fromNormalAndPoint(Plane *out, const Vec3 &normal, const Vec3 &poi Plane *Plane::normalize(Plane *out, const Plane &a) { const auto len = a.n.length(); - out->n = a.n.getNormalized(); + out->n = a.n.getNormalized(); if (len > 0) { out->d = a.d / len; } @@ -50,7 +50,7 @@ Plane *Plane::set(Plane *out, float nx, float ny, float nz, float d) { Plane::Plane(float nx, float ny, float nz, float d) { setType(ShapeEnum::SHAPE_PLANE); - n = {nx, ny, nz}; + n = {nx, ny, nz}; this->d = d; } diff --git a/native/cocos/core/geometry/Plane.h b/native/cocos/core/geometry/Plane.h index 465b584d55..bb0de91295 100644 --- a/native/cocos/core/geometry/Plane.h +++ b/native/cocos/core/geometry/Plane.h @@ -61,7 +61,7 @@ public: * @param c 点 c。 * @return out 接受操作的对象。 */ - static Plane *fromPoints(Plane * out, + static Plane *fromPoints(Plane *out, const Vec3 &a, const Vec3 &b, const Vec3 &c); @@ -104,13 +104,13 @@ public: static Plane *normalize(Plane *out, const Plane &a); // compatibility with vector interfaces - inline void setX(float val) { n.x = val; } + inline void setX(float val) { n.x = val; } inline float getX() const { return n.x; } - inline void setY(float val) { n.y = val; } + inline void setY(float val) { n.y = val; } inline float getY() const { return n.y; } - inline void setZ(float val) { n.z = val; } + inline void setZ(float val) { n.z = val; } inline float getZ() const { return n.z; } - inline void setW(float val) { d = val; } + inline void setW(float val) { d = val; } inline float getW() const { return d; } /** @@ -157,8 +157,8 @@ public: */ float d{0.0F}; - void define(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2); - void define(const Vec3 &normal, const Vec3 &point); + void define(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2); + void define(const Vec3 &normal, const Vec3 &point); float distance(const Vec3 &point) const; Plane clone() const; }; diff --git a/native/cocos/core/geometry/Ray.h b/native/cocos/core/geometry/Ray.h index 372be21a31..14dbbcebe9 100644 --- a/native/cocos/core/geometry/Ray.h +++ b/native/cocos/core/geometry/Ray.h @@ -117,8 +117,8 @@ public: Ray(const Ray &) = default; Ray &operator=(const Ray &) = default; Ray &operator=(Ray &&) = default; - Ray(Ray &&) = default; - ~Ray() override = default; + Ray(Ray &&) = default; + ~Ray() override = default; /** * @en diff --git a/native/cocos/core/geometry/Sphere.cpp b/native/cocos/core/geometry/Sphere.cpp index c551ad946d..44768744e9 100644 --- a/native/cocos/core/geometry/Sphere.cpp +++ b/native/cocos/core/geometry/Sphere.cpp @@ -68,7 +68,7 @@ Sphere *Sphere::mergePoint(Sphere *out, const Sphere &s, const Vec3 &point) { } auto offset = point - s._center; - auto dist = offset.length(); + auto dist = offset.length(); if (dist > s._radius) { auto half = (dist - s._radius) * 0.5F; @@ -105,22 +105,22 @@ Sphere::Sphere(float cx, float cy, float cz, float radius) { void Sphere::getBoundary(Vec3 *minPos, Vec3 *maxPos) const { Vec3 half = {_radius, _radius, _radius}; - *minPos = _center - half; - *maxPos = _center + half; + *minPos = _center - half; + *maxPos = _center + half; } void Sphere::transform(const Mat4 &m, const Vec3 & /*pos*/, const Quaternion & /*rot*/, const Vec3 &scale, - Sphere * out) const { + Sphere *out) const { Vec3::transformMat4(_center, m, &out->_center); out->_radius = _radius * mathutils::maxComponent(scale); } int Sphere::interset(const Plane &plane) const { const float dot = plane.n.dot(_center); - const float r = _radius * plane.n.length(); + const float r = _radius * plane.n.length(); if (dot + r < plane.d) { return -1; } @@ -134,7 +134,7 @@ int Sphere::interset(const Plane &plane) const { bool Sphere::interset(const Frustum &frustum) const { const auto &planes = frustum.planes; - const auto *self = this; + const auto *self = this; return std::all_of(planes.begin(), planes.end(), // frustum plane normal points to the inside @@ -148,7 +148,7 @@ void Sphere::mergePoint(const Vec3 &point) { return; } - auto offset = point - _center; + auto offset = point - _center; auto distance = offset.length(); if (distance > _radius) { @@ -170,7 +170,7 @@ void Sphere::define(const AABB &aabb) { // Calculate sphere const cc::Vec3 offset = maxPos - _center; - const float dist = offset.length(); + const float dist = offset.length(); const float half = dist * 0.5F; _radius += dist * 0.5F; @@ -187,7 +187,7 @@ void Sphere::mergeAABB(const AABB *aabb) { int Sphere::spherePlane(const Plane &plane) { const auto dot = cc::Vec3::dot(plane.n, _center); - const auto r = _radius * plane.n.length(); + const auto r = _radius * plane.n.length(); if (dot + r < plane.d) { return -1; } @@ -199,7 +199,7 @@ int Sphere::spherePlane(const Plane &plane) { bool Sphere::sphereFrustum(const Frustum &frustum) const { const auto &planes = frustum.planes; - const auto *self = this; + const auto *self = this; return std::all_of(planes.begin(), planes.end(), // frustum plane normal points to the inside diff --git a/native/cocos/core/geometry/Sphere.h b/native/cocos/core/geometry/Sphere.h index 3bbc14066b..226abd0c66 100644 --- a/native/cocos/core/geometry/Sphere.h +++ b/native/cocos/core/geometry/Sphere.h @@ -110,15 +110,15 @@ public: explicit Sphere(float cx = 0, float cy = 0, float cz = 0, float radius = 1.0F); Sphere(const Sphere &) = delete; - Sphere(Sphere &&) = delete; - ~Sphere() override = default; + Sphere(Sphere &&) = delete; + ~Sphere() override = default; Sphere &operator=(const Sphere &) = delete; Sphere &operator=(Sphere &&) = delete; - inline float getRadius() const { return _radius; } + inline float getRadius() const { return _radius; } inline const Vec3 &getCenter() const { return _center; } - inline void setCenter(const Vec3 &val) { _center = val; } - inline void setRadius(float val) { _radius = val; } + inline void setCenter(const Vec3 &val) { _center = val; } + inline void setRadius(float val) { _radius = val; } inline Sphere *clone() const { return Sphere::clone(*this); @@ -128,18 +128,18 @@ public: return Sphere::copy(out, *this); } - void define(const AABB &aabb); - void mergeAABB(const AABB *aabb); - void mergePoint(const Vec3 &point); - void mergeFrustum(const Frustum &frustum); + void define(const AABB &aabb); + void mergeAABB(const AABB *aabb); + void mergePoint(const Vec3 &point); + void mergeFrustum(const Frustum &frustum); inline void merge(const AABB *aabb) { mergeAABB(aabb); } inline void merge(const Vec3 &point) { mergePoint(point); } - void merge(const ccstd::vector &points); + void merge(const ccstd::vector &points); inline void merge(const Frustum &frustum) { mergeFrustum(frustum); } - bool interset(const Frustum &frustum) const; - int interset(const Plane &plane) const; - int spherePlane(const Plane &plane); - bool sphereFrustum(const Frustum &frustum) const; + bool interset(const Frustum &frustum) const; + int interset(const Plane &plane) const; + int spherePlane(const Plane &plane); + bool sphereFrustum(const Frustum &frustum) const; /** * @en @@ -166,7 +166,7 @@ public: const Vec3 & /*pos*/, const Quaternion & /*rot*/, const Vec3 &scale, - Sphere * out) const; + Sphere *out) const; /** * @en @@ -195,7 +195,7 @@ public: private: float _radius{-1.0}; - Vec3 _center; + Vec3 _center; }; } // namespace geometry diff --git a/native/cocos/core/geometry/Spline.cpp b/native/cocos/core/geometry/Spline.cpp index 4df43951ed..54bf44a10b 100644 --- a/native/cocos/core/geometry/Spline.cpp +++ b/native/cocos/core/geometry/Spline.cpp @@ -47,14 +47,14 @@ Spline *Spline::clone(const Spline &s) { } Spline *Spline::copy(Spline *out, const Spline &s) { - out->_mode = s._mode; + out->_mode = s._mode; out->_knots = s._knots; return out; } void Spline::setModeAndKnots(SplineMode mode, const ccstd::vector &knots) { - _mode = mode; + _mode = mode; _knots = knots; } @@ -102,7 +102,7 @@ Vec3 Spline::getPoint(float t, uint32_t index /*= SPLINE_WHOLE_INDEX*/) const { const auto deltaT = 1.0F / static_cast(segments); index = static_cast(t / deltaT); - t = std::fmod(t, deltaT) / deltaT; + t = std::fmod(t, deltaT) / deltaT; } if (index >= segments) { @@ -135,10 +135,10 @@ ccstd::vector Spline::getPoints(uint32_t num, uint32_t index /*= SPLINE_WH } ccstd::vector points; - const float deltaT = 1.0F / (static_cast(num) - 1.0F); + const float deltaT = 1.0F / (static_cast(num) - 1.0F); for (auto i = 0; i < num; i++) { - const auto t = static_cast(i) * deltaT; + const auto t = static_cast(i) * deltaT; const auto point = getPoint(t, index); points.push_back(point); @@ -178,7 +178,7 @@ Vec3 Spline::calcLinear(const Vec3 &v0, const Vec3 &v1, float t) { } Vec3 Spline::calcBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t) { - const auto s = 1.0F - t; + const auto s = 1.0F - t; const auto result = v0 * s * s * s + v1 * 3.0F * t * s * s + v2 * 3.0F * t * t * s + @@ -188,8 +188,8 @@ Vec3 Spline::calcBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Ve } Vec3 Spline::calcCatmullRom(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t) { - const auto t2 = t * t; - const auto t3 = t2 * t; + const auto t2 = t * t; + const auto t3 = t2 * t; const auto result = v0 * (-0.5F * t3 + t2 - 0.5F * t) + v1 * (1.5F * t3 - 2.5F * t2 + 1.0F) + v2 * (-1.5F * t3 + 2.0F * t2 + 0.5F * t) + diff --git a/native/cocos/core/geometry/Spline.h b/native/cocos/core/geometry/Spline.h index 435068af34..a90ef7dc21 100644 --- a/native/cocos/core/geometry/Spline.h +++ b/native/cocos/core/geometry/Spline.h @@ -73,8 +73,8 @@ public: explicit Spline(SplineMode mode = SplineMode::CATMULL_ROM, ccstd::vector knots = {}); Spline(const Spline &) = default; - Spline(Spline &&) = default; - ~Spline() override = default; + Spline(Spline &&) = default; + ~Spline() override = default; Spline &operator=(const Spline &) = default; Spline &operator=(Spline &&) = default; @@ -82,19 +82,19 @@ public: static Spline *clone(const Spline &s); static Spline *copy(Spline *out, const Spline &s); - inline void setMode(SplineMode mode) { _mode = mode; } - inline SplineMode getMode() const { return _mode; } - inline void setKnots(const ccstd::vector &knots) { _knots = knots; } + inline void setMode(SplineMode mode) { _mode = mode; } + inline SplineMode getMode() const { return _mode; } + inline void setKnots(const ccstd::vector &knots) { _knots = knots; } inline const ccstd::vector &getKnots() const { return _knots; } - inline void clearKnots() { _knots.clear(); } - inline uint32_t getKnotCount() const { return static_cast(_knots.size()); } - inline void addKnot(const Vec3 &knot) { _knots.push_back(knot); } - void setModeAndKnots(SplineMode mode, const ccstd::vector &knots); - void insertKnot(uint32_t index, const Vec3 &knot); - void removeKnot(uint32_t index); - void setKnot(uint32_t index, const Vec3 &knot); - const Vec3 & getKnot(uint32_t index) const; - Vec3 & getKnot(uint32_t index); + inline void clearKnots() { _knots.clear(); } + inline uint32_t getKnotCount() const { return static_cast(_knots.size()); } + inline void addKnot(const Vec3 &knot) { _knots.push_back(knot); } + void setModeAndKnots(SplineMode mode, const ccstd::vector &knots); + void insertKnot(uint32_t index, const Vec3 &knot); + void removeKnot(uint32_t index); + void setKnot(uint32_t index, const Vec3 &knot); + const Vec3 &getKnot(uint32_t index) const; + Vec3 &getKnot(uint32_t index); // get a point at t with repect to the `index` segment of curve or the whole curve. Vec3 getPoint(float t, uint32_t index = SPLINE_WHOLE_INDEX) const; @@ -103,12 +103,12 @@ public: ccstd::vector getPoints(uint32_t num, uint32_t index = SPLINE_WHOLE_INDEX) const; private: - uint32_t getSegments() const; + uint32_t getSegments() const; static Vec3 calcLinear(const Vec3 &v0, const Vec3 &v1, float t); static Vec3 calcBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t); static Vec3 calcCatmullRom(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t); - SplineMode _mode{SplineMode::CATMULL_ROM}; + SplineMode _mode{SplineMode::CATMULL_ROM}; ccstd::vector _knots; // control points of the curve. }; diff --git a/native/cocos/core/geometry/Triangle.h b/native/cocos/core/geometry/Triangle.h index 20180d52ad..b3b19445b8 100644 --- a/native/cocos/core/geometry/Triangle.h +++ b/native/cocos/core/geometry/Triangle.h @@ -140,8 +140,8 @@ public: float cx = 0, float cy = 1, float cz = 0); Triangle(const Triangle &) = default; - Triangle(Triangle &&) = default; - ~Triangle() override = default; + Triangle(Triangle &&) = default; + ~Triangle() override = default; Triangle &operator=(const Triangle &) = default; Triangle &operator=(Triangle &&) = default; diff --git a/native/cocos/core/memop/CachedArray.h b/native/cocos/core/memop/CachedArray.h index 4244094b92..b22fd4b2b9 100644 --- a/native/cocos/core/memop/CachedArray.h +++ b/native/cocos/core/memop/CachedArray.h @@ -59,7 +59,7 @@ public: } CachedArray(const CachedArray &) = delete; - CachedArray(CachedArray &&) = delete; + CachedArray(CachedArray &&) = delete; CachedArray &operator=(const CachedArray &) = delete; CachedArray &operator=(CachedArray &&) = delete; @@ -148,7 +148,7 @@ public: * @param array The given array to be appended */ void concat(const ccstd::vector &array) { - size_t freeSize = _array.capacity() - _length; + size_t freeSize = _array.capacity() - _length; size_t elementsToConcat = std::min(freeSize, array.size()); _array.insert(_array.begin() + _length, array.begin(), array.begin() + elementsToConcat); _length += elementsToConcat; @@ -165,7 +165,7 @@ public: } const uint32_t last = --_length; - _array[idx] = _array[last]; + _array[idx] = _array[last]; } /** @@ -183,7 +183,7 @@ public: } ccstd::vector _array; - uint32_t _length{0}; + uint32_t _length{0}; private: CompareFn _compareFn{nullptr}; diff --git a/native/cocos/core/memop/Pool.h b/native/cocos/core/memop/Pool.h index 7562cf8f60..adb639314d 100644 --- a/native/cocos/core/memop/Pool.h +++ b/native/cocos/core/memop/Pool.h @@ -55,8 +55,8 @@ public: } Pool(const Pool &) = delete; - Pool(Pool &&) = delete; - ~Pool() = default; + Pool(Pool &&) = delete; + ~Pool() = default; Pool &operator=(const Pool &) = delete; Pool &operator=(Pool &&) = delete; @@ -117,9 +117,9 @@ public: private: std::function _ctor{nullptr}; - uint32_t _elementsPerBatch{0}; - index_t _nextAvail{-1}; - ccstd::vector _freepool; + uint32_t _elementsPerBatch{0}; + index_t _nextAvail{-1}; + ccstd::vector _freepool; }; } // namespace memop diff --git a/native/cocos/core/memop/RecyclePool.h b/native/cocos/core/memop/RecyclePool.h index 7fc2eeaabb..fe3e2411a3 100644 --- a/native/cocos/core/memop/RecyclePool.h +++ b/native/cocos/core/memop/RecyclePool.h @@ -54,8 +54,8 @@ public: RecyclePool(const std::function &fn, uint32_t size); RecyclePool(const RecyclePool &) = delete; - RecyclePool(RecyclePool &&) = delete; - ~RecyclePool() = default; + RecyclePool(RecyclePool &&) = delete; + ~RecyclePool() = default; RecyclePool &operator=(const RecyclePool &) = delete; RecyclePool &operator=(RecyclePool &&) = delete; @@ -99,7 +99,7 @@ public: void removeAt(uint32_t idx); private: - uint32_t _count{0}; + uint32_t _count{0}; ccstd::vector _data; }; diff --git a/native/cocos/core/platform/Debug.cpp b/native/cocos/core/platform/Debug.cpp index 4cf0b35019..8691cf0ea2 100644 --- a/native/cocos/core/platform/Debug.cpp +++ b/native/cocos/core/platform/Debug.cpp @@ -27,8 +27,8 @@ THE SOFTWARE. namespace cc { namespace debug { -const ccstd::string CONSOLE_LOG = "log"; -const ccstd::string CONSOLE_WARN = "warn"; +const ccstd::string CONSOLE_LOG = "log"; +const ccstd::string CONSOLE_WARN = "warn"; const ccstd::string CONSOLE_ERROR = "error"; const ccstd::string CONSOLE_ASSET = "assert"; @@ -60,7 +60,7 @@ LogLevel getLogLevel(DebugMode mode) { ccstd::string getTypedFormatter(DebugMode mode, uint32_t id) { const ccstd::string &tag = getPrefixTag(mode); - ccstd::string msg; + ccstd::string msg; #if CC_DEBUG > 0 if (debugInfos.find(id) == debugInfos.end()) { msg = "unknown id"; @@ -77,13 +77,13 @@ ccstd::string getTypedFormatter(DebugMode mode, uint32_t id) { } void printLog(DebugMode mode, const ccstd::string &fmt, cc::any *arr, int paramsLength) { - ccstd::string msg = fmt; - const ccstd::string &prefix = getPrefixTag(mode); - LogLevel logLevel = getLogLevel(mode); + ccstd::string msg = fmt; + const ccstd::string &prefix = getPrefixTag(mode); + LogLevel logLevel = getLogLevel(mode); size_t pos; for (int i = 1; i <= paramsLength; i++) { - pos = msg.find('%'); + pos = msg.find('%'); bool needToReplace = false; if (pos != ccstd::string::npos && pos != (msg.length() - 1) && (msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) { needToReplace = true; diff --git a/native/cocos/core/platform/Debug.h b/native/cocos/core/platform/Debug.h index f62bfaa7ee..a596264f79 100644 --- a/native/cocos/core/platform/Debug.h +++ b/native/cocos/core/platform/Debug.h @@ -187,25 +187,25 @@ void printLog(DebugMode mode, const ccstd::string &fmt, cc::any *arr, int params template void logID(uint32_t id, Args... optionalParams) { - ccstd::string msg = getTypedFormatter(DebugMode::VERBOSE, id); - int size = sizeof...(optionalParams); - cc::any arr[] = {0, unpackParams(optionalParams)...}; + ccstd::string msg = getTypedFormatter(DebugMode::VERBOSE, id); + int size = sizeof...(optionalParams); + cc::any arr[] = {0, unpackParams(optionalParams)...}; printLog(DebugMode::VERBOSE, msg, arr, size); } template void warnID(uint32_t id, Args... optionalParams) { - ccstd::string msg = getTypedFormatter(DebugMode::WARN, id); - int size = sizeof...(optionalParams); - cc::any arr[] = {0, unpackParams(optionalParams)...}; + ccstd::string msg = getTypedFormatter(DebugMode::WARN, id); + int size = sizeof...(optionalParams); + cc::any arr[] = {0, unpackParams(optionalParams)...}; printLog(DebugMode::WARN, msg, arr, size); } template void errorID(uint32_t id, Args... optionalParams) { - ccstd::string msg = getTypedFormatter(DebugMode::ERROR_MODE, id); - int size = sizeof...(optionalParams); - cc::any arr[] = {0, unpackParams(optionalParams)...}; + ccstd::string msg = getTypedFormatter(DebugMode::ERROR_MODE, id); + int size = sizeof...(optionalParams); + cc::any arr[] = {0, unpackParams(optionalParams)...}; printLog(DebugMode::ERROR_MODE, msg, arr, size); } @@ -214,9 +214,9 @@ void assertID(bool condition, uint32_t id, Args... optionalParams) { if (condition) { return; } - ccstd::string msg = getTypedFormatter(DebugMode::INFO, id); - int size = sizeof...(optionalParams); - cc::any arr[] = {0, unpackParams(optionalParams)...}; + ccstd::string msg = getTypedFormatter(DebugMode::INFO, id); + int size = sizeof...(optionalParams); + cc::any arr[] = {0, unpackParams(optionalParams)...}; printLog(DebugMode::INFO, msg, arr, size); CC_ASSERT(false); } diff --git a/native/cocos/core/scene-graph/Layers.h b/native/cocos/core/scene-graph/Layers.h index 8063482008..c185284ac4 100644 --- a/native/cocos/core/scene-graph/Layers.h +++ b/native/cocos/core/scene-graph/Layers.h @@ -39,22 +39,22 @@ namespace cc { */ class Layers final { public: - Layers() = delete; + Layers() = delete; ~Layers() = delete; // built-in layers, users can use 0~19 bits, 20~31 are system preserve bits. enum class LayerList : uint32_t { - NONE = 0, + NONE = 0, IGNORE_RAYCAST = (1 << 20), - GIZMOS = (1 << 21), - EDITOR = (1 << 22), - UI_3D = (1 << 23), - SCENE_GIZMO = (1 << 24), - UI_2D = (1 << 25), + GIZMOS = (1 << 21), + EDITOR = (1 << 22), + UI_3D = (1 << 23), + SCENE_GIZMO = (1 << 24), + UI_2D = (1 << 25), PROFILER = (1 << 28), - DEFAULT = (1 << 30), - ALL = 0xffffffff, + DEFAULT = (1 << 30), + ALL = 0xffffffff, }; using Enum = LayerList; diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index e040f8eadb..033ee7edc1 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -41,24 +41,24 @@ namespace cc { // static variables -uint32_t Node::clearFrame{0}; -uint32_t Node::clearRound{1000}; -bool Node::isStatic{false}; -const uint32_t Node::TRANSFORM_ON{1 << 0}; -const uint32_t Node::DESTROYING{static_cast(CCObject::Flags::DESTROYING)}; -const uint32_t Node::DEACTIVATING{static_cast(CCObject::Flags::DEACTIVATING)}; -const uint32_t Node::DONT_DESTROY{static_cast(CCObject::Flags::DONT_DESTROY)}; -index_t Node::stackId{0}; +uint32_t Node::clearFrame{0}; +uint32_t Node::clearRound{1000}; +bool Node::isStatic{false}; +const uint32_t Node::TRANSFORM_ON{1 << 0}; +const uint32_t Node::DESTROYING{static_cast(CCObject::Flags::DESTROYING)}; +const uint32_t Node::DEACTIVATING{static_cast(CCObject::Flags::DEACTIVATING)}; +const uint32_t Node::DONT_DESTROY{static_cast(CCObject::Flags::DONT_DESTROY)}; +index_t Node::stackId{0}; ccstd::vector> Node::stacks; // namespace { CachedArray allNodes{128}; //cjh how to clear ? const ccstd::string EMPTY_NODE_NAME; -IDGenerator idGenerator("Node"); +IDGenerator idGenerator("Node"); ccstd::vector dirtyNodes; -CC_FORCE_INLINE void setDirtyNode(const index_t idx, Node *node) { +CC_FORCE_INLINE void setDirtyNode(const index_t idx, Node *node) { if (idx >= dirtyNodes.size()) { if (idx >= dirtyNodes.capacity()) { size_t minCapacity = std::max((idx + 1) * 2, 32); @@ -132,7 +132,7 @@ Node *Node::instantiate(Node *cloned, bool isSyncedNode) { void Node::onHierarchyChangedBase(Node *oldParent) { // NOLINT(misc-unused-parameters) Node *newParent = _parent; - auto *scene = dynamic_cast(newParent); + auto *scene = dynamic_cast(newParent); if (isPersistNode() && scene == nullptr) { emit(EventTypesToJS::NODE_REMOVE_PERSIST_ROOT_NODE); #if CC_EDITOR @@ -140,9 +140,9 @@ void Node::onHierarchyChangedBase(Node *oldParent) { // NOLINT(misc-unused-param #endif } #if CC_EDITOR - auto * curScene = getScene(); + auto *curScene = getScene(); const bool inCurrentSceneBefore = oldParent && oldParent->isChildOf(curScene); - const bool inCurrentSceneNow = newParent && newParent->isChildOf(curScene); + const bool inCurrentSceneNow = newParent && newParent->isChildOf(curScene); if (!inCurrentSceneBefore && inCurrentSceneNow) { // attached this->notifyEditorAttached(true); @@ -218,7 +218,7 @@ void Node::targetOff(const CallbacksInvoker::KeyType &type) { void Node::setActive(bool isActive) { if (_active != isActive) { - _active = isActive; + _active = isActive; Node *parent = _parent; if (parent) { bool couldActiveInScene = parent->isActiveInHierarchy(); @@ -246,7 +246,7 @@ void Node::setParent(Node *parent, bool isKeepWorld /* = false */) { debug::errorID(3821); } #endif - _parent = newParent; + _parent = newParent; _siblingIndex = 0; onSetParent(oldParent, isKeepWorld); emit(NodeEventType::PARENT_CHANGED, oldParent); @@ -288,11 +288,11 @@ void Node::walk(const std::function &preFunc) { } void Node::walk(const std::function &preFunc, const std::function &postFunc) { - index_t index{1}; - index_t i{0}; + index_t index{1}; + index_t i{0}; const ccstd::vector> *children = nullptr; - Node * curr{nullptr}; - auto stacksCount = static_cast(Node::stacks.size()); + Node *curr{nullptr}; + auto stacksCount = static_cast(Node::stacks.size()); if (stackId >= stacksCount) { stacks.resize(stackId + 1); } @@ -303,7 +303,7 @@ void Node::walk(const std::function &preFunc, const std::function< stack.resize(1); stack[0] = this; Node *parent{nullptr}; - bool afterChildren{false}; + bool afterChildren{false}; while (index) { index--; auto stackCount = static_cast(stack.size()); @@ -329,9 +329,9 @@ void Node::walk(const std::function &preFunc, const std::function< afterChildren = false; } else { if (static_cast(curr->_children.size()) > 0) { - parent = curr; - children = &curr->_children; - i = 0; + parent = curr; + children = &curr->_children; + i = 0; stack[index] = (*children)[i]; stack.resize(++index); } else { @@ -352,7 +352,7 @@ void Node::walk(const std::function &preFunc, const std::function< stack.resize(++index); afterChildren = true; if (parent->_parent != nullptr) { - children = &parent->_parent->_children; + children = &parent->_parent->_children; index_t idx = getIdxOfChild(*children, parent); if (idx != CC_INVALID_INDEX) { i = idx; @@ -360,7 +360,7 @@ void Node::walk(const std::function &preFunc, const std::function< parent = parent->_parent; } else { // At root - parent = nullptr; + parent = nullptr; children = nullptr; } if (i < 0) { @@ -500,8 +500,8 @@ void Node::setSiblingIndex(index_t index) { return; } ccstd::vector> &siblings = _parent->_children; - index = index != -1 ? index : static_cast(siblings.size()) - 1; - index_t oldIdx = getIdxOfChild(siblings, this); + index = index != -1 ? index : static_cast(siblings.size()) - 1; + index_t oldIdx = getIdxOfChild(siblings, this); if (index != oldIdx) { if (oldIdx != CC_INVALID_INDEX) { siblings.erase(siblings.begin() + oldIdx); @@ -519,9 +519,9 @@ void Node::setSiblingIndex(index_t index) { } Node *Node::getChildByPath(const ccstd::string &path) const { - size_t end = 0; + size_t end = 0; ccstd::vector segments = StringUtil::split(path, "/"); - auto * lastNode = const_cast(this); + auto *lastNode = const_cast(this); for (const ccstd::string &segment : segments) { if (segment.empty()) { continue; @@ -602,16 +602,16 @@ void Node::updateWorldTransform() { //NOLINT(misc-no-recursion) return; } - index_t i = 0; - Node * curr = this; - Mat3 mat3; - Mat3 m43; + index_t i = 0; + Node *curr = this; + Mat3 mat3; + Mat3 m43; Quaternion quat; while (curr && curr->getDirtyFlag()) { setDirtyNode(i++, curr); curr = curr->getParent(); } - Node * child{nullptr}; + Node *child{nullptr}; uint32_t dirtyBits = 0; while (i) { child = getDirtyNode(--i); @@ -682,7 +682,7 @@ Mat4 Node::getWorldRT() { } void Node::invalidateChildren(TransformBit dirtyBit) { - auto curDirtyBit{static_cast(dirtyBit)}; + auto curDirtyBit{static_cast(dirtyBit)}; const uint32_t childDirtyBit{curDirtyBit | static_cast(TransformBit::POSITION)}; setDirtyNode(0, this); int i{0}; @@ -841,7 +841,7 @@ void Node::rotate(const Quaternion &rot, NodeSpace ns /* = NodeSpace::LOCAL*/, b qTempB = qTempA * _worldRotation; qTempA = _worldRotation; qTempA.inverse(); - qTempB = qTempA * qTempB; + qTempB = qTempA * qTempB; _localRotation = _localRotation * qTempB; } _eulerDirty = true; @@ -856,7 +856,7 @@ void Node::rotate(const Quaternion &rot, NodeSpace ns /* = NodeSpace::LOCAL*/, b } void Node::lookAt(const Vec3 &pos, const Vec3 &up) { - Vec3 vTemp = getWorldPosition(); + Vec3 vTemp = getWorldPosition(); Quaternion qTemp{Quaternion::identity()}; vTemp -= pos; vTemp.normalize(); @@ -866,7 +866,7 @@ void Node::lookAt(const Vec3 &pos, const Vec3 &up) { void Node::inverseTransformPoint(Vec3 &out, const Vec3 &p) { out.set(p.x, p.y, p.z); - Node * cur{this}; + Node *cur{this}; index_t i{0}; while (cur != nullptr && cur->getParent()) { setDirtyNode(i++, cur); @@ -913,7 +913,7 @@ void Node::setRTSInternal(Quaternion *rot, Vec3 *pos, Vec3 *scale, bool calledFr if (rot) { dirtyBit |= static_cast(TransformBit::ROTATION); _localRotation = *rot; - _eulerDirty = true; + _eulerDirty = true; } if (pos) { _localPosition = *pos; diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index 40d3113922..2e18af472b 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -78,9 +78,9 @@ public: static Node *instantiate(Node *cloned, bool isSyncedNode); // for walk static ccstd::vector> stacks; - static index_t stackId; + static index_t stackId; - static void setScene(Node *); + static void setScene(Node *); static index_t getIdxOfChild(const ccstd::vector> &, Node *); static bool isStatic; // cjh TODO: add getter / setter @@ -190,7 +190,7 @@ public: void off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); template - void emit(const CallbacksInvoker::KeyType &type, Args &&...args); + void emit(const CallbacksInvoker::KeyType &type, Args &&... args); // void dispatchEvent(event::Event *event); bool hasEventListener(const CallbacksInvoker::KeyType &type) const; @@ -260,26 +260,26 @@ public: inline void setActiveInHierarchy(bool v) { _activeInHierarchyArr[0] = (v ? 1 : 0); } inline void setActiveInHierarchyPtr(uint8_t *ptr) { _activeInHierarchyArr = ptr; } - virtual void onPostActivated(bool active) {} + virtual void onPostActivated(bool active) {} inline const ccstd::vector> &getChildren() const { return _children; } - inline Node * getParent() const { return _parent; } - inline NodeEventProcessor * getEventProcessor() const { return _eventProcessor; } + inline Node *getParent() const { return _parent; } + inline NodeEventProcessor *getEventProcessor() const { return _eventProcessor; } - Node * getChildByUuid(const ccstd::string &) const; - Node * getChildByName(const ccstd::string &) const; - Node * getChildByPath(const ccstd::string &) const; - inline index_t getSiblingIndex() const { return _siblingIndex; } + Node *getChildByUuid(const ccstd::string &) const; + Node *getChildByName(const ccstd::string &) const; + Node *getChildByPath(const ccstd::string &) const; + inline index_t getSiblingIndex() const { return _siblingIndex; } inline UserData *getUserData() { return _userData.get(); } - inline void setUserData(UserData *data) { _userData = data; } - inline void insertChild(Node *child, index_t siblingIndex) { + inline void setUserData(UserData *data) { _userData = data; } + inline void insertChild(Node *child, index_t siblingIndex) { child->setParent(this); child->setSiblingIndex(siblingIndex); } void invalidateChildren(TransformBit dirtyBit); - void translate(const Vec3 &, NodeSpace ns = NodeSpace::LOCAL); - void rotate(const Quaternion &rot, NodeSpace ns = NodeSpace::LOCAL, bool calledFromJS = false); + void translate(const Vec3 &, NodeSpace ns = NodeSpace::LOCAL); + void rotate(const Quaternion &rot, NodeSpace ns = NodeSpace::LOCAL, bool calledFromJS = false); inline void rotateForJS(float x, float y, float z, float w, NodeSpace ns = NodeSpace::LOCAL) { rotate(Quaternion(x, y, z, w), ns, true); } @@ -301,7 +301,7 @@ public: inline void setPosition(float x, float y) { setPosition(x, y, _localPosition.z); } inline void setPosition(float x, float y, float z) { setPositionInternal(x, y, z, false); } inline void setPositionInternal(float x, float y, bool calledFromJS) { setPositionInternal(x, y, _localPosition.z, calledFromJS); } - void setPositionInternal(float x, float y, float z, bool calledFromJS); + void setPositionInternal(float x, float y, float z, bool calledFromJS); inline void setPositionForJS(float x, float y, float z) { _localPosition.set(x, y, z); } /** * @en Get position in local coordinate system, please try to pass `out` vector and reuse it to avoid garbage. @@ -318,13 +318,13 @@ public: */ inline void setRotation(const Quaternion &rotation) { setRotation(rotation.x, rotation.y, rotation.z, rotation.w); } inline void setRotation(float x, float y, float z, float w) { setRotationInternal(x, y, z, w, false); } - void setRotationInternal(float x, float y, float z, float w, bool calledFromJS); + void setRotationInternal(float x, float y, float z, float w, bool calledFromJS); inline void setRotationForJS(float x, float y, float z, float w) { _localRotation.set(x, y, z, w); } inline void setEulerAngles(const Vec3 &val) { setRotationFromEuler(val.x, val.y, val.z); } inline void setRotationFromEuler(const Vec3 &val) { setRotationFromEuler(val.x, val.y, val.z); } inline void setRotationFromEuler(float x, float y) { setRotationFromEuler(x, y, _euler.z); } - void setRotationFromEuler(float x, float y, float z); + void setRotationFromEuler(float x, float y, float z); inline void setRotationFromEulerForJS(float x, float y, float z) { _euler.set(x, y, z); } /** * @en Get rotation as quaternion in local coordinate system, please try to pass `out` quaternion and reuse it to avoid garbage. @@ -343,7 +343,7 @@ public: inline void setScale(float x, float y) { setScale(x, y, _localScale.z); } inline void setScale(float x, float y, float z) { setScaleInternal(x, y, z, false); } inline void setScaleInternal(float x, float y, bool calledFromJS) { setScaleInternal(x, y, _localScale.z, calledFromJS); } - void setScaleInternal(float x, float y, float z, bool calledFromJS); + void setScaleInternal(float x, float y, float z, bool calledFromJS); inline void setScaleForJS(float x, float y, float z) { _localScale.set(x, y, z); } /** * @en Get scale in local coordinate system, please try to pass `out` vector and reuse it to avoid garbage. @@ -367,7 +367,7 @@ public: * @param position Target position */ inline void setWorldPosition(const Vec3 &pos) { setWorldPosition(pos.x, pos.y, pos.z); } - void setWorldPosition(float x, float y, float z); + void setWorldPosition(float x, float y, float z); /** * @en Get position in world coordinate system, please try to pass `out` vector and reuse it to avoid garbage. @@ -383,7 +383,7 @@ public: * @param rotation Rotation in quaternion */ inline void setWorldRotation(const Quaternion &rotation) { setWorldRotation(rotation.x, rotation.y, rotation.z, rotation.w); } - void setWorldRotation(float x, float y, float z, float w); + void setWorldRotation(float x, float y, float z, float w); /** * @en Get rotation as quaternion in world coordinate system, please try to pass `out` quaternion and reuse it to avoid garbage. * @zh 获取世界坐标系下的旋转,注意,尽可能传递复用的 [[Quat]] 以避免产生垃圾。 @@ -400,7 +400,7 @@ public: * @param z Z axis rotation */ inline void setWorldScale(const Vec3 &scale) { setWorldScale(scale.x, scale.y, scale.z); } - void setWorldScale(float x, float y, float z); + void setWorldScale(float x, float y, float z); /** * @en Get scale in world coordinate system, please try to pass `out` vector and reuse it to avoid garbage. @@ -455,13 +455,13 @@ public: * @param pos The position * @param scale The scale */ - void setRTSInternal(Quaternion *rot, Vec3 *pos, Vec3 *scale, bool calledFromJS); + void setRTSInternal(Quaternion *rot, Vec3 *pos, Vec3 *scale, bool calledFromJS); inline void setRTS(Quaternion *rot, Vec3 *pos, Vec3 *scale) { setRTSInternal(rot, pos, scale, false); } inline void setForward(const Vec3 &dir) { - const float len = dir.length(); - Vec3 v3Temp = dir * (-1.F / len); - Quaternion qTemp{Quaternion::identity()}; + const float len = dir.length(); + Vec3 v3Temp = dir * (-1.F / len); + Quaternion qTemp{Quaternion::identity()}; Quaternion::fromViewUp(v3Temp, &qTemp); setWorldRotation(qTemp); } @@ -502,16 +502,16 @@ public: * @zh 这个节点的空间变换信息在当前帧内是否有变过? */ inline uint32_t getChangedFlags() const { return _flagChange; } - inline void setChangedFlags(uint32_t value) { _flagChange = value; } + inline void setChangedFlags(uint32_t value) { _flagChange = value; } - inline void setDirtyFlag(uint32_t value) { _dirtyFlag = value; } + inline void setDirtyFlag(uint32_t value) { _dirtyFlag = value; } inline uint32_t getDirtyFlag() const { return _dirtyFlag; } - inline void setLayer(uint32_t layer) { + inline void setLayer(uint32_t layer) { _layerArr[0] = layer; emit(NodeEventType::LAYER_CHANGED, layer); } inline uint32_t getLayer() const { return _layerArr[0]; } - inline void setLayerPtr(uint32_t *ptr) { _layerArr = ptr; } + inline void setLayerPtr(uint32_t *ptr) { _layerArr = ptr; } // inline NodeUiProperties *getUIProps() const { return _uiProps.get(); } @@ -613,7 +613,7 @@ public: void _setChildren(ccstd::vector> &&children); // NOLINT // For JS wrapper. inline uint32_t getEventMask() const { return _eventMask; } - inline void setEventMask(uint32_t mask) { _eventMask = mask; } + inline void setEventMask(uint32_t mask) { _eventMask = mask; } protected: bool onPreDestroy() override; @@ -659,12 +659,12 @@ private: } protected: - Scene * _scene{nullptr}; + Scene *_scene{nullptr}; NodeEventProcessor *_eventProcessor{nullptr}; uint32_t _eventMask{0}; - Mat4 _rtMat{Mat4::IDENTITY}; + Mat4 _rtMat{Mat4::IDENTITY}; cc::Mat4 _worldMatrix{Mat4::IDENTITY}; uint32_t _flagChange{0}; @@ -674,27 +674,27 @@ protected: // IntrusivePtr _uiProps; // bool _activeInHierarchy{false}; // Shared memory with JS. - uint8_t * _activeInHierarchyArr{nullptr}; + uint8_t *_activeInHierarchyArr{nullptr}; uint32_t *_layerArr{nullptr}; public: std::function onSiblingIndexChanged{nullptr}; - index_t _siblingIndex{0}; + index_t _siblingIndex{0}; // For deserialization - ccstd::string _id; + ccstd::string _id; ccstd::vector> _children; - Node * _parent{nullptr}; - bool _active{true}; + Node *_parent{nullptr}; + bool _active{true}; private: // local transform - cc::Vec3 _localPosition{Vec3::ZERO}; + cc::Vec3 _localPosition{Vec3::ZERO}; cc::Quaternion _localRotation{Quaternion::identity()}; - cc::Vec3 _localScale{Vec3::ONE}; + cc::Vec3 _localScale{Vec3::ONE}; // world transform - cc::Vec3 _worldPosition{Vec3::ZERO}; + cc::Vec3 _worldPosition{Vec3::ZERO}; cc::Quaternion _worldRotation{Quaternion::identity()}; - cc::Vec3 _worldScale{Vec3::ONE}; + cc::Vec3 _worldScale{Vec3::ONE}; // Vec3 _euler{0, 0, 0}; @@ -716,7 +716,7 @@ bool Node::isNode(T *obj) { } template -void Node::emit(const CallbacksInvoker::KeyType &type, Args &&...args) { +void Node::emit(const CallbacksInvoker::KeyType &type, Args &&... args) { _eventProcessor->emit(type, std::forward(args)...); } diff --git a/native/cocos/core/scene-graph/NodeEnum.h b/native/cocos/core/scene-graph/NodeEnum.h index a825b59912..a1b8481098 100644 --- a/native/cocos/core/scene-graph/NodeEnum.h +++ b/native/cocos/core/scene-graph/NodeEnum.h @@ -34,12 +34,12 @@ enum class NodeSpace { }; enum class TransformBit : uint32_t { - NONE = 0, + NONE = 0, POSITION = (1 << 0), ROTATION = (1 << 1), - SCALE = (1 << 2), - RS = ROTATION | SCALE, - TRS = POSITION | ROTATION | SCALE, + SCALE = (1 << 2), + RS = ROTATION | SCALE, + TRS = POSITION | ROTATION | SCALE, TRS_MASK = ~TRS, }; CC_ENUM_BITWISE_OPERATORS(TransformBit); diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.cpp b/native/cocos/core/scene-graph/NodeEventProcessor.cpp index 55f1142b7c..22003195ca 100644 --- a/native/cocos/core/scene-graph/NodeEventProcessor.cpp +++ b/native/cocos/core/scene-graph/NodeEventProcessor.cpp @@ -33,8 +33,8 @@ namespace { ccstd::vector cachedArray(16); -cc::Node * currentHovered = nullptr; -cc::Vec2 pos; +cc::Node *currentHovered = nullptr; +cc::Vec2 pos; //bool touchStartHandler(cc::event::EventListener *listener, cc::event::Touch *touch, cc::event::Event *event) { // auto *touchEvent = static_cast(event); diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.h b/native/cocos/core/scene-graph/NodeEventProcessor.h index 777fb1ce7a..507aecd107 100644 --- a/native/cocos/core/scene-graph/NodeEventProcessor.h +++ b/native/cocos/core/scene-graph/NodeEventProcessor.h @@ -57,8 +57,8 @@ public: ~NodeEventProcessor(); inline Node *getNode() { return _node; } - void reattach(); - void destroy(); + void reattach(); + void destroy(); /** * @zh @@ -130,7 +130,7 @@ public: * @param args - The arguments to be passed to the callback */ template - void emit(const CallbacksInvoker::KeyType &type, Args &&...args); + void emit(const CallbacksInvoker::KeyType &type, Args &&... args); void targetOff(const CallbacksInvoker::KeyType &target); @@ -190,7 +190,7 @@ private: }; template -void NodeEventProcessor::emit(const CallbacksInvoker::KeyType &type, Args &&...args) { +void NodeEventProcessor::emit(const CallbacksInvoker::KeyType &type, Args &&... args) { if (_bubblingTargets != nullptr) { _bubblingTargets->emit(type, std::forward(args)...); } diff --git a/native/cocos/core/scene-graph/Scene.cpp b/native/cocos/core/scene-graph/Scene.cpp index 801012d242..a21f746fa8 100644 --- a/native/cocos/core/scene-graph/Scene.cpp +++ b/native/cocos/core/scene-graph/Scene.cpp @@ -36,7 +36,7 @@ Scene::Scene(const ccstd::string &name) // _activeInHierarchy is initalized to 'false', so doesn't need to set it to false again // _activeInHierarchy = false; _renderScene = Root::getInstance()->createScene({}); - _globals = ccnew SceneGlobals(); + _globals = ccnew SceneGlobals(); } Scene::Scene() : Scene("") {} diff --git a/native/cocos/core/scene-graph/Scene.h b/native/cocos/core/scene-graph/Scene.h index 0887da489e..73b5aba298 100644 --- a/native/cocos/core/scene-graph/Scene.h +++ b/native/cocos/core/scene-graph/Scene.h @@ -41,10 +41,10 @@ public: ~Scene() override; inline scene::RenderScene *getRenderScene() const { return _renderScene; } - inline SceneGlobals * getSceneGlobals() const { return _globals.get(); } - void setSceneGlobals(SceneGlobals *globals); - inline bool isAutoReleaseAssets() const { return _autoReleaseAssets; } - inline void setAutoReleaseAssets(bool val) { _autoReleaseAssets = val; } + inline SceneGlobals *getSceneGlobals() const { return _globals.get(); } + void setSceneGlobals(SceneGlobals *globals); + inline bool isAutoReleaseAssets() const { return _autoReleaseAssets; } + inline void setAutoReleaseAssets(bool val) { _autoReleaseAssets = val; } void load(); void activate(bool active = true); @@ -62,7 +62,7 @@ protected: */ // @serializable IntrusivePtr _globals; - bool _inited{false}; + bool _inited{false}; /** * @en Indicates whether all (directly or indirectly) static referenced assets of this scene are releasable by default after scene unloading. diff --git a/native/cocos/core/scene-graph/SceneGlobals.cpp b/native/cocos/core/scene-graph/SceneGlobals.cpp index 983af8fcd0..121fd27b2a 100644 --- a/native/cocos/core/scene-graph/SceneGlobals.cpp +++ b/native/cocos/core/scene-graph/SceneGlobals.cpp @@ -37,10 +37,10 @@ namespace cc { SceneGlobals::SceneGlobals() { _ambientInfo = ccnew scene::AmbientInfo(); - _shadowInfo = ccnew scene::ShadowsInfo(); - _skyboxInfo = ccnew scene::SkyboxInfo(); - _fogInfo = ccnew scene::FogInfo(); - _octreeInfo = ccnew scene::OctreeInfo(); + _shadowInfo = ccnew scene::ShadowsInfo(); + _skyboxInfo = ccnew scene::SkyboxInfo(); + _fogInfo = ccnew scene::FogInfo(); + _octreeInfo = ccnew scene::OctreeInfo(); } void SceneGlobals::activate() { diff --git a/native/cocos/core/scene-graph/SceneGlobals.h b/native/cocos/core/scene-graph/SceneGlobals.h index c7f8346fe7..13e0e79cca 100644 --- a/native/cocos/core/scene-graph/SceneGlobals.h +++ b/native/cocos/core/scene-graph/SceneGlobals.h @@ -47,9 +47,9 @@ public: inline scene::AmbientInfo *getAmbientInfo() const { return _ambientInfo.get(); } inline scene::ShadowsInfo *getShadowsInfo() const { return _shadowInfo.get(); } - inline scene::SkyboxInfo * getSkyboxInfo() const { return _skyboxInfo.get(); } - inline scene::FogInfo * getFogInfo() const { return _fogInfo.get(); } - inline scene::OctreeInfo * getOctreeInfo() const { return _octreeInfo.get(); } + inline scene::SkyboxInfo *getSkyboxInfo() const { return _skyboxInfo.get(); } + inline scene::FogInfo *getFogInfo() const { return _fogInfo.get(); } + inline scene::OctreeInfo *getOctreeInfo() const { return _octreeInfo.get(); } void setAmbientInfo(scene::AmbientInfo *info); void setShadowsInfo(scene::ShadowsInfo *info); @@ -60,9 +60,9 @@ public: private: IntrusivePtr _ambientInfo; IntrusivePtr _shadowInfo; - IntrusivePtr _skyboxInfo; - IntrusivePtr _fogInfo; - IntrusivePtr _octreeInfo; + IntrusivePtr _skyboxInfo; + IntrusivePtr _fogInfo; + IntrusivePtr _octreeInfo; }; } // namespace cc diff --git a/native/cocos/core/utils/IDGenerator.cpp b/native/cocos/core/utils/IDGenerator.cpp index a2e50e2e8d..cf0abff656 100644 --- a/native/cocos/core/utils/IDGenerator.cpp +++ b/native/cocos/core/utils/IDGenerator.cpp @@ -10,7 +10,7 @@ IDGenerator globalIdGenerator("global"); IDGenerator::IDGenerator(const ccstd::string &category) { // Tnit with a random id to emphasize that the returns id should not be stored in persistence data. - _id = static_cast(RandomHelper::randomInt(0, 998)); + _id = static_cast(RandomHelper::randomInt(0, 998)); _prefix = (category + nonUuidMark); } @@ -18,7 +18,7 @@ ccstd::string IDGenerator::getNewId() { #if CC_EDITOR if (_prefix == "Node." || _prefix == "Comp.") { static boost::uuids::random_generator_mt19937 generator; - boost::uuids::uuid id = generator(); + boost::uuids::uuid id = generator(); return boost::uuids::to_string(id); } #endif diff --git a/native/cocos/core/utils/ImageUtils.cpp b/native/cocos/core/utils/ImageUtils.cpp index fe1c16f332..51ff964ed5 100644 --- a/native/cocos/core/utils/ImageUtils.cpp +++ b/native/cocos/core/utils/ImageUtils.cpp @@ -30,7 +30,7 @@ namespace { uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src++; + dst[i] = *src++; dst[i + 1] = *src++; dst[i + 2] = *src++; dst[i + 3] = 255; @@ -41,7 +41,7 @@ uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src; + dst[i] = *src; dst[i + 1] = *src; dst[i + 2] = *src++; dst[i + 3] = *src++; @@ -52,7 +52,7 @@ uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { - dst[i] = *src; + dst[i] = *src; dst[i + 1] = *src; dst[i + 2] = *src++; dst[i + 3] = 255; @@ -65,9 +65,9 @@ namespace cc { void ImageUtils::convert2RGBA(Image *image) { if (!image->_isCompressed && image->_renderFormat != gfx::Format::RGBA8) { image->_dataLen = image->_width * image->_height * 4; - uint8_t *dst = nullptr; + uint8_t *dst = nullptr; uint32_t length = static_cast(image->_dataLen); - uint8_t *src = image->_data; + uint8_t *src = image->_data; switch (image->_renderFormat) { case gfx::Format::A8: case gfx::Format::LA8: @@ -86,7 +86,7 @@ void ImageUtils::convert2RGBA(Image *image) { break; } if (dst != image->_data) free(image->_data); - image->_data = dst; + image->_data = dst; image->_renderFormat = gfx::Format::RGBA8; } } diff --git a/native/cocos/core/utils/MutableForwardIterator.cpp b/native/cocos/core/utils/MutableForwardIterator.cpp index a8bb576af0..f0e9e4c248 100644 --- a/native/cocos/core/utils/MutableForwardIterator.cpp +++ b/native/cocos/core/utils/MutableForwardIterator.cpp @@ -9,7 +9,7 @@ namespace cc { void MutableForwardIteratorTest() { using namespace cc; - ccstd::vector myarr{1, 2, 3, 43, 4, 5}; + ccstd::vector myarr{1, 2, 3, 43, 4, 5}; MutableForwardIterator iter{myarr}; iter.fastRemoveAt(2); diff --git a/native/cocos/core/utils/MutableForwardIterator.h b/native/cocos/core/utils/MutableForwardIterator.h index a943c18375..8a7430766b 100644 --- a/native/cocos/core/utils/MutableForwardIterator.h +++ b/native/cocos/core/utils/MutableForwardIterator.h @@ -102,7 +102,7 @@ public: array.emplace_back(std::forward(item)); } - int32_t i = 0; + int32_t i = 0; ccstd::vector &array; }; diff --git a/native/cocos/core/utils/Path.cpp b/native/cocos/core/utils/Path.cpp index 1e8dbd11d8..428facbc13 100644 --- a/native/cocos/core/utils/Path.cpp +++ b/native/cocos/core/utils/Path.cpp @@ -65,7 +65,7 @@ ccstd::string extname(const ccstd::string &path) { } ccstd::string newPath = path; - size_t index = path.find_first_of('?'); + size_t index = path.find_first_of('?'); if (index != ccstd::string::npos && index > 0) { newPath = newPath.substr(0, index); } @@ -91,7 +91,7 @@ ccstd::string mainFileName(const ccstd::string &fileName) { ccstd::string basename(const ccstd::string &path, const ccstd::string &extName /* = ""*/) { ccstd::string newPath = path; - size_t index = path.find_first_of('?'); + size_t index = path.find_first_of('?'); if (index != ccstd::string::npos && index > 0) { newPath = newPath.substr(0, index); } @@ -106,7 +106,7 @@ ccstd::string basename(const ccstd::string &path, const ccstd::string &extName / ccstd::string baseName = newPath.substr(index + 1); if (!extName.empty() && extName.length() < newPath.length()) { - ccstd::string extInPath = newPath.substr(newPath.length() - extName.length()); + ccstd::string extInPath = newPath.substr(newPath.length() - extName.length()); ccstd::string expectedExtName = extName; if (StringUtil::tolower(extInPath) == StringUtil::tolower(expectedExtName)) { baseName = baseName.substr(0, baseName.length() - extName.length()); @@ -128,7 +128,7 @@ ccstd::string dirname(const ccstd::string &path) { } ccstd::string changeExtname(const ccstd::string &path, const ccstd::string &extName /* = ""*/) { - size_t index = path.find_first_of('?'); + size_t index = path.find_first_of('?'); ccstd::string newPath = path; ccstd::string tempStr; if (index != ccstd::string::npos && index > 0) { @@ -149,10 +149,10 @@ ccstd::string changeBasename(const ccstd::string &path, const ccstd::string &bas return changeExtname(path, baseName); } - size_t index = path.find_last_of('?'); - ccstd::string tempStr; - ccstd::string newPath = path; - const ccstd::string ext = isSameExt ? extname(path) : ""; + size_t index = path.find_last_of('?'); + ccstd::string tempStr; + ccstd::string newPath = path; + const ccstd::string ext = isSameExt ? extname(path) : ""; if (index != ccstd::string::npos && index > 0) { tempStr = path.substr(index); newPath = path.substr(0, index); @@ -174,12 +174,12 @@ ccstd::string normalize(const ccstd::string &url) { // remove all ../ do { - oldUrl = newUrl; + oldUrl = newUrl; size_t index = newUrl.find("../"); if (index == ccstd::string::npos) { index = newUrl.find("..\\"); } - size_t previousSlashIndex = ccstd::string::npos; + size_t previousSlashIndex = ccstd::string::npos; size_t previousTwiceSlashIndex = ccstd::string::npos; if (index != ccstd::string::npos && index > 0) { previousSlashIndex = newUrl.find_last_of("/\\", index - 1); diff --git a/native/cocos/core/utils/Pool.h b/native/cocos/core/utils/Pool.h index 797898a5b9..2af13081e9 100644 --- a/native/cocos/core/utils/Pool.h +++ b/native/cocos/core/utils/Pool.h @@ -136,7 +136,7 @@ public: T _get() { //NOLINT(readability-identifier-naming) if (_count > 0) { --_count; - T cache = _pool[_count]; + T cache = _pool[_count]; _pool[_count] = nullptr; return cache; } @@ -174,7 +174,7 @@ public: private: ccstd::vector _pool; - CleanUpFunction _cleanup{nullptr}; + CleanUpFunction _cleanup{nullptr}; /** * @en diff --git a/native/cocos/editor-support/IOBuffer.cpp b/native/cocos/editor-support/IOBuffer.cpp index e56b08c62e..3457a5962d 100644 --- a/native/cocos/editor-support/IOBuffer.cpp +++ b/native/cocos/editor-support/IOBuffer.cpp @@ -35,9 +35,9 @@ void IOBuffer::resize(std::size_t newLen, bool needCopy) { } delete[] _buffer; - _buffer = newBuffer; + _buffer = newBuffer; _bufferSize = newLen; - _outRange = false; + _outRange = false; } } diff --git a/native/cocos/editor-support/IOBuffer.h b/native/cocos/editor-support/IOBuffer.h index e534061618..bb54f9d403 100644 --- a/native/cocos/editor-support/IOBuffer.h +++ b/native/cocos/editor-support/IOBuffer.h @@ -44,7 +44,7 @@ class IOBuffer { public: explicit IOBuffer(std::size_t defaultSize) { _bufferSize = defaultSize; - _buffer = new uint8_t[_bufferSize]; + _buffer = new uint8_t[_bufferSize]; } IOBuffer() = default; @@ -62,7 +62,7 @@ public: return; } auto *buffer = reinterpret_cast(_buffer + pos); - *buffer = val; + *buffer = val; } inline void writeFloat32(std::size_t pos, float val) { @@ -71,7 +71,7 @@ public: return; } auto *buffer = reinterpret_cast(_buffer + pos); - *buffer = val; + *buffer = val; } inline void writeBytes(const char *bytes, std::size_t bytesLen) { @@ -89,7 +89,7 @@ public: return; } auto *buffer = reinterpret_cast(_buffer + _curPos); - *buffer = val; + *buffer = val; _curPos += sizeof(val); } @@ -99,7 +99,7 @@ public: return; } auto *buffer = reinterpret_cast(_buffer + _curPos); - *buffer = val; + *buffer = val; _curPos += sizeof(val); } @@ -109,7 +109,7 @@ public: return; } auto *buffer = reinterpret_cast(_buffer + _curPos); - *buffer = val; + *buffer = val; _curPos += sizeof(val); } @@ -138,7 +138,7 @@ public: } inline void reset() { - _curPos = 0; + _curPos = 0; _readPos = 0; } @@ -180,7 +180,7 @@ public: inline int checkSpace(std::size_t needSize, bool needCopy = false) { auto needLen = _curPos + needSize; - auto isFull = 0; + auto isFull = 0; if (_maxSize > 0 && needLen > _maxSize) { isFull = 1; if (_fullCallback) { @@ -222,13 +222,13 @@ public: virtual void resize(std::size_t newLen, bool needCopy); protected: - uint8_t * _buffer = nullptr; - std::size_t _bufferSize = 0; - std::size_t _curPos = 0; - std::size_t _readPos = 0; - bool _outRange = false; - std::size_t _maxSize = 0; - fullCallback _fullCallback = nullptr; + uint8_t *_buffer = nullptr; + std::size_t _bufferSize = 0; + std::size_t _curPos = 0; + std::size_t _readPos = 0; + bool _outRange = false; + std::size_t _maxSize = 0; + fullCallback _fullCallback = nullptr; resizeCallback _resizeCallback = nullptr; }; diff --git a/native/cocos/editor-support/IOTypedArray.cpp b/native/cocos/editor-support/IOTypedArray.cpp index 681b573221..5e7fecb941 100644 --- a/native/cocos/editor-support/IOTypedArray.cpp +++ b/native/cocos/editor-support/IOTypedArray.cpp @@ -31,9 +31,9 @@ MIDDLEWARE_BEGIN IOTypedArray::IOTypedArray(se::Object::TypedArrayType arrayType, std::size_t defaultSize, bool usePool) { - _arrayType = arrayType; + _arrayType = arrayType; _bufferSize = defaultSize; - _usePool = usePool; + _usePool = usePool; if (_usePool) { _typeArray = TypedArrayPool::getInstance()->pop(_arrayType, _bufferSize); @@ -55,7 +55,7 @@ IOTypedArray::~IOTypedArray() { _typeArray->decRef(); } _typeArray = nullptr; - _buffer = nullptr; + _buffer = nullptr; } void IOTypedArray::resize(std::size_t newLen, bool needCopy) { @@ -71,7 +71,7 @@ void IOTypedArray::resize(std::size_t newLen, bool needCopy) { newTypeBuffer->root(); } - uint8_t * newBuffer = nullptr; + uint8_t *newBuffer = nullptr; se::AutoHandleScope hs; newTypeBuffer->getTypedArrayData(&newBuffer, static_cast(&newLen)); @@ -86,10 +86,10 @@ void IOTypedArray::resize(std::size_t newLen, bool needCopy) { _typeArray->decRef(); } - _typeArray = newTypeBuffer; - _buffer = newBuffer; + _typeArray = newTypeBuffer; + _buffer = newBuffer; _bufferSize = newLen; - _outRange = false; + _outRange = false; } MIDDLEWARE_END diff --git a/native/cocos/editor-support/IOTypedArray.h b/native/cocos/editor-support/IOTypedArray.h index 453118c36d..600270dbb1 100644 --- a/native/cocos/editor-support/IOTypedArray.h +++ b/native/cocos/editor-support/IOTypedArray.h @@ -53,8 +53,8 @@ public: private: se::Object::TypedArrayType _arrayType = se::Object::TypedArrayType::NONE; - se::Object * _typeArray = nullptr; - bool _usePool = false; + se::Object *_typeArray = nullptr; + bool _usePool = false; }; MIDDLEWARE_END diff --git a/native/cocos/editor-support/MeshBuffer.h b/native/cocos/editor-support/MeshBuffer.h index ab3a198dbd..bff57fa389 100644 --- a/native/cocos/editor-support/MeshBuffer.h +++ b/native/cocos/editor-support/MeshBuffer.h @@ -86,10 +86,10 @@ private: ccstd::vector _ibArr; ccstd::vector _vbArr; - std::size_t _bufferPos = 0; - IOBuffer _vb; - IOBuffer _ib; - int _vertexFormat = 0; + std::size_t _bufferPos = 0; + IOBuffer _vb; + IOBuffer _ib; + int _vertexFormat = 0; }; MIDDLEWARE_END diff --git a/native/cocos/editor-support/MiddlewareManager.cpp b/native/cocos/editor-support/MiddlewareManager.cpp index 82a2ec525d..3a5dd82376 100644 --- a/native/cocos/editor-support/MiddlewareManager.cpp +++ b/native/cocos/editor-support/MiddlewareManager.cpp @@ -38,9 +38,8 @@ MiddlewareManager::MiddlewareManager() : _renderInfo(se::Object::TypedArrayType: MiddlewareManager::~MiddlewareManager() { for (auto it : _mbMap) { auto *buffer = it.second; - - delete buffer; - + + delete buffer; } _mbMap.clear(); } diff --git a/native/cocos/editor-support/MiddlewareManager.h b/native/cocos/editor-support/MiddlewareManager.h index 5fc0293a3d..65a3b2c515 100644 --- a/native/cocos/editor-support/MiddlewareManager.h +++ b/native/cocos/editor-support/MiddlewareManager.h @@ -39,10 +39,10 @@ MIDDLEWARE_BEGIN */ class IMiddleware { public: - IMiddleware() = default; - virtual ~IMiddleware() = default; - virtual void update(float dt) = 0; - virtual void render(float dt) = 0; + IMiddleware() = default; + virtual ~IMiddleware() = default; + virtual void update(float dt) = 0; + virtual void render(float dt) = 0; virtual uint32_t getRenderOrder() const = 0; }; @@ -100,9 +100,9 @@ public: se_object_ptr getVBTypedArray(int format, int bufferPos); se_object_ptr getIBTypedArray(int format, int bufferPos); - std::size_t getBufferCount(int format); - std::size_t getVBTypedArrayLength(int format, std::size_t bufferPos); - std::size_t getIBTypedArrayLength(int format, std::size_t bufferPos); + std::size_t getBufferCount(int format); + std::size_t getVBTypedArrayLength(int format, std::size_t bufferPos); + std::size_t getIBTypedArrayLength(int format, std::size_t bufferPos); SharedBufferManager *getRenderInfoMgr(); SharedBufferManager *getAttachInfoMgr(); @@ -112,14 +112,14 @@ public: // If manager is traversing _updateMap, will set the flag untill traverse is finished. bool isRendering = false; - bool isUpdating = false; + bool isUpdating = false; private: void clearRemoveList(); ccstd::vector _updateList; ccstd::vector _removeList; - std::map _mbMap; + std::map _mbMap; SharedBufferManager _renderInfo; SharedBufferManager _attachInfo; diff --git a/native/cocos/editor-support/SharedBufferManager.h b/native/cocos/editor-support/SharedBufferManager.h index ceae574406..c189b08da6 100644 --- a/native/cocos/editor-support/SharedBufferManager.h +++ b/native/cocos/editor-support/SharedBufferManager.h @@ -58,8 +58,8 @@ private: void afterCleanupHandle(); se::Object::TypedArrayType _arrayType; - IOTypedArray * _buffer = nullptr; - resizeCallback _resizeCallback = nullptr; + IOTypedArray *_buffer = nullptr; + resizeCallback _resizeCallback = nullptr; }; MIDDLEWARE_END diff --git a/native/cocos/editor-support/TypedArrayPool.cpp b/native/cocos/editor-support/TypedArrayPool.cpp index 581c37e987..9a1fa74c12 100644 --- a/native/cocos/editor-support/TypedArrayPool.cpp +++ b/native/cocos/editor-support/TypedArrayPool.cpp @@ -105,7 +105,7 @@ void TypedArrayPool::dump() { } se::Object *TypedArrayPool::pop(arrayType type, std::size_t size) { - auto fitSize = static_cast(std::ceil(static_cast(size) / float(MIN_TYPE_ARRAY_SIZE)) * MIN_TYPE_ARRAY_SIZE); + auto fitSize = static_cast(std::ceil(static_cast(size) / float(MIN_TYPE_ARRAY_SIZE)) * MIN_TYPE_ARRAY_SIZE); objPool *objPoolPtr = getObjPool(type, fitSize); if (!objPoolPtr->empty()) { @@ -117,25 +117,25 @@ se::Object *TypedArrayPool::pop(arrayType type, std::size_t size) { POOL_LOG("TypedArrayPool:pop result:empty,type:%d,fitSize:%lu,objSize:%lu\n", (int)type, fitSize, objPoolPtr->size()); se::AutoHandleScope hs; - auto * typeArray = se::Object::createTypedArray(type, nullptr, fitSize); + auto *typeArray = se::Object::createTypedArray(type, nullptr, fitSize); typeArray->root(); return typeArray; } TypedArrayPool::objPool *TypedArrayPool::getObjPool(arrayType type, std::size_t fitSize) { - auto it = _pool.find(type); + auto it = _pool.find(type); fitMap *fitMapPtr = nullptr; if (it == _pool.end()) { - fitMapPtr = new fitMap(); + fitMapPtr = new fitMap(); _pool[type] = fitMapPtr; } else { fitMapPtr = it->second; } - auto itPool = fitMapPtr->find(fitSize); + auto itPool = fitMapPtr->find(fitSize); objPool *objPoolPtr = nullptr; if (itPool == fitMapPtr->end()) { - objPoolPtr = new objPool(); + objPoolPtr = new objPool(); (*fitMapPtr)[fitSize] = objPoolPtr; } else { objPoolPtr = itPool->second; @@ -157,7 +157,7 @@ void TypedArrayPool::push(arrayType type, std::size_t arrayCapacity, se::Object } objPool *objPoolPtr = getObjPool(type, arrayCapacity); - auto it = std::find(objPoolPtr->begin(), objPoolPtr->end(), object); + auto it = std::find(objPoolPtr->begin(), objPoolPtr->end(), object); if (it != objPoolPtr->end()) { POOL_LOG("TypedArrayPool:push result:repeat\n"); return; diff --git a/native/cocos/editor-support/TypedArrayPool.h b/native/cocos/editor-support/TypedArrayPool.h index 978b2d82b6..ecbf84f6e8 100644 --- a/native/cocos/editor-support/TypedArrayPool.h +++ b/native/cocos/editor-support/TypedArrayPool.h @@ -54,9 +54,9 @@ public: private: using arrayType = se::Object::TypedArrayType; - using objPool = ccstd::vector; - using fitMap = std::map; - using typeMap = std::map; + using objPool = ccstd::vector; + using fitMap = std::map; + using typeMap = std::map; objPool *getObjPool(arrayType type, std::size_t size); @@ -73,7 +73,7 @@ private: void afterInitHandle(); typeMap _pool; - bool _allowPush = true; + bool _allowPush = true; public: /** diff --git a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.cpp b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.cpp index 6e426adcb9..c64a377ef8 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.cpp @@ -32,7 +32,7 @@ using namespace cc; // NOLINT(google-build-using-namespace) DRAGONBONES_NAMESPACE_BEGIN -float ArmatureCache::FrameTime = 1.0F / 60.0F; +float ArmatureCache::FrameTime = 1.0F / 60.0F; float ArmatureCache::MaxCacheTime = 120.0F; ArmatureCache::SegmentData::SegmentData() = default; @@ -121,7 +121,7 @@ void ArmatureCache::AnimationData::reset() { } _frames.clear(); _isComplete = false; - _totalTime = 0.0F; + _totalTime = 0.0F; } bool ArmatureCache::AnimationData::needUpdate(int toFrameIdx) const { @@ -173,15 +173,15 @@ ArmatureCache::AnimationData *ArmatureCache::buildAnimationData(const std::strin if (!_armatureDisplay) return nullptr; AnimationData *aniData = nullptr; - auto it = _animationCaches.find(animationName); + auto it = _animationCaches.find(animationName); if (it == _animationCaches.end()) { - auto *armature = _armatureDisplay->getArmature(); + auto *armature = _armatureDisplay->getArmature(); auto *animation = armature->getAnimation(); - auto hasAni = animation->hasAnimation(animationName); + auto hasAni = animation->hasAnimation(animationName); if (!hasAni) return nullptr; - aniData = new AnimationData(); - aniData->_animationName = animationName; + aniData = new AnimationData(); + aniData->_animationName = animationName; _animationCaches[animationName] = aniData; } else { aniData = it->second; @@ -213,7 +213,7 @@ void ArmatureCache::updateToFrame(const std::string &animationName, int toFrameI _curAnimationName = animationName; } - auto *armature = _armatureDisplay->getArmature(); + auto *armature = _armatureDisplay->getArmature(); auto *animation = armature->getAnimation(); // init animation @@ -233,31 +233,31 @@ void ArmatureCache::updateToFrame(const std::string &animationName, int toFrameI void ArmatureCache::renderAnimationFrame(AnimationData *animationData) { std::size_t frameIndex = animationData->getFrameCount(); - _frameData = animationData->buildFrameData(frameIndex); + _frameData = animationData->buildFrameData(frameIndex); _preColor = Color4F(-1.0F, -1.0F, -1.0F, -1.0F); - _color = Color4F(1.0F, 1.0F, 1.0F, 1.0F); + _color = Color4F(1.0F, 1.0F, 1.0F, 1.0F); - _preBlendMode = -1; + _preBlendMode = -1; _preTextureIndex = -1; _curTextureIndex = -1; _preISegWritePos = -1; - _curISegLen = 0; - _curVSegLen = 0; - _materialLen = 0; + _curISegLen = 0; + _curVSegLen = 0; + _materialLen = 0; auto *armature = _armatureDisplay->getArmature(); traverseArmature(armature); if (_preISegWritePos != -1) { - SegmentData *preSegmentData = _frameData->buildSegmentData(_materialLen - 1); - preSegmentData->indexCount = _curISegLen; + SegmentData *preSegmentData = _frameData->buildSegmentData(_materialLen - 1); + preSegmentData->indexCount = _curISegLen; preSegmentData->vertexFloatCount = _curVSegLen; } auto colorCount = _frameData->getColorCount(); if (colorCount > 0) { - ColorData *preColorData = _frameData->buildColorData(colorCount - 1); + ColorData *preColorData = _frameData->buildColorData(colorCount - 1); preColorData->vertexFloatOffset = static_cast(_frameData->vb.getCurPos()) / sizeof(float); } @@ -269,19 +269,19 @@ void ArmatureCache::traverseArmature(Armature *armature, float parentOpacity /*= middleware::IOBuffer &ib = _frameData->ib; const auto &bones = armature->getBones(); - Bone * bone = nullptr; + Bone *bone = nullptr; const auto &slots = armature->getSlots(); - CCSlot * slot = nullptr; + CCSlot *slot = nullptr; // range [0.0, 1.0] - Color4F preColor(-1.0F, -1.0F, -1.0F, -1.0F); - Color4F color; + Color4F preColor(-1.0F, -1.0F, -1.0F, -1.0F); + Color4F color; middleware::Texture2D *texture = nullptr; auto flush = [&]() { // fill pre segment count field if (_preISegWritePos != -1) { - SegmentData *preSegmentData = _frameData->buildSegmentData(_materialLen - 1); - preSegmentData->indexCount = _curISegLen; + SegmentData *preSegmentData = _frameData->buildSegmentData(_materialLen - 1); + preSegmentData->indexCount = _curISegLen; preSegmentData->vertexFloatCount = _curVSegLen; } @@ -304,17 +304,17 @@ void ArmatureCache::traverseArmature(Armature *armature, float parentOpacity /*= }; for (auto *i : bones) { - bone = i; - auto boneCount = _frameData->getBoneCount(); - BoneData *boneData = _frameData->buildBoneData(boneCount); - auto & boneOriginMat = bone->globalTransformMatrix; - auto & matm = boneData->globalTransformMatrix.m; - matm[0] = boneOriginMat.a; - matm[1] = boneOriginMat.b; - matm[4] = -boneOriginMat.c; - matm[5] = -boneOriginMat.d; - matm[12] = boneOriginMat.tx; - matm[13] = boneOriginMat.ty; + bone = i; + auto boneCount = _frameData->getBoneCount(); + BoneData *boneData = _frameData->buildBoneData(boneCount); + auto &boneOriginMat = bone->globalTransformMatrix; + auto &matm = boneData->globalTransformMatrix.m; + matm[0] = boneOriginMat.a; + matm[1] = boneOriginMat.b; + matm[4] = -boneOriginMat.c; + matm[5] = -boneOriginMat.d; + matm[12] = boneOriginMat.tx; + matm[13] = boneOriginMat.ty; } for (auto *i : slots) { @@ -355,25 +355,25 @@ void ArmatureCache::traverseArmature(Armature *armature, float parentOpacity /*= color.b = static_cast(slot->color.b) / 255.0F; if (preColor != color) { - preColor = color; + preColor = color; auto colorCount = _frameData->getColorCount(); if (colorCount > 0) { - ColorData *preColorData = _frameData->buildColorData(colorCount - 1); + ColorData *preColorData = _frameData->buildColorData(colorCount - 1); preColorData->vertexFloatOffset = vb.getCurPos() / sizeof(float); } ColorData *colorData = _frameData->buildColorData(colorCount); - colorData->color = color; + colorData->color = color; } // Transform component matrix to global matrix - middleware::Triangles & triangles = slot->triangles; + middleware::Triangles &triangles = slot->triangles; middleware::V2F_T2F_C4F *worldTriangles = slot->worldVerts; for (int v = 0, w = 0, vn = triangles.vertCount; v < vn; ++v, w += 2) { - middleware::V2F_T2F_C4F *vertex = triangles.verts + v; + middleware::V2F_T2F_C4F *vertex = triangles.verts + v; middleware::V2F_T2F_C4F *worldVertex = worldTriangles + v; - worldVertex->vertex.x = vertex->vertex.x * worldMatrix->m[0] + vertex->vertex.y * worldMatrix->m[4] + worldMatrix->m[12]; - worldVertex->vertex.y = vertex->vertex.x * worldMatrix->m[1] + vertex->vertex.y * worldMatrix->m[5] + worldMatrix->m[13]; + worldVertex->vertex.x = vertex->vertex.x * worldMatrix->m[0] + vertex->vertex.y * worldMatrix->m[4] + worldMatrix->m[12]; + worldVertex->vertex.y = vertex->vertex.x * worldMatrix->m[1] + vertex->vertex.y * worldMatrix->m[5] + worldMatrix->m[13]; worldVertex->color.r = color.r; worldVertex->color.g = color.g; diff --git a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.h b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.h index 58bfe7b7f3..e5c0168dcf 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.h +++ b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCache.h @@ -37,12 +37,12 @@ public: SegmentData(); ~SegmentData(); - void setTexture(cc::middleware::Texture2D *value); + void setTexture(cc::middleware::Texture2D *value); cc::middleware::Texture2D *getTexture() const; public: - int blendMode = 0; - std::size_t indexCount = 0; + int blendMode = 0; + std::size_t indexCount = 0; std::size_t vertexFloatCount = 0; private: @@ -55,7 +55,7 @@ public: struct ColorData { cc::middleware::Color4F color; - std::size_t vertexFloatOffset = 0; + std::size_t vertexFloatOffset = 0; }; struct FrameData { @@ -87,8 +87,8 @@ public: // if bone data is empty, it will build new one. BoneData *buildBoneData(std::size_t index); - std::vector _bones; - std::vector _colors; + std::vector _bones; + std::vector _colors; std::vector _segments; public: @@ -103,7 +103,7 @@ public: ~AnimationData(); void reset(); - FrameData * getFrameData(std::size_t frameIdx) const; + FrameData *getFrameData(std::size_t frameIdx) const; std::size_t getFrameCount() const; bool isComplete() const { return _isComplete; } @@ -112,7 +112,7 @@ public: private: // if frame is empty, it will build new one. FrameData *buildFrameData(std::size_t frameIdx); - + std::string _animationName; bool _isComplete = false; float _totalTime = 0.0F; @@ -124,8 +124,8 @@ public: void updateToFrame(const std::string &animationName, int toFrameIdx = -1); // if animation data is empty, it will build new one. - AnimationData * buildAnimationData(const std::string &animationName); - AnimationData * getAnimationData(const std::string &animationName); + AnimationData *buildAnimationData(const std::string &animationName); + AnimationData *getAnimationData(const std::string &animationName); CCArmatureDisplay *getArmatureDisplay(); void resetAllAnimationData(); @@ -136,7 +136,7 @@ private: void traverseArmature(Armature *armature, float parentOpacity = 1.0F); public: - static float FrameTime; // NOLINT + static float FrameTime; // NOLINT static float MaxCacheTime; // NOLINT private: diff --git a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCacheMgr.cpp b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCacheMgr.cpp index 7b4937480d..9dbe14dd39 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/ArmatureCacheMgr.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/ArmatureCacheMgr.cpp @@ -27,7 +27,7 @@ DRAGONBONES_NAMESPACE_BEGIN ArmatureCacheMgr *ArmatureCacheMgr::_instance = nullptr; -ArmatureCache * ArmatureCacheMgr::buildArmatureCache(const std::string &armatureName, const std::string &armatureKey, const std::string &atlasUUID) { +ArmatureCache *ArmatureCacheMgr::buildArmatureCache(const std::string &armatureName, const std::string &armatureKey, const std::string &atlasUUID) { ArmatureCache *animation = _caches.at(armatureKey); if (!animation) { animation = new ArmatureCache(armatureName, armatureKey, atlasUUID); diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp index 4297f26e48..d9618d2d60 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.cpp @@ -34,11 +34,11 @@ using namespace cc; // NOLINT(google-build-using-namespace) using namespace cc::gfx; // NOLINT(google-build-using-namespace) -static const std::string TECH_STAGE = "opaque"; -static const std::string TEXTURE_KEY = "texture"; -static const std::string START_EVENT = "start"; +static const std::string TECH_STAGE = "opaque"; +static const std::string TEXTURE_KEY = "texture"; +static const std::string START_EVENT = "start"; static const std::string LOOP_COMPLETE_EVENT = "loopComplete"; -static const std::string COMPLETE_EVENT = "complete"; +static const std::string COMPLETE_EVENT = "complete"; DRAGONBONES_NAMESPACE_BEGIN @@ -120,8 +120,8 @@ void CCArmatureCacheDisplay::update(float dt) { _playCount++; _accTime = 0.0F; if (_playTimes > 0 && _playCount >= _playTimes) { - frameIdx = finalFrameIndex; - _playCount = 0; + frameIdx = finalFrameIndex; + _playCount = 0; _isAniComplete = true; } else { frameIdx = 0; @@ -145,16 +145,16 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { if (!mgr->isRendering) return; const auto &segments = frameData->getSegments(); - const auto &colors = frameData->getColors(); + const auto &colors = frameData->getColors(); _sharedBufferOffset->reset(); _sharedBufferOffset->clear(); - auto *renderMgr = mgr->getRenderInfoMgr(); + auto *renderMgr = mgr->getRenderInfoMgr(); auto *renderInfo = renderMgr->getBuffer(); if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); + auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; @@ -173,40 +173,40 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { if (segments.empty() || colors.empty()) return; - middleware::MeshBuffer *mb = mgr->getMeshBuffer(VF_XYZUVC); - middleware::IOBuffer & vb = mb->getVB(); - middleware::IOBuffer & ib = mb->getIB(); - const auto & srcVB = frameData->vb; - const auto & srcIB = frameData->ib; + middleware::MeshBuffer *mb = mgr->getMeshBuffer(VF_XYZUVC); + middleware::IOBuffer &vb = mb->getVB(); + middleware::IOBuffer &ib = mb->getIB(); + const auto &srcVB = frameData->vb; + const auto &srcIB = frameData->ib; - auto * paramsBuffer = _paramsBuffer->getBuffer(); + auto *paramsBuffer = _paramsBuffer->getBuffer(); const cc::Mat4 &nodeWorldMat = *reinterpret_cast(¶msBuffer[4]); - int colorOffset = 0; - ArmatureCache::ColorData *nowColor = colors[colorOffset++]; - auto maxVFOffset = nowColor->vertexFloatOffset; + int colorOffset = 0; + ArmatureCache::ColorData *nowColor = colors[colorOffset++]; + auto maxVFOffset = nowColor->vertexFloatOffset; Color4F color; - float tempR = 0.0F; - float tempG = 0.0F; - float tempB = 0.0F; - float tempA = 0.0F; - float multiplier = 1.0F; - std::size_t srcVertexBytesOffset = 0; - std::size_t srcIndexBytesOffset = 0; - std::size_t vertexBytes = 0; - std::size_t indexBytes = 0; - int curTextureIndex = 0; - BlendMode blendMode = BlendMode::Normal; - std::size_t dstVertexOffset = 0; - std::size_t dstIndexOffset = 0; - float * dstVertexBuffer = nullptr; - unsigned int *dstColorBuffer = nullptr; - uint16_t * dstIndexBuffer = nullptr; - bool needColor = false; - int curBlendSrc = -1; - int curBlendDst = -1; + float tempR = 0.0F; + float tempG = 0.0F; + float tempB = 0.0F; + float tempA = 0.0F; + float multiplier = 1.0F; + std::size_t srcVertexBytesOffset = 0; + std::size_t srcIndexBytesOffset = 0; + std::size_t vertexBytes = 0; + std::size_t indexBytes = 0; + int curTextureIndex = 0; + BlendMode blendMode = BlendMode::Normal; + std::size_t dstVertexOffset = 0; + std::size_t dstIndexOffset = 0; + float *dstVertexBuffer = nullptr; + unsigned int *dstColorBuffer = nullptr; + uint16_t *dstIndexBuffer = nullptr; + bool needColor = false; + int curBlendSrc = -1; + int curBlendDst = -1; if (abs(_nodeColor.r - 1.0F) > 0.0001F || abs(_nodeColor.g - 1.0F) > 0.0001F || @@ -217,11 +217,11 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { } auto handleColor = [&](ArmatureCache::ColorData *colorData) { - tempA = colorData->color.a * _nodeColor.a; + tempA = colorData->color.a * _nodeColor.a; multiplier = _premultipliedAlpha ? tempA / 255.0f : 1.0f; - tempR = _nodeColor.r * multiplier; - tempG = _nodeColor.g * multiplier; - tempB = _nodeColor.b * multiplier; + tempR = _nodeColor.r * multiplier; + tempG = _nodeColor.g * multiplier; + tempB = _nodeColor.b * multiplier; color.a = tempA; color.r = colorData->color.r * tempR; @@ -268,7 +268,7 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { vb.checkSpace(vertexBytes, true); dstVertexOffset = vb.getCurPos() / sizeof(V2F_T2F_C4F); dstVertexBuffer = reinterpret_cast(vb.getCurBuffer()); - dstColorBuffer = reinterpret_cast(vb.getCurBuffer()); + dstColorBuffer = reinterpret_cast(vb.getCurBuffer()); vb.writeBytes(reinterpret_cast(srcVB.getBuffer()) + srcVertexBytesOffset, vertexBytes); // batch handle @@ -322,7 +322,7 @@ void CCArmatureCacheDisplay::render(float /*dt*/) { if (_useAttach) { const auto &bonesData = frameData->getBones(); - auto boneCount = frameData->getBoneCount(); + auto boneCount = frameData->getBoneCount(); for (int i = 0; i < boneCount; i++) { auto *bone = bonesData[i]; @@ -363,12 +363,12 @@ Animation *CCArmatureCacheDisplay::getAnimation() const { } void CCArmatureCacheDisplay::playAnimation(const std::string &name, int playTimes) { - _playTimes = playTimes; + _playTimes = playTimes; _animationName = name; _animationData = _armatureCache->buildAnimationData(_animationName); _isAniComplete = false; - _accTime = 0.0F; - _playCount = 0; + _accTime = 0.0F; + _playCount = 0; _curFrameIndex = 0; } diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h index 8451c4f080..1886ac5b6f 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureCacheDisplay.h @@ -38,8 +38,8 @@ public: ~CCArmatureCacheDisplay() override; void dispose(); - void update(float dt) override; - void render(float dt) override; + void update(float dt) override; + void render(float dt) override; uint32_t getRenderOrder() const override; void setTimeScale(float scale) { @@ -55,7 +55,7 @@ public: void onEnable(); void onDisable(); - Armature * getArmature() const; + Armature *getArmature() const; Animation *getAnimation() const; void setColor(float r, float g, float b, float a); @@ -69,8 +69,8 @@ public: _premultipliedAlpha = value; } - using dbEventCallback = std::function; - void setDBEventCallback(dbEventCallback callback) { + using dbEventCallback = std::function; + void setDBEventCallback(dbEventCallback callback) { _dbEventCallback = std::move(callback); } void addDBEventListener(const std::string &type); @@ -93,26 +93,26 @@ public: se_object_ptr getParamsBuffer() const; private: - float _timeScale = 1; - int _curFrameIndex = -1; - float _accTime = 0.0F; - int _playCount = 0; - int _playTimes = 0; - bool _isAniComplete = true; + float _timeScale = 1; + int _curFrameIndex = -1; + float _accTime = 0.0F; + int _playCount = 0; + int _playTimes = 0; + bool _isAniComplete = true; std::string _animationName; - Armature * _armature = nullptr; + Armature *_armature = nullptr; ArmatureCache::AnimationData *_animationData = nullptr; - std::map _listenerIDMap; + std::map _listenerIDMap; - bool _useAttach = false; - bool _batch = true; + bool _useAttach = false; + bool _batch = true; cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; - bool _premultipliedAlpha = false; - dbEventCallback _dbEventCallback = nullptr; - ArmatureCache * _armatureCache = nullptr; - EventObject * _eventObject; + bool _premultipliedAlpha = false; + dbEventCallback _dbEventCallback = nullptr; + ArmatureCache *_armatureCache = nullptr; + EventObject *_eventObject; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; // Js fill this buffer to send parameter to cpp, avoid to call jsb function. diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp index 6733a3cdff..039f1f4c52 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.cpp @@ -35,7 +35,7 @@ USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace cc; // NOLINT(google-build-using-namespace) -static const std::string TECH_STAGE = "opaque"; +static const std::string TECH_STAGE = "opaque"; static const std::string TEXTURE_KEY = "texture"; namespace cc { @@ -105,11 +105,11 @@ void CCArmatureDisplay::dbRender() { auto *mgr = MiddlewareManager::getInstance(); if (!mgr->isRendering) return; - auto *renderMgr = mgr->getRenderInfoMgr(); + auto *renderMgr = mgr->getRenderInfoMgr(); auto *renderInfo = renderMgr->getBuffer(); if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); + auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; @@ -129,19 +129,19 @@ void CCArmatureDisplay::dbRender() { // render not ready auto *paramsBuffer = _paramsBuffer->getBuffer(); - float renderOrder = *reinterpret_cast(paramsBuffer); + float renderOrder = *reinterpret_cast(paramsBuffer); if (renderOrder < 0) { return; } - _preBlendMode = -1; + _preBlendMode = -1; _preTextureIndex = -1; _curTextureIndex = -1; _preISegWritePos = -1; - _curISegLen = 0; + _curISegLen = 0; _debugSlotsLen = 0; - _materialLen = 0; + _materialLen = 0; // Traverse all aramture to fill vertex and index buffer. traverseArmature(_armature); @@ -174,18 +174,18 @@ void CCArmatureDisplay::dbRender() { boneLen = bone->_boneData->length; } - boneMat.m[0] = bone->globalTransformMatrix.a; - boneMat.m[1] = bone->globalTransformMatrix.b; - boneMat.m[4] = -bone->globalTransformMatrix.c; - boneMat.m[5] = -bone->globalTransformMatrix.d; + boneMat.m[0] = bone->globalTransformMatrix.a; + boneMat.m[1] = bone->globalTransformMatrix.b; + boneMat.m[4] = -bone->globalTransformMatrix.c; + boneMat.m[5] = -bone->globalTransformMatrix.d; boneMat.m[12] = bone->globalTransformMatrix.tx; boneMat.m[13] = bone->globalTransformMatrix.ty; attachInfo->checkSpace(sizeof(boneMat), true); attachInfo->writeBytes(reinterpret_cast(&boneMat), sizeof(boneMat)); if (_debugDraw) { - float bx = bone->globalTransformMatrix.tx; - float by = bone->globalTransformMatrix.ty; + float bx = bone->globalTransformMatrix.tx; + float by = bone->globalTransformMatrix.ty; float endx = bx + bone->globalTransformMatrix.a * boneLen; float endy = by + bone->globalTransformMatrix.b * boneLen; _debugBuffer->writeFloat32(bx); @@ -212,8 +212,8 @@ const cc::Vec2 &CCArmatureDisplay::convertToRootSpace(float x, float y) const { slot->updateWorldMatrix(); cc::Mat4 &worldMatrix = slot->worldMatrix; - _tmpVec2.x = x * worldMatrix.m[0] + y * worldMatrix.m[4] + worldMatrix.m[12]; - _tmpVec2.y = x * worldMatrix.m[1] + y * worldMatrix.m[5] + worldMatrix.m[13]; + _tmpVec2.x = x * worldMatrix.m[0] + y * worldMatrix.m[4] + worldMatrix.m[12]; + _tmpVec2.y = x * worldMatrix.m[1] + y * worldMatrix.m[5] + worldMatrix.m[13]; return _tmpVec2; } @@ -225,7 +225,7 @@ CCArmatureDisplay *CCArmatureDisplay::getRootDisplay() { Slot *parentSlot = slot->_armature->getParent(); while (parentSlot) { - slot = parentSlot; + slot = parentSlot; parentSlot = parentSlot->_armature->getParent(); } return static_cast(slot->_armature->getDisplay()); @@ -239,29 +239,29 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity const cc::Mat4 &nodeWorldMat = *reinterpret_cast(¶msBuffer[4]); const auto &slots = armature->getSlots(); - auto * mgr = MiddlewareManager::getInstance(); + auto *mgr = MiddlewareManager::getInstance(); middleware::MeshBuffer *mb = mgr->getMeshBuffer(VF_XYZUVC); - IOBuffer & vb = mb->getVB(); - IOBuffer & ib = mb->getIB(); + IOBuffer &vb = mb->getVB(); + IOBuffer &ib = mb->getIB(); float realOpacity = _nodeColor.a; - auto *renderMgr = mgr->getRenderInfoMgr(); - auto *renderInfo = renderMgr->getBuffer(); + auto *renderMgr = mgr->getRenderInfoMgr(); + auto *renderInfo = renderMgr->getBuffer(); if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); + auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; // range [0.0, 255.0] - float r; - float g; - float b; - float a; - CCSlot * slot = nullptr; + float r; + float g; + float b; + float a; + CCSlot *slot = nullptr; middleware::Texture2D *texture = nullptr; - int isFull = 0; + int isFull = 0; auto flush = [&]() { // fill pre segment count field @@ -324,7 +324,7 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity for (auto *i : slots) { isFull = 0; - slot = dynamic_cast(i); //TODO(zhakasi): refine the logic + slot = dynamic_cast(i); //TODO(zhakasi): refine the logic if (slot == nullptr) { return; } @@ -344,7 +344,7 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity texture = slot->getTexture(); if (!texture) continue; _curTextureIndex = texture->getRealTextureIndex(); - auto vbSize = slot->triangles.vertCount * sizeof(middleware::V2F_T2F_C4F); + auto vbSize = slot->triangles.vertCount * sizeof(middleware::V2F_T2F_C4F); isFull |= vb.checkSpace(vbSize, true); // If texture or blendMode change,will change material. @@ -353,15 +353,15 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity } // Calculation vertex color. - a = realOpacity * static_cast(slot->color.a) * parentOpacity / 255.0F; + a = realOpacity * static_cast(slot->color.a) * parentOpacity / 255.0F; float multiplier = _premultipliedAlpha ? a / 255.0F : 1.0F / 255.0F; - r = _nodeColor.r * static_cast(slot->color.r) * multiplier; - g = _nodeColor.g * static_cast(slot->color.g) * multiplier; - b = _nodeColor.b * static_cast(slot->color.b) * multiplier; + r = _nodeColor.r * static_cast(slot->color.r) * multiplier; + g = _nodeColor.g * static_cast(slot->color.g) * multiplier; + b = _nodeColor.b * static_cast(slot->color.b) * multiplier; // Transform component matrix to global matrix - middleware::Triangles &triangles = slot->triangles; - cc::Mat4 * worldMatrix = &slot->worldMatrix; + middleware::Triangles &triangles = slot->triangles; + cc::Mat4 *worldMatrix = &slot->worldMatrix; if (_batch) { cc::Mat4::multiply(nodeWorldMat, *worldMatrix, &matrixTemp); worldMatrix = &matrixTemp; @@ -370,7 +370,7 @@ void CCArmatureDisplay::traverseArmature(Armature *armature, float parentOpacity middleware::V2F_T2F_C4F *worldTriangles = slot->worldVerts; for (int v = 0, w = 0, vn = triangles.vertCount; v < vn; ++v, w += 2) { - middleware::V2F_T2F_C4F *vertex = triangles.verts + v; + middleware::V2F_T2F_C4F *vertex = triangles.verts + v; middleware::V2F_T2F_C4F *worldVertex = worldTriangles + v; vertex->vertex.z = 0; //reset for z value diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h index 45001f1154..c52fcc0dae 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCArmatureDisplay.h @@ -56,8 +56,8 @@ private: void traverseArmature(Armature *armature, float parentOpacity = 1.0F); protected: - bool _debugDraw = false; - Armature *_armature = nullptr; + bool _debugDraw = false; + Armature *_armature = nullptr; public: CCArmatureDisplay(); @@ -171,31 +171,31 @@ public: private: std::map _listenerIDMap; - int _preBlendMode = -1; - int _preTextureIndex = -1; - int _curTextureIndex = -1; - int _curBlendSrc = -1; - int _curBlendDst = -1; + int _preBlendMode = -1; + int _preTextureIndex = -1; + int _curTextureIndex = -1; + int _curBlendSrc = -1; + int _curBlendDst = -1; int _preISegWritePos = -1; - int _curISegLen = 0; + int _curISegLen = 0; int _debugSlotsLen = 0; - int _materialLen = 0; + int _materialLen = 0; - bool _batch = true; - bool _useAttach = false; + bool _batch = true; + bool _useAttach = false; bool _premultipliedAlpha = false; // NOTE: We bind Vec2 to make JS deserialization works, we need to return const reference in convertToRootSpace method, // because returning Vec2 JSB object on stack to JS will let JS get mess data. mutable cc::Vec2 _tmpVec2; // - cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; - dbEventCallback _dbEventCallback = nullptr; + cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; + dbEventCallback _dbEventCallback = nullptr; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; - cc::middleware::IOTypedArray *_debugBuffer = nullptr; + cc::middleware::IOTypedArray *_debugBuffer = nullptr; // Js fill this buffer to send parameter to cpp, avoid to call jsb function. cc::middleware::IOTypedArray *_paramsBuffer = nullptr; }; diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp index 8a21ee769c..71c199f928 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp +++ b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.cpp @@ -32,13 +32,13 @@ using namespace cc; DRAGONBONES_NAMESPACE_BEGIN DragonBones *CCFactory::_dragonBonesInstance = nullptr; -CCFactory * CCFactory::_factory = nullptr; +CCFactory *CCFactory::_factory = nullptr; TextureAtlasData *CCFactory::_buildTextureAtlasData(TextureAtlasData *textureAtlasData, void *textureAtlas) const { if (textureAtlasData != nullptr) { const auto pos = _prevPath.find_last_of("/"); if (pos != std::string::npos) { - const auto basePath = _prevPath.substr(0, pos + 1); + const auto basePath = _prevPath.substr(0, pos + 1); textureAtlasData->imagePath = basePath + textureAtlasData->imagePath; } @@ -53,7 +53,7 @@ TextureAtlasData *CCFactory::_buildTextureAtlasData(TextureAtlasData *textureAtl } Armature *CCFactory::_buildArmature(const BuildArmaturePackage &dataPackage) const { - const auto armature = BaseObject::borrowObject(); + const auto armature = BaseObject::borrowObject(); const auto armatureDisplay = CCArmatureDisplay::create(); // will release when armature destructor @@ -146,7 +146,7 @@ void CCFactory::removeDragonBonesDataByUUID(const std::string &uuid, bool dispos } TextureAtlasData *CCFactory::loadTextureAtlasData(const std::string &filePath, const std::string &name, float scale) { - _prevPath = cc::FileUtils::getInstance()->fullPathForFilename(filePath); + _prevPath = cc::FileUtils::getInstance()->fullPathForFilename(filePath); const auto data = cc::FileUtils::getInstance()->getStringFromFile(_prevPath); if (data.empty()) { return nullptr; diff --git a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h index c9f7a644a0..07e098f7ad 100644 --- a/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h +++ b/native/cocos/editor-support/dragonbones-creator-support/CCFactory.h @@ -47,7 +47,7 @@ class CCFactory : public BaseFactory, public cc::middleware::IMiddleware { private: static DragonBones *_dragonBonesInstance; - static CCFactory * _factory; + static CCFactory *_factory; public: static bool isInit() { @@ -130,8 +130,8 @@ public: protected: virtual TextureAtlasData *_buildTextureAtlasData(TextureAtlasData *textureAtlasData, void *textureAtlas) const override; - virtual Armature * _buildArmature(const BuildArmaturePackage &dataPackage) const override; - virtual Slot * _buildSlot(const BuildArmaturePackage &dataPackage, const SlotData *slotData, Armature *armature) const override; + virtual Armature *_buildArmature(const BuildArmaturePackage &dataPackage) const override; + virtual Slot *_buildSlot(const BuildArmaturePackage &dataPackage, const SlotData *slotData, Armature *armature) const override; public: virtual DragonBonesData *loadDragonBonesData(const std::string &filePath, const std::string &name = "", float scale = 1.0f); @@ -245,7 +245,7 @@ public: void removeDragonBonesDataByUUID(const std::string &uuid, bool disposeData = true); CCTextureAtlasData *getTextureAtlasDataByIndex(const std::string &name, int textureIndex) const; - DragonBonesData * parseDragonBonesDataByPath(const std::string &filePath, const std::string &name = "", float scale = 1.0f); + DragonBonesData *parseDragonBonesDataByPath(const std::string &filePath, const std::string &name = "", float scale = 1.0f); }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/DragonBonesHeaders.h b/native/cocos/editor-support/dragonbones/DragonBonesHeaders.h index 8a7ab33d97..918610a6fe 100644 --- a/native/cocos/editor-support/dragonbones/DragonBonesHeaders.h +++ b/native/cocos/editor-support/dragonbones/DragonBonesHeaders.h @@ -70,13 +70,13 @@ #ifndef EGRET_WASM -// parser -#include "parser/DataParser.h" -#include "parser/JSONDataParser.h" -#include "parser/BinaryDataParser.h" + // parser + #include "parser/DataParser.h" + #include "parser/JSONDataParser.h" + #include "parser/BinaryDataParser.h" -// factory -#include "factory/BaseFactory.h" + // factory + #include "factory/BaseFactory.h" #endif // EGRET_WASM #endif // DRAGONBONES_HEADERS_H diff --git a/native/cocos/editor-support/dragonbones/animation/Animation.cpp b/native/cocos/editor-support/dragonbones/animation/Animation.cpp index 87269ad72c..adb0451902 100644 --- a/native/cocos/editor-support/dragonbones/animation/Animation.cpp +++ b/native/cocos/editor-support/dragonbones/animation/Animation.cpp @@ -9,15 +9,12 @@ DRAGONBONES_NAMESPACE_BEGIN -void Animation::_onClear() -{ - for (const auto animationState : _animationStates) - { +void Animation::_onClear() { + for (const auto animationState : _animationStates) { animationState->returnToPool(); } - if (_animationConfig != nullptr) - { + if (_animationConfig != nullptr) { _animationConfig->returnToPool(); } @@ -33,43 +30,34 @@ void Animation::_onClear() _lastAnimationState = nullptr; } -void Animation::_fadeOut(AnimationConfig* animationConfig) -{ - switch (animationConfig->fadeOutMode) - { +void Animation::_fadeOut(AnimationConfig* animationConfig) { + switch (animationConfig->fadeOutMode) { case AnimationFadeOutMode::SameLayer: - for (const auto animationState : _animationStates) - { - if (animationState->layer == (unsigned)animationConfig->layer) - { + for (const auto animationState : _animationStates) { + if (animationState->layer == (unsigned)animationConfig->layer) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::SameGroup: - for (const auto animationState : _animationStates) - { - if (animationState->group == animationConfig->group) - { + for (const auto animationState : _animationStates) { + if (animationState->group == animationConfig->group) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::SameLayerAndGroup: - for (const auto animationState : _animationStates) - { - if (animationState->layer == (unsigned)animationConfig->layer && animationState->group == animationConfig->group) - { + for (const auto animationState : _animationStates) { + if (animationState->layer == (unsigned)animationConfig->layer && animationState->group == animationConfig->group) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } } break; case AnimationFadeOutMode::All: - for (const auto animationState : _animationStates) - { + for (const auto animationState : _animationStates) { animationState->fadeOut(animationConfig->fadeOutTime, animationConfig->pauseFadeOut); } break; @@ -81,8 +69,7 @@ void Animation::_fadeOut(AnimationConfig* animationConfig) } } -void Animation::init(Armature* armature) -{ +void Animation::init(Armature* armature) { if (_armature != nullptr) { return; } @@ -91,60 +78,46 @@ void Animation::init(Armature* armature) _animationConfig = BaseObject::borrowObject(); } -void Animation::advanceTime(float passedTime) -{ - if (passedTime < 0.0f) - { +void Animation::advanceTime(float passedTime) { + if (passedTime < 0.0f) { passedTime = -passedTime; } if (_armature->inheritAnimation && _armature->_parent != nullptr) // Inherit parent animation timeScale. - { - _inheritTimeScale = _armature->_parent->_armature->getAnimation()->_inheritTimeScale * timeScale; - } - else { + _inheritTimeScale = _armature->_parent->_armature->getAnimation()->_inheritTimeScale * timeScale; + } else { _inheritTimeScale = timeScale; } - if (_inheritTimeScale != 1.0f) - { + if (_inheritTimeScale != 1.0f) { passedTime *= _inheritTimeScale; } const auto animationStateCount = _animationStates.size(); - if (animationStateCount == 1) - { + if (animationStateCount == 1) { const auto animationState = _animationStates[0]; - if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) - { + if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) { _armature->_dragonBones->bufferObject(animationState); _animationStates.clear(); _lastAnimationState = nullptr; - } - else - { + } else { const auto animationData = animationState->_animationData; const auto cacheFrameRate = animationData->cacheFrameRate; if (_animationDirty && cacheFrameRate > 0.0f) // Update cachedFrameIndices. { _animationDirty = false; - for (const auto bone : _armature->getBones()) - { + for (const auto bone : _armature->getBones()) { bone->_cachedFrameIndices = animationData->getBoneCachedFrameIndices(bone->getName()); } - for (const auto slot : _armature->getSlots()) - { + for (const auto slot : _armature->getSlots()) { const auto rawDisplayDatas = slot->getRawDisplayDatas(); - if (rawDisplayDatas != nullptr && !(*rawDisplayDatas).empty()) - { + if (rawDisplayDatas != nullptr && !(*rawDisplayDatas).empty()) { const auto rawDsplayData = (*rawDisplayDatas)[0]; - if (rawDsplayData != nullptr) - { - if (rawDsplayData->parent == _armature->getArmatureData()->defaultSkin) - { + if (rawDsplayData != nullptr) { + if (rawDsplayData->parent == _armature->getArmatureData()->defaultSkin) { slot->_cachedFrameIndices = animationData->getSlotCachedFrameIndices(slot->getName()); continue; } @@ -157,54 +130,40 @@ void Animation::advanceTime(float passedTime) animationState->advanceTime(passedTime, cacheFrameRate); } - } - else if (animationStateCount > 1) - { - for (std::size_t i = 0, r = 0; i < animationStateCount; ++i) - { + } else if (animationStateCount > 1) { + for (std::size_t i = 0, r = 0; i < animationStateCount; ++i) { const auto animationState = _animationStates[i]; - if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) - { + if (animationState->_fadeState > 0 && animationState->_subFadeState > 0) { r++; _armature->_dragonBones->bufferObject(animationState); _animationDirty = true; - if (_lastAnimationState == animationState) - { + if (_lastAnimationState == animationState) { _lastAnimationState = nullptr; } - } - else - { - if (r > 0) - { + } else { + if (r > 0) { _animationStates[i - r] = animationState; } animationState->advanceTime(passedTime, 0.0f); } - if (i == animationStateCount - 1 && r > 0) - { + if (i == animationStateCount - 1 && r > 0) { _animationStates.resize(animationStateCount - r); - if (_lastAnimationState == nullptr && !_animationStates.empty()) - { + if (_lastAnimationState == nullptr && !_animationStates.empty()) { _lastAnimationState = _animationStates[_animationStates.size() - 1]; } } } _armature->_cacheFrameIndex = -1; - } - else - { + } else { _armature->_cacheFrameIndex = -1; } } -void Animation::reset() -{ - for (const auto animationState : _animationStates) - { +void Animation::reset() { + for (const auto animationState : _animationStates) { animationState->returnToPool(); } @@ -214,113 +173,84 @@ void Animation::reset() _lastAnimationState = nullptr; } -void Animation::stop(const std::string& animationName) -{ - if (!animationName.empty()) - { +void Animation::stop(const std::string& animationName) { + if (!animationName.empty()) { const auto animationState = getState(animationName); - if (animationState != nullptr) - { + if (animationState != nullptr) { animationState->stop(); } - } - else - { + } else { for (const auto animationState : _animationStates) { animationState->stop(); } } } -AnimationState* Animation::playConfig(AnimationConfig* animationConfig) -{ +AnimationState* Animation::playConfig(AnimationConfig* animationConfig) { const auto& animationName = animationConfig->animation; - if (_animations.find(animationName) == _animations.end()) - { + if (_animations.find(animationName) == _animations.end()) { DRAGONBONES_ASSERT( false, "Non-existent animation.\n" + - " DragonBones name: " + this->_armature->getArmatureData().parent->name + - " Armature name: " + this->_armature->name + - " Animation name: " + animationName - ); + " DragonBones name: " + this->_armature->getArmatureData().parent->name + + " Armature name: " + this->_armature->name + + " Animation name: " + animationName); return nullptr; } const auto animationData = _animations[animationName]; - if (animationConfig->fadeOutMode == AnimationFadeOutMode::Single) - { - for (const auto animationState : _animationStates) - { - if (animationState->_animationData == animationData) - { + if (animationConfig->fadeOutMode == AnimationFadeOutMode::Single) { + for (const auto animationState : _animationStates) { + if (animationState->_animationData == animationData) { return animationState; } } } - if (animationConfig->fadeInTime < 0.0f) - { - if (_animationStates.empty()) - { + if (animationConfig->fadeInTime < 0.0f) { + if (_animationStates.empty()) { animationConfig->fadeInTime = 0.0f; - } - else - { + } else { animationConfig->fadeInTime = animationData->fadeInTime; } } - if (animationConfig->fadeOutTime < 0.0f) - { + if (animationConfig->fadeOutTime < 0.0f) { animationConfig->fadeOutTime = animationConfig->fadeInTime; } - if (animationConfig->timeScale <= -100.0f) - { + if (animationConfig->timeScale <= -100.0f) { animationConfig->timeScale = 1.0f / animationData->scale; } - if (animationData->frameCount > 1) - { - if (animationConfig->position < 0.0f) - { + if (animationData->frameCount > 1) { + if (animationConfig->position < 0.0f) { animationConfig->position = fmod(animationConfig->position, animationData->duration); animationConfig->position = animationData->duration - animationConfig->position; - } - else if (animationConfig->position == animationData->duration) - { + } else if (animationConfig->position == animationData->duration) { animationConfig->position -= 0.000001f; // Play a little time before end. - } - else if (animationConfig->position > animationData->duration) - { + } else if (animationConfig->position > animationData->duration) { animationConfig->position = fmod(animationConfig->position, animationData->duration); } - if (animationConfig->duration > 0.0f && animationConfig->position + animationConfig->duration > animationData->duration) - { + if (animationConfig->duration > 0.0f && animationConfig->position + animationConfig->duration > animationData->duration) { animationConfig->duration = animationData->duration - animationConfig->position; } - if (animationConfig->playTimes < 0) - { + if (animationConfig->playTimes < 0) { animationConfig->playTimes = animationData->playTimes; } - } - else - { + } else { animationConfig->playTimes = 1; animationConfig->position = 0.0f; - if (animationConfig->duration > 0.0f) - { + if (animationConfig->duration > 0.0f) { animationConfig->duration = 0.0f; } } - if (animationConfig->duration == 0.0f) - { + if (animationConfig->duration == 0.0f) { animationConfig->duration = -1.0f; } @@ -331,20 +261,15 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) _animationDirty = true; _armature->_cacheFrameIndex = -1; - if (!_animationStates.empty()) - { + if (!_animationStates.empty()) { auto added = false; - for (std::size_t i = 0, l = _animationStates.size(); i < l; ++i) - { - if (animationState->layer > _animationStates[i]->layer) - { + for (std::size_t i = 0, l = _animationStates.size(); i < l; ++i) { + if (animationState->layer > _animationStates[i]->layer) { added = true; auto parentInerator = std::find(_animationStates.begin(), _animationStates.end(), _animationStates[i]); _animationStates.insert(parentInerator, animationState); break; - } - else if (i != l - 1 && animationState->layer > _animationStates[i + 1]->layer) - { + } else if (i != l - 1 && animationState->layer > _animationStates[i + 1]->layer) { added = true; auto parentInerator = std::find(_animationStates.begin(), _animationStates.end(), _animationStates[i]); _animationStates.insert(parentInerator + 1, animationState); @@ -352,33 +277,27 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) } } - if (!added) - { + if (!added) { _animationStates.push_back(animationState); } - } - else - { + } else { _animationStates.push_back(animationState); } // Child armature play same name animation. - for (const auto slot : _armature->getSlots()) - { + for (const auto slot : _armature->getSlots()) { const auto childArmature = slot->getChildArmature(); if ( childArmature != nullptr && childArmature->inheritAnimation && childArmature->getAnimation()->hasAnimation(animationName) && - childArmature->getAnimation()->getState(animationName) == nullptr - ) - { + childArmature->getAnimation()->getState(animationName) == nullptr) { childArmature->getAnimation()->fadeIn(animationName); // } } if (animationConfig->fadeInTime <= 0.0f) // Blend animation state, update armature. { - _armature->advanceTime(0.0f); + _armature->advanceTime(0.0f); } _lastAnimationState = animationState; @@ -386,33 +305,24 @@ AnimationState* Animation::playConfig(AnimationConfig* animationConfig) return animationState; } -AnimationState* Animation::play(const std::string& animationName, int playTimes) -{ +AnimationState* Animation::play(const std::string& animationName, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; _animationConfig->fadeInTime = 0.0f; _animationConfig->animation = animationName; - if (!animationName.empty()) - { + if (!animationName.empty()) { playConfig(_animationConfig); - } - else if (_lastAnimationState == nullptr) - { + } else if (_lastAnimationState == nullptr) { const auto defaultAnimation = _armature->_armatureData->defaultAnimation; - if (defaultAnimation != nullptr) - { + if (defaultAnimation != nullptr) { _animationConfig->animation = defaultAnimation->name; playConfig(_animationConfig); } - } - else if (!_lastAnimationState->isPlaying() && !_lastAnimationState->isCompleted()) - { + } else if (!_lastAnimationState->isPlaying() && !_lastAnimationState->isCompleted()) { _lastAnimationState->play(); - } - else - { + } else { _animationConfig->animation = _lastAnimationState->name; playConfig(_animationConfig); } @@ -428,8 +338,7 @@ AnimationState* Animation::fadeIn( const std::string& animationName, float fadeInTime, int playTimes, int layer, const std::string& group, AnimationFadeOutMode fadeOutMode #endif // EGRET_WASM -) -{ +) { _animationConfig->clear(); _animationConfig->fadeOutMode = (AnimationFadeOutMode)fadeOutMode; _animationConfig->playTimes = playTimes; @@ -441,8 +350,7 @@ AnimationState* Animation::fadeIn( return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) -{ +AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, float time, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; @@ -453,8 +361,7 @@ AnimationState* Animation::gotoAndPlayByTime(const std::string& animationName, f return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) -{ +AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, unsigned frame, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; @@ -462,16 +369,14 @@ AnimationState* Animation::gotoAndPlayByFrame(const std::string& animationName, _animationConfig->animation = animationName; const auto animationData = mapFind(_animations, animationName); - if (animationData != nullptr) - { + if (animationData != nullptr) { _animationConfig->position = animationData->duration * frame / animationData->frameCount; } return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) -{ +AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationName, float progress, int playTimes) { _animationConfig->clear(); _animationConfig->resetToPose = true; _animationConfig->playTimes = playTimes; @@ -486,47 +391,38 @@ AnimationState* Animation::gotoAndPlayByProgress(const std::string& animationNam return playConfig(_animationConfig); } -AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) -{ +AnimationState* Animation::gotoAndStopByTime(const std::string& animationName, float time) { const auto animationState = gotoAndPlayByTime(animationName, time, 1); - if (animationState != nullptr) - { + if (animationState != nullptr) { animationState->stop(); } return animationState; } -AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) -{ +AnimationState* Animation::gotoAndStopByFrame(const std::string& animationName, unsigned frame) { const auto animationState = gotoAndPlayByFrame(animationName, frame, 1); - if (animationState != nullptr) - { + if (animationState != nullptr) { animationState->stop(); } return animationState; } -AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) -{ +AnimationState* Animation::gotoAndStopByProgress(const std::string& animationName, float progress) { const auto animationState = gotoAndPlayByProgress(animationName, progress, 1); - if (animationState != nullptr) - { + if (animationState != nullptr) { animationState->stop(); } return animationState; } -AnimationState* Animation::getState(const std::string& animationName) const -{ +AnimationState* Animation::getState(const std::string& animationName) const { int i = _animationStates.size(); - while (i--) - { + while (i--) { const auto animationState = _animationStates[i]; - if (animationState->name == animationName) - { + if (animationState->name == animationName) { return animationState; } } @@ -534,17 +430,13 @@ AnimationState* Animation::getState(const std::string& animationName) const return nullptr; } -bool Animation::hasAnimation(const std::string& animationName) const -{ +bool Animation::hasAnimation(const std::string& animationName) const { return _animations.find(animationName) != _animations.end(); } -bool Animation::isPlaying() const -{ - for (const auto animationState : _animationStates) - { - if (animationState->isPlaying()) - { +bool Animation::isPlaying() const { + for (const auto animationState : _animationStates) { + if (animationState->isPlaying()) { return true; } } @@ -552,12 +444,9 @@ bool Animation::isPlaying() const return false; } -bool Animation::isCompleted() const -{ - for (const auto animationState : _animationStates) - { - if (!animationState->isCompleted()) - { +bool Animation::isCompleted() const { + for (const auto animationState : _animationStates) { + if (!animationState->isCompleted()) { return false; } } @@ -565,10 +454,8 @@ bool Animation::isCompleted() const return !_animationStates.empty(); } -const std::string& Animation::getLastAnimationName() const -{ - if (_lastAnimationState != nullptr) - { +const std::string& Animation::getLastAnimationName() const { + if (_lastAnimationState != nullptr) { return _lastAnimationState->name; } @@ -576,25 +463,21 @@ const std::string& Animation::getLastAnimationName() const return DEFAULT_NAME; } -void Animation::setAnimations(const std::map& value) -{ - if (_animations == value) - { +void Animation::setAnimations(const std::map& value) { + if (_animations == value) { return; } _animationNames.clear(); _animations.clear(); - for (const auto& pair : value) - { + for (const auto& pair : value) { _animationNames.push_back(pair.first); _animations[pair.first] = pair.second; } } -AnimationConfig* Animation::getAnimationConfig() const -{ +AnimationConfig* Animation::getAnimationConfig() const { _animationConfig->clear(); return _animationConfig; } diff --git a/native/cocos/editor-support/dragonbones/animation/Animation.h b/native/cocos/editor-support/dragonbones/animation/Animation.h index d2e34f04c8..9264ecb7eb 100644 --- a/native/cocos/editor-support/dragonbones/animation/Animation.h +++ b/native/cocos/editor-support/dragonbones/animation/Animation.h @@ -40,8 +40,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Animation final : public BaseObject -{ +class Animation final : public BaseObject { BIND_CLASS_TYPE_B(Animation); public: @@ -58,7 +57,7 @@ public: * @language zh_CN */ float timeScale; - + private: bool _animationDirty; float _inheritTimeScale; @@ -70,13 +69,10 @@ private: AnimationState* _lastAnimationState; public: - Animation() : - _animationConfig(nullptr) - { + Animation() : _animationConfig(nullptr) { _onClear(); } - ~Animation() - { + ~Animation() { _onClear(); } @@ -209,8 +205,7 @@ public: */ AnimationState* fadeIn( const std::string& animationName, float fadeInTime = -1.f, int playTimes = -1, - int layer = 0, const std::string& group = "", AnimationFadeOutMode fadeOutMode = AnimationFadeOutMode::SameLayerAndGroup - ); + int layer = 0, const std::string& group = "", AnimationFadeOutMode fadeOutMode = AnimationFadeOutMode::SameLayerAndGroup); /** * - Play a specific animation from the specific time. * @param animationName - The name of animation data. @@ -371,8 +366,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - inline const std::vector& getStates() const - { + inline const std::vector& getStates() const { return _animationStates; } /** @@ -424,8 +418,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline const std::vector& getAnimationNames() const - { + inline const std::vector& getAnimationNames() const { return _animationNames; } /** @@ -438,8 +431,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline const std::map& getAnimations() const - { + inline const std::map& getAnimations() const { return _animations; } void setAnimations(const std::map& value); @@ -468,11 +460,10 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline AnimationState* getLastAnimationState() const - { + inline AnimationState* getLastAnimationState() const { return _lastAnimationState; } }; DRAGONBONES_NAMESPACE_END -#endif // DRAGONBONES_ANIMATION_H +#endif // DRAGONBONES_ANIMATION_H diff --git a/native/cocos/editor-support/dragonbones/animation/AnimationState.cpp b/native/cocos/editor-support/dragonbones/animation/AnimationState.cpp index 942e786f30..a9fcd850d5 100644 --- a/native/cocos/editor-support/dragonbones/animation/AnimationState.cpp +++ b/native/cocos/editor-support/dragonbones/animation/AnimationState.cpp @@ -13,29 +13,24 @@ DRAGONBONES_NAMESPACE_BEGIN -void AnimationState::_onClear() -{ - for (const auto timeline : _boneTimelines) - { +void AnimationState::_onClear() { + for (const auto timeline : _boneTimelines) { timeline->returnToPool(); } - for (const auto timeline : _slotTimelines) - { + for (const auto timeline : _slotTimelines) { timeline->returnToPool(); } - for (const auto timeline : _constraintTimelines) - { + for (const auto timeline : _constraintTimelines) { timeline->returnToPool(); } - for (const auto& pair : _bonePoses) - { + for (const auto& pair : _bonePoses) { pair.second->returnToPool(); } - if (_actionTimeline != nullptr) { + if (_actionTimeline != nullptr) { _actionTimeline->returnToPool(); } @@ -78,8 +73,7 @@ void AnimationState::_onClear() _zOrderTimeline = nullptr; } -void AnimationState::_updateTimelines() -{ +void AnimationState::_updateTimelines() { { // Update constraint timelines. std::map> constraintTimelines; for (const auto timeline : _constraintTimelines) // Create constraint timelines map. @@ -87,8 +81,7 @@ void AnimationState::_updateTimelines() constraintTimelines[timeline->constraint->getName()].push_back(timeline); } - for (const auto constraint : _armature->_constraints) - { + for (const auto constraint : _armature->_constraints) { const auto& timelineName = constraint->getName(); const auto timelineDatas = _animationData->getConstraintTimelines(timelineName); const auto iterator = constraintTimelines.find(timelineName); @@ -96,17 +89,12 @@ void AnimationState::_updateTimelines() if (iterator != constraintTimelines.end()) // Remove constraint timeline from map. { constraintTimelines.erase(iterator); - } - else // Create new constraint timeline. + } else // Create new constraint timeline. { - if (timelineDatas != nullptr) - { - for (const auto timelineData : *timelineDatas) - { - switch (timelineData->type) - { - case TimelineType::IKConstraint: - { + if (timelineDatas != nullptr) { + for (const auto timelineData : *timelineDatas) { + switch (timelineData->type) { + case TimelineType::IKConstraint: { const auto timeline = BaseObject::borrowObject(); timeline->constraint = constraint; timeline->init(_armature, this, timelineData); @@ -118,8 +106,7 @@ void AnimationState::_updateTimelines() break; } } - } - else if (resetToPose) // Pose timeline. + } else if (resetToPose) // Pose timeline. { const auto timeline = BaseObject::borrowObject(); timeline->constraint = constraint; @@ -132,8 +119,7 @@ void AnimationState::_updateTimelines() } } -void AnimationState::_updateBoneAndSlotTimelines() -{ +void AnimationState::_updateBoneAndSlotTimelines() { { // Update bone timelines. std::map> boneTimelines; for (const auto timeline : _boneTimelines) // Create bone timelines map. @@ -141,11 +127,9 @@ void AnimationState::_updateBoneAndSlotTimelines() boneTimelines[timeline->bone->getName()].push_back(timeline); } - for (const auto bone : _armature->getBones()) - { + for (const auto bone : _armature->getBones()) { const auto& timelineName = bone->getName(); - if (!containsBoneMask(timelineName)) - { + if (!containsBoneMask(timelineName)) { continue; } @@ -155,19 +139,14 @@ void AnimationState::_updateBoneAndSlotTimelines() if (iterator != boneTimelines.end()) // Remove bone timeline from map. { boneTimelines.erase(iterator); - } - else // Create new bone timeline. + } else // Create new bone timeline. { const auto bonePose = _bonePoses.find(timelineName) != _bonePoses.end() ? _bonePoses[timelineName] : (_bonePoses[timelineName] = BaseObject::borrowObject()); - if (timelineDatas != nullptr) - { - for (const auto timelineData : *timelineDatas) - { - switch (timelineData->type) - { - case TimelineType::BoneAll: - { + if (timelineDatas != nullptr) { + for (const auto timelineData : *timelineDatas) { + switch (timelineData->type) { + case TimelineType::BoneAll: { const auto timeline = BaseObject::borrowObject(); timeline->bone = bone; timeline->bonePose = bonePose; @@ -176,8 +155,7 @@ void AnimationState::_updateBoneAndSlotTimelines() break; } - case TimelineType::BoneTranslate: - { + case TimelineType::BoneTranslate: { const auto timeline = BaseObject::borrowObject(); timeline->bone = bone; timeline->bonePose = bonePose; @@ -186,8 +164,7 @@ void AnimationState::_updateBoneAndSlotTimelines() break; } - case TimelineType::BoneRotate: - { + case TimelineType::BoneRotate: { const auto timeline = BaseObject::borrowObject(); timeline->bone = bone; timeline->bonePose = bonePose; @@ -196,8 +173,7 @@ void AnimationState::_updateBoneAndSlotTimelines() break; } - case TimelineType::BoneScale: - { + case TimelineType::BoneScale: { const auto timeline = BaseObject::borrowObject(); timeline->bone = bone; timeline->bonePose = bonePose; @@ -208,10 +184,9 @@ void AnimationState::_updateBoneAndSlotTimelines() default: break; - } + } } - } - else if (resetToPose) // Pose timeline. + } else if (resetToPose) // Pose timeline. { const auto timeline = BaseObject::borrowObject(); timeline->bone = bone; @@ -225,8 +200,7 @@ void AnimationState::_updateBoneAndSlotTimelines() for (const auto& pair : boneTimelines) // Remove bone timelines. { - for (const auto timeline : pair.second) - { + for (const auto timeline : pair.second) { _boneTimelines.erase(std::find(_boneTimelines.begin(), _boneTimelines.end(), timeline)); timeline->returnToPool(); } @@ -241,11 +215,9 @@ void AnimationState::_updateBoneAndSlotTimelines() slotTimelines[timeline->slot->getName()].push_back(timeline); } - for (const auto slot : _armature->getSlots()) - { + for (const auto slot : _armature->getSlots()) { const auto& boneName = slot->getParent()->getName(); - if (!containsBoneMask(boneName)) - { + if (!containsBoneMask(boneName)) { continue; } @@ -256,21 +228,16 @@ void AnimationState::_updateBoneAndSlotTimelines() if (iterator != slotTimelines.end()) // Remove slot timeline from map. { slotTimelines.erase(iterator); - } - else // Create new slot timeline. + } else // Create new slot timeline. { auto displayIndexFlag = false; auto colorFlag = false; ffdFlags.clear(); - if (timelineDatas != nullptr) - { - for (const auto timelineData : *timelineDatas) - { - switch (timelineData->type) - { - case TimelineType::SlotDisplay: - { + if (timelineDatas != nullptr) { + for (const auto timelineData : *timelineDatas) { + switch (timelineData->type) { + case TimelineType::SlotDisplay: { const auto timeline = BaseObject::borrowObject(); timeline->slot = slot; timeline->init(_armature, this, timelineData); @@ -279,8 +246,7 @@ void AnimationState::_updateBoneAndSlotTimelines() break; } - case TimelineType::SlotColor: - { + case TimelineType::SlotColor: { const auto timeline = BaseObject::borrowObject(); timeline->slot = slot; timeline->init(_armature, this, timelineData); @@ -289,8 +255,7 @@ void AnimationState::_updateBoneAndSlotTimelines() break; } - case TimelineType::SlotDeform: - { + case TimelineType::SlotDeform: { const auto timeline = BaseObject::borrowObject(); timeline->slot = slot; timeline->init(_armature, this, timelineData); @@ -301,14 +266,13 @@ void AnimationState::_updateBoneAndSlotTimelines() default: break; - } + } } } if (resetToPose) // Pose timeline. { - if (!displayIndexFlag) - { + if (!displayIndexFlag) { const auto timeline = BaseObject::borrowObject(); timeline->slot = slot; timeline->init(_armature, this, nullptr); @@ -316,8 +280,7 @@ void AnimationState::_updateBoneAndSlotTimelines() _poseTimelines.push_back(std::make_pair(timeline, BaseTimelineType::Slot)); } - if (!colorFlag) - { + if (!colorFlag) { const auto timeline = BaseObject::borrowObject(); timeline->slot = slot; timeline->init(_armature, this, nullptr); @@ -325,15 +288,11 @@ void AnimationState::_updateBoneAndSlotTimelines() _poseTimelines.push_back(std::make_pair(timeline, BaseTimelineType::Slot)); } - if (slot->getRawDisplayDatas() != nullptr) - { - for (const auto displayData : *(slot->getRawDisplayDatas())) - { - if (displayData != nullptr && displayData->type == DisplayType::Mesh) - { + if (slot->getRawDisplayDatas() != nullptr) { + for (const auto displayData : *(slot->getRawDisplayDatas())) { + if (displayData != nullptr && displayData->type == DisplayType::Mesh) { const auto meshOffset = static_cast(displayData)->vertices.offset; - if (std::find(ffdFlags.cbegin(), ffdFlags.cend(), meshOffset) == ffdFlags.cend()) - { + if (std::find(ffdFlags.cbegin(), ffdFlags.cend(), meshOffset) == ffdFlags.cend()) { const auto timeline = BaseObject::borrowObject(); timeline->vertexOffset = meshOffset; timeline->slot = slot; @@ -350,8 +309,7 @@ void AnimationState::_updateBoneAndSlotTimelines() for (const auto& pair : slotTimelines) // Remove slot timelines. { - for (const auto timeline : pair.second) - { + for (const auto timeline : pair.second) { _slotTimelines.erase(std::find(_slotTimelines.begin(), _slotTimelines.end(), timeline)); timeline->returnToPool(); } @@ -359,17 +317,14 @@ void AnimationState::_updateBoneAndSlotTimelines() } } -void AnimationState::_advanceFadeTime(float passedTime) -{ +void AnimationState::_advanceFadeTime(float passedTime) { const auto isFadeOut = _fadeState > 0; - if (_subFadeState < 0) - { + if (_subFadeState < 0) { _subFadeState = 0; const auto eventType = isFadeOut ? EventObject::FADE_OUT : EventObject::FADE_IN; - if (_armature->getProxy()->hasDBEventListener(eventType)) - { + if (_armature->getProxy()->hasDBEventListener(eventType)) { const auto eventObject = BaseObject::borrowObject(); eventObject->type = eventType; eventObject->armature = _armature; @@ -378,38 +333,29 @@ void AnimationState::_advanceFadeTime(float passedTime) } } - if (passedTime < 0.0f) - { + if (passedTime < 0.0f) { passedTime = -passedTime; } _fadeTime += passedTime; - if (_fadeTime >= fadeTotalTime) - { + if (_fadeTime >= fadeTotalTime) { _subFadeState = 1; _fadeProgress = isFadeOut ? 0.0f : 1.0f; - } - else if (_fadeTime > 0.0f) - { + } else if (_fadeTime > 0.0f) { _fadeProgress = isFadeOut ? (1.0f - _fadeTime / fadeTotalTime) : (_fadeTime / fadeTotalTime); - } - else - { + } else { _fadeProgress = isFadeOut ? 1.0f : 0.0f; } - if (_subFadeState > 0) - { - if (!isFadeOut) - { + if (_subFadeState > 0) { + if (!isFadeOut) { _playheadState |= 1; // x1 _fadeState = 0; } const auto eventType = isFadeOut ? EventObject::FADE_OUT_COMPLETE : EventObject::FADE_IN_COMPLETE; - if (_armature->getProxy()->hasDBEventListener(eventType)) - { + if (_armature->getProxy()->hasDBEventListener(eventType)) { const auto eventObject = BaseObject::borrowObject(); eventObject->type = eventType; eventObject->armature = _armature; @@ -419,8 +365,7 @@ void AnimationState::_advanceFadeTime(float passedTime) } } -void AnimationState::init(Armature* parmature, AnimationData* panimationData, AnimationConfig* animationConfig) -{ +void AnimationState::init(Armature* parmature, AnimationData* panimationData, AnimationConfig* animationConfig) { if (_armature != nullptr) { return; } @@ -441,55 +386,40 @@ void AnimationState::init(Armature* parmature, AnimationData* panimationData, An name = !animationConfig->name.empty() ? animationConfig->name : animationConfig->animation; group = animationConfig->group; - if (animationConfig->pauseFadeIn) - { + if (animationConfig->pauseFadeIn) { _playheadState = 2; // 10 - } - else - { + } else { _playheadState = 3; // 11 } - if (animationConfig->duration < 0.0f) - { + if (animationConfig->duration < 0.0f) { _position = 0.0f; _duration = _animationData->duration; - if (animationConfig->position != 0.0f) - { - if (timeScale >= 0.0f) - { + if (animationConfig->position != 0.0f) { + if (timeScale >= 0.0f) { _time = animationConfig->position; - } - else - { + } else { _time = animationConfig->position - _duration; } - } - else - { + } else { _time = 0.0f; } - } - else - { + } else { _position = animationConfig->position; _duration = animationConfig->duration; _time = 0.0f; } - if (timeScale < 0.0f && _time == 0.0f) - { + if (timeScale < 0.0f && _time == 0.0f) { _time = -0.000001f; // Can not cross last frame event. } - if (fadeTotalTime <= 0.0f) - { + if (fadeTotalTime <= 0.0f) { _fadeProgress = 0.999999f; } - if (!animationConfig->boneMask.empty()) - { + if (!animationConfig->boneMask.empty()) { _boneMask.resize(animationConfig->boneMask.size()); for (std::size_t i = 0, l = _boneMask.size(); i < l; ++i) { _boneMask[i] = animationConfig->boneMask[i]; @@ -499,41 +429,34 @@ void AnimationState::init(Armature* parmature, AnimationData* panimationData, An _actionTimeline = BaseObject::borrowObject(); _actionTimeline->init(_armature, this, _animationData->actionTimeline); // _actionTimeline->currentTime = _time; - if (_actionTimeline->currentTime < 0.0f) - { + if (_actionTimeline->currentTime < 0.0f) { _actionTimeline->currentTime = _duration - _actionTimeline->currentTime; } - if (_animationData->zOrderTimeline != nullptr) - { + if (_animationData->zOrderTimeline != nullptr) { _zOrderTimeline = BaseObject::borrowObject(); _zOrderTimeline->init(_armature, this, _animationData->zOrderTimeline); } } -void AnimationState::advanceTime(float passedTime, float cacheFrameRate) -{ +void AnimationState::advanceTime(float passedTime, float cacheFrameRate) { // Update fade time. - if (_fadeState != 0 || _subFadeState != 0) - { + if (_fadeState != 0 || _subFadeState != 0) { _advanceFadeTime(passedTime); } // Update time. if (_playheadState == 3) // 11 { - if (timeScale != 1.0f) - { + if (timeScale != 1.0f) { passedTime *= timeScale; } _time += passedTime; } - if (_timelineDirty != 0) - { - if (_timelineDirty == 2) - { + if (_timelineDirty != 0) { + if (_timelineDirty == 2) { _updateTimelines(); } @@ -541,8 +464,7 @@ void AnimationState::advanceTime(float passedTime, float cacheFrameRate) _updateBoneAndSlotTimelines(); } - if (weight == 0.0f) - { + if (weight == 0.0f) { return; } @@ -552,8 +474,7 @@ void AnimationState::advanceTime(float passedTime, float cacheFrameRate) auto time = _time; _weightResult = weight * _fadeProgress; - if (_actionTimeline->playState <= 0) - { + if (_actionTimeline->playState <= 0) { _actionTimeline->update(time); // Update main timeline. } @@ -571,101 +492,77 @@ void AnimationState::advanceTime(float passedTime, float cacheFrameRate) if (isCacheEnabled) // Update cache. { const auto cacheFrameIndex = (unsigned)(_actionTimeline->currentTime * cacheFrameRate); // uint - if ((unsigned)_armature->_cacheFrameIndex == cacheFrameIndex) // Same cache. - { + if ((unsigned)_armature->_cacheFrameIndex == cacheFrameIndex) // Same cache. + { isUpdateTimeline = false; isUpdateBoneTimeline = false; - } - else - { + } else { _armature->_cacheFrameIndex = cacheFrameIndex; if (_animationData->cachedFrames[cacheFrameIndex]) // Cached. - { + { isUpdateBoneTimeline = false; - } - else // Cache. - { + } else // Cache. + { _animationData->cachedFrames[cacheFrameIndex] = true; } } } - if (isUpdateTimeline) - { + if (isUpdateTimeline) { if (isUpdateBoneTimeline) // Update bone timelines. { - for (std::size_t i = 0, l = _boneTimelines.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _boneTimelines.size(); i < l; ++i) { const auto timeline = _boneTimelines[i]; - if (timeline->playState <= 0) - { + if (timeline->playState <= 0) { timeline->update(time); } - if (i == l - 1 || timeline->bone != _boneTimelines[i + 1]->bone) - { + if (i == l - 1 || timeline->bone != _boneTimelines[i + 1]->bone) { const auto state = timeline->bone->_blendState.update(_weightResult, layer); - if (state != 0) - { + if (state != 0) { timeline->blend(state); } } } } - if (displayControl) - { - for (std::size_t i = 0, l = _slotTimelines.size(); i < l; ++i) - { + if (displayControl) { + for (std::size_t i = 0, l = _slotTimelines.size(); i < l; ++i) { const auto timeline = _slotTimelines[i]; const auto& displayController = timeline->slot->displayController; if ( displayController.empty() || displayController == name || - displayController == group - ) - { - if (timeline->playState <= 0) - { + displayController == group) { + if (timeline->playState <= 0) { timeline->update(time); } } } } - for (std::size_t i = 0, l = _constraintTimelines.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _constraintTimelines.size(); i < l; ++i) { const auto timeline = _constraintTimelines[i]; - if (timeline->playState <= 0) - { + if (timeline->playState <= 0) { timeline->update(time); } } } - if (_fadeState == 0) - { - if (_subFadeState > 0) - { + if (_fadeState == 0) { + if (_subFadeState > 0) { _subFadeState = 0; - if (!_poseTimelines.empty()) - { - for (const auto& pair : _poseTimelines) - { + if (!_poseTimelines.empty()) { + for (const auto& pair : _poseTimelines) { const auto timeline = pair.first; - if (pair.second == BaseTimelineType::Bone) - { + if (pair.second == BaseTimelineType::Bone) { _boneTimelines.erase(std::find(_boneTimelines.begin(), _boneTimelines.end(), timeline)); - } - else if (pair.second == BaseTimelineType::Slot) - { + } else if (pair.second == BaseTimelineType::Slot) { _slotTimelines.erase(std::find(_slotTimelines.begin(), _slotTimelines.end(), timeline)); - } - else if (pair.second == BaseTimelineType::Constraint) - { + } else if (pair.second == BaseTimelineType::Constraint) { _constraintTimelines.erase(std::find(_constraintTimelines.begin(), _constraintTimelines.end(), timeline)); } @@ -676,8 +573,7 @@ void AnimationState::advanceTime(float passedTime, float cacheFrameRate) } } - if (_actionTimeline->playState > 0) - { + if (_actionTimeline->playState > 0) { if (autoFadeOutTime >= 0.0f) // Auto fade out. { fadeOut(autoFadeOutTime); @@ -686,52 +582,41 @@ void AnimationState::advanceTime(float passedTime, float cacheFrameRate) } } -void AnimationState::play() -{ +void AnimationState::play() { _playheadState = 3; // 11 } -void AnimationState::stop() -{ +void AnimationState::stop() { _playheadState &= 1; // 0x } -void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) -{ - if (fadeOutTime < 0.0f) - { +void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) { + if (fadeOutTime < 0.0f) { fadeOutTime = 0.0f; } - if (pausePlayhead) - { + if (pausePlayhead) { _playheadState &= 2; // x0 } - if (_fadeState > 0) - { + if (_fadeState > 0) { if (fadeOutTime > fadeTotalTime - _fadeTime) // If the animation is already in fade out, the new fade out will be ignored. { return; } - } - else - { + } else { _fadeState = 1; _subFadeState = -1; - if (fadeOutTime <= 0.0f || _fadeProgress <= 0.0f) - { + if (fadeOutTime <= 0.0f || _fadeProgress <= 0.0f) { _fadeProgress = 0.000001f; // Modify fade progress to different value. } - for (const auto timeline : _boneTimelines) - { + for (const auto timeline : _boneTimelines) { timeline->fadeOut(); } - for (const auto timeline : _slotTimelines) - { + for (const auto timeline : _slotTimelines) { timeline->fadeOut(); } } @@ -741,30 +626,24 @@ void AnimationState::fadeOut(float fadeOutTime, bool pausePlayhead) _fadeTime = fadeTotalTime * (1.0f - _fadeProgress); } -bool AnimationState::containsBoneMask(const std::string& boneName) const -{ +bool AnimationState::containsBoneMask(const std::string& boneName) const { return _boneMask.empty() || std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) != _boneMask.cend(); } -void AnimationState::addBoneMask(const std::string& boneName, bool recursive) -{ +void AnimationState::addBoneMask(const std::string& boneName, bool recursive) { const auto currentBone = _armature->getBone(boneName); - if (currentBone == nullptr) - { + if (currentBone == nullptr) { return; } - if (std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) == _boneMask.cend()) - { + if (std::find(_boneMask.cbegin(), _boneMask.cend(), boneName) == _boneMask.cend()) { _boneMask.push_back(boneName); } if (recursive) // Add recursive mixing. { - for (const auto bone : _armature->getBones()) - { - if (std::find(_boneMask.cbegin(), _boneMask.cend(), bone->getName()) == _boneMask.cend() && currentBone->contains(bone)) - { + for (const auto bone : _armature->getBones()) { + if (std::find(_boneMask.cbegin(), _boneMask.cend(), bone->getName()) == _boneMask.cend() && currentBone->contains(bone)) { _boneMask.push_back(bone->getName()); } } @@ -773,8 +652,7 @@ void AnimationState::addBoneMask(const std::string& boneName, bool recursive) _timelineDirty = 1; } -void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) -{ +void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) { { auto iterator = std::find(_boneMask.begin(), _boneMask.end(), boneName); if (iterator != _boneMask.cend()) // Remove mixing. @@ -783,34 +661,26 @@ void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) } } - if (recursive) - { + if (recursive) { const auto currentBone = _armature->getBone(boneName); - if (currentBone != nullptr) - { + if (currentBone != nullptr) { const auto& bones = _armature->getBones(); if (!_boneMask.empty()) // Remove recursive mixing. { - for (const auto bone : bones) - { + for (const auto bone : bones) { auto iterator = std::find(_boneMask.begin(), _boneMask.end(), bone->getName()); - if (iterator != _boneMask.end() && currentBone->contains(bone)) - { + if (iterator != _boneMask.end() && currentBone->contains(bone)) { _boneMask.erase(iterator); } } - } - else // Add unrecursive mixing. + } else // Add unrecursive mixing. { - for (const auto bone : bones) - { - if (bone == currentBone) - { + for (const auto bone : bones) { + if (bone == currentBone) { continue; } - if (!currentBone->contains(bone)) - { + if (!currentBone->contains(bone)) { _boneMask.push_back(bone->getName()); } } @@ -821,104 +691,81 @@ void AnimationState::removeBoneMask(const std::string& boneName, bool recursive) _timelineDirty = 1; } -void AnimationState::removeAllBoneMask() -{ +void AnimationState::removeAllBoneMask() { _boneMask.clear(); _timelineDirty = 1; } -bool AnimationState::isPlaying() const -{ +bool AnimationState::isPlaying() const { return (_playheadState & 2) != 0 && _actionTimeline->playState <= 0; } -bool AnimationState::isCompleted() const -{ +bool AnimationState::isCompleted() const { return _actionTimeline->playState > 0; } -unsigned AnimationState::getCurrentPlayTimes() const -{ +unsigned AnimationState::getCurrentPlayTimes() const { return _actionTimeline->currentPlayTimes; } -float AnimationState::getCurrentTime() const -{ +float AnimationState::getCurrentTime() const { return _actionTimeline->currentTime; } -void AnimationState::setCurrentTime(float value) -{ +void AnimationState::setCurrentTime(float value) { const auto currentPlayTimes = _actionTimeline->currentPlayTimes - (_actionTimeline->playState > 0 ? 1 : 0); - if (value < 0.0f || _duration < value) - { + if (value < 0.0f || _duration < value) { value = fmod(value, _duration) + currentPlayTimes * _duration; - if (value < 0.0f) - { + if (value < 0.0f) { value += _duration; } } - if (playTimes > 0 && (unsigned)currentPlayTimes == playTimes - 1 && value == _duration) - { + if (playTimes > 0 && (unsigned)currentPlayTimes == playTimes - 1 && value == _duration) { value = _duration - 0.000001f; } - if (_time == value) - { + if (_time == value) { return; } _time = value; _actionTimeline->setCurrentTime(_time); - if (_zOrderTimeline != nullptr) - { + if (_zOrderTimeline != nullptr) { _zOrderTimeline->playState = -1; } - for (const auto timeline : _boneTimelines) - { + for (const auto timeline : _boneTimelines) { timeline->playState = -1; } - for (const auto timeline : _slotTimelines) - { + for (const auto timeline : _slotTimelines) { timeline->playState = -1; } } -void BonePose::_onClear() -{ +void BonePose::_onClear() { current.identity(); delta.identity(); result.identity(); } -int BlendState::update(float weight, int p_layer) -{ - if (dirty) - { - if (leftWeight > 0.0f) - { - if (layer != p_layer) - { - if (layerWeight >= leftWeight) - { +int BlendState::update(float weight, int p_layer) { + if (dirty) { + if (leftWeight > 0.0f) { + if (layer != p_layer) { + if (layerWeight >= leftWeight) { leftWeight = 0.0f; return 0; - } - else - { + } else { layer = p_layer; leftWeight -= layerWeight; layerWeight = 0.0f; } } - } - else - { + } else { return 0; } @@ -938,8 +785,7 @@ int BlendState::update(float weight, int p_layer) return 1; } -void BlendState::clear() -{ +void BlendState::clear() { dirty = false; layer = 0; leftWeight = 0.0f; @@ -947,6 +793,4 @@ void BlendState::clear() blendWeight = 0.0f; } - DRAGONBONES_NAMESPACE_END - diff --git a/native/cocos/editor-support/dragonbones/animation/AnimationState.h b/native/cocos/editor-support/dragonbones/animation/AnimationState.h index 1ecce6c7b9..ba02b34d47 100644 --- a/native/cocos/editor-support/dragonbones/animation/AnimationState.h +++ b/native/cocos/editor-support/dragonbones/animation/AnimationState.h @@ -41,8 +41,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class AnimationState : public BaseObject -{ +class AnimationState : public BaseObject { BIND_CLASS_TYPE_B(AnimationState); private: @@ -254,14 +253,11 @@ private: ZOrderTimelineState* _zOrderTimeline; public: - AnimationState() : - _actionTimeline(nullptr), - _zOrderTimeline(nullptr) - { + AnimationState() : _actionTimeline(nullptr), + _zOrderTimeline(nullptr) { _onClear(); } - virtual ~AnimationState() - { + virtual ~AnimationState() { _onClear(); } @@ -383,8 +379,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - inline bool isFadeIn() const - { + inline bool isFadeIn() const { return _fadeState < 0; } /** @@ -397,8 +392,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - inline bool isFadeOut() const - { + inline bool isFadeOut() const { return _fadeState > 0; } /** @@ -411,8 +405,7 @@ public: * @version DragonBones 5.1 * @language zh_CN */ - inline bool isFadeComplete() const - { + inline bool isFadeComplete() const { return _fadeState == 0; } /** @@ -458,8 +451,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline float getTotalTime() const - { + inline float getTotalTime() const { return _duration; } /** @@ -474,8 +466,7 @@ public: */ float getCurrentTime() const; void setCurrentTime(float value); - inline const std::string& getName() const - { + inline const std::string& getName() const { return name; } @@ -491,16 +482,14 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const AnimationData* getAnimationData() const - { - return _animationData; + inline const AnimationData* getAnimationData() const { + return _animationData; } }; /** * @internal */ -class BonePose : public BaseObject -{ +class BonePose : public BaseObject { BIND_CLASS_TYPE_A(BonePose); public: @@ -514,8 +503,7 @@ protected: /** * @internal */ -class BlendState -{ +class BlendState { public: bool dirty; int layer; @@ -531,4 +519,4 @@ public: }; DRAGONBONES_NAMESPACE_END -#endif // DRAGONBONES_ANIMATION_STATE_H +#endif // DRAGONBONES_ANIMATION_STATE_H diff --git a/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.cpp b/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.cpp index 8202717632..f68916bd5d 100644 --- a/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.cpp +++ b/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.cpp @@ -12,8 +12,7 @@ DRAGONBONES_NAMESPACE_BEGIN -void TimelineState::_onClear() -{ +void TimelineState::_onClear() { playState = -1; currentPlayTimes = -1; currentTime = -1.0f; @@ -42,8 +41,7 @@ void TimelineState::_onClear() _frameIndices = nullptr; } -bool TimelineState::_setCurrentTime(float passedTime) -{ +bool TimelineState::_setCurrentTime(float passedTime) { const auto prevState = playState; const auto prevPlayTimes = currentPlayTimes; const auto prevTime = currentTime; @@ -53,90 +51,71 @@ bool TimelineState::_setCurrentTime(float passedTime) playState = _actionTimeline->playState >= 0 ? 1 : -1; currentPlayTimes = 1; currentTime = _actionTimeline->currentTime; - } - else if (_actionTimeline == nullptr || _timeScale != 1.0f || _timeOffset != 0.0f) // Action timeline or has scale and offset. + } else if (_actionTimeline == nullptr || _timeScale != 1.0f || _timeOffset != 0.0f) // Action timeline or has scale and offset. { const auto playTimes = _animationState->playTimes; const auto totalTime = playTimes * _duration; passedTime *= _timeScale; - if (_timeOffset != 0.0f) - { + if (_timeOffset != 0.0f) { passedTime += _timeOffset * _animationData->duration; } - if (playTimes > 0 && (passedTime >= totalTime || passedTime <= -totalTime)) - { - if (playState <= 0 && _animationState->_playheadState == 3) - { + if (playTimes > 0 && (passedTime >= totalTime || passedTime <= -totalTime)) { + if (playState <= 0 && _animationState->_playheadState == 3) { playState = 1; } currentPlayTimes = playTimes; - if (passedTime < 0.0f) - { + if (passedTime < 0.0f) { currentTime = 0.0f; - } - else - { + } else { currentTime = _duration + 0.000001f; // Precision problem } - } - else - { - if (playState != 0 && _animationState->_playheadState == 3) - { + } else { + if (playState != 0 && _animationState->_playheadState == 3) { playState = 0; } - if (passedTime < 0.0f) - { + if (passedTime < 0.0f) { passedTime = -passedTime; currentPlayTimes = (int)(passedTime / _duration); currentTime = _duration - fmod(passedTime, _duration); - } - else - { + } else { currentPlayTimes = (int)(passedTime / _duration); currentTime = fmod(passedTime, _duration); } } currentTime += _position; - } - else // Multi frames. + } else // Multi frames. { playState = _actionTimeline->playState; currentPlayTimes = _actionTimeline->currentPlayTimes; currentTime = _actionTimeline->currentTime; } - if (currentPlayTimes == prevPlayTimes && currentTime == prevTime) - { + if (currentPlayTimes == prevPlayTimes && currentTime == prevTime) { return false; } // Clear frame flag when timeline start or loopComplete. if ( (prevState < 0 && playState != prevState) || - (playState <= 0 && currentPlayTimes != prevPlayTimes) - ) - { + (playState <= 0 && currentPlayTimes != prevPlayTimes)) { _frameIndex = -1; } return true; } -void TimelineState::init(Armature* armature, AnimationState* animationState, TimelineData* timelineData) -{ +void TimelineState::init(Armature* armature, AnimationState* animationState, TimelineData* timelineData) { _armature = armature; _animationState = animationState; _timelineData = timelineData; _actionTimeline = _animationState->_actionTimeline; - if (this == _actionTimeline) - { + if (this == _actionTimeline) { _actionTimeline = nullptr; // } @@ -148,8 +127,7 @@ void TimelineState::init(Armature* armature, AnimationState* animationState, Tim _duration = _animationState->_duration; _dragonBonesData = _animationData->parent->parent; - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { _frameIntArray = _dragonBonesData->frameIntArray; _frameFloatArray = _dragonBonesData->frameFloatArray; _frameArray = _dragonBonesData->frameArray; @@ -163,42 +141,34 @@ void TimelineState::init(Armature* armature, AnimationState* animationState, Tim } } -void TimelineState::update(float passedTime) -{ - if (_setCurrentTime(passedTime)) - { - if (_frameCount > 1) - { +void TimelineState::update(float passedTime) { + if (_setCurrentTime(passedTime)) { + if (_frameCount > 1) { const auto timelineFrameIndex = (unsigned)(currentTime * _frameRate); const auto frameIndex = (*_frameIndices)[_timelineData->frameIndicesOffset + timelineFrameIndex]; - if ((unsigned)_frameIndex != frameIndex) - { + if ((unsigned)_frameIndex != frameIndex) { _frameIndex = frameIndex; _frameOffset = _animationData->frameOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + _frameIndex]; _onArriveAtFrame(); } - } - else if (_frameIndex < 0) - { + } else if (_frameIndex < 0) { _frameIndex = 0; if (_timelineData != nullptr) // May be pose timeline. - { + { _frameOffset = _animationData->frameOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset]; } _onArriveAtFrame(); } - if (_tweenState != TweenState::None) - { + if (_tweenState != TweenState::None) { _onUpdateFrame(); } } } -void TweenTimelineState::_onClear() -{ +void TweenTimelineState::_onClear() { TimelineState::_onClear(); _tweenType = TweenType::None; @@ -209,111 +179,82 @@ void TweenTimelineState::_onClear() _tweenEasing = 0.0f; } -void TweenTimelineState::_onArriveAtFrame() -{ +void TweenTimelineState::_onArriveAtFrame() { if ( _frameCount > 1 && - ( - (unsigned)_frameIndex != _frameCount - 1 || - _animationState->playTimes == 0 || - _animationState->getCurrentPlayTimes() < _animationState->playTimes - 1 - ) - ) - { + ((unsigned)_frameIndex != _frameCount - 1 || + _animationState->playTimes == 0 || + _animationState->getCurrentPlayTimes() < _animationState->playTimes - 1)) { _tweenType = (TweenType)_frameArray[_frameOffset + (unsigned)BinaryOffset::FrameTweenType]; // TODO recode ture tween type. _tweenState = _tweenType == TweenType::None ? TweenState::Once : TweenState::Always; - if (_tweenType == TweenType::Curve) - { + if (_tweenType == TweenType::Curve) { _curveCount = _frameArray[_frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount]; - } - else if (_tweenType != TweenType::None && _tweenType != TweenType::Line) - { + } else if (_tweenType != TweenType::None && _tweenType != TweenType::Line) { _tweenEasing = _frameArray[_frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] * 0.01; } _framePosition = _frameArray[_frameOffset] * _frameRateR; - if ((unsigned)_frameIndex == _frameCount - 1) - { + if ((unsigned)_frameIndex == _frameCount - 1) { _frameDurationR = 1.0f / (_animationData->duration - _framePosition); - } - else - { + } else { const auto nextFrameOffset = _animationData->frameOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + _frameIndex + 1]; const auto frameDuration = _frameArray[nextFrameOffset] * _frameRateR - _framePosition; if (frameDuration > 0.0f) // Fixed animation data bug. { _frameDurationR = 1.0f / frameDuration; - } - else - { + } else { _frameDurationR = 0.0f; } } - } - else - { + } else { _tweenState = TweenState::Once; } } -void TweenTimelineState::_onUpdateFrame() -{ - if (_tweenState == TweenState::Always) - { +void TweenTimelineState::_onUpdateFrame() { + if (_tweenState == TweenState::Always) { _tweenProgress = (currentTime - _framePosition) * _frameDurationR; - if (_tweenType == TweenType::Curve) - { + if (_tweenType == TweenType::Curve) { _tweenProgress = TweenTimelineState::_getEasingCurveValue(_tweenProgress, _frameArray, _curveCount, _frameOffset + (unsigned)BinaryOffset::FrameCurveSamples); - } - else if (_tweenType != TweenType::Line) - { + } else if (_tweenType != TweenType::Line) { _tweenProgress = TweenTimelineState::_getEasingValue(_tweenType, _tweenProgress, _tweenEasing); } - } - else - { + } else { _tweenProgress = 0.0f; } } -void BoneTimelineState::_onClear() -{ +void BoneTimelineState::_onClear() { TweenTimelineState::_onClear(); bone = nullptr; bonePose = nullptr; } -void BoneTimelineState::blend(int state) -{ +void BoneTimelineState::blend(int state) { const auto blendWeight = bone->_blendState.blendWeight; auto& animationPose = bone->animationPose; const auto& result = bonePose->result; - if (state == 2) - { + if (state == 2) { animationPose.x += result.x * blendWeight; animationPose.y += result.y * blendWeight; animationPose.rotation += result.rotation * blendWeight; animationPose.skew += result.skew * blendWeight; animationPose.scaleX += (result.scaleX - 1.0f) * blendWeight; animationPose.scaleY += (result.scaleY - 1.0f) * blendWeight; - } - else if (blendWeight != 1.0f) - { + } else if (blendWeight != 1.0f) { animationPose.x = result.x * blendWeight; animationPose.y = result.y * blendWeight; animationPose.rotation = result.rotation * blendWeight; animationPose.skew = result.skew * blendWeight; animationPose.scaleX = (result.scaleX - 1.0f) * blendWeight + 1.0f; animationPose.scaleY = (result.scaleY - 1.0f) * blendWeight + 1.0f; - } - else - { + } else { animationPose.x = result.x; animationPose.y = result.y; animationPose.rotation = result.rotation; @@ -322,21 +263,18 @@ void BoneTimelineState::blend(int state) animationPose.scaleY = result.scaleY; } - if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) - { + if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) { bone->_transformDirty = true; } } -void SlotTimelineState::_onClear() -{ +void SlotTimelineState::_onClear() { TweenTimelineState::_onClear(); slot = nullptr; } -void ConstraintTimelineState::_onClear() -{ +void ConstraintTimelineState::_onClear() { TweenTimelineState::_onClear(); constraint = nullptr; diff --git a/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.h b/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.h index fdf6008c1b..0e5aa9a94d 100644 --- a/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.h +++ b/native/cocos/editor-support/dragonbones/animation/BaseTimelineState.h @@ -30,16 +30,14 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class TimelineState : public BaseObject -{ +class TimelineState : public BaseObject { ABSTRACT_CLASS(TimelineState) protected: /** * @internal */ - enum class TweenState - { + enum class TweenState { None = 0, Once = 1, Always = 2 @@ -91,16 +89,13 @@ public: /** * @internal */ -class TweenTimelineState : public TimelineState -{ +class TweenTimelineState : public TimelineState { ABSTRACT_CLASS(TweenTimelineState) private: - inline static float _getEasingValue(TweenType tweenType, float progress, float easing) - { + inline static float _getEasingValue(TweenType tweenType, float progress, float easing) { auto value = progress; - switch (tweenType) - { + switch (tweenType) { case TweenType::QuadIn: value = std::pow(progress, 2.0f); break; @@ -119,14 +114,10 @@ private: return (value - progress) * easing + progress; } - inline static float _getEasingCurveValue(float progress, const int16_t* samples, unsigned count, unsigned offset) - { - if (progress <= 0.0f) - { + inline static float _getEasingCurveValue(float progress, const int16_t* samples, unsigned count, unsigned offset) { + if (progress <= 0.0f) { return 0.0f; - } - else if (progress >= 1.0f) - { + } else if (progress >= 1.0f) { return 1.0f; } @@ -154,8 +145,7 @@ protected: /** * @internal */ -class BoneTimelineState : public TweenTimelineState -{ +class BoneTimelineState : public TweenTimelineState { ABSTRACT_CLASS(BoneTimelineState) public: @@ -171,8 +161,7 @@ public: /** * @internal */ -class SlotTimelineState : public TweenTimelineState -{ +class SlotTimelineState : public TweenTimelineState { ABSTRACT_CLASS(SlotTimelineState) public: @@ -184,8 +173,7 @@ protected: /** * @internal */ -class ConstraintTimelineState : public TweenTimelineState -{ +class ConstraintTimelineState : public TweenTimelineState { ABSTRACT_CLASS(ConstraintTimelineState) public: diff --git a/native/cocos/editor-support/dragonbones/animation/IAnimatable.h b/native/cocos/editor-support/dragonbones/animation/IAnimatable.h index 0b79d2e136..bbe1b7ae6f 100644 --- a/native/cocos/editor-support/dragonbones/animation/IAnimatable.h +++ b/native/cocos/editor-support/dragonbones/animation/IAnimatable.h @@ -42,8 +42,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class IAnimatable -{ +class IAnimatable { ABSTRACT_CLASS(IAnimatable) public: @@ -60,7 +59,7 @@ public: * @language zh_CN */ virtual void advanceTime(float passedTime) = 0; - + /** * - Render. * @version Cocos creator 2.3 @@ -96,7 +95,7 @@ public: */ virtual WorldClock* getClock() const = 0; virtual void setClock(WorldClock* value) = 0; - + /** * - Gets render order. * @version Cocos creator 2.3 diff --git a/native/cocos/editor-support/dragonbones/animation/TimelineState.cpp b/native/cocos/editor-support/dragonbones/animation/TimelineState.cpp index 34a5bde299..db7190f1e2 100644 --- a/native/cocos/editor-support/dragonbones/animation/TimelineState.cpp +++ b/native/cocos/editor-support/dragonbones/animation/TimelineState.cpp @@ -18,35 +18,28 @@ DRAGONBONES_NAMESPACE_BEGIN -void ActionTimelineState::_onCrossFrame(unsigned frameIndex) const -{ +void ActionTimelineState::_onCrossFrame(unsigned frameIndex) const { const auto eventDispatcher = _armature->getProxy(); - if (_animationState->actionEnabled) - { + if (_animationState->actionEnabled) { const auto frameOffset = _animationData->frameOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + frameIndex]; const unsigned actionCount = _frameArray[frameOffset + 1]; const auto& actions = _animationData->parent->actions; // May be the animaton data not belong to this armature data. - for (std::size_t i = 0; i < actionCount; ++i) - { + for (std::size_t i = 0; i < actionCount; ++i) { const auto actionIndex = _frameArray[frameOffset + 2 + i]; const auto action = actions[actionIndex]; - if (action->type == ActionType::Play) - { + if (action->type == ActionType::Play) { const auto eventObject = BaseObject::borrowObject(); // eventObject->time = _frameArray[frameOffset] * _frameRateR; // Precision problem eventObject->time = _frameArray[frameOffset] / _frameRate; eventObject->animationState = _animationState; EventObject::actionDataToInstance(action, eventObject, _armature); _armature->_bufferAction(eventObject, true); - } - else - { + } else { const auto eventType = action->type == ActionType::Frame ? EventObject::FRAME_EVENT : EventObject::SOUND_EVENT; - if (action->type == ActionType::Sound || eventDispatcher->hasDBEventListener(eventType)) - { + if (action->type == ActionType::Sound || eventDispatcher->hasDBEventListener(eventType)) { const auto eventObject = BaseObject::borrowObject(); // eventObject->time = _frameArray[frameOffset] * _frameRateR; // Precision problem eventObject->time = _frameArray[frameOffset] / _frameRate; @@ -59,19 +52,15 @@ void ActionTimelineState::_onCrossFrame(unsigned frameIndex) const } } -void ActionTimelineState::update(float passedTime) -{ +void ActionTimelineState::update(float passedTime) { const auto prevState = playState; auto prevPlayTimes = currentPlayTimes; auto prevTime = currentTime; - if (_setCurrentTime(passedTime)) - { + if (_setCurrentTime(passedTime)) { const auto eventDispatcher = _armature->getProxy(); - if (prevState < 0) - { - if (playState != prevState) - { + if (prevState < 0) { + if (playState != prevState) { if (_animationState->displayControl && _animationState->resetToPose) // Reset zorder to pose. { _armature->_sortZOrder(nullptr, 0); @@ -79,17 +68,14 @@ void ActionTimelineState::update(float passedTime) prevPlayTimes = currentPlayTimes; - if (eventDispatcher->hasDBEventListener(EventObject::START)) - { + if (eventDispatcher->hasDBEventListener(EventObject::START)) { const auto eventObject = BaseObject::borrowObject(); eventObject->type = EventObject::START; eventObject->armature = _armature; eventObject->animationState = _animationState; _armature->_dragonBones->bufferEvent(eventObject); } - } - else - { + } else { return; } } @@ -98,20 +84,16 @@ void ActionTimelineState::update(float passedTime) EventObject* loopCompleteEvent = nullptr; EventObject* completeEvent = nullptr; - if (currentPlayTimes != prevPlayTimes) - { - if (eventDispatcher->hasDBEventListener(EventObject::LOOP_COMPLETE)) - { + if (currentPlayTimes != prevPlayTimes) { + if (eventDispatcher->hasDBEventListener(EventObject::LOOP_COMPLETE)) { loopCompleteEvent = BaseObject::borrowObject(); loopCompleteEvent->type = EventObject::LOOP_COMPLETE; loopCompleteEvent->armature = _armature; loopCompleteEvent->animationState = _animationState; } - if (playState > 0) - { - if (eventDispatcher->hasDBEventListener(EventObject::COMPLETE)) - { + if (playState > 0) { + if (eventDispatcher->hasDBEventListener(EventObject::COMPLETE)) { completeEvent = BaseObject::borrowObject(); completeEvent->type = EventObject::COMPLETE; completeEvent->armature = _armature; @@ -120,25 +102,21 @@ void ActionTimelineState::update(float passedTime) } } - if (_frameCount > 1) - { + if (_frameCount > 1) { const auto timelineData = _timelineData; const auto timelineFrameIndex = (unsigned)(currentTime * _frameRate); // uint const auto frameIndex = (*_frameIndices)[timelineData->frameIndicesOffset + timelineFrameIndex]; - if ((unsigned)_frameIndex != frameIndex) // Arrive at frame. + if ((unsigned)_frameIndex != frameIndex) // Arrive at frame. { auto crossedFrameIndex = _frameIndex; _frameIndex = frameIndex; - if (_timelineArray != nullptr) - { + if (_timelineArray != nullptr) { _frameOffset = _animationData->frameOffset + _timelineArray[timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + _frameIndex]; - if (isReverse) - { - if (crossedFrameIndex < 0) - { + if (isReverse) { + if (crossedFrameIndex < 0) { const auto prevFrameIndex = (unsigned)(prevTime * _frameRate); crossedFrameIndex = (*_frameIndices)[timelineData->frameIndicesOffset + prevFrameIndex]; @@ -151,77 +129,60 @@ void ActionTimelineState::update(float passedTime) } } - while (crossedFrameIndex >= 0) - { + while (crossedFrameIndex >= 0) { const auto frameOffset = _animationData->frameOffset + _timelineArray[timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + crossedFrameIndex]; const auto framePosition = (float)_frameArray[frameOffset] / _frameRate; if ( _position <= framePosition && - framePosition <= _position + _duration - ) // Support interval play. + framePosition <= _position + _duration) // Support interval play. { _onCrossFrame(crossedFrameIndex); } if (loopCompleteEvent != nullptr && crossedFrameIndex == 0) // Add loop complete event after first frame. - { + { _armature->_dragonBones->bufferEvent(loopCompleteEvent); loopCompleteEvent = nullptr; } - if (crossedFrameIndex > 0) - { + if (crossedFrameIndex > 0) { crossedFrameIndex--; - } - else - { + } else { crossedFrameIndex = _frameCount - 1; } - if ((unsigned)crossedFrameIndex == frameIndex) - { + if ((unsigned)crossedFrameIndex == frameIndex) { break; } } - } - else - { - if (crossedFrameIndex < 0) - { + } else { + if (crossedFrameIndex < 0) { const auto prevFrameIndex = (unsigned)(prevTime * _frameRate); crossedFrameIndex = (*_frameIndices)[timelineData->frameIndicesOffset + prevFrameIndex]; const auto frameOffset = _animationData->frameOffset + _timelineArray[timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset + crossedFrameIndex]; const auto framePosition = (float)_frameArray[frameOffset] / _frameRate; if (currentPlayTimes == prevPlayTimes) // Start. - { + { if (prevTime <= framePosition) // Crossed. { - if (crossedFrameIndex > 0) - { + if (crossedFrameIndex > 0) { crossedFrameIndex--; - } - else - { + } else { crossedFrameIndex = _frameCount - 1; } - } - else if ((unsigned)crossedFrameIndex == frameIndex) // Uncrossed. - { + } else if ((unsigned)crossedFrameIndex == frameIndex) // Uncrossed. + { crossedFrameIndex = -1; } } } - while (crossedFrameIndex >= 0) - { - if ((unsigned)crossedFrameIndex < _frameCount - 1) - { + while (crossedFrameIndex >= 0) { + if ((unsigned)crossedFrameIndex < _frameCount - 1) { crossedFrameIndex++; - } - else - { + } else { crossedFrameIndex = 0; } @@ -230,8 +191,7 @@ void ActionTimelineState::update(float passedTime) if ( _position <= framePosition && - framePosition <= _position + _duration - ) // Support interval play. + framePosition <= _position + _duration) // Support interval play. { _onCrossFrame(crossedFrameIndex); } @@ -242,32 +202,26 @@ void ActionTimelineState::update(float passedTime) loopCompleteEvent = nullptr; } - if ((unsigned)crossedFrameIndex == frameIndex) - { + if ((unsigned)crossedFrameIndex == frameIndex) { break; } } } } } - } - else if (_frameIndex < 0) - { + } else if (_frameIndex < 0) { _frameIndex = 0; - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { _frameOffset = _animationData->frameOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameOffset]; // Arrive at frame. const auto framePosition = (float)_frameArray[_frameOffset] / _frameRate; if (currentPlayTimes == prevPlayTimes) // Start. { - if (prevTime <= framePosition) - { + if (prevTime <= framePosition) { _onCrossFrame(_frameIndex); } - } - else if (_position <= framePosition) // Loop complete. + } else if (_position <= framePosition) // Loop complete. { if (!isReverse && loopCompleteEvent != nullptr) // Add loop complete event before first frame. { @@ -280,45 +234,36 @@ void ActionTimelineState::update(float passedTime) } } - if (loopCompleteEvent != nullptr) - { + if (loopCompleteEvent != nullptr) { _armature->_dragonBones->bufferEvent(loopCompleteEvent); } - if (completeEvent != nullptr) - { + if (completeEvent != nullptr) { _armature->_dragonBones->bufferEvent(completeEvent); } } } -void ActionTimelineState::setCurrentTime(float value) -{ +void ActionTimelineState::setCurrentTime(float value) { _setCurrentTime(value); _frameIndex = -1; } -void ZOrderTimelineState::_onArriveAtFrame() -{ - if (playState >= 0) - { +void ZOrderTimelineState::_onArriveAtFrame() { + if (playState >= 0) { const auto count = _frameArray[_frameOffset + 1]; - if (count > 0) - { + if (count > 0) { _armature->_sortZOrder(_frameArray, _frameOffset + 2); - } - else { + } else { _armature->_sortZOrder(nullptr, 0); } } } -void BoneAllTimelineState::_onArriveAtFrame() -{ +void BoneAllTimelineState::_onArriveAtFrame() { BoneTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { auto valueOffset = _animationData->frameFloatOffset + _frameValueOffset + _frameIndex * 6; // ...(timeline value offset)|xxxxxx|xxxxxx|(Value offset)xxxxx|(Next offset)xxxxx|xxxxxx|xxxxxx|... const auto scale = _armature->_armatureData->scale; const auto frameFloatArray = _frameFloatArray; @@ -332,10 +277,8 @@ void BoneAllTimelineState::_onArriveAtFrame() current.scaleX = frameFloatArray[valueOffset++]; current.scaleY = frameFloatArray[valueOffset++]; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { valueOffset = _animationData->frameFloatOffset + _frameValueOffset; } @@ -345,9 +288,7 @@ void BoneAllTimelineState::_onArriveAtFrame() delta.skew = frameFloatArray[valueOffset++] - current.skew; delta.scaleX = frameFloatArray[valueOffset++] - current.scaleX; delta.scaleY = frameFloatArray[valueOffset++] - current.scaleY; - } - else - { + } else { delta.x = 0.0f; delta.y = 0.0f; delta.rotation = 0.0f; @@ -355,9 +296,7 @@ void BoneAllTimelineState::_onArriveAtFrame() delta.scaleX = 0.0f; delta.scaleY = 0.0f; } - } - else - { + } else { auto& current = bonePose->current; auto& delta = bonePose->delta; current.x = 0.0f; @@ -375,8 +314,7 @@ void BoneAllTimelineState::_onArriveAtFrame() } } -void BoneAllTimelineState::_onUpdateFrame() -{ +void BoneAllTimelineState::_onUpdateFrame() { BoneTimelineState::_onUpdateFrame(); auto& current = bonePose->current; @@ -384,8 +322,7 @@ void BoneAllTimelineState::_onUpdateFrame() auto& result = bonePose->result; bone->_transformDirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -397,19 +334,16 @@ void BoneAllTimelineState::_onUpdateFrame() result.scaleY = current.scaleY + delta.scaleY * _tweenProgress; } -void BoneAllTimelineState::fadeOut() -{ +void BoneAllTimelineState::fadeOut() { auto& result = bonePose->result; result.rotation = Transform::normalizeRadian(result.rotation); result.skew = Transform::normalizeRadian(result.skew); } -void BoneTranslateTimelineState::_onArriveAtFrame() -{ +void BoneTranslateTimelineState::_onArriveAtFrame() { BoneTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { auto valueOffset = _animationData->frameFloatOffset + _frameValueOffset + _frameIndex * 2; const auto scale = _armature->_armatureData->scale; const auto frameFloatArray = _frameFloatArray; @@ -419,24 +353,18 @@ void BoneTranslateTimelineState::_onArriveAtFrame() current.x = frameFloatArray[valueOffset++] * scale; current.y = frameFloatArray[valueOffset++] * scale; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { valueOffset = _animationData->frameFloatOffset + _frameValueOffset; // + 0 * 2 } delta.x = frameFloatArray[valueOffset++] * scale - current.x; delta.y = frameFloatArray[valueOffset++] * scale - current.y; - } - else - { + } else { delta.x = 0.0f; delta.y = 0.0f; } - } - else - { + } else { auto& current = bonePose->current; auto& delta = bonePose->delta; current.x = 0.0f; @@ -446,8 +374,7 @@ void BoneTranslateTimelineState::_onArriveAtFrame() } } -void BoneTranslateTimelineState::_onUpdateFrame() -{ +void BoneTranslateTimelineState::_onUpdateFrame() { BoneTimelineState::_onUpdateFrame(); auto& current = bonePose->current; @@ -455,8 +382,7 @@ void BoneTranslateTimelineState::_onUpdateFrame() auto& result = bonePose->result; bone->_transformDirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -464,12 +390,10 @@ void BoneTranslateTimelineState::_onUpdateFrame() result.y = current.y + delta.y * _tweenProgress; } -void BoneRotateTimelineState::_onArriveAtFrame() -{ +void BoneRotateTimelineState::_onArriveAtFrame() { BoneTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { auto valueOffset = _animationData->frameFloatOffset + _frameValueOffset + _frameIndex * 2; const auto frameFloatArray = _frameFloatArray; auto& current = bonePose->current; @@ -478,28 +402,20 @@ void BoneRotateTimelineState::_onArriveAtFrame() current.rotation = frameFloatArray[valueOffset++]; current.skew = frameFloatArray[valueOffset++]; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { valueOffset = _animationData->frameFloatOffset + _frameValueOffset; // + 0 * 2 delta.rotation = Transform::normalizeRadian(frameFloatArray[valueOffset++] - current.rotation); - } - else - { + } else { delta.rotation = frameFloatArray[valueOffset++] - current.rotation; } delta.skew = frameFloatArray[valueOffset++] - current.skew; - } - else - { + } else { delta.rotation = 0.0f; delta.skew = 0.0f; } - } - else - { + } else { auto& current = bonePose->current; auto& delta = bonePose->delta; current.rotation = 0.0f; @@ -509,8 +425,7 @@ void BoneRotateTimelineState::_onArriveAtFrame() } } -void BoneRotateTimelineState::_onUpdateFrame() -{ +void BoneRotateTimelineState::_onUpdateFrame() { BoneTimelineState::_onUpdateFrame(); auto& current = bonePose->current; @@ -518,8 +433,7 @@ void BoneRotateTimelineState::_onUpdateFrame() auto& result = bonePose->result; bone->_transformDirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -527,19 +441,16 @@ void BoneRotateTimelineState::_onUpdateFrame() result.skew = current.skew + delta.skew * _tweenProgress; } -void BoneRotateTimelineState::fadeOut() -{ +void BoneRotateTimelineState::fadeOut() { auto& result = bonePose->result; result.rotation = Transform::normalizeRadian(result.rotation); result.skew = Transform::normalizeRadian(result.skew); } -void BoneScaleTimelineState::_onArriveAtFrame() -{ +void BoneScaleTimelineState::_onArriveAtFrame() { BoneTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { auto valueOffset = _animationData->frameFloatOffset + _frameValueOffset + _frameIndex * 2; const auto frameFloatArray = _frameFloatArray; auto& current = bonePose->current; @@ -548,24 +459,18 @@ void BoneScaleTimelineState::_onArriveAtFrame() current.scaleX = frameFloatArray[valueOffset++]; current.scaleY = frameFloatArray[valueOffset++]; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { valueOffset = _animationData->frameFloatOffset + _frameValueOffset; // + 0 * 2 } delta.scaleX = frameFloatArray[valueOffset++] - current.scaleX; delta.scaleY = frameFloatArray[valueOffset++] - current.scaleY; - } - else - { + } else { delta.scaleX = 0.0f; delta.scaleY = 0.0f; } - } - else - { + } else { auto& current = bonePose->current; auto& delta = bonePose->delta; current.scaleX = 1.0f; @@ -575,8 +480,7 @@ void BoneScaleTimelineState::_onArriveAtFrame() } } -void BoneScaleTimelineState::_onUpdateFrame() -{ +void BoneScaleTimelineState::_onUpdateFrame() { BoneTimelineState::_onUpdateFrame(); auto& current = bonePose->current; @@ -584,8 +488,7 @@ void BoneScaleTimelineState::_onUpdateFrame() auto& result = bonePose->result; bone->_transformDirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -593,39 +496,32 @@ void BoneScaleTimelineState::_onUpdateFrame() result.scaleY = current.scaleY + delta.scaleY * _tweenProgress; } -void SlotDislayTimelineState::_onArriveAtFrame() -{ - if (playState >= 0) - { +void SlotDislayTimelineState::_onArriveAtFrame() { + if (playState >= 0) { const auto displayIndex = _timelineData != nullptr ? _frameArray[_frameOffset + 1] : slot->_slotData->displayIndex; - if (slot->getDisplayIndex() != displayIndex) - { + if (slot->getDisplayIndex() != displayIndex) { slot->_setDisplayIndex(displayIndex, true); } } } -void SlotColorTimelineState::_onClear() -{ +void SlotColorTimelineState::_onClear() { SlotTimelineState::_onClear(); _dirty = false; } -void SlotColorTimelineState::_onArriveAtFrame() -{ +void SlotColorTimelineState::_onArriveAtFrame() { SlotTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { const auto intArray = _dragonBonesData->intArray; const auto frameIntArray = _frameIntArray; const auto valueOffset = _animationData->frameIntOffset + _frameValueOffset + _frameIndex * 1; // ...(timeline value offset)|x|x|(Value offset)|(Next offset)|x|x|... int colorOffset = frameIntArray[valueOffset]; - if (colorOffset < 0) - { - colorOffset += 65536; // Fixed out of bouds bug. + if (colorOffset < 0) { + colorOffset += 65536; // Fixed out of bouds bug. } _current[0] = intArray[colorOffset++]; @@ -637,20 +533,15 @@ void SlotColorTimelineState::_onArriveAtFrame() _current[6] = intArray[colorOffset++]; _current[7] = intArray[colorOffset++]; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { colorOffset = frameIntArray[_animationData->frameIntOffset + _frameValueOffset]; - } - else - { + } else { colorOffset = frameIntArray[valueOffset + 1 * 1]; } - if (colorOffset < 0) - { - colorOffset += 65536; // Fixed out of bouds bug. + if (colorOffset < 0) { + colorOffset += 65536; // Fixed out of bouds bug. } _delta[0] = intArray[colorOffset++] - _current[0]; @@ -662,9 +553,7 @@ void SlotColorTimelineState::_onArriveAtFrame() _delta[6] = intArray[colorOffset++] - _current[6]; _delta[7] = intArray[colorOffset++] - _current[7]; } - } - else - { + } else { const auto color = slot->_slotData->color; _current[0] = color->alphaMultiplier * 100.0f; @@ -678,13 +567,11 @@ void SlotColorTimelineState::_onArriveAtFrame() } } -void SlotColorTimelineState::_onUpdateFrame() -{ +void SlotColorTimelineState::_onUpdateFrame() { SlotTimelineState::_onUpdateFrame(); _dirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -698,23 +585,19 @@ void SlotColorTimelineState::_onUpdateFrame() _result[7] = _current[7] + _delta[7] * _tweenProgress; } -void SlotColorTimelineState::fadeOut() -{ +void SlotColorTimelineState::fadeOut() { _tweenState = TweenState::None; _dirty = false; } -void SlotColorTimelineState::update(float passedTime) -{ +void SlotColorTimelineState::update(float passedTime) { SlotTimelineState::update(passedTime); // Fade animation. - if (_tweenState != TweenState::None || _dirty) - { + if (_tweenState != TweenState::None || _dirty) { auto& result = slot->_colorTransform; - if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) - { + if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) { if ( result.alphaMultiplier != _result[0] || result.redMultiplier != _result[1] || @@ -723,9 +606,7 @@ void SlotColorTimelineState::update(float passedTime) result.alphaOffset != _result[4] || result.redOffset != _result[5] || result.greenOffset != _result[6] || - result.blueOffset != _result[7] - ) - { + result.blueOffset != _result[7]) { const auto fadeProgress = pow(_animationState->_fadeProgress, 2); result.alphaMultiplier += (_result[0] - result.alphaMultiplier) * fadeProgress; @@ -739,9 +620,7 @@ void SlotColorTimelineState::update(float passedTime) slot->_colorDirty = true; } - } - else if (_dirty) - { + } else if (_dirty) { _dirty = false; if ( result.alphaMultiplier != _result[0] || @@ -751,9 +630,7 @@ void SlotColorTimelineState::update(float passedTime) result.alphaOffset != _result[4] || result.redOffset != _result[5] || result.greenOffset != _result[6] || - result.blueOffset != _result[7] - ) - { + result.blueOffset != _result[7]) { result.alphaMultiplier = _result[0]; result.redMultiplier = _result[1]; result.greenMultiplier = _result[2]; @@ -769,8 +646,7 @@ void SlotColorTimelineState::update(float passedTime) } } -void DeformTimelineState::_onClear() -{ +void DeformTimelineState::_onClear() { SlotTimelineState::_onClear(); vertexOffset = 0; @@ -785,83 +661,64 @@ void DeformTimelineState::_onClear() _result.clear(); } -void DeformTimelineState::_onArriveAtFrame() -{ +void DeformTimelineState::_onArriveAtFrame() { SlotTimelineState::_onArriveAtFrame(); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { const auto valueOffset = _animationData->frameFloatOffset + _frameValueOffset + _frameIndex * _valueCount; const auto scale = _armature->_armatureData->scale; const auto frameFloatArray = _frameFloatArray; - if (_tweenState == TweenState::Always) - { + if (_tweenState == TweenState::Always) { auto nextValueOffset = valueOffset + _valueCount; - if ((unsigned)_frameIndex == _frameCount - 1) - { + if ((unsigned)_frameIndex == _frameCount - 1) { nextValueOffset = _animationData->frameFloatOffset + _frameValueOffset; } - for (std::size_t i = 0; i < _valueCount; ++i) - { + for (std::size_t i = 0; i < _valueCount; ++i) { _delta[i] = frameFloatArray[nextValueOffset + i] * scale - (_current[i] = frameFloatArray[valueOffset + i] * scale); } - } - else - { - for (std::size_t i = 0; i < _valueCount; ++i) - { + } else { + for (std::size_t i = 0; i < _valueCount; ++i) { _current[i] = frameFloatArray[valueOffset + i] * scale; } } - } - else - { - for (std::size_t i = 0; i < _valueCount; ++i) - { + } else { + for (std::size_t i = 0; i < _valueCount; ++i) { _current[i] = 0.0f; } } } -void DeformTimelineState::_onUpdateFrame() -{ +void DeformTimelineState::_onUpdateFrame() { SlotTimelineState::_onUpdateFrame(); _dirty = true; - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } - for (std::size_t i = 0; i < _valueCount; ++i) - { + for (std::size_t i = 0; i < _valueCount; ++i) { _result[i] = _current[i] + _delta[i] * _tweenProgress; } } -void DeformTimelineState::init(Armature* armature, AnimationState* animationState, TimelineData* timelineData) -{ +void DeformTimelineState::init(Armature* armature, AnimationState* animationState, TimelineData* timelineData) { SlotTimelineState::init(armature, animationState, timelineData); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { const auto frameIntOffset = _animationData->frameIntOffset + _timelineArray[_timelineData->offset + (unsigned)BinaryOffset::TimelineFrameValueCount]; vertexOffset = _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset]; - if (vertexOffset < 0) - { - vertexOffset += 65536; // Fixed out of bouds bug. + if (vertexOffset < 0) { + vertexOffset += 65536; // Fixed out of bouds bug. } _deformCount = _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount]; _valueCount = _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount]; _valueOffset = _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset]; _frameFloatOffset = _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] + _animationData->frameFloatOffset; - } - else - { + } else { const auto deformVertices = slot->_deformVertices; _deformCount = deformVertices != nullptr ? deformVertices->vertices.size() : 0; _valueCount = _deformCount; @@ -874,93 +731,64 @@ void DeformTimelineState::init(Armature* armature, AnimationState* animationStat _result.resize(_valueCount); } -void DeformTimelineState::fadeOut() -{ +void DeformTimelineState::fadeOut() { _tweenState = TweenState::None; _dirty = false; } -void DeformTimelineState::update(float passedTime) -{ +void DeformTimelineState::update(float passedTime) { const auto deformVertices = slot->_deformVertices; - if (deformVertices == nullptr || deformVertices->verticesData == nullptr || deformVertices->verticesData->offset != vertexOffset) - { + if (deformVertices == nullptr || deformVertices->verticesData == nullptr || deformVertices->verticesData->offset != vertexOffset) { return; - } - else if (_timelineData != nullptr && _dragonBonesData != deformVertices->verticesData->data) - { + } else if (_timelineData != nullptr && _dragonBonesData != deformVertices->verticesData->data) { return; } SlotTimelineState::update(passedTime); // Fade animation. - if (_tweenState != TweenState::None || _dirty) - { + if (_tweenState != TweenState::None || _dirty) { auto& result = deformVertices->vertices; - if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) - { + if (_animationState->_fadeState != 0 || _animationState->_subFadeState != 0) { const auto fadeProgress = pow(_animationState->_fadeProgress, 2); - if (_timelineData != nullptr) - { - for (std::size_t i = 0; i < _deformCount; ++i) - { - if (i < _valueOffset) - { + if (_timelineData != nullptr) { + for (std::size_t i = 0; i < _deformCount; ++i) { + if (i < _valueOffset) { result[i] += (_frameFloatArray[_frameFloatOffset + i] - result[i]) * fadeProgress; - } - else if (i < _valueOffset + _valueCount) - { + } else if (i < _valueOffset + _valueCount) { result[i] += (_result[i - _valueOffset] - result[i]) * fadeProgress; - } - else - { + } else { result[i] += (_frameFloatArray[_frameFloatOffset + i - _valueCount] - result[i]) * fadeProgress; } } - } - else - { + } else { _deformCount = result.size(); - for (std::size_t i = 0; i < _deformCount; ++i) - { + for (std::size_t i = 0; i < _deformCount; ++i) { result[i] += (0.0f - result[i]) * fadeProgress; } } deformVertices->verticesDirty = true; - } - else if (_dirty) - { + } else if (_dirty) { _dirty = false; - if (_timelineData != nullptr) - { - for (std::size_t i = 0; i < _deformCount; ++i) - { - if (i < _valueOffset) - { + if (_timelineData != nullptr) { + for (std::size_t i = 0; i < _deformCount; ++i) { + if (i < _valueOffset) { result[i] = _frameFloatArray[_frameFloatOffset + i]; - } - else if (i < _valueOffset + _valueCount) - { + } else if (i < _valueOffset + _valueCount) { result[i] = _result[i - _valueOffset]; - } - else - { + } else { result[i] = _frameFloatArray[_frameFloatOffset + i - _valueCount]; } } - } - else - { + } else { _deformCount = result.size(); - for (std::size_t i = 0; i < _deformCount; ++i) - { + for (std::size_t i = 0; i < _deformCount; ++i) { result[i] = 0.0f; } } @@ -970,45 +798,36 @@ void DeformTimelineState::update(float passedTime) } } -void IKConstraintTimelineState::_onClear() -{ +void IKConstraintTimelineState::_onClear() { ConstraintTimelineState::_onClear(); _current = 0.0f; _delta = 0.0f; } -void IKConstraintTimelineState::_onArriveAtFrame() -{ +void IKConstraintTimelineState::_onArriveAtFrame() { ConstraintTimelineState::_onArriveAtFrame(); const auto ikConstraint = static_cast(constraint); - if (_timelineData != nullptr) - { + if (_timelineData != nullptr) { auto valueOffset = _animationData->frameIntOffset + _frameValueOffset + _frameIndex * 2; const auto frameIntArray = _frameIntArray; const auto bendPositive = frameIntArray[valueOffset++] != 0; _current = frameIntArray[valueOffset++] * 0.01f; - if (_tweenState == TweenState::Always) - { - if ((unsigned)_frameIndex == _frameCount - 1) - { + if (_tweenState == TweenState::Always) { + if ((unsigned)_frameIndex == _frameCount - 1) { valueOffset = _animationData->frameIntOffset + _frameValueOffset; // + 0 * 2 } _delta = frameIntArray[valueOffset + 1] * 0.01f - _current; - } - else - { + } else { _delta = 0.0f; } ikConstraint->_bendPositive = bendPositive; - } - else - { + } else { const auto ikConstraintData = static_cast(ikConstraint->_constraintData); _current = ikConstraintData->weight; _delta = 0.0f; @@ -1018,12 +837,10 @@ void IKConstraintTimelineState::_onArriveAtFrame() ikConstraint->invalidUpdate(); } -void IKConstraintTimelineState::_onUpdateFrame() -{ +void IKConstraintTimelineState::_onUpdateFrame() { ConstraintTimelineState::_onUpdateFrame(); - if (_tweenState != TweenState::Always) - { + if (_tweenState != TweenState::Always) { _tweenState = TweenState::None; } @@ -1032,5 +849,4 @@ void IKConstraintTimelineState::_onUpdateFrame() ikConstraint->invalidUpdate(); } - DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/animation/TimelineState.h b/native/cocos/editor-support/dragonbones/animation/TimelineState.h index 2481ca3991..14213056c5 100644 --- a/native/cocos/editor-support/dragonbones/animation/TimelineState.h +++ b/native/cocos/editor-support/dragonbones/animation/TimelineState.h @@ -29,8 +29,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class ActionTimelineState : public TimelineState -{ +class ActionTimelineState : public TimelineState { BIND_CLASS_TYPE_A(ActionTimelineState); void _onCrossFrame(unsigned frameIndex) const; @@ -46,8 +45,7 @@ public: /** * @internal */ -class ZOrderTimelineState : public TimelineState -{ +class ZOrderTimelineState : public TimelineState { BIND_CLASS_TYPE_A(ZOrderTimelineState); protected: @@ -57,8 +55,7 @@ protected: /** * @internal */ -class BoneAllTimelineState : public BoneTimelineState -{ +class BoneAllTimelineState : public BoneTimelineState { BIND_CLASS_TYPE_A(BoneAllTimelineState); protected: @@ -71,8 +68,7 @@ public: /** * @internal */ -class BoneTranslateTimelineState : public BoneTimelineState -{ +class BoneTranslateTimelineState : public BoneTimelineState { BIND_CLASS_TYPE_A(BoneTranslateTimelineState); protected: @@ -82,8 +78,7 @@ protected: /** * @internal */ -class BoneRotateTimelineState : public BoneTimelineState -{ +class BoneRotateTimelineState : public BoneTimelineState { BIND_CLASS_TYPE_A(BoneRotateTimelineState); protected: @@ -96,8 +91,7 @@ public: /** * @internal */ -class BoneScaleTimelineState : public BoneTimelineState -{ +class BoneScaleTimelineState : public BoneTimelineState { BIND_CLASS_TYPE_A(BoneScaleTimelineState); protected: @@ -107,8 +101,7 @@ protected: /** * @internal */ -class SlotDislayTimelineState : public SlotTimelineState -{ +class SlotDislayTimelineState : public SlotTimelineState { BIND_CLASS_TYPE_A(SlotDislayTimelineState); protected: @@ -117,8 +110,7 @@ protected: /** * @internal */ -class SlotColorTimelineState : public SlotTimelineState -{ +class SlotColorTimelineState : public SlotTimelineState { BIND_CLASS_TYPE_B(SlotColorTimelineState); private: @@ -128,15 +120,12 @@ private: float* _result; public: - SlotColorTimelineState() : - _current(new int[8]{ 0 }), - _delta(new int[8]{ 0 }), - _result(new float[8]{ 0.0f }) - { - _onClear(); + SlotColorTimelineState() : _current(new int[8]{0}), + _delta(new int[8]{0}), + _result(new float[8]{0.0f}) { + _onClear(); } - ~SlotColorTimelineState() - { + ~SlotColorTimelineState() { _onClear(); delete _current; @@ -156,8 +145,7 @@ public: /** * @internal */ -class DeformTimelineState : public SlotTimelineState -{ +class DeformTimelineState : public SlotTimelineState { BIND_CLASS_TYPE_A(DeformTimelineState); public: @@ -187,8 +175,7 @@ public: /** * @internal */ -class IKConstraintTimelineState : public ConstraintTimelineState -{ +class IKConstraintTimelineState : public ConstraintTimelineState { BIND_CLASS_TYPE_A(IKConstraintTimelineState); private: diff --git a/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp b/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp index 9659feb16e..8bfc227c68 100644 --- a/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp +++ b/native/cocos/editor-support/dragonbones/animation/WorldClock.cpp @@ -5,73 +5,55 @@ DRAGONBONES_NAMESPACE_BEGIN WorldClock WorldClock::clock; -void WorldClock::advanceTime(float passedTime) -{ - if (passedTime < 0.0f || passedTime != passedTime) - { +void WorldClock::advanceTime(float passedTime) { + if (passedTime < 0.0f || passedTime != passedTime) { passedTime = 0.0f; } const auto currentTime = 0.0f; - if (passedTime < 0.0f) - { + if (passedTime < 0.0f) { passedTime = currentTime - _systemTime; } _systemTime = currentTime; - if (timeScale != 1.0f) - { + if (timeScale != 1.0f) { passedTime *= timeScale; } - if (passedTime == 0.0f) - { + if (passedTime == 0.0f) { return; } - if (passedTime < 0.0f) - { + if (passedTime < 0.0f) { time -= passedTime; - } - else - { + } else { time += passedTime; } std::size_t i = 0, r = 0, l = _animatebles.size(); - for (; i < l; ++i) - { + for (; i < l; ++i) { const auto animatable = _animatebles[i]; - if (animatable != nullptr) - { - if (r > 0) - { + if (animatable != nullptr) { + if (r > 0) { _animatebles[i - r] = animatable; _animatebles[i] = nullptr; } animatable->advanceTime(passedTime); - } - else - { + } else { r++; } } - if (r > 0) - { + if (r > 0) { l = _animatebles.size(); - for (; i < l; ++i) - { + for (; i < l; ++i) { const auto animateble = _animatebles[i]; - if (animateble != nullptr) - { + if (animateble != nullptr) { _animatebles[i - r] = animateble; - } - else - { + } else { r++; } } @@ -80,98 +62,77 @@ void WorldClock::advanceTime(float passedTime) } } -bool WorldClock::contains(const IAnimatable* value) const -{ +bool WorldClock::contains(const IAnimatable* value) const { if (value == this) { return false; } auto ancestor = value; - while (ancestor != this && ancestor != nullptr) - { + while (ancestor != this && ancestor != nullptr) { ancestor = ancestor->getClock(); } return ancestor == this; } -void WorldClock::add(IAnimatable* value) -{ - if (std::find(_animatebles.begin(), _animatebles.end(), value) == _animatebles.end()) - { +void WorldClock::add(IAnimatable* value) { + if (std::find(_animatebles.begin(), _animatebles.end(), value) == _animatebles.end()) { _animatebles.push_back(value); value->setClock(this); } } -void WorldClock::remove(IAnimatable* value) -{ +void WorldClock::remove(IAnimatable* value) { const auto iterator = std::find(_animatebles.begin(), _animatebles.end(), value); - if (iterator != _animatebles.end()) - { + if (iterator != _animatebles.end()) { *iterator = nullptr; value->setClock(nullptr); } } -void WorldClock::render() -{ +void WorldClock::render() { auto isOrderDirty = false; uint32_t maxRenderOrder = 0; - for (const auto animatable : _animatebles) - { - if (animatable != nullptr) - { + for (const auto animatable : _animatebles) { + if (animatable != nullptr) { animatable->render(); auto renderOrder = animatable->getRenderOrder(); - if (maxRenderOrder > renderOrder) - { - isOrderDirty = true; - } - else - { + if (maxRenderOrder > renderOrder) { + isOrderDirty = true; + } else { maxRenderOrder = renderOrder; } } } - - if (isOrderDirty) - { - std::sort(_animatebles.begin(), _animatebles.end(), [](IAnimatable* it1, IAnimatable* it2) - { + + if (isOrderDirty) { + std::sort(_animatebles.begin(), _animatebles.end(), [](IAnimatable* it1, IAnimatable* it2) { if (!it1 || !it2) return false; return it1->getRenderOrder() < it2->getRenderOrder(); }); } } -void WorldClock::clear() -{ - for (const auto animatable : _animatebles) - { - if (animatable != nullptr) - { +void WorldClock::clear() { + for (const auto animatable : _animatebles) { + if (animatable != nullptr) { animatable->setClock(nullptr); } } } -void WorldClock::setClock(WorldClock* value) -{ - if (_clock == value) - { +void WorldClock::setClock(WorldClock* value) { + if (_clock == value) { return; } - if (_clock != nullptr) - { + if (_clock != nullptr) { _clock->remove(this); } _clock = value; - if (_clock != nullptr) - { + if (_clock != nullptr) { _clock->add(this); } } diff --git a/native/cocos/editor-support/dragonbones/animation/WorldClock.h b/native/cocos/editor-support/dragonbones/animation/WorldClock.h index 60155a5037..8038d8eb7c 100644 --- a/native/cocos/editor-support/dragonbones/animation/WorldClock.h +++ b/native/cocos/editor-support/dragonbones/animation/WorldClock.h @@ -41,8 +41,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class WorldClock : public IAnimatable -{ +class WorldClock : public IAnimatable { DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(WorldClock) public: @@ -104,17 +103,14 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - WorldClock(float timeValue = 0.0f) : - time(timeValue), - timeScale(1.0f), - _systemTime(0.0f), - _animatebles(), - _clock(nullptr) - { + WorldClock(float timeValue = 0.0f) : time(timeValue), + timeScale(1.0f), + _systemTime(0.0f), + _animatebles(), + _clock(nullptr) { _systemTime = 0.0f; } - virtual ~WorldClock() - { + virtual ~WorldClock() { clear(); } /** @@ -141,7 +137,7 @@ public: * @language zh_CN */ virtual void render() override; - + /** * - Check whether contains a specific instance of IAnimatable. * @param value - The IAnimatable instance. @@ -195,8 +191,7 @@ public: /** * @inheritDoc */ - inline virtual WorldClock* getClock() const override - { + inline virtual WorldClock* getClock() const override { return _clock; } virtual void setClock(WorldClock* value) override; diff --git a/native/cocos/editor-support/dragonbones/armature/Armature.cpp b/native/cocos/editor-support/dragonbones/armature/Armature.cpp index d700369f3f..f7f810578e 100644 --- a/native/cocos/editor-support/dragonbones/armature/Armature.cpp +++ b/native/cocos/editor-support/dragonbones/armature/Armature.cpp @@ -11,50 +11,41 @@ DRAGONBONES_NAMESPACE_BEGIN -bool Armature::_onSortSlots(Slot* a, Slot* b) -{ +bool Armature::_onSortSlots(Slot* a, Slot* b) { return a->_zOrder < b->_zOrder ? true : false; } -void Armature::_onClear() -{ +void Armature::_onClear() { if (_clock != nullptr) // Remove clock before slots clear. { _clock->remove(this); } - for (const auto bone : _bones) - { + for (const auto bone : _bones) { bone->returnToPool(); } - for (const auto slot : _slots) - { + for (const auto slot : _slots) { slot->returnToPool(); } - for (const auto constraint : _constraints) - { + for (const auto constraint : _constraints) { constraint->returnToPool(); } - for (const auto action : _actions) - { + for (const auto action : _actions) { action->returnToPool(); } - if(_animation != nullptr) - { + if (_animation != nullptr) { _animation->returnToPool(); } - if (_proxy != nullptr) - { + if (_proxy != nullptr) { _proxy->dbClear(); } - if (_replaceTextureAtlasData != nullptr) - { + if (_replaceTextureAtlasData != nullptr) { _replaceTextureAtlasData->returnToPool(); } @@ -83,25 +74,20 @@ void Armature::_onClear() _parent = nullptr; } -void Armature::_sortZOrder(const int16_t* slotIndices, unsigned offset) -{ +void Armature::_sortZOrder(const int16_t* slotIndices, unsigned offset) { const auto& slotDatas = _armatureData->sortedSlots; const auto isOriginal = slotIndices == nullptr; - if (_zOrderDirty || !isOriginal) - { - for (std::size_t i = 0, l = slotDatas.size(); i < l; ++i) - { + if (_zOrderDirty || !isOriginal) { + for (std::size_t i = 0, l = slotDatas.size(); i < l; ++i) { const auto slotIndex = isOriginal ? i : (std::size_t)slotIndices[offset + i]; - if (slotIndex < 0 || slotIndex >= l) - { + if (slotIndex < 0 || slotIndex >= l) { continue; } const auto slotData = slotDatas[slotIndex]; const auto slot = getSlot(slotData->name); - if (slot != nullptr) - { + if (slot != nullptr) { slot->_setZorder(i); } } @@ -111,58 +97,43 @@ void Armature::_sortZOrder(const int16_t* slotIndices, unsigned offset) } } -void Armature::_addBone(Bone* value) -{ - if (std::find(_bones.begin(), _bones.end(), value) == _bones.end()) - { +void Armature::_addBone(Bone* value) { + if (std::find(_bones.begin(), _bones.end(), value) == _bones.end()) { _bones.push_back(value); } } -void Armature::_addSlot(Slot* value) -{ - if (std::find(_slots.begin(), _slots.end(), value) == _slots.end()) - { +void Armature::_addSlot(Slot* value) { + if (std::find(_slots.begin(), _slots.end(), value) == _slots.end()) { _slots.push_back(value); } } -void Armature::_addConstraint(Constraint* value) -{ - if (std::find(_constraints.cbegin(), _constraints.cend(), value) == _constraints.cend()) - { +void Armature::_addConstraint(Constraint* value) { + if (std::find(_constraints.cbegin(), _constraints.cend(), value) == _constraints.cend()) { _constraints.push_back(value); } } -void Armature::_bufferAction(EventObject* action, bool append) -{ - if (std::find(_actions.cbegin(), _actions.cend(), action) == _actions.cend()) - { - if (append) - { +void Armature::_bufferAction(EventObject* action, bool append) { + if (std::find(_actions.cbegin(), _actions.cend(), action) == _actions.cend()) { + if (append) { _actions.push_back(action); - } - else - { + } else { _actions.insert(_actions.begin(), action); } } } -void Armature::dispose() -{ - if (_armatureData != nullptr) - { +void Armature::dispose() { + if (_armatureData != nullptr) { _lockUpdate = true; _dragonBones->bufferObject(this); } } -void Armature::init(ArmatureData *armatureData, IArmatureProxy* proxy, void* display, DragonBones* dragonBones) -{ - if (_armatureData != nullptr) - { +void Armature::init(ArmatureData* armatureData, IArmatureProxy* proxy, void* display, DragonBones* dragonBones) { + if (_armatureData != nullptr) { return; } @@ -177,20 +148,15 @@ void Armature::init(ArmatureData *armatureData, IArmatureProxy* proxy, void* dis _animation->setAnimations(_armatureData->animations); } -void Armature::advanceTime(float passedTime) -{ - if (_lockUpdate) - { +void Armature::advanceTime(float passedTime) { + if (_lockUpdate) { return; } - if (_armatureData == nullptr) - { + if (_armatureData == nullptr) { DRAGONBONES_ASSERT(false, "The armature has been disposed."); return; - } - else if(_armatureData->parent == nullptr) - { + } else if (_armatureData->parent == nullptr) { DRAGONBONES_ASSERT(false, "The armature data has been disposed.\nPlease make sure dispose armature before call factory.clear()."); return; } @@ -201,63 +167,46 @@ void Armature::advanceTime(float passedTime) _animation->advanceTime(passedTime); // Sort slots. - if (_slotsDirty) - { + if (_slotsDirty) { _slotsDirty = false; std::sort(_slots.begin(), _slots.end(), Armature::_onSortSlots); } // Update bones and slots. - if (_cacheFrameIndex < 0 || _cacheFrameIndex != prevCacheFrameIndex) - { - for (const auto bone : _bones) - { + if (_cacheFrameIndex < 0 || _cacheFrameIndex != prevCacheFrameIndex) { + for (const auto bone : _bones) { bone->update(_cacheFrameIndex); } - for (const auto slot : _slots) - { + for (const auto slot : _slots) { slot->update(_cacheFrameIndex); } } // Do actions. - if (!_actions.empty()) - { + if (!_actions.empty()) { _lockUpdate = true; - for (const auto action : _actions) - { + for (const auto action : _actions) { const auto actionData = action->actionData; - if (actionData != nullptr) - { - if (actionData->type == ActionType::Play) - { - if (action->slot != nullptr) - { + if (actionData != nullptr) { + if (actionData->type == ActionType::Play) { + if (action->slot != nullptr) { const auto childArmature = action->slot->getChildArmature(); - if (childArmature != nullptr) - { + if (childArmature != nullptr) { childArmature->getAnimation()->fadeIn(actionData->name); } - } - else if (action->bone != nullptr) - { - for (const auto slot : getSlots()) - { - if (slot->getParent() == action->bone) - { + } else if (action->bone != nullptr) { + for (const auto slot : getSlots()) { + if (slot->getParent() == action->bone) { const auto childArmature = slot->getChildArmature(); - if (childArmature != nullptr) - { + if (childArmature != nullptr) { childArmature->getAnimation()->fadeIn(actionData->name); } } } - } - else - { + } else { _animation->fadeIn(actionData->name); } } @@ -273,66 +222,49 @@ void Armature::advanceTime(float passedTime) _proxy->dbUpdate(); } -void Armature::render() -{ - if (_proxy) - { +void Armature::render() { + if (_proxy) { _proxy->dbRender(); } } -uint32_t Armature::getRenderOrder() const -{ - if (_proxy) - { +uint32_t Armature::getRenderOrder() const { + if (_proxy) { return _proxy->getRenderOrder(); } return 0; } -void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) -{ - if (!boneName.empty()) - { +void Armature::invalidUpdate(const std::string& boneName, bool updateSlot) { + if (!boneName.empty()) { const auto bone = getBone(boneName); - if (bone != nullptr) - { + if (bone != nullptr) { bone->invalidUpdate(); - if (updateSlot) - { - for (const auto slot : _slots) - { - if (slot->getParent() == bone) - { + if (updateSlot) { + for (const auto slot : _slots) { + if (slot->getParent() == bone) { slot->invalidUpdate(); } } } } - } - else - { - for (const auto bone : _bones) - { + } else { + for (const auto bone : _bones) { bone->invalidUpdate(); } - if (updateSlot) - { - for (const auto slot : _slots) - { + if (updateSlot) { + for (const auto slot : _slots) { slot->invalidUpdate(); } } } } -Slot* Armature::containsPoint(float x, float y) const -{ - for(const auto slot : _slots) - { - if(slot->containsPoint(x,y)) { +Slot* Armature::containsPoint(float x, float y) const { + for (const auto slot : _slots) { + if (slot->containsPoint(x, y)) { return slot; } } @@ -344,9 +276,7 @@ Slot* Armature::intersectsSegment( float xA, float yA, float xB, float yB, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) const -{ + Point* normalRadians) const { const auto isV = xA == xB; auto dMin = 0.0f; auto dMax = 0.0f; @@ -359,23 +289,17 @@ Slot* Armature::intersectsSegment( Slot* intSlotA = nullptr; Slot* intSlotB = nullptr; - for (const auto & slot : _slots) - { + for (const auto& slot : _slots) { auto intersectionCount = slot->intersectsSegment(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians); - if (intersectionCount > 0) - { - if (intersectionPointA != nullptr || intersectionPointB != nullptr) - { - if (intersectionPointA != nullptr) - { + if (intersectionCount > 0) { + if (intersectionPointA != nullptr || intersectionPointB != nullptr) { + if (intersectionPointA != nullptr) { float d = isV ? intersectionPointA->y - yA : intersectionPointA->x - xA; - if (d < 0.0f) - { + if (d < 0.0f) { d = -d; } - if (intSlotA == nullptr || d < dMin) - { + if (intSlotA == nullptr || d < dMin) { dMin = d; intXA = intersectionPointA->x; intYA = intersectionPointA->y; @@ -387,54 +311,44 @@ Slot* Armature::intersectsSegment( } } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { float d = intersectionPointB->x - xA; - if (d < 0.0f) - { + if (d < 0.0f) { d = -d; } - if (intSlotB == nullptr || d > dMax) - { + if (intSlotB == nullptr || d > dMax) { dMax = d; intXB = intersectionPointB->x; intYB = intersectionPointB->y; intSlotB = slot; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { intBN = normalRadians->y; } } } - } - else - { + } else { intSlotA = slot; break; } } } - if (intSlotA != nullptr && intersectionPointA != nullptr) - { + if (intSlotA != nullptr && intersectionPointA != nullptr) { intersectionPointA->x = intXA; intersectionPointA->y = intYA; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = intAN; } } - if (intSlotB != nullptr && intersectionPointB != nullptr) - { + if (intSlotB != nullptr && intersectionPointB != nullptr) { intersectionPointB->x = intXB; intersectionPointB->y = intYB; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->y = intBN; } } @@ -442,12 +356,9 @@ Slot* Armature::intersectsSegment( return intSlotA; } -Bone* Armature::getBone(const std::string& name) const -{ - for (const auto& bone : _bones) - { - if (bone->getName() == name) - { +Bone* Armature::getBone(const std::string& name) const { + for (const auto& bone : _bones) { + if (bone->getName() == name) { return bone; } } @@ -455,19 +366,15 @@ Bone* Armature::getBone(const std::string& name) const return nullptr; } -Bone* Armature::getBoneByDisplay(void* display) const -{ +Bone* Armature::getBoneByDisplay(void* display) const { const auto slot = getSlotByDisplay(display); return slot != nullptr ? slot->getParent() : nullptr; } -Slot* Armature::getSlot(const std::string& name) const -{ - for (const auto slot : _slots) - { - if (slot->getName() == name) - { +Slot* Armature::getSlot(const std::string& name) const { + for (const auto slot : _slots) { + if (slot->getName() == name) { return slot; } } @@ -475,14 +382,10 @@ Slot* Armature::getSlot(const std::string& name) const return nullptr; } -Slot* Armature::getSlotByDisplay(void* display) const -{ - if (display != nullptr) - { - for (const auto slot : _slots) - { - if (slot->getDisplay() == display) - { +Slot* Armature::getSlotByDisplay(void* display) const { + if (display != nullptr) { + for (const auto slot : _slots) { + if (slot->getDisplay() == display) { return slot; } } @@ -491,70 +394,56 @@ Slot* Armature::getSlotByDisplay(void* display) const return nullptr; } -void Armature::setCacheFrameRate(unsigned value) -{ - if (_armatureData->cacheFrameRate != value) - { +void Armature::setCacheFrameRate(unsigned value) { + if (_armatureData->cacheFrameRate != value) { _armatureData->cacheFrames(value); - for (const auto & slot : _slots) - { + for (const auto& slot : _slots) { const auto childArmature = slot->getChildArmature(); - if (childArmature != nullptr && childArmature->getCacheFrameRate() == 0) - { + if (childArmature != nullptr && childArmature->getCacheFrameRate() == 0) { childArmature->setCacheFrameRate(value); } } } } -void Armature::setClock(WorldClock* value) -{ - if(_clock == value) - { +void Armature::setClock(WorldClock* value) { + if (_clock == value) { return; } - if(_clock) - { + if (_clock) { _clock->remove(this); } _clock = value; - if(_clock) - { + if (_clock) { _clock->add(this); } // Update childArmature clock. - for (const auto& slot : _slots) - { + for (const auto& slot : _slots) { const auto childArmature = slot->getChildArmature(); - if (childArmature != nullptr) - { + if (childArmature != nullptr) { childArmature->setClock(_clock); } } } -void Armature::setReplacedTexture(void* value) -{ - if (_replacedTexture == value) - { +void Armature::setReplacedTexture(void* value) { + if (_replacedTexture == value) { return; } - if (_replaceTextureAtlasData != nullptr) - { + if (_replaceTextureAtlasData != nullptr) { _replaceTextureAtlasData->returnToPool(); _replaceTextureAtlasData = nullptr; } _replacedTexture = value; - for (const auto &slot : _slots) - { + for (const auto& slot : _slots) { slot->invalidUpdate(); slot->update(-1); } diff --git a/native/cocos/editor-support/dragonbones/armature/Armature.h b/native/cocos/editor-support/dragonbones/armature/Armature.h index 4719672c99..8ba723bed4 100644 --- a/native/cocos/editor-support/dragonbones/armature/Armature.h +++ b/native/cocos/editor-support/dragonbones/armature/Armature.h @@ -47,8 +47,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Armature : public virtual IAnimatable, public BaseObject -{ +class Armature : public virtual IAnimatable, public BaseObject { BIND_CLASS_TYPE_B(Armature); private: @@ -118,16 +117,13 @@ protected: void* _replacedTexture; public: - Armature() : - _animation(nullptr), - _proxy(nullptr), - _clock(nullptr), - _replaceTextureAtlasData(nullptr) - { + Armature() : _animation(nullptr), + _proxy(nullptr), + _clock(nullptr), + _replaceTextureAtlasData(nullptr) { _onClear(); } - virtual ~Armature() - { + virtual ~Armature() { _onClear(); } @@ -184,7 +180,7 @@ public: /** * @internal */ - void init(ArmatureData *armatureData, IArmatureProxy* proxy, void* display, DragonBones* dragonBones); + void init(ArmatureData* armatureData, IArmatureProxy* proxy, void* display, DragonBones* dragonBones); /** * @inheritDoc */ @@ -269,8 +265,7 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ) const; + Point* normalRadians = nullptr) const; /** * - Get a specific bone. * @param name - The bone name. @@ -343,8 +338,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::vector& getBones() const - { + inline const std::vector& getBones() const { return _bones; } /** @@ -359,8 +353,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::vector& getSlots() const - { + inline const std::vector& getSlots() const { return _slots; } /** @@ -373,12 +366,10 @@ public: * @version DragonBones 5.5 * @language zh_CN */ - bool getFlipX() const - { - return _flipX; + bool getFlipX() const { + return _flipX; } - void setFlipX(bool value) - { + void setFlipX(bool value) { _flipX = value; invalidUpdate(""); } @@ -393,12 +384,10 @@ public: * @version DragonBones 5.5 * @language zh_CN */ - bool getFlipY() const - { - return _flipY; + bool getFlipY() const { + return _flipY; } - void setFlipY(bool value) - { + void setFlipY(bool value) { _flipY = value; invalidUpdate(""); } @@ -432,8 +421,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline unsigned getCacheFrameRate() const - { + inline unsigned getCacheFrameRate() const { return _armatureData->cacheFrameRate; } void setCacheFrameRate(unsigned value); @@ -447,8 +435,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const - { + inline const std::string& getName() const { return _armatureData->name; } /** @@ -463,8 +450,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline const ArmatureData* getArmatureData() const - { + inline const ArmatureData* getArmatureData() const { return _armatureData; } /** @@ -479,15 +465,13 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline Animation* getAnimation() const - { + inline Animation* getAnimation() const { return _animation; } /** * @pivate */ - inline IArmatureProxy* getProxy() const - { + inline IArmatureProxy* getProxy() const { return _proxy; } /** @@ -500,8 +484,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline IEventDispatcher* getEventDispatcher() const - { + inline IEventDispatcher* getEventDispatcher() const { return _proxy; } /** @@ -518,23 +501,20 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void* getDisplay() const - { + inline void* getDisplay() const { return _display; } /** * @private */ - inline void* getReplacedTexture() const - { + inline void* getReplacedTexture() const { return _replacedTexture; } void setReplacedTexture(void* value); /** * @inheritDoc */ - inline WorldClock* getClock() const override - { + inline WorldClock* getClock() const override { return _clock; } void setClock(WorldClock* value) override; @@ -550,8 +530,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline Slot* getParent() const - { + inline Slot* getParent() const { return _parent; } diff --git a/native/cocos/editor-support/dragonbones/armature/Bone.cpp b/native/cocos/editor-support/dragonbones/armature/Bone.cpp index c84a7058c8..a1cec19041 100644 --- a/native/cocos/editor-support/dragonbones/armature/Bone.cpp +++ b/native/cocos/editor-support/dragonbones/armature/Bone.cpp @@ -8,8 +8,7 @@ DRAGONBONES_NAMESPACE_BEGIN -void Bone::_onClear() -{ +void Bone::_onClear() { TransformObject::_onClear(); offsetMode = OffsetMode::Additive; @@ -27,94 +26,67 @@ void Bone::_onClear() _cachedFrameIndices = nullptr; } -void Bone::_updateGlobalTransformMatrix(bool isCache) -{ +void Bone::_updateGlobalTransformMatrix(bool isCache) { const auto flipX = _armature->getFlipX(); const auto flipY = _armature->getFlipY() == DragonBones::yDown; auto inherit = _parent != nullptr; auto rotation = 0.0f; - if (offsetMode == OffsetMode::Additive) - { - if (origin != nullptr) - { + if (offsetMode == OffsetMode::Additive) { + if (origin != nullptr) { // global = *origin; // Copy. // global.add(offset).add(animationPose); global.x = origin->x + offset.x + animationPose.x; global.scaleX = origin->scaleX * offset.scaleX * animationPose.scaleX; global.scaleY = origin->scaleY * offset.scaleY * animationPose.scaleY; - if (DragonBones::yDown) - { + if (DragonBones::yDown) { global.y = origin->y + offset.y + animationPose.y; global.skew = origin->skew + offset.skew + animationPose.skew; global.rotation = origin->rotation + offset.rotation + animationPose.rotation; - } - else - { + } else { global.y = origin->y - offset.y + animationPose.y; global.skew = origin->skew - offset.skew + animationPose.skew; global.rotation = origin->rotation - offset.rotation + animationPose.rotation; } - } - else - { + } else { global = offset; // Copy. - if (!DragonBones::yDown) - { + if (!DragonBones::yDown) { global.y = -global.y; global.skew = -global.skew; global.rotation = -global.rotation; } global.add(animationPose); } - } - else if (offsetMode == OffsetMode::None) - { - if (origin != nullptr) - { + } else if (offsetMode == OffsetMode::None) { + if (origin != nullptr) { global = *origin; global.add(animationPose); - } - else - { + } else { global = animationPose; } - } - else - { + } else { inherit = false; global = offset; - if (!DragonBones::yDown) - { + if (!DragonBones::yDown) { global.y = -global.y; global.skew = -global.skew; global.rotation = -global.rotation; } } - if (inherit) - { + if (inherit) { const auto& parentMatrix = _parent->globalTransformMatrix; - if (_boneData->inheritScale) - { - if (!_boneData->inheritRotation) - { + if (_boneData->inheritScale) { + if (!_boneData->inheritRotation) { _parent->updateGlobalTransform(); - if (flipX && flipY) - { + if (flipX && flipY) { rotation = global.rotation - (_parent->global.rotation + Transform::PI); - } - else if (flipX) - { + } else if (flipX) { rotation = global.rotation + _parent->global.rotation + Transform::PI; - } - else if (flipY) - { + } else if (flipY) { rotation = global.rotation + _parent->global.rotation; - } - else - { + } else { rotation = global.rotation - _parent->global.rotation; } @@ -124,92 +96,64 @@ void Bone::_updateGlobalTransformMatrix(bool isCache) global.toMatrix(globalTransformMatrix); globalTransformMatrix.concat(parentMatrix); - if (_boneData->inheritTranslation) - { + if (_boneData->inheritTranslation) { global.x = globalTransformMatrix.tx; global.y = globalTransformMatrix.ty; - } - else - { + } else { globalTransformMatrix.tx = global.x; globalTransformMatrix.ty = global.y; } - if (isCache) - { + if (isCache) { global.fromMatrix(globalTransformMatrix); - } - else - { + } else { _globalDirty = true; } - } - else - { - if (_boneData->inheritTranslation) - { + } else { + if (_boneData->inheritTranslation) { const auto x = global.x; const auto y = global.y; global.x = parentMatrix.a * x + parentMatrix.c * y + parentMatrix.tx; global.y = parentMatrix.b * x + parentMatrix.d * y + parentMatrix.ty; - } - else - { - if (flipX) - { + } else { + if (flipX) { global.x = -global.x; } - if (flipY) - { + if (flipY) { global.y = -global.y; } } - if (_boneData->inheritRotation) - { + if (_boneData->inheritRotation) { _parent->updateGlobalTransform(); - if (_parent->global.scaleX < 0.0f) - { + if (_parent->global.scaleX < 0.0f) { rotation = global.rotation + _parent->global.rotation + Transform::PI; - } - else - { + } else { rotation = global.rotation + _parent->global.rotation; } - if (parentMatrix.a * parentMatrix.d - parentMatrix.b * parentMatrix.c < 0.0f) - { + if (parentMatrix.a * parentMatrix.d - parentMatrix.b * parentMatrix.c < 0.0f) { rotation -= global.rotation * 2.0f; - if (flipX != flipY || _boneData->inheritReflection) - { + if (flipX != flipY || _boneData->inheritReflection) { global.skew += Transform::PI; } - - if (!DragonBones::yDown) - { + + if (!DragonBones::yDown) { global.skew = -global.skew; } } global.rotation = rotation; - } - else if (flipX || flipY) - { - if (flipX && flipY) - { + } else if (flipX || flipY) { + if (flipX && flipY) { rotation = global.rotation + Transform::PI; - } - else - { - if (flipX) - { + } else { + if (flipX) { rotation = Transform::PI - global.rotation; - } - else - { + } else { rotation = -global.rotation; } @@ -221,33 +165,22 @@ void Bone::_updateGlobalTransformMatrix(bool isCache) global.toMatrix(globalTransformMatrix); } - } - else - { - if (flipX || flipY) - { - if (flipX) - { + } else { + if (flipX || flipY) { + if (flipX) { global.x = -global.x; } - if (flipY) - { + if (flipY) { global.y = -global.y; } - if (flipX && flipY) - { + if (flipX && flipY) { rotation = global.rotation + Transform::PI; - } - else - { - if (flipX) - { + } else { + if (flipX) { rotation = Transform::PI - global.rotation; - } - else - { + } else { rotation = -global.rotation; } @@ -261,18 +194,15 @@ void Bone::_updateGlobalTransformMatrix(bool isCache) } } -void Bone::init(const BoneData* boneData, Armature* armatureValue) -{ - if (_boneData != nullptr) - { +void Bone::init(const BoneData* boneData, Armature* armatureValue) { + if (_boneData != nullptr) { return; } _boneData = boneData; _armature = armatureValue; - if (_boneData->parent != nullptr) - { + if (_boneData->parent != nullptr) { _parent = _armature->getBone(_boneData->parent->name); } @@ -281,66 +211,53 @@ void Bone::init(const BoneData* boneData, Armature* armatureValue) origin = &(_boneData->transform); } -void Bone::update(int cacheFrameIndex) -{ +void Bone::update(int cacheFrameIndex) { _blendState.dirty = false; - if (cacheFrameIndex >= 0 && _cachedFrameIndices != nullptr) - { + if (cacheFrameIndex >= 0 && _cachedFrameIndices != nullptr) { const auto cachedFrameIndex = (*_cachedFrameIndices)[cacheFrameIndex]; if (cachedFrameIndex >= 0 && _cachedFrameIndex == cachedFrameIndex) // Same cache. { _transformDirty = false; - } - else if (cachedFrameIndex >= 0) // Has been Cached. + } else if (cachedFrameIndex >= 0) // Has been Cached. { _transformDirty = true; _cachedFrameIndex = cachedFrameIndex; - } - else - { + } else { if (_hasConstraint) // Update constraints. { - for (const auto constraint : _armature->_constraints) - { - if (constraint->_root == this) - { + for (const auto constraint : _armature->_constraints) { + if (constraint->_root == this) { constraint->update(); } } } - if ( _transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) // Dirty. + if (_transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) // Dirty. { _transformDirty = true; _cachedFrameIndex = -1; - } - else if (_cachedFrameIndex >= 0) // Same cache, but not set index yet. + } else if (_cachedFrameIndex >= 0) // Same cache, but not set index yet. { _transformDirty = false; (*_cachedFrameIndices)[cacheFrameIndex] = _cachedFrameIndex; - } - else // Dirty. + } else // Dirty. { _transformDirty = true; _cachedFrameIndex = -1; } } - } - else - { + } else { if (_hasConstraint) // Update constraints. { - for (const auto constraint : _armature->_constraints) - { - if (constraint->_root == this) - { + for (const auto constraint : _armature->_constraints) { + if (constraint->_root == this) { constraint->update(); } } } - if ( _transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) // Dirty. + if (_transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) // Dirty. { cacheFrameIndex = -1; _transformDirty = true; @@ -348,46 +265,35 @@ void Bone::update(int cacheFrameIndex) } } - if (_transformDirty) - { + if (_transformDirty) { _transformDirty = false; _childrenTransformDirty = true; // - if (_cachedFrameIndex < 0) - { + if (_cachedFrameIndex < 0) { const auto isCache = cacheFrameIndex >= 0; - if (_localDirty) - { + if (_localDirty) { _updateGlobalTransformMatrix(isCache); } - if (isCache && _cachedFrameIndices != nullptr) - { + if (isCache && _cachedFrameIndices != nullptr) { _cachedFrameIndex = (*_cachedFrameIndices)[cacheFrameIndex] = _armature->_armatureData->setCacheFrame(globalTransformMatrix, global); } - } - else - { + } else { _armature->_armatureData->getCacheFrame(globalTransformMatrix, global, _cachedFrameIndex); } // - } - else if (_childrenTransformDirty) - { + } else if (_childrenTransformDirty) { _childrenTransformDirty = false; } _localDirty = true; } -void Bone::updateByConstraint() -{ - if (_localDirty) - { +void Bone::updateByConstraint() { + if (_localDirty) { _localDirty = false; - if (_transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) - { + if (_transformDirty || (_parent != nullptr && _parent->_childrenTransformDirty)) { _updateGlobalTransformMatrix(true); } @@ -395,35 +301,28 @@ void Bone::updateByConstraint() } } -bool Bone::contains(const Bone* value) const -{ - if (value == this) - { +bool Bone::contains(const Bone* value) const { + if (value == this) { return false; } auto ancestor = value; - while (ancestor != this && ancestor != nullptr) - { + while (ancestor != this && ancestor != nullptr) { ancestor = ancestor->getParent(); } return ancestor == this; } -void Bone::setVisible(bool value) -{ - if (_visible == value) - { +void Bone::setVisible(bool value) { + if (_visible == value) { return; } _visible = value; - for (const auto & slot : _armature->getSlots()) - { - if (slot->getParent() == this) - { + for (const auto& slot : _armature->getSlots()) { + if (slot->getParent() == this) { slot->_updateVisible(); } } diff --git a/native/cocos/editor-support/dragonbones/armature/Bone.h b/native/cocos/editor-support/dragonbones/armature/Bone.h index 3395b8a097..710d65d1b1 100644 --- a/native/cocos/editor-support/dragonbones/armature/Bone.h +++ b/native/cocos/editor-support/dragonbones/armature/Bone.h @@ -47,8 +47,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Bone final : public TransformObject -{ +class Bone final : public TransformObject { BIND_CLASS_TYPE_A(Bone); public: @@ -147,8 +146,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void invalidUpdate() - { + inline void invalidUpdate() { _transformDirty = true; } /** @@ -174,8 +172,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline const BoneData* getBoneData() const - { + inline const BoneData* getBoneData() const { return _boneData; } /** @@ -192,8 +189,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline bool getVisible() const - { + inline bool getVisible() const { return _visible; } void setVisible(bool value); @@ -207,8 +203,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const - { + inline const std::string& getName() const { return _boneData->name; } /** @@ -221,8 +216,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline Bone* getParent() const - { + inline Bone* getParent() const { return _parent; } diff --git a/native/cocos/editor-support/dragonbones/armature/Constraint.cpp b/native/cocos/editor-support/dragonbones/armature/Constraint.cpp index b1943017d2..9bc4e0518e 100644 --- a/native/cocos/editor-support/dragonbones/armature/Constraint.cpp +++ b/native/cocos/editor-support/dragonbones/armature/Constraint.cpp @@ -12,8 +12,7 @@ Matrix Constraint::_helpMatrix; Transform Constraint::_helpTransform; Point Constraint::_helpPoint; -void Constraint::_onClear() -{ +void Constraint::_onClear() { _constraintData = nullptr; _armature = nullptr; _target = nullptr; @@ -21,8 +20,7 @@ void Constraint::_onClear() _bone = nullptr; } -void IKConstraint::_onClear() -{ +void IKConstraint::_onClear() { Constraint::_onClear(); _scaleEnabled = false; @@ -30,15 +28,13 @@ void IKConstraint::_onClear() _weight = 1.0f; } -void IKConstraint::_computeA() -{ +void IKConstraint::_computeA() { const auto& ikGlobal = _target->global; auto& global = _root->global; auto& globalTransformMatrix = _root->globalTransformMatrix; auto radian = std::atan2(ikGlobal.y - global.y, ikGlobal.x - global.x); - if (global.scaleX < 0.0f) - { + if (global.scaleX < 0.0f) { radian += Transform::PI; } @@ -46,8 +42,7 @@ void IKConstraint::_computeA() global.toMatrix(globalTransformMatrix); } -void IKConstraint::_computeB() -{ +void IKConstraint::_computeB() { const auto boneLength = _bone->_boneData->length; const auto parent = _root; const auto& ikGlobal = _target->global; @@ -73,19 +68,13 @@ void IKConstraint::_computeB() const auto lT = sqrt(lTT); auto radianA = 0.0f; - if (lL + lP <= lT || lT + lL <= lP || lT + lP <= lL) - { + if (lL + lP <= lT || lT + lL <= lP || lT + lP <= lL) { radianA = std::atan2(ikGlobal.y - parentGlobal.y, ikGlobal.x - parentGlobal.x); - if (lL + lP <= lT) - { - } - else if (lP < lL) - { + if (lL + lP <= lT) { + } else if (lP < lL) { radianA += Transform::PI; } - } - else - { + } else { const auto h = (lPP - lLL + lTT) / (2.0f * lTT); const auto r = sqrt(lPP - h * h * lTT) / lT; const auto hX = parentGlobal.x + (dX * h); @@ -95,19 +84,15 @@ void IKConstraint::_computeB() auto isPPR = false; const auto parentParent = parent->getParent(); - if (parentParent != nullptr) - { + if (parentParent != nullptr) { auto parentParentMatrix = parentParent->globalTransformMatrix; isPPR = parentParentMatrix.a * parentParentMatrix.d - parentParentMatrix.b * parentParentMatrix.c < 0.0f; } - if (isPPR != _bendPositive) - { + if (isPPR != _bendPositive) { global.x = hX - rX; global.y = hY - rY; - } - else - { + } else { global.x = hX + rX; global.y = hY + rY; } @@ -132,10 +117,8 @@ void IKConstraint::_computeB() global.toMatrix(globalTransformMatrix); } -void IKConstraint::init(ConstraintData* constraintData, Armature* armature) -{ - if (_constraintData != nullptr) - { +void IKConstraint::init(ConstraintData* constraintData, Armature* armature) { + if (_constraintData != nullptr) { return; } @@ -155,27 +138,21 @@ void IKConstraint::init(ConstraintData* constraintData, Armature* armature) _root->_hasConstraint = true; } -void IKConstraint::update() -{ +void IKConstraint::update() { _root->updateByConstraint(); - if (_bone != nullptr) - { + if (_bone != nullptr) { _bone->updateByConstraint(); _computeB(); - } - else - { + } else { _computeA(); } } -void IKConstraint::invalidUpdate() -{ +void IKConstraint::invalidUpdate() { _root->invalidUpdate(); - if (_bone != nullptr) - { + if (_bone != nullptr) { _bone->invalidUpdate(); } } diff --git a/native/cocos/editor-support/dragonbones/armature/Constraint.h b/native/cocos/editor-support/dragonbones/armature/Constraint.h index 13abed418a..746874139c 100644 --- a/native/cocos/editor-support/dragonbones/armature/Constraint.h +++ b/native/cocos/editor-support/dragonbones/armature/Constraint.h @@ -38,8 +38,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class Constraint : public BaseObject -{ +class Constraint : public BaseObject { ABSTRACT_CLASS(Constraint) protected: @@ -75,16 +74,14 @@ public: virtual void update() = 0; virtual void invalidUpdate() = 0; - inline const std::string& getName() - { + inline const std::string& getName() { return _constraintData->name; } }; /** * @internal */ -class IKConstraint : public Constraint -{ +class IKConstraint : public Constraint { BIND_CLASS_TYPE_A(IKConstraint); public: @@ -98,7 +95,7 @@ public: * @internal */ float _weight; - + private: bool _scaleEnabled; diff --git a/native/cocos/editor-support/dragonbones/armature/DeformVertices.cpp b/native/cocos/editor-support/dragonbones/armature/DeformVertices.cpp index b6c68b212c..ca5906a176 100644 --- a/native/cocos/editor-support/dragonbones/armature/DeformVertices.cpp +++ b/native/cocos/editor-support/dragonbones/armature/DeformVertices.cpp @@ -6,26 +6,21 @@ DRAGONBONES_NAMESPACE_BEGIN -void DeformVertices::_onClear() -{ +void DeformVertices::_onClear() { verticesDirty = false; vertices.clear(); bones.clear(); verticesData = nullptr; } -void DeformVertices::init(const VerticesData* verticesDataValue, Armature* armature) -{ +void DeformVertices::init(const VerticesData* verticesDataValue, Armature* armature) { verticesData = verticesDataValue; - if (verticesData != nullptr) - { + if (verticesData != nullptr) { unsigned vertexCount = 0; - if (verticesData->weight != nullptr) - { + if (verticesData->weight != nullptr) { vertexCount = verticesData->weight->count * 2; - } - else { + } else { vertexCount = verticesData->data->intArray[verticesData->offset + (unsigned)BinaryOffset::MeshVertexCount] * 2; } @@ -33,25 +28,19 @@ void DeformVertices::init(const VerticesData* verticesDataValue, Armature* armat vertices.resize(vertexCount); bones.clear(); // - for (std::size_t i = 0, l = vertices.size(); i < l; ++i) - { + for (std::size_t i = 0, l = vertices.size(); i < l; ++i) { vertices[i] = 0.0f; } - if (verticesData->weight != nullptr) - { - for (std::size_t i = 0, l = verticesData->weight->bones.size(); i < l; ++i) - { + if (verticesData->weight != nullptr) { + for (std::size_t i = 0, l = verticesData->weight->bones.size(); i < l; ++i) { const auto bone = armature->getBone(verticesData->weight->bones[i]->name); - if (bone != nullptr) - { + if (bone != nullptr) { bones.push_back(bone); } } } - } - else - { + } else { verticesDirty = false; vertices.clear(); bones.clear(); @@ -59,12 +48,9 @@ void DeformVertices::init(const VerticesData* verticesDataValue, Armature* armat } } -bool DeformVertices::isBonesUpdate() const -{ - for (const auto bone : bones) - { - if (bone != nullptr && bone->_childrenTransformDirty) - { +bool DeformVertices::isBonesUpdate() const { + for (const auto bone : bones) { + if (bone != nullptr && bone->_childrenTransformDirty) { return true; } } diff --git a/native/cocos/editor-support/dragonbones/armature/DeformVertices.h b/native/cocos/editor-support/dragonbones/armature/DeformVertices.h index 49a67eb167..9df25b30c7 100644 --- a/native/cocos/editor-support/dragonbones/armature/DeformVertices.h +++ b/native/cocos/editor-support/dragonbones/armature/DeformVertices.h @@ -30,8 +30,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class DeformVertices : public BaseObject -{ +class DeformVertices : public BaseObject { BIND_CLASS_TYPE_A(DeformVertices); public: diff --git a/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h b/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h index 0e9fcdf380..07c97b2585 100644 --- a/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h +++ b/native/cocos/editor-support/dragonbones/armature/IArmatureProxy.h @@ -40,8 +40,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 5.0 * @language zh_CN */ -class IArmatureProxy : public IEventDispatcher -{ +class IArmatureProxy : public IEventDispatcher { ABSTRACT_CLASS(IArmatureProxy); public: @@ -106,7 +105,7 @@ public: * @language zh_CN */ virtual Animation* getAnimation() const = 0; - + /** * - Gets render order * @version Cocos Creator 2.3 diff --git a/native/cocos/editor-support/dragonbones/armature/Slot.cpp b/native/cocos/editor-support/dragonbones/armature/Slot.cpp index 67370ab355..c4bf396c64 100644 --- a/native/cocos/editor-support/dragonbones/armature/Slot.cpp +++ b/native/cocos/editor-support/dragonbones/armature/Slot.cpp @@ -13,41 +13,31 @@ DRAGONBONES_NAMESPACE_BEGIN -void Slot::_onClear() -{ +void Slot::_onClear() { TransformObject::_onClear(); std::vector> disposeDisplayList; - for (const auto& pair : this->_displayList) - { + for (const auto& pair : this->_displayList) { if ( pair.first != nullptr && pair.first != _rawDisplay && pair.first != _meshDisplay && - std::find(disposeDisplayList.cbegin(), disposeDisplayList.cend(), pair) == disposeDisplayList.cend() - ) - { + std::find(disposeDisplayList.cbegin(), disposeDisplayList.cend(), pair) == disposeDisplayList.cend()) { disposeDisplayList.push_back(pair); } } - for (const auto& pair : disposeDisplayList) - { - if (pair.second == DisplayType::Armature) - { + for (const auto& pair : disposeDisplayList) { + if (pair.second == DisplayType::Armature) { static_cast(pair.first)->returnToPool(); - } - else - { + } else { _disposeDisplay(pair.first, true); } } - if (_deformVertices != nullptr) - { + if (_deformVertices != nullptr) { _deformVertices->returnToPool(); } - if (_meshDisplay && _meshDisplay != _rawDisplay) - { + if (_meshDisplay && _meshDisplay != _rawDisplay) { _disposeDisplay(_meshDisplay, false); } @@ -88,14 +78,11 @@ void Slot::_onClear() _cachedFrameIndices = nullptr; } -DisplayData* Slot::_getDefaultRawDisplayData(unsigned displayIndex) const -{ +DisplayData* Slot::_getDefaultRawDisplayData(unsigned displayIndex) const { const auto defaultSkin = _armature->_armatureData->defaultSkin; - if (defaultSkin != nullptr) - { + if (defaultSkin != nullptr) { const auto defaultRawDisplayDatas = defaultSkin->getDisplays(_slotData->name); - if (defaultRawDisplayDatas != nullptr) - { + if (defaultRawDisplayDatas != nullptr) { return displayIndex < defaultRawDisplayDatas->size() ? (*defaultRawDisplayDatas)[displayIndex] : nullptr; } } @@ -103,8 +90,7 @@ DisplayData* Slot::_getDefaultRawDisplayData(unsigned displayIndex) const return nullptr; } -void Slot::_updateDisplayData() -{ +void Slot::_updateDisplayData() { const auto prevDisplayData = _displayData; const auto prevVerticesData = _deformVertices != nullptr ? _deformVertices->verticesData : nullptr; const auto prevTextureData = _textureData; @@ -116,87 +102,60 @@ void Slot::_updateDisplayData() _boundingBoxData = nullptr; _textureData = nullptr; - if (_displayIndex >= 0) - { - if (_rawDisplayDatas != nullptr) - { + if (_displayIndex >= 0) { + if (_rawDisplayDatas != nullptr) { rawDisplayData = (unsigned)_displayIndex < _rawDisplayDatas->size() ? (*_rawDisplayDatas)[_displayIndex] : nullptr; } - if (rawDisplayData == nullptr) - { + if (rawDisplayData == nullptr) { rawDisplayData = _getDefaultRawDisplayData(_displayIndex); } - if ((unsigned)_displayIndex < _displayDatas.size()) - { + if ((unsigned)_displayIndex < _displayDatas.size()) { _displayData = _displayDatas[_displayIndex]; } } // Update texture and mesh data. - if (_displayData != nullptr) - { - if (_displayData->type == DisplayType::Mesh) - { + if (_displayData != nullptr) { + if (_displayData->type == DisplayType::Mesh) { currentVerticesData = &static_cast(_displayData)->vertices; - } - else if (_displayData->type == DisplayType::Path) - { + } else if (_displayData->type == DisplayType::Path) { // TODO - } - else if (rawDisplayData != nullptr) - { - if (rawDisplayData->type == DisplayType::Mesh) - { + } else if (rawDisplayData != nullptr) { + if (rawDisplayData->type == DisplayType::Mesh) { currentVerticesData = &static_cast(rawDisplayData)->vertices; - } - else if (rawDisplayData->type == DisplayType::Path) - { + } else if (rawDisplayData->type == DisplayType::Path) { // TODO } } - if (_displayData->type == DisplayType::BoundingBox) - { + if (_displayData->type == DisplayType::BoundingBox) { _boundingBoxData = static_cast(_displayData)->boundingBox; - } - else if (rawDisplayData != nullptr) - { - if (rawDisplayData->type == DisplayType::BoundingBox) - { + } else if (rawDisplayData != nullptr) { + if (rawDisplayData->type == DisplayType::BoundingBox) { _boundingBoxData = static_cast(rawDisplayData)->boundingBox; } } - if (_displayData->type == DisplayType::Image) - { + if (_displayData->type == DisplayType::Image) { _textureData = static_cast(_displayData)->texture; - } - else if (_displayData->type == DisplayType::Mesh) - { + } else if (_displayData->type == DisplayType::Mesh) { _textureData = static_cast(_displayData)->texture; } } // Update bounding box data. - if (_displayData != nullptr && _displayData->type == DisplayType::BoundingBox) - { + if (_displayData != nullptr && _displayData->type == DisplayType::BoundingBox) { _boundingBoxData = static_cast(_displayData)->boundingBox; - } - else if (rawDisplayData != nullptr && rawDisplayData->type == DisplayType::BoundingBox) - { + } else if (rawDisplayData != nullptr && rawDisplayData->type == DisplayType::BoundingBox) { _boundingBoxData = static_cast(rawDisplayData)->boundingBox; - } - else - { + } else { _boundingBoxData = nullptr; } - if (_displayData != prevDisplayData || currentVerticesData != prevVerticesData || _textureData != prevTextureData) - { - if (currentVerticesData == nullptr && _textureData != nullptr) - { + if (_displayData != prevDisplayData || currentVerticesData != prevVerticesData || _textureData != prevTextureData) { + if (currentVerticesData == nullptr && _textureData != nullptr) { const auto imageDisplayData = static_cast(_displayData); const auto scale = _textureData->parent->scale * _armature->_armatureData->scale; const auto frame = _textureData->frame; @@ -208,8 +167,7 @@ void Slot::_updateDisplayData() float width = rect.width; float height = rect.height; - if (_textureData->rotated && frame == nullptr) - { + if (_textureData->rotated && frame == nullptr) { width = rect.height; height = rect.width; } @@ -217,15 +175,13 @@ void Slot::_updateDisplayData() _pivotX *= width * scale; _pivotY *= height * scale; - if (frame != nullptr) - { + if (frame != nullptr) { _pivotX += frame->x * scale; _pivotY += frame->y * scale; } // Update replace pivot. - if (_displayData != nullptr && rawDisplayData != nullptr && _displayData != rawDisplayData) - { + if (_displayData != nullptr && rawDisplayData != nullptr && _displayData != rawDisplayData) { rawDisplayData->transform.toMatrix(_helpMatrix); _helpMatrix.invert(); _helpMatrix.transformPoint(0.0f, 0.0f, _helpPoint); @@ -239,43 +195,32 @@ void Slot::_updateDisplayData() _pivotY += _helpPoint.y; } - if (!DragonBones::yDown) - { + if (!DragonBones::yDown) { _pivotY = (_textureData->rotated ? _textureData->region.width : _textureData->region.height) * scale - _pivotY; } - } - else - { + } else { _pivotX = 0.0f; _pivotY = 0.0f; } // Update original transform. - if (rawDisplayData != nullptr) - { + if (rawDisplayData != nullptr) { origin = &rawDisplayData->transform; - } - else if (_displayData != nullptr) - { + } else if (_displayData != nullptr) { origin = &_displayData->transform; - } - else - { + } else { origin = nullptr; } // Update vertices. - if (currentVerticesData != prevVerticesData) - { - if (_deformVertices == nullptr) - { + if (currentVerticesData != prevVerticesData) { + if (_deformVertices == nullptr) { _deformVertices = BaseObject::borrowObject(); } _deformVertices->init(currentVerticesData, _armature); - } - else if (_deformVertices != nullptr && _textureData != prevTextureData) // Update mesh after update frame. - { + } else if (_deformVertices != nullptr && _textureData != prevTextureData) // Update mesh after update frame. + { _deformVertices->verticesDirty = true; } @@ -284,35 +229,27 @@ void Slot::_updateDisplayData() } } -void Slot::_updateDisplay() -{ +void Slot::_updateDisplay() { const auto prevDisplay = _display != nullptr ? _display : _rawDisplay; const auto prevChildArmature = _childArmature; // Update display and child armature. - if (_displayIndex >= 0 && (std::size_t)_displayIndex < _displayList.size()) - { + if (_displayIndex >= 0 && (std::size_t)_displayIndex < _displayList.size()) { const auto& displayPair = _displayList[_displayIndex]; _display = displayPair.first; - if (_display != nullptr && displayPair.second == DisplayType::Armature) - { + if (_display != nullptr && displayPair.second == DisplayType::Armature) { _childArmature = static_cast(displayPair.first); _display = _childArmature->getDisplay(); - } - else - { + } else { _childArmature = nullptr; } - } - else - { + } else { _display = nullptr; _childArmature = nullptr; } const auto currentDisplay = _display != nullptr ? _display : _rawDisplay; - if (currentDisplay != prevDisplay) - { + if (currentDisplay != prevDisplay) { _onUpdateDisplay(); _replaceDisplay(prevDisplay, prevChildArmature != nullptr); @@ -323,72 +260,56 @@ void Slot::_updateDisplay() } // Update frame. - if (currentDisplay == _rawDisplay || currentDisplay == _meshDisplay) - { + if (currentDisplay == _rawDisplay || currentDisplay == _meshDisplay) { _updateFrame(); } // Update child armature. - if (_childArmature != prevChildArmature) - { - if (prevChildArmature != nullptr) - { + if (_childArmature != prevChildArmature) { + if (prevChildArmature != nullptr) { prevChildArmature->_parent = nullptr; // Update child armature parent. prevChildArmature->setClock(nullptr); - if (prevChildArmature->inheritAnimation) - { + if (prevChildArmature->inheritAnimation) { prevChildArmature->getAnimation()->reset(); } } - if (_childArmature != nullptr) - { + if (_childArmature != nullptr) { _childArmature->_parent = this; // Update child armature parent. _childArmature->setClock(_armature->getClock()); if (_childArmature->inheritAnimation) // Set child armature cache frameRate. { - if (_childArmature->getCacheFrameRate() == 0) - { + if (_childArmature->getCacheFrameRate() == 0) { const auto chacheFrameRate = this->_armature->getCacheFrameRate(); - if (chacheFrameRate != 0) - { + if (chacheFrameRate != 0) { _childArmature->setCacheFrameRate(chacheFrameRate); } } // Child armature action. std::vector* actions = nullptr; - if (_displayData != nullptr && _displayData->type == DisplayType::Armature) - { + if (_displayData != nullptr && _displayData->type == DisplayType::Armature) { actions = &(static_cast(_displayData)->actions); - } - else if(_displayIndex >= 0 && _rawDisplayDatas != nullptr) - { + } else if (_displayIndex >= 0 && _rawDisplayDatas != nullptr) { auto rawDisplayData = (unsigned)_displayIndex < _rawDisplayDatas->size() ? (*_rawDisplayDatas)[_displayIndex] : nullptr; - if (rawDisplayData == nullptr) - { + if (rawDisplayData == nullptr) { rawDisplayData = _getDefaultRawDisplayData(_displayIndex); } - if (rawDisplayData != nullptr && rawDisplayData->type == DisplayType::Armature) - { + if (rawDisplayData != nullptr && rawDisplayData->type == DisplayType::Armature) { actions = &(static_cast(rawDisplayData)->actions); } } - if (actions != nullptr && !actions->empty()) - { - for (const auto action : *actions) - { + if (actions != nullptr && !actions->empty()) { + for (const auto action : *actions) { const auto eventObject = BaseObject::borrowObject(); EventObject::actionDataToInstance(action, eventObject, _armature); eventObject->slot = this; _armature->_bufferAction(eventObject, false); } - } - else - { + } else { _childArmature->getAnimation()->play(); } } @@ -396,36 +317,28 @@ void Slot::_updateDisplay() } } -void Slot::_updateGlobalTransformMatrix(bool isCache) -{ +void Slot::_updateGlobalTransformMatrix(bool isCache) { const auto& parentMatrix = _parent->globalTransformMatrix; globalTransformMatrix = _localMatrix; // Copy. globalTransformMatrix.concat(parentMatrix); - if (isCache) - { + if (isCache) { global.fromMatrix(globalTransformMatrix); - } - else - { + } else { _globalDirty = true; } } -bool Slot::_setDisplayIndex(int value, bool isAnimation) -{ - if (isAnimation) - { - if (_animationDisplayIndex == value) - { +bool Slot::_setDisplayIndex(int value, bool isAnimation) { + if (isAnimation) { + if (_animationDisplayIndex == value) { return false; } _animationDisplayIndex = value; } - if (_displayIndex == value) - { + if (_displayIndex == value) { return false; } @@ -437,10 +350,8 @@ bool Slot::_setDisplayIndex(int value, bool isAnimation) return _displayDirty; } -bool Slot::_setZorder(int value) -{ - if (_zOrder == value) - { +bool Slot::_setZorder(int value) { + if (_zOrder == value) { //return false; } @@ -450,50 +361,38 @@ bool Slot::_setZorder(int value) return _zOrderDirty; } -bool Slot::_setColor(const ColorTransform& value) -{ +bool Slot::_setColor(const ColorTransform& value) { _colorTransform = value; // copy _colorDirty = true; return true; } -bool Slot::_setDisplayList(const std::vector>& value) -{ - if (!value.empty()) - { - if (_displayList.size() != value.size()) - { +bool Slot::_setDisplayList(const std::vector>& value) { + if (!value.empty()) { + if (_displayList.size() != value.size()) { _displayList.resize(value.size()); } - for (std::size_t i = 0, l = value.size(); i < l; ++i) - { + for (std::size_t i = 0, l = value.size(); i < l; ++i) { const auto& eachPair = value[i]; if ( eachPair.first != nullptr && eachPair.first != _rawDisplay && eachPair.first != _meshDisplay && - eachPair.second != DisplayType::Armature && - std::find(_displayList.cbegin(), _displayList.cend(), eachPair) == _displayList.cend() - ) - { + eachPair.second != DisplayType::Armature && + std::find(_displayList.cbegin(), _displayList.cend(), eachPair) == _displayList.cend()) { _initDisplay(eachPair.first, true); } _displayList[i].first = eachPair.first; _displayList[i].second = eachPair.second; } - } - else if (!_displayList.empty()) - { + } else if (!_displayList.empty()) { _displayList.clear(); } - if (_displayIndex >= 0 && (std::size_t)_displayIndex < _displayList.size()) - { + if (_displayIndex >= 0 && (std::size_t)_displayIndex < _displayList.size()) { _displayDirty = _display != _displayList[_displayIndex].first; - } - else - { + } else { _displayDirty = _display != nullptr; } @@ -502,10 +401,8 @@ bool Slot::_setDisplayList(const std::vector>& val return _displayDirty; } -void Slot::init(const SlotData* slotData, Armature* armatureValue, void* rawDisplay, void* meshDisplay) -{ - if (_slotData != nullptr) - { +void Slot::init(const SlotData* slotData, Armature* armatureValue, void* rawDisplay, void* meshDisplay) { + if (_slotData != nullptr) { return; } @@ -523,20 +420,16 @@ void Slot::init(const SlotData* slotData, Armature* armatureValue, void* rawDisp _armature = armatureValue; // const auto slotParent = _armature->getBone(_slotData->parent->name); - if (slotParent != nullptr) - { + if (slotParent != nullptr) { _parent = slotParent; - } - else - { + } else { // Never; } _armature->_addSlot(this); // _initDisplay(_rawDisplay, false); - if (_rawDisplay != _meshDisplay) - { + if (_rawDisplay != _meshDisplay) { _initDisplay(_meshDisplay, false); } @@ -544,102 +437,82 @@ void Slot::init(const SlotData* slotData, Armature* armatureValue, void* rawDisp _addDisplay(); } -void Slot::update(int cacheFrameIndex) -{ - if (_displayDirty) - { +void Slot::update(int cacheFrameIndex) { + if (_displayDirty) { _displayDirty = false; _updateDisplay(); // TODO remove slot offset. if (_transformDirty) // Update local matrix. (Only updated when both display and transform are dirty.) { - if (origin != nullptr) - { + if (origin != nullptr) { global = *origin; // Copy. global.add(offset).toMatrix(_localMatrix); - } - else - { + } else { global = offset; // Copy. global.toMatrix(_localMatrix); } } } - if (_zOrderDirty) - { + if (_zOrderDirty) { _zOrderDirty = false; _updateZOrder(); } - if (cacheFrameIndex >= 0 && _cachedFrameIndices != nullptr) - { + if (cacheFrameIndex >= 0 && _cachedFrameIndices != nullptr) { const auto cachedFrameIndex = (*_cachedFrameIndices)[cacheFrameIndex]; if (cachedFrameIndex >= 0 && _cachedFrameIndex == cachedFrameIndex) // Same cache. { _transformDirty = false; - } - else if (cachedFrameIndex >= 0) // Has been Cached. + } else if (cachedFrameIndex >= 0) // Has been Cached. { _transformDirty = true; _cachedFrameIndex = cachedFrameIndex; - } - else if (_transformDirty || _parent->_childrenTransformDirty) // Dirty. + } else if (_transformDirty || _parent->_childrenTransformDirty) // Dirty. { _transformDirty = true; _cachedFrameIndex = -1; - } - else if (_cachedFrameIndex >= 0) // Same cache, but not set index yet. + } else if (_cachedFrameIndex >= 0) // Same cache, but not set index yet. { _transformDirty = false; (*_cachedFrameIndices)[cacheFrameIndex] = _cachedFrameIndex; - } - else // Dirty. + } else // Dirty. { _transformDirty = true; _cachedFrameIndex = -1; } - } - else if (_transformDirty || this->_parent->_childrenTransformDirty) - { + } else if (_transformDirty || this->_parent->_childrenTransformDirty) { cacheFrameIndex = -1; _transformDirty = true; _cachedFrameIndex = -1; } - if (_display == nullptr) - { + if (_display == nullptr) { return; } - if (_visibleDirty) - { + if (_visibleDirty) { _visibleDirty = false; _updateVisible(); } - if (_blendModeDirty) - { + if (_blendModeDirty) { _blendModeDirty = false; _updateBlendMode(); } - if (_colorDirty) - { + if (_colorDirty) { _colorDirty = false; _updateColor(); } - if (_deformVertices != nullptr && _deformVertices->verticesData != nullptr && _display == _meshDisplay) - { + if (_deformVertices != nullptr && _deformVertices->verticesData != nullptr && _display == _meshDisplay) { const auto isSkinned = _deformVertices->verticesData->weight != nullptr; if ( _deformVertices->verticesDirty || - (isSkinned && _deformVertices->isBonesUpdate()) - ) - { + (isSkinned && _deformVertices->isBonesUpdate())) { _deformVertices->verticesDirty = false; _updateMesh(); } @@ -650,22 +523,17 @@ void Slot::update(int cacheFrameIndex) } } - if (_transformDirty) - { + if (_transformDirty) { _transformDirty = false; - if (_cachedFrameIndex < 0) - { + if (_cachedFrameIndex < 0) { const auto isCache = cacheFrameIndex >= 0; _updateGlobalTransformMatrix(isCache); - if (isCache && _cachedFrameIndices != nullptr) - { + if (isCache && _cachedFrameIndices != nullptr) { _cachedFrameIndex = (*_cachedFrameIndices)[cacheFrameIndex] = _armature->_armatureData->setCacheFrame(globalTransformMatrix, global); } - } - else - { + } else { _armature->_armatureData->getCacheFrame(globalTransformMatrix, global, _cachedFrameIndex); } @@ -673,25 +541,18 @@ void Slot::update(int cacheFrameIndex) } } -void Slot::updateTransformAndMatrix() -{ - if (_transformDirty) - { +void Slot::updateTransformAndMatrix() { + if (_transformDirty) { _transformDirty = false; _updateGlobalTransformMatrix(false); } } -void Slot::replaceDisplayData(DisplayData *displayData, int displayIndex) -{ - if (displayIndex < 0) - { - if (_displayIndex < 0) - { +void Slot::replaceDisplayData(DisplayData* displayData, int displayIndex) { + if (displayIndex < 0) { + if (_displayIndex < 0) { displayIndex = 0; - } - else - { + } else { displayIndex = _displayIndex; } } @@ -703,10 +564,8 @@ void Slot::replaceDisplayData(DisplayData *displayData, int displayIndex) _displayDatas[displayIndex] = displayData; } -bool Slot::containsPoint(float x, float y) -{ - if (_boundingBoxData == nullptr) - { +bool Slot::containsPoint(float x, float y) { + if (_boundingBoxData == nullptr) { return false; } @@ -723,11 +582,8 @@ int Slot::intersectsSegment( float xA, float yA, float xB, float yB, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ - if (_boundingBoxData == nullptr) - { + Point* normalRadians) { + if (_boundingBoxData == nullptr) { return 0; } @@ -742,39 +598,28 @@ int Slot::intersectsSegment( yB = _helpPoint.y; const auto intersectionCount = _boundingBoxData->intersectsSegment(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians); - if (intersectionCount > 0) - { - if (intersectionCount == 1 || intersectionCount == 2) - { - if (intersectionPointA != nullptr) - { + if (intersectionCount > 0) { + if (intersectionCount == 1 || intersectionCount == 2) { + if (intersectionPointA != nullptr) { globalTransformMatrix.transformPoint(intersectionPointA->x, intersectionPointA->y, *intersectionPointA); - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = intersectionPointA->x; intersectionPointB->y = intersectionPointA->y; } - } - else if (intersectionPointB != nullptr) - { + } else if (intersectionPointB != nullptr) { globalTransformMatrix.transformPoint(intersectionPointB->x, intersectionPointB->y, *intersectionPointB); } - } - else - { - if (intersectionPointA != nullptr) - { + } else { + if (intersectionPointA != nullptr) { globalTransformMatrix.transformPoint(intersectionPointA->x, intersectionPointA->y, *intersectionPointA); } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { globalTransformMatrix.transformPoint(intersectionPointB->x, intersectionPointB->y, *intersectionPointB); } } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { globalTransformMatrix.transformPoint(cos(normalRadians->x), sin(normalRadians->x), _helpPoint, true); normalRadians->x = atan2(_helpPoint.y, _helpPoint.x); @@ -786,10 +631,8 @@ int Slot::intersectsSegment( return intersectionCount; } -void Slot::setVisible(bool value) -{ - if (_visible == value) - { +void Slot::setVisible(bool value) { + if (_visible == value) { return; } @@ -797,105 +640,81 @@ void Slot::setVisible(bool value) _updateVisible(); } -void Slot::setDisplayIndex(int value) -{ - if (_setDisplayIndex(value)) - { +void Slot::setDisplayIndex(int value) { + if (_setDisplayIndex(value)) { update(-1); } } //TODO lsc check -void Slot::setDisplayList(const std::vector>& value) -{ +void Slot::setDisplayList(const std::vector>& value) { const auto backupDisplayList = _displayList; // copy auto disposeDisplayList = backupDisplayList; // copy disposeDisplayList.clear(); - if (_setDisplayList(value)) - { + if (_setDisplayList(value)) { update(-1); } - for (const auto& pair : backupDisplayList) - { + for (const auto& pair : backupDisplayList) { if ( pair.first != nullptr && pair.first != _rawDisplay && pair.first != _meshDisplay && std::find(_displayList.cbegin(), _displayList.cend(), pair) == _displayList.cend() && - std::find(disposeDisplayList.cbegin(), disposeDisplayList.cend(), pair) == disposeDisplayList.cend() - ) - { + std::find(disposeDisplayList.cbegin(), disposeDisplayList.cend(), pair) == disposeDisplayList.cend()) { disposeDisplayList.push_back(pair); } } - for (const auto& pair : disposeDisplayList) - { - if (pair.second == DisplayType::Armature) - { + for (const auto& pair : disposeDisplayList) { + if (pair.second == DisplayType::Armature) { static_cast(pair.first)->returnToPool(); - } - else - { + } else { _disposeDisplay(pair.first, true); } } } -void Slot::setRawDisplayDatas(const std::vector* value) -{ - if (_rawDisplayDatas == value) - { +void Slot::setRawDisplayDatas(const std::vector* value) { + if (_rawDisplayDatas == value) { return; } _displayDirty = true; _rawDisplayDatas = value; - if (_rawDisplayDatas != nullptr) - { + if (_rawDisplayDatas != nullptr) { _displayDatas.resize(_rawDisplayDatas->size()); - for (std::size_t i = 0, l = _displayDatas.size(); i < l; ++i) - { + for (std::size_t i = 0, l = _displayDatas.size(); i < l; ++i) { auto rawDisplayData = (*_rawDisplayDatas)[i]; - if (rawDisplayData == nullptr) - { + if (rawDisplayData == nullptr) { rawDisplayData = _getDefaultRawDisplayData(i); } _displayDatas[i] = rawDisplayData; } - } - else - { + } else { _displayDatas.clear(); } } -void Slot::setDisplay(void* value, DisplayType displayType) -{ - if (_display == value) - { +void Slot::setDisplay(void* value, DisplayType displayType) { + if (_display == value) { return; } const auto displayListLength = _displayList.size(); - if (_displayIndex < 0 && displayListLength == 0) // Emprty + if (_displayIndex < 0 && displayListLength == 0) // Emprty { _displayIndex = 0; } - if (_displayIndex < 0) - { + if (_displayIndex < 0) { return; - } - else - { + } else { auto relpaceDisplayList = _displayList; // copy - if (displayListLength <= (std::size_t)_displayIndex) - { + if (displayListLength <= (std::size_t)_displayIndex) { relpaceDisplayList.resize(_displayIndex + 1); } @@ -906,10 +725,8 @@ void Slot::setDisplay(void* value, DisplayType displayType) } } -void Slot::setChildArmature(Armature* value) -{ - if (_childArmature == value) - { +void Slot::setChildArmature(Armature* value) { + if (_childArmature == value) { return; } diff --git a/native/cocos/editor-support/dragonbones/armature/Slot.h b/native/cocos/editor-support/dragonbones/armature/Slot.h index 8fb54d215f..e2d00a93b9 100644 --- a/native/cocos/editor-support/dragonbones/armature/Slot.h +++ b/native/cocos/editor-support/dragonbones/armature/Slot.h @@ -53,8 +53,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Slot : public TransformObject -{ +class Slot : public TransformObject { public: /** * - Displays the animated state or mixed group name controlled by the object, set to null to be controlled by all animation states. @@ -142,12 +141,10 @@ protected: Bone* _parent; public: - Slot() : - _deformVertices(nullptr), - _rawDisplay(nullptr), - _meshDisplay(nullptr) - {} - virtual ~Slot() {}; + Slot() : _deformVertices(nullptr), + _rawDisplay(nullptr), + _meshDisplay(nullptr) {} + virtual ~Slot(){}; protected: virtual void _onClear() override; @@ -267,8 +264,7 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ); + Point* normalRadians = nullptr); /** * - Forces the slot to update the state of the display object in the next frame. * @version DragonBones 4.5 @@ -279,8 +275,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline void invalidUpdate() - { + inline void invalidUpdate() { _displayDirty = true; _transformDirty = true; } @@ -296,8 +291,7 @@ public: * @version DragonBones 5.6 * @language zh_CN */ - inline bool getVisible() const - { + inline bool getVisible() const { return _visible; } void setVisible(bool value); @@ -325,8 +319,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - inline int getDisplayIndex() const - { + inline int getDisplayIndex() const { return _displayIndex; } void setDisplayIndex(int value); @@ -343,8 +336,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline const std::string& getName() const - { + inline const std::string& getName() const { return _slotData->name; } /** @@ -357,16 +349,14 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::vector> getDisplayList() const - { + inline std::vector> getDisplayList() const { return _displayList; } void setDisplayList(const std::vector>& value); /** * @private */ - inline const std::vector* getRawDisplayDatas() const - { + inline const std::vector* getRawDisplayDatas() const { return _rawDisplayDatas; } void setRawDisplayDatas(const std::vector* value); @@ -382,8 +372,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - const SlotData* getSlotData() const - { + const SlotData* getSlotData() const { return _slotData; } /** @@ -396,22 +385,19 @@ public: * @version DragonBones 5.0 * @language zh_CN */ - inline BoundingBoxData* getBoundingBoxData() const - { + inline BoundingBoxData* getBoundingBoxData() const { return _boundingBoxData; } /** * @private */ - inline void* getRawDisplay() const - { + inline void* getRawDisplay() const { return _rawDisplay; } /** * @private */ - inline void* getMeshDisplay() const - { + inline void* getMeshDisplay() const { return _meshDisplay; } /** @@ -436,8 +422,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void* getDisplay() const - { + inline void* getDisplay() const { return _display; } /** @@ -482,8 +467,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline Armature* getChildArmature() const - { + inline Armature* getChildArmature() const { return _childArmature; } void setChildArmature(Armature* value); @@ -497,8 +481,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline Bone* getParent() const - { + inline Bone* getParent() const { return _parent; } }; diff --git a/native/cocos/editor-support/dragonbones/armature/TransformObject.cpp b/native/cocos/editor-support/dragonbones/armature/TransformObject.cpp index c295246df9..b473785437 100644 --- a/native/cocos/editor-support/dragonbones/armature/TransformObject.cpp +++ b/native/cocos/editor-support/dragonbones/armature/TransformObject.cpp @@ -10,8 +10,7 @@ Matrix TransformObject::_helpMatrix; Transform TransformObject::_helpTransform; Point TransformObject::_helpPoint; -void TransformObject::_onClear() -{ +void TransformObject::_onClear() { globalTransformMatrix.identity(); global.identity(); offset.identity(); @@ -22,10 +21,8 @@ void TransformObject::_onClear() _armature = nullptr; } -void TransformObject::updateGlobalTransform() -{ - if (_globalDirty) - { +void TransformObject::updateGlobalTransform() { + if (_globalDirty) { _globalDirty = false; global.fromMatrix(globalTransformMatrix); } diff --git a/native/cocos/editor-support/dragonbones/armature/TransformObject.h b/native/cocos/editor-support/dragonbones/armature/TransformObject.h index 593477f866..b9266510b1 100644 --- a/native/cocos/editor-support/dragonbones/armature/TransformObject.h +++ b/native/cocos/editor-support/dragonbones/armature/TransformObject.h @@ -40,8 +40,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 4.5 * @language zh_CN */ -class TransformObject : public BaseObject -{ +class TransformObject : public BaseObject { ABSTRACT_CLASS(TransformObject); protected: @@ -145,8 +144,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline Armature* getArmature() const - { + inline Armature* getArmature() const { return _armature; } diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp index 4d795b1351..83a33d15ea 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.cpp +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.cpp @@ -8,8 +8,7 @@ std::map BaseObject::_maxCountMap; std::map> BaseObject::_poolsMap; BaseObject::RecycleOrDestroyCallback BaseObject::_recycleOrDestroyCallback = nullptr; -void BaseObject::_returnObject(BaseObject* object) -{ +void BaseObject::_returnObject(BaseObject* object) { const auto classType = object->getClassTypeIndex(); const auto maxCountIterator = _maxCountMap.find(classType); const auto maxCount = maxCountIterator != _maxCountMap.end() ? maxCountIterator->second : _defaultMaxCount; @@ -17,47 +16,34 @@ void BaseObject::_returnObject(BaseObject* object) // If script engine gc,then alway push object into pool,not immediately delete // Because object will be referenced more then one place possibly,if delete it immediately,will // crash. - if (!DragonBones::checkInPool || pool.size() < maxCount) - { - if (!object->_isInPool) - { + if (!DragonBones::checkInPool || pool.size() < maxCount) { + if (!object->_isInPool) { object->_isInPool = true; pool.push_back(object); if (_recycleOrDestroyCallback != nullptr) _recycleOrDestroyCallback(object, 0); - } - else - { + } else { // If script engine gc,repeat push into pool will happen. - if(DragonBones::checkInPool) - { + if (DragonBones::checkInPool) { DRAGONBONES_ASSERT(false, "The object is already in the pool."); } } - } - else - { + } else { delete object; } } -void BaseObject::setObjectRecycleOrDestroyCallback(const std::function& cb) -{ +void BaseObject::setObjectRecycleOrDestroyCallback(const std::function& cb) { _recycleOrDestroyCallback = cb; } -void BaseObject::setMaxCount(std::size_t classType, unsigned maxCount) -{ - if (classType > 0) - { +void BaseObject::setMaxCount(std::size_t classType, unsigned maxCount) { + if (classType > 0) { const auto iterator = _poolsMap.find(classType); - if (iterator != _poolsMap.end()) - { + if (iterator != _poolsMap.end()) { auto& pool = iterator->second; - if (pool.size() > (size_t)maxCount) - { - for (auto i = (size_t)maxCount, l = pool.size(); i < l; ++i) - { + if (pool.size() > (size_t)maxCount) { + for (auto i = (size_t)maxCount, l = pool.size(); i < l; ++i) { delete pool[i]; } @@ -66,58 +52,42 @@ void BaseObject::setMaxCount(std::size_t classType, unsigned maxCount) } _maxCountMap[classType] = maxCount; - } - else - { + } else { _defaultMaxCount = maxCount; - for (auto& pair : _poolsMap) - { + for (auto& pair : _poolsMap) { auto& pool = pair.second; - if (pool.size() > (size_t)maxCount) - { - for (auto i = (size_t)maxCount, l = pool.size(); i < l; ++i) - { + if (pool.size() > (size_t)maxCount) { + for (auto i = (size_t)maxCount, l = pool.size(); i < l; ++i) { delete pool[i]; } pool.resize(maxCount); } - if (_maxCountMap.find(pair.first) != _maxCountMap.end()) - { + if (_maxCountMap.find(pair.first) != _maxCountMap.end()) { _maxCountMap[pair.first] = maxCount; } } } } -void BaseObject::clearPool(std::size_t classType) -{ - if (classType > 0) - { +void BaseObject::clearPool(std::size_t classType) { + if (classType > 0) { const auto iterator = _poolsMap.find(classType); - if (iterator != _poolsMap.end()) - { + if (iterator != _poolsMap.end()) { auto& pool = iterator->second; - if (!pool.empty()) - { - for (auto object : pool) - { + if (!pool.empty()) { + for (auto object : pool) { delete object; } pool.clear(); } } - } - else - { - for (auto& pair : _poolsMap) - { + } else { + for (auto& pair : _poolsMap) { auto& pool = pair.second; - if (!pool.empty()) - { - for (auto object : pool) - { + if (!pool.empty()) { + for (auto object : pool) { delete object; } @@ -128,32 +98,26 @@ void BaseObject::clearPool(std::size_t classType) } BaseObject::BaseObject() -:hashCode(BaseObject::_hashCode++) -,_isInPool(false) -{ +: hashCode(BaseObject::_hashCode++), _isInPool(false) { __allDragonBonesObjects.push_back(this); } -BaseObject::~BaseObject() -{ +BaseObject::~BaseObject() { if (_recycleOrDestroyCallback != nullptr) _recycleOrDestroyCallback(this, 1); - + auto iter = std::find(__allDragonBonesObjects.begin(), __allDragonBonesObjects.end(), this); - if (iter != __allDragonBonesObjects.end()) - { + if (iter != __allDragonBonesObjects.end()) { __allDragonBonesObjects.erase(iter); } } -void BaseObject::returnToPool() -{ +void BaseObject::returnToPool() { _onClear(); BaseObject::_returnObject(this); } -std::vector& BaseObject::getAllObjects() -{ +std::vector& BaseObject::getAllObjects() { return __allDragonBonesObjects; } diff --git a/native/cocos/editor-support/dragonbones/core/BaseObject.h b/native/cocos/editor-support/dragonbones/core/BaseObject.h index 775987e453..94efbc91cb 100644 --- a/native/cocos/editor-support/dragonbones/core/BaseObject.h +++ b/native/cocos/editor-support/dragonbones/core/BaseObject.h @@ -39,18 +39,19 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 4.5 * @language zh_CN */ -class BaseObject -{ +class BaseObject { public: - typedef std::function RecycleOrDestroyCallback; + typedef std::function RecycleOrDestroyCallback; + private: static unsigned _hashCode; static unsigned _defaultMaxCount; static std::map _maxCountMap; static std::map> _poolsMap; - static void _returnObject(BaseObject *object); + static void _returnObject(BaseObject* object); static RecycleOrDestroyCallback _recycleOrDestroyCallback; + public: static void setObjectRecycleOrDestroyCallback(const RecycleOrDestroyCallback& cb); /** @@ -81,7 +82,7 @@ public: * @language zh_CN */ static void clearPool(std::size_t classTypeIndex = 0); - template + template /** * - Get an instance of the specify class from object pool. * @param objectConstructor - The specify class. @@ -94,15 +95,12 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - static T* borrowObject() - { + static T* borrowObject() { const auto classTypeIndex = T::getTypeIndex(); const auto iterator = _poolsMap.find(classTypeIndex); - if (iterator != _poolsMap.end()) - { + if (iterator != _poolsMap.end()) { auto& pool = iterator->second; - if (!pool.empty()) - { + if (!pool.empty()) { const auto object = static_cast(pool.back()); pool.pop_back(); object->_isInPool = false; @@ -114,8 +112,9 @@ public: return object; } - + static std::vector& getAllObjects(); + public: /** * - A unique identification number assigned to the object. diff --git a/native/cocos/editor-support/dragonbones/core/DragonBones.cpp b/native/cocos/editor-support/dragonbones/core/DragonBones.cpp index c4ce982584..7a368ab152 100644 --- a/native/cocos/editor-support/dragonbones/core/DragonBones.cpp +++ b/native/cocos/editor-support/dragonbones/core/DragonBones.cpp @@ -15,19 +15,15 @@ bool DragonBones::debugDraw = false; bool DragonBones::webAssembly = false; bool DragonBones::checkInPool = true; -DragonBones::DragonBones(IEventDispatcher* eventManager) : - _events(), - _clock(nullptr), - _eventManager(eventManager) -{ +DragonBones::DragonBones(IEventDispatcher* eventManager) : _events(), + _clock(nullptr), + _eventManager(eventManager) { _clock = new WorldClock(); _eventManager = eventManager; } -DragonBones::~DragonBones() -{ - if (_clock != nullptr) - { +DragonBones::~DragonBones() { + if (_clock != nullptr) { delete _clock; } @@ -35,12 +31,9 @@ DragonBones::~DragonBones() _eventManager = nullptr; } -void DragonBones::advanceTime(float passedTime) -{ - if (!_objectsMap.empty()) - { - for (auto it = _objectsMap.begin(); it != _objectsMap.end(); it ++) - { +void DragonBones::advanceTime(float passedTime) { + if (!_objectsMap.empty()) { + for (auto it = _objectsMap.begin(); it != _objectsMap.end(); it++) { auto object = it->first; if (object) { object->returnToPool(); @@ -48,18 +41,14 @@ void DragonBones::advanceTime(float passedTime) } _objectsMap.clear(); } - - if (!_events.empty()) - { - for (std::size_t i = 0; i < _events.size(); ++i) - { + + if (!_events.empty()) { + for (std::size_t i = 0; i < _events.size(); ++i) { const auto eventObject = _events[i]; const auto armature = eventObject->armature; - if (armature->_armatureData != nullptr) - { + if (armature->_armatureData != nullptr) { armature->getProxy()->dispatchDBEvent(eventObject->type, eventObject); - if (eventObject->type == EventObject::SOUND_EVENT) - { + if (eventObject->type == EventObject::SOUND_EVENT) { _eventManager->dispatchDBEvent(eventObject->type, eventObject); } } @@ -73,27 +62,22 @@ void DragonBones::advanceTime(float passedTime) _clock->advanceTime(passedTime); } -void DragonBones::render() -{ +void DragonBones::render() { _clock->render(); } -void DragonBones::bufferEvent(EventObject* value) -{ +void DragonBones::bufferEvent(EventObject* value) { _events.push_back(value); } -void DragonBones::bufferObject(BaseObject* object) -{ - if(object == nullptr || object->isInPool())return; +void DragonBones::bufferObject(BaseObject* object) { + if (object == nullptr || object->isInPool()) return; // Just mark object will be put in pool next frame, 'true' is useless. _objectsMap[object] = true; } -WorldClock* DragonBones::getClock() -{ +WorldClock* DragonBones::getClock() { return _clock; } - DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/dragonbones/core/DragonBones.h b/native/cocos/editor-support/dragonbones/core/DragonBones.h index 86e11c6978..a87f222ff2 100644 --- a/native/cocos/editor-support/dragonbones/core/DragonBones.h +++ b/native/cocos/editor-support/dragonbones/core/DragonBones.h @@ -35,70 +35,67 @@ #include // dragonBones assert #define DRAGONBONES_ASSERT(cond, msg) \ -do { \ - assert(cond); \ -} while (0) + do { \ + assert(cond); \ + } while (0) // namespace dragonBones {} #define DRAGONBONES_NAMESPACE_BEGIN namespace dragonBones { -#define DRAGONBONES_NAMESPACE_END } +#define DRAGONBONES_NAMESPACE_END } // using dragonBones namespace #define DRAGONBONES_USING_NAME_SPACE using namespace dragonBones #define ABSTRACT_CLASS(CLASS) \ -public:\ - CLASS(){}\ +public: \ + CLASS() {} \ virtual ~CLASS(){}; -#define BIND_CLASS_TYPE(CLASS) \ -public:\ - static std::size_t getTypeIndex()\ - {\ - static const auto typeIndex = typeid(CLASS).hash_code();\ - return typeIndex;\ - }\ - virtual std::size_t getClassTypeIndex() const override\ - {\ - return CLASS::getTypeIndex();\ - }\ +#define BIND_CLASS_TYPE(CLASS) \ +public: \ + static std::size_t getTypeIndex() { \ + static const auto typeIndex = typeid(CLASS).hash_code(); \ + return typeIndex; \ + } \ + virtual std::size_t getClassTypeIndex() const override { \ + return CLASS::getTypeIndex(); \ + } -#define BIND_CLASS_TYPE_A(CLASS) \ -public:\ - static std::size_t getTypeIndex()\ - {\ - static const auto typeIndex = typeid(CLASS).hash_code();\ - return typeIndex;\ - }\ - virtual std::size_t getClassTypeIndex() const override\ - {\ - return CLASS::getTypeIndex();\ - }\ -public:\ - CLASS(){_onClear();}\ - ~CLASS(){_onClear();}\ -private:\ - CLASS(const CLASS&);\ +#define BIND_CLASS_TYPE_A(CLASS) \ +public: \ + static std::size_t getTypeIndex() { \ + static const auto typeIndex = typeid(CLASS).hash_code(); \ + return typeIndex; \ + } \ + virtual std::size_t getClassTypeIndex() const override { \ + return CLASS::getTypeIndex(); \ + } \ + \ +public: \ + CLASS() { _onClear(); } \ + ~CLASS() { _onClear(); } \ + \ +private: \ + CLASS(const CLASS&); \ void operator=(const CLASS&) -#define BIND_CLASS_TYPE_B(CLASS) \ -public:\ - static std::size_t getTypeIndex()\ - {\ - static const auto typeIndex = typeid(CLASS).hash_code();\ - return typeIndex;\ - }\ - virtual std::size_t getClassTypeIndex() const override\ - {\ - return CLASS::getTypeIndex();\ - }\ -private:\ - CLASS(const CLASS&);\ +#define BIND_CLASS_TYPE_B(CLASS) \ +public: \ + static std::size_t getTypeIndex() { \ + static const auto typeIndex = typeid(CLASS).hash_code(); \ + return typeIndex; \ + } \ + virtual std::size_t getClassTypeIndex() const override { \ + return CLASS::getTypeIndex(); \ + } \ + \ +private: \ + CLASS(const CLASS&); \ void operator=(const CLASS&) #define DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(CLASS) \ -private:\ - CLASS(const CLASS&);\ +private: \ + CLASS(const CLASS&); \ void operator=(const CLASS&); DRAGONBONES_NAMESPACE_BEGIN @@ -106,8 +103,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -enum class BinaryOffset -{ +enum class BinaryOffset { WeigthBoneCount = 0, WeigthFloatOffset = 1, WeigthBoneIndices = 2, @@ -140,8 +136,7 @@ enum class BinaryOffset /** * @internal */ -enum class ArmatureType -{ +enum class ArmatureType { Armature = 0, MovieClip = 1, Stage = 2 @@ -166,10 +161,9 @@ enum class OffsetMode { /** * @private */ -enum class DisplayType -{ - Image = 0, - Armature = 1, +enum class DisplayType { + Image = 0, + Armature = 1, Mesh = 2, BoundingBox = 3, Path = 4 @@ -185,8 +179,7 @@ enum class DisplayType * @version DragonBones 5.0 * @language zh_CN */ -enum class BoundingBoxType -{ +enum class BoundingBoxType { Rectangle = 0, Ellipse = 1, Polygon = 2 @@ -204,8 +197,7 @@ enum class ActionType { /** * @internal */ -enum class BlendMode -{ +enum class BlendMode { Normal = 0, Add = 1, Alpha = 2, @@ -324,8 +316,7 @@ enum class AnimationFadeOutMode { Single }; -enum class TextureFormat -{ +enum class TextureFormat { DEFAULT, RGBA8888, BGRA8888, @@ -336,37 +327,31 @@ enum class TextureFormat }; template -std::string to_string(const T& value) -{ +std::string to_string(const T& value) { std::ostringstream stream; stream << value; return stream.str(); } -template -inline int indexOf(const std::vector& vector, const T& value) -{ - for (std::size_t i = 0, l = vector.size(); i < l; ++i) - { - if (vector[i] == value) - { - return (int) i; +template +inline int indexOf(const std::vector& vector, const T& value) { + for (std::size_t i = 0, l = vector.size(); i < l; ++i) { + if (vector[i] == value) { + return (int)i; } } - + return -1; } -template -inline T* mapFind(const std::map& map, const std::string& key) -{ +template +inline T* mapFind(const std::map& map, const std::string& key) { auto iterator = map.find(key); return (iterator != map.end()) ? iterator->second : nullptr; } -template -inline T* mapFindB(std::map& map, const std::string& key) -{ +template +inline T* mapFindB(std::map& map, const std::string& key) { auto iterator = map.find(key); return (iterator != map.end()) ? &iterator->second : nullptr; } @@ -447,8 +432,7 @@ class BuildArmaturePackage; /** * @private */ -class DragonBones -{ +class DragonBones { DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(DragonBones) public: @@ -459,9 +443,9 @@ public: static bool debugDraw; static bool webAssembly; static bool checkInPool; - + private: - std::map _objectsMap; + std::map _objectsMap; std::vector _events; WorldClock* _clock; IEventDispatcher* _eventManager; @@ -469,15 +453,14 @@ private: public: DragonBones(IEventDispatcher* eventManager); virtual ~DragonBones(); - + void advanceTime(float passedTime); void render(); void bufferEvent(EventObject* value); void bufferObject(BaseObject* object); - + WorldClock* getClock(); - IEventDispatcher* getEventManager() const - { + IEventDispatcher* getEventManager() const { return _eventManager; } }; diff --git a/native/cocos/editor-support/dragonbones/event/EventObject.cpp b/native/cocos/editor-support/dragonbones/event/EventObject.cpp index d2a99c7ab0..1e48ebf503 100644 --- a/native/cocos/editor-support/dragonbones/event/EventObject.cpp +++ b/native/cocos/editor-support/dragonbones/event/EventObject.cpp @@ -14,14 +14,10 @@ const char* EventObject::FADE_OUT_COMPLETE = "fadeOutComplete"; const char* EventObject::FRAME_EVENT = "frameEvent"; const char* EventObject::SOUND_EVENT = "soundEvent"; -void EventObject::actionDataToInstance(const ActionData* data, EventObject* instance, Armature* armature) -{ - if (data->type == ActionType::Play) - { +void EventObject::actionDataToInstance(const ActionData* data, EventObject* instance, Armature* armature) { + if (data->type == ActionType::Play) { instance->type = EventObject::FRAME_EVENT; - } - else - { + } else { instance->type = data->type == ActionType::Frame ? EventObject::FRAME_EVENT : EventObject::SOUND_EVENT; } @@ -30,19 +26,16 @@ void EventObject::actionDataToInstance(const ActionData* data, EventObject* inst instance->actionData = data; instance->data = data->data; - if (data->bone != nullptr) - { + if (data->bone != nullptr) { instance->bone = armature->getBone(data->bone->name); } - if (data->slot != nullptr) - { + if (data->slot != nullptr) { instance->slot = armature->getSlot(data->slot->name); } } -void EventObject::_onClear() -{ +void EventObject::_onClear() { time = 0.0f; type = ""; name = ""; diff --git a/native/cocos/editor-support/dragonbones/event/EventObject.h b/native/cocos/editor-support/dragonbones/event/EventObject.h index 0c6500373d..3eb42bff77 100644 --- a/native/cocos/editor-support/dragonbones/event/EventObject.h +++ b/native/cocos/editor-support/dragonbones/event/EventObject.h @@ -37,8 +37,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 4.5 * @language zh_CN */ -class EventObject : public BaseObject -{ +class EventObject : public BaseObject { BIND_CLASS_TYPE_A(EventObject); public: diff --git a/native/cocos/editor-support/dragonbones/event/IEventDispatcher.h b/native/cocos/editor-support/dragonbones/event/IEventDispatcher.h index c46f9f064f..34dfdd0604 100644 --- a/native/cocos/editor-support/dragonbones/event/IEventDispatcher.h +++ b/native/cocos/editor-support/dragonbones/event/IEventDispatcher.h @@ -38,8 +38,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 4.5 * @language zh_CN */ -class IEventDispatcher -{ +class IEventDispatcher { ABSTRACT_CLASS(IEventDispatcher) public: @@ -89,7 +88,7 @@ public: * @version DragonBones 4.5 * @language zh_CN */ - virtual void addDBEventListener(const std::string& type, const std::function & listener) = 0; + virtual void addDBEventListener(const std::string& type, const std::function& listener) = 0; /** * - Removes a listener from the object. * @param type - Event type. diff --git a/native/cocos/editor-support/dragonbones/factory/BaseFactory.cpp b/native/cocos/editor-support/dragonbones/factory/BaseFactory.cpp index 2cb750a07b..9b07a94d73 100644 --- a/native/cocos/editor-support/dragonbones/factory/BaseFactory.cpp +++ b/native/cocos/editor-support/dragonbones/factory/BaseFactory.cpp @@ -5,32 +5,23 @@ DRAGONBONES_NAMESPACE_BEGIN JSONDataParser BaseFactory::_jsonParser; BinaryDataParser BaseFactory::_binaryParser; -TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const -{ +TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, const std::string& textureName) const { const auto iterator = _textureAtlasDataMap.find(textureAtlasName); - if (iterator != _textureAtlasDataMap.end()) - { - for (const auto textureAtlasData : iterator->second) - { + if (iterator != _textureAtlasDataMap.end()) { + for (const auto textureAtlasData : iterator->second) { const auto textureData = textureAtlasData->getTexture(textureName); - if (textureData != nullptr) - { + if (textureData != nullptr) { return textureData; } } } - if (autoSearch) - { - for (const auto& pair : _textureAtlasDataMap) - { - for (const auto textureAtlasData : pair.second) - { - if (textureAtlasData->autoSearch) - { + if (autoSearch) { + for (const auto& pair : _textureAtlasDataMap) { + for (const auto textureAtlasData : pair.second) { + if (textureAtlasData->autoSearch) { const auto textureData = textureAtlasData->getTexture(textureName); - if (textureData != nullptr) - { + if (textureData != nullptr) { return textureData; } } @@ -42,34 +33,26 @@ TextureData* BaseFactory::_getTextureData(const std::string& textureAtlasName, c } bool BaseFactory::_fillBuildArmaturePackage( - BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, const std::string& armatureName, const std::string& skinName, const std::string& textureAtlasName -) const -{ + BuildArmaturePackage& dataPackage, + const std::string& dragonBonesName, const std::string& armatureName, const std::string& skinName, const std::string& textureAtlasName) const { std::string mapName = dragonBonesName; DragonBonesData* dragonBonesData = nullptr; ArmatureData* armatureData = nullptr; - if (!mapName.empty()) - { + if (!mapName.empty()) { const auto iterator = _dragonBonesDataMap.find(mapName); - if (iterator != _dragonBonesDataMap.end()) - { + if (iterator != _dragonBonesDataMap.end()) { dragonBonesData = iterator->second; armatureData = dragonBonesData->getArmature(armatureName); } } - if (armatureData == nullptr && (mapName.empty() || autoSearch)) - { - for (const auto& pair : _dragonBonesDataMap) - { + if (armatureData == nullptr && (mapName.empty() || autoSearch)) { + for (const auto& pair : _dragonBonesDataMap) { dragonBonesData = pair.second; - if (mapName.empty() || dragonBonesData->autoSearch) - { + if (mapName.empty() || dragonBonesData->autoSearch) { armatureData = dragonBonesData->getArmature(armatureName); - if (armatureData != nullptr) - { + if (armatureData != nullptr) { mapName = pair.first; break; } @@ -77,34 +60,28 @@ bool BaseFactory::_fillBuildArmaturePackage( } } - if (armatureData != nullptr) - { + if (armatureData != nullptr) { dataPackage.dataName = mapName; dataPackage.textureAtlasName = textureAtlasName; dataPackage.data = dragonBonesData; dataPackage.armature = armatureData; dataPackage.skin = nullptr; - if (!skinName.empty()) - { + if (!skinName.empty()) { dataPackage.skin = armatureData->getSkin(skinName); - if (dataPackage.skin == nullptr && autoSearch) - { - for (const auto& pair : _dragonBonesDataMap) - { + if (dataPackage.skin == nullptr && autoSearch) { + for (const auto& pair : _dragonBonesDataMap) { const auto skinDragonBonesData = pair.second; const auto skinArmatureData = skinDragonBonesData->getArmature(skinName); - if (skinArmatureData != nullptr) - { + if (skinArmatureData != nullptr) { dataPackage.skin = skinArmatureData->defaultSkin; break; } } } } - - if (dataPackage.skin == nullptr) - { + + if (dataPackage.skin == nullptr) { dataPackage.skin = armatureData->defaultSkin; } @@ -114,16 +91,13 @@ bool BaseFactory::_fillBuildArmaturePackage( return false; } -void BaseFactory::_buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const -{ - for (const auto boneData : dataPackage.armature->sortedBones) - { +void BaseFactory::_buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const { + for (const auto boneData : dataPackage.armature->sortedBones) { const auto bone = BaseObject::borrowObject(); bone->init(boneData, armature); } - for (const auto& pair : dataPackage.armature->constraints) - { + for (const auto& pair : dataPackage.armature->constraints) { // TODO more constraint type. const auto constraint = BaseObject::borrowObject(); constraint->init(pair.second, armature); @@ -131,49 +105,38 @@ void BaseFactory::_buildBones(const BuildArmaturePackage& dataPackage, Armature* } } -void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* armature) const -{ +void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* armature) const { const auto currentSkin = dataPackage.skin; const auto defaultSkin = dataPackage.armature->defaultSkin; - if (currentSkin == nullptr || defaultSkin == nullptr) - { + if (currentSkin == nullptr || defaultSkin == nullptr) { return; } std::map*> skinSlots; - for (auto& pair : defaultSkin->displays) - { + for (auto& pair : defaultSkin->displays) { auto& displays = pair.second; skinSlots[pair.first] = &displays; } - if (currentSkin != defaultSkin) - { - for (auto& pair : currentSkin->displays) - { + if (currentSkin != defaultSkin) { + for (auto& pair : currentSkin->displays) { auto& displays = pair.second; skinSlots[pair.first] = &displays; } } - for (const auto slotData : dataPackage.armature->sortedSlots) - { + for (const auto slotData : dataPackage.armature->sortedSlots) { const auto displayDatas = skinSlots[slotData->name]; const auto slot = _buildSlot(dataPackage, slotData, armature); slot->setRawDisplayDatas(displayDatas); - if (displayDatas != nullptr) - { + if (displayDatas != nullptr) { std::vector> displayList; - for (const auto displayData : *displayDatas) - { - if (displayData != nullptr) - { + for (const auto displayData : *displayDatas) { + if (displayData != nullptr) { displayList.push_back(_getSlotDisplay(&dataPackage, displayData, nullptr, slot)); - } - else - { + } else { displayList.push_back(std::make_pair(nullptr, DisplayType::Image)); } } @@ -185,49 +148,37 @@ void BaseFactory::_buildSlots(const BuildArmaturePackage& dataPackage, Armature* } } -Armature* BaseFactory::_buildChildArmature(const BuildArmaturePackage* dataPackage, Slot* slot, DisplayData* displayData) const -{ +Armature* BaseFactory::_buildChildArmature(const BuildArmaturePackage* dataPackage, Slot* slot, DisplayData* displayData) const { return buildArmature(displayData->path, dataPackage != nullptr ? dataPackage->dataName : "", "", dataPackage != nullptr ? dataPackage->textureAtlasName : ""); } -std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePackage* dataPackage, DisplayData* displayData, DisplayData* rawDisplayData, Slot* slot) const -{ +std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePackage* dataPackage, DisplayData* displayData, DisplayData* rawDisplayData, Slot* slot) const { std::string dataName = ""; - if (dataPackage != nullptr) - { + if (dataPackage != nullptr) { dataName = dataPackage->dataName; - } - else - { - for (const auto& pair : _dragonBonesDataMap) - { - if (pair.second == displayData->parent->parent->parent) - { + } else { + for (const auto& pair : _dragonBonesDataMap) { + if (pair.second == displayData->parent->parent->parent) { dataName = pair.first; } } - if (dataName.empty()) - { + if (dataName.empty()) { dataName = displayData->parent->parent->parent->name; } } std::pair display(nullptr, DisplayType::Image); - switch (displayData->type) - { - case DisplayType::Image: - { + switch (displayData->type) { + case DisplayType::Image: { auto imageDisplayData = static_cast(displayData); - if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty()) - { + if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty()) { imageDisplayData->texture = _getTextureData(dataPackage->textureAtlasName, displayData->path); } - if (imageDisplayData->texture == nullptr) - { + if (imageDisplayData->texture == nullptr) { imageDisplayData->texture = _getTextureData(dataName, displayData->path); } @@ -236,51 +187,39 @@ std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePa break; } - case DisplayType::Mesh: - { + case DisplayType::Mesh: { auto meshDisplayData = static_cast(displayData); - - if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty()) - { + + if (dataPackage != nullptr && !dataPackage->textureAtlasName.empty()) { meshDisplayData->texture = _getTextureData(dataPackage->textureAtlasName, meshDisplayData->path); } - if (meshDisplayData->texture == nullptr) - { + if (meshDisplayData->texture == nullptr) { meshDisplayData->texture = _getTextureData(dataName, meshDisplayData->path); } - if (_isSupportMesh()) - { + if (_isSupportMesh()) { display.first = slot->_meshDisplay; display.second = DisplayType::Mesh; - } - else - { + } else { display.first = slot->_rawDisplay; display.second = DisplayType::Image; } break; } - case DisplayType::Armature: - { + case DisplayType::Armature: { auto armatureDisplayData = static_cast(displayData); const auto childArmature = _buildChildArmature(dataPackage, slot, displayData); - if (childArmature != nullptr) - { + if (childArmature != nullptr) { childArmature->inheritAnimation = armatureDisplayData->inheritAnimation; - if (!childArmature->inheritAnimation) - { + if (!childArmature->inheritAnimation) { const auto actions = !armatureDisplayData->actions.empty() ? &(armatureDisplayData->actions) : &(childArmature->_armatureData->defaultActions); - if (!actions->empty()) - { - for (const auto action : *actions) - { + if (!actions->empty()) { + for (const auto action : *actions) { childArmature->getAnimation()->fadeIn(action->name); } - } - else { + } else { childArmature->getAnimation()->play(); } } @@ -303,8 +242,7 @@ std::pair BaseFactory::_getSlotDisplay(const BuildArmaturePa return display; } -DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale) -{ +DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const std::string& name, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); DataParser* dataParser = nullptr; @@ -313,42 +251,32 @@ DragonBonesData* BaseFactory::parseDragonBonesData(const char* rawData, const st rawData[0] == 'D' && rawData[1] == 'B' && rawData[2] == 'D' && - rawData[3] == 'T' - ) - { + rawData[3] == 'T') { dataParser = &_binaryParser; - } - else - { + } else { dataParser = _dataParser; } const auto dragonBonesData = dataParser->parseDragonBonesData(rawData, scale); - while (true) - { + while (true) { const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr); - if (dataParser->parseTextureAtlasData(nullptr, *textureAtlasData, scale)) - { + if (dataParser->parseTextureAtlasData(nullptr, *textureAtlasData, scale)) { addTextureAtlasData(textureAtlasData, name); - } - else - { + } else { textureAtlasData->returnToPool(); break; } } - - if (dragonBonesData != nullptr) - { + + if (dragonBonesData != nullptr) { addDragonBonesData(dragonBonesData, name); } return dragonBonesData; } -TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, const std::string& name, float scale) -{ +TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* textureAtlas, const std::string& name, float scale) { const auto textureAtlasData = _buildTextureAtlasData(nullptr, nullptr); _dataParser->parseTextureAtlasData(rawData, *textureAtlasData, scale); _buildTextureAtlasData(textureAtlasData, textureAtlas); @@ -357,13 +285,10 @@ TextureAtlasData* BaseFactory::parseTextureAtlasData(const char* rawData, void* return textureAtlasData; } -void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name) -{ - const auto& mapName = !name.empty()? name : data->name; - if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend()) - { - if (_dragonBonesDataMap[name] == data) - { +void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& name) { + const auto& mapName = !name.empty() ? name : data->name; + if (_dragonBonesDataMap.find(mapName) != _dragonBonesDataMap.cend()) { + if (_dragonBonesDataMap[name] == data) { return; } @@ -374,13 +299,10 @@ void BaseFactory::addDragonBonesData(DragonBonesData* data, const std::string& n _dragonBonesDataMap[mapName] = data; } -void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData) -{ +void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeData) { const auto iterator = _dragonBonesDataMap.find(name); - if (iterator != _dragonBonesDataMap.cend()) - { - if (disposeData) - { + if (iterator != _dragonBonesDataMap.cend()) { + if (disposeData) { iterator->second->returnToPool(); } @@ -388,25 +310,19 @@ void BaseFactory::removeDragonBonesData(const std::string& name, bool disposeDat } } -void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name) -{ - const auto& mapName = !name.empty() ? name : data->name; +void BaseFactory::addTextureAtlasData(TextureAtlasData* data, const std::string& name) { + const auto& mapName = !name.empty() ? name : data->name; auto& textureAtlasList = _textureAtlasDataMap[mapName]; - if (std::find(textureAtlasList.cbegin(), textureAtlasList.cend(), data) == textureAtlasList.cend()) - { + if (std::find(textureAtlasList.cbegin(), textureAtlasList.cend(), data) == textureAtlasList.cend()) { textureAtlasList.push_back(data); } } -void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData) -{ +void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeData) { const auto iterator = _textureAtlasDataMap.find(name); - if (iterator != _textureAtlasDataMap.end()) - { - if (disposeData) - { - for (const auto textureAtlasData : iterator->second) - { + if (iterator != _textureAtlasDataMap.end()) { + if (disposeData) { + for (const auto textureAtlasData : iterator->second) { textureAtlasData->returnToPool(); } } @@ -415,30 +331,23 @@ void BaseFactory::removeTextureAtlasData(const std::string& name, bool disposeDa } } -ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const -{ +ArmatureData* BaseFactory::getArmatureData(const std::string& name, const std::string& dragonBonesName) const { BuildArmaturePackage dataPackage; - if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", "")) - { + if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, name, "", "")) { return nullptr; } return dataPackage.armature; } -void BaseFactory::clear(bool disposeData) -{ - if (disposeData) - { - for (const auto& pair : _dragonBonesDataMap) - { +void BaseFactory::clear(bool disposeData) { + if (disposeData) { + for (const auto& pair : _dragonBonesDataMap) { pair.second->returnToPool(); } - for (const auto& pair : _textureAtlasDataMap) - { - for (const auto textureAtlasData : pair.second) - { + for (const auto& pair : _textureAtlasDataMap) { + for (const auto textureAtlasData : pair.second) { textureAtlasData->returnToPool(); } } @@ -448,11 +357,9 @@ void BaseFactory::clear(bool disposeData) _textureAtlasDataMap.clear(); } -Armature * BaseFactory::buildArmature(const std::string& armatureName, const std::string& dragonBonesName, const std::string& skinName, const std::string& textureAtlasName) const -{ +Armature* BaseFactory::buildArmature(const std::string& armatureName, const std::string& dragonBonesName, const std::string& skinName, const std::string& textureAtlasName) const { BuildArmaturePackage dataPackage; - if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) - { + if (!_fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) { DRAGONBONES_ASSERT(false, "No armature data: " + armatureName + ", " + (!dragonBonesName.empty() ? dragonBonesName : "")); return nullptr; } @@ -466,57 +373,46 @@ Armature * BaseFactory::buildArmature(const std::string& armatureName, const std return armature; } -void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displayIndex) const -{ - if (displayIndex < 0) - { +void BaseFactory::replaceDisplay(Slot* slot, DisplayData* displayData, int displayIndex) const { + if (displayIndex < 0) { displayIndex = slot->getDisplayIndex(); } - if (displayIndex < 0) - { + if (displayIndex < 0) { displayIndex = 0; } slot->replaceDisplayData(displayData, displayIndex); auto displayList = slot->getDisplayList(); // Copy. - if (displayList.size() <= (unsigned)displayIndex) - { + if (displayList.size() <= (unsigned)displayIndex) { displayList.resize(displayIndex + 1, std::make_pair(nullptr, DisplayType::Image)); } - if (displayData != nullptr) - { + if (displayData != nullptr) { const auto rawDisplayDatas = slot->getRawDisplayDatas(); displayList[displayIndex] = _getSlotDisplay( nullptr, displayData, rawDisplayDatas != nullptr && (unsigned)displayIndex < rawDisplayDatas->size() ? rawDisplayDatas->at(displayIndex) : nullptr, - slot - ); - } - else - { + slot); + } else { displayList[displayIndex] = std::make_pair(nullptr, DisplayType::Image); } slot->setDisplayList(displayList); } -bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, const std::string& displayName, Slot* slot, int displayIndex) const -{ +bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, const std::string& displayName, Slot* slot, int displayIndex) const { DRAGONBONES_ASSERT(slot, "Arguments error."); const auto armatureData = getArmatureData(armatureName, dragonBonesName); - if (!armatureData || !armatureData->defaultSkin) - { + if (!armatureData || !armatureData->defaultSkin) { return false; } const auto displayData = armatureData->defaultSkin->getDisplay(slotName, displayName); - if (!displayData) - { + if (!displayData) { return false; } @@ -525,55 +421,45 @@ bool BaseFactory::replaceSlotDisplay(const std::string& dragonBonesName, const s return true; } -bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, Slot* slot) const -{ +bool BaseFactory::replaceSlotDisplayList(const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, Slot* slot) const { DRAGONBONES_ASSERT(slot, "Arguments error."); const auto armatureData = getArmatureData(armatureName, dragonBonesName); - if (!armatureData || !armatureData->defaultSkin) - { + if (!armatureData || !armatureData->defaultSkin) { return false; } const auto displays = armatureData->defaultSkin->getDisplays(slotName); - if (!displays) - { + if (!displays) { return false; } auto displayIndex = 0; - for (const auto displayData : *displays) - { + for (const auto displayData : *displays) { replaceDisplay(slot, displayData, displayIndex++); } return true; } -bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector& exclude) const -{ +bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverride, const std::vector& exclude) const { DRAGONBONES_ASSERT(armature && skin, "Arguments error."); auto success = false; const auto defaultSkin = skin->parent->defaultSkin; - for (const auto slot : armature->getSlots()) - { - if (std::find(exclude.cbegin(), exclude.cend(), slot->getName()) != exclude.cend()) - { + for (const auto slot : armature->getSlots()) { + if (std::find(exclude.cbegin(), exclude.cend(), slot->getName()) != exclude.cend()) { continue; } auto displays = skin->getDisplays(slot->getName()); - if (displays == nullptr) - { - if (defaultSkin != nullptr && skin != defaultSkin) - { + if (displays == nullptr) { + if (defaultSkin != nullptr && skin != defaultSkin) { displays = defaultSkin->getDisplays(slot->getName()); } - if (isOverride) - { + if (isOverride) { std::vector> displayList; slot->setRawDisplayDatas(nullptr); slot->setDisplayList(displayList); @@ -583,15 +469,11 @@ bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverrid auto displayList = slot->getDisplayList(); // Copy. displayList.resize(displays->size(), std::make_pair(nullptr, DisplayType::Image)); - for (std::size_t i = 0, l = displays->size(); i < l; ++i) - { + for (std::size_t i = 0, l = displays->size(); i < l; ++i) { const auto displayData = displays->at(i); - if (displayData != nullptr) - { + if (displayData != nullptr) { displayList[i] = _getSlotDisplay(nullptr, displayData, nullptr, slot); - } - else - { + } else { displayList[i] = std::make_pair(nullptr, DisplayType::Image); } } @@ -604,45 +486,33 @@ bool BaseFactory::replaceSkin(Armature* armature, SkinData* skin, bool isOverrid return success; } -bool BaseFactory::replaceAnimation(Armature* armature, ArmatureData* armatureData, bool isReplaceAll) const -{ +bool BaseFactory::replaceAnimation(Armature* armature, ArmatureData* armatureData, bool isReplaceAll) const { const auto skinData = armatureData->defaultSkin; - if (skinData == nullptr) - { + if (skinData == nullptr) { return false; } - if (isReplaceAll) - { + if (isReplaceAll) { armature->getAnimation()->setAnimations(armatureData->animations); - } - else - { + } else { auto animations = armature->getAnimation()->getAnimations(); // Copy. - for (const auto& pair : armatureData->animations) - { + for (const auto& pair : armatureData->animations) { animations[pair.first] = pair.second; } armature->getAnimation()->setAnimations(animations); } - for (const auto slot : armature->getSlots()) - { + for (const auto slot : armature->getSlots()) { unsigned index = 0; - for (const auto& pair : slot->getDisplayList()) - { - if (pair.second == DisplayType::Armature) - { + for (const auto& pair : slot->getDisplayList()) { + if (pair.second == DisplayType::Armature) { auto displayDatas = skinData->getDisplays(slot->getName()); - if (displayDatas != nullptr && index < displayDatas->size()) - { + if (displayDatas != nullptr && index < displayDatas->size()) { const auto displayData = (*displayDatas)[index]; - if (displayData != nullptr && displayData->type == DisplayType::Armature) - { + if (displayData != nullptr && displayData->type == DisplayType::Armature) { const auto childArmatureData = getArmatureData(displayData->path, displayData->parent->parent->parent->name); - if (childArmatureData != nullptr) - { + if (childArmatureData != nullptr) { replaceAnimation((Armature*)pair.first, childArmatureData, isReplaceAll); } } diff --git a/native/cocos/editor-support/dragonbones/factory/BaseFactory.h b/native/cocos/editor-support/dragonbones/factory/BaseFactory.h index 0b788fadf2..5d183927b8 100644 --- a/native/cocos/editor-support/dragonbones/factory/BaseFactory.h +++ b/native/cocos/editor-support/dragonbones/factory/BaseFactory.h @@ -54,8 +54,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class BaseFactory -{ +class BaseFactory { protected: static JSONDataParser _jsonParser; static BinaryDataParser _binaryParser; @@ -83,17 +82,14 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - BaseFactory(DataParser* dataParser = nullptr) : - autoSearch(false), - _dragonBonesDataMap(), - _textureAtlasDataMap(), - _dragonBones(nullptr), - _dataParser(nullptr) - { + BaseFactory(DataParser* dataParser = nullptr) : autoSearch(false), + _dragonBonesDataMap(), + _textureAtlasDataMap(), + _dragonBones(nullptr), + _dataParser(nullptr) { _dataParser = dataParser != nullptr ? dataParser : &BaseFactory::_jsonParser; } - virtual ~BaseFactory() - { + virtual ~BaseFactory() { clear(); _dragonBones = nullptr; @@ -101,15 +97,13 @@ public: } protected: - virtual inline bool _isSupportMesh() const - { + virtual inline bool _isSupportMesh() const { return true; } virtual TextureData* _getTextureData(const std::string& textureAtlasName, const std::string& textureName) const; virtual bool _fillBuildArmaturePackage( BuildArmaturePackage& dataPackage, - const std::string& dragonBonesName, const std::string& armatureName, const std::string& skinName, const std::string& textureAtlasName - ) const; + const std::string& dragonBonesName, const std::string& armatureName, const std::string& skinName, const std::string& textureAtlasName) const; virtual void _buildBones(const BuildArmaturePackage& dataPackage, Armature* armature) const; /** * @private @@ -200,8 +194,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline DragonBonesData* getDragonBonesData(const std::string& name) const - { + inline DragonBonesData* getDragonBonesData(const std::string& name) const { return mapFind(_dragonBonesDataMap, name); } /** @@ -270,8 +263,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline std::vector* getTextureAtlasData(const std::string& name) - { + inline std::vector* getTextureAtlasData(const std::string& name) { return mapFindB(_textureAtlasDataMap, name); } /** @@ -386,7 +378,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - virtual Armature* buildArmature(const std::string& armatureName, const std::string& dragonBonesName = "", const std::string& skinName = "", const std::string & textureAtlasName = "") const; + virtual Armature* buildArmature(const std::string& armatureName, const std::string& dragonBonesName = "", const std::string& skinName = "", const std::string& textureAtlasName = "") const; /** * @private */ @@ -429,15 +421,13 @@ public: */ virtual bool replaceSlotDisplay( const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, const std::string& displayName, - Slot* slot, int displayIndex = -1 - ) const; + Slot* slot, int displayIndex = -1) const; /** * @private */ virtual bool replaceSlotDisplayList( const std::string& dragonBonesName, const std::string& armatureName, const std::string& slotName, - Slot* slot - ) const; + Slot* slot) const; /** * - Share specific skin data with specific armature. * @param armature - The armature. @@ -523,15 +513,13 @@ public: /** * @private */ - inline const std::map>& getAllTextureAtlasData() const - { + inline const std::map>& getAllTextureAtlasData() const { return _textureAtlasDataMap; } /** * @private */ - inline const std::map& getAllDragonBonesData() const - { + inline const std::map& getAllDragonBonesData() const { return _dragonBonesDataMap; } /** @@ -544,8 +532,7 @@ public: * @version DragonBones 5.7 * @language zh_CN */ - inline WorldClock* getClock() const - { + inline WorldClock* getClock() const { return _dragonBones->getClock(); } @@ -559,16 +546,14 @@ public: * @deprecated * @language zh_CN */ - inline bool changeSkin(Armature* armature, SkinData* skin, const std::vector& exclude) const - { + inline bool changeSkin(Armature* armature, SkinData* skin, const std::vector& exclude) const { return replaceSkin(armature, skin, false, exclude); } }; /** * @internal */ -class BuildArmaturePackage -{ +class BuildArmaturePackage { DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(BuildArmaturePackage) public: @@ -578,13 +563,11 @@ public: ArmatureData* armature; SkinData* skin; - BuildArmaturePackage() : - dataName(), - textureAtlasName(), - data(nullptr), - armature(nullptr), - skin(nullptr) - {} + BuildArmaturePackage() : dataName(), + textureAtlasName(), + data(nullptr), + armature(nullptr), + skin(nullptr) {} ~BuildArmaturePackage() {} }; diff --git a/native/cocos/editor-support/dragonbones/geom/ColorTransform.h b/native/cocos/editor-support/dragonbones/geom/ColorTransform.h index 0e52a1471e..a72b5ad0c0 100644 --- a/native/cocos/editor-support/dragonbones/geom/ColorTransform.h +++ b/native/cocos/editor-support/dragonbones/geom/ColorTransform.h @@ -29,8 +29,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class ColorTransform -{ +class ColorTransform { public: float alphaMultiplier; float redMultiplier; @@ -41,24 +40,20 @@ public: int greenOffset; int blueOffset; - ColorTransform(): - alphaMultiplier(1.0f), - redMultiplier(1.0f), - greenMultiplier(1.0f), - blueMultiplier(1.0f), - alphaOffset(0), - redOffset(0), - greenOffset(0), - blueOffset(0) - {} - ColorTransform(const ColorTransform &value) - { + ColorTransform() : alphaMultiplier(1.0f), + redMultiplier(1.0f), + greenMultiplier(1.0f), + blueMultiplier(1.0f), + alphaOffset(0), + redOffset(0), + greenOffset(0), + blueOffset(0) {} + ColorTransform(const ColorTransform &value) { operator=(value); } ~ColorTransform() {} - inline void operator=(const ColorTransform &value) - { + inline void operator=(const ColorTransform &value) { alphaMultiplier = value.alphaMultiplier; redMultiplier = value.redMultiplier; greenMultiplier = value.greenMultiplier; @@ -69,8 +64,7 @@ public: blueOffset = value.blueOffset; } - inline void identity() - { + inline void identity() { alphaMultiplier = redMultiplier = greenMultiplier = blueMultiplier = 1.0f; alphaOffset = redOffset = greenOffset = blueOffset = 0; } diff --git a/native/cocos/editor-support/dragonbones/geom/Matrix.h b/native/cocos/editor-support/dragonbones/geom/Matrix.h index febf9fd5b3..3f9e2ef78f 100644 --- a/native/cocos/editor-support/dragonbones/geom/Matrix.h +++ b/native/cocos/editor-support/dragonbones/geom/Matrix.h @@ -38,8 +38,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Matrix -{ +class Matrix { public: /** * - The value that affects the positioning of pixels along the x axis when scaling or rotating an image. @@ -120,25 +119,21 @@ public: */ float ty; - Matrix(): - a(1.0f), - b(0.0f), - c(0.0f), - d(1.0f), - tx(0.0f), - ty(0.0f) - {} + Matrix() : a(1.0f), + b(0.0f), + c(0.0f), + d(1.0f), + tx(0.0f), + ty(0.0f) {} /** * @private */ - Matrix(const Matrix& value) - { + Matrix(const Matrix& value) { operator=(value); } ~Matrix() {} - inline void operator=(const Matrix& value) - { + inline void operator=(const Matrix& value) { a = value.a; b = value.b; c = value.c; @@ -158,8 +153,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void identity() - { + inline void identity() { a = d = 1.0f; b = c = 0.0f; tx = ty = 0.0f; @@ -176,8 +170,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void concat(const Matrix& value) - { + inline void concat(const Matrix& value) { const auto aA = a; const auto bA = b; const auto cA = c; @@ -208,8 +201,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void invert() - { + inline void invert() { const auto aA = a; const auto bA = b; const auto cA = c; @@ -243,13 +235,11 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline void transformPoint(float x, float y, Point& result, bool delta = false) const - { + inline void transformPoint(float x, float y, Point& result, bool delta = false) const { result.x = a * x + c * y; result.y = b * x + d * y; - if (!delta) - { + if (!delta) { result.x += tx; result.y += ty; } @@ -257,8 +247,7 @@ public: /** * @private */ - inline void transformRectangle(Rectangle& rectangle, bool delta = false) const - { + inline void transformRectangle(Rectangle& rectangle, bool delta = false) const { const auto offsetX = delta ? 0.0f : this->tx; const auto offsetY = delta ? 0.0f : this->ty; @@ -277,15 +266,13 @@ public: auto y3 = b * x + d * yMax + offsetY; auto tmp = 0.0f; - if (x0 > x1) - { + if (x0 > x1) { tmp = x0; x0 = x1; x1 = tmp; } - if (x2 > x3) - { + if (x2 > x3) { tmp = x2; x2 = x3; x3 = tmp; @@ -294,15 +281,13 @@ public: rectangle.x = std::floor(x0 < x2 ? x0 : x2); rectangle.width = std::ceil((x1 > x3 ? x1 : x3) - rectangle.x); - if (y0 > y1) - { + if (y0 > y1) { tmp = y0; y0 = y1; y1 = tmp; } - if (y2 > y3) - { + if (y2 > y3) { tmp = y2; y2 = y3; y3 = tmp; diff --git a/native/cocos/editor-support/dragonbones/geom/Point.h b/native/cocos/editor-support/dragonbones/geom/Point.h index 3824a16009..b136cb3b6b 100644 --- a/native/cocos/editor-support/dragonbones/geom/Point.h +++ b/native/cocos/editor-support/dragonbones/geom/Point.h @@ -36,8 +36,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Point -{ +class Point { public: static Point helpPointA; static Point helpPointB; @@ -72,10 +71,8 @@ public: */ float y; - Point(): - x(0.0f), - y(0.0f) - {} + Point() : x(0.0f), + y(0.0f) {} /** * - Creates a new point. If you pass no parameters to this method, a point is created at (0,0). * @param x - The horizontal coordinate. @@ -90,14 +87,12 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - Point(const Point& value) - { + Point(const Point& value) { operator=(value); } ~Point() {} - inline void operator=(const Point& value) - { + inline void operator=(const Point& value) { x = value.x; y = value.y; } @@ -105,8 +100,7 @@ public: /** * @private */ - inline void clear() - { + inline void clear() { x = y = 0.0f; } diff --git a/native/cocos/editor-support/dragonbones/geom/Rectangle.h b/native/cocos/editor-support/dragonbones/geom/Rectangle.h index ec2d0c7dec..97a10b6371 100644 --- a/native/cocos/editor-support/dragonbones/geom/Rectangle.h +++ b/native/cocos/editor-support/dragonbones/geom/Rectangle.h @@ -44,8 +44,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Rectangle -{ +class Rectangle { public: /** * - The x coordinate of the top-left corner of the rectangle. @@ -100,23 +99,19 @@ public: */ float height; - Rectangle(): - x(0.0f), - y(0.0f), - width(0.0f), - height(0.0f) - {} + Rectangle() : x(0.0f), + y(0.0f), + width(0.0f), + height(0.0f) {} /** * @private */ - Rectangle(const Rectangle& value) - { + Rectangle(const Rectangle& value) { operator=(value); } ~Rectangle() {} - inline void operator=(const Rectangle& value) - { + inline void operator=(const Rectangle& value) { x = value.x; y = value.y; width = value.width; @@ -126,8 +121,7 @@ public: /** * @private */ - void clear() - { + void clear() { x = y = 0.0f; width = height = 0.0f; } diff --git a/native/cocos/editor-support/dragonbones/geom/Transform.h b/native/cocos/editor-support/dragonbones/geom/Transform.h index 432bc57bb5..b0327bf556 100644 --- a/native/cocos/editor-support/dragonbones/geom/Transform.h +++ b/native/cocos/editor-support/dragonbones/geom/Transform.h @@ -37,8 +37,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class Transform final -{ +class Transform final { public: /** * @private @@ -68,8 +67,7 @@ public: /** * @private */ - static float normalizeRadian(float value) - { + static float normalizeRadian(float value) { value = fmod(value + Transform::PI, Transform::PI * 2.0f); value += value > 0.0f ? -Transform::PI : Transform::PI; @@ -144,25 +142,21 @@ public: */ float scaleY; - Transform(): - x(0.0f), - y(0.0f), - skew(0.0f), - rotation(0.0f), - scaleX(1.0f), - scaleY(1.0f) - {} + Transform() : x(0.0f), + y(0.0f), + skew(0.0f), + rotation(0.0f), + scaleX(1.0f), + scaleY(1.0f) {} /** * @private */ - Transform(const Transform& value) - { + Transform(const Transform& value) { operator=(value); } ~Transform() {} - inline void operator=(const Transform& value) - { + inline void operator=(const Transform& value) { x = value.x; y = value.y; skew = value.skew; @@ -173,8 +167,7 @@ public: /** * @private */ - inline Transform& identity() - { + inline Transform& identity() { x = y = skew = rotation = 0.0f; scaleX = scaleY = 1.0f; @@ -183,8 +176,7 @@ public: /** * @private */ - inline Transform& add(const Transform& value) - { + inline Transform& add(const Transform& value) { x += value.x; y += value.y; skew += value.skew; @@ -197,8 +189,7 @@ public: /** * @private */ - inline Transform& minus(const Transform& value) - { + inline Transform& minus(const Transform& value) { x -= value.x; y -= value.y; skew -= value.skew; @@ -211,8 +202,7 @@ public: /** * @private */ - inline Transform& fromMatrix(const Matrix& matrix) - { + inline Transform& fromMatrix(const Matrix& matrix) { const auto backupScaleX = scaleX, backupScaleY = scaleY; x = matrix.tx; @@ -224,14 +214,12 @@ public: scaleX = (rotation > -PI_Q && rotation < PI_Q) ? matrix.a / std::cos(rotation) : matrix.b / std::sin(rotation); scaleY = (skewX > -PI_Q && skewX < PI_Q) ? matrix.d / std::cos(skewX) : -matrix.c / std::sin(skewX); - if (backupScaleX >= 0.0f && scaleX < 0.0f) - { + if (backupScaleX >= 0.0f && scaleX < 0.0f) { scaleX = -scaleX; rotation = rotation - PI; } - if (backupScaleY >= 0.0f && scaleY < 0.0f) - { + if (backupScaleY >= 0.0f && scaleY < 0.0f) { scaleY = -scaleY; skewX = skewX - PI; } @@ -243,37 +231,29 @@ public: /** * @private */ - inline Transform& toMatrix(Matrix& matrix) - { - if (rotation == 0.0f) - { + inline Transform& toMatrix(Matrix& matrix) { + if (rotation == 0.0f) { matrix.a = 1.0f; matrix.b = 0.0f; - } - else - { + } else { matrix.a = std::cos(rotation); matrix.b = std::sin(rotation); } - if (skew == 0.0f) - { + if (skew == 0.0f) { matrix.c = -matrix.b; matrix.d = matrix.a; - } - else { + } else { matrix.c = -std::sin(skew + rotation); matrix.d = std::cos(skew + rotation); } - if (scaleX != 1.0f) - { + if (scaleX != 1.0f) { matrix.a *= scaleX; matrix.b *= scaleX; } - if (scaleY != 1.0f) - { + if (scaleY != 1.0f) { matrix.c *= scaleY; matrix.d *= scaleY; } diff --git a/native/cocos/editor-support/dragonbones/model/AnimationConfig.cpp b/native/cocos/editor-support/dragonbones/model/AnimationConfig.cpp index 5a59c39a58..b3a2bc8960 100644 --- a/native/cocos/editor-support/dragonbones/model/AnimationConfig.cpp +++ b/native/cocos/editor-support/dragonbones/model/AnimationConfig.cpp @@ -4,8 +4,7 @@ DRAGONBONES_NAMESPACE_BEGIN -void AnimationConfig::_onClear() -{ +void AnimationConfig::_onClear() { pauseFadeOut = true; fadeOutMode = AnimationFadeOutMode::All; fadeOutTweenType = TweenType::Line; @@ -31,13 +30,11 @@ void AnimationConfig::_onClear() boneMask.clear(); } -void AnimationConfig::clear() -{ +void AnimationConfig::clear() { _onClear(); } -void AnimationConfig::copyFrom(AnimationConfig* value) -{ +void AnimationConfig::copyFrom(AnimationConfig* value) { pauseFadeOut = value->pauseFadeOut; fadeOutMode = value->fadeOutMode; autoFadeOutTime = value->autoFadeOutTime; @@ -63,19 +60,16 @@ void AnimationConfig::copyFrom(AnimationConfig* value) boneMask = value->boneMask; } -bool AnimationConfig::containsBoneMask(const std::string& boneName) const -{ +bool AnimationConfig::containsBoneMask(const std::string& boneName) const { return boneMask.empty() || std::find(boneMask.cbegin(), boneMask.cend(), boneName) != boneMask.cend(); } -void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneName, bool recursive) -{ +void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneName, bool recursive) { const auto currentBone = armature->getBone(boneName); - if (currentBone == nullptr) - { + if (currentBone == nullptr) { return; } - + if (std::find(boneMask.cbegin(), boneMask.cend(), boneName) == boneMask.cend()) // Add mixing { boneMask.push_back(boneName); @@ -83,18 +77,15 @@ void AnimationConfig::addBoneMask(Armature* armature, const std::string& boneNam if (recursive) // Add recursive mixing. { - for (const auto bone : armature->getBones()) - { - if (std::find(boneMask.cbegin(), boneMask.cend(), bone->getName()) == boneMask.cend() && currentBone->contains(bone)) - { + for (const auto bone : armature->getBones()) { + if (std::find(boneMask.cbegin(), boneMask.cend(), bone->getName()) == boneMask.cend() && currentBone->contains(bone)) { boneMask.push_back(bone->getName()); } } } } -void AnimationConfig::removeBoneMask(Armature* armature, const std::string& boneName, bool recursive) -{ +void AnimationConfig::removeBoneMask(Armature* armature, const std::string& boneName, bool recursive) { { auto iterator = std::find(boneMask.begin(), boneMask.end(), boneName); if (iterator != boneMask.end()) // Remove mixing. @@ -103,33 +94,25 @@ void AnimationConfig::removeBoneMask(Armature* armature, const std::string& bone } } - if (recursive) - { + if (recursive) { const auto currentBone = armature->getBone(boneName); - if (currentBone != nullptr) - { + if (currentBone != nullptr) { if (!boneMask.empty()) // Remove recursive mixing. { - for (const auto bone : armature->getBones()) - { + for (const auto bone : armature->getBones()) { auto iterator = std::find(boneMask.begin(), boneMask.end(), bone->getName()); - if (iterator != boneMask.end() && currentBone->contains(bone)) - { + if (iterator != boneMask.end() && currentBone->contains(bone)) { boneMask.erase(iterator); } } - } - else // Add unrecursive mixing. + } else // Add unrecursive mixing. { - for (const auto bone : armature->getBones()) - { - if (bone == currentBone) - { + for (const auto bone : armature->getBones()) { + if (bone == currentBone) { continue; } - if (!currentBone->contains(bone)) - { + if (!currentBone->contains(bone)) { boneMask.push_back(bone->getName()); } } diff --git a/native/cocos/editor-support/dragonbones/model/AnimationConfig.h b/native/cocos/editor-support/dragonbones/model/AnimationConfig.h index 67b3a7570f..727d2fddae 100644 --- a/native/cocos/editor-support/dragonbones/model/AnimationConfig.h +++ b/native/cocos/editor-support/dragonbones/model/AnimationConfig.h @@ -42,8 +42,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 5.0 * @language zh_CN */ -class AnimationConfig : public BaseObject -{ +class AnimationConfig : public BaseObject { BIND_CLASS_TYPE_A(AnimationConfig); public: diff --git a/native/cocos/editor-support/dragonbones/model/AnimationData.cpp b/native/cocos/editor-support/dragonbones/model/AnimationData.cpp index 24147c4a1f..89ccde3ee7 100644 --- a/native/cocos/editor-support/dragonbones/model/AnimationData.cpp +++ b/native/cocos/editor-support/dragonbones/model/AnimationData.cpp @@ -4,39 +4,30 @@ DRAGONBONES_NAMESPACE_BEGIN -void AnimationData::_onClear() -{ - for (const auto& pair : boneTimelines) - { - for (const auto timeline : pair.second) - { +void AnimationData::_onClear() { + for (const auto& pair : boneTimelines) { + for (const auto timeline : pair.second) { timeline->returnToPool(); } } - for (const auto& pair : slotTimelines) - { - for (const auto timeline : pair.second) - { + for (const auto& pair : slotTimelines) { + for (const auto timeline : pair.second) { timeline->returnToPool(); } } - for (const auto& pair : constraintTimelines) - { - for (const auto timeline : pair.second) - { + for (const auto& pair : constraintTimelines) { + for (const auto timeline : pair.second) { timeline->returnToPool(); } } - if (actionTimeline != nullptr) - { + if (actionTimeline != nullptr) { actionTimeline->returnToPool(); } - if (zOrderTimeline != nullptr) - { + if (zOrderTimeline != nullptr) { zOrderTimeline->returnToPool(); } @@ -61,8 +52,7 @@ void AnimationData::_onClear() zOrderTimeline = nullptr; } -void AnimationData::cacheFrames(unsigned frameRate) -{ +void AnimationData::cacheFrames(unsigned frameRate) { if (cacheFrameRate > 0.0f) // TODO clear cache. { return; @@ -73,46 +63,37 @@ void AnimationData::cacheFrames(unsigned frameRate) cachedFrames.resize(cacheFrameCount, false); - for (const auto bone : parent->sortedBones) - { + for (const auto bone : parent->sortedBones) { boneCachedFrameIndices[bone->name].resize(cacheFrameCount, -1); } - for (const auto slot : parent->sortedSlots) - { + for (const auto slot : parent->sortedSlots) { slotCachedFrameIndices[slot->name].resize(cacheFrameCount, -1); } } -void AnimationData::addBoneTimeline(BoneData* bone, TimelineData* value) -{ +void AnimationData::addBoneTimeline(BoneData* bone, TimelineData* value) { auto& timelines = boneTimelines[bone->name]; - if(std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) - { + if (std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) { timelines.push_back(value); } } -void AnimationData::addSlotTimeline(SlotData* slot, TimelineData* value) -{ +void AnimationData::addSlotTimeline(SlotData* slot, TimelineData* value) { auto& timelines = slotTimelines[slot->name]; - if (std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) - { + if (std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) { timelines.push_back(value); } } -void AnimationData::addConstraintTimeline(ConstraintData* constraint, TimelineData* value) -{ +void AnimationData::addConstraintTimeline(ConstraintData* constraint, TimelineData* value) { auto& timelines = constraintTimelines[constraint->name]; - if (std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) - { + if (std::find(timelines.cbegin(), timelines.cend(), value) == timelines.cend()) { timelines.push_back(value); } } -void TimelineData::_onClear() -{ +void TimelineData::_onClear() { type = TimelineType::BoneAll; offset = 0; frameIndicesOffset = -1; diff --git a/native/cocos/editor-support/dragonbones/model/AnimationData.h b/native/cocos/editor-support/dragonbones/model/AnimationData.h index 81e5ec7b4c..9c42fa16ac 100644 --- a/native/cocos/editor-support/dragonbones/model/AnimationData.h +++ b/native/cocos/editor-support/dragonbones/model/AnimationData.h @@ -36,8 +36,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class AnimationData : public BaseObject -{ +class AnimationData : public BaseObject { BIND_CLASS_TYPE_B(AnimationData); public: @@ -155,14 +154,11 @@ public: * @private */ ArmatureData* parent; - AnimationData() : - actionTimeline(nullptr), - zOrderTimeline(nullptr) - { + AnimationData() : actionTimeline(nullptr), + zOrderTimeline(nullptr) { _onClear(); } - ~AnimationData() - { + ~AnimationData() { _onClear(); } @@ -189,36 +185,31 @@ public: /** * @private */ - std::vector* getBoneTimelines(const std::string& timelineName) - { + std::vector* getBoneTimelines(const std::string& timelineName) { return mapFindB(boneTimelines, timelineName); } /** * @private */ - inline std::vector* getSlotTimelines(const std::string& timelineName) - { + inline std::vector* getSlotTimelines(const std::string& timelineName) { return mapFindB(slotTimelines, timelineName); } /** * @private */ - inline std::vector* getConstraintTimelines(const std::string& timelineName) - { + inline std::vector* getConstraintTimelines(const std::string& timelineName) { return mapFindB(constraintTimelines, timelineName); } /** * @private */ - inline std::vector* getBoneCachedFrameIndices(const std::string& boneName) - { + inline std::vector* getBoneCachedFrameIndices(const std::string& boneName) { return mapFindB(boneCachedFrameIndices, boneName); } /** * @private */ - inline std::vector* getSlotCachedFrameIndices(const std::string& slotName) - { + inline std::vector* getSlotCachedFrameIndices(const std::string& slotName) { return mapFindB(slotCachedFrameIndices, slotName); } @@ -235,8 +226,7 @@ public: // For WebAssembly. /** * @internal */ -class TimelineData : public BaseObject -{ +class TimelineData : public BaseObject { BIND_CLASS_TYPE_A(TimelineData); public: diff --git a/native/cocos/editor-support/dragonbones/model/ArmatureData.cpp b/native/cocos/editor-support/dragonbones/model/ArmatureData.cpp index 152f270a51..265356bee3 100644 --- a/native/cocos/editor-support/dragonbones/model/ArmatureData.cpp +++ b/native/cocos/editor-support/dragonbones/model/ArmatureData.cpp @@ -9,50 +9,40 @@ DRAGONBONES_NAMESPACE_BEGIN -void ArmatureData::_onClear() -{ - for (const auto action : defaultActions) - { +void ArmatureData::_onClear() { + for (const auto action : defaultActions) { action->returnToPool(); } - for (const auto action : actions) - { + for (const auto action : actions) { action->returnToPool(); } - for (const auto& pair : bones) - { + for (const auto& pair : bones) { pair.second->returnToPool(); } - for (const auto& pair : slots) - { + for (const auto& pair : slots) { pair.second->returnToPool(); } - for (const auto& pair : constraints) - { + for (const auto& pair : constraints) { pair.second->returnToPool(); } - for (const auto& pair : skins) - { + for (const auto& pair : skins) { pair.second->returnToPool(); } - for (const auto& pair : animations) - { + for (const auto& pair : animations) { pair.second->returnToPool(); } - if (canvas != nullptr) - { + if (canvas != nullptr) { canvas->returnToPool(); } - if (userData != nullptr) - { + if (userData != nullptr) { userData->returnToPool(); } @@ -79,11 +69,9 @@ void ArmatureData::_onClear() userData = nullptr; } -void ArmatureData::sortBones() -{ +void ArmatureData::sortBones() { const auto total = sortedBones.size(); - if (total <= 0) - { + if (total <= 0) { return; } @@ -91,37 +79,30 @@ void ArmatureData::sortBones() unsigned index = 0; unsigned count = 0; sortedBones.clear(); - while (count < total) - { + while (count < total) { const auto bone = sortHelper[index++]; - if (index >= total) - { + if (index >= total) { index = 0; } - if (std::find(sortedBones.cbegin(), sortedBones.cend(), bone) != sortedBones.cend()) - { + if (std::find(sortedBones.cbegin(), sortedBones.cend(), bone) != sortedBones.cend()) { continue; } auto flag = false; - for(const auto& pair : constraints) - { + for (const auto& pair : constraints) { const auto constrait = pair.second; - if(constrait->root == bone && std::find(sortedBones.cbegin(), sortedBones.cend(), constrait->target) == sortedBones.cend()) - { + if (constrait->root == bone && std::find(sortedBones.cbegin(), sortedBones.cend(), constrait->target) == sortedBones.cend()) { flag = true; break; } } - if(flag) - { + if (flag) { continue; } - if (bone->parent != nullptr && std::find(sortedBones.cbegin(), sortedBones.cend(), bone->parent) == sortedBones.cend()) - { + if (bone->parent != nullptr && std::find(sortedBones.cbegin(), sortedBones.cend(), bone->parent) == sortedBones.cend()) { continue; } @@ -130,22 +111,19 @@ void ArmatureData::sortBones() } } -void ArmatureData::cacheFrames(unsigned value) -{ +void ArmatureData::cacheFrames(unsigned value) { if (cacheFrameRate > value) // TODO clear cache. { return; } cacheFrameRate = value; - for (const auto& pair : animations) - { + for (const auto& pair : animations) { pair.second->cacheFrames(cacheFrameRate); } } -int ArmatureData::setCacheFrame(const Matrix& globalTransformMatrix, const Transform& transform) -{ +int ArmatureData::setCacheFrame(const Matrix& globalTransformMatrix, const Transform& transform) { auto& dataArray = *&parent->cachedFrames; auto arrayOffset = dataArray.size(); @@ -164,8 +142,7 @@ int ArmatureData::setCacheFrame(const Matrix& globalTransformMatrix, const Trans return arrayOffset; } -void ArmatureData::getCacheFrame(Matrix& globalTransformMatrix, Transform& transform, unsigned arrayOffset) const -{ +void ArmatureData::getCacheFrame(Matrix& globalTransformMatrix, Transform& transform, unsigned arrayOffset) const { auto& dataArray = *&parent->cachedFrames; globalTransformMatrix.a = dataArray[arrayOffset]; globalTransformMatrix.b = dataArray[arrayOffset + 1]; @@ -181,10 +158,8 @@ void ArmatureData::getCacheFrame(Matrix& globalTransformMatrix, Transform& trans transform.y = globalTransformMatrix.ty; } -void ArmatureData::addBone(BoneData* value) -{ - if (bones.find(value->name) != bones.cend()) - { +void ArmatureData::addBone(BoneData* value) { + if (bones.find(value->name) != bones.cend()) { DRAGONBONES_ASSERT(false, "Same bone: " + value->name); return; } @@ -193,10 +168,8 @@ void ArmatureData::addBone(BoneData* value) sortedBones.push_back(value); } -void ArmatureData::addSlot(SlotData* value) -{ - if (slots.find(value->name) != slots.cend()) - { +void ArmatureData::addSlot(SlotData* value) { + if (slots.find(value->name) != slots.cend()) { DRAGONBONES_ASSERT(false, "Same slot: " + value->name); return; } @@ -205,10 +178,8 @@ void ArmatureData::addSlot(SlotData* value) sortedSlots.push_back(value); } -void ArmatureData::addConstraint(ConstraintData * value) -{ - if (constraints.find(value->name) != constraints.cend()) - { +void ArmatureData::addConstraint(ConstraintData* value) { + if (constraints.find(value->name) != constraints.cend()) { DRAGONBONES_ASSERT(false, "Same constaint: " + value->name); return; } @@ -216,10 +187,8 @@ void ArmatureData::addConstraint(ConstraintData * value) constraints[value->name] = value; } -void ArmatureData::addSkin(SkinData* value) -{ - if (skins.find(value->name) != skins.cend()) - { +void ArmatureData::addSkin(SkinData* value) { + if (skins.find(value->name) != skins.cend()) { DRAGONBONES_ASSERT(false, "Same skin: " + value->name); return; } @@ -227,16 +196,13 @@ void ArmatureData::addSkin(SkinData* value) value->parent = this; skins[value->name] = value; - if (defaultSkin == nullptr) - { + if (defaultSkin == nullptr) { defaultSkin = value; } } -void ArmatureData::addAnimation(AnimationData* value) -{ - if (animations.find(value->name) != animations.cend()) - { +void ArmatureData::addAnimation(AnimationData* value) { + if (animations.find(value->name) != animations.cend()) { DRAGONBONES_ASSERT(false, "Same animation: " + value->name); return; } @@ -244,26 +210,20 @@ void ArmatureData::addAnimation(AnimationData* value) value->parent = this; animations[value->name] = value; animationNames.push_back(value->name); - if (defaultAnimation == nullptr) - { + if (defaultAnimation == nullptr) { defaultAnimation = value; } } -void ArmatureData::addAction(ActionData* value, bool isDefault) -{ - if (isDefault) - { +void ArmatureData::addAction(ActionData* value, bool isDefault) { + if (isDefault) { defaultActions.push_back(value); - } - else - { + } else { actions.push_back(value); } } -MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, const std::string& slotName, const std::string& meshName) const -{ +MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, const std::string& slotName, const std::string& meshName) const { const auto skin = getSkin(skinName); if (skin == nullptr) { return nullptr; @@ -272,10 +232,8 @@ MeshDisplayData* ArmatureData::getMesh(const std::string& skinName, const std::s return static_cast(skin->getDisplay(slotName, meshName)); } -void BoneData::_onClear() -{ - if (userData != nullptr) - { +void BoneData::_onClear() { + if (userData != nullptr) { userData->returnToPool(); } @@ -291,20 +249,16 @@ void BoneData::_onClear() } ColorTransform SlotData::DEFAULT_COLOR; -ColorTransform* SlotData::createColor() -{ +ColorTransform* SlotData::createColor() { return new ColorTransform(); } -void SlotData::_onClear() -{ - if (userData != nullptr) - { +void SlotData::_onClear() { + if (userData != nullptr) { userData->returnToPool(); } - if (color != nullptr && color != &DEFAULT_COLOR) - { + if (color != nullptr && color != &DEFAULT_COLOR) { delete color; } diff --git a/native/cocos/editor-support/dragonbones/model/ArmatureData.h b/native/cocos/editor-support/dragonbones/model/ArmatureData.h index f4f9d62902..87b0ad4053 100644 --- a/native/cocos/editor-support/dragonbones/model/ArmatureData.h +++ b/native/cocos/editor-support/dragonbones/model/ArmatureData.h @@ -40,8 +40,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class ArmatureData : public BaseObject -{ +class ArmatureData : public BaseObject { BIND_CLASS_TYPE_B(ArmatureData); public: @@ -164,19 +163,16 @@ public: * @private */ DragonBonesData* parent; - ArmatureData() : - canvas(nullptr), - userData(nullptr) - { + ArmatureData() : canvas(nullptr), + userData(nullptr) { _onClear(); } - ~ArmatureData() - { + ~ArmatureData() { _onClear(); } protected: -virtual void _onClear() override; + virtual void _onClear() override; public: /** @@ -231,8 +227,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline BoneData* getBone(const std::string& boneName) const - { + inline BoneData* getBone(const std::string& boneName) const { return mapFind(bones, boneName); } /** @@ -247,15 +242,13 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SlotData* getSlot(const std::string& slotName) const - { + inline SlotData* getSlot(const std::string& slotName) const { return mapFind(slots, slotName); } /** * @private */ - inline ConstraintData* getConstraint(const std::string& constraintName) const - { + inline ConstraintData* getConstraint(const std::string& constraintName) const { return mapFind(constraints, constraintName); } /** @@ -270,8 +263,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline SkinData* getSkin(const std::string& skinName) const - { + inline SkinData* getSkin(const std::string& skinName) const { return mapFind(skins, skinName); } /** @@ -290,8 +282,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline AnimationData* getAnimation(const std::string& animationName) const - { + inline AnimationData* getAnimation(const std::string& animationName) const { return mapFind(animations, animationName); } @@ -328,8 +319,7 @@ public: // For WebAssembly. * @version DragonBones 3.0 * @language zh_CN */ -class BoneData : public BaseObject -{ +class BoneData : public BaseObject { BIND_CLASS_TYPE_B(BoneData); public: @@ -390,13 +380,10 @@ public: * @language zh_CN */ BoneData* parent; - BoneData() : - userData(nullptr) - { + BoneData() : userData(nullptr) { _onClear(); } - ~BoneData() - { + ~BoneData() { _onClear(); } @@ -422,8 +409,7 @@ public: // For WebAssembly. * @version DragonBones 3.0 * @language zh_CN */ -class SlotData : public BaseObject -{ +class SlotData : public BaseObject { BIND_CLASS_TYPE_B(SlotData); public: @@ -479,14 +465,11 @@ public: * @language zh_CN */ BoneData* parent; - SlotData() : - color(nullptr), - userData(nullptr) - { + SlotData() : color(nullptr), + userData(nullptr) { _onClear(); } - ~SlotData() - { + ~SlotData() { _onClear(); } diff --git a/native/cocos/editor-support/dragonbones/model/BoundingBoxData.cpp b/native/cocos/editor-support/dragonbones/model/BoundingBoxData.cpp index 556f024e64..d026c84049 100644 --- a/native/cocos/editor-support/dragonbones/model/BoundingBoxData.cpp +++ b/native/cocos/editor-support/dragonbones/model/BoundingBoxData.cpp @@ -2,34 +2,29 @@ #include "BoundingBoxData.h" #include "DisplayData.h" - DRAGONBONES_NAMESPACE_BEGIN -void BoundingBoxData::_onClear() -{ +void BoundingBoxData::_onClear() { color = 0x000000; width = 0.0f; height = 0.0f; } -int RectangleBoundingBoxData::_computeOutCode(float x, float y, float xMin, float yMin, float xMax, float yMax) -{ - int code = OutCode::InSide; // initialised as being inside of [[clip window]] +int RectangleBoundingBoxData::_computeOutCode(float x, float y, float xMin, float yMin, float xMax, float yMax) { + int code = OutCode::InSide; // initialised as being inside of [[clip window]] - if (x < xMin) // to the left of clip window + if (x < xMin) // to the left of clip window { code |= OutCode::Left; - } - else if (x > xMax) // to the right of clip window + } else if (x > xMax) // to the right of clip window { code |= OutCode::Right; } - if (y < yMin) // below the clip window + if (y < yMin) // below the clip window { code |= OutCode::Top; - } - else if (y > yMax) // above the clip window + } else if (y > yMax) // above the clip window { code |= OutCode::Bottom; } @@ -42,14 +37,11 @@ int RectangleBoundingBoxData::rectangleIntersectsSegment( float xMin, float yMin, float xMax, float yMax, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ + Point* normalRadians) { const auto inSideA = xA > xMin && xA < xMax && yA > yMin && yA < yMax; const auto inSideB = xB > xMin && xB < xMax && yB > yMin && yB < yMax; - if (inSideA && inSideB) - { + if (inSideA && inSideB) { return -1; } @@ -57,14 +49,12 @@ int RectangleBoundingBoxData::rectangleIntersectsSegment( auto outcode0 = RectangleBoundingBoxData::_computeOutCode(xA, yA, xMin, yMin, xMax, yMax); auto outcode1 = RectangleBoundingBoxData::_computeOutCode(xB, yB, xMin, yMin, xMax, yMax); - while (true) - { + while (true) { if ((outcode0 | outcode1) == 0) // Bitwise OR is 0. Trivially accept and get out of loop { intersectionCount = 2; break; - } - else if ((outcode0 & outcode1) != 0) // Bitwise AND is not 0. Trivially reject and get out of loop + } else if ((outcode0 & outcode1) != 0) // Bitwise AND is not 0. Trivially reject and get out of loop { break; } @@ -79,128 +69,102 @@ int RectangleBoundingBoxData::rectangleIntersectsSegment( const auto outcodeOut = outcode0 != 0 ? outcode0 : outcode1; // Now find the intersection point; - if ((outcodeOut & OutCode::Top) != 0) // point is above the clip rectangle + if ((outcodeOut & OutCode::Top) != 0) // point is above the clip rectangle { x = xA + (xB - xA) * (yMin - yA) / (yB - yA); y = yMin; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadian = -Transform::PI * 0.5f; } - } - else if ((outcodeOut & OutCode::Bottom) != 0) // point is below the clip rectangle + } else if ((outcodeOut & OutCode::Bottom) != 0) // point is below the clip rectangle { x = xA + (xB - xA) * (yMax - yA) / (yB - yA); y = yMax; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadian = Transform::PI * 0.5; } - } - else if ((outcodeOut & OutCode::Right) != 0) // point is to the right of clip rectangle + } else if ((outcodeOut & OutCode::Right) != 0) // point is to the right of clip rectangle { y = yA + (yB - yA) * (xMax - xA) / (xB - xA); x = xMax; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadian = 0; } - } - else if ((outcodeOut & OutCode::Left) != 0) // point is to the left of clip rectangle + } else if ((outcodeOut & OutCode::Left) != 0) // point is to the left of clip rectangle { y = yA + (yB - yA) * (xMin - xA) / (xB - xA); x = xMin; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadian = Transform::PI; } } // Now we move outside point to intersection point to clip // and get ready for next pass. - if (outcodeOut == outcode0) - { + if (outcodeOut == outcode0) { xA = x; yA = y; outcode0 = RectangleBoundingBoxData::_computeOutCode(xA, yA, xMin, yMin, xMax, yMax); - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = normalRadian; } - } - else - { + } else { xB = x; yB = y; outcode1 = RectangleBoundingBoxData::_computeOutCode(xB, yB, xMin, yMin, xMax, yMax); - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->y = normalRadian; } } } - if (intersectionCount) - { - if (inSideA) - { + if (intersectionCount) { + if (inSideA) { intersectionCount = 2; // 10 - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xB; intersectionPointA->y = yB; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xB; intersectionPointB->y = xB; } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = normalRadians->y + Transform::PI; } - } - else if (inSideB) - { + } else if (inSideB) { intersectionCount = 1; // 01 - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xA; intersectionPointA->y = yA; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xA; intersectionPointB->y = yA; } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->y = normalRadians->x + Transform::PI; } - } - else - { + } else { intersectionCount = 3; // 11 - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xA; intersectionPointA->y = yA; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xB; intersectionPointB->y = yB; } @@ -210,21 +174,17 @@ int RectangleBoundingBoxData::rectangleIntersectsSegment( return intersectionCount; } -void RectangleBoundingBoxData::_onClear() -{ +void RectangleBoundingBoxData::_onClear() { BoundingBoxData::_onClear(); type = BoundingBoxType::Rectangle; } -bool RectangleBoundingBoxData::containsPoint(float pX, float pY) -{ +bool RectangleBoundingBoxData::containsPoint(float pX, float pY) { const auto widthH = width * 0.5f; - if (pX >= -widthH && pX <= widthH) - { + if (pX >= -widthH && pX <= widthH) { const auto heightH = height * 0.5f; - if (pY >= -heightH && pY <= heightH) - { + if (pY >= -heightH && pY <= heightH) { return true; } } @@ -236,16 +196,13 @@ int RectangleBoundingBoxData::intersectsSegment( float xA, float yA, float xB, float yB, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ + Point* normalRadians) { const auto widthH = width * 0.5f; const auto heightH = height * 0.5f; const auto intersectionCount = RectangleBoundingBoxData::rectangleIntersectsSegment( xA, yA, xB, yB, -widthH, -heightH, widthH, heightH, - intersectionPointA, intersectionPointB, normalRadians - ); + intersectionPointA, intersectionPointB, normalRadians); return intersectionCount; } @@ -255,9 +212,7 @@ int EllipseBoundingBoxData::ellipseIntersectsSegment( float xC, float yC, float widthH, float heightH, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ + Point* normalRadians) { const auto d = widthH / heightH; const auto dd = d * d; @@ -276,8 +231,7 @@ int EllipseBoundingBoxData::ellipseIntersectsSegment( const auto dR = rr - ee + aa; auto intersectionCount = 0; - if (dR >= 0.0f) - { + if (dR >= 0.0f) { const auto dT = sqrt(dR); const auto sA = a - dT; const auto sB = a + dT; @@ -285,82 +239,64 @@ int EllipseBoundingBoxData::ellipseIntersectsSegment( const auto inSideB = sB < 0.0f ? -1 : (sB <= lAB ? 0 : 1); const auto sideAB = inSideA * inSideB; - if (sideAB < 0) - { + if (sideAB < 0) { return -1; - } - else if (sideAB == 0) - { - if (inSideA == -1) - { + } else if (sideAB == 0) { + if (inSideA == -1) { intersectionCount = 2; // 10 xB = xA + sB * xD; yB = (yA + sB * yD) / d; - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xB; intersectionPointA->y = yB; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xB; intersectionPointB->y = yB; } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(yB / rr * dd, xB / rr); normalRadians->y = normalRadians->x + Transform::PI; } - } - else if (inSideB == 1) - { + } else if (inSideB == 1) { intersectionCount = 1; // 01 xA = xA + sA * xD; yA = (yA + sA * yD) / d; - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xA; intersectionPointA->y = yA; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xA; intersectionPointB->y = yA; } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(yA / rr * dd, xA / rr); normalRadians->y = normalRadians->x + Transform::PI; } - } - else - { + } else { intersectionCount = 3; // 11 - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xA + sA * xD; intersectionPointA->y = (yA + sA * yD) / d; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(intersectionPointA->y / rr * dd, intersectionPointA->x / rr); } } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xA + sB * xD; intersectionPointB->y = (yA + sB * yD) / d; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->y = atan2(intersectionPointB->y / rr * dd, intersectionPointB->x / rr); } } @@ -379,14 +315,11 @@ void EllipseBoundingBoxData::_onClear() type = BoundingBoxType::Ellipse; } -bool EllipseBoundingBoxData::containsPoint(float pX, float pY) -{ +bool EllipseBoundingBoxData::containsPoint(float pX, float pY) { const auto widthH = width * 0.5f; - if (pX >= -widthH && pX <= widthH) - { + if (pX >= -widthH && pX <= widthH) { const auto heightH = height * 0.5f; - if (pY >= -heightH && pY <= heightH) - { + if (pY >= -heightH && pY <= heightH) { pY *= widthH / heightH; return sqrt(pX * pX + pY * pY) <= widthH; } @@ -399,14 +332,11 @@ int EllipseBoundingBoxData::intersectsSegment( float xA, float yA, float xB, float yB, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ + Point* normalRadians) { const auto intersectionCount = EllipseBoundingBoxData::ellipseIntersectsSegment( xA, yA, xB, yB, 0.0f, 0.0f, width * 0.5f, height * 0.5f, - intersectionPointA, intersectionPointB, normalRadians - ); + intersectionPointA, intersectionPointB, normalRadians); return intersectionCount; } @@ -416,15 +346,12 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( const std::vector& vertices, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians) -{ - if (xA == xB) - { + Point* normalRadians) { + if (xA == xB) { xA = xB + 0.000001f; } - if (yA == yB) - { + if (yA == yB) { yA = yB + 0.000001f; } @@ -442,18 +369,15 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( auto xMax = 0.0f; auto yMax = 0.0f; - for (std::size_t i = 0; i < count; i += 2) - { + for (std::size_t i = 0; i < count; i += 2) { const auto xD = vertices[i]; const auto yD = vertices[i + 1]; - if (xC == xD) - { + if (xC == xD) { xC = xD + 0.000001f; } - if (yC == yD) - { + if (yC == yD) { yC = yD + 0.000001f; } @@ -463,21 +387,16 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( const auto ll = dXAB * dYCD - dYAB * dXCD; const auto x = (llAB * dXCD - dXAB * llCD) / ll; - if (((x >= xC && x <= xD) || (x >= xD && x <= xC)) && (dXAB == 0.0f || (x >= xA && x <= xB) || (x >= xB && x <= xA))) - { + if (((x >= xC && x <= xD) || (x >= xD && x <= xC)) && (dXAB == 0.0f || (x >= xA && x <= xB) || (x >= xB && x <= xA))) { const auto y = (llAB * dYCD - dYAB * llCD) / ll; - if (((y >= yC && y <= yD) || (y >= yD && y <= yC)) && (dYAB == 0.0f || (y >= yA && y <= yB) || (y >= yB && y <= yA))) - { - if (intersectionPointB != nullptr) - { + if (((y >= yC && y <= yD) || (y >= yD && y <= yC)) && (dYAB == 0.0f || (y >= yA && y <= yB) || (y >= yB && y <= yA))) { + if (intersectionPointB != nullptr) { float d = x - xA; - if (d < 0.0f) - { + if (d < 0.0f) { d = -d; } - if (intersectionCount == 0) - { + if (intersectionCount == 0) { dMin = d; dMax = d; xMin = x; @@ -485,28 +404,22 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( xMax = x; yMax = y; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(yD - yC, xD - xC) - Transform::PI * 0.5f; normalRadians->y = normalRadians->x; } - } - else - { - if (d < dMin) - { + } else { + if (d < dMin) { dMin = d; xMin = x; yMin = y; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(yD - yC, xD - xC) - Transform::PI * 0.5f; } } - if (d > dMax) - { + if (d > dMax) { dMax = d; xMax = x; yMax = y; @@ -518,17 +431,14 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( } intersectionCount++; - } - else - { + } else { xMin = x; yMin = y; xMax = x; yMax = y; intersectionCount++; - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->x = atan2(yD - yC, xD - xC) - Transform::PI * 0.5f; normalRadians->y = normalRadians->x; } @@ -541,37 +451,29 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( yC = yD; } - if (intersectionCount == 1) - { - if (intersectionPointA != nullptr) - { + if (intersectionCount == 1) { + if (intersectionPointA != nullptr) { intersectionPointA->x = xMin; intersectionPointA->y = yMin; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xMin; intersectionPointB->y = yMin; } - if (normalRadians != nullptr) - { + if (normalRadians != nullptr) { normalRadians->y = normalRadians->x + Transform::PI; } - } - else if (intersectionCount > 1) - { + } else if (intersectionCount > 1) { intersectionCount++; - if (intersectionPointA != nullptr) - { + if (intersectionPointA != nullptr) { intersectionPointA->x = xMin; intersectionPointA->y = yMin; } - if (intersectionPointB != nullptr) - { + if (intersectionPointB != nullptr) { intersectionPointB->x = xMax; intersectionPointB->y = yMax; } @@ -580,12 +482,10 @@ int PolygonBoundingBoxData::polygonIntersectsSegment( return intersectionCount; } -void PolygonBoundingBoxData::_onClear() -{ +void PolygonBoundingBoxData::_onClear() { BoundingBoxData::_onClear(); - if (weight != nullptr) - { + if (weight != nullptr) { weight->returnToPool(); } @@ -596,21 +496,16 @@ void PolygonBoundingBoxData::_onClear() weight = nullptr; } -bool PolygonBoundingBoxData::containsPoint(float pX, float pY) -{ +bool PolygonBoundingBoxData::containsPoint(float pX, float pY) { auto isInSide = false; - if (pX >= x && pX <= width && pY >= y && pY <= height) - { - for (std::size_t i = 0, l = vertices.size(), iP = l - 2; i < l; i += 2) - { + if (pX >= x && pX <= width && pY >= y && pY <= height) { + for (std::size_t i = 0, l = vertices.size(), iP = l - 2; i < l; i += 2) { const auto yA = vertices[iP + 1]; const auto yB = vertices[i + 1]; - if ((yB < pY && yA >= pY) || (yA < pY && yB >= pY)) - { + if ((yB < pY && yA >= pY) || (yA < pY && yB >= pY)) { const auto xA = vertices[iP]; const auto xB = vertices[i]; - if ((pY - yB) * (xA - xB) / (yA - yB) + xB < pX) - { + if ((pY - yB) * (xA - xB) / (yA - yB) + xB < pX) { isInSide = !isInSide; } } @@ -626,16 +521,13 @@ int PolygonBoundingBoxData::intersectsSegment( float xA, float yA, float xB, float yB, Point* intersectionPointA, Point* intersectionPointB, - Point* normalRadians -) -{ + Point* normalRadians) { auto intersectionCount = 0; if (RectangleBoundingBoxData::rectangleIntersectsSegment(xA, yA, xB, yB, x, y, x + width, y + height, nullptr, nullptr, nullptr) != 0) { intersectionCount = PolygonBoundingBoxData::polygonIntersectsSegment( xA, yA, xB, yB, vertices, - intersectionPointA, intersectionPointB, normalRadians - ); + intersectionPointA, intersectionPointB, normalRadians); } return intersectionCount; diff --git a/native/cocos/editor-support/dragonbones/model/BoundingBoxData.h b/native/cocos/editor-support/dragonbones/model/BoundingBoxData.h index cb653ef73c..5a498166f6 100644 --- a/native/cocos/editor-support/dragonbones/model/BoundingBoxData.h +++ b/native/cocos/editor-support/dragonbones/model/BoundingBoxData.h @@ -43,8 +43,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 5.0 * @language zh_CN */ -class BoundingBoxData : public BaseObject -{ +class BoundingBoxData : public BaseObject { ABSTRACT_CLASS(BoundingBoxData); public: @@ -101,8 +100,7 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ) = 0; + Point* normalRadians = nullptr) = 0; public: // For WebAssembly. int getType() const { return (int)type; } @@ -118,8 +116,7 @@ public: // For WebAssembly. * @version DragonBones 5.1 * @language zh_CN */ -class RectangleBoundingBoxData : public BoundingBoxData -{ +class RectangleBoundingBoxData : public BoundingBoxData { BIND_CLASS_TYPE_A(RectangleBoundingBoxData); private: @@ -144,8 +141,7 @@ public: float xMin, float yMin, float xMax, float yMax, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ); + Point* normalRadians = nullptr); /** * @inheritDoc */ @@ -157,8 +153,7 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ) override; + Point* normalRadians = nullptr) override; protected: virtual void _onClear() override; @@ -173,8 +168,7 @@ protected: * @version DragonBones 5.1 * @language zh_CN */ -class EllipseBoundingBoxData : public BoundingBoxData -{ +class EllipseBoundingBoxData : public BoundingBoxData { BIND_CLASS_TYPE_A(EllipseBoundingBoxData); public: @@ -186,8 +180,7 @@ public: float xC, float yC, float widthH, float heightH, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ); + Point* normalRadians = nullptr); /** * @inheritDoc */ @@ -199,8 +192,7 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ) override; + Point* normalRadians = nullptr) override; protected: virtual void _onClear() override; @@ -215,8 +207,7 @@ protected: * @version DragonBones 5.1 * @language zh_CN */ -class PolygonBoundingBoxData : public BoundingBoxData -{ +class PolygonBoundingBoxData : public BoundingBoxData { BIND_CLASS_TYPE_B(PolygonBoundingBoxData); public: @@ -228,8 +219,7 @@ public: const std::vector& vertices, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ); + Point* normalRadians = nullptr); /** * @private */ @@ -261,16 +251,12 @@ public: float xA, float yA, float xB, float yB, Point* intersectionPointA = nullptr, Point* intersectionPointB = nullptr, - Point* normalRadians = nullptr - ) override; + Point* normalRadians = nullptr) override; - PolygonBoundingBoxData() : - weight(nullptr) - { + PolygonBoundingBoxData() : weight(nullptr) { _onClear(); } - ~PolygonBoundingBoxData() - { + ~PolygonBoundingBoxData() { _onClear(); } diff --git a/native/cocos/editor-support/dragonbones/model/CanvasData.cpp b/native/cocos/editor-support/dragonbones/model/CanvasData.cpp index 722ffd4a7e..1a7565ca79 100644 --- a/native/cocos/editor-support/dragonbones/model/CanvasData.cpp +++ b/native/cocos/editor-support/dragonbones/model/CanvasData.cpp @@ -2,8 +2,7 @@ DRAGONBONES_NAMESPACE_BEGIN -void CanvasData::_onClear() -{ +void CanvasData::_onClear() { hasBackground = false; color = 0x000000; aabb.clear(); diff --git a/native/cocos/editor-support/dragonbones/model/CanvasData.h b/native/cocos/editor-support/dragonbones/model/CanvasData.h index 954c769eb6..2a7df32b17 100644 --- a/native/cocos/editor-support/dragonbones/model/CanvasData.h +++ b/native/cocos/editor-support/dragonbones/model/CanvasData.h @@ -30,8 +30,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class CanvasData : public BaseObject -{ +class CanvasData : public BaseObject { BIND_CLASS_TYPE_A(CanvasData); public: diff --git a/native/cocos/editor-support/dragonbones/model/ConstraintData.cpp b/native/cocos/editor-support/dragonbones/model/ConstraintData.cpp index 5dde00a540..79298aca65 100644 --- a/native/cocos/editor-support/dragonbones/model/ConstraintData.cpp +++ b/native/cocos/editor-support/dragonbones/model/ConstraintData.cpp @@ -6,8 +6,7 @@ DRAGONBONES_NAMESPACE_BEGIN -void ConstraintData::_onClear() -{ +void ConstraintData::_onClear() { order = 0; name = ""; target = nullptr; @@ -15,8 +14,7 @@ void ConstraintData::_onClear() bone = nullptr; } -void IKConstraintData::_onClear() -{ +void IKConstraintData::_onClear() { ConstraintData::_onClear(); scaleEnabled = false; diff --git a/native/cocos/editor-support/dragonbones/model/ConstraintData.h b/native/cocos/editor-support/dragonbones/model/ConstraintData.h index 8483a6b6db..3dbc1f468f 100644 --- a/native/cocos/editor-support/dragonbones/model/ConstraintData.h +++ b/native/cocos/editor-support/dragonbones/model/ConstraintData.h @@ -33,8 +33,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class ConstraintData : public BaseObject -{ +class ConstraintData : public BaseObject { ABSTRACT_CLASS(ConstraintData) public: @@ -48,7 +47,7 @@ protected: virtual void _onClear() override; public: // For WebAssembly. - const BoneData* getTarget() const { return target; } + const BoneData* getTarget() const { return target; } void setTarget(const BoneData* value) { target = value; } const BoneData* getBone() const { return bone; } @@ -60,8 +59,7 @@ public: // For WebAssembly. /** * @internal */ -class IKConstraintData : public ConstraintData -{ +class IKConstraintData : public ConstraintData { BIND_CLASS_TYPE_A(IKConstraintData); public: diff --git a/native/cocos/editor-support/dragonbones/model/DisplayData.cpp b/native/cocos/editor-support/dragonbones/model/DisplayData.cpp index 66e67e6814..9dae5d49e8 100644 --- a/native/cocos/editor-support/dragonbones/model/DisplayData.cpp +++ b/native/cocos/editor-support/dragonbones/model/DisplayData.cpp @@ -8,10 +8,8 @@ DRAGONBONES_NAMESPACE_BEGIN -void VerticesData::clear() -{ - if (!isShared && weight != nullptr) - { +void VerticesData::clear() { + if (!isShared && weight != nullptr) { weight->returnToPool(); } @@ -22,23 +20,20 @@ void VerticesData::clear() weight = nullptr; } -void VerticesData::shareFrom(const VerticesData& value) -{ +void VerticesData::shareFrom(const VerticesData& value) { isShared = true; offset = value.offset; weight = value.weight; } -void DisplayData::_onClear() -{ +void DisplayData::_onClear() { name = ""; path = ""; transform.identity(); parent = nullptr; } -void ImageDisplayData::_onClear() -{ +void ImageDisplayData::_onClear() { DisplayData::_onClear(); type = DisplayType::Image; @@ -46,12 +41,10 @@ void ImageDisplayData::_onClear() texture = nullptr; } -void ArmatureDisplayData::_onClear() -{ +void ArmatureDisplayData::_onClear() { DisplayData::_onClear(); - for(const auto action : actions) - { + for (const auto action : actions) { action->returnToPool(); } @@ -61,13 +54,11 @@ void ArmatureDisplayData::_onClear() armature = nullptr; } -void ArmatureDisplayData::addAction(ActionData* value) -{ +void ArmatureDisplayData::addAction(ActionData* value) { actions.push_back(value); } -void MeshDisplayData::_onClear() -{ +void MeshDisplayData::_onClear() { DisplayData::_onClear(); type = DisplayType::Mesh; @@ -75,12 +66,10 @@ void MeshDisplayData::_onClear() texture = nullptr; } -void BoundingBoxDisplayData::_onClear() -{ +void BoundingBoxDisplayData::_onClear() { DisplayData::_onClear(); - if(boundingBox != nullptr) - { + if (boundingBox != nullptr) { boundingBox->returnToPool(); } @@ -88,15 +77,13 @@ void BoundingBoxDisplayData::_onClear() boundingBox = nullptr; } -void WeightData::_onClear() -{ +void WeightData::_onClear() { count = 0; offset = 0; bones.clear(); } -void WeightData::addBone(BoneData* value) -{ +void WeightData::addBone(BoneData* value) { bones.push_back(value); } diff --git a/native/cocos/editor-support/dragonbones/model/DisplayData.h b/native/cocos/editor-support/dragonbones/model/DisplayData.h index 2e441d8917..5f7479b2f2 100644 --- a/native/cocos/editor-support/dragonbones/model/DisplayData.h +++ b/native/cocos/editor-support/dragonbones/model/DisplayData.h @@ -31,8 +31,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class VerticesData -{ +class VerticesData { public: bool isShared; bool inheritDeform; @@ -40,12 +39,9 @@ public: DragonBonesData* data; WeightData* weight; - VerticesData() : - weight(nullptr) - { + VerticesData() : weight(nullptr) { } - ~VerticesData() - { + ~VerticesData() { } void clear(); @@ -54,8 +50,7 @@ public: /** * @internal */ -class DisplayData : public BaseObject -{ +class DisplayData : public BaseObject { ABSTRACT_CLASS(DisplayData) public: @@ -80,8 +75,7 @@ public: // For WebAssembly. /** * @internal */ -class ImageDisplayData : public DisplayData -{ +class ImageDisplayData : public DisplayData { BIND_CLASS_TYPE_A(ImageDisplayData); public: @@ -100,8 +94,7 @@ public: // For WebAssembly. /** * @internal */ -class ArmatureDisplayData : public DisplayData -{ +class ArmatureDisplayData : public DisplayData { BIND_CLASS_TYPE_A(ArmatureDisplayData); public: @@ -127,8 +120,7 @@ public: // For WebAssembly. /** * @internal */ -class MeshDisplayData : public DisplayData -{ +class MeshDisplayData : public DisplayData { BIND_CLASS_TYPE_A(MeshDisplayData); public: @@ -141,20 +133,16 @@ protected: /** * @internal */ -class BoundingBoxDisplayData : public DisplayData -{ +class BoundingBoxDisplayData : public DisplayData { BIND_CLASS_TYPE_B(BoundingBoxDisplayData); public: BoundingBoxData* boundingBox; - BoundingBoxDisplayData() : - boundingBox(nullptr) - { - _onClear(); + BoundingBoxDisplayData() : boundingBox(nullptr) { + _onClear(); } - ~BoundingBoxDisplayData() - { + ~BoundingBoxDisplayData() { _onClear(); } @@ -168,8 +156,7 @@ public: // For WebAssembly. /** * @internal */ -class WeightData : public BaseObject -{ +class WeightData : public BaseObject { BIND_CLASS_TYPE_A(WeightData); public: diff --git a/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp b/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp index c5fe80910d..8be62eb83a 100644 --- a/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp +++ b/native/cocos/editor-support/dragonbones/model/DragonBonesData.cpp @@ -2,23 +2,18 @@ #include "UserData.h" #include "ArmatureData.h" - DRAGONBONES_NAMESPACE_BEGIN -void DragonBonesData::_onClear() -{ - for (const auto& pair : armatures) - { +void DragonBonesData::_onClear() { + for (const auto& pair : armatures) { pair.second->returnToPool(); } - if (binary != nullptr) - { + if (binary != nullptr) { delete binary; } - if (userData != nullptr) - { + if (userData != nullptr) { userData->returnToPool(); } @@ -40,10 +35,8 @@ void DragonBonesData::_onClear() userData = nullptr; } -void DragonBonesData::addArmature(ArmatureData* value) -{ - if (armatures.find(value->name) != armatures.end()) - { +void DragonBonesData::addArmature(ArmatureData* value) { + if (armatures.find(value->name) != armatures.end()) { DRAGONBONES_ASSERT(false, "Same armature: " + value->name); return; } diff --git a/native/cocos/editor-support/dragonbones/model/DragonBonesData.h b/native/cocos/editor-support/dragonbones/model/DragonBonesData.h index d498b27dd1..25bbbb1b7b 100644 --- a/native/cocos/editor-support/dragonbones/model/DragonBonesData.h +++ b/native/cocos/editor-support/dragonbones/model/DragonBonesData.h @@ -41,8 +41,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class DragonBonesData : public BaseObject -{ +class DragonBonesData : public BaseObject { BIND_CLASS_TYPE_B(DragonBonesData); public: @@ -140,14 +139,11 @@ public: * @private */ UserData* userData; - DragonBonesData() : - binary(nullptr), - userData(nullptr) - { + DragonBonesData() : binary(nullptr), + userData(nullptr) { _onClear(); } - ~DragonBonesData() - { + ~DragonBonesData() { _onClear(); } /** @@ -166,8 +162,7 @@ public: * @version DragonBones 3.0 * @language zh_CN */ - inline ArmatureData* getArmature(const std::string& armatureName) const - { + inline ArmatureData* getArmature(const std::string& armatureName) const { return mapFind(armatures, armatureName); } @@ -179,8 +174,7 @@ public: // For WebAssembly. const std::vector& getArmatureNames() const { return armatureNames; } #if EGRET_WASM - unsigned getBinary() const - { + unsigned getBinary() const { return (unsigned)binary; } #endif // EGRET_WASM diff --git a/native/cocos/editor-support/dragonbones/model/SkinData.cpp b/native/cocos/editor-support/dragonbones/model/SkinData.cpp index e3b1883595..bf440b55bb 100644 --- a/native/cocos/editor-support/dragonbones/model/SkinData.cpp +++ b/native/cocos/editor-support/dragonbones/model/SkinData.cpp @@ -3,14 +3,10 @@ DRAGONBONES_NAMESPACE_BEGIN -void SkinData::_onClear() -{ - for (const auto& pair : displays) - { - for (const auto display : pair.second) - { - if (display != nullptr) - { +void SkinData::_onClear() { + for (const auto& pair : displays) { + for (const auto display : pair.second) { + if (display != nullptr) { display->returnToPool(); } } @@ -21,25 +17,19 @@ void SkinData::_onClear() parent = nullptr; } -void SkinData::addDisplay(const std::string& slotName, DisplayData* value) -{ - if (value != nullptr) - { +void SkinData::addDisplay(const std::string& slotName, DisplayData* value) { + if (value != nullptr) { value->parent = this; } displays[slotName].push_back(value); // TODO clear prev } -DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName) -{ +DisplayData* SkinData::getDisplay(const std::string& slotName, const std::string& displayName) { const auto slotDisplays = getDisplays(slotName); - if (slotDisplays != nullptr) - { - for (const auto display : *slotDisplays) - { - if (display != nullptr && display->name == displayName) - { + if (slotDisplays != nullptr) { + for (const auto display : *slotDisplays) { + if (display != nullptr && display->name == displayName) { return display; } } diff --git a/native/cocos/editor-support/dragonbones/model/SkinData.h b/native/cocos/editor-support/dragonbones/model/SkinData.h index 14daef6e76..3786ebed93 100644 --- a/native/cocos/editor-support/dragonbones/model/SkinData.h +++ b/native/cocos/editor-support/dragonbones/model/SkinData.h @@ -36,8 +36,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class SkinData : public BaseObject -{ +class SkinData : public BaseObject { BIND_CLASS_TYPE_A(SkinData); public: @@ -76,8 +75,7 @@ public: /** * @private */ - std::vector* getDisplays(const std::string& slotName) - { + std::vector* getDisplays(const std::string& slotName) { return mapFindB(displays, slotName); } diff --git a/native/cocos/editor-support/dragonbones/model/TextureAtlasData.cpp b/native/cocos/editor-support/dragonbones/model/TextureAtlasData.cpp index 207c864522..819917951e 100644 --- a/native/cocos/editor-support/dragonbones/model/TextureAtlasData.cpp +++ b/native/cocos/editor-support/dragonbones/model/TextureAtlasData.cpp @@ -2,10 +2,8 @@ DRAGONBONES_NAMESPACE_BEGIN -void TextureAtlasData::_onClear() -{ - for (const auto& pair : textures) - { +void TextureAtlasData::_onClear() { + for (const auto& pair : textures) { pair.second->returnToPool(); } @@ -19,8 +17,7 @@ void TextureAtlasData::_onClear() textures.clear(); } -void TextureAtlasData::copyFrom(const TextureAtlasData& value) -{ +void TextureAtlasData::copyFrom(const TextureAtlasData& value) { autoSearch = value.autoSearch; format = value.format; width = value.width; @@ -29,25 +26,21 @@ void TextureAtlasData::copyFrom(const TextureAtlasData& value) name = value.name; imagePath = value.imagePath; - for (const auto& pair : textures) - { + for (const auto& pair : textures) { pair.second->returnToPool(); } textures.clear(); - for (const auto& pair : value.textures) - { + for (const auto& pair : value.textures) { const auto texture = createTexture(); texture->copyFrom(*(pair.second)); textures[pair.first] = texture; } } -void TextureAtlasData::addTexture(TextureData* value) -{ - if (textures.find(value->name) != textures.cend()) - { +void TextureAtlasData::addTexture(TextureData* value) { + if (textures.find(value->name) != textures.cend()) { DRAGONBONES_ASSERT(false, "Same texture: " + value->name); return; } @@ -56,19 +49,15 @@ void TextureAtlasData::addTexture(TextureData* value) value->parent = this; } -Rectangle* TextureData::createRectangle() -{ +Rectangle* TextureData::createRectangle() { return new Rectangle(); } -TextureData::~TextureData() -{ +TextureData::~TextureData() { } -void TextureData::_onClear() -{ - if (frame != nullptr) - { +void TextureData::_onClear() { + if (frame != nullptr) { delete frame; } @@ -79,25 +68,20 @@ void TextureData::_onClear() frame = nullptr; } -void TextureData::copyFrom(const TextureData &value) -{ +void TextureData::copyFrom(const TextureData& value) { rotated = value.rotated; name = value.name; region = value.region; // Copy. parent = value.parent; - if (frame == nullptr && value.frame != nullptr) - { + if (frame == nullptr && value.frame != nullptr) { frame = TextureData::createRectangle(); - } - else if (frame != nullptr && value.frame == nullptr) - { + } else if (frame != nullptr && value.frame == nullptr) { delete frame; frame = nullptr; } - if (frame != nullptr && value.frame != nullptr) - { + if (frame != nullptr && value.frame != nullptr) { *frame = *(value.frame); // Copy. } } diff --git a/native/cocos/editor-support/dragonbones/model/TextureAtlasData.h b/native/cocos/editor-support/dragonbones/model/TextureAtlasData.h index 6458dc994b..4b87cc826b 100644 --- a/native/cocos/editor-support/dragonbones/model/TextureAtlasData.h +++ b/native/cocos/editor-support/dragonbones/model/TextureAtlasData.h @@ -37,8 +37,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 3.0 * @language zh_CN */ -class TextureAtlasData : public BaseObject -{ +class TextureAtlasData : public BaseObject { ABSTRACT_CLASS(TextureAtlasData); public: @@ -100,8 +99,7 @@ public: /** * @private */ - inline TextureData* getTexture(const std::string& textureName) const - { + inline TextureData* getTexture(const std::string& textureName) const { return mapFind(textures, textureName); } @@ -114,8 +112,7 @@ public: // For WebAssembly. /** * @internal */ -class TextureData : public BaseObject -{ +class TextureData : public BaseObject { public: static Rectangle* createRectangle(); @@ -126,9 +123,7 @@ public: Rectangle* frame; TextureAtlasData* parent; - TextureData() : - frame(nullptr) - {} + TextureData() : frame(nullptr) {} virtual ~TextureData() = 0; void copyFrom(const TextureData& value); diff --git a/native/cocos/editor-support/dragonbones/model/UserData.cpp b/native/cocos/editor-support/dragonbones/model/UserData.cpp index b197980d63..39ab1dade1 100644 --- a/native/cocos/editor-support/dragonbones/model/UserData.cpp +++ b/native/cocos/editor-support/dragonbones/model/UserData.cpp @@ -2,47 +2,38 @@ DRAGONBONES_NAMESPACE_BEGIN -void UserData::_onClear() -{ +void UserData::_onClear() { ints.clear(); floats.clear(); strings.clear(); } -void UserData::addInt(int value) -{ +void UserData::addInt(int value) { ints.push_back(value); } -void UserData::addFloat(float value) -{ +void UserData::addFloat(float value) { floats.push_back(value); } -void UserData::addString(std::string value) -{ +void UserData::addString(std::string value) { strings.push_back(value); } -int UserData::getInt(unsigned index) const -{ +int UserData::getInt(unsigned index) const { return index < ints.size() ? ints[index] : 0; } -float UserData::getFloat(unsigned index) const -{ +float UserData::getFloat(unsigned index) const { return index < floats.size() ? floats[index] : 0; } -std::string UserData::getString(unsigned index) const -{ +std::string UserData::getString(unsigned index) const { return index < strings.size() ? strings[index] : 0; } -void ActionData::_onClear() -{ - if (data != nullptr) - { +void ActionData::_onClear() { + if (data != nullptr) { data->returnToPool(); } diff --git a/native/cocos/editor-support/dragonbones/model/UserData.h b/native/cocos/editor-support/dragonbones/model/UserData.h index 68b4e4b24e..afd230f87c 100644 --- a/native/cocos/editor-support/dragonbones/model/UserData.h +++ b/native/cocos/editor-support/dragonbones/model/UserData.h @@ -36,8 +36,7 @@ DRAGONBONES_NAMESPACE_BEGIN * @version DragonBones 5.0 * @language zh_CN */ -class UserData : public BaseObject -{ +class UserData : public BaseObject { BIND_CLASS_TYPE_A(UserData); public: @@ -133,8 +132,7 @@ public: // For WebAssembly. /** * @internal */ -class ActionData : public BaseObject -{ +class ActionData : public BaseObject { BIND_CLASS_TYPE_B(ActionData); public: @@ -144,13 +142,10 @@ public: const SlotData* slot; UserData* data; - ActionData() : - data(nullptr) - { + ActionData() : data(nullptr) { _onClear(); } - virtual ~ActionData() - { + virtual ~ActionData() { _onClear(); } diff --git a/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.cpp b/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.cpp index 515c43b1ed..9c7c0ec7f6 100644 --- a/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.cpp +++ b/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.cpp @@ -2,8 +2,7 @@ DRAGONBONES_NAMESPACE_BEGIN -TimelineData* BinaryDataParser::_parseBinaryTimeline(TimelineType type, unsigned offset, TimelineData* timelineData) -{ +TimelineData* BinaryDataParser::_parseBinaryTimeline(TimelineType type, unsigned offset, TimelineData* timelineData) { const auto timeline = timelineData != nullptr ? timelineData : BaseObject::borrowObject(); timeline->type = type; timeline->offset = offset; @@ -11,12 +10,9 @@ TimelineData* BinaryDataParser::_parseBinaryTimeline(TimelineType type, unsigned _timeline = timeline; const auto keyFrameCount = (unsigned)_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount]; - if (keyFrameCount == 1) - { + if (keyFrameCount == 1) { timeline->frameIndicesOffset = -1; - } - else - { + } else { unsigned frameIndicesOffset = 0; const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. auto& frameIndices = _data->frameIndices; @@ -28,18 +24,12 @@ TimelineData* BinaryDataParser::_parseBinaryTimeline(TimelineType type, unsigned for ( std::size_t i = 0, iK = 0, frameStart = 0, frameCount = 0; i < totalFrameCount; - ++i - ) - { - if (frameStart + frameCount <= i && iK < keyFrameCount) - { + ++i) { + if (frameStart + frameCount <= i && iK < keyFrameCount) { frameStart = _frameArray[_animation->frameOffset + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + iK]]; - if (iK == keyFrameCount - 1) - { + if (iK == keyFrameCount - 1) { frameCount = _animation->frameCount - frameStart; - } - else - { + } else { frameCount = _frameArray[_animation->frameOffset + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + iK + 1]] - frameStart; } @@ -55,28 +45,24 @@ TimelineData* BinaryDataParser::_parseBinaryTimeline(TimelineType type, unsigned return timeline; } -void BinaryDataParser::_parseVertices(const rapidjson::Value& rawData, VerticesData& vertices) -{ +void BinaryDataParser::_parseVertices(const rapidjson::Value& rawData, VerticesData& vertices) { vertices.offset = rawData[OFFSET].GetUint(); const auto weightOffset = _intArray[vertices.offset + (unsigned)BinaryOffset::MeshWeightOffset]; - if (weightOffset >= 0) - { + if (weightOffset >= 0) { const auto weight = BaseObject::borrowObject(); const auto vertexCount = _intArray[vertices.offset + (unsigned)BinaryOffset::MeshVertexCount]; const auto boneCount = (unsigned)_intArray[weightOffset + (unsigned)BinaryOffset::WeigthBoneCount]; weight->offset = weightOffset; - for (std::size_t i = 0; i < boneCount; ++i) - { + for (std::size_t i = 0; i < boneCount; ++i) { const auto boneIndex = _intArray[weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + i]; weight->addBone(_rawBones[boneIndex]); } auto boneIndicesOffset = weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + boneCount; unsigned weightCount = 0; - for (std::size_t i = 0, l = vertexCount; i < l; ++i) - { + for (std::size_t i = 0, l = vertexCount; i < l; ++i) { const auto vertexBoneCount = (unsigned)_intArray[boneIndicesOffset++]; weightCount += vertexBoneCount; boneIndicesOffset += vertexBoneCount; @@ -87,22 +73,19 @@ void BinaryDataParser::_parseVertices(const rapidjson::Value& rawData, VerticesD } } -void BinaryDataParser::_parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh) -{ +void BinaryDataParser::_parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh) { _parseVertices(rawData, mesh.vertices); } -AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData) -{ - const auto animation = BaseObject::borrowObject(); +AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData) { + const auto animation = BaseObject::borrowObject(); animation->frameCount = std::max(_getNumber(rawData, DURATION, 1), 1); animation->playTimes = _getNumber(rawData, PLAY_TIMES, 1); animation->duration = (float)(animation->frameCount) / _armature->frameRate; // float animation->fadeInTime = _getNumber(rawData, FADE_IN_TIME, 0.0f); animation->scale = _getNumber(rawData, SCALE, 1.0f); animation->name = _getString(rawData, NAME, DEFAULT_NAME); - if (animation->name.empty()) - { + if (animation->name.empty()) { animation->name = DEFAULT_NAME; } @@ -114,30 +97,24 @@ AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData _animation = animation; - if (rawData.HasMember(ACTION)) - { + if (rawData.HasMember(ACTION)) { animation->actionTimeline = _parseBinaryTimeline(TimelineType::Action, rawData[ACTION].GetUint()); } - if (rawData.HasMember(Z_ORDER)) - { + if (rawData.HasMember(Z_ORDER)) { animation->zOrderTimeline = _parseBinaryTimeline(TimelineType::ZOrder, rawData[Z_ORDER].GetUint()); } - if (rawData.HasMember(BONE)) - { + if (rawData.HasMember(BONE)) { const auto& rawTimeliness = rawData[BONE]; - for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) - { + for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) { const auto bone = _armature->getBone(iterator->name.GetString()); - if (bone == nullptr) - { + if (bone == nullptr) { continue; } const auto& rawTimelines = *&(iterator->value); - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) - { + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) { const auto timelineType = (TimelineType)rawTimelines[i].GetInt(); const auto timelineOffset = rawTimelines[i + 1].GetUint(); const auto timeline = _parseBinaryTimeline(timelineType, timelineOffset); @@ -146,20 +123,16 @@ AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData } } - if (rawData.HasMember(SLOT)) - { + if (rawData.HasMember(SLOT)) { const auto& rawTimeliness = rawData[SLOT]; - for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) - { + for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) { const auto slot = _armature->getSlot(iterator->name.GetString()); - if (slot == nullptr) - { + if (slot == nullptr) { continue; } const auto& rawTimelines = *&(iterator->value); - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) - { + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) { const auto timelineType = (TimelineType)rawTimelines[i].GetInt(); const auto timelineOffset = rawTimelines[i + 1].GetUint(); const auto timeline = _parseBinaryTimeline(timelineType, timelineOffset); @@ -168,20 +141,16 @@ AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData } } - if (rawData.HasMember(CONSTRAINT)) - { + if (rawData.HasMember(CONSTRAINT)) { const auto& rawTimeliness = rawData[CONSTRAINT]; - for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) - { + for (auto iterator = rawTimeliness.MemberBegin(); iterator != rawTimeliness.MemberEnd(); ++iterator) { const auto constraint = _armature->getConstraint(iterator->name.GetString()); - if (constraint == nullptr) - { + if (constraint == nullptr) { continue; } const auto& rawTimelines = *&(iterator->value); - for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) - { + for (std::size_t i = 0, l = rawTimelines.Size(); i < l; i += 2) { const auto timelineType = (TimelineType)rawTimelines[i].GetInt(); const auto timelineOffset = rawTimelines[i + 1].GetUint(); const auto timeline = _parseBinaryTimeline(timelineType, timelineOffset); @@ -195,11 +164,10 @@ AnimationData* BinaryDataParser::_parseAnimation(const rapidjson::Value& rawData return animation; } -void BinaryDataParser::_parseArray(const rapidjson::Value& rawData) -{ +void BinaryDataParser::_parseArray(const rapidjson::Value& rawData) { const auto& offsets = rawData[OFFSET]; - _data->binary = _binary; + _data->binary = _binary; _data->intArray = _intArray = (int16_t*)(_binary + _binaryOffset + offsets[0].GetUint()); _data->floatArray = _floatArray = (float*)(_binary + _binaryOffset + offsets[2].GetUint()); _data->frameIntArray = _frameIntArray = (int16_t*)(_binary + _binaryOffset + offsets[4].GetUint()); @@ -208,17 +176,14 @@ void BinaryDataParser::_parseArray(const rapidjson::Value& rawData) _data->timelineArray = _timelineArray = (uint16_t*)(_binary + _binaryOffset + offsets[10].GetUint()); } -DragonBonesData* BinaryDataParser::parseDragonBonesData(const char* rawData, float scale) -{ +DragonBonesData* BinaryDataParser::parseDragonBonesData(const char* rawData, float scale) { DRAGONBONES_ASSERT(rawData != nullptr, ""); if ( rawData[0] != 'D' || rawData[1] != 'B' || rawData[2] != 'D' || - rawData[3] != 'T' - ) - { + rawData[3] != 'T') { DRAGONBONES_ASSERT(false, "Nonsupport data."); return nullptr; } diff --git a/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.h b/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.h index 896196e887..28615e019f 100644 --- a/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.h +++ b/native/cocos/editor-support/dragonbones/parser/BinaryDataParser.h @@ -30,8 +30,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class BinaryDataParser : public JSONDataParser -{ +class BinaryDataParser : public JSONDataParser { DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(BinaryDataParser) private: @@ -53,16 +52,14 @@ protected: virtual void _parseArray(const rapidjson::Value& rawData) override; public: - BinaryDataParser() : - _binaryOffset(0), - _binary(nullptr), - _intArray(nullptr), - _floatArray(nullptr), - _frameIntArray(nullptr), - _frameFloatArray(nullptr), - _frameArray(nullptr), - _timelineArray(nullptr) - {} + BinaryDataParser() : _binaryOffset(0), + _binary(nullptr), + _intArray(nullptr), + _floatArray(nullptr), + _frameIntArray(nullptr), + _frameFloatArray(nullptr), + _frameArray(nullptr), + _timelineArray(nullptr) {} virtual ~BinaryDataParser() {} virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) override; diff --git a/native/cocos/editor-support/dragonbones/parser/DataParser.cpp b/native/cocos/editor-support/dragonbones/parser/DataParser.cpp index a5632ffbed..c4b666375c 100644 --- a/native/cocos/editor-support/dragonbones/parser/DataParser.cpp +++ b/native/cocos/editor-support/dragonbones/parser/DataParser.cpp @@ -10,13 +10,11 @@ const char* DataParser::DATA_VERSION_5_0 = "5.0"; const char* DataParser::DATA_VERSION_5_5 = "5.5"; const char* DataParser::DATA_VERSION = DataParser::DATA_VERSION_5_5; -const std::vector DataParser::DATA_VERSIONS -{ +const std::vector DataParser::DATA_VERSIONS{ DataParser::DATA_VERSION_4_0, DataParser::DATA_VERSION_4_5, DataParser::DATA_VERSION_5_0, - DataParser::DATA_VERSION_5_5 -}; + DataParser::DATA_VERSION_5_5}; const char* DataParser::TEXTURE_ATLAS = "TextureAtlas"; const char* DataParser::SUB_TEXTURE = "SubTexture"; @@ -130,186 +128,120 @@ const char* DataParser::GOTO_AND_PLAY = "gotoAndPlay"; const char* DataParser::DEFAULT_NAME = "default"; -TextureFormat DataParser::_getTextureFormat(const std::string& value) -{ +TextureFormat DataParser::_getTextureFormat(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "rgba8888") - { + if (lower == "rgba8888") { return TextureFormat::RGBA8888; - } - else if (lower == "bgra8888") - { + } else if (lower == "bgra8888") { return TextureFormat::BGRA8888; - } - else if (lower == "rgba4444") - { + } else if (lower == "rgba4444") { return TextureFormat::RGBA4444; - } - else if (lower == "rgb888") - { + } else if (lower == "rgb888") { return TextureFormat::RGB888; - } - else if (lower == "rgb565") - { + } else if (lower == "rgb565") { return TextureFormat::RGB565; - } - else if (lower == "rgba5551") - { + } else if (lower == "rgba5551") { return TextureFormat::RGBA5551; } return TextureFormat::DEFAULT; } -ArmatureType DataParser::_getArmatureType(const std::string& value) -{ +ArmatureType DataParser::_getArmatureType(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "armature") - { + if (lower == "armature") { return ArmatureType::Armature; - } - else if (lower == "movieClip") - { + } else if (lower == "movieClip") { return ArmatureType::MovieClip; - } - else if (lower == "stage") - { + } else if (lower == "stage") { return ArmatureType::Stage; } return ArmatureType::Armature; } -DisplayType DataParser::_getDisplayType(const std::string& value) -{ +DisplayType DataParser::_getDisplayType(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "image") - { + if (lower == "image") { return DisplayType::Image; - } - else if (lower == "armature") - { + } else if (lower == "armature") { return DisplayType::Armature; - } - else if (lower == "mesh") - { + } else if (lower == "mesh") { return DisplayType::Mesh; - } - else if (lower == "boundingbox") - { + } else if (lower == "boundingbox") { return DisplayType::BoundingBox; } return DisplayType::Image; } -BoundingBoxType DataParser::_getBoundingBoxType(const std::string & value) -{ +BoundingBoxType DataParser::_getBoundingBoxType(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "rectangle") - { + if (lower == "rectangle") { return BoundingBoxType::Rectangle; - } - else if (lower == "ellipse") - { + } else if (lower == "ellipse") { return BoundingBoxType::Ellipse; - } - else if (lower == "polygon") - { + } else if (lower == "polygon") { return BoundingBoxType::Polygon; } return BoundingBoxType::Rectangle; } -ActionType DataParser::_getActionType(const std::string& value) -{ +ActionType DataParser::_getActionType(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "play") - { + if (lower == "play") { return ActionType::Play; - } - else if (lower == "frame") - { + } else if (lower == "frame") { return ActionType::Frame; - } - else if (lower == "sound") - { + } else if (lower == "sound") { return ActionType::Sound; } return ActionType::Play; } -BlendMode DataParser::_getBlendMode(const std::string& value) -{ +BlendMode DataParser::_getBlendMode(const std::string& value) { auto lower = value; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "normal") - { + if (lower == "normal") { return BlendMode::Normal; - } - else if (lower == "add") - { + } else if (lower == "add") { return BlendMode::Add; - } - else if (lower == "alpha") - { + } else if (lower == "alpha") { return BlendMode::Alpha; - } - else if (lower == "darken") - { + } else if (lower == "darken") { return BlendMode::Darken; - } - else if (lower == "difference") - { + } else if (lower == "difference") { return BlendMode::Difference; - } - else if (lower == "erase") - { + } else if (lower == "erase") { return BlendMode::Erase; - } - else if (lower == "hardlight") - { + } else if (lower == "hardlight") { return BlendMode::HardLight; - } - else if (lower == "invert") - { + } else if (lower == "invert") { return BlendMode::Invert; - } - else if (lower == "layer") - { + } else if (lower == "layer") { return BlendMode::Layer; - } - else if (lower == "lighten") - { + } else if (lower == "lighten") { return BlendMode::Lighten; - } - else if (lower == "multiply") - { + } else if (lower == "multiply") { return BlendMode::Multiply; - } - else if (lower == "overlay") - { + } else if (lower == "overlay") { return BlendMode::Overlay; - } - else if (lower == "screen") - { + } else if (lower == "screen") { return BlendMode::Screen; - } - else if (lower == "subtract") - { + } else if (lower == "subtract") { return BlendMode::Subtract; } diff --git a/native/cocos/editor-support/dragonbones/parser/DataParser.h b/native/cocos/editor-support/dragonbones/parser/DataParser.h index de97eeb1e3..ad437df6b5 100644 --- a/native/cocos/editor-support/dragonbones/parser/DataParser.h +++ b/native/cocos/editor-support/dragonbones/parser/DataParser.h @@ -39,8 +39,7 @@ DRAGONBONES_NAMESPACE_BEGIN /** * @internal */ -class DataParser -{ +class DataParser { ABSTRACT_CLASS(DataParser) protected: diff --git a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp index 03714c72e8..822d6991ac 100644 --- a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp +++ b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.cpp @@ -5,15 +5,15 @@ DRAGONBONES_NAMESPACE_BEGIN void JSONDataParser::_getCurvePoint( float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, - float t, + float t, Point &result) { - const auto l_t = 1.0f - t; + const auto l_t = 1.0f - t; const auto powA = l_t * l_t; const auto powB = t * t; - const auto kA = l_t * powA; - const auto kB = 3.0f * t * powA; - const auto kC = 3.0f * l_t * powB; - const auto kD = t * powB; + const auto kA = l_t * powA; + const auto kB = 3.0f * t * powA; + const auto kC = 3.0f * l_t * powB; + const auto kD = t * powB; result.x = kA * x1 + kB * x2 + kC * x3 + kD * x4; result.y = kA * y1 + kB * y2 + kC * y3 + kD * y4; @@ -21,7 +21,7 @@ void JSONDataParser::_getCurvePoint( void JSONDataParser::_samplingEasingCurve(const rapidjson::Value &curve, std::vector &samples) { int curveCount = curve.Size(); - int stepIndex = -2; + int stepIndex = -2; for (std::size_t i = 0, l = samples.size(); i < l; ++i) { float t = (float)(i + 1) / (l + 1); // float while ((stepIndex + 6 < curveCount ? curve[stepIndex + 6].GetDouble() : 1) < t) // stepIndex + 3 * 2 @@ -30,16 +30,16 @@ void JSONDataParser::_samplingEasingCurve(const rapidjson::Value &curve, std::ve } const auto isInCurve = stepIndex >= 0 && stepIndex + 6 < curveCount; - const auto x1 = isInCurve ? curve[stepIndex].GetDouble() : 0.0f; - const auto y1 = isInCurve ? curve[stepIndex + 1].GetDouble() : 0.0f; - const auto x2 = curve[stepIndex + 2].GetDouble(); - const auto y2 = curve[stepIndex + 3].GetDouble(); - const auto x3 = curve[stepIndex + 4].GetDouble(); - const auto y3 = curve[stepIndex + 5].GetDouble(); - const auto x4 = isInCurve ? curve[stepIndex + 6].GetDouble() : 1.0f; - const auto y4 = isInCurve ? curve[stepIndex + 7].GetDouble() : 1.0f; + const auto x1 = isInCurve ? curve[stepIndex].GetDouble() : 0.0f; + const auto y1 = isInCurve ? curve[stepIndex + 1].GetDouble() : 0.0f; + const auto x2 = curve[stepIndex + 2].GetDouble(); + const auto y2 = curve[stepIndex + 3].GetDouble(); + const auto x3 = curve[stepIndex + 4].GetDouble(); + const auto y3 = curve[stepIndex + 5].GetDouble(); + const auto x4 = isInCurve ? curve[stepIndex + 6].GetDouble() : 1.0f; + const auto y4 = isInCurve ? curve[stepIndex + 7].GetDouble() : 1.0f; - float lower = 0.0f; + float lower = 0.0f; float higher = 1.0f; while (higher - lower > 0.0001f) { const auto percentage = (higher + lower) * 0.5f; @@ -78,9 +78,9 @@ void JSONDataParser::_parseActionDataInFrame(const rapidjson::Value &rawData, un } void JSONDataParser::_mergeActionFrame(const rapidjson::Value &rawData, unsigned frameStart, ActionType type, BoneData *bone, SlotData *slot) { - const auto actionOffset = _armature->actions.size(); - const auto & actions = _parseActionData(rawData, type, bone, slot); - ActionFrame *frame = nullptr; + const auto actionOffset = _armature->actions.size(); + const auto &actions = _parseActionData(rawData, type, bone, slot); + ActionFrame *frame = nullptr; for (const auto action : actions) { _armature->addAction(action, false); @@ -104,7 +104,7 @@ void JSONDataParser::_mergeActionFrame(const rapidjson::Value &rawData, unsigned { const auto frameCount = _actionFrames.size(); _actionFrames.resize(frameCount + 1); - frame = &_actionFrames[frameCount]; + frame = &_actionFrames[frameCount]; frame->frameStart = frameStart; } @@ -118,7 +118,7 @@ unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame &frame) { const auto frameOffset = _frameArray.size(); const auto actionCount = frame.actions.size(); _frameArray.resize(_frameArray.size() + 1 + 1 + actionCount); - _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frame.frameStart; + _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frame.frameStart; _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count. for (std::size_t i = 0; i < actionCount; ++i) // Action offsets. @@ -131,9 +131,9 @@ unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame &frame) { ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, float scale) { const auto armature = BaseObject::borrowObject(); - armature->name = _getString(rawData, NAME, ""); + armature->name = _getString(rawData, NAME, ""); armature->frameRate = _getNumber(rawData, FRAME_RATE, _data->frameRate); - armature->scale = scale; + armature->scale = scale; if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) { armature->type = _getArmatureType(rawData[TYPE].GetString()); @@ -150,31 +150,31 @@ ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, fl if (rawData.HasMember(CANVAS)) { const auto &rawCanvas = rawData[CANVAS]; - const auto canvas = BaseObject::borrowObject(); + const auto canvas = BaseObject::borrowObject(); canvas->hasBackground = rawCanvas.HasMember(COLOR); - canvas->color = _getNumber(rawCanvas, COLOR, 0); - canvas->aabb.x = _getNumber(rawCanvas, X, 0.0f) * armature->scale; - canvas->aabb.y = _getNumber(rawCanvas, Y, 0.0f) * armature->scale; - canvas->aabb.width = _getNumber(rawCanvas, WIDTH, 0.0f) * armature->scale; - canvas->aabb.height = _getNumber(rawCanvas, HEIGHT, 0.0f) * armature->scale; + canvas->color = _getNumber(rawCanvas, COLOR, 0); + canvas->aabb.x = _getNumber(rawCanvas, X, 0.0f) * armature->scale; + canvas->aabb.y = _getNumber(rawCanvas, Y, 0.0f) * armature->scale; + canvas->aabb.width = _getNumber(rawCanvas, WIDTH, 0.0f) * armature->scale; + canvas->aabb.height = _getNumber(rawCanvas, HEIGHT, 0.0f) * armature->scale; // armature->canvas = canvas; } if (rawData.HasMember(AABB)) { - const auto &rawAABB = rawData[AABB]; - armature->aabb.x = _getNumber(rawAABB, X, 0.0f) * armature->scale; - armature->aabb.y = _getNumber(rawAABB, Y, 0.0f) * armature->scale; - armature->aabb.width = _getNumber(rawAABB, WIDTH, 0.0f) * armature->scale; + const auto &rawAABB = rawData[AABB]; + armature->aabb.x = _getNumber(rawAABB, X, 0.0f) * armature->scale; + armature->aabb.y = _getNumber(rawAABB, Y, 0.0f) * armature->scale; + armature->aabb.width = _getNumber(rawAABB, WIDTH, 0.0f) * armature->scale; armature->aabb.height = _getNumber(rawAABB, HEIGHT, 0.0f) * armature->scale; } if (rawData.HasMember(BONE)) { const auto &rawBones = rawData[BONE]; for (std::size_t i = 0, l = rawBones.Size(); i < l; ++i) { - const auto &rawBone = rawBones[i]; + const auto &rawBone = rawBones[i]; const auto &parentName = _getString(rawBone, PARENT, ""); - const auto bone = _parseBone(rawBone); + const auto bone = _parseBone(rawBone); if (!parentName.empty()) // Get bone parent. { @@ -215,7 +215,7 @@ ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, fl armature->sortBones(); if (rawData.HasMember(SLOT)) { - int zOrder = 0; + int zOrder = 0; const auto &rawSlots = rawData[SLOT]; for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) { armature->addSlot(_parseSlot(rawSlots[i], zOrder++)); @@ -231,8 +231,8 @@ ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, fl for (std::size_t i = 0, l = _cacheRawMeshes.size(); i < l; ++i) // Link mesh. { - const auto rawMeshData = _cacheRawMeshes[i]; - const auto &shareName = _getString(*rawMeshData, SHARE, ""); + const auto rawMeshData = _cacheRawMeshes[i]; + const auto &shareName = _getString(*rawMeshData, SHARE, ""); if (shareName.empty()) { continue; } @@ -297,13 +297,13 @@ ArmatureData *JSONDataParser::_parseArmature(const rapidjson::Value &rawData, fl } BoneData *JSONDataParser::_parseBone(const rapidjson::Value &rawData) { - const auto bone = BaseObject::borrowObject(); + const auto bone = BaseObject::borrowObject(); bone->inheritTranslation = _getBoolean(rawData, INHERIT_TRANSLATION, true); - bone->inheritRotation = _getBoolean(rawData, INHERIT_ROTATION, true); - bone->inheritScale = _getBoolean(rawData, INHERIT_SCALE, true); - bone->inheritReflection = _getBoolean(rawData, INHERIT_REFLECTION, true); - bone->length = _getNumber(rawData, LENGTH, 0.0f) * _armature->scale; - bone->name = _getString(rawData, NAME, ""); + bone->inheritRotation = _getBoolean(rawData, INHERIT_ROTATION, true); + bone->inheritScale = _getBoolean(rawData, INHERIT_SCALE, true); + bone->inheritReflection = _getBoolean(rawData, INHERIT_REFLECTION, true); + bone->length = _getNumber(rawData, LENGTH, 0.0f) * _armature->scale; + bone->name = _getString(rawData, NAME, ""); if (rawData.HasMember(TRANSFORM)) { _parseTransform(rawData[TRANSFORM], bone->transform, _armature->scale); @@ -323,13 +323,13 @@ ConstraintData *JSONDataParser::_parseIKConstraint(const rapidjson::Value &rawDa return nullptr; } - const auto constraint = BaseObject::borrowObject(); + const auto constraint = BaseObject::borrowObject(); constraint->scaleEnabled = _getBoolean(rawData, SCALE, false); constraint->bendPositive = _getBoolean(rawData, BEND_POSITIVE, true); - constraint->weight = _getNumber(rawData, WEIGHT, 1.0f); - constraint->name = _getString(rawData, NAME, ""); - constraint->bone = bone; - constraint->target = target; + constraint->weight = _getNumber(rawData, WEIGHT, 1.0f); + constraint->name = _getString(rawData, NAME, ""); + constraint->bone = bone; + constraint->target = target; const auto chain = _getNumber(rawData, CHAIN, (unsigned)0); if (chain > 0 && bone->parent != nullptr) { @@ -344,11 +344,11 @@ ConstraintData *JSONDataParser::_parseIKConstraint(const rapidjson::Value &rawDa } SlotData *JSONDataParser::_parseSlot(const rapidjson::Value &rawData, int zOrder) { - const auto slot = BaseObject::borrowObject(); + const auto slot = BaseObject::borrowObject(); slot->displayIndex = _getNumber(rawData, DISPLAY_INDEX, (int)0); - slot->zOrder = zOrder; - slot->name = _getString(rawData, NAME, ""); - slot->parent = _armature->getBone(_getString(rawData, PARENT, "")); + slot->zOrder = zOrder; + slot->name = _getString(rawData, NAME, ""); + slot->parent = _armature->getBone(_getString(rawData, PARENT, "")); if (rawData.HasMember(BLEND_MODE) && rawData[BLEND_MODE].IsString()) { slot->blendMode = _getBlendMode(rawData[BLEND_MODE].GetString()); @@ -372,19 +372,19 @@ SlotData *JSONDataParser::_parseSlot(const rapidjson::Value &rawData, int zOrder SkinData *JSONDataParser::_parseSkin(const rapidjson::Value &rawData) { const auto skin = BaseObject::borrowObject(); - skin->name = _getString(rawData, NAME, DEFAULT_NAME); + skin->name = _getString(rawData, NAME, DEFAULT_NAME); if (skin->name.empty()) { skin->name = DEFAULT_NAME; } if (rawData.HasMember(SLOT)) { const auto &rawSlots = rawData[SLOT]; - _skin = skin; + _skin = skin; for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i) { - const auto &rawSlot = rawSlots[i]; + const auto &rawSlot = rawSlots[i]; const auto &slotName = _getString(rawSlot, NAME, ""); - const auto slot = _armature->getSlot(slotName); + const auto slot = _armature->getSlot(slotName); if (slot != nullptr) { _slot = slot; @@ -411,9 +411,9 @@ SkinData *JSONDataParser::_parseSkin(const rapidjson::Value &rawData) { } DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { - const auto & name = _getString(rawData, NAME, ""); - const auto & path = _getString(rawData, PATH, ""); - auto type = DisplayType::Image; + const auto &name = _getString(rawData, NAME, ""); + const auto &path = _getString(rawData, PATH, ""); + auto type = DisplayType::Image; DisplayData *display = nullptr; if (rawData.HasMember(TYPE) && rawData[TYPE].IsString()) { @@ -425,8 +425,8 @@ DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { switch (type) { case dragonBones::DisplayType::Image: { const auto imageDisplay = BaseObject::borrowObject(); - imageDisplay->name = name; - imageDisplay->path = !path.empty() ? path : name; + imageDisplay->name = name; + imageDisplay->path = !path.empty() ? path : name; _parsePivot(rawData, *imageDisplay); display = imageDisplay; @@ -434,9 +434,9 @@ DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { } case dragonBones::DisplayType::Armature: { - const auto armatureDisplay = BaseObject::borrowObject(); - armatureDisplay->name = name; - armatureDisplay->path = !path.empty() ? path : name; + const auto armatureDisplay = BaseObject::borrowObject(); + armatureDisplay->name = name; + armatureDisplay->path = !path.empty() ? path : name; armatureDisplay->inheritAnimation = true; if (rawData.HasMember(ACTIONS)) { @@ -461,11 +461,11 @@ DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { } case dragonBones::DisplayType::Mesh: { - const auto meshDisplay = BaseObject::borrowObject(); + const auto meshDisplay = BaseObject::borrowObject(); meshDisplay->vertices.inheritDeform = _getBoolean(rawData, INHERIT_DEFORM, true); - meshDisplay->name = name; - meshDisplay->path = !path.empty() ? path : name; - meshDisplay->vertices.data = _data; + meshDisplay->name = name; + meshDisplay->path = !path.empty() ? path : name; + meshDisplay->vertices.data = _data; if (rawData.HasMember(SHARE)) { _cacheRawMeshes.push_back(&rawData); @@ -481,9 +481,9 @@ DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { case dragonBones::DisplayType::BoundingBox: { const auto boundingBox = _parseBoundingBox(rawData); if (boundingBox != nullptr) { - const auto boundingBoxDisplay = BaseObject::borrowObject(); - boundingBoxDisplay->name = name; - boundingBoxDisplay->path = !path.empty() ? path : name; + const auto boundingBoxDisplay = BaseObject::borrowObject(); + boundingBoxDisplay->name = name; + boundingBoxDisplay->path = !path.empty() ? path : name; boundingBoxDisplay->boundingBox = boundingBox; display = boundingBoxDisplay; @@ -507,8 +507,8 @@ DisplayData *JSONDataParser::_parseDisplay(const rapidjson::Value &rawData) { void JSONDataParser::_parsePivot(const rapidjson::Value &rawData, ImageDisplayData &display) { if (rawData.HasMember(PIVOT)) { const auto &rawPivot = rawData[PIVOT]; - display.pivot.x = _getNumber(rawPivot, X, 0.0f); - display.pivot.y = _getNumber(rawPivot, Y, 0.0f); + display.pivot.x = _getNumber(rawPivot, X, 0.0f); + display.pivot.y = _getNumber(rawPivot, Y, 0.0f); } else { display.pivot.x = 0.5f; display.pivot.y = 0.5f; @@ -516,21 +516,21 @@ void JSONDataParser::_parsePivot(const rapidjson::Value &rawData, ImageDisplayDa } void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData &mesh) { - const auto &rawVertices = rawData[VERTICES]; - const auto &rawUVs = rawData[UVS]; - const auto &rawTriangles = rawData[TRIANGLES]; - const auto vertexCount = rawVertices.Size() / 2; - const auto triangleCount = rawTriangles.Size() / 3; - const auto vertexOffset = _floatArray.size(); - const auto uvOffset = vertexOffset + vertexCount * 2; - const auto meshOffset = _intArray.size(); - const auto meshName = _skin->name + "_" + _slot->name + "_" + mesh.name; // Cache pose data. + const auto &rawVertices = rawData[VERTICES]; + const auto &rawUVs = rawData[UVS]; + const auto &rawTriangles = rawData[TRIANGLES]; + const auto vertexCount = rawVertices.Size() / 2; + const auto triangleCount = rawTriangles.Size() / 3; + const auto vertexOffset = _floatArray.size(); + const auto uvOffset = vertexOffset + vertexCount * 2; + const auto meshOffset = _intArray.size(); + const auto meshName = _skin->name + "_" + _slot->name + "_" + mesh.name; // Cache pose data. mesh.vertices.offset = meshOffset; _intArray.resize(_intArray.size() + 1 + 1 + 1 + 1 + triangleCount * 3); - _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexCount] = vertexCount; + _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexCount] = vertexCount; _intArray[meshOffset + (unsigned)BinaryOffset::MeshTriangleCount] = triangleCount; - _intArray[meshOffset + (unsigned)BinaryOffset::MeshFloatOffset] = vertexOffset; + _intArray[meshOffset + (unsigned)BinaryOffset::MeshFloatOffset] = vertexOffset; for (std::size_t i = 0, l = triangleCount * 3; i < l; ++i) { _intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexIndices + i] = rawTriangles[i].GetUint(); } @@ -538,22 +538,22 @@ void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData _floatArray.resize(_floatArray.size() + vertexCount * 2 + vertexCount * 2); for (std::size_t i = 0, l = vertexCount * 2; i < l; ++i) { _floatArray[vertexOffset + i] = rawVertices[i].GetDouble(); - _floatArray[uvOffset + i] = rawUVs[i].GetDouble(); + _floatArray[uvOffset + i] = rawUVs[i].GetDouble(); } if (rawData.HasMember(WEIGHTS)) { - const auto & rawWeights = rawData[WEIGHTS]; - const auto & rawSlotPose = rawData[SLOT_POSE]; - const auto & rawBonePoses = rawData[BONE_POSE]; - const auto & sortedBones = _armature->sortedBones; + const auto &rawWeights = rawData[WEIGHTS]; + const auto &rawSlotPose = rawData[SLOT_POSE]; + const auto &rawBonePoses = rawData[BONE_POSE]; + const auto &sortedBones = _armature->sortedBones; std::vector weightBoneIndices; - const unsigned weightBoneCount = rawBonePoses.Size() / 7; - const auto floatOffset = _floatArray.size(); - const auto weightCount = (rawWeights.Size() - vertexCount) / 2; // uint - const auto weightOffset = _intArray.size(); - const auto weight = BaseObject::borrowObject(); + const unsigned weightBoneCount = rawBonePoses.Size() / 7; + const auto floatOffset = _floatArray.size(); + const auto weightCount = (rawWeights.Size() - vertexCount) / 2; // uint + const auto weightOffset = _intArray.size(); + const auto weight = BaseObject::borrowObject(); - weight->count = weightCount; + weight->count = weightCount; weight->offset = weightOffset; weightBoneIndices.resize(weightBoneCount); _intArray.resize(_intArray.size() + 1 + 1 + weightBoneCount + vertexCount + weightCount); @@ -561,18 +561,18 @@ void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData for (std::size_t i = 0; i < weightBoneCount; ++i) { const auto rawBoneIndex = rawBonePoses[i * 7].GetUint(); - const auto bone = _rawBones[rawBoneIndex]; + const auto bone = _rawBones[rawBoneIndex]; weight->addBone(bone); - weightBoneIndices[i] = rawBoneIndex; + weightBoneIndices[i] = rawBoneIndex; _intArray[weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + i] = indexOf(sortedBones, bone); } _floatArray.resize(_floatArray.size() + weightCount * 3); - _helpMatrixA.a = rawSlotPose[0].GetDouble(); - _helpMatrixA.b = rawSlotPose[1].GetDouble(); - _helpMatrixA.c = rawSlotPose[2].GetDouble(); - _helpMatrixA.d = rawSlotPose[3].GetDouble(); + _helpMatrixA.a = rawSlotPose[0].GetDouble(); + _helpMatrixA.b = rawSlotPose[1].GetDouble(); + _helpMatrixA.c = rawSlotPose[2].GetDouble(); + _helpMatrixA.d = rawSlotPose[3].GetDouble(); _helpMatrixA.tx = rawSlotPose[4].GetDouble(); _helpMatrixA.ty = rawSlotPose[5].GetDouble(); @@ -580,9 +580,9 @@ void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData std::size_t i = 0, iW = 0, iB = weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + weightBoneCount, iV = floatOffset; i < vertexCount; ++i) { - const auto iD = i * 2; + const auto iD = i * 2; const auto vertexBoneCount = rawWeights[iW++].GetUint(); - _intArray[iB++] = vertexBoneCount; + _intArray[iB++] = vertexBoneCount; auto x = _floatArray[vertexOffset + iD]; auto y = _floatArray[vertexOffset + iD + 1]; @@ -593,34 +593,34 @@ void JSONDataParser::_parseMesh(const rapidjson::Value &rawData, MeshDisplayData for (std::size_t j = 0; j < vertexBoneCount; ++j) { const auto rawBoneIndex = rawWeights[iW++].GetUint(); - const auto boneIndex = indexOf(weightBoneIndices, rawBoneIndex); + const auto boneIndex = indexOf(weightBoneIndices, rawBoneIndex); const auto matrixOffset = boneIndex * 7 + 1; - _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); - _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); - _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); - _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); + _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); + _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); + _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); + _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); _helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble(); _helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble(); _helpMatrixB.invert(); _helpMatrixB.transformPoint(x, y, _helpPoint); - _intArray[iB++] = boneIndex; + _intArray[iB++] = boneIndex; _floatArray[iV++] = rawWeights[iW++].GetDouble(); _floatArray[iV++] = _helpPoint.x; _floatArray[iV++] = _helpPoint.y; } } - mesh.vertices.weight = weight; - _weightSlotPose[meshName] = &rawSlotPose; + mesh.vertices.weight = weight; + _weightSlotPose[meshName] = &rawSlotPose; _weightBonePoses[meshName] = &rawBonePoses; } } BoundingBoxData *JSONDataParser::_parseBoundingBox(const rapidjson::Value &rawData) { BoundingBoxData *boundingBox = nullptr; - BoundingBoxType type = BoundingBoxType::Rectangle; + BoundingBoxType type = BoundingBoxType::Rectangle; if (rawData.HasMember(SUB_TYPE) && rawData[SUB_TYPE].IsString()) { type = _getBoundingBoxType(rawData[SUB_TYPE].GetString()); } else { @@ -644,7 +644,7 @@ BoundingBoxData *JSONDataParser::_parseBoundingBox(const rapidjson::Value &rawDa if (boundingBox != nullptr) { boundingBox->color = _getNumber(rawData, COLOR, 0x000000); if (boundingBox->type == BoundingBoxType::Rectangle || boundingBox->type == BoundingBoxType::Ellipse) { - boundingBox->width = _getNumber(rawData, WIDTH, 0.0f); + boundingBox->width = _getNumber(rawData, WIDTH, 0.0f); boundingBox->height = _getNumber(rawData, HEIGHT, 0.0f); } } @@ -657,21 +657,21 @@ PolygonBoundingBoxData *JSONDataParser::_parsePolygonBoundingBox(const rapidjson if (rawData.HasMember(VERTICES)) { const auto &rawVertices = rawData[VERTICES]; - auto & vertices = polygonBoundingBox->vertices; + auto &vertices = polygonBoundingBox->vertices; polygonBoundingBox->vertices.resize(rawVertices.Size()); for (std::size_t i = 0, l = rawVertices.Size(); i < l; i += 2) { - const auto x = rawVertices[i].GetDouble(); - const auto y = rawVertices[i + 1].GetDouble(); - vertices[i] = x; + const auto x = rawVertices[i].GetDouble(); + const auto y = rawVertices[i + 1].GetDouble(); + vertices[i] = x; vertices[i + 1] = y; // AABB. if (i == 0) { - polygonBoundingBox->x = x; - polygonBoundingBox->y = y; - polygonBoundingBox->width = x; + polygonBoundingBox->x = x; + polygonBoundingBox->y = y; + polygonBoundingBox->width = x; polygonBoundingBox->height = y; } else { if (x < polygonBoundingBox->x) { @@ -698,27 +698,27 @@ PolygonBoundingBoxData *JSONDataParser::_parsePolygonBoundingBox(const rapidjson } AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) { - const auto animation = BaseObject::borrowObject(); + const auto animation = BaseObject::borrowObject(); animation->frameCount = std::max(_getNumber(rawData, DURATION, (unsigned)1), (unsigned)1); - animation->playTimes = _getNumber(rawData, PLAY_TIMES, (unsigned)1); - animation->duration = (float)animation->frameCount / _armature->frameRate; // float + animation->playTimes = _getNumber(rawData, PLAY_TIMES, (unsigned)1); + animation->duration = (float)animation->frameCount / _armature->frameRate; // float animation->fadeInTime = _getNumber(rawData, FADE_IN_TIME, 0.0f); - animation->scale = _getNumber(rawData, SCALE, 1.0f); - animation->name = _getString(rawData, NAME, DEFAULT_NAME); + animation->scale = _getNumber(rawData, SCALE, 1.0f); + animation->name = _getString(rawData, NAME, DEFAULT_NAME); if (animation->name.empty()) { animation->name = DEFAULT_NAME; } - animation->frameIntOffset = _frameIntArray.size(); + animation->frameIntOffset = _frameIntArray.size(); animation->frameFloatOffset = _frameFloatArray.size(); - animation->frameOffset = _frameArray.size(); + animation->frameOffset = _frameArray.size(); _animation = animation; if (rawData.HasMember(FRAME)) { - const auto &rawFrames = rawData[FRAME]; - const auto keyFrameCount = rawFrames.Size(); + const auto &rawFrames = rawData[FRAME]; + const auto keyFrameCount = rawFrames.Size(); if (keyFrameCount > 0) { for (std::size_t i = 0, frameStart = 0; i < keyFrameCount; ++i) { const auto &rawFrame = rawFrames[i]; @@ -753,8 +753,8 @@ AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) const auto &rawTimelines = rawData[FFD]; for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { const auto &rawTimeline = rawTimelines[i]; - auto skinName = _getString(rawTimeline, SKIN, DEFAULT_NAME); - const auto &slotName = _getString(rawTimeline, SLOT, ""); + auto skinName = _getString(rawTimeline, SKIN, DEFAULT_NAME); + const auto &slotName = _getString(rawTimeline, SLOT, ""); const auto &displayName = _getString(rawTimeline, NAME, ""); if (skinName.empty()) // @@ -784,9 +784,9 @@ AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) if (rawData.HasMember(IK)) { const auto &rawTimelines = rawData[IK]; for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i) { - const auto &rawTimeline = rawTimelines[i]; + const auto &rawTimeline = rawTimelines[i]; const auto &constraintName = _getString(rawTimeline, NAME, ""); - const auto constraint = _armature->getConstraint(constraintName); + const auto constraint = _armature->getConstraint(constraintName); if (constraint == nullptr) { continue; } @@ -806,24 +806,24 @@ AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) std::sort(_actionFrames.begin(), _actionFrames.end()); const auto timeline = _animation->actionTimeline = BaseObject::borrowObject(); - const auto keyFrameCount = _actionFrames.size(); - timeline->type = TimelineType::Action; - timeline->offset = _timelineArray.size(); + const auto keyFrameCount = _actionFrames.size(); + timeline->type = TimelineType::Action; + timeline->offset = _timelineArray.size(); _timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount); - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = 100; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = 0; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = 0; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = 100; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = 0; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = 0; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = 0; _timeline = timeline; if (keyFrameCount == 1) { - timeline->frameIndicesOffset = -1; + timeline->frameIndicesOffset = -1; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = _parseCacheActionFrame(_actionFrames[0]) - _animation->frameOffset; } else { - const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. - auto & frameIndices = _data->frameIndices; + const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. + auto &frameIndices = _data->frameIndices; timeline->frameIndicesOffset = frameIndices.size(); frameIndices.resize(frameIndices.size() + totalFrameCount); @@ -833,7 +833,7 @@ AnimationData *JSONDataParser::_parseAnimation(const rapidjson::Value &rawData) ++i) { if (frameStart + frameCount <= i && iK < keyFrameCount) { auto &frame = _actionFrames[iK]; - frameStart = frame.frameStart; + frameStart = frame.frameStart; if (iK == keyFrameCount - 1) { frameCount = _animation->frameCount - frameStart; } else { @@ -865,19 +865,19 @@ TimelineData *JSONDataParser::_parseTimeline( return nullptr; } - const auto &rawFrames = rawData[framesKey]; - const auto keyFrameCount = rawFrames.Size(); + const auto &rawFrames = rawData[framesKey]; + const auto keyFrameCount = rawFrames.Size(); if (keyFrameCount == 0) { return nullptr; } const auto timeline = BaseObject::borrowObject(); - timeline->type = type; - timeline->offset = _timelineArray.size(); + timeline->type = type; + timeline->offset = _timelineArray.size(); _timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount); - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = _getNumber(rawData, SCALE, 1.0f) * 100.f; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = _getNumber(rawData, OFFSET, 0.0f) * 100.f; - _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = _getNumber(rawData, SCALE, 1.0f) * 100.f; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = _getNumber(rawData, OFFSET, 0.0f) * 100.f; + _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameValueCount; if (addIntOffset) { _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = _frameIntArray.size() - _animation->frameIntOffset; @@ -891,13 +891,13 @@ TimelineData *JSONDataParser::_parseTimeline( if (keyFrameCount == 1) // Only one frame. { - timeline->frameIndicesOffset = -1; + timeline->frameIndicesOffset = -1; _timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = frameParser(rawFrames[0], 0, 0) - _animation->frameOffset; } else { - unsigned frameIndicesOffset = 0; - auto & frameIndices = _data->frameIndices; - const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. - frameIndicesOffset = frameIndices.size(); + unsigned frameIndicesOffset = 0; + auto &frameIndices = _data->frameIndices; + const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation. + frameIndicesOffset = frameIndices.size(); frameIndices.resize(frameIndicesOffset + totalFrameCount); timeline->frameIndicesOffset = frameIndicesOffset; @@ -907,8 +907,8 @@ TimelineData *JSONDataParser::_parseTimeline( ++i) { if (frameStart + frameCount <= i && iK < keyFrameCount) { const auto &rawFrame = rawFrames[iK]; - frameStart = i; - frameCount = _getNumber(rawFrame, DURATION, (unsigned)1); + frameStart = i; + frameCount = _getNumber(rawFrame, DURATION, (unsigned)1); if (iK == keyFrameCount - 1) { frameCount = _animation->frameCount - frameStart; } @@ -986,8 +986,8 @@ void JSONDataParser::_parseSlotTimeline(const rapidjson::Value &rawData) { } TimelineData *displayTimeline = nullptr; - TimelineData *colorTimeline = nullptr; - _slot = slot; + TimelineData *colorTimeline = nullptr; + _slot = slot; if (rawData.HasMember(DISPLAY_FRAME)) { displayTimeline = _parseTimeline( @@ -1041,14 +1041,14 @@ unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value &rawData, unsig _helpArray.resize(sampleCount); _samplingEasingCurve(rawData[CURVE], _helpArray); _frameArray.resize(_frameArray.size() + 1 + 1 + _helpArray.size()); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int)TweenType::Curve; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int)TweenType::Curve; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = sampleCount; for (std::size_t i = 0; i < sampleCount; ++i) { _frameArray[frameOffset + (unsigned)BinaryOffset::FrameCurveSamples + i] = _helpArray[i] * 10000.0f; } } else { - const auto noTween = -2.0f; - auto tweenEasing = noTween; + const auto noTween = -2.0f; + auto tweenEasing = noTween; if (rawData.HasMember(TWEEN_EASING)) { tweenEasing = _getNumber(rawData, TWEEN_EASING, noTween); } @@ -1061,15 +1061,15 @@ unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value &rawData, unsig _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::Line; } else if (tweenEasing < 0.0f) { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadIn; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadIn; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = -tweenEasing * 100.0f; } else if (tweenEasing <= 1.0f) { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadOut; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadOut; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f; } else { _frameArray.resize(_frameArray.size() + 1 + 1); - _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadInOut; + _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadInOut; _frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f - 100.0f; } } @@ -1085,7 +1085,7 @@ unsigned JSONDataParser::_parseActionFrame(const ActionFrame &frame, unsigned fr const auto frameOffset = _frameArray.size(); const auto actionCount = frame.actions.size(); _frameArray.resize(_frameArray.size() + 1 + 1 + actionCount); - _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart; + _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart; _frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count. for (std::size_t i = 0; i < actionCount; ++i) // Action offsets. @@ -1102,7 +1102,7 @@ unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value &rawData, unsi if (rawData.HasMember(Z_ORDER)) { const auto &rawZOrder = rawData[Z_ORDER]; if (!rawZOrder.Empty()) { - const auto slotCount = _armature->sortedSlots.size(); + const auto slotCount = _armature->sortedSlots.size(); std::vector unchanged; std::vector zOrders; unchanged.resize(slotCount - rawZOrder.Size() / 2); @@ -1116,10 +1116,10 @@ unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value &rawData, unsi zOrders[i] = -1; } - unsigned originalIndex = 0; + unsigned originalIndex = 0; unsigned unchangedIndex = 0; for (std::size_t i = 0, l = rawZOrder.Size(); i < l; i += 2) { - const auto slotIndex = rawZOrder[i].GetInt(); + const auto slotIndex = rawZOrder[i].GetInt(); const auto zOrderOffset = rawZOrder[i + 1].GetInt(); while (originalIndex != (unsigned)slotIndex) { unchanged[unchangedIndex++] = originalIndex++; @@ -1188,10 +1188,10 @@ unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value &rawData, uns } _prevClockwise = _getNumber(rawData, TWEEN_ROTATE, 0.0f); - _prevRotation = rotation; + _prevRotation = rotation; // - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 6); _frameFloatArray[frameFloatOffset++] = _helpTransform.x; _frameFloatArray[frameFloatOffset++] = _helpTransform.y; @@ -1205,8 +1205,8 @@ unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value &rawData, uns } unsigned JSONDataParser::_parseBoneTranslateFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 2); _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, X, 0.0f); _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, Y, 0.0f); @@ -1230,10 +1230,10 @@ unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value &rawData, } _prevClockwise = _getNumber(rawData, CLOCK_WISE, 0.0f); - _prevRotation = rotation; + _prevRotation = rotation; // - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto frameFloatOffset = _frameFloatArray.size(); + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + auto frameFloatOffset = _frameFloatArray.size(); _frameFloatArray.resize(_frameFloatArray.size() + 2); _frameFloatArray[frameFloatOffset++] = rotation; _frameFloatArray[frameFloatOffset++] = _getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD; @@ -1270,7 +1270,7 @@ unsigned JSONDataParser::_parseSlotDisplayFrame(const rapidjson::Value &rawData, unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - auto colorOffset = -1; + auto colorOffset = -1; if (rawData.HasMember(VALUE) || rawData.HasMember(COLOR)) { const auto &rawColor = rawData.HasMember(VALUE) ? rawData[VALUE] : rawData[COLOR]; @@ -1324,23 +1324,23 @@ unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value &rawData, u unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, unsigned frameStart, unsigned frameCount) { const auto frameFloatOffset = _frameFloatArray.size(); - const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); - const auto offset = _getNumber(rawData, OFFSET, (unsigned)0); - const auto vertexCount = (unsigned)_intArray[_mesh->vertices.offset + (unsigned)BinaryOffset::MeshVertexCount]; - const auto meshName = _mesh->parent->name + "_" + _slot->name + "_" + _mesh->name; - const auto weight = _mesh->vertices.weight; + const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount); + const auto offset = _getNumber(rawData, OFFSET, (unsigned)0); + const auto vertexCount = (unsigned)_intArray[_mesh->vertices.offset + (unsigned)BinaryOffset::MeshVertexCount]; + const auto meshName = _mesh->parent->name + "_" + _slot->name + "_" + _mesh->name; + const auto weight = _mesh->vertices.weight; - auto x = 0.0f; - auto y = 0.0f; + auto x = 0.0f; + auto y = 0.0f; unsigned iB = 0; unsigned iV = 0; if (weight != nullptr) { const auto &rawSlotPose = *(_weightSlotPose[meshName]); - _helpMatrixA.a = rawSlotPose[0].GetDouble(); - _helpMatrixA.b = rawSlotPose[1].GetDouble(); - _helpMatrixA.c = rawSlotPose[2].GetDouble(); - _helpMatrixA.d = rawSlotPose[3].GetDouble(); + _helpMatrixA.a = rawSlotPose[0].GetDouble(); + _helpMatrixA.b = rawSlotPose[1].GetDouble(); + _helpMatrixA.c = rawSlotPose[2].GetDouble(); + _helpMatrixA.d = rawSlotPose[3].GetDouble(); _helpMatrixA.tx = rawSlotPose[4].GetDouble(); _helpMatrixA.ty = rawSlotPose[5].GetDouble(); @@ -1374,7 +1374,7 @@ unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, uns if (weight != nullptr) // If mesh is skinned, transform point by bone bind pose. { - const auto & rawBonePoses = *(_weightBonePoses[meshName]); + const auto &rawBonePoses = *(_weightBonePoses[meshName]); const unsigned vertexBoneCount = _intArray[iB++]; _helpMatrixA.transformPoint(x, y, _helpPoint, true); @@ -1382,13 +1382,13 @@ unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, uns y = _helpPoint.y; for (std::size_t j = 0; j < vertexBoneCount; ++j) { - const auto boneIndex = _intArray[iB++]; + const auto boneIndex = _intArray[iB++]; const auto matrixOffset = boneIndex * 7 + 1; - _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); - _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); - _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); - _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); + _helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble(); + _helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble(); + _helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble(); + _helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble(); _helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble(); _helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble(); _helpMatrixB.invert(); @@ -1398,7 +1398,7 @@ unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, uns _frameFloatArray[frameFloatOffset + iV++] = _helpPoint.y; } } else { - _frameFloatArray[frameFloatOffset + i] = x; + _frameFloatArray[frameFloatOffset + i] = x; _frameFloatArray[frameFloatOffset + i + 1] = y; } } @@ -1406,11 +1406,11 @@ unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value &rawData, uns if (frameStart == 0) { const auto frameIntOffset = _frameIntArray.size(); _frameIntArray.resize(_frameIntArray.size() + 1 + 1 + 1 + 1 + 1); - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset] = _mesh->vertices.offset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount] = _frameFloatArray.size() - frameFloatOffset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount] = _frameFloatArray.size() - frameFloatOffset; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset] = 0; - _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] = frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset] = _mesh->vertices.offset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount] = _frameFloatArray.size() - frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount] = _frameFloatArray.size() - frameFloatOffset; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset] = 0; + _frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] = frameFloatOffset; _timelineArray[_timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameIntOffset - _animation->frameIntOffset; } @@ -1434,15 +1434,15 @@ const std::vector &JSONDataParser::_parseActionData(const rapidjso if (rawData.IsString()) { const auto action = BaseObject::borrowObject(); - action->type = type; - action->name = rawData.GetString(); - action->bone = bone; - action->slot = slot; + action->type = type; + action->name = rawData.GetString(); + action->bone = bone; + action->slot = slot; actions.push_back(action); } else if (rawData.IsArray()) { for (std::size_t iA = 0, lA = rawData.Size(); iA < lA; ++iA) { const auto &rawAction = rawData[iA]; - const auto action = BaseObject::borrowObject(); + const auto action = BaseObject::borrowObject(); if (rawAction.HasMember(GOTO_AND_PLAY)) { action->type = ActionType::Play; @@ -1459,14 +1459,14 @@ const std::vector &JSONDataParser::_parseActionData(const rapidjso if (rawAction.HasMember(BONE)) { const auto &boneName = _getString(rawAction, BONE, ""); - action->bone = _armature->getBone(boneName); + action->bone = _armature->getBone(boneName); } else { action->bone = bone; } if (rawAction.HasMember(SLOT)) { const auto &slotName = _getString(rawAction, SLOT, ""); - action->slot = _armature->getSlot(slotName); + action->slot = _armature->getSlot(slotName); } else { action->slot = slot; } @@ -1517,10 +1517,10 @@ void JSONDataParser::_parseTransform(const rapidjson::Value &rawData, Transform if (rawData.HasMember(ROTATE) || rawData.HasMember(SKEW)) { transform.rotation = Transform::normalizeRadian(_getNumber(rawData, ROTATE, 0.0f) * Transform::DEG_RAD); - transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD); + transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD); } else if (rawData.HasMember(SKEW_X) || rawData.HasMember(SKEW_Y)) { transform.rotation = Transform::normalizeRadian(_getNumber(rawData, SKEW_Y, 0.0f) * Transform::DEG_RAD); - transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW_X, 0.0f) * Transform::DEG_RAD) - transform.rotation; + transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW_X, 0.0f) * Transform::DEG_RAD) - transform.rotation; } transform.scaleX = _getNumber(rawData, SCALE_X, 1.0f); @@ -1529,13 +1529,13 @@ void JSONDataParser::_parseTransform(const rapidjson::Value &rawData, Transform void JSONDataParser::_parseColorTransform(const rapidjson::Value &rawData, ColorTransform &color) { color.alphaMultiplier = _getNumber(rawData, ALPHA_MULTIPLIER, (int)100) * 0.01f; - color.redMultiplier = _getNumber(rawData, RED_MULTIPLIER, (int)100) * 0.01f; + color.redMultiplier = _getNumber(rawData, RED_MULTIPLIER, (int)100) * 0.01f; color.greenMultiplier = _getNumber(rawData, GREEN_MULTIPLIER, (int)100) * 0.01f; - color.blueMultiplier = _getNumber(rawData, BLUE_MULTIPLIER, (int)100) * 0.01f; - color.alphaOffset = _getNumber(rawData, ALPHA_OFFSET, (int)0); - color.redOffset = _getNumber(rawData, RED_OFFSET, (int)0); - color.greenOffset = _getNumber(rawData, GREEN_OFFSET, (int)0); - color.blueOffset = _getNumber(rawData, BLUE_OFFSET, (int)0); + color.blueMultiplier = _getNumber(rawData, BLUE_MULTIPLIER, (int)100) * 0.01f; + color.alphaOffset = _getNumber(rawData, ALPHA_OFFSET, (int)0); + color.redOffset = _getNumber(rawData, RED_OFFSET, (int)0); + color.greenOffset = _getNumber(rawData, GREEN_OFFSET, (int)0); + color.blueOffset = _getNumber(rawData, BLUE_OFFSET, (int)0); } void JSONDataParser::_parseArray(const rapidjson::Value &rawData) { @@ -1548,15 +1548,15 @@ void JSONDataParser::_parseArray(const rapidjson::Value &rawData) { } DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &rawData, float scale) { - const auto &version = _getString(rawData, VERSION, ""); + const auto &version = _getString(rawData, VERSION, ""); const auto &compatibleVersion = _getString(rawData, COMPATIBLE_VERSION, ""); if ( indexOf(DATA_VERSIONS, version) >= 0 || indexOf(DATA_VERSIONS, compatibleVersion) >= 0) { const auto data = BaseObject::borrowObject(); - data->version = version; - data->name = _getString(rawData, NAME, ""); + data->version = version; + data->name = _getString(rawData, NAME, ""); data->frameRate = _getNumber(rawData, FRAME_RATE, 24); if (data->frameRate == 0) // Data error. @@ -1598,13 +1598,13 @@ DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &r const auto l5 = _frameArray.size() * 2; const auto l6 = _timelineArray.size() * 2; - auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6]; - auto intArray = (int16_t *)binary; - auto floatArray = (float *)(binary + l1); - auto frameIntArray = (int16_t *)(binary + l1 + l2); + auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6]; + auto intArray = (int16_t *)binary; + auto floatArray = (float *)(binary + l1); + auto frameIntArray = (int16_t *)(binary + l1 + l2); auto frameFloatArray = (float *)(binary + l1 + l2 + l3); - auto frameArray = (int16_t *)(binary + l1 + l2 + l3 + l4); - auto timelineArray = (uint16_t *)(binary + l1 + l2 + l3 + l4 + l5); + auto frameArray = (int16_t *)(binary + l1 + l2 + l3 + l4); + auto timelineArray = (uint16_t *)(binary + l1 + l2 + l3 + l4 + l5); for (std::size_t i = 0, l = _intArray.size(); i < l; ++i) { intArray[i] = _intArray[i]; @@ -1630,17 +1630,17 @@ DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &r timelineArray[i] = _timelineArray[i]; } - data->binary = binary; - data->intArray = intArray; - data->floatArray = floatArray; - data->frameIntArray = frameIntArray; + data->binary = binary; + data->intArray = intArray; + data->floatArray = floatArray; + data->frameIntArray = frameIntArray; data->frameFloatArray = frameFloatArray; - data->frameArray = frameArray; - data->timelineArray = timelineArray; + data->frameArray = frameArray; + data->timelineArray = timelineArray; } _defaultColorOffset = -1; - _data = nullptr; + _data = nullptr; } if (rawData.HasMember(TEXTURE_ATLAS)) { @@ -1660,32 +1660,32 @@ DragonBonesData *JSONDataParser::_parseDragonBonesData(const rapidjson::Value &r } void JSONDataParser::_parseTextureAtlasData(const rapidjson::Value &rawData, TextureAtlasData &textureAtlasData, float scale) { - textureAtlasData.format = _getTextureFormat(_getString(rawData, FORMAT, "")); - textureAtlasData.width = _getNumber(rawData, WIDTH, (unsigned)0); - textureAtlasData.height = _getNumber(rawData, HEIGHT, (unsigned)0); - textureAtlasData.scale = scale == 1.0f ? 1.0f / _getNumber(rawData, SCALE, 1.0f) : scale; - textureAtlasData.name = _getString(rawData, NAME, ""); + textureAtlasData.format = _getTextureFormat(_getString(rawData, FORMAT, "")); + textureAtlasData.width = _getNumber(rawData, WIDTH, (unsigned)0); + textureAtlasData.height = _getNumber(rawData, HEIGHT, (unsigned)0); + textureAtlasData.scale = scale == 1.0f ? 1.0f / _getNumber(rawData, SCALE, 1.0f) : scale; + textureAtlasData.name = _getString(rawData, NAME, ""); textureAtlasData.imagePath = _getString(rawData, IMAGE_PATH, ""); if (rawData.HasMember(SUB_TEXTURE)) { const auto &rawTextures = rawData[SUB_TEXTURE]; for (std::size_t i = 0, l = rawTextures.Size(); i < l; ++i) { - const auto &rawTexture = rawTextures[i]; - const auto textureData = textureAtlasData.createTexture(); - textureData->rotated = _getBoolean(rawTexture, ROTATED, false); - textureData->name = _getString(rawTexture, NAME, ""); - textureData->region.x = _getNumber(rawTexture, X, 0.0f); - textureData->region.y = _getNumber(rawTexture, Y, 0.0f); - textureData->region.width = _getNumber(rawTexture, WIDTH, 0.0f); + const auto &rawTexture = rawTextures[i]; + const auto textureData = textureAtlasData.createTexture(); + textureData->rotated = _getBoolean(rawTexture, ROTATED, false); + textureData->name = _getString(rawTexture, NAME, ""); + textureData->region.x = _getNumber(rawTexture, X, 0.0f); + textureData->region.y = _getNumber(rawTexture, Y, 0.0f); + textureData->region.width = _getNumber(rawTexture, WIDTH, 0.0f); textureData->region.height = _getNumber(rawTexture, HEIGHT, 0.0f); - const auto frameWidth = _getNumber(rawTexture, FRAME_WIDTH, -1.0f); + const auto frameWidth = _getNumber(rawTexture, FRAME_WIDTH, -1.0f); const auto frameHeight = _getNumber(rawTexture, FRAME_HEIGHT, -1.0f); if (frameWidth > 0.0f && frameHeight > 0.0f) { - textureData->frame = TextureData::createRectangle(); - textureData->frame->x = _getNumber(rawTexture, FRAME_X, 0.0f); - textureData->frame->y = _getNumber(rawTexture, FRAME_Y, 0.0f); - textureData->frame->width = frameWidth; + textureData->frame = TextureData::createRectangle(); + textureData->frame->x = _getNumber(rawTexture, FRAME_X, 0.0f); + textureData->frame->y = _getNumber(rawTexture, FRAME_Y, 0.0f); + textureData->frame->width = frameWidth; textureData->frame->height = frameHeight; } @@ -1713,7 +1713,7 @@ bool JSONDataParser::parseTextureAtlasData(const char *rawData, TextureAtlasData _parseTextureAtlasData(rawTextureAtlas, textureAtlasData, scale); if (_rawTextureAtlasIndex >= _rawTextureAtlases->Size()) { _rawTextureAtlasIndex = 0; - _rawTextureAtlases = nullptr; + _rawTextureAtlases = nullptr; } return true; diff --git a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h index f8b04edc59..b1339c83af 100644 --- a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h +++ b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h @@ -8,7 +8,7 @@ DRAGONBONES_NAMESPACE_BEGIN class ActionFrame { public: - unsigned frameStart; + unsigned frameStart; std::vector actions; bool operator<(const ActionFrame& b) const { @@ -107,40 +107,40 @@ protected: } protected: - unsigned _rawTextureAtlasIndex; + unsigned _rawTextureAtlasIndex; std::vector _rawBones; - DragonBonesData* _data; - ArmatureData* _armature; - BoneData* _bone; - SlotData* _slot; - SkinData* _skin; - MeshDisplayData* _mesh; - AnimationData* _animation; - TimelineData* _timeline; - rapidjson::Value* _rawTextureAtlases; + DragonBonesData* _data; + ArmatureData* _armature; + BoneData* _bone; + SlotData* _slot; + SkinData* _skin; + MeshDisplayData* _mesh; + AnimationData* _animation; + TimelineData* _timeline; + rapidjson::Value* _rawTextureAtlases; private: - int _defaultColorOffset; - int _prevClockwise; - float _prevRotation; - Matrix _helpMatrixA; - Matrix _helpMatrixB; - Transform _helpTransform; - ColorTransform _helpColorTransform; - Point _helpPoint; - std::vector _helpArray; - std::vector _intArray; - std::vector _floatArray; - std::vector _frameIntArray; - std::vector _frameFloatArray; - std::vector _frameArray; - std::vector _timelineArray; - std::vector _cacheRawMeshes; - std::vector _cacheMeshes; - std::vector _actionFrames; - std::map _weightSlotPose; - std::map _weightBonePoses; - std::map> _cacheBones; + int _defaultColorOffset; + int _prevClockwise; + float _prevRotation; + Matrix _helpMatrixA; + Matrix _helpMatrixB; + Transform _helpTransform; + ColorTransform _helpColorTransform; + Point _helpPoint; + std::vector _helpArray; + std::vector _intArray; + std::vector _floatArray; + std::vector _frameIntArray; + std::vector _frameFloatArray; + std::vector _frameArray; + std::vector _timelineArray; + std::vector _cacheRawMeshes; + std::vector _cacheMeshes; + std::vector _actionFrames; + std::map _weightSlotPose; + std::map _weightBonePoses; + std::map> _cacheBones; std::map> _slotChildActions; public: @@ -185,53 +185,53 @@ public: private: void _getCurvePoint( float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, - float t, + float t, Point& result); - void _samplingEasingCurve(const rapidjson::Value& curve, std::vector& samples); - void _parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot); - void _mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot); + void _samplingEasingCurve(const rapidjson::Value& curve, std::vector& samples); + void _parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot); + void _mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot); unsigned _parseCacheActionFrame(ActionFrame& frame); protected: - virtual ArmatureData* _parseArmature(const rapidjson::Value& rawData, float scale); - virtual BoneData* _parseBone(const rapidjson::Value& rawData); - virtual ConstraintData* _parseIKConstraint(const rapidjson::Value& rawData); - virtual SlotData* _parseSlot(const rapidjson::Value& rawData, int zOrder); - virtual SkinData* _parseSkin(const rapidjson::Value& rawData); - virtual DisplayData* _parseDisplay(const rapidjson::Value& rawData); - virtual void _parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display); - virtual void _parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh); - virtual BoundingBoxData* _parseBoundingBox(const rapidjson::Value& rawData); + virtual ArmatureData* _parseArmature(const rapidjson::Value& rawData, float scale); + virtual BoneData* _parseBone(const rapidjson::Value& rawData); + virtual ConstraintData* _parseIKConstraint(const rapidjson::Value& rawData); + virtual SlotData* _parseSlot(const rapidjson::Value& rawData, int zOrder); + virtual SkinData* _parseSkin(const rapidjson::Value& rawData); + virtual DisplayData* _parseDisplay(const rapidjson::Value& rawData); + virtual void _parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display); + virtual void _parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh); + virtual BoundingBoxData* _parseBoundingBox(const rapidjson::Value& rawData); virtual PolygonBoundingBoxData* _parsePolygonBoundingBox(const rapidjson::Value& rawData); - virtual AnimationData* _parseAnimation(const rapidjson::Value& rawData); - virtual TimelineData* _parseTimeline( - const rapidjson::Value& rawData, const char* framesKey, TimelineType type, - bool addIntOffset, bool addFloatOffset, unsigned frameValueCount, - const std::function& frameParser); - virtual void _parseBoneTimeline(const rapidjson::Value& rawData); - virtual void _parseSlotTimeline(const rapidjson::Value& rawData); - virtual unsigned _parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseActionFrame(const ActionFrame& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual AnimationData* _parseAnimation(const rapidjson::Value& rawData); + virtual TimelineData* _parseTimeline( + const rapidjson::Value& rawData, const char* framesKey, TimelineType type, + bool addIntOffset, bool addFloatOffset, unsigned frameValueCount, + const std::function& frameParser); + virtual void _parseBoneTimeline(const rapidjson::Value& rawData); + virtual void _parseSlotTimeline(const rapidjson::Value& rawData); + virtual unsigned _parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseActionFrame(const ActionFrame& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); virtual const std::vector& _parseActionData(const rapidjson::Value& rawData, ActionType type, BoneData* bone, SlotData* slot); - virtual void _parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale); - virtual void _parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color); - virtual void _parseArray(const rapidjson::Value& rawData); - virtual DragonBonesData* _parseDragonBonesData(const rapidjson::Value& rawData, float scale = 1.0f); - virtual void _parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f); + virtual void _parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale); + virtual void _parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color); + virtual void _parseArray(const rapidjson::Value& rawData); + virtual DragonBonesData* _parseDragonBonesData(const rapidjson::Value& rawData, float scale = 1.0f); + virtual void _parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f); public: virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) override; - virtual bool parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f) override; + virtual bool parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f) override; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/middleware-adapter.cpp b/native/cocos/editor-support/middleware-adapter.cpp index fd6fee9d84..6a9aa8a987 100644 --- a/native/cocos/editor-support/middleware-adapter.cpp +++ b/native/cocos/editor-support/middleware-adapter.cpp @@ -131,11 +131,11 @@ bool SpriteFrame::initWithTexture(Texture2D *texture, const cc::Rect &rect, bool texture->addRef(); } - _rectInPixels = rect; - _offsetInPixels = offset; + _rectInPixels = rect; + _offsetInPixels = offset; _originalSizeInPixels = originalSize; - _rotated = rotated; - _anchorPoint = cc::Vec2(NAN, NAN); + _rotated = rotated; + _anchorPoint = cc::Vec2(NAN, NAN); return true; } diff --git a/native/cocos/editor-support/middleware-adapter.h b/native/cocos/editor-support/middleware-adapter.h index 03cbdd1777..f4bf8458b9 100644 --- a/native/cocos/editor-support/middleware-adapter.h +++ b/native/cocos/editor-support/middleware-adapter.h @@ -36,8 +36,8 @@ MIDDLEWARE_BEGIN struct Color4B { Color4B(uint32_t r, uint32_t g, uint32_t b, uint32_t a); Color4B(); - bool operator==(const Color4B &right) const; - bool operator!=(const Color4B &right) const; + bool operator==(const Color4B &right) const; + bool operator!=(const Color4B &right) const; Color4B &operator=(const Color4B &right); uint32_t r = 0; @@ -53,8 +53,8 @@ struct Color4F { Color4F(); bool operator==(const Color4F &right) const; bool operator!=(const Color4F &right) const; - Color4F& operator=(const Color4B &right); - + Color4F &operator=(const Color4B &right); + float r = 0.0F; float g = 0.0F; float b = 0.0F; @@ -144,7 +144,7 @@ public: /** * set texture param callback */ - using texParamCallback = std::function; + using texParamCallback = std::function; /** Sets the min filter, mag filter, wrap s and wrap t texture parameters. If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}. @@ -227,11 +227,11 @@ public: void setTexture(Texture2D *pobTexture); protected: - cc::Vec2 _anchorPoint; - cc::Rect _rectInPixels; - bool _rotated = false; - cc::Vec2 _offsetInPixels; - cc::Size _originalSizeInPixels; + cc::Vec2 _anchorPoint; + cc::Rect _rectInPixels; + bool _rotated = false; + cc::Vec2 _offsetInPixels; + cc::Size _originalSizeInPixels; Texture2D *_texture = nullptr; }; MIDDLEWARE_END diff --git a/native/cocos/editor-support/spine-creator-support/AttachmentVertices.cpp b/native/cocos/editor-support/spine-creator-support/AttachmentVertices.cpp index 1f8b42232b..cd3151b9fe 100644 --- a/native/cocos/editor-support/spine-creator-support/AttachmentVertices.cpp +++ b/native/cocos/editor-support/spine-creator-support/AttachmentVertices.cpp @@ -37,10 +37,10 @@ AttachmentVertices::AttachmentVertices(middleware::Texture2D *texture, int verti _texture = texture; if (_texture) _texture->addRef(); - _triangles = new middleware::Triangles(); - _triangles->verts = new middleware::V2F_T2F_C4F[verticesCount]; - _triangles->vertCount = verticesCount; - _triangles->indices = triangles; + _triangles = new middleware::Triangles(); + _triangles->verts = new middleware::V2F_T2F_C4F[verticesCount]; + _triangles->vertCount = verticesCount; + _triangles->indices = triangles; _triangles->indexCount = trianglesCount; } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp index a8fbda055e..da92b836f5 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp @@ -37,12 +37,12 @@ namespace spine { struct TrackEntryListeners { - StartListener startListener; + StartListener startListener; InterruptListener interruptListener; - EndListener endListener; - DisposeListener disposeListener; - CompleteListener completeListener; - EventListener eventListener; + EndListener endListener; + DisposeListener disposeListener; + CompleteListener completeListener; + EventListener eventListener; }; void animationCallback(AnimationState *state, EventType type, TrackEntry *entry, Event *event) { @@ -68,7 +68,7 @@ static TrackEntryListeners *getListeners(TrackEntry *entry) { } float SkeletonAnimation::GlobalTimeScale = 1.0F; -void SkeletonAnimation::setGlobalTimeScale(float timeScale) { +void SkeletonAnimation::setGlobalTimeScale(float timeScale) { GlobalTimeScale = timeScale; } @@ -99,7 +99,7 @@ void SkeletonAnimation::initialize() { super::initialize(); _ownsAnimationStateData = true; - _state = new (__FILE__, __LINE__) AnimationState(new (__FILE__, __LINE__) AnimationStateData(_skeleton->getData())); + _state = new (__FILE__, __LINE__) AnimationState(new (__FILE__, __LINE__) AnimationStateData(_skeleton->getData())); _state->setRendererObject(this); _state->setListener(animationCallback); } @@ -107,12 +107,12 @@ void SkeletonAnimation::initialize() { SkeletonAnimation::SkeletonAnimation() = default; SkeletonAnimation::~SkeletonAnimation() { - _startListener = nullptr; + _startListener = nullptr; _interruptListener = nullptr; - _endListener = nullptr; - _disposeListener = nullptr; - _completeListener = nullptr; - _eventListener = nullptr; + _endListener = nullptr; + _disposeListener = nullptr; + _completeListener = nullptr; + _eventListener = nullptr; if (_state) { if (_ownsAnimationStateData) delete _state->getData(); @@ -140,7 +140,7 @@ void SkeletonAnimation::setAnimationStateData(AnimationStateData *stateData) { } _ownsAnimationStateData = false; - _state = new (__FILE__, __LINE__) AnimationState(stateData); + _state = new (__FILE__, __LINE__) AnimationState(stateData); _state->setRendererObject(this); _state->setListener(animationCallback); } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp index f06a0f0a78..143c4dd89d 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp @@ -36,7 +36,7 @@ using namespace cc; // NOLINT(google-build-using-namespace) namespace spine { -float SkeletonCache::FrameTime = 1.0F / 60.0F; +float SkeletonCache::FrameTime = 1.0F / 60.0F; float SkeletonCache::MaxCacheTime = 120.0F; SkeletonCache::SegmentData::SegmentData() = default; @@ -125,7 +125,7 @@ void SkeletonCache::AnimationData::reset() { } _frames.clear(); _isComplete = false; - _totalTime = 0.0F; + _totalTime = 0.0F; } bool SkeletonCache::AnimationData::needUpdate(int toFrameIdx) const { @@ -165,13 +165,13 @@ SkeletonCache::~SkeletonCache() { SkeletonCache::AnimationData *SkeletonCache::buildAnimationData(const std::string &animationName) { AnimationData *aniData = nullptr; - auto it = _animationCaches.find(animationName); + auto it = _animationCaches.find(animationName); if (it == _animationCaches.end()) { auto *animation = findAnimation(animationName); if (animation == nullptr) return nullptr; - aniData = new AnimationData(); - aniData->_animationName = animationName; + aniData = new AnimationData(); + aniData->_animationName = animationName; _animationCaches[animationName] = aniData; } else { aniData = it->second; @@ -225,7 +225,7 @@ void SkeletonCache::updateToFrame(const std::string &animationName, int toFrameI void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { std::size_t frameIndex = animationData->getFrameCount(); - FrameData * frameData = animationData->buildFrameData(frameIndex); + FrameData *frameData = animationData->buildFrameData(frameIndex); if (!_skeleton) return; @@ -240,9 +240,9 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { Color4F color; Color4F darkColor; - AttachmentVertices * attachmentVertices = nullptr; - middleware::IOBuffer &vb = frameData->vb; - middleware::IOBuffer &ib = frameData->ib; + AttachmentVertices *attachmentVertices = nullptr; + middleware::IOBuffer &vb = frameData->vb; + middleware::IOBuffer &ib = frameData->ib; // vertex size int bytes with two color int vbs2 = sizeof(V2F_T2F_C4F_C4F); @@ -252,24 +252,24 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { int vbSize = 0; int ibSize = 0; - int preBlendMode = -1; + int preBlendMode = -1; int preTextureIndex = -1; int curTextureIndex = -1; int preISegWritePos = -1; - int curISegLen = 0; - int curVSegLen = 0; + int curISegLen = 0; + int curVSegLen = 0; - int materialLen = 0; - Slot *slot = nullptr; + int materialLen = 0; + Slot *slot = nullptr; middleware::Texture2D *texture = nullptr; auto flush = [&]() { // fill pre segment count field if (preISegWritePos != -1) { - SegmentData *preSegmentData = frameData->buildSegmentData(materialLen - 1); - preSegmentData->indexCount = curISegLen; + SegmentData *preSegmentData = frameData->buildSegmentData(materialLen - 1); + preSegmentData->indexCount = curISegLen; preSegmentData->vertexFloatCount = curVSegLen; } @@ -293,16 +293,16 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { auto &bones = _skeleton->getBones(); for (std::size_t i = 0, n = bones.size(); i < n; i++) { - auto & bone = bones[i]; - auto boneCount = frameData->getBoneCount(); - BoneData *boneData = frameData->buildBoneData(boneCount); - auto & matm = boneData->globalTransformMatrix.m; - matm[0] = bone->getA(); - matm[1] = bone->getC(); - matm[4] = bone->getB(); - matm[5] = bone->getD(); - matm[12] = bone->getWorldX(); - matm[13] = bone->getWorldY(); + auto &bone = bones[i]; + auto boneCount = frameData->getBoneCount(); + BoneData *boneData = frameData->buildBoneData(boneCount); + auto &matm = boneData->globalTransformMatrix.m; + matm[0] = bone->getA(); + matm[1] = bone->getC(); + matm[4] = bone->getB(); + matm[5] = bone->getD(); + matm[12] = bone->getWorldX(); + matm[13] = bone->getWorldY(); } auto &drawOrder = _skeleton->getDrawOrder(); @@ -327,7 +327,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { TwoColorTriangles trianglesTwoColor; if (slot->getAttachment()->getRTTI().isExactly(RegionAttachment::rtti)) { - auto *attachment = dynamic_cast(slot->getAttachment()); + auto *attachment = dynamic_cast(slot->getAttachment()); attachmentVertices = static_cast(attachment->getRendererObject()); // Early exit if attachment is invisible @@ -337,7 +337,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { } trianglesTwoColor.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); + vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); for (int ii = 0; ii < trianglesTwoColor.vertCount; ii++) { @@ -346,7 +346,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { attachment->computeWorldVertices(slot->getBone(), reinterpret_cast(trianglesTwoColor.verts), 0, vs2); trianglesTwoColor.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); + ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); ib.checkSpace(ibSize, true); trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, attachmentVertices->_triangles->indices, ibSize); @@ -357,7 +357,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { color.a = attachment->getColor().a; } else if (slot->getAttachment()->getRTTI().isExactly(MeshAttachment::rtti)) { - auto *attachment = dynamic_cast(slot->getAttachment()); + auto *attachment = dynamic_cast(slot->getAttachment()); attachmentVertices = static_cast(attachment->getRendererObject()); // Early exit if attachment is invisible @@ -367,7 +367,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { } trianglesTwoColor.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); + vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); for (int ii = 0; ii < trianglesTwoColor.vertCount; ii++) { @@ -376,7 +376,7 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { attachment->computeWorldVertices(*slot, 0, attachment->getWorldVerticesLength(), reinterpret_cast(trianglesTwoColor.verts), 0, vs2); trianglesTwoColor.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); + ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); ib.checkSpace(ibSize, true); trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, attachmentVertices->_triangles->indices, ibSize); @@ -402,9 +402,9 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { continue; } - float red = _skeleton->getColor().r * color.r * 255; + float red = _skeleton->getColor().r * color.r * 255; float green = _skeleton->getColor().g * color.g * 255; - float blue = _skeleton->getColor().b * color.b * 255; + float blue = _skeleton->getColor().b * color.b * 255; color.r = red * slot->getColor().r; color.g = green * slot->getColor().g; @@ -422,16 +422,16 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { darkColor.a = 0; if (preColor != color || preDarkColor != darkColor) { - preColor = color; - preDarkColor = darkColor; + preColor = color; + preDarkColor = darkColor; auto colorCount = frameData->getColorCount(); if (colorCount > 0) { - ColorData *preColorData = frameData->buildColorData(colorCount - 1); + ColorData *preColorData = frameData->buildColorData(colorCount - 1); preColorData->vertexFloatOffset = static_cast(vb.getCurPos() / sizeof(float)); } - ColorData *colorData = frameData->buildColorData(colorCount); + ColorData *colorData = frameData->buildColorData(colorCount); colorData->finalColor = color; - colorData->darkColor = darkColor; + colorData->darkColor = darkColor; } // Two color tint logic @@ -444,49 +444,49 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { } trianglesTwoColor.vertCount = static_cast(_clipper->getClippedVertices().size()) >> 1; - vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); + vbSize = static_cast(trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F)); vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); trianglesTwoColor.indexCount = static_cast(_clipper->getClippedTriangles().size()); - ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); + ibSize = static_cast(trianglesTwoColor.indexCount * sizeof(uint16_t)); ib.checkSpace(ibSize, true); trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, _clipper->getClippedTriangles().buffer(), sizeof(uint16_t) * _clipper->getClippedTriangles().size()); float *verts = _clipper->getClippedVertices().buffer(); - float *uvs = _clipper->getClippedUVs().buffer(); + float *uvs = _clipper->getClippedUVs().buffer(); for (int v = 0, vn = trianglesTwoColor.vertCount, vv = 0; v < vn; ++v, vv += 2) { V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - vertex->vertex.x = verts[vv]; - vertex->vertex.y = verts[vv + 1]; - vertex->texCoord.u = uvs[vv]; - vertex->texCoord.v = uvs[vv + 1]; - vertex->color.r = color.r / 255.0F; - vertex->color.g = color.g / 255.0F; - vertex->color.b = color.b / 255.0F; - vertex->color.a = color.a / 255.0F; - vertex->color2.r = darkColor.r / 255.0F; - vertex->color2.g = darkColor.g / 255.0F; - vertex->color2.b = darkColor.b / 255.0F; - vertex->color2.a = darkColor.a / 255.0F; + vertex->vertex.x = verts[vv]; + vertex->vertex.y = verts[vv + 1]; + vertex->texCoord.u = uvs[vv]; + vertex->texCoord.v = uvs[vv + 1]; + vertex->color.r = color.r / 255.0F; + vertex->color.g = color.g / 255.0F; + vertex->color.b = color.b / 255.0F; + vertex->color.a = color.a / 255.0F; + vertex->color2.r = darkColor.r / 255.0F; + vertex->color2.g = darkColor.g / 255.0F; + vertex->color2.b = darkColor.b / 255.0F; + vertex->color2.a = darkColor.a / 255.0F; } } else { for (int v = 0, vn = trianglesTwoColor.vertCount; v < vn; ++v) { V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - vertex->color.r = color.r / 255.0F; - vertex->color.g = color.g / 255.0F; - vertex->color.b = color.b / 255.0F; - vertex->color.a = color.a / 255.0F; - vertex->color2.r = darkColor.r / 255.0F; - vertex->color2.g = darkColor.g / 255.0F; - vertex->color2.b = darkColor.b / 255.0F; - vertex->color2.a = darkColor.a / 255.0F; + vertex->color.r = color.r / 255.0F; + vertex->color.g = color.g / 255.0F; + vertex->color.b = color.b / 255.0F; + vertex->color.a = color.a / 255.0F; + vertex->color2.r = darkColor.r / 255.0F; + vertex->color2.g = darkColor.g / 255.0F; + vertex->color2.b = darkColor.b / 255.0F; + vertex->color2.a = darkColor.a / 255.0F; } } - texture = attachmentVertices->_texture; + texture = attachmentVertices->_texture; curTextureIndex = attachmentVertices->_texture->getRealTextureIndex(); // If texture or blendMode change,will change material. if (preTextureIndex != curTextureIndex || preBlendMode != slot->getData().getBlendMode()) { @@ -516,14 +516,14 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { _clipper->clipEnd(); if (preISegWritePos != -1) { - SegmentData *preSegmentData = frameData->buildSegmentData(materialLen - 1); - preSegmentData->indexCount = curISegLen; + SegmentData *preSegmentData = frameData->buildSegmentData(materialLen - 1); + preSegmentData->indexCount = curISegLen; preSegmentData->vertexFloatCount = curVSegLen; } auto colorCount = frameData->getColorCount(); if (colorCount > 0) { - ColorData *preColorData = frameData->buildColorData(colorCount - 1); + ColorData *preColorData = frameData->buildColorData(colorCount - 1); preColorData->vertexFloatOffset = static_cast(vb.getCurPos() / sizeof(float)); } } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp index 78660be0ef..dd8f0c275f 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.cpp @@ -40,7 +40,7 @@ USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace cc; // NOLINT(google-build-using-namespace) using namespace cc::gfx; // NOLINT(google-build-using-namespace) -static const std::string TECH_STAGE = "opaque"; +static const std::string TECH_STAGE = "opaque"; static const std::string TEXTURE_KEY = "texture"; namespace spine { @@ -113,7 +113,7 @@ void SkeletonCacheAnimation::update(float dt) { _accTime += dt; if (_accTime > _headAnimation->delay) { std::string name = _headAnimation->animationName; - bool loop = _headAnimation->loop; + bool loop = _headAnimation->loop; delete _headAnimation; _headAnimation = nullptr; setAnimation(name, loop); @@ -140,8 +140,8 @@ void SkeletonCacheAnimation::update(float dt) { _playCount++; _accTime = 0.0F; if (_playTimes > 0 && _playCount >= _playTimes) { - frameIdx = finalFrameIndex; - _playCount = 0; + frameIdx = finalFrameIndex; + _playCount = 0; _isAniComplete = true; } else { frameIdx = 0; @@ -162,7 +162,7 @@ void SkeletonCacheAnimation::render(float /*dt*/) { if (!frameData) return; const auto &segments = frameData->getSegments(); - const auto &colors = frameData->getColors(); + const auto &colors = frameData->getColors(); if (segments.empty() || colors.empty()) return; auto *mgr = MiddlewareManager::getInstance(); @@ -171,11 +171,11 @@ void SkeletonCacheAnimation::render(float /*dt*/) { _sharedBufferOffset->reset(); _sharedBufferOffset->clear(); - auto *renderMgr = mgr->getRenderInfoMgr(); + auto *renderMgr = mgr->getRenderInfoMgr(); auto *renderInfo = renderMgr->getBuffer(); if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); + auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; @@ -192,12 +192,12 @@ void SkeletonCacheAnimation::render(float /*dt*/) { // material len renderInfo->writeUint32(segments.size()); - auto vertexFormat = _useTint ? VF_XYZUVCC : VF_XYZUVC; - middleware::MeshBuffer *mb = mgr->getMeshBuffer(vertexFormat); - middleware::IOBuffer & vb = mb->getVB(); - middleware::IOBuffer & ib = mb->getIB(); - const auto & srcVB = frameData->vb; - const auto & srcIB = frameData->ib; + auto vertexFormat = _useTint ? VF_XYZUVCC : VF_XYZUVC; + middleware::MeshBuffer *mb = mgr->getMeshBuffer(vertexFormat); + middleware::IOBuffer &vb = mb->getVB(); + middleware::IOBuffer &ib = mb->getIB(); + const auto &srcVB = frameData->vb; + const auto &srcIB = frameData->ib; // vertex size int bytes with one color int vbs1 = sizeof(V2F_T2F_C4F); @@ -208,41 +208,41 @@ void SkeletonCacheAnimation::render(float /*dt*/) { // vertex size in floats with two color int vs2 = static_cast(vbs2 / sizeof(float)); - int vs = _useTint ? vs2 : vs1; + int vs = _useTint ? vs2 : vs1; int vbs = _useTint ? vbs2 : vbs1; - auto * paramsBuffer = _paramsBuffer->getBuffer(); + auto *paramsBuffer = _paramsBuffer->getBuffer(); const cc::Mat4 &nodeWorldMat = *reinterpret_cast(¶msBuffer[4]); - int colorOffset = 0; - SkeletonCache::ColorData *nowColor = colors[colorOffset++]; - auto maxVFOffset = nowColor->vertexFloatOffset; + int colorOffset = 0; + SkeletonCache::ColorData *nowColor = colors[colorOffset++]; + auto maxVFOffset = nowColor->vertexFloatOffset; - Color4F finalColor; - Color4F darkColor; - float tempR = 0.0F; - float tempG = 0.0F; - float tempB = 0.0F; - float tempA = 0.0F; - float multiplier = 1.0F; - int srcVertexBytesOffset = 0; - int srcVertexBytes = 0; - int vertexBytes = 0; - int vertexFloats = 0; - int tintBytes = 0; - int srcIndexBytesOffset = 0; - int indexBytes = 0; - int curTextureIndex = 0; - double effectHash = 0; - int blendMode = 0; - int dstVertexOffset = 0; - int dstIndexOffset = 0; - float * dstVertexBuffer = nullptr; - unsigned int *dstColorBuffer = nullptr; - uint16_t * dstIndexBuffer = nullptr; - bool needColor = false; - int curBlendSrc = -1; - int curBlendDst = -1; + Color4F finalColor; + Color4F darkColor; + float tempR = 0.0F; + float tempG = 0.0F; + float tempB = 0.0F; + float tempA = 0.0F; + float multiplier = 1.0F; + int srcVertexBytesOffset = 0; + int srcVertexBytes = 0; + int vertexBytes = 0; + int vertexFloats = 0; + int tintBytes = 0; + int srcIndexBytesOffset = 0; + int indexBytes = 0; + int curTextureIndex = 0; + double effectHash = 0; + int blendMode = 0; + int dstVertexOffset = 0; + int dstIndexOffset = 0; + float *dstVertexBuffer = nullptr; + unsigned int *dstColorBuffer = nullptr; + uint16_t *dstIndexBuffer = nullptr; + bool needColor = false; + int curBlendSrc = -1; + int curBlendDst = -1; if (abs(_nodeColor.r - 1.0F) > 0.0001F || abs(_nodeColor.g - 1.0F) > 0.0001F || @@ -253,11 +253,11 @@ void SkeletonCacheAnimation::render(float /*dt*/) { } auto handleColor = [&](SkeletonCache::ColorData *colorData) { - tempA = colorData->finalColor.a * _nodeColor.a; + tempA = colorData->finalColor.a * _nodeColor.a; multiplier = _premultipliedAlpha ? tempA / 255 : 1; - tempR = _nodeColor.r * multiplier; - tempG = _nodeColor.g * multiplier; - tempB = _nodeColor.b * multiplier; + tempR = _nodeColor.r * multiplier; + tempG = _nodeColor.g * multiplier; + tempB = _nodeColor.b * multiplier; finalColor.a = tempA / 255.0f; finalColor.r = (colorData->finalColor.r * tempR) / 255.0f; @@ -275,11 +275,11 @@ void SkeletonCacheAnimation::render(float /*dt*/) { for (auto *segment : segments) { srcVertexBytes = static_cast(segment->vertexFloatCount * sizeof(float)); if (!_useTint) { - tintBytes = static_cast(segment->vertexFloatCount / vs2 * sizeof(float)); - vertexBytes = srcVertexBytes - tintBytes; + tintBytes = static_cast(segment->vertexFloatCount / vs2 * sizeof(float)); + vertexBytes = srcVertexBytes - tintBytes; vertexFloats = static_cast(vertexBytes / sizeof(float)); } else { - vertexBytes = srcVertexBytes; + vertexBytes = srcVertexBytes; vertexFloats = segment->vertexFloatCount; } @@ -316,7 +316,7 @@ void SkeletonCacheAnimation::render(float /*dt*/) { vb.checkSpace(vertexBytes, true); dstVertexOffset = static_cast(vb.getCurPos()) / vbs; dstVertexBuffer = reinterpret_cast(vb.getCurBuffer()); - dstColorBuffer = reinterpret_cast(vb.getCurBuffer()); + dstColorBuffer = reinterpret_cast(vb.getCurBuffer()); if (!_useTint) { char *srcBuffer = reinterpret_cast(srcVB.getBuffer()) + srcVertexBytesOffset; for (std::size_t srcBufferIdx = 0; srcBufferIdx < srcVertexBytes; srcBufferIdx += vbs2) { @@ -388,7 +388,7 @@ void SkeletonCacheAnimation::render(float /*dt*/) { if (_useAttach) { const auto &bonesData = frameData->getBones(); - auto boneCount = frameData->getBoneCount(); + auto boneCount = frameData->getBoneCount(); for (std::size_t i = 0, n = boneCount; i < n; i++) { auto *bone = bonesData[i]; @@ -499,20 +499,20 @@ void SkeletonCacheAnimation::setAttachEnabled(bool enabled) { } void SkeletonCacheAnimation::setAnimation(const std::string &name, bool loop) { - _playTimes = loop ? 0 : 1; + _playTimes = loop ? 0 : 1; _animationName = name; _animationData = _skeletonCache->buildAnimationData(_animationName); _isAniComplete = false; - _accTime = 0.0F; - _playCount = 0; + _accTime = 0.0F; + _playCount = 0; _curFrameIndex = 0; } void SkeletonCacheAnimation::addAnimation(const std::string &name, bool loop, float delay) { - auto *aniInfo = new AniQueueData(); + auto *aniInfo = new AniQueueData(); aniInfo->animationName = name; - aniInfo->loop = loop; - aniInfo->delay = delay; + aniInfo->loop = loop; + aniInfo->delay = delay; _animationQueue.push(aniInfo); } diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h index 73dc686a4f..086cb1287c 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h @@ -42,13 +42,13 @@ public: SkeletonCacheAnimation(const std::string &uuid, bool isShare); ~SkeletonCacheAnimation() override; - void update(float dt) override; - void render(float dt) override; + void update(float dt) override; + void render(float dt) override; uint32_t getRenderOrder() const override; Skeleton *getSkeleton() const; - void setTimeScale(float scale); + void setTimeScale(float scale); float getTimeScale() const; void paused(bool value); @@ -60,11 +60,11 @@ public: void setSkin(const char *skinName); Attachment *getAttachment(const std::string &slotName, const std::string &attachmentName) const; - bool setAttachment(const std::string &slotName, const std::string &attachmentName); - bool setAttachment(const std::string &slotName, const char *attachmentName); - void setColor(float r, float g, float b, float a); - void setBatchEnabled(bool enabled); - void setAttachEnabled(bool enabled); + bool setAttachment(const std::string &slotName, const std::string &attachmentName); + bool setAttachment(const std::string &slotName, const char *attachmentName); + void setColor(float r, float g, float b, float a); + void setBatchEnabled(bool enabled); + void setAttachEnabled(bool enabled); void setOpacityModifyRGB(bool value); bool isOpacityModifyRGB() const; @@ -75,8 +75,8 @@ public: void onDisable(); void setUseTint(bool enabled); - void setAnimation(const std::string &name, bool loop); - void addAnimation(const std::string &name, bool loop, float delay = 0); + void setAnimation(const std::string &name, bool loop); + void addAnimation(const std::string &name, bool loop, float delay = 0); Animation *findAnimation(const std::string &name) const; using CacheFrameEvent = std::function; @@ -102,35 +102,35 @@ public: se_object_ptr getParamsBuffer() const; private: - float _timeScale = 1; - bool _paused = false; - bool _useAttach = false; - bool _batch = true; - cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; - bool _premultipliedAlpha = false; + float _timeScale = 1; + bool _paused = false; + bool _useAttach = false; + bool _batch = true; + cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; + bool _premultipliedAlpha = false; - CacheFrameEvent _startListener = nullptr; - CacheFrameEvent _endListener = nullptr; + CacheFrameEvent _startListener = nullptr; + CacheFrameEvent _endListener = nullptr; CacheFrameEvent _completeListener = nullptr; - SkeletonCache * _skeletonCache = nullptr; + SkeletonCache *_skeletonCache = nullptr; SkeletonCache::AnimationData *_animationData = nullptr; - int _curFrameIndex = -1; + int _curFrameIndex = -1; - float _accTime = 0.0F; - int _playCount = 0; - int _playTimes = 0; - bool _isAniComplete = true; + float _accTime = 0.0F; + int _playCount = 0; + int _playTimes = 0; + bool _isAniComplete = true; std::string _animationName; - bool _useTint = true; + bool _useTint = true; struct AniQueueData { std::string animationName; - bool loop = false; - float delay = 0.0F; + bool loop = false; + float delay = 0.0F; }; std::queue _animationQueue; - AniQueueData * _headAnimation = nullptr; + AniQueueData *_headAnimation = nullptr; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; // Js fill this buffer to send parameter to cpp, avoid to call jsb function. diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheMgr.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCacheMgr.cpp index 674a83dd00..85bfeca2c7 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheMgr.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheMgr.cpp @@ -32,7 +32,7 @@ namespace spine { SkeletonCacheMgr *SkeletonCacheMgr::instance = nullptr; -SkeletonCache * SkeletonCacheMgr::buildSkeletonCache(const std::string &uuid) { +SkeletonCache *SkeletonCacheMgr::buildSkeletonCache(const std::string &uuid) { SkeletonCache *animation = _caches.at(uuid); if (!animation) { animation = new SkeletonCache(); diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h index b5572d170e..a43768a093 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h @@ -78,8 +78,8 @@ public: } private: - static SkeletonDataMgr * instance; - destroyCallback _destroyCallback = nullptr; + static SkeletonDataMgr *instance; + destroyCallback _destroyCallback = nullptr; std::map _dataMap; }; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp index af3dfcb654..cfda1c5c28 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp @@ -49,7 +49,7 @@ using namespace cc::gfx; // NOLINT(google-build-using-namespace) using std::max; using std::min; -static const std::string TECH_STAGE = "opaque"; +static const std::string TECH_STAGE = "opaque"; static const std::string TEXTURE_KEY = "texture"; static spine::Cocos2dTextureLoader textureLoader; @@ -125,7 +125,7 @@ void SkeletonRenderer::stopSchedule() { } void SkeletonRenderer::setSkeletonData(SkeletonData *skeletonData, bool ownsSkeletonData) { - _skeleton = new (__FILE__, __LINE__) Skeleton(skeletonData); + _skeleton = new (__FILE__, __LINE__) Skeleton(skeletonData); _ownsSkeletonData = ownsSkeletonData; } @@ -170,8 +170,8 @@ SkeletonRenderer::~SkeletonRenderer() { } void SkeletonRenderer::initWithUUID(const std::string &uuid) { - _ownsSkeleton = true; - _uuid = uuid; + _ownsSkeleton = true; + _uuid = uuid; SkeletonData *skeletonData = SkeletonDataMgr::getInstance()->retainByUUID(uuid); CC_ASSERT(skeletonData); @@ -180,10 +180,10 @@ void SkeletonRenderer::initWithUUID(const std::string &uuid) { } void SkeletonRenderer::initWithSkeleton(Skeleton *skeleton, bool ownsSkeleton, bool ownsSkeletonData, bool ownsAtlas) { - _skeleton = skeleton; - _ownsSkeleton = ownsSkeleton; + _skeleton = skeleton; + _ownsSkeleton = ownsSkeleton; _ownsSkeletonData = ownsSkeletonData; - _ownsAtlas = ownsAtlas; + _ownsAtlas = ownsAtlas; initialize(); } @@ -195,7 +195,7 @@ void SkeletonRenderer::initWithData(SkeletonData *skeletonData, bool ownsSkeleto } void SkeletonRenderer::initWithJsonFile(const std::string &skeletonDataFile, Atlas *atlas, float scale) { - _atlas = atlas; + _atlas = atlas; _attachmentLoader = new (__FILE__, __LINE__) Cocos2dAtlasAttachmentLoader(_atlas); SkeletonJson json(_attachmentLoader); @@ -221,14 +221,14 @@ void SkeletonRenderer::initWithJsonFile(const std::string &skeletonDataFile, con CC_ASSERT(skeletonData); // Can use json.getError() to get error message. _ownsSkeleton = true; - _ownsAtlas = true; + _ownsAtlas = true; setSkeletonData(skeletonData, true); initialize(); } void SkeletonRenderer::initWithBinaryFile(const std::string &skeletonDataFile, Atlas *atlas, float scale) { - _atlas = atlas; + _atlas = atlas; _attachmentLoader = new (__FILE__, __LINE__) Cocos2dAtlasAttachmentLoader(_atlas); SkeletonBinary binary(_attachmentLoader); @@ -254,7 +254,7 @@ void SkeletonRenderer::initWithBinaryFile(const std::string &skeletonDataFile, c CC_ASSERT(skeletonData); // Can use binary.getError() to get error message. _ownsSkeleton = true; - _ownsAtlas = true; + _ownsAtlas = true; setSkeletonData(skeletonData, true); initialize(); @@ -270,11 +270,11 @@ void SkeletonRenderer::render(float /*deltaTime*/) { auto *mgr = MiddlewareManager::getInstance(); if (!mgr->isRendering) return; - auto *renderMgr = mgr->getRenderInfoMgr(); + auto *renderMgr = mgr->getRenderInfoMgr(); auto *renderInfo = renderMgr->getBuffer(); if (!renderInfo) return; - auto *attachMgr = mgr->getAttachInfoMgr(); + auto *attachMgr = mgr->getAttachInfoMgr(); auto *attachInfo = attachMgr->getBuffer(); if (!attachInfo) return; @@ -298,14 +298,14 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } // color range is [0.0, 1.0] - cc::middleware::Color4F color; - cc::middleware::Color4F darkColor; - AttachmentVertices * attachmentVertices = nullptr; - bool inRange = !(_startSlotIndex != -1 || _endSlotIndex != -1); - auto vertexFormat = _useTint ? VF_XYZUVCC : VF_XYZUVC; - cc::middleware::MeshBuffer *mb = mgr->getMeshBuffer(vertexFormat); - cc::middleware::IOBuffer & vb = mb->getVB(); - cc::middleware::IOBuffer & ib = mb->getIB(); + cc::middleware::Color4F color; + cc::middleware::Color4F darkColor; + AttachmentVertices *attachmentVertices = nullptr; + bool inRange = !(_startSlotIndex != -1 || _endSlotIndex != -1); + auto vertexFormat = _useTint ? VF_XYZUVCC : VF_XYZUVC; + cc::middleware::MeshBuffer *mb = mgr->getMeshBuffer(vertexFormat); + cc::middleware::IOBuffer &vb = mb->getVB(); + cc::middleware::IOBuffer &ib = mb->getIB(); // vertex size int bytes with one color unsigned int vbs1 = sizeof(V2F_T2F_C4F); @@ -328,19 +328,19 @@ void SkeletonRenderer::render(float /*deltaTime*/) { unsigned int vbSize = 0; unsigned int ibSize = 0; - int curBlendSrc = -1; - int curBlendDst = -1; - int curBlendMode = -1; - int preBlendMode = -1; + int curBlendSrc = -1; + int curBlendDst = -1; + int curBlendMode = -1; + int preBlendMode = -1; int preTextureIndex = -1; int curTextureIndex = -1; - int preISegWritePos = -1; - uint32_t curISegLen = 0; + int preISegWritePos = -1; + uint32_t curISegLen = 0; - int materialLen = 0; - Slot *slot = nullptr; - int isFull = 0; + int materialLen = 0; + Slot *slot = nullptr; + int isFull = 0; if (_debugSlots || _debugBones || _debugMesh) { // If enable debug draw,then init debug buffer. @@ -416,7 +416,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { auto &drawOrder = _skeleton->getDrawOrder(); for (size_t i = 0, n = drawOrder.size(); i < n; ++i) { isFull = 0; - slot = drawOrder[i]; + slot = drawOrder[i]; if (slot->getBone().isActive() == false) { continue; @@ -446,11 +446,11 @@ void SkeletonRenderer::render(float /*deltaTime*/) { continue; } - cc::middleware::Triangles triangles; + cc::middleware::Triangles triangles; cc::middleware::TwoColorTriangles trianglesTwoColor; if (slot->getAttachment()->getRTTI().isExactly(RegionAttachment::rtti)) { - auto *attachment = dynamic_cast(slot->getAttachment()); + auto *attachment = dynamic_cast(slot->getAttachment()); attachmentVertices = reinterpret_cast(attachment->getRendererObject()); // Early exit if attachment is invisible @@ -461,20 +461,20 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (!_useTint) { triangles.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); + vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); isFull |= vb.checkSpace(vbSize, true); triangles.verts = reinterpret_cast(vb.getCurBuffer()); memcpy(static_cast(triangles.verts), static_cast(attachmentVertices->_triangles->verts), vbSize); attachment->computeWorldVertices(slot->getBone(), reinterpret_cast(triangles.verts), 0, vs1); triangles.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = triangles.indexCount * sizeof(uint16_t); + ibSize = triangles.indexCount * sizeof(uint16_t); ib.checkSpace(ibSize, true); triangles.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(triangles.indices, attachmentVertices->_triangles->indices, ibSize); } else { trianglesTwoColor.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); + vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); isFull |= vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); for (int ii = 0; ii < trianglesTwoColor.vertCount; ii++) { @@ -483,7 +483,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { attachment->computeWorldVertices(slot->getBone(), reinterpret_cast(trianglesTwoColor.verts), 0, vs2); trianglesTwoColor.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); + ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); ib.checkSpace(ibSize, true); trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, attachmentVertices->_triangles->indices, ibSize); @@ -497,8 +497,8 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (_debugSlots) { _debugBuffer->writeFloat32(DebugType::SLOTS); _debugBuffer->writeFloat32(8); - float * vertices = _useTint ? reinterpret_cast(trianglesTwoColor.verts) : reinterpret_cast(triangles.verts); - unsigned int stride = _useTint ? vs2 : vs1; + float *vertices = _useTint ? reinterpret_cast(trianglesTwoColor.verts) : reinterpret_cast(triangles.verts); + unsigned int stride = _useTint ? vs2 : vs1; // Quadrangle has 4 vertex. for (int ii = 0; ii < 4; ii++) { _debugBuffer->writeFloat32(vertices[0]); @@ -507,7 +507,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } } } else if (slot->getAttachment()->getRTTI().isExactly(MeshAttachment::rtti)) { - auto *attachment = dynamic_cast(slot->getAttachment()); + auto *attachment = dynamic_cast(slot->getAttachment()); attachmentVertices = static_cast(attachment->getRendererObject()); // Early exit if attachment is invisible @@ -518,20 +518,20 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (!_useTint) { triangles.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); + vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); isFull |= vb.checkSpace(vbSize, true); triangles.verts = reinterpret_cast(vb.getCurBuffer()); memcpy(static_cast(triangles.verts), static_cast(attachmentVertices->_triangles->verts), vbSize); attachment->computeWorldVertices(*slot, 0, attachment->getWorldVerticesLength(), reinterpret_cast(triangles.verts), 0, vs1); triangles.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = triangles.indexCount * sizeof(uint16_t); + ibSize = triangles.indexCount * sizeof(uint16_t); ib.checkSpace(ibSize, true); triangles.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(triangles.indices, attachmentVertices->_triangles->indices, ibSize); } else { trianglesTwoColor.vertCount = attachmentVertices->_triangles->vertCount; - vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); + vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); isFull |= vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); for (int ii = 0; ii < trianglesTwoColor.vertCount; ii++) { @@ -540,7 +540,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { attachment->computeWorldVertices(*slot, 0, attachment->getWorldVerticesLength(), reinterpret_cast(trianglesTwoColor.verts), 0, vs2); trianglesTwoColor.indexCount = attachmentVertices->_triangles->indexCount; - ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); + ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); ib.checkSpace(ibSize, true); trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, attachmentVertices->_triangles->indices, ibSize); @@ -552,9 +552,9 @@ void SkeletonRenderer::render(float /*deltaTime*/) { color.a = attachment->getColor().a; if (_debugMesh) { - int indexCount = _useTint ? trianglesTwoColor.indexCount : triangles.indexCount; - uint16_t *indices = _useTint ? trianglesTwoColor.indices : triangles.indices; - float * vertices = _useTint ? reinterpret_cast(trianglesTwoColor.verts) : reinterpret_cast(triangles.verts); + int indexCount = _useTint ? trianglesTwoColor.indexCount : triangles.indexCount; + uint16_t *indices = _useTint ? trianglesTwoColor.indices : triangles.indices; + float *vertices = _useTint ? reinterpret_cast(trianglesTwoColor.verts) : reinterpret_cast(triangles.verts); unsigned int stride = _useTint ? vs2 : vs1; _debugBuffer->writeFloat32(DebugType::MESH); @@ -589,9 +589,9 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } float multiplier = _premultipliedAlpha ? color.a : 255; - float red = _nodeColor.r * _skeleton->getColor().r * color.r * multiplier; - float green = _nodeColor.g * _skeleton->getColor().g * color.g * multiplier; - float blue = _nodeColor.b * _skeleton->getColor().b * color.b * multiplier; + float red = _nodeColor.r * _skeleton->getColor().r * color.r * multiplier; + float green = _nodeColor.g * _skeleton->getColor().g * color.g * multiplier; + float blue = _nodeColor.b * _skeleton->getColor().b * color.b * multiplier; color.r = red * slot->getColor().r; color.g = green * slot->getColor().g; @@ -620,18 +620,18 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } triangles.vertCount = static_cast(_clipper->getClippedVertices().size()) >> 1; - vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); + vbSize = triangles.vertCount * sizeof(V2F_T2F_C4F); isFull |= vb.checkSpace(vbSize, true); triangles.verts = reinterpret_cast(vb.getCurBuffer()); triangles.indexCount = static_cast(_clipper->getClippedTriangles().size()); - ibSize = triangles.indexCount * sizeof(uint16_t); + ibSize = triangles.indexCount * sizeof(uint16_t); ib.checkSpace(ibSize, true); triangles.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(triangles.indices, _clipper->getClippedTriangles().buffer(), sizeof(uint16_t) * _clipper->getClippedTriangles().size()); float *verts = _clipper->getClippedVertices().buffer(); - float *uvs = _clipper->getClippedUVs().buffer(); + float *uvs = _clipper->getClippedUVs().buffer(); Color light; Color dark; @@ -643,13 +643,13 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (effect) { for (int v = 0, vn = triangles.vertCount, vv = 0; v < vn; ++v, vv += 2) { - V2F_T2F_C4F *vertex = triangles.verts + v; - Color lightCopy = light; - Color darkCopy = dark; - vertex->vertex.x = verts[vv]; - vertex->vertex.y = verts[vv + 1]; - vertex->texCoord.u = uvs[vv]; - vertex->texCoord.v = uvs[vv + 1]; + V2F_T2F_C4F *vertex = triangles.verts + v; + Color lightCopy = light; + Color darkCopy = dark; + vertex->vertex.x = verts[vv]; + vertex->vertex.y = verts[vv + 1]; + vertex->texCoord.u = uvs[vv]; + vertex->texCoord.v = uvs[vv + 1]; effect->transform(vertex->vertex.x, vertex->vertex.y, vertex->texCoord.u, vertex->texCoord.v, lightCopy, darkCopy); vertex->color.r = lightCopy.r; vertex->color.g = lightCopy.g; @@ -659,14 +659,14 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } else { for (int v = 0, vn = triangles.vertCount, vv = 0; v < vn; ++v, vv += 2) { V2F_T2F_C4F *vertex = triangles.verts + v; - vertex->vertex.x = verts[vv]; - vertex->vertex.y = verts[vv + 1]; - vertex->texCoord.u = uvs[vv]; - vertex->texCoord.v = uvs[vv + 1]; - vertex->color.r = light.r; - vertex->color.g = light.g; - vertex->color.b = light.b; - vertex->color.a = light.a; + vertex->vertex.x = verts[vv]; + vertex->vertex.y = verts[vv + 1]; + vertex->texCoord.u = uvs[vv]; + vertex->texCoord.v = uvs[vv + 1]; + vertex->color.r = light.r; + vertex->color.g = light.g; + vertex->color.b = light.b; + vertex->color.a = light.a; } } // No cliping logic @@ -681,9 +681,9 @@ void SkeletonRenderer::render(float /*deltaTime*/) { Color dark; dark.r = dark.g = dark.b = dark.a = 0; for (int v = 0, vn = triangles.vertCount; v < vn; ++v) { - V2F_T2F_C4F *vertex = triangles.verts + v; - Color lightCopy = light; - Color darkCopy = dark; + V2F_T2F_C4F *vertex = triangles.verts + v; + Color lightCopy = light; + Color darkCopy = dark; effect->transform(vertex->vertex.x, vertex->vertex.y, vertex->texCoord.u, vertex->texCoord.v, lightCopy, darkCopy); vertex->color.r = lightCopy.r; vertex->color.g = lightCopy.g; @@ -693,10 +693,10 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } else { for (int v = 0, vn = triangles.vertCount; v < vn; ++v) { V2F_T2F_C4F *vertex = triangles.verts + v; - vertex->color.r = light.r; - vertex->color.g = light.g; - vertex->color.b = light.b; - vertex->color.a = light.a; + vertex->color.r = light.r; + vertex->color.g = light.g; + vertex->color.b = light.b; + vertex->color.a = light.a; } } } @@ -712,17 +712,17 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } trianglesTwoColor.vertCount = static_cast(_clipper->getClippedVertices().size()) >> 1; - vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); + vbSize = trianglesTwoColor.vertCount * sizeof(V2F_T2F_C4F_C4F); isFull |= vb.checkSpace(vbSize, true); trianglesTwoColor.verts = reinterpret_cast(vb.getCurBuffer()); trianglesTwoColor.indexCount = static_cast(_clipper->getClippedTriangles().size()); - ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); - trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); + ibSize = trianglesTwoColor.indexCount * sizeof(uint16_t); + trianglesTwoColor.indices = reinterpret_cast(ib.getCurBuffer()); memcpy(trianglesTwoColor.indices, _clipper->getClippedTriangles().buffer(), sizeof(uint16_t) * _clipper->getClippedTriangles().size()); float *verts = _clipper->getClippedVertices().buffer(); - float *uvs = _clipper->getClippedUVs().buffer(); + float *uvs = _clipper->getClippedUVs().buffer(); Color light; Color dark; @@ -730,25 +730,25 @@ void SkeletonRenderer::render(float /*deltaTime*/) { light.g = color.g / 255.0F; light.b = color.b / 255.0F; light.a = color.a / 255.0F; - dark.r = darkColor.r / 255.0F; - dark.g = darkColor.g / 255.0F; - dark.b = darkColor.b / 255.0F; - dark.a = darkColor.a / 255.0F; + dark.r = darkColor.r / 255.0F; + dark.g = darkColor.g / 255.0F; + dark.b = darkColor.b / 255.0F; + dark.a = darkColor.a / 255.0F; if (effect) { for (int v = 0, vn = trianglesTwoColor.vertCount, vv = 0; v < vn; ++v, vv += 2) { - V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - Color lightCopy = light; - Color darkCopy = dark; - vertex->vertex.x = verts[vv]; - vertex->vertex.y = verts[vv + 1]; - vertex->texCoord.u = uvs[vv]; - vertex->texCoord.v = uvs[vv + 1]; + V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; + Color lightCopy = light; + Color darkCopy = dark; + vertex->vertex.x = verts[vv]; + vertex->vertex.y = verts[vv + 1]; + vertex->texCoord.u = uvs[vv]; + vertex->texCoord.v = uvs[vv + 1]; effect->transform(vertex->vertex.x, vertex->vertex.y, vertex->texCoord.u, vertex->texCoord.v, lightCopy, darkCopy); - vertex->color.r = lightCopy.r; - vertex->color.g = lightCopy.g; - vertex->color.b = lightCopy.b; - vertex->color.a = lightCopy.a; + vertex->color.r = lightCopy.r; + vertex->color.g = lightCopy.g; + vertex->color.b = lightCopy.b; + vertex->color.a = lightCopy.a; vertex->color2.r = darkCopy.r; vertex->color2.g = darkCopy.g; vertex->color2.b = darkCopy.b; @@ -757,18 +757,18 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } else { for (int v = 0, vn = trianglesTwoColor.vertCount, vv = 0; v < vn; ++v, vv += 2) { V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - vertex->vertex.x = verts[vv]; - vertex->vertex.y = verts[vv + 1]; - vertex->texCoord.u = uvs[vv]; - vertex->texCoord.v = uvs[vv + 1]; - vertex->color.r = light.r; - vertex->color.g = light.g; - vertex->color.b = light.b; - vertex->color.a = light.a; - vertex->color2.r = dark.r; - vertex->color2.g = dark.g; - vertex->color2.b = dark.b; - vertex->color2.a = dark.a; + vertex->vertex.x = verts[vv]; + vertex->vertex.y = verts[vv + 1]; + vertex->texCoord.u = uvs[vv]; + vertex->texCoord.v = uvs[vv + 1]; + vertex->color.r = light.r; + vertex->color.g = light.g; + vertex->color.b = light.b; + vertex->color.a = light.a; + vertex->color2.r = dark.r; + vertex->color2.g = dark.g; + vertex->color2.b = dark.b; + vertex->color2.a = dark.a; } } } else { @@ -778,21 +778,21 @@ void SkeletonRenderer::render(float /*deltaTime*/) { light.g = color.g / 255.0F; light.b = color.b / 255.0F; light.a = color.a / 255.0F; - dark.r = darkColor.r / 255.0F; - dark.g = darkColor.g / 255.0F; - dark.b = darkColor.b / 255.0F; - dark.a = darkColor.a / 255.0F; + dark.r = darkColor.r / 255.0F; + dark.g = darkColor.g / 255.0F; + dark.b = darkColor.b / 255.0F; + dark.a = darkColor.a / 255.0F; if (effect) { for (int v = 0, vn = trianglesTwoColor.vertCount; v < vn; ++v) { - V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - Color lightCopy = light; - Color darkCopy = dark; + V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; + Color lightCopy = light; + Color darkCopy = dark; effect->transform(vertex->vertex.x, vertex->vertex.y, vertex->texCoord.u, vertex->texCoord.v, lightCopy, darkCopy); - vertex->color.r = lightCopy.r; - vertex->color.g = lightCopy.g; - vertex->color.b = lightCopy.b; - vertex->color.a = lightCopy.a; + vertex->color.r = lightCopy.r; + vertex->color.g = lightCopy.g; + vertex->color.b = lightCopy.b; + vertex->color.a = lightCopy.a; vertex->color2.r = darkCopy.r; vertex->color2.g = darkCopy.g; vertex->color2.b = darkCopy.b; @@ -801,14 +801,14 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } else { for (int v = 0, vn = trianglesTwoColor.vertCount; v < vn; ++v) { V2F_T2F_C4F_C4F *vertex = trianglesTwoColor.verts + v; - vertex->color.r = light.r; - vertex->color.g = light.g; - vertex->color.b = light.b; - vertex->color.a = light.a; - vertex->color2.r = dark.r; - vertex->color2.g = dark.g; - vertex->color2.b = dark.b; - vertex->color2.a = dark.a; + vertex->color.r = light.r; + vertex->color.g = light.g; + vertex->color.b = light.b; + vertex->color.a = light.a; + vertex->color2.r = dark.r; + vertex->color2.g = dark.g; + vertex->color2.b = dark.b; + vertex->color2.a = dark.a; } } } @@ -824,10 +824,10 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (vbSize > 0 && ibSize > 0) { if (_batch) { - uint8_t * vbBuffer = vb.getCurBuffer(); - cc::Vec3 *point = nullptr; + uint8_t *vbBuffer = vb.getCurBuffer(); + cc::Vec3 *point = nullptr; for (unsigned int ii = 0, nn = vbSize; ii < nn; ii += vbs) { - point = reinterpret_cast(vbBuffer + ii); + point = reinterpret_cast(vbBuffer + ii); point->z = 0; //reset for z value point->transformMat4(*point, nodeWorldMat); } @@ -859,7 +859,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } if (_useAttach || _debugBones) { - auto & bones = _skeleton->getBones(); + auto &bones = _skeleton->getBones(); size_t bonesCount = bones.size(); cc::Mat4 boneMat = cc::Mat4::IDENTITY; @@ -872,10 +872,10 @@ void SkeletonRenderer::render(float /*deltaTime*/) { for (size_t i = 0, n = bonesCount; i < n; i++) { Bone *bone = bones[i]; - boneMat.m[0] = bone->getA(); - boneMat.m[1] = bone->getC(); - boneMat.m[4] = bone->getB(); - boneMat.m[5] = bone->getD(); + boneMat.m[0] = bone->getA(); + boneMat.m[1] = bone->getC(); + boneMat.m[4] = bone->getB(); + boneMat.m[5] = bone->getD(); boneMat.m[12] = bone->getWorldX(); boneMat.m[13] = bone->getWorldY(); attachInfo->checkSpace(sizeof(boneMat), true); @@ -883,8 +883,8 @@ void SkeletonRenderer::render(float /*deltaTime*/) { if (_debugBones) { float boneLength = bone->getData().getLength(); - float x = boneLength * bone->getA() + bone->getWorldX(); - float y = boneLength * bone->getC() + bone->getWorldY(); + float x = boneLength * bone->getA() + bone->getWorldX(); + float y = boneLength * bone->getC() + bone->getWorldY(); _debugBuffer->writeFloat32(bone->getWorldX()); _debugBuffer->writeFloat32(bone->getWorldY()); _debugBuffer->writeFloat32(x); @@ -906,11 +906,11 @@ void SkeletonRenderer::render(float /*deltaTime*/) { cc::Rect SkeletonRenderer::getBoundingBox() const { static cc::middleware::IOBuffer buffer(1024); - float * worldVertices = nullptr; - float minX = 999999.0F; - float minY = 999999.0F; - float maxX = -999999.0F; - float maxY = -999999.0F; + float *worldVertices = nullptr; + float minX = 999999.0F; + float minY = 999999.0F; + float maxX = -999999.0F; + float maxY = -999999.0F; for (int i = 0; i < _skeleton->getSlots().size(); ++i) { Slot *slot = _skeleton->getSlots()[i]; if (!slot->getAttachment()) continue; @@ -933,10 +933,10 @@ cc::Rect SkeletonRenderer::getBoundingBox() const { for (int ii = 0; ii < verticesCount; ii += 2) { float x = worldVertices[ii]; float y = worldVertices[ii + 1]; - minX = min(minX, x); - minY = min(minY, y); - maxX = max(maxX, x); - maxY = max(maxY, y); + minX = min(minX, x); + minY = min(minY, y); + maxX = max(maxX, x); + maxY = max(maxY, y); } } if (minX == 999999.0F) minX = minY = maxX = maxY = 0; @@ -1035,7 +1035,7 @@ void SkeletonRenderer::setVertexEffectDelegate(VertexEffectDelegate *effectDeleg void SkeletonRenderer::setSlotsRange(int startSlotIndex, int endSlotIndex) { this->_startSlotIndex = startSlotIndex; - this->_endSlotIndex = endSlotIndex; + this->_endSlotIndex = endSlotIndex; } spine::Skeleton *SkeletonRenderer::getSkeleton() const { diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h index 45373f0985..5dca07b529 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h @@ -53,14 +53,14 @@ public: static SkeletonRenderer *createWithData(SkeletonData *skeletonData, bool ownsSkeletonData = false); static SkeletonRenderer *createWithFile(const std::string &skeletonDataFile, const std::string &atlasFile, float scale = 1); - void update(float deltaTime) override {} - void render(float deltaTime) override; + void update(float deltaTime) override {} + void render(float deltaTime) override; virtual cc::Rect getBoundingBox() const; - uint32_t getRenderOrder() const override; + uint32_t getRenderOrder() const override; Skeleton *getSkeleton() const; - void setTimeScale(float scale); + void setTimeScale(float scale); float getTimeScale() const; void updateWorldTransform(); @@ -126,8 +126,8 @@ public: virtual void beginSchedule(); virtual void stopSchedule(); - void onEnable(); - void onDisable(); + void onEnable(); + void onDisable(); SkeletonRenderer(); explicit SkeletonRenderer(Skeleton *skeleton, bool ownsSkeleton = false, bool ownsSkeletonData = false, bool ownsAtlas = false); @@ -149,32 +149,32 @@ public: protected: void setSkeletonData(SkeletonData *skeletonData, bool ownsSkeletonData); - bool _ownsSkeletonData = false; - bool _ownsSkeleton = false; - bool _ownsAtlas = false; - Atlas * _atlas = nullptr; - AttachmentLoader * _attachmentLoader = nullptr; - Skeleton * _skeleton = nullptr; - VertexEffectDelegate *_effectDelegate = nullptr; - float _timeScale = 1; - bool _paused = false; + bool _ownsSkeletonData = false; + bool _ownsSkeleton = false; + bool _ownsAtlas = false; + Atlas *_atlas = nullptr; + AttachmentLoader *_attachmentLoader = nullptr; + Skeleton *_skeleton = nullptr; + VertexEffectDelegate *_effectDelegate = nullptr; + float _timeScale = 1; + bool _paused = false; - bool _batch = true; - bool _useAttach = false; - bool _debugMesh = false; - bool _debugSlots = false; - bool _debugBones = false; - cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; - bool _premultipliedAlpha = false; - SkeletonClipping * _clipper = nullptr; - bool _useTint = false; - std::string _uuid; + bool _batch = true; + bool _useAttach = false; + bool _debugMesh = false; + bool _debugSlots = false; + bool _debugBones = false; + cc::middleware::Color4F _nodeColor = cc::middleware::Color4F::WHITE; + bool _premultipliedAlpha = false; + SkeletonClipping *_clipper = nullptr; + bool _useTint = false; + std::string _uuid; int _startSlotIndex = -1; - int _endSlotIndex = -1; + int _endSlotIndex = -1; cc::middleware::IOTypedArray *_sharedBufferOffset = nullptr; - cc::middleware::IOTypedArray *_debugBuffer = nullptr; + cc::middleware::IOTypedArray *_debugBuffer = nullptr; // Js fill this buffer to send parameter to cpp, avoid to call jsb function. cc::middleware::IOTypedArray *_paramsBuffer = nullptr; }; diff --git a/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.h b/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.h index 0c489fa760..a4a077cf93 100644 --- a/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.h +++ b/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.h @@ -39,21 +39,21 @@ public: VertexEffectDelegate(); ~VertexEffectDelegate() override; JitterVertexEffect *initJitter(float jitterX, float jitterY); - SwirlVertexEffect * initSwirlWithPow(float radius, int power); - SwirlVertexEffect * initSwirlWithPowOut(float radius, int power); - VertexEffect * getVertexEffect() { + SwirlVertexEffect *initSwirlWithPow(float radius, int power); + SwirlVertexEffect *initSwirlWithPowOut(float radius, int power); + VertexEffect *getVertexEffect() { return _vertexEffect; } JitterVertexEffect *getJitterVertexEffect(); - SwirlVertexEffect * getSwirlVertexEffect(); - const std::string & getEffectType() const { + SwirlVertexEffect *getSwirlVertexEffect(); + const std::string &getEffectType() const { return _effectType; } void clear(); private: - VertexEffect * _vertexEffect = nullptr; + VertexEffect *_vertexEffect = nullptr; Interpolation *_interpolation = nullptr; - std::string _effectType = "none"; + std::string _effectType = "none"; }; } // namespace spine diff --git a/native/cocos/editor-support/spine-creator-support/spine-cocos2dx.cpp b/native/cocos/editor-support/spine-creator-support/spine-cocos2dx.cpp index d1898f0614..5be1bf59ca 100644 --- a/native/cocos/editor-support/spine-creator-support/spine-cocos2dx.cpp +++ b/native/cocos/editor-support/spine-creator-support/spine-cocos2dx.cpp @@ -35,12 +35,12 @@ namespace spine { static CustomTextureLoader customTextureLoader = nullptr; -void spAtlasPage_setCustomTextureLoader(CustomTextureLoader texLoader) { +void spAtlasPage_setCustomTextureLoader(CustomTextureLoader texLoader) { customTextureLoader = texLoader; } static SpineObjectDisposeCallback spineObjectDisposeCallback = nullptr; -void setSpineObjectDisposeCallback(SpineObjectDisposeCallback callback) { +void setSpineObjectDisposeCallback(SpineObjectDisposeCallback callback) { spineObjectDisposeCallback = callback; } } // namespace spine @@ -56,9 +56,9 @@ static void deleteAttachmentVertices(void *vertices) { static uint16_t quadTriangles[6] = {0, 1, 2, 2, 3, 0}; static void setAttachmentVertices(RegionAttachment *attachment) { - auto * region = static_cast(attachment->getRendererObject()); - auto * attachmentVertices = new AttachmentVertices(static_cast(region->page->getRendererObject()), 4, quadTriangles, 6); - V2F_T2F_C4F *vertices = attachmentVertices->_triangles->verts; + auto *region = static_cast(attachment->getRendererObject()); + auto *attachmentVertices = new AttachmentVertices(static_cast(region->page->getRendererObject()), 4, quadTriangles, 6); + V2F_T2F_C4F *vertices = attachmentVertices->_triangles->verts; for (int i = 0, ii = 0; i < 4; ++i, ii += 2) { vertices[i].texCoord.u = attachment->getUVs()[ii]; vertices[i].texCoord.v = attachment->getUVs()[ii + 1]; @@ -67,10 +67,10 @@ static void setAttachmentVertices(RegionAttachment *attachment) { } static void setAttachmentVertices(MeshAttachment *attachment) { - auto * region = static_cast(attachment->getRendererObject()); - auto * attachmentVertices = new AttachmentVertices(static_cast(region->page->getRendererObject()), + auto *region = static_cast(attachment->getRendererObject()); + auto *attachmentVertices = new AttachmentVertices(static_cast(region->page->getRendererObject()), static_cast(attachment->getWorldVerticesLength() >> 1), attachment->getTriangles().buffer(), static_cast(attachment->getTriangles().size())); - V2F_T2F_C4F *vertices = attachmentVertices->_triangles->verts; + V2F_T2F_C4F *vertices = attachmentVertices->_triangles->verts; for (size_t i = 0, ii = 0, nn = attachment->getWorldVerticesLength(); ii < nn; ++i, ii += 2) { vertices[i].texCoord.u = attachment->getUVs()[ii]; vertices[i].texCoord.v = attachment->getUVs()[ii + 1]; @@ -99,7 +99,7 @@ uint32_t filter(TextureFilter filter) { return static_cast(filter); } -Cocos2dTextureLoader::Cocos2dTextureLoader() = default; +Cocos2dTextureLoader::Cocos2dTextureLoader() = default; Cocos2dTextureLoader::~Cocos2dTextureLoader() = default; void Cocos2dTextureLoader::load(AtlasPage &page, const spine::String &path) { @@ -116,7 +116,7 @@ void Cocos2dTextureLoader::load(AtlasPage &page, const spine::String &path) { texture->setTexParameters(textureParams); page.setRendererObject(texture); - page.width = texture->getPixelsWide(); + page.width = texture->getPixelsWide(); page.height = texture->getPixelsHigh(); } } @@ -132,7 +132,7 @@ Cocos2dExtension::Cocos2dExtension() = default; Cocos2dExtension::~Cocos2dExtension() = default; char *Cocos2dExtension::_readFile(const spine::String &path, int *length) { - *length = 0; + *length = 0; Data data = FileUtils::getInstance()->getDataFromFile(FileUtils::getInstance()->fullPathForFilename(path.buffer())); if (data.isNull()) return nullptr; diff --git a/native/cocos/editor-support/spine/Animation.cpp b/native/cocos/editor-support/spine/Animation.cpp index bc4156cce0..5789033a13 100644 --- a/native/cocos/editor-support/spine/Animation.cpp +++ b/native/cocos/editor-support/spine/Animation.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -42,101 +42,99 @@ using namespace spine; -Animation::Animation(const String &name, Vector &timelines, float duration) : - _timelines(timelines), - _timelineIds(), - _duration(duration), - _name(name) { - assert(_name.length() > 0); - for (int i = 0; i < (int)timelines.size(); i++) - _timelineIds.put(timelines[i]->getPropertyId(), true); +Animation::Animation(const String &name, Vector &timelines, float duration) : _timelines(timelines), + _timelineIds(), + _duration(duration), + _name(name) { + assert(_name.length() > 0); + for (int i = 0; i < (int)timelines.size(); i++) + _timelineIds.put(timelines[i]->getPropertyId(), true); } bool Animation::hasTimeline(int id) { - return _timelineIds.containsKey(id); + return _timelineIds.containsKey(id); } Animation::~Animation() { - ContainerUtil::cleanUpVectorOfPointers(_timelines); + ContainerUtil::cleanUpVectorOfPointers(_timelines); } void Animation::apply(Skeleton &skeleton, float lastTime, float time, bool loop, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - if (loop && _duration != 0) { - time = MathUtil::fmod(time, _duration); - if (lastTime > 0) { - lastTime = MathUtil::fmod(lastTime, _duration); - } - } + MixBlend blend, MixDirection direction) { + if (loop && _duration != 0) { + time = MathUtil::fmod(time, _duration); + if (lastTime > 0) { + lastTime = MathUtil::fmod(lastTime, _duration); + } + } - for (size_t i = 0, n = _timelines.size(); i < n; ++i) { - _timelines[i]->apply(skeleton, lastTime, time, pEvents, alpha, blend, direction); - } + for (size_t i = 0, n = _timelines.size(); i < n; ++i) { + _timelines[i]->apply(skeleton, lastTime, time, pEvents, alpha, blend, direction); + } } const String &Animation::getName() { - return _name; + return _name; } Vector &Animation::getTimelines() { - return _timelines; + return _timelines; } float Animation::getDuration() { - return _duration; + return _duration; } void Animation::setDuration(float inValue) { - _duration = inValue; + _duration = inValue; } int Animation::binarySearch(Vector &values, float target, int step) { - int low = 0; - int size = (int)values.size(); - int high = size / step - 2; - if (high == 0) { - return step; - } + int low = 0; + int size = (int)values.size(); + int high = size / step - 2; + if (high == 0) { + return step; + } - int current = (int) (static_cast(high) >> 1); - while (true) { - if (values[(current + 1) * step] <= target) - low = current + 1; - else - high = current; + int current = (int)(static_cast(high) >> 1); + while (true) { + if (values[(current + 1) * step] <= target) + low = current + 1; + else + high = current; - if (low == high) return (low + 1) * step; + if (low == high) return (low + 1) * step; - current = (int) (static_cast(low + high) >> 1); - } + current = (int)(static_cast(low + high) >> 1); + } } int Animation::binarySearch(Vector &values, float target) { - int low = 0; - int size = (int)values.size(); - int high = size - 2; - if (high == 0) return 1; + int low = 0; + int size = (int)values.size(); + int high = size - 2; + if (high == 0) return 1; - int current = (int) (static_cast(high) >> 1); - while (true) { - if (values[(current + 1)] <= target) - low = current + 1; - else - high = current; + int current = (int)(static_cast(high) >> 1); + while (true) { + if (values[(current + 1)] <= target) + low = current + 1; + else + high = current; - if (low == high) return (low + 1); + if (low == high) return (low + 1); - current = (int) (static_cast(low + high) >> 1); - } + current = (int)(static_cast(low + high) >> 1); + } } int Animation::linearSearch(Vector &values, float target, int step) { - for (int i = 0, last = (int)values.size() - step; i <= last; i += step) { - if (values[i] > target) { - return i; - } - } + for (int i = 0, last = (int)values.size() - step; i <= last; i += step) { + if (values[i] > target) { + return i; + } + } - return -1; + return -1; } diff --git a/native/cocos/editor-support/spine/Animation.h b/native/cocos/editor-support/spine/Animation.h index 9e4004fcbb..072c286bdd 100644 --- a/native/cocos/editor-support/spine/Animation.h +++ b/native/cocos/editor-support/spine/Animation.h @@ -45,78 +45,76 @@ class Skeleton; class Event; class SP_API Animation : public SpineObject { - friend class AnimationState; + friend class AnimationState; - friend class TrackEntry; + friend class TrackEntry; - friend class AnimationStateData; + friend class AnimationStateData; - friend class AttachmentTimeline; + friend class AttachmentTimeline; - friend class ColorTimeline; + friend class ColorTimeline; - friend class DeformTimeline; + friend class DeformTimeline; - friend class DrawOrderTimeline; + friend class DrawOrderTimeline; - friend class EventTimeline; + friend class EventTimeline; - friend class IkConstraintTimeline; + friend class IkConstraintTimeline; - friend class PathConstraintMixTimeline; + friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; + friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; + friend class PathConstraintSpacingTimeline; - friend class RotateTimeline; + friend class RotateTimeline; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TransformConstraintTimeline; + friend class TransformConstraintTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; - friend class TwoColorTimeline; + friend class TwoColorTimeline; public: - Animation(const String &name, Vector &timelines, float duration); + Animation(const String &name, Vector &timelines, float duration); - ~Animation(); + ~Animation(); - /// Applies all the animation's timelines to the specified skeleton. - /// See also Timeline::apply(Skeleton&, float, float, Vector, float, MixPose, MixDirection) - void apply(Skeleton &skeleton, float lastTime, float time, bool loop, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction); + /// Applies all the animation's timelines to the specified skeleton. + /// See also Timeline::apply(Skeleton&, float, float, Vector, float, MixPose, MixDirection) + void apply(Skeleton &skeleton, float lastTime, float time, bool loop, Vector *pEvents, float alpha, + MixBlend blend, MixDirection direction); - const String &getName(); + const String &getName(); - Vector &getTimelines(); + Vector &getTimelines(); - bool hasTimeline(int id); - - float getDuration(); - - void setDuration(float inValue); + bool hasTimeline(int id); + float getDuration(); + void setDuration(float inValue); private: - Vector _timelines; - HashMap _timelineIds; - float _duration; - String _name; + Vector _timelines; + HashMap _timelineIds; + float _duration; + String _name; - /// @param target After the first and before the last entry. - static int binarySearch(Vector &values, float target, int step); + /// @param target After the first and before the last entry. + static int binarySearch(Vector &values, float target, int step); - /// @param target After the first and before the last entry. - static int binarySearch(Vector &values, float target); + /// @param target After the first and before the last entry. + static int binarySearch(Vector &values, float target); - static int linearSearch(Vector &values, float target, int step); + static int linearSearch(Vector &values, float target, int step); }; -} +} // namespace spine #endif /* Spine_Animation_h */ diff --git a/native/cocos/editor-support/spine/AnimationState.cpp b/native/cocos/editor-support/spine/AnimationState.cpp index 399a2521a7..b0894424cb 100644 --- a/native/cocos/editor-support/spine/AnimationState.cpp +++ b/native/cocos/editor-support/spine/AnimationState.cpp @@ -95,7 +95,7 @@ void TrackEntry::setAnimationEnd(float inValue) { _animationEnd = inValue; } float TrackEntry::getAnimationLast() { return _animationLast; } void TrackEntry::setAnimationLast(float inValue) { - _animationLast = inValue; + _animationLast = inValue; _nextAnimationLast = inValue; } @@ -156,20 +156,20 @@ void TrackEntry::resetRotationDirections() { } void TrackEntry::setListener(AnimationStateListener inValue) { - _listener = inValue; + _listener = inValue; _listenerObject = NULL; } void TrackEntry::setListener(AnimationStateListenerObject *inValue) { - _listener = dummyOnAnimationEventFunc; + _listener = dummyOnAnimationEventFunc; _listenerObject = inValue; } void TrackEntry::reset() { - _animation = NULL; - _next = NULL; + _animation = NULL; + _next = NULL; _mixingFrom = NULL; - _mixingTo = NULL; + _mixingTo = NULL; setRendererObject(NULL); @@ -177,7 +177,7 @@ void TrackEntry::reset() { _timelineHoldMix.clear(); _timelinesRotation.clear(); - _listener = dummyOnAnimationEventFunc; + _listener = dummyOnAnimationEventFunc; _listenerObject = NULL; } @@ -241,7 +241,7 @@ void EventQueue::drain() { // Don't cache _eventQueueEntries.size() so callbacks can queue their own events (eg, call setAnimation in AnimationState_Complete). for (size_t i = 0; i < _eventQueueEntries.size(); ++i) { EventQueueEntry *queueEntry = &_eventQueueEntries[i]; - TrackEntry * trackEntry = queueEntry->_entry; + TrackEntry *trackEntry = queueEntry->_entry; switch (queueEntry->_type) { case EventType_Start: @@ -297,10 +297,10 @@ void EventQueue::drain() { } const int Subsequent = 0; -const int First = 1; -const int Hold = 2; -const int HoldMix = 3; -const int NotLast = 4; +const int First = 1; +const int Hold = 2; +const int HoldMix = 3; +const int NotLast = 4; AnimationState::AnimationState(AnimationStateData *data) : _data(data), _queue(EventQueue::newEventQueue(*this, _trackEntryPool)), @@ -317,13 +317,13 @@ AnimationState::~AnimationState() { TrackEntry *from = entry->_mixingFrom; while (from) { TrackEntry *curr = from; - from = curr->_mixingFrom; + from = curr->_mixingFrom; delete curr; } TrackEntry *next = entry->_next; while (next) { TrackEntry *curr = next; - next = curr->_next; + next = curr->_next; delete curr; } delete entry; @@ -343,7 +343,7 @@ void AnimationState::update(float delta) { TrackEntry ¤t = *currentP; current._animationLast = current._nextAnimationLast; - current._trackLast = current._nextTrackLast; + current._trackLast = current._nextTrackLast; float currentDelta = delta * current._timeScale; @@ -352,7 +352,7 @@ void AnimationState::update(float delta) { if (current._delay > 0) { continue; } - currentDelta = -current._delay; + currentDelta = -current._delay; current._delay = 0; } @@ -382,7 +382,7 @@ void AnimationState::update(float delta) { if (current._mixingFrom != NULL && updateMixingFrom(currentP, delta)) { // End mixing from entries once all have completed. - TrackEntry *from = current._mixingFrom; + TrackEntry *from = current._mixingFrom; current._mixingFrom = NULL; if (from != NULL) from->_mixingTo = NULL; while (from != NULL) { @@ -411,7 +411,7 @@ bool AnimationState::apply(Skeleton &skeleton) { TrackEntry ¤t = *currentP; - applied = true; + applied = true; MixBlend blend = i == 0 ? MixBlend_First : current._mixBlend; // apply mixing from entries first. @@ -423,9 +423,9 @@ bool AnimationState::apply(Skeleton &skeleton) { } // apply current entry. - float animationLast = current._animationLast, animationTime = current.getAnimationTime(); - size_t timelineCount = current._animation->_timelines.size(); - Vector &timelines = current._animation->_timelines; + float animationLast = current._animationLast, animationTime = current.getAnimationTime(); + size_t timelineCount = current._animation->_timelines.size(); + Vector &timelines = current._animation->_timelines; if ((i == 0 && mix == 1) || blend == MixBlend_Add) { for (size_t ii = 0; ii < timelineCount; ++ii) timelines[ii]->apply(skeleton, animationLast, animationTime, &_events, mix, blend, MixDirection_In); @@ -455,7 +455,7 @@ bool AnimationState::apply(Skeleton &skeleton) { queueEvents(currentP, animationTime); _events.clear(); current._nextAnimationLast = animationTime; - current._nextTrackLast = current._trackTime; + current._nextTrackLast = current._trackTime; } _queue->drain(); @@ -463,7 +463,7 @@ bool AnimationState::apply(Skeleton &skeleton) { } void AnimationState::clearTracks() { - bool oldDrainDisabled = _queue->_drainDisabled; + bool oldDrainDisabled = _queue->_drainDisabled; _queue->_drainDisabled = true; for (size_t i = 0, n = _tracks.size(); i < n; ++i) clearTrack(i); @@ -489,8 +489,8 @@ void AnimationState::clearTrack(size_t trackIndex) { _queue->end(from); entry->_mixingFrom = NULL; - entry->_mixingTo = NULL; - entry = from; + entry->_mixingTo = NULL; + entry = from; } _tracks[current->_trackIndex] = NULL; @@ -507,8 +507,8 @@ TrackEntry *AnimationState::setAnimation(size_t trackIndex, const String &animat TrackEntry *AnimationState::setAnimation(size_t trackIndex, Animation *animation, bool loop) { assert(animation != NULL); - bool interrupt = true; - TrackEntry *current = expandToIndex(trackIndex); + bool interrupt = true; + TrackEntry *current = expandToIndex(trackIndex); if (current != NULL) { if (current->_nextTrackLast == -1) { // Don't mix from an entry that was never applied. @@ -516,7 +516,7 @@ TrackEntry *AnimationState::setAnimation(size_t trackIndex, Animation *animation _queue->interrupt(current); _queue->end(current); disposeNext(current); - current = current->_mixingFrom; + current = current->_mixingFrom; interrupt = false; } else { disposeNext(current); @@ -572,9 +572,9 @@ TrackEntry *AnimationState::addAnimation(size_t trackIndex, Animation *animation } TrackEntry *AnimationState::setEmptyAnimation(size_t trackIndex, float mixDuration) { - TrackEntry *entry = setAnimation(trackIndex, AnimationState::getEmptyAnimation(), false); + TrackEntry *entry = setAnimation(trackIndex, AnimationState::getEmptyAnimation(), false); entry->_mixDuration = mixDuration; - entry->_trackEnd = mixDuration; + entry->_trackEnd = mixDuration; return entry; } @@ -583,14 +583,14 @@ TrackEntry *AnimationState::addEmptyAnimation(size_t trackIndex, float mixDurati delay -= mixDuration; } - TrackEntry *entry = addAnimation(trackIndex, AnimationState::getEmptyAnimation(), false, delay); + TrackEntry *entry = addAnimation(trackIndex, AnimationState::getEmptyAnimation(), false, delay); entry->_mixDuration = mixDuration; - entry->_trackEnd = mixDuration; + entry->_trackEnd = mixDuration; return entry; } void AnimationState::setEmptyAnimations(float mixDuration) { - bool oldDrainDisabled = _queue->_drainDisabled; + bool oldDrainDisabled = _queue->_drainDisabled; _queue->_drainDisabled = true; for (size_t i = 0, n = _tracks.size(); i < n; ++i) { TrackEntry *current = _tracks[i]; @@ -623,12 +623,12 @@ void AnimationState::setTimeScale(float inValue) { } void AnimationState::setListener(AnimationStateListener inValue) { - _listener = inValue; + _listener = inValue; _listenerObject = NULL; } void AnimationState::setListener(AnimationStateListenerObject *inValue) { - _listener = dummyOnAnimationEventFunc; + _listener = dummyOnAnimationEventFunc; _listenerObject = inValue; } @@ -641,7 +641,7 @@ void AnimationState::enableQueue() { Animation *AnimationState::getEmptyAnimation() { static Vector timelines; - static Animation ret(String(""), timelines, 0); + static Animation ret(String(""), timelines, 0); return &ret; } @@ -657,7 +657,7 @@ void AnimationState::applyRotateTimeline(RotateTimeline *rotateTimeline, Skeleto Bone *bone = skeleton._bones[rotateTimeline->_boneIndex]; if (!bone->isActive()) return; Vector &frames = rotateTimeline->_frames; - float r1, r2; + float r1, r2; if (time < frames[0]) { switch (blend) { case MixBlend_Setup: @@ -675,13 +675,13 @@ void AnimationState::applyRotateTimeline(RotateTimeline *rotateTimeline, Skeleto r2 = bone->_data._rotation + frames[frames.size() + RotateTimeline::PREV_ROTATION]; } else { // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(frames, time, RotateTimeline::ENTRIES); + int frame = Animation::binarySearch(frames, time, RotateTimeline::ENTRIES); float prevRotation = frames[frame + RotateTimeline::PREV_ROTATION]; - float frameTime = frames[frame]; - float percent = rotateTimeline->getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + + float frameTime = frames[frame]; + float percent = rotateTimeline->getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline::PREV_TIME] - frameTime)); - r2 = frames[frame + RotateTimeline::ROTATION] - prevRotation; + r2 = frames[frame + RotateTimeline::ROTATION] - prevRotation; r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; r2 = prevRotation + r2 * percent + bone->_data._rotation; r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; @@ -697,10 +697,10 @@ void AnimationState::applyRotateTimeline(RotateTimeline *rotateTimeline, Skeleto float lastTotal, lastDiff; if (firstFrame) { lastTotal = 0; - lastDiff = diff; + lastDiff = diff; } else { - lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops. - lastDiff = timelinesRotation[i + 1]; // Difference between bones. + lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops. + lastDiff = timelinesRotation[i + 1]; // Difference between bones. } bool current = diff > 0, dir = lastTotal >= 0; @@ -731,7 +731,7 @@ bool AnimationState::updateMixingFrom(TrackEntry *to, float delta) { bool finished = updateMixingFrom(from, delta); from->_animationLast = from->_nextAnimationLast; - from->_trackLast = from->_nextTrackLast; + from->_trackLast = from->_nextTrackLast; // Require mixTime > 0 to ensure the mixing from entry was applied at least once. if (to->_mixTime > 0 && to->_mixTime >= to->_mixDuration) { @@ -768,18 +768,18 @@ float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBle if (blend != MixBlend_First) blend = from->_mixBlend; } - Vector * eventBuffer = mix < from->_eventThreshold ? &_events : NULL; - bool attachments = mix < from->_attachmentThreshold, drawOrder = mix < from->_drawOrderThreshold; - float animationLast = from->_animationLast, animationTime = from->getAnimationTime(); - Vector &timelines = from->_animation->_timelines; - size_t timelineCount = timelines.size(); - float alphaHold = from->_alpha * to->_interruptAlpha, alphaMix = alphaHold * (1 - mix); + Vector *eventBuffer = mix < from->_eventThreshold ? &_events : NULL; + bool attachments = mix < from->_attachmentThreshold, drawOrder = mix < from->_drawOrderThreshold; + float animationLast = from->_animationLast, animationTime = from->getAnimationTime(); + Vector &timelines = from->_animation->_timelines; + size_t timelineCount = timelines.size(); + float alphaHold = from->_alpha * to->_interruptAlpha, alphaMix = alphaHold * (1 - mix); if (blend == MixBlend_Add) { for (size_t i = 0; i < timelineCount; i++) timelines[i]->apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection_Out); } else { - Vector & timelineMode = from->_timelineMode; + Vector &timelineMode = from->_timelineMode; Vector &timelineHoldMix = from->_timelineHoldMix; bool firstFrame = from->_timelinesRotation.size() == 0; @@ -789,10 +789,10 @@ float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBle from->_totalAlpha = 0; for (size_t i = 0; i < timelineCount; i++) { - Timeline * timeline = timelines[i]; + Timeline *timeline = timelines[i]; MixDirection direction = MixDirection_Out; - MixBlend timelineBlend; - float alpha; + MixBlend timelineBlend; + float alpha; switch (timelineMode[i] & (NotLast - 1)) { case Subsequent: timelineBlend = blend; @@ -805,16 +805,16 @@ float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBle break; case First: timelineBlend = MixBlend_Setup; - alpha = alphaMix; + alpha = alphaMix; break; case Hold: timelineBlend = MixBlend_Setup; - alpha = alphaHold; + alpha = alphaHold; break; default: - timelineBlend = MixBlend_Setup; + timelineBlend = MixBlend_Setup; TrackEntry *holdMix = timelineHoldMix[i]; - alpha = alphaHold * MathUtil::max(0.0f, 1.0f - holdMix->_mixTime / holdMix->_mixDuration); + alpha = alphaHold * MathUtil::max(0.0f, 1.0f - holdMix->_mixTime / holdMix->_mixDuration); break; } from->_totalAlpha += alpha; @@ -839,14 +839,14 @@ float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBle _events.clear(); from->_nextAnimationLast = animationTime; - from->_nextTrackLast = from->_trackTime; + from->_nextTrackLast = from->_trackTime; return mix; } void AnimationState::queueEvents(TrackEntry *entry, float animationTime) { float animationStart = entry->_animationStart, animationEnd = entry->_animationEnd; - float duration = animationEnd - animationStart; + float duration = animationEnd - animationStart; float trackLastWrapped = MathUtil::fmod(entry->_trackLast, duration); // Queue events before complete. @@ -876,14 +876,14 @@ void AnimationState::queueEvents(TrackEntry *entry, float animationTime) { void AnimationState::setCurrent(size_t index, TrackEntry *current, bool interrupt) { TrackEntry *from = expandToIndex(index); - _tracks[index] = current; + _tracks[index] = current; if (from != NULL) { if (interrupt) _queue->interrupt(from); current->_mixingFrom = from; - from->_mixingTo = current; - current->_mixTime = 0; + from->_mixingTo = current; + current->_mixTime = 0; // Store interrupted mix percentage. if (from->_mixingFrom != NULL && from->_mixDuration > 0) { @@ -905,33 +905,33 @@ TrackEntry *AnimationState::expandToIndex(size_t index) { TrackEntry *AnimationState::newTrackEntry(size_t trackIndex, Animation *animation, bool loop, TrackEntry *last) { TrackEntry *entryP = _trackEntryPool.obtain(); // Pooling - TrackEntry &entry = *entryP; + TrackEntry &entry = *entryP; - entry._trackIndex = trackIndex; - entry._animation = animation; - entry._loop = loop; + entry._trackIndex = trackIndex; + entry._animation = animation; + entry._loop = loop; entry._holdPrevious = 0; - entry._eventThreshold = 0; + entry._eventThreshold = 0; entry._attachmentThreshold = 0; - entry._drawOrderThreshold = 0; + entry._drawOrderThreshold = 0; - entry._animationStart = 0; - entry._animationEnd = animation->getDuration(); - entry._animationLast = -1; + entry._animationStart = 0; + entry._animationEnd = animation->getDuration(); + entry._animationLast = -1; entry._nextAnimationLast = -1; - entry._delay = 0; - entry._trackTime = 0; - entry._trackLast = -1; - entry._nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet. - entry._trackEnd = FLT_MAX; // loop ? float.MaxValue : animation.Duration; - entry._timeScale = 1; + entry._delay = 0; + entry._trackTime = 0; + entry._trackLast = -1; + entry._nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet. + entry._trackEnd = FLT_MAX; // loop ? float.MaxValue : animation.Duration; + entry._timeScale = 1; - entry._alpha = 1; + entry._alpha = 1; entry._interruptAlpha = 1; - entry._mixTime = 0; - entry._mixDuration = (last == NULL) ? 0 : _data->getMix(last->_animation, animation); + entry._mixTime = 0; + entry._mixDuration = (last == NULL) ? 0 : _data->getMix(last->_animation, animation); return entryP; } @@ -974,10 +974,10 @@ void AnimationState::animationsChanged() { } void AnimationState::computeHold(TrackEntry *entry) { - TrackEntry * to = entry->_mixingTo; - Vector &timelines = entry->_animation->_timelines; - size_t timelinesCount = timelines.size(); - Vector & timelineMode = entry->_timelineMode; + TrackEntry *to = entry->_mixingTo; + Vector &timelines = entry->_animation->_timelines; + size_t timelinesCount = timelines.size(); + Vector &timelineMode = entry->_timelineMode; timelineMode.setSize(timelinesCount, 0); Vector &timelineHoldMix = entry->_timelineHoldMix; timelineHoldMix.setSize(timelinesCount, 0); @@ -996,7 +996,7 @@ void AnimationState::computeHold(TrackEntry *entry) { continue_outer: for (; i < timelinesCount; ++i) { Timeline *timeline = timelines[i]; - int id = timeline->getPropertyId(); + int id = timeline->getPropertyId(); if (_propertyIDs.containsKey(id)) { timelineMode[i] = Subsequent; } else { @@ -1010,7 +1010,7 @@ continue_outer: for (TrackEntry *next = to->_mixingTo; next != NULL; next = next->_mixingTo) { if (next->_animation->hasTimeline(id)) continue; if (entry->_mixDuration > 0) { - timelineMode[i] = HoldMix; + timelineMode[i] = HoldMix; timelineHoldMix[i] = entry; i++; goto continue_outer; // continue outer; @@ -1024,9 +1024,9 @@ continue_outer: } void AnimationState::computeNotLast(TrackEntry *entry) { - Vector &timelines = entry->_animation->_timelines; - size_t timelinesCount = timelines.size(); - Vector & timelineMode = entry->_timelineMode; + Vector &timelines = entry->_animation->_timelines; + size_t timelinesCount = timelines.size(); + Vector &timelineMode = entry->_timelineMode; for (size_t i = 0; i < timelinesCount; i++) { if (timelines[i]->getRTTI().isExactly(AttachmentTimeline::rtti)) { diff --git a/native/cocos/editor-support/spine/AnimationState.h b/native/cocos/editor-support/spine/AnimationState.h index 818d3e3663..208a2cc4db 100644 --- a/native/cocos/editor-support/spine/AnimationState.h +++ b/native/cocos/editor-support/spine/AnimationState.h @@ -38,398 +38,398 @@ #include #ifdef SPINE_USE_STD_FUNCTION -#include + #include #endif namespace spine { - enum EventType { - EventType_Start, - EventType_Interrupt, - EventType_End, - EventType_Complete, - EventType_Dispose, - EventType_Event - }; +enum EventType { + EventType_Start, + EventType_Interrupt, + EventType_End, + EventType_Complete, + EventType_Dispose, + EventType_Event +}; - class AnimationState; - class TrackEntry; +class AnimationState; +class TrackEntry; - class Animation; - class Event; - class AnimationStateData; - class Skeleton; - class RotateTimeline; +class Animation; +class Event; +class AnimationStateData; +class Skeleton; +class RotateTimeline; #ifdef SPINE_USE_STD_FUNCTION - typedef std::function AnimationStateListener; +typedef std::function AnimationStateListener; #else - typedef void (*AnimationStateListener) (AnimationState* state, EventType type, TrackEntry* entry, Event* event); +typedef void (*AnimationStateListener)(AnimationState* state, EventType type, TrackEntry* entry, Event* event); #endif - /// Abstract class to inherit from to create a callback object - class SP_API AnimationStateListenerObject { - public: - AnimationStateListenerObject() { }; - virtual ~AnimationStateListenerObject() { }; - public: - /// The callback function to be called - virtual void callback(AnimationState* state, EventType type, TrackEntry* entry, Event* event) = 0; - }; - - /// State for the playback of an animation - class SP_API TrackEntry : public SpineObject, public HasRendererObject { - friend class EventQueue; - friend class AnimationState; - - public: - TrackEntry(); - - virtual ~TrackEntry(); - - /// The index of the track where this entry is either current or queued. - int getTrackIndex(); - - /// The animation to apply for this track entry. - Animation* getAnimation(); - - /// If true, the animation will repeat. If false, it will not, instead its last frame is applied if played beyond its duration. - bool getLoop(); - void setLoop(bool inValue); - - /// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead - /// of being mixed out. - /// - /// When mixing between animations that key the same property, if a lower track also keys that property then the value will - /// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0% - /// while the second animation mixes from 0% to 100%. Setting holdPrevious to true applies the first animation - /// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which - /// keys the property, only when a higher track also keys the property. - /// - /// Snapping will occur if holdPrevious is true and this animation does not key all the same properties as the - /// previous animation. - bool getHoldPrevious(); - void setHoldPrevious(bool inValue); - - /// Seconds to postpone playing the animation. When a track entry is the current track entry, delay postpones incrementing - /// the track time. When a track entry is queued, delay is the time from the start of the previous animation to when the - /// track entry will become the current track entry. - float getDelay(); - void setDelay(float inValue); - - /// Current time in seconds this track entry has been the current track entry. The track time determines - /// TrackEntry.AnimationTime. The track time can be set to start the animation at a time other than 0, without affecting looping. - float getTrackTime(); - void setTrackTime(float inValue); - - /// The track time in seconds when this animation will be removed from the track. Defaults to the animation duration for - /// non-looping animations and to int.MaxValue for looping animations. If the track end time is reached and no - /// other animations are queued for playback, and mixing from any previous animations is complete, properties keyed by the animation, - /// are set to the setup pose and the track is cleared. - /// - /// It may be desired to use AnimationState.addEmptyAnimation(int, float, float) to mix the properties back to the - /// setup pose over time, rather than have it happen instantly. - float getTrackEnd(); - void setTrackEnd(float inValue); - - /// Seconds when this animation starts, both initially and after looping. Defaults to 0. - /// - /// When changing the animation start time, it often makes sense to set TrackEntry.AnimationLast to the same value to - /// prevent timeline keys before the start time from triggering. - float getAnimationStart(); - void setAnimationStart(float inValue); - - /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will - /// loop back to TrackEntry.AnimationStart at this time. Defaults to the animation duration. - float getAnimationEnd(); - void setAnimationEnd(float inValue); - - /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this - /// animation is applied, event timelines will fire all events between the animation last time (exclusive) and animation time - /// (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation is applied. - float getAnimationLast(); - void setAnimationLast(float inValue); - - /// Uses TrackEntry.TrackTime to compute the animation time between TrackEntry.AnimationStart. and - /// TrackEntry.AnimationEnd. When the track time is 0, the animation time is equal to the animation start time. - float getAnimationTime(); - - /// Multiplier for the delta time when the animation state is updated, causing time for this animation to play slower or - /// faster. Defaults to 1. - float getTimeScale(); - void setTimeScale(float inValue); - - /// Values less than 1 mix this animation with the last skeleton pose. Defaults to 1, which overwrites the last skeleton pose with - /// this animation. - /// - /// Typically track 0 is used to completely pose the skeleton, then alpha can be used on higher tracks. It doesn't make sense - /// to use alpha on track 0 if the skeleton pose is from the last frame render. - float getAlpha(); - void setAlpha(float inValue); - - /// - /// When the mix percentage (mix time / mix duration) is less than the event threshold, event timelines for the animation - /// being mixed out will be applied. Defaults to 0, so event timelines are not applied for an animation being mixed out. - float getEventThreshold(); - void setEventThreshold(float inValue); - - /// When the mix percentage (mix time / mix duration) is less than the attachment threshold, attachment timelines for the - /// animation being mixed out will be applied. Defaults to 0, so attachment timelines are not applied for an animation being - /// mixed out. - float getAttachmentThreshold(); - void setAttachmentThreshold(float inValue); - - /// When the mix percentage (mix time / mix duration) is less than the draw order threshold, draw order timelines for the - /// animation being mixed out will be applied. Defaults to 0, so draw order timelines are not applied for an animation being - /// mixed out. - float getDrawOrderThreshold(); - void setDrawOrderThreshold(float inValue); - - /// The animation queued to start after this animation, or NULL. - TrackEntry* getNext(); - - /// Returns true if at least one loop has been completed. - bool isComplete(); - - /// Seconds from 0 to the mix duration when mixing from the previous animation to this animation. May be slightly more than - /// TrackEntry.MixDuration when the mix is complete. - float getMixTime(); - void setMixTime(float inValue); - - /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by - /// AnimationStateData based on the animation before this animation (if any). - /// - /// The mix duration can be set manually rather than use the value from AnimationStateData.GetMix. - /// In that case, the mixDuration must be set before AnimationState.update(float) is next called. - /// - /// When using AnimationState::addAnimation(int, Animation, bool, float) with a delay - /// less than or equal to 0, note the Delay is set using the mix duration from the AnimationStateData - float getMixDuration(); - void setMixDuration(float inValue); - - MixBlend getMixBlend(); - void setMixBlend(MixBlend blend); - - /// The track entry for the previous animation when mixing from the previous animation to this animation, or NULL if no - /// mixing is currently occuring. When mixing from multiple animations, MixingFrom makes up a double linked list with MixingTo. - TrackEntry* getMixingFrom(); - - /// The track entry for the next animation when mixing from this animation, or NULL if no mixing is currently occuring. - /// When mixing from multiple animations, MixingTo makes up a double linked list with MixingFrom. - TrackEntry* getMixingTo(); - - /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the - /// long way around when using alpha and starting animations on other tracks. - /// - /// Mixing involves finding a rotation between two others, which has two possible solutions: the short way or the long way around. - /// The two rotations likely change over time, so which direction is the short or long way also changes. - /// If the short way was always chosen, bones would flip to the other side when that direction became the long way. - /// TrackEntry chooses the short way the first time it is applied and remembers that direction. - void resetRotationDirections(); - - void setListener(AnimationStateListener listener); - - void setListener(AnimationStateListenerObject* listener); - - private: - Animation* _animation; - - TrackEntry* _next; - TrackEntry* _mixingFrom; - TrackEntry* _mixingTo; - int _trackIndex; - - bool _loop, _holdPrevious; - float _eventThreshold, _attachmentThreshold, _drawOrderThreshold; - float _animationStart, _animationEnd, _animationLast, _nextAnimationLast; - float _delay, _trackTime, _trackLast, _nextTrackLast, _trackEnd, _timeScale; - float _alpha, _mixTime, _mixDuration, _interruptAlpha, _totalAlpha; - MixBlend _mixBlend; - Vector _timelineMode; - Vector _timelineHoldMix; - Vector _timelinesRotation; - AnimationStateListener _listener; - AnimationStateListenerObject* _listenerObject; - - void reset(); - }; - - class SP_API EventQueueEntry : public SpineObject { - friend class EventQueue; - - public: - EventType _type; - TrackEntry* _entry; - Event* _event; - - EventQueueEntry(EventType eventType, TrackEntry* trackEntry, Event* event = NULL); - }; - - class SP_API EventQueue : public SpineObject { - friend class AnimationState; - - private: - Vector _eventQueueEntries; - AnimationState& _state; - Pool& _trackEntryPool; - bool _drainDisabled; - - static EventQueue* newEventQueue(AnimationState& state, Pool& trackEntryPool); - - static EventQueueEntry newEventQueueEntry(EventType eventType, TrackEntry* entry, Event* event = NULL); - - EventQueue(AnimationState& state, Pool& trackEntryPool); - - ~EventQueue(); +/// Abstract class to inherit from to create a callback object +class SP_API AnimationStateListenerObject { +public: + AnimationStateListenerObject(){}; + virtual ~AnimationStateListenerObject(){}; + +public: + /// The callback function to be called + virtual void callback(AnimationState* state, EventType type, TrackEntry* entry, Event* event) = 0; +}; + +/// State for the playback of an animation +class SP_API TrackEntry : public SpineObject, public HasRendererObject { + friend class EventQueue; + friend class AnimationState; + +public: + TrackEntry(); + + virtual ~TrackEntry(); + + /// The index of the track where this entry is either current or queued. + int getTrackIndex(); + + /// The animation to apply for this track entry. + Animation* getAnimation(); + + /// If true, the animation will repeat. If false, it will not, instead its last frame is applied if played beyond its duration. + bool getLoop(); + void setLoop(bool inValue); + + /// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead + /// of being mixed out. + /// + /// When mixing between animations that key the same property, if a lower track also keys that property then the value will + /// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0% + /// while the second animation mixes from 0% to 100%. Setting holdPrevious to true applies the first animation + /// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which + /// keys the property, only when a higher track also keys the property. + /// + /// Snapping will occur if holdPrevious is true and this animation does not key all the same properties as the + /// previous animation. + bool getHoldPrevious(); + void setHoldPrevious(bool inValue); + + /// Seconds to postpone playing the animation. When a track entry is the current track entry, delay postpones incrementing + /// the track time. When a track entry is queued, delay is the time from the start of the previous animation to when the + /// track entry will become the current track entry. + float getDelay(); + void setDelay(float inValue); + + /// Current time in seconds this track entry has been the current track entry. The track time determines + /// TrackEntry.AnimationTime. The track time can be set to start the animation at a time other than 0, without affecting looping. + float getTrackTime(); + void setTrackTime(float inValue); + + /// The track time in seconds when this animation will be removed from the track. Defaults to the animation duration for + /// non-looping animations and to int.MaxValue for looping animations. If the track end time is reached and no + /// other animations are queued for playback, and mixing from any previous animations is complete, properties keyed by the animation, + /// are set to the setup pose and the track is cleared. + /// + /// It may be desired to use AnimationState.addEmptyAnimation(int, float, float) to mix the properties back to the + /// setup pose over time, rather than have it happen instantly. + float getTrackEnd(); + void setTrackEnd(float inValue); + + /// Seconds when this animation starts, both initially and after looping. Defaults to 0. + /// + /// When changing the animation start time, it often makes sense to set TrackEntry.AnimationLast to the same value to + /// prevent timeline keys before the start time from triggering. + float getAnimationStart(); + void setAnimationStart(float inValue); + + /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will + /// loop back to TrackEntry.AnimationStart at this time. Defaults to the animation duration. + float getAnimationEnd(); + void setAnimationEnd(float inValue); + + /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this + /// animation is applied, event timelines will fire all events between the animation last time (exclusive) and animation time + /// (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation is applied. + float getAnimationLast(); + void setAnimationLast(float inValue); + + /// Uses TrackEntry.TrackTime to compute the animation time between TrackEntry.AnimationStart. and + /// TrackEntry.AnimationEnd. When the track time is 0, the animation time is equal to the animation start time. + float getAnimationTime(); + + /// Multiplier for the delta time when the animation state is updated, causing time for this animation to play slower or + /// faster. Defaults to 1. + float getTimeScale(); + void setTimeScale(float inValue); + + /// Values less than 1 mix this animation with the last skeleton pose. Defaults to 1, which overwrites the last skeleton pose with + /// this animation. + /// + /// Typically track 0 is used to completely pose the skeleton, then alpha can be used on higher tracks. It doesn't make sense + /// to use alpha on track 0 if the skeleton pose is from the last frame render. + float getAlpha(); + void setAlpha(float inValue); + + /// + /// When the mix percentage (mix time / mix duration) is less than the event threshold, event timelines for the animation + /// being mixed out will be applied. Defaults to 0, so event timelines are not applied for an animation being mixed out. + float getEventThreshold(); + void setEventThreshold(float inValue); + + /// When the mix percentage (mix time / mix duration) is less than the attachment threshold, attachment timelines for the + /// animation being mixed out will be applied. Defaults to 0, so attachment timelines are not applied for an animation being + /// mixed out. + float getAttachmentThreshold(); + void setAttachmentThreshold(float inValue); + + /// When the mix percentage (mix time / mix duration) is less than the draw order threshold, draw order timelines for the + /// animation being mixed out will be applied. Defaults to 0, so draw order timelines are not applied for an animation being + /// mixed out. + float getDrawOrderThreshold(); + void setDrawOrderThreshold(float inValue); + + /// The animation queued to start after this animation, or NULL. + TrackEntry* getNext(); + + /// Returns true if at least one loop has been completed. + bool isComplete(); + + /// Seconds from 0 to the mix duration when mixing from the previous animation to this animation. May be slightly more than + /// TrackEntry.MixDuration when the mix is complete. + float getMixTime(); + void setMixTime(float inValue); + + /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by + /// AnimationStateData based on the animation before this animation (if any). + /// + /// The mix duration can be set manually rather than use the value from AnimationStateData.GetMix. + /// In that case, the mixDuration must be set before AnimationState.update(float) is next called. + /// + /// When using AnimationState::addAnimation(int, Animation, bool, float) with a delay + /// less than or equal to 0, note the Delay is set using the mix duration from the AnimationStateData + float getMixDuration(); + void setMixDuration(float inValue); + + MixBlend getMixBlend(); + void setMixBlend(MixBlend blend); + + /// The track entry for the previous animation when mixing from the previous animation to this animation, or NULL if no + /// mixing is currently occuring. When mixing from multiple animations, MixingFrom makes up a double linked list with MixingTo. + TrackEntry* getMixingFrom(); + + /// The track entry for the next animation when mixing from this animation, or NULL if no mixing is currently occuring. + /// When mixing from multiple animations, MixingTo makes up a double linked list with MixingFrom. + TrackEntry* getMixingTo(); + + /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the + /// long way around when using alpha and starting animations on other tracks. + /// + /// Mixing involves finding a rotation between two others, which has two possible solutions: the short way or the long way around. + /// The two rotations likely change over time, so which direction is the short or long way also changes. + /// If the short way was always chosen, bones would flip to the other side when that direction became the long way. + /// TrackEntry chooses the short way the first time it is applied and remembers that direction. + void resetRotationDirections(); + + void setListener(AnimationStateListener listener); + + void setListener(AnimationStateListenerObject* listener); + +private: + Animation* _animation; + + TrackEntry* _next; + TrackEntry* _mixingFrom; + TrackEntry* _mixingTo; + int _trackIndex; + + bool _loop, _holdPrevious; + float _eventThreshold, _attachmentThreshold, _drawOrderThreshold; + float _animationStart, _animationEnd, _animationLast, _nextAnimationLast; + float _delay, _trackTime, _trackLast, _nextTrackLast, _trackEnd, _timeScale; + float _alpha, _mixTime, _mixDuration, _interruptAlpha, _totalAlpha; + MixBlend _mixBlend; + Vector _timelineMode; + Vector _timelineHoldMix; + Vector _timelinesRotation; + AnimationStateListener _listener; + AnimationStateListenerObject* _listenerObject; + + void reset(); +}; + +class SP_API EventQueueEntry : public SpineObject { + friend class EventQueue; + +public: + EventType _type; + TrackEntry* _entry; + Event* _event; + + EventQueueEntry(EventType eventType, TrackEntry* trackEntry, Event* event = NULL); +}; + +class SP_API EventQueue : public SpineObject { + friend class AnimationState; + +private: + Vector _eventQueueEntries; + AnimationState& _state; + Pool& _trackEntryPool; + bool _drainDisabled; + + static EventQueue* newEventQueue(AnimationState& state, Pool& trackEntryPool); + + static EventQueueEntry newEventQueueEntry(EventType eventType, TrackEntry* entry, Event* event = NULL); + + EventQueue(AnimationState& state, Pool& trackEntryPool); + + ~EventQueue(); - void start(TrackEntry* entry); + void start(TrackEntry* entry); - void interrupt(TrackEntry* entry); + void interrupt(TrackEntry* entry); - void end(TrackEntry* entry); + void end(TrackEntry* entry); - void dispose(TrackEntry* entry); + void dispose(TrackEntry* entry); - void complete(TrackEntry* entry); + void complete(TrackEntry* entry); + + void event(TrackEntry* entry, Event* event); - void event(TrackEntry* entry, Event* event); + /// Raises all events in the queue and drains the queue. + void drain(); +}; - /// Raises all events in the queue and drains the queue. - void drain(); - }; +class SP_API AnimationState : public SpineObject, public HasRendererObject { + friend class TrackEntry; + friend class EventQueue; - class SP_API AnimationState : public SpineObject, public HasRendererObject { - friend class TrackEntry; - friend class EventQueue; +public: + explicit AnimationState(AnimationStateData* data); - public: - explicit AnimationState(AnimationStateData* data); + ~AnimationState(); - ~AnimationState(); + /// Increments the track entry times, setting queued animations as current if needed + /// @param delta delta time + void update(float delta); - /// Increments the track entry times, setting queued animations as current if needed - /// @param delta delta time - void update(float delta); + /// Poses the skeleton using the track entry animations. There are no side effects other than invoking listeners, so the + /// animation state can be applied to multiple skeletons to pose them identically. + bool apply(Skeleton& skeleton); - /// Poses the skeleton using the track entry animations. There are no side effects other than invoking listeners, so the - /// animation state can be applied to multiple skeletons to pose them identically. - bool apply(Skeleton& skeleton); + /// Removes all animations from all tracks, leaving skeletons in their previous pose. + /// It may be desired to use AnimationState.setEmptyAnimations(float) to mix the skeletons back to the setup pose, + /// rather than leaving them in their previous pose. + void clearTracks(); - /// Removes all animations from all tracks, leaving skeletons in their previous pose. - /// It may be desired to use AnimationState.setEmptyAnimations(float) to mix the skeletons back to the setup pose, - /// rather than leaving them in their previous pose. - void clearTracks(); + /// Removes all animations from the tracks, leaving skeletons in their previous pose. + /// It may be desired to use AnimationState.setEmptyAnimations(float) to mix the skeletons back to the setup pose, + /// rather than leaving them in their previous pose. + void clearTrack(size_t trackIndex); - /// Removes all animations from the tracks, leaving skeletons in their previous pose. - /// It may be desired to use AnimationState.setEmptyAnimations(float) to mix the skeletons back to the setup pose, - /// rather than leaving them in their previous pose. - void clearTrack(size_t trackIndex); + /// Sets an animation by name. setAnimation(int, Animation, bool) + TrackEntry* setAnimation(size_t trackIndex, const String& animationName, bool loop); - /// Sets an animation by name. setAnimation(int, Animation, bool) - TrackEntry* setAnimation(size_t trackIndex, const String& animationName, bool loop); + /// Sets the current animation for a track, discarding any queued animations. + /// @param loop If true, the animation will repeat. + /// If false, it will not, instead its last frame is applied if played beyond its duration. + /// In either case TrackEntry.TrackEnd determines when the track is cleared. + /// @return + /// A track entry to allow further customization of animation playback. References to the track entry must not be kept + /// after AnimationState.Dispose. + TrackEntry* setAnimation(size_t trackIndex, Animation* animation, bool loop); - /// Sets the current animation for a track, discarding any queued animations. - /// @param loop If true, the animation will repeat. - /// If false, it will not, instead its last frame is applied if played beyond its duration. - /// In either case TrackEntry.TrackEnd determines when the track is cleared. - /// @return - /// A track entry to allow further customization of animation playback. References to the track entry must not be kept - /// after AnimationState.Dispose. - TrackEntry* setAnimation(size_t trackIndex, Animation* animation, bool loop); + /// Queues an animation by name. + /// addAnimation(int, Animation, bool, float) + TrackEntry* addAnimation(size_t trackIndex, const String& animationName, bool loop, float delay); - /// Queues an animation by name. - /// addAnimation(int, Animation, bool, float) - TrackEntry* addAnimation(size_t trackIndex, const String& animationName, bool loop, float delay); + /// Adds an animation to be played delay seconds after the current or last queued animation + /// for a track. If the track is empty, it is equivalent to calling setAnimation. + /// @param delay + /// Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation + /// duration of the previous track minus any mix duration plus the negative delay. + /// + /// @return A track entry to allow further customization of animation playback. References to the track entry must not be kept + /// after AnimationState.Dispose + TrackEntry* addAnimation(size_t trackIndex, Animation* animation, bool loop, float delay); - /// Adds an animation to be played delay seconds after the current or last queued animation - /// for a track. If the track is empty, it is equivalent to calling setAnimation. - /// @param delay - /// Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation - /// duration of the previous track minus any mix duration plus the negative delay. - /// - /// @return A track entry to allow further customization of animation playback. References to the track entry must not be kept - /// after AnimationState.Dispose - TrackEntry* addAnimation(size_t trackIndex, Animation* animation, bool loop, float delay); + /// Sets an empty animation for a track, discarding any queued animations, and mixes to it over the specified mix duration. + TrackEntry* setEmptyAnimation(size_t trackIndex, float mixDuration); - /// Sets an empty animation for a track, discarding any queued animations, and mixes to it over the specified mix duration. - TrackEntry* setEmptyAnimation(size_t trackIndex, float mixDuration); + /// Adds an empty animation to be played after the current or last queued animation for a track, and mixes to it over the + /// specified mix duration. + /// @return + /// A track entry to allow further customization of animation playback. References to the track entry must not be kept after AnimationState.Dispose. + /// + /// @param trackIndex Track number. + /// @param mixDuration Mix duration. + /// @param delay Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation + /// duration of the previous track minus any mix duration plus the negative delay. + TrackEntry* addEmptyAnimation(size_t trackIndex, float mixDuration, float delay); - /// Adds an empty animation to be played after the current or last queued animation for a track, and mixes to it over the - /// specified mix duration. - /// @return - /// A track entry to allow further customization of animation playback. References to the track entry must not be kept after AnimationState.Dispose. - /// - /// @param trackIndex Track number. - /// @param mixDuration Mix duration. - /// @param delay Seconds to begin this animation after the start of the previous animation. May be <= 0 to use the animation - /// duration of the previous track minus any mix duration plus the negative delay. - TrackEntry* addEmptyAnimation(size_t trackIndex, float mixDuration, float delay); + /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix duration. + void setEmptyAnimations(float mixDuration); - /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix duration. - void setEmptyAnimations(float mixDuration); + /// @return The track entry for the animation currently playing on the track, or NULL if no animation is currently playing. + TrackEntry* getCurrent(size_t trackIndex); - /// @return The track entry for the animation currently playing on the track, or NULL if no animation is currently playing. - TrackEntry* getCurrent(size_t trackIndex); + AnimationStateData* getData(); - AnimationStateData* getData(); + /// A list of tracks that have animations, which may contain NULLs. + Vector& getTracks(); - /// A list of tracks that have animations, which may contain NULLs. - Vector &getTracks(); + float getTimeScale(); + void setTimeScale(float inValue); - float getTimeScale(); - void setTimeScale(float inValue); + void setListener(AnimationStateListener listener); + void setListener(AnimationStateListenerObject* listener); - void setListener(AnimationStateListener listener); - void setListener(AnimationStateListenerObject* listener); + void disableQueue(); + void enableQueue(); - void disableQueue(); - void enableQueue(); +private: + AnimationStateData* _data; - private: + Pool _trackEntryPool; + Vector _tracks; + Vector _events; + EventQueue* _queue; - AnimationStateData* _data; + HashMap _propertyIDs; + bool _animationsChanged; - Pool _trackEntryPool; - Vector _tracks; - Vector _events; - EventQueue* _queue; + AnimationStateListener _listener; + AnimationStateListenerObject* _listenerObject; - HashMap _propertyIDs; - bool _animationsChanged; + float _timeScale; - AnimationStateListener _listener; - AnimationStateListenerObject* _listenerObject; + static Animation* getEmptyAnimation(); - float _timeScale; + static void applyRotateTimeline(RotateTimeline* rotateTimeline, Skeleton& skeleton, float time, float alpha, MixBlend pose, Vector& timelinesRotation, size_t i, bool firstFrame); - static Animation* getEmptyAnimation(); + /// Returns true when all mixing from entries are complete. + bool updateMixingFrom(TrackEntry* to, float delta); - static void applyRotateTimeline(RotateTimeline* rotateTimeline, Skeleton& skeleton, float time, float alpha, MixBlend pose, Vector& timelinesRotation, size_t i, bool firstFrame); + float applyMixingFrom(TrackEntry* to, Skeleton& skeleton, MixBlend currentPose); - /// Returns true when all mixing from entries are complete. - bool updateMixingFrom(TrackEntry* to, float delta); + void queueEvents(TrackEntry* entry, float animationTime); - float applyMixingFrom(TrackEntry* to, Skeleton& skeleton, MixBlend currentPose); + /// Sets the active TrackEntry for a given track number. + void setCurrent(size_t index, TrackEntry* current, bool interrupt); - void queueEvents(TrackEntry* entry, float animationTime); + TrackEntry* expandToIndex(size_t index); - /// Sets the active TrackEntry for a given track number. - void setCurrent(size_t index, TrackEntry *current, bool interrupt); + /// Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values. + /// @param last May be NULL. + TrackEntry* newTrackEntry(size_t trackIndex, Animation* animation, bool loop, TrackEntry* last); - TrackEntry* expandToIndex(size_t index); + /// Dispose all track entries queued after the given TrackEntry. + void disposeNext(TrackEntry* entry); - /// Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values. - /// @param last May be NULL. - TrackEntry* newTrackEntry(size_t trackIndex, Animation *animation, bool loop, TrackEntry *last); + void animationsChanged(); - /// Dispose all track entries queued after the given TrackEntry. - void disposeNext(TrackEntry* entry); + void computeHold(TrackEntry* entry); - void animationsChanged(); - - void computeHold(TrackEntry *entry); - - void computeNotLast(TrackEntry *entry); - }; -} + void computeNotLast(TrackEntry* entry); +}; +} // namespace spine #endif /* Spine_AnimationState_h */ diff --git a/native/cocos/editor-support/spine/AnimationStateData.cpp b/native/cocos/editor-support/spine/AnimationStateData.cpp index afd1d2bee0..f1f7dad675 100644 --- a/native/cocos/editor-support/spine/AnimationStateData.cpp +++ b/native/cocos/editor-support/spine/AnimationStateData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -41,45 +41,45 @@ AnimationStateData::AnimationStateData(SkeletonData *skeletonData) : _skeletonDa } void AnimationStateData::setMix(const String &fromName, const String &toName, float duration) { - Animation *from = _skeletonData->findAnimation(fromName); - Animation *to = _skeletonData->findAnimation(toName); + Animation *from = _skeletonData->findAnimation(fromName); + Animation *to = _skeletonData->findAnimation(toName); - setMix(from, to, duration); + setMix(from, to, duration); } void AnimationStateData::setMix(Animation *from, Animation *to, float duration) { - assert(from != NULL); - assert(to != NULL); + assert(from != NULL); + assert(to != NULL); - AnimationPair key(from, to); - _animationToMixTime.put(key, duration); + AnimationPair key(from, to); + _animationToMixTime.put(key, duration); } float AnimationStateData::getMix(Animation *from, Animation *to) { - assert(from != NULL); - assert(to != NULL); + assert(from != NULL); + assert(to != NULL); - AnimationPair key(from, to); + AnimationPair key(from, to); - if (_animationToMixTime.containsKey(key)) return _animationToMixTime[key]; - return _defaultMix; + if (_animationToMixTime.containsKey(key)) return _animationToMixTime[key]; + return _defaultMix; } SkeletonData *AnimationStateData::getSkeletonData() { - return _skeletonData; + return _skeletonData; } float AnimationStateData::getDefaultMix() { - return _defaultMix; + return _defaultMix; } void AnimationStateData::setDefaultMix(float inValue) { - _defaultMix = inValue; + _defaultMix = inValue; } AnimationStateData::AnimationPair::AnimationPair(Animation *a1, Animation *a2) : _a1(a1), _a2(a2) { } bool AnimationStateData::AnimationPair::operator==(const AnimationPair &other) const { - return _a1->_name == other._a1->_name && _a2->_name == other._a2->_name; + return _a1->_name == other._a1->_name && _a2->_name == other._a2->_name; } diff --git a/native/cocos/editor-support/spine/AnimationStateData.h b/native/cocos/editor-support/spine/AnimationStateData.h index 336f75ba9d..95a47e2374 100644 --- a/native/cocos/editor-support/spine/AnimationStateData.h +++ b/native/cocos/editor-support/spine/AnimationStateData.h @@ -37,49 +37,49 @@ #include namespace spine { - class SkeletonData; - class Animation; +class SkeletonData; +class Animation; - /// Stores mix (crossfade) durations to be applied when AnimationState animations are changed. - class SP_API AnimationStateData : public SpineObject { - friend class AnimationState; +/// Stores mix (crossfade) durations to be applied when AnimationState animations are changed. +class SP_API AnimationStateData : public SpineObject { + friend class AnimationState; - public: - explicit AnimationStateData(SkeletonData* skeletonData); +public: + explicit AnimationStateData(SkeletonData* skeletonData); - /// The SkeletonData to look up animations when they are specified by name. - SkeletonData* getSkeletonData(); + /// The SkeletonData to look up animations when they are specified by name. + SkeletonData* getSkeletonData(); - /// The mix duration to use when no mix duration has been specifically defined between two animations. - float getDefaultMix(); - void setDefaultMix(float inValue); + /// The mix duration to use when no mix duration has been specifically defined between two animations. + float getDefaultMix(); + void setDefaultMix(float inValue); - /// Sets a mix duration by animation names. - void setMix(const String& fromName, const String& toName, float duration); + /// Sets a mix duration by animation names. + void setMix(const String& fromName, const String& toName, float duration); - /// Sets a mix duration when changing from the specified animation to the other. - /// See TrackEntry.MixDuration. - void setMix(Animation* from, Animation* to, float duration); + /// Sets a mix duration when changing from the specified animation to the other. + /// See TrackEntry.MixDuration. + void setMix(Animation* from, Animation* to, float duration); - /// The mix duration to use when changing from the specified animation to the other, - /// or the DefaultMix if no mix duration has been set. - float getMix(Animation* from, Animation* to); + /// The mix duration to use when changing from the specified animation to the other, + /// or the DefaultMix if no mix duration has been set. + float getMix(Animation* from, Animation* to); - private: - class AnimationPair : public SpineObject { - public: - Animation* _a1; - Animation* _a2; +private: + class AnimationPair : public SpineObject { + public: + Animation* _a1; + Animation* _a2; - explicit AnimationPair(Animation* a1 = NULL, Animation* a2 = NULL); + explicit AnimationPair(Animation* a1 = NULL, Animation* a2 = NULL); - bool operator==(const AnimationPair &other) const; - }; + bool operator==(const AnimationPair& other) const; + }; - SkeletonData* _skeletonData; - float _defaultMix; - HashMap _animationToMixTime; - }; -} + SkeletonData* _skeletonData; + float _defaultMix; + HashMap _animationToMixTime; +}; +} // namespace spine #endif /* Spine_AnimationStateData_h */ diff --git a/native/cocos/editor-support/spine/Atlas.cpp b/native/cocos/editor-support/spine/Atlas.cpp index bd5484b6f3..d7f0affb36 100644 --- a/native/cocos/editor-support/spine/Atlas.cpp +++ b/native/cocos/editor-support/spine/Atlas.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -40,290 +40,293 @@ using namespace spine; Atlas::Atlas(const String &path, TextureLoader *textureLoader, bool createTexture) : _textureLoader(textureLoader) { - int dirLength; - char *dir; - int length; - const char *data; + int dirLength; + char *dir; + int length; + const char *data; - /* Get directory from atlas path. */ - const char *lastForwardSlash = strrchr(path.buffer(), '/'); - const char *lastBackwardSlash = strrchr(path.buffer(), '\\'); - const char *lastSlash = lastForwardSlash > lastBackwardSlash ? lastForwardSlash : lastBackwardSlash; - if (lastSlash == path) lastSlash++; /* Never drop starting slash. */ - dirLength = (int) (lastSlash ? lastSlash - path.buffer() : 0); - dir = SpineExtension::calloc(dirLength + 1, __FILE__, __LINE__); - memcpy(dir, path.buffer(), dirLength); - dir[dirLength] = '\0'; + /* Get directory from atlas path. */ + const char *lastForwardSlash = strrchr(path.buffer(), '/'); + const char *lastBackwardSlash = strrchr(path.buffer(), '\\'); + const char *lastSlash = lastForwardSlash > lastBackwardSlash ? lastForwardSlash : lastBackwardSlash; + if (lastSlash == path) lastSlash++; /* Never drop starting slash. */ + dirLength = (int)(lastSlash ? lastSlash - path.buffer() : 0); + dir = SpineExtension::calloc(dirLength + 1, __FILE__, __LINE__); + memcpy(dir, path.buffer(), dirLength); + dir[dirLength] = '\0'; - data = SpineExtension::readFile(path, &length); - if (data) { - load(data, length, dir, createTexture); - } + data = SpineExtension::readFile(path, &length); + if (data) { + load(data, length, dir, createTexture); + } - SpineExtension::free(data, __FILE__, __LINE__); - SpineExtension::free(dir, __FILE__, __LINE__); + SpineExtension::free(data, __FILE__, __LINE__); + SpineExtension::free(dir, __FILE__, __LINE__); } Atlas::Atlas(const char *data, int length, const char *dir, TextureLoader *textureLoader, bool createTexture) : _textureLoader( - textureLoader) { - load(data, length, dir, createTexture); + textureLoader) { + load(data, length, dir, createTexture); } Atlas::~Atlas() { - if (_textureLoader) { - for (size_t i = 0, n = _pages.size(); i < n; ++i) { - _textureLoader->unload(_pages[i]->getRendererObject()); - } - } - ContainerUtil::cleanUpVectorOfPointers(_pages); - ContainerUtil::cleanUpVectorOfPointers(_regions); + if (_textureLoader) { + for (size_t i = 0, n = _pages.size(); i < n; ++i) { + _textureLoader->unload(_pages[i]->getRendererObject()); + } + } + ContainerUtil::cleanUpVectorOfPointers(_pages); + ContainerUtil::cleanUpVectorOfPointers(_regions); } void Atlas::flipV() { - for (size_t i = 0, n = _regions.size(); i < n; ++i) { - AtlasRegion *regionP = _regions[i]; - AtlasRegion ®ion = *regionP; - region.v = 1 - region.v; - region.v2 = 1 - region.v2; - } + for (size_t i = 0, n = _regions.size(); i < n; ++i) { + AtlasRegion *regionP = _regions[i]; + AtlasRegion ®ion = *regionP; + region.v = 1 - region.v; + region.v2 = 1 - region.v2; + } } AtlasRegion *Atlas::findRegion(const String &name) { - for (size_t i = 0, n = _regions.size(); i < n; ++i) - if (_regions[i]->name == name) return _regions[i]; - return NULL; + for (size_t i = 0, n = _regions.size(); i < n; ++i) + if (_regions[i]->name == name) return _regions[i]; + return NULL; } -Vector &Atlas::getPages() { - return _pages; +Vector &Atlas::getPages() { + return _pages; } void Atlas::load(const char *begin, int length, const char *dir, bool createTexture) { - static const char *formatNames[] = {"", "Alpha", "Intensity", "LuminanceAlpha", "RGB565", "RGBA4444", "RGB888", "RGBA8888"}; - static const char *textureFilterNames[] = {"", "Nearest", "Linear", "MipMap", "MipMapNearestNearest", "MipMapLinearNearest", - "MipMapNearestLinear", "MipMapLinearLinear"}; + static const char *formatNames[] = {"", "Alpha", "Intensity", "LuminanceAlpha", "RGB565", "RGBA4444", "RGB888", "RGBA8888"}; + static const char *textureFilterNames[] = {"", "Nearest", "Linear", "MipMap", "MipMapNearestNearest", "MipMapLinearNearest", + "MipMapNearestLinear", "MipMapLinearLinear"}; - int count; - const char *end = begin + length; - int dirLength = (int) strlen(dir); - int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\'; + int count; + const char *end = begin + length; + int dirLength = (int)strlen(dir); + int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\'; - AtlasPage *page = NULL; - Str str; - Str tuple[4]; + AtlasPage *page = NULL; + Str str; + Str tuple[4]; - while (readLine(&begin, end, &str)) { - if (str.end - str.begin == 0) { - page = 0; - } else if (!page) { - char *name = mallocString(&str); - char *path = SpineExtension::calloc(dirLength + needsSlash + strlen(name) + 1, __FILE__, __LINE__); - memcpy(path, dir, dirLength); - if (needsSlash) path[dirLength] = '/'; - strcpy(path + dirLength + needsSlash, name); + while (readLine(&begin, end, &str)) { + if (str.end - str.begin == 0) { + page = 0; + } else if (!page) { + char *name = mallocString(&str); + char *path = SpineExtension::calloc(dirLength + needsSlash + strlen(name) + 1, __FILE__, __LINE__); + memcpy(path, dir, dirLength); + if (needsSlash) path[dirLength] = '/'; + strcpy(path + dirLength + needsSlash, name); - page = new(__FILE__, __LINE__) AtlasPage(String(name, true)); + page = new (__FILE__, __LINE__) AtlasPage(String(name, true)); - int tupleVal = readTuple(&begin, end, tuple); - assert(tupleVal == 2); + int tupleVal = readTuple(&begin, end, tuple); + assert(tupleVal == 2); - /* size is only optional for an atlas packed with an old TexturePacker. */ - page->width = toInt(tuple); - page->height = toInt(tuple + 1); - readTuple(&begin, end, tuple); + /* size is only optional for an atlas packed with an old TexturePacker. */ + page->width = toInt(tuple); + page->height = toInt(tuple + 1); + readTuple(&begin, end, tuple); - page->format = (Format) indexOf(formatNames, 8, tuple); + page->format = (Format)indexOf(formatNames, 8, tuple); - readTuple(&begin, end, tuple); - page->minFilter = (TextureFilter) indexOf(textureFilterNames, 8, tuple); - page->magFilter = (TextureFilter) indexOf(textureFilterNames, 8, tuple + 1); + readTuple(&begin, end, tuple); + page->minFilter = (TextureFilter)indexOf(textureFilterNames, 8, tuple); + page->magFilter = (TextureFilter)indexOf(textureFilterNames, 8, tuple + 1); - readValue(&begin, end, &str); + readValue(&begin, end, &str); - page->uWrap = TextureWrap_ClampToEdge; - page->vWrap = TextureWrap_ClampToEdge; - if (!equals(&str, "none")) { - if (str.end - str.begin == 1) { - if (*str.begin == 'x') { - page->uWrap = TextureWrap_Repeat; - } else if (*str.begin == 'y') { - page->vWrap = TextureWrap_Repeat; - } - } else if (equals(&str, "xy")) { - page->uWrap = TextureWrap_Repeat; - page->vWrap = TextureWrap_Repeat; - } - } + page->uWrap = TextureWrap_ClampToEdge; + page->vWrap = TextureWrap_ClampToEdge; + if (!equals(&str, "none")) { + if (str.end - str.begin == 1) { + if (*str.begin == 'x') { + page->uWrap = TextureWrap_Repeat; + } else if (*str.begin == 'y') { + page->vWrap = TextureWrap_Repeat; + } + } else if (equals(&str, "xy")) { + page->uWrap = TextureWrap_Repeat; + page->vWrap = TextureWrap_Repeat; + } + } - if (createTexture) { - if (_textureLoader) _textureLoader->load(*page, String(path)); - SpineExtension::free(path, __FILE__, __LINE__); - } else - page->texturePath = String(path, true); + if (createTexture) { + if (_textureLoader) _textureLoader->load(*page, String(path)); + SpineExtension::free(path, __FILE__, __LINE__); + } else + page->texturePath = String(path, true); - _pages.add(page); - } else { - AtlasRegion *region = new(__FILE__, __LINE__) AtlasRegion(); + _pages.add(page); + } else { + AtlasRegion *region = new (__FILE__, __LINE__) AtlasRegion(); - region->page = page; - region->name = String(mallocString(&str), true); + region->page = page; + region->name = String(mallocString(&str), true); - readValue(&begin, end, &str); - if (equals(&str, "true")) region->degrees = 90; - else if (equals(&str, "false")) region->degrees = 0; - else region->degrees = toInt(&str); - region->rotate = region->degrees == 90; + readValue(&begin, end, &str); + if (equals(&str, "true")) + region->degrees = 90; + else if (equals(&str, "false")) + region->degrees = 0; + else + region->degrees = toInt(&str); + region->rotate = region->degrees == 90; - readTuple(&begin, end, tuple); - region->x = toInt(tuple); - region->y = toInt(tuple + 1); + readTuple(&begin, end, tuple); + region->x = toInt(tuple); + region->y = toInt(tuple + 1); - readTuple(&begin, end, tuple); - region->width = toInt(tuple); - region->height = toInt(tuple + 1); + readTuple(&begin, end, tuple); + region->width = toInt(tuple); + region->height = toInt(tuple + 1); - region->u = region->x / (float) page->width; - region->v = region->y / (float) page->height; - if (region->rotate) { - region->u2 = (region->x + region->height) / (float) page->width; - region->v2 = (region->y + region->width) / (float) page->height; - } else { - region->u2 = (region->x + region->width) / (float) page->width; - region->v2 = (region->y + region->height) / (float) page->height; - } + region->u = region->x / (float)page->width; + region->v = region->y / (float)page->height; + if (region->rotate) { + region->u2 = (region->x + region->height) / (float)page->width; + region->v2 = (region->y + region->width) / (float)page->height; + } else { + region->u2 = (region->x + region->width) / (float)page->width; + region->v2 = (region->y + region->height) / (float)page->height; + } - count = readTuple(&begin, end, tuple); - assert(count); + count = readTuple(&begin, end, tuple); + assert(count); - if (count == 4) { - /* split is optional */ - region->splits.setSize(4, 0); - region->splits[0] = toInt(tuple); - region->splits[1] = toInt(tuple + 1); - region->splits[2] = toInt(tuple + 2); - region->splits[3] = toInt(tuple + 3); + if (count == 4) { + /* split is optional */ + region->splits.setSize(4, 0); + region->splits[0] = toInt(tuple); + region->splits[1] = toInt(tuple + 1); + region->splits[2] = toInt(tuple + 2); + region->splits[3] = toInt(tuple + 3); - count = readTuple(&begin, end, tuple); - assert(count); + count = readTuple(&begin, end, tuple); + assert(count); - if (count == 4) { - /* pad is optional, but only present with splits */ - region->pads.setSize(4, 0); - region->pads[0] = toInt(tuple); - region->pads[1] = toInt(tuple + 1); - region->pads[2] = toInt(tuple + 2); - region->pads[3] = toInt(tuple + 3); + if (count == 4) { + /* pad is optional, but only present with splits */ + region->pads.setSize(4, 0); + region->pads[0] = toInt(tuple); + region->pads[1] = toInt(tuple + 1); + region->pads[2] = toInt(tuple + 2); + region->pads[3] = toInt(tuple + 3); - readTuple(&begin, end, tuple); - } - } + readTuple(&begin, end, tuple); + } + } - region->originalWidth = toInt(tuple); - region->originalHeight = toInt(tuple + 1); + region->originalWidth = toInt(tuple); + region->originalHeight = toInt(tuple + 1); - readTuple(&begin, end, tuple); - region->offsetX = (float)toInt(tuple); - region->offsetY = (float)toInt(tuple + 1); + readTuple(&begin, end, tuple); + region->offsetX = (float)toInt(tuple); + region->offsetY = (float)toInt(tuple + 1); - readValue(&begin, end, &str); + readValue(&begin, end, &str); - region->index = toInt(&str); + region->index = toInt(&str); - _regions.add(region); - } - } + _regions.add(region); + } + } } void Atlas::trim(Str *str) { - while (isspace((unsigned char) *str->begin) && str->begin < str->end) - (str->begin)++; + while (isspace((unsigned char)*str->begin) && str->begin < str->end) + (str->begin)++; - if (str->begin == str->end) return; + if (str->begin == str->end) return; - str->end--; + str->end--; - while (((unsigned char)*str->end == '\r') && str->end >= str->begin) - str->end--; + while (((unsigned char)*str->end == '\r') && str->end >= str->begin) + str->end--; - str->end++; + str->end++; } int Atlas::readLine(const char **begin, const char *end, Str *str) { - if (*begin == end) return 0; + if (*begin == end) return 0; - str->begin = *begin; + str->begin = *begin; - /* Find next delimiter. */ - while (*begin != end && **begin != '\n') - (*begin)++; + /* Find next delimiter. */ + while (*begin != end && **begin != '\n') + (*begin)++; - str->end = *begin; - trim(str); + str->end = *begin; + trim(str); - if (*begin != end) (*begin)++; + if (*begin != end) (*begin)++; - return 1; + return 1; } int Atlas::beginPast(Str *str, char c) { - const char *begin = str->begin; - while (true) { - char lastSkippedChar = *begin; - if (begin == str->end) return 0; - begin++; - if (lastSkippedChar == c) break; - } - str->begin = begin; - return 1; + const char *begin = str->begin; + while (true) { + char lastSkippedChar = *begin; + if (begin == str->end) return 0; + begin++; + if (lastSkippedChar == c) break; + } + str->begin = begin; + return 1; } int Atlas::readValue(const char **begin, const char *end, Str *str) { - readLine(begin, end, str); - if (!beginPast(str, ':')) return 0; - trim(str); - return 1; + readLine(begin, end, str); + if (!beginPast(str, ':')) return 0; + trim(str); + return 1; } int Atlas::readTuple(const char **begin, const char *end, Str tuple[]) { - int i; - Str str = {NULL, NULL}; - readLine(begin, end, &str); - if (!beginPast(&str, ':')) return 0; + int i; + Str str = {NULL, NULL}; + readLine(begin, end, &str); + if (!beginPast(&str, ':')) return 0; - for (i = 0; i < 3; ++i) { - tuple[i].begin = str.begin; - if (!beginPast(&str, ',')) break; - tuple[i].end = str.begin - 2; - trim(&tuple[i]); - } + for (i = 0; i < 3; ++i) { + tuple[i].begin = str.begin; + if (!beginPast(&str, ',')) break; + tuple[i].end = str.begin - 2; + trim(&tuple[i]); + } - tuple[i].begin = str.begin; - tuple[i].end = str.end; - trim(&tuple[i]); + tuple[i].begin = str.begin; + tuple[i].end = str.end; + trim(&tuple[i]); - return i + 1; + return i + 1; } char *Atlas::mallocString(Str *str) { - int length = (int) (str->end - str->begin); - char *string = SpineExtension::calloc(length + 1, __FILE__, __LINE__); - memcpy(string, str->begin, length); - string[length] = '\0'; - return string; + int length = (int)(str->end - str->begin); + char *string = SpineExtension::calloc(length + 1, __FILE__, __LINE__); + memcpy(string, str->begin, length); + string[length] = '\0'; + return string; } int Atlas::indexOf(const char **array, int count, Str *str) { - int length = (int) (str->end - str->begin); - int i; - for (i = count - 1; i >= 0; i--) - if (strncmp(array[i], str->begin, length) == 0) return i; - return 0; + int length = (int)(str->end - str->begin); + int i; + for (i = count - 1; i >= 0; i--) + if (strncmp(array[i], str->begin, length) == 0) return i; + return 0; } int Atlas::equals(Str *str, const char *other) { - return strncmp(other, str->begin, str->end - str->begin) == 0; + return strncmp(other, str->begin, str->end - str->begin) == 0; } int Atlas::toInt(Str *str) { - return (int) strtol(str->begin, (char **) &str->end, 10); + return (int)strtol(str->begin, (char **)&str->end, 10); } diff --git a/native/cocos/editor-support/spine/Atlas.h b/native/cocos/editor-support/spine/Atlas.h index 257942d692..ec8c0245db 100644 --- a/native/cocos/editor-support/spine/Atlas.h +++ b/native/cocos/editor-support/spine/Atlas.h @@ -38,120 +38,118 @@ namespace spine { enum Format { - Format_Alpha, - Format_Intensity, - Format_LuminanceAlpha, - Format_RGB565, - Format_RGBA4444, - Format_RGB888, - Format_RGBA8888 + Format_Alpha, + Format_Intensity, + Format_LuminanceAlpha, + Format_RGB565, + Format_RGBA4444, + Format_RGB888, + Format_RGBA8888 }; enum TextureFilter { - TextureFilter_Unknown, - TextureFilter_Nearest, - TextureFilter_Linear, - TextureFilter_MipMap, - TextureFilter_MipMapNearestNearest, - TextureFilter_MipMapLinearNearest, - TextureFilter_MipMapNearestLinear, - TextureFilter_MipMapLinearLinear + TextureFilter_Unknown, + TextureFilter_Nearest, + TextureFilter_Linear, + TextureFilter_MipMap, + TextureFilter_MipMapNearestNearest, + TextureFilter_MipMapLinearNearest, + TextureFilter_MipMapNearestLinear, + TextureFilter_MipMapLinearLinear }; enum TextureWrap { - TextureWrap_MirroredRepeat, - TextureWrap_ClampToEdge, - TextureWrap_Repeat + TextureWrap_MirroredRepeat, + TextureWrap_ClampToEdge, + TextureWrap_Repeat }; class SP_API AtlasPage : public SpineObject, public HasRendererObject { public: - String name; - String texturePath; - Format format; - TextureFilter minFilter; - TextureFilter magFilter; - TextureWrap uWrap; - TextureWrap vWrap; - int width, height; + String name; + String texturePath; + Format format; + TextureFilter minFilter; + TextureFilter magFilter; + TextureWrap uWrap; + TextureWrap vWrap; + int width, height; - explicit AtlasPage(const String &inName) : name(inName), format(Format_RGBA8888), minFilter(TextureFilter_Nearest), - magFilter(TextureFilter_Nearest), uWrap(TextureWrap_ClampToEdge), - vWrap(TextureWrap_ClampToEdge), width(0), height(0) { - } + explicit AtlasPage(const String &inName) : name(inName), format(Format_RGBA8888), minFilter(TextureFilter_Nearest), magFilter(TextureFilter_Nearest), uWrap(TextureWrap_ClampToEdge), vWrap(TextureWrap_ClampToEdge), width(0), height(0) { + } }; class SP_API AtlasRegion : public SpineObject { public: - AtlasPage *page; - String name; - int x, y, width, height; - float u, v, u2, v2; - float offsetX, offsetY; - int originalWidth, originalHeight; - int index; - bool rotate; - int degrees; - Vector splits; - Vector pads; + AtlasPage *page; + String name; + int x, y, width, height; + float u, v, u2, v2; + float offsetX, offsetY; + int originalWidth, originalHeight; + int index; + bool rotate; + int degrees; + Vector splits; + Vector pads; }; class TextureLoader; class SP_API Atlas : public SpineObject { public: - Atlas(const String &path, TextureLoader *textureLoader, bool createTexture = true); + Atlas(const String &path, TextureLoader *textureLoader, bool createTexture = true); - Atlas(const char *data, int length, const char *dir, TextureLoader *textureLoader, bool createTexture = true); + Atlas(const char *data, int length, const char *dir, TextureLoader *textureLoader, bool createTexture = true); - ~Atlas(); + ~Atlas(); - void flipV(); + void flipV(); - /// Returns the first region found with the specified name. This method uses String comparison to find the region, so the result - /// should be cached rather than calling this method multiple times. - /// @return The region, or NULL. - AtlasRegion *findRegion(const String &name); + /// Returns the first region found with the specified name. This method uses String comparison to find the region, so the result + /// should be cached rather than calling this method multiple times. + /// @return The region, or NULL. + AtlasRegion *findRegion(const String &name); - Vector &getPages(); + Vector &getPages(); private: - Vector _pages; - Vector _regions; - TextureLoader *_textureLoader; + Vector _pages; + Vector _regions; + TextureLoader *_textureLoader; - void load(const char *begin, int length, const char *dir, bool createTexture); + void load(const char *begin, int length, const char *dir, bool createTexture); - class Str { - public: - const char *begin; - const char *end; - }; + class Str { + public: + const char *begin; + const char *end; + }; - static void trim(Str *str); + static void trim(Str *str); - /// Tokenize string without modification. Returns 0 on failure - static int readLine(const char **begin, const char *end, Str *str); + /// Tokenize string without modification. Returns 0 on failure + static int readLine(const char **begin, const char *end, Str *str); - /// Moves str->begin past the first occurence of c. Returns 0 on failure - static int beginPast(Str *str, char c); + /// Moves str->begin past the first occurence of c. Returns 0 on failure + static int beginPast(Str *str, char c); - /// Returns 0 on failure - static int readValue(const char **begin, const char *end, Str *str); + /// Returns 0 on failure + static int readValue(const char **begin, const char *end, Str *str); - /// Returns the number of tuple values read (1, 2, 4, or 0 for failure) - static int readTuple(const char **begin, const char *end, Str tuple[]); + /// Returns the number of tuple values read (1, 2, 4, or 0 for failure) + static int readTuple(const char **begin, const char *end, Str tuple[]); - static char *mallocString(Str *str); + static char *mallocString(Str *str); - static int indexOf(const char **array, int count, Str *str); + static int indexOf(const char **array, int count, Str *str); - static int equals(Str *str, const char *other); + static int equals(Str *str, const char *other); - static int toInt(Str *str); + static int toInt(Str *str); - static Atlas *abortAtlas(Atlas *atlas); + static Atlas *abortAtlas(Atlas *atlas); }; -} +} // namespace spine #endif /* Spine_Atlas_h */ diff --git a/native/cocos/editor-support/spine/AtlasAttachmentLoader.cpp b/native/cocos/editor-support/spine/AtlasAttachmentLoader.cpp index 92e4d16d43..e76728ac75 100644 --- a/native/cocos/editor-support/spine/AtlasAttachmentLoader.cpp +++ b/native/cocos/editor-support/spine/AtlasAttachmentLoader.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -49,81 +49,81 @@ AtlasAttachmentLoader::AtlasAttachmentLoader(Atlas *atlas) : AttachmentLoader(), } RegionAttachment *AtlasAttachmentLoader::newRegionAttachment(Skin &skin, const String &name, const String &path) { - SP_UNUSED(skin); + SP_UNUSED(skin); - AtlasRegion *regionP = findRegion(path); - if (!regionP) return NULL; + AtlasRegion *regionP = findRegion(path); + if (!regionP) return NULL; - AtlasRegion ®ion = *regionP; + AtlasRegion ®ion = *regionP; - RegionAttachment *attachmentP = new(__FILE__, __LINE__) RegionAttachment(name); + RegionAttachment *attachmentP = new (__FILE__, __LINE__) RegionAttachment(name); - RegionAttachment &attachment = *attachmentP; - attachment.setRendererObject(regionP); - attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); - attachment._regionOffsetX = region.offsetX; - attachment._regionOffsetY = region.offsetY; - attachment._regionWidth = (float)region.width; - attachment._regionHeight = (float)region.height; - attachment._regionOriginalWidth = (float)region.originalWidth; - attachment._regionOriginalHeight = (float)region.originalHeight; - return attachmentP; + RegionAttachment &attachment = *attachmentP; + attachment.setRendererObject(regionP); + attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); + attachment._regionOffsetX = region.offsetX; + attachment._regionOffsetY = region.offsetY; + attachment._regionWidth = (float)region.width; + attachment._regionHeight = (float)region.height; + attachment._regionOriginalWidth = (float)region.originalWidth; + attachment._regionOriginalHeight = (float)region.originalHeight; + return attachmentP; } MeshAttachment *AtlasAttachmentLoader::newMeshAttachment(Skin &skin, const String &name, const String &path) { - SP_UNUSED(skin); + SP_UNUSED(skin); - AtlasRegion *regionP = findRegion(path); - if (!regionP) return NULL; + AtlasRegion *regionP = findRegion(path); + if (!regionP) return NULL; - AtlasRegion ®ion = *regionP; + AtlasRegion ®ion = *regionP; - MeshAttachment *attachmentP = new(__FILE__, __LINE__) MeshAttachment(name); + MeshAttachment *attachmentP = new (__FILE__, __LINE__) MeshAttachment(name); - MeshAttachment &attachment = *attachmentP; - attachment.setRendererObject(regionP); - attachment._regionU = region.u; - attachment._regionV = region.v; - attachment._regionU2 = region.u2; - attachment._regionV2 = region.v2; - attachment._regionRotate = region.rotate; - attachment._regionDegrees = region.degrees; - attachment._regionOffsetX = region.offsetX; - attachment._regionOffsetY = region.offsetY; - attachment._regionWidth = (float)region.width; - attachment._regionHeight = (float)region.height; - attachment._regionOriginalWidth = (float)region.originalWidth; - attachment._regionOriginalHeight = (float)region.originalHeight; + MeshAttachment &attachment = *attachmentP; + attachment.setRendererObject(regionP); + attachment._regionU = region.u; + attachment._regionV = region.v; + attachment._regionU2 = region.u2; + attachment._regionV2 = region.v2; + attachment._regionRotate = region.rotate; + attachment._regionDegrees = region.degrees; + attachment._regionOffsetX = region.offsetX; + attachment._regionOffsetY = region.offsetY; + attachment._regionWidth = (float)region.width; + attachment._regionHeight = (float)region.height; + attachment._regionOriginalWidth = (float)region.originalWidth; + attachment._regionOriginalHeight = (float)region.originalHeight; - return attachmentP; + return attachmentP; } BoundingBoxAttachment *AtlasAttachmentLoader::newBoundingBoxAttachment(Skin &skin, const String &name) { - SP_UNUSED(skin); - return new(__FILE__, __LINE__) BoundingBoxAttachment(name); + SP_UNUSED(skin); + return new (__FILE__, __LINE__) BoundingBoxAttachment(name); } PathAttachment *AtlasAttachmentLoader::newPathAttachment(Skin &skin, const String &name) { - SP_UNUSED(skin); - return new(__FILE__, __LINE__) PathAttachment(name); + SP_UNUSED(skin); + return new (__FILE__, __LINE__) PathAttachment(name); } PointAttachment *AtlasAttachmentLoader::newPointAttachment(Skin &skin, const String &name) { - SP_UNUSED(skin); - return new(__FILE__, __LINE__) PointAttachment(name); + SP_UNUSED(skin); + return new (__FILE__, __LINE__) PointAttachment(name); } ClippingAttachment *AtlasAttachmentLoader::newClippingAttachment(Skin &skin, const String &name) { - SP_UNUSED(skin); - return new(__FILE__, __LINE__) ClippingAttachment(name); + SP_UNUSED(skin); + return new (__FILE__, __LINE__) ClippingAttachment(name); } -void AtlasAttachmentLoader::configureAttachment(Attachment* attachment) { - SP_UNUSED(attachment); +void AtlasAttachmentLoader::configureAttachment(Attachment *attachment) { + SP_UNUSED(attachment); } AtlasRegion *AtlasAttachmentLoader::findRegion(const String &name) { - return _atlas->findRegion(name); + return _atlas->findRegion(name); } -} +} // namespace spine diff --git a/native/cocos/editor-support/spine/AtlasAttachmentLoader.h b/native/cocos/editor-support/spine/AtlasAttachmentLoader.h index 0db41cd1af..4332312f13 100644 --- a/native/cocos/editor-support/spine/AtlasAttachmentLoader.h +++ b/native/cocos/editor-support/spine/AtlasAttachmentLoader.h @@ -34,38 +34,37 @@ #include #include - namespace spine { - class Atlas; - class AtlasRegion; +class Atlas; +class AtlasRegion; - /// An AttachmentLoader that configures attachments using texture regions from an Atlas. - /// See http://esotericsoftware.com/spine-loading-skeleton-data#JSON-and-binary-data about Loading Skeleton Data in the Spine Runtimes Guide. - class SP_API AtlasAttachmentLoader : public AttachmentLoader { - public: - RTTI_DECL +/// An AttachmentLoader that configures attachments using texture regions from an Atlas. +/// See http://esotericsoftware.com/spine-loading-skeleton-data#JSON-and-binary-data about Loading Skeleton Data in the Spine Runtimes Guide. +class SP_API AtlasAttachmentLoader : public AttachmentLoader { +public: + RTTI_DECL - explicit AtlasAttachmentLoader(Atlas* atlas); + explicit AtlasAttachmentLoader(Atlas* atlas); - virtual RegionAttachment* newRegionAttachment(Skin& skin, const String& name, const String& path); + virtual RegionAttachment* newRegionAttachment(Skin& skin, const String& name, const String& path); - virtual MeshAttachment* newMeshAttachment(Skin& skin, const String& name, const String& path); + virtual MeshAttachment* newMeshAttachment(Skin& skin, const String& name, const String& path); - virtual BoundingBoxAttachment* newBoundingBoxAttachment(Skin& skin, const String& name); + virtual BoundingBoxAttachment* newBoundingBoxAttachment(Skin& skin, const String& name); - virtual PathAttachment* newPathAttachment(Skin& skin, const String& name); + virtual PathAttachment* newPathAttachment(Skin& skin, const String& name); - virtual PointAttachment* newPointAttachment(Skin& skin, const String& name); + virtual PointAttachment* newPointAttachment(Skin& skin, const String& name); - virtual ClippingAttachment* newClippingAttachment(Skin& skin, const String& name); + virtual ClippingAttachment* newClippingAttachment(Skin& skin, const String& name); - virtual void configureAttachment(Attachment* attachment); + virtual void configureAttachment(Attachment* attachment); - AtlasRegion* findRegion(const String& name); + AtlasRegion* findRegion(const String& name); - private: - Atlas* _atlas; - }; -} +private: + Atlas* _atlas; +}; +} // namespace spine #endif /* Spine_AtlasAttachmentLoader_h */ diff --git a/native/cocos/editor-support/spine/Attachment.cpp b/native/cocos/editor-support/spine/Attachment.cpp index fd83f2f8fd..7172b4c67b 100644 --- a/native/cocos/editor-support/spine/Attachment.cpp +++ b/native/cocos/editor-support/spine/Attachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -40,24 +40,24 @@ using namespace spine; RTTI_IMPL_NOPARENT(Attachment) Attachment::Attachment(const String &name) : _name(name), _refCount(0) { - assert(_name.length() > 0); + assert(_name.length() > 0); } Attachment::~Attachment() { } const String &Attachment::getName() const { - return _name; + return _name; } int Attachment::getRefCount() { - return _refCount; + return _refCount; } void Attachment::reference() { - _refCount++; + _refCount++; } void Attachment::dereference() { - _refCount--; + _refCount--; } diff --git a/native/cocos/editor-support/spine/Attachment.h b/native/cocos/editor-support/spine/Attachment.h index 5b1c4c1856..a88516d28b 100644 --- a/native/cocos/editor-support/spine/Attachment.h +++ b/native/cocos/editor-support/spine/Attachment.h @@ -36,25 +36,25 @@ namespace spine { class SP_API Attachment : public SpineObject { -RTTI_DECL + RTTI_DECL public: - explicit Attachment(const String &name); + explicit Attachment(const String &name); - virtual ~Attachment(); + virtual ~Attachment(); - const String &getName() const; + const String &getName() const; - virtual Attachment* copy() = 0; + virtual Attachment *copy() = 0; - int getRefCount(); - void reference(); - void dereference(); + int getRefCount(); + void reference(); + void dereference(); private: - const String _name; - int _refCount; + const String _name; + int _refCount; }; -} +} // namespace spine #endif /* Spine_Attachment_h */ diff --git a/native/cocos/editor-support/spine/AttachmentLoader.cpp b/native/cocos/editor-support/spine/AttachmentLoader.cpp index 5875f7e6c7..7471073232 100644 --- a/native/cocos/editor-support/spine/AttachmentLoader.cpp +++ b/native/cocos/editor-support/spine/AttachmentLoader.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include diff --git a/native/cocos/editor-support/spine/AttachmentLoader.h b/native/cocos/editor-support/spine/AttachmentLoader.h index 6201e927a9..d3d4f433e3 100644 --- a/native/cocos/editor-support/spine/AttachmentLoader.h +++ b/native/cocos/editor-support/spine/AttachmentLoader.h @@ -35,41 +35,41 @@ #include namespace spine { - class Skin; - class Attachment; - class RegionAttachment; - class MeshAttachment; - class BoundingBoxAttachment; - class PathAttachment; - class PointAttachment; - class ClippingAttachment; +class Skin; +class Attachment; +class RegionAttachment; +class MeshAttachment; +class BoundingBoxAttachment; +class PathAttachment; +class PointAttachment; +class ClippingAttachment; - class SP_API AttachmentLoader : public SpineObject { - public: - RTTI_DECL +class SP_API AttachmentLoader : public SpineObject { +public: + RTTI_DECL - AttachmentLoader(); + AttachmentLoader(); - virtual ~AttachmentLoader(); + virtual ~AttachmentLoader(); - /// @return May be NULL to not load any attachment. - virtual RegionAttachment* newRegionAttachment(Skin& skin, const String& name, const String& path) = 0; + /// @return May be NULL to not load any attachment. + virtual RegionAttachment* newRegionAttachment(Skin& skin, const String& name, const String& path) = 0; - /// @return May be NULL to not load any attachment. - virtual MeshAttachment* newMeshAttachment(Skin& skin, const String& name, const String& path) = 0; + /// @return May be NULL to not load any attachment. + virtual MeshAttachment* newMeshAttachment(Skin& skin, const String& name, const String& path) = 0; - /// @return May be NULL to not load any attachment. - virtual BoundingBoxAttachment* newBoundingBoxAttachment(Skin& skin, const String& name) = 0; + /// @return May be NULL to not load any attachment. + virtual BoundingBoxAttachment* newBoundingBoxAttachment(Skin& skin, const String& name) = 0; - /// @return May be NULL to not load any attachment - virtual PathAttachment* newPathAttachment(Skin& skin, const String& name) = 0; + /// @return May be NULL to not load any attachment + virtual PathAttachment* newPathAttachment(Skin& skin, const String& name) = 0; - virtual PointAttachment* newPointAttachment(Skin& skin, const String& name) = 0; + virtual PointAttachment* newPointAttachment(Skin& skin, const String& name) = 0; - virtual ClippingAttachment* newClippingAttachment(Skin& skin, const String& name) = 0; + virtual ClippingAttachment* newClippingAttachment(Skin& skin, const String& name) = 0; - virtual void configureAttachment(Attachment* attachment) = 0; - }; -} + virtual void configureAttachment(Attachment* attachment) = 0; +}; +} // namespace spine #endif /* Spine_AttachmentLoader_h */ diff --git a/native/cocos/editor-support/spine/AttachmentTimeline.cpp b/native/cocos/editor-support/spine/AttachmentTimeline.cpp index e71e4e18f4..480bdc0cfc 100644 --- a/native/cocos/editor-support/spine/AttachmentTimeline.cpp +++ b/native/cocos/editor-support/spine/AttachmentTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -47,82 +47,81 @@ using namespace spine; RTTI_IMPL(AttachmentTimeline, Timeline) AttachmentTimeline::AttachmentTimeline(int frameCount) : Timeline(), _slotIndex(0) { - _frames.ensureCapacity(frameCount); - _attachmentNames.ensureCapacity(frameCount); + _frames.ensureCapacity(frameCount); + _attachmentNames.ensureCapacity(frameCount); - _frames.setSize(frameCount, 0); + _frames.setSize(frameCount, 0); - for (int i = 0; i < frameCount; ++i) { - _attachmentNames.add(String()); - } + for (int i = 0; i < frameCount; ++i) { + _attachmentNames.add(String()); + } } void AttachmentTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(alpha); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(alpha); - assert(_slotIndex < skeleton._slots.size()); + assert(_slotIndex < skeleton._slots.size()); - String *attachmentName; - Slot *slotP = skeleton._slots[_slotIndex]; - Slot &slot = *slotP; - if (!slot._bone.isActive()) return; + String *attachmentName; + Slot *slotP = skeleton._slots[_slotIndex]; + Slot &slot = *slotP; + if (!slot._bone.isActive()) return; - if (direction == MixDirection_Out && blend == MixBlend_Setup) { - attachmentName = &slot._data._attachmentName; - slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); - return; - } + if (direction == MixDirection_Out && blend == MixBlend_Setup) { + attachmentName = &slot._data._attachmentName; + slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); + return; + } - if (time < _frames[0]) { - // Time is before first frame. - if (blend == MixBlend_Setup || blend == MixBlend_First) { - attachmentName = &slot._data._attachmentName; - slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); - } - return; - } + if (time < _frames[0]) { + // Time is before first frame. + if (blend == MixBlend_Setup || blend == MixBlend_First) { + attachmentName = &slot._data._attachmentName; + slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); + } + return; + } - size_t frameIndex; - if (time >= _frames[_frames.size() - 1]) { - // Time is after last frame. - frameIndex = _frames.size() - 1; - } else { - frameIndex = Animation::binarySearch(_frames, time, 1) - 1; - } + size_t frameIndex; + if (time >= _frames[_frames.size() - 1]) { + // Time is after last frame. + frameIndex = _frames.size() - 1; + } else { + frameIndex = Animation::binarySearch(_frames, time, 1) - 1; + } - attachmentName = &_attachmentNames[frameIndex]; - slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); + attachmentName = &_attachmentNames[frameIndex]; + slot.setAttachment(attachmentName->length() == 0 ? NULL : skeleton.getAttachment(_slotIndex, *attachmentName)); } int AttachmentTimeline::getPropertyId() { - return ((int) TimelineType_Attachment << 24) + _slotIndex; + return ((int)TimelineType_Attachment << 24) + _slotIndex; } void AttachmentTimeline::setFrame(int frameIndex, float time, const String &attachmentName) { - _frames[frameIndex] = time; - _attachmentNames[frameIndex] = attachmentName; + _frames[frameIndex] = time; + _attachmentNames[frameIndex] = attachmentName; } size_t AttachmentTimeline::getSlotIndex() { - return _slotIndex; + return _slotIndex; } void AttachmentTimeline::setSlotIndex(size_t inValue) { - _slotIndex = inValue; + _slotIndex = inValue; } const Vector &AttachmentTimeline::getFrames() { - return _frames; + return _frames; } const Vector &AttachmentTimeline::getAttachmentNames() { - return _attachmentNames; + return _attachmentNames; } size_t AttachmentTimeline::getFrameCount() { - return _frames.size(); + return _frames.size(); } diff --git a/native/cocos/editor-support/spine/AttachmentTimeline.h b/native/cocos/editor-support/spine/AttachmentTimeline.h index c8a022a334..8a6fb80928 100644 --- a/native/cocos/editor-support/spine/AttachmentTimeline.h +++ b/native/cocos/editor-support/spine/AttachmentTimeline.h @@ -39,35 +39,36 @@ namespace spine { - class Skeleton; - class Event; +class Skeleton; +class Event; - class SP_API AttachmentTimeline : public Timeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API AttachmentTimeline : public Timeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit AttachmentTimeline(int frameCount); +public: + explicit AttachmentTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, const String& attachmentName); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, const String& attachmentName); - size_t getSlotIndex(); - void setSlotIndex(size_t inValue); - const Vector& getFrames(); - const Vector& getAttachmentNames(); - size_t getFrameCount(); - private: - size_t _slotIndex; - Vector _frames; - Vector _attachmentNames; - }; -} + size_t getSlotIndex(); + void setSlotIndex(size_t inValue); + const Vector& getFrames(); + const Vector& getAttachmentNames(); + size_t getFrameCount(); + +private: + size_t _slotIndex; + Vector _frames; + Vector _attachmentNames; +}; +} // namespace spine #endif /* Spine_AttachmentTimeline_h */ diff --git a/native/cocos/editor-support/spine/AttachmentType.h b/native/cocos/editor-support/spine/AttachmentType.h index bb62f9f50c..b4d12c10ad 100644 --- a/native/cocos/editor-support/spine/AttachmentType.h +++ b/native/cocos/editor-support/spine/AttachmentType.h @@ -31,15 +31,15 @@ #define Spine_AttachmentType_h namespace spine { - enum AttachmentType { - AttachmentType_Region, - AttachmentType_Boundingbox, - AttachmentType_Mesh, - AttachmentType_Linkedmesh, - AttachmentType_Path, - AttachmentType_Point, - AttachmentType_Clipping - }; +enum AttachmentType { + AttachmentType_Region, + AttachmentType_Boundingbox, + AttachmentType_Mesh, + AttachmentType_Linkedmesh, + AttachmentType_Path, + AttachmentType_Point, + AttachmentType_Clipping +}; } #endif /* Spine_AttachmentType_h */ diff --git a/native/cocos/editor-support/spine/BlendMode.h b/native/cocos/editor-support/spine/BlendMode.h index eca09cf8e6..5c6cbda228 100644 --- a/native/cocos/editor-support/spine/BlendMode.h +++ b/native/cocos/editor-support/spine/BlendMode.h @@ -32,10 +32,10 @@ namespace spine { enum BlendMode { - BlendMode_Normal = 0, - BlendMode_Additive, - BlendMode_Multiply, - BlendMode_Screen + BlendMode_Normal = 0, + BlendMode_Additive, + BlendMode_Multiply, + BlendMode_Screen }; } diff --git a/native/cocos/editor-support/spine/Bone.cpp b/native/cocos/editor-support/spine/Bone.cpp index 305cba173e..0e174a349c 100644 --- a/native/cocos/editor-support/spine/Bone.cpp +++ b/native/cocos/editor-support/spine/Bone.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -43,507 +43,505 @@ RTTI_IMPL(Bone, Updatable) bool Bone::yDown = false; void Bone::setYDown(bool inValue) { - yDown = inValue; + yDown = inValue; } bool Bone::isYDown() { - return yDown; + return yDown; } Bone::Bone(BoneData &data, Skeleton &skeleton, Bone *parent) : Updatable(), - _data(data), - _skeleton(skeleton), - _parent(parent), - _x(0), - _y(0), - _rotation(0), - _scaleX(0), - _scaleY(0), - _shearX(0), - _shearY(0), - _ax(0), - _ay(0), - _arotation(0), - _ascaleX(0), - _ascaleY(0), - _ashearX(0), - _ashearY(0), - _appliedValid(false), - _a(1), - _b(0), - _worldX(0), - _c(0), - _d(1), - _worldY(0), - _sorted(false), - _active(false) -{ - setToSetupPose(); + _data(data), + _skeleton(skeleton), + _parent(parent), + _x(0), + _y(0), + _rotation(0), + _scaleX(0), + _scaleY(0), + _shearX(0), + _shearY(0), + _ax(0), + _ay(0), + _arotation(0), + _ascaleX(0), + _ascaleY(0), + _ashearX(0), + _ashearY(0), + _appliedValid(false), + _a(1), + _b(0), + _worldX(0), + _c(0), + _d(1), + _worldY(0), + _sorted(false), + _active(false) { + setToSetupPose(); } void Bone::update() { - updateWorldTransform(_x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY); + updateWorldTransform(_x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY); } void Bone::updateWorldTransform() { - updateWorldTransform(_x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY); + updateWorldTransform(_x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY); } void Bone::updateWorldTransform(float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY) { - float cosine, sine; - float pa, pb, pc, pd; - Bone *parent = _parent; + float cosine, sine; + float pa, pb, pc, pd; + Bone *parent = _parent; - _ax = x; - _ay = y; - _arotation = rotation; - _ascaleX = scaleX; - _ascaleY = scaleY; - _ashearX = shearX; - _ashearY = shearY; - _appliedValid = true; + _ax = x; + _ay = y; + _arotation = rotation; + _ascaleX = scaleX; + _ascaleY = scaleY; + _ashearX = shearX; + _ashearY = shearY; + _appliedValid = true; - if (!parent) { /* Root bone. */ - float rotationY = rotation + 90 + shearY; - float sx = _skeleton.getScaleX(); - float sy = _skeleton.getScaleY(); - _a = MathUtil::cosDeg(rotation + shearX) * scaleX * sx; - _b = MathUtil::cosDeg(rotationY) * scaleY * sx; - _c = MathUtil::sinDeg(rotation + shearX) * scaleX * sy; - _d = MathUtil::sinDeg(rotationY) * scaleY * sy; - _worldX = x * sx + _skeleton.getX(); - _worldY = y * sy + _skeleton.getY(); - return; - } + if (!parent) { /* Root bone. */ + float rotationY = rotation + 90 + shearY; + float sx = _skeleton.getScaleX(); + float sy = _skeleton.getScaleY(); + _a = MathUtil::cosDeg(rotation + shearX) * scaleX * sx; + _b = MathUtil::cosDeg(rotationY) * scaleY * sx; + _c = MathUtil::sinDeg(rotation + shearX) * scaleX * sy; + _d = MathUtil::sinDeg(rotationY) * scaleY * sy; + _worldX = x * sx + _skeleton.getX(); + _worldY = y * sy + _skeleton.getY(); + return; + } - pa = parent->_a; - pb = parent->_b; - pc = parent->_c; - pd = parent->_d; + pa = parent->_a; + pb = parent->_b; + pc = parent->_c; + pd = parent->_d; - _worldX = pa * x + pb * y + parent->_worldX; - _worldY = pc * x + pd * y + parent->_worldY; + _worldX = pa * x + pb * y + parent->_worldX; + _worldY = pc * x + pd * y + parent->_worldY; - switch (_data.getTransformMode()) { - case TransformMode_Normal: { - float rotationY = rotation + 90 + shearY; - float la = MathUtil::cosDeg(rotation + shearX) * scaleX; - float lb = MathUtil::cosDeg(rotationY) * scaleY; - float lc = MathUtil::sinDeg(rotation + shearX) * scaleX; - float ld = MathUtil::sinDeg(rotationY) * scaleY; - _a = pa * la + pb * lc; - _b = pa * lb + pb * ld; - _c = pc * la + pd * lc; - _d = pc * lb + pd * ld; - return; - } - case TransformMode_OnlyTranslation: { - float rotationY = rotation + 90 + shearY; - _a = MathUtil::cosDeg(rotation + shearX) * scaleX; - _b = MathUtil::cosDeg(rotationY) * scaleY; - _c = MathUtil::sinDeg(rotation + shearX) * scaleX; - _d = MathUtil::sinDeg(rotationY) * scaleY; - break; - } - case TransformMode_NoRotationOrReflection: { - float s = pa * pa + pc * pc; - float prx, rx, ry, la, lb, lc, ld; - if (s > 0.0001f) { - s = MathUtil::abs(pa * pd - pb * pc) / s; - pb = pc * s; - pd = pa * s; - prx = MathUtil::atan2(pc, pa) * MathUtil::Rad_Deg; - } else { - pa = 0; - pc = 0; - prx = 90 - MathUtil::atan2(pd, pb) * MathUtil::Rad_Deg; - } - rx = rotation + shearX - prx; - ry = rotation + shearY - prx + 90; - la = MathUtil::cosDeg(rx) * scaleX; - lb = MathUtil::cosDeg(ry) * scaleY; - lc = MathUtil::sinDeg(rx) * scaleX; - ld = MathUtil::sinDeg(ry) * scaleY; - _a = pa * la - pb * lc; - _b = pa * lb - pb * ld; - _c = pc * la + pd * lc; - _d = pc * lb + pd * ld; - break; - } - case TransformMode_NoScale: - case TransformMode_NoScaleOrReflection: { - float za, zc, s; - float r, zb, zd, la, lb, lc, ld; - cosine = MathUtil::cosDeg(rotation); - sine = MathUtil::sinDeg(rotation); - za = (pa * cosine + pb * sine) / _skeleton.getScaleX(); - zc = (pc * cosine + pd * sine) / _skeleton.getScaleY(); - s = MathUtil::sqrt(za * za + zc * zc); - if (s > 0.00001f) s = 1 / s; - za *= s; - zc *= s; - s = MathUtil::sqrt(za * za + zc * zc); - if (_data.getTransformMode() == TransformMode_NoScale - && (pa * pd - pb * pc < 0) != (_skeleton.getScaleX() < 0 != _skeleton.getScaleY() < 0)) - s = -s; - r = MathUtil::Pi / 2 + MathUtil::atan2(zc, za); - zb = MathUtil::cos(r) * s; - zd = MathUtil::sin(r) * s; - la = MathUtil::cosDeg(shearX) * scaleX; - lb = MathUtil::cosDeg(90 + shearY) * scaleY; - lc = MathUtil::sinDeg(shearX) * scaleX; - ld = MathUtil::sinDeg(90 + shearY) * scaleY; - _a = za * la + zb * lc; - _b = za * lb + zb * ld; - _c = zc * la + zd * lc; - _d = zc * lb + zd * ld; - break; - } - } - _a *= _skeleton.getScaleX(); - _b *= _skeleton.getScaleX(); - _c *= _skeleton.getScaleY(); - _d *= _skeleton.getScaleY(); + switch (_data.getTransformMode()) { + case TransformMode_Normal: { + float rotationY = rotation + 90 + shearY; + float la = MathUtil::cosDeg(rotation + shearX) * scaleX; + float lb = MathUtil::cosDeg(rotationY) * scaleY; + float lc = MathUtil::sinDeg(rotation + shearX) * scaleX; + float ld = MathUtil::sinDeg(rotationY) * scaleY; + _a = pa * la + pb * lc; + _b = pa * lb + pb * ld; + _c = pc * la + pd * lc; + _d = pc * lb + pd * ld; + return; + } + case TransformMode_OnlyTranslation: { + float rotationY = rotation + 90 + shearY; + _a = MathUtil::cosDeg(rotation + shearX) * scaleX; + _b = MathUtil::cosDeg(rotationY) * scaleY; + _c = MathUtil::sinDeg(rotation + shearX) * scaleX; + _d = MathUtil::sinDeg(rotationY) * scaleY; + break; + } + case TransformMode_NoRotationOrReflection: { + float s = pa * pa + pc * pc; + float prx, rx, ry, la, lb, lc, ld; + if (s > 0.0001f) { + s = MathUtil::abs(pa * pd - pb * pc) / s; + pb = pc * s; + pd = pa * s; + prx = MathUtil::atan2(pc, pa) * MathUtil::Rad_Deg; + } else { + pa = 0; + pc = 0; + prx = 90 - MathUtil::atan2(pd, pb) * MathUtil::Rad_Deg; + } + rx = rotation + shearX - prx; + ry = rotation + shearY - prx + 90; + la = MathUtil::cosDeg(rx) * scaleX; + lb = MathUtil::cosDeg(ry) * scaleY; + lc = MathUtil::sinDeg(rx) * scaleX; + ld = MathUtil::sinDeg(ry) * scaleY; + _a = pa * la - pb * lc; + _b = pa * lb - pb * ld; + _c = pc * la + pd * lc; + _d = pc * lb + pd * ld; + break; + } + case TransformMode_NoScale: + case TransformMode_NoScaleOrReflection: { + float za, zc, s; + float r, zb, zd, la, lb, lc, ld; + cosine = MathUtil::cosDeg(rotation); + sine = MathUtil::sinDeg(rotation); + za = (pa * cosine + pb * sine) / _skeleton.getScaleX(); + zc = (pc * cosine + pd * sine) / _skeleton.getScaleY(); + s = MathUtil::sqrt(za * za + zc * zc); + if (s > 0.00001f) s = 1 / s; + za *= s; + zc *= s; + s = MathUtil::sqrt(za * za + zc * zc); + if (_data.getTransformMode() == TransformMode_NoScale && (pa * pd - pb * pc < 0) != (_skeleton.getScaleX() < 0 != _skeleton.getScaleY() < 0)) + s = -s; + r = MathUtil::Pi / 2 + MathUtil::atan2(zc, za); + zb = MathUtil::cos(r) * s; + zd = MathUtil::sin(r) * s; + la = MathUtil::cosDeg(shearX) * scaleX; + lb = MathUtil::cosDeg(90 + shearY) * scaleY; + lc = MathUtil::sinDeg(shearX) * scaleX; + ld = MathUtil::sinDeg(90 + shearY) * scaleY; + _a = za * la + zb * lc; + _b = za * lb + zb * ld; + _c = zc * la + zd * lc; + _d = zc * lb + zd * ld; + break; + } + } + _a *= _skeleton.getScaleX(); + _b *= _skeleton.getScaleX(); + _c *= _skeleton.getScaleY(); + _d *= _skeleton.getScaleY(); } void Bone::setToSetupPose() { - BoneData &data = _data; - _x = data.getX(); - _y = data.getY(); - _rotation = data.getRotation(); - _scaleX = data.getScaleX(); - _scaleY = data.getScaleY(); - _shearX = data.getShearX(); - _shearY = data.getShearY(); + BoneData &data = _data; + _x = data.getX(); + _y = data.getY(); + _rotation = data.getRotation(); + _scaleX = data.getScaleX(); + _scaleY = data.getScaleY(); + _shearX = data.getShearX(); + _shearY = data.getShearY(); } void Bone::worldToLocal(float worldX, float worldY, float &outLocalX, float &outLocalY) { - float a = _a; - float b = _b; - float c = _c; - float d = _d; + float a = _a; + float b = _b; + float c = _c; + float d = _d; - float invDet = 1 / (a * d - b * c); - float x = worldX - _worldX; - float y = worldY - _worldY; + float invDet = 1 / (a * d - b * c); + float x = worldX - _worldX; + float y = worldY - _worldY; - outLocalX = (x * d * invDet - y * b * invDet); - outLocalY = (y * a * invDet - x * c * invDet); + outLocalX = (x * d * invDet - y * b * invDet); + outLocalY = (y * a * invDet - x * c * invDet); } void Bone::localToWorld(float localX, float localY, float &outWorldX, float &outWorldY) { - outWorldX = localX * _a + localY * _b + _worldX; - outWorldY = localX * _c + localY * _d + _worldY; + outWorldX = localX * _a + localY * _b + _worldX; + outWorldY = localX * _c + localY * _d + _worldY; } float Bone::worldToLocalRotation(float worldRotation) { - float sin = MathUtil::sinDeg(worldRotation); - float cos = MathUtil::cosDeg(worldRotation); + float sin = MathUtil::sinDeg(worldRotation); + float cos = MathUtil::cosDeg(worldRotation); - return MathUtil::atan2(_a * sin - _c * cos, _d * cos - _b * sin) * MathUtil::Rad_Deg + this->_rotation - this->_shearX; + return MathUtil::atan2(_a * sin - _c * cos, _d * cos - _b * sin) * MathUtil::Rad_Deg + this->_rotation - this->_shearX; } float Bone::localToWorldRotation(float localRotation) { - localRotation -= this->_rotation - this->_shearX; - float sin = MathUtil::sinDeg(localRotation); - float cos = MathUtil::cosDeg(localRotation); + localRotation -= this->_rotation - this->_shearX; + float sin = MathUtil::sinDeg(localRotation); + float cos = MathUtil::cosDeg(localRotation); - return MathUtil::atan2(cos * _c + sin * _d, cos * _a + sin * _b) * MathUtil::Rad_Deg; + return MathUtil::atan2(cos * _c + sin * _d, cos * _a + sin * _b) * MathUtil::Rad_Deg; } void Bone::rotateWorld(float degrees) { - float a = _a; - float b = _b; - float c = _c; - float d = _d; + float a = _a; + float b = _b; + float c = _c; + float d = _d; - float cos = MathUtil::cosDeg(degrees); - float sin = MathUtil::sinDeg(degrees); + float cos = MathUtil::cosDeg(degrees); + float sin = MathUtil::sinDeg(degrees); - _a = cos * a - sin * c; - _b = cos * b - sin * d; - _c = sin * a + cos * c; - _d = sin * b + cos * d; + _a = cos * a - sin * c; + _b = cos * b - sin * d; + _c = sin * a + cos * c; + _d = sin * b + cos * d; - _appliedValid = false; + _appliedValid = false; } float Bone::getWorldToLocalRotationX() { - Bone *parent = _parent; - if (!parent) { - return _arotation; - } + Bone *parent = _parent; + if (!parent) { + return _arotation; + } - float pa = parent->_a; - float pb = parent->_b; - float pc = parent->_c; - float pd = parent->_d; - float a = _a; - float c = _c; + float pa = parent->_a; + float pb = parent->_b; + float pc = parent->_c; + float pd = parent->_d; + float a = _a; + float c = _c; - return MathUtil::atan2(pa * c - pc * a, pd * a - pb * c) * MathUtil::Rad_Deg; + return MathUtil::atan2(pa * c - pc * a, pd * a - pb * c) * MathUtil::Rad_Deg; } float Bone::getWorldToLocalRotationY() { - Bone *parent = _parent; - if (!parent) { - return _arotation; - } + Bone *parent = _parent; + if (!parent) { + return _arotation; + } - float pa = parent->_a; - float pb = parent->_b; - float pc = parent->_c; - float pd = parent->_d; - float b = _b; - float d = _d; + float pa = parent->_a; + float pb = parent->_b; + float pc = parent->_c; + float pd = parent->_d; + float b = _b; + float d = _d; - return MathUtil::atan2(pa * d - pc * b, pd * b - pb * d) * MathUtil::Rad_Deg; + return MathUtil::atan2(pa * d - pc * b, pd * b - pb * d) * MathUtil::Rad_Deg; } BoneData &Bone::getData() { - return _data; + return _data; } Skeleton &Bone::getSkeleton() { - return _skeleton; + return _skeleton; } Bone *Bone::getParent() { - return _parent; + return _parent; } Vector &Bone::getChildren() { - return _children; + return _children; } float Bone::getX() { - return _x; + return _x; } void Bone::setX(float inValue) { - _x = inValue; + _x = inValue; } float Bone::getY() { - return _y; + return _y; } void Bone::setY(float inValue) { - _y = inValue; + _y = inValue; } float Bone::getRotation() { - return _rotation; + return _rotation; } void Bone::setRotation(float inValue) { - _rotation = inValue; + _rotation = inValue; } float Bone::getScaleX() { - return _scaleX; + return _scaleX; } void Bone::setScaleX(float inValue) { - _scaleX = inValue; + _scaleX = inValue; } float Bone::getScaleY() { - return _scaleY; + return _scaleY; } void Bone::setScaleY(float inValue) { - _scaleY = inValue; + _scaleY = inValue; } float Bone::getShearX() { - return _shearX; + return _shearX; } void Bone::setShearX(float inValue) { - _shearX = inValue; + _shearX = inValue; } float Bone::getShearY() { - return _shearY; + return _shearY; } void Bone::setShearY(float inValue) { - _shearY = inValue; + _shearY = inValue; } float Bone::getAppliedRotation() { - return _arotation; + return _arotation; } void Bone::setAppliedRotation(float inValue) { - _arotation = inValue; + _arotation = inValue; } float Bone::getAX() { - return _ax; + return _ax; } void Bone::setAX(float inValue) { - _ax = inValue; + _ax = inValue; } float Bone::getAY() { - return _ay; + return _ay; } void Bone::setAY(float inValue) { - _ay = inValue; + _ay = inValue; } float Bone::getAScaleX() { - return _ascaleX; + return _ascaleX; } void Bone::setAScaleX(float inValue) { - _ascaleX = inValue; + _ascaleX = inValue; } float Bone::getAScaleY() { - return _ascaleY; + return _ascaleY; } void Bone::setAScaleY(float inValue) { - _ascaleY = inValue; + _ascaleY = inValue; } float Bone::getAShearX() { - return _ashearX; + return _ashearX; } void Bone::setAShearX(float inValue) { - _ashearX = inValue; + _ashearX = inValue; } float Bone::getAShearY() { - return _ashearY; + return _ashearY; } void Bone::setAShearY(float inValue) { - _ashearY = inValue; + _ashearY = inValue; } float Bone::getA() { - return _a; + return _a; } void Bone::setA(float inValue) { - _a = inValue; + _a = inValue; } float Bone::getB() { - return _b; + return _b; } void Bone::setB(float inValue) { - _b = inValue; + _b = inValue; } float Bone::getC() { - return _c; + return _c; } void Bone::setC(float inValue) { - _c = inValue; + _c = inValue; } float Bone::getD() { - return _d; + return _d; } void Bone::setD(float inValue) { - _d = inValue; + _d = inValue; } float Bone::getWorldX() { - return _worldX; + return _worldX; } void Bone::setWorldX(float inValue) { - _worldX = inValue; + _worldX = inValue; } float Bone::getWorldY() { - return _worldY; + return _worldY; } void Bone::setWorldY(float inValue) { - _worldY = inValue; + _worldY = inValue; } float Bone::getWorldRotationX() { - return MathUtil::atan2(_c, _a) * MathUtil::MathUtil::Rad_Deg; + return MathUtil::atan2(_c, _a) * MathUtil::MathUtil::Rad_Deg; } float Bone::getWorldRotationY() { - return MathUtil::atan2(_d, _b) * MathUtil::Rad_Deg; + return MathUtil::atan2(_d, _b) * MathUtil::Rad_Deg; } float Bone::getWorldScaleX() { - return MathUtil::sqrt(_a * _a + _c * _c); + return MathUtil::sqrt(_a * _a + _c * _c); } float Bone::getWorldScaleY() { - return MathUtil::sqrt(_b * _b + _d * _d); + return MathUtil::sqrt(_b * _b + _d * _d); } bool Bone::isAppliedValid() { - return _appliedValid; + return _appliedValid; } void Bone::setAppliedValid(bool valid) { - _appliedValid = valid; + _appliedValid = valid; } void Bone::updateAppliedTransform() { - Bone *parent = _parent; - _appliedValid = 1; - if (!parent) { - _ax = _worldX; - _ay = _worldY; - _arotation = MathUtil::atan2(_c, _a) * MathUtil::Rad_Deg; - _ascaleX = MathUtil::sqrt(_a * _a + _c * _c); - _ascaleY = MathUtil::sqrt(_b * _b + _d * _d); - _ashearX = 0; - _ashearY = MathUtil::atan2(_a * _b + _c * _d, _a * _d - _b * _c) * MathUtil::Rad_Deg; - } else { - float pa = parent->_a, pb = parent->_b, pc = parent->_c, pd = parent->_d; - float pid = 1 / (pa * pd - pb * pc); - float dx = _worldX - parent->_worldX, dy = _worldY - parent->_worldY; - float ia = pid * pd; - float id = pid * pa; - float ib = pid * pb; - float ic = pid * pc; - float ra = ia * _a - ib * _c; - float rb = ia * _b - ib * _d; - float rc = id * _c - ic * _a; - float rd = id * _d - ic * _b; - _ax = (dx * pd * pid - dy * pb * pid); - _ay = (dy * pa * pid - dx * pc * pid); - _ashearX = 0; - _ascaleX = MathUtil::sqrt(ra * ra + rc * rc); - if (_ascaleX > 0.0001f) { - float det = ra * rd - rb * rc; - _ascaleY = det / _ascaleX; - _ashearY = MathUtil::atan2(ra * rb + rc * rd, det) * MathUtil::Rad_Deg; - _arotation = MathUtil::atan2(rc, ra) * MathUtil::Rad_Deg; - } else { - _ascaleX = 0; - _ascaleY = MathUtil::sqrt(rb * rb + rd * rd); - _ashearY = 0; - _arotation = 90 - MathUtil::atan2(rd, rb) * MathUtil::Rad_Deg; - } - } + Bone *parent = _parent; + _appliedValid = 1; + if (!parent) { + _ax = _worldX; + _ay = _worldY; + _arotation = MathUtil::atan2(_c, _a) * MathUtil::Rad_Deg; + _ascaleX = MathUtil::sqrt(_a * _a + _c * _c); + _ascaleY = MathUtil::sqrt(_b * _b + _d * _d); + _ashearX = 0; + _ashearY = MathUtil::atan2(_a * _b + _c * _d, _a * _d - _b * _c) * MathUtil::Rad_Deg; + } else { + float pa = parent->_a, pb = parent->_b, pc = parent->_c, pd = parent->_d; + float pid = 1 / (pa * pd - pb * pc); + float dx = _worldX - parent->_worldX, dy = _worldY - parent->_worldY; + float ia = pid * pd; + float id = pid * pa; + float ib = pid * pb; + float ic = pid * pc; + float ra = ia * _a - ib * _c; + float rb = ia * _b - ib * _d; + float rc = id * _c - ic * _a; + float rd = id * _d - ic * _b; + _ax = (dx * pd * pid - dy * pb * pid); + _ay = (dy * pa * pid - dx * pc * pid); + _ashearX = 0; + _ascaleX = MathUtil::sqrt(ra * ra + rc * rc); + if (_ascaleX > 0.0001f) { + float det = ra * rd - rb * rc; + _ascaleY = det / _ascaleX; + _ashearY = MathUtil::atan2(ra * rb + rc * rd, det) * MathUtil::Rad_Deg; + _arotation = MathUtil::atan2(rc, ra) * MathUtil::Rad_Deg; + } else { + _ascaleX = 0; + _ascaleY = MathUtil::sqrt(rb * rb + rd * rd); + _ashearY = 0; + _arotation = 90 - MathUtil::atan2(rd, rb) * MathUtil::Rad_Deg; + } + } } bool Bone::isActive() { - return _active; + return _active; } void Bone::setActive(bool inValue) { - _active = inValue; + _active = inValue; } diff --git a/native/cocos/editor-support/spine/Bone.h b/native/cocos/editor-support/spine/Bone.h index 148c6c5c64..44b1583a9d 100644 --- a/native/cocos/editor-support/spine/Bone.h +++ b/native/cocos/editor-support/spine/Bone.h @@ -45,207 +45,207 @@ class Skeleton; /// local transform that can be applied to compute the world transform. The local transform and applied transform may differ if a /// constraint or application code modifies the world transform after it was computed from the local transform. class SP_API Bone : public Updatable { - friend class AnimationState; + friend class AnimationState; - friend class RotateTimeline; + friend class RotateTimeline; - friend class IkConstraint; + friend class IkConstraint; - friend class TransformConstraint; + friend class TransformConstraint; - friend class VertexAttachment; + friend class VertexAttachment; - friend class PathConstraint; + friend class PathConstraint; - friend class Skeleton; + friend class Skeleton; - friend class RegionAttachment; + friend class RegionAttachment; - friend class PointAttachment; + friend class PointAttachment; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; -RTTI_DECL + RTTI_DECL public: - static void setYDown(bool inValue); + static void setYDown(bool inValue); - static bool isYDown(); + static bool isYDown(); - /// @param parent May be NULL. - Bone(BoneData &data, Skeleton &skeleton, Bone *parent = NULL); + /// @param parent May be NULL. + Bone(BoneData &data, Skeleton &skeleton, Bone *parent = NULL); - /// Same as updateWorldTransform. This method exists for Bone to implement Spine::Updatable. - virtual void update(); + /// Same as updateWorldTransform. This method exists for Bone to implement Spine::Updatable. + virtual void update(); - /// Computes the world transform using the parent bone and this bone's local transform. - void updateWorldTransform(); + /// Computes the world transform using the parent bone and this bone's local transform. + void updateWorldTransform(); - /// Computes the world transform using the parent bone and the specified local transform. - void updateWorldTransform(float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY); + /// Computes the world transform using the parent bone and the specified local transform. + void updateWorldTransform(float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY); - void setToSetupPose(); + void setToSetupPose(); - void worldToLocal(float worldX, float worldY, float &outLocalX, float &outLocalY); + void worldToLocal(float worldX, float worldY, float &outLocalX, float &outLocalY); - void localToWorld(float localX, float localY, float &outWorldX, float &outWorldY); + void localToWorld(float localX, float localY, float &outWorldX, float &outWorldY); - float worldToLocalRotation(float worldRotation); + float worldToLocalRotation(float worldRotation); - float localToWorldRotation(float localRotation); + float localToWorldRotation(float localRotation); - /// Rotates the world transform the specified amount and sets isAppliedValid to false. - /// @param degrees Degrees. - void rotateWorld(float degrees); + /// Rotates the world transform the specified amount and sets isAppliedValid to false. + /// @param degrees Degrees. + void rotateWorld(float degrees); - float getWorldToLocalRotationX(); + float getWorldToLocalRotationX(); - float getWorldToLocalRotationY(); + float getWorldToLocalRotationY(); - BoneData &getData(); + BoneData &getData(); - Skeleton &getSkeleton(); + Skeleton &getSkeleton(); - Bone *getParent(); + Bone *getParent(); - Vector &getChildren(); + Vector &getChildren(); - /// The local X translation. - float getX(); + /// The local X translation. + float getX(); - void setX(float inValue); + void setX(float inValue); - /// The local Y translation. - float getY(); + /// The local Y translation. + float getY(); - void setY(float inValue); + void setY(float inValue); - /// The local rotation. - float getRotation(); + /// The local rotation. + float getRotation(); - void setRotation(float inValue); + void setRotation(float inValue); - /// The local scaleX. - float getScaleX(); + /// The local scaleX. + float getScaleX(); - void setScaleX(float inValue); + void setScaleX(float inValue); - /// The local scaleY. - float getScaleY(); + /// The local scaleY. + float getScaleY(); - void setScaleY(float inValue); + void setScaleY(float inValue); - /// The local shearX. - float getShearX(); + /// The local shearX. + float getShearX(); - void setShearX(float inValue); + void setShearX(float inValue); - /// The local shearY. - float getShearY(); + /// The local shearY. + float getShearY(); - void setShearY(float inValue); + void setShearY(float inValue); - /// The rotation, as calculated by any constraints. - float getAppliedRotation(); + /// The rotation, as calculated by any constraints. + float getAppliedRotation(); - void setAppliedRotation(float inValue); + void setAppliedRotation(float inValue); - /// The applied local x translation. - float getAX(); + /// The applied local x translation. + float getAX(); - void setAX(float inValue); + void setAX(float inValue); - /// The applied local y translation. - float getAY(); + /// The applied local y translation. + float getAY(); - void setAY(float inValue); + void setAY(float inValue); - /// The applied local scaleX. - float getAScaleX(); + /// The applied local scaleX. + float getAScaleX(); - void setAScaleX(float inValue); + void setAScaleX(float inValue); - /// The applied local scaleY. - float getAScaleY(); + /// The applied local scaleY. + float getAScaleY(); - void setAScaleY(float inValue); + void setAScaleY(float inValue); - /// The applied local shearX. - float getAShearX(); + /// The applied local shearX. + float getAShearX(); - void setAShearX(float inValue); + void setAShearX(float inValue); - /// The applied local shearY. - float getAShearY(); + /// The applied local shearY. + float getAShearY(); - void setAShearY(float inValue); + void setAShearY(float inValue); - float getA(); + float getA(); - void setA(float inValue); + void setA(float inValue); - float getB(); + float getB(); - void setB(float inValue); + void setB(float inValue); - float getC(); + float getC(); - void setC(float inValue); + void setC(float inValue); - float getD(); + float getD(); - void setD(float inValue); + void setD(float inValue); - float getWorldX(); + float getWorldX(); - void setWorldX(float inValue); + void setWorldX(float inValue); - float getWorldY(); + float getWorldY(); - void setWorldY(float inValue); + void setWorldY(float inValue); - float getWorldRotationX(); + float getWorldRotationX(); - float getWorldRotationY(); + float getWorldRotationY(); - /// Returns the magnitide (always positive) of the world scale X. - float getWorldScaleX(); + /// Returns the magnitide (always positive) of the world scale X. + float getWorldScaleX(); - /// Returns the magnitide (always positive) of the world scale Y. - float getWorldScaleY(); + /// Returns the magnitide (always positive) of the world scale Y. + float getWorldScaleY(); - bool isAppliedValid(); - void setAppliedValid(bool valid); + bool isAppliedValid(); + void setAppliedValid(bool valid); - bool isActive(); + bool isActive(); - void setActive(bool inValue); + void setActive(bool inValue); private: - static bool yDown; + static bool yDown; - BoneData &_data; - Skeleton &_skeleton; - Bone *_parent; - Vector _children; - float _x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY; - float _ax, _ay, _arotation, _ascaleX, _ascaleY, _ashearX, _ashearY; - bool _appliedValid; - float _a, _b, _worldX; - float _c, _d, _worldY; - bool _sorted; - bool _active; + BoneData &_data; + Skeleton &_skeleton; + Bone *_parent; + Vector _children; + float _x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY; + float _ax, _ay, _arotation, _ascaleX, _ascaleY, _ashearX, _ashearY; + bool _appliedValid; + float _a, _b, _worldX; + float _c, _d, _worldY; + bool _sorted; + bool _active; - /// Computes the individual applied transform values from the world transform. This can be useful to perform processing using - /// the applied transform after the world transform has been modified directly (eg, by a constraint).. - /// - /// Some information is ambiguous in the world transform, such as -1,-1 scale versus 180 rotation. - void updateAppliedTransform(); + /// Computes the individual applied transform values from the world transform. This can be useful to perform processing using + /// the applied transform after the world transform has been modified directly (eg, by a constraint).. + /// + /// Some information is ambiguous in the world transform, such as -1,-1 scale versus 180 rotation. + void updateAppliedTransform(); }; -} +} // namespace spine #endif /* Spine_Bone_h */ diff --git a/native/cocos/editor-support/spine/BoneData.cpp b/native/cocos/editor-support/spine/BoneData.cpp index 36a3221631..c6720b7a12 100644 --- a/native/cocos/editor-support/spine/BoneData.cpp +++ b/native/cocos/editor-support/spine/BoneData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,112 +37,111 @@ using namespace spine; -BoneData::BoneData(int index, const String &name, BoneData *parent) : - _index(index), - _name(name), - _parent(parent), - _length(0), - _x(0), - _y(0), - _rotation(0), - _scaleX(1), - _scaleY(1), - _shearX(0), - _shearY(0), - _transformMode(TransformMode_Normal), - _skinRequired(false) { - assert(index >= 0); - assert(_name.length() > 0); +BoneData::BoneData(int index, const String &name, BoneData *parent) : _index(index), + _name(name), + _parent(parent), + _length(0), + _x(0), + _y(0), + _rotation(0), + _scaleX(1), + _scaleY(1), + _shearX(0), + _shearY(0), + _transformMode(TransformMode_Normal), + _skinRequired(false) { + assert(index >= 0); + assert(_name.length() > 0); } int BoneData::getIndex() { - return _index; + return _index; } const String &BoneData::getName() { - return _name; + return _name; } BoneData *BoneData::getParent() { - return _parent; + return _parent; } float BoneData::getLength() { - return _length; + return _length; } void BoneData::setLength(float inValue) { - _length = inValue; + _length = inValue; } float BoneData::getX() { - return _x; + return _x; } void BoneData::setX(float inValue) { - _x = inValue; + _x = inValue; } float BoneData::getY() { - return _y; + return _y; } void BoneData::setY(float inValue) { - _y = inValue; + _y = inValue; } float BoneData::getRotation() { - return _rotation; + return _rotation; } void BoneData::setRotation(float inValue) { - _rotation = inValue; + _rotation = inValue; } float BoneData::getScaleX() { - return _scaleX; + return _scaleX; } void BoneData::setScaleX(float inValue) { - _scaleX = inValue; + _scaleX = inValue; } float BoneData::getScaleY() { - return _scaleY; + return _scaleY; } void BoneData::setScaleY(float inValue) { - _scaleY = inValue; + _scaleY = inValue; } float BoneData::getShearX() { - return _shearX; + return _shearX; } void BoneData::setShearX(float inValue) { - _shearX = inValue; + _shearX = inValue; } float BoneData::getShearY() { - return _shearY; + return _shearY; } void BoneData::setShearY(float inValue) { - _shearY = inValue; + _shearY = inValue; } TransformMode BoneData::getTransformMode() { - return _transformMode; + return _transformMode; } void BoneData::setTransformMode(TransformMode inValue) { - _transformMode = inValue; + _transformMode = inValue; } bool BoneData::isSkinRequired() { - return _skinRequired; + return _skinRequired; } void BoneData::setSkinRequired(bool inValue) { - _skinRequired = inValue; + _skinRequired = inValue; } diff --git a/native/cocos/editor-support/spine/BoneData.h b/native/cocos/editor-support/spine/BoneData.h index bd997f6515..3922631885 100644 --- a/native/cocos/editor-support/spine/BoneData.h +++ b/native/cocos/editor-support/spine/BoneData.h @@ -36,88 +36,88 @@ namespace spine { class SP_API BoneData : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; - friend class AnimationState; + friend class AnimationState; - friend class RotateTimeline; + friend class RotateTimeline; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; public: - BoneData(int index, const String &name, BoneData *parent = NULL); + BoneData(int index, const String &name, BoneData *parent = NULL); - /// The index of the bone in Skeleton.Bones - int getIndex(); + /// The index of the bone in Skeleton.Bones + int getIndex(); - /// The name of the bone, which is unique within the skeleton. - const String &getName(); + /// The name of the bone, which is unique within the skeleton. + const String &getName(); - /// May be NULL. - BoneData *getParent(); + /// May be NULL. + BoneData *getParent(); - float getLength(); + float getLength(); - void setLength(float inValue); + void setLength(float inValue); - /// Local X translation. - float getX(); + /// Local X translation. + float getX(); - void setX(float inValue); + void setX(float inValue); - /// Local Y translation. - float getY(); + /// Local Y translation. + float getY(); - void setY(float inValue); + void setY(float inValue); - /// Local rotation. - float getRotation(); + /// Local rotation. + float getRotation(); - void setRotation(float inValue); + void setRotation(float inValue); - /// Local scaleX. - float getScaleX(); + /// Local scaleX. + float getScaleX(); - void setScaleX(float inValue); + void setScaleX(float inValue); - /// Local scaleY. - float getScaleY(); + /// Local scaleY. + float getScaleY(); - void setScaleY(float inValue); + void setScaleY(float inValue); - /// Local shearX. - float getShearX(); + /// Local shearX. + float getShearX(); - void setShearX(float inValue); + void setShearX(float inValue); - /// Local shearY. - float getShearY(); + /// Local shearY. + float getShearY(); - void setShearY(float inValue); + void setShearY(float inValue); - /// The transform mode for how parent world transforms affect this bone. - TransformMode getTransformMode(); + /// The transform mode for how parent world transforms affect this bone. + TransformMode getTransformMode(); - void setTransformMode(TransformMode inValue); + void setTransformMode(TransformMode inValue); - bool isSkinRequired(); - void setSkinRequired(bool inValue); + bool isSkinRequired(); + void setSkinRequired(bool inValue); private: - const int _index; - const String _name; - BoneData *_parent; - float _length; - float _x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY; - TransformMode _transformMode; - bool _skinRequired; + const int _index; + const String _name; + BoneData *_parent; + float _length; + float _x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY; + TransformMode _transformMode; + bool _skinRequired; }; -} +} // namespace spine #endif /* Spine_BoneData_h */ diff --git a/native/cocos/editor-support/spine/BoundingBoxAttachment.cpp b/native/cocos/editor-support/spine/BoundingBoxAttachment.cpp index 918493a7ee..1ff2e5f94d 100644 --- a/native/cocos/editor-support/spine/BoundingBoxAttachment.cpp +++ b/native/cocos/editor-support/spine/BoundingBoxAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,11 +37,11 @@ using namespace spine; RTTI_IMPL(BoundingBoxAttachment, VertexAttachment) -BoundingBoxAttachment::BoundingBoxAttachment(const String &name) : VertexAttachment(name) { +BoundingBoxAttachment::BoundingBoxAttachment(const String& name) : VertexAttachment(name) { } Attachment* BoundingBoxAttachment::copy() { - BoundingBoxAttachment* copy = new (__FILE__, __LINE__) BoundingBoxAttachment(getName()); - copyTo(copy); - return copy; + BoundingBoxAttachment* copy = new (__FILE__, __LINE__) BoundingBoxAttachment(getName()); + copyTo(copy); + return copy; } diff --git a/native/cocos/editor-support/spine/BoundingBoxAttachment.h b/native/cocos/editor-support/spine/BoundingBoxAttachment.h index 7118c70242..bffe86b06e 100644 --- a/native/cocos/editor-support/spine/BoundingBoxAttachment.h +++ b/native/cocos/editor-support/spine/BoundingBoxAttachment.h @@ -34,14 +34,14 @@ #include namespace spine { - /// Attachment that has a polygon for bounds checking. - class SP_API BoundingBoxAttachment : public VertexAttachment { - RTTI_DECL +/// Attachment that has a polygon for bounds checking. +class SP_API BoundingBoxAttachment : public VertexAttachment { + RTTI_DECL - explicit BoundingBoxAttachment(const String& name); + explicit BoundingBoxAttachment(const String& name); - virtual Attachment* copy(); - }; -} + virtual Attachment* copy(); +}; +} // namespace spine #endif /* Spine_BoundingBoxAttachment_h */ diff --git a/native/cocos/editor-support/spine/ClippingAttachment.cpp b/native/cocos/editor-support/spine/ClippingAttachment.cpp index b1a54619da..e8ff0422fa 100644 --- a/native/cocos/editor-support/spine/ClippingAttachment.cpp +++ b/native/cocos/editor-support/spine/ClippingAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -43,16 +43,16 @@ ClippingAttachment::ClippingAttachment(const String &name) : VertexAttachment(na } SlotData *ClippingAttachment::getEndSlot() { - return _endSlot; + return _endSlot; } void ClippingAttachment::setEndSlot(SlotData *inValue) { - _endSlot = inValue; + _endSlot = inValue; } -Attachment* ClippingAttachment::copy() { - ClippingAttachment* copy = new (__FILE__, __LINE__) ClippingAttachment(getName()); - copyTo(copy); - copy->_endSlot = _endSlot; - return copy; +Attachment *ClippingAttachment::copy() { + ClippingAttachment *copy = new (__FILE__, __LINE__) ClippingAttachment(getName()); + copyTo(copy); + copy->_endSlot = _endSlot; + return copy; } diff --git a/native/cocos/editor-support/spine/ClippingAttachment.h b/native/cocos/editor-support/spine/ClippingAttachment.h index 21834cb4a6..bd21e223ea 100644 --- a/native/cocos/editor-support/spine/ClippingAttachment.h +++ b/native/cocos/editor-support/spine/ClippingAttachment.h @@ -33,27 +33,27 @@ #include namespace spine { - class SlotData; +class SlotData; - class SP_API ClippingAttachment : public VertexAttachment { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API ClippingAttachment : public VertexAttachment { + friend class SkeletonBinary; + friend class SkeletonJson; - friend class SkeletonClipping; + friend class SkeletonClipping; - RTTI_DECL + RTTI_DECL - public: - explicit ClippingAttachment(const String& name); +public: + explicit ClippingAttachment(const String& name); - SlotData* getEndSlot(); - void setEndSlot(SlotData* inValue); + SlotData* getEndSlot(); + void setEndSlot(SlotData* inValue); - virtual Attachment* copy(); + virtual Attachment* copy(); - private: - SlotData* _endSlot; - }; -} +private: + SlotData* _endSlot; +}; +} // namespace spine #endif /* Spine_ClippingAttachment_h */ diff --git a/native/cocos/editor-support/spine/Color.h b/native/cocos/editor-support/spine/Color.h index 1f288f7a86..f56b5c83d1 100644 --- a/native/cocos/editor-support/spine/Color.h +++ b/native/cocos/editor-support/spine/Color.h @@ -35,60 +35,59 @@ namespace spine { class SP_API Color : public SpineObject { public: - Color() : r(0), g(0), b(0), a(0) { - } + Color() : r(0), g(0), b(0), a(0) { + } - Color(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) { - clamp(); - } + Color(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) { + clamp(); + } - inline Color &set(float _r, float _g, float _b, float _a) { - this->r = _r; - this->g = _g; - this->b = _b; - this->a = _a; - clamp(); - return *this; - } + inline Color &set(float _r, float _g, float _b, float _a) { + this->r = _r; + this->g = _g; + this->b = _b; + this->a = _a; + clamp(); + return *this; + } - inline Color &set(const Color &other) { - r = other.r; - g = other.g; - b = other.b; - a = other.a; - clamp(); - return *this; - } + inline Color &set(const Color &other) { + r = other.r; + g = other.g; + b = other.b; + a = other.a; + clamp(); + return *this; + } - inline Color &add(float _r, float _g, float _b, float _a) { - this->r += _r; - this->g += _g; - this->b += _b; - this->a += _a; - clamp(); - return *this; - } + inline Color &add(float _r, float _g, float _b, float _a) { + this->r += _r; + this->g += _g; + this->b += _b; + this->a += _a; + clamp(); + return *this; + } - inline Color &add(const Color &other) { - r += other.r; - g += other.g; - b += other.b; - a += other.a; - clamp(); - return *this; - } + inline Color &add(const Color &other) { + r += other.r; + g += other.g; + b += other.b; + a += other.a; + clamp(); + return *this; + } - inline Color &clamp() { - r = MathUtil::clamp(this->r, 0, 1); - g = MathUtil::clamp(this->g, 0, 1); - b = MathUtil::clamp(this->b, 0, 1); - a = MathUtil::clamp(this->a, 0, 1); - return *this; - } + inline Color &clamp() { + r = MathUtil::clamp(this->r, 0, 1); + g = MathUtil::clamp(this->g, 0, 1); + b = MathUtil::clamp(this->b, 0, 1); + a = MathUtil::clamp(this->a, 0, 1); + return *this; + } - float r, g, b, a; + float r, g, b, a; }; -} - +} // namespace spine #endif //SPINE_COLOR_H diff --git a/native/cocos/editor-support/spine/ColorTimeline.cpp b/native/cocos/editor-support/spine/ColorTimeline.cpp index b01bd29fdf..6b7a44b85a 100644 --- a/native/cocos/editor-support/spine/ColorTimeline.cpp +++ b/native/cocos/editor-support/spine/ColorTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -58,88 +58,87 @@ const int ColorTimeline::B = 3; const int ColorTimeline::A = 4; ColorTimeline::ColorTimeline(int frameCount) : CurveTimeline(frameCount), _slotIndex(0) { - _frames.setSize(frameCount * ENTRIES, 0); + _frames.setSize(frameCount * ENTRIES, 0); } void ColorTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Slot *slotP = skeleton._slots[_slotIndex]; - Slot &slot = *slotP; - if (!slot._bone.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - slot._color.set(slot._data._color); - return; - case MixBlend_First: { - Color &color = slot._color, setup = slot._data._color; - color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, - (setup.a - color.a) * alpha); - } - default: ; - } - return; - } + Slot *slotP = skeleton._slots[_slotIndex]; + Slot &slot = *slotP; + if (!slot._bone.isActive()) return; + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + slot._color.set(slot._data._color); + return; + case MixBlend_First: { + Color &color = slot._color, setup = slot._data._color; + color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, + (setup.a - color.a) * alpha); + } + default:; + } + return; + } - float r, g, b, a; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - size_t i = _frames.size(); - r = _frames[i + PREV_R]; - g = _frames[i + PREV_G]; - b = _frames[i + PREV_B]; - a = _frames[i + PREV_A]; - } else { - // Interpolate between the previous frame and the current frame. - size_t frame = (size_t)Animation::binarySearch(_frames, time, ENTRIES); - r = _frames[frame + PREV_R]; - g = _frames[frame + PREV_G]; - b = _frames[frame + PREV_B]; - a = _frames[frame + PREV_A]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float r, g, b, a; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + size_t i = _frames.size(); + r = _frames[i + PREV_R]; + g = _frames[i + PREV_G]; + b = _frames[i + PREV_B]; + a = _frames[i + PREV_A]; + } else { + // Interpolate between the previous frame and the current frame. + size_t frame = (size_t)Animation::binarySearch(_frames, time, ENTRIES); + r = _frames[frame + PREV_R]; + g = _frames[frame + PREV_G]; + b = _frames[frame + PREV_B]; + a = _frames[frame + PREV_A]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - r += (_frames[frame + R] - r) * percent; - g += (_frames[frame + G] - g) * percent; - b += (_frames[frame + B] - b) * percent; - a += (_frames[frame + A] - a) * percent; - } + r += (_frames[frame + R] - r) * percent; + g += (_frames[frame + G] - g) * percent; + b += (_frames[frame + B] - b) * percent; + a += (_frames[frame + A] - a) * percent; + } - if (alpha == 1) { - slot.getColor().set(r, g, b, a); - } else { - Color &color = slot.getColor(); - if (blend == MixBlend_Setup) color.set(slot.getData().getColor()); - color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha); - } + if (alpha == 1) { + slot.getColor().set(r, g, b, a); + } else { + Color &color = slot.getColor(); + if (blend == MixBlend_Setup) color.set(slot.getData().getColor()); + color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha); + } } int ColorTimeline::getPropertyId() { - return ((int) TimelineType_Color << 24) + _slotIndex; + return ((int)TimelineType_Color << 24) + _slotIndex; } void ColorTimeline::setFrame(int frameIndex, float time, float r, float g, float b, float a) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + R] = r; - _frames[frameIndex + G] = g; - _frames[frameIndex + B] = b; - _frames[frameIndex + A] = a; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + R] = r; + _frames[frameIndex + G] = g; + _frames[frameIndex + B] = b; + _frames[frameIndex + A] = a; } int ColorTimeline::getSlotIndex() { - return _slotIndex; + return _slotIndex; } void ColorTimeline::setSlotIndex(int inValue) { - _slotIndex = inValue; + _slotIndex = inValue; } Vector &ColorTimeline::getFrames() { - return _frames; + return _frames; } diff --git a/native/cocos/editor-support/spine/ColorTimeline.h b/native/cocos/editor-support/spine/ColorTimeline.h index 3d3540060d..6c02f6ddf9 100644 --- a/native/cocos/editor-support/spine/ColorTimeline.h +++ b/native/cocos/editor-support/spine/ColorTimeline.h @@ -34,47 +34,47 @@ namespace spine { class SP_API ColorTimeline : public CurveTimeline { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; -RTTI_DECL + RTTI_DECL public: - static const int ENTRIES; + static const int ENTRIES; - explicit ColorTimeline(int frameCount); + explicit ColorTimeline(int frameCount); - virtual void - apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, MixBlend blend, - MixDirection direction); + virtual void + apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, MixBlend blend, + MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, float r, float g, float b, float a); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, float r, float g, float b, float a); - int getSlotIndex(); + int getSlotIndex(); - void setSlotIndex(int inValue); + void setSlotIndex(int inValue); - Vector &getFrames(); + Vector &getFrames(); protected: - static const int PREV_TIME; - static const int PREV_R; - static const int PREV_G; - static const int PREV_B; - static const int PREV_A; - static const int R; - static const int G; - static const int B; - static const int A; + static const int PREV_TIME; + static const int PREV_R; + static const int PREV_G; + static const int PREV_B; + static const int PREV_A; + static const int R; + static const int G; + static const int B; + static const int A; private: - int _slotIndex; - Vector _frames; + int _slotIndex; + Vector _frames; }; -} +} // namespace spine #endif /* Spine_ColorTimeline_h */ diff --git a/native/cocos/editor-support/spine/Constraint.cpp b/native/cocos/editor-support/spine/Constraint.cpp index 39ca6656ab..444c042a67 100644 --- a/native/cocos/editor-support/spine/Constraint.cpp +++ b/native/cocos/editor-support/spine/Constraint.cpp @@ -29,7 +29,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include diff --git a/native/cocos/editor-support/spine/Constraint.h b/native/cocos/editor-support/spine/Constraint.h index 3d42586eb5..b3f6875fd4 100644 --- a/native/cocos/editor-support/spine/Constraint.h +++ b/native/cocos/editor-support/spine/Constraint.h @@ -36,18 +36,18 @@ namespace spine { /// The interface for all constraints. class SP_API Constraint : public Updatable { -RTTI_DECL + RTTI_DECL public: - Constraint(); + Constraint(); - virtual ~Constraint(); + virtual ~Constraint(); - virtual void update() = 0; + virtual void update() = 0; - /// The ordinal for the order a skeleton's constraints will be applied. - virtual int getOrder() = 0; + /// The ordinal for the order a skeleton's constraints will be applied. + virtual int getOrder() = 0; }; -} +} // namespace spine #endif /* Spine_Constraint_h */ diff --git a/native/cocos/editor-support/spine/ConstraintData.cpp b/native/cocos/editor-support/spine/ConstraintData.cpp index 9e4e313ee3..59547a9d2a 100644 --- a/native/cocos/editor-support/spine/ConstraintData.cpp +++ b/native/cocos/editor-support/spine/ConstraintData.cpp @@ -28,35 +28,35 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include using namespace spine; -ConstraintData::ConstraintData(const String& name): _name(name), _order(0), _skinRequired(false) { +ConstraintData::ConstraintData(const String& name) : _name(name), _order(0), _skinRequired(false) { } ConstraintData::~ConstraintData() { } const String& ConstraintData::getName() { - return _name; + return _name; } size_t ConstraintData::getOrder() { - return _order; + return _order; } void ConstraintData::setOrder(size_t inValue) { - _order = inValue; + _order = inValue; } bool ConstraintData::isSkinRequired() { - return _skinRequired; + return _skinRequired; } void ConstraintData::setSkinRequired(bool inValue) { - _skinRequired = inValue; + _skinRequired = inValue; } diff --git a/native/cocos/editor-support/spine/ConstraintData.h b/native/cocos/editor-support/spine/ConstraintData.h index 1f928a96b6..0d3cf0bb9f 100644 --- a/native/cocos/editor-support/spine/ConstraintData.h +++ b/native/cocos/editor-support/spine/ConstraintData.h @@ -36,28 +36,27 @@ namespace spine { /// The interface for all constraints. class SP_API ConstraintData : public SpineObject { - public: - ConstraintData(const String& name); + ConstraintData(const String& name); - virtual ~ConstraintData(); + virtual ~ConstraintData(); - /// The IK constraint's name, which is unique within the skeleton. - const String& getName(); + /// The IK constraint's name, which is unique within the skeleton. + const String& getName(); - /// The ordinal for the order a skeleton's constraints will be applied. - size_t getOrder(); - void setOrder(size_t inValue); + /// The ordinal for the order a skeleton's constraints will be applied. + size_t getOrder(); + void setOrder(size_t inValue); - /// Whether the constraint is only active for a specific skin. - bool isSkinRequired(); - void setSkinRequired(bool inValue); + /// Whether the constraint is only active for a specific skin. + bool isSkinRequired(); + void setSkinRequired(bool inValue); private: - const String _name; - size_t _order; - bool _skinRequired; + const String _name; + size_t _order; + bool _skinRequired; }; -} +} // namespace spine #endif /* Spine_Constraint_h */ diff --git a/native/cocos/editor-support/spine/ContainerUtil.h b/native/cocos/editor-support/spine/ContainerUtil.h index af0a2bc2a4..cba102a9a9 100644 --- a/native/cocos/editor-support/spine/ContainerUtil.h +++ b/native/cocos/editor-support/spine/ContainerUtil.h @@ -39,89 +39,89 @@ #include namespace spine { - class SP_API ContainerUtil : public SpineObject { - public: - /// Finds an item by comparing each item's name. - /// It is more efficient to cache the results of this method than to call it multiple times. - /// @return May be NULL. - template - static T* findWithName(Vector& items, const String& name) { - assert(name.length() > 0); +class SP_API ContainerUtil : public SpineObject { +public: + /// Finds an item by comparing each item's name. + /// It is more efficient to cache the results of this method than to call it multiple times. + /// @return May be NULL. + template + static T* findWithName(Vector& items, const String& name) { + assert(name.length() > 0); - for (size_t i = 0; i < items.size(); ++i) { - T* item = items[i]; - if (item->getName() == name) { - return item; - } - } + for (size_t i = 0; i < items.size(); ++i) { + T* item = items[i]; + if (item->getName() == name) { + return item; + } + } - return NULL; - } + return NULL; + } - /// @return -1 if the item was not found. - template - static int findIndexWithName(Vector& items, const String& name) { - assert(name.length() > 0); + /// @return -1 if the item was not found. + template + static int findIndexWithName(Vector& items, const String& name) { + assert(name.length() > 0); - for (size_t i = 0, len = items.size(); i < len; ++i) { - T* item = items[i]; - if (item->getName() == name) { - return static_cast(i); - } - } + for (size_t i = 0, len = items.size(); i < len; ++i) { + T* item = items[i]; + if (item->getName() == name) { + return static_cast(i); + } + } - return -1; - } + return -1; + } - /// Finds an item by comparing each item's name. - /// It is more efficient to cache the results of this method than to call it multiple times. - /// @return May be NULL. - template - static T* findWithDataName(Vector& items, const String& name) { - assert(name.length() > 0); + /// Finds an item by comparing each item's name. + /// It is more efficient to cache the results of this method than to call it multiple times. + /// @return May be NULL. + template + static T* findWithDataName(Vector& items, const String& name) { + assert(name.length() > 0); - for (size_t i = 0; i < items.size(); ++i) { - T* item = items[i]; - if (item->getData().getName() == name) { - return item; - } - } + for (size_t i = 0; i < items.size(); ++i) { + T* item = items[i]; + if (item->getData().getName() == name) { + return item; + } + } - return NULL; - } + return NULL; + } - /// @return -1 if the item was not found. - template - static int findIndexWithDataName(Vector& items, const String& name) { - assert(name.length() > 0); + /// @return -1 if the item was not found. + template + static int findIndexWithDataName(Vector& items, const String& name) { + assert(name.length() > 0); - for (size_t i = 0, len = items.size(); i < len; ++i) { - T* item = items[i]; - if (item->getData().getName() == name) { - return static_cast(i); - } - } + for (size_t i = 0, len = items.size(); i < len; ++i) { + T* item = items[i]; + if (item->getData().getName() == name) { + return static_cast(i); + } + } - return -1; - } + return -1; + } - template - static void cleanUpVectorOfPointers(Vector& items) { - for (int i = (int)items.size() - 1; i >= 0; i--) { - T* item = items[i]; + template + static void cleanUpVectorOfPointers(Vector& items) { + for (int i = (int)items.size() - 1; i >= 0; i--) { + T* item = items[i]; - delete item; + delete item; - items.removeAt(i); - } - } + items.removeAt(i); + } + } - private: - // ctor, copy ctor, and assignment should be private in a Singleton - ContainerUtil(); - ContainerUtil(const ContainerUtil&); - ContainerUtil& operator=(const ContainerUtil&); - }; -} +private: + // ctor, copy ctor, and assignment should be private in a Singleton + ContainerUtil(); + ContainerUtil(const ContainerUtil&); + ContainerUtil& operator=(const ContainerUtil&); +}; +} // namespace spine #endif /* Spine_ContainerUtil_h */ diff --git a/native/cocos/editor-support/spine/CurveTimeline.cpp b/native/cocos/editor-support/spine/CurveTimeline.cpp index 92e9a08d54..8149465ca7 100644 --- a/native/cocos/editor-support/spine/CurveTimeline.cpp +++ b/native/cocos/editor-support/spine/CurveTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -45,83 +45,83 @@ const float CurveTimeline::BEZIER = 2; const int CurveTimeline::BEZIER_SIZE = 10 * 2 - 1; CurveTimeline::CurveTimeline(int frameCount) { - assert(frameCount > 0); + assert(frameCount > 0); - _curves.setSize((frameCount - 1) * BEZIER_SIZE, 0); + _curves.setSize((frameCount - 1) * BEZIER_SIZE, 0); } CurveTimeline::~CurveTimeline() { } size_t CurveTimeline::getFrameCount() { - return _curves.size() / BEZIER_SIZE + 1; + return _curves.size() / BEZIER_SIZE + 1; } void CurveTimeline::setLinear(size_t frameIndex) { - _curves[frameIndex * BEZIER_SIZE] = LINEAR; + _curves[frameIndex * BEZIER_SIZE] = LINEAR; } void CurveTimeline::setStepped(size_t frameIndex) { - _curves[frameIndex * BEZIER_SIZE] = STEPPED; + _curves[frameIndex * BEZIER_SIZE] = STEPPED; } void CurveTimeline::setCurve(size_t frameIndex, float cx1, float cy1, float cx2, float cy2) { - float tmpx = (-cx1 * 2 + cx2) * 0.03f, tmpy = (-cy1 * 2 + cy2) * 0.03f; - float dddfx = ((cx1 - cx2) * 3 + 1) * 0.006f, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006f; - float ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy; - float dfx = cx1 * 0.3f + tmpx + dddfx * 0.16666667f, dfy = cy1 * 0.3f + tmpy + dddfy * 0.16666667f; + float tmpx = (-cx1 * 2 + cx2) * 0.03f, tmpy = (-cy1 * 2 + cy2) * 0.03f; + float dddfx = ((cx1 - cx2) * 3 + 1) * 0.006f, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006f; + float ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy; + float dfx = cx1 * 0.3f + tmpx + dddfx * 0.16666667f, dfy = cy1 * 0.3f + tmpy + dddfy * 0.16666667f; - size_t i = frameIndex * BEZIER_SIZE; - _curves[i++] = BEZIER; + size_t i = frameIndex * BEZIER_SIZE; + _curves[i++] = BEZIER; - float x = dfx, y = dfy; - for (size_t n = i + BEZIER_SIZE - 1; i < n; i += 2) { - _curves[i] = x; - _curves[i + 1] = y; - dfx += ddfx; - dfy += ddfy; - ddfx += dddfx; - ddfy += dddfy; - x += dfx; - y += dfy; - } + float x = dfx, y = dfy; + for (size_t n = i + BEZIER_SIZE - 1; i < n; i += 2) { + _curves[i] = x; + _curves[i + 1] = y; + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + x += dfx; + y += dfy; + } } float CurveTimeline::getCurvePercent(size_t frameIndex, float percent) { - percent = MathUtil::clamp(percent, 0, 1); - size_t i = frameIndex * BEZIER_SIZE; - float type = _curves[i]; + percent = MathUtil::clamp(percent, 0, 1); + size_t i = frameIndex * BEZIER_SIZE; + float type = _curves[i]; - if (type == LINEAR) { - return percent; - } + if (type == LINEAR) { + return percent; + } - if (type == STEPPED) { - return 0; - } + if (type == STEPPED) { + return 0; + } - i++; - float x = 0; - for (size_t start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) { - x = _curves[i]; - if (x >= percent) { - float prevX, prevY; - if (i == start) { - prevX = 0; - prevY = 0; - } else { - prevX = _curves[i - 2]; - prevY = _curves[i - 1]; - } - return prevY + (_curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); - } - } + i++; + float x = 0; + for (size_t start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) { + x = _curves[i]; + if (x >= percent) { + float prevX, prevY; + if (i == start) { + prevX = 0; + prevY = 0; + } else { + prevX = _curves[i - 2]; + prevY = _curves[i - 1]; + } + return prevY + (_curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); + } + } - float y = _curves[i - 1]; + float y = _curves[i - 1]; - return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. + return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. } float CurveTimeline::getCurveType(size_t frameIndex) { - return _curves[frameIndex * BEZIER_SIZE]; + return _curves[frameIndex * BEZIER_SIZE]; } diff --git a/native/cocos/editor-support/spine/CurveTimeline.h b/native/cocos/editor-support/spine/CurveTimeline.h index 9d739d4bbf..cacb2860ac 100644 --- a/native/cocos/editor-support/spine/CurveTimeline.h +++ b/native/cocos/editor-support/spine/CurveTimeline.h @@ -34,43 +34,43 @@ #include namespace spine { - /// Base class for frames that use an interpolation bezier curve. - class SP_API CurveTimeline : public Timeline { - RTTI_DECL +/// Base class for frames that use an interpolation bezier curve. +class SP_API CurveTimeline : public Timeline { + RTTI_DECL - public: - explicit CurveTimeline(int frameCount); +public: + explicit CurveTimeline(int frameCount); - virtual ~CurveTimeline(); + virtual ~CurveTimeline(); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction) = 0; + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction) = 0; - virtual int getPropertyId() = 0; + virtual int getPropertyId() = 0; - size_t getFrameCount(); + size_t getFrameCount(); - void setLinear(size_t frameIndex); + void setLinear(size_t frameIndex); - void setStepped(size_t frameIndex); + void setStepped(size_t frameIndex); - /// Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. - /// cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of - /// the difference between the keyframe's values. - void setCurve(size_t frameIndex, float cx1, float cy1, float cx2, float cy2); + /// Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. + /// cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of + /// the difference between the keyframe's values. + void setCurve(size_t frameIndex, float cx1, float cy1, float cx2, float cy2); - float getCurvePercent(size_t frameIndex, float percent); + float getCurvePercent(size_t frameIndex, float percent); - float getCurveType(size_t frameIndex); + float getCurveType(size_t frameIndex); - protected: - static const float LINEAR; - static const float STEPPED; - static const float BEZIER; - static const int BEZIER_SIZE; +protected: + static const float LINEAR; + static const float STEPPED; + static const float BEZIER; + static const int BEZIER_SIZE; - private: - Vector _curves; // type, x, y, ... - }; -} +private: + Vector _curves; // type, x, y, ... +}; +} // namespace spine #endif /* Spine_CurveTimeline_h */ diff --git a/native/cocos/editor-support/spine/Debug.h b/native/cocos/editor-support/spine/Debug.h index 61c3d3bb6e..fcdd10654a 100644 --- a/native/cocos/editor-support/spine/Debug.h +++ b/native/cocos/editor-support/spine/Debug.h @@ -36,92 +36,91 @@ namespace spine { class SP_API DebugExtension : public SpineExtension { - struct Allocation { - void *address; - size_t size; - const char *fileName; - int line; + struct Allocation { + void *address; + size_t size; + const char *fileName; + int line; - Allocation() : address(NULL), size(0), fileName(NULL), line(0) { - } + Allocation() : address(NULL), size(0), fileName(NULL), line(0) { + } - Allocation(void *a, size_t s, const char *f, int l) : address(a), size(s), fileName(f), line(l) { - } - }; + Allocation(void *a, size_t s, const char *f, int l) : address(a), size(s), fileName(f), line(l) { + } + }; public: - DebugExtension(SpineExtension* extension): _extension(extension), _allocations(0), _reallocations(0), _frees(0) { - } + DebugExtension(SpineExtension *extension) : _extension(extension), _allocations(0), _reallocations(0), _frees(0) { + } - void reportLeaks() { - for (std::map::iterator it = _allocated.begin(); it != _allocated.end(); it++) { - printf("\"%s:%i (%zu bytes at %p)\n", it->second.fileName, it->second.line, it->second.size, it->second.address); - } - printf("allocations: %zu, reallocations: %zu, frees: %zu\n", _allocations, _reallocations, _frees); - if (_allocated.empty()) printf("No leaks detected"); - } + void reportLeaks() { + for (std::map::iterator it = _allocated.begin(); it != _allocated.end(); it++) { + printf("\"%s:%i (%zu bytes at %p)\n", it->second.fileName, it->second.line, it->second.size, it->second.address); + } + printf("allocations: %zu, reallocations: %zu, frees: %zu\n", _allocations, _reallocations, _frees); + if (_allocated.empty()) printf("No leaks detected"); + } - void clearAllocations() { - _allocated.clear(); - _usedMemory = 0; - } + void clearAllocations() { + _allocated.clear(); + _usedMemory = 0; + } - virtual void *_alloc(size_t size, const char *file, int line) { - void *result = _extension->_alloc(size, file, line); - _allocated[result] = Allocation(result, size, file, line); - _allocations++; - _usedMemory += size; - return result; - } + virtual void *_alloc(size_t size, const char *file, int line) { + void *result = _extension->_alloc(size, file, line); + _allocated[result] = Allocation(result, size, file, line); + _allocations++; + _usedMemory += size; + return result; + } - virtual void *_calloc(size_t size, const char *file, int line) { - void *result = _extension->_calloc(size, file, line); - _allocated[result] = Allocation(result, size, file, line); - _allocations++; - _usedMemory += size; - return result; - } + virtual void *_calloc(size_t size, const char *file, int line) { + void *result = _extension->_calloc(size, file, line); + _allocated[result] = Allocation(result, size, file, line); + _allocations++; + _usedMemory += size; + return result; + } - virtual void *_realloc(void *ptr, size_t size, const char *file, int line) { - if (_allocated.count(ptr)) _usedMemory -= _allocated[ptr].size; - _allocated.erase(ptr); - void *result = _extension->_realloc(ptr, size, file, line); - _reallocations++; - _allocated[result] = Allocation(result, size, file, line); - _usedMemory += size; - return result; - } + virtual void *_realloc(void *ptr, size_t size, const char *file, int line) { + if (_allocated.count(ptr)) _usedMemory -= _allocated[ptr].size; + _allocated.erase(ptr); + void *result = _extension->_realloc(ptr, size, file, line); + _reallocations++; + _allocated[result] = Allocation(result, size, file, line); + _usedMemory += size; + return result; + } - virtual void _free(void *mem, const char *file, int line) { - if (_allocated.count(mem)) { - _extension->_free(mem, file, line); - _frees++; - _usedMemory -= _allocated[mem].size; - _allocated.erase(mem); - return; - } + virtual void _free(void *mem, const char *file, int line) { + if (_allocated.count(mem)) { + _extension->_free(mem, file, line); + _frees++; + _usedMemory -= _allocated[mem].size; + _allocated.erase(mem); + return; + } - printf("%s:%i (address %p): Double free or not allocated through SpineExtension\n", file, line, mem); - _extension->_free(mem, file, line); - } + printf("%s:%i (address %p): Double free or not allocated through SpineExtension\n", file, line, mem); + _extension->_free(mem, file, line); + } - virtual char *_readFile(const String &path, int *length) { - return _extension->_readFile(path, length); - } - - size_t getUsedMemory() { - return _usedMemory; - } + virtual char *_readFile(const String &path, int *length) { + return _extension->_readFile(path, length); + } + + size_t getUsedMemory() { + return _usedMemory; + } private: - SpineExtension* _extension; - std::map _allocated; - size_t _allocations; - size_t _reallocations; - size_t _frees; - size_t _usedMemory; + SpineExtension *_extension; + std::map _allocated; + size_t _allocations; + size_t _reallocations; + size_t _frees; + size_t _usedMemory; }; -} - +} // namespace spine #endif //SPINE_DEBUG_H diff --git a/native/cocos/editor-support/spine/DeformTimeline.cpp b/native/cocos/editor-support/spine/DeformTimeline.cpp index bdec6e4402..8647cd7b4e 100644 --- a/native/cocos/editor-support/spine/DeformTimeline.cpp +++ b/native/cocos/editor-support/spine/DeformTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -49,250 +49,249 @@ using namespace spine; RTTI_IMPL(DeformTimeline, CurveTimeline) DeformTimeline::DeformTimeline(int frameCount) : CurveTimeline(frameCount), _slotIndex(0), _attachment(NULL) { - _frames.ensureCapacity(frameCount); - _frameVertices.ensureCapacity(frameCount); + _frames.ensureCapacity(frameCount); + _frameVertices.ensureCapacity(frameCount); - _frames.setSize(frameCount, 0); + _frames.setSize(frameCount, 0); - for (int i = 0; i < frameCount; ++i) { - Vector vec; - _frameVertices.add(vec); - } + for (int i = 0; i < frameCount; ++i) { + Vector vec; + _frameVertices.add(vec); + } } void DeformTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Slot *slotP = skeleton._slots[_slotIndex]; - Slot &slot = *slotP; - if (!slot._bone.isActive()) return; + Slot *slotP = skeleton._slots[_slotIndex]; + Slot &slot = *slotP; + if (!slot._bone.isActive()) return; - Attachment *slotAttachment = slot.getAttachment(); - if (slotAttachment == NULL || !slotAttachment->getRTTI().instanceOf(VertexAttachment::rtti)) { - return; - } + Attachment *slotAttachment = slot.getAttachment(); + if (slotAttachment == NULL || !slotAttachment->getRTTI().instanceOf(VertexAttachment::rtti)) { + return; + } - VertexAttachment *attachment = static_cast(slotAttachment); - if (attachment->_deformAttachment != _attachment) { - return; - } + VertexAttachment *attachment = static_cast(slotAttachment); + if (attachment->_deformAttachment != _attachment) { + return; + } - Vector &deformArray = slot._deform; - if (deformArray.size() == 0) { - blend = MixBlend_Setup; - } + Vector &deformArray = slot._deform; + if (deformArray.size() == 0) { + blend = MixBlend_Setup; + } - Vector< Vector > &frameVertices = _frameVertices; - size_t vertexCount = frameVertices[0].size(); + Vector > &frameVertices = _frameVertices; + size_t vertexCount = frameVertices[0].size(); - Vector &frames = _frames; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - deformArray.clear(); - return; - case MixBlend_First: { - if (alpha == 1) { - deformArray.clear(); - return; - } - deformArray.setSize(vertexCount, 0); - Vector &deformInner = deformArray; - if (attachment->getBones().size() == 0) { - // Unweighted vertex positions. - Vector &setupVertices = attachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) - deformInner[i] += (setupVertices[i] - deformInner[i]) * alpha; - } else { - // Weighted deform offsets. - alpha = 1 - alpha; - for (size_t i = 0; i < vertexCount; i++) - deformInner[i] *= alpha; - } - } - case MixBlend_Replace: - case MixBlend_Add: - return; - } - } + Vector &frames = _frames; + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + deformArray.clear(); + return; + case MixBlend_First: { + if (alpha == 1) { + deformArray.clear(); + return; + } + deformArray.setSize(vertexCount, 0); + Vector &deformInner = deformArray; + if (attachment->getBones().size() == 0) { + // Unweighted vertex positions. + Vector &setupVertices = attachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) + deformInner[i] += (setupVertices[i] - deformInner[i]) * alpha; + } else { + // Weighted deform offsets. + alpha = 1 - alpha; + for (size_t i = 0; i < vertexCount; i++) + deformInner[i] *= alpha; + } + } + case MixBlend_Replace: + case MixBlend_Add: + return; + } + } - deformArray.setSize(vertexCount, 0); - Vector &deform = deformArray; + deformArray.setSize(vertexCount, 0); + Vector &deform = deformArray; - if (time >= frames[frames.size() - 1]) { // Time is after last frame. - Vector &lastVertices = frameVertices[frames.size() - 1]; - if (alpha == 1) { - if (blend == MixBlend_Add) { - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, no alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) - deform[i] += lastVertices[i] - setupVertices[i]; - } else { - // Weighted deform offsets, no alpha. - for (size_t i = 0; i < vertexCount; i++) - deform[i] += lastVertices[i]; - } - } else { - // Vertex positions or deform offsets, no alpha. - memcpy(deform.buffer(), lastVertices.buffer(), vertexCount * sizeof(float)); - } - } else { - switch (blend) { - case MixBlend_Setup: { - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, with alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) { - float setup = setupVertices[i]; - deform[i] = setup + (lastVertices[i] - setup) * alpha; - } - } else { - // Weighted deform offsets, with alpha. - for (size_t i = 0; i < vertexCount; i++) - deform[i] = lastVertices[i] * alpha; - } - break; - } - case MixBlend_First: - case MixBlend_Replace: - // Vertex positions or deform offsets, with alpha. - for (size_t i = 0; i < vertexCount; i++) - deform[i] += (lastVertices[i] - deform[i]) * alpha; - break; - case MixBlend_Add: - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, no alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) - deform[i] += (lastVertices[i] - setupVertices[i]) * alpha; - } else { - // Weighted deform offsets, alpha. - for (size_t i = 0; i < vertexCount; i++) - deform[i] += lastVertices[i] * alpha; - } - } - } - return; - } + if (time >= frames[frames.size() - 1]) { // Time is after last frame. + Vector &lastVertices = frameVertices[frames.size() - 1]; + if (alpha == 1) { + if (blend == MixBlend_Add) { + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, no alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i] - setupVertices[i]; + } else { + // Weighted deform offsets, no alpha. + for (size_t i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i]; + } + } else { + // Vertex positions or deform offsets, no alpha. + memcpy(deform.buffer(), lastVertices.buffer(), vertexCount * sizeof(float)); + } + } else { + switch (blend) { + case MixBlend_Setup: { + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, with alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) { + float setup = setupVertices[i]; + deform[i] = setup + (lastVertices[i] - setup) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (size_t i = 0; i < vertexCount; i++) + deform[i] = lastVertices[i] * alpha; + } + break; + } + case MixBlend_First: + case MixBlend_Replace: + // Vertex positions or deform offsets, with alpha. + for (size_t i = 0; i < vertexCount; i++) + deform[i] += (lastVertices[i] - deform[i]) * alpha; + break; + case MixBlend_Add: + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, no alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) + deform[i] += (lastVertices[i] - setupVertices[i]) * alpha; + } else { + // Weighted deform offsets, alpha. + for (size_t i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i] * alpha; + } + } + } + return; + } - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(frames, time); - Vector &prevVertices = frameVertices[frame - 1]; - Vector &nextVertices = frameVertices[frame]; - float frameTime = frames[frame]; - float percent = getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(frames, time); + Vector &prevVertices = frameVertices[frame - 1]; + Vector &nextVertices = frameVertices[frame]; + float frameTime = frames[frame]; + float percent = getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); - if (alpha == 1) { - if (blend == MixBlend_Add) { - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, no alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] += prev + (nextVertices[i] - prev) * percent - setupVertices[i]; - } - } else { - // Weighted deform offsets, no alpha. - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] += prev + (nextVertices[i] - prev) * percent; - } - } - } else { - // Vertex positions or deform offsets, no alpha. - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] = prev + (nextVertices[i] - prev) * percent; - } - } - } else { - switch (blend) { - case MixBlend_Setup: { - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, with alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i], setup = setupVertices[i]; - deform[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha; - } - } else { - // Weighted deform offsets, with alpha. - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] = (prev + (nextVertices[i] - prev) * percent) * alpha; - } - } - break; - } - case MixBlend_First: - case MixBlend_Replace: - // Vertex positions or deform offsets, with alpha. - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] += (prev + (nextVertices[i] - prev) * percent - deform[i]) * alpha; - } - break; - case MixBlend_Add: - VertexAttachment *vertexAttachment = static_cast(slotAttachment); - if (vertexAttachment->getBones().size() == 0) { - // Unweighted vertex positions, with alpha. - Vector &setupVertices = vertexAttachment->getVertices(); - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] += (prev + (nextVertices[i] - prev) * percent - setupVertices[i]) * alpha; - } - } else { - // Weighted deform offsets, with alpha. - for (size_t i = 0; i < vertexCount; i++) { - float prev = prevVertices[i]; - deform[i] += (prev + (nextVertices[i] - prev) * percent) * alpha; - } - } - } - } + if (alpha == 1) { + if (blend == MixBlend_Add) { + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, no alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += prev + (nextVertices[i] - prev) * percent - setupVertices[i]; + } + } else { + // Weighted deform offsets, no alpha. + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += prev + (nextVertices[i] - prev) * percent; + } + } + } else { + // Vertex positions or deform offsets, no alpha. + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] = prev + (nextVertices[i] - prev) * percent; + } + } + } else { + switch (blend) { + case MixBlend_Setup: { + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, with alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i], setup = setupVertices[i]; + deform[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] = (prev + (nextVertices[i] - prev) * percent) * alpha; + } + } + break; + } + case MixBlend_First: + case MixBlend_Replace: + // Vertex positions or deform offsets, with alpha. + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent - deform[i]) * alpha; + } + break; + case MixBlend_Add: + VertexAttachment *vertexAttachment = static_cast(slotAttachment); + if (vertexAttachment->getBones().size() == 0) { + // Unweighted vertex positions, with alpha. + Vector &setupVertices = vertexAttachment->getVertices(); + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent - setupVertices[i]) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (size_t i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent) * alpha; + } + } + } + } } int DeformTimeline::getPropertyId() { - assert(_attachment != NULL); - return ((int) TimelineType_Deform << 24) + _attachment->_id + _slotIndex; + assert(_attachment != NULL); + return ((int)TimelineType_Deform << 24) + _attachment->_id + _slotIndex; } void DeformTimeline::setFrame(int frameIndex, float time, Vector &vertices) { - _frames[frameIndex] = time; - _frameVertices[frameIndex].clear(); - _frameVertices[frameIndex].addAll(vertices); + _frames[frameIndex] = time; + _frameVertices[frameIndex].clear(); + _frameVertices[frameIndex].addAll(vertices); } int DeformTimeline::getSlotIndex() { - return _slotIndex; + return _slotIndex; } void DeformTimeline::setSlotIndex(int inValue) { - _slotIndex = inValue; + _slotIndex = inValue; } Vector &DeformTimeline::getFrames() { - return _frames; + return _frames; } Vector > &DeformTimeline::getVertices() { - return _frameVertices; + return _frameVertices; } VertexAttachment *DeformTimeline::getAttachment() { - return _attachment; + return _attachment; } void DeformTimeline::setAttachment(VertexAttachment *inValue) { - _attachment = inValue; + _attachment = inValue; } diff --git a/native/cocos/editor-support/spine/DeformTimeline.h b/native/cocos/editor-support/spine/DeformTimeline.h index 05632c3010..c3c9110e59 100644 --- a/native/cocos/editor-support/spine/DeformTimeline.h +++ b/native/cocos/editor-support/spine/DeformTimeline.h @@ -33,37 +33,37 @@ #include namespace spine { - class VertexAttachment; +class VertexAttachment; - class SP_API DeformTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API DeformTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit DeformTimeline(int frameCount); +public: + explicit DeformTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, Vector& vertices); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, Vector& vertices); - int getSlotIndex(); - void setSlotIndex(int inValue); - Vector& getFrames(); - Vector< Vector >& getVertices(); - VertexAttachment* getAttachment(); - void setAttachment(VertexAttachment* inValue); + int getSlotIndex(); + void setSlotIndex(int inValue); + Vector& getFrames(); + Vector >& getVertices(); + VertexAttachment* getAttachment(); + void setAttachment(VertexAttachment* inValue); - private: - int _slotIndex; - Vector _frames; - Vector< Vector > _frameVertices; - VertexAttachment* _attachment; - }; -} +private: + int _slotIndex; + Vector _frames; + Vector > _frameVertices; + VertexAttachment* _attachment; +}; +} // namespace spine #endif /* Spine_DeformTimeline_h */ diff --git a/native/cocos/editor-support/spine/DrawOrderTimeline.cpp b/native/cocos/editor-support/spine/DrawOrderTimeline.cpp index 9f40288916..a00fc7a80e 100644 --- a/native/cocos/editor-support/spine/DrawOrderTimeline.cpp +++ b/native/cocos/editor-support/spine/DrawOrderTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -46,80 +46,79 @@ using namespace spine; RTTI_IMPL(DrawOrderTimeline, Timeline) DrawOrderTimeline::DrawOrderTimeline(int frameCount) : Timeline() { - _frames.ensureCapacity(frameCount); - _drawOrders.ensureCapacity(frameCount); + _frames.ensureCapacity(frameCount); + _drawOrders.ensureCapacity(frameCount); - _frames.setSize(frameCount, 0); + _frames.setSize(frameCount, 0); - for (int i = 0; i < frameCount; ++i) { - Vector vec; - _drawOrders.add(vec); - } + for (int i = 0; i < frameCount; ++i) { + Vector vec; + _drawOrders.add(vec); + } } void DrawOrderTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(alpha); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(alpha); - Vector &drawOrder = skeleton._drawOrder; - Vector &slots = skeleton._slots; - if (direction == MixDirection_Out && blend == MixBlend_Setup) { - drawOrder.clear(); - drawOrder.ensureCapacity(slots.size()); - for (size_t i = 0, n = slots.size(); i < n; ++i) - drawOrder.add(slots[i]); - return; - } + Vector &drawOrder = skeleton._drawOrder; + Vector &slots = skeleton._slots; + if (direction == MixDirection_Out && blend == MixBlend_Setup) { + drawOrder.clear(); + drawOrder.ensureCapacity(slots.size()); + for (size_t i = 0, n = slots.size(); i < n; ++i) + drawOrder.add(slots[i]); + return; + } - if (time < _frames[0]) { - if (blend == MixBlend_Setup || blend == MixBlend_First) { - drawOrder.clear(); - drawOrder.ensureCapacity(slots.size()); - for (size_t i = 0, n = slots.size(); i < n; ++i) - drawOrder.add(slots[i]); - } - return; - } + if (time < _frames[0]) { + if (blend == MixBlend_Setup || blend == MixBlend_First) { + drawOrder.clear(); + drawOrder.ensureCapacity(slots.size()); + for (size_t i = 0, n = slots.size(); i < n; ++i) + drawOrder.add(slots[i]); + } + return; + } - size_t frame; - if (time >= _frames[_frames.size() - 1]) { - // Time is after last frame. - frame = _frames.size() - 1; - } else - frame = (size_t)Animation::binarySearch(_frames, time) - 1; + size_t frame; + if (time >= _frames[_frames.size() - 1]) { + // Time is after last frame. + frame = _frames.size() - 1; + } else + frame = (size_t)Animation::binarySearch(_frames, time) - 1; - Vector &drawOrderToSetupIndex = _drawOrders[frame]; - if (drawOrderToSetupIndex.size() == 0) { - drawOrder.clear(); - for (size_t i = 0, n = slots.size(); i < n; ++i) - drawOrder.add(slots[i]); - } else { - for (size_t i = 0, n = drawOrderToSetupIndex.size(); i < n; ++i) - drawOrder[i] = slots[drawOrderToSetupIndex[i]]; - } + Vector &drawOrderToSetupIndex = _drawOrders[frame]; + if (drawOrderToSetupIndex.size() == 0) { + drawOrder.clear(); + for (size_t i = 0, n = slots.size(); i < n; ++i) + drawOrder.add(slots[i]); + } else { + for (size_t i = 0, n = drawOrderToSetupIndex.size(); i < n; ++i) + drawOrder[i] = slots[drawOrderToSetupIndex[i]]; + } } int DrawOrderTimeline::getPropertyId() { - return ((int) TimelineType_DrawOrder << 24); + return ((int)TimelineType_DrawOrder << 24); } void DrawOrderTimeline::setFrame(size_t frameIndex, float time, Vector &drawOrder) { - _frames[frameIndex] = time; - _drawOrders[frameIndex].clear(); - _drawOrders[frameIndex].addAll(drawOrder); + _frames[frameIndex] = time; + _drawOrders[frameIndex].clear(); + _drawOrders[frameIndex].addAll(drawOrder); } Vector &DrawOrderTimeline::getFrames() { - return _frames; + return _frames; } Vector > &DrawOrderTimeline::getDrawOrders() { - return _drawOrders; + return _drawOrders; } size_t DrawOrderTimeline::getFrameCount() { - return _frames.size(); + return _frames.size(); } diff --git a/native/cocos/editor-support/spine/DrawOrderTimeline.h b/native/cocos/editor-support/spine/DrawOrderTimeline.h index 867e94e97f..4236ab2b09 100644 --- a/native/cocos/editor-support/spine/DrawOrderTimeline.h +++ b/native/cocos/editor-support/spine/DrawOrderTimeline.h @@ -33,31 +33,31 @@ #include namespace spine { - class SP_API DrawOrderTimeline : public Timeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API DrawOrderTimeline : public Timeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit DrawOrderTimeline(int frameCount); +public: + explicit DrawOrderTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - /// @param drawOrder May be NULL to use bind pose draw order - void setFrame(size_t frameIndex, float time, Vector& drawOrder); + /// Sets the time and value of the specified keyframe. + /// @param drawOrder May be NULL to use bind pose draw order + void setFrame(size_t frameIndex, float time, Vector& drawOrder); - Vector& getFrames(); - Vector< Vector >& getDrawOrders(); - size_t getFrameCount(); + Vector& getFrames(); + Vector >& getDrawOrders(); + size_t getFrameCount(); - private: - Vector _frames; - Vector< Vector > _drawOrders; - }; -} +private: + Vector _frames; + Vector > _drawOrders; +}; +} // namespace spine #endif /* Spine_DrawOrderTimeline_h */ diff --git a/native/cocos/editor-support/spine/Event.cpp b/native/cocos/editor-support/spine/Event.cpp index 4f1c1e87af..3e3b4a6be3 100644 --- a/native/cocos/editor-support/spine/Event.cpp +++ b/native/cocos/editor-support/spine/Event.cpp @@ -28,68 +28,66 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include #include -spine::Event::Event(float time, const spine::EventData &data) : - _data(data), - _time(time), - _intValue(0), - _floatValue(0), - _stringValue(), - _volume(1), - _balance(0) { +spine::Event::Event(float time, const spine::EventData &data) : _data(data), + _time(time), + _intValue(0), + _floatValue(0), + _stringValue(), + _volume(1), + _balance(0) { } const spine::EventData &spine::Event::getData() { - return _data; + return _data; } float spine::Event::getTime() { - return _time; + return _time; } int spine::Event::getIntValue() { - return _intValue; + return _intValue; } void spine::Event::setIntValue(int inValue) { - _intValue = inValue; + _intValue = inValue; } float spine::Event::getFloatValue() { - return _floatValue; + return _floatValue; } void spine::Event::setFloatValue(float inValue) { - _floatValue = inValue; + _floatValue = inValue; } const spine::String &spine::Event::getStringValue() { - return _stringValue; + return _stringValue; } void spine::Event::setStringValue(const spine::String &inValue) { - _stringValue = inValue; + _stringValue = inValue; } - float spine::Event::getVolume() { - return _volume; + return _volume; } void spine::Event::setVolume(float inValue) { - _volume = inValue; + _volume = inValue; } float spine::Event::getBalance() { - return _balance; + return _balance; } void spine::Event::setBalance(float inValue) { - _balance = inValue; + _balance = inValue; } diff --git a/native/cocos/editor-support/spine/Event.h b/native/cocos/editor-support/spine/Event.h index 23d082e4a2..8eba17ab84 100644 --- a/native/cocos/editor-support/spine/Event.h +++ b/native/cocos/editor-support/spine/Event.h @@ -38,49 +38,49 @@ class EventData; /// Stores the current pose values for an Event. class SP_API Event : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; - friend class AnimationState; + friend class AnimationState; public: - Event(float time, const EventData &data); + Event(float time, const EventData &data); - const EventData &getData(); + const EventData &getData(); - /// The animation time this event was keyed. - float getTime(); + /// The animation time this event was keyed. + float getTime(); - int getIntValue(); + int getIntValue(); - void setIntValue(int inValue); + void setIntValue(int inValue); - float getFloatValue(); + float getFloatValue(); - void setFloatValue(float inValue); + void setFloatValue(float inValue); - const String &getStringValue(); + const String &getStringValue(); - void setStringValue(const String &inValue); + void setStringValue(const String &inValue); - float getVolume(); + float getVolume(); - void setVolume(float inValue); + void setVolume(float inValue); - float getBalance(); + float getBalance(); - void setBalance(float inValue); + void setBalance(float inValue); private: - const EventData &_data; - const float _time; - int _intValue; - float _floatValue; - String _stringValue; - float _volume; - float _balance; + const EventData &_data; + const float _time; + int _intValue; + float _floatValue; + String _stringValue; + float _volume; + float _balance; }; -} +} // namespace spine #endif /* Spine_Event_h */ diff --git a/native/cocos/editor-support/spine/EventData.cpp b/native/cocos/editor-support/spine/EventData.cpp index 6c03797bbc..ea0ebfb190 100644 --- a/native/cocos/editor-support/spine/EventData.cpp +++ b/native/cocos/editor-support/spine/EventData.cpp @@ -28,74 +28,72 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include #include -spine::EventData::EventData(const spine::String &name) : - _name(name), - _intValue(0), - _floatValue(0), - _stringValue(), - _audioPath(), - _volume(1), - _balance(0) { - assert(_name.length() > 0); +spine::EventData::EventData(const spine::String &name) : _name(name), + _intValue(0), + _floatValue(0), + _stringValue(), + _audioPath(), + _volume(1), + _balance(0) { + assert(_name.length() > 0); } /// The name of the event, which is unique within the skeleton. const spine::String &spine::EventData::getName() const { - return _name; + return _name; } int spine::EventData::getIntValue() { - return _intValue; + return _intValue; } void spine::EventData::setIntValue(int inValue) { - _intValue = inValue; + _intValue = inValue; } float spine::EventData::getFloatValue() { - return _floatValue; + return _floatValue; } void spine::EventData::setFloatValue(float inValue) { - _floatValue = inValue; + _floatValue = inValue; } const spine::String &spine::EventData::getStringValue() { - return _stringValue; + return _stringValue; } void spine::EventData::setStringValue(const spine::String &inValue) { - this->_stringValue = inValue; + this->_stringValue = inValue; } const spine::String &spine::EventData::getAudioPath() { - return _audioPath; + return _audioPath; } void spine::EventData::setAudioPath(const spine::String &inValue) { - _audioPath = inValue; + _audioPath = inValue; } - float spine::EventData::getVolume() { - return _volume; + return _volume; } void spine::EventData::setVolume(float inValue) { - _volume = inValue; + _volume = inValue; } float spine::EventData::getBalance() { - return _balance; + return _balance; } void spine::EventData::setBalance(float inValue) { - _balance = inValue; + _balance = inValue; } diff --git a/native/cocos/editor-support/spine/EventData.h b/native/cocos/editor-support/spine/EventData.h index 9140f54b95..28fdbe02a6 100644 --- a/native/cocos/editor-support/spine/EventData.h +++ b/native/cocos/editor-support/spine/EventData.h @@ -36,51 +36,51 @@ namespace spine { /// Stores the setup pose values for an Event. class SP_API EventData : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; - friend class Event; + friend class Event; public: - explicit EventData(const String &name); + explicit EventData(const String &name); - /// The name of the event, which is unique within the skeleton. - const String &getName() const; + /// The name of the event, which is unique within the skeleton. + const String &getName() const; - int getIntValue(); + int getIntValue(); - void setIntValue(int inValue); + void setIntValue(int inValue); - float getFloatValue(); + float getFloatValue(); - void setFloatValue(float inValue); + void setFloatValue(float inValue); - const String &getStringValue(); + const String &getStringValue(); - void setStringValue(const String &inValue); + void setStringValue(const String &inValue); - const String &getAudioPath(); + const String &getAudioPath(); - void setAudioPath(const String &inValue); + void setAudioPath(const String &inValue); - float getVolume(); + float getVolume(); - void setVolume(float inValue); + void setVolume(float inValue); - float getBalance(); + float getBalance(); - void setBalance(float inValue); + void setBalance(float inValue); private: - const String _name; - int _intValue; - float _floatValue; - String _stringValue; - String _audioPath; - float _volume; - float _balance; + const String _name; + int _intValue; + float _floatValue; + String _stringValue; + String _audioPath; + float _volume; + float _balance; }; -} +} // namespace spine #endif /* Spine_EventData_h */ diff --git a/native/cocos/editor-support/spine/EventTimeline.cpp b/native/cocos/editor-support/spine/EventTimeline.cpp index f055523759..28f55ce6fb 100644 --- a/native/cocos/editor-support/spine/EventTimeline.cpp +++ b/native/cocos/editor-support/spine/EventTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -50,58 +50,57 @@ using namespace spine; RTTI_IMPL(EventTimeline, Timeline) EventTimeline::EventTimeline(int frameCount) : Timeline() { - _frames.setSize(frameCount, 0); - _events.setSize(frameCount, NULL); + _frames.setSize(frameCount, 0); + _events.setSize(frameCount, NULL); } EventTimeline::~EventTimeline() { - ContainerUtil::cleanUpVectorOfPointers(_events); + ContainerUtil::cleanUpVectorOfPointers(_events); } void EventTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - if (pEvents == NULL) return; + MixBlend blend, MixDirection direction) { + if (pEvents == NULL) return; - Vector &events = *pEvents; + Vector &events = *pEvents; - size_t frameCount = _frames.size(); + size_t frameCount = _frames.size(); - if (lastTime > time) { - // Fire events after last time for looped animations. - apply(skeleton, lastTime, FLT_MAX, pEvents, alpha, blend, direction); - lastTime = -1.0f; - } else if (lastTime >= _frames[frameCount - 1]) { - // Last time is after last frame. - return; - } + if (lastTime > time) { + // Fire events after last time for looped animations. + apply(skeleton, lastTime, FLT_MAX, pEvents, alpha, blend, direction); + lastTime = -1.0f; + } else if (lastTime >= _frames[frameCount - 1]) { + // Last time is after last frame. + return; + } - if (time < _frames[0]) return; // Time is before first frame. + if (time < _frames[0]) return; // Time is before first frame. - int frame; - if (lastTime < _frames[0]) { - frame = 0; - } else { - frame = Animation::binarySearch(_frames, lastTime); - float frameTime = _frames[frame]; - while (frame > 0) { - // Fire multiple events with the same frame. - if (_frames[frame - 1] != frameTime) break; - frame--; - } - } + int frame; + if (lastTime < _frames[0]) { + frame = 0; + } else { + frame = Animation::binarySearch(_frames, lastTime); + float frameTime = _frames[frame]; + while (frame > 0) { + // Fire multiple events with the same frame. + if (_frames[frame - 1] != frameTime) break; + frame--; + } + } - for (; (size_t)frame < frameCount && time >= _frames[frame]; ++frame) - events.add(_events[frame]); + for (; (size_t)frame < frameCount && time >= _frames[frame]; ++frame) + events.add(_events[frame]); } int EventTimeline::getPropertyId() { - return ((int) TimelineType_Event << 24); + return ((int)TimelineType_Event << 24); } void EventTimeline::setFrame(size_t frameIndex, Event *event) { - _frames[frameIndex] = event->getTime(); - _events[frameIndex] = event; + _frames[frameIndex] = event->getTime(); + _events[frameIndex] = event; } Vector EventTimeline::getFrames() { return _frames; } diff --git a/native/cocos/editor-support/spine/EventTimeline.h b/native/cocos/editor-support/spine/EventTimeline.h index 6d39a74673..42d569d6ed 100644 --- a/native/cocos/editor-support/spine/EventTimeline.h +++ b/native/cocos/editor-support/spine/EventTimeline.h @@ -33,32 +33,32 @@ #include namespace spine { - class SP_API EventTimeline : public Timeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API EventTimeline : public Timeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit EventTimeline(int frameCount); +public: + explicit EventTimeline(int frameCount); - ~EventTimeline(); + ~EventTimeline(); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(size_t frameIndex, Event* event); + /// Sets the time and value of the specified keyframe. + void setFrame(size_t frameIndex, Event* event); - Vector getFrames(); - Vector& getEvents(); - size_t getFrameCount(); + Vector getFrames(); + Vector& getEvents(); + size_t getFrameCount(); - private: - Vector _frames; - Vector _events; - }; -} +private: + Vector _frames; + Vector _events; +}; +} // namespace spine #endif /* Spine_EventTimeline_h */ diff --git a/native/cocos/editor-support/spine/Extension.cpp b/native/cocos/editor-support/spine/Extension.cpp index e19f2738e8..000e69e63e 100644 --- a/native/cocos/editor-support/spine/Extension.cpp +++ b/native/cocos/editor-support/spine/Extension.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -41,16 +41,16 @@ using namespace spine; SpineExtension *SpineExtension::_instance = NULL; void SpineExtension::setInstance(SpineExtension *inValue) { - assert(inValue); + assert(inValue); - _instance = inValue; + _instance = inValue; } SpineExtension *SpineExtension::getInstance() { - if (!_instance) _instance = spine::getDefaultExtension(); - assert(_instance); + if (!_instance) _instance = spine::getDefaultExtension(); + assert(_instance); - return _instance; + return _instance; } SpineExtension::~SpineExtension() { @@ -63,64 +63,64 @@ DefaultSpineExtension::~DefaultSpineExtension() { } void *DefaultSpineExtension::_alloc(size_t size, const char *file, int line) { - SP_UNUSED(file); - SP_UNUSED(line); + SP_UNUSED(file); + SP_UNUSED(line); - if (size == 0) - return 0; - void *ptr = ::malloc(size); - return ptr; + if (size == 0) + return 0; + void *ptr = ::malloc(size); + return ptr; } void *DefaultSpineExtension::_calloc(size_t size, const char *file, int line) { - SP_UNUSED(file); - SP_UNUSED(line); + SP_UNUSED(file); + SP_UNUSED(line); - if (size == 0) - return 0; + if (size == 0) + return 0; - void *ptr = ::malloc(size); - if (ptr) { - memset(ptr, 0, size); - } - return ptr; + void *ptr = ::malloc(size); + if (ptr) { + memset(ptr, 0, size); + } + return ptr; } void *DefaultSpineExtension::_realloc(void *ptr, size_t size, const char *file, int line) { - SP_UNUSED(file); - SP_UNUSED(line); + SP_UNUSED(file); + SP_UNUSED(line); - void *mem = NULL; - if (size == 0) - return 0; - if (ptr == NULL) - mem = ::malloc(size); - else - mem = ::realloc(ptr, size); - return mem; + void *mem = NULL; + if (size == 0) + return 0; + if (ptr == NULL) + mem = ::malloc(size); + else + mem = ::realloc(ptr, size); + return mem; } void DefaultSpineExtension::_free(void *mem, const char *file, int line) { - SP_UNUSED(file); - SP_UNUSED(line); + SP_UNUSED(file); + SP_UNUSED(line); - ::free(mem); + ::free(mem); } char *DefaultSpineExtension::_readFile(const String &path, int *length) { - char *data; - FILE *file = fopen(path.buffer(), "rb"); - if (!file) return 0; + char *data; + FILE *file = fopen(path.buffer(), "rb"); + if (!file) return 0; - fseek(file, 0, SEEK_END); - *length = (int) ftell(file); - fseek(file, 0, SEEK_SET); + fseek(file, 0, SEEK_END); + *length = (int)ftell(file); + fseek(file, 0, SEEK_SET); - data = SpineExtension::alloc(*length, __FILE__, __LINE__); - fread(data, 1, *length, file); - fclose(file); + data = SpineExtension::alloc(*length, __FILE__, __LINE__); + fread(data, 1, *length, file); + fclose(file); - return data; + return data; } DefaultSpineExtension::DefaultSpineExtension() : SpineExtension() { diff --git a/native/cocos/editor-support/spine/Extension.h b/native/cocos/editor-support/spine/Extension.h index a64b0a61a5..51a0a2bb3f 100644 --- a/native/cocos/editor-support/spine/Extension.h +++ b/native/cocos/editor-support/spine/Extension.h @@ -30,7 +30,6 @@ #ifndef Spine_Extension_h #define Spine_Extension_h - #include #include @@ -41,71 +40,71 @@ class String; class SP_API SpineExtension { public: - template - static T *alloc(size_t num, const char *file, int line) { - return (T *) getInstance()->_alloc(sizeof(T) * num, file, line); - } + template + static T *alloc(size_t num, const char *file, int line) { + return (T *)getInstance()->_alloc(sizeof(T) * num, file, line); + } - template - static T *calloc(size_t num, const char *file, int line) { - return (T *) getInstance()->_calloc(sizeof(T) * num, file, line); - } + template + static T *calloc(size_t num, const char *file, int line) { + return (T *)getInstance()->_calloc(sizeof(T) * num, file, line); + } - template - static T *realloc(T *ptr, size_t num, const char *file, int line) { - return (T *) getInstance()->_realloc(ptr, sizeof(T) * num, file, line); - } + template + static T *realloc(T *ptr, size_t num, const char *file, int line) { + return (T *)getInstance()->_realloc(ptr, sizeof(T) * num, file, line); + } - template - static void free(T *ptr, const char *file, int line) { - getInstance()->_free((void *) ptr, file, line); - } + template + static void free(T *ptr, const char *file, int line) { + getInstance()->_free((void *)ptr, file, line); + } - static char *readFile(const String &path, int *length) { - return getInstance()->_readFile(path, length); - } + static char *readFile(const String &path, int *length) { + return getInstance()->_readFile(path, length); + } - static void setInstance(SpineExtension *inSpineExtension); + static void setInstance(SpineExtension *inSpineExtension); - static SpineExtension *getInstance(); + static SpineExtension *getInstance(); - virtual ~SpineExtension(); + virtual ~SpineExtension(); - /// Implement this function to use your own memory allocator - virtual void *_alloc(size_t size, const char *file, int line) = 0; + /// Implement this function to use your own memory allocator + virtual void *_alloc(size_t size, const char *file, int line) = 0; - virtual void *_calloc(size_t size, const char *file, int line) = 0; + virtual void *_calloc(size_t size, const char *file, int line) = 0; - virtual void *_realloc(void *ptr, size_t size, const char *file, int line) = 0; + virtual void *_realloc(void *ptr, size_t size, const char *file, int line) = 0; - /// If you provide a spineAllocFunc, you should also provide a spineFreeFunc - virtual void _free(void *mem, const char *file, int line) = 0; + /// If you provide a spineAllocFunc, you should also provide a spineFreeFunc + virtual void _free(void *mem, const char *file, int line) = 0; - virtual char *_readFile(const String &path, int *length) = 0; + virtual char *_readFile(const String &path, int *length) = 0; protected: - SpineExtension(); + SpineExtension(); private: - static SpineExtension *_instance; + static SpineExtension *_instance; }; class SP_API DefaultSpineExtension : public SpineExtension { public: - DefaultSpineExtension(); + DefaultSpineExtension(); - virtual ~DefaultSpineExtension(); + virtual ~DefaultSpineExtension(); protected: - virtual void *_alloc(size_t size, const char *file, int line); + virtual void *_alloc(size_t size, const char *file, int line); - virtual void *_calloc(size_t size, const char *file, int line); + virtual void *_calloc(size_t size, const char *file, int line); - virtual void *_realloc(void *ptr, size_t size, const char *file, int line); + virtual void *_realloc(void *ptr, size_t size, const char *file, int line); - virtual void _free(void *mem, const char *file, int line); + virtual void _free(void *mem, const char *file, int line); - virtual char *_readFile(const String &path, int *length); + virtual char *_readFile(const String &path, int *length); }; // This function is to be implemented by engine specific runtimes to provide @@ -113,6 +112,6 @@ protected: // SpineExtension::getInstance() is called, when no instance has been set // yet. extern SpineExtension *getDefaultExtension(); -} +} // namespace spine #endif /* Spine_Extension_h */ diff --git a/native/cocos/editor-support/spine/HasRendererObject.h b/native/cocos/editor-support/spine/HasRendererObject.h index 73162dadc6..8155fc952b 100644 --- a/native/cocos/editor-support/spine/HasRendererObject.h +++ b/native/cocos/editor-support/spine/HasRendererObject.h @@ -32,30 +32,31 @@ namespace spine { -typedef void (*DisposeRendererObject) (void* rendererObject); +typedef void (*DisposeRendererObject)(void* rendererObject); class SP_API HasRendererObject { public: - explicit HasRendererObject() : _rendererObject(NULL), _dispose(NULL) {}; + explicit HasRendererObject() : _rendererObject(NULL), _dispose(NULL){}; - virtual ~HasRendererObject() { - if (_dispose && _rendererObject) - _dispose(_rendererObject); - } + virtual ~HasRendererObject() { + if (_dispose && _rendererObject) + _dispose(_rendererObject); + } - void* getRendererObject() { return _rendererObject; } - void setRendererObject(void* rendererObject, DisposeRendererObject dispose = NULL) { + void* getRendererObject() { return _rendererObject; } + void setRendererObject(void* rendererObject, DisposeRendererObject dispose = NULL) { if (_dispose && _rendererObject && _rendererObject != rendererObject) _dispose(_rendererObject); - - _rendererObject = rendererObject; - _dispose = dispose; - } + + _rendererObject = rendererObject; + _dispose = dispose; + } + private: - void *_rendererObject; - DisposeRendererObject _dispose; + void* _rendererObject; + DisposeRendererObject _dispose; }; -} +} // namespace spine #endif diff --git a/native/cocos/editor-support/spine/HashMap.h b/native/cocos/editor-support/spine/HashMap.h index 9a1a1ecdc9..81b920e887 100644 --- a/native/cocos/editor-support/spine/HashMap.h +++ b/native/cocos/editor-support/spine/HashMap.h @@ -34,157 +34,159 @@ #include #include - // Required for new with line number and file name in MSVC +// Required for new with line number and file name in MSVC #ifdef _MSC_VER -#pragma warning(disable:4291) + #pragma warning(disable : 4291) #endif namespace spine { -template +template class SP_API HashMap : public SpineObject { private: - class Entry; + class Entry; public: - class SP_API Pair { - public: - explicit Pair(K &k, V &v) : key(k), value(v) {} + class SP_API Pair { + public: + explicit Pair(K &k, V &v) : key(k), value(v) {} - K &key; - V &value; - }; + K &key; + V &value; + }; - class SP_API Entries { - public: - friend class HashMap; + class SP_API Entries { + public: + friend class HashMap; - explicit Entries(Entry *entry) : _entry(NULL), _hasChecked(false) { - _start.next = entry; - _entry = &_start; - } + explicit Entries(Entry *entry) : _entry(NULL), _hasChecked(false) { + _start.next = entry; + _entry = &_start; + } - Pair next() { - assert(_entry); - assert(_hasChecked); - _entry = _entry->next; - Pair pair(_entry->_key, _entry->_value); - _hasChecked = false; - return pair; - } + Pair next() { + assert(_entry); + assert(_hasChecked); + _entry = _entry->next; + Pair pair(_entry->_key, _entry->_value); + _hasChecked = false; + return pair; + } - bool hasNext() { - _hasChecked = true; - return _entry->next; - } + bool hasNext() { + _hasChecked = true; + return _entry->next; + } - private: - bool _hasChecked; - Entry _start; - Entry *_entry; - }; + private: + bool _hasChecked; + Entry _start; + Entry *_entry; + }; - HashMap() : - _head(NULL), - _size(0) { - } + HashMap() : _head(NULL), + _size(0) { + } - ~HashMap() { - clear(); - } + ~HashMap() { + clear(); + } - void clear() { - for (Entry *entry = _head; entry != NULL;) { - Entry* next = entry->next; - delete entry; - entry = next; - } - _head = NULL; - _size = 0; - } + void clear() { + for (Entry *entry = _head; entry != NULL;) { + Entry *next = entry->next; + delete entry; + entry = next; + } + _head = NULL; + _size = 0; + } - size_t size() { - return _size; - } + size_t size() { + return _size; + } - void put(const K &key, const V &value) { - Entry *entry = find(key); - if (entry) { - entry->_key = key; - entry->_value = value; - } else { - entry = new(__FILE__, __LINE__) Entry(); - entry->_key = key; - entry->_value = value; + void put(const K &key, const V &value) { + Entry *entry = find(key); + if (entry) { + entry->_key = key; + entry->_value = value; + } else { + entry = new (__FILE__, __LINE__) Entry(); + entry->_key = key; + entry->_value = value; - Entry *oldHead = _head; + Entry *oldHead = _head; - if (oldHead) { - _head = entry; - oldHead->prev = entry; - entry->next = oldHead; - } else { - _head = entry; - } - _size++; - } - } + if (oldHead) { + _head = entry; + oldHead->prev = entry; + entry->next = oldHead; + } else { + _head = entry; + } + _size++; + } + } - bool containsKey(const K &key) { - return find(key) != NULL; - } + bool containsKey(const K &key) { + return find(key) != NULL; + } - bool remove(const K &key) { - Entry *entry = find(key); - if (!entry) return false; + bool remove(const K &key) { + Entry *entry = find(key); + if (!entry) return false; - Entry *prev = entry->prev; - Entry *next = entry->next; + Entry *prev = entry->prev; + Entry *next = entry->next; - if (prev) prev->next = next; - else _head = next; - if (next) next->prev = entry->prev; + if (prev) + prev->next = next; + else + _head = next; + if (next) next->prev = entry->prev; - delete entry; - _size--; + delete entry; + _size--; - return true; - } + return true; + } - V operator[](const K &key) { - Entry *entry = find(key); - if (entry) return entry->_value; - else { - assert(false); - return 0; - } - } + V operator[](const K &key) { + Entry *entry = find(key); + if (entry) + return entry->_value; + else { + assert(false); + return 0; + } + } - Entries getEntries() const { - return Entries(_head); - } + Entries getEntries() const { + return Entries(_head); + } private: - Entry *find(const K &key) { - for (Entry *entry = _head; entry != NULL; entry = entry->next) { - if (entry->_key == key) - return entry; - } - return NULL; - } + Entry *find(const K &key) { + for (Entry *entry = _head; entry != NULL; entry = entry->next) { + if (entry->_key == key) + return entry; + } + return NULL; + } - class SP_API Entry : public SpineObject { - public: - K _key; - V _value; - Entry *next; - Entry *prev; + class SP_API Entry : public SpineObject { + public: + K _key; + V _value; + Entry *next; + Entry *prev; - Entry() : next(NULL), prev(NULL) {} - }; + Entry() : next(NULL), prev(NULL) {} + }; - Entry *_head; - size_t _size; + Entry *_head; + size_t _size; }; -} +} // namespace spine #endif /* Spine_HashMap_h */ diff --git a/native/cocos/editor-support/spine/IkConstraint.cpp b/native/cocos/editor-support/spine/IkConstraint.cpp index e6ba21ddc4..0db6ea9e36 100644 --- a/native/cocos/editor-support/spine/IkConstraint.cpp +++ b/native/cocos/editor-support/spine/IkConstraint.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -44,13 +44,13 @@ using namespace spine; RTTI_IMPL(IkConstraint, Updatable) void IkConstraint::apply(Bone &bone, float targetX, float targetY, bool compress, bool stretch, bool uniform, float alpha) { - Bone *p = bone.getParent(); - float pa = p->_a, pb = p->_b, pc = p->_c, pd = p->_d; - float rotationIK = -bone._ashearX - bone._arotation; - float tx = 0, ty = 0; + Bone *p = bone.getParent(); + float pa = p->_a, pb = p->_b, pc = p->_c, pd = p->_d; + float rotationIK = -bone._ashearX - bone._arotation; + float tx = 0, ty = 0; if (!bone._appliedValid) bone.updateAppliedTransform(); - switch(bone._data.getTransformMode()) { + switch (bone._data.getTransformMode()) { case TransformMode_OnlyTranslation: tx = targetX - bone._worldX; ty = targetY - bone._worldY; @@ -61,296 +61,299 @@ void IkConstraint::apply(Bone &bone, float targetX, float targetY, bool compress pb = -pc * ps; pd = pa * ps; } - default: - float x = targetX - p->_worldX, y = targetY - p->_worldY; - float d = pa * pd - pb * pc; - tx = (x * pd - y * pb) / d - bone._ax; - ty = (y * pa - x * pc) / d - bone._ay; - } + default: + float x = targetX - p->_worldX, y = targetY - p->_worldY; + float d = pa * pd - pb * pc; + tx = (x * pd - y * pb) / d - bone._ax; + ty = (y * pa - x * pc) / d - bone._ay; + } rotationIK += MathUtil::atan2(ty, tx) * MathUtil::Rad_Deg; - if (bone._ascaleX < 0) rotationIK += 180; - if (rotationIK > 180) rotationIK -= 360; - else if (rotationIK < -180) rotationIK += 360; - float sx = bone._ascaleX; - float sy = bone._ascaleY; - if (compress || stretch) { - switch(bone._data.getTransformMode()) { - case TransformMode_NoScale: - case TransformMode_NoScaleOrReflection: - tx = targetX - bone._worldX; - ty = targetY - bone._worldY; - default: ; - } - float b = bone._data.getLength() * sx, dd = MathUtil::sqrt(tx * tx + ty * ty); - if (((compress && dd < b) || (stretch && dd > b)) && (b > 0.0001f)) { - float s = (dd / b - 1) * alpha + 1; - sx *= s; - if (uniform) sy *= s; - } - } - bone.updateWorldTransform(bone._ax, bone._ay, bone._arotation + rotationIK * alpha, sx, sy, bone._ashearX, bone._ashearY); + if (bone._ascaleX < 0) rotationIK += 180; + if (rotationIK > 180) + rotationIK -= 360; + else if (rotationIK < -180) + rotationIK += 360; + float sx = bone._ascaleX; + float sy = bone._ascaleY; + if (compress || stretch) { + switch (bone._data.getTransformMode()) { + case TransformMode_NoScale: + case TransformMode_NoScaleOrReflection: + tx = targetX - bone._worldX; + ty = targetY - bone._worldY; + default:; + } + float b = bone._data.getLength() * sx, dd = MathUtil::sqrt(tx * tx + ty * ty); + if (((compress && dd < b) || (stretch && dd > b)) && (b > 0.0001f)) { + float s = (dd / b - 1) * alpha + 1; + sx *= s; + if (uniform) sy *= s; + } + } + bone.updateWorldTransform(bone._ax, bone._ay, bone._arotation + rotationIK * alpha, sx, sy, bone._ashearX, bone._ashearY); } void IkConstraint::apply(Bone &parent, Bone &child, float targetX, float targetY, int bendDir, bool stretch, float softness, float alpha) { - float a, b, c, d; - float px, py, psx, sx, psy; - float cx, cy, csx, cwx, cwy; - int o1, o2, s2, u; - Bone *pp = parent.getParent(); - float tx, ty, dx, dy, dd, l1, l2, a1, a2, r, td, sd, p; - float id, x, y; - if (alpha == 0) { - child.updateWorldTransform(); - return; - } - if (!parent._appliedValid) parent.updateAppliedTransform(); - if (!child._appliedValid) child.updateAppliedTransform(); - px = parent._ax; - py = parent._ay; - psx = parent._ascaleX; - sx = psx; - psy = parent._ascaleY; - csx = child._ascaleX; - if (psx < 0) { - psx = -psx; - o1 = 180; - s2 = -1; - } else { - o1 = 0; - s2 = 1; - } - if (psy < 0) { - psy = -psy; - s2 = -s2; - } - if (csx < 0) { - csx = -csx; - o2 = 180; - } else - o2 = 0; - r = psx - psy; - cx = child._ax; - u = (r < 0 ? -r : r) <= 0.0001f; - if (!u) { - cy = 0; - cwx = parent._a * cx + parent._worldX; - cwy = parent._c * cx + parent._worldY; - } else { - cy = child._ay; - cwx = parent._a * cx + parent._b * cy + parent._worldX; - cwy = parent._c * cx + parent._d * cy + parent._worldY; - } - a = pp->_a; - b = pp->_b; - c = pp->_c; - d = pp->_d; - id = 1 / (a * d - b * c); - x = cwx - pp->_worldX; - y = cwy - pp->_worldY; - dx = (x * d - y * b) * id - px; - dy = (y * a - x * c) * id - py; - l1 = MathUtil::sqrt(dx * dx + dy * dy); - l2 = child._data.getLength() * csx; - if (l1 < 0.0001) { - apply(parent, targetX, targetY, false, stretch, false, alpha); - child.updateWorldTransform(cx, cy, 0, child._ascaleX, child._ascaleY, child._ashearX, child._ashearY); - return; - } - x = targetX - pp->_worldX; - y = targetY - pp->_worldY; - tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; - dd = tx * tx + ty * ty; - if (softness != 0) { - softness *= psx * (csx + 1) / 2; - td = MathUtil::sqrt(dd), sd = td - l1 - l2 * psx + softness; - if (sd > 0) { - p = MathUtil::min(1.0f, sd / (softness * 2)) - 1; - p = (sd - softness * (1 - p * p)) / td; - tx -= p * tx; - ty -= p * ty; - dd = tx * tx + ty * ty; - } - } - if (u) { - float cosine; - l2 *= psx; - cosine = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2); - if (cosine < -1) cosine = -1; - else if (cosine > 1) { - cosine = 1; - if (stretch) sx *= (MathUtil::sqrt(dd) / (l1 + l2) - 1) * alpha + 1; - } - a2 = MathUtil::acos(cosine) * bendDir; - a = l1 + l2 * cosine; - b = l2 * MathUtil::sin(a2); - a1 = MathUtil::atan2(ty * a - tx * b, tx * a + ty * b); - } else { - a = psx * l2, b = psy * l2; - float aa = a * a, bb = b * b, ll = l1 * l1, ta = MathUtil::atan2(ty, tx); - float c0 = bb * ll + aa * dd - aa * bb, c1 = -2 * bb * l1, c2 = bb - aa; - d = c1 * c1 - 4 * c2 * c0; - if (d >= 0) { - float q = MathUtil::sqrt(d), r0, r1; - if (c1 < 0) q = -q; - q = -(c1 + q) / 2; - r0 = q / c2; - r1 = c0 / q; - r = MathUtil::abs(r0) < MathUtil::abs(r1) ? r0 : r1; - if (r * r <= dd) { - y = MathUtil::sqrt(dd - r * r) * bendDir; - a1 = ta - MathUtil::atan2(y, r); - a2 = MathUtil::atan2(y / psy, (r - l1) / psx); - goto break_outer; - } - } - { - float minAngle = MathUtil::Pi, minX = l1 - a, minDist = minX * minX, minY = 0; - float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0; - c0 = -a * l1 / (aa - bb); - if (c0 >= -1 && c0 <= 1) { - c0 = MathUtil::acos(c0); - x = a * MathUtil::cos(c0) + l1; - y = b * MathUtil::sin(c0); - d = x * x + y * y; - if (d < minDist) { - minAngle = c0; - minDist = d; - minX = x; - minY = y; - } - if (d > maxDist) { - maxAngle = c0; - maxDist = d; - maxX = x; - maxY = y; - } - } - if (dd <= (minDist + maxDist) / 2) { - a1 = ta - MathUtil::atan2(minY * bendDir, minX); - a2 = minAngle * bendDir; - } else { - a1 = ta - MathUtil::atan2(maxY * bendDir, maxX); - a2 = maxAngle * bendDir; - } - } - } - break_outer: - { - float os = MathUtil::atan2(cy, cx) * s2; - a1 = (a1 - os) * MathUtil::Rad_Deg + o1 - parent._arotation; - if (a1 > 180) a1 -= 360; - else if (a1 < -180) a1 += 360; - parent.updateWorldTransform(px, py, parent._rotation + a1 * alpha, sx, parent._ascaleY, 0, 0); - a2 = ((a2 + os) * MathUtil::Rad_Deg - child._ashearX) * s2 + o2 - child._arotation; - if (a2 > 180) a2 -= 360; - else if (a2 < -180) a2 += 360; - child.updateWorldTransform(cx, cy, child._arotation + a2 * alpha, child._ascaleX, child._ascaleY, child._ashearX, child._ashearY); - } + float a, b, c, d; + float px, py, psx, sx, psy; + float cx, cy, csx, cwx, cwy; + int o1, o2, s2, u; + Bone *pp = parent.getParent(); + float tx, ty, dx, dy, dd, l1, l2, a1, a2, r, td, sd, p; + float id, x, y; + if (alpha == 0) { + child.updateWorldTransform(); + return; + } + if (!parent._appliedValid) parent.updateAppliedTransform(); + if (!child._appliedValid) child.updateAppliedTransform(); + px = parent._ax; + py = parent._ay; + psx = parent._ascaleX; + sx = psx; + psy = parent._ascaleY; + csx = child._ascaleX; + if (psx < 0) { + psx = -psx; + o1 = 180; + s2 = -1; + } else { + o1 = 0; + s2 = 1; + } + if (psy < 0) { + psy = -psy; + s2 = -s2; + } + if (csx < 0) { + csx = -csx; + o2 = 180; + } else + o2 = 0; + r = psx - psy; + cx = child._ax; + u = (r < 0 ? -r : r) <= 0.0001f; + if (!u) { + cy = 0; + cwx = parent._a * cx + parent._worldX; + cwy = parent._c * cx + parent._worldY; + } else { + cy = child._ay; + cwx = parent._a * cx + parent._b * cy + parent._worldX; + cwy = parent._c * cx + parent._d * cy + parent._worldY; + } + a = pp->_a; + b = pp->_b; + c = pp->_c; + d = pp->_d; + id = 1 / (a * d - b * c); + x = cwx - pp->_worldX; + y = cwy - pp->_worldY; + dx = (x * d - y * b) * id - px; + dy = (y * a - x * c) * id - py; + l1 = MathUtil::sqrt(dx * dx + dy * dy); + l2 = child._data.getLength() * csx; + if (l1 < 0.0001) { + apply(parent, targetX, targetY, false, stretch, false, alpha); + child.updateWorldTransform(cx, cy, 0, child._ascaleX, child._ascaleY, child._ashearX, child._ashearY); + return; + } + x = targetX - pp->_worldX; + y = targetY - pp->_worldY; + tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; + dd = tx * tx + ty * ty; + if (softness != 0) { + softness *= psx * (csx + 1) / 2; + td = MathUtil::sqrt(dd), sd = td - l1 - l2 * psx + softness; + if (sd > 0) { + p = MathUtil::min(1.0f, sd / (softness * 2)) - 1; + p = (sd - softness * (1 - p * p)) / td; + tx -= p * tx; + ty -= p * ty; + dd = tx * tx + ty * ty; + } + } + if (u) { + float cosine; + l2 *= psx; + cosine = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2); + if (cosine < -1) + cosine = -1; + else if (cosine > 1) { + cosine = 1; + if (stretch) sx *= (MathUtil::sqrt(dd) / (l1 + l2) - 1) * alpha + 1; + } + a2 = MathUtil::acos(cosine) * bendDir; + a = l1 + l2 * cosine; + b = l2 * MathUtil::sin(a2); + a1 = MathUtil::atan2(ty * a - tx * b, tx * a + ty * b); + } else { + a = psx * l2, b = psy * l2; + float aa = a * a, bb = b * b, ll = l1 * l1, ta = MathUtil::atan2(ty, tx); + float c0 = bb * ll + aa * dd - aa * bb, c1 = -2 * bb * l1, c2 = bb - aa; + d = c1 * c1 - 4 * c2 * c0; + if (d >= 0) { + float q = MathUtil::sqrt(d), r0, r1; + if (c1 < 0) q = -q; + q = -(c1 + q) / 2; + r0 = q / c2; + r1 = c0 / q; + r = MathUtil::abs(r0) < MathUtil::abs(r1) ? r0 : r1; + if (r * r <= dd) { + y = MathUtil::sqrt(dd - r * r) * bendDir; + a1 = ta - MathUtil::atan2(y, r); + a2 = MathUtil::atan2(y / psy, (r - l1) / psx); + goto break_outer; + } + } + { + float minAngle = MathUtil::Pi, minX = l1 - a, minDist = minX * minX, minY = 0; + float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0; + c0 = -a * l1 / (aa - bb); + if (c0 >= -1 && c0 <= 1) { + c0 = MathUtil::acos(c0); + x = a * MathUtil::cos(c0) + l1; + y = b * MathUtil::sin(c0); + d = x * x + y * y; + if (d < minDist) { + minAngle = c0; + minDist = d; + minX = x; + minY = y; + } + if (d > maxDist) { + maxAngle = c0; + maxDist = d; + maxX = x; + maxY = y; + } + } + if (dd <= (minDist + maxDist) / 2) { + a1 = ta - MathUtil::atan2(minY * bendDir, minX); + a2 = minAngle * bendDir; + } else { + a1 = ta - MathUtil::atan2(maxY * bendDir, maxX); + a2 = maxAngle * bendDir; + } + } + } +break_outer : { + float os = MathUtil::atan2(cy, cx) * s2; + a1 = (a1 - os) * MathUtil::Rad_Deg + o1 - parent._arotation; + if (a1 > 180) + a1 -= 360; + else if (a1 < -180) + a1 += 360; + parent.updateWorldTransform(px, py, parent._rotation + a1 * alpha, sx, parent._ascaleY, 0, 0); + a2 = ((a2 + os) * MathUtil::Rad_Deg - child._ashearX) * s2 + o2 - child._arotation; + if (a2 > 180) + a2 -= 360; + else if (a2 < -180) + a2 += 360; + child.updateWorldTransform(cx, cy, child._arotation + a2 * alpha, child._ascaleX, child._ascaleY, child._ashearX, child._ashearY); +} } IkConstraint::IkConstraint(IkConstraintData &data, Skeleton &skeleton) : Updatable(), - _data(data), - _bendDirection(data.getBendDirection()), - _compress(data.getCompress()), - _stretch(data.getStretch()), - _mix(data.getMix()), - _softness(data.getSoftness()), - _target(skeleton.findBone( - data.getTarget()->getName())), - _active(false) -{ - _bones.ensureCapacity(_data.getBones().size()); - for (size_t i = 0; i < _data.getBones().size(); i++) { - BoneData *boneData = _data.getBones()[i]; - _bones.add(skeleton.findBone(boneData->getName())); - } + _data(data), + _bendDirection(data.getBendDirection()), + _compress(data.getCompress()), + _stretch(data.getStretch()), + _mix(data.getMix()), + _softness(data.getSoftness()), + _target(skeleton.findBone( + data.getTarget()->getName())), + _active(false) { + _bones.ensureCapacity(_data.getBones().size()); + for (size_t i = 0; i < _data.getBones().size(); i++) { + BoneData *boneData = _data.getBones()[i]; + _bones.add(skeleton.findBone(boneData->getName())); + } } /// Applies the constraint to the constrained bones. void IkConstraint::apply() { - update(); + update(); } void IkConstraint::update() { - switch (_bones.size()) { - case 1: { - Bone *bone0 = _bones[0]; - apply(*bone0, _target->getWorldX(), _target->getWorldY(), _compress, _stretch, _data._uniform, _mix); - } - break; - case 2: { - Bone *bone0 = _bones[0]; - Bone *bone1 = _bones[1]; - apply(*bone0, *bone1, _target->getWorldX(), _target->getWorldY(), _bendDirection, _stretch, _softness, _mix); - } - break; - } + switch (_bones.size()) { + case 1: { + Bone *bone0 = _bones[0]; + apply(*bone0, _target->getWorldX(), _target->getWorldY(), _compress, _stretch, _data._uniform, _mix); + } break; + case 2: { + Bone *bone0 = _bones[0]; + Bone *bone1 = _bones[1]; + apply(*bone0, *bone1, _target->getWorldX(), _target->getWorldY(), _bendDirection, _stretch, _softness, _mix); + } break; + } } int IkConstraint::getOrder() { - return _data.getOrder(); + return _data.getOrder(); } IkConstraintData &IkConstraint::getData() { - return _data; + return _data; } Vector &IkConstraint::getBones() { - return _bones; + return _bones; } Bone *IkConstraint::getTarget() { - return _target; + return _target; } void IkConstraint::setTarget(Bone *inValue) { - _target = inValue; + _target = inValue; } int IkConstraint::getBendDirection() { - return _bendDirection; + return _bendDirection; } void IkConstraint::setBendDirection(int inValue) { - _bendDirection = inValue; + _bendDirection = inValue; } float IkConstraint::getMix() { - return _mix; + return _mix; } void IkConstraint::setMix(float inValue) { - _mix = inValue; + _mix = inValue; } bool IkConstraint::getStretch() { - return _stretch; + return _stretch; } void IkConstraint::setStretch(bool inValue) { - _stretch = inValue; + _stretch = inValue; } bool IkConstraint::getCompress() { - return _compress; + return _compress; } void IkConstraint::setCompress(bool inValue) { - _compress = inValue; + _compress = inValue; } bool IkConstraint::isActive() { - return _active; + return _active; } void IkConstraint::setActive(bool inValue) { - _active = inValue; + _active = inValue; } float IkConstraint::getSoftness() { - return _softness; + return _softness; } void IkConstraint::setSoftness(float inValue) { - _softness = inValue; + _softness = inValue; } diff --git a/native/cocos/editor-support/spine/IkConstraint.h b/native/cocos/editor-support/spine/IkConstraint.h index bef483241e..5fb217a9bf 100644 --- a/native/cocos/editor-support/spine/IkConstraint.h +++ b/native/cocos/editor-support/spine/IkConstraint.h @@ -42,74 +42,74 @@ class Skeleton; class Bone; class SP_API IkConstraint : public Updatable { - friend class Skeleton; + friend class Skeleton; - friend class IkConstraintTimeline; + friend class IkConstraintTimeline; -RTTI_DECL + RTTI_DECL public: - /// Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified - /// in the world coordinate system. - static void apply(Bone &bone, float targetX, float targetY, bool compress, bool stretch, bool uniform, float alpha); + /// Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified + /// in the world coordinate system. + static void apply(Bone &bone, float targetX, float targetY, bool compress, bool stretch, bool uniform, float alpha); - /// Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as - /// possible. The target is specified in the world coordinate system. - /// @param child A direct descendant of the parent bone. - static void apply(Bone &parent, Bone &child, float targetX, float targetY, int bendDir, bool stretch, float softness, float alpha); + /// Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as + /// possible. The target is specified in the world coordinate system. + /// @param child A direct descendant of the parent bone. + static void apply(Bone &parent, Bone &child, float targetX, float targetY, int bendDir, bool stretch, float softness, float alpha); - IkConstraint(IkConstraintData &data, Skeleton &skeleton); + IkConstraint(IkConstraintData &data, Skeleton &skeleton); - /// Applies the constraint to the constrained bones. - void apply(); + /// Applies the constraint to the constrained bones. + void apply(); - virtual void update(); + virtual void update(); - virtual int getOrder(); + virtual int getOrder(); - IkConstraintData &getData(); + IkConstraintData &getData(); - Vector &getBones(); + Vector &getBones(); - Bone *getTarget(); + Bone *getTarget(); - void setTarget(Bone *inValue); + void setTarget(Bone *inValue); - int getBendDirection(); + int getBendDirection(); - void setBendDirection(int inValue); + void setBendDirection(int inValue); - bool getCompress(); + bool getCompress(); - void setCompress(bool inValue); + void setCompress(bool inValue); - bool getStretch(); + bool getStretch(); - void setStretch(bool inValue); + void setStretch(bool inValue); - float getMix(); + float getMix(); - void setMix(float inValue); + void setMix(float inValue); - float getSoftness(); + float getSoftness(); - void setSoftness(float inValue); + void setSoftness(float inValue); - bool isActive(); + bool isActive(); - void setActive(bool inValue); + void setActive(bool inValue); private: - IkConstraintData &_data; - Vector _bones; - int _bendDirection; - bool _compress; - bool _stretch; - float _mix; - float _softness; - Bone *_target; - bool _active; + IkConstraintData &_data; + Vector _bones; + int _bendDirection; + bool _compress; + bool _stretch; + float _mix; + float _softness; + Bone *_target; + bool _active; }; -} +} // namespace spine #endif /* Spine_IkConstraint_h */ diff --git a/native/cocos/editor-support/spine/IkConstraintData.cpp b/native/cocos/editor-support/spine/IkConstraintData.cpp index f13fe5f690..263f9df830 100644 --- a/native/cocos/editor-support/spine/IkConstraintData.cpp +++ b/native/cocos/editor-support/spine/IkConstraintData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,74 +37,72 @@ using namespace spine; -IkConstraintData::IkConstraintData(const String &name) : - ConstraintData(name), - _target(NULL), - _bendDirection(1), - _compress(false), - _stretch(false), - _uniform(false), - _mix(1), - _softness(0) { +IkConstraintData::IkConstraintData(const String &name) : ConstraintData(name), + _target(NULL), + _bendDirection(1), + _compress(false), + _stretch(false), + _uniform(false), + _mix(1), + _softness(0) { } Vector &IkConstraintData::getBones() { - return _bones; + return _bones; } BoneData *IkConstraintData::getTarget() { - return _target; + return _target; } void IkConstraintData::setTarget(BoneData *inValue) { - _target = inValue; + _target = inValue; } int IkConstraintData::getBendDirection() { - return _bendDirection; + return _bendDirection; } void IkConstraintData::setBendDirection(int inValue) { - _bendDirection = inValue; + _bendDirection = inValue; } float IkConstraintData::getMix() { - return _mix; + return _mix; } void IkConstraintData::setMix(float inValue) { - _mix = inValue; + _mix = inValue; } bool IkConstraintData::getStretch() { - return _stretch; + return _stretch; } void IkConstraintData::setStretch(bool inValue) { - _stretch = inValue; + _stretch = inValue; } bool IkConstraintData::getCompress() { - return _compress; + return _compress; } void IkConstraintData::setCompress(bool inValue) { - _compress = inValue; + _compress = inValue; } - bool IkConstraintData::getUniform() { - return _uniform; + return _uniform; } void IkConstraintData::setUniform(bool inValue) { - _uniform = inValue; + _uniform = inValue; } float IkConstraintData::getSoftness() { - return _softness; + return _softness; } void IkConstraintData::setSoftness(float inValue) { - _softness = inValue; + _softness = inValue; } diff --git a/native/cocos/editor-support/spine/IkConstraintData.h b/native/cocos/editor-support/spine/IkConstraintData.h index cbf7cd87a6..0de1f239f2 100644 --- a/native/cocos/editor-support/spine/IkConstraintData.h +++ b/native/cocos/editor-support/spine/IkConstraintData.h @@ -36,54 +36,54 @@ #include namespace spine { - class BoneData; +class BoneData; - class SP_API IkConstraintData : public ConstraintData { - friend class SkeletonBinary; - friend class SkeletonJson; - friend class IkConstraint; - friend class Skeleton; - friend class IkConstraintTimeline; +class SP_API IkConstraintData : public ConstraintData { + friend class SkeletonBinary; + friend class SkeletonJson; + friend class IkConstraint; + friend class Skeleton; + friend class IkConstraintTimeline; - public: - explicit IkConstraintData(const String& name); +public: + explicit IkConstraintData(const String& name); - /// The bones that are constrained by this IK Constraint. - Vector& getBones(); + /// The bones that are constrained by this IK Constraint. + Vector& getBones(); - /// The bone that is the IK target. - BoneData* getTarget(); - void setTarget(BoneData* inValue); + /// The bone that is the IK target. + BoneData* getTarget(); + void setTarget(BoneData* inValue); - /// Controls the bend direction of the IK bones, either 1 or -1. - int getBendDirection(); - void setBendDirection(int inValue); + /// Controls the bend direction of the IK bones, either 1 or -1. + int getBendDirection(); + void setBendDirection(int inValue); - bool getCompress(); - void setCompress(bool inValue); + bool getCompress(); + void setCompress(bool inValue); - bool getStretch(); - void setStretch(bool inValue); + bool getStretch(); + void setStretch(bool inValue); - bool getUniform(); - void setUniform(bool inValue); + bool getUniform(); + void setUniform(bool inValue); - float getMix(); - void setMix(float inValue); + float getMix(); + void setMix(float inValue); - float getSoftness(); - void setSoftness(float inValue); + float getSoftness(); + void setSoftness(float inValue); - private: - Vector _bones; - BoneData* _target; - int _bendDirection; - bool _compress; - bool _stretch; - bool _uniform; - float _mix; - float _softness; - }; -} +private: + Vector _bones; + BoneData* _target; + int _bendDirection; + bool _compress; + bool _stretch; + bool _uniform; + float _mix; + float _softness; +}; +} // namespace spine #endif /* Spine_IkConstraintData_h */ diff --git a/native/cocos/editor-support/spine/IkConstraintTimeline.cpp b/native/cocos/editor-support/spine/IkConstraintTimeline.cpp index f0e817a5d6..05d79432f7 100644 --- a/native/cocos/editor-support/spine/IkConstraintTimeline.cpp +++ b/native/cocos/editor-support/spine/IkConstraintTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -61,110 +61,108 @@ const int IkConstraintTimeline::COMPRESS = 4; const int IkConstraintTimeline::STRETCH = 5; IkConstraintTimeline::IkConstraintTimeline(int frameCount) : CurveTimeline(frameCount), _ikConstraintIndex(0) { - _frames.setSize(frameCount * ENTRIES, 0); + _frames.setSize(frameCount * ENTRIES, 0); } void IkConstraintTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); - IkConstraint *constraintP = skeleton._ikConstraints[_ikConstraintIndex]; - IkConstraint &constraint = *constraintP; - if (!constraint.isActive()) return; + IkConstraint *constraintP = skeleton._ikConstraints[_ikConstraintIndex]; + IkConstraint &constraint = *constraintP; + if (!constraint.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - constraint._mix = constraint._data._mix; - constraint._softness = constraint._data._softness; - constraint._bendDirection = constraint._data._bendDirection; - constraint._compress = constraint._data._compress; - constraint._stretch = constraint._data._stretch; - return; - case MixBlend_First: - constraint._mix += (constraint._data._mix - constraint._mix) * alpha; - constraint._softness += (constraint._data._softness - constraint._softness) * alpha; - constraint._bendDirection = constraint._data._bendDirection; - constraint._compress = constraint._data._compress; - constraint._stretch = constraint._data._stretch; - return; - default: - return; - } - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + constraint._mix = constraint._data._mix; + constraint._softness = constraint._data._softness; + constraint._bendDirection = constraint._data._bendDirection; + constraint._compress = constraint._data._compress; + constraint._stretch = constraint._data._stretch; + return; + case MixBlend_First: + constraint._mix += (constraint._data._mix - constraint._mix) * alpha; + constraint._softness += (constraint._data._softness - constraint._softness) * alpha; + constraint._bendDirection = constraint._data._bendDirection; + constraint._compress = constraint._data._compress; + constraint._stretch = constraint._data._stretch; + return; + default: + return; + } + } - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - if (blend == MixBlend_Setup) { - constraint._mix = - constraint._data._mix + (_frames[_frames.size() + PREV_MIX] - constraint._data._mix) * alpha; - constraint._softness = constraint._data._softness - + (_frames[_frames.size() + PREV_SOFTNESS] - constraint._data._softness) * alpha; - if (direction == MixDirection_Out) { - constraint._bendDirection = constraint._data._bendDirection; - constraint._compress = constraint._data._compress; - constraint._stretch = constraint._data._stretch; - } else { - constraint._bendDirection = (int) _frames[_frames.size() + PREV_BEND_DIRECTION]; - constraint._compress = _frames[_frames.size() + PREV_COMPRESS] != 0; - constraint._stretch = _frames[_frames.size() + PREV_STRETCH] != 0; - } - } else { - constraint._mix += (_frames[_frames.size() + PREV_MIX] - constraint._mix) * alpha; - constraint._softness += (_frames[_frames.size() + PREV_SOFTNESS] - constraint._softness) * alpha; - if (direction == MixDirection_In) { - constraint._bendDirection = (int) _frames[_frames.size() + PREV_BEND_DIRECTION]; - constraint._compress = _frames[_frames.size() + PREV_COMPRESS] != 0; - constraint._stretch = _frames[_frames.size() + PREV_STRETCH] != 0; - } - } - return; - } + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + if (blend == MixBlend_Setup) { + constraint._mix = + constraint._data._mix + (_frames[_frames.size() + PREV_MIX] - constraint._data._mix) * alpha; + constraint._softness = constraint._data._softness + (_frames[_frames.size() + PREV_SOFTNESS] - constraint._data._softness) * alpha; + if (direction == MixDirection_Out) { + constraint._bendDirection = constraint._data._bendDirection; + constraint._compress = constraint._data._compress; + constraint._stretch = constraint._data._stretch; + } else { + constraint._bendDirection = (int)_frames[_frames.size() + PREV_BEND_DIRECTION]; + constraint._compress = _frames[_frames.size() + PREV_COMPRESS] != 0; + constraint._stretch = _frames[_frames.size() + PREV_STRETCH] != 0; + } + } else { + constraint._mix += (_frames[_frames.size() + PREV_MIX] - constraint._mix) * alpha; + constraint._softness += (_frames[_frames.size() + PREV_SOFTNESS] - constraint._softness) * alpha; + if (direction == MixDirection_In) { + constraint._bendDirection = (int)_frames[_frames.size() + PREV_BEND_DIRECTION]; + constraint._compress = _frames[_frames.size() + PREV_COMPRESS] != 0; + constraint._stretch = _frames[_frames.size() + PREV_STRETCH] != 0; + } + } + return; + } - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - float mix = _frames[frame + PREV_MIX]; - float softness = _frames[frame + PREV_SOFTNESS]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + float mix = _frames[frame + PREV_MIX]; + float softness = _frames[frame + PREV_SOFTNESS]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - if (blend == MixBlend_Setup) { - constraint._mix = - constraint._data._mix + (mix + (_frames[frame + MIX] - mix) * percent - constraint._data._mix) * alpha; - constraint._softness = constraint._data._softness - + (softness + (_frames[frame + SOFTNESS] - softness) * percent - constraint._data._softness) * alpha; - if (direction == MixDirection_Out) { - constraint._bendDirection = constraint._data._bendDirection; - constraint._compress = constraint._data._compress; - constraint._stretch = constraint._data._stretch; - } else { - constraint._bendDirection = (int) _frames[_frames.size() + PREV_BEND_DIRECTION]; - constraint._compress = _frames[frame + PREV_COMPRESS] != 0; - constraint._stretch = _frames[frame + PREV_STRETCH] != 0; - } - } else { - constraint._mix += (mix + (_frames[frame + MIX] - mix) * percent - constraint._mix) * alpha; - constraint._softness += (softness + (_frames[frame + SOFTNESS] - softness) * percent - constraint._softness) * alpha; - if (direction == MixDirection_In) { - constraint._bendDirection = (int) _frames[frame + PREV_BEND_DIRECTION]; - constraint._compress = _frames[frame + PREV_COMPRESS] != 0; - constraint._stretch = _frames[frame + PREV_STRETCH] != 0; - } - } + if (blend == MixBlend_Setup) { + constraint._mix = + constraint._data._mix + (mix + (_frames[frame + MIX] - mix) * percent - constraint._data._mix) * alpha; + constraint._softness = constraint._data._softness + (softness + (_frames[frame + SOFTNESS] - softness) * percent - constraint._data._softness) * alpha; + if (direction == MixDirection_Out) { + constraint._bendDirection = constraint._data._bendDirection; + constraint._compress = constraint._data._compress; + constraint._stretch = constraint._data._stretch; + } else { + constraint._bendDirection = (int)_frames[_frames.size() + PREV_BEND_DIRECTION]; + constraint._compress = _frames[frame + PREV_COMPRESS] != 0; + constraint._stretch = _frames[frame + PREV_STRETCH] != 0; + } + } else { + constraint._mix += (mix + (_frames[frame + MIX] - mix) * percent - constraint._mix) * alpha; + constraint._softness += (softness + (_frames[frame + SOFTNESS] - softness) * percent - constraint._softness) * alpha; + if (direction == MixDirection_In) { + constraint._bendDirection = (int)_frames[frame + PREV_BEND_DIRECTION]; + constraint._compress = _frames[frame + PREV_COMPRESS] != 0; + constraint._stretch = _frames[frame + PREV_STRETCH] != 0; + } + } } int IkConstraintTimeline::getPropertyId() { - return ((int) TimelineType_IkConstraint << 24) + _ikConstraintIndex; + return ((int)TimelineType_IkConstraint << 24) + _ikConstraintIndex; } void IkConstraintTimeline::setFrame(int frameIndex, float time, float mix, float softness, int bendDirection, bool compress, bool stretch) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + MIX] = mix; - _frames[frameIndex + SOFTNESS] = softness; - _frames[frameIndex + BEND_DIRECTION] = (float)bendDirection; - _frames[frameIndex + COMPRESS] = compress ? 1 : 0; - _frames[frameIndex + STRETCH] = stretch ? 1 : 0; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + MIX] = mix; + _frames[frameIndex + SOFTNESS] = softness; + _frames[frameIndex + BEND_DIRECTION] = (float)bendDirection; + _frames[frameIndex + COMPRESS] = compress ? 1 : 0; + _frames[frameIndex + STRETCH] = stretch ? 1 : 0; } diff --git a/native/cocos/editor-support/spine/IkConstraintTimeline.h b/native/cocos/editor-support/spine/IkConstraintTimeline.h index c710b78c75..c5ceffadea 100644 --- a/native/cocos/editor-support/spine/IkConstraintTimeline.h +++ b/native/cocos/editor-support/spine/IkConstraintTimeline.h @@ -34,40 +34,40 @@ namespace spine { - class SP_API IkConstraintTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API IkConstraintTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit IkConstraintTimeline(int frameCount); + explicit IkConstraintTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time, mix and bend direction of the specified keyframe. - void setFrame (int frameIndex, float time, float mix, float softness, int bendDirection, bool compress, bool stretch); + /// Sets the time, mix and bend direction of the specified keyframe. + void setFrame(int frameIndex, float time, float mix, float softness, int bendDirection, bool compress, bool stretch); - private: - static const int PREV_TIME; - static const int PREV_MIX; - static const int PREV_SOFTNESS; - static const int PREV_BEND_DIRECTION; - static const int PREV_COMPRESS; - static const int PREV_STRETCH; - static const int MIX; - static const int SOFTNESS; - static const int BEND_DIRECTION; - static const int COMPRESS; - static const int STRETCH; +private: + static const int PREV_TIME; + static const int PREV_MIX; + static const int PREV_SOFTNESS; + static const int PREV_BEND_DIRECTION; + static const int PREV_COMPRESS; + static const int PREV_STRETCH; + static const int MIX; + static const int SOFTNESS; + static const int BEND_DIRECTION; + static const int COMPRESS; + static const int STRETCH; - Vector _frames; - int _ikConstraintIndex; - }; -} + Vector _frames; + int _ikConstraintIndex; +}; +} // namespace spine #endif /* Spine_IkConstraintTimeline_h */ diff --git a/native/cocos/editor-support/spine/Json.cpp b/native/cocos/editor-support/spine/Json.cpp index 8466816e27..abef7f1883 100644 --- a/native/cocos/editor-support/spine/Json.cpp +++ b/native/cocos/editor-support/spine/Json.cpp @@ -22,20 +22,20 @@ THE SOFTWARE. */ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif /* Json */ /* JSON parser in CPP, from json.c in the spine-c runtime */ #ifndef _DEFAULT_SOURCE -/* Bring strings.h definitions into string.h, where appropriate */ -#define _DEFAULT_SOURCE + /* Bring strings.h definitions into string.h, where appropriate */ + #define _DEFAULT_SOURCE #endif #ifndef _BSD_SOURCE -/* Bring strings.h definitions into string.h, where appropriate */ -#define _BSD_SOURCE + /* Bring strings.h definitions into string.h, where appropriate */ + #define _BSD_SOURCE #endif #include @@ -58,79 +58,78 @@ const int Json::JSON_OBJECT = 6; const char *Json::_error = NULL; Json *Json::getItem(Json *object, const char *string) { - Json *c = object->_child; - while (c && json_strcasecmp(c->_name, string)) { - c = c->_next; - } - return c; + Json *c = object->_child; + while (c && json_strcasecmp(c->_name, string)) { + c = c->_next; + } + return c; } const char *Json::getString(Json *object, const char *name, const char *defaultValue) { - object = getItem(object, name); - if (object) { - return object->_valueString; - } + object = getItem(object, name); + if (object) { + return object->_valueString; + } - return defaultValue; + return defaultValue; } float Json::getFloat(Json *value, const char *name, float defaultValue) { - value = getItem(value, name); - return value ? value->_valueFloat : defaultValue; + value = getItem(value, name); + return value ? value->_valueFloat : defaultValue; } int Json::getInt(Json *value, const char *name, int defaultValue) { - value = getItem(value, name); - return value ? value->_valueInt : defaultValue; + value = getItem(value, name); + return value ? value->_valueInt : defaultValue; } bool Json::getBoolean(spine::Json *value, const char *name, bool defaultValue) { - value = getItem(value, name); - if (value) { - if (value->_valueString) return strcmp(value->_valueString, "true") == 0; - if (value->_type == JSON_TRUE) return true; - if (value->_type == JSON_FALSE) return false; - if (value->_type == JSON_NULL) return false; - if (value->_type == JSON_NUMBER) return value->_valueFloat != 0; - return defaultValue; - } else { - return defaultValue; - } + value = getItem(value, name); + if (value) { + if (value->_valueString) return strcmp(value->_valueString, "true") == 0; + if (value->_type == JSON_TRUE) return true; + if (value->_type == JSON_FALSE) return false; + if (value->_type == JSON_NULL) return false; + if (value->_type == JSON_NUMBER) return value->_valueFloat != 0; + return defaultValue; + } else { + return defaultValue; + } } const char *Json::getError() { - return _error; + return _error; } -Json::Json(const char *value) : - _next(NULL), +Json::Json(const char *value) : _next(NULL), #if SPINE_JSON_HAVE_PREV - _prev(NULL), + _prev(NULL), #endif - _child(NULL), - _type(0), - _size(0), - _valueString(NULL), - _valueInt(0), - _valueFloat(0), - _name(NULL) { - if (value) { - value = parseValue(this, skip(value)); + _child(NULL), + _type(0), + _size(0), + _valueString(NULL), + _valueInt(0), + _valueFloat(0), + _name(NULL) { + if (value) { + value = parseValue(this, skip(value)); - assert(value); - } + assert(value); + } } Json::~Json() { - spine::Json* curr = nullptr; - spine::Json* next = _child; + spine::Json *curr = nullptr; + spine::Json *next = _child; do { curr = next; if (curr) { next = curr->_next; } delete curr; - } while(next); + } while (next); if (_valueString) { SpineExtension::free(_valueString, __FILE__, __LINE__); @@ -142,416 +141,416 @@ Json::~Json() { } const char *Json::skip(const char *inValue) { - if (!inValue) { - /* must propagate NULL since it's often called in skip(f(...)) form */ - return NULL; - } + if (!inValue) { + /* must propagate NULL since it's often called in skip(f(...)) form */ + return NULL; + } - while (*inValue && (unsigned char) *inValue <= 32) { - inValue++; - } + while (*inValue && (unsigned char)*inValue <= 32) { + inValue++; + } - return inValue; + return inValue; } const char *Json::parseValue(Json *item, const char *value) { - /* Referenced by constructor, parseArray(), and parseObject(). */ - /* Always called with the result of skip(). */ + /* Referenced by constructor, parseArray(), and parseObject(). */ + /* Always called with the result of skip(). */ #ifdef SPINE_JSON_DEBUG /* Checked at entry to graph, constructor, and after every parse call. */ - if (!value) { - /* Fail on null. */ - return NULL; - } + if (!value) { + /* Fail on null. */ + return NULL; + } #endif - switch (*value) { - case 'n': { - if (!strncmp(value + 1, "ull", 3)) { - item->_type = JSON_NULL; - return value + 4; - } - break; - } - case 'f': { - if (!strncmp(value + 1, "alse", 4)) { - item->_type = JSON_FALSE; - /* calloc prevents us needing item->_type = JSON_FALSE or valueInt = 0 here */ - return value + 5; - } - break; - } - case 't': { - if (!strncmp(value + 1, "rue", 3)) { - item->_type = JSON_TRUE; - item->_valueInt = 1; - return value + 4; - } - break; - } - case '\"': - return parseString(item, value); - case '[': - return parseArray(item, value); - case '{': - return parseObject(item, value); - case '-': /* fallthrough */ - case '0': /* fallthrough */ - case '1': /* fallthrough */ - case '2': /* fallthrough */ - case '3': /* fallthrough */ - case '4': /* fallthrough */ - case '5': /* fallthrough */ - case '6': /* fallthrough */ - case '7': /* fallthrough */ - case '8': /* fallthrough */ - case '9': - return parseNumber(item, value); - default: - break; - } + switch (*value) { + case 'n': { + if (!strncmp(value + 1, "ull", 3)) { + item->_type = JSON_NULL; + return value + 4; + } + break; + } + case 'f': { + if (!strncmp(value + 1, "alse", 4)) { + item->_type = JSON_FALSE; + /* calloc prevents us needing item->_type = JSON_FALSE or valueInt = 0 here */ + return value + 5; + } + break; + } + case 't': { + if (!strncmp(value + 1, "rue", 3)) { + item->_type = JSON_TRUE; + item->_valueInt = 1; + return value + 4; + } + break; + } + case '\"': + return parseString(item, value); + case '[': + return parseArray(item, value); + case '{': + return parseObject(item, value); + case '-': /* fallthrough */ + case '0': /* fallthrough */ + case '1': /* fallthrough */ + case '2': /* fallthrough */ + case '3': /* fallthrough */ + case '4': /* fallthrough */ + case '5': /* fallthrough */ + case '6': /* fallthrough */ + case '7': /* fallthrough */ + case '8': /* fallthrough */ + case '9': + return parseNumber(item, value); + default: + break; + } - _error = value; - return NULL; /* failure. */ + _error = value; + return NULL; /* failure. */ } static const unsigned char firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; const char *Json::parseString(Json *item, const char *str) { - const char *ptr = str + 1; - char *ptr2; - char *out; - int len = 0; - unsigned uc, uc2; - if (*str != '\"') { - /* TODO: don't need this check when called from parseValue, but do need from parseObject */ - _error = str; - return 0; - } /* not a string! */ + const char *ptr = str + 1; + char *ptr2; + char *out; + int len = 0; + unsigned uc, uc2; + if (*str != '\"') { + /* TODO: don't need this check when called from parseValue, but do need from parseObject */ + _error = str; + return 0; + } /* not a string! */ - while (*ptr != '\"' && *ptr && ++len) { - if (*ptr++ == '\\') { - ptr++; /* Skip escaped quotes. */ - } - } + while (*ptr != '\"' && *ptr && ++len) { + if (*ptr++ == '\\') { + ptr++; /* Skip escaped quotes. */ + } + } - out = SpineExtension::alloc(len + 1, __FILE__, __LINE__); /* The length needed for the string, roughly. */ - if (!out) { - return 0; - } + out = SpineExtension::alloc(len + 1, __FILE__, __LINE__); /* The length needed for the string, roughly. */ + if (!out) { + return 0; + } - ptr = str + 1; - ptr2 = out; - while (*ptr != '\"' && *ptr) { - if (*ptr != '\\') { - *ptr2++ = *ptr++; - } else { - ptr++; - switch (*ptr) { - case 'b': - *ptr2++ = '\b'; - break; - case 'f': - *ptr2++ = '\f'; - break; - case 'n': - *ptr2++ = '\n'; - break; - case 'r': - *ptr2++ = '\r'; - break; - case 't': - *ptr2++ = '\t'; - break; - case 'u': { - /* transcode utf16 to utf8. */ - sscanf(ptr + 1, "%4x", &uc); - ptr += 4; /* get the unicode char. */ + ptr = str + 1; + ptr2 = out; + while (*ptr != '\"' && *ptr) { + if (*ptr != '\\') { + *ptr2++ = *ptr++; + } else { + ptr++; + switch (*ptr) { + case 'b': + *ptr2++ = '\b'; + break; + case 'f': + *ptr2++ = '\f'; + break; + case 'n': + *ptr2++ = '\n'; + break; + case 'r': + *ptr2++ = '\r'; + break; + case 't': + *ptr2++ = '\t'; + break; + case 'u': { + /* transcode utf16 to utf8. */ + sscanf(ptr + 1, "%4x", &uc); + ptr += 4; /* get the unicode char. */ - if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) { - break; /* check for invalid. */ - } + if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) { + break; /* check for invalid. */ + } - /* TODO provide an option to ignore surrogates, use unicode replacement character? */ - if (uc >= 0xD800 && uc <= 0xDBFF) /* UTF16 surrogate pairs. */ { - if (ptr[1] != '\\' || ptr[2] != 'u') { - break; /* missing second-half of surrogate. */ - } - sscanf(ptr + 3, "%4x", &uc2); - ptr += 6; - if (uc2 < 0xDC00 || uc2 > 0xDFFF) { - break; /* invalid second-half of surrogate. */ - } - uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF)); - } + /* TODO provide an option to ignore surrogates, use unicode replacement character? */ + if (uc >= 0xD800 && uc <= 0xDBFF) /* UTF16 surrogate pairs. */ { + if (ptr[1] != '\\' || ptr[2] != 'u') { + break; /* missing second-half of surrogate. */ + } + sscanf(ptr + 3, "%4x", &uc2); + ptr += 6; + if (uc2 < 0xDC00 || uc2 > 0xDFFF) { + break; /* invalid second-half of surrogate. */ + } + uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF)); + } - len = 4; - if (uc < 0x80) { - len = 1; - } else if (uc < 0x800) { - len = 2; - } else if (uc < 0x10000) { - len = 3; - } - ptr2 += len; + len = 4; + if (uc < 0x80) { + len = 1; + } else if (uc < 0x800) { + len = 2; + } else if (uc < 0x10000) { + len = 3; + } + ptr2 += len; - switch (len) { - case 4: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - /* fallthrough */ - case 3: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - /* fallthrough */ - case 2: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - /* fallthrough */ - case 1: - *--ptr2 = (uc | firstByteMark[len]); - } - ptr2 += len; - break; - } - default: - *ptr2++ = *ptr; - break; - } - ptr++; - } - } + switch (len) { + case 4: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + /* fallthrough */ + case 3: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + /* fallthrough */ + case 2: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + /* fallthrough */ + case 1: + *--ptr2 = (uc | firstByteMark[len]); + } + ptr2 += len; + break; + } + default: + *ptr2++ = *ptr; + break; + } + ptr++; + } + } - *ptr2 = 0; + *ptr2 = 0; - if (*ptr == '\"') { - ptr++; /* TODO error handling if not \" or \0 ? */ - } + if (*ptr == '\"') { + ptr++; /* TODO error handling if not \" or \0 ? */ + } - item->_valueString = out; - item->_type = JSON_STRING; + item->_valueString = out; + item->_type = JSON_STRING; - return ptr; + return ptr; } const char *Json::parseNumber(Json *item, const char *num) { - double result = 0.0; - int negative = 0; - char *ptr = (char *) num; + double result = 0.0; + int negative = 0; + char *ptr = (char *)num; - if (*ptr == '-') { - negative = -1; - ++ptr; - } + if (*ptr == '-') { + negative = -1; + ++ptr; + } - while (*ptr >= '0' && *ptr <= '9') { - result = result * 10.0 + (*ptr - '0'); - ++ptr; - } + while (*ptr >= '0' && *ptr <= '9') { + result = result * 10.0 + (*ptr - '0'); + ++ptr; + } - if (*ptr == '.') { - double fraction = 0.0; - int n = 0; - ++ptr; + if (*ptr == '.') { + double fraction = 0.0; + int n = 0; + ++ptr; - while (*ptr >= '0' && *ptr <= '9') { - fraction = (fraction * 10.0) + (*ptr - '0'); - ++ptr; - ++n; - } - result += fraction / pow(10.0, n); - } + while (*ptr >= '0' && *ptr <= '9') { + fraction = (fraction * 10.0) + (*ptr - '0'); + ++ptr; + ++n; + } + result += fraction / pow(10.0, n); + } - if (negative) { - result = -result; - } + if (negative) { + result = -result; + } - if (*ptr == 'e' || *ptr == 'E') { - double exponent = 0; - int expNegative = 0; - int n = 0; - ++ptr; + if (*ptr == 'e' || *ptr == 'E') { + double exponent = 0; + int expNegative = 0; + int n = 0; + ++ptr; - if (*ptr == '-') { - expNegative = -1; - ++ptr; - } else if (*ptr == '+') { - ++ptr; - } + if (*ptr == '-') { + expNegative = -1; + ++ptr; + } else if (*ptr == '+') { + ++ptr; + } - while (*ptr >= '0' && *ptr <= '9') { - exponent = (exponent * 10.0) + (*ptr - '0'); - ++ptr; - ++n; - } + while (*ptr >= '0' && *ptr <= '9') { + exponent = (exponent * 10.0) + (*ptr - '0'); + ++ptr; + ++n; + } - if (expNegative) { - result = result / pow(10, exponent); - } else { - result = result * pow(10, exponent); - } - } + if (expNegative) { + result = result / pow(10, exponent); + } else { + result = result * pow(10, exponent); + } + } - if (ptr != num) { - /* Parse success, number found. */ - item->_valueFloat = (float)result; - item->_valueInt = (int)result; - item->_type = JSON_NUMBER; - return ptr; - } else { - /* Parse failure, _error is set. */ - _error = num; - return NULL; - } + if (ptr != num) { + /* Parse success, number found. */ + item->_valueFloat = (float)result; + item->_valueInt = (int)result; + item->_type = JSON_NUMBER; + return ptr; + } else { + /* Parse failure, _error is set. */ + _error = num; + return NULL; + } } const char *Json::parseArray(Json *item, const char *value) { - Json *child; + Json *child; #ifdef SPINE_JSON_DEBUG /* unnecessary, only callsite (parse_value) verifies this */ - if (*value != '[') { - ep = value; - return 0; - } /* not an array! */ + if (*value != '[') { + ep = value; + return 0; + } /* not an array! */ #endif - item->_type = JSON_ARRAY; - value = skip(value + 1); - if (*value == ']') { - return value + 1; /* empty array. */ - } + item->_type = JSON_ARRAY; + value = skip(value + 1); + if (*value == ']') { + return value + 1; /* empty array. */ + } - item->_child = child = new Json(NULL); - if (!item->_child) { - return NULL; /* memory fail */ - } + item->_child = child = new Json(NULL); + if (!item->_child) { + return NULL; /* memory fail */ + } - value = skip(parseValue(child, skip(value))); /* skip any spacing, get the value. */ + value = skip(parseValue(child, skip(value))); /* skip any spacing, get the value. */ - if (!value) { - return NULL; - } + if (!value) { + return NULL; + } - item->_size = 1; + item->_size = 1; - while (*value == ',') { - Json *new_item = new Json(NULL); - if (!new_item) { - return NULL; /* memory fail */ - } - child->_next = new_item; + while (*value == ',') { + Json *new_item = new Json(NULL); + if (!new_item) { + return NULL; /* memory fail */ + } + child->_next = new_item; #if SPINE_JSON_HAVE_PREV - new_item->prev = child; + new_item->prev = child; #endif - child = new_item; - value = skip(parseValue(child, skip(value + 1))); - if (!value) { - return NULL; /* parse fail */ - } - item->_size++; - } + child = new_item; + value = skip(parseValue(child, skip(value + 1))); + if (!value) { + return NULL; /* parse fail */ + } + item->_size++; + } - if (*value == ']') { - return value + 1; /* end of array */ - } + if (*value == ']') { + return value + 1; /* end of array */ + } - _error = value; + _error = value; - return NULL; /* malformed. */ + return NULL; /* malformed. */ } /* Build an object from the text. */ const char *Json::parseObject(Json *item, const char *value) { - Json *child; + Json *child; #ifdef SPINE_JSON_DEBUG /* unnecessary, only callsite (parse_value) verifies this */ - if (*value != '{') { - ep = value; - return 0; - } /* not an object! */ + if (*value != '{') { + ep = value; + return 0; + } /* not an object! */ #endif - item->_type = JSON_OBJECT; - value = skip(value + 1); - if (*value == '}') { - return value + 1; /* empty array. */ - } + item->_type = JSON_OBJECT; + value = skip(value + 1); + if (*value == '}') { + return value + 1; /* empty array. */ + } - item->_child = child = new Json(NULL); - if (!item->_child) { - return NULL; - } - value = skip(parseString(child, skip(value))); - if (!value) { - return NULL; - } - child->_name = child->_valueString; - child->_valueString = 0; - if (*value != ':') { - _error = value; - return NULL; - } /* fail! */ + item->_child = child = new Json(NULL); + if (!item->_child) { + return NULL; + } + value = skip(parseString(child, skip(value))); + if (!value) { + return NULL; + } + child->_name = child->_valueString; + child->_valueString = 0; + if (*value != ':') { + _error = value; + return NULL; + } /* fail! */ - value = skip(parseValue(child, skip(value + 1))); /* skip any spacing, get the value. */ - if (!value) { - return NULL; - } + value = skip(parseValue(child, skip(value + 1))); /* skip any spacing, get the value. */ + if (!value) { + return NULL; + } - item->_size = 1; + item->_size = 1; - while (*value == ',') { - Json *new_item = new Json(NULL); - if (!new_item) { - return NULL; /* memory fail */ - } - child->_next = new_item; + while (*value == ',') { + Json *new_item = new Json(NULL); + if (!new_item) { + return NULL; /* memory fail */ + } + child->_next = new_item; #if SPINE_JSON_HAVE_PREV - new_item->prev = child; + new_item->prev = child; #endif - child = new_item; - value = skip(parseString(child, skip(value + 1))); - if (!value) { - return NULL; - } - child->_name = child->_valueString; - child->_valueString = 0; - if (*value != ':') { - _error = value; - return NULL; - } /* fail! */ + child = new_item; + value = skip(parseString(child, skip(value + 1))); + if (!value) { + return NULL; + } + child->_name = child->_valueString; + child->_valueString = 0; + if (*value != ':') { + _error = value; + return NULL; + } /* fail! */ - value = skip(parseValue(child, skip(value + 1))); /* skip any spacing, get the value. */ - if (!value) { - return NULL; - } - item->_size++; - } + value = skip(parseValue(child, skip(value + 1))); /* skip any spacing, get the value. */ + if (!value) { + return NULL; + } + item->_size++; + } - if (*value == '}') { - return value + 1; /* end of array */ - } + if (*value == '}') { + return value + 1; /* end of array */ + } - _error = value; + _error = value; - return NULL; /* malformed. */ + return NULL; /* malformed. */ } int Json::json_strcasecmp(const char *s1, const char *s2) { - /* TODO we may be able to elide these NULL checks if we can prove + /* TODO we may be able to elide these NULL checks if we can prove * the graph and input (only callsite is Json_getItem) should not have NULLs */ - if (s1 && s2) { + if (s1 && s2) { #if defined(_WIN32) - return _stricmp(s1, s2); + return _stricmp(s1, s2); #else - return strcasecmp(s1, s2); + return strcasecmp(s1, s2); #endif - } else { - if (s1 < s2) { - return -1; /* s1 is null, s2 is not */ - } else if (s1 == s2) { - return 0; /* both are null */ - } else { - return 1; /* s2 is nul s1 is not */ - } - } + } else { + if (s1 < s2) { + return -1; /* s1 is null, s2 is not */ + } else if (s1 == s2) { + return 0; /* both are null */ + } else { + return 1; /* s2 is nul s1 is not */ + } + } } diff --git a/native/cocos/editor-support/spine/Json.h b/native/cocos/editor-support/spine/Json.h index 3b023596cc..478d84b43b 100644 --- a/native/cocos/editor-support/spine/Json.h +++ b/native/cocos/editor-support/spine/Json.h @@ -33,83 +33,81 @@ #include #ifndef SPINE_JSON_HAVE_PREV -/* spine doesn't use the "prev" link in the Json sibling lists. */ -#define SPINE_JSON_HAVE_PREV 0 + /* spine doesn't use the "prev" link in the Json sibling lists. */ + #define SPINE_JSON_HAVE_PREV 0 #endif namespace spine { class SP_API Json { - friend class SkeletonJson; + friend class SkeletonJson; public: - /* Json Types: */ - static const int JSON_FALSE; - static const int JSON_TRUE; - static const int JSON_NULL; - static const int JSON_NUMBER; - static const int JSON_STRING; - static const int JSON_ARRAY; - static const int JSON_OBJECT; + /* Json Types: */ + static const int JSON_FALSE; + static const int JSON_TRUE; + static const int JSON_NULL; + static const int JSON_NUMBER; + static const int JSON_STRING; + static const int JSON_ARRAY; + static const int JSON_OBJECT; - /* Get item "string" from object. Case insensitive. */ - static Json *getItem(Json *object, const char *string); + /* Get item "string" from object. Case insensitive. */ + static Json *getItem(Json *object, const char *string); - static const char *getString(Json *object, const char *name, const char *defaultValue); + static const char *getString(Json *object, const char *name, const char *defaultValue); - static float getFloat(Json *object, const char *name, float defaultValue); + static float getFloat(Json *object, const char *name, float defaultValue); - static int getInt(Json *object, const char *name, int defaultValue); + static int getInt(Json *object, const char *name, int defaultValue); - static bool getBoolean(Json *object, const char *name, bool defaultValue); + static bool getBoolean(Json *object, const char *name, bool defaultValue); - /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when Json_create() returns 0. 0 when Json_create() succeeds. */ - static const char *getError(); - - /* Supply a block of JSON, and this returns a Json object you can interrogate. Call Json_dispose when finished. */ - explicit Json(const char *value); - - ~Json(); + /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when Json_create() returns 0. 0 when Json_create() succeeds. */ + static const char *getError(); + /* Supply a block of JSON, and this returns a Json object you can interrogate. Call Json_dispose when finished. */ + explicit Json(const char *value); + ~Json(); private: - static const char *_error; + static const char *_error; - Json *_next; + Json *_next; #if SPINE_JSON_HAVE_PREV - Json* _prev; /* next/prev allow you to walk array/object chains. Alternatively, use getSize/getItem */ + Json *_prev; /* next/prev allow you to walk array/object chains. Alternatively, use getSize/getItem */ #endif - Json *_child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + Json *_child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - int _type; /* The type of the item, as above. */ - int _size; /* The number of children. */ + int _type; /* The type of the item, as above. */ + int _size; /* The number of children. */ - const char *_valueString; /* The item's string, if type==JSON_STRING */ - int _valueInt; /* The item's number, if type==JSON_NUMBER */ - float _valueFloat; /* The item's number, if type==JSON_NUMBER */ + const char *_valueString; /* The item's string, if type==JSON_STRING */ + int _valueInt; /* The item's number, if type==JSON_NUMBER */ + float _valueFloat; /* The item's number, if type==JSON_NUMBER */ - const char *_name; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + const char *_name; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ - /* Utility to jump whitespace and cr/lf */ - static const char *skip(const char *inValue); + /* Utility to jump whitespace and cr/lf */ + static const char *skip(const char *inValue); - /* Parser core - when encountering text, process appropriately. */ - static const char *parseValue(Json *item, const char *value); + /* Parser core - when encountering text, process appropriately. */ + static const char *parseValue(Json *item, const char *value); - /* Parse the input text into an unescaped cstring, and populate item. */ - static const char *parseString(Json *item, const char *str); + /* Parse the input text into an unescaped cstring, and populate item. */ + static const char *parseString(Json *item, const char *str); - /* Parse the input text to generate a number, and populate the result into item. */ - static const char *parseNumber(Json *item, const char *num); + /* Parse the input text to generate a number, and populate the result into item. */ + static const char *parseNumber(Json *item, const char *num); - /* Build an array from input text. */ - static const char *parseArray(Json *item, const char *value); + /* Build an array from input text. */ + static const char *parseArray(Json *item, const char *value); - /* Build an object from the text. */ - static const char *parseObject(Json *item, const char *value); + /* Build an object from the text. */ + static const char *parseObject(Json *item, const char *value); - static int json_strcasecmp(const char *s1, const char *s2); + static int json_strcasecmp(const char *s1, const char *s2); }; -} +} // namespace spine #endif /* Spine_Json_h */ diff --git a/native/cocos/editor-support/spine/LinkedMesh.cpp b/native/cocos/editor-support/spine/LinkedMesh.cpp index cfc082a148..861a102a5a 100644 --- a/native/cocos/editor-support/spine/LinkedMesh.cpp +++ b/native/cocos/editor-support/spine/LinkedMesh.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,10 +37,9 @@ using namespace spine; -LinkedMesh::LinkedMesh(MeshAttachment *mesh, const String &skin, size_t slotIndex, const String &parent, bool inheritDeform) : - _mesh(mesh), - _skin(skin), - _slotIndex(slotIndex), - _parent(parent), - _inheritDeform(inheritDeform) { +LinkedMesh::LinkedMesh(MeshAttachment *mesh, const String &skin, size_t slotIndex, const String &parent, bool inheritDeform) : _mesh(mesh), + _skin(skin), + _slotIndex(slotIndex), + _parent(parent), + _inheritDeform(inheritDeform) { } diff --git a/native/cocos/editor-support/spine/LinkedMesh.h b/native/cocos/editor-support/spine/LinkedMesh.h index 10e7003aa8..accd83a66a 100644 --- a/native/cocos/editor-support/spine/LinkedMesh.h +++ b/native/cocos/editor-support/spine/LinkedMesh.h @@ -37,20 +37,20 @@ namespace spine { class MeshAttachment; class SP_API LinkedMesh : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; public: - LinkedMesh(MeshAttachment *mesh, const String &skin, size_t slotIndex, const String &parent, bool inheritDeform); + LinkedMesh(MeshAttachment *mesh, const String &skin, size_t slotIndex, const String &parent, bool inheritDeform); private: - MeshAttachment *_mesh; - String _skin; - size_t _slotIndex; - String _parent; - bool _inheritDeform; + MeshAttachment *_mesh; + String _skin; + size_t _slotIndex; + String _parent; + bool _inheritDeform; }; -} +} // namespace spine #endif /* Spine_LinkedMesh_h */ diff --git a/native/cocos/editor-support/spine/MathUtil.cpp b/native/cocos/editor-support/spine/MathUtil.cpp index 4601f7179d..a5c38fe984 100644 --- a/native/cocos/editor-support/spine/MathUtil.cpp +++ b/native/cocos/editor-support/spine/MathUtil.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,7 +37,7 @@ // Required for division by 0 in _isNaN on MSVC #ifdef _MSC_VER -#pragma warning(disable:4723) + #pragma warning(disable : 4723) #endif using namespace spine; @@ -48,80 +48,80 @@ const float MathUtil::Deg_Rad = (3.1415926535897932385f / 180.0f); const float MathUtil::Rad_Deg = (180.0f / 3.1415926535897932385f); float MathUtil::abs(float v) { - return ((v) < 0 ? -(v) : (v)); + return ((v) < 0 ? -(v) : (v)); } float MathUtil::sign(float v) { - return ((v) < 0 ? -1.0f : (v) > 0 ? 1.0f : 0.0f); + return ((v) < 0 ? -1.0f : (v) > 0 ? 1.0f : 0.0f); } float MathUtil::clamp(float x, float min, float max) { - return ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x))); + return ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x))); } float MathUtil::fmod(float a, float b) { - return (float)::fmod(a, b); + return (float)::fmod(a, b); } /// Returns atan2 in radians, faster but less accurate than Math.Atan2. Average error of 0.00231 radians (0.1323 /// degrees), largest error of 0.00488 radians (0.2796 degrees). float MathUtil::atan2(float y, float x) { - return (float)::atan2(y, x); + return (float)::atan2(y, x); } /// Returns the cosine in radians from a lookup table. float MathUtil::cos(float radians) { - return (float)::cos(radians); + return (float)::cos(radians); } /// Returns the sine in radians from a lookup table. float MathUtil::sin(float radians) { - return (float)::sin(radians); + return (float)::sin(radians); } float MathUtil::sqrt(float v) { - return (float)::sqrt(v); + return (float)::sqrt(v); } float MathUtil::acos(float v) { - return (float)::acos(v); + return (float)::acos(v); } /// Returns the sine in radians from a lookup table. float MathUtil::sinDeg(float degrees) { - return (float)::sin(degrees * MathUtil::Deg_Rad); + return (float)::sin(degrees * MathUtil::Deg_Rad); } /// Returns the cosine in radians from a lookup table. float MathUtil::cosDeg(float degrees) { - return (float)::cos(degrees * MathUtil::Deg_Rad); + return (float)::cos(degrees * MathUtil::Deg_Rad); } /* Need to pass 0 as an argument, so VC++ doesn't error with C2124 */ static bool _isNan(float value, float zero) { - float _nan = (float) 0.0 / zero; - return 0 == memcmp((void *) &value, (void *) &_nan, sizeof(value)); + float _nan = (float)0.0 / zero; + return 0 == memcmp((void *)&value, (void *)&_nan, sizeof(value)); } bool MathUtil::isNan(float v) { - return _isNan(v, 0); + return _isNan(v, 0); } float MathUtil::random() { - return ::rand() / (float)RAND_MAX; + return ::rand() / (float)RAND_MAX; } float MathUtil::randomTriangular(float min, float max) { - return randomTriangular(min, max, (min + max) * 0.5f); + return randomTriangular(min, max, (min + max) * 0.5f); } float MathUtil::randomTriangular(float min, float max, float mode) { - float u = random(); - float d = max - min; - if (u <= (mode - min) / d) return min + sqrt(u * d * (mode - min)); - return max - sqrt((1 - u) * d * (max - mode)); + float u = random(); + float d = max - min; + if (u <= (mode - min) / d) return min + sqrt(u * d * (mode - min)); + return max - sqrt((1 - u) * d * (max - mode)); } float MathUtil::pow(float a, float b) { - return (float)::pow(a, b); + return (float)::pow(a, b); } diff --git a/native/cocos/editor-support/spine/MathUtil.h b/native/cocos/editor-support/spine/MathUtil.h index 7d85c7d1c0..1041eb6ebc 100644 --- a/native/cocos/editor-support/spine/MathUtil.h +++ b/native/cocos/editor-support/spine/MathUtil.h @@ -38,92 +38,92 @@ namespace spine { class SP_API MathUtil : public SpineObject { private: - MathUtil(); + MathUtil(); public: - static const float Pi; - static const float Pi_2; - static const float Deg_Rad; - static const float Rad_Deg; + static const float Pi; + static const float Pi_2; + static const float Deg_Rad; + static const float Rad_Deg; - template - static inline T min(T a, T b) { return a < b ? a : b; } + template + static inline T min(T a, T b) { return a < b ? a : b; } - template - static inline T max(T a, T b) { return a > b ? a : b; } + template + static inline T max(T a, T b) { return a > b ? a : b; } - static float sign(float val); + static float sign(float val); - static float clamp(float x, float lower, float upper); + static float clamp(float x, float lower, float upper); - static float abs(float v); + static float abs(float v); - /// Returns the sine in radians from a lookup table. - static float sin(float radians); + /// Returns the sine in radians from a lookup table. + static float sin(float radians); - /// Returns the cosine in radians from a lookup table. - static float cos(float radians); + /// Returns the cosine in radians from a lookup table. + static float cos(float radians); - /// Returns the sine in radians from a lookup table. - static float sinDeg(float degrees); + /// Returns the sine in radians from a lookup table. + static float sinDeg(float degrees); - /// Returns the cosine in radians from a lookup table. - static float cosDeg(float degrees); + /// Returns the cosine in radians from a lookup table. + static float cosDeg(float degrees); - /// Returns atan2 in radians, faster but less accurate than Math.Atan2. Average error of 0.00231 radians (0.1323 - /// degrees), largest error of 0.00488 radians (0.2796 degrees). - static float atan2(float y, float x); + /// Returns atan2 in radians, faster but less accurate than Math.Atan2. Average error of 0.00231 radians (0.1323 + /// degrees), largest error of 0.00488 radians (0.2796 degrees). + static float atan2(float y, float x); - static float acos(float v); + static float acos(float v); - static float sqrt(float v); + static float sqrt(float v); - static float fmod(float a, float b); + static float fmod(float a, float b); - static bool isNan(float v); + static bool isNan(float v); - static float random(); + static float random(); - static float randomTriangular(float min, float max); + static float randomTriangular(float min, float max); - static float randomTriangular(float min, float max, float mode); + static float randomTriangular(float min, float max, float mode); - static float pow(float a, float b); + static float pow(float a, float b); }; struct SP_API Interpolation { - virtual float apply(float a) = 0; + virtual float apply(float a) = 0; - virtual float interpolate(float start, float end, float a) { - return start + (end - start) * apply(a); - } + virtual float interpolate(float start, float end, float a) { + return start + (end - start) * apply(a); + } - virtual ~Interpolation() {}; + virtual ~Interpolation(){}; }; -struct SP_API PowInterpolation: public Interpolation { - PowInterpolation(int power): power(power) { - } +struct SP_API PowInterpolation : public Interpolation { + PowInterpolation(int power) : power(power) { + } - float apply(float a) { - if (a <= 0.5f) return MathUtil::pow(a * 2.0f, (float)power) / 2.0f; - return MathUtil::pow((a - 1.0f) * 2.0f, (float)power) / (power % 2 == 0 ? -2.0f : 2.0f) + 1.0f; - } + float apply(float a) { + if (a <= 0.5f) return MathUtil::pow(a * 2.0f, (float)power) / 2.0f; + return MathUtil::pow((a - 1.0f) * 2.0f, (float)power) / (power % 2 == 0 ? -2.0f : 2.0f) + 1.0f; + } - int power; + int power; }; -struct SP_API PowOutInterpolation: public Interpolation { - PowOutInterpolation(int power): power(power) { - } +struct SP_API PowOutInterpolation : public Interpolation { + PowOutInterpolation(int power) : power(power) { + } - float apply(float a) { - return MathUtil::pow(a - 1, (float)power) * (power % 2 == 0 ? -1.0f : 1.0f) + 1.0f; - } + float apply(float a) { + return MathUtil::pow(a - 1, (float)power) * (power % 2 == 0 ? -1.0f : 1.0f) + 1.0f; + } - int power; + int power; }; -} +} // namespace spine #endif /* Spine_MathUtil_h */ diff --git a/native/cocos/editor-support/spine/MeshAttachment.cpp b/native/cocos/editor-support/spine/MeshAttachment.cpp index 4bb4338abb..7a45711d84 100644 --- a/native/cocos/editor-support/spine/MeshAttachment.cpp +++ b/native/cocos/editor-support/spine/MeshAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -38,312 +38,293 @@ using namespace spine; RTTI_IMPL(MeshAttachment, VertexAttachment) -MeshAttachment::MeshAttachment(const String &name) : VertexAttachment(name), HasRendererObject(), - _regionOffsetX(0), - _regionOffsetY(0), - _regionWidth(0), - _regionHeight(0), - _regionOriginalWidth(0), - _regionOriginalHeight(0), - _parentMesh(NULL), - _path(), - _regionU(0), - _regionV(0), - _regionU2(0), - _regionV2(0), - _width(0), - _height(0), - _color(1, 1, 1, 1), - _hullLength(0), - _regionRotate(false), - _regionDegrees(0) -{} +MeshAttachment::MeshAttachment(const String &name) : VertexAttachment(name), HasRendererObject(), _regionOffsetX(0), _regionOffsetY(0), _regionWidth(0), _regionHeight(0), _regionOriginalWidth(0), _regionOriginalHeight(0), _parentMesh(NULL), _path(), _regionU(0), _regionV(0), _regionU2(0), _regionV2(0), _width(0), _height(0), _color(1, 1, 1, 1), _hullLength(0), _regionRotate(false), _regionDegrees(0) {} MeshAttachment::~MeshAttachment() {} void MeshAttachment::updateUVs() { - if (_uvs.size() != _regionUVs.size()) { - _uvs.setSize(_regionUVs.size(), 0); - } + if (_uvs.size() != _regionUVs.size()) { + _uvs.setSize(_regionUVs.size(), 0); + } - int i = 0, n = _regionUVs.size(); - float u = _regionU, v = _regionV; - float width = 0, height = 0; + int i = 0, n = _regionUVs.size(); + float u = _regionU, v = _regionV; + float width = 0, height = 0; - switch (_regionDegrees) { - case 90: { - float textureWidth = _regionHeight / (_regionU2 - _regionU); - float textureHeight = _regionWidth / (_regionV2 - _regionV); - u -= (_regionOriginalHeight - _regionOffsetY - _regionHeight) / textureWidth; - v -= (_regionOriginalWidth - _regionOffsetX - _regionWidth) / textureHeight; - width = _regionOriginalHeight / textureWidth; - height = _regionOriginalWidth / textureHeight; - for (i = 0; i < n; i += 2) { - _uvs[i] = u + _regionUVs[i + 1] * width; - _uvs[i + 1] = v + (1 - _regionUVs[i]) * height; - } - return; - } - case 180: { - float textureWidth = _regionWidth / (_regionU2 - _regionU); - float textureHeight = _regionHeight / (_regionV2 - _regionV); - u -= (_regionOriginalWidth - _regionOffsetX - _regionWidth) / textureWidth; - v -= _regionOffsetY / textureHeight; - width = _regionOriginalWidth / textureWidth; - height = _regionOriginalHeight / textureHeight; - for (i = 0; i < n; i += 2) { - _uvs[i] = u + (1 - _regionUVs[i]) * width; - _uvs[i + 1] = v + (1 - _regionUVs[i + 1]) * height; - } - return; - } - case 270: { - float textureHeight = _regionHeight / (_regionV2 - _regionV); - float textureWidth = _regionWidth / (_regionU2 - _regionU); - u -= _regionOffsetY / textureWidth; - v -= _regionOffsetX / textureHeight; - width = _regionOriginalHeight / textureWidth; - height = _regionOriginalWidth / textureHeight; - for (i = 0; i < n; i += 2) { - _uvs[i] = u + (1 - _regionUVs[i + 1]) * width; - _uvs[i + 1] = v + _regionUVs[i] * height; - } - return; - } - default: { - float textureWidth = _regionWidth / (_regionU2 - _regionU); - float textureHeight = _regionHeight / (_regionV2 - _regionV); - u -= _regionOffsetX / textureWidth; - v -= (_regionOriginalHeight - _regionOffsetY - _regionHeight) / textureHeight; - width = _regionOriginalWidth / textureWidth; - height = _regionOriginalHeight / textureHeight; - for (i = 0; i < n; i += 2) { - _uvs[i] = u + _regionUVs[i] * width; - _uvs[i + 1] = v + _regionUVs[i + 1] * height; - } - } - } + switch (_regionDegrees) { + case 90: { + float textureWidth = _regionHeight / (_regionU2 - _regionU); + float textureHeight = _regionWidth / (_regionV2 - _regionV); + u -= (_regionOriginalHeight - _regionOffsetY - _regionHeight) / textureWidth; + v -= (_regionOriginalWidth - _regionOffsetX - _regionWidth) / textureHeight; + width = _regionOriginalHeight / textureWidth; + height = _regionOriginalWidth / textureHeight; + for (i = 0; i < n; i += 2) { + _uvs[i] = u + _regionUVs[i + 1] * width; + _uvs[i + 1] = v + (1 - _regionUVs[i]) * height; + } + return; + } + case 180: { + float textureWidth = _regionWidth / (_regionU2 - _regionU); + float textureHeight = _regionHeight / (_regionV2 - _regionV); + u -= (_regionOriginalWidth - _regionOffsetX - _regionWidth) / textureWidth; + v -= _regionOffsetY / textureHeight; + width = _regionOriginalWidth / textureWidth; + height = _regionOriginalHeight / textureHeight; + for (i = 0; i < n; i += 2) { + _uvs[i] = u + (1 - _regionUVs[i]) * width; + _uvs[i + 1] = v + (1 - _regionUVs[i + 1]) * height; + } + return; + } + case 270: { + float textureHeight = _regionHeight / (_regionV2 - _regionV); + float textureWidth = _regionWidth / (_regionU2 - _regionU); + u -= _regionOffsetY / textureWidth; + v -= _regionOffsetX / textureHeight; + width = _regionOriginalHeight / textureWidth; + height = _regionOriginalWidth / textureHeight; + for (i = 0; i < n; i += 2) { + _uvs[i] = u + (1 - _regionUVs[i + 1]) * width; + _uvs[i + 1] = v + _regionUVs[i] * height; + } + return; + } + default: { + float textureWidth = _regionWidth / (_regionU2 - _regionU); + float textureHeight = _regionHeight / (_regionV2 - _regionV); + u -= _regionOffsetX / textureWidth; + v -= (_regionOriginalHeight - _regionOffsetY - _regionHeight) / textureHeight; + width = _regionOriginalWidth / textureWidth; + height = _regionOriginalHeight / textureHeight; + for (i = 0; i < n; i += 2) { + _uvs[i] = u + _regionUVs[i] * width; + _uvs[i + 1] = v + _regionUVs[i + 1] * height; + } + } + } } int MeshAttachment::getHullLength() { - return _hullLength; + return _hullLength; } void MeshAttachment::setHullLength(int inValue) { - _hullLength = inValue; + _hullLength = inValue; } Vector &MeshAttachment::getRegionUVs() { - return _regionUVs; + return _regionUVs; } Vector &MeshAttachment::getUVs() { - return _uvs; + return _uvs; } Vector &MeshAttachment::getTriangles() { - return _triangles; + return _triangles; } const String &MeshAttachment::getPath() { - return _path; + return _path; } void MeshAttachment::setPath(const String &inValue) { - _path = inValue; + _path = inValue; } float MeshAttachment::getRegionU() { - return _regionU; + return _regionU; } void MeshAttachment::setRegionU(float inValue) { - _regionU = inValue; + _regionU = inValue; } float MeshAttachment::getRegionV() { - return _regionV; + return _regionV; } void MeshAttachment::setRegionV(float inValue) { - _regionV = inValue; + _regionV = inValue; } float MeshAttachment::getRegionU2() { - return _regionU2; + return _regionU2; } void MeshAttachment::setRegionU2(float inValue) { - _regionU2 = inValue; + _regionU2 = inValue; } float MeshAttachment::getRegionV2() { - return _regionV2; + return _regionV2; } void MeshAttachment::setRegionV2(float inValue) { - _regionV2 = inValue; + _regionV2 = inValue; } bool MeshAttachment::getRegionRotate() { - return _regionRotate; + return _regionRotate; } void MeshAttachment::setRegionRotate(bool inValue) { - _regionRotate = inValue; + _regionRotate = inValue; } int MeshAttachment::getRegionDegrees() { - return _regionDegrees; + return _regionDegrees; } void MeshAttachment::setRegionDegrees(int inValue) { - _regionDegrees = inValue; + _regionDegrees = inValue; } float MeshAttachment::getRegionOffsetX() { - return _regionOffsetX; + return _regionOffsetX; } void MeshAttachment::setRegionOffsetX(float inValue) { - _regionOffsetX = inValue; + _regionOffsetX = inValue; } float MeshAttachment::getRegionOffsetY() { - return _regionOffsetY; + return _regionOffsetY; } void MeshAttachment::setRegionOffsetY(float inValue) { - _regionOffsetY = inValue; + _regionOffsetY = inValue; } float MeshAttachment::getRegionWidth() { - return _regionWidth; + return _regionWidth; } void MeshAttachment::setRegionWidth(float inValue) { - _regionWidth = inValue; + _regionWidth = inValue; } float MeshAttachment::getRegionHeight() { - return _regionHeight; + return _regionHeight; } void MeshAttachment::setRegionHeight(float inValue) { - _regionHeight = inValue; + _regionHeight = inValue; } float MeshAttachment::getRegionOriginalWidth() { - return _regionOriginalWidth; + return _regionOriginalWidth; } void MeshAttachment::setRegionOriginalWidth(float inValue) { - _regionOriginalWidth = inValue; + _regionOriginalWidth = inValue; } float MeshAttachment::getRegionOriginalHeight() { - return _regionOriginalHeight; + return _regionOriginalHeight; } void MeshAttachment::setRegionOriginalHeight(float inValue) { - _regionOriginalHeight = inValue; + _regionOriginalHeight = inValue; } MeshAttachment *MeshAttachment::getParentMesh() { - return _parentMesh; + return _parentMesh; } void MeshAttachment::setParentMesh(MeshAttachment *inValue) { - _parentMesh = inValue; - if (inValue != NULL) { - _bones.clearAndAddAll(inValue->_bones); - _vertices.clearAndAddAll(inValue->_vertices); - _worldVerticesLength = inValue->_worldVerticesLength; - _regionUVs.clearAndAddAll(inValue->_regionUVs); - _triangles.clearAndAddAll(inValue->_triangles); - _hullLength = inValue->_hullLength; - _edges.clearAndAddAll(inValue->_edges); - _width = inValue->_width; - _height = inValue->_height; - } + _parentMesh = inValue; + if (inValue != NULL) { + _bones.clearAndAddAll(inValue->_bones); + _vertices.clearAndAddAll(inValue->_vertices); + _worldVerticesLength = inValue->_worldVerticesLength; + _regionUVs.clearAndAddAll(inValue->_regionUVs); + _triangles.clearAndAddAll(inValue->_triangles); + _hullLength = inValue->_hullLength; + _edges.clearAndAddAll(inValue->_edges); + _width = inValue->_width; + _height = inValue->_height; + } } Vector &MeshAttachment::getEdges() { - return _edges; + return _edges; } float MeshAttachment::getWidth() { - return _width; + return _width; } void MeshAttachment::setWidth(float inValue) { - _width = inValue; + _width = inValue; } float MeshAttachment::getHeight() { - return _height; + return _height; } void MeshAttachment::setHeight(float inValue) { - _height = inValue; + _height = inValue; } spine::Color &MeshAttachment::getColor() { - return _color; + return _color; } -Attachment* MeshAttachment::copy() { - if (_parentMesh) return newLinkedMesh(); +Attachment *MeshAttachment::copy() { + if (_parentMesh) return newLinkedMesh(); - MeshAttachment* copy = new (__FILE__, __LINE__) MeshAttachment(getName()); - copy->setRendererObject(getRendererObject()); - copy->_regionU = _regionU; - copy->_regionV = _regionV; - copy->_regionU2 = _regionU2; - copy->_regionV2 = _regionV2; - copy->_regionRotate = _regionRotate; - copy->_regionDegrees = _regionDegrees; - copy->_regionOffsetX = _regionOffsetX; - copy->_regionOffsetY = _regionOffsetY; - copy->_regionWidth = _regionWidth; - copy->_regionHeight = _regionHeight; - copy->_regionOriginalWidth = _regionOriginalWidth; - copy->_regionOriginalHeight = _regionOriginalHeight; - copy->_path = _path; - copy->_color.set(_color); + MeshAttachment *copy = new (__FILE__, __LINE__) MeshAttachment(getName()); + copy->setRendererObject(getRendererObject()); + copy->_regionU = _regionU; + copy->_regionV = _regionV; + copy->_regionU2 = _regionU2; + copy->_regionV2 = _regionV2; + copy->_regionRotate = _regionRotate; + copy->_regionDegrees = _regionDegrees; + copy->_regionOffsetX = _regionOffsetX; + copy->_regionOffsetY = _regionOffsetY; + copy->_regionWidth = _regionWidth; + copy->_regionHeight = _regionHeight; + copy->_regionOriginalWidth = _regionOriginalWidth; + copy->_regionOriginalHeight = _regionOriginalHeight; + copy->_path = _path; + copy->_color.set(_color); - copyTo(copy); - copy->_regionUVs.clearAndAddAll(_regionUVs); - copy->_uvs.clearAndAddAll(_uvs); - copy->_triangles.clearAndAddAll(_triangles); - copy->_hullLength = _hullLength; + copyTo(copy); + copy->_regionUVs.clearAndAddAll(_regionUVs); + copy->_uvs.clearAndAddAll(_uvs); + copy->_triangles.clearAndAddAll(_triangles); + copy->_hullLength = _hullLength; - // Nonessential. - copy->_edges.clearAndAddAll(copy->_edges); - copy->_width = _width; - copy->_height = _height; - return copy; + // Nonessential. + copy->_edges.clearAndAddAll(copy->_edges); + copy->_width = _width; + copy->_height = _height; + return copy; } -MeshAttachment* MeshAttachment::newLinkedMesh() { - MeshAttachment* copy = new (__FILE__, __LINE__) MeshAttachment(getName()); - copy->setRendererObject(getRendererObject()); - copy->_regionU = _regionU; - copy->_regionV = _regionV; - copy->_regionU2 = _regionU2; - copy->_regionV2 = _regionV2; - copy->_regionRotate = _regionRotate; - copy->_regionDegrees = _regionDegrees; - copy->_regionOffsetX = _regionOffsetX; - copy->_regionOffsetY = _regionOffsetY; - copy->_regionWidth = _regionWidth; - copy->_regionHeight = _regionHeight; - copy->_regionOriginalWidth = _regionOriginalWidth; - copy->_regionOriginalHeight = _regionOriginalHeight; - copy->_path = _path; - copy->_color.set(_color); - copy->_deformAttachment = this->_deformAttachment; - copy->setParentMesh(_parentMesh ? _parentMesh : this); - copy->updateUVs(); - return copy; +MeshAttachment *MeshAttachment::newLinkedMesh() { + MeshAttachment *copy = new (__FILE__, __LINE__) MeshAttachment(getName()); + copy->setRendererObject(getRendererObject()); + copy->_regionU = _regionU; + copy->_regionV = _regionV; + copy->_regionU2 = _regionU2; + copy->_regionV2 = _regionV2; + copy->_regionRotate = _regionRotate; + copy->_regionDegrees = _regionDegrees; + copy->_regionOffsetX = _regionOffsetX; + copy->_regionOffsetY = _regionOffsetY; + copy->_regionWidth = _regionWidth; + copy->_regionHeight = _regionHeight; + copy->_regionOriginalWidth = _regionOriginalWidth; + copy->_regionOriginalHeight = _regionOriginalHeight; + copy->_path = _path; + copy->_color.set(_color); + copy->_deformAttachment = this->_deformAttachment; + copy->setParentMesh(_parentMesh ? _parentMesh : this); + copy->updateUVs(); + return copy; } diff --git a/native/cocos/editor-support/spine/MeshAttachment.h b/native/cocos/editor-support/spine/MeshAttachment.h index dece05f94d..27be1e3b06 100644 --- a/native/cocos/editor-support/spine/MeshAttachment.h +++ b/native/cocos/editor-support/spine/MeshAttachment.h @@ -36,108 +36,108 @@ #include namespace spine { - /// Attachment that displays a texture region using a mesh. - class SP_API MeshAttachment : public VertexAttachment, public HasRendererObject { - friend class SkeletonBinary; - friend class SkeletonJson; - friend class AtlasAttachmentLoader; +/// Attachment that displays a texture region using a mesh. +class SP_API MeshAttachment : public VertexAttachment, public HasRendererObject { + friend class SkeletonBinary; + friend class SkeletonJson; + friend class AtlasAttachmentLoader; - RTTI_DECL + RTTI_DECL - public: - explicit MeshAttachment(const String& name); +public: + explicit MeshAttachment(const String& name); - virtual ~MeshAttachment(); + virtual ~MeshAttachment(); - void updateUVs(); + void updateUVs(); - int getHullLength(); - void setHullLength(int inValue); + int getHullLength(); + void setHullLength(int inValue); - Vector& getRegionUVs(); + Vector& getRegionUVs(); - /// The UV pair for each vertex, normalized within the entire texture. See also MeshAttachment::updateUVs - Vector& getUVs(); + /// The UV pair for each vertex, normalized within the entire texture. See also MeshAttachment::updateUVs + Vector& getUVs(); - Vector& getTriangles(); + Vector& getTriangles(); - Color& getColor(); + Color& getColor(); - const String& getPath(); - void setPath(const String& inValue); + const String& getPath(); + void setPath(const String& inValue); - float getRegionU(); - void setRegionU(float inValue); + float getRegionU(); + void setRegionU(float inValue); - float getRegionV(); - void setRegionV(float inValue); + float getRegionV(); + void setRegionV(float inValue); - float getRegionU2(); - void setRegionU2(float inValue); + float getRegionU2(); + void setRegionU2(float inValue); - float getRegionV2(); - void setRegionV2(float inValue); + float getRegionV2(); + void setRegionV2(float inValue); - bool getRegionRotate(); - void setRegionRotate(bool inValue); + bool getRegionRotate(); + void setRegionRotate(bool inValue); - int getRegionDegrees(); - void setRegionDegrees(int inValue); + int getRegionDegrees(); + void setRegionDegrees(int inValue); - float getRegionOffsetX(); - void setRegionOffsetX(float inValue); + float getRegionOffsetX(); + void setRegionOffsetX(float inValue); - // Pixels stripped from the bottom left, unrotated. - float getRegionOffsetY(); - void setRegionOffsetY(float inValue); + // Pixels stripped from the bottom left, unrotated. + float getRegionOffsetY(); + void setRegionOffsetY(float inValue); - float getRegionWidth(); - void setRegionWidth(float inValue); + float getRegionWidth(); + void setRegionWidth(float inValue); - // Unrotated, stripped size. - float getRegionHeight(); - void setRegionHeight(float inValue); + // Unrotated, stripped size. + float getRegionHeight(); + void setRegionHeight(float inValue); - float getRegionOriginalWidth(); - void setRegionOriginalWidth(float inValue); + float getRegionOriginalWidth(); + void setRegionOriginalWidth(float inValue); - // Unrotated, unstripped size. - float getRegionOriginalHeight(); - void setRegionOriginalHeight(float inValue); + // Unrotated, unstripped size. + float getRegionOriginalHeight(); + void setRegionOriginalHeight(float inValue); - MeshAttachment* getParentMesh(); - void setParentMesh(MeshAttachment* inValue); + MeshAttachment* getParentMesh(); + void setParentMesh(MeshAttachment* inValue); - // Nonessential. - Vector& getEdges(); - float getWidth(); - void setWidth(float inValue); - float getHeight(); - void setHeight(float inValue); + // Nonessential. + Vector& getEdges(); + float getWidth(); + void setWidth(float inValue); + float getHeight(); + void setHeight(float inValue); - virtual Attachment* copy(); + virtual Attachment* copy(); - MeshAttachment* newLinkedMesh(); + MeshAttachment* newLinkedMesh(); - private: - float _regionOffsetX, _regionOffsetY, _regionWidth, _regionHeight, _regionOriginalWidth, _regionOriginalHeight; - MeshAttachment* _parentMesh; - Vector _uvs; - Vector _regionUVs; - Vector _triangles; - Vector _edges; - String _path; - float _regionU; - float _regionV; - float _regionU2; - float _regionV2; - float _width; - float _height; - Color _color; - int _hullLength; - bool _regionRotate; - int _regionDegrees; - }; -} +private: + float _regionOffsetX, _regionOffsetY, _regionWidth, _regionHeight, _regionOriginalWidth, _regionOriginalHeight; + MeshAttachment* _parentMesh; + Vector _uvs; + Vector _regionUVs; + Vector _triangles; + Vector _edges; + String _path; + float _regionU; + float _regionV; + float _regionU2; + float _regionV2; + float _width; + float _height; + Color _color; + int _hullLength; + bool _regionRotate; + int _regionDegrees; +}; +} // namespace spine #endif /* Spine_MeshAttachment_h */ diff --git a/native/cocos/editor-support/spine/MixBlend.h b/native/cocos/editor-support/spine/MixBlend.h index 5e709aefd7..a0824ea31b 100644 --- a/native/cocos/editor-support/spine/MixBlend.h +++ b/native/cocos/editor-support/spine/MixBlend.h @@ -35,11 +35,11 @@ namespace spine { /// Controls how a timeline is mixed with the setup or current pose. /// See also Timeline::apply(Skeleton&, float, float, Vector&, float, Blend, MixDirection) enum MixBlend { - MixBlend_Setup = 0, - MixBlend_First, - MixBlend_Replace, - MixBlend_Add + MixBlend_Setup = 0, + MixBlend_First, + MixBlend_Replace, + MixBlend_Add }; -} +} // namespace spine #endif /* Spine_MixPose_h */ diff --git a/native/cocos/editor-support/spine/MixDirection.h b/native/cocos/editor-support/spine/MixDirection.h index 1a618324df..1f9920b2f7 100644 --- a/native/cocos/editor-support/spine/MixDirection.h +++ b/native/cocos/editor-support/spine/MixDirection.h @@ -35,10 +35,10 @@ namespace spine { /// Indicates whether a timeline's alpha is mixing out over time toward 0 (the setup or current pose) or mixing in toward 1 (the timeline's pose). /// See also Timeline::apply(Skeleton&, float, float, Vector&, float, MixPose, MixDirection) enum MixDirection { - MixDirection_In = 0, - MixDirection_Out + MixDirection_In = 0, + MixDirection_Out }; -} +} // namespace spine #endif /* Spine_MixDirection_h */ diff --git a/native/cocos/editor-support/spine/PathAttachment.cpp b/native/cocos/editor-support/spine/PathAttachment.cpp index ff74a4fb3b..3bdc71945a 100644 --- a/native/cocos/editor-support/spine/PathAttachment.cpp +++ b/native/cocos/editor-support/spine/PathAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,34 +37,34 @@ using namespace spine; RTTI_IMPL(PathAttachment, VertexAttachment) -PathAttachment::PathAttachment(const String &name) : VertexAttachment(name), _closed(false), _constantSpeed(false) { +PathAttachment::PathAttachment(const String& name) : VertexAttachment(name), _closed(false), _constantSpeed(false) { } -Vector &PathAttachment::getLengths() { - return _lengths; +Vector& PathAttachment::getLengths() { + return _lengths; } bool PathAttachment::isClosed() { - return _closed; + return _closed; } void PathAttachment::setClosed(bool inValue) { - _closed = inValue; + _closed = inValue; } bool PathAttachment::isConstantSpeed() { - return _constantSpeed; + return _constantSpeed; } void PathAttachment::setConstantSpeed(bool inValue) { - _constantSpeed = inValue; + _constantSpeed = inValue; } Attachment* PathAttachment::copy() { - PathAttachment* copy = new (__FILE__, __LINE__) PathAttachment(getName()); - copyTo(copy); - copy->_lengths.clearAndAddAll(_lengths); - copy->_closed = _closed; - copy->_constantSpeed = _constantSpeed; - return copy; + PathAttachment* copy = new (__FILE__, __LINE__) PathAttachment(getName()); + copyTo(copy); + copy->_lengths.clearAndAddAll(_lengths); + copy->_closed = _closed; + copy->_constantSpeed = _constantSpeed; + return copy; } diff --git a/native/cocos/editor-support/spine/PathAttachment.h b/native/cocos/editor-support/spine/PathAttachment.h index fd054b4e0a..0c968aff50 100644 --- a/native/cocos/editor-support/spine/PathAttachment.h +++ b/native/cocos/editor-support/spine/PathAttachment.h @@ -33,28 +33,29 @@ #include namespace spine { - class SP_API PathAttachment : public VertexAttachment { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API PathAttachment : public VertexAttachment { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit PathAttachment(const String& name); +public: + explicit PathAttachment(const String& name); - /// The length in the setup pose from the start of the path to the end of each curve. - Vector& getLengths(); - bool isClosed(); - void setClosed(bool inValue); - bool isConstantSpeed(); - void setConstantSpeed(bool inValue); + /// The length in the setup pose from the start of the path to the end of each curve. + Vector& getLengths(); + bool isClosed(); + void setClosed(bool inValue); + bool isConstantSpeed(); + void setConstantSpeed(bool inValue); - virtual Attachment* copy(); - private: - Vector _lengths; - bool _closed; - bool _constantSpeed; - }; -} + virtual Attachment* copy(); + +private: + Vector _lengths; + bool _closed; + bool _constantSpeed; +}; +} // namespace spine #endif /* Spine_PathAttachment_h */ diff --git a/native/cocos/editor-support/spine/PathConstraint.cpp b/native/cocos/editor-support/spine/PathConstraint.cpp index b28f80fed1..cab677deac 100644 --- a/native/cocos/editor-support/spine/PathConstraint.cpp +++ b/native/cocos/editor-support/spine/PathConstraint.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -52,498 +52,496 @@ const int PathConstraint::BEFORE = -2; const int PathConstraint::AFTER = -3; PathConstraint::PathConstraint(PathConstraintData &data, Skeleton &skeleton) : Updatable(), - _data(data), - _target(skeleton.findSlot( - data.getTarget()->getName())), - _position(data.getPosition()), - _spacing(data.getSpacing()), - _rotateMix(data.getRotateMix()), - _translateMix(data.getTranslateMix()), - _active(false) -{ - _bones.ensureCapacity(_data.getBones().size()); - for (size_t i = 0; i < _data.getBones().size(); i++) { - BoneData *boneData = _data.getBones()[i]; - _bones.add(skeleton.findBone(boneData->getName())); - } + _data(data), + _target(skeleton.findSlot( + data.getTarget()->getName())), + _position(data.getPosition()), + _spacing(data.getSpacing()), + _rotateMix(data.getRotateMix()), + _translateMix(data.getTranslateMix()), + _active(false) { + _bones.ensureCapacity(_data.getBones().size()); + for (size_t i = 0; i < _data.getBones().size(); i++) { + BoneData *boneData = _data.getBones()[i]; + _bones.add(skeleton.findBone(boneData->getName())); + } - _segments.setSize(10, 0); + _segments.setSize(10, 0); } void PathConstraint::apply() { - update(); + update(); } void PathConstraint::update() { - Attachment *baseAttachment = _target->getAttachment(); - if (baseAttachment == NULL || !baseAttachment->getRTTI().instanceOf(PathAttachment::rtti)) { - return; - } + Attachment *baseAttachment = _target->getAttachment(); + if (baseAttachment == NULL || !baseAttachment->getRTTI().instanceOf(PathAttachment::rtti)) { + return; + } - PathAttachment *attachment = static_cast(baseAttachment); + PathAttachment *attachment = static_cast(baseAttachment); - float rotateMix = _rotateMix; - float translateMix = _translateMix; - bool translate = translateMix > 0; - bool rotate = rotateMix > 0; - if (!translate && !rotate) { - return; - } + float rotateMix = _rotateMix; + float translateMix = _translateMix; + bool translate = translateMix > 0; + bool rotate = rotateMix > 0; + if (!translate && !rotate) { + return; + } - PathConstraintData &data = _data; - bool percentSpacing = data._spacingMode == SpacingMode_Percent; - RotateMode rotateMode = data._rotateMode; - bool tangents = rotateMode == RotateMode_Tangent, scale = rotateMode == RotateMode_ChainScale; - size_t boneCount = _bones.size(); - size_t spacesCount = tangents ? boneCount : boneCount + 1; - _spaces.setSize(spacesCount, 0); - float spacing = _spacing; - if (scale || !percentSpacing) { - if (scale) _lengths.setSize(boneCount, 0); - bool lengthSpacing = data._spacingMode == SpacingMode_Length; + PathConstraintData &data = _data; + bool percentSpacing = data._spacingMode == SpacingMode_Percent; + RotateMode rotateMode = data._rotateMode; + bool tangents = rotateMode == RotateMode_Tangent, scale = rotateMode == RotateMode_ChainScale; + size_t boneCount = _bones.size(); + size_t spacesCount = tangents ? boneCount : boneCount + 1; + _spaces.setSize(spacesCount, 0); + float spacing = _spacing; + if (scale || !percentSpacing) { + if (scale) _lengths.setSize(boneCount, 0); + bool lengthSpacing = data._spacingMode == SpacingMode_Length; - for (size_t i = 0, n = spacesCount - 1; i < n;) { - Bone *boneP = _bones[i]; - Bone &bone = *boneP; - float setupLength = bone._data.getLength(); - if (setupLength < PathConstraint::EPSILON) { - if (scale) _lengths[i] = 0; - _spaces[++i] = 0; - } else if (percentSpacing) { - if (scale) { - float x = setupLength * bone._a, y = setupLength * bone._c; - float length = MathUtil::sqrt(x * x + y * y); - _lengths[i] = length; - } - _spaces[++i] = spacing; - } else { - float x = setupLength * bone._a; - float y = setupLength * bone._c; - float length = MathUtil::sqrt(x * x + y * y); - if (scale) { - _lengths[i] = length; - } + for (size_t i = 0, n = spacesCount - 1; i < n;) { + Bone *boneP = _bones[i]; + Bone &bone = *boneP; + float setupLength = bone._data.getLength(); + if (setupLength < PathConstraint::EPSILON) { + if (scale) _lengths[i] = 0; + _spaces[++i] = 0; + } else if (percentSpacing) { + if (scale) { + float x = setupLength * bone._a, y = setupLength * bone._c; + float length = MathUtil::sqrt(x * x + y * y); + _lengths[i] = length; + } + _spaces[++i] = spacing; + } else { + float x = setupLength * bone._a; + float y = setupLength * bone._c; + float length = MathUtil::sqrt(x * x + y * y); + if (scale) { + _lengths[i] = length; + } - _spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length / setupLength; - } - } - } else { - for (size_t i = 1; i < spacesCount; ++i) { - _spaces[i] = spacing; - } - } + _spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length / setupLength; + } + } + } else { + for (size_t i = 1; i < spacesCount; ++i) { + _spaces[i] = spacing; + } + } - Vector& positions = computeWorldPositions(*attachment, spacesCount, tangents, - data.getPositionMode() == PositionMode_Percent, percentSpacing); - float boneX = positions[0]; - float boneY = positions[1]; - float offsetRotation = data.getOffsetRotation(); - bool tip; - if (offsetRotation == 0) { - tip = rotateMode == RotateMode_Chain; - } else { - tip = false; - Bone &p = _target->getBone(); - offsetRotation *= p.getA() * p.getD() - p.getB() * p.getC() > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; - } + Vector &positions = computeWorldPositions(*attachment, spacesCount, tangents, + data.getPositionMode() == PositionMode_Percent, percentSpacing); + float boneX = positions[0]; + float boneY = positions[1]; + float offsetRotation = data.getOffsetRotation(); + bool tip; + if (offsetRotation == 0) { + tip = rotateMode == RotateMode_Chain; + } else { + tip = false; + Bone &p = _target->getBone(); + offsetRotation *= p.getA() * p.getD() - p.getB() * p.getC() > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; + } - for (size_t i = 0, p = 3; i < boneCount; i++, p += 3) { - Bone *boneP = _bones[i]; - Bone &bone = *boneP; - bone._worldX += (boneX - bone._worldX) * translateMix; - bone._worldY += (boneY - bone._worldY) * translateMix; - float x = positions[p]; - float y = positions[p + 1]; - float dx = x - boneX; - float dy = y - boneY; - if (scale) { - float length = _lengths[i]; - if (length >= PathConstraint::EPSILON) { - float s = (MathUtil::sqrt(dx * dx + dy * dy) / length - 1) * rotateMix + 1; - bone._a *= s; - bone._c *= s; - } - } + for (size_t i = 0, p = 3; i < boneCount; i++, p += 3) { + Bone *boneP = _bones[i]; + Bone &bone = *boneP; + bone._worldX += (boneX - bone._worldX) * translateMix; + bone._worldY += (boneY - bone._worldY) * translateMix; + float x = positions[p]; + float y = positions[p + 1]; + float dx = x - boneX; + float dy = y - boneY; + if (scale) { + float length = _lengths[i]; + if (length >= PathConstraint::EPSILON) { + float s = (MathUtil::sqrt(dx * dx + dy * dy) / length - 1) * rotateMix + 1; + bone._a *= s; + bone._c *= s; + } + } - boneX = x; - boneY = y; + boneX = x; + boneY = y; - if (rotate) { - float a = bone._a, b = bone._b, c = bone._c, d = bone._d, r, cos, sin; - if (tangents) - r = positions[p - 1]; - else if (_spaces[i + 1] < PathConstraint::EPSILON) - r = positions[p + 2]; - else - r = MathUtil::atan2(dy, dx); + if (rotate) { + float a = bone._a, b = bone._b, c = bone._c, d = bone._d, r, cos, sin; + if (tangents) + r = positions[p - 1]; + else if (_spaces[i + 1] < PathConstraint::EPSILON) + r = positions[p + 2]; + else + r = MathUtil::atan2(dy, dx); - r -= MathUtil::atan2(c, a); + r -= MathUtil::atan2(c, a); - if (tip) { - cos = MathUtil::cos(r); - sin = MathUtil::sin(r); - float length = bone._data.getLength(); - boneX += (length * (cos * a - sin * c) - dx) * rotateMix; - boneY += (length * (sin * a + cos * c) - dy) * rotateMix; - } else - r += offsetRotation; + if (tip) { + cos = MathUtil::cos(r); + sin = MathUtil::sin(r); + float length = bone._data.getLength(); + boneX += (length * (cos * a - sin * c) - dx) * rotateMix; + boneY += (length * (sin * a + cos * c) - dy) * rotateMix; + } else + r += offsetRotation; - if (r > MathUtil::Pi) - r -= MathUtil::Pi_2; - else if (r < -MathUtil::Pi) - r += MathUtil::Pi_2; + if (r > MathUtil::Pi) + r -= MathUtil::Pi_2; + else if (r < -MathUtil::Pi) + r += MathUtil::Pi_2; - r *= rotateMix; - cos = MathUtil::cos(r); - sin = MathUtil::sin(r); - bone._a = cos * a - sin * c; - bone._b = cos * b - sin * d; - bone._c = sin * a + cos * c; - bone._d = sin * b + cos * d; - } + r *= rotateMix; + cos = MathUtil::cos(r); + sin = MathUtil::sin(r); + bone._a = cos * a - sin * c; + bone._b = cos * b - sin * d; + bone._c = sin * a + cos * c; + bone._d = sin * b + cos * d; + } - bone._appliedValid = false; - } + bone._appliedValid = false; + } } int PathConstraint::getOrder() { - return _data.getOrder(); + return _data.getOrder(); } float PathConstraint::getPosition() { - return _position; + return _position; } void PathConstraint::setPosition(float inValue) { - _position = inValue; + _position = inValue; } float PathConstraint::getSpacing() { - return _spacing; + return _spacing; } void PathConstraint::setSpacing(float inValue) { - _spacing = inValue; + _spacing = inValue; } float PathConstraint::getRotateMix() { - return _rotateMix; + return _rotateMix; } void PathConstraint::setRotateMix(float inValue) { - _rotateMix = inValue; + _rotateMix = inValue; } float PathConstraint::getTranslateMix() { - return _translateMix; + return _translateMix; } void PathConstraint::setTranslateMix(float inValue) { - _translateMix = inValue; + _translateMix = inValue; } Vector &PathConstraint::getBones() { - return _bones; + return _bones; } Slot *PathConstraint::getTarget() { - return _target; + return _target; } void PathConstraint::setTarget(Slot *inValue) { - _target = inValue; + _target = inValue; } PathConstraintData &PathConstraint::getData() { - return _data; + return _data; } -Vector& +Vector & PathConstraint::computeWorldPositions(PathAttachment &path, int spacesCount, bool tangents, bool percentPosition, bool percentSpacing) { - Slot &target = *_target; - float position = _position; - _positions.setSize(spacesCount * 3 + 2, 0); - Vector &out = _positions; - Vector &world = _world; - bool closed = path.isClosed(); - int verticesLength = path.getWorldVerticesLength(); - int curveCount = verticesLength / 6; - int prevCurve = NONE; + Slot &target = *_target; + float position = _position; + _positions.setSize(spacesCount * 3 + 2, 0); + Vector &out = _positions; + Vector &world = _world; + bool closed = path.isClosed(); + int verticesLength = path.getWorldVerticesLength(); + int curveCount = verticesLength / 6; + int prevCurve = NONE; - float pathLength; - if (!path.isConstantSpeed()) { - Vector &lengths = path.getLengths(); - curveCount -= closed ? 1 : 2; - pathLength = lengths[curveCount]; - if (percentPosition) position *= pathLength; + float pathLength; + if (!path.isConstantSpeed()) { + Vector &lengths = path.getLengths(); + curveCount -= closed ? 1 : 2; + pathLength = lengths[curveCount]; + if (percentPosition) position *= pathLength; - if (percentSpacing) { - for (int i = 1; i < spacesCount; ++i) - _spaces[i] *= pathLength; - } + if (percentSpacing) { + for (int i = 1; i < spacesCount; ++i) + _spaces[i] *= pathLength; + } - world.setSize(8, 0); - for (int i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { - float space = _spaces[i]; - position += space; - float p = position; + world.setSize(8, 0); + for (int i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { + float space = _spaces[i]; + position += space; + float p = position; - if (closed) { - p = MathUtil::fmod(p, pathLength); - if (p < 0) p += pathLength; - curve = 0; - } else if (p < 0) { - if (prevCurve != BEFORE) { - prevCurve = BEFORE; - path.computeWorldVertices(target, 2, 4, world, 0); - } + if (closed) { + p = MathUtil::fmod(p, pathLength); + if (p < 0) p += pathLength; + curve = 0; + } else if (p < 0) { + if (prevCurve != BEFORE) { + prevCurve = BEFORE; + path.computeWorldVertices(target, 2, 4, world, 0); + } - addBeforePosition(p, world, 0, out, o); + addBeforePosition(p, world, 0, out, o); - continue; - } else if (p > pathLength) { - if (prevCurve != AFTER) { - prevCurve = AFTER; - path.computeWorldVertices(target, verticesLength - 6, 4, world, 0); - } + continue; + } else if (p > pathLength) { + if (prevCurve != AFTER) { + prevCurve = AFTER; + path.computeWorldVertices(target, verticesLength - 6, 4, world, 0); + } - addAfterPosition(p - pathLength, world, 0, out, o); + addAfterPosition(p - pathLength, world, 0, out, o); - continue; - } + continue; + } - // Determine curve containing position. - for (;; curve++) { - float length = lengths[curve]; - if (p > length) continue; + // Determine curve containing position. + for (;; curve++) { + float length = lengths[curve]; + if (p > length) continue; - if (curve == 0) - p /= length; - else { - float prev = lengths[curve - 1]; - p = (p - prev) / (length - prev); - } - break; - } + if (curve == 0) + p /= length; + else { + float prev = lengths[curve - 1]; + p = (p - prev) / (length - prev); + } + break; + } - if (curve != prevCurve) { - prevCurve = curve; - if (closed && curve == curveCount) { - path.computeWorldVertices(target, verticesLength - 4, 4, world, 0); - path.computeWorldVertices(target, 0, 4, world, 4); - } else - path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0); - } + if (curve != prevCurve) { + prevCurve = curve; + if (closed && curve == curveCount) { + path.computeWorldVertices(target, verticesLength - 4, 4, world, 0); + path.computeWorldVertices(target, 0, 4, world, 4); + } else + path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0); + } - addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], - out, o, tangents || (i > 0 && space < EPSILON)); - } - return out; - } + addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], + out, o, tangents || (i > 0 && space < EPSILON)); + } + return out; + } - // World vertices. - if (closed) { - verticesLength += 2; - world.setSize(verticesLength, 0); - path.computeWorldVertices(target, 2, verticesLength - 4, world, 0); - path.computeWorldVertices(target, 0, 2, world, verticesLength - 4); - world[verticesLength - 2] = world[0]; - world[verticesLength - 1] = world[1]; - } else { - curveCount--; - verticesLength -= 4; - world.setSize(verticesLength, 0); - path.computeWorldVertices(target, 2, verticesLength, world, 0); - } + // World vertices. + if (closed) { + verticesLength += 2; + world.setSize(verticesLength, 0); + path.computeWorldVertices(target, 2, verticesLength - 4, world, 0); + path.computeWorldVertices(target, 0, 2, world, verticesLength - 4); + world[verticesLength - 2] = world[0]; + world[verticesLength - 1] = world[1]; + } else { + curveCount--; + verticesLength -= 4; + world.setSize(verticesLength, 0); + path.computeWorldVertices(target, 2, verticesLength, world, 0); + } - // Curve lengths. - _curves.setSize(curveCount, 0); - pathLength = 0; - float x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; - float tmpx, tmpy, dddfx, dddfy, ddfx, ddfy, dfx, dfy; - for (int i = 0, w = 2; i < curveCount; i++, w += 6) { - cx1 = world[w]; - cy1 = world[w + 1]; - cx2 = world[w + 2]; - cy2 = world[w + 3]; - x2 = world[w + 4]; - y2 = world[w + 5]; - tmpx = (x1 - cx1 * 2 + cx2) * 0.1875f; - tmpy = (y1 - cy1 * 2 + cy2) * 0.1875f; - dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375f; - dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375f; - ddfx = tmpx * 2 + dddfx; - ddfy = tmpy * 2 + dddfy; - dfx = (cx1 - x1) * 0.75f + tmpx + dddfx * 0.16666667f; - dfy = (cy1 - y1) * 0.75f + tmpy + dddfy * 0.16666667f; - pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - dfx += ddfx; - dfy += ddfy; - ddfx += dddfx; - ddfy += dddfy; - pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - dfx += ddfx; - dfy += ddfy; - pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - dfx += ddfx + dddfx; - dfy += ddfy + dddfy; - pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - _curves[i] = pathLength; - x1 = x2; - y1 = y2; - } + // Curve lengths. + _curves.setSize(curveCount, 0); + pathLength = 0; + float x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; + float tmpx, tmpy, dddfx, dddfy, ddfx, ddfy, dfx, dfy; + for (int i = 0, w = 2; i < curveCount; i++, w += 6) { + cx1 = world[w]; + cy1 = world[w + 1]; + cx2 = world[w + 2]; + cy2 = world[w + 3]; + x2 = world[w + 4]; + y2 = world[w + 5]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.1875f; + tmpy = (y1 - cy1 * 2 + cy2) * 0.1875f; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375f; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375f; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.75f + tmpx + dddfx * 0.16666667f; + dfy = (cy1 - y1) * 0.75f + tmpy + dddfy * 0.16666667f; + pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + pathLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + _curves[i] = pathLength; + x1 = x2; + y1 = y2; + } - if (percentPosition) - position *= pathLength; - else - position *= pathLength / path.getLengths()[curveCount - 1]; + if (percentPosition) + position *= pathLength; + else + position *= pathLength / path.getLengths()[curveCount - 1]; - if (percentSpacing) { - for (int i = 1; i < spacesCount; ++i) - _spaces[i] *= pathLength; - } + if (percentSpacing) { + for (int i = 1; i < spacesCount; ++i) + _spaces[i] *= pathLength; + } - float curveLength = 0; - for (int i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { - float space = _spaces[i]; - position += space; - float p = position; + float curveLength = 0; + for (int i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { + float space = _spaces[i]; + position += space; + float p = position; - if (closed) { - p = MathUtil::fmod(p, pathLength); - if (p < 0) p += pathLength; - curve = 0; - } else if (p < 0) { - addBeforePosition(p, world, 0, out, o); - continue; - } else if (p > pathLength) { - addAfterPosition(p - pathLength, world, verticesLength - 4, out, o); - continue; - } + if (closed) { + p = MathUtil::fmod(p, pathLength); + if (p < 0) p += pathLength; + curve = 0; + } else if (p < 0) { + addBeforePosition(p, world, 0, out, o); + continue; + } else if (p > pathLength) { + addAfterPosition(p - pathLength, world, verticesLength - 4, out, o); + continue; + } - // Determine curve containing position. - for (;; curve++) { - float length = _curves[curve]; - if (p > length) continue; - if (curve == 0) - p /= length; - else { - float prev = _curves[curve - 1]; - p = (p - prev) / (length - prev); - } - break; - } + // Determine curve containing position. + for (;; curve++) { + float length = _curves[curve]; + if (p > length) continue; + if (curve == 0) + p /= length; + else { + float prev = _curves[curve - 1]; + p = (p - prev) / (length - prev); + } + break; + } - // Curve segment lengths. - if (curve != prevCurve) { - prevCurve = curve; - int ii = curve * 6; - x1 = world[ii]; - y1 = world[ii + 1]; - cx1 = world[ii + 2]; - cy1 = world[ii + 3]; - cx2 = world[ii + 4]; - cy2 = world[ii + 5]; - x2 = world[ii + 6]; - y2 = world[ii + 7]; - tmpx = (x1 - cx1 * 2 + cx2) * 0.03f; - tmpy = (y1 - cy1 * 2 + cy2) * 0.03f; - dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006f; - dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006f; - ddfx = tmpx * 2 + dddfx; - ddfy = tmpy * 2 + dddfy; - dfx = (cx1 - x1) * 0.3f + tmpx + dddfx * 0.16666667f; - dfy = (cy1 - y1) * 0.3f + tmpy + dddfy * 0.16666667f; - curveLength = MathUtil::sqrt(dfx * dfx + dfy * dfy); - _segments[0] = curveLength; - for (ii = 1; ii < 8; ii++) { - dfx += ddfx; - dfy += ddfy; - ddfx += dddfx; - ddfy += dddfy; - curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - _segments[ii] = curveLength; - } - dfx += ddfx; - dfy += ddfy; - curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - _segments[8] = curveLength; - dfx += ddfx + dddfx; - dfy += ddfy + dddfy; - curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); - _segments[9] = curveLength; - segment = 0; - } + // Curve segment lengths. + if (curve != prevCurve) { + prevCurve = curve; + int ii = curve * 6; + x1 = world[ii]; + y1 = world[ii + 1]; + cx1 = world[ii + 2]; + cy1 = world[ii + 3]; + cx2 = world[ii + 4]; + cy2 = world[ii + 5]; + x2 = world[ii + 6]; + y2 = world[ii + 7]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.03f; + tmpy = (y1 - cy1 * 2 + cy2) * 0.03f; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006f; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006f; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.3f + tmpx + dddfx * 0.16666667f; + dfy = (cy1 - y1) * 0.3f + tmpy + dddfy * 0.16666667f; + curveLength = MathUtil::sqrt(dfx * dfx + dfy * dfy); + _segments[0] = curveLength; + for (ii = 1; ii < 8; ii++) { + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + _segments[ii] = curveLength; + } + dfx += ddfx; + dfy += ddfy; + curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + _segments[8] = curveLength; + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + curveLength += MathUtil::sqrt(dfx * dfx + dfy * dfy); + _segments[9] = curveLength; + segment = 0; + } - // Weight by segment length. - p *= curveLength; - for (;; segment++) { - float length = _segments[segment]; - if (p > length) continue; - if (segment == 0) - p /= length; - else { - float prev = _segments[segment - 1]; - p = segment + (p - prev) / (length - prev); - } - break; - } - addCurvePosition(p * 0.1f, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, - tangents || (i > 0 && space < EPSILON)); - } + // Weight by segment length. + p *= curveLength; + for (;; segment++) { + float length = _segments[segment]; + if (p > length) continue; + if (segment == 0) + p /= length; + else { + float prev = _segments[segment - 1]; + p = segment + (p - prev) / (length - prev); + } + break; + } + addCurvePosition(p * 0.1f, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, + tangents || (i > 0 && space < EPSILON)); + } - return out; + return out; } void PathConstraint::addBeforePosition(float p, Vector &temp, int i, Vector &output, int o) { - float x1 = temp[i]; - float y1 = temp[i + 1]; - float dx = temp[i + 2] - x1; - float dy = temp[i + 3] - y1; - float r = MathUtil::atan2(dy, dx); - output[o] = x1 + p * MathUtil::cos(r); - output[o + 1] = y1 + p * MathUtil::sin(r); - output[o + 2] = r; + float x1 = temp[i]; + float y1 = temp[i + 1]; + float dx = temp[i + 2] - x1; + float dy = temp[i + 3] - y1; + float r = MathUtil::atan2(dy, dx); + output[o] = x1 + p * MathUtil::cos(r); + output[o + 1] = y1 + p * MathUtil::sin(r); + output[o + 2] = r; } void PathConstraint::addAfterPosition(float p, Vector &temp, int i, Vector &output, int o) { - float x1 = temp[i + 2]; - float y1 = temp[i + 3]; - float dx = x1 - temp[i]; - float dy = y1 - temp[i + 1]; - float r = MathUtil::atan2(dy, dx); - output[o] = x1 + p * MathUtil::cos(r); - output[o + 1] = y1 + p * MathUtil::sin(r); - output[o + 2] = r; + float x1 = temp[i + 2]; + float y1 = temp[i + 3]; + float dx = x1 - temp[i]; + float dy = y1 - temp[i + 1]; + float r = MathUtil::atan2(dy, dx); + output[o] = x1 + p * MathUtil::cos(r); + output[o + 1] = y1 + p * MathUtil::sin(r); + output[o + 2] = r; } void PathConstraint::addCurvePosition(float p, float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, - float y2, Vector &output, int o, bool tangents -) { - if (p < EPSILON || MathUtil::isNan(p)) { - output[o] = x1; - output[o + 1] = y1; - output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); - return; - } + float y2, Vector &output, int o, bool tangents) { + if (p < EPSILON || MathUtil::isNan(p)) { + output[o] = x1; + output[o + 1] = y1; + output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); + return; + } - float tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; - float ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p; - float x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; - output[o] = x; - output[o + 1] = y; - if (tangents) { - if (p < 0.001) - output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); - else - output[o + 2] = MathUtil::atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)); - } + float tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; + float ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p; + float x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; + output[o] = x; + output[o + 1] = y; + if (tangents) { + if (p < 0.001) + output[o + 2] = MathUtil::atan2(cy1 - y1, cx1 - x1); + else + output[o + 2] = MathUtil::atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)); + } } bool PathConstraint::isActive() { - return _active; + return _active; } void PathConstraint::setActive(bool inValue) { - _active = inValue; + _active = inValue; } diff --git a/native/cocos/editor-support/spine/PathConstraint.h b/native/cocos/editor-support/spine/PathConstraint.h index 470d899979..f8fb569b3e 100644 --- a/native/cocos/editor-support/spine/PathConstraint.h +++ b/native/cocos/editor-support/spine/PathConstraint.h @@ -35,81 +35,81 @@ #include namespace spine { - class PathConstraintData; - class Skeleton; - class PathAttachment; - class Bone; - class Slot; +class PathConstraintData; +class Skeleton; +class PathAttachment; +class Bone; +class Slot; - class SP_API PathConstraint : public Updatable { - friend class Skeleton; - friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; +class SP_API PathConstraint : public Updatable { + friend class Skeleton; + friend class PathConstraintMixTimeline; + friend class PathConstraintPositionTimeline; + friend class PathConstraintSpacingTimeline; - RTTI_DECL + RTTI_DECL - public: - PathConstraint(PathConstraintData& data, Skeleton& skeleton); +public: + PathConstraint(PathConstraintData& data, Skeleton& skeleton); - /// Applies the constraint to the constrained bones. - void apply(); + /// Applies the constraint to the constrained bones. + void apply(); - virtual void update(); + virtual void update(); - virtual int getOrder(); + virtual int getOrder(); - float getPosition(); - void setPosition(float inValue); + float getPosition(); + void setPosition(float inValue); - float getSpacing(); - void setSpacing(float inValue); + float getSpacing(); + void setSpacing(float inValue); - float getRotateMix(); - void setRotateMix(float inValue); + float getRotateMix(); + void setRotateMix(float inValue); - float getTranslateMix(); - void setTranslateMix(float inValue); + float getTranslateMix(); + void setTranslateMix(float inValue); - Vector& getBones(); + Vector& getBones(); - Slot* getTarget(); - void setTarget(Slot* inValue); + Slot* getTarget(); + void setTarget(Slot* inValue); - PathConstraintData& getData(); + PathConstraintData& getData(); - bool isActive(); + bool isActive(); - void setActive(bool inValue); + void setActive(bool inValue); - private: - static const float EPSILON; - static const int NONE; - static const int BEFORE; - static const int AFTER; +private: + static const float EPSILON; + static const int NONE; + static const int BEFORE; + static const int AFTER; - PathConstraintData& _data; - Vector _bones; - Slot* _target; - float _position, _spacing, _rotateMix, _translateMix; + PathConstraintData& _data; + Vector _bones; + Slot* _target; + float _position, _spacing, _rotateMix, _translateMix; - Vector _spaces; - Vector _positions; - Vector _world; - Vector _curves; - Vector _lengths; - Vector _segments; + Vector _spaces; + Vector _positions; + Vector _world; + Vector _curves; + Vector _lengths; + Vector _segments; - bool _active; + bool _active; - Vector& computeWorldPositions(PathAttachment& path, int spacesCount, bool tangents, bool percentPosition, bool percentSpacing); + Vector& computeWorldPositions(PathAttachment& path, int spacesCount, bool tangents, bool percentPosition, bool percentSpacing); - static void addBeforePosition(float p, Vector& temp, int i, Vector& output, int o); + static void addBeforePosition(float p, Vector& temp, int i, Vector& output, int o); - static void addAfterPosition(float p, Vector& temp, int i, Vector& output, int o); + static void addAfterPosition(float p, Vector& temp, int i, Vector& output, int o); - static void addCurvePosition(float p, float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2, Vector& output, int o, bool tangents); - }; -} + static void addCurvePosition(float p, float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2, Vector& output, int o, bool tangents); +}; +} // namespace spine #endif /* Spine_PathConstraint_h */ diff --git a/native/cocos/editor-support/spine/PathConstraintData.cpp b/native/cocos/editor-support/spine/PathConstraintData.cpp index 55f69dbf37..607cd9a7fd 100644 --- a/native/cocos/editor-support/spine/PathConstraintData.cpp +++ b/native/cocos/editor-support/spine/PathConstraintData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -40,91 +40,90 @@ using namespace spine; -PathConstraintData::PathConstraintData(const String &name) : - ConstraintData(name), - _target(NULL), - _positionMode(PositionMode_Fixed), - _spacingMode(SpacingMode_Length), - _rotateMode(RotateMode_Tangent), - _offsetRotation(0), - _position(0), - _spacing(0), - _rotateMix(0), - _translateMix(0) { +PathConstraintData::PathConstraintData(const String &name) : ConstraintData(name), + _target(NULL), + _positionMode(PositionMode_Fixed), + _spacingMode(SpacingMode_Length), + _rotateMode(RotateMode_Tangent), + _offsetRotation(0), + _position(0), + _spacing(0), + _rotateMix(0), + _translateMix(0) { } Vector &PathConstraintData::getBones() { - return _bones; + return _bones; } SlotData *PathConstraintData::getTarget() { - return _target; + return _target; } void PathConstraintData::setTarget(SlotData *inValue) { - _target = inValue; + _target = inValue; } PositionMode PathConstraintData::getPositionMode() { - return _positionMode; + return _positionMode; } void PathConstraintData::setPositionMode(PositionMode inValue) { - _positionMode = inValue; + _positionMode = inValue; } SpacingMode PathConstraintData::getSpacingMode() { - return _spacingMode; + return _spacingMode; } void PathConstraintData::setSpacingMode(SpacingMode inValue) { - _spacingMode = inValue; + _spacingMode = inValue; } RotateMode PathConstraintData::getRotateMode() { - return _rotateMode; + return _rotateMode; } void PathConstraintData::setRotateMode(RotateMode inValue) { - _rotateMode = inValue; + _rotateMode = inValue; } float PathConstraintData::getOffsetRotation() { - return _offsetRotation; + return _offsetRotation; } void PathConstraintData::setOffsetRotation(float inValue) { - _offsetRotation = inValue; + _offsetRotation = inValue; } float PathConstraintData::getPosition() { - return _position; + return _position; } void PathConstraintData::setPosition(float inValue) { - _position = inValue; + _position = inValue; } float PathConstraintData::getSpacing() { - return _spacing; + return _spacing; } void PathConstraintData::setSpacing(float inValue) { - _spacing = inValue; + _spacing = inValue; } float PathConstraintData::getRotateMix() { - return _rotateMix; + return _rotateMix; } void PathConstraintData::setRotateMix(float inValue) { - _rotateMix = inValue; + _rotateMix = inValue; } float PathConstraintData::getTranslateMix() { - return _translateMix; + return _translateMix; } void PathConstraintData::setTranslateMix(float inValue) { - _translateMix = inValue; + _translateMix = inValue; } diff --git a/native/cocos/editor-support/spine/PathConstraintData.h b/native/cocos/editor-support/spine/PathConstraintData.h index 97f8b84cc4..654ec4d776 100644 --- a/native/cocos/editor-support/spine/PathConstraintData.h +++ b/native/cocos/editor-support/spine/PathConstraintData.h @@ -39,60 +39,60 @@ #include namespace spine { - class BoneData; - class SlotData; +class BoneData; +class SlotData; - class SP_API PathConstraintData : public ConstraintData { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API PathConstraintData : public ConstraintData { + friend class SkeletonBinary; + friend class SkeletonJson; - friend class PathConstraint; - friend class Skeleton; - friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; + friend class PathConstraint; + friend class Skeleton; + friend class PathConstraintMixTimeline; + friend class PathConstraintPositionTimeline; + friend class PathConstraintSpacingTimeline; - public: - explicit PathConstraintData(const String& name); +public: + explicit PathConstraintData(const String& name); - Vector& getBones(); + Vector& getBones(); - SlotData* getTarget(); - void setTarget(SlotData* inValue); + SlotData* getTarget(); + void setTarget(SlotData* inValue); - PositionMode getPositionMode(); - void setPositionMode(PositionMode inValue); + PositionMode getPositionMode(); + void setPositionMode(PositionMode inValue); - SpacingMode getSpacingMode(); - void setSpacingMode(SpacingMode inValue); + SpacingMode getSpacingMode(); + void setSpacingMode(SpacingMode inValue); - RotateMode getRotateMode(); - void setRotateMode(RotateMode inValue); + RotateMode getRotateMode(); + void setRotateMode(RotateMode inValue); - float getOffsetRotation(); - void setOffsetRotation(float inValue); + float getOffsetRotation(); + void setOffsetRotation(float inValue); - float getPosition(); - void setPosition(float inValue); + float getPosition(); + void setPosition(float inValue); - float getSpacing(); - void setSpacing(float inValue); + float getSpacing(); + void setSpacing(float inValue); - float getRotateMix(); - void setRotateMix(float inValue); + float getRotateMix(); + void setRotateMix(float inValue); - float getTranslateMix(); - void setTranslateMix(float inValue); + float getTranslateMix(); + void setTranslateMix(float inValue); - private: - Vector _bones; - SlotData* _target; - PositionMode _positionMode; - SpacingMode _spacingMode; - RotateMode _rotateMode; - float _offsetRotation; - float _position, _spacing, _rotateMix, _translateMix; - }; -} +private: + Vector _bones; + SlotData* _target; + PositionMode _positionMode; + SpacingMode _spacingMode; + RotateMode _rotateMode; + float _offsetRotation; + float _position, _spacing, _rotateMix, _translateMix; +}; +} // namespace spine #endif /* Spine_PathConstraintData_h */ diff --git a/native/cocos/editor-support/spine/PathConstraintMixTimeline.cpp b/native/cocos/editor-support/spine/PathConstraintMixTimeline.cpp index 5d4404e58b..67d94e0440 100644 --- a/native/cocos/editor-support/spine/PathConstraintMixTimeline.cpp +++ b/native/cocos/editor-support/spine/PathConstraintMixTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -55,72 +55,70 @@ const int PathConstraintMixTimeline::ROTATE = 1; const int PathConstraintMixTimeline::TRANSLATE = 2; PathConstraintMixTimeline::PathConstraintMixTimeline(int frameCount) : CurveTimeline(frameCount), - _pathConstraintIndex(0) -{ - _frames.setSize(frameCount * ENTRIES, 0); + _pathConstraintIndex(0) { + _frames.setSize(frameCount * ENTRIES, 0); } void PathConstraintMixTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; - PathConstraint &constraint = *constraintP; - if (!constraint.isActive()) return; + PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; + PathConstraint &constraint = *constraintP; + if (!constraint.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - constraint._rotateMix = constraint._data._rotateMix; - constraint._translateMix = constraint._data._translateMix; - return; - case MixBlend_First: - constraint._rotateMix += (constraint._data._rotateMix - constraint._rotateMix) * alpha; - constraint._translateMix += (constraint._data._translateMix - constraint._translateMix) * alpha; - return; - default: - return; - } - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + constraint._rotateMix = constraint._data._rotateMix; + constraint._translateMix = constraint._data._translateMix; + return; + case MixBlend_First: + constraint._rotateMix += (constraint._data._rotateMix - constraint._rotateMix) * alpha; + constraint._translateMix += (constraint._data._translateMix - constraint._translateMix) * alpha; + return; + default: + return; + } + } - float rotate, translate; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - rotate = _frames[_frames.size() + PREV_ROTATE]; - translate = _frames[_frames.size() + PREV_TRANSLATE]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - rotate = _frames[frame + PREV_ROTATE]; - translate = _frames[frame + PREV_TRANSLATE]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float rotate, translate; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + rotate = _frames[_frames.size() + PREV_ROTATE]; + translate = _frames[_frames.size() + PREV_TRANSLATE]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + rotate = _frames[frame + PREV_ROTATE]; + translate = _frames[frame + PREV_TRANSLATE]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - rotate += (_frames[frame + ROTATE] - rotate) * percent; - translate += (_frames[frame + TRANSLATE] - translate) * percent; - } + rotate += (_frames[frame + ROTATE] - rotate) * percent; + translate += (_frames[frame + TRANSLATE] - translate) * percent; + } - if (blend == MixBlend_Setup) { - constraint._rotateMix = constraint._data._rotateMix + (rotate - constraint._data._rotateMix) * alpha; - constraint._translateMix = - constraint._data._translateMix + (translate - constraint._data._translateMix) * alpha; - } else { - constraint._rotateMix += (rotate - constraint._rotateMix) * alpha; - constraint._translateMix += (translate - constraint._translateMix) * alpha; - } + if (blend == MixBlend_Setup) { + constraint._rotateMix = constraint._data._rotateMix + (rotate - constraint._data._rotateMix) * alpha; + constraint._translateMix = + constraint._data._translateMix + (translate - constraint._data._translateMix) * alpha; + } else { + constraint._rotateMix += (rotate - constraint._rotateMix) * alpha; + constraint._translateMix += (translate - constraint._translateMix) * alpha; + } } int PathConstraintMixTimeline::getPropertyId() { - return ((int) TimelineType_PathConstraintMix << 24) + _pathConstraintIndex; + return ((int)TimelineType_PathConstraintMix << 24) + _pathConstraintIndex; } void PathConstraintMixTimeline::setFrame(int frameIndex, float time, float rotateMix, float translateMix) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + ROTATE] = rotateMix; - _frames[frameIndex + TRANSLATE] = translateMix; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + ROTATE] = rotateMix; + _frames[frameIndex + TRANSLATE] = translateMix; } diff --git a/native/cocos/editor-support/spine/PathConstraintMixTimeline.h b/native/cocos/editor-support/spine/PathConstraintMixTimeline.h index 9537ff06ba..4e5141ade5 100644 --- a/native/cocos/editor-support/spine/PathConstraintMixTimeline.h +++ b/native/cocos/editor-support/spine/PathConstraintMixTimeline.h @@ -35,34 +35,34 @@ namespace spine { #define SP_PATHCONSTRAINTMIXTIMELINE_ENTRIES 5 - class SP_API PathConstraintMixTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API PathConstraintMixTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit PathConstraintMixTimeline(int frameCount); + explicit PathConstraintMixTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - private: - static const int PREV_TIME; - static const int PREV_ROTATE; - static const int PREV_TRANSLATE; - static const int ROTATE; - static const int TRANSLATE; +private: + static const int PREV_TIME; + static const int PREV_ROTATE; + static const int PREV_TRANSLATE; + static const int ROTATE; + static const int TRANSLATE; - Vector _frames; - int _pathConstraintIndex; + Vector _frames; + int _pathConstraintIndex; - /// Sets the time and mixes of the specified keyframe. - void setFrame(int frameIndex, float time, float rotateMix, float translateMix); - }; -} + /// Sets the time and mixes of the specified keyframe. + void setFrame(int frameIndex, float time, float rotateMix, float translateMix); +}; +} // namespace spine #endif /* Spine_PathConstraintMixTimeline_h */ diff --git a/native/cocos/editor-support/spine/PathConstraintPositionTimeline.cpp b/native/cocos/editor-support/spine/PathConstraintPositionTimeline.cpp index f470e4f0b6..39b4414044 100644 --- a/native/cocos/editor-support/spine/PathConstraintPositionTimeline.cpp +++ b/native/cocos/editor-support/spine/PathConstraintPositionTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -53,64 +53,62 @@ const int PathConstraintPositionTimeline::PREV_VALUE = -1; const int PathConstraintPositionTimeline::VALUE = 1; PathConstraintPositionTimeline::PathConstraintPositionTimeline(int frameCount) : CurveTimeline(frameCount), - _pathConstraintIndex(0) -{ - _frames.setSize(frameCount * ENTRIES, 0); + _pathConstraintIndex(0) { + _frames.setSize(frameCount * ENTRIES, 0); } PathConstraintPositionTimeline::~PathConstraintPositionTimeline() { } void PathConstraintPositionTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, - float alpha, MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + float alpha, MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; - PathConstraint &constraint = *constraintP; - if (!constraint.isActive()) return; + PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; + PathConstraint &constraint = *constraintP; + if (!constraint.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - constraint._position = constraint._data._position; - return; - case MixBlend_First: - constraint._position += (constraint._data._position - constraint._position) * alpha; - return; - default: - return; - } - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + constraint._position = constraint._data._position; + return; + case MixBlend_First: + constraint._position += (constraint._data._position - constraint._position) * alpha; + return; + default: + return; + } + } - float position; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - position = _frames[_frames.size() + PREV_VALUE]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - position = _frames[frame + PREV_VALUE]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float position; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + position = _frames[_frames.size() + PREV_VALUE]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + position = _frames[frame + PREV_VALUE]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - position += (_frames[frame + VALUE] - position) * percent; - } - if (blend == MixBlend_Setup) - constraint._position = constraint._data._position + (position - constraint._data._position) * alpha; - else - constraint._position += (position - constraint._position) * alpha; + position += (_frames[frame + VALUE] - position) * percent; + } + if (blend == MixBlend_Setup) + constraint._position = constraint._data._position + (position - constraint._data._position) * alpha; + else + constraint._position += (position - constraint._position) * alpha; } int PathConstraintPositionTimeline::getPropertyId() { - return ((int) TimelineType_PathConstraintPosition << 24) + _pathConstraintIndex; + return ((int)TimelineType_PathConstraintPosition << 24) + _pathConstraintIndex; } void PathConstraintPositionTimeline::setFrame(int frameIndex, float time, float value) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + VALUE] = value; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + VALUE] = value; } diff --git a/native/cocos/editor-support/spine/PathConstraintPositionTimeline.h b/native/cocos/editor-support/spine/PathConstraintPositionTimeline.h index 3c11bf19bd..986cc2143f 100644 --- a/native/cocos/editor-support/spine/PathConstraintPositionTimeline.h +++ b/native/cocos/editor-support/spine/PathConstraintPositionTimeline.h @@ -34,34 +34,34 @@ namespace spine { - class SP_API PathConstraintPositionTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API PathConstraintPositionTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit PathConstraintPositionTimeline(int frameCount); + explicit PathConstraintPositionTimeline(int frameCount); - virtual ~PathConstraintPositionTimeline(); + virtual ~PathConstraintPositionTimeline(); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, float value); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, float value); - protected: - static const int PREV_TIME; - static const int PREV_VALUE; - static const int VALUE; +protected: + static const int PREV_TIME; + static const int PREV_VALUE; + static const int VALUE; - Vector _frames; - int _pathConstraintIndex; - }; -} + Vector _frames; + int _pathConstraintIndex; +}; +} // namespace spine #endif /* Spine_PathConstraintPositionTimeline_h */ diff --git a/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.cpp b/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.cpp index b84f46b12d..d3fb620de4 100644 --- a/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.cpp +++ b/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -48,54 +48,53 @@ using namespace spine; RTTI_IMPL(PathConstraintSpacingTimeline, PathConstraintPositionTimeline) PathConstraintSpacingTimeline::PathConstraintSpacingTimeline(int frameCount) : PathConstraintPositionTimeline( - frameCount) { + frameCount) { } void PathConstraintSpacingTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, - float alpha, MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + float alpha, MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; - PathConstraint &constraint = *constraintP; - if (!constraint.isActive()) return; + PathConstraint *constraintP = skeleton._pathConstraints[_pathConstraintIndex]; + PathConstraint &constraint = *constraintP; + if (!constraint.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - constraint._spacing = constraint._data._spacing; - return; - case MixBlend_First: - constraint._spacing += (constraint._data._spacing - constraint._spacing) * alpha; - return; - default: - return; - } - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + constraint._spacing = constraint._data._spacing; + return; + case MixBlend_First: + constraint._spacing += (constraint._data._spacing - constraint._spacing) * alpha; + return; + default: + return; + } + } - float spacing; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - spacing = _frames[_frames.size() + PREV_VALUE]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - spacing = _frames[frame + PREV_VALUE]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float spacing; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + spacing = _frames[_frames.size() + PREV_VALUE]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + spacing = _frames[frame + PREV_VALUE]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - spacing += (_frames[frame + VALUE] - spacing) * percent; - } + spacing += (_frames[frame + VALUE] - spacing) * percent; + } - if (blend == MixBlend_Setup) - constraint._spacing = constraint._data._spacing + (spacing - constraint._data._spacing) * alpha; - else - constraint._spacing += (spacing - constraint._spacing) * alpha; + if (blend == MixBlend_Setup) + constraint._spacing = constraint._data._spacing + (spacing - constraint._data._spacing) * alpha; + else + constraint._spacing += (spacing - constraint._spacing) * alpha; } int PathConstraintSpacingTimeline::getPropertyId() { - return ((int) TimelineType_PathConstraintSpacing << 24) + _pathConstraintIndex; + return ((int)TimelineType_PathConstraintSpacing << 24) + _pathConstraintIndex; } diff --git a/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.h b/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.h index d3e9bd979c..ee88e72abe 100644 --- a/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.h +++ b/native/cocos/editor-support/spine/PathConstraintSpacingTimeline.h @@ -33,19 +33,19 @@ #include namespace spine { - class SP_API PathConstraintSpacingTimeline : public PathConstraintPositionTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API PathConstraintSpacingTimeline : public PathConstraintPositionTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit PathConstraintSpacingTimeline(int frameCount); +public: + explicit PathConstraintSpacingTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); - }; -} + virtual int getPropertyId(); +}; +} // namespace spine #endif /* Spine_PathConstraintSpacingTimeline_h */ diff --git a/native/cocos/editor-support/spine/PointAttachment.cpp b/native/cocos/editor-support/spine/PointAttachment.cpp index 8c5ceb981f..d71d89cf4b 100644 --- a/native/cocos/editor-support/spine/PointAttachment.cpp +++ b/native/cocos/editor-support/spine/PointAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -45,46 +45,46 @@ PointAttachment::PointAttachment(const String &name) : Attachment(name), _x(0), } void PointAttachment::computeWorldPosition(Bone &bone, float &ox, float &oy) { - bone.localToWorld(_x, _y, ox, oy); + bone.localToWorld(_x, _y, ox, oy); } float PointAttachment::computeWorldRotation(Bone &bone) { - float cos = MathUtil::cosDeg(_rotation); - float sin = MathUtil::sinDeg(_rotation); - float ix = cos * bone._a + sin * bone._b; - float iy = cos * bone._c + sin * bone._d; + float cos = MathUtil::cosDeg(_rotation); + float sin = MathUtil::sinDeg(_rotation); + float ix = cos * bone._a + sin * bone._b; + float iy = cos * bone._c + sin * bone._d; - return MathUtil::atan2(iy, ix) * MathUtil::Rad_Deg; + return MathUtil::atan2(iy, ix) * MathUtil::Rad_Deg; } float PointAttachment::getX() { - return _x; + return _x; } void PointAttachment::setX(float inValue) { - _x = inValue; + _x = inValue; } float PointAttachment::getY() { - return _y; + return _y; } void PointAttachment::setY(float inValue) { - _y = inValue; + _y = inValue; } float PointAttachment::getRotation() { - return _rotation; + return _rotation; } void PointAttachment::setRotation(float inValue) { - _rotation = inValue; + _rotation = inValue; } -Attachment* PointAttachment::copy() { - PointAttachment* copy = new(__FILE__, __LINE__) PointAttachment(getName()); - copy->_x = _x; - copy->_y = _y; - copy->_rotation = _rotation; - return copy; +Attachment *PointAttachment::copy() { + PointAttachment *copy = new (__FILE__, __LINE__) PointAttachment(getName()); + copy->_x = _x; + copy->_y = _y; + copy->_rotation = _rotation; + return copy; } diff --git a/native/cocos/editor-support/spine/PointAttachment.h b/native/cocos/editor-support/spine/PointAttachment.h index 7860a99611..b9caaff7f3 100644 --- a/native/cocos/editor-support/spine/PointAttachment.h +++ b/native/cocos/editor-support/spine/PointAttachment.h @@ -33,41 +33,41 @@ #include namespace spine { - class Bone; +class Bone; - /// An attachment which is a single point and a rotation. This can be used to spawn projectiles, particles, etc. A bone can be - /// used in similar ways, but a PointAttachment is slightly less expensive to compute and can be hidden, shown, and placed in a - /// skin. - /// - /// See http://esotericsoftware.com/spine-point-attachments for Point Attachments in the Spine User Guide. - /// - class SP_API PointAttachment : public Attachment { - friend class SkeletonBinary; - friend class SkeletonJson; +/// An attachment which is a single point and a rotation. This can be used to spawn projectiles, particles, etc. A bone can be +/// used in similar ways, but a PointAttachment is slightly less expensive to compute and can be hidden, shown, and placed in a +/// skin. +/// +/// See http://esotericsoftware.com/spine-point-attachments for Point Attachments in the Spine User Guide. +/// +class SP_API PointAttachment : public Attachment { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit PointAttachment(const String& name); +public: + explicit PointAttachment(const String& name); - void computeWorldPosition(Bone& bone, float& ox, float& oy); + void computeWorldPosition(Bone& bone, float& ox, float& oy); - float computeWorldRotation(Bone& bone); + float computeWorldRotation(Bone& bone); - float getX(); - void setX(float inValue); + float getX(); + void setX(float inValue); - float getY(); - void setY(float inValue); + float getY(); + void setY(float inValue); - float getRotation(); - void setRotation(float inValue); + float getRotation(); + void setRotation(float inValue); - virtual Attachment* copy(); + virtual Attachment* copy(); - private: - float _x, _y, _rotation; - }; -} +private: + float _x, _y, _rotation; +}; +} // namespace spine #endif /* Spine_PointAttachment_h */ diff --git a/native/cocos/editor-support/spine/Pool.h b/native/cocos/editor-support/spine/Pool.h index 54e220c958..b0a688d867 100644 --- a/native/cocos/editor-support/spine/Pool.h +++ b/native/cocos/editor-support/spine/Pool.h @@ -36,39 +36,39 @@ #include namespace spine { -template +template class SP_API Pool : public SpineObject { public: - Pool() { - } + Pool() { + } - ~Pool() { - ContainerUtil::cleanUpVectorOfPointers(_objects); - } + ~Pool() { + ContainerUtil::cleanUpVectorOfPointers(_objects); + } - T *obtain() { - if (_objects.size() > 0) { - T **object = &_objects[_objects.size() - 1]; - T *ret = *object; - _objects.removeAt(_objects.size() - 1); + T *obtain() { + if (_objects.size() > 0) { + T **object = &_objects[_objects.size() - 1]; + T *ret = *object; + _objects.removeAt(_objects.size() - 1); - return ret; - } else { - T *ret = new(__FILE__, __LINE__) T(); + return ret; + } else { + T *ret = new (__FILE__, __LINE__) T(); - return ret; - } - } + return ret; + } + } - void free(T *object) { - if (!_objects.contains(object)) { - _objects.add(object); - } - } + void free(T *object) { + if (!_objects.contains(object)) { + _objects.add(object); + } + } private: - Vector _objects; + Vector _objects; }; -} +} // namespace spine #endif /* Spine_Pool_h */ diff --git a/native/cocos/editor-support/spine/PositionMode.h b/native/cocos/editor-support/spine/PositionMode.h index 0c9157becf..fe828d32fe 100644 --- a/native/cocos/editor-support/spine/PositionMode.h +++ b/native/cocos/editor-support/spine/PositionMode.h @@ -32,8 +32,8 @@ namespace spine { enum PositionMode { - PositionMode_Fixed = 0, - PositionMode_Percent + PositionMode_Fixed = 0, + PositionMode_Percent }; } diff --git a/native/cocos/editor-support/spine/RTTI.cpp b/native/cocos/editor-support/spine/RTTI.cpp index 4b915445eb..fa7e8fde6c 100644 --- a/native/cocos/editor-support/spine/RTTI.cpp +++ b/native/cocos/editor-support/spine/RTTI.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -43,18 +43,18 @@ RTTI::RTTI(const char *className, const RTTI &baseRTTI) : _className(className), } const char *RTTI::getClassName() const { - return _className; + return _className; } bool RTTI::isExactly(const RTTI &rtti) const { - return !strcmp(this->_className, rtti._className); + return !strcmp(this->_className, rtti._className); } bool RTTI::instanceOf(const RTTI &rtti) const { - const RTTI *pCompare = this; - while (pCompare) { - if (!strcmp(pCompare->_className, rtti._className)) return true; - pCompare = pCompare->_pBaseRTTI; - } - return false; + const RTTI *pCompare = this; + while (pCompare) { + if (!strcmp(pCompare->_className, rtti._className)) return true; + pCompare = pCompare->_pBaseRTTI; + } + return false; } diff --git a/native/cocos/editor-support/spine/RTTI.h b/native/cocos/editor-support/spine/RTTI.h index 7f12e542b8..d4744431fb 100644 --- a/native/cocos/editor-support/spine/RTTI.h +++ b/native/cocos/editor-support/spine/RTTI.h @@ -35,38 +35,38 @@ namespace spine { class SP_API RTTI : public SpineObject { public: - explicit RTTI(const char *className); + explicit RTTI(const char *className); - RTTI(const char *className, const RTTI &baseRTTI); + RTTI(const char *className, const RTTI &baseRTTI); - const char *getClassName() const; + const char *getClassName() const; - bool isExactly(const RTTI &rtti) const; + bool isExactly(const RTTI &rtti) const; - bool instanceOf(const RTTI &rtti) const; + bool instanceOf(const RTTI &rtti) const; private: - // Prevent copying - RTTI(const RTTI &obj); + // Prevent copying + RTTI(const RTTI &obj); - RTTI &operator=(const RTTI &obj); + RTTI &operator=(const RTTI &obj); - const char* _className; - const RTTI *_pBaseRTTI; + const char *_className; + const RTTI *_pBaseRTTI; }; -} +} // namespace spine -#define RTTI_DECL \ -public: \ -static const spine::RTTI rtti; \ -virtual const spine::RTTI& getRTTI() const; +#define RTTI_DECL \ +public: \ + static const spine::RTTI rtti; \ + virtual const spine::RTTI &getRTTI() const; -#define RTTI_IMPL_NOPARENT(name) \ -const spine::RTTI name::rtti(#name); \ -const spine::RTTI& name::getRTTI() const { return rtti; } +#define RTTI_IMPL_NOPARENT(name) \ + const spine::RTTI name::rtti(#name); \ + const spine::RTTI &name::getRTTI() const { return rtti; } -#define RTTI_IMPL(name, parent) \ -const spine::RTTI name::rtti(#name, parent::rtti); \ -const spine::RTTI& name::getRTTI() const { return rtti; } +#define RTTI_IMPL(name, parent) \ + const spine::RTTI name::rtti(#name, parent::rtti); \ + const spine::RTTI &name::getRTTI() const { return rtti; } #endif /* Spine_RTTI_h */ diff --git a/native/cocos/editor-support/spine/RegionAttachment.cpp b/native/cocos/editor-support/spine/RegionAttachment.cpp index 461a5a9f0d..e83afc9844 100644 --- a/native/cocos/editor-support/spine/RegionAttachment.cpp +++ b/native/cocos/editor-support/spine/RegionAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -50,258 +50,238 @@ const int RegionAttachment::URY = 5; const int RegionAttachment::BRX = 6; const int RegionAttachment::BRY = 7; -RegionAttachment::RegionAttachment(const String &name) : Attachment(name), HasRendererObject(), - _x(0), - _y(0), - _rotation(0), - _scaleX(1), - _scaleY(1), - _width(0), - _height(0), - _regionOffsetX(0), - _regionOffsetY(0), - _regionWidth(0), - _regionHeight(0), - _regionOriginalWidth(0), - _regionOriginalHeight(0), - _path(), - _regionU(0), - _regionV(0), - _regionU2(0), - _regionV2(0), - _color(1, 1, 1, 1) -{ - _vertexOffset.setSize(NUM_UVS, 0); - _uvs.setSize(NUM_UVS, 0); +RegionAttachment::RegionAttachment(const String &name) : Attachment(name), HasRendererObject(), _x(0), _y(0), _rotation(0), _scaleX(1), _scaleY(1), _width(0), _height(0), _regionOffsetX(0), _regionOffsetY(0), _regionWidth(0), _regionHeight(0), _regionOriginalWidth(0), _regionOriginalHeight(0), _path(), _regionU(0), _regionV(0), _regionU2(0), _regionV2(0), _color(1, 1, 1, 1) { + _vertexOffset.setSize(NUM_UVS, 0); + _uvs.setSize(NUM_UVS, 0); } void RegionAttachment::updateOffset() { - float regionScaleX = _width / _regionOriginalWidth * _scaleX; - float regionScaleY = _height / _regionOriginalHeight * _scaleY; - float localX = -_width / 2 * _scaleX + _regionOffsetX * regionScaleX; - float localY = -_height / 2 * _scaleY + _regionOffsetY * regionScaleY; - float localX2 = localX + _regionWidth * regionScaleX; - float localY2 = localY + _regionHeight * regionScaleY; - float cos = MathUtil::cosDeg(_rotation); - float sin = MathUtil::sinDeg(_rotation); - float localXCos = localX * cos + _x; - float localXSin = localX * sin; - float localYCos = localY * cos + _y; - float localYSin = localY * sin; - float localX2Cos = localX2 * cos + _x; - float localX2Sin = localX2 * sin; - float localY2Cos = localY2 * cos + _y; - float localY2Sin = localY2 * sin; + float regionScaleX = _width / _regionOriginalWidth * _scaleX; + float regionScaleY = _height / _regionOriginalHeight * _scaleY; + float localX = -_width / 2 * _scaleX + _regionOffsetX * regionScaleX; + float localY = -_height / 2 * _scaleY + _regionOffsetY * regionScaleY; + float localX2 = localX + _regionWidth * regionScaleX; + float localY2 = localY + _regionHeight * regionScaleY; + float cos = MathUtil::cosDeg(_rotation); + float sin = MathUtil::sinDeg(_rotation); + float localXCos = localX * cos + _x; + float localXSin = localX * sin; + float localYCos = localY * cos + _y; + float localYSin = localY * sin; + float localX2Cos = localX2 * cos + _x; + float localX2Sin = localX2 * sin; + float localY2Cos = localY2 * cos + _y; + float localY2Sin = localY2 * sin; - _vertexOffset[BLX] = localXCos - localYSin; - _vertexOffset[BLY] = localYCos + localXSin; - _vertexOffset[ULX] = localXCos - localY2Sin; - _vertexOffset[ULY] = localY2Cos + localXSin; - _vertexOffset[URX] = localX2Cos - localY2Sin; - _vertexOffset[URY] = localY2Cos + localX2Sin; - _vertexOffset[BRX] = localX2Cos - localYSin; - _vertexOffset[BRY] = localYCos + localX2Sin; + _vertexOffset[BLX] = localXCos - localYSin; + _vertexOffset[BLY] = localYCos + localXSin; + _vertexOffset[ULX] = localXCos - localY2Sin; + _vertexOffset[ULY] = localY2Cos + localXSin; + _vertexOffset[URX] = localX2Cos - localY2Sin; + _vertexOffset[URY] = localY2Cos + localX2Sin; + _vertexOffset[BRX] = localX2Cos - localYSin; + _vertexOffset[BRY] = localYCos + localX2Sin; } void RegionAttachment::setUVs(float u, float v, float u2, float v2, bool rotate) { - if (rotate) { - _uvs[URX] = u; - _uvs[URY] = v2; - _uvs[BRX] = u; - _uvs[BRY] = v; - _uvs[BLX] = u2; - _uvs[BLY] = v; - _uvs[ULX] = u2; - _uvs[ULY] = v2; - } else { - _uvs[ULX] = u; - _uvs[ULY] = v2; - _uvs[URX] = u; - _uvs[URY] = v; - _uvs[BRX] = u2; - _uvs[BRY] = v; - _uvs[BLX] = u2; - _uvs[BLY] = v2; - } + if (rotate) { + _uvs[URX] = u; + _uvs[URY] = v2; + _uvs[BRX] = u; + _uvs[BRY] = v; + _uvs[BLX] = u2; + _uvs[BLY] = v; + _uvs[ULX] = u2; + _uvs[ULY] = v2; + } else { + _uvs[ULX] = u; + _uvs[ULY] = v2; + _uvs[URX] = u; + _uvs[URY] = v; + _uvs[BRX] = u2; + _uvs[BRY] = v; + _uvs[BLX] = u2; + _uvs[BLY] = v2; + } } void RegionAttachment::computeWorldVertices(Bone &bone, Vector &worldVertices, size_t offset, size_t stride) { - assert(worldVertices.size() >= (offset + 8)); - computeWorldVertices(bone, worldVertices.buffer(), offset, stride); + assert(worldVertices.size() >= (offset + 8)); + computeWorldVertices(bone, worldVertices.buffer(), offset, stride); } -void RegionAttachment::computeWorldVertices(Bone &bone, float* worldVertices, size_t offset, size_t stride) { - float x = bone.getWorldX(), y = bone.getWorldY(); - float a = bone.getA(), b = bone.getB(), c = bone.getC(), d = bone.getD(); - float offsetX, offsetY; +void RegionAttachment::computeWorldVertices(Bone &bone, float *worldVertices, size_t offset, size_t stride) { + float x = bone.getWorldX(), y = bone.getWorldY(); + float a = bone.getA(), b = bone.getB(), c = bone.getC(), d = bone.getD(); + float offsetX, offsetY; - offsetX = _vertexOffset[BRX]; - offsetY = _vertexOffset[BRY]; - worldVertices[offset] = offsetX * a + offsetY * b + x; // br - worldVertices[offset + 1] = offsetX * c + offsetY * d + y; - offset += stride; + offsetX = _vertexOffset[BRX]; + offsetY = _vertexOffset[BRY]; + worldVertices[offset] = offsetX * a + offsetY * b + x; // br + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; - offsetX = _vertexOffset[BLX]; - offsetY = _vertexOffset[BLY]; - worldVertices[offset] = offsetX * a + offsetY * b + x; // bl - worldVertices[offset + 1] = offsetX * c + offsetY * d + y; - offset += stride; + offsetX = _vertexOffset[BLX]; + offsetY = _vertexOffset[BLY]; + worldVertices[offset] = offsetX * a + offsetY * b + x; // bl + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; - offsetX = _vertexOffset[ULX]; - offsetY = _vertexOffset[ULY]; - worldVertices[offset] = offsetX * a + offsetY * b + x; // ul - worldVertices[offset + 1] = offsetX * c + offsetY * d + y; - offset += stride; + offsetX = _vertexOffset[ULX]; + offsetY = _vertexOffset[ULY]; + worldVertices[offset] = offsetX * a + offsetY * b + x; // ul + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; - offsetX = _vertexOffset[URX]; - offsetY = _vertexOffset[URY]; - worldVertices[offset] = offsetX * a + offsetY * b + x; // ur - worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offsetX = _vertexOffset[URX]; + offsetY = _vertexOffset[URY]; + worldVertices[offset] = offsetX * a + offsetY * b + x; // ur + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; } float RegionAttachment::getX() { - return _x; + return _x; } void RegionAttachment::setX(float inValue) { - _x = inValue; + _x = inValue; } float RegionAttachment::getY() { - return _y; + return _y; } void RegionAttachment::setY(float inValue) { - _y = inValue; + _y = inValue; } float RegionAttachment::getRotation() { - return _rotation; + return _rotation; } void RegionAttachment::setRotation(float inValue) { - _rotation = inValue; + _rotation = inValue; } float RegionAttachment::getScaleX() { - return _scaleX; + return _scaleX; } void RegionAttachment::setScaleX(float inValue) { - _scaleX = inValue; + _scaleX = inValue; } float RegionAttachment::getScaleY() { - return _scaleY; + return _scaleY; } void RegionAttachment::setScaleY(float inValue) { - _scaleY = inValue; + _scaleY = inValue; } float RegionAttachment::getWidth() { - return _width; + return _width; } void RegionAttachment::setWidth(float inValue) { - _width = inValue; + _width = inValue; } float RegionAttachment::getHeight() { - return _height; + return _height; } void RegionAttachment::setHeight(float inValue) { - _height = inValue; + _height = inValue; } const String &RegionAttachment::getPath() { - return _path; + return _path; } void RegionAttachment::setPath(const String &inValue) { - _path = inValue; + _path = inValue; } float RegionAttachment::getRegionOffsetX() { - return _regionOffsetX; + return _regionOffsetX; } void RegionAttachment::setRegionOffsetX(float inValue) { - _regionOffsetX = inValue; + _regionOffsetX = inValue; } float RegionAttachment::getRegionOffsetY() { - return _regionOffsetY; + return _regionOffsetY; } void RegionAttachment::setRegionOffsetY(float inValue) { - _regionOffsetY = inValue; + _regionOffsetY = inValue; } float RegionAttachment::getRegionWidth() { - return _regionWidth; + return _regionWidth; } void RegionAttachment::setRegionWidth(float inValue) { - _regionWidth = inValue; + _regionWidth = inValue; } float RegionAttachment::getRegionHeight() { - return _regionHeight; + return _regionHeight; } void RegionAttachment::setRegionHeight(float inValue) { - _regionHeight = inValue; + _regionHeight = inValue; } float RegionAttachment::getRegionOriginalWidth() { - return _regionOriginalWidth; + return _regionOriginalWidth; } void RegionAttachment::setRegionOriginalWidth(float inValue) { - _regionOriginalWidth = inValue; + _regionOriginalWidth = inValue; } float RegionAttachment::getRegionOriginalHeight() { - return _regionOriginalHeight; + return _regionOriginalHeight; } void RegionAttachment::setRegionOriginalHeight(float inValue) { - _regionOriginalHeight = inValue; + _regionOriginalHeight = inValue; } Vector &RegionAttachment::getOffset() { - return _vertexOffset; + return _vertexOffset; } Vector &RegionAttachment::getUVs() { - return _uvs; + return _uvs; } spine::Color &RegionAttachment::getColor() { - return _color; + return _color; } -Attachment* RegionAttachment::copy() { - RegionAttachment* copy = new (__FILE__, __LINE__) RegionAttachment(getName()); - copy->_regionWidth = _regionWidth; - copy->_regionHeight = _regionHeight; - copy->_regionOffsetX = _regionOffsetX; - copy->_regionOffsetY = _regionOffsetY; - copy->_regionOriginalWidth = _regionOriginalWidth; - copy->_regionOriginalHeight = _regionOriginalHeight; - copy->setRendererObject(getRendererObject()); - copy->_path = _path; - copy->_x = _x; - copy->_y = _y; - copy->_scaleX = _scaleX; - copy->_scaleY = _scaleY; - copy->_rotation = _rotation; - copy->_width = _width; - copy->_height = _height; - copy->_uvs.clearAndAddAll(_uvs); - copy->_vertexOffset.clearAndAddAll(_vertexOffset); - copy->_color.set(_color); - return copy; +Attachment *RegionAttachment::copy() { + RegionAttachment *copy = new (__FILE__, __LINE__) RegionAttachment(getName()); + copy->_regionWidth = _regionWidth; + copy->_regionHeight = _regionHeight; + copy->_regionOffsetX = _regionOffsetX; + copy->_regionOffsetY = _regionOffsetY; + copy->_regionOriginalWidth = _regionOriginalWidth; + copy->_regionOriginalHeight = _regionOriginalHeight; + copy->setRendererObject(getRendererObject()); + copy->_path = _path; + copy->_x = _x; + copy->_y = _y; + copy->_scaleX = _scaleX; + copy->_scaleY = _scaleY; + copy->_rotation = _rotation; + copy->_width = _width; + copy->_height = _height; + copy->_uvs.clearAndAddAll(_uvs); + copy->_vertexOffset.clearAndAddAll(_vertexOffset); + copy->_color.set(_color); + return copy; } diff --git a/native/cocos/editor-support/spine/RegionAttachment.h b/native/cocos/editor-support/spine/RegionAttachment.h index fe8720706f..7ff4c5023f 100644 --- a/native/cocos/editor-support/spine/RegionAttachment.h +++ b/native/cocos/editor-support/spine/RegionAttachment.h @@ -39,95 +39,95 @@ #define NUM_UVS 8 namespace spine { - class Bone; +class Bone; - /// Attachment that displays a texture region. - class SP_API RegionAttachment : public Attachment, public HasRendererObject { - friend class SkeletonBinary; - friend class SkeletonJson; - friend class AtlasAttachmentLoader; +/// Attachment that displays a texture region. +class SP_API RegionAttachment : public Attachment, public HasRendererObject { + friend class SkeletonBinary; + friend class SkeletonJson; + friend class AtlasAttachmentLoader; - RTTI_DECL + RTTI_DECL - public: - explicit RegionAttachment(const String& name); +public: + explicit RegionAttachment(const String& name); - void updateOffset(); + void updateOffset(); - void setUVs(float u, float v, float u2, float v2, bool rotate); + void setUVs(float u, float v, float u2, float v2, bool rotate); - /// Transforms the attachment's four vertices to world coordinates. - /// @param bone The parent bone. - /// @param worldVertices The output world vertices. Must have a length greater than or equal to offset + 8. - /// @param offset The worldVertices index to begin writing values. - /// @param stride The number of worldVertices entries between the value pairs written. - void computeWorldVertices(Bone& bone, float *worldVertices, size_t offset, size_t stride = 2); - void computeWorldVertices(Bone& bone, Vector& worldVertices, size_t offset, size_t stride = 2); + /// Transforms the attachment's four vertices to world coordinates. + /// @param bone The parent bone. + /// @param worldVertices The output world vertices. Must have a length greater than or equal to offset + 8. + /// @param offset The worldVertices index to begin writing values. + /// @param stride The number of worldVertices entries between the value pairs written. + void computeWorldVertices(Bone& bone, float* worldVertices, size_t offset, size_t stride = 2); + void computeWorldVertices(Bone& bone, Vector& worldVertices, size_t offset, size_t stride = 2); - float getX(); - void setX(float inValue); - float getY(); - void setY(float inValue); - float getRotation(); - void setRotation(float inValue); - float getScaleX(); - void setScaleX(float inValue); - float getScaleY(); - void setScaleY(float inValue); - float getWidth(); - void setWidth(float inValue); - float getHeight(); - void setHeight(float inValue); + float getX(); + void setX(float inValue); + float getY(); + void setY(float inValue); + float getRotation(); + void setRotation(float inValue); + float getScaleX(); + void setScaleX(float inValue); + float getScaleY(); + void setScaleY(float inValue); + float getWidth(); + void setWidth(float inValue); + float getHeight(); + void setHeight(float inValue); - Color& getColor(); + Color& getColor(); - const String& getPath(); - void setPath(const String& inValue); + const String& getPath(); + void setPath(const String& inValue); - float getRegionOffsetX(); - void setRegionOffsetX(float inValue); + float getRegionOffsetX(); + void setRegionOffsetX(float inValue); - float getRegionOffsetY(); - void setRegionOffsetY(float inValue); + float getRegionOffsetY(); + void setRegionOffsetY(float inValue); - float getRegionWidth(); - void setRegionWidth(float inValue); + float getRegionWidth(); + void setRegionWidth(float inValue); - float getRegionHeight(); - void setRegionHeight(float inValue); + float getRegionHeight(); + void setRegionHeight(float inValue); - float getRegionOriginalWidth(); - void setRegionOriginalWidth(float inValue); + float getRegionOriginalWidth(); + void setRegionOriginalWidth(float inValue); - float getRegionOriginalHeight(); - void setRegionOriginalHeight(float inValue); + float getRegionOriginalHeight(); + void setRegionOriginalHeight(float inValue); - Vector& getOffset(); - Vector& getUVs(); + Vector& getOffset(); + Vector& getUVs(); - virtual Attachment* copy(); + virtual Attachment* copy(); - private: - static const int BLX; - static const int BLY; - static const int ULX; - static const int ULY; - static const int URX; - static const int URY; - static const int BRX; - static const int BRY; +private: + static const int BLX; + static const int BLY; + static const int ULX; + static const int ULY; + static const int URX; + static const int URY; + static const int BRX; + static const int BRY; - float _x, _y, _rotation, _scaleX, _scaleY, _width, _height; - float _regionOffsetX, _regionOffsetY, _regionWidth, _regionHeight, _regionOriginalWidth, _regionOriginalHeight; - Vector _vertexOffset; - Vector _uvs; - String _path; - float _regionU; - float _regionV; - float _regionU2; - float _regionV2; - Color _color; - }; -} + float _x, _y, _rotation, _scaleX, _scaleY, _width, _height; + float _regionOffsetX, _regionOffsetY, _regionWidth, _regionHeight, _regionOriginalWidth, _regionOriginalHeight; + Vector _vertexOffset; + Vector _uvs; + String _path; + float _regionU; + float _regionV; + float _regionU2; + float _regionV2; + Color _color; +}; +} // namespace spine #endif /* Spine_RegionAttachment_h */ diff --git a/native/cocos/editor-support/spine/RotateMode.h b/native/cocos/editor-support/spine/RotateMode.h index 42f3355c19..3a76863260 100644 --- a/native/cocos/editor-support/spine/RotateMode.h +++ b/native/cocos/editor-support/spine/RotateMode.h @@ -32,9 +32,9 @@ namespace spine { enum RotateMode { - RotateMode_Tangent = 0, - RotateMode_Chain, - RotateMode_ChainScale + RotateMode_Tangent = 0, + RotateMode_Chain, + RotateMode_ChainScale }; } diff --git a/native/cocos/editor-support/spine/RotateTimeline.cpp b/native/cocos/editor-support/spine/RotateTimeline.cpp index 0373639174..769748f3f6 100644 --- a/native/cocos/editor-support/spine/RotateTimeline.cpp +++ b/native/cocos/editor-support/spine/RotateTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -46,94 +46,93 @@ using namespace spine; RTTI_IMPL(RotateTimeline, CurveTimeline) RotateTimeline::RotateTimeline(int frameCount) : CurveTimeline(frameCount), _boneIndex(0) { - _frames.setSize(frameCount << 1, 0); + _frames.setSize(frameCount << 1, 0); } void RotateTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Bone *bone = skeleton.getBones()[_boneIndex]; - if (!bone->_active) return; + Bone *bone = skeleton.getBones()[_boneIndex]; + if (!bone->_active) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: { - bone->_rotation = bone->_data._rotation; - break; - } - case MixBlend_First: { - float r = bone->_data._rotation - bone->_rotation; - bone->_rotation += (r - (16384 - (int) (16384.499999999996 - r / 360)) * 360) * alpha; - break; - } - default: { - // TODO? - break; - } - } - return; - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: { + bone->_rotation = bone->_data._rotation; + break; + } + case MixBlend_First: { + float r = bone->_data._rotation - bone->_rotation; + bone->_rotation += (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + break; + } + default: { + // TODO? + break; + } + } + return; + } - if (time >= _frames[_frames.size() - ENTRIES]) { - float r = _frames[_frames.size() + PREV_ROTATION]; - switch (blend) { - case MixBlend_Setup: - bone->_rotation = bone->_data._rotation + r * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - r += bone->_data._rotation - bone->_rotation; - r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; - // Fall through. - case MixBlend_Add: - bone->_rotation += r * alpha; - } - return; - } + if (time >= _frames[_frames.size() - ENTRIES]) { + float r = _frames[_frames.size() + PREV_ROTATION]; + switch (blend) { + case MixBlend_Setup: + bone->_rotation = bone->_data._rotation + r * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + r += bone->_data._rotation - bone->_rotation; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + // Fall through. + case MixBlend_Add: + bone->_rotation += r * alpha; + } + return; + } - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - float prevRotation = _frames[frame + PREV_ROTATION]; - float frameTime = _frames[frame]; - float percent = getCurvePercent((frame >> 1) - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - float r = _frames[frame + ROTATION] - prevRotation; - r = prevRotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * percent; - switch (blend) { - case MixBlend_Setup: - bone->_rotation = bone->_data._rotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - r += bone->_data._rotation - bone->_rotation; - // Fall through. - case MixBlend_Add: - bone->_rotation += (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; - } + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + float prevRotation = _frames[frame + PREV_ROTATION]; + float frameTime = _frames[frame]; + float percent = getCurvePercent((frame >> 1) - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float r = _frames[frame + ROTATION] - prevRotation; + r = prevRotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * percent; + switch (blend) { + case MixBlend_Setup: + bone->_rotation = bone->_data._rotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + r += bone->_data._rotation - bone->_rotation; + // Fall through. + case MixBlend_Add: + bone->_rotation += (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + } } int RotateTimeline::getPropertyId() { - return ((int) TimelineType_Rotate << 24) + _boneIndex; + return ((int)TimelineType_Rotate << 24) + _boneIndex; } void RotateTimeline::setFrame(int frameIndex, float time, float degrees) { - frameIndex <<= 1; - _frames[frameIndex] = time; - _frames[frameIndex + ROTATION] = degrees; + frameIndex <<= 1; + _frames[frameIndex] = time; + _frames[frameIndex + ROTATION] = degrees; } int RotateTimeline::getBoneIndex() { - return _boneIndex; + return _boneIndex; } void RotateTimeline::setBoneIndex(int inValue) { - _boneIndex = inValue; + _boneIndex = inValue; } Vector &RotateTimeline::getFrames() { - return _frames; + return _frames; } diff --git a/native/cocos/editor-support/spine/RotateTimeline.h b/native/cocos/editor-support/spine/RotateTimeline.h index 0c6f89b317..fc9e463328 100644 --- a/native/cocos/editor-support/spine/RotateTimeline.h +++ b/native/cocos/editor-support/spine/RotateTimeline.h @@ -33,38 +33,38 @@ #include namespace spine { - class SP_API RotateTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; - friend class AnimationState; +class SP_API RotateTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; + friend class AnimationState; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES = 2; +public: + static const int ENTRIES = 2; - explicit RotateTimeline(int frameCount); + explicit RotateTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, float degrees); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, float degrees); - int getBoneIndex(); - void setBoneIndex(int inValue); + int getBoneIndex(); + void setBoneIndex(int inValue); - Vector& getFrames(); + Vector& getFrames(); - private: - static const int PREV_TIME = -2; - static const int PREV_ROTATION = -1; - static const int ROTATION = 1; +private: + static const int PREV_TIME = -2; + static const int PREV_ROTATION = -1; + static const int ROTATION = 1; - int _boneIndex; - Vector _frames; // time, angle, ... - }; -} + int _boneIndex; + Vector _frames; // time, angle, ... +}; +} // namespace spine #endif /* Spine_RotateTimeline_h */ diff --git a/native/cocos/editor-support/spine/ScaleTimeline.cpp b/native/cocos/editor-support/spine/ScaleTimeline.cpp index f00e0320c4..0ac1715cb3 100644 --- a/native/cocos/editor-support/spine/ScaleTimeline.cpp +++ b/native/cocos/editor-support/spine/ScaleTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -49,105 +49,105 @@ ScaleTimeline::ScaleTimeline(int frameCount) : TranslateTimeline(frameCount) { } void ScaleTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); - Bone *boneP = skeleton._bones[_boneIndex]; - Bone &bone = *boneP; + Bone *boneP = skeleton._bones[_boneIndex]; + Bone &bone = *boneP; - if (!bone._active) return; + if (!bone._active) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - bone._scaleX = bone._data._scaleX; - bone._scaleY = bone._data._scaleY; - return; - case MixBlend_First: - bone._scaleX += (bone._data._scaleX - bone._scaleX) * alpha; - bone._scaleY += (bone._data._scaleY - bone._scaleY) * alpha; - default: {} - } - return; - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + bone._scaleX = bone._data._scaleX; + bone._scaleY = bone._data._scaleY; + return; + case MixBlend_First: + bone._scaleX += (bone._data._scaleX - bone._scaleX) * alpha; + bone._scaleY += (bone._data._scaleY - bone._scaleY) * alpha; + default: { + } + } + return; + } - float x, y; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - x = _frames[_frames.size() + PREV_X] * bone._data._scaleX; - y = _frames[_frames.size() + PREV_Y] * bone._data._scaleY; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - x = _frames[frame + PREV_X]; - y = _frames[frame + PREV_Y]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float x, y; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + x = _frames[_frames.size() + PREV_X] * bone._data._scaleX; + y = _frames[_frames.size() + PREV_Y] * bone._data._scaleY; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + x = _frames[frame + PREV_X]; + y = _frames[frame + PREV_Y]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - x = (x + (_frames[frame + X] - x) * percent) * bone._data._scaleX; - y = (y + (_frames[frame + Y] - y) * percent) * bone._data._scaleY; - } + x = (x + (_frames[frame + X] - x) * percent) * bone._data._scaleX; + y = (y + (_frames[frame + Y] - y) * percent) * bone._data._scaleY; + } - if (alpha == 1) { - if (blend == MixBlend_Add) { - bone._scaleX += x - bone._data._scaleX; - bone._scaleY += y - bone._data._scaleY; - } else { - bone._scaleX = x; - bone._scaleY = y; - } - } else { - // Mixing out uses sign of setup or current pose, else use sign of key. - float bx, by; - if (direction == MixDirection_Out) { - switch (blend) { - case MixBlend_Setup: - bx = bone._data._scaleX; - by = bone._data._scaleY; - bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bx) * alpha; - bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - by) * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - bx = bone._scaleX; - by = bone._scaleY; - bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bx) * alpha; - bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - by) * alpha; - break; - case MixBlend_Add: - bx = bone._scaleX; - by = bone._scaleY; - bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bone._data._scaleX) * alpha; - bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - bone._data._scaleY) * alpha; - } - } else { - switch (blend) { - case MixBlend_Setup: - bx = MathUtil::abs(bone._data._scaleX) * MathUtil::sign(x); - by = MathUtil::abs(bone._data._scaleY) * MathUtil::sign(y); - bone._scaleX = bx + (x - bx) * alpha; - bone._scaleY = by + (y - by) * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - bx = MathUtil::abs(bone._scaleX) * MathUtil::sign(x); - by = MathUtil::abs(bone._scaleY) * MathUtil::sign(y); - bone._scaleX = bx + (x - bx) * alpha; - bone._scaleY = by + (y - by) * alpha; - break; - case MixBlend_Add: - bx = MathUtil::sign(x); - by = MathUtil::sign(y); - bone._scaleX = MathUtil::abs(bone._scaleX) * bx + (x - MathUtil::abs(bone._data._scaleX) * bx) * alpha; - bone._scaleY = MathUtil::abs(bone._scaleY) * by + (y - MathUtil::abs(bone._data._scaleY) * by) * alpha; - } - } - } + if (alpha == 1) { + if (blend == MixBlend_Add) { + bone._scaleX += x - bone._data._scaleX; + bone._scaleY += y - bone._data._scaleY; + } else { + bone._scaleX = x; + bone._scaleY = y; + } + } else { + // Mixing out uses sign of setup or current pose, else use sign of key. + float bx, by; + if (direction == MixDirection_Out) { + switch (blend) { + case MixBlend_Setup: + bx = bone._data._scaleX; + by = bone._data._scaleY; + bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bx) * alpha; + bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - by) * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + bx = bone._scaleX; + by = bone._scaleY; + bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bx) * alpha; + bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - by) * alpha; + break; + case MixBlend_Add: + bx = bone._scaleX; + by = bone._scaleY; + bone._scaleX = bx + (MathUtil::abs(x) * MathUtil::sign(bx) - bone._data._scaleX) * alpha; + bone._scaleY = by + (MathUtil::abs(y) * MathUtil::sign(by) - bone._data._scaleY) * alpha; + } + } else { + switch (blend) { + case MixBlend_Setup: + bx = MathUtil::abs(bone._data._scaleX) * MathUtil::sign(x); + by = MathUtil::abs(bone._data._scaleY) * MathUtil::sign(y); + bone._scaleX = bx + (x - bx) * alpha; + bone._scaleY = by + (y - by) * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + bx = MathUtil::abs(bone._scaleX) * MathUtil::sign(x); + by = MathUtil::abs(bone._scaleY) * MathUtil::sign(y); + bone._scaleX = bx + (x - bx) * alpha; + bone._scaleY = by + (y - by) * alpha; + break; + case MixBlend_Add: + bx = MathUtil::sign(x); + by = MathUtil::sign(y); + bone._scaleX = MathUtil::abs(bone._scaleX) * bx + (x - MathUtil::abs(bone._data._scaleX) * bx) * alpha; + bone._scaleY = MathUtil::abs(bone._scaleY) * by + (y - MathUtil::abs(bone._data._scaleY) * by) * alpha; + } + } + } } int ScaleTimeline::getPropertyId() { - return ((int) TimelineType_Scale << 24) + _boneIndex; + return ((int)TimelineType_Scale << 24) + _boneIndex; } diff --git a/native/cocos/editor-support/spine/ScaleTimeline.h b/native/cocos/editor-support/spine/ScaleTimeline.h index 984b9d72c6..01a85c89f1 100644 --- a/native/cocos/editor-support/spine/ScaleTimeline.h +++ b/native/cocos/editor-support/spine/ScaleTimeline.h @@ -33,19 +33,19 @@ #include namespace spine { - class SP_API ScaleTimeline : public TranslateTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API ScaleTimeline : public TranslateTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit ScaleTimeline(int frameCount); +public: + explicit ScaleTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); - }; -} + virtual int getPropertyId(); +}; +} // namespace spine #endif /* Spine_ScaleTimeline_h */ diff --git a/native/cocos/editor-support/spine/ShearTimeline.cpp b/native/cocos/editor-support/spine/ShearTimeline.cpp index 046d057ad1..4f0d0fca2e 100644 --- a/native/cocos/editor-support/spine/ShearTimeline.cpp +++ b/native/cocos/editor-support/spine/ShearTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -49,64 +49,64 @@ ShearTimeline::ShearTimeline(int frameCount) : TranslateTimeline(frameCount) { } void ShearTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Bone *boneP = skeleton._bones[_boneIndex]; - Bone &bone = *boneP; - if (!bone._active) return; + Bone *boneP = skeleton._bones[_boneIndex]; + Bone &bone = *boneP; + if (!bone._active) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - bone._shearX = bone._data._shearX; - bone._shearY = bone._data._shearY; - return; - case MixBlend_First: - bone._shearX += (bone._data._shearX - bone._shearX) * alpha; - bone._shearY += (bone._data._shearY - bone._shearY) * alpha; - default: {} - } - return; - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + bone._shearX = bone._data._shearX; + bone._shearY = bone._data._shearY; + return; + case MixBlend_First: + bone._shearX += (bone._data._shearX - bone._shearX) * alpha; + bone._shearY += (bone._data._shearY - bone._shearY) * alpha; + default: { + } + } + return; + } - float x, y; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - x = _frames[_frames.size() + PREV_X]; - y = _frames[_frames.size() + PREV_Y]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - x = _frames[frame + PREV_X]; - y = _frames[frame + PREV_Y]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float x, y; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + x = _frames[_frames.size() + PREV_X]; + y = _frames[_frames.size() + PREV_Y]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + x = _frames[frame + PREV_X]; + y = _frames[frame + PREV_Y]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - x = x + (_frames[frame + X] - x) * percent; - y = y + (_frames[frame + Y] - y) * percent; - } + x = x + (_frames[frame + X] - x) * percent; + y = y + (_frames[frame + Y] - y) * percent; + } - switch (blend) { - case MixBlend_Setup: - bone._shearX = bone._data._shearX + x * alpha; - bone._shearY = bone._data._shearY + y * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - bone._shearX += (bone._data._shearX + x - bone._shearX) * alpha; - bone._shearY += (bone._data._shearY + y - bone._shearY) * alpha; - break; - case MixBlend_Add: - bone._shearX += x * alpha; - bone._shearY += y * alpha; - } + switch (blend) { + case MixBlend_Setup: + bone._shearX = bone._data._shearX + x * alpha; + bone._shearY = bone._data._shearY + y * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + bone._shearX += (bone._data._shearX + x - bone._shearX) * alpha; + bone._shearY += (bone._data._shearY + y - bone._shearY) * alpha; + break; + case MixBlend_Add: + bone._shearX += x * alpha; + bone._shearY += y * alpha; + } } int ShearTimeline::getPropertyId() { - return ((int) TimelineType_Shear << 24) + _boneIndex; + return ((int)TimelineType_Shear << 24) + _boneIndex; } diff --git a/native/cocos/editor-support/spine/ShearTimeline.h b/native/cocos/editor-support/spine/ShearTimeline.h index 4f6f12f7e8..de00885826 100644 --- a/native/cocos/editor-support/spine/ShearTimeline.h +++ b/native/cocos/editor-support/spine/ShearTimeline.h @@ -33,19 +33,19 @@ #include namespace spine { - class SP_API ShearTimeline : public TranslateTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API ShearTimeline : public TranslateTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - explicit ShearTimeline(int frameCount); +public: + explicit ShearTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); - }; -} + virtual int getPropertyId(); +}; +} // namespace spine #endif /* Spine_ShearTimeline_h */ diff --git a/native/cocos/editor-support/spine/Skeleton.cpp b/native/cocos/editor-support/spine/Skeleton.cpp index d71207e973..7c8398b962 100644 --- a/native/cocos/editor-support/spine/Skeleton.cpp +++ b/native/cocos/editor-support/spine/Skeleton.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -57,626 +57,625 @@ using namespace spine; -Skeleton::Skeleton(SkeletonData *skeletonData) : - _data(skeletonData), - _skin(NULL), - _color(1, 1, 1, 1), - _time(0), - _scaleX(1), - _scaleY(1), - _x(0), - _y(0) { - _bones.ensureCapacity(_data->getBones().size()); - for (size_t i = 0; i < _data->getBones().size(); ++i) { - BoneData *data = _data->getBones()[i]; +Skeleton::Skeleton(SkeletonData *skeletonData) : _data(skeletonData), + _skin(NULL), + _color(1, 1, 1, 1), + _time(0), + _scaleX(1), + _scaleY(1), + _x(0), + _y(0) { + _bones.ensureCapacity(_data->getBones().size()); + for (size_t i = 0; i < _data->getBones().size(); ++i) { + BoneData *data = _data->getBones()[i]; - Bone *bone; - if (data->getParent() == NULL) { - bone = new(__FILE__, __LINE__) Bone(*data, *this, NULL); - } else { - Bone *parent = _bones[data->getParent()->getIndex()]; - bone = new(__FILE__, __LINE__) Bone(*data, *this, parent); - parent->getChildren().add(bone); - } + Bone *bone; + if (data->getParent() == NULL) { + bone = new (__FILE__, __LINE__) Bone(*data, *this, NULL); + } else { + Bone *parent = _bones[data->getParent()->getIndex()]; + bone = new (__FILE__, __LINE__) Bone(*data, *this, parent); + parent->getChildren().add(bone); + } - _bones.add(bone); - } + _bones.add(bone); + } - _slots.ensureCapacity(_data->getSlots().size()); - _drawOrder.ensureCapacity(_data->getSlots().size()); - for (size_t i = 0; i < _data->getSlots().size(); ++i) { - SlotData *data = _data->getSlots()[i]; + _slots.ensureCapacity(_data->getSlots().size()); + _drawOrder.ensureCapacity(_data->getSlots().size()); + for (size_t i = 0; i < _data->getSlots().size(); ++i) { + SlotData *data = _data->getSlots()[i]; - Bone *bone = _bones[data->getBoneData().getIndex()]; - Slot *slot = new(__FILE__, __LINE__) Slot(*data, *bone); + Bone *bone = _bones[data->getBoneData().getIndex()]; + Slot *slot = new (__FILE__, __LINE__) Slot(*data, *bone); - _slots.add(slot); - _drawOrder.add(slot); - } + _slots.add(slot); + _drawOrder.add(slot); + } - _ikConstraints.ensureCapacity(_data->getIkConstraints().size()); - for (size_t i = 0; i < _data->getIkConstraints().size(); ++i) { - IkConstraintData *data = _data->getIkConstraints()[i]; + _ikConstraints.ensureCapacity(_data->getIkConstraints().size()); + for (size_t i = 0; i < _data->getIkConstraints().size(); ++i) { + IkConstraintData *data = _data->getIkConstraints()[i]; - IkConstraint *constraint = new(__FILE__, __LINE__) IkConstraint(*data, *this); + IkConstraint *constraint = new (__FILE__, __LINE__) IkConstraint(*data, *this); - _ikConstraints.add(constraint); - } + _ikConstraints.add(constraint); + } - _transformConstraints.ensureCapacity(_data->getTransformConstraints().size()); - for (size_t i = 0; i < _data->getTransformConstraints().size(); ++i) { - TransformConstraintData *data = _data->getTransformConstraints()[i]; + _transformConstraints.ensureCapacity(_data->getTransformConstraints().size()); + for (size_t i = 0; i < _data->getTransformConstraints().size(); ++i) { + TransformConstraintData *data = _data->getTransformConstraints()[i]; - TransformConstraint *constraint = new(__FILE__, __LINE__) TransformConstraint(*data, *this); + TransformConstraint *constraint = new (__FILE__, __LINE__) TransformConstraint(*data, *this); - _transformConstraints.add(constraint); - } + _transformConstraints.add(constraint); + } - _pathConstraints.ensureCapacity(_data->getPathConstraints().size()); - for (size_t i = 0; i < _data->getPathConstraints().size(); ++i) { - PathConstraintData *data = _data->getPathConstraints()[i]; + _pathConstraints.ensureCapacity(_data->getPathConstraints().size()); + for (size_t i = 0; i < _data->getPathConstraints().size(); ++i) { + PathConstraintData *data = _data->getPathConstraints()[i]; - PathConstraint *constraint = new(__FILE__, __LINE__) PathConstraint(*data, *this); + PathConstraint *constraint = new (__FILE__, __LINE__) PathConstraint(*data, *this); - _pathConstraints.add(constraint); - } + _pathConstraints.add(constraint); + } - updateCache(); + updateCache(); } Skeleton::~Skeleton() { - ContainerUtil::cleanUpVectorOfPointers(_bones); - ContainerUtil::cleanUpVectorOfPointers(_slots); - ContainerUtil::cleanUpVectorOfPointers(_ikConstraints); - ContainerUtil::cleanUpVectorOfPointers(_transformConstraints); - ContainerUtil::cleanUpVectorOfPointers(_pathConstraints); + ContainerUtil::cleanUpVectorOfPointers(_bones); + ContainerUtil::cleanUpVectorOfPointers(_slots); + ContainerUtil::cleanUpVectorOfPointers(_ikConstraints); + ContainerUtil::cleanUpVectorOfPointers(_transformConstraints); + ContainerUtil::cleanUpVectorOfPointers(_pathConstraints); } void Skeleton::updateCache() { - _updateCache.clear(); - _updateCacheReset.clear(); + _updateCache.clear(); + _updateCacheReset.clear(); - for (size_t i = 0, n = _bones.size(); i < n; ++i) { - Bone* bone = _bones[i]; - bone->_sorted = bone->_data.isSkinRequired(); - bone->_active = !bone->_sorted; - } + for (size_t i = 0, n = _bones.size(); i < n; ++i) { + Bone *bone = _bones[i]; + bone->_sorted = bone->_data.isSkinRequired(); + bone->_active = !bone->_sorted; + } - if (_skin) { - Vector& skinBones = _skin->getBones(); - for (size_t i = 0, n = skinBones.size(); i < n; i++) { - Bone* bone = _bones[skinBones[i]->getIndex()]; - do { - bone->_sorted = false; - bone->_active = true; - bone = bone->_parent; - } while (bone); - } - } + if (_skin) { + Vector &skinBones = _skin->getBones(); + for (size_t i = 0, n = skinBones.size(); i < n; i++) { + Bone *bone = _bones[skinBones[i]->getIndex()]; + do { + bone->_sorted = false; + bone->_active = true; + bone = bone->_parent; + } while (bone); + } + } - size_t ikCount = _ikConstraints.size(); - size_t transformCount = _transformConstraints.size(); - size_t pathCount = _pathConstraints.size(); + size_t ikCount = _ikConstraints.size(); + size_t transformCount = _transformConstraints.size(); + size_t pathCount = _pathConstraints.size(); - size_t constraintCount = ikCount + transformCount + pathCount; + size_t constraintCount = ikCount + transformCount + pathCount; - size_t i = 0; - continue_outer: - for (; i < constraintCount; ++i) { - for (size_t ii = 0; ii < ikCount; ++ii) { - IkConstraint *constraint = _ikConstraints[ii]; - if (constraint->getData().getOrder() == i) { - sortIkConstraint(constraint); - i++; - goto continue_outer; - } - } + size_t i = 0; +continue_outer: + for (; i < constraintCount; ++i) { + for (size_t ii = 0; ii < ikCount; ++ii) { + IkConstraint *constraint = _ikConstraints[ii]; + if (constraint->getData().getOrder() == i) { + sortIkConstraint(constraint); + i++; + goto continue_outer; + } + } - for (size_t ii = 0; ii < transformCount; ++ii) { - TransformConstraint *constraint = _transformConstraints[ii]; - if (constraint->getData().getOrder() == i) { - sortTransformConstraint(constraint); - i++; - goto continue_outer; - } - } + for (size_t ii = 0; ii < transformCount; ++ii) { + TransformConstraint *constraint = _transformConstraints[ii]; + if (constraint->getData().getOrder() == i) { + sortTransformConstraint(constraint); + i++; + goto continue_outer; + } + } - for (size_t ii = 0; ii < pathCount; ++ii) { - PathConstraint *constraint = _pathConstraints[ii]; - if (constraint->getData().getOrder() == i) { - sortPathConstraint(constraint); - i++; - goto continue_outer; - } - } - } + for (size_t ii = 0; ii < pathCount; ++ii) { + PathConstraint *constraint = _pathConstraints[ii]; + if (constraint->getData().getOrder() == i) { + sortPathConstraint(constraint); + i++; + goto continue_outer; + } + } + } - size_t n = _bones.size(); - for (i = 0; i < n; ++i) { - sortBone(_bones[i]); - } + size_t n = _bones.size(); + for (i = 0; i < n; ++i) { + sortBone(_bones[i]); + } } void Skeleton::printUpdateCache() { - for (size_t i = 0; i < _updateCache.size(); i++) { - Updatable *updatable = _updateCache[i]; - if (updatable->getRTTI().isExactly(Bone::rtti)) { - printf("bone %s\n", ((Bone *) updatable)->getData().getName().buffer()); - } else if (updatable->getRTTI().isExactly(TransformConstraint::rtti)) { - printf("transform constraint %s\n", ((TransformConstraint *) updatable)->getData().getName().buffer()); - } else if (updatable->getRTTI().isExactly(IkConstraint::rtti)) { - printf("ik constraint %s\n", ((IkConstraint *) updatable)->getData().getName().buffer()); - } else if (updatable->getRTTI().isExactly(PathConstraint::rtti)) { - printf("path constraint %s\n", ((PathConstraint *) updatable)->getData().getName().buffer()); - } - } + for (size_t i = 0; i < _updateCache.size(); i++) { + Updatable *updatable = _updateCache[i]; + if (updatable->getRTTI().isExactly(Bone::rtti)) { + printf("bone %s\n", ((Bone *)updatable)->getData().getName().buffer()); + } else if (updatable->getRTTI().isExactly(TransformConstraint::rtti)) { + printf("transform constraint %s\n", ((TransformConstraint *)updatable)->getData().getName().buffer()); + } else if (updatable->getRTTI().isExactly(IkConstraint::rtti)) { + printf("ik constraint %s\n", ((IkConstraint *)updatable)->getData().getName().buffer()); + } else if (updatable->getRTTI().isExactly(PathConstraint::rtti)) { + printf("path constraint %s\n", ((PathConstraint *)updatable)->getData().getName().buffer()); + } + } } void Skeleton::updateWorldTransform() { - for (size_t i = 0, n = _updateCacheReset.size(); i < n; ++i) { - Bone *boneP = _updateCacheReset[i]; - Bone &bone = *boneP; - bone._ax = bone._x; - bone._ay = bone._y; - bone._arotation = bone._rotation; - bone._ascaleX = bone._scaleX; - bone._ascaleY = bone._scaleY; - bone._ashearX = bone._shearX; - bone._ashearY = bone._shearY; - bone._appliedValid = true; - } + for (size_t i = 0, n = _updateCacheReset.size(); i < n; ++i) { + Bone *boneP = _updateCacheReset[i]; + Bone &bone = *boneP; + bone._ax = bone._x; + bone._ay = bone._y; + bone._arotation = bone._rotation; + bone._ascaleX = bone._scaleX; + bone._ascaleY = bone._scaleY; + bone._ashearX = bone._shearX; + bone._ashearY = bone._shearY; + bone._appliedValid = true; + } - for (size_t i = 0, n = _updateCache.size(); i < n; ++i) { - _updateCache[i]->update(); - } + for (size_t i = 0, n = _updateCache.size(); i < n; ++i) { + _updateCache[i]->update(); + } } void Skeleton::setToSetupPose() { - setBonesToSetupPose(); - setSlotsToSetupPose(); + setBonesToSetupPose(); + setSlotsToSetupPose(); } void Skeleton::setBonesToSetupPose() { - for (size_t i = 0, n = _bones.size(); i < n; ++i) { - _bones[i]->setToSetupPose(); - } + for (size_t i = 0, n = _bones.size(); i < n; ++i) { + _bones[i]->setToSetupPose(); + } - for (size_t i = 0, n = _ikConstraints.size(); i < n; ++i) { - IkConstraint *constraintP = _ikConstraints[i]; - IkConstraint &constraint = *constraintP; + for (size_t i = 0, n = _ikConstraints.size(); i < n; ++i) { + IkConstraint *constraintP = _ikConstraints[i]; + IkConstraint &constraint = *constraintP; - constraint._bendDirection = constraint._data._bendDirection; - constraint._compress = constraint._data._compress; - constraint._stretch = constraint._data._stretch; - constraint._mix = constraint._data._mix; - constraint._softness = constraint._data._softness; - } + constraint._bendDirection = constraint._data._bendDirection; + constraint._compress = constraint._data._compress; + constraint._stretch = constraint._data._stretch; + constraint._mix = constraint._data._mix; + constraint._softness = constraint._data._softness; + } - for (size_t i = 0, n = _transformConstraints.size(); i < n; ++i) { - TransformConstraint *constraintP = _transformConstraints[i]; - TransformConstraint &constraint = *constraintP; - TransformConstraintData &constraintData = constraint._data; + for (size_t i = 0, n = _transformConstraints.size(); i < n; ++i) { + TransformConstraint *constraintP = _transformConstraints[i]; + TransformConstraint &constraint = *constraintP; + TransformConstraintData &constraintData = constraint._data; - constraint._rotateMix = constraintData._rotateMix; - constraint._translateMix = constraintData._translateMix; - constraint._scaleMix = constraintData._scaleMix; - constraint._shearMix = constraintData._shearMix; - } + constraint._rotateMix = constraintData._rotateMix; + constraint._translateMix = constraintData._translateMix; + constraint._scaleMix = constraintData._scaleMix; + constraint._shearMix = constraintData._shearMix; + } - for (size_t i = 0, n = _pathConstraints.size(); i < n; ++i) { - PathConstraint *constraintP = _pathConstraints[i]; - PathConstraint &constraint = *constraintP; - PathConstraintData &constraintData = constraint._data; + for (size_t i = 0, n = _pathConstraints.size(); i < n; ++i) { + PathConstraint *constraintP = _pathConstraints[i]; + PathConstraint &constraint = *constraintP; + PathConstraintData &constraintData = constraint._data; - constraint._position = constraintData._position; - constraint._spacing = constraintData._spacing; - constraint._rotateMix = constraintData._rotateMix; - constraint._translateMix = constraintData._translateMix; - } + constraint._position = constraintData._position; + constraint._spacing = constraintData._spacing; + constraint._rotateMix = constraintData._rotateMix; + constraint._translateMix = constraintData._translateMix; + } } void Skeleton::setSlotsToSetupPose() { - _drawOrder.clear(); - for (size_t i = 0, n = _slots.size(); i < n; ++i) { - _drawOrder.add(_slots[i]); - } + _drawOrder.clear(); + for (size_t i = 0, n = _slots.size(); i < n; ++i) { + _drawOrder.add(_slots[i]); + } - for (size_t i = 0, n = _slots.size(); i < n; ++i) { - _slots[i]->setToSetupPose(); - } + for (size_t i = 0, n = _slots.size(); i < n; ++i) { + _slots[i]->setToSetupPose(); + } } Bone *Skeleton::findBone(const String &boneName) { - return ContainerUtil::findWithDataName(_bones, boneName); + return ContainerUtil::findWithDataName(_bones, boneName); } int Skeleton::findBoneIndex(const String &boneName) { - return ContainerUtil::findIndexWithDataName(_bones, boneName); + return ContainerUtil::findIndexWithDataName(_bones, boneName); } Slot *Skeleton::findSlot(const String &slotName) { - return ContainerUtil::findWithDataName(_slots, slotName); + return ContainerUtil::findWithDataName(_slots, slotName); } int Skeleton::findSlotIndex(const String &slotName) { - return ContainerUtil::findIndexWithDataName(_slots, slotName); + return ContainerUtil::findIndexWithDataName(_slots, slotName); } void Skeleton::setSkin(const String &skinName) { - Skin *foundSkin = _data->findSkin(skinName); + Skin *foundSkin = _data->findSkin(skinName); - assert(foundSkin != NULL); + assert(foundSkin != NULL); - setSkin(foundSkin); + setSkin(foundSkin); } void Skeleton::setSkin(Skin *newSkin) { - if (_skin == newSkin) return; - if (newSkin != NULL) { - if (_skin != NULL) { - Skeleton &thisRef = *this; - newSkin->attachAll(thisRef, *_skin); - } else { - for (size_t i = 0, n = _slots.size(); i < n; ++i) { - Slot *slotP = _slots[i]; - Slot &slot = *slotP; - const String &name = slot._data.getAttachmentName(); - if (name.length() > 0) { - Attachment *attachment = newSkin->getAttachment(i, name); - if (attachment != NULL) { - slot.setAttachment(attachment); - } - } - } - } - } + if (_skin == newSkin) return; + if (newSkin != NULL) { + if (_skin != NULL) { + Skeleton &thisRef = *this; + newSkin->attachAll(thisRef, *_skin); + } else { + for (size_t i = 0, n = _slots.size(); i < n; ++i) { + Slot *slotP = _slots[i]; + Slot &slot = *slotP; + const String &name = slot._data.getAttachmentName(); + if (name.length() > 0) { + Attachment *attachment = newSkin->getAttachment(i, name); + if (attachment != NULL) { + slot.setAttachment(attachment); + } + } + } + } + } - _skin = newSkin; - updateCache(); + _skin = newSkin; + updateCache(); } Attachment *Skeleton::getAttachment(const String &slotName, const String &attachmentName) { - return getAttachment(_data->findSlotIndex(slotName), attachmentName); + return getAttachment(_data->findSlotIndex(slotName), attachmentName); } Attachment *Skeleton::getAttachment(int slotIndex, const String &attachmentName) { - assert(attachmentName.length() > 0); + assert(attachmentName.length() > 0); - if (_skin != NULL) { - Attachment *attachment = _skin->getAttachment(slotIndex, attachmentName); - if (attachment != NULL) { - return attachment; - } - } + if (_skin != NULL) { + Attachment *attachment = _skin->getAttachment(slotIndex, attachmentName); + if (attachment != NULL) { + return attachment; + } + } - return _data->getDefaultSkin() != NULL ? _data->getDefaultSkin()->getAttachment(slotIndex, attachmentName) : NULL; + return _data->getDefaultSkin() != NULL ? _data->getDefaultSkin()->getAttachment(slotIndex, attachmentName) : NULL; } void Skeleton::setAttachment(const String &slotName, const String &attachmentName) { - assert(slotName.length() > 0); + assert(slotName.length() > 0); - for (size_t i = 0, n = _slots.size(); i < n; ++i) { - Slot *slot = _slots[i]; - if (slot->_data.getName() == slotName) { - Attachment *attachment = NULL; - if (attachmentName.length() > 0) { - attachment = getAttachment(i, attachmentName); + for (size_t i = 0, n = _slots.size(); i < n; ++i) { + Slot *slot = _slots[i]; + if (slot->_data.getName() == slotName) { + Attachment *attachment = NULL; + if (attachmentName.length() > 0) { + attachment = getAttachment(i, attachmentName); - assert(attachment != NULL); - } + assert(attachment != NULL); + } - slot->setAttachment(attachment); + slot->setAttachment(attachment); - return; - } - } + return; + } + } - printf("Slot not found: %s", slotName.buffer()); + printf("Slot not found: %s", slotName.buffer()); - assert(false); + assert(false); } IkConstraint *Skeleton::findIkConstraint(const String &constraintName) { - assert(constraintName.length() > 0); + assert(constraintName.length() > 0); - for (size_t i = 0, n = _ikConstraints.size(); i < n; ++i) { - IkConstraint *ikConstraint = _ikConstraints[i]; - if (ikConstraint->_data.getName() == constraintName) { - return ikConstraint; - } - } - return NULL; + for (size_t i = 0, n = _ikConstraints.size(); i < n; ++i) { + IkConstraint *ikConstraint = _ikConstraints[i]; + if (ikConstraint->_data.getName() == constraintName) { + return ikConstraint; + } + } + return NULL; } TransformConstraint *Skeleton::findTransformConstraint(const String &constraintName) { - assert(constraintName.length() > 0); + assert(constraintName.length() > 0); - for (size_t i = 0, n = _transformConstraints.size(); i < n; ++i) { - TransformConstraint *transformConstraint = _transformConstraints[i]; - if (transformConstraint->_data.getName() == constraintName) { - return transformConstraint; - } - } + for (size_t i = 0, n = _transformConstraints.size(); i < n; ++i) { + TransformConstraint *transformConstraint = _transformConstraints[i]; + if (transformConstraint->_data.getName() == constraintName) { + return transformConstraint; + } + } - return NULL; + return NULL; } PathConstraint *Skeleton::findPathConstraint(const String &constraintName) { - assert(constraintName.length() > 0); + assert(constraintName.length() > 0); - for (size_t i = 0, n = _pathConstraints.size(); i < n; ++i) { - PathConstraint *constraint = _pathConstraints[i]; - if (constraint->_data.getName() == constraintName) { - return constraint; - } - } + for (size_t i = 0, n = _pathConstraints.size(); i < n; ++i) { + PathConstraint *constraint = _pathConstraints[i]; + if (constraint->_data.getName() == constraintName) { + return constraint; + } + } - return NULL; + return NULL; } void Skeleton::update(float delta) { - _time += delta; + _time += delta; } void Skeleton::getBounds(float &outX, float &outY, float &outWidth, float &outHeight, Vector &outVertexBuffer) { - float minX = FLT_MAX; - float minY = FLT_MAX; - float maxX = FLT_MIN; - float maxY = FLT_MIN; + float minX = FLT_MAX; + float minY = FLT_MAX; + float maxX = FLT_MIN; + float maxY = FLT_MIN; - for (size_t i = 0; i < _drawOrder.size(); ++i) { - Slot *slot = _drawOrder[i]; - if (!slot->_bone._active) continue; - size_t verticesLength = 0; - Attachment *attachment = slot->getAttachment(); + for (size_t i = 0; i < _drawOrder.size(); ++i) { + Slot *slot = _drawOrder[i]; + if (!slot->_bone._active) continue; + size_t verticesLength = 0; + Attachment *attachment = slot->getAttachment(); - if (attachment != NULL && attachment->getRTTI().instanceOf(RegionAttachment::rtti)) { - RegionAttachment *regionAttachment = static_cast(attachment); + if (attachment != NULL && attachment->getRTTI().instanceOf(RegionAttachment::rtti)) { + RegionAttachment *regionAttachment = static_cast(attachment); - verticesLength = 8; - if (outVertexBuffer.size() < 8) { - outVertexBuffer.setSize(8, 0); - } - regionAttachment->computeWorldVertices(slot->getBone(), outVertexBuffer, 0); - } else if (attachment != NULL && attachment->getRTTI().instanceOf(MeshAttachment::rtti)) { - MeshAttachment *mesh = static_cast(attachment); + verticesLength = 8; + if (outVertexBuffer.size() < 8) { + outVertexBuffer.setSize(8, 0); + } + regionAttachment->computeWorldVertices(slot->getBone(), outVertexBuffer, 0); + } else if (attachment != NULL && attachment->getRTTI().instanceOf(MeshAttachment::rtti)) { + MeshAttachment *mesh = static_cast(attachment); - verticesLength = mesh->getWorldVerticesLength(); - if (outVertexBuffer.size() < verticesLength) { - outVertexBuffer.setSize(verticesLength, 0); - } + verticesLength = mesh->getWorldVerticesLength(); + if (outVertexBuffer.size() < verticesLength) { + outVertexBuffer.setSize(verticesLength, 0); + } - mesh->computeWorldVertices(*slot, 0, verticesLength, outVertexBuffer, 0); - } + mesh->computeWorldVertices(*slot, 0, verticesLength, outVertexBuffer, 0); + } - for (size_t ii = 0; ii < verticesLength; ii += 2) { - float vx = outVertexBuffer[ii]; - float vy = outVertexBuffer[ii + 1]; + for (size_t ii = 0; ii < verticesLength; ii += 2) { + float vx = outVertexBuffer[ii]; + float vy = outVertexBuffer[ii + 1]; - minX = MathUtil::min(minX, vx); - minY = MathUtil::min(minY, vy); - maxX = MathUtil::max(maxX, vx); - maxY = MathUtil::max(maxY, vy); - } - } + minX = MathUtil::min(minX, vx); + minY = MathUtil::min(minY, vy); + maxX = MathUtil::max(maxX, vx); + maxY = MathUtil::max(maxY, vy); + } + } - outX = minX; - outY = minY; - outWidth = maxX - minX; - outHeight = maxY - minY; + outX = minX; + outY = minY; + outWidth = maxX - minX; + outHeight = maxY - minY; } Bone *Skeleton::getRootBone() { - return _bones.size() == 0 ? NULL : _bones[0]; + return _bones.size() == 0 ? NULL : _bones[0]; } SkeletonData *Skeleton::getData() { - return _data; + return _data; } Vector &Skeleton::getBones() { - return _bones; + return _bones; } Vector &Skeleton::getUpdateCacheList() { - return _updateCache; + return _updateCache; } Vector &Skeleton::getSlots() { - return _slots; + return _slots; } Vector &Skeleton::getDrawOrder() { - return _drawOrder; + return _drawOrder; } Vector &Skeleton::getIkConstraints() { - return _ikConstraints; + return _ikConstraints; } Vector &Skeleton::getPathConstraints() { - return _pathConstraints; + return _pathConstraints; } Vector &Skeleton::getTransformConstraints() { - return _transformConstraints; + return _transformConstraints; } Skin *Skeleton::getSkin() { - return _skin; + return _skin; } Color &Skeleton::getColor() { - return _color; + return _color; } float Skeleton::getTime() { - return _time; + return _time; } void Skeleton::setTime(float inValue) { - _time = inValue; + _time = inValue; } void Skeleton::setPosition(float x, float y) { - _x = x; - _y = y; + _x = x; + _y = y; } float Skeleton::getX() { - return _x; + return _x; } void Skeleton::setX(float inValue) { - _x = inValue; + _x = inValue; } float Skeleton::getY() { - return _y; + return _y; } void Skeleton::setY(float inValue) { - _y = inValue; + _y = inValue; } float Skeleton::getScaleX() { - return _scaleX; + return _scaleX; } void Skeleton::setScaleX(float inValue) { - _scaleX = inValue; + _scaleX = inValue; } float Skeleton::getScaleY() { - return _scaleY * (Bone::isYDown() ? -1 : 1); + return _scaleY * (Bone::isYDown() ? -1 : 1); } void Skeleton::setScaleY(float inValue) { - _scaleY = inValue; + _scaleY = inValue; } void Skeleton::sortIkConstraint(IkConstraint *constraint) { - constraint->_active = constraint->_target->_active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); - if (!constraint->_active) return; + constraint->_active = constraint->_target->_active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); + if (!constraint->_active) return; - Bone *target = constraint->getTarget(); - sortBone(target); + Bone *target = constraint->getTarget(); + sortBone(target); - Vector &constrained = constraint->getBones(); - Bone *parent = constrained[0]; - sortBone(parent); + Vector &constrained = constraint->getBones(); + Bone *parent = constrained[0]; + sortBone(parent); - if (constrained.size() > 1) { - Bone *child = constrained[constrained.size() - 1]; - if (!_updateCache.contains(child)) _updateCacheReset.add(child); - } + if (constrained.size() > 1) { + Bone *child = constrained[constrained.size() - 1]; + if (!_updateCache.contains(child)) _updateCacheReset.add(child); + } - _updateCache.add(constraint); + _updateCache.add(constraint); - sortReset(parent->getChildren()); - constrained[constrained.size() - 1]->_sorted = true; + sortReset(parent->getChildren()); + constrained[constrained.size() - 1]->_sorted = true; } void Skeleton::sortPathConstraint(PathConstraint *constraint) { - constraint->_active = constraint->_target->_bone._active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); - if (!constraint->_active) return; + constraint->_active = constraint->_target->_bone._active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); + if (!constraint->_active) return; - Slot *slot = constraint->getTarget(); - int slotIndex = slot->getData().getIndex(); - Bone &slotBone = slot->getBone(); - if (_skin != NULL) sortPathConstraintAttachment(_skin, slotIndex, slotBone); - if (_data->_defaultSkin != NULL && _data->_defaultSkin != _skin) - sortPathConstraintAttachment(_data->_defaultSkin, slotIndex, slotBone); - for (size_t ii = 0, nn = _data->_skins.size(); ii < nn; ii++) - sortPathConstraintAttachment(_data->_skins[ii], slotIndex, slotBone); + Slot *slot = constraint->getTarget(); + int slotIndex = slot->getData().getIndex(); + Bone &slotBone = slot->getBone(); + if (_skin != NULL) sortPathConstraintAttachment(_skin, slotIndex, slotBone); + if (_data->_defaultSkin != NULL && _data->_defaultSkin != _skin) + sortPathConstraintAttachment(_data->_defaultSkin, slotIndex, slotBone); + for (size_t ii = 0, nn = _data->_skins.size(); ii < nn; ii++) + sortPathConstraintAttachment(_data->_skins[ii], slotIndex, slotBone); - Attachment *attachment = slot->getAttachment(); - if (attachment != NULL && attachment->getRTTI().instanceOf(PathAttachment::rtti)) - sortPathConstraintAttachment(attachment, slotBone); + Attachment *attachment = slot->getAttachment(); + if (attachment != NULL && attachment->getRTTI().instanceOf(PathAttachment::rtti)) + sortPathConstraintAttachment(attachment, slotBone); - Vector &constrained = constraint->getBones(); - size_t boneCount = constrained.size(); - for (size_t i = 0; i < boneCount; ++i) { - sortBone(constrained[i]); - } + Vector &constrained = constraint->getBones(); + size_t boneCount = constrained.size(); + for (size_t i = 0; i < boneCount; ++i) { + sortBone(constrained[i]); + } - _updateCache.add(constraint); + _updateCache.add(constraint); - for (size_t i = 0; i < boneCount; i++) - sortReset(constrained[i]->getChildren()); - for (size_t i = 0; i < boneCount; i++) - constrained[i]->_sorted = true; + for (size_t i = 0; i < boneCount; i++) + sortReset(constrained[i]->getChildren()); + for (size_t i = 0; i < boneCount; i++) + constrained[i]->_sorted = true; } void Skeleton::sortTransformConstraint(TransformConstraint *constraint) { - constraint->_active = constraint->_target->_active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); - if (!constraint->_active) return; + constraint->_active = constraint->_target->_active && (!constraint->_data.isSkinRequired() || (_skin && _skin->_constraints.contains(&constraint->_data))); + if (!constraint->_active) return; - sortBone(constraint->getTarget()); + sortBone(constraint->getTarget()); - Vector &constrained = constraint->getBones(); - size_t boneCount = constrained.size(); - if (constraint->_data.isLocal()) { - for (size_t i = 0; i < boneCount; i++) { - Bone *child = constrained[i]; - sortBone(child->getParent()); - if (!_updateCache.contains(child)) _updateCacheReset.add(child); - } - } else { - for (size_t i = 0; i < boneCount; ++i) { - sortBone(constrained[i]); - } - } + Vector &constrained = constraint->getBones(); + size_t boneCount = constrained.size(); + if (constraint->_data.isLocal()) { + for (size_t i = 0; i < boneCount; i++) { + Bone *child = constrained[i]; + sortBone(child->getParent()); + if (!_updateCache.contains(child)) _updateCacheReset.add(child); + } + } else { + for (size_t i = 0; i < boneCount; ++i) { + sortBone(constrained[i]); + } + } - _updateCache.add(constraint); + _updateCache.add(constraint); - for (size_t i = 0; i < boneCount; ++i) - sortReset(constrained[i]->getChildren()); - for (size_t i = 0; i < boneCount; ++i) - constrained[i]->_sorted = true; + for (size_t i = 0; i < boneCount; ++i) + sortReset(constrained[i]->getChildren()); + for (size_t i = 0; i < boneCount; ++i) + constrained[i]->_sorted = true; } void Skeleton::sortPathConstraintAttachment(Skin *skin, size_t slotIndex, Bone &slotBone) { - Skin::AttachmentMap::Entries attachments = skin->getAttachments(); + Skin::AttachmentMap::Entries attachments = skin->getAttachments(); - while (attachments.hasNext()) { - Skin::AttachmentMap::Entry entry = attachments.next(); - if (entry._slotIndex == slotIndex) { - Attachment *value = entry._attachment; - sortPathConstraintAttachment(value, slotBone); - } - } + while (attachments.hasNext()) { + Skin::AttachmentMap::Entry entry = attachments.next(); + if (entry._slotIndex == slotIndex) { + Attachment *value = entry._attachment; + sortPathConstraintAttachment(value, slotBone); + } + } } void Skeleton::sortPathConstraintAttachment(Attachment *attachment, Bone &slotBone) { - if (attachment == NULL || !attachment->getRTTI().instanceOf(PathAttachment::rtti)) return; - Vector &pathBones = static_cast(attachment)->getBones(); - if (pathBones.size() == 0) - sortBone(&slotBone); - else { - for (size_t i = 0, n = pathBones.size(); i < n;) { - size_t nn = pathBones[i++]; - nn += i; - while (i < nn) { - sortBone(_bones[pathBones[i++]]); - } - } - } + if (attachment == NULL || !attachment->getRTTI().instanceOf(PathAttachment::rtti)) return; + Vector &pathBones = static_cast(attachment)->getBones(); + if (pathBones.size() == 0) + sortBone(&slotBone); + else { + for (size_t i = 0, n = pathBones.size(); i < n;) { + size_t nn = pathBones[i++]; + nn += i; + while (i < nn) { + sortBone(_bones[pathBones[i++]]); + } + } + } } void Skeleton::sortBone(Bone *bone) { - if (bone->_sorted) return; - Bone *parent = bone->_parent; - if (parent != NULL) sortBone(parent); - bone->_sorted = true; - _updateCache.add(bone); + if (bone->_sorted) return; + Bone *parent = bone->_parent; + if (parent != NULL) sortBone(parent); + bone->_sorted = true; + _updateCache.add(bone); } void Skeleton::sortReset(Vector &bones) { - for (size_t i = 0, n = bones.size(); i < n; ++i) { - Bone *bone = bones[i]; - if (!bone->_active) continue; - if (bone->_sorted) sortReset(bone->getChildren()); - bone->_sorted = false; - } + for (size_t i = 0, n = bones.size(); i < n; ++i) { + Bone *bone = bones[i]; + if (!bone->_active) continue; + if (bone->_sorted) sortReset(bone->getChildren()); + bone->_sorted = false; + } } diff --git a/native/cocos/editor-support/spine/Skeleton.h b/native/cocos/editor-support/spine/Skeleton.h index 27a3d83931..80c6e2ff8d 100644 --- a/native/cocos/editor-support/spine/Skeleton.h +++ b/native/cocos/editor-support/spine/Skeleton.h @@ -56,188 +56,188 @@ class Skin; class Attachment; class SP_API Skeleton : public SpineObject { - friend class AnimationState; + friend class AnimationState; - friend class SkeletonBounds; + friend class SkeletonBounds; - friend class SkeletonClipping; + friend class SkeletonClipping; - friend class AttachmentTimeline; + friend class AttachmentTimeline; - friend class ColorTimeline; + friend class ColorTimeline; - friend class DeformTimeline; + friend class DeformTimeline; - friend class DrawOrderTimeline; + friend class DrawOrderTimeline; - friend class EventTimeline; + friend class EventTimeline; - friend class IkConstraintTimeline; + friend class IkConstraintTimeline; - friend class PathConstraintMixTimeline; + friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; + friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; + friend class PathConstraintSpacingTimeline; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TransformConstraintTimeline; + friend class TransformConstraintTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; - friend class TwoColorTimeline; + friend class TwoColorTimeline; public: - explicit Skeleton(SkeletonData *skeletonData); + explicit Skeleton(SkeletonData *skeletonData); - ~Skeleton(); + ~Skeleton(); - /// Caches information about bones and constraints. Must be called if bones, constraints or weighted path attachments are added - /// or removed. - void updateCache(); + /// Caches information about bones and constraints. Must be called if bones, constraints or weighted path attachments are added + /// or removed. + void updateCache(); - void printUpdateCache(); + void printUpdateCache(); - /// Updates the world transform for each bone and applies constraints. - void updateWorldTransform(); + /// Updates the world transform for each bone and applies constraints. + void updateWorldTransform(); - /// Sets the bones, constraints, and slots to their setup pose values. - void setToSetupPose(); + /// Sets the bones, constraints, and slots to their setup pose values. + void setToSetupPose(); - /// Sets the bones and constraints to their setup pose values. - void setBonesToSetupPose(); + /// Sets the bones and constraints to their setup pose values. + void setBonesToSetupPose(); - void setSlotsToSetupPose(); + void setSlotsToSetupPose(); - /// @return May be NULL. - Bone *findBone(const String &boneName); + /// @return May be NULL. + Bone *findBone(const String &boneName); - /// @return -1 if the bone was not found. - int findBoneIndex(const String &boneName); + /// @return -1 if the bone was not found. + int findBoneIndex(const String &boneName); - /// @return May be NULL. - Slot *findSlot(const String &slotName); + /// @return May be NULL. + Slot *findSlot(const String &slotName); - /// @return -1 if the bone was not found. - int findSlotIndex(const String &slotName); + /// @return -1 if the bone was not found. + int findSlotIndex(const String &slotName); - /// Sets a skin by name (see setSkin). - void setSkin(const String &skinName); + /// Sets a skin by name (see setSkin). + void setSkin(const String &skinName); - /// Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. - /// If there was no old skin, each slot's setup mode attachment is attached from the new skin. - /// After changing the skin, the visible attachments can be reset to those attached in the setup pose by calling - /// See Skeleton::setSlotsToSetupPose() - /// Also, often AnimationState::apply(Skeleton&) is called before the next time the - /// skeleton is rendered to allow any attachment keys in the current animation(s) to hide or show attachments from the new skin. - /// @param newSkin May be NULL. - void setSkin(Skin *newSkin); + /// Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. + /// If there was no old skin, each slot's setup mode attachment is attached from the new skin. + /// After changing the skin, the visible attachments can be reset to those attached in the setup pose by calling + /// See Skeleton::setSlotsToSetupPose() + /// Also, often AnimationState::apply(Skeleton&) is called before the next time the + /// skeleton is rendered to allow any attachment keys in the current animation(s) to hide or show attachments from the new skin. + /// @param newSkin May be NULL. + void setSkin(Skin *newSkin); - /// @return May be NULL. - Attachment *getAttachment(const String &slotName, const String &attachmentName); + /// @return May be NULL. + Attachment *getAttachment(const String &slotName, const String &attachmentName); - /// @return May be NULL. - Attachment *getAttachment(int slotIndex, const String &attachmentName); + /// @return May be NULL. + Attachment *getAttachment(int slotIndex, const String &attachmentName); - /// @param attachmentName May be empty. - void setAttachment(const String &slotName, const String &attachmentName); + /// @param attachmentName May be empty. + void setAttachment(const String &slotName, const String &attachmentName); - /// @return May be NULL. - IkConstraint *findIkConstraint(const String &constraintName); + /// @return May be NULL. + IkConstraint *findIkConstraint(const String &constraintName); - /// @return May be NULL. - TransformConstraint *findTransformConstraint(const String &constraintName); + /// @return May be NULL. + TransformConstraint *findTransformConstraint(const String &constraintName); - /// @return May be NULL. - PathConstraint *findPathConstraint(const String &constraintName); + /// @return May be NULL. + PathConstraint *findPathConstraint(const String &constraintName); - void update(float delta); + void update(float delta); - /// Returns the axis aligned bounding box (AABB) of the region and mesh attachments for the current pose. - /// @param outX The horizontal distance between the skeleton origin and the left side of the AABB. - /// @param outY The vertical distance between the skeleton origin and the bottom side of the AABB. - /// @param outWidth The width of the AABB - /// @param outHeight The height of the AABB. - /// @param outVertexBuffer Reference to hold a Vector of floats. This method will assign it with new floats as needed. - void getBounds(float &outX, float &outY, float &outWidth, float &outHeight, Vector &outVertexBuffer); + /// Returns the axis aligned bounding box (AABB) of the region and mesh attachments for the current pose. + /// @param outX The horizontal distance between the skeleton origin and the left side of the AABB. + /// @param outY The vertical distance between the skeleton origin and the bottom side of the AABB. + /// @param outWidth The width of the AABB + /// @param outHeight The height of the AABB. + /// @param outVertexBuffer Reference to hold a Vector of floats. This method will assign it with new floats as needed. + void getBounds(float &outX, float &outY, float &outWidth, float &outHeight, Vector &outVertexBuffer); - Bone *getRootBone(); + Bone *getRootBone(); - SkeletonData *getData(); + SkeletonData *getData(); - Vector &getBones(); + Vector &getBones(); - Vector &getUpdateCacheList(); + Vector &getUpdateCacheList(); - Vector &getSlots(); + Vector &getSlots(); - Vector &getDrawOrder(); + Vector &getDrawOrder(); - Vector &getIkConstraints(); + Vector &getIkConstraints(); - Vector &getPathConstraints(); + Vector &getPathConstraints(); - Vector &getTransformConstraints(); + Vector &getTransformConstraints(); - Skin *getSkin(); + Skin *getSkin(); - Color &getColor(); + Color &getColor(); - float getTime(); + float getTime(); - void setTime(float inValue); + void setTime(float inValue); - void setPosition(float x, float y); + void setPosition(float x, float y); - float getX(); + float getX(); - void setX(float inValue); + void setX(float inValue); - float getY(); + float getY(); - void setY(float inValue); + void setY(float inValue); - float getScaleX(); + float getScaleX(); - void setScaleX(float inValue); + void setScaleX(float inValue); - float getScaleY(); + float getScaleY(); - void setScaleY(float inValue); + void setScaleY(float inValue); private: - SkeletonData *_data; - Vector _bones; - Vector _slots; - Vector _drawOrder; - Vector _ikConstraints; - Vector _transformConstraints; - Vector _pathConstraints; - Vector _updateCache; - Vector _updateCacheReset; - Skin *_skin; - Color _color; - float _time; - float _scaleX, _scaleY; - float _x, _y; + SkeletonData *_data; + Vector _bones; + Vector _slots; + Vector _drawOrder; + Vector _ikConstraints; + Vector _transformConstraints; + Vector _pathConstraints; + Vector _updateCache; + Vector _updateCacheReset; + Skin *_skin; + Color _color; + float _time; + float _scaleX, _scaleY; + float _x, _y; - void sortIkConstraint(IkConstraint *constraint); + void sortIkConstraint(IkConstraint *constraint); - void sortPathConstraint(PathConstraint *constraint); + void sortPathConstraint(PathConstraint *constraint); - void sortTransformConstraint(TransformConstraint *constraint); + void sortTransformConstraint(TransformConstraint *constraint); - void sortPathConstraintAttachment(Skin *skin, size_t slotIndex, Bone &slotBone); + void sortPathConstraintAttachment(Skin *skin, size_t slotIndex, Bone &slotBone); - void sortPathConstraintAttachment(Attachment *attachment, Bone &slotBone); + void sortPathConstraintAttachment(Attachment *attachment, Bone &slotBone); - void sortBone(Bone *bone); + void sortBone(Bone *bone); - static void sortReset(Vector &bones); + static void sortReset(Vector &bones); }; -} +} // namespace spine #endif /* Spine_Skeleton_h */ diff --git a/native/cocos/editor-support/spine/SkeletonBinary.cpp b/native/cocos/editor-support/spine/SkeletonBinary.cpp index ea002a01c0..f0814a24c0 100644 --- a/native/cocos/editor-support/spine/SkeletonBinary.cpp +++ b/native/cocos/editor-support/spine/SkeletonBinary.cpp @@ -76,22 +76,22 @@ using namespace spine; -const int SkeletonBinary::BONE_ROTATE = 0; +const int SkeletonBinary::BONE_ROTATE = 0; const int SkeletonBinary::BONE_TRANSLATE = 1; -const int SkeletonBinary::BONE_SCALE = 2; -const int SkeletonBinary::BONE_SHEAR = 3; +const int SkeletonBinary::BONE_SCALE = 2; +const int SkeletonBinary::BONE_SHEAR = 3; const int SkeletonBinary::SLOT_ATTACHMENT = 0; -const int SkeletonBinary::SLOT_COLOR = 1; -const int SkeletonBinary::SLOT_TWO_COLOR = 2; +const int SkeletonBinary::SLOT_COLOR = 1; +const int SkeletonBinary::SLOT_TWO_COLOR = 2; const int SkeletonBinary::PATH_POSITION = 0; -const int SkeletonBinary::PATH_SPACING = 1; -const int SkeletonBinary::PATH_MIX = 2; +const int SkeletonBinary::PATH_SPACING = 1; +const int SkeletonBinary::PATH_MIX = 2; -const int SkeletonBinary::CURVE_LINEAR = 0; +const int SkeletonBinary::CURVE_LINEAR = 0; const int SkeletonBinary::CURVE_STEPPED = 1; -const int SkeletonBinary::CURVE_BEZIER = 2; +const int SkeletonBinary::CURVE_BEZIER = 2; SkeletonBinary::SkeletonBinary(Atlas *atlasArray) : _attachmentLoader( new (__FILE__, __LINE__) AtlasAttachmentLoader(atlasArray)), @@ -112,12 +112,12 @@ SkeletonBinary::~SkeletonBinary() { } SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, const int length) { - bool nonessential; + bool nonessential; SkeletonData *skeletonData; DataInput *input = new (__FILE__, __LINE__) DataInput(); - input->cursor = binary; - input->end = binary + length; + input->cursor = binary; + input->end = binary + length; _linkedMeshes.clear(); @@ -135,9 +135,9 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons return NULL; } - skeletonData->_x = readFloat(input); - skeletonData->_y = readFloat(input); - skeletonData->_width = readFloat(input); + skeletonData->_x = readFloat(input); + skeletonData->_y = readFloat(input); + skeletonData->_width = readFloat(input); skeletonData->_height = readFloat(input); nonessential = readBoolean(input); @@ -157,19 +157,19 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons int numBones = readVarint(input, true); skeletonData->_bones.setSize(numBones, 0); for (int i = 0; i < numBones; ++i) { - const char *name = readString(input); - BoneData * parent = i == 0 ? 0 : skeletonData->_bones[readVarint(input, true)]; - BoneData * data = new (__FILE__, __LINE__) BoneData(i, String(name, true), parent); - data->_rotation = readFloat(input); - data->_x = readFloat(input) * _scale; - data->_y = readFloat(input) * _scale; - data->_scaleX = readFloat(input); - data->_scaleY = readFloat(input); - data->_shearX = readFloat(input); - data->_shearY = readFloat(input); - data->_length = readFloat(input) * _scale; + const char *name = readString(input); + BoneData *parent = i == 0 ? 0 : skeletonData->_bones[readVarint(input, true)]; + BoneData *data = new (__FILE__, __LINE__) BoneData(i, String(name, true), parent); + data->_rotation = readFloat(input); + data->_x = readFloat(input) * _scale; + data->_y = readFloat(input) * _scale; + data->_scaleX = readFloat(input); + data->_scaleY = readFloat(input); + data->_shearX = readFloat(input); + data->_shearY = readFloat(input); + data->_length = readFloat(input) * _scale; data->_transformMode = static_cast(readVarint(input, true)); - data->_skinRequired = readBoolean(input); + data->_skinRequired = readBoolean(input); if (nonessential) readInt(input); /* Skip bone color. */ skeletonData->_bones[i] = data; } @@ -179,8 +179,8 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons skeletonData->_slots.setSize(slotsCount, 0); for (int i = 0; i < slotsCount; ++i) { const char *slotName = readString(input); - BoneData * boneData = skeletonData->_bones[readVarint(input, true)]; - SlotData * slotData = new (__FILE__, __LINE__) SlotData(i, String(slotName, true), *boneData); + BoneData *boneData = skeletonData->_bones[readVarint(input, true)]; + SlotData *slotData = new (__FILE__, __LINE__) SlotData(i, String(slotName, true), *boneData); readColor(input, slotData->getColor()); unsigned char r = readByte(input); @@ -192,15 +192,15 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons slotData->setHasDarkColor(true); } slotData->_attachmentName = readStringRef(input, skeletonData); - slotData->_blendMode = static_cast(readVarint(input, true)); - skeletonData->_slots[i] = slotData; + slotData->_blendMode = static_cast(readVarint(input, true)); + skeletonData->_slots[i] = slotData; } /* IK constraints. */ int ikConstraintsCount = readVarint(input, true); skeletonData->_ikConstraints.setSize(ikConstraintsCount, 0); for (int i = 0; i < ikConstraintsCount; ++i) { - const char * name = readString(input); + const char *name = readString(input); IkConstraintData *data = new (__FILE__, __LINE__) IkConstraintData(String(name, true)); data->setOrder(readVarint(input, true)); data->setSkinRequired(readBoolean(input)); @@ -208,13 +208,13 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons data->_bones.setSize(bonesCount, 0); for (int ii = 0; ii < bonesCount; ++ii) data->_bones[ii] = skeletonData->_bones[readVarint(input, true)]; - data->_target = skeletonData->_bones[readVarint(input, true)]; - data->_mix = readFloat(input); - data->_softness = readFloat(input) * _scale; - data->_bendDirection = readSByte(input); - data->_compress = readBoolean(input); - data->_stretch = readBoolean(input); - data->_uniform = readBoolean(input); + data->_target = skeletonData->_bones[readVarint(input, true)]; + data->_mix = readFloat(input); + data->_softness = readFloat(input) * _scale; + data->_bendDirection = readSByte(input); + data->_compress = readBoolean(input); + data->_stretch = readBoolean(input); + data->_uniform = readBoolean(input); skeletonData->_ikConstraints[i] = data; } @@ -222,7 +222,7 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons int transformConstraintsCount = readVarint(input, true); skeletonData->_transformConstraints.setSize(transformConstraintsCount, 0); for (int i = 0; i < transformConstraintsCount; ++i) { - const char * name = readString(input); + const char *name = readString(input); TransformConstraintData *data = new (__FILE__, __LINE__) TransformConstraintData(String(name, true)); data->setOrder(readVarint(input, true)); data->setSkinRequired(readBoolean(input)); @@ -230,19 +230,19 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons data->_bones.setSize(bonesCount, 0); for (int ii = 0; ii < bonesCount; ++ii) data->_bones[ii] = skeletonData->_bones[readVarint(input, true)]; - data->_target = skeletonData->_bones[readVarint(input, true)]; - data->_local = readBoolean(input); - data->_relative = readBoolean(input); - data->_offsetRotation = readFloat(input); - data->_offsetX = readFloat(input) * _scale; - data->_offsetY = readFloat(input) * _scale; - data->_offsetScaleX = readFloat(input); - data->_offsetScaleY = readFloat(input); - data->_offsetShearY = readFloat(input); - data->_rotateMix = readFloat(input); - data->_translateMix = readFloat(input); - data->_scaleMix = readFloat(input); - data->_shearMix = readFloat(input); + data->_target = skeletonData->_bones[readVarint(input, true)]; + data->_local = readBoolean(input); + data->_relative = readBoolean(input); + data->_offsetRotation = readFloat(input); + data->_offsetX = readFloat(input) * _scale; + data->_offsetY = readFloat(input) * _scale; + data->_offsetScaleX = readFloat(input); + data->_offsetScaleY = readFloat(input); + data->_offsetShearY = readFloat(input); + data->_rotateMix = readFloat(input); + data->_translateMix = readFloat(input); + data->_scaleMix = readFloat(input); + data->_shearMix = readFloat(input); skeletonData->_transformConstraints[i] = data; } @@ -250,7 +250,7 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons int pathConstraintsCount = readVarint(input, true); skeletonData->_pathConstraints.setSize(pathConstraintsCount, 0); for (int i = 0; i < pathConstraintsCount; ++i) { - const char * name = readString(input); + const char *name = readString(input); PathConstraintData *data = new (__FILE__, __LINE__) PathConstraintData(String(name, true)); data->setOrder(readVarint(input, true)); data->setSkinRequired(readBoolean(input)); @@ -258,18 +258,18 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons data->_bones.setSize(bonesCount, 0); for (int ii = 0; ii < bonesCount; ++ii) data->_bones[ii] = skeletonData->_bones[readVarint(input, true)]; - data->_target = skeletonData->_slots[readVarint(input, true)]; - data->_positionMode = static_cast(readVarint(input, true)); - data->_spacingMode = static_cast(readVarint(input, true)); - data->_rotateMode = static_cast(readVarint(input, true)); + data->_target = skeletonData->_slots[readVarint(input, true)]; + data->_positionMode = static_cast(readVarint(input, true)); + data->_spacingMode = static_cast(readVarint(input, true)); + data->_rotateMode = static_cast(readVarint(input, true)); data->_offsetRotation = readFloat(input); - data->_position = readFloat(input); + data->_position = readFloat(input); if (data->_positionMode == PositionMode_Fixed) data->_position *= _scale; data->_spacing = readFloat(input); if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed) data->_spacing *= _scale; - data->_rotateMix = readFloat(input); - data->_translateMix = readFloat(input); + data->_rotateMix = readFloat(input); + data->_translateMix = readFloat(input); skeletonData->_pathConstraints[i] = data; } @@ -287,7 +287,7 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons /* Linked meshes. */ for (int i = 0, n = _linkedMeshes.size(); i < n; ++i) { LinkedMesh *linkedMesh = _linkedMeshes[i]; - Skin * skin = linkedMesh->_skin.length() == 0 ? skeletonData->getDefaultSkin() : skeletonData->findSkin(linkedMesh->_skin); + Skin *skin = linkedMesh->_skin.length() == 0 ? skeletonData->getDefaultSkin() : skeletonData->findSkin(linkedMesh->_skin); if (skin == NULL) { delete input; delete skeletonData; @@ -313,14 +313,14 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons int eventsCount = readVarint(input, true); skeletonData->_events.setSize(eventsCount, 0); for (int i = 0; i < eventsCount; ++i) { - const char *name = readStringRef(input, skeletonData); - EventData * eventData = new (__FILE__, __LINE__) EventData(String(name)); - eventData->_intValue = readVarint(input, false); + const char *name = readStringRef(input, skeletonData); + EventData *eventData = new (__FILE__, __LINE__) EventData(String(name)); + eventData->_intValue = readVarint(input, false); eventData->_floatValue = readFloat(input); eventData->_stringValue.own(readString(input)); eventData->_audioPath.own(readString(input)); // skip audio path if (!eventData->_audioPath.isEmpty()) { - eventData->_volume = readFloat(input); + eventData->_volume = readFloat(input); eventData->_balance = readFloat(input); } skeletonData->_events[i] = eventData; @@ -330,7 +330,7 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons int animationsCount = readVarint(input, true); skeletonData->_animations.setSize(animationsCount, 0); for (int i = 0; i < animationsCount; ++i) { - String name(readString(input), true); + String name(readString(input), true); Animation *animation = readAnimation(name, input, skeletonData); if (!animation) { delete input; @@ -345,9 +345,9 @@ SkeletonData *SkeletonBinary::readSkeletonData(const unsigned char *binary, cons } SkeletonData *SkeletonBinary::readSkeletonDataFile(const String &path) { - int length; + int length; SkeletonData *skeletonData; - const char * binary = SpineExtension::readFile(path.buffer(), &length); + const char *binary = SpineExtension::readFile(path.buffer(), &length); if (length == 0 || !binary) { setError("Unable to read skeleton file: ", path.buffer()); return NULL; @@ -359,7 +359,7 @@ SkeletonData *SkeletonBinary::readSkeletonDataFile(const String &path) { void SkeletonBinary::setError(const char *value1, const char *value2) { char message[256]; - int length; + int length; strcpy(message, value1); length = (int)strlen(value1); if (value2) strncat(message + length, value2, 255 - length); @@ -367,7 +367,7 @@ void SkeletonBinary::setError(const char *value1, const char *value2) { } char *SkeletonBinary::readString(DataInput *input) { - int length = readVarint(input, true); + int length = readVarint(input, true); char *string; if (length == 0) return NULL; string = SpineExtension::alloc(length, __FILE__, __LINE__); @@ -384,7 +384,7 @@ char *SkeletonBinary::readStringRef(DataInput *input, SkeletonData *skeletonData float SkeletonBinary::readFloat(DataInput *input) { union { - int intValue; + int intValue; float floatValue; } intToFloat; intToFloat.intValue = readInt(input); @@ -422,8 +422,8 @@ void SkeletonBinary::readColor(DataInput *input, Color &color) { } int SkeletonBinary::readVarint(DataInput *input, bool optimizePositive) { - unsigned char b = readByte(input); - int value = b & 0x7F; + unsigned char b = readByte(input); + int value = b & 0x7F; if (b & 0x80) { b = readByte(input); value |= (b & 0x7F) << 7; @@ -443,7 +443,7 @@ int SkeletonBinary::readVarint(DataInput *input, bool optimizePositive) { Skin *SkeletonBinary::readSkin(DataInput *input, bool defaultSkin, SkeletonData *skeletonData, bool nonessential) { Skin *skin; - int slotCount = 0; + int slotCount = 0; if (defaultSkin) { slotCount = readVarint(input, true); if (slotCount == 0) return NULL; @@ -467,7 +467,7 @@ Skin *SkeletonBinary::readSkin(DataInput *input, bool defaultSkin, SkeletonData for (int i = 0; i < slotCount; ++i) { int slotIndex = readVarint(input, true); for (int ii = 0, nn = readVarint(input, true); ii < nn; ++ii) { - String name(readStringRef(input, skeletonData)); + String name(readStringRef(input, skeletonData)); Attachment *attachment = readAttachment(input, skin, slotIndex, name, skeletonData, nonessential); if (attachment) skin->setAttachment(slotIndex, String(name), attachment); } @@ -486,12 +486,12 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo String path(readStringRef(input, skeletonData)); if (path.isEmpty()) path = name; auto rotation = readFloat(input); - auto x = readFloat(input); - auto y = readFloat(input); - auto scaleX = readFloat(input); - auto scaleY = readFloat(input); - auto width = readFloat(input); - auto height = readFloat(input); + auto x = readFloat(input); + auto y = readFloat(input); + auto scaleX = readFloat(input); + auto scaleY = readFloat(input); + auto width = readFloat(input); + auto height = readFloat(input); static Color color; readColor(input, color); @@ -500,22 +500,22 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo if (region == NULL) { return NULL; } - region->_path = path; + region->_path = path; region->_rotation = rotation; - region->_x = x * _scale; - region->_y = y * _scale; - region->_scaleX = scaleX; - region->_scaleY = scaleY; - region->_width = width * _scale; - region->_height = height * _scale; - region->_color = color; + region->_x = x * _scale; + region->_y = y * _scale; + region->_scaleX = scaleX; + region->_scaleY = scaleY; + region->_width = width * _scale; + region->_height = height * _scale; + region->_color = color; region->updateOffset(); _attachmentLoader->configureAttachment(region); return region; } case AttachmentType_Boundingbox: { - int vertexCount = readVarint(input, true); - BoundingBoxAttachment *box = _attachmentLoader->newBoundingBoxAttachment(*skin, String(name)); + int vertexCount = readVarint(input, true); + BoundingBoxAttachment *box = _attachmentLoader->newBoundingBoxAttachment(*skin, String(name)); readVertices(input, static_cast(box), vertexCount); if (nonessential) { /* Skip color. */ @@ -525,12 +525,12 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo return box; } case AttachmentType_Mesh: { - int vertexCount; + int vertexCount; MeshAttachment *mesh; - String path(readStringRef(input, skeletonData)); + String path(readStringRef(input, skeletonData)); if (path.isEmpty()) path = name; - mesh = _attachmentLoader->newMeshAttachment(*skin, String(name), String(path)); + mesh = _attachmentLoader->newMeshAttachment(*skin, String(name), String(path)); mesh->_path = path; readColor(input, mesh->getColor()); vertexCount = readVarint(input, true); @@ -541,10 +541,10 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo mesh->_hullLength = readVarint(input, true) << 1; if (nonessential) { readShortArray(input, mesh->getEdges()); - mesh->_width = readFloat(input) * _scale; + mesh->_width = readFloat(input) * _scale; mesh->_height = readFloat(input) * _scale; } else { - mesh->_width = 0; + mesh->_width = 0; mesh->_height = 0; } _attachmentLoader->configureAttachment(mesh); @@ -555,13 +555,13 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo if (path.isEmpty()) path = name; MeshAttachment *mesh = _attachmentLoader->newMeshAttachment(*skin, String(name), String(path)); - mesh->_path = path; + mesh->_path = path; readColor(input, mesh->getColor()); String skinName(readStringRef(input, skeletonData)); String parent(readStringRef(input, skeletonData)); - bool inheritDeform = readBoolean(input); + bool inheritDeform = readBoolean(input); if (nonessential) { - mesh->_width = readFloat(input) * _scale; + mesh->_width = readFloat(input) * _scale; mesh->_height = readFloat(input) * _scale; } @@ -572,9 +572,9 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo } case AttachmentType_Path: { PathAttachment *path = _attachmentLoader->newPathAttachment(*skin, String(name)); - path->_closed = readBoolean(input); + path->_closed = readBoolean(input); path->_constantSpeed = readBoolean(input); - int vertexCount = readVarint(input, true); + int vertexCount = readVarint(input, true); readVertices(input, static_cast(path), vertexCount); int lengthsLength = vertexCount / 3; path->_lengths.setSize(lengthsLength, 0); @@ -590,9 +590,9 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo } case AttachmentType_Point: { PointAttachment *point = _attachmentLoader->newPointAttachment(*skin, String(name)); - point->_rotation = readFloat(input); - point->_x = readFloat(input) * _scale; - point->_y = readFloat(input) * _scale; + point->_rotation = readFloat(input); + point->_x = readFloat(input) * _scale; + point->_y = readFloat(input) * _scale; if (nonessential) { /* Skip color. */ @@ -602,9 +602,9 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo return point; } case AttachmentType_Clipping: { - int endSlotIndex = readVarint(input, true); - int vertexCount = readVarint(input, true); - ClippingAttachment *clip = _attachmentLoader->newClippingAttachment(*skin, name); + int endSlotIndex = readVarint(input, true); + int vertexCount = readVarint(input, true); + ClippingAttachment *clip = _attachmentLoader->newClippingAttachment(*skin, name); readVertices(input, static_cast(clip), vertexCount); clip->_endSlot = skeletonData->_slots[endSlotIndex]; if (nonessential) { @@ -619,8 +619,8 @@ Attachment *SkeletonBinary::readAttachment(DataInput *input, Skin *skin, int slo } void SkeletonBinary::readVertices(DataInput *input, VertexAttachment *attachment, int vertexCount) { - float scale = _scale; - int verticesLength = vertexCount << 1; + float scale = _scale; + int verticesLength = vertexCount << 1; attachment->setWorldVerticesLength(vertexCount << 1); if (!readBoolean(input)) { @@ -628,8 +628,8 @@ void SkeletonBinary::readVertices(DataInput *input, VertexAttachment *attachment return; } - Vector & vertices = attachment->getVertices(); - Vector &bones = attachment->getBones(); + Vector &vertices = attachment->getVertices(); + Vector &bones = attachment->getBones(); vertices.ensureCapacity(verticesLength * 3 * 3); bones.ensureCapacity(verticesLength * 3); @@ -673,21 +673,21 @@ void SkeletonBinary::readShortArray(DataInput *input, Vector &ar Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, SkeletonData *skeletonData) { Vector timelines; - float scale = _scale; - float duration = 0; + float scale = _scale; + float duration = 0; // Slot timelines. for (int i = 0, n = readVarint(input, true); i < n; ++i) { int slotIndex = readVarint(input, true); for (int ii = 0, nn = readVarint(input, true); ii < nn; ++ii) { unsigned char timelineType = readByte(input); - int frameCount = readVarint(input, true); + int frameCount = readVarint(input, true); switch (timelineType) { case SLOT_ATTACHMENT: { AttachmentTimeline *timeline = new (__FILE__, __LINE__) AttachmentTimeline(frameCount); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); + float time = readFloat(input); String attachmentName(readStringRef(input, skeletonData)); timeline->setFrame(frameIndex, time, attachmentName); } @@ -697,14 +697,14 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S } case SLOT_COLOR: { ColorTimeline *timeline = new (__FILE__, __LINE__) ColorTimeline(frameCount); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); - int color = readInt(input); - float r = ((color & 0xff000000) >> 24) / 255.0f; - float g = ((color & 0x00ff0000) >> 16) / 255.0f; - float b = ((color & 0x0000ff00) >> 8) / 255.0f; - float a = ((color & 0x000000ff)) / 255.0f; + float time = readFloat(input); + int color = readInt(input); + float r = ((color & 0xff000000) >> 24) / 255.0f; + float g = ((color & 0x00ff0000) >> 16) / 255.0f; + float b = ((color & 0x0000ff00) >> 8) / 255.0f; + float a = ((color & 0x000000ff)) / 255.0f; timeline->setFrame(frameIndex, time, r, g, b, a); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); } @@ -714,18 +714,18 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S } case SLOT_TWO_COLOR: { TwoColorTimeline *timeline = new (__FILE__, __LINE__) TwoColorTimeline(frameCount); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); - int color = readInt(input); - float r = ((color & 0xff000000) >> 24) / 255.0f; - float g = ((color & 0x00ff0000) >> 16) / 255.0f; - float b = ((color & 0x0000ff00) >> 8) / 255.0f; - float a = ((color & 0x000000ff)) / 255.0f; - int color2 = readInt(input); // 0x00rrggbb - float r2 = ((color2 & 0x00ff0000) >> 16) / 255.0f; - float g2 = ((color2 & 0x0000ff00) >> 8) / 255.0f; - float b2 = ((color2 & 0x000000ff)) / 255.0f; + float time = readFloat(input); + int color = readInt(input); + float r = ((color & 0xff000000) >> 24) / 255.0f; + float g = ((color & 0x00ff0000) >> 16) / 255.0f; + float b = ((color & 0x0000ff00) >> 8) / 255.0f; + float a = ((color & 0x000000ff)) / 255.0f; + int color2 = readInt(input); // 0x00rrggbb + float r2 = ((color2 & 0x00ff0000) >> 16) / 255.0f; + float g2 = ((color2 & 0x0000ff00) >> 8) / 255.0f; + float b2 = ((color2 & 0x000000ff)) / 255.0f; timeline->setFrame(frameIndex, time, r, g, b, a, r2, g2, b2); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); @@ -748,13 +748,13 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S int boneIndex = readVarint(input, true); for (int ii = 0, nn = readVarint(input, true); ii < nn; ++ii) { unsigned char timelineType = readByte(input); - int frameCount = readVarint(input, true); + int frameCount = readVarint(input, true); switch (timelineType) { case BONE_ROTATE: { RotateTimeline *timeline = new (__FILE__, __LINE__) RotateTimeline(frameCount); - timeline->_boneIndex = boneIndex; + timeline->_boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); + float time = readFloat(input); float degrees = readFloat(input); timeline->setFrame(frameIndex, time, degrees); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); @@ -767,20 +767,20 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S case BONE_SCALE: case BONE_SHEAR: { TranslateTimeline *timeline; - float timelineScale = 1; + float timelineScale = 1; if (timelineType == BONE_SCALE) { timeline = new (__FILE__, __LINE__) ScaleTimeline(frameCount); } else if (timelineType == BONE_SHEAR) { timeline = new (__FILE__, __LINE__) ShearTimeline(frameCount); } else { - timeline = new (__FILE__, __LINE__) TranslateTimeline(frameCount); + timeline = new (__FILE__, __LINE__) TranslateTimeline(frameCount); timelineScale = scale; } timeline->_boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { float time = readFloat(input); - float x = readFloat(input) * timelineScale; - float y = readFloat(input) * timelineScale; + float x = readFloat(input) * timelineScale; + float y = readFloat(input) * timelineScale; timeline->setFrame(frameIndex, time, x, y); if (frameIndex < frameCount - 1) { readCurve(input, frameIndex, timeline); @@ -801,17 +801,17 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S // IK timelines. for (int i = 0, n = readVarint(input, true); i < n; ++i) { - int index = readVarint(input, true); - int frameCount = readVarint(input, true); - IkConstraintTimeline *timeline = new (__FILE__, __LINE__) IkConstraintTimeline(frameCount); - timeline->_ikConstraintIndex = index; + int index = readVarint(input, true); + int frameCount = readVarint(input, true); + IkConstraintTimeline *timeline = new (__FILE__, __LINE__) IkConstraintTimeline(frameCount); + timeline->_ikConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); - float mix = readFloat(input); - float softness = readFloat(input) * _scale; + float time = readFloat(input); + float mix = readFloat(input); + float softness = readFloat(input) * _scale; signed char bendDirection = readSByte(input); - bool compress = readBoolean(input); - bool stretch = readBoolean(input); + bool compress = readBoolean(input); + bool stretch = readBoolean(input); timeline->setFrame(frameIndex, time, mix, softness, bendDirection, compress, stretch); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); } @@ -821,16 +821,16 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S // Transform constraint timelines. for (int i = 0, n = readVarint(input, true); i < n; ++i) { - int index = readVarint(input, true); - int frameCount = readVarint(input, true); - TransformConstraintTimeline *timeline = new (__FILE__, __LINE__) TransformConstraintTimeline(frameCount); - timeline->_transformConstraintIndex = index; + int index = readVarint(input, true); + int frameCount = readVarint(input, true); + TransformConstraintTimeline *timeline = new (__FILE__, __LINE__) TransformConstraintTimeline(frameCount); + timeline->_transformConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); - float rotateMix = readFloat(input); + float time = readFloat(input); + float rotateMix = readFloat(input); float translateMix = readFloat(input); - float scaleMix = readFloat(input); - float shearMix = readFloat(input); + float scaleMix = readFloat(input); + float shearMix = readFloat(input); timeline->setFrame(frameIndex, time, rotateMix, translateMix, scaleMix, shearMix); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); } @@ -840,16 +840,16 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S // Path constraint timelines. for (int i = 0, n = readVarint(input, true); i < n; ++i) { - int index = readVarint(input, true); - PathConstraintData *data = skeletonData->_pathConstraints[index]; + int index = readVarint(input, true); + PathConstraintData *data = skeletonData->_pathConstraints[index]; for (int ii = 0, nn = readVarint(input, true); ii < nn; ++ii) { int timelineType = readSByte(input); - int frameCount = readVarint(input, true); + int frameCount = readVarint(input, true); switch (timelineType) { case PATH_POSITION: case PATH_SPACING: { PathConstraintPositionTimeline *timeline; - float timelineScale = 1; + float timelineScale = 1; if (timelineType == PATH_SPACING) { timeline = new (__FILE__, __LINE__) PathConstraintSpacingTimeline(frameCount); @@ -861,7 +861,7 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S } timeline->_pathConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); + float time = readFloat(input); float value = readFloat(input) * timelineScale; timeline->setFrame(frameIndex, time, value); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); @@ -875,8 +875,8 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S timeline->_pathConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); - float rotateMix = readFloat(input); + float time = readFloat(input); + float rotateMix = readFloat(input); float translateMix = readFloat(input); timeline->setFrame(frameIndex, time, rotateMix, translateMix); if (frameIndex < frameCount - 1) readCurve(input, frameIndex, timeline); @@ -906,20 +906,20 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S VertexAttachment *attachment = static_cast(baseAttachment); - bool weighted = attachment->_bones.size() > 0; - Vector &vertices = attachment->_vertices; - size_t deformLength = weighted ? vertices.size() / 3 * 2 : vertices.size(); + bool weighted = attachment->_bones.size() > 0; + Vector &vertices = attachment->_vertices; + size_t deformLength = weighted ? vertices.size() / 3 * 2 : vertices.size(); size_t frameCount = (size_t)readVarint(input, true); DeformTimeline *timeline = new (__FILE__, __LINE__) DeformTimeline(frameCount); - timeline->_slotIndex = slotIndex; - timeline->_attachment = attachment; + timeline->_slotIndex = slotIndex; + timeline->_attachment = attachment; for (size_t frameIndex = 0; frameIndex < frameCount; ++frameIndex) { - float time = readFloat(input); + float time = readFloat(input); Vector deform; - size_t end = (size_t)readVarint(input, true); + size_t end = (size_t)readVarint(input, true); if (end == 0) { if (weighted) { deform.setSize(deformLength, 0); @@ -963,7 +963,7 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S size_t slotCount = skeletonData->_slots.size(); for (size_t i = 0; i < drawOrderCount; ++i) { - float time = readFloat(input); + float time = readFloat(input); size_t offsetCount = (size_t)readVarint(input, true); Vector drawOrder; @@ -980,7 +980,7 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; // Set changed items. - size_t index = originalIndex; + size_t index = originalIndex; drawOrder[index + (size_t)readVarint(input, true)] = originalIndex++; } @@ -1004,19 +1004,19 @@ Animation *SkeletonBinary::readAnimation(const String &name, DataInput *input, S EventTimeline *timeline = new (__FILE__, __LINE__) EventTimeline(eventCount); for (int i = 0; i < eventCount; ++i) { - float time = readFloat(input); + float time = readFloat(input); EventData *eventData = skeletonData->_events[readVarint(input, true)]; - Event * event = new (__FILE__, __LINE__) Event(time, *eventData); + Event *event = new (__FILE__, __LINE__) Event(time, *eventData); - event->_intValue = readVarint(input, false); - event->_floatValue = readFloat(input); - bool freeString = readBoolean(input); + event->_intValue = readVarint(input, false); + event->_floatValue = readFloat(input); + bool freeString = readBoolean(input); const char *event_stringValue = freeString ? readString(input) : eventData->_stringValue.buffer(); - event->_stringValue = String(event_stringValue); + event->_stringValue = String(event_stringValue); if (freeString) SpineExtension::free(event_stringValue, __FILE__, __LINE__); if (!eventData->_audioPath.isEmpty()) { - event->_volume = readFloat(input); + event->_volume = readFloat(input); event->_balance = readFloat(input); } timeline->setFrame(i, event); diff --git a/native/cocos/editor-support/spine/SkeletonBinary.h b/native/cocos/editor-support/spine/SkeletonBinary.h index 88af8bd772..30982a48f5 100644 --- a/native/cocos/editor-support/spine/SkeletonBinary.h +++ b/native/cocos/editor-support/spine/SkeletonBinary.h @@ -37,95 +37,95 @@ #include namespace spine { - class SkeletonData; - class Atlas; - class AttachmentLoader; - class LinkedMesh; - class Skin; - class Attachment; - class VertexAttachment; - class Animation; - class CurveTimeline; +class SkeletonData; +class Atlas; +class AttachmentLoader; +class LinkedMesh; +class Skin; +class Attachment; +class VertexAttachment; +class Animation; +class CurveTimeline; - class SP_API SkeletonBinary : public SpineObject { - public: - static const int BONE_ROTATE; - static const int BONE_TRANSLATE; - static const int BONE_SCALE; - static const int BONE_SHEAR; +class SP_API SkeletonBinary : public SpineObject { +public: + static const int BONE_ROTATE; + static const int BONE_TRANSLATE; + static const int BONE_SCALE; + static const int BONE_SHEAR; - static const int SLOT_ATTACHMENT; - static const int SLOT_COLOR; - static const int SLOT_TWO_COLOR; + static const int SLOT_ATTACHMENT; + static const int SLOT_COLOR; + static const int SLOT_TWO_COLOR; - static const int PATH_POSITION; - static const int PATH_SPACING; - static const int PATH_MIX; + static const int PATH_POSITION; + static const int PATH_SPACING; + static const int PATH_MIX; - static const int CURVE_LINEAR; - static const int CURVE_STEPPED; - static const int CURVE_BEZIER; + static const int CURVE_LINEAR; + static const int CURVE_STEPPED; + static const int CURVE_BEZIER; - explicit SkeletonBinary(Atlas* atlasArray); + explicit SkeletonBinary(Atlas* atlasArray); - explicit SkeletonBinary(AttachmentLoader* attachmentLoader); + explicit SkeletonBinary(AttachmentLoader* attachmentLoader); - ~SkeletonBinary(); + ~SkeletonBinary(); - SkeletonData* readSkeletonData(const unsigned char* binary, int length); + SkeletonData* readSkeletonData(const unsigned char* binary, int length); - SkeletonData* readSkeletonDataFile(const String& path); + SkeletonData* readSkeletonDataFile(const String& path); - void setScale(float scale) { _scale = scale; } + void setScale(float scale) { _scale = scale; } - String& getError() { return _error; } + String& getError() { return _error; } - private: - struct DataInput : public SpineObject { - const unsigned char* cursor; - const unsigned char* end; - }; +private: + struct DataInput : public SpineObject { + const unsigned char* cursor; + const unsigned char* end; + }; - AttachmentLoader* _attachmentLoader; - Vector _linkedMeshes; - String _error; - float _scale; - const bool _ownsLoader; + AttachmentLoader* _attachmentLoader; + Vector _linkedMeshes; + String _error; + float _scale; + const bool _ownsLoader; - void setError(const char* value1, const char* value2); + void setError(const char* value1, const char* value2); - char* readString(DataInput* input); + char* readString(DataInput* input); - char* readStringRef(DataInput* input, SkeletonData* skeletonData); + char* readStringRef(DataInput* input, SkeletonData* skeletonData); - float readFloat(DataInput* input); + float readFloat(DataInput* input); - unsigned char readByte(DataInput* input); + unsigned char readByte(DataInput* input); - signed char readSByte(DataInput* input); + signed char readSByte(DataInput* input); - bool readBoolean(DataInput* input); + bool readBoolean(DataInput* input); - int readInt(DataInput* input); + int readInt(DataInput* input); - void readColor(DataInput* input, Color& color); + void readColor(DataInput* input, Color& color); - int readVarint(DataInput* input, bool optimizePositive); + int readVarint(DataInput* input, bool optimizePositive); - Skin* readSkin(DataInput* input, bool defaultSkin, SkeletonData* skeletonData, bool nonessential); + Skin* readSkin(DataInput* input, bool defaultSkin, SkeletonData* skeletonData, bool nonessential); - Attachment* readAttachment(DataInput* input, Skin* skin, int slotIndex, const String& attachmentName, SkeletonData* skeletonData, bool nonessential); + Attachment* readAttachment(DataInput* input, Skin* skin, int slotIndex, const String& attachmentName, SkeletonData* skeletonData, bool nonessential); - void readVertices(DataInput* input, VertexAttachment* attachment, int vertexCount); + void readVertices(DataInput* input, VertexAttachment* attachment, int vertexCount); - void readFloatArray(DataInput *input, int n, float scale, Vector& array); + void readFloatArray(DataInput* input, int n, float scale, Vector& array); - void readShortArray(DataInput *input, Vector& array); + void readShortArray(DataInput* input, Vector& array); - Animation* readAnimation(const String& name, DataInput* input, SkeletonData *skeletonData); + Animation* readAnimation(const String& name, DataInput* input, SkeletonData* skeletonData); - void readCurve(DataInput* input, int frameIndex, CurveTimeline* timeline); - }; -} + void readCurve(DataInput* input, int frameIndex, CurveTimeline* timeline); +}; +} // namespace spine #endif /* Spine_SkeletonBinary_h */ diff --git a/native/cocos/editor-support/spine/SkeletonBounds.cpp b/native/cocos/editor-support/spine/SkeletonBounds.cpp index 6e2620f3ec..d66a23a439 100644 --- a/native/cocos/editor-support/spine/SkeletonBounds.cpp +++ b/native/cocos/editor-support/spine/SkeletonBounds.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -47,177 +47,177 @@ SkeletonBounds::SkeletonBounds() : _minX(0), _minY(0), _maxX(0), _maxY(0) { } void SkeletonBounds::update(Skeleton &skeleton, bool updateAabb) { - Vector &slots = skeleton._slots; - size_t slotCount = slots.size(); + Vector &slots = skeleton._slots; + size_t slotCount = slots.size(); - _boundingBoxes.clear(); - for (size_t i = 0, n = _polygons.size(); i < n; ++i) { - _polygonPool.add(_polygons[i]); - } + _boundingBoxes.clear(); + for (size_t i = 0, n = _polygons.size(); i < n; ++i) { + _polygonPool.add(_polygons[i]); + } - _polygons.clear(); + _polygons.clear(); - for (size_t i = 0; i < slotCount; i++) { - Slot *slot = slots[i]; - if (!slot->getBone().isActive()) continue; + for (size_t i = 0; i < slotCount; i++) { + Slot *slot = slots[i]; + if (!slot->getBone().isActive()) continue; - Attachment *attachment = slot->getAttachment(); - if (attachment == NULL || !attachment->getRTTI().instanceOf(BoundingBoxAttachment::rtti)) continue; - BoundingBoxAttachment *boundingBox = static_cast(attachment); - _boundingBoxes.add(boundingBox); + Attachment *attachment = slot->getAttachment(); + if (attachment == NULL || !attachment->getRTTI().instanceOf(BoundingBoxAttachment::rtti)) continue; + BoundingBoxAttachment *boundingBox = static_cast(attachment); + _boundingBoxes.add(boundingBox); - spine::Polygon *polygonP = NULL; - size_t poolCount = _polygonPool.size(); - if (poolCount > 0) { - polygonP = _polygonPool[poolCount - 1]; - _polygonPool.removeAt(poolCount - 1); - } else - polygonP = new(__FILE__, __LINE__) Polygon(); + spine::Polygon *polygonP = NULL; + size_t poolCount = _polygonPool.size(); + if (poolCount > 0) { + polygonP = _polygonPool[poolCount - 1]; + _polygonPool.removeAt(poolCount - 1); + } else + polygonP = new (__FILE__, __LINE__) Polygon(); - _polygons.add(polygonP); + _polygons.add(polygonP); - Polygon &polygon = *polygonP; + Polygon &polygon = *polygonP; - size_t count = boundingBox->getWorldVerticesLength(); - polygon._count = count; - if (polygon._vertices.size() < count) { - polygon._vertices.setSize(count, 0); - } - boundingBox->computeWorldVertices(*slot, polygon._vertices); - } + size_t count = boundingBox->getWorldVerticesLength(); + polygon._count = count; + if (polygon._vertices.size() < count) { + polygon._vertices.setSize(count, 0); + } + boundingBox->computeWorldVertices(*slot, polygon._vertices); + } - if (updateAabb) - aabbCompute(); - else { - _minX = FLT_MIN; - _minY = FLT_MIN; - _maxX = FLT_MAX; - _maxY = FLT_MAX; - } + if (updateAabb) + aabbCompute(); + else { + _minX = FLT_MIN; + _minY = FLT_MIN; + _maxX = FLT_MAX; + _maxY = FLT_MAX; + } } bool SkeletonBounds::aabbcontainsPoint(float x, float y) { - return x >= _minX && x <= _maxX && y >= _minY && y <= _maxY; + return x >= _minX && x <= _maxX && y >= _minY && y <= _maxY; } bool SkeletonBounds::aabbintersectsSegment(float x1, float y1, float x2, float y2) { - float minX = _minX; - float minY = _minY; - float maxX = _maxX; - float maxY = _maxY; + float minX = _minX; + float minY = _minY; + float maxX = _maxX; + float maxY = _maxY; - if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || - (y1 >= maxY && y2 >= maxY)) { - return false; - } + if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || + (y1 >= maxY && y2 >= maxY)) { + return false; + } - float m = (y2 - y1) / (x2 - x1); - float y = m * (minX - x1) + y1; - if (y > minY && y < maxY) return true; - y = m * (maxX - x1) + y1; - if (y > minY && y < maxY) return true; - float x = (minY - y1) / m + x1; - if (x > minX && x < maxX) return true; - x = (maxY - y1) / m + x1; - if (x > minX && x < maxX) return true; - return false; + float m = (y2 - y1) / (x2 - x1); + float y = m * (minX - x1) + y1; + if (y > minY && y < maxY) return true; + y = m * (maxX - x1) + y1; + if (y > minY && y < maxY) return true; + float x = (minY - y1) / m + x1; + if (x > minX && x < maxX) return true; + x = (maxY - y1) / m + x1; + if (x > minX && x < maxX) return true; + return false; } bool SkeletonBounds::aabbIntersectsSkeleton(SkeletonBounds bounds) { - return _minX < bounds._maxX && _maxX > bounds._minX && _minY < bounds._maxY && _maxY > bounds._minY; + return _minX < bounds._maxX && _maxX > bounds._minX && _minY < bounds._maxY && _maxY > bounds._minY; } bool SkeletonBounds::containsPoint(spine::Polygon *polygon, float x, float y) { - Vector &vertices = polygon->_vertices; - int nn = polygon->_count; + Vector &vertices = polygon->_vertices; + int nn = polygon->_count; - int prevIndex = nn - 2; - bool inside = false; - for (int ii = 0; ii < nn; ii += 2) { - float vertexY = vertices[ii + 1]; - float prevY = vertices[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { - float vertexX = vertices[ii]; - if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) { - inside = !inside; - } - } - prevIndex = ii; - } - return inside; + int prevIndex = nn - 2; + bool inside = false; + for (int ii = 0; ii < nn; ii += 2) { + float vertexY = vertices[ii + 1]; + float prevY = vertices[prevIndex + 1]; + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + float vertexX = vertices[ii]; + if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) { + inside = !inside; + } + } + prevIndex = ii; + } + return inside; } BoundingBoxAttachment *SkeletonBounds::containsPoint(float x, float y) { - for (size_t i = 0, n = _polygons.size(); i < n; ++i) - if (containsPoint(_polygons[i], x, y)) return _boundingBoxes[i]; - return NULL; + for (size_t i = 0, n = _polygons.size(); i < n; ++i) + if (containsPoint(_polygons[i], x, y)) return _boundingBoxes[i]; + return NULL; } BoundingBoxAttachment *SkeletonBounds::intersectsSegment(float x1, float y1, float x2, float y2) { - for (size_t i = 0, n = _polygons.size(); i < n; ++i) - if (intersectsSegment(_polygons[i], x1, y1, x2, y2)) return _boundingBoxes[i]; - return NULL; + for (size_t i = 0, n = _polygons.size(); i < n; ++i) + if (intersectsSegment(_polygons[i], x1, y1, x2, y2)) return _boundingBoxes[i]; + return NULL; } bool SkeletonBounds::intersectsSegment(spine::Polygon *polygon, float x1, float y1, float x2, float y2) { - Vector &vertices = polygon->_vertices; - size_t nn = polygon->_count; + Vector &vertices = polygon->_vertices; + size_t nn = polygon->_count; - float width12 = x1 - x2, height12 = y1 - y2; - float det1 = x1 * y2 - y1 * x2; - float x3 = vertices[nn - 2], y3 = vertices[nn - 1]; - for (size_t ii = 0; ii < nn; ii += 2) { - float x4 = vertices[ii], y4 = vertices[ii + 1]; - float det2 = x3 * y4 - y3 * x4; - float width34 = x3 - x4, height34 = y3 - y4; - float det3 = width12 * height34 - height12 * width34; - float x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { - float y = (det1 * height34 - height12 * det2) / det3; - if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) { - return true; - } - } - x3 = x4; - y3 = y4; - } + float width12 = x1 - x2, height12 = y1 - y2; + float det1 = x1 * y2 - y1 * x2; + float x3 = vertices[nn - 2], y3 = vertices[nn - 1]; + for (size_t ii = 0; ii < nn; ii += 2) { + float x4 = vertices[ii], y4 = vertices[ii + 1]; + float det2 = x3 * y4 - y3 * x4; + float width34 = x3 - x4, height34 = y3 - y4; + float det3 = width12 * height34 - height12 * width34; + float x = (det1 * width34 - width12 * det2) / det3; + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + float y = (det1 * height34 - height12 * det2) / det3; + if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) { + return true; + } + } + x3 = x4; + y3 = y4; + } - return false; + return false; } spine::Polygon *SkeletonBounds::getPolygon(BoundingBoxAttachment *attachment) { - int index = _boundingBoxes.indexOf(attachment); - return index == -1 ? NULL : _polygons[index]; + int index = _boundingBoxes.indexOf(attachment); + return index == -1 ? NULL : _polygons[index]; } float SkeletonBounds::getWidth() { - return _maxX - _minX; + return _maxX - _minX; } float SkeletonBounds::getHeight() { - return _maxY - _minY; + return _maxY - _minY; } void SkeletonBounds::aabbCompute() { - float minX = FLT_MIN; - float minY = FLT_MIN; - float maxX = FLT_MAX; - float maxY = FLT_MAX; + float minX = FLT_MIN; + float minY = FLT_MIN; + float maxX = FLT_MAX; + float maxY = FLT_MAX; - for (size_t i = 0, n = _polygons.size(); i < n; ++i) { - spine::Polygon *polygon = _polygons[i]; - Vector &vertices = polygon->_vertices; - for (int ii = 0, nn = polygon->_count; ii < nn; ii += 2) { - float x = vertices[ii]; - float y = vertices[ii + 1]; - minX = MathUtil::min(minX, x); - minY = MathUtil::min(minY, y); - maxX = MathUtil::max(maxX, x); - maxY = MathUtil::max(maxY, y); - } - } - _minX = minX; - _minY = minY; - _maxX = maxX; - _maxY = maxY; + for (size_t i = 0, n = _polygons.size(); i < n; ++i) { + spine::Polygon *polygon = _polygons[i]; + Vector &vertices = polygon->_vertices; + for (int ii = 0, nn = polygon->_count; ii < nn; ii += 2) { + float x = vertices[ii]; + float y = vertices[ii + 1]; + minX = MathUtil::min(minX, x); + minY = MathUtil::min(minY, y); + maxX = MathUtil::max(maxX, x); + maxY = MathUtil::max(maxY, y); + } + } + _minX = minX; + _minY = minY; + _maxX = maxX; + _maxY = maxY; } diff --git a/native/cocos/editor-support/spine/SkeletonBounds.h b/native/cocos/editor-support/spine/SkeletonBounds.h index c4955e685c..3457962c6f 100644 --- a/native/cocos/editor-support/spine/SkeletonBounds.h +++ b/native/cocos/editor-support/spine/SkeletonBounds.h @@ -34,71 +34,71 @@ #include namespace spine { - class Skeleton; - class BoundingBoxAttachment; - class Polygon; +class Skeleton; +class BoundingBoxAttachment; +class Polygon; - /// Collects each BoundingBoxAttachment that is visible and computes the world vertices for its polygon. - /// The polygon vertices are provided along with convenience methods for doing hit detection. - class SP_API SkeletonBounds : public SpineObject { - public: - SkeletonBounds(); +/// Collects each BoundingBoxAttachment that is visible and computes the world vertices for its polygon. +/// The polygon vertices are provided along with convenience methods for doing hit detection. +class SP_API SkeletonBounds : public SpineObject { +public: + SkeletonBounds(); - /// Clears any previous polygons, finds all visible bounding box attachments, - /// and computes the world vertices for each bounding box's polygon. - /// @param skeleton The skeleton. - /// @param updateAabb - /// If true, the axis aligned bounding box containing all the polygons is computed. - /// If false, the SkeletonBounds AABB methods will always return true. - /// - void update(Skeleton& skeleton, bool updateAabb); + /// Clears any previous polygons, finds all visible bounding box attachments, + /// and computes the world vertices for each bounding box's polygon. + /// @param skeleton The skeleton. + /// @param updateAabb + /// If true, the axis aligned bounding box containing all the polygons is computed. + /// If false, the SkeletonBounds AABB methods will always return true. + /// + void update(Skeleton& skeleton, bool updateAabb); - /// Returns true if the axis aligned bounding box contains the point. - bool aabbcontainsPoint(float x, float y); + /// Returns true if the axis aligned bounding box contains the point. + bool aabbcontainsPoint(float x, float y); - /// Returns true if the axis aligned bounding box intersects the line segment. - bool aabbintersectsSegment(float x1, float y1, float x2, float y2); + /// Returns true if the axis aligned bounding box intersects the line segment. + bool aabbintersectsSegment(float x1, float y1, float x2, float y2); - /// Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. - bool aabbIntersectsSkeleton(SkeletonBounds bounds); + /// Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. + bool aabbIntersectsSkeleton(SkeletonBounds bounds); - /// Returns true if the polygon contains the point. - bool containsPoint(Polygon* polygon, float x, float y); + /// Returns true if the polygon contains the point. + bool containsPoint(Polygon* polygon, float x, float y); - /// Returns the first bounding box attachment that contains the point, or NULL. When doing many checks, it is usually more - /// efficient to only call this method if {@link #aabbcontainsPoint(float, float)} returns true. - BoundingBoxAttachment* containsPoint(float x, float y); + /// Returns the first bounding box attachment that contains the point, or NULL. When doing many checks, it is usually more + /// efficient to only call this method if {@link #aabbcontainsPoint(float, float)} returns true. + BoundingBoxAttachment* containsPoint(float x, float y); - /// Returns the first bounding box attachment that contains the line segment, or NULL. When doing many checks, it is usually - /// more efficient to only call this method if {@link #aabbintersectsSegment(float, float, float, float)} returns true. - BoundingBoxAttachment* intersectsSegment(float x1, float y1, float x2, float y2); + /// Returns the first bounding box attachment that contains the line segment, or NULL. When doing many checks, it is usually + /// more efficient to only call this method if {@link #aabbintersectsSegment(float, float, float, float)} returns true. + BoundingBoxAttachment* intersectsSegment(float x1, float y1, float x2, float y2); - /// Returns true if the polygon contains the line segment. - bool intersectsSegment(Polygon* polygon, float x1, float y1, float x2, float y2); + /// Returns true if the polygon contains the line segment. + bool intersectsSegment(Polygon* polygon, float x1, float y1, float x2, float y2); - Polygon* getPolygon(BoundingBoxAttachment* attachment); + Polygon* getPolygon(BoundingBoxAttachment* attachment); - float getWidth(); - float getHeight(); + float getWidth(); + float getHeight(); - private: - Vector _polygonPool; - Vector _boundingBoxes; - Vector _polygons; - float _minX, _minY, _maxX, _maxY; +private: + Vector _polygonPool; + Vector _boundingBoxes; + Vector _polygons; + float _minX, _minY, _maxX, _maxY; - void aabbCompute(); - }; + void aabbCompute(); +}; - class Polygon : public SpineObject { - public: - Vector _vertices; - int _count; +class Polygon : public SpineObject { +public: + Vector _vertices; + int _count; - Polygon() : _count(0) { - _vertices.ensureCapacity(16); - } - }; -} + Polygon() : _count(0) { + _vertices.ensureCapacity(16); + } +}; +} // namespace spine #endif /* Spine_SkeletonBounds_h */ diff --git a/native/cocos/editor-support/spine/SkeletonClipping.cpp b/native/cocos/editor-support/spine/SkeletonClipping.cpp index fa5bb48671..96de4b1cd3 100644 --- a/native/cocos/editor-support/spine/SkeletonClipping.cpp +++ b/native/cocos/editor-support/spine/SkeletonClipping.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -39,290 +39,288 @@ using namespace spine; SkeletonClipping::SkeletonClipping() : _clipAttachment(NULL) { - _clipOutput.ensureCapacity(128); - _clippedVertices.ensureCapacity(128); - _clippedTriangles.ensureCapacity(128); - _clippedUVs.ensureCapacity(128); + _clipOutput.ensureCapacity(128); + _clippedVertices.ensureCapacity(128); + _clippedTriangles.ensureCapacity(128); + _clippedUVs.ensureCapacity(128); } size_t SkeletonClipping::clipStart(Slot &slot, ClippingAttachment *clip) { - if (_clipAttachment != NULL) { - return 0; - } + if (_clipAttachment != NULL) { + return 0; + } - _clipAttachment = clip; + _clipAttachment = clip; - int n = clip->getWorldVerticesLength(); - _clippingPolygon.setSize(n, 0); - clip->computeWorldVertices(slot, 0, n, _clippingPolygon, 0, 2); - makeClockwise(_clippingPolygon); - _clippingPolygons = &_triangulator.decompose(_clippingPolygon, _triangulator.triangulate(_clippingPolygon)); + int n = clip->getWorldVerticesLength(); + _clippingPolygon.setSize(n, 0); + clip->computeWorldVertices(slot, 0, n, _clippingPolygon, 0, 2); + makeClockwise(_clippingPolygon); + _clippingPolygons = &_triangulator.decompose(_clippingPolygon, _triangulator.triangulate(_clippingPolygon)); - for (size_t i = 0; i < _clippingPolygons->size(); ++i) { - Vector *polygonP = (*_clippingPolygons)[i]; - Vector &polygon = *polygonP; - makeClockwise(polygon); - polygon.add(polygon[0]); - polygon.add(polygon[1]); - } + for (size_t i = 0; i < _clippingPolygons->size(); ++i) { + Vector *polygonP = (*_clippingPolygons)[i]; + Vector &polygon = *polygonP; + makeClockwise(polygon); + polygon.add(polygon[0]); + polygon.add(polygon[1]); + } - return (*_clippingPolygons).size(); + return (*_clippingPolygons).size(); } void SkeletonClipping::clipEnd(Slot &slot) { - if (_clipAttachment != NULL && _clipAttachment->_endSlot == &slot._data) { - clipEnd(); - } + if (_clipAttachment != NULL && _clipAttachment->_endSlot == &slot._data) { + clipEnd(); + } } void SkeletonClipping::clipEnd() { - if (_clipAttachment == NULL) return; + if (_clipAttachment == NULL) return; - _clipAttachment = NULL; - _clippingPolygons = NULL; - _clippedVertices.clear(); - _clippedUVs.clear(); - _clippedTriangles.clear(); - _clippingPolygon.clear(); + _clipAttachment = NULL; + _clippingPolygons = NULL; + _clippedVertices.clear(); + _clippedUVs.clear(); + _clippedTriangles.clear(); + _clippingPolygon.clear(); } void SkeletonClipping::clipTriangles(Vector &vertices, Vector &triangles, Vector &uvs, size_t stride) { - clipTriangles(vertices.buffer(), triangles.buffer(), triangles.size(), uvs.buffer(), stride); + clipTriangles(vertices.buffer(), triangles.buffer(), triangles.size(), uvs.buffer(), stride); } void SkeletonClipping::clipTriangles(float *vertices, unsigned short *triangles, - size_t trianglesLength, float *uvs, size_t stride -) { - Vector &clipOutput = _clipOutput; - Vector &clippedVertices = _clippedVertices; - Vector &clippedTriangles = _clippedTriangles; - Vector *> &polygons = *_clippingPolygons; - size_t polygonsCount = (*_clippingPolygons).size(); + size_t trianglesLength, float *uvs, size_t stride) { + Vector &clipOutput = _clipOutput; + Vector &clippedVertices = _clippedVertices; + Vector &clippedTriangles = _clippedTriangles; + Vector *> &polygons = *_clippingPolygons; + size_t polygonsCount = (*_clippingPolygons).size(); - size_t index = 0; - clippedVertices.clear(); - _clippedUVs.clear(); - clippedTriangles.clear(); + size_t index = 0; + clippedVertices.clear(); + _clippedUVs.clear(); + clippedTriangles.clear(); - size_t i = 0; - continue_outer: - for (; i < trianglesLength; i += 3) { - int vertexOffset = triangles[i] * stride; - float x1 = vertices[vertexOffset], y1 = vertices[vertexOffset + 1]; - float u1 = uvs[vertexOffset], v1 = uvs[vertexOffset + 1]; + size_t i = 0; +continue_outer: + for (; i < trianglesLength; i += 3) { + int vertexOffset = triangles[i] * stride; + float x1 = vertices[vertexOffset], y1 = vertices[vertexOffset + 1]; + float u1 = uvs[vertexOffset], v1 = uvs[vertexOffset + 1]; - vertexOffset = triangles[i + 1] * stride; - float x2 = vertices[vertexOffset], y2 = vertices[vertexOffset + 1]; - float u2 = uvs[vertexOffset], v2 = uvs[vertexOffset + 1]; + vertexOffset = triangles[i + 1] * stride; + float x2 = vertices[vertexOffset], y2 = vertices[vertexOffset + 1]; + float u2 = uvs[vertexOffset], v2 = uvs[vertexOffset + 1]; - vertexOffset = triangles[i + 2] * stride; - float x3 = vertices[vertexOffset], y3 = vertices[vertexOffset + 1]; - float u3 = uvs[vertexOffset], v3 = uvs[vertexOffset + 1]; + vertexOffset = triangles[i + 2] * stride; + float x3 = vertices[vertexOffset], y3 = vertices[vertexOffset + 1]; + float u3 = uvs[vertexOffset], v3 = uvs[vertexOffset + 1]; - for (size_t p = 0; p < polygonsCount; p++) { - size_t s = clippedVertices.size(); - if (clip(x1, y1, x2, y2, x3, y3, &(*polygons[p]), &clipOutput)) { - size_t clipOutputLength = clipOutput.size(); - if (clipOutputLength == 0) continue; - float d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1; - float d = 1 / (d0 * d2 + d1 * (y1 - y3)); + for (size_t p = 0; p < polygonsCount; p++) { + size_t s = clippedVertices.size(); + if (clip(x1, y1, x2, y2, x3, y3, &(*polygons[p]), &clipOutput)) { + size_t clipOutputLength = clipOutput.size(); + if (clipOutputLength == 0) continue; + float d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1; + float d = 1 / (d0 * d2 + d1 * (y1 - y3)); - size_t clipOutputCount = clipOutputLength >> 1; - clippedVertices.setSize(s + clipOutputCount * 2, 0); - _clippedUVs.setSize(s + clipOutputCount * 2, 0); - for (size_t ii = 0; ii < clipOutputLength; ii += 2) { - float x = clipOutput[ii], y = clipOutput[ii + 1]; - clippedVertices[s] = x; - clippedVertices[s + 1] = y; - float c0 = x - x3, c1 = y - y3; - float a = (d0 * c0 + d1 * c1) * d; - float b = (d4 * c0 + d2 * c1) * d; - float c = 1 - a - b; - _clippedUVs[s] = u1 * a + u2 * b + u3 * c; - _clippedUVs[s + 1] = v1 * a + v2 * b + v3 * c; - s += 2; - } + size_t clipOutputCount = clipOutputLength >> 1; + clippedVertices.setSize(s + clipOutputCount * 2, 0); + _clippedUVs.setSize(s + clipOutputCount * 2, 0); + for (size_t ii = 0; ii < clipOutputLength; ii += 2) { + float x = clipOutput[ii], y = clipOutput[ii + 1]; + clippedVertices[s] = x; + clippedVertices[s + 1] = y; + float c0 = x - x3, c1 = y - y3; + float a = (d0 * c0 + d1 * c1) * d; + float b = (d4 * c0 + d2 * c1) * d; + float c = 1 - a - b; + _clippedUVs[s] = u1 * a + u2 * b + u3 * c; + _clippedUVs[s + 1] = v1 * a + v2 * b + v3 * c; + s += 2; + } - s = clippedTriangles.size(); - clippedTriangles.setSize(s + 3 * (clipOutputCount - 2), 0); - clipOutputCount--; - for (size_t ii = 1; ii < clipOutputCount; ii++) { - clippedTriangles[s] = (unsigned short)(index); - clippedTriangles[s + 1] = (unsigned short)(index + ii); - clippedTriangles[s + 2] = (unsigned short)(index + ii + 1); - s += 3; - } - index += clipOutputCount + 1; - } else { - clippedVertices.setSize(s + 3 * 2, 0); - _clippedUVs.setSize(s + 3 * 2, 0); - clippedVertices[s] = x1; - clippedVertices[s + 1] = y1; - clippedVertices[s + 2] = x2; - clippedVertices[s + 3] = y2; - clippedVertices[s + 4] = x3; - clippedVertices[s + 5] = y3; + s = clippedTriangles.size(); + clippedTriangles.setSize(s + 3 * (clipOutputCount - 2), 0); + clipOutputCount--; + for (size_t ii = 1; ii < clipOutputCount; ii++) { + clippedTriangles[s] = (unsigned short)(index); + clippedTriangles[s + 1] = (unsigned short)(index + ii); + clippedTriangles[s + 2] = (unsigned short)(index + ii + 1); + s += 3; + } + index += clipOutputCount + 1; + } else { + clippedVertices.setSize(s + 3 * 2, 0); + _clippedUVs.setSize(s + 3 * 2, 0); + clippedVertices[s] = x1; + clippedVertices[s + 1] = y1; + clippedVertices[s + 2] = x2; + clippedVertices[s + 3] = y2; + clippedVertices[s + 4] = x3; + clippedVertices[s + 5] = y3; - _clippedUVs[s] = u1; - _clippedUVs[s + 1] = v1; - _clippedUVs[s + 2] = u2; - _clippedUVs[s + 3] = v2; - _clippedUVs[s + 4] = u3; - _clippedUVs[s + 5] = v3; + _clippedUVs[s] = u1; + _clippedUVs[s + 1] = v1; + _clippedUVs[s + 2] = u2; + _clippedUVs[s + 3] = v2; + _clippedUVs[s + 4] = u3; + _clippedUVs[s + 5] = v3; - s = clippedTriangles.size(); - clippedTriangles.setSize(s + 3, 0); - clippedTriangles[s] = (unsigned short)index; - clippedTriangles[s + 1] = (unsigned short)(index + 1); - clippedTriangles[s + 2] = (unsigned short)(index + 2); - index += 3; - i += 3; - goto continue_outer; - } - } - } + s = clippedTriangles.size(); + clippedTriangles.setSize(s + 3, 0); + clippedTriangles[s] = (unsigned short)index; + clippedTriangles[s + 1] = (unsigned short)(index + 1); + clippedTriangles[s + 2] = (unsigned short)(index + 2); + index += 3; + i += 3; + goto continue_outer; + } + } + } } bool SkeletonClipping::isClipping() { - return _clipAttachment != NULL; + return _clipAttachment != NULL; } Vector &SkeletonClipping::getClippedVertices() { - return _clippedVertices; + return _clippedVertices; } Vector &SkeletonClipping::getClippedTriangles() { - return _clippedTriangles; + return _clippedTriangles; } Vector &SkeletonClipping::getClippedUVs() { - return _clippedUVs; + return _clippedUVs; } bool SkeletonClipping::clip(float x1, float y1, float x2, float y2, float x3, float y3, Vector *clippingArea, - Vector *output -) { - Vector *originalOutput = output; - bool clipped = false; + Vector *output) { + Vector *originalOutput = output; + bool clipped = false; - // Avoid copy at the end. - Vector *input; - if (clippingArea->size() % 4 >= 2) { - input = output; - output = &_scratch; - } else - input = &_scratch; + // Avoid copy at the end. + Vector *input; + if (clippingArea->size() % 4 >= 2) { + input = output; + output = &_scratch; + } else + input = &_scratch; - input->clear(); - input->add(x1); - input->add(y1); - input->add(x2); - input->add(y2); - input->add(x3); - input->add(y3); - input->add(x1); - input->add(y1); - output->clear(); + input->clear(); + input->add(x1); + input->add(y1); + input->add(x2); + input->add(y2); + input->add(x3); + input->add(y3); + input->add(x1); + input->add(y1); + output->clear(); - Vector &clippingVertices = *clippingArea; - size_t clippingVerticesLast = clippingArea->size() - 4; - for (size_t i = 0;; i += 2) { - float edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1]; - float edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3]; - float deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2; + Vector &clippingVertices = *clippingArea; + size_t clippingVerticesLast = clippingArea->size() - 4; + for (size_t i = 0;; i += 2) { + float edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1]; + float edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3]; + float deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2; - Vector &inputVertices = *input; - size_t inputVerticesLength = input->size() - 2, outputStart = output->size(); - for (size_t ii = 0; ii < inputVerticesLength; ii += 2) { - float inputX = inputVertices[ii], inputY = inputVertices[ii + 1]; - float inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3]; - bool side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0; - if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) { - if (side2) { - // v1 inside, v2 inside - output->add(inputX2); - output->add(inputY2); - continue; - } - // v1 inside, v2 outside - float c0 = inputY2 - inputY, c2 = inputX2 - inputX; - float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); - if (MathUtil::abs(s) > 0.000001f) { - float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; - output->add(edgeX + (edgeX2 - edgeX) * ua); - output->add(edgeY + (edgeY2 - edgeY) * ua); - } else { - output->add(edgeX); - output->add(edgeY); - } - } else if (side2) { - // v1 outside, v2 inside - float c0 = inputY2 - inputY, c2 = inputX2 - inputX; - float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); - if (MathUtil::abs(s) > 0.000001f) { - float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; - output->add(edgeX + (edgeX2 - edgeX) * ua); - output->add(edgeY + (edgeY2 - edgeY) * ua); - } else { - output->add(edgeX); - output->add(edgeY); - } - output->add(inputX2); - output->add(inputY2); - } - clipped = true; - } + Vector &inputVertices = *input; + size_t inputVerticesLength = input->size() - 2, outputStart = output->size(); + for (size_t ii = 0; ii < inputVerticesLength; ii += 2) { + float inputX = inputVertices[ii], inputY = inputVertices[ii + 1]; + float inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3]; + bool side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0; + if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) { + if (side2) { + // v1 inside, v2 inside + output->add(inputX2); + output->add(inputY2); + continue; + } + // v1 inside, v2 outside + float c0 = inputY2 - inputY, c2 = inputX2 - inputX; + float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); + if (MathUtil::abs(s) > 0.000001f) { + float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; + output->add(edgeX + (edgeX2 - edgeX) * ua); + output->add(edgeY + (edgeY2 - edgeY) * ua); + } else { + output->add(edgeX); + output->add(edgeY); + } + } else if (side2) { + // v1 outside, v2 inside + float c0 = inputY2 - inputY, c2 = inputX2 - inputX; + float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); + if (MathUtil::abs(s) > 0.000001f) { + float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; + output->add(edgeX + (edgeX2 - edgeX) * ua); + output->add(edgeY + (edgeY2 - edgeY) * ua); + } else { + output->add(edgeX); + output->add(edgeY); + } + output->add(inputX2); + output->add(inputY2); + } + clipped = true; + } - if (outputStart == output->size()) { - // All edges outside. - originalOutput->clear(); - return true; - } + if (outputStart == output->size()) { + // All edges outside. + originalOutput->clear(); + return true; + } - output->add((*output)[0]); - output->add((*output)[1]); + output->add((*output)[0]); + output->add((*output)[1]); - if (i == clippingVerticesLast) { - break; - } - Vector *temp = output; - output = input; - output->clear(); - input = temp; - } + if (i == clippingVerticesLast) { + break; + } + Vector *temp = output; + output = input; + output->clear(); + input = temp; + } - if (originalOutput != output) { - originalOutput->clear(); - for (size_t i = 0, n = output->size() - 2; i < n; ++i) - originalOutput->add((*output)[i]); - } else - originalOutput->setSize(originalOutput->size() - 2, 0); + if (originalOutput != output) { + originalOutput->clear(); + for (size_t i = 0, n = output->size() - 2; i < n; ++i) + originalOutput->add((*output)[i]); + } else + originalOutput->setSize(originalOutput->size() - 2, 0); - return clipped; + return clipped; } void SkeletonClipping::makeClockwise(Vector &polygon) { - size_t verticeslength = polygon.size(); + size_t verticeslength = polygon.size(); - float area = polygon[verticeslength - 2] * polygon[1] - polygon[0] * polygon[verticeslength - 1]; - float p1x, p1y, p2x, p2y; + float area = polygon[verticeslength - 2] * polygon[1] - polygon[0] * polygon[verticeslength - 1]; + float p1x, p1y, p2x, p2y; - for (size_t i = 0, n = verticeslength - 3; i < n; i += 2) { - p1x = polygon[i]; - p1y = polygon[i + 1]; - p2x = polygon[i + 2]; - p2y = polygon[i + 3]; - area += p1x * p2y - p2x * p1y; - } + for (size_t i = 0, n = verticeslength - 3; i < n; i += 2) { + p1x = polygon[i]; + p1y = polygon[i + 1]; + p2x = polygon[i + 2]; + p2y = polygon[i + 3]; + area += p1x * p2y - p2x * p1y; + } - if (area < 0) return; + if (area < 0) return; - for (size_t i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) { - float x = polygon[i], y = polygon[i + 1]; - int other = lastX - i; - polygon[i] = polygon[other]; - polygon[i + 1] = polygon[other + 1]; - polygon[other] = x; - polygon[other + 1] = y; - } + for (size_t i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) { + float x = polygon[i], y = polygon[i + 1]; + int other = lastX - i; + polygon[i] = polygon[other]; + polygon[i + 1] = polygon[other + 1]; + polygon[other] = x; + polygon[other + 1] = y; + } } diff --git a/native/cocos/editor-support/spine/SkeletonClipping.h b/native/cocos/editor-support/spine/SkeletonClipping.h index ae8bddb7c1..a75c5d5ec3 100644 --- a/native/cocos/editor-support/spine/SkeletonClipping.h +++ b/native/cocos/editor-support/spine/SkeletonClipping.h @@ -34,46 +34,46 @@ #include namespace spine { - class Slot; - class ClippingAttachment; +class Slot; +class ClippingAttachment; - class SP_API SkeletonClipping : public SpineObject { - public: - SkeletonClipping(); +class SP_API SkeletonClipping : public SpineObject { +public: + SkeletonClipping(); - size_t clipStart(Slot& slot, ClippingAttachment* clip); + size_t clipStart(Slot& slot, ClippingAttachment* clip); - void clipEnd(Slot& slot); + void clipEnd(Slot& slot); - void clipEnd(); + void clipEnd(); - void clipTriangles(float* vertices, unsigned short* triangles, size_t trianglesLength, float* uvs, size_t stride); + void clipTriangles(float* vertices, unsigned short* triangles, size_t trianglesLength, float* uvs, size_t stride); - void clipTriangles(Vector& vertices, Vector& triangles, Vector& uvs, size_t stride); + void clipTriangles(Vector& vertices, Vector& triangles, Vector& uvs, size_t stride); - bool isClipping(); + bool isClipping(); - Vector& getClippedVertices(); - Vector& getClippedTriangles(); - Vector& getClippedUVs(); + Vector& getClippedVertices(); + Vector& getClippedTriangles(); + Vector& getClippedUVs(); - private: - Triangulator _triangulator; - Vector _clippingPolygon; - Vector _clipOutput; - Vector _clippedVertices; - Vector _clippedTriangles; - Vector _clippedUVs; - Vector _scratch; - ClippingAttachment* _clipAttachment; - Vector< Vector* > *_clippingPolygons; +private: + Triangulator _triangulator; + Vector _clippingPolygon; + Vector _clipOutput; + Vector _clippedVertices; + Vector _clippedTriangles; + Vector _clippedUVs; + Vector _scratch; + ClippingAttachment* _clipAttachment; + Vector*>* _clippingPolygons; - /** Clips the input triangle against the convex, clockwise clipping area. If the triangle lies entirely within the clipping + /** Clips the input triangle against the convex, clockwise clipping area. If the triangle lies entirely within the clipping * area, false is returned. The clipping area must duplicate the first vertex at the end of the vertices list. */ - bool clip(float x1, float y1, float x2, float y2, float x3, float y3, Vector* clippingArea, Vector* output); + bool clip(float x1, float y1, float x2, float y2, float x3, float y3, Vector* clippingArea, Vector* output); - static void makeClockwise(Vector& polygon); - }; -} + static void makeClockwise(Vector& polygon); +}; +} // namespace spine #endif /* Spine_SkeletonClipping_h */ diff --git a/native/cocos/editor-support/spine/SkeletonData.cpp b/native/cocos/editor-support/spine/SkeletonData.cpp index a23ab043b8..a51584fdcb 100644 --- a/native/cocos/editor-support/spine/SkeletonData.cpp +++ b/native/cocos/editor-support/spine/SkeletonData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -46,197 +46,195 @@ using namespace spine; -SkeletonData::SkeletonData() : - _name(), - _defaultSkin(NULL), - _x(0), - _y(0), - _width(0), - _height(0), - _version(), - _hash(), - _fps(0), - _imagesPath() { +SkeletonData::SkeletonData() : _name(), + _defaultSkin(NULL), + _x(0), + _y(0), + _width(0), + _height(0), + _version(), + _hash(), + _fps(0), + _imagesPath() { } SkeletonData::~SkeletonData() { - ContainerUtil::cleanUpVectorOfPointers(_bones); - ContainerUtil::cleanUpVectorOfPointers(_slots); - ContainerUtil::cleanUpVectorOfPointers(_skins); + ContainerUtil::cleanUpVectorOfPointers(_bones); + ContainerUtil::cleanUpVectorOfPointers(_slots); + ContainerUtil::cleanUpVectorOfPointers(_skins); - _defaultSkin = NULL; + _defaultSkin = NULL; - ContainerUtil::cleanUpVectorOfPointers(_events); - ContainerUtil::cleanUpVectorOfPointers(_animations); - ContainerUtil::cleanUpVectorOfPointers(_ikConstraints); - ContainerUtil::cleanUpVectorOfPointers(_transformConstraints); - ContainerUtil::cleanUpVectorOfPointers(_pathConstraints); - for (size_t i = 0; i < _strings.size(); i++) { - SpineExtension::free(_strings[i], __FILE__, __LINE__); - } + ContainerUtil::cleanUpVectorOfPointers(_events); + ContainerUtil::cleanUpVectorOfPointers(_animations); + ContainerUtil::cleanUpVectorOfPointers(_ikConstraints); + ContainerUtil::cleanUpVectorOfPointers(_transformConstraints); + ContainerUtil::cleanUpVectorOfPointers(_pathConstraints); + for (size_t i = 0; i < _strings.size(); i++) { + SpineExtension::free(_strings[i], __FILE__, __LINE__); + } } BoneData *SkeletonData::findBone(const String &boneName) { - return ContainerUtil::findWithName(_bones, boneName); + return ContainerUtil::findWithName(_bones, boneName); } int SkeletonData::findBoneIndex(const String &boneName) { - return ContainerUtil::findIndexWithName(_bones, boneName); + return ContainerUtil::findIndexWithName(_bones, boneName); } SlotData *SkeletonData::findSlot(const String &slotName) { - return ContainerUtil::findWithName(_slots, slotName); + return ContainerUtil::findWithName(_slots, slotName); } int SkeletonData::findSlotIndex(const String &slotName) { - return ContainerUtil::findIndexWithName(_slots, slotName); + return ContainerUtil::findIndexWithName(_slots, slotName); } Skin *SkeletonData::findSkin(const String &skinName) { - return ContainerUtil::findWithName(_skins, skinName); + return ContainerUtil::findWithName(_skins, skinName); } spine::EventData *SkeletonData::findEvent(const String &eventDataName) { - return ContainerUtil::findWithName(_events, eventDataName); + return ContainerUtil::findWithName(_events, eventDataName); } Animation *SkeletonData::findAnimation(const String &animationName) { - return ContainerUtil::findWithName(_animations, animationName); + return ContainerUtil::findWithName(_animations, animationName); } IkConstraintData *SkeletonData::findIkConstraint(const String &constraintName) { - return ContainerUtil::findWithName(_ikConstraints, constraintName); + return ContainerUtil::findWithName(_ikConstraints, constraintName); } TransformConstraintData *SkeletonData::findTransformConstraint(const String &constraintName) { - return ContainerUtil::findWithName(_transformConstraints, constraintName); + return ContainerUtil::findWithName(_transformConstraints, constraintName); } PathConstraintData *SkeletonData::findPathConstraint(const String &constraintName) { - return ContainerUtil::findWithName(_pathConstraints, constraintName); + return ContainerUtil::findWithName(_pathConstraints, constraintName); } int SkeletonData::findPathConstraintIndex(const String &pathConstraintName) { - return ContainerUtil::findIndexWithName(_pathConstraints, pathConstraintName); + return ContainerUtil::findIndexWithName(_pathConstraints, pathConstraintName); } const String &SkeletonData::getName() { - return _name; + return _name; } void SkeletonData::setName(const String &inValue) { - _name = inValue; + _name = inValue; } Vector &SkeletonData::getBones() { - return _bones; + return _bones; } Vector &SkeletonData::getSlots() { - return _slots; + return _slots; } Vector &SkeletonData::getSkins() { - return _skins; + return _skins; } Skin *SkeletonData::getDefaultSkin() { - return _defaultSkin; + return _defaultSkin; } void SkeletonData::setDefaultSkin(Skin *inValue) { - _defaultSkin = inValue; + _defaultSkin = inValue; } Vector &SkeletonData::getEvents() { - return _events; + return _events; } Vector &SkeletonData::getAnimations() { - return _animations; + return _animations; } Vector &SkeletonData::getIkConstraints() { - return _ikConstraints; + return _ikConstraints; } Vector &SkeletonData::getTransformConstraints() { - return _transformConstraints; + return _transformConstraints; } Vector &SkeletonData::getPathConstraints() { - return _pathConstraints; + return _pathConstraints; } float SkeletonData::getX() { - return _x; + return _x; } void SkeletonData::setX(float inValue) { - _x = inValue; + _x = inValue; } float SkeletonData::getY() { - return _y; + return _y; } void SkeletonData::setY(float inValue) { - _y = inValue; + _y = inValue; } float SkeletonData::getWidth() { - return _width; + return _width; } void SkeletonData::setWidth(float inValue) { - _width = inValue; + _width = inValue; } float SkeletonData::getHeight() { - return _height; + return _height; } void SkeletonData::setHeight(float inValue) { - _height = inValue; + _height = inValue; } const String &SkeletonData::getVersion() { - return _version; + return _version; } void SkeletonData::setVersion(const String &inValue) { - _version = inValue; + _version = inValue; } const String &SkeletonData::getHash() { - return _hash; + return _hash; } void SkeletonData::setHash(const String &inValue) { - _hash = inValue; + _hash = inValue; } const String &SkeletonData::getImagesPath() { - return _imagesPath; + return _imagesPath; } void SkeletonData::setImagesPath(const String &inValue) { - _imagesPath = inValue; + _imagesPath = inValue; } - const String &SkeletonData::getAudioPath() { - return _audioPath; + return _audioPath; } void SkeletonData::setAudioPath(const String &inValue) { - _audioPath = inValue; + _audioPath = inValue; } float SkeletonData::getFps() { - return _fps; + return _fps; } void SkeletonData::setFps(float inValue) { - _fps = inValue; + _fps = inValue; } diff --git a/native/cocos/editor-support/spine/SkeletonData.h b/native/cocos/editor-support/spine/SkeletonData.h index 90e629b12a..1bd2949eb6 100644 --- a/native/cocos/editor-support/spine/SkeletonData.h +++ b/native/cocos/editor-support/spine/SkeletonData.h @@ -52,140 +52,140 @@ class PathConstraintData; /// Stores the setup pose and all of the stateless data for a skeleton. class SP_API SkeletonData : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; - friend class Skeleton; + friend class Skeleton; public: - SkeletonData(); + SkeletonData(); - ~SkeletonData(); + ~SkeletonData(); - /// Finds a bone by comparing each bone's name. - /// It is more efficient to cache the results of this method than to call it multiple times. - /// @return May be NULL. - BoneData *findBone(const String &boneName); + /// Finds a bone by comparing each bone's name. + /// It is more efficient to cache the results of this method than to call it multiple times. + /// @return May be NULL. + BoneData *findBone(const String &boneName); - /// @return -1 if the bone was not found. - int findBoneIndex(const String &boneName); + /// @return -1 if the bone was not found. + int findBoneIndex(const String &boneName); - /// @return May be NULL. - SlotData *findSlot(const String &slotName); + /// @return May be NULL. + SlotData *findSlot(const String &slotName); - /// @return -1 if the slot was not found. - int findSlotIndex(const String &slotName); + /// @return -1 if the slot was not found. + int findSlotIndex(const String &slotName); - /// @return May be NULL. - Skin *findSkin(const String &skinName); + /// @return May be NULL. + Skin *findSkin(const String &skinName); - /// @return May be NULL. - spine::EventData *findEvent(const String &eventDataName); + /// @return May be NULL. + spine::EventData *findEvent(const String &eventDataName); - /// @return May be NULL. - Animation *findAnimation(const String &animationName); + /// @return May be NULL. + Animation *findAnimation(const String &animationName); - /// @return May be NULL. - IkConstraintData *findIkConstraint(const String &constraintName); + /// @return May be NULL. + IkConstraintData *findIkConstraint(const String &constraintName); - /// @return May be NULL. - TransformConstraintData *findTransformConstraint(const String &constraintName); + /// @return May be NULL. + TransformConstraintData *findTransformConstraint(const String &constraintName); - /// @return May be NULL. - PathConstraintData *findPathConstraint(const String &constraintName); + /// @return May be NULL. + PathConstraintData *findPathConstraint(const String &constraintName); - /// @return -1 if the path constraint was not found. - int findPathConstraintIndex(const String &pathConstraintName); + /// @return -1 if the path constraint was not found. + int findPathConstraintIndex(const String &pathConstraintName); - const String &getName(); + const String &getName(); - void setName(const String &inValue); + void setName(const String &inValue); - /// The skeleton's bones, sorted parent first. The root bone is always the first bone. - Vector &getBones(); + /// The skeleton's bones, sorted parent first. The root bone is always the first bone. + Vector &getBones(); - Vector &getSlots(); + Vector &getSlots(); - /// All skins, including the default skin. - Vector &getSkins(); + /// All skins, including the default skin. + Vector &getSkins(); - /// The skeleton's default skin. - /// By default this skin contains all attachments that were not in a skin in Spine. - /// @return May be NULL. - Skin *getDefaultSkin(); + /// The skeleton's default skin. + /// By default this skin contains all attachments that were not in a skin in Spine. + /// @return May be NULL. + Skin *getDefaultSkin(); - void setDefaultSkin(Skin *inValue); + void setDefaultSkin(Skin *inValue); - Vector &getEvents(); + Vector &getEvents(); - Vector &getAnimations(); + Vector &getAnimations(); - Vector &getIkConstraints(); + Vector &getIkConstraints(); - Vector &getTransformConstraints(); + Vector &getTransformConstraints(); - Vector &getPathConstraints(); + Vector &getPathConstraints(); - float getX(); + float getX(); - void setX(float inValue); + void setX(float inValue); - float getY(); + float getY(); - void setY(float inValue); + void setY(float inValue); - float getWidth(); + float getWidth(); - void setWidth(float inValue); + void setWidth(float inValue); - float getHeight(); + float getHeight(); - void setHeight(float inValue); + void setHeight(float inValue); - /// The Spine version used to export this data, or NULL. - const String &getVersion(); + /// The Spine version used to export this data, or NULL. + const String &getVersion(); - void setVersion(const String &inValue); + void setVersion(const String &inValue); - const String &getHash(); + const String &getHash(); - void setHash(const String &inValue); + void setHash(const String &inValue); - const String &getImagesPath(); + const String &getImagesPath(); - void setImagesPath(const String &inValue); + void setImagesPath(const String &inValue); - const String &getAudioPath(); + const String &getAudioPath(); - void setAudioPath(const String &inValue); + void setAudioPath(const String &inValue); - /// The dopesheet FPS in Spine. Available only when nonessential data was exported. - float getFps(); + /// The dopesheet FPS in Spine. Available only when nonessential data was exported. + float getFps(); - void setFps(float inValue); + void setFps(float inValue); private: - String _name; - Vector _bones; // Ordered parents first - Vector _slots; // Setup pose draw order. - Vector _skins; - Skin *_defaultSkin; - Vector _events; - Vector _animations; - Vector _ikConstraints; - Vector _transformConstraints; - Vector _pathConstraints; - float _x, _y, _width, _height; - String _version; - String _hash; - Vector _strings; + String _name; + Vector _bones; // Ordered parents first + Vector _slots; // Setup pose draw order. + Vector _skins; + Skin *_defaultSkin; + Vector _events; + Vector _animations; + Vector _ikConstraints; + Vector _transformConstraints; + Vector _pathConstraints; + float _x, _y, _width, _height; + String _version; + String _hash; + Vector _strings; - // Nonessential. - float _fps; - String _imagesPath; - String _audioPath; + // Nonessential. + float _fps; + String _imagesPath; + String _audioPath; }; -} +} // namespace spine #endif /* Spine_SkeletonData_h */ diff --git a/native/cocos/editor-support/spine/SkeletonJson.cpp b/native/cocos/editor-support/spine/SkeletonJson.cpp index 9d2d14b8e3..6a9067cda4 100644 --- a/native/cocos/editor-support/spine/SkeletonJson.cpp +++ b/native/cocos/editor-support/spine/SkeletonJson.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -75,1167 +75,1186 @@ #include #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) -#define strdup _strdup + #define strdup _strdup #endif using namespace spine; -SkeletonJson::SkeletonJson(Atlas *atlas) : _attachmentLoader(new(__FILE__, __LINE__) AtlasAttachmentLoader(atlas)), - _scale(1), _ownsLoader(true) -{} +SkeletonJson::SkeletonJson(Atlas *atlas) : _attachmentLoader(new (__FILE__, __LINE__) AtlasAttachmentLoader(atlas)), + _scale(1), + _ownsLoader(true) {} -SkeletonJson::SkeletonJson(AttachmentLoader *attachmentLoader) : _attachmentLoader(attachmentLoader), _scale(1), - _ownsLoader(false) -{ - assert(_attachmentLoader != NULL); +SkeletonJson::SkeletonJson(AttachmentLoader *attachmentLoader) : _attachmentLoader(attachmentLoader), _scale(1), _ownsLoader(false) { + assert(_attachmentLoader != NULL); } SkeletonJson::~SkeletonJson() { - ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes); + ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes); - if (_ownsLoader) delete _attachmentLoader; + if (_ownsLoader) delete _attachmentLoader; } SkeletonData *SkeletonJson::readSkeletonDataFile(const String &path) { - int length; - SkeletonData *skeletonData; - const char *json = SpineExtension::readFile(path, &length); - if (length == 0 || !json) { - setError(NULL, "Unable to read skeleton file: ", path); - return NULL; - } + int length; + SkeletonData *skeletonData; + const char *json = SpineExtension::readFile(path, &length); + if (length == 0 || !json) { + setError(NULL, "Unable to read skeleton file: ", path); + return NULL; + } - skeletonData = readSkeletonData(json); + skeletonData = readSkeletonData(json); - SpineExtension::free(json, __FILE__, __LINE__); + SpineExtension::free(json, __FILE__, __LINE__); - return skeletonData; + return skeletonData; } SkeletonData *SkeletonJson::readSkeletonData(const char *json) { - int i, ii; - SkeletonData *skeletonData; - Json *root, *skeleton, *bones, *boneMap, *ik, *transform, *path, *slots, *skins, *animations, *events; + int i, ii; + SkeletonData *skeletonData; + Json *root, *skeleton, *bones, *boneMap, *ik, *transform, *path, *slots, *skins, *animations, *events; - _error = ""; - _linkedMeshes.clear(); + _error = ""; + _linkedMeshes.clear(); - root = new Json(json); + root = new Json(json); - if (!root) { - setError(NULL, "Invalid skeleton JSON: ", Json::getError()); - return NULL; - } + if (!root) { + setError(NULL, "Invalid skeleton JSON: ", Json::getError()); + return NULL; + } - skeletonData = new(__FILE__, __LINE__) SkeletonData(); + skeletonData = new (__FILE__, __LINE__) SkeletonData(); - skeleton = Json::getItem(root, "skeleton"); - if (skeleton) { - skeletonData->_hash = Json::getString(skeleton, "hash", 0); - skeletonData->_version = Json::getString(skeleton, "spine", 0); - skeletonData->_x = Json::getFloat(skeleton, "x", 0); - skeletonData->_y = Json::getFloat(skeleton, "y", 0); - skeletonData->_width = Json::getFloat(skeleton, "width", 0); - skeletonData->_height = Json::getFloat(skeleton, "height", 0); - skeletonData->_fps = Json::getFloat(skeleton, "fps", 30); - skeletonData->_audioPath = Json::getString(skeleton, "audio", 0); - skeletonData->_imagesPath = Json::getString(skeleton, "images", 0); - } + skeleton = Json::getItem(root, "skeleton"); + if (skeleton) { + skeletonData->_hash = Json::getString(skeleton, "hash", 0); + skeletonData->_version = Json::getString(skeleton, "spine", 0); + skeletonData->_x = Json::getFloat(skeleton, "x", 0); + skeletonData->_y = Json::getFloat(skeleton, "y", 0); + skeletonData->_width = Json::getFloat(skeleton, "width", 0); + skeletonData->_height = Json::getFloat(skeleton, "height", 0); + skeletonData->_fps = Json::getFloat(skeleton, "fps", 30); + skeletonData->_audioPath = Json::getString(skeleton, "audio", 0); + skeletonData->_imagesPath = Json::getString(skeleton, "images", 0); + } - /* Bones. */ - bones = Json::getItem(root, "bones"); - skeletonData->_bones.setSize(bones->_size, 0); - int bonesCount = 0; - for (boneMap = bones->_child, i = 0; boneMap; boneMap = boneMap->_next, ++i) { - BoneData *data; - const char *transformMode; + /* Bones. */ + bones = Json::getItem(root, "bones"); + skeletonData->_bones.setSize(bones->_size, 0); + int bonesCount = 0; + for (boneMap = bones->_child, i = 0; boneMap; boneMap = boneMap->_next, ++i) { + BoneData *data; + const char *transformMode; - BoneData *parent = 0; - const char *parentName = Json::getString(boneMap, "parent", 0); - if (parentName) { - parent = skeletonData->findBone(parentName); - if (!parent) { - delete skeletonData; - setError(root, "Parent bone not found: ", parentName); - return NULL; - } - } + BoneData *parent = 0; + const char *parentName = Json::getString(boneMap, "parent", 0); + if (parentName) { + parent = skeletonData->findBone(parentName); + if (!parent) { + delete skeletonData; + setError(root, "Parent bone not found: ", parentName); + return NULL; + } + } - data = new(__FILE__, __LINE__) BoneData(bonesCount, Json::getString(boneMap, "name", 0), parent); + data = new (__FILE__, __LINE__) BoneData(bonesCount, Json::getString(boneMap, "name", 0), parent); - data->_length = Json::getFloat(boneMap, "length", 0) * _scale; - data->_x = Json::getFloat(boneMap, "x", 0) * _scale; - data->_y = Json::getFloat(boneMap, "y", 0) * _scale; - data->_rotation = Json::getFloat(boneMap, "rotation", 0); - data->_scaleX = Json::getFloat(boneMap, "scaleX", 1); - data->_scaleY = Json::getFloat(boneMap, "scaleY", 1); - data->_shearX = Json::getFloat(boneMap, "shearX", 0); - data->_shearY = Json::getFloat(boneMap, "shearY", 0); - transformMode = Json::getString(boneMap, "transform", "normal"); - data->_transformMode = TransformMode_Normal; - if (strcmp(transformMode, "normal") == 0) data->_transformMode = TransformMode_Normal; - else if (strcmp(transformMode, "onlyTranslation") == 0) data->_transformMode = TransformMode_OnlyTranslation; - else if (strcmp(transformMode, "noRotationOrReflection") == 0) data->_transformMode = TransformMode_NoRotationOrReflection; - else if (strcmp(transformMode, "noScale") == 0) data->_transformMode = TransformMode_NoScale; - else if (strcmp(transformMode, "noScaleOrReflection") == 0) data->_transformMode = TransformMode_NoScaleOrReflection; - data->_skinRequired = Json::getBoolean(boneMap, "skin", false); + data->_length = Json::getFloat(boneMap, "length", 0) * _scale; + data->_x = Json::getFloat(boneMap, "x", 0) * _scale; + data->_y = Json::getFloat(boneMap, "y", 0) * _scale; + data->_rotation = Json::getFloat(boneMap, "rotation", 0); + data->_scaleX = Json::getFloat(boneMap, "scaleX", 1); + data->_scaleY = Json::getFloat(boneMap, "scaleY", 1); + data->_shearX = Json::getFloat(boneMap, "shearX", 0); + data->_shearY = Json::getFloat(boneMap, "shearY", 0); + transformMode = Json::getString(boneMap, "transform", "normal"); + data->_transformMode = TransformMode_Normal; + if (strcmp(transformMode, "normal") == 0) + data->_transformMode = TransformMode_Normal; + else if (strcmp(transformMode, "onlyTranslation") == 0) + data->_transformMode = TransformMode_OnlyTranslation; + else if (strcmp(transformMode, "noRotationOrReflection") == 0) + data->_transformMode = TransformMode_NoRotationOrReflection; + else if (strcmp(transformMode, "noScale") == 0) + data->_transformMode = TransformMode_NoScale; + else if (strcmp(transformMode, "noScaleOrReflection") == 0) + data->_transformMode = TransformMode_NoScaleOrReflection; + data->_skinRequired = Json::getBoolean(boneMap, "skin", false); - skeletonData->_bones[i] = data; - bonesCount++; - } + skeletonData->_bones[i] = data; + bonesCount++; + } - /* Slots. */ - slots = Json::getItem(root, "slots"); - if (slots) { - Json *slotMap; - skeletonData->_slots.ensureCapacity(slots->_size); - skeletonData->_slots.setSize(slots->_size, 0); - for (slotMap = slots->_child, i = 0; slotMap; slotMap = slotMap->_next, ++i) { - SlotData *data; - const char *color; - const char *dark; - Json *item; + /* Slots. */ + slots = Json::getItem(root, "slots"); + if (slots) { + Json *slotMap; + skeletonData->_slots.ensureCapacity(slots->_size); + skeletonData->_slots.setSize(slots->_size, 0); + for (slotMap = slots->_child, i = 0; slotMap; slotMap = slotMap->_next, ++i) { + SlotData *data; + const char *color; + const char *dark; + Json *item; - const char *boneName = Json::getString(slotMap, "bone", 0); - BoneData *boneData = skeletonData->findBone(boneName); - if (!boneData) { - delete skeletonData; - setError(root, "Slot bone not found: ", boneName); - return NULL; - } + const char *boneName = Json::getString(slotMap, "bone", 0); + BoneData *boneData = skeletonData->findBone(boneName); + if (!boneData) { + delete skeletonData; + setError(root, "Slot bone not found: ", boneName); + return NULL; + } - data = new(__FILE__, __LINE__) SlotData(i, Json::getString(slotMap, "name", 0), *boneData); + data = new (__FILE__, __LINE__) SlotData(i, Json::getString(slotMap, "name", 0), *boneData); - color = Json::getString(slotMap, "color", 0); - if (color) { - Color &c = data->getColor(); - c.r = toColor(color, 0); - c.g = toColor(color, 1); - c.b = toColor(color, 2); - c.a = toColor(color, 3); - } + color = Json::getString(slotMap, "color", 0); + if (color) { + Color &c = data->getColor(); + c.r = toColor(color, 0); + c.g = toColor(color, 1); + c.b = toColor(color, 2); + c.a = toColor(color, 3); + } - dark = Json::getString(slotMap, "dark", 0); - if (dark) { - Color &darkColor = data->getDarkColor(); - darkColor.r = toColor(dark, 0); - darkColor.g = toColor(dark, 1); - darkColor.b = toColor(dark, 2); - darkColor.a = 1; - data->setHasDarkColor(true); - } + dark = Json::getString(slotMap, "dark", 0); + if (dark) { + Color &darkColor = data->getDarkColor(); + darkColor.r = toColor(dark, 0); + darkColor.g = toColor(dark, 1); + darkColor.b = toColor(dark, 2); + darkColor.a = 1; + data->setHasDarkColor(true); + } - item = Json::getItem(slotMap, "attachment"); - if (item) data->setAttachmentName(item->_valueString); + item = Json::getItem(slotMap, "attachment"); + if (item) data->setAttachmentName(item->_valueString); - item = Json::getItem(slotMap, "blend"); - if (item) { - if (strcmp(item->_valueString, "additive") == 0) data->_blendMode = BlendMode_Additive; - else if (strcmp(item->_valueString, "multiply") == 0) data->_blendMode = BlendMode_Multiply; - else if (strcmp(item->_valueString, "screen") == 0) data->_blendMode = BlendMode_Screen; - } + item = Json::getItem(slotMap, "blend"); + if (item) { + if (strcmp(item->_valueString, "additive") == 0) + data->_blendMode = BlendMode_Additive; + else if (strcmp(item->_valueString, "multiply") == 0) + data->_blendMode = BlendMode_Multiply; + else if (strcmp(item->_valueString, "screen") == 0) + data->_blendMode = BlendMode_Screen; + } - skeletonData->_slots[i] = data; - } - } + skeletonData->_slots[i] = data; + } + } - /* IK constraints. */ - ik = Json::getItem(root, "ik"); - if (ik) { - Json *constraintMap; - skeletonData->_ikConstraints.ensureCapacity(ik->_size); - skeletonData->_ikConstraints.setSize(ik->_size, 0); - for (constraintMap = ik->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { - const char *targetName; + /* IK constraints. */ + ik = Json::getItem(root, "ik"); + if (ik) { + Json *constraintMap; + skeletonData->_ikConstraints.ensureCapacity(ik->_size); + skeletonData->_ikConstraints.setSize(ik->_size, 0); + for (constraintMap = ik->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { + const char *targetName; - IkConstraintData *data = new(__FILE__, __LINE__) IkConstraintData(Json::getString(constraintMap, "name", 0)); - data->setOrder(Json::getInt(constraintMap, "order", 0)); - data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); + IkConstraintData *data = new (__FILE__, __LINE__) IkConstraintData(Json::getString(constraintMap, "name", 0)); + data->setOrder(Json::getInt(constraintMap, "order", 0)); + data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); - boneMap = Json::getItem(constraintMap, "bones"); - data->_bones.ensureCapacity(boneMap->_size); - data->_bones.setSize(boneMap->_size, 0); - for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { - data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); - if (!data->_bones[ii]) { - delete skeletonData; - setError(root, "IK bone not found: ", boneMap->_valueString); - return NULL; - } - } + boneMap = Json::getItem(constraintMap, "bones"); + data->_bones.ensureCapacity(boneMap->_size); + data->_bones.setSize(boneMap->_size, 0); + for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { + data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); + if (!data->_bones[ii]) { + delete skeletonData; + setError(root, "IK bone not found: ", boneMap->_valueString); + return NULL; + } + } - targetName = Json::getString(constraintMap, "target", 0); - data->_target = skeletonData->findBone(targetName); - if (!data->_target) { - delete skeletonData; - setError(root, "Target bone not found: ", targetName); - return NULL; - } + targetName = Json::getString(constraintMap, "target", 0); + data->_target = skeletonData->findBone(targetName); + if (!data->_target) { + delete skeletonData; + setError(root, "Target bone not found: ", targetName); + return NULL; + } - data->_mix = Json::getFloat(constraintMap, "mix", 1); - data->_softness = Json::getFloat(constraintMap, "softness", 0) * _scale; - data->_bendDirection = Json::getInt(constraintMap, "bendPositive", 1) ? 1 : -1; - data->_compress = Json::getInt(constraintMap, "compress", 0) ? true: false; - data->_stretch = Json::getInt(constraintMap, "stretch", 0) ? true: false; - data->_uniform = Json::getInt(constraintMap, "uniform", 0) ? true: false; + data->_mix = Json::getFloat(constraintMap, "mix", 1); + data->_softness = Json::getFloat(constraintMap, "softness", 0) * _scale; + data->_bendDirection = Json::getInt(constraintMap, "bendPositive", 1) ? 1 : -1; + data->_compress = Json::getInt(constraintMap, "compress", 0) ? true : false; + data->_stretch = Json::getInt(constraintMap, "stretch", 0) ? true : false; + data->_uniform = Json::getInt(constraintMap, "uniform", 0) ? true : false; - skeletonData->_ikConstraints[i] = data; - } - } + skeletonData->_ikConstraints[i] = data; + } + } - /* Transform constraints. */ - transform = Json::getItem(root, "transform"); - if (transform) { - Json *constraintMap; - skeletonData->_transformConstraints.ensureCapacity(transform->_size); - skeletonData->_transformConstraints.setSize(transform->_size, 0); - for (constraintMap = transform->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { - const char *name; + /* Transform constraints. */ + transform = Json::getItem(root, "transform"); + if (transform) { + Json *constraintMap; + skeletonData->_transformConstraints.ensureCapacity(transform->_size); + skeletonData->_transformConstraints.setSize(transform->_size, 0); + for (constraintMap = transform->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { + const char *name; - TransformConstraintData *data = new(__FILE__, __LINE__) TransformConstraintData(Json::getString(constraintMap, "name", 0)); - data->setOrder(Json::getInt(constraintMap, "order", 0)); - data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); + TransformConstraintData *data = new (__FILE__, __LINE__) TransformConstraintData(Json::getString(constraintMap, "name", 0)); + data->setOrder(Json::getInt(constraintMap, "order", 0)); + data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); - boneMap = Json::getItem(constraintMap, "bones"); - data->_bones.ensureCapacity(boneMap->_size); - data->_bones.setSize(boneMap->_size, 0); - for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { - data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); - if (!data->_bones[ii]) { - delete skeletonData; - setError(root, "Transform bone not found: ", boneMap->_valueString); - return NULL; - } - } + boneMap = Json::getItem(constraintMap, "bones"); + data->_bones.ensureCapacity(boneMap->_size); + data->_bones.setSize(boneMap->_size, 0); + for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { + data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); + if (!data->_bones[ii]) { + delete skeletonData; + setError(root, "Transform bone not found: ", boneMap->_valueString); + return NULL; + } + } - name = Json::getString(constraintMap, "target", 0); - data->_target = skeletonData->findBone(name); - if (!data->_target) { - delete skeletonData; - setError(root, "Target bone not found: ", name); - return NULL; - } + name = Json::getString(constraintMap, "target", 0); + data->_target = skeletonData->findBone(name); + if (!data->_target) { + delete skeletonData; + setError(root, "Target bone not found: ", name); + return NULL; + } - data->_local = Json::getInt(constraintMap, "local", 0) ? true : false; - data->_relative = Json::getInt(constraintMap, "relative", 0) ? true : false; - data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0); - data->_offsetX = Json::getFloat(constraintMap, "x", 0) * _scale; - data->_offsetY = Json::getFloat(constraintMap, "y", 0) * _scale; - data->_offsetScaleX = Json::getFloat(constraintMap, "scaleX", 0); - data->_offsetScaleY = Json::getFloat(constraintMap, "scaleY", 0); - data->_offsetShearY = Json::getFloat(constraintMap, "shearY", 0); + data->_local = Json::getInt(constraintMap, "local", 0) ? true : false; + data->_relative = Json::getInt(constraintMap, "relative", 0) ? true : false; + data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0); + data->_offsetX = Json::getFloat(constraintMap, "x", 0) * _scale; + data->_offsetY = Json::getFloat(constraintMap, "y", 0) * _scale; + data->_offsetScaleX = Json::getFloat(constraintMap, "scaleX", 0); + data->_offsetScaleY = Json::getFloat(constraintMap, "scaleY", 0); + data->_offsetShearY = Json::getFloat(constraintMap, "shearY", 0); - data->_rotateMix = Json::getFloat(constraintMap, "rotateMix", 1); - data->_translateMix = Json::getFloat(constraintMap, "translateMix", 1); - data->_scaleMix = Json::getFloat(constraintMap, "scaleMix", 1); - data->_shearMix = Json::getFloat(constraintMap, "shearMix", 1); + data->_rotateMix = Json::getFloat(constraintMap, "rotateMix", 1); + data->_translateMix = Json::getFloat(constraintMap, "translateMix", 1); + data->_scaleMix = Json::getFloat(constraintMap, "scaleMix", 1); + data->_shearMix = Json::getFloat(constraintMap, "shearMix", 1); - skeletonData->_transformConstraints[i] = data; - } - } + skeletonData->_transformConstraints[i] = data; + } + } - /* Path constraints */ - path = Json::getItem(root, "path"); - if (path) { - Json *constraintMap; - skeletonData->_pathConstraints.ensureCapacity(path->_size); - skeletonData->_pathConstraints.setSize(path->_size, 0); - for (constraintMap = path->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { - const char *name; - const char *item; + /* Path constraints */ + path = Json::getItem(root, "path"); + if (path) { + Json *constraintMap; + skeletonData->_pathConstraints.ensureCapacity(path->_size); + skeletonData->_pathConstraints.setSize(path->_size, 0); + for (constraintMap = path->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) { + const char *name; + const char *item; - PathConstraintData *data = new(__FILE__, __LINE__) PathConstraintData(Json::getString(constraintMap, "name", 0)); - data->setOrder(Json::getInt(constraintMap, "order", 0)); - data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); + PathConstraintData *data = new (__FILE__, __LINE__) PathConstraintData(Json::getString(constraintMap, "name", 0)); + data->setOrder(Json::getInt(constraintMap, "order", 0)); + data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false)); - boneMap = Json::getItem(constraintMap, "bones"); - data->_bones.ensureCapacity(boneMap->_size); - data->_bones.setSize(boneMap->_size, 0); - for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { - data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); - if (!data->_bones[ii]) { - delete skeletonData; - setError(root, "Path bone not found: ", boneMap->_valueString); - return NULL; - } - } + boneMap = Json::getItem(constraintMap, "bones"); + data->_bones.ensureCapacity(boneMap->_size); + data->_bones.setSize(boneMap->_size, 0); + for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) { + data->_bones[ii] = skeletonData->findBone(boneMap->_valueString); + if (!data->_bones[ii]) { + delete skeletonData; + setError(root, "Path bone not found: ", boneMap->_valueString); + return NULL; + } + } - name = Json::getString(constraintMap, "target", 0); - data->_target = skeletonData->findSlot(name); - if (!data->_target) { - delete skeletonData; - setError(root, "Target slot not found: ", name); - return NULL; - } + name = Json::getString(constraintMap, "target", 0); + data->_target = skeletonData->findSlot(name); + if (!data->_target) { + delete skeletonData; + setError(root, "Target slot not found: ", name); + return NULL; + } - item = Json::getString(constraintMap, "positionMode", "percent"); - if (strcmp(item, "fixed") == 0) { - data->_positionMode = PositionMode_Fixed; - } else if (strcmp(item, "percent") == 0) { - data->_positionMode = PositionMode_Percent; - } + item = Json::getString(constraintMap, "positionMode", "percent"); + if (strcmp(item, "fixed") == 0) { + data->_positionMode = PositionMode_Fixed; + } else if (strcmp(item, "percent") == 0) { + data->_positionMode = PositionMode_Percent; + } - item = Json::getString(constraintMap, "spacingMode", "length"); - if (strcmp(item, "length") == 0) data->_spacingMode = SpacingMode_Length; - else if (strcmp(item, "fixed") == 0) data->_spacingMode = SpacingMode_Fixed; - else if (strcmp(item, "percent") == 0) data->_spacingMode = SpacingMode_Percent; + item = Json::getString(constraintMap, "spacingMode", "length"); + if (strcmp(item, "length") == 0) + data->_spacingMode = SpacingMode_Length; + else if (strcmp(item, "fixed") == 0) + data->_spacingMode = SpacingMode_Fixed; + else if (strcmp(item, "percent") == 0) + data->_spacingMode = SpacingMode_Percent; - item = Json::getString(constraintMap, "rotateMode", "tangent"); - if (strcmp(item, "tangent") == 0) data->_rotateMode = RotateMode_Tangent; - else if (strcmp(item, "chain") == 0) data->_rotateMode = RotateMode_Chain; - else if (strcmp(item, "chainScale") == 0) data->_rotateMode = RotateMode_ChainScale; + item = Json::getString(constraintMap, "rotateMode", "tangent"); + if (strcmp(item, "tangent") == 0) + data->_rotateMode = RotateMode_Tangent; + else if (strcmp(item, "chain") == 0) + data->_rotateMode = RotateMode_Chain; + else if (strcmp(item, "chainScale") == 0) + data->_rotateMode = RotateMode_ChainScale; - data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0); - data->_position = Json::getFloat(constraintMap, "position", 0); - if (data->_positionMode == PositionMode_Fixed) data->_position *= _scale; - data->_spacing = Json::getFloat(constraintMap, "spacing", 0); - if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed) data->_spacing *= _scale; - data->_rotateMix = Json::getFloat(constraintMap, "rotateMix", 1); - data->_translateMix = Json::getFloat(constraintMap, "translateMix", 1); + data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0); + data->_position = Json::getFloat(constraintMap, "position", 0); + if (data->_positionMode == PositionMode_Fixed) data->_position *= _scale; + data->_spacing = Json::getFloat(constraintMap, "spacing", 0); + if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed) data->_spacing *= _scale; + data->_rotateMix = Json::getFloat(constraintMap, "rotateMix", 1); + data->_translateMix = Json::getFloat(constraintMap, "translateMix", 1); - skeletonData->_pathConstraints[i] = data; - } - } + skeletonData->_pathConstraints[i] = data; + } + } - /* Skins. */ - skins = Json::getItem(root, "skins"); - if (skins) { - Json *skinMap; - skeletonData->_skins.ensureCapacity(skins->_size); - skeletonData->_skins.setSize(skins->_size, 0); - int skinsIndex = 0; - for (skinMap = skins->_child, i = 0; skinMap; skinMap = skinMap->_next, ++i) { - Json *attachmentsMap; - Json *curves; + /* Skins. */ + skins = Json::getItem(root, "skins"); + if (skins) { + Json *skinMap; + skeletonData->_skins.ensureCapacity(skins->_size); + skeletonData->_skins.setSize(skins->_size, 0); + int skinsIndex = 0; + for (skinMap = skins->_child, i = 0; skinMap; skinMap = skinMap->_next, ++i) { + Json *attachmentsMap; + Json *curves; Skin *skin = nullptr; auto skinName = Json::getString(skinMap, "name", ""); if (strlen(skinName) == 0) { skinName = skinMap->_name; } - skin = new(__FILE__, __LINE__) Skin(skinName); - - Json *item = Json::getItem(skinMap, "bones"); - if (item) { - for (item = item->_child; item; item = item->_next) { - BoneData* data = skeletonData->findBone(item->_valueString); - if (!data) { - delete skeletonData; - setError(root, String("Skin bone not found: "), item->_valueString); - return NULL; - } - skin->getBones().add(data); - } - } + skin = new (__FILE__, __LINE__) Skin(skinName); - item = Json::getItem(skinMap, "ik"); - if (item) { - for (item = item->_child; item; item = item->_next) { - IkConstraintData* data = skeletonData->findIkConstraint(item->_valueString); - if (!data) { - delete skeletonData; - setError(root, String("Skin IK constraint not found: "), item->_valueString); - return NULL; - } - skin->getConstraints().add(data); - } - } + Json *item = Json::getItem(skinMap, "bones"); + if (item) { + for (item = item->_child; item; item = item->_next) { + BoneData *data = skeletonData->findBone(item->_valueString); + if (!data) { + delete skeletonData; + setError(root, String("Skin bone not found: "), item->_valueString); + return NULL; + } + skin->getBones().add(data); + } + } - item = Json::getItem(skinMap, "transform"); - if (item) { - for (item = item->_child; item; item = item->_next) { - TransformConstraintData* data = skeletonData->findTransformConstraint(item->_valueString); - if (!data) { - delete skeletonData; - setError(root, String("Skin transform constraint not found: "), item->_valueString); - return NULL; - } - skin->getConstraints().add(data); - } - } + item = Json::getItem(skinMap, "ik"); + if (item) { + for (item = item->_child; item; item = item->_next) { + IkConstraintData *data = skeletonData->findIkConstraint(item->_valueString); + if (!data) { + delete skeletonData; + setError(root, String("Skin IK constraint not found: "), item->_valueString); + return NULL; + } + skin->getConstraints().add(data); + } + } - item = Json::getItem(skinMap, "path"); - if (item) { - for (item = item->_child; item; item = item->_next) { - PathConstraintData* data = skeletonData->findPathConstraint(item->_valueString); - if (!data) { - delete skeletonData; - setError(root, String("Skin path constraint not found: "), item->_valueString); - return NULL; - } - skin->getConstraints().add(data); - } - } + item = Json::getItem(skinMap, "transform"); + if (item) { + for (item = item->_child; item; item = item->_next) { + TransformConstraintData *data = skeletonData->findTransformConstraint(item->_valueString); + if (!data) { + delete skeletonData; + setError(root, String("Skin transform constraint not found: "), item->_valueString); + return NULL; + } + skin->getConstraints().add(data); + } + } - skeletonData->_skins[skinsIndex++] = skin; - if (strcmp(skinName, "default") == 0) { - skeletonData->_defaultSkin = skin; - } + item = Json::getItem(skinMap, "path"); + if (item) { + for (item = item->_child; item; item = item->_next) { + PathConstraintData *data = skeletonData->findPathConstraint(item->_valueString); + if (!data) { + delete skeletonData; + setError(root, String("Skin path constraint not found: "), item->_valueString); + return NULL; + } + skin->getConstraints().add(data); + } + } + + skeletonData->_skins[skinsIndex++] = skin; + if (strcmp(skinName, "default") == 0) { + skeletonData->_defaultSkin = skin; + } auto attachmentsData = Json::getItem(skinMap, "attachments"); if (!attachmentsData) { attachmentsData = skinMap; } - for (attachmentsMap = attachmentsData->_child; attachmentsMap; attachmentsMap = attachmentsMap->_next) { - SlotData* slot = skeletonData->findSlot(attachmentsMap->_name); - Json *attachmentMap; + for (attachmentsMap = attachmentsData->_child; attachmentsMap; attachmentsMap = attachmentsMap->_next) { + SlotData *slot = skeletonData->findSlot(attachmentsMap->_name); + Json *attachmentMap; - for (attachmentMap = attachmentsMap->_child; attachmentMap; attachmentMap = attachmentMap->_next) { - Attachment *attachment = NULL; - const char *skinAttachmentName = attachmentMap->_name; - const char *attachmentName = Json::getString(attachmentMap, "name", skinAttachmentName); - const char *attachmentPath = Json::getString(attachmentMap, "path", attachmentName); - const char *color; - Json *entry; + for (attachmentMap = attachmentsMap->_child; attachmentMap; attachmentMap = attachmentMap->_next) { + Attachment *attachment = NULL; + const char *skinAttachmentName = attachmentMap->_name; + const char *attachmentName = Json::getString(attachmentMap, "name", skinAttachmentName); + const char *attachmentPath = Json::getString(attachmentMap, "path", attachmentName); + const char *color; + Json *entry; - const char *typeString = Json::getString(attachmentMap, "type", "region"); - AttachmentType type; - if (strcmp(typeString, "region") == 0) type = AttachmentType_Region; - else if (strcmp(typeString, "mesh") == 0) type = AttachmentType_Mesh; - else if (strcmp(typeString, "linkedmesh") == 0) type = AttachmentType_Linkedmesh; - else if (strcmp(typeString, "boundingbox") == 0) type = AttachmentType_Boundingbox; - else if (strcmp(typeString, "path") == 0) type = AttachmentType_Path; - else if (strcmp(typeString, "clipping") == 0) type = AttachmentType_Clipping; - else if (strcmp(typeString, "point") == 0) type = AttachmentType_Point; - else { - delete skeletonData; - setError(root, "Unknown attachment type: ", typeString); - return NULL; - } + const char *typeString = Json::getString(attachmentMap, "type", "region"); + AttachmentType type; + if (strcmp(typeString, "region") == 0) + type = AttachmentType_Region; + else if (strcmp(typeString, "mesh") == 0) + type = AttachmentType_Mesh; + else if (strcmp(typeString, "linkedmesh") == 0) + type = AttachmentType_Linkedmesh; + else if (strcmp(typeString, "boundingbox") == 0) + type = AttachmentType_Boundingbox; + else if (strcmp(typeString, "path") == 0) + type = AttachmentType_Path; + else if (strcmp(typeString, "clipping") == 0) + type = AttachmentType_Clipping; + else if (strcmp(typeString, "point") == 0) + type = AttachmentType_Point; + else { + delete skeletonData; + setError(root, "Unknown attachment type: ", typeString); + return NULL; + } - switch (type) { - case AttachmentType_Region: { - attachment = _attachmentLoader->newRegionAttachment(*skin, attachmentName, attachmentPath); - if (!attachment) { - // delete skeletonData; - // setError(root, "Error reading attachment: ", skinAttachmentName); - // return NULL; - continue; - } + switch (type) { + case AttachmentType_Region: { + attachment = _attachmentLoader->newRegionAttachment(*skin, attachmentName, attachmentPath); + if (!attachment) { + // delete skeletonData; + // setError(root, "Error reading attachment: ", skinAttachmentName); + // return NULL; + continue; + } - RegionAttachment *region = static_cast(attachment); - region->_path = attachmentPath; + RegionAttachment *region = static_cast(attachment); + region->_path = attachmentPath; - region->_x = Json::getFloat(attachmentMap, "x", 0) * _scale; - region->_y = Json::getFloat(attachmentMap, "y", 0) * _scale; - region->_scaleX = Json::getFloat(attachmentMap, "scaleX", 1); - region->_scaleY = Json::getFloat(attachmentMap, "scaleY", 1); - region->_rotation = Json::getFloat(attachmentMap, "rotation", 0); - region->_width = Json::getFloat(attachmentMap, "width", 32) * _scale; - region->_height = Json::getFloat(attachmentMap, "height", 32) * _scale; + region->_x = Json::getFloat(attachmentMap, "x", 0) * _scale; + region->_y = Json::getFloat(attachmentMap, "y", 0) * _scale; + region->_scaleX = Json::getFloat(attachmentMap, "scaleX", 1); + region->_scaleY = Json::getFloat(attachmentMap, "scaleY", 1); + region->_rotation = Json::getFloat(attachmentMap, "rotation", 0); + region->_width = Json::getFloat(attachmentMap, "width", 32) * _scale; + region->_height = Json::getFloat(attachmentMap, "height", 32) * _scale; - color = Json::getString(attachmentMap, "color", 0); - if (color) { - region->getColor().r = toColor(color, 0); - region->getColor().g = toColor(color, 1); - region->getColor().b = toColor(color, 2); - region->getColor().a = toColor(color, 3); - } + color = Json::getString(attachmentMap, "color", 0); + if (color) { + region->getColor().r = toColor(color, 0); + region->getColor().g = toColor(color, 1); + region->getColor().b = toColor(color, 2); + region->getColor().a = toColor(color, 3); + } - region->updateOffset(); - _attachmentLoader->configureAttachment(region); - break; - } - case AttachmentType_Mesh: - case AttachmentType_Linkedmesh: { - attachment = _attachmentLoader->newMeshAttachment(*skin, attachmentName, attachmentPath); + region->updateOffset(); + _attachmentLoader->configureAttachment(region); + break; + } + case AttachmentType_Mesh: + case AttachmentType_Linkedmesh: { + attachment = _attachmentLoader->newMeshAttachment(*skin, attachmentName, attachmentPath); - if (!attachment) { - // delete skeletonData; - // setError(root, "Error reading attachment: ", skinAttachmentName); - // return NULL; - continue; - } + if (!attachment) { + // delete skeletonData; + // setError(root, "Error reading attachment: ", skinAttachmentName); + // return NULL; + continue; + } - MeshAttachment *mesh = static_cast(attachment); - mesh->_path = attachmentPath; + MeshAttachment *mesh = static_cast(attachment); + mesh->_path = attachmentPath; - color = Json::getString(attachmentMap, "color", 0); - if (color) { - mesh->getColor().r = toColor(color, 0); - mesh->getColor().g = toColor(color, 1); - mesh->getColor().b = toColor(color, 2); - mesh->getColor().a = toColor(color, 3); - } + color = Json::getString(attachmentMap, "color", 0); + if (color) { + mesh->getColor().r = toColor(color, 0); + mesh->getColor().g = toColor(color, 1); + mesh->getColor().b = toColor(color, 2); + mesh->getColor().a = toColor(color, 3); + } - mesh->_width = Json::getFloat(attachmentMap, "width", 32) * _scale; - mesh->_height = Json::getFloat(attachmentMap, "height", 32) * _scale; + mesh->_width = Json::getFloat(attachmentMap, "width", 32) * _scale; + mesh->_height = Json::getFloat(attachmentMap, "height", 32) * _scale; - entry = Json::getItem(attachmentMap, "parent"); - if (!entry) { - int verticesLength; - entry = Json::getItem(attachmentMap, "triangles"); - mesh->_triangles.ensureCapacity(entry->_size); - mesh->_triangles.setSize(entry->_size, 0); - for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) - mesh->_triangles[ii] = (unsigned short) entry->_valueInt; + entry = Json::getItem(attachmentMap, "parent"); + if (!entry) { + int verticesLength; + entry = Json::getItem(attachmentMap, "triangles"); + mesh->_triangles.ensureCapacity(entry->_size); + mesh->_triangles.setSize(entry->_size, 0); + for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) + mesh->_triangles[ii] = (unsigned short)entry->_valueInt; - entry = Json::getItem(attachmentMap, "uvs"); - verticesLength = entry->_size; - mesh->_regionUVs.ensureCapacity(verticesLength); - mesh->_regionUVs.setSize(verticesLength, 0); - for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) - mesh->_regionUVs[ii] = entry->_valueFloat; + entry = Json::getItem(attachmentMap, "uvs"); + verticesLength = entry->_size; + mesh->_regionUVs.ensureCapacity(verticesLength); + mesh->_regionUVs.setSize(verticesLength, 0); + for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) + mesh->_regionUVs[ii] = entry->_valueFloat; - readVertices(attachmentMap, mesh, verticesLength); + readVertices(attachmentMap, mesh, verticesLength); - mesh->updateUVs(); + mesh->updateUVs(); - mesh->_hullLength = Json::getInt(attachmentMap, "hull", 0); + mesh->_hullLength = Json::getInt(attachmentMap, "hull", 0); - entry = Json::getItem(attachmentMap, "edges"); - if (entry) { - mesh->_edges.ensureCapacity(entry->_size); - mesh->_edges.setSize(entry->_size, 0); - for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) - mesh->_edges[ii] = entry->_valueInt; - } - _attachmentLoader->configureAttachment(mesh); - } else { - bool inheritDeform = Json::getInt(attachmentMap, "deform", 1) ? true : false; - LinkedMesh *linkedMesh = new(__FILE__, __LINE__) LinkedMesh(mesh, - String(Json::getString(attachmentMap, "skin", 0)), slot->getIndex(), String(entry->_valueString), - inheritDeform); - _linkedMeshes.add(linkedMesh); - } - break; - } - case AttachmentType_Boundingbox: { - attachment = _attachmentLoader->newBoundingBoxAttachment(*skin, attachmentName); + entry = Json::getItem(attachmentMap, "edges"); + if (entry) { + mesh->_edges.ensureCapacity(entry->_size); + mesh->_edges.setSize(entry->_size, 0); + for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii) + mesh->_edges[ii] = entry->_valueInt; + } + _attachmentLoader->configureAttachment(mesh); + } else { + bool inheritDeform = Json::getInt(attachmentMap, "deform", 1) ? true : false; + LinkedMesh *linkedMesh = new (__FILE__, __LINE__) LinkedMesh(mesh, + String(Json::getString(attachmentMap, "skin", 0)), slot->getIndex(), String(entry->_valueString), + inheritDeform); + _linkedMeshes.add(linkedMesh); + } + break; + } + case AttachmentType_Boundingbox: { + attachment = _attachmentLoader->newBoundingBoxAttachment(*skin, attachmentName); - BoundingBoxAttachment *box = static_cast(attachment); + BoundingBoxAttachment *box = static_cast(attachment); - int vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1; - readVertices(attachmentMap, box, vertexCount); - _attachmentLoader->configureAttachment(attachment); - break; - } - case AttachmentType_Path: { - attachment = _attachmentLoader->newPathAttachment(*skin, attachmentName); + int vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1; + readVertices(attachmentMap, box, vertexCount); + _attachmentLoader->configureAttachment(attachment); + break; + } + case AttachmentType_Path: { + attachment = _attachmentLoader->newPathAttachment(*skin, attachmentName); - PathAttachment *pathAttatchment = static_cast(attachment); + PathAttachment *pathAttatchment = static_cast(attachment); - int vertexCount = 0; - pathAttatchment->_closed = Json::getInt(attachmentMap, "closed", 0) ? true : false; - pathAttatchment->_constantSpeed = Json::getInt(attachmentMap, "constantSpeed", 1) ? true : false; - vertexCount = Json::getInt(attachmentMap, "vertexCount", 0); - readVertices(attachmentMap, pathAttatchment, vertexCount << 1); + int vertexCount = 0; + pathAttatchment->_closed = Json::getInt(attachmentMap, "closed", 0) ? true : false; + pathAttatchment->_constantSpeed = Json::getInt(attachmentMap, "constantSpeed", 1) ? true : false; + vertexCount = Json::getInt(attachmentMap, "vertexCount", 0); + readVertices(attachmentMap, pathAttatchment, vertexCount << 1); - pathAttatchment->_lengths.ensureCapacity(vertexCount / 3); - pathAttatchment->_lengths.setSize(vertexCount / 3, 0); + pathAttatchment->_lengths.ensureCapacity(vertexCount / 3); + pathAttatchment->_lengths.setSize(vertexCount / 3, 0); - curves = Json::getItem(attachmentMap, "lengths"); - for (curves = curves->_child, ii = 0; curves; curves = curves->_next, ++ii) - pathAttatchment->_lengths[ii] = curves->_valueFloat * _scale; - _attachmentLoader->configureAttachment(attachment); - break; - } - case AttachmentType_Point: { - attachment = _attachmentLoader->newPointAttachment(*skin, attachmentName); + curves = Json::getItem(attachmentMap, "lengths"); + for (curves = curves->_child, ii = 0; curves; curves = curves->_next, ++ii) + pathAttatchment->_lengths[ii] = curves->_valueFloat * _scale; + _attachmentLoader->configureAttachment(attachment); + break; + } + case AttachmentType_Point: { + attachment = _attachmentLoader->newPointAttachment(*skin, attachmentName); - PointAttachment *point = static_cast(attachment); + PointAttachment *point = static_cast(attachment); - point->_x = Json::getFloat(attachmentMap, "x", 0) * _scale; - point->_y = Json::getFloat(attachmentMap, "y", 0) * _scale; - point->_rotation = Json::getFloat(attachmentMap, "rotation", 0); - _attachmentLoader->configureAttachment(attachment); - break; - } - case AttachmentType_Clipping: { - attachment = _attachmentLoader->newClippingAttachment(*skin, attachmentName); + point->_x = Json::getFloat(attachmentMap, "x", 0) * _scale; + point->_y = Json::getFloat(attachmentMap, "y", 0) * _scale; + point->_rotation = Json::getFloat(attachmentMap, "rotation", 0); + _attachmentLoader->configureAttachment(attachment); + break; + } + case AttachmentType_Clipping: { + attachment = _attachmentLoader->newClippingAttachment(*skin, attachmentName); - ClippingAttachment *clip = static_cast(attachment); + ClippingAttachment *clip = static_cast(attachment); - int vertexCount = 0; - const char *end = Json::getString(attachmentMap, "end", 0); - if (end) clip->_endSlot = skeletonData->findSlot(end); - vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1; - readVertices(attachmentMap, clip, vertexCount); - _attachmentLoader->configureAttachment(attachment); - break; - } - } + int vertexCount = 0; + const char *end = Json::getString(attachmentMap, "end", 0); + if (end) clip->_endSlot = skeletonData->findSlot(end); + vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1; + readVertices(attachmentMap, clip, vertexCount); + _attachmentLoader->configureAttachment(attachment); + break; + } + } - skin->setAttachment(slot->getIndex(), skinAttachmentName, attachment); - } - } - } - } + skin->setAttachment(slot->getIndex(), skinAttachmentName, attachment); + } + } + } + } - /* Linked meshes. */ - int n = _linkedMeshes.size(); - for (i = 0; i < n; ++i) { - LinkedMesh *linkedMesh = _linkedMeshes[i]; - Skin *skin = linkedMesh->_skin.length() == 0 ? skeletonData->getDefaultSkin() : skeletonData->findSkin(linkedMesh->_skin); - if (skin == NULL) { - // delete skeletonData; - // setError(root, "Skin not found: ", linkedMesh->_skin.buffer()); - // return NULL; - continue; - } - Attachment *parent = skin->getAttachment(linkedMesh->_slotIndex, linkedMesh->_parent); - if (parent == NULL) { - // delete skeletonData; - // setError(root, "Parent mesh not found: ", linkedMesh->_parent.buffer()); - // return NULL; - continue; - } - linkedMesh->_mesh->_deformAttachment = linkedMesh->_inheritDeform ? static_cast(parent) : linkedMesh->_mesh; - linkedMesh->_mesh->setParentMesh(static_cast(parent)); - linkedMesh->_mesh->updateUVs(); - _attachmentLoader->configureAttachment(linkedMesh->_mesh); - } - ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes); - _linkedMeshes.clear(); + /* Linked meshes. */ + int n = _linkedMeshes.size(); + for (i = 0; i < n; ++i) { + LinkedMesh *linkedMesh = _linkedMeshes[i]; + Skin *skin = linkedMesh->_skin.length() == 0 ? skeletonData->getDefaultSkin() : skeletonData->findSkin(linkedMesh->_skin); + if (skin == NULL) { + // delete skeletonData; + // setError(root, "Skin not found: ", linkedMesh->_skin.buffer()); + // return NULL; + continue; + } + Attachment *parent = skin->getAttachment(linkedMesh->_slotIndex, linkedMesh->_parent); + if (parent == NULL) { + // delete skeletonData; + // setError(root, "Parent mesh not found: ", linkedMesh->_parent.buffer()); + // return NULL; + continue; + } + linkedMesh->_mesh->_deformAttachment = linkedMesh->_inheritDeform ? static_cast(parent) : linkedMesh->_mesh; + linkedMesh->_mesh->setParentMesh(static_cast(parent)); + linkedMesh->_mesh->updateUVs(); + _attachmentLoader->configureAttachment(linkedMesh->_mesh); + } + ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes); + _linkedMeshes.clear(); - /* Events. */ - events = Json::getItem(root, "events"); - if (events) { - Json *eventMap; - skeletonData->_events.ensureCapacity(events->_size); - skeletonData->_events.setSize(events->_size, 0); - for (eventMap = events->_child, i = 0; eventMap; eventMap = eventMap->_next, ++i) { - EventData *eventData = new(__FILE__, __LINE__) EventData(String(eventMap->_name)); + /* Events. */ + events = Json::getItem(root, "events"); + if (events) { + Json *eventMap; + skeletonData->_events.ensureCapacity(events->_size); + skeletonData->_events.setSize(events->_size, 0); + for (eventMap = events->_child, i = 0; eventMap; eventMap = eventMap->_next, ++i) { + EventData *eventData = new (__FILE__, __LINE__) EventData(String(eventMap->_name)); - eventData->_intValue = Json::getInt(eventMap, "int", 0); - eventData->_floatValue = Json::getFloat(eventMap, "float", 0); - const char *stringValue = Json::getString(eventMap, "string", 0); - eventData->_stringValue = stringValue; - const char *audioPath = Json::getString(eventMap, "audio", 0); - eventData->_audioPath = audioPath; - if (audioPath) { - eventData->_volume = Json::getFloat(eventMap, "volume", 1); - eventData->_balance = Json::getFloat(eventMap, "balance", 0); - } - skeletonData->_events[i] = eventData; - } - } + eventData->_intValue = Json::getInt(eventMap, "int", 0); + eventData->_floatValue = Json::getFloat(eventMap, "float", 0); + const char *stringValue = Json::getString(eventMap, "string", 0); + eventData->_stringValue = stringValue; + const char *audioPath = Json::getString(eventMap, "audio", 0); + eventData->_audioPath = audioPath; + if (audioPath) { + eventData->_volume = Json::getFloat(eventMap, "volume", 1); + eventData->_balance = Json::getFloat(eventMap, "balance", 0); + } + skeletonData->_events[i] = eventData; + } + } - /* Animations. */ - animations = Json::getItem(root, "animations"); - if (animations) { - Json *animationMap; - skeletonData->_animations.ensureCapacity(animations->_size); - skeletonData->_animations.setSize(animations->_size, 0); - int animationsIndex = 0; - for (animationMap = animations->_child; animationMap; animationMap = animationMap->_next) { - Animation *animation = readAnimation(animationMap, skeletonData); - if (!animation) { - // delete skeletonData; - // delete root; - // return NULL; - continue; - } - skeletonData->_animations[animationsIndex++] = animation; - } - } + /* Animations. */ + animations = Json::getItem(root, "animations"); + if (animations) { + Json *animationMap; + skeletonData->_animations.ensureCapacity(animations->_size); + skeletonData->_animations.setSize(animations->_size, 0); + int animationsIndex = 0; + for (animationMap = animations->_child; animationMap; animationMap = animationMap->_next) { + Animation *animation = readAnimation(animationMap, skeletonData); + if (!animation) { + // delete skeletonData; + // delete root; + // return NULL; + continue; + } + skeletonData->_animations[animationsIndex++] = animation; + } + } - delete root; + delete root; - return skeletonData; + return skeletonData; } float SkeletonJson::toColor(const char *value, size_t index) { - char digits[3]; - char *error; - int color; + char digits[3]; + char *error; + int color; - if (index >= strlen(value) / 2) return -1; + if (index >= strlen(value) / 2) return -1; - value += index * 2; + value += index * 2; - digits[0] = *value; - digits[1] = *(value + 1); - digits[2] = '\0'; - color = (int) strtoul(digits, &error, 16); - if (*error != 0) return -1; + digits[0] = *value; + digits[1] = *(value + 1); + digits[2] = '\0'; + color = (int)strtoul(digits, &error, 16); + if (*error != 0) return -1; - return color / (float) 255; + return color / (float)255; } void SkeletonJson::readCurve(Json *frame, CurveTimeline *timeline, size_t frameIndex) { - Json *curve = Json::getItem(frame, "curve"); - if (!curve) return; - if (curve->_type == Json::JSON_STRING && strcmp(curve->_valueString, "stepped") == 0) - timeline->setStepped(frameIndex); - else { - float c1 = Json::getFloat(frame, "curve", 0); - float c2 = Json::getFloat(frame, "c2", 0); - float c3 = Json::getFloat(frame, "c3", 1); - float c4 = Json::getFloat(frame, "c4", 1); - timeline->setCurve(frameIndex, c1, c2, c3, c4); - } + Json *curve = Json::getItem(frame, "curve"); + if (!curve) return; + if (curve->_type == Json::JSON_STRING && strcmp(curve->_valueString, "stepped") == 0) + timeline->setStepped(frameIndex); + else { + float c1 = Json::getFloat(frame, "curve", 0); + float c2 = Json::getFloat(frame, "c2", 0); + float c3 = Json::getFloat(frame, "c3", 1); + float c4 = Json::getFloat(frame, "c4", 1); + timeline->setCurve(frameIndex, c1, c2, c3, c4); + } } Animation *SkeletonJson::readAnimation(Json *root, SkeletonData *skeletonData) { - Vector timelines; - float duration = 0; + Vector timelines; + float duration = 0; - size_t frameIndex; - Json *valueMap; - int timelinesCount = 0; + size_t frameIndex; + Json *valueMap; + int timelinesCount = 0; - Json *bones = Json::getItem(root, "bones"); - Json *slots = Json::getItem(root, "slots"); - Json *ik = Json::getItem(root, "ik"); - Json *transform = Json::getItem(root, "transform"); - Json *paths = Json::getItem(root, "path"); - if (paths == NULL) { - paths = Json::getItem(root, "paths"); - } - Json *deform = Json::getItem(root, "deform"); - Json *drawOrder = Json::getItem(root, "drawOrder"); - Json *events = Json::getItem(root, "events"); - Json *boneMap, *slotMap, *constraintMap; - if (!drawOrder) drawOrder = Json::getItem(root, "draworder"); + Json *bones = Json::getItem(root, "bones"); + Json *slots = Json::getItem(root, "slots"); + Json *ik = Json::getItem(root, "ik"); + Json *transform = Json::getItem(root, "transform"); + Json *paths = Json::getItem(root, "path"); + if (paths == NULL) { + paths = Json::getItem(root, "paths"); + } + Json *deform = Json::getItem(root, "deform"); + Json *drawOrder = Json::getItem(root, "drawOrder"); + Json *events = Json::getItem(root, "events"); + Json *boneMap, *slotMap, *constraintMap; + if (!drawOrder) drawOrder = Json::getItem(root, "draworder"); - for (boneMap = bones ? bones->_child : NULL; boneMap; boneMap = boneMap->_next) - timelinesCount += boneMap->_size; + for (boneMap = bones ? bones->_child : NULL; boneMap; boneMap = boneMap->_next) + timelinesCount += boneMap->_size; - for (slotMap = slots ? slots->_child : NULL; slotMap; slotMap = slotMap->_next) - timelinesCount += slotMap->_size; + for (slotMap = slots ? slots->_child : NULL; slotMap; slotMap = slotMap->_next) + timelinesCount += slotMap->_size; - timelinesCount += ik ? ik->_size : 0; - timelinesCount += transform ? transform->_size : 0; + timelinesCount += ik ? ik->_size : 0; + timelinesCount += transform ? transform->_size : 0; - for (constraintMap = paths ? paths->_child : NULL; constraintMap; constraintMap = constraintMap->_next) - timelinesCount += constraintMap->_size; + for (constraintMap = paths ? paths->_child : NULL; constraintMap; constraintMap = constraintMap->_next) + timelinesCount += constraintMap->_size; - for (constraintMap = deform ? deform->_child : NULL; constraintMap; constraintMap = constraintMap->_next) - for (slotMap = constraintMap->_child; slotMap; slotMap = slotMap->_next) - timelinesCount += slotMap->_size; + for (constraintMap = deform ? deform->_child : NULL; constraintMap; constraintMap = constraintMap->_next) + for (slotMap = constraintMap->_child; slotMap; slotMap = slotMap->_next) + timelinesCount += slotMap->_size; - if (drawOrder) ++timelinesCount; + if (drawOrder) ++timelinesCount; - if (events) ++timelinesCount; + if (events) ++timelinesCount; - /** Slot timelines. */ - for (slotMap = slots ? slots->_child : 0; slotMap; slotMap = slotMap->_next) { - Json *timelineMap; + /** Slot timelines. */ + for (slotMap = slots ? slots->_child : 0; slotMap; slotMap = slotMap->_next) { + Json *timelineMap; - int slotIndex = skeletonData->findSlotIndex(slotMap->_name); - if (slotIndex == -1) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Slot not found: ", slotMap->_name); - return NULL; - } + int slotIndex = skeletonData->findSlotIndex(slotMap->_name); + if (slotIndex == -1) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Slot not found: ", slotMap->_name); + return NULL; + } - for (timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) { - if (strcmp(timelineMap->_name, "attachment") == 0) { - AttachmentTimeline *timeline = new(__FILE__, __LINE__) AttachmentTimeline(timelineMap->_size); + for (timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) { + if (strcmp(timelineMap->_name, "attachment") == 0) { + AttachmentTimeline *timeline = new (__FILE__, __LINE__) AttachmentTimeline(timelineMap->_size); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - Json *name = Json::getItem(valueMap, "name"); - String attachmentName = name->_type == Json::JSON_NULL ? "" : name->_valueString; - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), attachmentName); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[timelineMap->_size - 1]); + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + Json *name = Json::getItem(valueMap, "name"); + String attachmentName = name->_type == Json::JSON_NULL ? "" : name->_valueString; + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), attachmentName); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[timelineMap->_size - 1]); - } else if (strcmp(timelineMap->_name, "color") == 0) { - ColorTimeline *timeline = new(__FILE__, __LINE__) ColorTimeline(timelineMap->_size); + } else if (strcmp(timelineMap->_name, "color") == 0) { + ColorTimeline *timeline = new (__FILE__, __LINE__) ColorTimeline(timelineMap->_size); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - const char *s = Json::getString(valueMap, "color", 0); - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), toColor(s, 0), toColor(s, 1), - toColor(s, 2), toColor(s, 3)); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * ColorTimeline::ENTRIES]); + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + const char *s = Json::getString(valueMap, "color", 0); + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), toColor(s, 0), toColor(s, 1), + toColor(s, 2), toColor(s, 3)); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * ColorTimeline::ENTRIES]); - } else if (strcmp(timelineMap->_name, "twoColor") == 0) { - TwoColorTimeline *timeline = new(__FILE__, __LINE__) TwoColorTimeline(timelineMap->_size); + } else if (strcmp(timelineMap->_name, "twoColor") == 0) { + TwoColorTimeline *timeline = new (__FILE__, __LINE__) TwoColorTimeline(timelineMap->_size); - timeline->_slotIndex = slotIndex; + timeline->_slotIndex = slotIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - const char *s = Json::getString(valueMap, "light", 0); - const char *ds = Json::getString(valueMap, "dark", 0); - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), toColor(s, 0), toColor(s, 1), - toColor(s, 2), toColor(s, 3), toColor(ds, 0), toColor(ds, 1), toColor(ds, 2)); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, - timeline->_frames[(timelineMap->_size - 1) * TwoColorTimeline::ENTRIES]); - } else { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Invalid timeline type for a slot: ", timelineMap->_name); - return NULL; - } - } - } + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + const char *s = Json::getString(valueMap, "light", 0); + const char *ds = Json::getString(valueMap, "dark", 0); + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), toColor(s, 0), toColor(s, 1), + toColor(s, 2), toColor(s, 3), toColor(ds, 0), toColor(ds, 1), toColor(ds, 2)); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, + timeline->_frames[(timelineMap->_size - 1) * TwoColorTimeline::ENTRIES]); + } else { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Invalid timeline type for a slot: ", timelineMap->_name); + return NULL; + } + } + } - /** Bone timelines. */ - for (boneMap = bones ? bones->_child : 0; boneMap; boneMap = boneMap->_next) { - Json *timelineMap; + /** Bone timelines. */ + for (boneMap = bones ? bones->_child : 0; boneMap; boneMap = boneMap->_next) { + Json *timelineMap; - int boneIndex = skeletonData->findBoneIndex(boneMap->_name); - if (boneIndex == -1) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Bone not found: ", boneMap->_name); - return NULL; - } + int boneIndex = skeletonData->findBoneIndex(boneMap->_name); + if (boneIndex == -1) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Bone not found: ", boneMap->_name); + return NULL; + } - for (timelineMap = boneMap->_child; timelineMap; timelineMap = timelineMap->_next) { - if (strcmp(timelineMap->_name, "rotate") == 0) { - RotateTimeline *timeline = new(__FILE__, __LINE__) RotateTimeline(timelineMap->_size); + for (timelineMap = boneMap->_child; timelineMap; timelineMap = timelineMap->_next) { + if (strcmp(timelineMap->_name, "rotate") == 0) { + RotateTimeline *timeline = new (__FILE__, __LINE__) RotateTimeline(timelineMap->_size); - timeline->_boneIndex = boneIndex; + timeline->_boneIndex = boneIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), Json::getFloat(valueMap, "angle", 0)); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * RotateTimeline::ENTRIES]); - } else { - int isScale = strcmp(timelineMap->_name, "scale") == 0; - int isTranslate = strcmp(timelineMap->_name, "translate") == 0; - int isShear = strcmp(timelineMap->_name, "shear") == 0; - if (isScale || isTranslate || isShear) { - float timelineScale = isTranslate ? _scale : 1; - float defaultValue = 0; - TranslateTimeline *timeline = 0; - if (isScale) { - timeline = new(__FILE__, __LINE__) ScaleTimeline(timelineMap->_size); - defaultValue = 1; - } else if (isTranslate) { - timeline = new(__FILE__, __LINE__) TranslateTimeline(timelineMap->_size); - } else if (isShear) { - timeline = new(__FILE__, __LINE__) ShearTimeline(timelineMap->_size); - } - timeline->_boneIndex = boneIndex; + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), Json::getFloat(valueMap, "angle", 0)); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * RotateTimeline::ENTRIES]); + } else { + int isScale = strcmp(timelineMap->_name, "scale") == 0; + int isTranslate = strcmp(timelineMap->_name, "translate") == 0; + int isShear = strcmp(timelineMap->_name, "shear") == 0; + if (isScale || isTranslate || isShear) { + float timelineScale = isTranslate ? _scale : 1; + float defaultValue = 0; + TranslateTimeline *timeline = 0; + if (isScale) { + timeline = new (__FILE__, __LINE__) ScaleTimeline(timelineMap->_size); + defaultValue = 1; + } else if (isTranslate) { + timeline = new (__FILE__, __LINE__) TranslateTimeline(timelineMap->_size); + } else if (isShear) { + timeline = new (__FILE__, __LINE__) ShearTimeline(timelineMap->_size); + } + timeline->_boneIndex = boneIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), - Json::getFloat(valueMap, "x", defaultValue) * timelineScale, - Json::getFloat(valueMap, "y", defaultValue) * timelineScale); - readCurve(valueMap, timeline, frameIndex); - } + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), + Json::getFloat(valueMap, "x", defaultValue) * timelineScale, + Json::getFloat(valueMap, "y", defaultValue) * timelineScale); + readCurve(valueMap, timeline, frameIndex); + } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * TranslateTimeline::ENTRIES]); - } else { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Invalid timeline type for a bone: ", timelineMap->_name); - return NULL; - } - } - } - } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * TranslateTimeline::ENTRIES]); + } else { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Invalid timeline type for a bone: ", timelineMap->_name); + return NULL; + } + } + } + } - /** IK constraint timelines. */ - for (constraintMap = ik ? ik->_child : 0; constraintMap; constraintMap = constraintMap->_next) { - IkConstraintData *constraint = skeletonData->findIkConstraint(constraintMap->_name); - IkConstraintTimeline *timeline = new(__FILE__, __LINE__) IkConstraintTimeline(constraintMap->_size); + /** IK constraint timelines. */ + for (constraintMap = ik ? ik->_child : 0; constraintMap; constraintMap = constraintMap->_next) { + IkConstraintData *constraint = skeletonData->findIkConstraint(constraintMap->_name); + IkConstraintTimeline *timeline = new (__FILE__, __LINE__) IkConstraintTimeline(constraintMap->_size); - for (frameIndex = 0; frameIndex < skeletonData->_ikConstraints.size(); ++frameIndex) { - if (constraint == skeletonData->_ikConstraints[frameIndex]) { - timeline->_ikConstraintIndex = frameIndex; - break; - } - } - for (valueMap = constraintMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), Json::getFloat(valueMap, "mix", 1), - Json::getFloat(valueMap, "softness", 0) * _scale, Json::getInt(valueMap, "bendPositive", 1) ? 1 : -1, - Json::getInt(valueMap, "compress", 0) ? true : false, Json::getInt(valueMap, "stretch", 0) ? true : false); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(constraintMap->_size - 1) * IkConstraintTimeline::ENTRIES]); - } + for (frameIndex = 0; frameIndex < skeletonData->_ikConstraints.size(); ++frameIndex) { + if (constraint == skeletonData->_ikConstraints[frameIndex]) { + timeline->_ikConstraintIndex = frameIndex; + break; + } + } + for (valueMap = constraintMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), Json::getFloat(valueMap, "mix", 1), + Json::getFloat(valueMap, "softness", 0) * _scale, Json::getInt(valueMap, "bendPositive", 1) ? 1 : -1, + Json::getInt(valueMap, "compress", 0) ? true : false, Json::getInt(valueMap, "stretch", 0) ? true : false); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(constraintMap->_size - 1) * IkConstraintTimeline::ENTRIES]); + } - /** Transform constraint timelines. */ - for (constraintMap = transform ? transform->_child : 0; constraintMap; constraintMap = constraintMap->_next) { - TransformConstraintData *constraint = skeletonData->findTransformConstraint(constraintMap->_name); - TransformConstraintTimeline *timeline = new(__FILE__, __LINE__) TransformConstraintTimeline(constraintMap->_size); + /** Transform constraint timelines. */ + for (constraintMap = transform ? transform->_child : 0; constraintMap; constraintMap = constraintMap->_next) { + TransformConstraintData *constraint = skeletonData->findTransformConstraint(constraintMap->_name); + TransformConstraintTimeline *timeline = new (__FILE__, __LINE__) TransformConstraintTimeline(constraintMap->_size); - for (frameIndex = 0; frameIndex < skeletonData->_transformConstraints.size(); ++frameIndex) { - if (constraint == skeletonData->_transformConstraints[frameIndex]) { - timeline->_transformConstraintIndex = frameIndex; - break; - } - } - for (valueMap = constraintMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), - Json::getFloat(valueMap, "rotateMix", 1), Json::getFloat(valueMap, "translateMix", 1), - Json::getFloat(valueMap, "scaleMix", 1), Json::getFloat(valueMap, "shearMix", 1)); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(constraintMap->_size - 1) * TransformConstraintTimeline::ENTRIES]); - } + for (frameIndex = 0; frameIndex < skeletonData->_transformConstraints.size(); ++frameIndex) { + if (constraint == skeletonData->_transformConstraints[frameIndex]) { + timeline->_transformConstraintIndex = frameIndex; + break; + } + } + for (valueMap = constraintMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), + Json::getFloat(valueMap, "rotateMix", 1), Json::getFloat(valueMap, "translateMix", 1), + Json::getFloat(valueMap, "scaleMix", 1), Json::getFloat(valueMap, "shearMix", 1)); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(constraintMap->_size - 1) * TransformConstraintTimeline::ENTRIES]); + } - /** Path constraint timelines. */ - for (constraintMap = paths ? paths->_child : 0; constraintMap; constraintMap = constraintMap->_next) { - size_t constraintIndex = 0, i; - Json *timelineMap; + /** Path constraint timelines. */ + for (constraintMap = paths ? paths->_child : 0; constraintMap; constraintMap = constraintMap->_next) { + size_t constraintIndex = 0, i; + Json *timelineMap; - PathConstraintData *data = skeletonData->findPathConstraint(constraintMap->_name); - if (!data) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Path constraint not found: ", constraintMap->_name); - return NULL; - } + PathConstraintData *data = skeletonData->findPathConstraint(constraintMap->_name); + if (!data) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Path constraint not found: ", constraintMap->_name); + return NULL; + } - for (i = 0; i < skeletonData->_pathConstraints.size(); i++) { - if (skeletonData->_pathConstraints[i] == data) { - constraintIndex = i; - break; - } - } + for (i = 0; i < skeletonData->_pathConstraints.size(); i++) { + if (skeletonData->_pathConstraints[i] == data) { + constraintIndex = i; + break; + } + } - for (timelineMap = constraintMap->_child; timelineMap; timelineMap = timelineMap->_next) { - const char *timelineName = timelineMap->_name; - if (strcmp(timelineName, "position") == 0 || strcmp(timelineName, "spacing") == 0) { - PathConstraintPositionTimeline *timeline; - float timelineScale = 1; - if (strcmp(timelineName, "spacing") == 0) { - timeline = new(__FILE__, __LINE__) PathConstraintSpacingTimeline(timelineMap->_size); + for (timelineMap = constraintMap->_child; timelineMap; timelineMap = timelineMap->_next) { + const char *timelineName = timelineMap->_name; + if (strcmp(timelineName, "position") == 0 || strcmp(timelineName, "spacing") == 0) { + PathConstraintPositionTimeline *timeline; + float timelineScale = 1; + if (strcmp(timelineName, "spacing") == 0) { + timeline = new (__FILE__, __LINE__) PathConstraintSpacingTimeline(timelineMap->_size); - if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed) { - timelineScale = _scale; - } - } else { - timeline = new(__FILE__, __LINE__) PathConstraintPositionTimeline(timelineMap->_size); + if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed) { + timelineScale = _scale; + } + } else { + timeline = new (__FILE__, __LINE__) PathConstraintPositionTimeline(timelineMap->_size); - if (data->_positionMode == PositionMode_Fixed) { - timelineScale = _scale; - } - } + if (data->_positionMode == PositionMode_Fixed) { + timelineScale = _scale; + } + } - timeline->_pathConstraintIndex = constraintIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), - Json::getFloat(valueMap, timelineName, 0) * timelineScale); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * - PathConstraintPositionTimeline::ENTRIES]); - } else if (strcmp(timelineName, "mix") == 0) { - PathConstraintMixTimeline *timeline = new(__FILE__, __LINE__) PathConstraintMixTimeline(timelineMap->_size); - timeline->_pathConstraintIndex = constraintIndex; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), - Json::getFloat(valueMap, "rotateMix", 1), - Json::getFloat(valueMap, "translateMix", 1)); - readCurve(valueMap, timeline, frameIndex); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * PathConstraintMixTimeline::ENTRIES]); - } - } - } + timeline->_pathConstraintIndex = constraintIndex; + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), + Json::getFloat(valueMap, timelineName, 0) * timelineScale); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * + PathConstraintPositionTimeline::ENTRIES]); + } else if (strcmp(timelineName, "mix") == 0) { + PathConstraintMixTimeline *timeline = new (__FILE__, __LINE__) PathConstraintMixTimeline(timelineMap->_size); + timeline->_pathConstraintIndex = constraintIndex; + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), + Json::getFloat(valueMap, "rotateMix", 1), + Json::getFloat(valueMap, "translateMix", 1)); + readCurve(valueMap, timeline, frameIndex); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[(timelineMap->_size - 1) * PathConstraintMixTimeline::ENTRIES]); + } + } + } - /** Deform timelines. */ - for (constraintMap = deform ? deform->_child : NULL; constraintMap; constraintMap = constraintMap->_next) { - Skin *skin = skeletonData->findSkin(constraintMap->_name); - for (slotMap = constraintMap->_child; slotMap; slotMap = slotMap->_next) { - int slotIndex = skeletonData->findSlotIndex(slotMap->_name); - Json *timelineMap; - for (timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) { - DeformTimeline *timeline; - int weighted, deformLength; + /** Deform timelines. */ + for (constraintMap = deform ? deform->_child : NULL; constraintMap; constraintMap = constraintMap->_next) { + Skin *skin = skeletonData->findSkin(constraintMap->_name); + for (slotMap = constraintMap->_child; slotMap; slotMap = slotMap->_next) { + int slotIndex = skeletonData->findSlotIndex(slotMap->_name); + Json *timelineMap; + for (timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) { + DeformTimeline *timeline; + int weighted, deformLength; - Attachment *baseAttachment = skin->getAttachment(slotIndex, timelineMap->_name); + Attachment *baseAttachment = skin->getAttachment(slotIndex, timelineMap->_name); - if (!baseAttachment) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - // setError(NULL, "Attachment not found: ", timelineMap->_name); - // return NULL; - continue; - } + if (!baseAttachment) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + // setError(NULL, "Attachment not found: ", timelineMap->_name); + // return NULL; + continue; + } - VertexAttachment *attachment = static_cast(baseAttachment); + VertexAttachment *attachment = static_cast(baseAttachment); - weighted = attachment->_bones.size() != 0; - Vector &verts = attachment->_vertices; - deformLength = weighted ? verts.size() / 3 * 2 : verts.size(); + weighted = attachment->_bones.size() != 0; + Vector &verts = attachment->_vertices; + deformLength = weighted ? verts.size() / 3 * 2 : verts.size(); - timeline = new(__FILE__, __LINE__) DeformTimeline(timelineMap->_size); + timeline = new (__FILE__, __LINE__) DeformTimeline(timelineMap->_size); - timeline->_slotIndex = slotIndex; - timeline->_attachment = attachment; + timeline->_slotIndex = slotIndex; + timeline->_attachment = attachment; - for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - Json *vertices = Json::getItem(valueMap, "vertices"); - Vector deformed; - if (!vertices) { - if (weighted) { - deformed.setSize(deformLength, 0); - } else { - deformed.clearAndAddAll(attachment->_vertices); - } - } else { - int v, start = Json::getInt(valueMap, "offset", 0); - Json *vertex; - deformed.setSize(deformLength, 0); - if (_scale == 1) { - for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) { - deformed[v] = vertex->_valueFloat; - } - } else { - for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) { - deformed[v] = vertex->_valueFloat * _scale; - } - } - if (!weighted) { - Vector &verticesAttachment = attachment->_vertices; - for (v = 0; v < deformLength; ++v) { - deformed[v] += verticesAttachment[v]; - } - } - } - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), deformed); - readCurve(valueMap, timeline, frameIndex); - } + for (valueMap = timelineMap->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + Json *vertices = Json::getItem(valueMap, "vertices"); + Vector deformed; + if (!vertices) { + if (weighted) { + deformed.setSize(deformLength, 0); + } else { + deformed.clearAndAddAll(attachment->_vertices); + } + } else { + int v, start = Json::getInt(valueMap, "offset", 0); + Json *vertex; + deformed.setSize(deformLength, 0); + if (_scale == 1) { + for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) { + deformed[v] = vertex->_valueFloat; + } + } else { + for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) { + deformed[v] = vertex->_valueFloat * _scale; + } + } + if (!weighted) { + Vector &verticesAttachment = attachment->_vertices; + for (v = 0; v < deformLength; ++v) { + deformed[v] += verticesAttachment[v]; + } + } + } + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), deformed); + readCurve(valueMap, timeline, frameIndex); + } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[timelineMap->_size - 1]); - } - } - } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[timelineMap->_size - 1]); + } + } + } - /** Draw order timeline. */ - if (drawOrder) { - DrawOrderTimeline *timeline = new(__FILE__, __LINE__) DrawOrderTimeline(drawOrder->_size); + /** Draw order timeline. */ + if (drawOrder) { + DrawOrderTimeline *timeline = new (__FILE__, __LINE__) DrawOrderTimeline(drawOrder->_size); - for (valueMap = drawOrder->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - int ii; - Vector drawOrder2; - Json *offsets = Json::getItem(valueMap, "offsets"); - if (offsets) { - Json *offsetMap; - Vector unchanged; - unchanged.ensureCapacity(skeletonData->_slots.size() - offsets->_size); - unchanged.setSize(skeletonData->_slots.size() - offsets->_size, 0); - size_t originalIndex = 0, unchangedIndex = 0; + for (valueMap = drawOrder->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + int ii; + Vector drawOrder2; + Json *offsets = Json::getItem(valueMap, "offsets"); + if (offsets) { + Json *offsetMap; + Vector unchanged; + unchanged.ensureCapacity(skeletonData->_slots.size() - offsets->_size); + unchanged.setSize(skeletonData->_slots.size() - offsets->_size, 0); + size_t originalIndex = 0, unchangedIndex = 0; - drawOrder2.ensureCapacity(skeletonData->_slots.size()); - drawOrder2.setSize(skeletonData->_slots.size(), 0); - for (ii = (int)skeletonData->_slots.size() - 1; ii >= 0; --ii) - drawOrder2[ii] = -1; + drawOrder2.ensureCapacity(skeletonData->_slots.size()); + drawOrder2.setSize(skeletonData->_slots.size(), 0); + for (ii = (int)skeletonData->_slots.size() - 1; ii >= 0; --ii) + drawOrder2[ii] = -1; - for (offsetMap = offsets->_child; offsetMap; offsetMap = offsetMap->_next) { - int slotIndex = skeletonData->findSlotIndex(Json::getString(offsetMap, "slot", 0)); - if (slotIndex == -1) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Slot not found: ", Json::getString(offsetMap, "slot", 0)); - return NULL; - } - /* Collect unchanged items. */ - while (originalIndex != (size_t)slotIndex) - unchanged[unchangedIndex++] = originalIndex++; - /* Set changed items. */ - drawOrder2[originalIndex + Json::getInt(offsetMap, "offset", 0)] = originalIndex; - originalIndex++; - } - /* Collect remaining unchanged items. */ - while (originalIndex < skeletonData->_slots.size()) - unchanged[unchangedIndex++] = originalIndex++; - /* Fill in unchanged items. */ - for (ii = (int)skeletonData->_slots.size() - 1; ii >= 0; ii--) - if (drawOrder2[ii] == -1) drawOrder2[ii] = unchanged[--unchangedIndex]; - } - timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), drawOrder2); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[drawOrder->_size - 1]); - } + for (offsetMap = offsets->_child; offsetMap; offsetMap = offsetMap->_next) { + int slotIndex = skeletonData->findSlotIndex(Json::getString(offsetMap, "slot", 0)); + if (slotIndex == -1) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Slot not found: ", Json::getString(offsetMap, "slot", 0)); + return NULL; + } + /* Collect unchanged items. */ + while (originalIndex != (size_t)slotIndex) + unchanged[unchangedIndex++] = originalIndex++; + /* Set changed items. */ + drawOrder2[originalIndex + Json::getInt(offsetMap, "offset", 0)] = originalIndex; + originalIndex++; + } + /* Collect remaining unchanged items. */ + while (originalIndex < skeletonData->_slots.size()) + unchanged[unchangedIndex++] = originalIndex++; + /* Fill in unchanged items. */ + for (ii = (int)skeletonData->_slots.size() - 1; ii >= 0; ii--) + if (drawOrder2[ii] == -1) drawOrder2[ii] = unchanged[--unchangedIndex]; + } + timeline->setFrame(frameIndex, Json::getFloat(valueMap, "time", 0), drawOrder2); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[drawOrder->_size - 1]); + } - /** Event timeline. */ - if (events) { - EventTimeline *timeline = new(__FILE__, __LINE__) EventTimeline(events->_size); + /** Event timeline. */ + if (events) { + EventTimeline *timeline = new (__FILE__, __LINE__) EventTimeline(events->_size); - for (valueMap = events->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { - Event *event; - EventData *eventData = skeletonData->findEvent(Json::getString(valueMap, "name", 0)); - if (!eventData) { - ContainerUtil::cleanUpVectorOfPointers(timelines); - setError(NULL, "Event not found: ", Json::getString(valueMap, "name", 0)); - return NULL; - } + for (valueMap = events->_child, frameIndex = 0; valueMap; valueMap = valueMap->_next, ++frameIndex) { + Event *event; + EventData *eventData = skeletonData->findEvent(Json::getString(valueMap, "name", 0)); + if (!eventData) { + ContainerUtil::cleanUpVectorOfPointers(timelines); + setError(NULL, "Event not found: ", Json::getString(valueMap, "name", 0)); + return NULL; + } - event = new(__FILE__, __LINE__) Event(Json::getFloat(valueMap, "time", 0), *eventData); - event->_intValue = Json::getInt(valueMap, "int", eventData->_intValue); - event->_floatValue = Json::getFloat(valueMap, "float", eventData->_floatValue); - event->_stringValue = Json::getString(valueMap, "string", eventData->_stringValue.buffer()); - if (!eventData->_audioPath.isEmpty()) { - event->_volume = Json::getFloat(valueMap, "volume", 1); - event->_balance = Json::getFloat(valueMap, "balance", 0); - } - timeline->setFrame(frameIndex, event); - } - timelines.add(timeline); - timelinesCount++; - duration = MathUtil::max(duration, timeline->_frames[events->_size - 1]); - } + event = new (__FILE__, __LINE__) Event(Json::getFloat(valueMap, "time", 0), *eventData); + event->_intValue = Json::getInt(valueMap, "int", eventData->_intValue); + event->_floatValue = Json::getFloat(valueMap, "float", eventData->_floatValue); + event->_stringValue = Json::getString(valueMap, "string", eventData->_stringValue.buffer()); + if (!eventData->_audioPath.isEmpty()) { + event->_volume = Json::getFloat(valueMap, "volume", 1); + event->_balance = Json::getFloat(valueMap, "balance", 0); + } + timeline->setFrame(frameIndex, event); + } + timelines.add(timeline); + timelinesCount++; + duration = MathUtil::max(duration, timeline->_frames[events->_size - 1]); + } - return new(__FILE__, __LINE__) Animation(String(root->_name), timelines, duration); + return new (__FILE__, __LINE__) Animation(String(root->_name), timelines, duration); } void SkeletonJson::readVertices(Json *attachmentMap, VertexAttachment *attachment, size_t verticesLength) { - Json *entry; - size_t i, n, nn, entrySize; - Vector vertices; + Json *entry; + size_t i, n, nn, entrySize; + Vector vertices; - attachment->setWorldVerticesLength(verticesLength); + attachment->setWorldVerticesLength(verticesLength); - entry = Json::getItem(attachmentMap, "vertices"); - entrySize = entry->_size; - vertices.ensureCapacity(entrySize); - vertices.setSize(entrySize, 0); - for (entry = entry->_child, i = 0; entry; entry = entry->_next, ++i) - vertices[i] = entry->_valueFloat; + entry = Json::getItem(attachmentMap, "vertices"); + entrySize = entry->_size; + vertices.ensureCapacity(entrySize); + vertices.setSize(entrySize, 0); + for (entry = entry->_child, i = 0; entry; entry = entry->_next, ++i) + vertices[i] = entry->_valueFloat; - if (verticesLength == entrySize) { - if (_scale != 1) { - for (i = 0; i < entrySize; ++i) - vertices[i] *= _scale; - } + if (verticesLength == entrySize) { + if (_scale != 1) { + for (i = 0; i < entrySize; ++i) + vertices[i] *= _scale; + } - attachment->getVertices().clearAndAddAll(vertices); - return; - } + attachment->getVertices().clearAndAddAll(vertices); + return; + } - Vertices bonesAndWeights; - bonesAndWeights._bones.ensureCapacity(verticesLength * 3); - bonesAndWeights._vertices.ensureCapacity(verticesLength * 3 * 3); + Vertices bonesAndWeights; + bonesAndWeights._bones.ensureCapacity(verticesLength * 3); + bonesAndWeights._vertices.ensureCapacity(verticesLength * 3 * 3); - for (i = 0, n = entrySize; i < n;) { - int boneCount = (int) vertices[i++]; - bonesAndWeights._bones.add(boneCount); - for (nn = i + boneCount * 4; i < nn; i += 4) { - bonesAndWeights._bones.add((int) vertices[i]); - bonesAndWeights._vertices.add(vertices[i + 1] * _scale); - bonesAndWeights._vertices.add(vertices[i + 2] * _scale); - bonesAndWeights._vertices.add(vertices[i + 3]); - } - } + for (i = 0, n = entrySize; i < n;) { + int boneCount = (int)vertices[i++]; + bonesAndWeights._bones.add(boneCount); + for (nn = i + boneCount * 4; i < nn; i += 4) { + bonesAndWeights._bones.add((int)vertices[i]); + bonesAndWeights._vertices.add(vertices[i + 1] * _scale); + bonesAndWeights._vertices.add(vertices[i + 2] * _scale); + bonesAndWeights._vertices.add(vertices[i + 3]); + } + } - attachment->getVertices().clearAndAddAll(bonesAndWeights._vertices); - attachment->getBones().clearAndAddAll(bonesAndWeights._bones); + attachment->getVertices().clearAndAddAll(bonesAndWeights._vertices); + attachment->getBones().clearAndAddAll(bonesAndWeights._bones); } void SkeletonJson::setError(Json *root, const String &value1, const String &value2) { - _error = String(value1).append(value2); - delete root; + _error = String(value1).append(value2); + delete root; } diff --git a/native/cocos/editor-support/spine/SkeletonJson.h b/native/cocos/editor-support/spine/SkeletonJson.h index b719855a44..2abeb949ca 100644 --- a/native/cocos/editor-support/spine/SkeletonJson.h +++ b/native/cocos/editor-support/spine/SkeletonJson.h @@ -55,37 +55,37 @@ class String; class SP_API SkeletonJson : public SpineObject { public: - explicit SkeletonJson(Atlas *atlas); + explicit SkeletonJson(Atlas *atlas); - explicit SkeletonJson(AttachmentLoader *attachmentLoader); + explicit SkeletonJson(AttachmentLoader *attachmentLoader); - ~SkeletonJson(); + ~SkeletonJson(); - SkeletonData *readSkeletonDataFile(const String &path); + SkeletonData *readSkeletonDataFile(const String &path); - SkeletonData *readSkeletonData(const char *json); + SkeletonData *readSkeletonData(const char *json); - void setScale(float scale) { _scale = scale; } + void setScale(float scale) { _scale = scale; } - String &getError() { return _error; } + String &getError() { return _error; } private: - AttachmentLoader *_attachmentLoader; - Vector _linkedMeshes; - float _scale; - const bool _ownsLoader; - String _error; + AttachmentLoader *_attachmentLoader; + Vector _linkedMeshes; + float _scale; + const bool _ownsLoader; + String _error; - static float toColor(const char *value, size_t index); + static float toColor(const char *value, size_t index); - static void readCurve(Json *frame, CurveTimeline *timeline, size_t frameIndex); + static void readCurve(Json *frame, CurveTimeline *timeline, size_t frameIndex); - Animation *readAnimation(Json *root, SkeletonData *skeletonData); + Animation *readAnimation(Json *root, SkeletonData *skeletonData); - void readVertices(Json *attachmentMap, VertexAttachment *attachment, size_t verticesLength); + void readVertices(Json *attachmentMap, VertexAttachment *attachment, size_t verticesLength); - void setError(Json *root, const String &value1, const String &value2); + void setError(Json *root, const String &value1, const String &value2); }; -} +} // namespace spine #endif /* Spine_SkeletonJson_h */ diff --git a/native/cocos/editor-support/spine/Skin.cpp b/native/cocos/editor-support/spine/Skin.cpp index caf02258e9..70a2de7eb3 100644 --- a/native/cocos/editor-support/spine/Skin.cpp +++ b/native/cocos/editor-support/spine/Skin.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -47,152 +47,152 @@ using namespace spine; Skin::AttachmentMap::AttachmentMap() { } -static void disposeAttachment(Attachment* attachment) { - if (!attachment) return; - attachment->dereference(); - if (attachment->getRefCount() == 0) delete attachment; +static void disposeAttachment(Attachment *attachment) { + if (!attachment) return; + attachment->dereference(); + if (attachment->getRefCount() == 0) delete attachment; } void Skin::AttachmentMap::put(size_t slotIndex, const String &attachmentName, Attachment *attachment) { - if (slotIndex >= _buckets.size()) - _buckets.setSize(slotIndex + 1, Vector()); - Vector &bucket = _buckets[slotIndex]; - int existing = findInBucket(bucket, attachmentName); - attachment->reference(); - if (existing >= 0) { - disposeAttachment(bucket[existing]._attachment); - bucket[existing]._attachment = attachment; - } else { - bucket.add(Entry(slotIndex, attachmentName, attachment)); - } + if (slotIndex >= _buckets.size()) + _buckets.setSize(slotIndex + 1, Vector()); + Vector &bucket = _buckets[slotIndex]; + int existing = findInBucket(bucket, attachmentName); + attachment->reference(); + if (existing >= 0) { + disposeAttachment(bucket[existing]._attachment); + bucket[existing]._attachment = attachment; + } else { + bucket.add(Entry(slotIndex, attachmentName, attachment)); + } } Attachment *Skin::AttachmentMap::get(size_t slotIndex, const String &attachmentName) { - if (slotIndex >= _buckets.size()) return NULL; - int existing = findInBucket(_buckets[slotIndex], attachmentName); - return existing >= 0 ? _buckets[slotIndex][existing]._attachment : NULL; + if (slotIndex >= _buckets.size()) return NULL; + int existing = findInBucket(_buckets[slotIndex], attachmentName); + return existing >= 0 ? _buckets[slotIndex][existing]._attachment : NULL; } void Skin::AttachmentMap::remove(size_t slotIndex, const String &attachmentName) { - if (slotIndex >= _buckets.size()) return; - int existing = findInBucket(_buckets[slotIndex], attachmentName); - if (existing >= 0) { - disposeAttachment(_buckets[slotIndex][existing]._attachment); - _buckets[slotIndex].removeAt(existing); - } + if (slotIndex >= _buckets.size()) return; + int existing = findInBucket(_buckets[slotIndex], attachmentName); + if (existing >= 0) { + disposeAttachment(_buckets[slotIndex][existing]._attachment); + _buckets[slotIndex].removeAt(existing); + } } int Skin::AttachmentMap::findInBucket(Vector &bucket, const String &attachmentName) { - for (size_t i = 0; i < bucket.size(); i++) - if (bucket[i]._name == attachmentName) return i; - return -1; + for (size_t i = 0; i < bucket.size(); i++) + if (bucket[i]._name == attachmentName) return i; + return -1; } Skin::AttachmentMap::Entries Skin::AttachmentMap::getEntries() { - return Skin::AttachmentMap::Entries(_buckets); + return Skin::AttachmentMap::Entries(_buckets); } Skin::Skin(const String &name) : _name(name), _attachments() { - assert(_name.length() > 0); + assert(_name.length() > 0); } Skin::~Skin() { - Skin::AttachmentMap::Entries entries = _attachments.getEntries(); - while (entries.hasNext()) { - Skin::AttachmentMap::Entry entry = entries.next(); - disposeAttachment(entry._attachment); - } + Skin::AttachmentMap::Entries entries = _attachments.getEntries(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry entry = entries.next(); + disposeAttachment(entry._attachment); + } } void Skin::setAttachment(size_t slotIndex, const String &name, Attachment *attachment) { - assert(attachment); - _attachments.put(slotIndex, name, attachment); + assert(attachment); + _attachments.put(slotIndex, name, attachment); } Attachment *Skin::getAttachment(size_t slotIndex, const String &name) { - return _attachments.get(slotIndex, name); + return _attachments.get(slotIndex, name); } -void Skin::removeAttachment(size_t slotIndex, const String& name) { - _attachments.remove(slotIndex, name); +void Skin::removeAttachment(size_t slotIndex, const String &name) { + _attachments.remove(slotIndex, name); } void Skin::findNamesForSlot(size_t slotIndex, Vector &names) { - Skin::AttachmentMap::Entries entries = _attachments.getEntries(); - while (entries.hasNext()) { - Skin::AttachmentMap::Entry &entry = entries.next(); - if (entry._slotIndex == slotIndex) { - names.add(entry._name); - } - } + Skin::AttachmentMap::Entries entries = _attachments.getEntries(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry &entry = entries.next(); + if (entry._slotIndex == slotIndex) { + names.add(entry._name); + } + } } void Skin::findAttachmentsForSlot(size_t slotIndex, Vector &attachments) { - Skin::AttachmentMap::Entries entries = _attachments.getEntries(); - while (entries.hasNext()) { - Skin::AttachmentMap::Entry &entry = entries.next(); - if (entry._slotIndex == slotIndex) attachments.add(entry._attachment); - } + Skin::AttachmentMap::Entries entries = _attachments.getEntries(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry &entry = entries.next(); + if (entry._slotIndex == slotIndex) attachments.add(entry._attachment); + } } const String &Skin::getName() { - return _name; + return _name; } Skin::AttachmentMap::Entries Skin::getAttachments() { - return _attachments.getEntries(); + return _attachments.getEntries(); } void Skin::attachAll(Skeleton &skeleton, Skin &oldSkin) { - Vector &slots = skeleton.getSlots(); - Skin::AttachmentMap::Entries entries = oldSkin.getAttachments(); - while (entries.hasNext()) { - Skin::AttachmentMap::Entry &entry = entries.next(); - int slotIndex = entry._slotIndex; - Slot *slot = slots[slotIndex]; + Vector &slots = skeleton.getSlots(); + Skin::AttachmentMap::Entries entries = oldSkin.getAttachments(); + while (entries.hasNext()) { + Skin::AttachmentMap::Entry &entry = entries.next(); + int slotIndex = entry._slotIndex; + Slot *slot = slots[slotIndex]; - if (slot->getAttachment() == entry._attachment) { - Attachment *attachment = getAttachment(slotIndex, entry._name); - if (attachment) slot->setAttachment(attachment); - } - } + if (slot->getAttachment() == entry._attachment) { + Attachment *attachment = getAttachment(slotIndex, entry._name); + if (attachment) slot->setAttachment(attachment); + } + } } -void Skin::addSkin(Skin* other) { - for (size_t i = 0; i < other->getBones().size(); i++) - if (!_bones.contains(other->getBones()[i])) _bones.add(other->getBones()[i]); +void Skin::addSkin(Skin *other) { + for (size_t i = 0; i < other->getBones().size(); i++) + if (!_bones.contains(other->getBones()[i])) _bones.add(other->getBones()[i]); - for (size_t i = 0; i < other->getConstraints().size(); i++) - if (!_constraints.contains(other->getConstraints()[i])) _constraints.add(other->getConstraints()[i]); + for (size_t i = 0; i < other->getConstraints().size(); i++) + if (!_constraints.contains(other->getConstraints()[i])) _constraints.add(other->getConstraints()[i]); - AttachmentMap::Entries entries = other->getAttachments(); - while(entries.hasNext()) { - AttachmentMap::Entry& entry = entries.next(); - setAttachment(entry._slotIndex, entry._name, entry._attachment); - } + AttachmentMap::Entries entries = other->getAttachments(); + while (entries.hasNext()) { + AttachmentMap::Entry &entry = entries.next(); + setAttachment(entry._slotIndex, entry._name, entry._attachment); + } } -void Skin::copySkin(Skin* other) { - for (size_t i = 0; i < other->getBones().size(); i++) - if (!_bones.contains(other->getBones()[i])) _bones.add(other->getBones()[i]); +void Skin::copySkin(Skin *other) { + for (size_t i = 0; i < other->getBones().size(); i++) + if (!_bones.contains(other->getBones()[i])) _bones.add(other->getBones()[i]); - for (size_t i = 0; i < other->getConstraints().size(); i++) - if (!_constraints.contains(other->getConstraints()[i])) _constraints.add(other->getConstraints()[i]); + for (size_t i = 0; i < other->getConstraints().size(); i++) + if (!_constraints.contains(other->getConstraints()[i])) _constraints.add(other->getConstraints()[i]); - AttachmentMap::Entries entries = other->getAttachments(); - while(entries.hasNext()) { - AttachmentMap::Entry& entry = entries.next(); - if (entry._attachment->getRTTI().isExactly(MeshAttachment::rtti)) - setAttachment(entry._slotIndex, entry._name, static_cast(entry._attachment)->newLinkedMesh()); - else - setAttachment(entry._slotIndex, entry._name, entry._attachment->copy()); - } + AttachmentMap::Entries entries = other->getAttachments(); + while (entries.hasNext()) { + AttachmentMap::Entry &entry = entries.next(); + if (entry._attachment->getRTTI().isExactly(MeshAttachment::rtti)) + setAttachment(entry._slotIndex, entry._name, static_cast(entry._attachment)->newLinkedMesh()); + else + setAttachment(entry._slotIndex, entry._name, entry._attachment->copy()); + } } -Vector& Skin::getConstraints() { - return _constraints; +Vector &Skin::getConstraints() { + return _constraints; } -Vector& Skin::getBones() { - return _bones; +Vector &Skin::getBones() { + return _bones; } diff --git a/native/cocos/editor-support/spine/Skin.h b/native/cocos/editor-support/spine/Skin.h index 18dadba7ed..371295716d 100644 --- a/native/cocos/editor-support/spine/Skin.h +++ b/native/cocos/editor-support/spine/Skin.h @@ -44,121 +44,120 @@ class ConstraintData; /// See SkeletonData::getDefaultSkin, Skeleton::getSkin, and /// http://esotericsoftware.com/spine-runtime-skins in the Spine Runtimes Guide. class SP_API Skin : public SpineObject { - friend class Skeleton; + friend class Skeleton; public: - class SP_API AttachmentMap : public SpineObject { - friend class Skin; + class SP_API AttachmentMap : public SpineObject { + friend class Skin; - public: - struct SP_API Entry { - size_t _slotIndex; - String _name; - Attachment *_attachment; + public: + struct SP_API Entry { + size_t _slotIndex; + String _name; + Attachment *_attachment; - Entry(size_t slotIndex, const String &name, Attachment *attachment) : - _slotIndex(slotIndex), - _name(name), - _attachment(attachment) { - } - }; + Entry(size_t slotIndex, const String &name, Attachment *attachment) : _slotIndex(slotIndex), + _name(name), + _attachment(attachment) { + } + }; - class SP_API Entries { - friend class AttachmentMap; + class SP_API Entries { + friend class AttachmentMap; - public: - bool hasNext() { - while(true) { - if (_slotIndex >= _buckets.size()) return false; - if (_bucketIndex >= _buckets[_slotIndex].size()) { - _bucketIndex = 0; - ++_slotIndex; - continue; - }; - return true; - } - } + public: + bool hasNext() { + while (true) { + if (_slotIndex >= _buckets.size()) return false; + if (_bucketIndex >= _buckets[_slotIndex].size()) { + _bucketIndex = 0; + ++_slotIndex; + continue; + }; + return true; + } + } - Entry &next() { - Entry &result = _buckets[_slotIndex][_bucketIndex]; - ++_bucketIndex; - return result; - } + Entry &next() { + Entry &result = _buckets[_slotIndex][_bucketIndex]; + ++_bucketIndex; + return result; + } - protected: - Entries(Vector< Vector > &buckets) : _buckets(buckets), _slotIndex(0), _bucketIndex(0) { - } + protected: + Entries(Vector > &buckets) : _buckets(buckets), _slotIndex(0), _bucketIndex(0) { + } - private: - Vector< Vector > &_buckets; - size_t _slotIndex; - size_t _bucketIndex; - }; + private: + Vector > &_buckets; + size_t _slotIndex; + size_t _bucketIndex; + }; - void put(size_t slotIndex, const String &attachmentName, Attachment *attachment); + void put(size_t slotIndex, const String &attachmentName, Attachment *attachment); - Attachment *get(size_t slotIndex, const String &attachmentName); + Attachment *get(size_t slotIndex, const String &attachmentName); - void remove(size_t slotIndex, const String &attachmentName); + void remove(size_t slotIndex, const String &attachmentName); - Entries getEntries(); + Entries getEntries(); - protected: - AttachmentMap(); + protected: + AttachmentMap(); - private: + private: + int findInBucket(Vector &, const String &attachmentName); - int findInBucket(Vector &, const String &attachmentName); + Vector > _buckets; + }; - Vector > _buckets; - }; + explicit Skin(const String &name); - explicit Skin(const String &name); + ~Skin(); - ~Skin(); + /// Adds an attachment to the skin for the specified slot index and name. + /// If the name already exists for the slot, the previous value is replaced. + void setAttachment(size_t slotIndex, const String &name, Attachment *attachment); - /// Adds an attachment to the skin for the specified slot index and name. - /// If the name already exists for the slot, the previous value is replaced. - void setAttachment(size_t slotIndex, const String &name, Attachment *attachment); + /// Returns the attachment for the specified slot index and name, or NULL. + Attachment *getAttachment(size_t slotIndex, const String &name); - /// Returns the attachment for the specified slot index and name, or NULL. - Attachment *getAttachment(size_t slotIndex, const String &name); + // Removes the attachment from the skin. + void removeAttachment(size_t slotIndex, const String &name); - // Removes the attachment from the skin. - void removeAttachment(size_t slotIndex, const String& name); + /// Finds the skin keys for a given slot. The results are added to the passed array of names. + /// @param slotIndex The target slotIndex. To find the slot index, use Skeleton::findSlotIndex or SkeletonData::findSlotIndex + /// @param names Found skin key names will be added to this array. + void findNamesForSlot(size_t slotIndex, Vector &names); - /// Finds the skin keys for a given slot. The results are added to the passed array of names. - /// @param slotIndex The target slotIndex. To find the slot index, use Skeleton::findSlotIndex or SkeletonData::findSlotIndex - /// @param names Found skin key names will be added to this array. - void findNamesForSlot(size_t slotIndex, Vector &names); + /// Finds the attachments for a given slot. The results are added to the passed array of Attachments. + /// @param slotIndex The target slotIndex. To find the slot index, use Skeleton::findSlotIndex or SkeletonData::findSlotIndex + /// @param attachments Found Attachments will be added to this array. + void findAttachmentsForSlot(size_t slotIndex, Vector &attachments); - /// Finds the attachments for a given slot. The results are added to the passed array of Attachments. - /// @param slotIndex The target slotIndex. To find the slot index, use Skeleton::findSlotIndex or SkeletonData::findSlotIndex - /// @param attachments Found Attachments will be added to this array. - void findAttachmentsForSlot(size_t slotIndex, Vector &attachments); + const String &getName(); - const String &getName(); + /// Adds all attachments, bones, and constraints from the specified skin to this skin. + void addSkin(Skin *other); - /// Adds all attachments, bones, and constraints from the specified skin to this skin. - void addSkin(Skin* other); + /// Adds all attachments, bones, and constraints from the specified skin to this skin. Attachments are deep copied. + void copySkin(Skin *other); - /// Adds all attachments, bones, and constraints from the specified skin to this skin. Attachments are deep copied. - void copySkin(Skin* other); + AttachmentMap::Entries getAttachments(); - AttachmentMap::Entries getAttachments(); + Vector &getBones(); - Vector& getBones(); + Vector &getConstraints(); - Vector& getConstraints(); private: - const String _name; - AttachmentMap _attachments; - Vector _bones; - Vector _constraints; + const String _name; + AttachmentMap _attachments; + Vector _bones; + Vector _constraints; - /// Attach all attachments from this skin if the corresponding attachment from the old skin is currently attached. - void attachAll(Skeleton &skeleton, Skin &oldSkin); + /// Attach all attachments from this skin if the corresponding attachment from the old skin is currently attached. + void attachAll(Skeleton &skeleton, Skin &oldSkin); }; -} +} // namespace spine #endif /* Spine_Skin_h */ diff --git a/native/cocos/editor-support/spine/Slot.cpp b/native/cocos/editor-support/spine/Slot.cpp index 0cc8f23e68..ae3ffb7743 100644 --- a/native/cocos/editor-support/spine/Slot.cpp +++ b/native/cocos/editor-support/spine/Slot.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -40,76 +40,75 @@ using namespace spine; -Slot::Slot(SlotData &data, Bone &bone) : - _data(data), - _bone(bone), - _skeleton(bone.getSkeleton()), - _color(1, 1, 1, 1), - _darkColor(0, 0, 0, 0), - _hasDarkColor(data.hasDarkColor()), - _attachment(NULL), - _attachmentTime(0) { - setToSetupPose(); +Slot::Slot(SlotData &data, Bone &bone) : _data(data), + _bone(bone), + _skeleton(bone.getSkeleton()), + _color(1, 1, 1, 1), + _darkColor(0, 0, 0, 0), + _hasDarkColor(data.hasDarkColor()), + _attachment(NULL), + _attachmentTime(0) { + setToSetupPose(); } void Slot::setToSetupPose() { - _color.set(_data.getColor()); + _color.set(_data.getColor()); - const String &attachmentName = _data.getAttachmentName(); - if (attachmentName.length() > 0) { - _attachment = NULL; - setAttachment(_skeleton.getAttachment(_data.getIndex(), attachmentName)); - } else { - setAttachment(NULL); - } + const String &attachmentName = _data.getAttachmentName(); + if (attachmentName.length() > 0) { + _attachment = NULL; + setAttachment(_skeleton.getAttachment(_data.getIndex(), attachmentName)); + } else { + setAttachment(NULL); + } } SlotData &Slot::getData() { - return _data; + return _data; } Bone &Slot::getBone() { - return _bone; + return _bone; } Skeleton &Slot::getSkeleton() { - return _skeleton; + return _skeleton; } Color &Slot::getColor() { - return _color; + return _color; } Color &Slot::getDarkColor() { - return _darkColor; + return _darkColor; } bool Slot::hasDarkColor() { - return _hasDarkColor; + return _hasDarkColor; } Attachment *Slot::getAttachment() { - return _attachment; + return _attachment; } void Slot::setAttachment(Attachment *inValue) { - if (_attachment == inValue) { - return; - } + if (_attachment == inValue) { + return; + } - _attachment = inValue; - _attachmentTime = _skeleton.getTime(); - _deform.clear(); + _attachment = inValue; + _attachmentTime = _skeleton.getTime(); + _deform.clear(); } float Slot::getAttachmentTime() { - return _skeleton.getTime() - _attachmentTime; + return _skeleton.getTime() - _attachmentTime; } void Slot::setAttachmentTime(float inValue) { - _attachmentTime = _skeleton.getTime() - inValue; + _attachmentTime = _skeleton.getTime() - inValue; } Vector &Slot::getDeform() { - return _deform; + return _deform; } diff --git a/native/cocos/editor-support/spine/Slot.h b/native/cocos/editor-support/spine/Slot.h index 0f2f5144fa..d437ad7056 100644 --- a/native/cocos/editor-support/spine/Slot.h +++ b/native/cocos/editor-support/spine/Slot.h @@ -44,81 +44,81 @@ class Skeleton; class Attachment; class SP_API Slot : public SpineObject { - friend class VertexAttachment; + friend class VertexAttachment; - friend class Skeleton; + friend class Skeleton; - friend class SkeletonBounds; + friend class SkeletonBounds; - friend class SkeletonClipping; + friend class SkeletonClipping; - friend class AttachmentTimeline; + friend class AttachmentTimeline; - friend class ColorTimeline; + friend class ColorTimeline; - friend class DeformTimeline; + friend class DeformTimeline; - friend class DrawOrderTimeline; + friend class DrawOrderTimeline; - friend class EventTimeline; + friend class EventTimeline; - friend class IkConstraintTimeline; + friend class IkConstraintTimeline; - friend class PathConstraintMixTimeline; + friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; + friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; + friend class PathConstraintSpacingTimeline; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TransformConstraintTimeline; + friend class TransformConstraintTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; - friend class TwoColorTimeline; + friend class TwoColorTimeline; public: - Slot(SlotData &data, Bone &bone); + Slot(SlotData &data, Bone &bone); - void setToSetupPose(); + void setToSetupPose(); - SlotData &getData(); + SlotData &getData(); - Bone &getBone(); + Bone &getBone(); - Skeleton &getSkeleton(); + Skeleton &getSkeleton(); - Color &getColor(); + Color &getColor(); - Color &getDarkColor(); + Color &getDarkColor(); - bool hasDarkColor(); + bool hasDarkColor(); - /// May be NULL. - Attachment *getAttachment(); + /// May be NULL. + Attachment *getAttachment(); - void setAttachment(Attachment *inValue); + void setAttachment(Attachment *inValue); - float getAttachmentTime(); + float getAttachmentTime(); - void setAttachmentTime(float inValue); + void setAttachmentTime(float inValue); - Vector &getDeform(); + Vector &getDeform(); private: - SlotData &_data; - Bone &_bone; - Skeleton &_skeleton; - Color _color; - Color _darkColor; - bool _hasDarkColor; - Attachment *_attachment; - float _attachmentTime; - Vector _deform; + SlotData &_data; + Bone &_bone; + Skeleton &_skeleton; + Color _color; + Color _darkColor; + bool _hasDarkColor; + Attachment *_attachment; + float _attachmentTime; + Vector _deform; }; -} +} // namespace spine #endif /* Spine_Slot_h */ diff --git a/native/cocos/editor-support/spine/SlotData.cpp b/native/cocos/editor-support/spine/SlotData.cpp index 4f61894e8f..281c9da365 100644 --- a/native/cocos/editor-support/spine/SlotData.cpp +++ b/native/cocos/editor-support/spine/SlotData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,59 +37,58 @@ using namespace spine; -SlotData::SlotData(int index, const String &name, BoneData &boneData) : - _index(index), - _name(name), - _boneData(boneData), - _color(1, 1, 1, 1), - _darkColor(0, 0, 0, 0), - _hasDarkColor(false), - _attachmentName(), - _blendMode(BlendMode_Normal) { - assert(_index >= 0); - assert(_name.length() > 0); +SlotData::SlotData(int index, const String &name, BoneData &boneData) : _index(index), + _name(name), + _boneData(boneData), + _color(1, 1, 1, 1), + _darkColor(0, 0, 0, 0), + _hasDarkColor(false), + _attachmentName(), + _blendMode(BlendMode_Normal) { + assert(_index >= 0); + assert(_name.length() > 0); } int SlotData::getIndex() { - return _index; + return _index; } const String &SlotData::getName() { - return _name; + return _name; } BoneData &SlotData::getBoneData() { - return _boneData; + return _boneData; } Color &SlotData::getColor() { - return _color; + return _color; } Color &SlotData::getDarkColor() { - return _darkColor; + return _darkColor; } bool SlotData::hasDarkColor() { - return _hasDarkColor; + return _hasDarkColor; } void SlotData::setHasDarkColor(bool inValue) { - _hasDarkColor = inValue; + _hasDarkColor = inValue; } const String &SlotData::getAttachmentName() { - return _attachmentName; + return _attachmentName; } void SlotData::setAttachmentName(const String &inValue) { - _attachmentName = inValue; + _attachmentName = inValue; } BlendMode SlotData::getBlendMode() { - return _blendMode; + return _blendMode; } void SlotData::setBlendMode(BlendMode inValue) { - _blendMode = inValue; + _blendMode = inValue; } diff --git a/native/cocos/editor-support/spine/SlotData.h b/native/cocos/editor-support/spine/SlotData.h index 24919be570..2bf7638cf4 100644 --- a/native/cocos/editor-support/spine/SlotData.h +++ b/native/cocos/editor-support/spine/SlotData.h @@ -39,75 +39,75 @@ namespace spine { class BoneData; class SP_API SlotData : public SpineObject { - friend class SkeletonBinary; + friend class SkeletonBinary; - friend class SkeletonJson; + friend class SkeletonJson; - friend class AttachmentTimeline; + friend class AttachmentTimeline; - friend class ColorTimeline; + friend class ColorTimeline; - friend class DeformTimeline; + friend class DeformTimeline; - friend class DrawOrderTimeline; + friend class DrawOrderTimeline; - friend class EventTimeline; + friend class EventTimeline; - friend class IkConstraintTimeline; + friend class IkConstraintTimeline; - friend class PathConstraintMixTimeline; + friend class PathConstraintMixTimeline; - friend class PathConstraintPositionTimeline; + friend class PathConstraintPositionTimeline; - friend class PathConstraintSpacingTimeline; + friend class PathConstraintSpacingTimeline; - friend class ScaleTimeline; + friend class ScaleTimeline; - friend class ShearTimeline; + friend class ShearTimeline; - friend class TransformConstraintTimeline; + friend class TransformConstraintTimeline; - friend class TranslateTimeline; + friend class TranslateTimeline; - friend class TwoColorTimeline; + friend class TwoColorTimeline; public: - SlotData(int index, const String &name, BoneData &boneData); + SlotData(int index, const String &name, BoneData &boneData); - int getIndex(); + int getIndex(); - const String &getName(); + const String &getName(); - BoneData &getBoneData(); + BoneData &getBoneData(); - Color &getColor(); + Color &getColor(); - Color &getDarkColor(); + Color &getDarkColor(); - bool hasDarkColor(); + bool hasDarkColor(); - void setHasDarkColor(bool inValue); + void setHasDarkColor(bool inValue); - /// May be empty. - const String &getAttachmentName(); + /// May be empty. + const String &getAttachmentName(); - void setAttachmentName(const String &inValue); + void setAttachmentName(const String &inValue); - BlendMode getBlendMode(); + BlendMode getBlendMode(); - void setBlendMode(BlendMode inValue); + void setBlendMode(BlendMode inValue); private: - const int _index; - String _name; - BoneData &_boneData; - Color _color; - Color _darkColor; + const int _index; + String _name; + BoneData &_boneData; + Color _color; + Color _darkColor; - bool _hasDarkColor; - String _attachmentName; - BlendMode _blendMode; + bool _hasDarkColor; + String _attachmentName; + BlendMode _blendMode; }; -} +} // namespace spine #endif /* Spine_SlotData_h */ diff --git a/native/cocos/editor-support/spine/SpacingMode.h b/native/cocos/editor-support/spine/SpacingMode.h index c76d6dbfab..c84ea5ed40 100644 --- a/native/cocos/editor-support/spine/SpacingMode.h +++ b/native/cocos/editor-support/spine/SpacingMode.h @@ -32,9 +32,9 @@ namespace spine { enum SpacingMode { - SpacingMode_Length = 0, - SpacingMode_Fixed, - SpacingMode_Percent + SpacingMode_Length = 0, + SpacingMode_Fixed, + SpacingMode_Percent }; } diff --git a/native/cocos/editor-support/spine/SpineObject.cpp b/native/cocos/editor-support/spine/SpineObject.cpp index 34308f4325..2ff229a438 100644 --- a/native/cocos/editor-support/spine/SpineObject.cpp +++ b/native/cocos/editor-support/spine/SpineObject.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,29 +37,29 @@ using namespace spine; void *SpineObject::operator new(size_t sz) { - return SpineExtension::getInstance()->_calloc(sz, __FILE__, __LINE__); + return SpineExtension::getInstance()->_calloc(sz, __FILE__, __LINE__); } void *SpineObject::operator new(size_t sz, const char *file, int line) { - return SpineExtension::getInstance()->_calloc(sz, file, line); + return SpineExtension::getInstance()->_calloc(sz, file, line); } void *SpineObject::operator new(size_t sz, void *ptr) { - SP_UNUSED(sz); - return ptr; + SP_UNUSED(sz); + return ptr; } void SpineObject::operator delete(void *p, const char *file, int line) { - SpineExtension::free(p, file, line); + SpineExtension::free(p, file, line); } void SpineObject::operator delete(void *p, void *mem) { - SP_UNUSED(mem); - SpineExtension::free(p, __FILE__, __LINE__); + SP_UNUSED(mem); + SpineExtension::free(p, __FILE__, __LINE__); } void SpineObject::operator delete(void *p) { - SpineExtension::free(p, __FILE__, __LINE__); + SpineExtension::free(p, __FILE__, __LINE__); } SpineObject::~SpineObject() { diff --git a/native/cocos/editor-support/spine/SpineObject.h b/native/cocos/editor-support/spine/SpineObject.h index 896a8aeb4b..f618a4231c 100644 --- a/native/cocos/editor-support/spine/SpineObject.h +++ b/native/cocos/editor-support/spine/SpineObject.h @@ -40,20 +40,20 @@ class String; class SP_API SpineObject { public: - void *operator new(size_t sz); + void *operator new(size_t sz); - void *operator new(size_t sz, const char *file, int line); + void *operator new(size_t sz, const char *file, int line); - void *operator new(size_t sz, void *ptr); + void *operator new(size_t sz, void *ptr); - void operator delete(void *p, const char *file, int line); + void operator delete(void *p, const char *file, int line); - void operator delete(void *p, void *mem); + void operator delete(void *p, void *mem); - void operator delete(void *p); + void operator delete(void *p); - virtual ~SpineObject(); + virtual ~SpineObject(); }; -} +} // namespace spine #endif diff --git a/native/cocos/editor-support/spine/SpineString.h b/native/cocos/editor-support/spine/SpineString.h index 06479fcc6e..db45d16b36 100644 --- a/native/cocos/editor-support/spine/SpineString.h +++ b/native/cocos/editor-support/spine/SpineString.h @@ -38,175 +38,174 @@ // Required for sprintf on MSVC #ifdef _MSC_VER -#pragma warning(disable:4996) + #pragma warning(disable : 4996) #endif namespace spine { class SP_API String : public SpineObject { public: - String() : _length(0), _buffer(NULL) { - } + String() : _length(0), _buffer(NULL) { + } - String(const char *chars, bool own = false) { - if (!chars) { - _length = 0; - _buffer = NULL; - } else { - _length = strlen(chars); - if (!own) { - _buffer = SpineExtension::calloc(_length + 1, __FILE__, __LINE__); - memcpy((void *) _buffer, chars, _length + 1); - } else { - _buffer = (char *) chars; - } - } - } + String(const char *chars, bool own = false) { + if (!chars) { + _length = 0; + _buffer = NULL; + } else { + _length = strlen(chars); + if (!own) { + _buffer = SpineExtension::calloc(_length + 1, __FILE__, __LINE__); + memcpy((void *)_buffer, chars, _length + 1); + } else { + _buffer = (char *)chars; + } + } + } - String(const String &other) { - if (!other._buffer) { - _length = 0; - _buffer = NULL; - } else { - _length = other._length; - _buffer = SpineExtension::calloc(other._length + 1, __FILE__, __LINE__); - memcpy((void *) _buffer, other._buffer, other._length + 1); - } - } + String(const String &other) { + if (!other._buffer) { + _length = 0; + _buffer = NULL; + } else { + _length = other._length; + _buffer = SpineExtension::calloc(other._length + 1, __FILE__, __LINE__); + memcpy((void *)_buffer, other._buffer, other._length + 1); + } + } - size_t length() const { - return _length; - } + size_t length() const { + return _length; + } - bool isEmpty() const { - return _length == 0; - } + bool isEmpty() const { + return _length == 0; + } - const char *buffer() const { - return _buffer; - } + const char *buffer() const { + return _buffer; + } - void own(const String &other) { - if (this == &other) return; - if (_buffer) { - SpineExtension::free(_buffer, __FILE__, __LINE__); - } - _length = other._length; - _buffer = other._buffer; - other._length = 0; - other._buffer = NULL; - } + void own(const String &other) { + if (this == &other) return; + if (_buffer) { + SpineExtension::free(_buffer, __FILE__, __LINE__); + } + _length = other._length; + _buffer = other._buffer; + other._length = 0; + other._buffer = NULL; + } - void own(const char *chars) { - if (_buffer == chars) return; - if (_buffer) { - SpineExtension::free(_buffer, __FILE__, __LINE__); - } + void own(const char *chars) { + if (_buffer == chars) return; + if (_buffer) { + SpineExtension::free(_buffer, __FILE__, __LINE__); + } - if (!chars) { - _length = 0; - _buffer = NULL; - } else { - _length = strlen(chars); - _buffer = (char *) chars; - } - } + if (!chars) { + _length = 0; + _buffer = NULL; + } else { + _length = strlen(chars); + _buffer = (char *)chars; + } + } - void unown() { - _length = 0; - _buffer = NULL; - } + void unown() { + _length = 0; + _buffer = NULL; + } - String &operator=(const String &other) { - if (this == &other) return *this; - if (_buffer) { - SpineExtension::free(_buffer, __FILE__, __LINE__); - } - if (!other._buffer) { - _length = 0; - _buffer = NULL; - } else { - _length = other._length; - _buffer = SpineExtension::calloc(other._length + 1, __FILE__, __LINE__); - memcpy((void *) _buffer, other._buffer, other._length + 1); - } - return *this; - } + String &operator=(const String &other) { + if (this == &other) return *this; + if (_buffer) { + SpineExtension::free(_buffer, __FILE__, __LINE__); + } + if (!other._buffer) { + _length = 0; + _buffer = NULL; + } else { + _length = other._length; + _buffer = SpineExtension::calloc(other._length + 1, __FILE__, __LINE__); + memcpy((void *)_buffer, other._buffer, other._length + 1); + } + return *this; + } - String &operator=(const char *chars) { - if (_buffer == chars) return *this; - if (_buffer) { - SpineExtension::free(_buffer, __FILE__, __LINE__); - } - if (!chars) { - _length = 0; - _buffer = NULL; - } else { - _length = strlen(chars); - _buffer = SpineExtension::calloc(_length + 1, __FILE__, __LINE__); - memcpy((void *) _buffer, chars, _length + 1); - } - return *this; - } + String &operator=(const char *chars) { + if (_buffer == chars) return *this; + if (_buffer) { + SpineExtension::free(_buffer, __FILE__, __LINE__); + } + if (!chars) { + _length = 0; + _buffer = NULL; + } else { + _length = strlen(chars); + _buffer = SpineExtension::calloc(_length + 1, __FILE__, __LINE__); + memcpy((void *)_buffer, chars, _length + 1); + } + return *this; + } - String &append(const char *chars) { - size_t len = strlen(chars); - size_t thisLen = _length; - _length = _length + len; - bool same = chars == _buffer; - _buffer = SpineExtension::realloc(_buffer, _length + 1, __FILE__, __LINE__); - memcpy((void *) (_buffer + thisLen), (void *) (same ? _buffer : chars), len + 1); - return *this; - } + String &append(const char *chars) { + size_t len = strlen(chars); + size_t thisLen = _length; + _length = _length + len; + bool same = chars == _buffer; + _buffer = SpineExtension::realloc(_buffer, _length + 1, __FILE__, __LINE__); + memcpy((void *)(_buffer + thisLen), (void *)(same ? _buffer : chars), len + 1); + return *this; + } - String &append(const String &other) { - size_t len = other.length(); - size_t thisLen = _length; - _length = _length + len; - bool same = other._buffer == _buffer; - _buffer = SpineExtension::realloc(_buffer, _length + 1, __FILE__, __LINE__); - memcpy((void *) (_buffer + thisLen), (void *) (same ? _buffer : other._buffer), len + 1); - return *this; - } + String &append(const String &other) { + size_t len = other.length(); + size_t thisLen = _length; + _length = _length + len; + bool same = other._buffer == _buffer; + _buffer = SpineExtension::realloc(_buffer, _length + 1, __FILE__, __LINE__); + memcpy((void *)(_buffer + thisLen), (void *)(same ? _buffer : other._buffer), len + 1); + return *this; + } - String &append(int other) { - char str[100]; - sprintf(str, "%i", other); - append(str); - return *this; - } + String &append(int other) { + char str[100]; + sprintf(str, "%i", other); + append(str); + return *this; + } - String &append(float other) { - char str[100]; - sprintf(str, "%f", other); - append(str); - return *this; - } + String &append(float other) { + char str[100]; + sprintf(str, "%f", other); + append(str); + return *this; + } - friend bool operator==(const String &a, const String &b) { - if (a._buffer == b._buffer) return true; - if (a._length != b._length) return false; - if (a._buffer && b._buffer) { - return strcmp(a._buffer, b._buffer) == 0; - } else { - return false; - } - } + friend bool operator==(const String &a, const String &b) { + if (a._buffer == b._buffer) return true; + if (a._length != b._length) return false; + if (a._buffer && b._buffer) { + return strcmp(a._buffer, b._buffer) == 0; + } else { + return false; + } + } - friend bool operator!=(const String &a, const String &b) { - return !(a == b); - } + friend bool operator!=(const String &a, const String &b) { + return !(a == b); + } - ~String() { - if (_buffer) { - SpineExtension::free(_buffer, __FILE__, __LINE__); - } - } + ~String() { + if (_buffer) { + SpineExtension::free(_buffer, __FILE__, __LINE__); + } + } private: - mutable size_t _length; - mutable char *_buffer; + mutable size_t _length; + mutable char *_buffer; }; -} - +} // namespace spine #endif //SPINE_STRING_H diff --git a/native/cocos/editor-support/spine/TextureLoader.cpp b/native/cocos/editor-support/spine/TextureLoader.cpp index 4cffb3209e..9039834fbf 100644 --- a/native/cocos/editor-support/spine/TextureLoader.cpp +++ b/native/cocos/editor-support/spine/TextureLoader.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -39,4 +39,4 @@ TextureLoader::TextureLoader() { TextureLoader::~TextureLoader() { } -} +} // namespace spine diff --git a/native/cocos/editor-support/spine/TextureLoader.h b/native/cocos/editor-support/spine/TextureLoader.h index fa305a3285..0b54c333a0 100644 --- a/native/cocos/editor-support/spine/TextureLoader.h +++ b/native/cocos/editor-support/spine/TextureLoader.h @@ -34,18 +34,18 @@ #include namespace spine { - class AtlasPage; +class AtlasPage; - class SP_API TextureLoader : public SpineObject { - public: - TextureLoader(); +class SP_API TextureLoader : public SpineObject { +public: + TextureLoader(); - virtual ~TextureLoader(); + virtual ~TextureLoader(); - virtual void load(AtlasPage& page, const String& path) = 0; + virtual void load(AtlasPage& page, const String& path) = 0; - virtual void unload(void* texture) = 0; - }; -} + virtual void unload(void* texture) = 0; +}; +} // namespace spine #endif /* Spine_TextureLoader_h */ diff --git a/native/cocos/editor-support/spine/Timeline.cpp b/native/cocos/editor-support/spine/Timeline.cpp index 23bf723efc..eb89c5054f 100644 --- a/native/cocos/editor-support/spine/Timeline.cpp +++ b/native/cocos/editor-support/spine/Timeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -45,4 +45,4 @@ Timeline::Timeline() { Timeline::~Timeline() { } -} +} // namespace spine diff --git a/native/cocos/editor-support/spine/Timeline.h b/native/cocos/editor-support/spine/Timeline.h index cc98353e54..9b9257fb24 100644 --- a/native/cocos/editor-support/spine/Timeline.h +++ b/native/cocos/editor-support/spine/Timeline.h @@ -42,29 +42,29 @@ class Skeleton; class Event; class SP_API Timeline : public SpineObject { -RTTI_DECL + RTTI_DECL public: - Timeline(); + Timeline(); - virtual ~Timeline(); + virtual ~Timeline(); - /// Sets the value(s) for the specified time. - /// @param skeleton The skeleton the timeline is being applied to. This provides access to the bones, slots, and other skeleton components the timeline may change. - /// @param lastTime lastTime The time this timeline was last applied. Timelines such as EventTimeline trigger only at specific times rather than every frame. In that case, the timeline triggers everything between lastTime (exclusive) and time (inclusive). - /// @param time The time within the animation. Most timelines find the key before and the key after this time so they can interpolate between the keys. - /// @param pEvents If any events are fired, they are added to this array. Can be NULL to ignore firing events or if the timeline does not fire events. May be NULL. - /// @param alpha alpha 0 applies the current or setup pose value (depending on pose parameter). 1 applies the timeline - /// value. Between 0 and 1 applies a value between the current or setup pose and the timeline value. By adjusting alpha over - /// time, an animation can be mixed in or out. alpha can also be useful to apply animations on top of each other (layered). - /// @param blend Controls how mixing is applied when alpha is than 1. - /// @param direction Indicates whether the timeline is mixing in or out. Used by timelines which perform instant transitions such as DrawOrderTimeline and AttachmentTimeline. - virtual void - apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, MixBlend blend, - MixDirection direction) = 0; + /// Sets the value(s) for the specified time. + /// @param skeleton The skeleton the timeline is being applied to. This provides access to the bones, slots, and other skeleton components the timeline may change. + /// @param lastTime lastTime The time this timeline was last applied. Timelines such as EventTimeline trigger only at specific times rather than every frame. In that case, the timeline triggers everything between lastTime (exclusive) and time (inclusive). + /// @param time The time within the animation. Most timelines find the key before and the key after this time so they can interpolate between the keys. + /// @param pEvents If any events are fired, they are added to this array. Can be NULL to ignore firing events or if the timeline does not fire events. May be NULL. + /// @param alpha alpha 0 applies the current or setup pose value (depending on pose parameter). 1 applies the timeline + /// value. Between 0 and 1 applies a value between the current or setup pose and the timeline value. By adjusting alpha over + /// time, an animation can be mixed in or out. alpha can also be useful to apply animations on top of each other (layered). + /// @param blend Controls how mixing is applied when alpha is than 1. + /// @param direction Indicates whether the timeline is mixing in or out. Used by timelines which perform instant transitions such as DrawOrderTimeline and AttachmentTimeline. + virtual void + apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, MixBlend blend, + MixDirection direction) = 0; - virtual int getPropertyId() = 0; + virtual int getPropertyId() = 0; }; -} +} // namespace spine #endif /* Spine_Timeline_h */ diff --git a/native/cocos/editor-support/spine/TimelineType.h b/native/cocos/editor-support/spine/TimelineType.h index b1f07811ed..a86c0fa094 100644 --- a/native/cocos/editor-support/spine/TimelineType.h +++ b/native/cocos/editor-support/spine/TimelineType.h @@ -32,21 +32,21 @@ namespace spine { enum TimelineType { - TimelineType_Rotate = 0, - TimelineType_Translate, - TimelineType_Scale, - TimelineType_Shear, - TimelineType_Attachment, - TimelineType_Color, - TimelineType_Deform, - TimelineType_Event, - TimelineType_DrawOrder, - TimelineType_IkConstraint, - TimelineType_TransformConstraint, - TimelineType_PathConstraintPosition, - TimelineType_PathConstraintSpacing, - TimelineType_PathConstraintMix, - TimelineType_TwoColor + TimelineType_Rotate = 0, + TimelineType_Translate, + TimelineType_Scale, + TimelineType_Shear, + TimelineType_Attachment, + TimelineType_Color, + TimelineType_Deform, + TimelineType_Event, + TimelineType_DrawOrder, + TimelineType_IkConstraint, + TimelineType_TransformConstraint, + TimelineType_PathConstraintPosition, + TimelineType_PathConstraintSpacing, + TimelineType_PathConstraintMix, + TimelineType_TwoColor }; } diff --git a/native/cocos/editor-support/spine/TransformConstraint.cpp b/native/cocos/editor-support/spine/TransformConstraint.cpp index c2ac1b5ab3..a36619da6c 100644 --- a/native/cocos/editor-support/spine/TransformConstraint.cpp +++ b/native/cocos/editor-support/spine/TransformConstraint.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -44,312 +44,311 @@ using namespace spine; RTTI_IMPL(TransformConstraint, Updatable) TransformConstraint::TransformConstraint(TransformConstraintData &data, Skeleton &skeleton) : Updatable(), - _data(data), - _target(skeleton.findBone( - data.getTarget()->getName())), - _rotateMix( - data.getRotateMix()), - _translateMix( - data.getTranslateMix()), - _scaleMix( - data.getScaleMix()), - _shearMix( - data.getShearMix()), - _active(false) -{ - _bones.ensureCapacity(_data.getBones().size()); - for (size_t i = 0; i < _data.getBones().size(); ++i) { - BoneData *boneData = _data.getBones()[i]; - _bones.add(skeleton.findBone(boneData->getName())); - } + _data(data), + _target(skeleton.findBone( + data.getTarget()->getName())), + _rotateMix( + data.getRotateMix()), + _translateMix( + data.getTranslateMix()), + _scaleMix( + data.getScaleMix()), + _shearMix( + data.getShearMix()), + _active(false) { + _bones.ensureCapacity(_data.getBones().size()); + for (size_t i = 0; i < _data.getBones().size(); ++i) { + BoneData *boneData = _data.getBones()[i]; + _bones.add(skeleton.findBone(boneData->getName())); + } } void TransformConstraint::apply() { - update(); + update(); } void TransformConstraint::update() { - if (_data.isLocal()) { - if (_data.isRelative()) - applyRelativeLocal(); - else - applyAbsoluteLocal(); - } else { - if (_data.isRelative()) - applyRelativeWorld(); - else - applyAbsoluteWorld(); - } + if (_data.isLocal()) { + if (_data.isRelative()) + applyRelativeLocal(); + else + applyAbsoluteLocal(); + } else { + if (_data.isRelative()) + applyRelativeWorld(); + else + applyAbsoluteWorld(); + } } int TransformConstraint::getOrder() { - return _data.getOrder(); + return _data.getOrder(); } TransformConstraintData &TransformConstraint::getData() { - return _data; + return _data; } Vector &TransformConstraint::getBones() { - return _bones; + return _bones; } Bone *TransformConstraint::getTarget() { - return _target; + return _target; } void TransformConstraint::setTarget(Bone *inValue) { - _target = inValue; + _target = inValue; } float TransformConstraint::getRotateMix() { - return _rotateMix; + return _rotateMix; } void TransformConstraint::setRotateMix(float inValue) { - _rotateMix = inValue; + _rotateMix = inValue; } float TransformConstraint::getTranslateMix() { - return _translateMix; + return _translateMix; } void TransformConstraint::setTranslateMix(float inValue) { - _translateMix = inValue; + _translateMix = inValue; } float TransformConstraint::getScaleMix() { - return _scaleMix; + return _scaleMix; } void TransformConstraint::setScaleMix(float inValue) { - _scaleMix = inValue; + _scaleMix = inValue; } float TransformConstraint::getShearMix() { - return _shearMix; + return _shearMix; } void TransformConstraint::setShearMix(float inValue) { - _shearMix = inValue; + _shearMix = inValue; } void TransformConstraint::applyAbsoluteWorld() { - float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; - Bone &target = *_target; - float ta = target._a, tb = target._b, tc = target._c, td = target._d; - float degRadReflect = ta * td - tb * tc > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; - float offsetRotation = _data._offsetRotation * degRadReflect, offsetShearY = _data._offsetShearY * degRadReflect; + float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; + Bone &target = *_target; + float ta = target._a, tb = target._b, tc = target._c, td = target._d; + float degRadReflect = ta * td - tb * tc > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; + float offsetRotation = _data._offsetRotation * degRadReflect, offsetShearY = _data._offsetShearY * degRadReflect; - for (size_t i = 0; i < _bones.size(); ++i) { - Bone *item = _bones[i]; - Bone &bone = *item; + for (size_t i = 0; i < _bones.size(); ++i) { + Bone *item = _bones[i]; + Bone &bone = *item; - bool modified = false; + bool modified = false; - if (rotateMix != 0) { - float a = bone._a, b = bone._b, c = bone._c, d = bone._d; - float r = MathUtil::atan2(tc, ta) - MathUtil::atan2(c, a) + offsetRotation; - if (r > MathUtil::Pi) - r -= MathUtil::Pi_2; - else if (r < -MathUtil::Pi) - r += MathUtil::Pi_2; + if (rotateMix != 0) { + float a = bone._a, b = bone._b, c = bone._c, d = bone._d; + float r = MathUtil::atan2(tc, ta) - MathUtil::atan2(c, a) + offsetRotation; + if (r > MathUtil::Pi) + r -= MathUtil::Pi_2; + else if (r < -MathUtil::Pi) + r += MathUtil::Pi_2; - r *= rotateMix; - float cos = MathUtil::cos(r), sin = MathUtil::sin(r); - bone._a = cos * a - sin * c; - bone._b = cos * b - sin * d; - bone._c = sin * a + cos * c; - bone._d = sin * b + cos * d; - modified = true; - } + r *= rotateMix; + float cos = MathUtil::cos(r), sin = MathUtil::sin(r); + bone._a = cos * a - sin * c; + bone._b = cos * b - sin * d; + bone._c = sin * a + cos * c; + bone._d = sin * b + cos * d; + modified = true; + } - if (translateMix != 0) { - float tx, ty; - target.localToWorld(_data._offsetX, _data._offsetY, tx, ty); - bone._worldX += (tx - bone._worldX) * translateMix; - bone._worldY += (ty - bone._worldY) * translateMix; - modified = true; - } + if (translateMix != 0) { + float tx, ty; + target.localToWorld(_data._offsetX, _data._offsetY, tx, ty); + bone._worldX += (tx - bone._worldX) * translateMix; + bone._worldY += (ty - bone._worldY) * translateMix; + modified = true; + } - if (scaleMix > 0) { - float s = MathUtil::sqrt(bone._a * bone._a + bone._c * bone._c); + if (scaleMix > 0) { + float s = MathUtil::sqrt(bone._a * bone._a + bone._c * bone._c); - if (s > 0.00001f) s = (s + (MathUtil::sqrt(ta * ta + tc * tc) - s + _data._offsetScaleX) * scaleMix) / s; - bone._a *= s; - bone._c *= s; - s = MathUtil::sqrt(bone._b * bone._b + bone._d * bone._d); + if (s > 0.00001f) s = (s + (MathUtil::sqrt(ta * ta + tc * tc) - s + _data._offsetScaleX) * scaleMix) / s; + bone._a *= s; + bone._c *= s; + s = MathUtil::sqrt(bone._b * bone._b + bone._d * bone._d); - if (s > 0.00001f) s = (s + (MathUtil::sqrt(tb * tb + td * td) - s + _data._offsetScaleY) * scaleMix) / s; - bone._b *= s; - bone._d *= s; - modified = true; - } + if (s > 0.00001f) s = (s + (MathUtil::sqrt(tb * tb + td * td) - s + _data._offsetScaleY) * scaleMix) / s; + bone._b *= s; + bone._d *= s; + modified = true; + } - if (shearMix > 0) { - float b = bone._b, d = bone._d; - float by = MathUtil::atan2(d, b); - float r = MathUtil::atan2(td, tb) - MathUtil::atan2(tc, ta) - (by - MathUtil::atan2(bone._c, bone._a)); - if (r > MathUtil::Pi) - r -= MathUtil::Pi_2; - else if (r < -MathUtil::Pi) - r += MathUtil::Pi_2; + if (shearMix > 0) { + float b = bone._b, d = bone._d; + float by = MathUtil::atan2(d, b); + float r = MathUtil::atan2(td, tb) - MathUtil::atan2(tc, ta) - (by - MathUtil::atan2(bone._c, bone._a)); + if (r > MathUtil::Pi) + r -= MathUtil::Pi_2; + else if (r < -MathUtil::Pi) + r += MathUtil::Pi_2; - r = by + (r + offsetShearY) * shearMix; - float s = MathUtil::sqrt(b * b + d * d); - bone._b = MathUtil::cos(r) * s; - bone._d = MathUtil::sin(r) * s; - modified = true; - } + r = by + (r + offsetShearY) * shearMix; + float s = MathUtil::sqrt(b * b + d * d); + bone._b = MathUtil::cos(r) * s; + bone._d = MathUtil::sin(r) * s; + modified = true; + } - if (modified) bone._appliedValid = false; - } + if (modified) bone._appliedValid = false; + } } void TransformConstraint::applyRelativeWorld() { - float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; - Bone &target = *_target; - float ta = target._a, tb = target._b, tc = target._c, td = target._d; - float degRadReflect = ta * td - tb * tc > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; - float offsetRotation = _data._offsetRotation * degRadReflect, offsetShearY = _data._offsetShearY * degRadReflect; - for (size_t i = 0; i < _bones.size(); ++i) { - Bone *item = _bones[i]; - Bone &bone = *item; + float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; + Bone &target = *_target; + float ta = target._a, tb = target._b, tc = target._c, td = target._d; + float degRadReflect = ta * td - tb * tc > 0 ? MathUtil::Deg_Rad : -MathUtil::Deg_Rad; + float offsetRotation = _data._offsetRotation * degRadReflect, offsetShearY = _data._offsetShearY * degRadReflect; + for (size_t i = 0; i < _bones.size(); ++i) { + Bone *item = _bones[i]; + Bone &bone = *item; - bool modified = false; + bool modified = false; - if (rotateMix != 0) { - float a = bone._a, b = bone._b, c = bone._c, d = bone._d; - float r = MathUtil::atan2(tc, ta) + offsetRotation; - if (r > MathUtil::Pi) - r -= MathUtil::Pi_2; - else if (r < -MathUtil::Pi) - r += MathUtil::Pi_2; + if (rotateMix != 0) { + float a = bone._a, b = bone._b, c = bone._c, d = bone._d; + float r = MathUtil::atan2(tc, ta) + offsetRotation; + if (r > MathUtil::Pi) + r -= MathUtil::Pi_2; + else if (r < -MathUtil::Pi) + r += MathUtil::Pi_2; - r *= rotateMix; - float cos = MathUtil::cos(r), sin = MathUtil::sin(r); - bone._a = cos * a - sin * c; - bone._b = cos * b - sin * d; - bone._c = sin * a + cos * c; - bone._d = sin * b + cos * d; - modified = true; - } + r *= rotateMix; + float cos = MathUtil::cos(r), sin = MathUtil::sin(r); + bone._a = cos * a - sin * c; + bone._b = cos * b - sin * d; + bone._c = sin * a + cos * c; + bone._d = sin * b + cos * d; + modified = true; + } - if (translateMix != 0) { - float tx, ty; - target.localToWorld(_data._offsetX, _data._offsetY, tx, ty); - bone._worldX += tx * translateMix; - bone._worldY += ty * translateMix; - modified = true; - } + if (translateMix != 0) { + float tx, ty; + target.localToWorld(_data._offsetX, _data._offsetY, tx, ty); + bone._worldX += tx * translateMix; + bone._worldY += ty * translateMix; + modified = true; + } - if (scaleMix > 0) { - float s = (MathUtil::sqrt(ta * ta + tc * tc) - 1 + _data._offsetScaleX) * scaleMix + 1; - bone._a *= s; - bone._c *= s; - s = (MathUtil::sqrt(tb * tb + td * td) - 1 + _data._offsetScaleY) * scaleMix + 1; - bone._b *= s; - bone._d *= s; - modified = true; - } + if (scaleMix > 0) { + float s = (MathUtil::sqrt(ta * ta + tc * tc) - 1 + _data._offsetScaleX) * scaleMix + 1; + bone._a *= s; + bone._c *= s; + s = (MathUtil::sqrt(tb * tb + td * td) - 1 + _data._offsetScaleY) * scaleMix + 1; + bone._b *= s; + bone._d *= s; + modified = true; + } - if (shearMix > 0) { - float r = MathUtil::atan2(td, tb) - MathUtil::atan2(tc, ta); - if (r > MathUtil::Pi) - r -= MathUtil::Pi_2; - else if (r < -MathUtil::Pi) - r += MathUtil::Pi_2; + if (shearMix > 0) { + float r = MathUtil::atan2(td, tb) - MathUtil::atan2(tc, ta); + if (r > MathUtil::Pi) + r -= MathUtil::Pi_2; + else if (r < -MathUtil::Pi) + r += MathUtil::Pi_2; - float b = bone._b, d = bone._d; - r = MathUtil::atan2(d, b) + (r - MathUtil::Pi / 2 + offsetShearY) * shearMix; - float s = MathUtil::sqrt(b * b + d * d); - bone._b = MathUtil::cos(r) * s; - bone._d = MathUtil::sin(r) * s; - modified = true; - } + float b = bone._b, d = bone._d; + r = MathUtil::atan2(d, b) + (r - MathUtil::Pi / 2 + offsetShearY) * shearMix; + float s = MathUtil::sqrt(b * b + d * d); + bone._b = MathUtil::cos(r) * s; + bone._d = MathUtil::sin(r) * s; + modified = true; + } - if (modified) bone._appliedValid = false; - } + if (modified) bone._appliedValid = false; + } } void TransformConstraint::applyAbsoluteLocal() { - float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; - Bone &target = *_target; - if (!target._appliedValid) target.updateAppliedTransform(); + float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; + Bone &target = *_target; + if (!target._appliedValid) target.updateAppliedTransform(); - for (size_t i = 0; i < _bones.size(); ++i) { - Bone *item = _bones[i]; - Bone &bone = *item; + for (size_t i = 0; i < _bones.size(); ++i) { + Bone *item = _bones[i]; + Bone &bone = *item; - if (!bone._appliedValid) bone.updateAppliedTransform(); + if (!bone._appliedValid) bone.updateAppliedTransform(); - float rotation = bone._arotation; - if (rotateMix != 0) { - float r = target._arotation - rotation + _data._offsetRotation; - r -= (16384 - (int) (16384.499999999996 - r / 360)) * 360; - rotation += r * rotateMix; - } + float rotation = bone._arotation; + if (rotateMix != 0) { + float r = target._arotation - rotation + _data._offsetRotation; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + rotation += r * rotateMix; + } - float x = bone._ax, y = bone._ay; - if (translateMix != 0) { - x += (target._ax - x + _data._offsetX) * translateMix; - y += (target._ay - y + _data._offsetY) * translateMix; - } + float x = bone._ax, y = bone._ay; + if (translateMix != 0) { + x += (target._ax - x + _data._offsetX) * translateMix; + y += (target._ay - y + _data._offsetY) * translateMix; + } - float scaleX = bone._ascaleX, scaleY = bone._ascaleY; - if (scaleMix != 0) { - if (scaleX > 0.00001f) scaleX = (scaleX + (target._ascaleX - scaleX + _data._offsetScaleX) * scaleMix) / scaleX; - if (scaleY > 0.00001f) scaleY = (scaleY + (target._ascaleY - scaleY + _data._offsetScaleY) * scaleMix) / scaleY; - } + float scaleX = bone._ascaleX, scaleY = bone._ascaleY; + if (scaleMix != 0) { + if (scaleX > 0.00001f) scaleX = (scaleX + (target._ascaleX - scaleX + _data._offsetScaleX) * scaleMix) / scaleX; + if (scaleY > 0.00001f) scaleY = (scaleY + (target._ascaleY - scaleY + _data._offsetScaleY) * scaleMix) / scaleY; + } - float shearY = bone._ashearY; - if (shearMix != 0) { - float r = target._ashearY - shearY + _data._offsetShearY; - r -= (16384 - (int) (16384.499999999996 - r / 360)) * 360; - bone._shearY += r * shearMix; - } + float shearY = bone._ashearY; + if (shearMix != 0) { + float r = target._ashearY - shearY + _data._offsetShearY; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + bone._shearY += r * shearMix; + } - bone.updateWorldTransform(x, y, rotation, scaleX, scaleY, bone._ashearX, shearY); - } + bone.updateWorldTransform(x, y, rotation, scaleX, scaleY, bone._ashearX, shearY); + } } void TransformConstraint::applyRelativeLocal() { - float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; - Bone &target = *_target; - if (!target._appliedValid) target.updateAppliedTransform(); + float rotateMix = _rotateMix, translateMix = _translateMix, scaleMix = _scaleMix, shearMix = _shearMix; + Bone &target = *_target; + if (!target._appliedValid) target.updateAppliedTransform(); - for (size_t i = 0; i < _bones.size(); ++i) { - Bone *item = _bones[i]; - Bone &bone = *item; + for (size_t i = 0; i < _bones.size(); ++i) { + Bone *item = _bones[i]; + Bone &bone = *item; - if (!bone._appliedValid) bone.updateAppliedTransform(); + if (!bone._appliedValid) bone.updateAppliedTransform(); - float rotation = bone._arotation; - if (rotateMix != 0) rotation += (target._arotation + _data._offsetRotation) * rotateMix; + float rotation = bone._arotation; + if (rotateMix != 0) rotation += (target._arotation + _data._offsetRotation) * rotateMix; - float x = bone._ax, y = bone._ay; - if (translateMix != 0) { - x += (target._ax + _data._offsetX) * translateMix; - y += (target._ay + _data._offsetY) * translateMix; - } + float x = bone._ax, y = bone._ay; + if (translateMix != 0) { + x += (target._ax + _data._offsetX) * translateMix; + y += (target._ay + _data._offsetY) * translateMix; + } - float scaleX = bone._ascaleX, scaleY = bone._ascaleY; - if (scaleMix != 0) { - if (scaleX > 0.00001f) scaleX *= ((target._ascaleX - 1 + _data._offsetScaleX) * scaleMix) + 1; - if (scaleY > 0.00001f) scaleY *= ((target._ascaleY - 1 + _data._offsetScaleY) * scaleMix) + 1; - } + float scaleX = bone._ascaleX, scaleY = bone._ascaleY; + if (scaleMix != 0) { + if (scaleX > 0.00001f) scaleX *= ((target._ascaleX - 1 + _data._offsetScaleX) * scaleMix) + 1; + if (scaleY > 0.00001f) scaleY *= ((target._ascaleY - 1 + _data._offsetScaleY) * scaleMix) + 1; + } - float shearY = bone._ashearY; - if (shearMix != 0) shearY += (target._ashearY + _data._offsetShearY) * shearMix; + float shearY = bone._ashearY; + if (shearMix != 0) shearY += (target._ashearY + _data._offsetShearY) * shearMix; - bone.updateWorldTransform(x, y, rotation, scaleX, scaleY, bone._ashearX, shearY); - } + bone.updateWorldTransform(x, y, rotation, scaleX, scaleY, bone._ashearX, shearY); + } } bool TransformConstraint::isActive() { - return _active; + return _active; } void TransformConstraint::setActive(bool inValue) { - _active = inValue; + _active = inValue; } diff --git a/native/cocos/editor-support/spine/TransformConstraint.h b/native/cocos/editor-support/spine/TransformConstraint.h index e271e5cfb6..625dc8ea1f 100644 --- a/native/cocos/editor-support/spine/TransformConstraint.h +++ b/native/cocos/editor-support/spine/TransformConstraint.h @@ -35,63 +35,63 @@ #include namespace spine { - class TransformConstraintData; - class Skeleton; - class Bone; +class TransformConstraintData; +class Skeleton; +class Bone; - class SP_API TransformConstraint : public Updatable { - friend class Skeleton; - friend class TransformConstraintTimeline; +class SP_API TransformConstraint : public Updatable { + friend class Skeleton; + friend class TransformConstraintTimeline; - RTTI_DECL + RTTI_DECL - public: - TransformConstraint(TransformConstraintData& data, Skeleton& skeleton); +public: + TransformConstraint(TransformConstraintData& data, Skeleton& skeleton); - void apply(); + void apply(); - virtual void update(); + virtual void update(); - virtual int getOrder(); + virtual int getOrder(); - TransformConstraintData& getData(); + TransformConstraintData& getData(); - Vector& getBones(); + Vector& getBones(); - Bone* getTarget(); - void setTarget(Bone* inValue); + Bone* getTarget(); + void setTarget(Bone* inValue); - float getRotateMix(); - void setRotateMix(float inValue); + float getRotateMix(); + void setRotateMix(float inValue); - float getTranslateMix(); - void setTranslateMix(float inValue); + float getTranslateMix(); + void setTranslateMix(float inValue); - float getScaleMix(); - void setScaleMix(float inValue); + float getScaleMix(); + void setScaleMix(float inValue); - float getShearMix(); - void setShearMix(float inValue); + float getShearMix(); + void setShearMix(float inValue); - bool isActive(); + bool isActive(); - void setActive(bool inValue); + void setActive(bool inValue); - private: - TransformConstraintData& _data; - Vector _bones; - Bone* _target; - float _rotateMix, _translateMix, _scaleMix, _shearMix; - bool _active; +private: + TransformConstraintData& _data; + Vector _bones; + Bone* _target; + float _rotateMix, _translateMix, _scaleMix, _shearMix; + bool _active; - void applyAbsoluteWorld(); + void applyAbsoluteWorld(); - void applyRelativeWorld(); + void applyRelativeWorld(); - void applyAbsoluteLocal(); + void applyAbsoluteLocal(); - void applyRelativeLocal(); - }; -} + void applyRelativeLocal(); +}; +} // namespace spine #endif /* Spine_TransformConstraint_h */ diff --git a/native/cocos/editor-support/spine/TransformConstraintData.cpp b/native/cocos/editor-support/spine/TransformConstraintData.cpp index 52cf4540dc..5da407b2b9 100644 --- a/native/cocos/editor-support/spine/TransformConstraintData.cpp +++ b/native/cocos/editor-support/spine/TransformConstraintData.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -38,75 +38,74 @@ #include using namespace spine; -TransformConstraintData::TransformConstraintData(const String &name) : - ConstraintData(name), - _target(NULL), - _rotateMix(0), - _translateMix(0), - _scaleMix(0), - _shearMix(0), - _offsetRotation(0), - _offsetX(0), - _offsetY(0), - _offsetScaleX(0), - _offsetScaleY(0), - _offsetShearY(0), - _relative(false), - _local(false) { +TransformConstraintData::TransformConstraintData(const String &name) : ConstraintData(name), + _target(NULL), + _rotateMix(0), + _translateMix(0), + _scaleMix(0), + _shearMix(0), + _offsetRotation(0), + _offsetX(0), + _offsetY(0), + _offsetScaleX(0), + _offsetScaleY(0), + _offsetShearY(0), + _relative(false), + _local(false) { } Vector &TransformConstraintData::getBones() { - return _bones; + return _bones; } BoneData *TransformConstraintData::getTarget() { - return _target; + return _target; } float TransformConstraintData::getRotateMix() { - return _rotateMix; + return _rotateMix; } float TransformConstraintData::getTranslateMix() { - return _translateMix; + return _translateMix; } float TransformConstraintData::getScaleMix() { - return _scaleMix; + return _scaleMix; } float TransformConstraintData::getShearMix() { - return _shearMix; + return _shearMix; } float TransformConstraintData::getOffsetRotation() { - return _offsetRotation; + return _offsetRotation; } float TransformConstraintData::getOffsetX() { - return _offsetX; + return _offsetX; } float TransformConstraintData::getOffsetY() { - return _offsetY; + return _offsetY; } float TransformConstraintData::getOffsetScaleX() { - return _offsetScaleX; + return _offsetScaleX; } float TransformConstraintData::getOffsetScaleY() { - return _offsetScaleY; + return _offsetScaleY; } float TransformConstraintData::getOffsetShearY() { - return _offsetShearY; + return _offsetShearY; } bool TransformConstraintData::isRelative() { - return _relative; + return _relative; } bool TransformConstraintData::isLocal() { - return _local; + return _local; } diff --git a/native/cocos/editor-support/spine/TransformConstraintData.h b/native/cocos/editor-support/spine/TransformConstraintData.h index 783eaacc17..e6df0a5018 100644 --- a/native/cocos/editor-support/spine/TransformConstraintData.h +++ b/native/cocos/editor-support/spine/TransformConstraintData.h @@ -36,43 +36,43 @@ #include namespace spine { - class BoneData; +class BoneData; - class SP_API TransformConstraintData : public ConstraintData { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API TransformConstraintData : public ConstraintData { + friend class SkeletonBinary; + friend class SkeletonJson; - friend class TransformConstraint; - friend class Skeleton; - friend class TransformConstraintTimeline; + friend class TransformConstraint; + friend class Skeleton; + friend class TransformConstraintTimeline; - public: - explicit TransformConstraintData(const String& name); +public: + explicit TransformConstraintData(const String& name); - Vector& getBones(); - BoneData* getTarget(); - float getRotateMix(); - float getTranslateMix(); - float getScaleMix(); - float getShearMix(); + Vector& getBones(); + BoneData* getTarget(); + float getRotateMix(); + float getTranslateMix(); + float getScaleMix(); + float getShearMix(); - float getOffsetRotation(); - float getOffsetX(); - float getOffsetY(); - float getOffsetScaleX(); - float getOffsetScaleY(); - float getOffsetShearY(); + float getOffsetRotation(); + float getOffsetX(); + float getOffsetY(); + float getOffsetScaleX(); + float getOffsetScaleY(); + float getOffsetShearY(); - bool isRelative(); - bool isLocal(); + bool isRelative(); + bool isLocal(); - private: - Vector _bones; - BoneData* _target; - float _rotateMix, _translateMix, _scaleMix, _shearMix; - float _offsetRotation, _offsetX, _offsetY, _offsetScaleX, _offsetScaleY, _offsetShearY; - bool _relative, _local; - }; -} +private: + Vector _bones; + BoneData* _target; + float _rotateMix, _translateMix, _scaleMix, _shearMix; + float _offsetRotation, _offsetX, _offsetY, _offsetScaleX, _offsetScaleY, _offsetShearY; + bool _relative, _local; +}; +} // namespace spine #endif /* Spine_TransformConstraintData_h */ diff --git a/native/cocos/editor-support/spine/TransformConstraintTimeline.cpp b/native/cocos/editor-support/spine/TransformConstraintTimeline.cpp index 2da77e8b40..813cdef731 100644 --- a/native/cocos/editor-support/spine/TransformConstraintTimeline.cpp +++ b/native/cocos/editor-support/spine/TransformConstraintTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -59,90 +59,88 @@ const int TransformConstraintTimeline::SCALE = 3; const int TransformConstraintTimeline::SHEAR = 4; TransformConstraintTimeline::TransformConstraintTimeline(int frameCount) : CurveTimeline(frameCount), - _transformConstraintIndex(0) -{ - _frames.setSize(frameCount * ENTRIES, 0); + _transformConstraintIndex(0) { + _frames.setSize(frameCount * ENTRIES, 0); } void TransformConstraintTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, - float alpha, MixBlend blend, MixDirection direction) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + float alpha, MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - TransformConstraint *constraintP = skeleton._transformConstraints[_transformConstraintIndex]; - TransformConstraint &constraint = *constraintP; - if (!constraint.isActive()) return; + TransformConstraint *constraintP = skeleton._transformConstraints[_transformConstraintIndex]; + TransformConstraint &constraint = *constraintP; + if (!constraint.isActive()) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - constraint._rotateMix = constraint._data._rotateMix; - constraint._translateMix = constraint._data._translateMix; - constraint._scaleMix = constraint._data._scaleMix; - constraint._shearMix = constraint._data._shearMix; - return; - case MixBlend_First: - constraint._rotateMix += (constraint._data._rotateMix - constraint._rotateMix) * alpha; - constraint._translateMix += (constraint._data._translateMix - constraint._translateMix) * alpha; - constraint._scaleMix += (constraint._data._scaleMix - constraint._scaleMix) * alpha; - constraint._shearMix += (constraint._data._shearMix - constraint._shearMix) * alpha; - return; - default: - return; - } - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + constraint._rotateMix = constraint._data._rotateMix; + constraint._translateMix = constraint._data._translateMix; + constraint._scaleMix = constraint._data._scaleMix; + constraint._shearMix = constraint._data._shearMix; + return; + case MixBlend_First: + constraint._rotateMix += (constraint._data._rotateMix - constraint._rotateMix) * alpha; + constraint._translateMix += (constraint._data._translateMix - constraint._translateMix) * alpha; + constraint._scaleMix += (constraint._data._scaleMix - constraint._scaleMix) * alpha; + constraint._shearMix += (constraint._data._shearMix - constraint._shearMix) * alpha; + return; + default: + return; + } + } - float rotate, translate, scale, shear; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - size_t i = _frames.size(); - rotate = _frames[i + PREV_ROTATE]; - translate = _frames[i + PREV_TRANSLATE]; - scale = _frames[i + PREV_SCALE]; - shear = _frames[i + PREV_SHEAR]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - rotate = _frames[frame + PREV_ROTATE]; - translate = _frames[frame + PREV_TRANSLATE]; - scale = _frames[frame + PREV_SCALE]; - shear = _frames[frame + PREV_SHEAR]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float rotate, translate, scale, shear; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + size_t i = _frames.size(); + rotate = _frames[i + PREV_ROTATE]; + translate = _frames[i + PREV_TRANSLATE]; + scale = _frames[i + PREV_SCALE]; + shear = _frames[i + PREV_SHEAR]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + rotate = _frames[frame + PREV_ROTATE]; + translate = _frames[frame + PREV_TRANSLATE]; + scale = _frames[frame + PREV_SCALE]; + shear = _frames[frame + PREV_SHEAR]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - rotate += (_frames[frame + ROTATE] - rotate) * percent; - translate += (_frames[frame + TRANSLATE] - translate) * percent; - scale += (_frames[frame + SCALE] - scale) * percent; - shear += (_frames[frame + SHEAR] - shear) * percent; - } + rotate += (_frames[frame + ROTATE] - rotate) * percent; + translate += (_frames[frame + TRANSLATE] - translate) * percent; + scale += (_frames[frame + SCALE] - scale) * percent; + shear += (_frames[frame + SHEAR] - shear) * percent; + } - if (blend == MixBlend_Setup) { - TransformConstraintData &data = constraint._data; - constraint._rotateMix = data._rotateMix + (rotate - data._rotateMix) * alpha; - constraint._translateMix = data._translateMix + (translate - data._translateMix) * alpha; - constraint._scaleMix = data._scaleMix + (scale - data._scaleMix) * alpha; - constraint._shearMix = data._shearMix + (shear - data._shearMix) * alpha; - } else { - constraint._rotateMix += (rotate - constraint._rotateMix) * alpha; - constraint._translateMix += (translate - constraint._translateMix) * alpha; - constraint._scaleMix += (scale - constraint._scaleMix) * alpha; - constraint._shearMix += (shear - constraint._shearMix) * alpha; - } + if (blend == MixBlend_Setup) { + TransformConstraintData &data = constraint._data; + constraint._rotateMix = data._rotateMix + (rotate - data._rotateMix) * alpha; + constraint._translateMix = data._translateMix + (translate - data._translateMix) * alpha; + constraint._scaleMix = data._scaleMix + (scale - data._scaleMix) * alpha; + constraint._shearMix = data._shearMix + (shear - data._shearMix) * alpha; + } else { + constraint._rotateMix += (rotate - constraint._rotateMix) * alpha; + constraint._translateMix += (translate - constraint._translateMix) * alpha; + constraint._scaleMix += (scale - constraint._scaleMix) * alpha; + constraint._shearMix += (shear - constraint._shearMix) * alpha; + } } int TransformConstraintTimeline::getPropertyId() { - return ((int) TimelineType_TransformConstraint << 24) + _transformConstraintIndex; + return ((int)TimelineType_TransformConstraint << 24) + _transformConstraintIndex; } void TransformConstraintTimeline::setFrame(size_t frameIndex, float time, float rotateMix, float translateMix, float scaleMix, - float shearMix -) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + ROTATE] = rotateMix; - _frames[frameIndex + TRANSLATE] = translateMix; - _frames[frameIndex + SCALE] = scaleMix; - _frames[frameIndex + SHEAR] = shearMix; + float shearMix) { + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + ROTATE] = rotateMix; + _frames[frameIndex + TRANSLATE] = translateMix; + _frames[frameIndex + SCALE] = scaleMix; + _frames[frameIndex + SHEAR] = shearMix; } diff --git a/native/cocos/editor-support/spine/TransformConstraintTimeline.h b/native/cocos/editor-support/spine/TransformConstraintTimeline.h index 3173238229..5e3047afc9 100644 --- a/native/cocos/editor-support/spine/TransformConstraintTimeline.h +++ b/native/cocos/editor-support/spine/TransformConstraintTimeline.h @@ -34,37 +34,37 @@ namespace spine { - class SP_API TransformConstraintTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API TransformConstraintTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit TransformConstraintTimeline(int frameCount); + explicit TransformConstraintTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - void setFrame(size_t frameIndex, float time, float rotateMix, float translateMix, float scaleMix, float shearMix); + void setFrame(size_t frameIndex, float time, float rotateMix, float translateMix, float scaleMix, float shearMix); - private: - static const int PREV_TIME; - static const int PREV_ROTATE; - static const int PREV_TRANSLATE; - static const int PREV_SCALE; - static const int PREV_SHEAR; - static const int ROTATE; - static const int TRANSLATE; - static const int SCALE; - static const int SHEAR; +private: + static const int PREV_TIME; + static const int PREV_ROTATE; + static const int PREV_TRANSLATE; + static const int PREV_SCALE; + static const int PREV_SHEAR; + static const int ROTATE; + static const int TRANSLATE; + static const int SCALE; + static const int SHEAR; - Vector _frames; - int _transformConstraintIndex; - }; -} + Vector _frames; + int _transformConstraintIndex; +}; +} // namespace spine #endif /* Spine_TransformConstraintTimeline_h */ diff --git a/native/cocos/editor-support/spine/TransformMode.h b/native/cocos/editor-support/spine/TransformMode.h index c4da701d71..c827b4ec4d 100644 --- a/native/cocos/editor-support/spine/TransformMode.h +++ b/native/cocos/editor-support/spine/TransformMode.h @@ -31,13 +31,13 @@ #define Spine_TransformMode_h namespace spine { - enum TransformMode { - TransformMode_Normal = 0, - TransformMode_OnlyTranslation, - TransformMode_NoRotationOrReflection, - TransformMode_NoScale, - TransformMode_NoScaleOrReflection - }; +enum TransformMode { + TransformMode_Normal = 0, + TransformMode_OnlyTranslation, + TransformMode_NoRotationOrReflection, + TransformMode_NoScale, + TransformMode_NoScaleOrReflection +}; } #endif /* Spine_TransformMode_h */ diff --git a/native/cocos/editor-support/spine/TranslateTimeline.cpp b/native/cocos/editor-support/spine/TranslateTimeline.cpp index 09f9b065fd..f46d2834a5 100644 --- a/native/cocos/editor-support/spine/TranslateTimeline.cpp +++ b/native/cocos/editor-support/spine/TranslateTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -53,79 +53,79 @@ const int TranslateTimeline::X = 1; const int TranslateTimeline::Y = 2; TranslateTimeline::TranslateTimeline(int frameCount) : CurveTimeline(frameCount), _boneIndex(0) { - _frames.ensureCapacity(frameCount * ENTRIES); - _frames.setSize(frameCount * ENTRIES, 0); + _frames.ensureCapacity(frameCount * ENTRIES); + _frames.setSize(frameCount * ENTRIES, 0); } TranslateTimeline::~TranslateTimeline() { } void TranslateTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Bone *boneP = skeleton._bones[_boneIndex]; - Bone &bone = *boneP; - if (!bone._active) return; + Bone *boneP = skeleton._bones[_boneIndex]; + Bone &bone = *boneP; + if (!bone._active) return; - if (time < _frames[0]) { - switch (blend) { - case MixBlend_Setup: - bone._x = bone._data._x; - bone._y = bone._data._y; - return; - case MixBlend_First: - bone._x += (bone._data._x - bone._x) * alpha; - bone._y += (bone._data._y - bone._y) * alpha; - default: {} - } - return; - } + if (time < _frames[0]) { + switch (blend) { + case MixBlend_Setup: + bone._x = bone._data._x; + bone._y = bone._data._y; + return; + case MixBlend_First: + bone._x += (bone._data._x - bone._x) * alpha; + bone._y += (bone._data._y - bone._y) * alpha; + default: { + } + } + return; + } - float x, y; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - x = _frames[_frames.size() + PREV_X]; - y = _frames[_frames.size() + PREV_Y]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(_frames, time, ENTRIES); - x = _frames[frame + PREV_X]; - y = _frames[frame + PREV_Y]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float x, y; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + x = _frames[_frames.size() + PREV_X]; + y = _frames[_frames.size() + PREV_Y]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(_frames, time, ENTRIES); + x = _frames[frame + PREV_X]; + y = _frames[frame + PREV_Y]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - x += (_frames[frame + X] - x) * percent; - y += (_frames[frame + Y] - y) * percent; - } + x += (_frames[frame + X] - x) * percent; + y += (_frames[frame + Y] - y) * percent; + } - switch (blend) { - case MixBlend_Setup: - bone._x = bone._data._x + x * alpha; - bone._y = bone._data._y + y * alpha; - break; - case MixBlend_First: - case MixBlend_Replace: - bone._x += (bone._data._x + x - bone._x) * alpha; - bone._y += (bone._data._y + y - bone._y) * alpha; - break; - case MixBlend_Add: - bone._x += x * alpha; - bone._y += y * alpha; - } + switch (blend) { + case MixBlend_Setup: + bone._x = bone._data._x + x * alpha; + bone._y = bone._data._y + y * alpha; + break; + case MixBlend_First: + case MixBlend_Replace: + bone._x += (bone._data._x + x - bone._x) * alpha; + bone._y += (bone._data._y + y - bone._y) * alpha; + break; + case MixBlend_Add: + bone._x += x * alpha; + bone._y += y * alpha; + } } int TranslateTimeline::getPropertyId() { - return ((int) TimelineType_Translate << 24) + _boneIndex; + return ((int)TimelineType_Translate << 24) + _boneIndex; } void TranslateTimeline::setFrame(int frameIndex, float time, float x, float y) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + X] = x; - _frames[frameIndex + Y] = y; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + X] = x; + _frames[frameIndex + Y] = y; } diff --git a/native/cocos/editor-support/spine/TranslateTimeline.h b/native/cocos/editor-support/spine/TranslateTimeline.h index 88f1dfb5b4..68b8102291 100644 --- a/native/cocos/editor-support/spine/TranslateTimeline.h +++ b/native/cocos/editor-support/spine/TranslateTimeline.h @@ -37,36 +37,36 @@ namespace spine { - class SP_API TranslateTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API TranslateTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit TranslateTimeline(int frameCount); + explicit TranslateTimeline(int frameCount); - virtual ~TranslateTimeline(); + virtual ~TranslateTimeline(); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, float x, float y); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, float x, float y); - protected: - static const int PREV_TIME; - static const int PREV_X; - static const int PREV_Y; - static const int X; - static const int Y; +protected: + static const int PREV_TIME; + static const int PREV_X; + static const int PREV_Y; + static const int X; + static const int Y; - Vector _frames; - int _boneIndex; - }; -} + Vector _frames; + int _boneIndex; +}; +} // namespace spine #endif /* Spine_TranslateTimeline_h */ diff --git a/native/cocos/editor-support/spine/Triangulator.cpp b/native/cocos/editor-support/spine/Triangulator.cpp index 3c5602531d..291f73196f 100644 --- a/native/cocos/editor-support/spine/Triangulator.cpp +++ b/native/cocos/editor-support/spine/Triangulator.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -38,252 +38,252 @@ using namespace spine; Triangulator::~Triangulator() { - ContainerUtil::cleanUpVectorOfPointers(_convexPolygons); - ContainerUtil::cleanUpVectorOfPointers(_convexPolygonsIndices); + ContainerUtil::cleanUpVectorOfPointers(_convexPolygons); + ContainerUtil::cleanUpVectorOfPointers(_convexPolygonsIndices); } Vector &Triangulator::triangulate(Vector &vertices) { - size_t vertexCount = vertices.size() >> 1; + size_t vertexCount = vertices.size() >> 1; - Vector &indices = _indices; - indices.clear(); - indices.ensureCapacity(vertexCount); - indices.setSize(vertexCount, 0); - for (size_t i = 0; i < vertexCount; ++i) { - indices[i] = i; - } + Vector &indices = _indices; + indices.clear(); + indices.ensureCapacity(vertexCount); + indices.setSize(vertexCount, 0); + for (size_t i = 0; i < vertexCount; ++i) { + indices[i] = i; + } - Vector &isConcaveArray = _isConcaveArray; - isConcaveArray.ensureCapacity(vertexCount); - isConcaveArray.setSize(vertexCount, 0); - for (size_t i = 0, n = vertexCount; i < n; ++i) { - isConcaveArray[i] = isConcave(i, vertexCount, vertices, indices); - } + Vector &isConcaveArray = _isConcaveArray; + isConcaveArray.ensureCapacity(vertexCount); + isConcaveArray.setSize(vertexCount, 0); + for (size_t i = 0, n = vertexCount; i < n; ++i) { + isConcaveArray[i] = isConcave(i, vertexCount, vertices, indices); + } - Vector &triangles = _triangles; - triangles.clear(); - triangles.ensureCapacity(MathUtil::max((int)0, (int)vertexCount - 2) << 2); + Vector &triangles = _triangles; + triangles.clear(); + triangles.ensureCapacity(MathUtil::max((int)0, (int)vertexCount - 2) << 2); - while (vertexCount > 3) { - // Find ear tip. - size_t previous = vertexCount - 1, i = 0, next = 1; + while (vertexCount > 3) { + // Find ear tip. + size_t previous = vertexCount - 1, i = 0, next = 1; - // outer: - while (true) { - if (!isConcaveArray[i]) { - int p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; - float p1x = vertices[p1], p1y = vertices[p1 + 1]; - float p2x = vertices[p2], p2y = vertices[p2 + 1]; - float p3x = vertices[p3], p3y = vertices[p3 + 1]; - for (size_t ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { - if (!isConcaveArray[ii]) continue; + // outer: + while (true) { + if (!isConcaveArray[i]) { + int p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; + float p1x = vertices[p1], p1y = vertices[p1 + 1]; + float p2x = vertices[p2], p2y = vertices[p2 + 1]; + float p3x = vertices[p3], p3y = vertices[p3 + 1]; + for (size_t ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { + if (!isConcaveArray[ii]) continue; - int v = indices[ii] << 1; - float &vx = vertices[v], vy = vertices[v + 1]; - if (positiveArea(p3x, p3y, p1x, p1y, vx, vy)) { - if (positiveArea(p1x, p1y, p2x, p2y, vx, vy)) { - if (positiveArea(p2x, p2y, p3x, p3y, vx, vy)) { - goto break_outer; // break outer; - } - } - } - } - break; - } - break_outer: + int v = indices[ii] << 1; + float &vx = vertices[v], vy = vertices[v + 1]; + if (positiveArea(p3x, p3y, p1x, p1y, vx, vy)) { + if (positiveArea(p1x, p1y, p2x, p2y, vx, vy)) { + if (positiveArea(p2x, p2y, p3x, p3y, vx, vy)) { + goto break_outer; // break outer; + } + } + } + } + break; + } + break_outer: - if (next == 0) { - do { - if (!isConcaveArray[i]) break; - i--; - } while (i > 0); - break; - } + if (next == 0) { + do { + if (!isConcaveArray[i]) break; + i--; + } while (i > 0); + break; + } - previous = i; - i = next; - next = (next + 1) % vertexCount; - } + previous = i; + i = next; + next = (next + 1) % vertexCount; + } - // Cut ear tip. - triangles.add(indices[(vertexCount + i - 1) % vertexCount]); - triangles.add(indices[i]); - triangles.add(indices[(i + 1) % vertexCount]); - indices.removeAt(i); - isConcaveArray.removeAt(i); - vertexCount--; + // Cut ear tip. + triangles.add(indices[(vertexCount + i - 1) % vertexCount]); + triangles.add(indices[i]); + triangles.add(indices[(i + 1) % vertexCount]); + indices.removeAt(i); + isConcaveArray.removeAt(i); + vertexCount--; - int previousIndex = (vertexCount + i - 1) % vertexCount; - int nextIndex = i == vertexCount ? 0 : i; - isConcaveArray[previousIndex] = isConcave(previousIndex, vertexCount, vertices, indices); - isConcaveArray[nextIndex] = isConcave(nextIndex, vertexCount, vertices, indices); - } + int previousIndex = (vertexCount + i - 1) % vertexCount; + int nextIndex = i == vertexCount ? 0 : i; + isConcaveArray[previousIndex] = isConcave(previousIndex, vertexCount, vertices, indices); + isConcaveArray[nextIndex] = isConcave(nextIndex, vertexCount, vertices, indices); + } - if (vertexCount == 3) { - triangles.add(indices[2]); - triangles.add(indices[0]); - triangles.add(indices[1]); - } + if (vertexCount == 3) { + triangles.add(indices[2]); + triangles.add(indices[0]); + triangles.add(indices[1]); + } - return triangles; + return triangles; } Vector *> &Triangulator::decompose(Vector &vertices, Vector &triangles) { - Vector *> &convexPolygons = _convexPolygons; - for (size_t i = 0, n = convexPolygons.size(); i < n; ++i) - _polygonPool.free(convexPolygons[i]); - convexPolygons.clear(); + Vector *> &convexPolygons = _convexPolygons; + for (size_t i = 0, n = convexPolygons.size(); i < n; ++i) + _polygonPool.free(convexPolygons[i]); + convexPolygons.clear(); - Vector *> &convexPolygonsIndices = _convexPolygonsIndices; - for (size_t i = 0, n = convexPolygonsIndices.size(); i < n; ++i) - _polygonIndicesPool.free(convexPolygonsIndices[i]); - convexPolygonsIndices.clear(); + Vector *> &convexPolygonsIndices = _convexPolygonsIndices; + for (size_t i = 0, n = convexPolygonsIndices.size(); i < n; ++i) + _polygonIndicesPool.free(convexPolygonsIndices[i]); + convexPolygonsIndices.clear(); - Vector *polygonIndices = _polygonIndicesPool.obtain(); - polygonIndices->clear(); + Vector *polygonIndices = _polygonIndicesPool.obtain(); + polygonIndices->clear(); - Vector *polygon = _polygonPool.obtain(); - polygon->clear(); + Vector *polygon = _polygonPool.obtain(); + polygon->clear(); - // Merge subsequent triangles if they form a triangle fan. - int fanBaseIndex = -1, lastwinding = 0; - for (size_t i = 0, n = triangles.size(); i < n; i += 3) { - int t1 = triangles[i] << 1, t2 = triangles[i + 1] << 1, t3 = triangles[i + 2] << 1; - float x1 = vertices[t1], y1 = vertices[t1 + 1]; - float x2 = vertices[t2], y2 = vertices[t2 + 1]; - float x3 = vertices[t3], y3 = vertices[t3 + 1]; + // Merge subsequent triangles if they form a triangle fan. + int fanBaseIndex = -1, lastwinding = 0; + for (size_t i = 0, n = triangles.size(); i < n; i += 3) { + int t1 = triangles[i] << 1, t2 = triangles[i + 1] << 1, t3 = triangles[i + 2] << 1; + float x1 = vertices[t1], y1 = vertices[t1 + 1]; + float x2 = vertices[t2], y2 = vertices[t2 + 1]; + float x3 = vertices[t3], y3 = vertices[t3 + 1]; - // If the base of the last triangle is the same as this triangle, check if they form a convex polygon (triangle fan). - bool merged = false; - if (fanBaseIndex == t1) { - size_t o = polygon->size() - 4; - Vector &p = *polygon; - int winding1 = winding(p[o], p[o + 1], p[o + 2], p[o + 3], x3, y3); - int winding2 = winding(x3, y3, p[0], p[1], p[2], p[3]); - if (winding1 == lastwinding && winding2 == lastwinding) { - polygon->add(x3); - polygon->add(y3); - polygonIndices->add(t3); - merged = true; - } - } + // If the base of the last triangle is the same as this triangle, check if they form a convex polygon (triangle fan). + bool merged = false; + if (fanBaseIndex == t1) { + size_t o = polygon->size() - 4; + Vector &p = *polygon; + int winding1 = winding(p[o], p[o + 1], p[o + 2], p[o + 3], x3, y3); + int winding2 = winding(x3, y3, p[0], p[1], p[2], p[3]); + if (winding1 == lastwinding && winding2 == lastwinding) { + polygon->add(x3); + polygon->add(y3); + polygonIndices->add(t3); + merged = true; + } + } - // Otherwise make this triangle the new base. - if (!merged) { - if (polygon->size() > 0) { - convexPolygons.add(polygon); - convexPolygonsIndices.add(polygonIndices); - } else { - _polygonPool.free(polygon); - _polygonIndicesPool.free(polygonIndices); - } + // Otherwise make this triangle the new base. + if (!merged) { + if (polygon->size() > 0) { + convexPolygons.add(polygon); + convexPolygonsIndices.add(polygonIndices); + } else { + _polygonPool.free(polygon); + _polygonIndicesPool.free(polygonIndices); + } - polygon = _polygonPool.obtain(); - polygon->clear(); - polygon->add(x1); - polygon->add(y1); - polygon->add(x2); - polygon->add(y2); - polygon->add(x3); - polygon->add(y3); - polygonIndices = _polygonIndicesPool.obtain(); - polygonIndices->clear(); - polygonIndices->add(t1); - polygonIndices->add(t2); - polygonIndices->add(t3); - lastwinding = winding(x1, y1, x2, y2, x3, y3); - fanBaseIndex = t1; - } - } + polygon = _polygonPool.obtain(); + polygon->clear(); + polygon->add(x1); + polygon->add(y1); + polygon->add(x2); + polygon->add(y2); + polygon->add(x3); + polygon->add(y3); + polygonIndices = _polygonIndicesPool.obtain(); + polygonIndices->clear(); + polygonIndices->add(t1); + polygonIndices->add(t2); + polygonIndices->add(t3); + lastwinding = winding(x1, y1, x2, y2, x3, y3); + fanBaseIndex = t1; + } + } - if (polygon->size() > 0) { - convexPolygons.add(polygon); - convexPolygonsIndices.add(polygonIndices); - } + if (polygon->size() > 0) { + convexPolygons.add(polygon); + convexPolygonsIndices.add(polygonIndices); + } - // Go through the list of polygons and try to merge the remaining triangles with the found triangle fans. - for (size_t i = 0, n = convexPolygons.size(); i < n; ++i) { - polygonIndices = convexPolygonsIndices[i]; + // Go through the list of polygons and try to merge the remaining triangles with the found triangle fans. + for (size_t i = 0, n = convexPolygons.size(); i < n; ++i) { + polygonIndices = convexPolygonsIndices[i]; - if (polygonIndices->size() == 0) continue; - int firstIndex = (*polygonIndices)[0]; - int lastIndex = (*polygonIndices)[polygonIndices->size() - 1]; + if (polygonIndices->size() == 0) continue; + int firstIndex = (*polygonIndices)[0]; + int lastIndex = (*polygonIndices)[polygonIndices->size() - 1]; - polygon = convexPolygons[i]; - size_t o = polygon->size() - 4; - Vector &p = *polygon; - float prevPrevX = p[o], prevPrevY = p[o + 1]; - float prevX = p[o + 2], prevY = p[o + 3]; - float firstX = p[0], firstY = p[1]; - float secondX = p[2], secondY = p[3]; - int winding0 = winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); + polygon = convexPolygons[i]; + size_t o = polygon->size() - 4; + Vector &p = *polygon; + float prevPrevX = p[o], prevPrevY = p[o + 1]; + float prevX = p[o + 2], prevY = p[o + 3]; + float firstX = p[0], firstY = p[1]; + float secondX = p[2], secondY = p[3]; + int winding0 = winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); - for (size_t ii = 0; ii < n; ++ii) { - if (ii == i) continue; + for (size_t ii = 0; ii < n; ++ii) { + if (ii == i) continue; - Vector *otherIndicesP = convexPolygonsIndices[ii]; - Vector &otherIndices = *otherIndicesP; + Vector *otherIndicesP = convexPolygonsIndices[ii]; + Vector &otherIndices = *otherIndicesP; - if (otherIndices.size() != 3) continue; + if (otherIndices.size() != 3) continue; - int otherFirstIndex = otherIndices[0]; - int otherSecondIndex = otherIndices[1]; - int otherLastIndex = otherIndices[2]; + int otherFirstIndex = otherIndices[0]; + int otherSecondIndex = otherIndices[1]; + int otherLastIndex = otherIndices[2]; - Vector *otherPolyP = convexPolygons[ii]; - Vector &otherPoly = *otherPolyP; + Vector *otherPolyP = convexPolygons[ii]; + Vector &otherPoly = *otherPolyP; - float x3 = otherPoly[otherPoly.size() - 2], y3 = otherPoly[otherPoly.size() - 1]; + float x3 = otherPoly[otherPoly.size() - 2], y3 = otherPoly[otherPoly.size() - 1]; - if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; + if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; - int winding1 = winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); - int winding2 = winding(x3, y3, firstX, firstY, secondX, secondY); - if (winding1 == winding0 && winding2 == winding0) { - otherPoly.clear(); - otherIndices.clear(); - polygon->add(x3); - polygon->add(y3); - polygonIndices->add(otherLastIndex); - prevPrevX = prevX; - prevPrevY = prevY; - prevX = x3; - prevY = y3; - ii = 0; - } - } - } + int winding1 = winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); + int winding2 = winding(x3, y3, firstX, firstY, secondX, secondY); + if (winding1 == winding0 && winding2 == winding0) { + otherPoly.clear(); + otherIndices.clear(); + polygon->add(x3); + polygon->add(y3); + polygonIndices->add(otherLastIndex); + prevPrevX = prevX; + prevPrevY = prevY; + prevX = x3; + prevY = y3; + ii = 0; + } + } + } - // Remove empty polygons that resulted from the merge step above. - for (int i = (int)convexPolygons.size() - 1; i >= 0; --i) { - polygon = convexPolygons[i]; - if (polygon->size() == 0) { - convexPolygons.removeAt(i); - _polygonPool.free(polygon); - polygonIndices = convexPolygonsIndices[i]; - convexPolygonsIndices.removeAt(i); - _polygonIndicesPool.free(polygonIndices); - } - } + // Remove empty polygons that resulted from the merge step above. + for (int i = (int)convexPolygons.size() - 1; i >= 0; --i) { + polygon = convexPolygons[i]; + if (polygon->size() == 0) { + convexPolygons.removeAt(i); + _polygonPool.free(polygon); + polygonIndices = convexPolygonsIndices[i]; + convexPolygonsIndices.removeAt(i); + _polygonIndicesPool.free(polygonIndices); + } + } - return convexPolygons; + return convexPolygons; } bool Triangulator::isConcave(int index, int vertexCount, Vector &vertices, Vector &indices) { - int previous = indices[(vertexCount + index - 1) % vertexCount] << 1; - int current = indices[index] << 1; - int next = indices[(index + 1) % vertexCount] << 1; + int previous = indices[(vertexCount + index - 1) % vertexCount] << 1; + int current = indices[index] << 1; + int next = indices[(index + 1) % vertexCount] << 1; - return !positiveArea(vertices[previous], vertices[previous + 1], - vertices[current], vertices[current + 1], - vertices[next], vertices[next + 1]); + return !positiveArea(vertices[previous], vertices[previous + 1], + vertices[current], vertices[current + 1], + vertices[next], vertices[next + 1]); } bool Triangulator::positiveArea(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { - return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; + return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; } int Triangulator::winding(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { - float px = p2x - p1x, py = p2y - p1y; - return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; + float px = p2x - p1x, py = p2y - p1y; + return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; } diff --git a/native/cocos/editor-support/spine/Triangulator.h b/native/cocos/editor-support/spine/Triangulator.h index 6a6d881cd8..e122e6330b 100644 --- a/native/cocos/editor-support/spine/Triangulator.h +++ b/native/cocos/editor-support/spine/Triangulator.h @@ -36,29 +36,29 @@ namespace spine { class SP_API Triangulator : public SpineObject { public: - ~Triangulator(); + ~Triangulator(); - Vector &triangulate(Vector &vertices); + Vector &triangulate(Vector &vertices); - Vector< Vector* > &decompose(Vector &vertices, Vector &triangles); + Vector *> &decompose(Vector &vertices, Vector &triangles); private: - Vector* > _convexPolygons; - Vector* > _convexPolygonsIndices; + Vector *> _convexPolygons; + Vector *> _convexPolygonsIndices; - Vector _indices; - Vector _isConcaveArray; - Vector _triangles; + Vector _indices; + Vector _isConcaveArray; + Vector _triangles; - Pool > _polygonPool; - Pool > _polygonIndicesPool; + Pool > _polygonPool; + Pool > _polygonIndicesPool; - static bool isConcave(int index, int vertexCount, Vector &vertices, Vector &indices); + static bool isConcave(int index, int vertexCount, Vector &vertices, Vector &indices); - static bool positiveArea(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y); + static bool positiveArea(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y); - static int winding(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y); + static int winding(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y); }; -} +} // namespace spine #endif /* Spine_Triangulator_h */ diff --git a/native/cocos/editor-support/spine/TwoColorTimeline.cpp b/native/cocos/editor-support/spine/TwoColorTimeline.cpp index 89d34d85e4..11421db043 100644 --- a/native/cocos/editor-support/spine/TwoColorTimeline.cpp +++ b/native/cocos/editor-support/spine/TwoColorTimeline.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -64,119 +64,118 @@ const int TwoColorTimeline::G2 = 6; const int TwoColorTimeline::B2 = 7; TwoColorTimeline::TwoColorTimeline(int frameCount) : CurveTimeline(frameCount), _slotIndex(0) { - _frames.ensureCapacity(frameCount * ENTRIES); - _frames.setSize(frameCount * ENTRIES, 0); + _frames.ensureCapacity(frameCount * ENTRIES); + _frames.setSize(frameCount * ENTRIES, 0); } void TwoColorTimeline::apply(Skeleton &skeleton, float lastTime, float time, Vector *pEvents, float alpha, - MixBlend blend, MixDirection direction -) { - SP_UNUSED(lastTime); - SP_UNUSED(pEvents); - SP_UNUSED(direction); + MixBlend blend, MixDirection direction) { + SP_UNUSED(lastTime); + SP_UNUSED(pEvents); + SP_UNUSED(direction); - Slot *slotP = skeleton._slots[_slotIndex]; - Slot &slot = *slotP; - if (!slot._bone.isActive()) return; + Slot *slotP = skeleton._slots[_slotIndex]; + Slot &slot = *slotP; + if (!slot._bone.isActive()) return; - if (time < _frames[0]) { - // Time is before first frame. - switch (blend) { - case MixBlend_Setup: - slot.getColor().set(slot.getData().getColor()); - slot.getDarkColor().set(slot.getData().getDarkColor()); - return; - case MixBlend_First: { - Color &color = slot.getColor(); - color.r += (color.r - slot._data.getColor().r) * alpha; - color.g += (color.g - slot._data.getColor().g) * alpha; - color.b += (color.b - slot._data.getColor().b) * alpha; - color.a += (color.a - slot._data.getColor().a) * alpha; + if (time < _frames[0]) { + // Time is before first frame. + switch (blend) { + case MixBlend_Setup: + slot.getColor().set(slot.getData().getColor()); + slot.getDarkColor().set(slot.getData().getDarkColor()); + return; + case MixBlend_First: { + Color &color = slot.getColor(); + color.r += (color.r - slot._data.getColor().r) * alpha; + color.g += (color.g - slot._data.getColor().g) * alpha; + color.b += (color.b - slot._data.getColor().b) * alpha; + color.a += (color.a - slot._data.getColor().a) * alpha; - Color &darkColor = slot.getDarkColor(); - darkColor.r += (darkColor.r - slot._data.getDarkColor().r) * alpha; - darkColor.g += (darkColor.g - slot._data.getDarkColor().g) * alpha; - darkColor.b += (darkColor.b - slot._data.getDarkColor().b) * alpha; - return; - } - default: - return; - } - } + Color &darkColor = slot.getDarkColor(); + darkColor.r += (darkColor.r - slot._data.getDarkColor().r) * alpha; + darkColor.g += (darkColor.g - slot._data.getDarkColor().g) * alpha; + darkColor.b += (darkColor.b - slot._data.getDarkColor().b) * alpha; + return; + } + default: + return; + } + } - float r, g, b, a, r2, g2, b2; - if (time >= _frames[_frames.size() - ENTRIES]) { - // Time is after last frame. - size_t i = _frames.size(); - r = _frames[i + PREV_R]; - g = _frames[i + PREV_G]; - b = _frames[i + PREV_B]; - a = _frames[i + PREV_A]; - r2 = _frames[i + PREV_R2]; - g2 = _frames[i + PREV_G2]; - b2 = _frames[i + PREV_B2]; - } else { - // Interpolate between the previous frame and the current frame. - size_t frame = (size_t)Animation::binarySearch(_frames, time, ENTRIES); - r = _frames[frame + PREV_R]; - g = _frames[frame + PREV_G]; - b = _frames[frame + PREV_B]; - a = _frames[frame + PREV_A]; - r2 = _frames[frame + PREV_R2]; - g2 = _frames[frame + PREV_G2]; - b2 = _frames[frame + PREV_B2]; - float frameTime = _frames[frame]; - float percent = getCurvePercent(frame / ENTRIES - 1, - 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); + float r, g, b, a, r2, g2, b2; + if (time >= _frames[_frames.size() - ENTRIES]) { + // Time is after last frame. + size_t i = _frames.size(); + r = _frames[i + PREV_R]; + g = _frames[i + PREV_G]; + b = _frames[i + PREV_B]; + a = _frames[i + PREV_A]; + r2 = _frames[i + PREV_R2]; + g2 = _frames[i + PREV_G2]; + b2 = _frames[i + PREV_B2]; + } else { + // Interpolate between the previous frame and the current frame. + size_t frame = (size_t)Animation::binarySearch(_frames, time, ENTRIES); + r = _frames[frame + PREV_R]; + g = _frames[frame + PREV_G]; + b = _frames[frame + PREV_B]; + a = _frames[frame + PREV_A]; + r2 = _frames[frame + PREV_R2]; + g2 = _frames[frame + PREV_G2]; + b2 = _frames[frame + PREV_B2]; + float frameTime = _frames[frame]; + float percent = getCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (_frames[frame + PREV_TIME] - frameTime)); - r += (_frames[frame + R] - r) * percent; - g += (_frames[frame + G] - g) * percent; - b += (_frames[frame + B] - b) * percent; - a += (_frames[frame + A] - a) * percent; - r2 += (_frames[frame + R2] - r2) * percent; - g2 += (_frames[frame + G2] - g2) * percent; - b2 += (_frames[frame + B2] - b2) * percent; - } + r += (_frames[frame + R] - r) * percent; + g += (_frames[frame + G] - g) * percent; + b += (_frames[frame + B] - b) * percent; + a += (_frames[frame + A] - a) * percent; + r2 += (_frames[frame + R2] - r2) * percent; + g2 += (_frames[frame + G2] - g2) * percent; + b2 += (_frames[frame + B2] - b2) * percent; + } - if (alpha == 1) { - Color &color = slot.getColor(); - color.set(r, g, b, a); + if (alpha == 1) { + Color &color = slot.getColor(); + color.set(r, g, b, a); - Color &darkColor = slot.getDarkColor(); - darkColor.set(r2, g2, b2, 1); - } else { - Color &light = slot._color; - Color &dark = slot._darkColor; - if (blend == MixBlend_Setup) { - light.set(slot._data._color); - dark.set(slot._data._darkColor); - } - light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha); - dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0); - } + Color &darkColor = slot.getDarkColor(); + darkColor.set(r2, g2, b2, 1); + } else { + Color &light = slot._color; + Color &dark = slot._darkColor; + if (blend == MixBlend_Setup) { + light.set(slot._data._color); + dark.set(slot._data._darkColor); + } + light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha); + dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0); + } } int TwoColorTimeline::getPropertyId() { - return ((int) TimelineType_TwoColor << 24) + _slotIndex; + return ((int)TimelineType_TwoColor << 24) + _slotIndex; } void TwoColorTimeline::setFrame(int frameIndex, float time, float r, float g, float b, float a, float r2, float g2, float b2) { - frameIndex *= ENTRIES; - _frames[frameIndex] = time; - _frames[frameIndex + R] = r; - _frames[frameIndex + G] = g; - _frames[frameIndex + B] = b; - _frames[frameIndex + A] = a; - _frames[frameIndex + R2] = r2; - _frames[frameIndex + G2] = g2; - _frames[frameIndex + B2] = b2; + frameIndex *= ENTRIES; + _frames[frameIndex] = time; + _frames[frameIndex + R] = r; + _frames[frameIndex + G] = g; + _frames[frameIndex + B] = b; + _frames[frameIndex + A] = a; + _frames[frameIndex + R2] = r2; + _frames[frameIndex + G2] = g2; + _frames[frameIndex + B2] = b2; } int TwoColorTimeline::getSlotIndex() { - return _slotIndex; + return _slotIndex; } void TwoColorTimeline::setSlotIndex(int inValue) { - assert(inValue >= 0); - _slotIndex = inValue; + assert(inValue >= 0); + _slotIndex = inValue; } diff --git a/native/cocos/editor-support/spine/TwoColorTimeline.h b/native/cocos/editor-support/spine/TwoColorTimeline.h index 6cc1104189..ee8dcc9d2a 100644 --- a/native/cocos/editor-support/spine/TwoColorTimeline.h +++ b/native/cocos/editor-support/spine/TwoColorTimeline.h @@ -34,47 +34,47 @@ namespace spine { - class SP_API TwoColorTimeline : public CurveTimeline { - friend class SkeletonBinary; - friend class SkeletonJson; +class SP_API TwoColorTimeline : public CurveTimeline { + friend class SkeletonBinary; + friend class SkeletonJson; - RTTI_DECL + RTTI_DECL - public: - static const int ENTRIES; +public: + static const int ENTRIES; - explicit TwoColorTimeline(int frameCount); + explicit TwoColorTimeline(int frameCount); - virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); + virtual void apply(Skeleton& skeleton, float lastTime, float time, Vector* pEvents, float alpha, MixBlend blend, MixDirection direction); - virtual int getPropertyId(); + virtual int getPropertyId(); - /// Sets the time and value of the specified keyframe. - void setFrame(int frameIndex, float time, float r, float g, float b, float a, float r2, float g2, float b2); + /// Sets the time and value of the specified keyframe. + void setFrame(int frameIndex, float time, float r, float g, float b, float a, float r2, float g2, float b2); - int getSlotIndex(); - void setSlotIndex(int inValue); + int getSlotIndex(); + void setSlotIndex(int inValue); - private: - static const int PREV_TIME; - static const int PREV_R; - static const int PREV_G; - static const int PREV_B; - static const int PREV_A; - static const int PREV_R2; - static const int PREV_G2; - static const int PREV_B2; - static const int R; - static const int G; - static const int B; - static const int A; - static const int R2; - static const int G2; - static const int B2; +private: + static const int PREV_TIME; + static const int PREV_R; + static const int PREV_G; + static const int PREV_B; + static const int PREV_A; + static const int PREV_R2; + static const int PREV_G2; + static const int PREV_B2; + static const int R; + static const int G; + static const int B; + static const int A; + static const int R2; + static const int G2; + static const int B2; - Vector _frames; // time, r, g, b, a, r2, g2, b2, ... - int _slotIndex; - }; -} + Vector _frames; // time, r, g, b, a, r2, g2, b2, ... + int _slotIndex; +}; +} // namespace spine #endif /* Spine_TwoColorTimeline_h */ diff --git a/native/cocos/editor-support/spine/Updatable.cpp b/native/cocos/editor-support/spine/Updatable.cpp index 419347335f..2aae06552f 100644 --- a/native/cocos/editor-support/spine/Updatable.cpp +++ b/native/cocos/editor-support/spine/Updatable.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include diff --git a/native/cocos/editor-support/spine/Updatable.h b/native/cocos/editor-support/spine/Updatable.h index 51f8cec409..98d8cd0bc9 100644 --- a/native/cocos/editor-support/spine/Updatable.h +++ b/native/cocos/editor-support/spine/Updatable.h @@ -35,19 +35,19 @@ namespace spine { class SP_API Updatable : public SpineObject { -RTTI_DECL + RTTI_DECL public: - Updatable(); + Updatable(); - virtual ~Updatable(); + virtual ~Updatable(); - virtual void update() = 0; + virtual void update() = 0; - virtual bool isActive() = 0; + virtual bool isActive() = 0; - virtual void setActive(bool inValue) = 0; + virtual void setActive(bool inValue) = 0; }; -} +} // namespace spine #endif /* Spine_Updatable_h */ diff --git a/native/cocos/editor-support/spine/Vector.h b/native/cocos/editor-support/spine/Vector.h index 4d263725cd..ac79affa0a 100644 --- a/native/cocos/editor-support/spine/Vector.h +++ b/native/cocos/editor-support/spine/Vector.h @@ -36,187 +36,187 @@ #include namespace spine { -template +template class SP_API Vector : public SpineObject { public: - Vector() : _size(0), _capacity(0), _buffer(NULL) { - } + Vector() : _size(0), _capacity(0), _buffer(NULL) { + } - Vector(const Vector &inVector) : _size(inVector._size), _capacity(inVector._capacity), _buffer(NULL) { - if (_capacity > 0) { - _buffer = allocate(_capacity); - for (size_t i = 0; i < _size; ++i) { - construct(_buffer + i, inVector._buffer[i]); - } - } - } + Vector(const Vector &inVector) : _size(inVector._size), _capacity(inVector._capacity), _buffer(NULL) { + if (_capacity > 0) { + _buffer = allocate(_capacity); + for (size_t i = 0; i < _size; ++i) { + construct(_buffer + i, inVector._buffer[i]); + } + } + } - ~Vector() { - clear(); - deallocate(_buffer); - } + ~Vector() { + clear(); + deallocate(_buffer); + } - inline void clear() { - for (size_t i = 0; i < _size; ++i) { - destroy(_buffer + (_size - 1 - i)); - } + inline void clear() { + for (size_t i = 0; i < _size; ++i) { + destroy(_buffer + (_size - 1 - i)); + } - _size = 0; - } + _size = 0; + } - inline size_t getCapacity() const { - return _capacity; - } + inline size_t getCapacity() const { + return _capacity; + } - inline size_t size() const { - return _size; - } + inline size_t size() const { + return _size; + } - inline void setSize(size_t newSize, const T &defaultValue) { - assert(newSize >= 0); - size_t oldSize = _size; - _size = newSize; - if (_capacity < newSize) { - _capacity = (int) (_size * 1.75f); - if (_capacity < 8) _capacity = 8; - _buffer = spine::SpineExtension::realloc(_buffer, _capacity, __FILE__, __LINE__); - } - if (oldSize < _size) { - for (size_t i = oldSize; i < _size; i++) { - construct(_buffer + i, defaultValue); - } - } - } + inline void setSize(size_t newSize, const T &defaultValue) { + assert(newSize >= 0); + size_t oldSize = _size; + _size = newSize; + if (_capacity < newSize) { + _capacity = (int)(_size * 1.75f); + if (_capacity < 8) _capacity = 8; + _buffer = spine::SpineExtension::realloc(_buffer, _capacity, __FILE__, __LINE__); + } + if (oldSize < _size) { + for (size_t i = oldSize; i < _size; i++) { + construct(_buffer + i, defaultValue); + } + } + } - inline void ensureCapacity(size_t newCapacity = 0) { - if (_capacity >= newCapacity) return; - _capacity = newCapacity; - _buffer = SpineExtension::realloc(_buffer, newCapacity, __FILE__, __LINE__); - } + inline void ensureCapacity(size_t newCapacity = 0) { + if (_capacity >= newCapacity) return; + _capacity = newCapacity; + _buffer = SpineExtension::realloc(_buffer, newCapacity, __FILE__, __LINE__); + } - inline void add(const T &inValue) { - if (_size == _capacity) { - // inValue might reference an element in this buffer - // When we reallocate, the reference becomes invalid. - // We thus need to create a defensive copy before - // reallocating. - T valueCopy = inValue; - _capacity = (int) (_size * 1.75f); - if (_capacity < 8) _capacity = 8; - _buffer = spine::SpineExtension::realloc(_buffer, _capacity, __FILE__, __LINE__); - construct(_buffer + _size++, valueCopy); - } else { - construct(_buffer + _size++, inValue); - } - } + inline void add(const T &inValue) { + if (_size == _capacity) { + // inValue might reference an element in this buffer + // When we reallocate, the reference becomes invalid. + // We thus need to create a defensive copy before + // reallocating. + T valueCopy = inValue; + _capacity = (int)(_size * 1.75f); + if (_capacity < 8) _capacity = 8; + _buffer = spine::SpineExtension::realloc(_buffer, _capacity, __FILE__, __LINE__); + construct(_buffer + _size++, valueCopy); + } else { + construct(_buffer + _size++, inValue); + } + } - inline void addAll(Vector &inValue) { - ensureCapacity(this->size() + inValue.size()); - for (size_t i = 0; i < inValue.size(); i++) { - add(inValue[i]); - } - } + inline void addAll(Vector &inValue) { + ensureCapacity(this->size() + inValue.size()); + for (size_t i = 0; i < inValue.size(); i++) { + add(inValue[i]); + } + } - inline void clearAndAddAll(Vector &inValue) { - this->clear(); - this->addAll(inValue); - } + inline void clearAndAddAll(Vector &inValue) { + this->clear(); + this->addAll(inValue); + } - inline void removeAt(size_t inIndex) { - assert(inIndex < _size); + inline void removeAt(size_t inIndex) { + assert(inIndex < _size); - --_size; + --_size; - if (inIndex != _size) { - for (size_t i = inIndex; i < _size; ++i) { - T tmp(_buffer[i]); - _buffer[i] = _buffer[i + 1]; - _buffer[i + 1] = tmp; - } - } + if (inIndex != _size) { + for (size_t i = inIndex; i < _size; ++i) { + T tmp(_buffer[i]); + _buffer[i] = _buffer[i + 1]; + _buffer[i + 1] = tmp; + } + } - destroy(_buffer + _size); - } + destroy(_buffer + _size); + } - inline bool contains(const T &inValue) { - for (size_t i = 0; i < _size; ++i) { - if (_buffer[i] == inValue) { - return true; - } - } + inline bool contains(const T &inValue) { + for (size_t i = 0; i < _size; ++i) { + if (_buffer[i] == inValue) { + return true; + } + } - return false; - } + return false; + } - inline int indexOf(const T &inValue) { - for (size_t i = 0; i < _size; ++i) { - if (_buffer[i] == inValue) { - return (int)i; - } - } + inline int indexOf(const T &inValue) { + for (size_t i = 0; i < _size; ++i) { + if (_buffer[i] == inValue) { + return (int)i; + } + } - return -1; - } + return -1; + } - inline T &operator[](size_t inIndex) { - assert(inIndex < _size); + inline T &operator[](size_t inIndex) { + assert(inIndex < _size); - return _buffer[inIndex]; - } + return _buffer[inIndex]; + } - inline friend bool operator==(Vector &lhs, Vector &rhs) { - if (lhs.size() != rhs.size()) { - return false; - } + inline friend bool operator==(Vector &lhs, Vector &rhs) { + if (lhs.size() != rhs.size()) { + return false; + } - for (size_t i = 0, n = lhs.size(); i < n; ++i) { - if (lhs[i] != rhs[i]) { - return false; - } - } + for (size_t i = 0, n = lhs.size(); i < n; ++i) { + if (lhs[i] != rhs[i]) { + return false; + } + } - return true; - } + return true; + } - inline friend bool operator!=(Vector &lhs, Vector &rhs) { - return !(lhs == rhs); - } + inline friend bool operator!=(Vector &lhs, Vector &rhs) { + return !(lhs == rhs); + } - inline T *buffer() { - return _buffer; - } + inline T *buffer() { + return _buffer; + } private: - size_t _size; - size_t _capacity; - T *_buffer; + size_t _size; + size_t _capacity; + T *_buffer; - inline T *allocate(size_t n) { - assert(n > 0); + inline T *allocate(size_t n) { + assert(n > 0); - T *ptr = SpineExtension::calloc(n, __FILE__, __LINE__); + T *ptr = SpineExtension::calloc(n, __FILE__, __LINE__); - assert(ptr); + assert(ptr); - return ptr; - } + return ptr; + } - inline void deallocate(T *buffer) { - if (_buffer) { - SpineExtension::free(buffer, __FILE__, __LINE__); - } - } + inline void deallocate(T *buffer) { + if (_buffer) { + SpineExtension::free(buffer, __FILE__, __LINE__); + } + } - inline void construct(T *buffer, const T &val) { - new(buffer) T(val); - } + inline void construct(T *buffer, const T &val) { + new (buffer) T(val); + } - inline void destroy(T *buffer) { - buffer->~T(); - } + inline void destroy(T *buffer) { + buffer->~T(); + } - // Vector &operator=(const Vector &inVector) {}; + // Vector &operator=(const Vector &inVector) {}; }; -} +} // namespace spine #endif /* Spine_Vector_h */ diff --git a/native/cocos/editor-support/spine/VertexAttachment.cpp b/native/cocos/editor-support/spine/VertexAttachment.cpp index 9ff2cdaf7b..58a0979901 100644 --- a/native/cocos/editor-support/spine/VertexAttachment.cpp +++ b/native/cocos/editor-support/spine/VertexAttachment.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -49,121 +49,121 @@ VertexAttachment::~VertexAttachment() { } void VertexAttachment::computeWorldVertices(Slot &slot, Vector &worldVertices) { - computeWorldVertices(slot, 0, _worldVerticesLength, worldVertices, 0); + computeWorldVertices(slot, 0, _worldVerticesLength, worldVertices, 0); } void VertexAttachment::computeWorldVertices(Slot &slot, float *worldVertices) { - computeWorldVertices(slot, 0, _worldVerticesLength, worldVertices, 0); + computeWorldVertices(slot, 0, _worldVerticesLength, worldVertices, 0); } void VertexAttachment::computeWorldVertices(Slot &slot, size_t start, size_t count, Vector &worldVertices, size_t offset, size_t stride) { - computeWorldVertices(slot, start, count, worldVertices.buffer(), offset, stride); + computeWorldVertices(slot, start, count, worldVertices.buffer(), offset, stride); } void VertexAttachment::computeWorldVertices(Slot &slot, size_t start, size_t count, float *worldVertices, size_t offset, size_t stride) { - count = offset + (count >> 1) * stride; - Skeleton &skeleton = slot._bone._skeleton; - Vector *deformArray = &slot.getDeform(); - Vector *vertices = &_vertices; - Vector &bones = _bones; - if (bones.size() == 0) { - if (deformArray->size() > 0) vertices = deformArray; + count = offset + (count >> 1) * stride; + Skeleton &skeleton = slot._bone._skeleton; + Vector *deformArray = &slot.getDeform(); + Vector *vertices = &_vertices; + Vector &bones = _bones; + if (bones.size() == 0) { + if (deformArray->size() > 0) vertices = deformArray; - Bone &bone = slot._bone; - float x = bone._worldX; - float y = bone._worldY; - float a = bone._a, b = bone._b, c = bone._c, d = bone._d; - for (size_t vv = start, w = offset; w < count; vv += 2, w += stride) { - float vx = (*vertices)[vv]; - float vy = (*vertices)[vv + 1]; - worldVertices[w] = vx * a + vy * b + x; - worldVertices[w + 1] = vx * c + vy * d + y; - } - return; - } + Bone &bone = slot._bone; + float x = bone._worldX; + float y = bone._worldY; + float a = bone._a, b = bone._b, c = bone._c, d = bone._d; + for (size_t vv = start, w = offset; w < count; vv += 2, w += stride) { + float vx = (*vertices)[vv]; + float vy = (*vertices)[vv + 1]; + worldVertices[w] = vx * a + vy * b + x; + worldVertices[w + 1] = vx * c + vy * d + y; + } + return; + } - int v = 0, skip = 0; - for (size_t i = 0; i < start; i += 2) { - int n = bones[v]; - v += n + 1; - skip += n; - } + int v = 0, skip = 0; + for (size_t i = 0; i < start; i += 2) { + int n = bones[v]; + v += n + 1; + skip += n; + } - Vector &skeletonBones = skeleton.getBones(); - if (deformArray->size() == 0) { - for (size_t w = offset, b = skip * 3; w < count; w += stride) { - float wx = 0, wy = 0; - int n = bones[v++]; - n += v; - for (; v < n; v++, b += 3) { - Bone *boneP = skeletonBones[bones[v]]; - Bone &bone = *boneP; - float vx = (*vertices)[b]; - float vy = (*vertices)[b + 1]; - float weight = (*vertices)[b + 2]; - wx += (vx * bone._a + vy * bone._b + bone._worldX) * weight; - wy += (vx * bone._c + vy * bone._d + bone._worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; - } - } else { - for (size_t w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) { - float wx = 0, wy = 0; - int n = bones[v++]; - n += v; - for (; v < n; v++, b += 3, f += 2) { - Bone *boneP = skeletonBones[bones[v]]; - Bone &bone = *boneP; - float vx = (*vertices)[b] + (*deformArray)[f]; - float vy = (*vertices)[b + 1] + (*deformArray)[f + 1]; - float weight = (*vertices)[b + 2]; - wx += (vx * bone._a + vy * bone._b + bone._worldX) * weight; - wy += (vx * bone._c + vy * bone._d + bone._worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; - } - } + Vector &skeletonBones = skeleton.getBones(); + if (deformArray->size() == 0) { + for (size_t w = offset, b = skip * 3; w < count; w += stride) { + float wx = 0, wy = 0; + int n = bones[v++]; + n += v; + for (; v < n; v++, b += 3) { + Bone *boneP = skeletonBones[bones[v]]; + Bone &bone = *boneP; + float vx = (*vertices)[b]; + float vy = (*vertices)[b + 1]; + float weight = (*vertices)[b + 2]; + wx += (vx * bone._a + vy * bone._b + bone._worldX) * weight; + wy += (vx * bone._c + vy * bone._d + bone._worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } else { + for (size_t w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) { + float wx = 0, wy = 0; + int n = bones[v++]; + n += v; + for (; v < n; v++, b += 3, f += 2) { + Bone *boneP = skeletonBones[bones[v]]; + Bone &bone = *boneP; + float vx = (*vertices)[b] + (*deformArray)[f]; + float vy = (*vertices)[b + 1] + (*deformArray)[f + 1]; + float weight = (*vertices)[b + 2]; + wx += (vx * bone._a + vy * bone._b + bone._worldX) * weight; + wy += (vx * bone._c + vy * bone._d + bone._worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } } int VertexAttachment::getId() { - return _id; + return _id; } Vector &VertexAttachment::getBones() { - return _bones; + return _bones; } Vector &VertexAttachment::getVertices() { - return _vertices; + return _vertices; } size_t VertexAttachment::getWorldVerticesLength() { - return _worldVerticesLength; + return _worldVerticesLength; } void VertexAttachment::setWorldVerticesLength(size_t inValue) { - _worldVerticesLength = inValue; + _worldVerticesLength = inValue; } -VertexAttachment* VertexAttachment::getDeformAttachment() { - return _deformAttachment; +VertexAttachment *VertexAttachment::getDeformAttachment() { + return _deformAttachment; } -void VertexAttachment::setDeformAttachment(VertexAttachment* attachment) { - _deformAttachment = attachment; +void VertexAttachment::setDeformAttachment(VertexAttachment *attachment) { + _deformAttachment = attachment; } int VertexAttachment::getNextID() { - static int nextID = 0; + static int nextID = 0; - return (nextID++ & 65535) << 11; + return (nextID++ & 65535) << 11; } -void VertexAttachment::copyTo(VertexAttachment* other) { - other->_bones.clearAndAddAll(this->_bones); - other->_vertices.clearAndAddAll(this->_vertices); - other->_worldVerticesLength = this->_worldVerticesLength; - other->_deformAttachment = this->_deformAttachment; +void VertexAttachment::copyTo(VertexAttachment *other) { + other->_bones.clearAndAddAll(this->_bones); + other->_vertices.clearAndAddAll(this->_vertices); + other->_worldVerticesLength = this->_worldVerticesLength; + other->_deformAttachment = this->_deformAttachment; } diff --git a/native/cocos/editor-support/spine/VertexAttachment.h b/native/cocos/editor-support/spine/VertexAttachment.h index 5cf8f00650..d522f4a624 100644 --- a/native/cocos/editor-support/spine/VertexAttachment.h +++ b/native/cocos/editor-support/spine/VertexAttachment.h @@ -35,59 +35,59 @@ #include namespace spine { - class Slot; +class Slot; - /// An attachment with vertices that are transformed by one or more bones and can be deformed by a slot's vertices. - class SP_API VertexAttachment : public Attachment { - friend class SkeletonBinary; - friend class SkeletonJson; - friend class DeformTimeline; +/// An attachment with vertices that are transformed by one or more bones and can be deformed by a slot's vertices. +class SP_API VertexAttachment : public Attachment { + friend class SkeletonBinary; + friend class SkeletonJson; + friend class DeformTimeline; - RTTI_DECL + RTTI_DECL - public: - explicit VertexAttachment(const String& name); +public: + explicit VertexAttachment(const String& name); - virtual ~VertexAttachment(); + virtual ~VertexAttachment(); - void computeWorldVertices(Slot& slot, float* worldVertices); - void computeWorldVertices(Slot& slot, Vector& worldVertices); + void computeWorldVertices(Slot& slot, float* worldVertices); + void computeWorldVertices(Slot& slot, Vector& worldVertices); - /// Transforms local vertices to world coordinates. - /// @param start The index of the first Vertices value to transform. Each vertex has 2 values, x and y. - /// @param count The number of world vertex values to output. Must be less than or equal to WorldVerticesLength - start. - /// @param worldVertices The output world vertices. Must have a length greater than or equal to offset + count. - /// @param offset The worldVertices index to begin writing values. - /// @param stride The number of worldVertices entries between the value pairs written. - void computeWorldVertices(Slot& slot, size_t start, size_t count, float* worldVertices, size_t offset, size_t stride = 2); - void computeWorldVertices(Slot& slot, size_t start, size_t count, Vector& worldVertices, size_t offset, size_t stride = 2); + /// Transforms local vertices to world coordinates. + /// @param start The index of the first Vertices value to transform. Each vertex has 2 values, x and y. + /// @param count The number of world vertex values to output. Must be less than or equal to WorldVerticesLength - start. + /// @param worldVertices The output world vertices. Must have a length greater than or equal to offset + count. + /// @param offset The worldVertices index to begin writing values. + /// @param stride The number of worldVertices entries between the value pairs written. + void computeWorldVertices(Slot& slot, size_t start, size_t count, float* worldVertices, size_t offset, size_t stride = 2); + void computeWorldVertices(Slot& slot, size_t start, size_t count, Vector& worldVertices, size_t offset, size_t stride = 2); - /// Gets a unique ID for this attachment. - int getId(); + /// Gets a unique ID for this attachment. + int getId(); - Vector& getBones(); + Vector& getBones(); - Vector& getVertices(); + Vector& getVertices(); - size_t getWorldVerticesLength(); - void setWorldVerticesLength(size_t inValue); + size_t getWorldVerticesLength(); + void setWorldVerticesLength(size_t inValue); - VertexAttachment* getDeformAttachment(); - void setDeformAttachment(VertexAttachment* attachment); + VertexAttachment* getDeformAttachment(); + void setDeformAttachment(VertexAttachment* attachment); - void copyTo(VertexAttachment* other); + void copyTo(VertexAttachment* other); - protected: - Vector _bones; - Vector _vertices; - size_t _worldVerticesLength; - VertexAttachment* _deformAttachment; +protected: + Vector _bones; + Vector _vertices; + size_t _worldVerticesLength; + VertexAttachment* _deformAttachment; - private: - const int _id; +private: + const int _id; - static int getNextID(); - }; -} + static int getNextID(); +}; +} // namespace spine #endif /* Spine_VertexAttachment_h */ diff --git a/native/cocos/editor-support/spine/VertexEffect.cpp b/native/cocos/editor-support/spine/VertexEffect.cpp index 68e22e68a1..d7f9dda3be 100644 --- a/native/cocos/editor-support/spine/VertexEffect.cpp +++ b/native/cocos/editor-support/spine/VertexEffect.cpp @@ -28,7 +28,7 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif #include @@ -37,123 +37,121 @@ using namespace spine; -JitterVertexEffect::JitterVertexEffect(float jitterX, float jitterY): _jitterX(jitterX), _jitterY(jitterY) { +JitterVertexEffect::JitterVertexEffect(float jitterX, float jitterY) : _jitterX(jitterX), _jitterY(jitterY) { } void JitterVertexEffect::begin(Skeleton &skeleton) { - SP_UNUSED(skeleton); + SP_UNUSED(skeleton); } void JitterVertexEffect::transform(float &x, float &y, float &u, float &v, Color &light, Color &dark) { - SP_UNUSED(u); - SP_UNUSED(v); - SP_UNUSED(light); - SP_UNUSED(dark); - float jitterX = _jitterX; - float jitterY = _jitterY; - x += MathUtil::randomTriangular(-jitterX, jitterX); - y += MathUtil::randomTriangular(-jitterX, jitterY); + SP_UNUSED(u); + SP_UNUSED(v); + SP_UNUSED(light); + SP_UNUSED(dark); + float jitterX = _jitterX; + float jitterY = _jitterY; + x += MathUtil::randomTriangular(-jitterX, jitterX); + y += MathUtil::randomTriangular(-jitterX, jitterY); } void JitterVertexEffect::end() { } void JitterVertexEffect::setJitterX(float jitterX) { - _jitterX = jitterX; + _jitterX = jitterX; } float JitterVertexEffect::getJitterX() { - return _jitterX; + return _jitterX; } void JitterVertexEffect::setJitterY(float jitterY) { - _jitterY = jitterY; + _jitterY = jitterY; } float JitterVertexEffect::getJitterY() { - return _jitterY; + return _jitterY; } -SwirlVertexEffect::SwirlVertexEffect(float radius, Interpolation &interpolation): - _centerX(0), - _centerY(0), - _radius(radius), - _angle(0), - _worldX(0), - _worldY(0), - _interpolation(interpolation) { +SwirlVertexEffect::SwirlVertexEffect(float radius, Interpolation &interpolation) : _centerX(0), + _centerY(0), + _radius(radius), + _angle(0), + _worldX(0), + _worldY(0), + _interpolation(interpolation) { } void SwirlVertexEffect::begin(Skeleton &skeleton) { - _worldX = skeleton.getX() + _centerX; - _worldY = skeleton.getY() + _centerY; + _worldX = skeleton.getX() + _centerX; + _worldY = skeleton.getY() + _centerY; } void SwirlVertexEffect::transform(float &positionX, float &positionY, float &u, float &v, Color &light, Color &dark) { - SP_UNUSED(u); - SP_UNUSED(v); - SP_UNUSED(light); - SP_UNUSED(dark); + SP_UNUSED(u); + SP_UNUSED(v); + SP_UNUSED(light); + SP_UNUSED(dark); - float x = positionX - _worldX; - float y = positionY - _worldY; - float dist = (float)MathUtil::sqrt(x * x + y * y); - if (dist < _radius) { - float theta = _interpolation.interpolate(0, _angle, (_radius - dist) / _radius); - float cos = MathUtil::cos(theta), sin = MathUtil::sin(theta); - positionX = cos * x - sin * y + _worldX; - positionY = sin * x + cos * y + _worldY; - } + float x = positionX - _worldX; + float y = positionY - _worldY; + float dist = (float)MathUtil::sqrt(x * x + y * y); + if (dist < _radius) { + float theta = _interpolation.interpolate(0, _angle, (_radius - dist) / _radius); + float cos = MathUtil::cos(theta), sin = MathUtil::sin(theta); + positionX = cos * x - sin * y + _worldX; + positionY = sin * x + cos * y + _worldY; + } } void SwirlVertexEffect::end() { - } void SwirlVertexEffect::setCenterX(float centerX) { - _centerX = centerX; + _centerX = centerX; } float SwirlVertexEffect::getCenterX() { - return _centerX; + return _centerX; } void SwirlVertexEffect::setCenterY(float centerY) { - _centerY = centerY; + _centerY = centerY; } float SwirlVertexEffect::getCenterY() { - return _centerY; + return _centerY; } void SwirlVertexEffect::setRadius(float radius) { - _radius = radius; + _radius = radius; } float SwirlVertexEffect::getRadius() { - return _radius; + return _radius; } void SwirlVertexEffect::setAngle(float angle) { - _angle = angle * MathUtil::Deg_Rad; + _angle = angle * MathUtil::Deg_Rad; } float SwirlVertexEffect::getAngle() { - return _angle; + return _angle; } void SwirlVertexEffect::setWorldX(float worldX) { - _worldX = worldX; + _worldX = worldX; } float SwirlVertexEffect::getWorldX() { - return _worldX; + return _worldX; } void SwirlVertexEffect::setWorldY(float worldY) { - _worldY = worldY; + _worldY = worldY; } float SwirlVertexEffect::getWorldY() { - return _worldY; + return _worldY; } diff --git a/native/cocos/editor-support/spine/VertexEffect.h b/native/cocos/editor-support/spine/VertexEffect.h index dbe7ae58f2..a734d5d719 100644 --- a/native/cocos/editor-support/spine/VertexEffect.h +++ b/native/cocos/editor-support/spine/VertexEffect.h @@ -38,68 +38,68 @@ namespace spine { class Skeleton; class Color; -class SP_API VertexEffect: public SpineObject { +class SP_API VertexEffect : public SpineObject { public: - virtual void begin(Skeleton& skeleton) = 0; - virtual void transform(float& x, float& y, float &u, float &v, Color &light, Color &dark) = 0; - virtual void end() = 0; + virtual void begin(Skeleton &skeleton) = 0; + virtual void transform(float &x, float &y, float &u, float &v, Color &light, Color &dark) = 0; + virtual void end() = 0; }; -class SP_API JitterVertexEffect: public VertexEffect { +class SP_API JitterVertexEffect : public VertexEffect { public: - JitterVertexEffect(float jitterX, float jitterY); + JitterVertexEffect(float jitterX, float jitterY); - void begin(Skeleton& skeleton); - void transform(float& x, float& y, float &u, float &v, Color &light, Color &dark); - void end(); + void begin(Skeleton &skeleton); + void transform(float &x, float &y, float &u, float &v, Color &light, Color &dark); + void end(); - void setJitterX(float jitterX); - float getJitterX(); + void setJitterX(float jitterX); + float getJitterX(); - void setJitterY(float jitterY); - float getJitterY(); + void setJitterY(float jitterY); + float getJitterY(); protected: - float _jitterX; - float _jitterY; + float _jitterX; + float _jitterY; }; -class SP_API SwirlVertexEffect: public VertexEffect { +class SP_API SwirlVertexEffect : public VertexEffect { public: - SwirlVertexEffect(float radius, Interpolation &interpolation); + SwirlVertexEffect(float radius, Interpolation &interpolation); - void begin(Skeleton& skeleton); - void transform(float& x, float& y, float &u, float &v, Color &light, Color &dark); - void end(); + void begin(Skeleton &skeleton); + void transform(float &x, float &y, float &u, float &v, Color &light, Color &dark); + void end(); - void setCenterX(float centerX); - float getCenterX(); + void setCenterX(float centerX); + float getCenterX(); - void setCenterY(float centerY); - float getCenterY(); + void setCenterY(float centerY); + float getCenterY(); - void setRadius(float radius); - float getRadius(); + void setRadius(float radius); + float getRadius(); - void setAngle(float angle); - float getAngle(); + void setAngle(float angle); + float getAngle(); - void setWorldX(float worldX); - float getWorldX(); + void setWorldX(float worldX); + float getWorldX(); - void setWorldY(float worldY); - float getWorldY(); + void setWorldY(float worldY); + float getWorldY(); protected: - float _centerX; - float _centerY; - float _radius; - float _angle; - float _worldX; - float _worldY; + float _centerX; + float _centerY; + float _radius; + float _angle; + float _worldX; + float _worldY; - Interpolation& _interpolation; + Interpolation &_interpolation; }; -} +} // namespace spine #endif /* Spine_VertexEffect_h */ diff --git a/native/cocos/editor-support/spine/Vertices.h b/native/cocos/editor-support/spine/Vertices.h index fa2b0f5de0..903f8d2df9 100644 --- a/native/cocos/editor-support/spine/Vertices.h +++ b/native/cocos/editor-support/spine/Vertices.h @@ -35,9 +35,9 @@ namespace spine { class SP_API Vertices : public SpineObject { public: - Vector _bones; - Vector _vertices; + Vector _bones; + Vector _vertices; }; -} +} // namespace spine #endif /* Spine_Vertices_h */ diff --git a/native/cocos/editor-support/spine/dll.h b/native/cocos/editor-support/spine/dll.h index 2fe0160306..5f500f5d3a 100644 --- a/native/cocos/editor-support/spine/dll.h +++ b/native/cocos/editor-support/spine/dll.h @@ -31,21 +31,21 @@ #define SPINE_SHAREDLIB_H #ifdef _WIN32 -#define DLLIMPORT __declspec(dllimport) -#define DLLEXPORT __declspec(dllexport) + #define DLLIMPORT __declspec(dllimport) + #define DLLEXPORT __declspec(dllexport) #else -#ifndef DLLIMPORT -#define DLLIMPORT -#endif -#ifndef DLLEXPORT -#define DLLEXPORT -#endif + #ifndef DLLIMPORT + #define DLLIMPORT + #endif + #ifndef DLLEXPORT + #define DLLEXPORT + #endif #endif #ifdef SPINEPLUGIN_API -#define SP_API SPINEPLUGIN_API + #define SP_API SPINEPLUGIN_API #else -#define SP_API + #define SP_API #endif #endif /* SPINE_SHAREDLIB_H */ diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index f184aeba41..d2fcb2c699 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -68,10 +68,10 @@ namespace { bool setCanvasCallback(se::Object * /*global*/) { se::AutoHandleScope scope; - se::ScriptEngine * se = se::ScriptEngine::getInstance(); - auto * window = CC_CURRENT_ENGINE()->getInterface(); - auto handler = window->getWindowHandler(); - auto viewSize = window->getViewSize(); + se::ScriptEngine *se = se::ScriptEngine::getInstance(); + auto *window = CC_CURRENT_ENGINE()->getInterface(); + auto handler = window->getWindowHandler(); + auto viewSize = window->getViewSize(); std::stringstream ss; { @@ -235,8 +235,8 @@ void Engine::tick() { static std::chrono::steady_clock::time_point prevTime; static std::chrono::steady_clock::time_point now; - static float dt = 0.F; - static double dtNS = NANOSECONDS_60FPS; + static float dt = 0.F; + static double dtNS = NANOSECONDS_60FPS; ++_totalFrames; @@ -260,9 +260,9 @@ void Engine::tick() { cc::DeferredReleasePool::clear(); - now = std::chrono::steady_clock::now(); + now = std::chrono::steady_clock::now(); dtNS = dtNS * 0.1 + 0.9 * static_cast(std::chrono::duration_cast(now - prevTime).count()); - dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; + dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; } CC_PROFILER_END_FRAME; @@ -305,8 +305,8 @@ int32_t Engine::restartVM() { } bool Engine::handleEvent(const OSEvent &ev) { - bool isHandled = false; - OSEventType type = ev.eventType(); + bool isHandled = false; + OSEventType type = ev.eventType(); if (type == OSEventType::TOUCH_OSEVENT) { cc::EventDispatcher::dispatchTouchEvent(OSEvent::castEvent(ev)); isHandled = true; @@ -328,7 +328,7 @@ bool Engine::handleEvent(const OSEvent &ev) { return isHandled; } -bool Engine::handleTouchEvent(const TouchEvent& ev) { // NOLINT(readability-convert-member-functions-to-static) +bool Engine::handleTouchEvent(const TouchEvent &ev) { // NOLINT(readability-convert-member-functions-to-static) cc::EventDispatcher::dispatchTouchEvent(ev); return true; } diff --git a/native/cocos/engine/Engine.h b/native/cocos/engine/Engine.h index 20e0648fec..9dc6d57beb 100644 --- a/native/cocos/engine/Engine.h +++ b/native/cocos/engine/Engine.h @@ -110,24 +110,24 @@ public: */ SchedulerPtr getScheduler() const override; - bool isInited() const override {return _inited;} + bool isInited() const override { return _inited; } private: - void tick(); - bool dispatchWindowEvent(const WindowEvent& ev); - bool dispatchDeviceEvent(const DeviceEvent& ev); - bool dispatchEventToApp(OSEventType type, const OSEvent& ev); + void tick(); + bool dispatchWindowEvent(const WindowEvent& ev); + bool dispatchDeviceEvent(const DeviceEvent& ev); + bool dispatchEventToApp(OSEventType type, const OSEvent& ev); int32_t restartVM(); - bool _close{false}; - bool _pause{false}; - bool _resune{false}; + bool _close{false}; + bool _pause{false}; + bool _resune{false}; std::shared_ptr _scheduler{nullptr}; - int64_t _prefererredNanosecondsPerFrame{NANOSECONDS_60FPS}; - uint _totalFrames{0}; - cc::Vec2 _viewLogicalSize{0, 0}; - bool _needRestart{false}; - bool _inited{false}; + int64_t _prefererredNanosecondsPerFrame{NANOSECONDS_60FPS}; + uint _totalFrames{0}; + cc::Vec2 _viewLogicalSize{0, 0}; + bool _needRestart{false}; + bool _inited{false}; std::map _eventCallbacks; CC_DISALLOW_COPY_MOVE_ASSIGN(Engine); diff --git a/native/cocos/math/Geometry.cpp b/native/cocos/math/Geometry.cpp index d45439c17d..dd2122db7c 100644 --- a/native/cocos/math/Geometry.cpp +++ b/native/cocos/math/Geometry.cpp @@ -75,7 +75,7 @@ Size Size::operator/(float a) const { } void Size::setSize(float w, float h) { - this->width = w; + this->width = w; this->height = h; } @@ -114,7 +114,7 @@ void Rect::setRect(float x, float y, float width, float height) { origin.x = x; origin.y = y; - size.width = width; + size.width = width; size.height = height; } @@ -203,9 +203,9 @@ void Rect::merge(const Rect &rect) { } Rect Rect::unionWithRect(const Rect &rect) const { - float thisLeftX = origin.x; - float thisRightX = origin.x + size.width; - float thisTopY = origin.y + size.height; + float thisLeftX = origin.x; + float thisRightX = origin.x + size.width; + float thisTopY = origin.y + size.height; float thisBottomY = origin.y; if (thisRightX < thisLeftX) { @@ -216,9 +216,9 @@ Rect Rect::unionWithRect(const Rect &rect) const { std::swap(thisTopY, thisBottomY); // This rect has negative height } - float otherLeftX = rect.origin.x; - float otherRightX = rect.origin.x + rect.size.width; - float otherTopY = rect.origin.y + rect.size.height; + float otherLeftX = rect.origin.x; + float otherRightX = rect.origin.x + rect.size.width; + float otherTopY = rect.origin.y + rect.size.height; float otherBottomY = rect.origin.y; if (otherRightX < otherLeftX) { @@ -229,9 +229,9 @@ Rect Rect::unionWithRect(const Rect &rect) const { std::swap(otherTopY, otherBottomY); // Other rect has negative height } - float combinedLeftX = std::min(thisLeftX, otherLeftX); - float combinedRightX = std::max(thisRightX, otherRightX); - float combinedTopY = std::max(thisTopY, otherTopY); + float combinedLeftX = std::min(thisLeftX, otherLeftX); + float combinedRightX = std::max(thisRightX, otherRightX); + float combinedTopY = std::max(thisTopY, otherTopY); float combinedBottomY = std::min(thisBottomY, otherBottomY); return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY); diff --git a/native/cocos/math/Geometry.h b/native/cocos/math/Geometry.h index 8440548587..0f1f0ea6e1 100644 --- a/native/cocos/math/Geometry.h +++ b/native/cocos/math/Geometry.h @@ -59,10 +59,10 @@ public: Size &operator=(const Size &other); Size &operator=(const Vec2 &point); - Size operator+(const Size &right) const; - Size operator-(const Size &right) const; - Size operator*(float a) const; - Size operator/(float a) const; + Size operator+(const Size &right) const; + Size operator-(const Size &right) const; + Size operator*(float a) const; + Size operator/(float a) const; /** Set the width and height of Size. */ @@ -88,7 +88,7 @@ public: Rect(const Vec2 &pos, const Size &dimension); Rect(const Rect &other); Rect &operator=(const Rect &other); - void setRect(float x, float y, float width, float height); + void setRect(float x, float y, float width, float height); /** Get the left of the rect. */ diff --git a/native/cocos/math/Mat3.cpp b/native/cocos/math/Mat3.cpp index 21461bbcad..ad318b1248 100644 --- a/native/cocos/math/Mat3.cpp +++ b/native/cocos/math/Mat3.cpp @@ -112,12 +112,12 @@ void Mat3::transpose() { float a01 = m[1]; float a02 = m[2]; float a12 = m[5]; - m[1] = m[3]; - m[2] = m[6]; - m[3] = a01; - m[5] = m[7]; - m[6] = a02; - m[7] = a12; + m[1] = m[3]; + m[2] = m[6]; + m[3] = a01; + m[5] = m[7]; + m[6] = a02; + m[7] = a12; } void Mat3::transpose(const Mat3 &mat, Mat3 *out) { @@ -151,7 +151,7 @@ void Mat3::inverse() { // Calculate the determinant float det = a00 * b01 + a01 * b11 + a02 * b21; - det = 1.0F / det; + det = 1.0F / det; m[0] = b01 * det; m[1] = (-a22 * a01 + a02 * a21) * det; m[2] = (a12 * a01 - a02 * a11) * det; @@ -236,8 +236,8 @@ void Mat3::translate(const Mat3 &mat, const Vec2 &vec, Mat3 *out) { float a20 = mat.m[6]; float a21 = mat.m[7]; float a22 = mat.m[8]; - float x = vec.x; - float y = vec.y; + float x = vec.x; + float y = vec.y; out->m[0] = a00; out->m[1] = a01; @@ -359,10 +359,10 @@ void Mat3::fromScaling(const Vec2 &vec, Mat3 *out) { void Mat3::fromQuat(const Quaternion &quat, Mat3 *out) { CC_ASSERT(out); - float x = quat.x; - float y = quat.y; - float z = quat.z; - float w = quat.w; + float x = quat.x; + float y = quat.y; + float z = quat.z; + float w = quat.w; float x2 = x + x; float y2 = y + y; float z2 = z + z; diff --git a/native/cocos/math/Mat4.cpp b/native/cocos/math/Mat4.cpp index 185af03b34..7b4b0d3443 100644 --- a/native/cocos/math/Mat4.cpp +++ b/native/cocos/math/Mat4.cpp @@ -97,8 +97,8 @@ void Mat4::createLookAt(float eyePositionX, float eyePositionY, float eyePositio dst->m[6] = zaxis.y; dst->m[7] = 0.0F; - dst->m[8] = xaxis.z; - dst->m[9] = yaxis.z; + dst->m[8] = xaxis.z; + dst->m[9] = yaxis.z; dst->m[10] = zaxis.z; dst->m[11] = 0.0F; @@ -114,7 +114,7 @@ void Mat4::createPerspective(float fieldOfView, float aspectRatio, float zNearPl CC_ASSERT(zFarPlane != zNearPlane); CC_ASSERT(fieldOfView != 0.0F); - const float f = 1.0F / tanf(fieldOfView / 2.0F); + const float f = 1.0F / tanf(fieldOfView / 2.0F); const float nf = 1.0F / (zNearPlane - zFarPlane); const float x = isFieldOfViewY ? f / aspectRatio : f; @@ -122,16 +122,16 @@ void Mat4::createPerspective(float fieldOfView, float aspectRatio, float zNearPl const ccstd::array &preTransform = PRE_TRANSFORMS[orientation]; - dst->m[0] = x * preTransform[0]; - dst->m[1] = x * preTransform[1]; - dst->m[2] = 0.0F; - dst->m[3] = 0.0F; - dst->m[4] = y * preTransform[2]; - dst->m[5] = y * preTransform[3]; - dst->m[6] = 0.0F; - dst->m[7] = 0.0F; - dst->m[8] = 0.0F; - dst->m[9] = 0.0F; + dst->m[0] = x * preTransform[0]; + dst->m[1] = x * preTransform[1]; + dst->m[2] = 0.0F; + dst->m[3] = 0.0F; + dst->m[4] = y * preTransform[2]; + dst->m[5] = y * preTransform[3]; + dst->m[6] = 0.0F; + dst->m[7] = 0.0F; + dst->m[8] = 0.0F; + dst->m[9] = 0.0F; dst->m[10] = (zFarPlane - minClipZ * zNearPlane) * nf; dst->m[11] = -1.0F; dst->m[12] = 0.0F; @@ -156,25 +156,25 @@ void Mat4::createOrthographicOffCenter(float left, float right, float bottom, fl CC_ASSERT(zFarPlane != zNearPlane); const ccstd::array &preTransform = PRE_TRANSFORMS[orientation]; - const float lr = 1.F / (left - right); - const float bt = 1.F / (bottom - top) * projectionSignY; - const float nf = 1.F / (zNearPlane - zFarPlane); + const float lr = 1.F / (left - right); + const float bt = 1.F / (bottom - top) * projectionSignY; + const float nf = 1.F / (zNearPlane - zFarPlane); - const float x = -2 * lr; - const float y = -2 * bt; + const float x = -2 * lr; + const float y = -2 * bt; const float dx = (left + right) * lr; const float dy = (top + bottom) * bt; - dst->m[0] = x * preTransform[0]; - dst->m[1] = x * preTransform[1]; - dst->m[2] = 0; - dst->m[3] = 0; - dst->m[4] = y * preTransform[2]; - dst->m[5] = y * preTransform[3]; - dst->m[6] = 0; - dst->m[7] = 0; - dst->m[8] = 0; - dst->m[9] = 0; + dst->m[0] = x * preTransform[0]; + dst->m[1] = x * preTransform[1]; + dst->m[2] = 0; + dst->m[3] = 0; + dst->m[4] = y * preTransform[2]; + dst->m[5] = y * preTransform[3]; + dst->m[6] = 0; + dst->m[7] = 0; + dst->m[8] = 0; + dst->m[9] = 0; dst->m[10] = nf * (1 - minClipZ); dst->m[11] = 0; dst->m[12] = dx * preTransform[0] + dy * preTransform[2]; @@ -201,8 +201,8 @@ void Mat4::createBillboardHelper(const Vec3 &objectPosition, const Vec3 &cameraP bool isSufficientDelta = delta.lengthSquared() > MATH_EPSILON; dst->setIdentity(); - dst->m[3] = objectPosition.x; - dst->m[7] = objectPosition.y; + dst->m[3] = objectPosition.x; + dst->m[7] = objectPosition.y; dst->m[11] = objectPosition.z; // As per the contracts for the 2 variants of createBillboard, we need @@ -213,14 +213,14 @@ void Mat4::createBillboardHelper(const Vec3 &objectPosition, const Vec3 &cameraP // A billboard is the inverse of a lookAt rotation Mat4 lookAt; createLookAt(objectPosition, target, cameraUpVector, &lookAt); - dst->m[0] = lookAt.m[0]; - dst->m[1] = lookAt.m[4]; - dst->m[2] = lookAt.m[8]; - dst->m[4] = lookAt.m[1]; - dst->m[5] = lookAt.m[5]; - dst->m[6] = lookAt.m[9]; - dst->m[8] = lookAt.m[2]; - dst->m[9] = lookAt.m[6]; + dst->m[0] = lookAt.m[0]; + dst->m[1] = lookAt.m[4]; + dst->m[2] = lookAt.m[8]; + dst->m[4] = lookAt.m[1]; + dst->m[5] = lookAt.m[5]; + dst->m[6] = lookAt.m[9]; + dst->m[8] = lookAt.m[2]; + dst->m[9] = lookAt.m[6]; dst->m[10] = lookAt.m[10]; } } @@ -249,8 +249,8 @@ void Mat4::createScale(const Vec3 &scale, Mat4 *dst) { memcpy(dst->m, IDENTITY.m, MATRIX_SIZE); - dst->m[0] = scale.x; - dst->m[5] = scale.y; + dst->m[0] = scale.x; + dst->m[5] = scale.y; dst->m[10] = scale.z; } @@ -259,8 +259,8 @@ void Mat4::createScale(float xScale, float yScale, float zScale, Mat4 *dst) { memcpy(dst->m, IDENTITY.m, MATRIX_SIZE); - dst->m[0] = xScale; - dst->m[5] = yScale; + dst->m[0] = xScale; + dst->m[5] = yScale; dst->m[10] = zScale; } @@ -291,8 +291,8 @@ void Mat4::createRotation(const Quaternion &q, Mat4 *dst) { dst->m[6] = yz2 + wx2; dst->m[7] = 0.0F; - dst->m[8] = xz2 + wy2; - dst->m[9] = yz2 - wx2; + dst->m[8] = xz2 + wy2; + dst->m[9] = yz2 - wx2; dst->m[10] = 1.0F - xx2 - yy2; dst->m[11] = 0.0F; @@ -326,16 +326,16 @@ void Mat4::createRotation(const Vec3 &axis, float angle, Mat4 *dst) { float c = std::cos(angle); float s = std::sin(angle); - float t = 1.0F - c; - float tx = t * x; - float ty = t * y; - float tz = t * z; + float t = 1.0F - c; + float tx = t * x; + float ty = t * y; + float tz = t * z; float txy = tx * y; float txz = tx * z; float tyz = ty * z; - float sx = s * x; - float sy = s * y; - float sz = s * z; + float sx = s * x; + float sy = s * y; + float sz = s * z; dst->m[0] = c + tx * x; dst->m[1] = txy + sz; @@ -347,8 +347,8 @@ void Mat4::createRotation(const Vec3 &axis, float angle, Mat4 *dst) { dst->m[6] = tyz + sx; dst->m[7] = 0.0F; - dst->m[8] = txz + sy; - dst->m[9] = tyz - sx; + dst->m[8] = txz + sy; + dst->m[9] = tyz - sx; dst->m[10] = c + tz * z; dst->m[11] = 0.0F; @@ -366,9 +366,9 @@ void Mat4::createRotationX(float angle, Mat4 *dst) { float c = std::cos(angle); float s = std::sin(angle); - dst->m[5] = c; - dst->m[6] = s; - dst->m[9] = -s; + dst->m[5] = c; + dst->m[6] = s; + dst->m[9] = -s; dst->m[10] = c; } @@ -380,9 +380,9 @@ void Mat4::createRotationY(float angle, Mat4 *dst) { float c = std::cos(angle); float s = std::sin(angle); - dst->m[0] = c; - dst->m[2] = -s; - dst->m[8] = s; + dst->m[0] = c; + dst->m[2] = -s; + dst->m[8] = s; dst->m[10] = c; } @@ -447,10 +447,10 @@ void Mat4::add(const Mat4 &m1, const Mat4 &m2, Mat4 *dst) { } void Mat4::fromRT(const Quaternion &rotation, const Vec3 &translation, Mat4 *dst) { - const auto x = rotation.x; - const auto y = rotation.y; - const auto z = rotation.z; - const auto w = rotation.w; + const auto x = rotation.x; + const auto y = rotation.y; + const auto z = rotation.z; + const auto w = rotation.w; const auto x2 = x + x; const auto y2 = y + y; const auto z2 = z + z; @@ -465,16 +465,16 @@ void Mat4::fromRT(const Quaternion &rotation, const Vec3 &translation, Mat4 *dst const auto wy = w * y2; const auto wz = w * z2; - dst->m[0] = 1 - (yy + zz); - dst->m[1] = xy + wz; - dst->m[2] = xz - wy; - dst->m[3] = 0; - dst->m[4] = xy - wz; - dst->m[5] = 1 - (xx + zz); - dst->m[6] = yz + wx; - dst->m[7] = 0; - dst->m[8] = xz + wy; - dst->m[9] = yz - wx; + dst->m[0] = 1 - (yy + zz); + dst->m[1] = xy + wz; + dst->m[2] = xz - wy; + dst->m[3] = 0; + dst->m[4] = xy - wz; + dst->m[5] = 1 - (xx + zz); + dst->m[6] = yz + wx; + dst->m[7] = 0; + dst->m[8] = xz + wy; + dst->m[9] = yz - wx; dst->m[10] = 1 - (xx + yy); dst->m[11] = 0; dst->m[12] = translation.x; @@ -484,10 +484,10 @@ void Mat4::fromRT(const Quaternion &rotation, const Vec3 &translation, Mat4 *dst } void Mat4::fromRTS(const Quaternion &rotation, const Vec3 &translation, const Vec3 &scale, Mat4 *dst) { - const float x = rotation.x; - const float y = rotation.y; - const float z = rotation.z; - const float w = rotation.w; + const float x = rotation.x; + const float y = rotation.y; + const float z = rotation.z; + const float w = rotation.w; const float x2 = x + x; const float y2 = y + y; const float z2 = z + z; @@ -505,16 +505,16 @@ void Mat4::fromRTS(const Quaternion &rotation, const Vec3 &translation, const Ve const float sy = scale.y; const float sz = scale.z; - dst->m[0] = (1 - (yy + zz)) * sx; - dst->m[1] = (xy + wz) * sx; - dst->m[2] = (xz - wy) * sx; - dst->m[3] = 0; - dst->m[4] = (xy - wz) * sy; - dst->m[5] = (1 - (xx + zz)) * sy; - dst->m[6] = (yz + wx) * sy; - dst->m[7] = 0; - dst->m[8] = (xz + wy) * sz; - dst->m[9] = (yz - wx) * sz; + dst->m[0] = (1 - (yy + zz)) * sx; + dst->m[1] = (xy + wz) * sx; + dst->m[2] = (xz - wy) * sx; + dst->m[3] = 0; + dst->m[4] = (xy - wz) * sy; + dst->m[5] = (1 - (xx + zz)) * sy; + dst->m[6] = (yz + wx) * sy; + dst->m[7] = 0; + dst->m[8] = (xz + wy) * sz; + dst->m[9] = (yz - wx) * sz; dst->m[10] = (1 - (xx + yy)) * sz; dst->m[11] = 0; dst->m[12] = translation.x; @@ -545,13 +545,13 @@ bool Mat4::decompose(Vec3 *scale, Quaternion *rotation, Vec3 *translation) const // Extract the scale. // This is simply the length of each axis (row/column) in the matrix. - Vec3 xaxis(m[0], m[1], m[2]); + Vec3 xaxis(m[0], m[1], m[2]); float scaleX = xaxis.length(); - Vec3 yaxis(m[4], m[5], m[6]); + Vec3 yaxis(m[4], m[5], m[6]); float scaleY = yaxis.length(); - Vec3 zaxis(m[8], m[9], m[10]); + Vec3 zaxis(m[8], m[9], m[10]); float scaleZ = zaxis.length(); // Determine if we have a negative scale (true if determinant is less than zero). @@ -599,7 +599,7 @@ bool Mat4::decompose(Vec3 *scale, Quaternion *rotation, Vec3 *translation) const float trace = xaxis.x + yaxis.y + zaxis.z + 1.0F; if (trace > MATH_EPSILON) { - float s = 0.5F / std::sqrt(trace); + float s = 0.5F / std::sqrt(trace); rotation->w = 0.25F / s; rotation->x = (yaxis.z - zaxis.y) * s; rotation->y = (zaxis.x - xaxis.z) * s; @@ -608,19 +608,19 @@ bool Mat4::decompose(Vec3 *scale, Quaternion *rotation, Vec3 *translation) const // Note: since xaxis, yaxis, and zaxis are normalized, // we will never divide by zero in the code below. if (xaxis.x > yaxis.y && xaxis.x > zaxis.z) { - float s = 0.5F / std::sqrt(1.0F + xaxis.x - yaxis.y - zaxis.z); + float s = 0.5F / std::sqrt(1.0F + xaxis.x - yaxis.y - zaxis.z); rotation->w = (yaxis.z - zaxis.y) * s; rotation->x = 0.25F / s; rotation->y = (yaxis.x + xaxis.y) * s; rotation->z = (zaxis.x + xaxis.z) * s; } else if (yaxis.y > zaxis.z) { - float s = 0.5F / std::sqrt(1.0F + yaxis.y - xaxis.x - zaxis.z); + float s = 0.5F / std::sqrt(1.0F + yaxis.y - xaxis.x - zaxis.z); rotation->w = (zaxis.x - xaxis.z) * s; rotation->x = (yaxis.x + xaxis.y) * s; rotation->y = 0.25F / s; rotation->z = (zaxis.y + yaxis.z) * s; } else { - float s = 0.5F / std::sqrt(1.0F + zaxis.z - xaxis.x - yaxis.y); + float s = 0.5F / std::sqrt(1.0F + zaxis.z - xaxis.x - yaxis.y); rotation->w = (xaxis.y - yaxis.x) * s; rotation->x = (zaxis.x + xaxis.z) * s; rotation->y = (zaxis.y + yaxis.z) * s; @@ -698,8 +698,8 @@ void Mat4::inverseTranspose(const Mat4 &mat, Mat4 *dst) { dst->m[6] = (a01 * b08 - a00 * b10 - a03 * b06) * det; dst->m[7] = 0; - dst->m[8] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - dst->m[9] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + dst->m[8] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + dst->m[9] = (a32 * b02 - a30 * b05 - a33 * b01) * det; dst->m[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; dst->m[11] = 0; @@ -814,8 +814,8 @@ bool Mat4::inverse() { inverse.m[6] = -m[12] * a5 + m[14] * a2 - m[15] * a1; inverse.m[7] = m[8] * a5 - m[10] * a2 + m[11] * a1; - inverse.m[8] = m[4] * b4 - m[5] * b2 + m[7] * b0; - inverse.m[9] = -m[0] * b4 + m[1] * b2 - m[3] * b0; + inverse.m[8] = m[4] * b4 - m[5] * b2 + m[7] * b0; + inverse.m[9] = -m[0] * b4 + m[1] * b2 - m[3] * b0; inverse.m[10] = m[12] * a4 - m[13] * a2 + m[15] * a0; inverse.m[11] = -m[8] * a4 + m[9] * a2 - m[11] * a0; @@ -955,16 +955,16 @@ void Mat4::scale(const Vec3 &s, Mat4 *dst) const { void Mat4::set(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { - m[0] = m11; - m[1] = m21; - m[2] = m31; - m[3] = m41; - m[4] = m12; - m[5] = m22; - m[6] = m32; - m[7] = m42; - m[8] = m13; - m[9] = m23; + m[0] = m11; + m[1] = m21; + m[2] = m31; + m[3] = m41; + m[4] = m12; + m[5] = m22; + m[6] = m32; + m[7] = m42; + m[8] = m13; + m[9] = m23; m[10] = m33; m[11] = m43; m[12] = m14; diff --git a/native/cocos/math/Mat4.h b/native/cocos/math/Mat4.h index 591fa6ec73..d42daa0334 100644 --- a/native/cocos/math/Mat4.h +++ b/native/cocos/math/Mat4.h @@ -93,7 +93,7 @@ public: #ifdef __SSE__ union { __m128 col[4]; - float m[16]; + float m[16]; }; #else float m[16]; diff --git a/native/cocos/math/Quaternion.cpp b/native/cocos/math/Quaternion.cpp index b7be5ba39e..229fe95375 100644 --- a/native/cocos/math/Quaternion.cpp +++ b/native/cocos/math/Quaternion.cpp @@ -77,7 +77,7 @@ void Quaternion::createFromRotationMatrix(const Mat4 &m, Quaternion *dst) { void Quaternion::createFromAxisAngle(const Vec3 &axis, float angle, Quaternion *dst) { CC_ASSERT(dst); - float halfAngle = angle * 0.5F; + float halfAngle = angle * 0.5F; float sinHalfAngle = sinf(halfAngle); Vec3 normal(axis); @@ -93,8 +93,8 @@ void Quaternion::createFromAngleZ(float z, Quaternion *dst) { z *= mathutils::HALF_TO_RAD; dst->x = dst->y = 0.F; - dst->z = sinf(z); - dst->w = cosf(z); + dst->z = sinf(z); + dst->w = cosf(z); } void Quaternion::conjugate() { @@ -314,25 +314,25 @@ void Quaternion::toEuler(const Quaternion &q, bool outerZ, Vec3 *out) { float heading{0}; float attitude{0}; float test = x * y + z * w; - float r2d = 180.F / math::PI; + float r2d = 180.F / math::PI; if (test > 0.499999) { - bank = 0; - heading = -2 * atan2(x, w) * r2d; + bank = 0; + heading = -2 * atan2(x, w) * r2d; attitude = 90; } else if (test < -0.499999) { - bank = 0; - heading = -2 * atan2(x, w) * r2d; + bank = 0; + heading = -2 * atan2(x, w) * r2d; attitude = -90; } else { float sqx = x * x; float sqy = y * y; float sqz = z * z; - bank = atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz) * r2d; - heading = atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz) * r2d; - attitude = asin(2 * test) * r2d; + bank = atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz) * r2d; + heading = atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz) * r2d; + attitude = asin(2 * test) * r2d; if (outerZ) { - bank = static_cast(-180.F * math::Sgn(bank + 1e-6) + bank); - heading = static_cast(-180.F * math::Sgn(heading + 1e-6) + heading); + bank = static_cast(-180.F * math::Sgn(bank + 1e-6) + bank); + heading = static_cast(-180.F * math::Sgn(heading + 1e-6) + heading); attitude = static_cast(180.F * math::Sgn(attitude + 1e-6) - attitude); } } @@ -343,22 +343,22 @@ void Quaternion::toEuler(const Quaternion &q, bool outerZ, Vec3 *out) { void Quaternion::fromMat3(const Mat3 &m, Quaternion *out) { CC_ASSERT(out); - float m00 = m.m[0]; - float m03 = m.m[1]; - float m06 = m.m[2]; - float m01 = m.m[3]; - float m04 = m.m[4]; - float m07 = m.m[5]; - float m02 = m.m[6]; - float m05 = m.m[7]; - float m08 = m.m[8]; + float m00 = m.m[0]; + float m03 = m.m[1]; + float m06 = m.m[2]; + float m01 = m.m[3]; + float m04 = m.m[4]; + float m07 = m.m[5]; + float m02 = m.m[6]; + float m05 = m.m[7]; + float m08 = m.m[8]; float trace = m00 + m04 + m08; if (trace > 0) { const float s = 0.5F / sqrtf(trace + 1.F); - out->w = 0.25F / s; - out->x = (m05 - m07) * s; - out->y = (m06 - m02) * s; - out->z = (m01 - m03) * s; + out->w = 0.25F / s; + out->x = (m05 - m07) * s; + out->y = (m06 - m02) * s; + out->z = (m01 - m03) * s; } else if ((m00 > m04) && (m00 > m08)) { const float s = 2.F * sqrtf(1.F + m04 - m00 - m08); @@ -441,7 +441,7 @@ void Quaternion::slerp(float q1x, float q1y, float q1z, float q1w, float q2x, fl // Here we bisect the interval, so we need to fold t as well. f2b = t - 0.5F; - u = f2b >= 0 ? f2b : -f2b; + u = f2b >= 0 ? f2b : -f2b; f2a = u - f2b; f2b += u; u += u; @@ -460,7 +460,7 @@ void Quaternion::slerp(float q1x, float q1y, float q1z, float q1w, float q2x, fl ratio1 = -0.333333333F + ratio1 * (sqNotU - 4.F) * versHalfTheta; ratio1 = 1.F + ratio1 * (sqNotU - 1.F) * versHalfTheta; - sqU = u * u; + sqU = u * u; ratio2 = -0.00158730159F + (sqU - 16.F) * ratio2; ratio2 = 0.0333333333F + ratio2 * (sqU - 9.F) * versHalfTheta; ratio2 = -0.333333333F + ratio2 * (sqU - 4.F) * versHalfTheta; @@ -484,7 +484,7 @@ void Quaternion::slerp(float q1x, float q1y, float q1z, float q1w, float q2x, fl // can see, it comes at the cost of 9 additional multiplication // operations. If this error-correcting feature is not required, // the following code may be removed. - f1 = 1.5F - 0.5F * (w * w + x * x + y * y + z * z); + f1 = 1.5F - 0.5F * (w * w + x * x + y * y + z * z); *dstw = w * f1; *dstx = x * f1; *dsty = y * f1; @@ -509,7 +509,7 @@ void Quaternion::slerpForSquad(const Quaternion &q1, const Quaternion &q2, float } float omega = std::acos(c); - float s = std::sqrt(1.F - c * c); + float s = std::sqrt(1.F - c * c); if (std::abs(s) <= 0.00001F) { dst->x = q1.x; dst->y = q1.y; @@ -520,10 +520,10 @@ void Quaternion::slerpForSquad(const Quaternion &q1, const Quaternion &q2, float float r1 = std::sin((1 - t) * omega) / s; float r2 = std::sin(t * omega) / s; - dst->x = (q1.x * r1 + q2.x * r2); - dst->y = (q1.y * r1 + q2.y * r2); - dst->z = (q1.z * r1 + q2.z * r2); - dst->w = (q1.w * r1 + q2.w * r2); + dst->x = (q1.x * r1 + q2.x * r2); + dst->y = (q1.y * r1 + q2.y * r2); + dst->z = (q1.z * r1 + q2.z * r2); + dst->w = (q1.w * r1 + q2.w * r2); } NS_CC_MATH_END diff --git a/native/cocos/math/Utils.cpp b/native/cocos/math/Utils.cpp index a49a50a657..dede0bcffe 100644 --- a/native/cocos/math/Utils.cpp +++ b/native/cocos/math/Utils.cpp @@ -6,7 +6,7 @@ #include "math/Math.h" namespace { -std::random_device rd; +std::random_device rd; std::uniform_real_distribution uniformReal{0.0F, 1.0F}; } // namespace diff --git a/native/cocos/math/Utils.h b/native/cocos/math/Utils.h index f0095b174d..ad29a01ebf 100644 --- a/native/cocos/math/Utils.h +++ b/native/cocos/math/Utils.h @@ -8,9 +8,9 @@ namespace cc { namespace mathutils { -constexpr auto EPSILON = 0.000001; -constexpr auto D2R = M_PI / 180.0; -constexpr auto R2D = 180.0 / M_PI; +constexpr auto EPSILON = 0.000001; +constexpr auto D2R = M_PI / 180.0; +constexpr auto R2D = 180.0 / M_PI; constexpr auto HALF_TO_RAD = 0.5 * D2R; /** * @en Tests whether or not the arguments have approximately the same value, within an absolute
@@ -55,12 +55,11 @@ typename std::enable_if::value, F>::type clamp(F val, F min, F max) { if (min > max) { const auto temp = min; - min = max; - max = temp; + min = max; + max = temp; } - return val < min ? min : val > max ? max - : val; + return val < min ? min : val > max ? max : val; } /** @@ -71,8 +70,7 @@ clamp(F val, F min, F max) { template auto clamp01(F val) { static_assert(std::is_floating_point::value, "number expected"); - return val < 0 ? 0 : val > 1 ? 1 - : val; + return val < 0 ? 0 : val > 1 ? 1 : val; } /** diff --git a/native/cocos/math/Vec2.cpp b/native/cocos/math/Vec2.cpp index a245581741..8ac8e99fde 100644 --- a/native/cocos/math/Vec2.cpp +++ b/native/cocos/math/Vec2.cpp @@ -159,8 +159,8 @@ void Vec2::rotate(const Vec2 &point, float angle) { if (point.isZero()) { float tempX = x * cosAngle - y * sinAngle; - y = y * cosAngle + x * sinAngle; - x = tempX; + y = y * cosAngle + x * sinAngle; + x = tempX; } else { float tempX = x - point.x; float tempY = y - point.y; @@ -199,8 +199,8 @@ bool Vec2::fuzzyEquals(const Vec2 &b, float var) const { } float Vec2::getAngle(const Vec2 &other) const { - Vec2 a2 = getNormalized(); - Vec2 b2 = other.getNormalized(); + Vec2 a2 = getNormalized(); + Vec2 b2 = other.getNormalized(); float angle = atan2f(a2.cross(b2), a2.dot(b2)); if (std::abs(angle) < FLT_EPSILON) { return 0.F; diff --git a/native/cocos/math/Vec2.h b/native/cocos/math/Vec2.h index a134d09350..dee7f367d3 100644 --- a/native/cocos/math/Vec2.h +++ b/native/cocos/math/Vec2.h @@ -36,8 +36,7 @@ inline float clampf(float value, float minInclusive, float maxInclusive) { if (minInclusive > maxInclusive) { std::swap(minInclusive, maxInclusive); } - return value < minInclusive ? minInclusive : value < maxInclusive ? value - : maxInclusive; + return value < minInclusive ? minInclusive : value < maxInclusive ? value : maxInclusive; } class Mat4; diff --git a/native/cocos/math/Vec3.cpp b/native/cocos/math/Vec3.cpp index 9227429044..cfe4f881bb 100644 --- a/native/cocos/math/Vec3.cpp +++ b/native/cocos/math/Vec3.cpp @@ -49,7 +49,7 @@ Vec3::Vec3(const Vec3 ©) { Vec3 Vec3::fromColor(unsigned int color) { float components[3]; - int componentIndex = 0; + int componentIndex = 0; for (int i = 2; i >= 0; --i) { auto component = (color >> i * 8) & 0x0000ff; @@ -70,9 +70,9 @@ void Vec3::transformInverseRTS(const Vec3 &v, const Quaternion &r, const Vec3 &t const float iy = r.w * y - r.z * x + r.x * z; const float iz = r.w * z - r.x * y + r.y * x; const float iw = r.x * x + r.y * y + r.z * z; - out->x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x; - out->y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y; - out->z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z; + out->x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x; + out->y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y; + out->z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z; } float Vec3::angle(const Vec3 &v1, const Vec3 &v2) { @@ -187,18 +187,18 @@ void Vec3::transformMat3(const Vec3 &v, const Mat3 &m) { const float ix = v.x; const float iy = v.y; const float iz = v.z; - x = ix * m.m[0] + iy * m.m[3] + iz * m.m[6]; - y = ix * m.m[1] + iy * m.m[4] + iz * m.m[7]; - z = ix * m.m[2] + iy * m.m[5] + iz * m.m[8]; + x = ix * m.m[0] + iy * m.m[3] + iz * m.m[6]; + y = ix * m.m[1] + iy * m.m[4] + iz * m.m[7]; + z = ix * m.m[2] + iy * m.m[5] + iz * m.m[8]; } void Vec3::transformMat4(const Vec3 &v, const Mat4 &m) { alignas(16) float tmp[4] = {v.x, v.y, v.z, 1.0F}; MathUtil::transformVec4(m.m, tmp, tmp); float rhw = math::IsNotEqualF(tmp[3], 0.0F) ? 1 / tmp[3] : 1; - x = tmp[0] * rhw; - y = tmp[1] * rhw; - z = tmp[2] * rhw; + x = tmp[0] * rhw; + y = tmp[1] * rhw; + z = tmp[2] * rhw; } void Vec3::transformMat4(const Vec3 &v, const Mat4 &m, Vec3 *dst) { @@ -206,14 +206,14 @@ void Vec3::transformMat4(const Vec3 &v, const Mat4 &m, Vec3 *dst) { } void Vec3::transformMat4Normal(const Vec3 &v, const Mat4 &m, Vec3 *dst) { - float x = v.x; - float y = v.y; - float z = v.z; + float x = v.x; + float y = v.y; + float z = v.z; float rhw = m.m[3] * x + m.m[7] * y + m.m[11] * z; - rhw = rhw != 0.0F ? std::abs(1.0F / rhw) : 1.0F; - dst->x = (m.m[0] * x + m.m[4] * y + m.m[8] * z) * rhw; - dst->y = (m.m[1] * x + m.m[5] * y + m.m[9] * z) * rhw; - dst->z = (m.m[2] * x + m.m[6] * y + m.m[10] * z) * rhw; + rhw = rhw != 0.0F ? std::abs(1.0F / rhw) : 1.0F; + dst->x = (m.m[0] * x + m.m[4] * y + m.m[8] * z) * rhw; + dst->y = (m.m[1] * x + m.m[5] * y + m.m[9] * z) * rhw; + dst->z = (m.m[2] * x + m.m[6] * y + m.m[10] * z) * rhw; } void Vec3::transformQuat(const Quaternion &q) { diff --git a/native/cocos/math/Vec4.cpp b/native/cocos/math/Vec4.cpp index b8f31cbf11..a200e30735 100644 --- a/native/cocos/math/Vec4.cpp +++ b/native/cocos/math/Vec4.cpp @@ -58,7 +58,7 @@ Vec4::Vec4(const Vec4 ©) { Vec4 Vec4::fromColor(unsigned int color) { float components[4]; - int componentIndex = 0; + int componentIndex = 0; for (int i = 3; i >= 0; --i) { uint32_t component = (color >> i * 8) & 0x000000ff; @@ -306,8 +306,8 @@ void Vec4::lerp(const Vec4 &a, const Vec4 &b, float t, Vec4 *dst) { dst->w = a.w + t * (b.w - a.w); } -const Vec4 Vec4::ZERO = Vec4(0.0F, 0.0F, 0.0F, 0.0F); -const Vec4 Vec4::ONE = Vec4(1.0F, 1.0F, 1.0F, 1.0F); +const Vec4 Vec4::ZERO = Vec4(0.0F, 0.0F, 0.0F, 0.0F); +const Vec4 Vec4::ONE = Vec4(1.0F, 1.0F, 1.0F, 1.0F); const Vec4 Vec4::UNIT_X = Vec4(1.0F, 0.0F, 0.0F, 0.0F); const Vec4 Vec4::UNIT_Y = Vec4(0.0F, 1.0F, 0.0F, 0.0F); const Vec4 Vec4::UNIT_Z = Vec4(0.0F, 0.0F, 1.0F, 0.0F); diff --git a/native/cocos/math/Vertex.cpp b/native/cocos/math/Vertex.cpp index 29a7d2961a..567430dff7 100644 --- a/native/cocos/math/Vertex.cpp +++ b/native/cocos/math/Vertex.cpp @@ -41,7 +41,7 @@ void ccVertexLineToPolygon(const ccstd::vector &points, float stroke, unsi unsigned int nuPointsMinus = nuPoints - 1; for (unsigned int i = offset; i < nuPoints; i++) { - idx = i * 2; + idx = i * 2; Vec2 p1 = points[i]; Vec2 perpVector; @@ -76,7 +76,7 @@ void ccVertexLineToPolygon(const ccstd::vector &points, float stroke, unsi // Validate vertexes offset = (offset == 0) ? 0 : offset - 1; for (unsigned int i = offset; i < nuPointsMinus; i++) { - idx = i * 2; + idx = i * 2; const unsigned int idx1 = idx + 2; Vec2 p1 = (*vertices)[idx]; @@ -94,7 +94,7 @@ void ccVertexLineToPolygon(const ccstd::vector &points, float stroke, unsi } if (fixVertex) { - (*vertices)[idx1] = p4; + (*vertices)[idx1] = p4; (*vertices)[idx1 + 1] = p3; } } @@ -128,12 +128,12 @@ bool ccVertexLineIntersect(float ax, float ay, // Rotate the system so that point B is on the positive X axis. theCos = bx / distAB; theSin = by / distAB; - newX = cx * theCos + cy * theSin; - cy = cy * theCos - cx * theSin; - cx = newX; - newX = dx * theCos + dy * theSin; - dy = dy * theCos - dx * theSin; - dx = newX; + newX = cx * theCos + cy * theSin; + cy = cy * theCos - cx * theSin; + cx = newX; + newX = dx * theCos + dy * theSin; + dy = dy * theCos - dx * theSin; + dx = newX; // FAIL: Lines are parallel. if (cy == dy) { diff --git a/native/cocos/network/Downloader-curl.cpp b/native/cocos/network/Downloader-curl.cpp index 4136a47d69..cf103ba3c3 100644 --- a/native/cocos/network/Downloader-curl.cpp +++ b/native/cocos/network/Downloader-curl.cpp @@ -93,15 +93,15 @@ public: } // file task - _fileName = filename; + _fileName = filename; _tempFileName = filename; _tempFileName.append(tempSuffix); if (_sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName)) { // there is another task uses this storage path - _errCode = DownloadTask::ERROR_FILE_OP_FAILED; + _errCode = DownloadTask::ERROR_FILE_OP_FAILED; _errCodeInternal = 0; - _errDescription = "More than one download file task write to same file:"; + _errDescription = "More than one download file task write to same file:"; _errDescription.append(_tempFileName); return false; } @@ -111,22 +111,22 @@ public: bool ret = false; do { ccstd::string dir; - size_t found = _tempFileName.find_last_of("/\\"); + size_t found = _tempFileName.find_last_of("/\\"); if (found == ccstd::string::npos) { - _errCode = DownloadTask::ERROR_INVALID_PARAMS; + _errCode = DownloadTask::ERROR_INVALID_PARAMS; _errCodeInternal = 0; - _errDescription = "Can't find dirname in storagePath."; + _errDescription = "Can't find dirname in storagePath."; break; } // ensure directory is exist auto util = FileUtils::getInstance(); - dir = _tempFileName.substr(0, found + 1); + dir = _tempFileName.substr(0, found + 1); if (false == util->isDirectoryExist(dir)) { if (false == util->createDirectory(dir)) { - _errCode = DownloadTask::ERROR_FILE_OP_FAILED; + _errCode = DownloadTask::ERROR_FILE_OP_FAILED; _errCodeInternal = 0; - _errDescription = "Can't create dir:"; + _errDescription = "Can't create dir:"; _errDescription.append(dir); break; } @@ -135,9 +135,9 @@ public: // open file _fp = fopen(util->getSuitableFOpen(_tempFileName).c_str(), "ab"); if (nullptr == _fp) { - _errCode = DownloadTask::ERROR_FILE_OP_FAILED; + _errCode = DownloadTask::ERROR_FILE_OP_FAILED; _errCodeInternal = 0; - _errDescription = "Can't open file:"; + _errDescription = "Can't open file:"; _errDescription.append(_tempFileName); } ret = true; @@ -153,19 +153,19 @@ public: void setErrorProc(int code, int codeInternal, const char *desc) { std::lock_guard lock(_mutex); - _errCode = code; + _errCode = code; _errCodeInternal = codeInternal; - _errDescription = desc; + _errDescription = desc; } size_t writeDataProc(unsigned char *buffer, size_t size, size_t count) { std::lock_guard lock(_mutex); - size_t ret = 0; + size_t ret = 0; if (_fp) { ret = fwrite(buffer, size, count, _fp); } else { - ret = size * count; - auto cap = _buf.capacity(); + ret = size * count; + auto cap = _buf.capacity(); auto bufSize = _buf.size(); if (cap < bufSize + ret) { _buf.reserve(bufSize * 2); @@ -186,8 +186,8 @@ private: std::mutex _mutex; // header info - bool _acceptRanges; - bool _headerAchieved; + bool _acceptRanges; + bool _headerAchieved; int64_t _totalBytesExpected; ccstd::string _header; // temp buffer for receive header string, only used in thread proc @@ -197,29 +197,29 @@ private: int64_t _totalBytesReceived; // error - int _errCode; - int _errCodeInternal; + int _errCode; + int _errCodeInternal; ccstd::string _errDescription; // for saving data - ccstd::string _fileName; - ccstd::string _tempFileName; + ccstd::string _fileName; + ccstd::string _tempFileName; ccstd::vector _buf; - FILE * _fp; + FILE *_fp; void _initInternal() { - _acceptRanges = (false); - _headerAchieved = (false); - _bytesReceived = (0); + _acceptRanges = (false); + _headerAchieved = (false); + _bytesReceived = (0); _totalBytesReceived = (0); _totalBytesExpected = (0); - _errCode = (DownloadTask::ERROR_NO_ERROR); - _errCodeInternal = (CURLE_OK); + _errCode = (DownloadTask::ERROR_NO_ERROR); + _errCodeInternal = (CURLE_OK); _header.resize(0); _header.reserve(384); // pre alloc header string buffer } }; -int DownloadTaskCURL::_sSerialId; +int DownloadTaskCURL::_sSerialId; ccstd::set DownloadTaskCURL::_sStoragePathSet; typedef std::pair, DownloadTaskCURL *> TaskWrapper; @@ -305,7 +305,7 @@ private: // the curl handle destroyed in _threadProc // handle inited for get header void _initCurlHandleProc(CURL *handle, TaskWrapper &wrapper, bool forContent = false) { - const DownloadTask & task = *wrapper.first; + const DownloadTask &task = *wrapper.first; const DownloadTaskCURL *coTask = wrapper.second; // set url @@ -346,7 +346,7 @@ private: } static const long LOW_SPEED_LIMIT = 1; - static const long LOW_SPEED_TIME = 10; + static const long LOW_SPEED_TIME = 10; curl_easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, LOW_SPEED_LIMIT); curl_easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, LOW_SPEED_TIME); @@ -363,10 +363,10 @@ private: // get header info, if success set handle to content download state bool _getHeaderInfoProc(CURL *handle, TaskWrapper &wrapper) { DownloadTaskCURL &coTask = *wrapper.second; - CURLcode rc = CURLE_OK; + CURLcode rc = CURLE_OK; do { long httpResponseCode = 0; - rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode); + rc = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpResponseCode); if (CURLE_OK != rc) { break; } @@ -379,7 +379,7 @@ private: // curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &effectiveUrl); // curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &contentType); double contentLen = 0; - rc = curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLen); + rc = curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &contentLen); if (CURLE_OK != rc) { break; } @@ -395,7 +395,7 @@ private: // set header info to coTask std::lock_guard lock(coTask._mutex); coTask._totalBytesExpected = (int64_t)contentLen; - coTask._acceptRanges = acceptRanges; + coTask._acceptRanges = acceptRanges; if (acceptRanges && fileSize > 0) { coTask._totalBytesReceived = fileSize; } @@ -411,15 +411,15 @@ private: void _threadProc() { DLLOG("++++DownloaderCURL::Impl::_threadProc begin %p", this); // the holder prevent DownloaderCURL::Impl class instance be destruct in main thread - auto holder = this->shared_from_this(); - auto thisThreadId = std::this_thread::get_id(); + auto holder = this->shared_from_this(); + auto thisThreadId = std::this_thread::get_id(); uint32_t countOfMaxProcessingTasks = this->hints.countOfMaxProcessingTasks; // init curl content - CURLM * curlmHandle = curl_multi_init(); + CURLM *curlmHandle = curl_multi_init(); ccstd::unordered_map coTaskMap; - int runningHandles = 0; - CURLMcode mcode = CURLM_OK; - int rc = 0; // select return code + int runningHandles = 0; + CURLMcode mcode = CURLM_OK; + int rc = 0; // select return code do { // check the thread should exit or not @@ -444,7 +444,7 @@ private: fd_set fdread; fd_set fdwrite; fd_set fdexcep; - int maxfd = -1; + int maxfd = -1; FD_ZERO(&fdread); FD_ZERO(&fdwrite); @@ -462,7 +462,7 @@ private: } else { struct timeval timeout; - timeout.tv_sec = timeoutMS / 1000; + timeout.tv_sec = timeoutMS / 1000; timeout.tv_usec = (timeoutMS % 1000) * 1000; rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); @@ -485,10 +485,10 @@ private: struct CURLMsg *m; do { int msgq = 0; - m = curl_multi_info_read(curlmHandle, &msgq); + m = curl_multi_info_read(curlmHandle, &msgq); if (m && (m->msg == CURLMSG_DONE)) { - CURL * curlHandle = m->easy_handle; - CURLcode errCode = m->data.result; + CURL *curlHandle = m->easy_handle; + CURLcode errCode = m->data.result; TaskWrapper wrapper = coTaskMap[curlHandle]; @@ -613,9 +613,9 @@ private: DLLOG("----DownloaderCURL::Impl::_threadProc end"); } - std::thread _thread; + std::thread _thread; ccstd::deque _requestQueue; - ccstd::set _processSet; + ccstd::set _processSet; ccstd::deque _finishedQueue; std::mutex _threadMutex; @@ -631,11 +631,11 @@ DownloaderCURL::DownloaderCURL(const DownloaderHints &hints) _currTask(nullptr) { DLLOG("Construct DownloaderCURL %p", this); _impl->hints = hints; - _scheduler = CC_CURRENT_ENGINE()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); _transferDataToBuffer = [this](void *buf, int64_t len) -> int64_t { - DownloadTaskCURL &coTask = *_currTask; - int64_t dataLen = coTask._buf.size(); + DownloadTaskCURL &coTask = *_currTask; + int64_t dataLen = coTask._buf.size(); if (len < dataLen) { return 0; } @@ -694,8 +694,8 @@ void DownloaderCURL::_onSchedule(float) { // update processing tasks _impl->getProcessTasks(tasks); for (auto &wrapper : tasks) { - const DownloadTask &task = *wrapper.first; - DownloadTaskCURL & coTask = *wrapper.second; + const DownloadTask &task = *wrapper.first; + DownloadTaskCURL &coTask = *wrapper.second; std::lock_guard lock(coTask._mutex); if (coTask._bytesReceived) { @@ -705,7 +705,7 @@ void DownloaderCURL::_onSchedule(float) { coTask._totalBytesReceived, coTask._totalBytesExpected, _transferDataToBuffer); - _currTask = nullptr; + _currTask = nullptr; coTask._bytesReceived = 0; } } @@ -720,8 +720,8 @@ void DownloaderCURL::_onSchedule(float) { } for (auto &wrapper : tasks) { - const DownloadTask &task = *wrapper.first; - DownloadTaskCURL & coTask = *wrapper.second; + const DownloadTask &task = *wrapper.first; + DownloadTaskCURL &coTask = *wrapper.second; // if there is bytesReceived, call progress update first if (coTask._bytesReceived) { @@ -732,7 +732,7 @@ void DownloaderCURL::_onSchedule(float) { coTask._totalBytesExpected, _transferDataToBuffer); coTask._bytesReceived = 0; - _currTask = nullptr; + _currTask = nullptr; } // if file task, close file handle and rename file if needed @@ -748,9 +748,9 @@ void DownloaderCURL::_onSchedule(float) { // if file already exist, remove it if (util->isFileExist(coTask._fileName)) { if (false == util->removeFile(coTask._fileName)) { - coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED; + coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED; coTask._errCodeInternal = 0; - coTask._errDescription = "Can't remove old file: "; + coTask._errDescription = "Can't remove old file: "; coTask._errDescription.append(coTask._fileName); break; } @@ -763,9 +763,9 @@ void DownloaderCURL::_onSchedule(float) { break; } // failed - coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED; + coTask._errCode = DownloadTask::ERROR_FILE_OP_FAILED; coTask._errCodeInternal = 0; - coTask._errDescription = "Can't renamefile from: "; + coTask._errDescription = "Can't renamefile from: "; coTask._errDescription.append(coTask._tempFileName); coTask._errDescription.append(" to: "); coTask._errDescription.append(coTask._fileName); diff --git a/native/cocos/network/Downloader-curl.h b/native/cocos/network/Downloader-curl.h index 3d2980a522..26df6a42a8 100644 --- a/native/cocos/network/Downloader-curl.h +++ b/native/cocos/network/Downloader-curl.h @@ -51,12 +51,12 @@ protected: std::shared_ptr _impl; // for transfer data on schedule - DownloadTaskCURL * _currTask; // temp ref + DownloadTaskCURL *_currTask; // temp ref std::function _transferDataToBuffer; // scheduler for update processing and finished task in main schedule - void _onSchedule(float); - ccstd::string _schedulerKey; + void _onSchedule(float); + ccstd::string _schedulerKey; std::weak_ptr _scheduler; }; diff --git a/native/cocos/network/Downloader-java.cpp b/native/cocos/network/Downloader-java.cpp index 2dc7d194b1..b0576be493 100644 --- a/native/cocos/network/Downloader-java.cpp +++ b/native/cocos/network/Downloader-java.cpp @@ -45,7 +45,7 @@ #define JNI_DOWNLOADER(FUNC) JNI_METHOD1(ORG_DOWNLOADER_CLASS_NAME, FUNC) ccstd::unordered_map sDownloaderMap; -std::mutex sDownloaderMutex; +std::mutex sDownloaderMutex; static void insertDownloaderJava(int id, cc::network::DownloaderJava *downloaderPtr) { std::lock_guard guard(sDownloaderMutex); @@ -62,7 +62,7 @@ static void eraseDownloaderJava(int id) { */ static cc::network::DownloaderJava *findDownloaderJava(int id) { std::lock_guard guard(sDownloaderMutex); - auto iter = sDownloaderMap.find(id); + auto iter = sDownloaderMap.find(id); if (sDownloaderMap.end() == iter) { return nullptr; } @@ -72,7 +72,7 @@ static cc::network::DownloaderJava *findDownloaderJava(int id) { namespace cc { namespace network { -static int sTaskCounter = 0; +static int sTaskCounter = 0; static int sDownloaderCounter = 0; struct DownloadTaskAndroid : public IDownloadTask { @@ -84,7 +84,7 @@ struct DownloadTaskAndroid : public IDownloadTask { DLLOG("Destruct DownloadTaskAndroid: %p", this); } - int id; + int id; std::shared_ptr task; // reference to DownloadTask, when task finish, release }; @@ -146,12 +146,12 @@ IDownloadTask *DownloaderJava::createCoTask(std::shared_ptr JCLS_DOWNLOADER, "createTask", "(" JARG_DOWNLOADER "I" JARG_STR JARG_STR "[" JARG_STR ")V")) { - jclass jclassString = methodInfo.env->FindClass("java/lang/String"); - jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str()); - jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str()); - jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size() * 2, jclassString, nullptr); - const ccstd::unordered_map &headMap = task->header; - int index = 0; + jclass jclassString = methodInfo.env->FindClass("java/lang/String"); + jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str()); + jstring jstrPath = methodInfo.env->NewStringUTF(task->storagePath.c_str()); + jobjectArray jarrayHeader = methodInfo.env->NewObjectArray(task->header.size() * 2, jclassString, nullptr); + const ccstd::unordered_map &headMap = task->header; + int index = 0; for (const auto &it : headMap) { methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it.first.c_str())); methodInfo.env->SetObjectArrayElement(jarrayHeader, index++, methodInfo.env->NewStringUTF(it.second.c_str())); @@ -214,7 +214,7 @@ void DownloaderJava::onProcessImpl(int taskId, int64_t dl, int64_t dlNow, int64_ DLLOG("DownloaderJava::onProgress can't find task with id: %d", taskId); return; } - DownloadTaskAndroid * coTask = iter->second; + DownloadTaskAndroid *coTask = iter->second; std::function transferDataToBuffer; onTaskProgress(*coTask->task, dl, dlNow, dlTotal, transferDataToBuffer); } @@ -227,7 +227,7 @@ void DownloaderJava::onFinishImpl(int taskId, int errCode, const char *errStr, c return; } DownloadTaskAndroid *coTask = iter->second; - ccstd::string str = (errStr ? errStr : ""); + ccstd::string str = (errStr ? errStr : ""); _taskMap.erase(iter); onTaskFinish(*coTask->task, errStr ? DownloadTask::ERROR_IMPL_INTERNAL : DownloadTask::ERROR_NO_ERROR, @@ -256,11 +256,11 @@ JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnProgress)(JNIEnv * /*env*/, jclass } JNIEXPORT void JNICALL JNI_DOWNLOADER(nativeOnFinish)(JNIEnv *env, jclass /*clazz*/, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { - ccstd::string errStrTmp; + ccstd::string errStrTmp; ccstd::vector dataTmp; if (errStr) { const char *nativeErrStr = env->GetStringUTFChars(errStr, JNI_FALSE); - errStrTmp = nativeErrStr; + errStrTmp = nativeErrStr; env->ReleaseStringUTFChars(errStr, nativeErrStr); } if (data && env->GetArrayLength(data) > 0) { diff --git a/native/cocos/network/Downloader-java.h b/native/cocos/network/Downloader-java.h index 41eb80024e..67c84f8819 100644 --- a/native/cocos/network/Downloader-java.h +++ b/native/cocos/network/Downloader-java.h @@ -49,8 +49,8 @@ public: void onFinishImpl(int taskId, int errCode, const char *errStr, const ccstd::vector &data); protected: - int _id; - _jobject * _impl; + int _id; + _jobject *_impl; ccstd::unordered_map _taskMap; }; } // namespace network diff --git a/native/cocos/network/Downloader.cpp b/native/cocos/network/Downloader.cpp index ed383b4cb4..01c909d469 100644 --- a/native/cocos/network/Downloader.cpp +++ b/native/cocos/network/Downloader.cpp @@ -71,21 +71,21 @@ Downloader::Downloader() { Downloader::Downloader(const DownloaderHints &hints) { DLLOG("Construct Downloader %p", this); - _impl = std::make_unique(hints); + _impl = std::make_unique(hints); _impl->onTaskProgress = [this](const DownloadTask &task, - int64_t bytesReceived, - int64_t totalBytesReceived, - int64_t totalBytesExpected, + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpected, std::function & /*transferDataToBuffer*/) { if (onTaskProgress) { onTaskProgress(task, bytesReceived, totalBytesReceived, totalBytesExpected); } }; - _impl->onTaskFinish = [this](const DownloadTask & task, - int errorCode, - int errorCodeInternal, - const ccstd::string & errorStr, + _impl->onTaskFinish = [this](const DownloadTask &task, + int errorCode, + int errorCodeInternal, + const ccstd::string &errorStr, const ccstd::vector &data) { if (DownloadTask::ERROR_NO_ERROR != errorCode) { if (onTaskError) { @@ -113,7 +113,7 @@ Downloader::~Downloader() { } std::shared_ptr Downloader::createDownloadDataTask(const ccstd::string &srcUrl, const ccstd::string &identifier /* = ""*/) { - auto * iTask = ccnew DownloadTask(); + auto *iTask = ccnew DownloadTask(); std::shared_ptr task(iTask); do { iTask->requestURL = srcUrl; @@ -131,17 +131,17 @@ std::shared_ptr Downloader::createDownloadDataTask(const ccs return task; } -std::shared_ptr Downloader::createDownloadFileTask(const ccstd::string & srcUrl, - const ccstd::string & storagePath, +std::shared_ptr Downloader::createDownloadFileTask(const ccstd::string &srcUrl, + const ccstd::string &storagePath, const ccstd::unordered_map &header, - const ccstd::string & identifier /* = ""*/) { - auto * iTask = ccnew DownloadTask(); + const ccstd::string &identifier /* = ""*/) { + auto *iTask = ccnew DownloadTask(); std::shared_ptr task(iTask); do { - iTask->requestURL = srcUrl; + iTask->requestURL = srcUrl; iTask->storagePath = storagePath; - iTask->identifier = identifier; - iTask->header = header; + iTask->identifier = identifier; + iTask->header = header; if (0 == srcUrl.length() || 0 == storagePath.length()) { if (onTaskError) { onTaskError(*task, DownloadTask::ERROR_INVALID_PARAMS, 0, "URL or storage path is empty."); diff --git a/native/cocos/network/Downloader.h b/native/cocos/network/Downloader.h index 2887031f3a..603f23f457 100644 --- a/native/cocos/network/Downloader.h +++ b/native/cocos/network/Downloader.h @@ -43,15 +43,15 @@ class Downloader; class CC_DLL DownloadTask final { public: - const static int ERROR_NO_ERROR = 0; + const static int ERROR_NO_ERROR = 0; const static int ERROR_INVALID_PARAMS = -1; const static int ERROR_FILE_OP_FAILED = -2; - const static int ERROR_IMPL_INTERNAL = -3; - const static int ERROR_ABORT = -4; + const static int ERROR_IMPL_INTERNAL = -3; + const static int ERROR_ABORT = -4; - ccstd::string identifier; - ccstd::string requestURL; - ccstd::string storagePath; + ccstd::string identifier; + ccstd::string requestURL; + ccstd::string storagePath; ccstd::unordered_map header; DownloadTask(); @@ -63,8 +63,8 @@ private: }; struct CC_DLL DownloaderHints { - uint32_t countOfMaxProcessingTasks; - uint32_t timeoutInSeconds; + uint32_t countOfMaxProcessingTasks; + uint32_t timeoutInSeconds; ccstd::string tempFileNameSuffix; }; @@ -74,34 +74,34 @@ public: explicit Downloader(const DownloaderHints &hints); ~Downloader(); - std::function &data)> onDataTaskSuccess; std::function onFileTaskSuccess; std::function + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpected)> onTaskProgress; - std::function onTaskError; void setOnFileTaskSuccess(const std::function &callback) { onFileTaskSuccess = callback; }; void setOnTaskProgress(const std::function &callback) { onTaskProgress = callback; }; + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpected)> &callback) { onTaskProgress = callback; }; - void setOnTaskError(const std::function &callback) { onTaskError = callback; }; std::shared_ptr createDownloadDataTask(const ccstd::string &srcUrl, const ccstd::string &identifier = ""); diff --git a/native/cocos/network/DownloaderImpl.h b/native/cocos/network/DownloaderImpl.h index 56b6ab953c..a023f141d9 100644 --- a/native/cocos/network/DownloaderImpl.h +++ b/native/cocos/network/DownloaderImpl.h @@ -55,17 +55,17 @@ class IDownloaderImpl { public: virtual ~IDownloaderImpl() {} - std::function &transferDataToBuffer)> onTaskProgress; - std::function &data)> onTaskFinish; diff --git a/native/cocos/network/HttpAsynConnection-apple.m b/native/cocos/network/HttpAsynConnection-apple.m index eeb41cc6ca..b6962f74fd 100755 --- a/native/cocos/network/HttpAsynConnection-apple.m +++ b/native/cocos/network/HttpAsynConnection-apple.m @@ -24,7 +24,7 @@ #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) || (CC_PLATFORM == CC_PLATFORM_MAC_IOS) -#import "network/HttpAsynConnection-apple.h" + #import "network/HttpAsynConnection-apple.h" @interface HttpAsynConnection () @@ -61,42 +61,41 @@ } - (void)startRequest:(NSURLRequest *)request { -#ifdef CC_DEBUG - // NSLog(@"Starting to load %@", srcURL); -#endif - + #ifdef CC_DEBUG + // NSLog(@"Starting to load %@", srcURL); + #endif + finish = false; - + self.responseData = [NSMutableData data]; getDataTime = 0; - + self.responseError = nil; self.connError = nil; - + session = [NSURLSession sharedSession]; - - task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * _Nullable error) { - - if(error != nil) { - self.connError = error; - finish = true; - return; - } - if(response != nil) { -#ifdef CC_DEBUG - // NSLog(@"Received response from request to url %@", srcURL); -#endif - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - //NSLog(@"All headers = %@", [httpResponse allHeaderFields]); - self.responseHeader = [httpResponse allHeaderFields]; - - responseCode = httpResponse.statusCode; - self.statusString = [NSHTTPURLResponse localizedStringForStatusCode:responseCode]; - if (responseCode == 200) - self.statusString = @"OK"; - - /*The individual values of the numeric status codes defined for HTTP/1.1 + + task = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *_Nullable error) { + if (error != nil) { + self.connError = error; + finish = true; + return; + } + if (response != nil) { + #ifdef CC_DEBUG + // NSLog(@"Received response from request to url %@", srcURL); + #endif + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; + //NSLog(@"All headers = %@", [httpResponse allHeaderFields]); + self.responseHeader = [httpResponse allHeaderFields]; + + responseCode = httpResponse.statusCode; + self.statusString = [NSHTTPURLResponse localizedStringForStatusCode:responseCode]; + if (responseCode == 200) + self.statusString = @"OK"; + + /*The individual values of the numeric status codes defined for HTTP/1.1 | "200" ; OK | "201" ; Created | "202" ; Accepted @@ -105,22 +104,22 @@ | "205" ; Reset Content | "206" ; Partial Content */ - if (responseCode < 200 || responseCode >= 300) { // something went wrong, abort the whole thing - self.responseError = [NSError errorWithDomain:@"CCBackendDomain" - code:responseCode - userInfo:@{NSLocalizedDescriptionKey : @"Bad HTTP Response Code"}]; - } - - [responseData setLength:0]; - } - - if (data != nil) { - [responseData appendData:data]; - getDataTime++; - } - - finish = true; - }]; + if (responseCode < 200 || responseCode >= 300) { // something went wrong, abort the whole thing + self.responseError = [NSError errorWithDomain:@"CCBackendDomain" + code:responseCode + userInfo:@{NSLocalizedDescriptionKey : @"Bad HTTP Response Code"}]; + } + + [responseData setLength:0]; + } + + if (data != nil) { + [responseData appendData:data]; + getDataTime++; + } + + finish = true; + }]; [task resume]; } @@ -133,16 +132,16 @@ NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath]; CFDataRef certDataRef = (CFDataRef)certData; SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef); - + //Establish a chain of trust anchored on our bundled certificate CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL); SecTrustRef serverTrust = protectionSpace.serverTrust; SecTrustSetAnchorCertificates(serverTrust, certArrayRef); - + //Verify that trust SecTrustResultType trustResult; SecTrustEvaluate(serverTrust, &trustResult); - + if (trustResult == kSecTrustResultRecoverableTrustFailure) { CFDataRef errDataRef = SecTrustCopyExceptions(serverTrust); SecTrustSetExceptions(serverTrust, errDataRef); @@ -161,10 +160,10 @@ } - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler { + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *_Nullable credential))completionHandler { id sender = challenge.sender; NSURLProtectionSpace *protectionSpace = challenge.protectionSpace; - + //Should server trust client? if ([self shouldTrustProtectionSpace:protectionSpace]) { SecTrustRef trust = [protectionSpace serverTrust]; diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index d89e72d7f3..43f5faf575 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -50,7 +50,6 @@ void HttpClient::networkThread() { increaseThreadCount(); while (true) @autoreleasepool { - HttpRequest *request; // step 1: send http request if the requestQueue isn't empty @@ -340,7 +339,7 @@ HttpClient::HttpClient() _requestSentinel = ccnew HttpRequest(); _requestSentinel->addRef(); memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE); - _scheduler = CC_CURRENT_ENGINE()->getScheduler(); + _scheduler = CC_CURRENT_ENGINE()->getScheduler(); increaseThreadCount(); } diff --git a/native/cocos/network/HttpClient-java.cpp b/native/cocos/network/HttpClient-java.cpp index 44ef77d147..82eafc089f 100644 --- a/native/cocos/network/HttpClient-java.cpp +++ b/native/cocos/network/HttpClient-java.cpp @@ -46,18 +46,18 @@ namespace cc { namespace network { -using HttpRequestHeaders = ccstd::vector; +using HttpRequestHeaders = ccstd::vector; using HttpRequestHeadersIter = HttpRequestHeaders::iterator; -using HttpCookies = ccstd::vector; -using HttpCookiesIter = HttpCookies::iterator; +using HttpCookies = ccstd::vector; +using HttpCookiesIter = HttpCookies::iterator; static HttpClient *gHttpClient = nullptr; // pointer to singleton struct CookiesInfo { ccstd::string domain; - bool tailmatch; + bool tailmatch; ccstd::string path; - bool secure; + bool secure; ccstd::string key; ccstd::string value; ccstd::string expires; @@ -138,7 +138,7 @@ public: } int connect() { // NOLINT - int suc = 0; + int suc = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -169,7 +169,7 @@ public: } int getResponseCode() { // NOLINT - int responseCode = 0; + int responseCode = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -186,7 +186,7 @@ public: } char *getResponseMessage() { // NOLINT - char * message = nullptr; + char *message = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -213,8 +213,8 @@ public: "sendRequest", "(Ljava/net/HttpURLConnection;[B)V")) { jbyteArray bytearray; - ssize_t dataSize = request->getRequestDataSize(); - bytearray = methodInfo.env->NewByteArray(dataSize); + ssize_t dataSize = request->getRequestDataSize(); + bytearray = methodInfo.env->NewByteArray(dataSize); methodInfo.env->SetByteArrayRegion(bytearray, 0, dataSize, reinterpret_cast(request->getRequestData())); methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, bytearray); @@ -248,7 +248,7 @@ public: } char *getResponseHeaders() { // NOLINT - char * headers = nullptr; + char *headers = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -273,7 +273,7 @@ public: return nullptr; } - char * content = nullptr; + char *content = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -295,14 +295,14 @@ public: } char *getResponseHeaderByKey(const char *key) { - char * value = nullptr; + char *value = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, "getResponseHeaderByKey", "(Ljava/net/HttpURLConnection;Ljava/lang/String;)Ljava/lang/String;")) { jstring jstrKey = methodInfo.env->NewStringUTF(key); - jobject jObj = methodInfo.env->CallStaticObjectMethod( + jobject jObj = methodInfo.env->CallStaticObjectMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey); value = getBufferFromJString(static_cast(jObj), methodInfo.env); ccDeleteLocalRef(methodInfo.env, jstrKey); @@ -318,14 +318,14 @@ public: } int getResponseHeaderByKeyInt(const char *key) { - int contentLength = 0; + int contentLength = 0; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, "getResponseHeaderByKeyInt", "(Ljava/net/HttpURLConnection;Ljava/lang/String;)I")) { jstring jstrKey = methodInfo.env->NewStringUTF(key); - contentLength = methodInfo.env->CallStaticIntMethod( + contentLength = methodInfo.env->CallStaticIntMethod( methodInfo.classID, methodInfo.methodID, _httpURLConnection, jstrKey); ccDeleteLocalRef(methodInfo.env, jstrKey); ccDeleteLocalRef(methodInfo.env, methodInfo.classID); @@ -337,7 +337,7 @@ public: } char *getResponseHeaderByIdx(int idx) { - char * header = nullptr; + char *header = nullptr; JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HTTPCLIENT, @@ -376,9 +376,9 @@ private: JCLS_HTTPCLIENT, "createHttpURLConnection", "(Ljava/lang/String;)Ljava/net/HttpURLConnection;")) { - _url = url; - jstring jurl = methodInfo.env->NewStringUTF(url.c_str()); - jobject jObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, jurl); + _url = url; + jstring jurl = methodInfo.env->NewStringUTF(url.c_str()); + jobject jObj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, jurl); _httpURLConnection = methodInfo.env->NewGlobalRef(jObj); ccDeleteLocalRef(methodInfo.env, jurl); ccDeleteLocalRef(methodInfo.env, jObj); @@ -423,7 +423,7 @@ private: cookiesVec.clear(); std::stringstream stream(cookiesInfo); - ccstd::string item; + ccstd::string item; while (std::getline(stream, item, '\n')) { cookiesVec.push_back(item); } @@ -444,9 +444,9 @@ private: continue; } - CookiesInfo co; - std::stringstream streamInfo(cookies); - ccstd::string item; + CookiesInfo co; + std::stringstream streamInfo(cookies); + ccstd::string item; ccstd::vector elems; while (std::getline(streamInfo, item, '\t')) { @@ -458,16 +458,16 @@ private: co.domain = co.domain.substr(1); } co.tailmatch = strcmp("TRUE", elems.at(1).c_str()) != 0; - co.path = elems.at(2); - co.secure = strcmp("TRUE", elems.at(3).c_str()) != 0; - co.expires = elems.at(4); - co.key = elems.at(5); - co.value = elems.at(6); + co.path = elems.at(2); + co.secure = strcmp("TRUE", elems.at(3).c_str()) != 0; + co.expires = elems.at(4); + co.key = elems.at(5); + co.value = elems.at(6); cookiesInfoVec.push_back(co); } ccstd::string sendCookiesInfo; - int cookiesCount = 0; + int cookiesCount = 0; for (auto &cookieInfo : cookiesInfoVec) { if (_url.find(cookieInfo.domain) != ccstd::string::npos) { ccstd::string keyValue = cookieInfo.key; @@ -544,8 +544,8 @@ private: return nullptr; } ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, jstr); - size_t size = strValue.size() + 1; - char * retVal = static_cast(malloc(size)); + size_t size = strValue.size() + 1; + char *retVal = static_cast(malloc(size)); if (retVal == nullptr) { return nullptr; } @@ -559,7 +559,7 @@ private: return 0; } - int len = env->GetArrayLength(jba); + int len = env->GetArrayLength(jba); auto *str = static_cast(malloc(sizeof(jbyte) * len)); env->GetByteArrayRegion(jba, 0, len, str); @@ -572,18 +572,18 @@ private: } private: // NOLINT(readability-redundant-access-specifiers) - HttpClient * _client; - jobject _httpURLConnection; + HttpClient *_client; + jobject _httpURLConnection; ccstd::string _requestmethod; ccstd::string _responseCookies; ccstd::string _cookieFileName; ccstd::string _url; - int _contentLength; + int _contentLength; }; // Process Response void HttpClient::processResponse(HttpResponse *response, char *responseMessage) { - auto * request = response->getHttpRequest(); + auto *request = response->getHttpRequest(); HttpRequest::Type requestType = request->getRequestType(); if (HttpRequest::Type::GET != requestType && @@ -596,7 +596,7 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) } int64_t responseCode = -1; - int retValue = 0; + int retValue = 0; HttpURLConnection urlConnection(this); if (!urlConnection.init(request)) { @@ -665,8 +665,8 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) free(cookiesInfo); //content len - int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length"); - char *contentInfo = urlConnection.getResponseContent(response); + int contentLength = urlConnection.getResponseHeaderByKeyInt("Content-Length"); + char *contentInfo = urlConnection.getResponseContent(response); if (nullptr != contentInfo) { auto *recvBuffer = static_cast *>(response->getResponseData()); recvBuffer->clear(); @@ -775,7 +775,7 @@ void HttpClient::networkThreadAlone(HttpRequest *request, HttpResponse *response // HttpClient implementation HttpClient *HttpClient::getInstance() { if (gHttpClient == nullptr) { - gHttpClient = ccnew HttpClient(); + gHttpClient = ccnew HttpClient(); } return gHttpClient; @@ -789,7 +789,7 @@ void HttpClient::destroyInstance() { CC_LOG_DEBUG("HttpClient::destroyInstance ..."); - auto *thiz = gHttpClient; + auto *thiz = gHttpClient; gHttpClient = nullptr; if (auto sche = thiz->_scheduler.lock()) { @@ -902,7 +902,7 @@ void HttpClient::dispatchResponseCallbacks() { _responseQueueMutex.unlock(); if (response) { - HttpRequest * request = response->getHttpRequest(); + HttpRequest *request = response->getHttpRequest(); const ccHttpRequestCallback &callback = request->getResponseCallback(); if (callback != nullptr) { diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index 3affb8a99b..a202ceb7ed 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -50,7 +50,7 @@ typedef size_t (*write_callback)(void *ptr, size_t size, size_t nmemb, void *str // Callback function used by libcurl for collect response data static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) { ccstd::vector *recvBuffer = (ccstd::vector *)stream; - size_t sizes = size * nmemb; + size_t sizes = size * nmemb; // add data to the end of recvBuffer // write data maybe called more than once in a single request @@ -62,7 +62,7 @@ static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) { // Callback function used by libcurl for collect header data static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream) { ccstd::vector *recvBuffer = (ccstd::vector *)stream; - size_t sizes = size * nmemb; + size_t sizes = size * nmemb; // add data to the end of recvBuffer // write data maybe called more than once in a single request @@ -272,35 +272,35 @@ public: //Process Get Request static int processGetTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { CURLRaii curl; - bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_FOLLOWLOCATION, true) && curl.perform(responseCode); + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_FOLLOWLOCATION, true) && curl.perform(responseCode); return ok ? 0 : 1; } //Process POST Request static int processPostTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { CURLRaii curl; - bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_POST, 1) && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_POST, 1) && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); return ok ? 0 : 1; } //Process PUT Request static int processPutTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { CURLRaii curl; - bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_CUSTOMREQUEST, "PUT") && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_CUSTOMREQUEST, "PUT") && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); return ok ? 0 : 1; } //Process HEAD Request static int processHeadTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { CURLRaii curl; - bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_NOBODY, "HEAD") && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_NOBODY, "HEAD") && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData()) && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize()) && curl.perform(responseCode); return ok ? 0 : 1; } //Process DELETE Request static int processDeleteTask(HttpClient *client, HttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream, char *errorBuffer) { CURLRaii curl; - bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_CUSTOMREQUEST, "DELETE") && curl.setOption(CURLOPT_FOLLOWLOCATION, true) && curl.perform(responseCode); + bool ok = curl.init(client, request, callback, stream, headerCallback, headerStream, errorBuffer) && curl.setOption(CURLOPT_CUSTOMREQUEST, "DELETE") && curl.setOption(CURLOPT_FOLLOWLOCATION, true) && curl.perform(responseCode); return ok ? 0 : 1; } @@ -320,7 +320,7 @@ void HttpClient::destroyInstance() { } CC_LOG_DEBUG("HttpClient::destroyInstance begin"); - auto thiz = _httpClient; + auto thiz = _httpClient; _httpClient = nullptr; if (auto sche = thiz->_scheduler.lock()) { @@ -434,7 +434,7 @@ void HttpClient::dispatchResponseCallbacks() { _responseQueueMutex.unlock(); if (response) { - HttpRequest * request = response->getHttpRequest(); + HttpRequest *request = response->getHttpRequest(); const ccHttpRequestCallback &callback = request->getResponseCallback(); if (callback != nullptr) { @@ -449,9 +449,9 @@ void HttpClient::dispatchResponseCallbacks() { // Process Response void HttpClient::processResponse(HttpResponse *response, char *responseMessage) { - auto request = response->getHttpRequest(); + auto request = response->getHttpRequest(); long responseCode = -1; - int retValue = 0; + int retValue = 0; // Process the request -> get response packet switch (request->getRequestType()) { diff --git a/native/cocos/network/HttpClient.h b/native/cocos/network/HttpClient.h index 03f9adc939..ff082afbbc 100644 --- a/native/cocos/network/HttpClient.h +++ b/native/cocos/network/HttpClient.h @@ -141,29 +141,29 @@ private: private: // NOLINT(readability-redundant-access-specifiers) bool _isInited; - int _timeoutForConnect; + int _timeoutForConnect; std::mutex _timeoutForConnectMutex; - int _timeoutForRead; + int _timeoutForRead; std::mutex _timeoutForReadMutex; - int _threadCount; + int _threadCount; std::mutex _threadCountMutex; std::weak_ptr _scheduler; - std::mutex _schedulerMutex; + std::mutex _schedulerMutex; RefVector _requestQueue; - std::mutex _requestQueueMutex; + std::mutex _requestQueueMutex; RefVector _responseQueue; - std::mutex _responseQueueMutex; + std::mutex _responseQueueMutex; ccstd::string _cookieFilename; - std::mutex _cookieFileMutex; + std::mutex _cookieFileMutex; ccstd::string _sslCaFilename; - std::mutex _sslCaFileMutex; + std::mutex _sslCaFileMutex; HttpCookie *_cookie; diff --git a/native/cocos/network/HttpCookie.cpp b/native/cocos/network/HttpCookie.cpp index 088c09afe7..a72ff5b209 100644 --- a/native/cocos/network/HttpCookie.cpp +++ b/native/cocos/network/HttpCookie.cpp @@ -37,7 +37,7 @@ void HttpCookie::readFile() { cookiesVec.clear(); std::stringstream stream(inString); - ccstd::string item; + ccstd::string item; while (std::getline(stream, item, '\n')) { cookiesVec.push_back(item); } @@ -61,10 +61,10 @@ void HttpCookie::readFile() { continue; } - CookiesInfo co; - std::stringstream streamInfo(cookie); + CookiesInfo co; + std::stringstream streamInfo(cookie); ccstd::vector elems; - ccstd::string elemsItem; + ccstd::string elemsItem; while (std::getline(streamInfo, elemsItem, '\t')) { elems.push_back(elemsItem); @@ -75,11 +75,11 @@ void HttpCookie::readFile() { co.domain = co.domain.substr(1); } co.tailmatch = (strcmp("TRUE", elems[1].c_str()) != 0); - co.path = elems[2]; - co.secure = (strcmp("TRUE", elems[3].c_str()) != 0); - co.expires = elems[4]; - co.name = elems[5]; - co.value = elems[6]; + co.path = elems[2]; + co.secure = (strcmp("TRUE", elems[3].c_str()) != 0); + co.expires = elems[4]; + co.name = elems[5]; + co.value = elems[6]; _cookies.push_back(co); } } diff --git a/native/cocos/network/HttpCookie.h b/native/cocos/network/HttpCookie.h index a492588529..5be98e4e47 100644 --- a/native/cocos/network/HttpCookie.h +++ b/native/cocos/network/HttpCookie.h @@ -33,9 +33,9 @@ struct CookiesInfo { ccstd::string domain; - bool tailmatch; + bool tailmatch; ccstd::string path; - bool secure; + bool secure; ccstd::string name; ccstd::string value; ccstd::string expires; @@ -49,11 +49,11 @@ public: void setCookieFileName(const ccstd::string &fileName); const ccstd::vector *getCookies() const; - const CookiesInfo * getMatchCookie(const ccstd::string &url) const; - void updateOrAddCookie(CookiesInfo *cookie); + const CookiesInfo *getMatchCookie(const ccstd::string &url) const; + void updateOrAddCookie(CookiesInfo *cookie); private: - ccstd::string _cookieFileName; + ccstd::string _cookieFileName; ccstd::vector _cookies; }; diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index 75ed3179e8..8180cb7d56 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -248,14 +248,14 @@ public: protected: // properties - Type _requestType{Type::UNKNOWN}; /// kHttpRequestGet, kHttpRequestPost or other enums - ccstd::string _url; /// target url that this request is sent to - ccstd::vector _requestData; /// used for POST - ccstd::string _tag; /// user defined tag, to identify different requests in response callback - ccHttpRequestCallback _callback; /// C++11 style callbacks - void * _userData{nullptr}; /// You can add your customed data here - ccstd::vector _headers; /// custom http headers - float _timeoutInSeconds{10.F}; + Type _requestType{Type::UNKNOWN}; /// kHttpRequestGet, kHttpRequestPost or other enums + ccstd::string _url; /// target url that this request is sent to + ccstd::vector _requestData; /// used for POST + ccstd::string _tag; /// user defined tag, to identify different requests in response callback + ccHttpRequestCallback _callback; /// C++11 style callbacks + void *_userData{nullptr}; /// You can add your customed data here + ccstd::vector _headers; /// custom http headers + float _timeoutInSeconds{10.F}; }; } // namespace network diff --git a/native/cocos/network/HttpResponse.h b/native/cocos/network/HttpResponse.h index 9c03fecca8..33fe5d2693 100644 --- a/native/cocos/network/HttpResponse.h +++ b/native/cocos/network/HttpResponse.h @@ -193,13 +193,13 @@ protected: bool initWithRequest(HttpRequest *request); // properties - HttpRequest * _pHttpRequest; /// the corresponding HttpRequest pointer who leads to this response - bool _succeed; /// to indicate if the http request is successful simply - ccstd::vector _responseData; /// the returned raw data. You can also dump it as a string - ccstd::vector _responseHeader; /// the returned raw header data. You can also dump it as a string - long _responseCode; /// the status code returned from libcurl, e.g. 200, 404 - ccstd::string _errorBuffer; /// if _responseCode != 200, please read _errorBuffer to find the reason - ccstd::string _responseDataString; // the returned raw data. You can also dump it as a string + HttpRequest *_pHttpRequest; /// the corresponding HttpRequest pointer who leads to this response + bool _succeed; /// to indicate if the http request is successful simply + ccstd::vector _responseData; /// the returned raw data. You can also dump it as a string + ccstd::vector _responseHeader; /// the returned raw header data. You can also dump it as a string + long _responseCode; /// the status code returned from libcurl, e.g. 200, 404 + ccstd::string _errorBuffer; /// if _responseCode != 200, please read _errorBuffer to find the reason + ccstd::string _responseDataString; // the returned raw data. You can also dump it as a string }; } // namespace network diff --git a/native/cocos/network/SocketIO.cpp b/native/cocos/network/SocketIO.cpp index af1eae87d5..9f112f3b29 100644 --- a/native/cocos/network/SocketIO.cpp +++ b/native/cocos/network/SocketIO.cpp @@ -63,39 +63,39 @@ public: void initWithType(const ccstd::string &packetType); void initWithTypeIndex(int index); - ccstd::string toString() const; - virtual int typeAsNumber() const; + ccstd::string toString() const; + virtual int typeAsNumber() const; const ccstd::string &typeForIndex(int index) const; - void setEndpoint(const ccstd::string &endpoint) { _endpoint = endpoint; }; + void setEndpoint(const ccstd::string &endpoint) { _endpoint = endpoint; }; const ccstd::string &getEndpoint() const { return _endpoint; }; - void setEvent(const ccstd::string &event) { _name = event; }; + void setEvent(const ccstd::string &event) { _name = event; }; const ccstd::string &getEvent() const { return _name; }; - void addData(const ccstd::string &data); + void addData(const ccstd::string &data); ccstd::vector getData() const { return _args; }; - virtual ccstd::string stringify() const; + virtual ccstd::string stringify() const; static SocketIOPacket *createPacketWithType(const ccstd::string &type, SocketIOVersion version); static SocketIOPacket *createPacketWithTypeIndex(int type, SocketIOVersion version); protected: - ccstd::string _pId; //id message - ccstd::string _ack; // - ccstd::string _name; //event name - ccstd::vector _args; //we will be using a vector of strings to store multiple data - ccstd::string _endpoint; // - ccstd::string _endpointseparator; //socket.io 1.x requires a ',' between endpoint and payload - ccstd::string _type; //message type - ccstd::string _separator; //for stringify the object - ccstd::vector _types; //types of messages + ccstd::string _pId; //id message + ccstd::string _ack; // + ccstd::string _name; //event name + ccstd::vector _args; //we will be using a vector of strings to store multiple data + ccstd::string _endpoint; // + ccstd::string _endpointseparator; //socket.io 1.x requires a ',' between endpoint and payload + ccstd::string _type; //message type + ccstd::string _separator; //for stringify the object + ccstd::vector _types; //types of messages }; class SocketIOPacketV10x : public SocketIOPacket { public: SocketIOPacketV10x(); ~SocketIOPacketV10x() override; - int typeAsNumber() const override; + int typeAsNumber() const override; ccstd::string stringify() const override; private: @@ -160,8 +160,8 @@ ccstd::string SocketIOPacket::toString() const { return encoded.str(); } int SocketIOPacket::typeAsNumber() const { - ccstd::string::size_type num = 0; - auto item = std::find(_types.begin(), _types.end(), _type); + ccstd::string::size_type num = 0; + auto item = std::find(_types.begin(), _types.end(), _type); if (item != _types.end()) { num = item - _types.begin(); } @@ -180,7 +180,7 @@ ccstd::string SocketIOPacket::stringify() const { if (_type == "message") { outS = _args[0]; } else { - rapidjson::StringBuffer s; + rapidjson::StringBuffer s; rapidjson::Writer writer(s); writer.StartObject(); @@ -207,7 +207,7 @@ ccstd::string SocketIOPacket::stringify() const { } SocketIOPacketV10x::SocketIOPacketV10x() { - _separator = ""; + _separator = ""; _endpointseparator = ","; _types.emplace_back("disconnected"); _types.emplace_back("connected"); @@ -226,8 +226,8 @@ SocketIOPacketV10x::SocketIOPacketV10x() { } int SocketIOPacketV10x::typeAsNumber() const { - ccstd::vector::size_type num = 0; - auto item = std::find(_typesMessage.begin(), _typesMessage.end(), _type); + ccstd::vector::size_type num = 0; + auto item = std::find(_typesMessage.begin(), _typesMessage.end(), _type); if (item != _typesMessage.end()) { //it's a message num = item - _typesMessage.begin(); num += 40; @@ -241,7 +241,7 @@ int SocketIOPacketV10x::typeAsNumber() const { ccstd::string SocketIOPacketV10x::stringify() const { ccstd::string outS; - rapidjson::StringBuffer s; + rapidjson::StringBuffer s; rapidjson::Writer writer(s); writer.StartArray(); @@ -300,11 +300,11 @@ SocketIOPacket *SocketIOPacket::createPacketWithTypeIndex(int type, SocketIOPack class SIOClientImpl : public cc::RefCounted, public WebSocket::Delegate { private: - int _heartbeat, _timeout; - ccstd::string _sid; - Uri _uri; - ccstd::string _caFilePath; - bool _connected; + int _heartbeat, _timeout; + ccstd::string _sid; + Uri _uri; + ccstd::string _caFilePath; + bool _connected; SocketIOPacket::SocketIOVersion _version; WebSocket *_ws; @@ -322,16 +322,16 @@ public: void onClose(WebSocket *ws) override; void onError(WebSocket *ws, const WebSocket::ErrorCode &error) override; - void connect(); - void disconnect(); + void connect(); + void disconnect(); static bool init(); - void handshake(); - void handshakeResponse(HttpClient *sender, HttpResponse *response); - void openSocket(); - void heartbeat(float dt); + void handshake(); + void handshakeResponse(HttpClient *sender, HttpResponse *response); + void openSocket(); + void heartbeat(float dt); SIOClient *getClient(const ccstd::string &endpoint); - void addClient(const ccstd::string &endpoint, SIOClient *client); + void addClient(const ccstd::string &endpoint, SIOClient *client); void connectToEndpoint(const ccstd::string &endpoint); void disconnectFromEndpoint(const ccstd::string &endpoint); @@ -393,7 +393,7 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res CC_LOG_INFO("%s completed", response->getHttpRequest()->getTag()); } - auto statusCode = static_cast(response->getResponseCode()); + auto statusCode = static_cast(response->getResponseCode()); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); CC_LOG_INFO("response code: %ld", statusCode); @@ -413,7 +413,7 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res CC_LOG_INFO("SIOClientImpl::handshake() succeeded"); ccstd::vector *buffer = response->getResponseData(); - std::stringstream s; + std::stringstream s; s.str(""); for (const auto &iter : *buffer) { @@ -424,8 +424,8 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res ccstd::string res = s.str(); ccstd::string sid; - int heartbeat = 0; - int timeout = 0; + int heartbeat = 0; + int timeout = 0; if (res.find('}') != ccstd::string::npos) { CC_LOG_INFO("SIOClientImpl::handshake() Socket.IO 1.x detected"); @@ -434,7 +434,7 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res // 96:0{"sid":"jzrjDlQusSUxLTd3AAAV","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}2:40 ccstd::string::size_type a; ccstd::string::size_type b; - a = res.find('{'); + a = res.find('{'); ccstd::string temp = res.substr(a, res.size() - a); // find the sid @@ -455,15 +455,15 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res b = temp.find(','); ccstd::string heartbeatStr = temp.substr(a + 1, b - a); - heartbeat = atoi(heartbeatStr.c_str()) / 1000; - temp = temp.erase(0, b + 1); + heartbeat = atoi(heartbeatStr.c_str()) / 1000; + temp = temp.erase(0, b + 1); // get the timeout a = temp.find(':'); b = temp.find('}'); ccstd::string timeoutStr = temp.substr(a + 1, b - a); - timeout = atoi(timeoutStr.c_str()) / 1000; + timeout = atoi(timeoutStr.c_str()) / 1000; CC_LOG_INFO("done parsing 1.x"); } else { @@ -489,9 +489,9 @@ void SIOClientImpl::handshakeResponse(HttpClient * /*sender*/, HttpResponse *res } } - _sid = sid; + _sid = sid; _heartbeat = heartbeat; - _timeout = timeout; + _timeout = timeout; openSocket(); } @@ -535,7 +535,7 @@ void SIOClientImpl::disconnect() { if (_ws->getReadyState() == WebSocket::State::OPEN) { ccstd::string s; ccstd::string endpoint; - s = ""; + s = ""; endpoint = ""; if (_version == SocketIOPacket::SocketIOVersion::V09X) { @@ -666,8 +666,8 @@ void SIOClientImpl::onMessage(WebSocket * /*ws*/, const WebSocket::Data &data) { CC_LOG_INFO("SIOClientImpl::onMessage received: %s", data.bytes); ccstd::string payload = data.bytes; - int control = atoi(payload.substr(0, 1).c_str()); - payload = payload.substr(1, payload.size() - 1); + int control = atoi(payload.substr(0, 1).c_str()); + payload = payload.substr(1, payload.size() - 1); SIOClient *c = nullptr; @@ -741,11 +741,11 @@ void SIOClientImpl::onMessage(WebSocket * /*ws*/, const WebSocket::Data &data) { if (c) { eventname = ""; - pos = sData.find(':'); - pos2 = sData.find(','); + pos = sData.find(':'); + pos2 = sData.find(','); if (pos2 > pos) { eventname = sData.substr(pos + 2, pos2 - (pos + 3)); - sData = sData.substr(pos2 + 9, sData.size() - (pos2 + 11)); + sData = sData.substr(pos2 + 9, sData.size() - (pos2 + 11)); } c->fireEvent(eventname, sData); @@ -831,7 +831,7 @@ void SIOClientImpl::onMessage(WebSocket * /*ws*/, const WebSocket::Data &data) { case 2: { CC_LOG_INFO("Event Received (%s)", payload.c_str()); - ccstd::string::size_type payloadFirstSlashPos = payload.find('\"'); + ccstd::string::size_type payloadFirstSlashPos = payload.find('\"'); ccstd::string::size_type payloadSecondSlashPos = payload.substr(payloadFirstSlashPos + 1).find('\"'); ccstd::string eventname = payload.substr(payloadFirstSlashPos + 1, @@ -902,7 +902,7 @@ SIOClient::SIOClient(ccstd::string path, SIOClientImpl *impl, SocketIO::SIODeleg _socket(impl), _delegate(&delegate) { static uint32_t instanceIdCounter = 0; - _instanceId = instanceIdCounter++; + _instanceId = instanceIdCounter++; } SIOClient::~SIOClient() { @@ -1009,7 +1009,7 @@ SIOClient *SocketIO::connect(const ccstd::string &uri, SIODelegate &delegate, co Uri uriObj = Uri::parse(uri); SIOClientImpl *socket = SocketIO::getInstance()->getSocket(uriObj.getAuthority()); - SIOClient * c = nullptr; + SIOClient *c = nullptr; ccstd::string path = uriObj.getPath(); if (path.empty()) { @@ -1041,7 +1041,7 @@ SIOClient *SocketIO::connect(const ccstd::string &uri, SIODelegate &delegate, co CC_LOG_DEBUG("SocketIO: recreate a new socket, new client, connect"); SIOClientImpl *newSocket = SIOClientImpl::create(uriObj, caFilePath); - auto * newC = ccnew SIOClient(path, newSocket, delegate); + auto *newC = ccnew SIOClient(path, newSocket, delegate); newSocket->addClient(path, newC); newSocket->connect(); diff --git a/native/cocos/network/SocketIO.h b/native/cocos/network/SocketIO.h index 7fa9fb3ece..d19eb2b7d3 100644 --- a/native/cocos/network/SocketIO.h +++ b/native/cocos/network/SocketIO.h @@ -59,7 +59,7 @@ public: * @return SocketIO* the instance of SocketIO. */ static SocketIO *getInstance(); - static void destroyInstance(); + static void destroyInstance(); /** * The delegate class to process socket.io events. @@ -147,8 +147,8 @@ private: cc::RefMap _sockets; SIOClientImpl *getSocket(const ccstd::string &uri); - void addSocket(const ccstd::string &uri, SIOClientImpl *socket); - void removeSocket(const ccstd::string &uri); + void addSocket(const ccstd::string &uri, SIOClientImpl *socket); + void removeSocket(const ccstd::string &uri); friend class SIOClientImpl; @@ -170,14 +170,14 @@ class CC_DLL SIOClient private: friend class SocketIO; // Only SocketIO class could contruct a SIOClient instance. - ccstd::string _path, _tag; - bool _connected; + ccstd::string _path, _tag; + bool _connected; SIOClientImpl *_socket; SocketIO::SIODelegate *_delegate; EventRegistry _eventRegistry; - uint32_t _instanceId; + uint32_t _instanceId; void fireEvent(const ccstd::string &eventName, const ccstd::string &data); diff --git a/native/cocos/network/Uri.cpp b/native/cocos/network/Uri.cpp index a8e7ae8462..efb28f75e7 100644 --- a/native/cocos/network/Uri.cpp +++ b/native/cocos/network/Uri.cpp @@ -80,21 +80,21 @@ Uri::Uri(Uri &&o) { Uri &Uri::operator=(const Uri &o) { if (this != &o) { - _isValid = o._isValid; - _isSecure = o._isSecure; - _scheme = o._scheme; - _username = o._username; - _password = o._password; - _host = o._host; - _hostName = o._hostName; + _isValid = o._isValid; + _isSecure = o._isSecure; + _scheme = o._scheme; + _username = o._username; + _password = o._password; + _host = o._host; + _hostName = o._hostName; _hasAuthority = o._hasAuthority; - _port = o._port; - _authority = o._authority; - _pathEtc = o._pathEtc; - _path = o._path; - _query = o._query; - _fragment = o._fragment; - _queryParams = o._queryParams; + _port = o._port; + _authority = o._authority; + _pathEtc = o._pathEtc; + _path = o._path; + _query = o._query; + _fragment = o._fragment; + _queryParams = o._queryParams; } return *this; @@ -102,25 +102,25 @@ Uri &Uri::operator=(const Uri &o) { Uri &Uri::operator=(Uri &&o) { if (this != &o) { - _isValid = o._isValid; - o._isValid = false; - _isSecure = o._isSecure; - o._isSecure = false; - _scheme = std::move(o._scheme); - _username = std::move(o._username); - _password = std::move(o._password); - _host = std::move(o._host); - _hostName = std::move(o._hostName); - _hasAuthority = o._hasAuthority; + _isValid = o._isValid; + o._isValid = false; + _isSecure = o._isSecure; + o._isSecure = false; + _scheme = std::move(o._scheme); + _username = std::move(o._username); + _password = std::move(o._password); + _host = std::move(o._host); + _hostName = std::move(o._hostName); + _hasAuthority = o._hasAuthority; o._hasAuthority = false; - _port = o._port; - o._port = 0; - _authority = std::move(o._authority); - _pathEtc = std::move(o._pathEtc); - _path = std::move(o._path); - _query = std::move(o._query); - _fragment = std::move(o._fragment); - _queryParams = std::move(o._queryParams); + _port = o._port; + o._port = 0; + _authority = std::move(o._authority); + _pathEtc = std::move(o._pathEtc); + _path = std::move(o._path); + _query = std::move(o._query); + _fragment = std::move(o._fragment); + _queryParams = std::move(o._queryParams); } return *this; } @@ -175,14 +175,14 @@ bool Uri::doParse(const ccstd::string &str) { } ccstd::string authorityAndPath(match[2].first, match[2].second); - std::smatch authorityAndPathMatch; + std::smatch authorityAndPathMatch; if (!std::regex_match(authorityAndPath.cbegin(), authorityAndPath.cend(), authorityAndPathMatch, authorityAndPathRegex)) { // Does not start with //, doesn't have authority _hasAuthority = false; - _path = authorityAndPath; + _path = authorityAndPath; } else { static const std::regex authorityRegex( "(?:([^@:]*)(?::([^@]*))?@)?" // username, password @@ -190,7 +190,7 @@ bool Uri::doParse(const ccstd::string &str) { // dotted-IPv4, or named host) "(?::(\\d*))?"); // port - auto authority = authorityAndPathMatch[1]; + auto authority = authorityAndPathMatch[1]; std::smatch authorityMatch; if (!std::regex_match(authority.first, authority.second, @@ -207,15 +207,15 @@ bool Uri::doParse(const ccstd::string &str) { } _hasAuthority = true; - _username = submatch(authorityMatch, 1); - _password = submatch(authorityMatch, 2); - _host = submatch(authorityMatch, 3); - _path = submatch(authorityAndPathMatch, 2); + _username = submatch(authorityMatch, 1); + _password = submatch(authorityMatch, 2); + _host = submatch(authorityMatch, 3); + _path = submatch(authorityAndPathMatch, 2); } - _query = submatch(match, 3); + _query = submatch(match, 3); _fragment = submatch(match, 4); - _isValid = true; + _isValid = true; // Assign authority part // @@ -265,7 +265,7 @@ bool Uri::doParse(const ccstd::string &str) { } void Uri::clear() { - _isValid = false; + _isValid = false; _isSecure = false; _scheme.clear(); _username.clear(); @@ -273,7 +273,7 @@ void Uri::clear() { _host.clear(); _hostName.clear(); _hasAuthority = false; - _port = 0; + _port = 0; _authority.clear(); _pathEtc.clear(); _path.clear(); diff --git a/native/cocos/network/Uri.h b/native/cocos/network/Uri.h index bf1f4d57e7..cc07747472 100644 --- a/native/cocos/network/Uri.h +++ b/native/cocos/network/Uri.h @@ -157,20 +157,20 @@ public: private: bool doParse(const ccstd::string &str); - bool _isValid; - bool _isSecure; - ccstd::string _scheme; - ccstd::string _username; - ccstd::string _password; - ccstd::string _host; - ccstd::string _hostName; - bool _hasAuthority; - uint16_t _port; - ccstd::string _authority; - ccstd::string _pathEtc; - ccstd::string _path; - ccstd::string _query; - ccstd::string _fragment; + bool _isValid; + bool _isSecure; + ccstd::string _scheme; + ccstd::string _username; + ccstd::string _password; + ccstd::string _host; + ccstd::string _hostName; + bool _hasAuthority; + uint16_t _port; + ccstd::string _authority; + ccstd::string _pathEtc; + ccstd::string _path; + ccstd::string _query; + ccstd::string _fragment; ccstd::vector> _queryParams; }; diff --git a/native/cocos/network/WebSocket-apple.mm b/native/cocos/network/WebSocket-apple.mm index 8a5cd3da3b..769fd6d900 100644 --- a/native/cocos/network/WebSocket-apple.mm +++ b/native/cocos/network/WebSocket-apple.mm @@ -43,22 +43,22 @@ ccstd::vector websocketInstances; // @implementation WebSocketImpl { - SRWebSocket * _ws; - cc::network::WebSocket * _ccws; + SRWebSocket *_ws; + cc::network::WebSocket *_ccws; cc::network::WebSocket::Delegate *_delegate; ccstd::string _url; ccstd::string _selectedProtocol; - bool _isDestroyed; + bool _isDestroyed; } - (id)initWithURL:(const ccstd::string &)url protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates ws:(cc::network::WebSocket *)ccws delegate:(const cc::network::WebSocket::Delegate &)delegate { if (self = [super init]) { - _ccws = ccws; - _delegate = const_cast(&delegate); - _url = url; + _ccws = ccws; + _delegate = const_cast(&delegate); + _url = url; NSURL *nsUrl = [[NSURL alloc] initWithString:[[NSString alloc] initWithUTF8String:_url.c_str()]]; - _ws = [[SRWebSocket alloc] initWithURL:nsUrl protocols:protocols allowsUntrustedSSLCertificates:allowsUntrustedSSLCertificates]; + _ws = [[SRWebSocket alloc] initWithURL:nsUrl protocols:protocols allowsUntrustedSSLCertificates:allowsUntrustedSSLCertificates]; _ws.delegate = self; [_ws open]; _isDestroyed = false; @@ -92,7 +92,7 @@ ccstd::vector websocketInstances; - (cc::network::WebSocket::State)getReadyState { cc::network::WebSocket::State ret; - SRReadyState state = _ws.readyState; + SRReadyState state = _ws.readyState; switch (state) { case SR_OPEN: ret = cc::network::WebSocket::State::OPEN; @@ -150,11 +150,11 @@ ccstd::vector websocketInstances; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string { if (!_isDestroyed) { cc::network::WebSocket::Data data; - data.bytes = const_cast([string cStringUsingEncoding:NSUTF8StringEncoding]); - data.len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + data.bytes = const_cast([string cStringUsingEncoding:NSUTF8StringEncoding]); + data.len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; data.isBinary = false; - data.issued = 0; - data.ext = nullptr; + data.issued = 0; + data.ext = nullptr; _delegate->onMessage(_ccws, data); } else { @@ -165,11 +165,11 @@ ccstd::vector websocketInstances; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)nsData { if (!_isDestroyed) { cc::network::WebSocket::Data data; - data.bytes = (char *)nsData.bytes; - data.len = nsData.length; + data.bytes = (char *)nsData.bytes; + data.len = nsData.length; data.isBinary = true; - data.issued = 0; - data.ext = nullptr; + data.issued = 0; + data.ext = nullptr; _delegate->onMessage(_ccws, data); } else { NSLog(@"WebSocketImpl didReceiveMessageWithData was destroyed!"); @@ -198,7 +198,7 @@ void WebSocket::closeAllConnections() { (*iter)->close(); ++iter; } - + websocketInstances.clear(); } @@ -220,10 +220,10 @@ WebSocket::~WebSocket() { } } -bool WebSocket::init(const Delegate & delegate, - const ccstd::string & url, +bool WebSocket::init(const Delegate &delegate, + const ccstd::string &url, const ccstd::vector *protocols /* = nullptr*/, - const ccstd::string & caFilePath /* = ""*/) { + const ccstd::string &caFilePath /* = ""*/) { if (url.empty()) return false; diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index dc758623cd..047ac765a0 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -93,8 +93,8 @@ struct lws_vhost; //IDEA: Move _winLog, winLog to a separated file static void _winLog(const char *format, va_list args) { static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char * buf = nullptr; + int bufferSize = MAX_LOG_LENGTH; + char *buf = nullptr; do { buf = ccnew char[bufferSize]; @@ -113,10 +113,10 @@ static void _winLog(const char *format, va_list args) { strcat(buf, "\n"); - int pos = 0; - int len = strlen(buf); - char tempBuf[MAX_LOG_LENGTH + 1] = {0}; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; + int pos = 0; + int len = strlen(buf); + char tempBuf[MAX_LOG_LENGTH + 1] = {0}; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; do { std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); @@ -186,7 +186,7 @@ static void printWebSocketLog(int level, const char *line) { }; char buf[30] = {0}; - int n; + int n; for (n = 0; n < LLL_COUNT; n++) { if (level != (1 << n)) { @@ -208,27 +208,27 @@ public: ~WebSocketImpl(); bool init(const cc::network::WebSocket::Delegate &delegate, - const ccstd::string & url, - const ccstd::vector * protocols = nullptr, - const ccstd::string & caFilePath = ""); + const ccstd::string &url, + const ccstd::vector *protocols = nullptr, + const ccstd::string &caFilePath = ""); - void send(const ccstd::string &message); - void send(const unsigned char *binaryMsg, unsigned int len); - void close(); - void closeAsync(); - void closeAsync(int code, const ccstd::string &reason); - cc::network::WebSocket::State getReadyState() const; - const ccstd::string & getUrl() const; - const ccstd::string & getProtocol() const; + void send(const ccstd::string &message); + void send(const unsigned char *binaryMsg, unsigned int len); + void close(); + void closeAsync(); + void closeAsync(int code, const ccstd::string &reason); + cc::network::WebSocket::State getReadyState() const; + const ccstd::string &getUrl() const; + const ccstd::string &getProtocol() const; cc::network::WebSocket::Delegate *getDelegate() const; - size_t getBufferedAmount() const; + size_t getBufferedAmount() const; ccstd::string getExtensions() const; private: // The following callback functions are invoked in websocket thread void onClientOpenConnectionRequest(); - int onSocketCallback(struct lws *wsi, enum lws_callback_reasons reason, void *in, ssize_t len); + int onSocketCallback(struct lws *wsi, enum lws_callback_reasons reason, void *in, ssize_t len); int onClientWritable(); int onClientReceivedData(void *in, ssize_t len); @@ -238,21 +238,21 @@ private: struct lws_vhost *createVhost(struct lws_protocols *protocols, int *sslConnection); - cc::network::WebSocket * _ws; + cc::network::WebSocket *_ws; cc::network::WebSocket::State _readyState; - std::mutex _readyStateMutex; - ccstd::string _url; - ccstd::vector _receivedData; + std::mutex _readyStateMutex; + ccstd::string _url; + ccstd::vector _receivedData; - struct lws * _wsInstance; + struct lws *_wsInstance; struct lws_protocols *_lwsProtocols; - ccstd::string _clientSupportedProtocols; - ccstd::string _selectedProtocol; + ccstd::string _clientSupportedProtocols; + ccstd::string _selectedProtocol; std::shared_ptr> _isDestroyed; - cc::network::WebSocket::Delegate * _delegate; + cc::network::WebSocket::Delegate *_delegate; - std::mutex _closeMutex; + std::mutex _closeMutex; std::condition_variable _closeCondition; ccstd::vector _enabledExtensions; @@ -280,15 +280,15 @@ enum WsMsg { class WsThreadHelper; static ccstd::vector *websocketInstances{nullptr}; -static std::recursive_mutex instanceMutex; -static struct lws_context * wsContext{nullptr}; -static WsThreadHelper * wsHelper{nullptr}; -static std::atomic_bool wsPolling{false}; +static std::recursive_mutex instanceMutex; +static struct lws_context *wsContext{nullptr}; +static WsThreadHelper *wsHelper{nullptr}; +static std::atomic_bool wsPolling{false}; #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) static ccstd::string getFileNameForPath(const ccstd::string &filePath) { - ccstd::string fileName = filePath; - const size_t lastSlashIdx = fileName.find_last_of("\\/"); + ccstd::string fileName = filePath; + const size_t lastSlashIdx = fileName.find_last_of("\\/"); if (ccstd::string::npos != lastSlashIdx) { fileName.erase(0, lastSlashIdx + 1); } @@ -309,7 +309,7 @@ static lws_context_creation_info convertToContextCreationInfo(const struct lws_p * For this client-only demo, we tell it to not listen on any port. */ - info.port = CONTEXT_PORT_NO_LISTEN; + info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; // IDEA: Disable 'permessage-deflate' extension temporarily because of issues: @@ -339,10 +339,10 @@ static lws_context_creation_info convertToContextCreationInfo(const struct lws_p class WsMessage { public: WsMessage() : id(++idCount) {} - unsigned int id; - unsigned int what{0}; // message type + unsigned int id; + unsigned int what{0}; // message type cc::network::WebSocket::Data *data{nullptr}; - void * user{nullptr}; + void *user{nullptr}; private: static unsigned int idCount; @@ -383,8 +383,8 @@ protected: public: ccstd::list *_subThreadWsMessageQueue; - std::mutex _subThreadWsMessageQueueMutex; - std::thread * _subThreadInstance{nullptr}; + std::mutex _subThreadWsMessageQueueMutex; + std::thread *_subThreadInstance{nullptr}; private: bool _needQuit{false}; @@ -401,7 +401,7 @@ public: int ret = 0; { std::lock_guard lk(instanceMutex); - auto * ws = static_cast(lws_wsi_user(wsi)); + auto *ws = static_cast(lws_wsi_user(wsi)); if (ws != nullptr && websocketInstances != nullptr) { if (std::find(websocketInstances->begin(), websocketInstances->end(), ws) != websocketInstances->end()) { ret = ws->onSocketCallback(wsi, reason, in, len); @@ -448,7 +448,7 @@ void WsThreadHelper::onSubThreadLoop() { auto iter = wsHelper->_subThreadWsMessageQueue->begin(); for (; iter != wsHelper->_subThreadWsMessageQueue->end();) { auto *msg = (*iter); - auto *ws = static_cast(msg->user); + auto *ws = static_cast(msg->user); // REFINE: ws may be a invalid pointer if (msg->what == WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION) { ws->onClientOpenConnectionRequest(); @@ -474,13 +474,13 @@ void WsThreadHelper::onSubThreadStarted() { memset(defaultProtocols, 0, 2 * sizeof(struct lws_protocols)); - defaultProtocols[0].name = ""; - defaultProtocols[0].callback = WebSocketCallbackWrapper::onSocketCallback; + defaultProtocols[0].name = ""; + defaultProtocols[0].callback = WebSocketCallbackWrapper::onSocketCallback; defaultProtocols[0].rx_buffer_size = WS_RX_BUFFER_SIZE; - defaultProtocols[0].id = std::numeric_limits::max(); + defaultProtocols[0].id = std::numeric_limits::max(); lws_context_creation_info creationInfo = convertToContextCreationInfo(defaultProtocols, true); - wsContext = lws_create_context(&creationInfo); + wsContext = lws_create_context(&creationInfo); #if WS_ENABLE_LIBUV if (lws_uv_initloop(wsContext, nullptr, 0)) { LOGE("WsThreadHelper: failed to init libuv"); @@ -523,7 +523,7 @@ void WsThreadHelper::sendMessageToWebSocketThread(WsMessage *msg) { size_t WsThreadHelper::countBufferedBytes(const WebSocketImpl *ws) { std::lock_guard lk(_subThreadWsMessageQueueMutex); - size_t total = 0; + size_t total = 0; for (auto *msg : *_subThreadWsMessageQueue) { if (msg->user == ws && msg->data && (msg->what == WS_MSG_TO_SUBTRHEAD_SENDING_STRING || msg->what == WS_MSG_TO_SUBTRHEAD_SENDING_BINARY)) { total += msg->data->getRemain(); @@ -556,9 +556,9 @@ public: std::copy(buf, buf + len, _data.begin() + LWS_PRE); } - _payload = _data.data() + LWS_PRE; + _payload = _data.data() + LWS_PRE; _payloadLength = len; - _frameLength = len; + _frameLength = len; return true; } @@ -568,14 +568,14 @@ public: } unsigned char *getPayload() const { return _payload; } - ssize_t getPayloadLength() const { return _payloadLength; } - ssize_t getFrameLength() const { return _frameLength; } + ssize_t getPayloadLength() const { return _payloadLength; } + ssize_t getFrameLength() const { return _frameLength; } private: unsigned char *_payload{nullptr}; - ssize_t _payloadLength{0}; + ssize_t _payloadLength{0}; - ssize_t _frameLength{0}; + ssize_t _frameLength{0}; ccstd::vector _data; }; @@ -659,11 +659,11 @@ WebSocketImpl::~WebSocketImpl() { } bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, - const ccstd::string & url, - const ccstd::vector * protocols /* = nullptr*/, - const ccstd::string & caFilePath /* = ""*/) { - _delegate = const_cast(&delegate); - _url = url; + const ccstd::string &url, + const ccstd::vector *protocols /* = nullptr*/, + const ccstd::string &caFilePath /* = ""*/) { + _delegate = const_cast(&delegate); + _url = url; _caFilePath = caFilePath; if (_url.empty()) { @@ -671,7 +671,7 @@ bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, } if (protocols != nullptr && !protocols->empty()) { - size_t size = protocols->size(); + size_t size = protocols->size(); _lwsProtocols = static_cast(malloc((size + 1) * sizeof(struct lws_protocols))); memset(_lwsProtocols, 0, (size + 1) * sizeof(struct lws_protocols)); @@ -679,15 +679,15 @@ bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, for (size_t i = 0; i < size; ++i) { _lwsProtocols[i].callback = WebSocketCallbackWrapper::onSocketCallback; - size_t nameLen = protocols->at(i).length(); - char * name = static_cast(malloc(nameLen + 1)); - name[nameLen] = '\0'; + size_t nameLen = protocols->at(i).length(); + char *name = static_cast(malloc(nameLen + 1)); + name[nameLen] = '\0'; strcpy(name, protocols->at(i).c_str()); - _lwsProtocols[i].name = name; - _lwsProtocols[i].id = ++wsId; - _lwsProtocols[i].rx_buffer_size = WS_RX_BUFFER_SIZE; + _lwsProtocols[i].name = name; + _lwsProtocols[i].id = ++wsId; + _lwsProtocols[i].rx_buffer_size = WS_RX_BUFFER_SIZE; _lwsProtocols[i].per_session_data_size = 0; - _lwsProtocols[i].user = nullptr; + _lwsProtocols[i].user = nullptr; _clientSupportedProtocols += name; if (i < (size - 1)) { @@ -698,7 +698,7 @@ bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, bool isWebSocketThreadCreated = true; if (wsHelper == nullptr) { - wsHelper = ccnew WsThreadHelper(); + wsHelper = ccnew WsThreadHelper(); isWebSocketThreadCreated = false; } @@ -742,7 +742,7 @@ ccstd::string WebSocketImpl::getExtensions() const { void WebSocketImpl::send(const ccstd::string &message) { if (_readyState == cc::network::WebSocket::State::OPEN) { // In main thread - auto *data = ccnew cc::network::WebSocket::Data(); + auto *data = ccnew cc::network::WebSocket::Data(); data->bytes = static_cast(malloc(message.length() + 1)); // Make sure the last byte is '\0' data->bytes[message.length()] = '\0'; @@ -765,7 +765,7 @@ void WebSocketImpl::send(const unsigned char *binaryMsg, unsigned int len) { auto *data = ccnew cc::network::WebSocket::Data(); if (len == 0) { // If data length is zero, allocate 1 byte for safe. - data->bytes = static_cast(malloc(1)); + data->bytes = static_cast(malloc(1)); data->bytes[0] = '\0'; } else { data->bytes = static_cast(malloc(len)); @@ -858,8 +858,8 @@ cc::network::WebSocket::Delegate *WebSocketImpl::getDelegate() const { } struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, int *sslConnectionOut) { - auto *fileUtils = cc::FileUtils::getInstance(); - bool isCAFileExist = fileUtils->isFileExist(_caFilePath); + auto *fileUtils = cc::FileUtils::getInstance(); + bool isCAFileExist = fileUtils->isFileExist(_caFilePath); if (isCAFileExist) { _caFilePath = fileUtils->fullPathForFilename(_caFilePath); } @@ -871,13 +871,13 @@ struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, in if (isCAFileExist) { #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS) // if ca file is in the apk, try to extract it to writable path - ccstd::string writablePath = fileUtils->getWritablePath(); - ccstd::string caFileName = getFileNameForPath(_caFilePath); + ccstd::string writablePath = fileUtils->getWritablePath(); + ccstd::string caFileName = getFileNameForPath(_caFilePath); ccstd::string newCaFilePath = writablePath + caFileName; if (fileUtils->isFileExist(newCaFilePath)) { LOGD("CA file (%s) in writable path exists!", newCaFilePath.c_str()); - _caFilePath = newCaFilePath; + _caFilePath = newCaFilePath; info.ssl_ca_filepath = _caFilePath.c_str(); } else { if (fileUtils->isFileExist(_caFilePath)) { @@ -892,7 +892,7 @@ struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, in LOGD("New CA file path: %s", newCaFilePath.c_str()); fwrite(caData.getBytes(), caData.getSize(), 1, fp); fclose(fp); - _caFilePath = newCaFilePath; + _caFilePath = newCaFilePath; info.ssl_ca_filepath = _caFilePath.c_str(); } else { CC_ASSERT(false); // Open new CA file failed @@ -902,7 +902,7 @@ struct lws_vhost *WebSocketImpl::createVhost(struct lws_protocols *protocols, in } } else { LOGD("CA file isn't in APK!"); - _caFilePath = fullPath; + _caFilePath = fullPath; info.ssl_ca_filepath = _caFilePath.c_str(); } } else { @@ -961,8 +961,8 @@ void WebSocketImpl::onClientOpenConnectionRequest() { port = uri.isSecure() ? 443 : 80; } - const ccstd::string &hostName = uri.getHostName(); - ccstd::string path = uri.getPathEtc(); + const ccstd::string &hostName = uri.getHostName(); + ccstd::string path = uri.getPathEtc(); const ccstd::string &authority = uri.getAuthority(); if (path.empty()) { path = "/"; @@ -970,18 +970,18 @@ void WebSocketImpl::onClientOpenConnectionRequest() { struct lws_client_connect_info connectInfo; memset(&connectInfo, 0, sizeof(connectInfo)); - connectInfo.context = wsContext; - connectInfo.address = hostName.c_str(); - connectInfo.port = port; - connectInfo.ssl_connection = sslConnection; - connectInfo.path = path.c_str(); - connectInfo.host = hostName.c_str(); - connectInfo.origin = authority.c_str(); - connectInfo.protocol = _clientSupportedProtocols.empty() ? nullptr : _clientSupportedProtocols.c_str(); + connectInfo.context = wsContext; + connectInfo.address = hostName.c_str(); + connectInfo.port = port; + connectInfo.ssl_connection = sslConnection; + connectInfo.path = path.c_str(); + connectInfo.host = hostName.c_str(); + connectInfo.origin = authority.c_str(); + connectInfo.protocol = _clientSupportedProtocols.empty() ? nullptr : _clientSupportedProtocols.c_str(); connectInfo.ietf_version_or_minus_one = -1; - connectInfo.userdata = this; - connectInfo.client_exts = EXTS; - connectInfo.vhost = vhost; + connectInfo.userdata = this; + connectInfo.client_exts = EXTS; + connectInfo.vhost = vhost; _wsInstance = lws_client_connect_via_info(&connectInfo); @@ -1030,14 +1030,14 @@ int WebSocketImpl::onClientWritable() { const ssize_t cBufferSize = WS_RX_BUFFER_SIZE; const ssize_t remaining = data->len - data->issued; - const ssize_t n = std::min(remaining, cBufferSize); + const ssize_t n = std::min(remaining, cBufferSize); WebSocketFrame *frame = nullptr; if (data->ext) { frame = static_cast(data->ext); } else { - frame = ccnew WebSocketFrame(); + frame = ccnew WebSocketFrame(); bool success = frame && frame->init(reinterpret_cast(data->bytes + data->issued), n); if (success) { data->ext = frame; @@ -1148,8 +1148,8 @@ int WebSocketImpl::onClientReceivedData(void *in, ssize_t len) { } // If no more data pending, send it to the client thread - size_t remainingSize = lws_remaining_packet_payload(_wsInstance); - int isFinalFragment = lws_is_final_fragment(_wsInstance); + size_t remainingSize = lws_remaining_packet_payload(_wsInstance); + int isFinalFragment = lws_is_final_fragment(_wsInstance); // LOGD("remainingSize: %d, isFinalFragment: %d\n", (int)remainingSize, isFinalFragment); if (remainingSize == 0 && isFinalFragment) { @@ -1173,8 +1173,8 @@ int WebSocketImpl::onClientReceivedData(void *in, ssize_t len) { cc::network::WebSocket::Data data; data.isBinary = isBinary; - data.bytes = static_cast(frameData->data()); - data.len = frameSize; + data.bytes = static_cast(frameData->data()); + data.len = frameSize; if (*isDestroyed) { LOGD("WebSocket instance was destroyed!\n"); @@ -1191,7 +1191,7 @@ int WebSocketImpl::onClientReceivedData(void *in, ssize_t len) { int WebSocketImpl::onConnectionOpened() { const lws_protocols *lwsSelectedProtocol = lws_get_protocol(_wsInstance); - _selectedProtocol = lwsSelectedProtocol->name; + _selectedProtocol = lwsSelectedProtocol->name; LOGD("onConnectionOpened...: %p, client protocols: %s, server selected protocol: %s\n", this, _clientSupportedProtocols.c_str(), _selectedProtocol.c_str()); /* * start the ball rolling, @@ -1352,10 +1352,10 @@ WebSocket::~WebSocket() { delete _impl; } -bool WebSocket::init(const Delegate & delegate, - const ccstd::string & url, +bool WebSocket::init(const Delegate &delegate, + const ccstd::string &url, const ccstd::vector *protocols /* = nullptr*/, - const ccstd::string & caFilePath /* = ""*/) { + const ccstd::string &caFilePath /* = ""*/) { return _impl->init(delegate, url, protocols, caFilePath); } diff --git a/native/cocos/network/WebSocket-okhttp.cpp b/native/cocos/network/WebSocket-okhttp.cpp index 2ba1c2ab79..cd7a8e1a0f 100644 --- a/native/cocos/network/WebSocket-okhttp.cpp +++ b/native/cocos/network/WebSocket-okhttp.cpp @@ -42,13 +42,13 @@ using cc::JniHelper; using cc::network::WebSocket; class WebSocketImpl final { public: - static const char * connectID; - static const char * removeHandlerID; - static const char * sendBinaryID; - static const char * sendStringID; - static const char * closeID; - static const char * getBufferedAmountID; - static std::atomic_int64_t idGenerator; + static const char *connectID; + static const char *removeHandlerID; + static const char *sendBinaryID; + static const char *sendStringID; + static const char *closeID; + static const char *getBufferedAmountID; + static std::atomic_int64_t idGenerator; static std::unordered_map allConnections; static void closeAllConnections(); @@ -57,21 +57,21 @@ public: ~WebSocketImpl(); bool init(const cc::network::WebSocket::Delegate &delegate, - const std::string & url, - const std::vector * protocols = nullptr, - const std::string & caFilePath = ""); + const std::string &url, + const std::vector *protocols = nullptr, + const std::string &caFilePath = ""); - void send(const std::string &message); - void send(const unsigned char *binaryMsg, unsigned int len); - void close(); - void closeAsync(); - void closeAsync(int code, const std::string &reason); - cc::network::WebSocket::State getReadyState() const { return _readyState; } - const std::string & getUrl() const { return _url; } - const std::string & getProtocol() const { return _protocolString; } + void send(const std::string &message); + void send(const unsigned char *binaryMsg, unsigned int len); + void close(); + void closeAsync(); + void closeAsync(int code, const std::string &reason); + cc::network::WebSocket::State getReadyState() const { return _readyState; } + const std::string &getUrl() const { return _url; } + const std::string &getProtocol() const { return _protocolString; } cc::network::WebSocket::Delegate *getDelegate() const { return _delegate; } - size_t getBufferedAmount() const; + size_t getBufferedAmount() const; std::string getExtensions() const { return _extensions; } void onOpen(const std::string &protocol, const std::string &headers); @@ -81,25 +81,25 @@ public: void onBinaryMessage(const uint8_t *buf, size_t len); private: - WebSocket * _socket{nullptr}; - WebSocket::Delegate * _delegate{nullptr}; - jobject _javaSocket{nullptr}; - int64_t _identifier{0}; - std::string _protocolString; - std::string _selectedProtocol; - std::string _url; - std::string _extensions; - WebSocket::State _readyState{WebSocket::State::CONNECTING}; + WebSocket *_socket{nullptr}; + WebSocket::Delegate *_delegate{nullptr}; + jobject _javaSocket{nullptr}; + int64_t _identifier{0}; + std::string _protocolString; + std::string _selectedProtocol; + std::string _url; + std::string _extensions; + WebSocket::State _readyState{WebSocket::State::CONNECTING}; std::unordered_map _headerMap{}; }; -const char * WebSocketImpl::connectID = "_connect"; -const char * WebSocketImpl::removeHandlerID = "_removeHander"; -const char * WebSocketImpl::sendBinaryID = "_send"; -const char * WebSocketImpl::sendStringID = "_send"; -const char * WebSocketImpl::closeID = "_close"; -const char * WebSocketImpl::getBufferedAmountID = "_getBufferedAmountID"; -std::atomic_int64_t WebSocketImpl::idGenerator{0}; +const char *WebSocketImpl::connectID = "_connect"; +const char *WebSocketImpl::removeHandlerID = "_removeHander"; +const char *WebSocketImpl::sendBinaryID = "_send"; +const char *WebSocketImpl::sendStringID = "_send"; +const char *WebSocketImpl::closeID = "_close"; +const char *WebSocketImpl::getBufferedAmountID = "_getBufferedAmountID"; +std::atomic_int64_t WebSocketImpl::idGenerator{0}; std::unordered_map WebSocketImpl::allConnections{}; void WebSocketImpl::closeAllConnections() { @@ -123,20 +123,20 @@ WebSocketImpl::~WebSocketImpl() { bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, const std::string &url, const std::vector *protocols, const std::string &caFilePath) { - auto * env = JniHelper::getEnv(); - auto handler = static_cast(reinterpret_cast(this)); - bool tcpNoDelay = false; - bool perMessageDeflate = true; - int64_t timeout = 60 * 60 * 1000 /*ms*/; //TODO(PatriceJiang): set timeout - std::vector headers; //TODO(PatriceJiang): allow set headers - _url = url; + auto *env = JniHelper::getEnv(); + auto handler = static_cast(reinterpret_cast(this)); + bool tcpNoDelay = false; + bool perMessageDeflate = true; + int64_t timeout = 60 * 60 * 1000 /*ms*/; //TODO(PatriceJiang): set timeout + std::vector headers; //TODO(PatriceJiang): allow set headers + _url = url; _delegate = const_cast(&delegate); if (protocols != nullptr && !protocols->empty()) { // protocol should add to Request Header as part of the original handshake for key // Sec-WebSocket-Protocol, use ',' to separate more than one. // https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers std::string item; - auto it = protocols->begin(); + auto it = protocols->begin(); while (it != protocols->end()) { item = *it++; _protocolString.append(item); @@ -147,7 +147,7 @@ bool WebSocketImpl::init(const cc::network::WebSocket::Delegate &delegate, const } // header jobject jObj = JniHelper::newObject(JAVA_CLASS_WEBSOCKET, _identifier, handler, headers, tcpNoDelay, perMessageDeflate, timeout); - _javaSocket = env->NewGlobalRef(jObj); + _javaSocket = env->NewGlobalRef(jObj); JniHelper::callObjectVoidMethod(jObj, JAVA_CLASS_WEBSOCKET, connectID, url, _protocolString, caFilePath); env->DeleteLocalRef(jObj); _readyState = WebSocket::State::CONNECTING; @@ -232,16 +232,16 @@ void WebSocketImpl::onError(int code, const std::string & /*reason*/) { void WebSocketImpl::onBinaryMessage(const uint8_t *buf, size_t len) { WebSocket::Data data; - data.bytes = reinterpret_cast(const_cast(buf)); - data.len = static_cast(len); + data.bytes = reinterpret_cast(const_cast(buf)); + data.len = static_cast(len); data.isBinary = true; _delegate->onMessage(_socket, data); } void WebSocketImpl::onStringMessage(const std::string &message) { WebSocket::Data data; - data.bytes = const_cast(message.c_str()); - data.len = static_cast(message.length()); + data.bytes = const_cast(message.c_str()); + data.len = static_cast(message.length()); data.isBinary = false; _delegate->onMessage(_socket, data); } @@ -261,10 +261,10 @@ WebSocket::~WebSocket() { delete _impl; } -bool WebSocket::init(const Delegate & delegate, - const std::string & url, +bool WebSocket::init(const Delegate &delegate, + const std::string &url, const std::vector *protocols /* = nullptr*/, - const std::string & caFilePath /* = ""*/) { + const std::string &caFilePath /* = ""*/) { return _impl->init(delegate, url, protocols, caFilePath); } @@ -340,8 +340,8 @@ JNI_PATH(nativeOnStringMessage)(JNIEnv * /*env*/, jstring msg, jlong /*identifier*/, jlong handler) { - auto * wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) - std::string msgStr = JniHelper::jstring2string(msg); + auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) + std::string msgStr = JniHelper::jstring2string(msg); RUN_IN_GAMETHREAD(wsOkHttp3->onStringMessage(msgStr)); } @@ -351,13 +351,13 @@ JNI_PATH(nativeOnBinaryMessage)(JNIEnv *env, jbyteArray msg, jlong /*identifier*/, jlong handler) { - auto * wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) + auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) jobject strongRef = env->NewGlobalRef(msg); RUN_IN_GAMETHREAD(do { - auto * env = JniHelper::getEnv(); - auto len = env->GetArrayLength(static_cast(strongRef)); + auto *env = JniHelper::getEnv(); + auto len = env->GetArrayLength(static_cast(strongRef)); jboolean isCopy = JNI_FALSE; - jbyte * array = env->GetByteArrayElements(static_cast(strongRef), &isCopy); + jbyte *array = env->GetByteArrayElements(static_cast(strongRef), &isCopy); wsOkHttp3->onBinaryMessage(reinterpret_cast(array), len); env->DeleteGlobalRef(strongRef); } while (false)); @@ -370,9 +370,9 @@ JNI_PATH(nativeOnOpen)(JNIEnv * /*env*/, jstring header, jlong /*identifier*/, jlong handler) { - auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) - auto protocolStr = JniHelper::jstring2string(protocol); - auto headerStr = JniHelper::jstring2string(header); + auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) + auto protocolStr = JniHelper::jstring2string(protocol); + auto headerStr = JniHelper::jstring2string(header); RUN_IN_GAMETHREAD(wsOkHttp3->onOpen(protocolStr, headerStr)); } @@ -393,9 +393,9 @@ JNI_PATH(nativeOnError)(JNIEnv * /*env*/, jstring reason, jlong /*identifier*/, jlong handler) { - auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) - int unknownError = static_cast(cc::network::WebSocket::ErrorCode::UNKNOWN); - auto errorReason = JniHelper::jstring2string(reason); + auto *wsOkHttp3 = HANDLE_TO_WS_OKHTTP3(handler); // NOLINT(performance-no-int-to-ptr) + int unknownError = static_cast(cc::network::WebSocket::ErrorCode::UNKNOWN); + auto errorReason = JniHelper::jstring2string(reason); RUN_IN_GAMETHREAD(wsOkHttp3->onError(unknownError, errorReason)); } diff --git a/native/cocos/network/WebSocket.h b/native/cocos/network/WebSocket.h index a0c377da78..07c06e0c9f 100644 --- a/native/cocos/network/WebSocket.h +++ b/native/cocos/network/WebSocket.h @@ -87,10 +87,10 @@ public: */ struct Data { Data() = default; - char * bytes{nullptr}; + char *bytes{nullptr}; uint32_t len{0}, issued{0}; - bool isBinary{false}; - void * ext{nullptr}; + bool isBinary{false}; + void *ext{nullptr}; uint32_t getRemain() const { return std::max(static_cast(0), len - issued); } }; @@ -166,10 +166,10 @@ public: * @return true: Success, false: Failure. * @lua NA */ - bool init(const Delegate & delegate, - const ccstd::string & url, - const ccstd::vector *protocols = nullptr, - const ccstd::string & caFilePath = ""); + bool init(const Delegate &delegate, + const ccstd::string &url, + const ccstd::vector *protocols = nullptr, + const ccstd::string &caFilePath = ""); /** * @brief Sends string data to websocket server. diff --git a/native/cocos/network/WebSocketServer.cpp b/native/cocos/network/WebSocketServer.cpp index bc00695353..97e5559271 100644 --- a/native/cocos/network/WebSocketServer.cpp +++ b/native/cocos/network/WebSocketServer.cpp @@ -56,13 +56,13 @@ const struct lws_extension exts[] = { {nullptr, nullptr, nullptr}}; struct AsyncTaskData { - std::mutex mtx; + std::mutex mtx; ccstd::list> tasks; }; // run in server thread loop void flush_tasks_in_server_loop_cb(uv_async_t *asyn) { - AsyncTaskData * data = (AsyncTaskData *)asyn->data; + AsyncTaskData *data = (AsyncTaskData *)asyn->data; std::lock_guard guard(data->mtx); while (!data->tasks.empty()) { // fetch task, run task @@ -211,16 +211,16 @@ void WebSocketServer::listen(std::shared_ptr server, int port, struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); - info.port = port; - info.iface = server->_host.empty() ? nullptr : server->_host.c_str(); - info.protocols = protocols; - info.gid = -1; - info.uid = -1; - info.extensions = exts; - info.options = LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_LIBUV | LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME; - info.timeout_secs = 60; // + info.port = port; + info.iface = server->_host.empty() ? nullptr : server->_host.c_str(); + info.protocols = protocols; + info.gid = -1; + info.uid = -1; + info.extensions = exts; + info.options = LWS_SERVER_OPTION_VALIDATE_UTF8 | LWS_SERVER_OPTION_LIBUV | LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME; + info.timeout_secs = 60; // info.max_http_header_pool = 1; - info.user = server.get(); + info.user = server.get(); server->_ctx = lws_create_context(&info); @@ -270,7 +270,7 @@ void WebSocketServer::listenAsync(std::shared_ptr &server, int } ccstd::vector> WebSocketServer::getConnections() const { - std::lock_guard guard(_connsMtx); + std::lock_guard guard(_connsMtx); ccstd::vector> ret; for (auto itr : _conns) { ret.emplace_back(itr.second); @@ -311,13 +311,13 @@ void WebSocketServer::onCloseClient(struct lws *wsi) { void WebSocketServer::onCloseClientInit(struct lws *wsi, void *in, int len) { int16_t code; - char * msg = nullptr; + char *msg = nullptr; std::shared_ptr conn = findConnection(wsi); if (conn && len > 2) { code = ntohs(*(int16_t *)in); - msg = (char *)in + sizeof(code); + msg = (char *)in + sizeof(code); ccstd::string cp(msg, len - sizeof(code)); conn->onClientCloseInit(code, cp); } else { @@ -352,7 +352,7 @@ std::shared_ptr WebSocketServer::findConnection(struc std::shared_ptr conn; { std::lock_guard guard(_connsMtx); - auto itr = _conns.find(wsi); + auto itr = _conns.find(wsi); if (itr != _conns.end()) { conn = itr->second; } @@ -412,9 +412,9 @@ void WebSocketServerConnection::sendBinaryAsync(const void *in, size_t len, std: bool WebSocketServerConnection::close(int code, ccstd::string message) { if (!_wsi) return false; - _readyState = ReadyState::CLOSING; + _readyState = ReadyState::CLOSING; _closeReason = message; - _closeCode = code; + _closeCode = code; onClientCloseInit(); //trigger callback to return -1 which indicates connection closed lws_callback_on_writable(_wsi); @@ -431,7 +431,7 @@ void WebSocketServerConnection::onConnected() { } void WebSocketServerConnection::onDataReceive(void *in, int len) { - bool isFinal = (bool)lws_is_final_fragment(_wsi); + bool isFinal = (bool)lws_is_final_fragment(_wsi); bool isBinary = (bool)lws_frame_is_binary(_wsi); if (!_prevPkg) { @@ -463,10 +463,10 @@ int WebSocketServerConnection::onDrainData() { return -1; } if (_readyState != ReadyState::OPEN) return 0; - unsigned char *p = nullptr; - int send_len = 0; - int finish_len = 0; - int flags = 0; + unsigned char *p = nullptr; + int send_len = 0; + int finish_len = 0; + int flags = 0; ccstd::vector buff(SEND_BUFF + LWS_PRE); @@ -521,12 +521,12 @@ void WebSocketServerConnection::onHTTP() { _headers.clear(); - int n = 0, len; + int n = 0, len; ccstd::vector buf(256); - const char * c; + const char *c; do { lws_token_indexes idx = static_cast(n); - c = (const char *)lws_token_to_string(idx); + c = (const char *)lws_token_to_string(idx); if (!c) { n++; break; @@ -546,7 +546,7 @@ void WebSocketServerConnection::onHTTP() { } void WebSocketServerConnection::onClientCloseInit(int code, const ccstd::string &msg) { - _closeCode = code; + _closeCode = code; _closeReason = msg; } @@ -587,9 +587,9 @@ ccstd::unordered_map WebSocketServerConnection::ge int WebSocketServer::_websocketServerCallback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { - int ret = 0; + int ret = 0; WebSocketServer *server = nullptr; - lws_context * ctx = nullptr; + lws_context *ctx = nullptr; if (wsi) ctx = lws_get_context(wsi); diff --git a/native/cocos/network/WebSocketServer.h b/native/cocos/network/WebSocketServer.h index b344dbe713..7268ee5361 100644 --- a/native/cocos/network/WebSocketServer.h +++ b/native/cocos/network/WebSocketServer.h @@ -91,9 +91,9 @@ public: unsigned char *getData() { return _underlyingData.data() + LWS_PRE; } private: - ccstd::vector _underlyingData; - int _consumed = 0; - bool _isBinary = false; + ccstd::vector _underlyingData; + int _consumed = 0; + bool _isBinary = false; std::function _callback; }; @@ -104,9 +104,9 @@ public: enum ReadyState { CONNECTING = 1, - OPEN = 2, - CLOSING = 3, - CLOSED = 4 + OPEN = 2, + CLOSING = 3, + CLOSED = 4 }; void sendTextAsync(const ccstd::string &, std::function callback); @@ -164,7 +164,7 @@ public: void onClientCloseInit(); - inline void setData(void *d) { _data = d; } + inline void setData(void *d) { _data = d; } inline void *getData() const { return _data; } private: @@ -178,31 +178,31 @@ private: void onConnected(); void onDataReceive(void *in, int len); - int onDrainData(); + int onDrainData(); void onHTTP(); void onClientCloseInit(int code, const ccstd::string &msg); void onDestroyClient(); - struct lws * _wsi = nullptr; + struct lws *_wsi = nullptr; ccstd::unordered_map _headers; - ccstd::list> _sendQueue; - std::shared_ptr _prevPkg; - bool _closed = false; - ccstd::string _closeReason = "close connection"; - int _closeCode = 1000; - std::atomic _readyState{ReadyState::CLOSED}; + ccstd::list> _sendQueue; + std::shared_ptr _prevPkg; + bool _closed = false; + ccstd::string _closeReason = "close connection"; + int _closeCode = 1000; + std::atomic _readyState{ReadyState::CLOSED}; // Attention: do not reference **this** in callbacks std::function _onclose; - std::function _onerror; + std::function _onerror; std::function)> _ontext; std::function)> _onbinary; std::function)> _ondata; - std::function _onconnect; - std::function _onend; - uv_async_t _async = {0}; - void * _data = nullptr; + std::function _onconnect; + std::function _onend; + uv_async_t _async = {0}; + void *_data = nullptr; friend class WebSocketServer; }; @@ -213,7 +213,7 @@ public: virtual ~WebSocketServer(); static void listenAsync(std::shared_ptr &server, int port, const ccstd::string &host, std::function callback); - void closeAsync(std::function callback = nullptr); + void closeAsync(std::function callback = nullptr); ccstd::vector> getConnections() const; @@ -241,39 +241,39 @@ public: _onbegin = cb; } - inline void setData(void *d) { _data = d; } + inline void setData(void *d) { _data = d; } inline void *getData() const { return _data; } protected: static void listen(std::shared_ptr server, int port, const ccstd::string &host, std::function callback); - bool close(std::function callback = nullptr); + bool close(std::function callback = nullptr); void onCreateClient(struct lws *wsi); void onDestroyClient(struct lws *wsi); void onCloseClient(struct lws *wsi); void onCloseClientInit(struct lws *wsi, void *in, int len); void onClientReceive(struct lws *wsi, void *in, int len); - int onServerWritable(struct lws *wsi); + int onServerWritable(struct lws *wsi); void onClientHTTP(struct lws *wsi); private: std::shared_ptr findConnection(struct lws *wsi); - void destroyContext(); + void destroyContext(); ccstd::string _host; - lws_context * _ctx = nullptr; - uv_async_t _async = {0}; + lws_context *_ctx = nullptr; + uv_async_t _async = {0}; - mutable std::mutex _connsMtx; + mutable std::mutex _connsMtx; ccstd::unordered_map> _conns; // Attention: do not reference **this** in callbacks - std::function _onlistening; - std::function _onerror; - std::function _onclose; - std::function _onclose_cb; - std::function _onend; - std::function _onbegin; + std::function _onlistening; + std::function _onerror; + std::function _onclose; + std::function _onclose_cb; + std::function _onend; + std::function _onbegin; std::function)> _onconnection; enum class ServerThreadState { @@ -284,8 +284,8 @@ private: DESTROIED }; std::atomic _serverState{ServerThreadState::NOT_BOOTED}; - std::mutex _serverLock; - void * _data = nullptr; + std::mutex _serverLock; + void *_data = nullptr; public: static int _websocketServerCallback(struct lws *wsi, enum lws_callback_reasons reason, diff --git a/native/cocos/physics/physx/PhysXEventManager.cpp b/native/cocos/physics/physx/PhysXEventManager.cpp index abb61cabc8..dbbf3af617 100644 --- a/native/cocos/physics/physx/PhysXEventManager.cpp +++ b/native/cocos/physics/physx/PhysXEventManager.cpp @@ -40,16 +40,16 @@ void PhysXEventManager::SimulationEventCallback::onTrigger(physx::PxTriggerPair continue; } - const auto &selfIter = getPxShapeMap().find(reinterpret_cast(tp.triggerShape)); + const auto &selfIter = getPxShapeMap().find(reinterpret_cast(tp.triggerShape)); const auto &otherIter = getPxShapeMap().find(reinterpret_cast(tp.otherShape)); if (selfIter == getPxShapeMap().end() || otherIter == getPxShapeMap().end()) { continue; } - const auto &self = selfIter->second; + const auto &self = selfIter->second; const auto &other = otherIter->second; - auto & pairs = mManager->getTriggerPairs(); - const auto &iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { + auto &pairs = mManager->getTriggerPairs(); + const auto &iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { return (pair->shapeA == self || pair->shapeA == other) && (pair->shapeB == self || pair->shapeB == other); }); if (tp.status & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND) { @@ -67,16 +67,16 @@ void PhysXEventManager::SimulationEventCallback::onContact(const physx::PxContac continue; } - const auto &selfIter = getPxShapeMap().find(reinterpret_cast(cp.shapes[0])); + const auto &selfIter = getPxShapeMap().find(reinterpret_cast(cp.shapes[0])); const auto &otherIter = getPxShapeMap().find(reinterpret_cast(cp.shapes[1])); if (selfIter == getPxShapeMap().end() || otherIter == getPxShapeMap().end()) { continue; } - const auto &self = selfIter->second; + const auto &self = selfIter->second; const auto &other = otherIter->second; - auto & pairs = mManager->getConatctPairs(); - auto iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { + auto &pairs = mManager->getConatctPairs(); + auto iter = std::find_if(pairs.begin(), pairs.end(), [self, other](std::shared_ptr &pair) { return (pair->shapeA == self || pair->shapeA == other) && (pair->shapeB == self || pair->shapeB == other); }); @@ -103,7 +103,7 @@ void PhysXEventManager::SimulationEventCallback::onContact(const physx::PxContac void PhysXEventManager::refreshPairs() { for (auto iter = getTriggerPairs().begin(); iter != getTriggerPairs().end();) { - const auto &selfIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(iter->get()->shapeA)->getShape()))); + const auto &selfIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(iter->get()->shapeA)->getShape()))); const auto &otherIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(iter->get()->shapeB)->getShape()))); if (selfIter == getPxShapeMap().end() || otherIter == getPxShapeMap().end()) { iter = getTriggerPairs().erase(iter); diff --git a/native/cocos/physics/physx/PhysXEventManager.h b/native/cocos/physics/physx/PhysXEventManager.h index 10fe88508e..d17f05f3d0 100644 --- a/native/cocos/physics/physx/PhysXEventManager.h +++ b/native/cocos/physics/physx/PhysXEventManager.h @@ -46,27 +46,27 @@ public: } struct SimulationEventCallback : public physx::PxSimulationEventCallback { - void onConstraintBreak(physx::PxConstraintInfo * /*constraints*/, physx::PxU32 /*count*/) override{}; - void onWake(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override{}; - void onSleep(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override{}; - void onTrigger(physx::PxTriggerPair * /*pairs*/, physx::PxU32 /*count*/) override; - void onContact(const physx::PxContactPairHeader & /*pairHeader*/, const physx::PxContactPair * /*pairs*/, physx::PxU32 /*nbPairs*/) override; - void onAdvance(const physx::PxRigidBody *const * /*bodyBuffer*/, const physx::PxTransform * /*poseBuffer*/, const physx::PxU32 /*count*/) override{}; + void onConstraintBreak(physx::PxConstraintInfo * /*constraints*/, physx::PxU32 /*count*/) override{}; + void onWake(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override{}; + void onSleep(physx::PxActor ** /*actors*/, physx::PxU32 /*count*/) override{}; + void onTrigger(physx::PxTriggerPair * /*pairs*/, physx::PxU32 /*count*/) override; + void onContact(const physx::PxContactPairHeader & /*pairHeader*/, const physx::PxContactPair * /*pairs*/, physx::PxU32 /*nbPairs*/) override; + void onAdvance(const physx::PxRigidBody *const * /*bodyBuffer*/, const physx::PxTransform * /*poseBuffer*/, const physx::PxU32 /*count*/) override{}; PhysXEventManager *mManager; public: explicit SimulationEventCallback(PhysXEventManager *m) : mManager(m) {} }; - inline SimulationEventCallback & getEventCallback() { return *_mCallback; } + inline SimulationEventCallback &getEventCallback() { return *_mCallback; } inline ccstd::vector> &getTriggerPairs() { return _mTriggerPairs; } inline ccstd::vector> &getConatctPairs() { return _mConatctPairs; } - void refreshPairs(); + void refreshPairs(); private: ccstd::vector> _mTriggerPairs; ccstd::vector> _mConatctPairs; - SimulationEventCallback * _mCallback; + SimulationEventCallback *_mCallback; }; } // namespace physics diff --git a/native/cocos/physics/physx/PhysXFilterShader.h b/native/cocos/physics/physx/PhysXFilterShader.h index ba537b848e..a2d0373409 100644 --- a/native/cocos/physics/physx/PhysXFilterShader.h +++ b/native/cocos/physics/physx/PhysXFilterShader.h @@ -30,13 +30,13 @@ namespace cc { namespace physics { -constexpr physx::PxU32 QUERY_FILTER = 1 << 0; -constexpr physx::PxU32 QUERY_CHECK_TRIGGER = 1 << 1; -constexpr physx::PxU32 QUERY_SINGLE_HIT = 1 << 2; +constexpr physx::PxU32 QUERY_FILTER = 1 << 0; +constexpr physx::PxU32 QUERY_CHECK_TRIGGER = 1 << 1; +constexpr physx::PxU32 QUERY_SINGLE_HIT = 1 << 2; constexpr physx::PxU32 DETECT_TRIGGER_EVENT = 1 << 3; constexpr physx::PxU32 DETECT_CONTACT_EVENT = 1 << 4; constexpr physx::PxU32 DETECT_CONTACT_POINT = 1 << 5; -constexpr physx::PxU32 DETECT_CONTACT_CCD = 1 << 6; +constexpr physx::PxU32 DETECT_CONTACT_CCD = 1 << 6; physx::PxFilterFlags simpleFilterShader( physx::PxFilterObjectAttributes attributes0, physx::PxFilterData fd0, diff --git a/native/cocos/physics/physx/PhysXRigidBody.cpp b/native/cocos/physics/physx/PhysXRigidBody.cpp index 3708de275e..0c5e89977a 100644 --- a/native/cocos/physics/physx/PhysXRigidBody.cpp +++ b/native/cocos/physics/physx/PhysXRigidBody.cpp @@ -41,9 +41,9 @@ PhysXRigidBody::PhysXRigidBody() : _mEnabled(false), _mGroup(1) {} void PhysXRigidBody::initialize(Node *node, ERigidBodyType t, uint32_t g) { - _mGroup = g; + _mGroup = g; PhysXWorld &ins = PhysXWorld::getInstance(); - _mSharedBody = ins.getSharedBody(node, this); + _mSharedBody = ins.getSharedBody(node, this); getSharedBody().reference(true); getSharedBody().setType(t); } @@ -197,10 +197,10 @@ void PhysXRigidBody::applyLocalForce(float x, float y, float z, float rx, float if (!getSharedBody().isInWorld() || getSharedBody().isStaticOrKinematic()) return; const PxVec3 force{x, y, z}; if (force.isZero()) return; - auto * body = getSharedBody().getImpl().rigidDynamic; - const PxTransform bodyPose = body->getGlobalPose(); - const PxVec3 worldForce = bodyPose.rotate(force); - const PxVec3 worldPos = bodyPose.rotate(PxVec3{rx, ry, rz}); + auto *body = getSharedBody().getImpl().rigidDynamic; + const PxTransform bodyPose = body->getGlobalPose(); + const PxVec3 worldForce = bodyPose.rotate(force); + const PxVec3 worldPos = bodyPose.rotate(PxVec3{rx, ry, rz}); body->addForce(worldForce, PxForceMode::eFORCE, true); const PxVec3 torque = worldPos.cross(worldForce); if (!torque.isZero()) body->addTorque(torque, PxForceMode::eFORCE, true); @@ -210,7 +210,7 @@ void PhysXRigidBody::applyImpulse(float x, float y, float z, float rx, float ry, if (!getSharedBody().isInWorld() || getSharedBody().isStaticOrKinematic()) return; const PxVec3 impulse{x, y, z}; if (impulse.isZero()) return; - auto * body = getSharedBody().getImpl().rigidDynamic; + auto *body = getSharedBody().getImpl().rigidDynamic; const PxVec3 torque = (PxVec3{rx, ry, rz}).cross(impulse); body->addForce(impulse, PxForceMode::eIMPULSE, true); if (!torque.isZero()) body->addTorque(torque, PxForceMode::eIMPULSE, true); @@ -220,10 +220,10 @@ void PhysXRigidBody::applyLocalImpulse(float x, float y, float z, float rx, floa if (!getSharedBody().isInWorld() || getSharedBody().isStaticOrKinematic()) return; const PxVec3 impulse{x, y, z}; if (impulse.isZero()) return; - auto * body = getSharedBody().getImpl().rigidDynamic; - const PxTransform bodyPose = body->getGlobalPose(); - const PxVec3 worldImpulse = bodyPose.rotate(impulse); - const PxVec3 worldPos = bodyPose.rotate(PxVec3{rx, ry, rz}); + auto *body = getSharedBody().getImpl().rigidDynamic; + const PxTransform bodyPose = body->getGlobalPose(); + const PxVec3 worldImpulse = bodyPose.rotate(impulse); + const PxVec3 worldPos = bodyPose.rotate(PxVec3{rx, ry, rz}); body->addForce(worldImpulse, PxForceMode::eIMPULSE, true); const PxVec3 torque = worldPos.cross(worldImpulse); if (!torque.isZero()) body->addTorque(torque, PxForceMode::eIMPULSE, true); @@ -240,7 +240,7 @@ void PhysXRigidBody::applyLocalTorque(float x, float y, float z) { if (!getSharedBody().isInWorld() || getSharedBody().isStaticOrKinematic()) return; PxVec3 torque{x, y, z}; if (torque.isZero()) return; - auto * body = getSharedBody().getImpl().rigidDynamic; + auto *body = getSharedBody().getImpl().rigidDynamic; const PxTransform bodyPose = body->getGlobalPose(); body->addTorque(bodyPose.rotate(PxVec3{x, y, z}), PxForceMode::eFORCE, true); } diff --git a/native/cocos/physics/physx/PhysXRigidBody.h b/native/cocos/physics/physx/PhysXRigidBody.h index 9886e3e095..d692240e54 100644 --- a/native/cocos/physics/physx/PhysXRigidBody.h +++ b/native/cocos/physics/physx/PhysXRigidBody.h @@ -37,55 +37,55 @@ class PhysXRigidBody final : public IRigidBody { public: PhysXRigidBody(); ~PhysXRigidBody() override = default; - inline bool isEnabled() const { return _mEnabled; } + inline bool isEnabled() const { return _mEnabled; } inline const PhysXSharedBody &getSharedBody() const { return *_mSharedBody; } - inline PhysXSharedBody & getSharedBody() { return *_mSharedBody; } - inline uintptr_t getImpl() override { return reinterpret_cast(this); } - inline uintptr_t getNodeHandle() override { return reinterpret_cast(this->_mSharedBody->getNode()); } - void initialize(Node *node, ERigidBodyType t, uint32_t g) override; - void onEnable() override; - void onDisable() override; - void onDestroy() override; - bool isAwake() override; - bool isSleepy() override; - bool isSleeping() override; - void setType(ERigidBodyType v) override; - void setMass(float v) override; - void setLinearDamping(float v) override; - void setAngularDamping(float v) override; - void useGravity(bool v) override; - void useCCD(bool v) override; - void setLinearFactor(float x, float y, float z) override; - void setAngularFactor(float x, float y, float z) override; - void setAllowSleep(bool v) override; - void wakeUp() override; - void sleep() override; - void clearState() override; - void clearForces() override; - void clearVelocity() override; - void setSleepThreshold(float v) override; - float getSleepThreshold() override; - cc::Vec3 getLinearVelocity() override; - void setLinearVelocity(float x, float y, float z) override; - cc::Vec3 getAngularVelocity() override; - void setAngularVelocity(float x, float y, float z) override; - void applyForce(float x, float y, float z, float rx, float ry, float rz) override; - void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) override; - void applyImpulse(float x, float y, float z, float rx, float ry, float rz) override; - void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) override; - void applyTorque(float x, float y, float z) override; - void applyLocalTorque(float x, float y, float z) override; - uint32_t getGroup() override; - uint32_t getMask() override; - void setGroup(uint32_t g) override; - void setMask(uint32_t m) override; - inline uint32_t getInitialGroup() const { return _mGroup; } + inline PhysXSharedBody &getSharedBody() { return *_mSharedBody; } + inline uintptr_t getImpl() override { return reinterpret_cast(this); } + inline uintptr_t getNodeHandle() override { return reinterpret_cast(this->_mSharedBody->getNode()); } + void initialize(Node *node, ERigidBodyType t, uint32_t g) override; + void onEnable() override; + void onDisable() override; + void onDestroy() override; + bool isAwake() override; + bool isSleepy() override; + bool isSleeping() override; + void setType(ERigidBodyType v) override; + void setMass(float v) override; + void setLinearDamping(float v) override; + void setAngularDamping(float v) override; + void useGravity(bool v) override; + void useCCD(bool v) override; + void setLinearFactor(float x, float y, float z) override; + void setAngularFactor(float x, float y, float z) override; + void setAllowSleep(bool v) override; + void wakeUp() override; + void sleep() override; + void clearState() override; + void clearForces() override; + void clearVelocity() override; + void setSleepThreshold(float v) override; + float getSleepThreshold() override; + cc::Vec3 getLinearVelocity() override; + void setLinearVelocity(float x, float y, float z) override; + cc::Vec3 getAngularVelocity() override; + void setAngularVelocity(float x, float y, float z) override; + void applyForce(float x, float y, float z, float rx, float ry, float rz) override; + void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) override; + void applyImpulse(float x, float y, float z, float rx, float ry, float rz) override; + void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) override; + void applyTorque(float x, float y, float z) override; + void applyLocalTorque(float x, float y, float z) override; + uint32_t getGroup() override; + uint32_t getMask() override; + void setGroup(uint32_t g) override; + void setMask(uint32_t m) override; + inline uint32_t getInitialGroup() const { return _mGroup; } protected: // physx::PhysXWorld* mWrappedWorld; PhysXSharedBody *_mSharedBody; - uint32_t _mGroup; - bool _mEnabled; + uint32_t _mGroup; + bool _mEnabled; }; } // namespace physics diff --git a/native/cocos/physics/physx/PhysXSharedBody.cpp b/native/cocos/physics/physx/PhysXSharedBody.cpp index f37ed03777..9641ac3ac0 100644 --- a/native/cocos/physics/physx/PhysXSharedBody.cpp +++ b/native/cocos/physics/physx/PhysXSharedBody.cpp @@ -50,8 +50,8 @@ ccstd::unordered_map PhysXSharedBody::sharedBodesMap; static int idCounter = 0; PhysXSharedBody::PhysXSharedBody( - Node * node, - PhysXWorld *const world, + Node *node, + PhysXWorld *const world, PhysXRigidBody *const body) : _mID(idCounter++), _mRef(0), _mType(ERigidBodyType::STATIC), @@ -63,22 +63,22 @@ PhysXSharedBody::PhysXSharedBody( _mWrappedWorld(world), _mWrappedBody(body) { _mImpl.ptr = 0; - _mNode = node; + _mNode = node; }; PhysXSharedBody *PhysXSharedBody::getSharedBody(const Node *node, PhysXWorld *const world, PhysXRigidBody *const body) { - auto iter = sharedBodesMap.find(const_cast(node)); + auto iter = sharedBodesMap.find(const_cast(node)); PhysXSharedBody *newSB; if (iter != sharedBodesMap.end()) { newSB = iter->second; } else { - newSB = ccnew PhysXSharedBody(const_cast(node), world, body); + newSB = ccnew PhysXSharedBody(const_cast(node), world, body); newSB->_mFilterData.word0 = 1; newSB->_mFilterData.word1 = world->getMaskByIndex(0); sharedBodesMap.insert(std::pair(const_cast(node), newSB)); } if (body != nullptr) { - auto g = body->getInitialGroup(); + auto g = body->getInitialGroup(); newSB->_mFilterData.word0 = g; newSB->_mFilterData.word1 = world->getMaskByIndex(static_cast(log2(g))); } @@ -121,9 +121,9 @@ void PhysXSharedBody::enabled(bool v) { _mWrappedWorld->addActor(*this); } } else { - auto *wb = _mWrappedBody; - auto ws = _mWrappedShapes; - auto isRemove = ws.empty() && (wb == nullptr || (wb != nullptr && !wb->isEnabled())); + auto *wb = _mWrappedBody; + auto ws = _mWrappedShapes; + auto isRemove = ws.empty() && (wb == nullptr || (wb != nullptr && !wb->isEnabled())); if (isRemove) { _mIndex = -1; if (!isStaticOrKinematic()) { @@ -179,7 +179,7 @@ void PhysXSharedBody::initStaticActor() { if (!transform.p.isFinite()) transform.p = PxVec3{PxIdentity}; if (!transform.q.isUnit()) transform.q = PxQuat{PxIdentity}; PxPhysics &phy = PxGetPhysics(); - _mStaticActor = phy.createRigidStatic(transform); + _mStaticActor = phy.createRigidStatic(transform); } } @@ -245,7 +245,7 @@ void PhysXSharedBody::syncSceneToPhysics() { void PhysXSharedBody::syncSceneWithCheck() { if (getNode()->getChangedFlags() & static_cast(TransformBit::SCALE)) syncScale(); - auto wp = getImpl().rigidActor->getGlobalPose(); + auto wp = getImpl().rigidActor->getGlobalPose(); bool needUpdate = false; getNode()->updateWorldTransform(); if (wp.p != getNode()->getWorldPosition()) { @@ -272,8 +272,8 @@ void PhysXSharedBody::syncPhysicsToScene() { } void PhysXSharedBody::addShape(const PhysXShape &shape) { - auto beg = _mWrappedShapes.begin(); - auto end = _mWrappedShapes.end(); + auto beg = _mWrappedShapes.begin(); + auto end = _mWrappedShapes.end(); auto iter = find(beg, end, &shape); if (iter == end) { shape.getShape().setSimulationFilterData(_mFilterData); @@ -288,8 +288,8 @@ void PhysXSharedBody::addShape(const PhysXShape &shape) { } void PhysXSharedBody::removeShape(const PhysXShape &shape) { - auto beg = _mWrappedShapes.begin(); - auto end = _mWrappedShapes.end(); + auto beg = _mWrappedShapes.begin(); + auto end = _mWrappedShapes.end(); auto iter = find(beg, end, &shape); if (iter != end) { _mWrappedShapes.erase(iter); @@ -303,13 +303,13 @@ void PhysXSharedBody::removeShape(const PhysXShape &shape) { void PhysXSharedBody::addJoint(const PhysXJoint &joint, const PxJointActorIndex::Enum index) { if (index == PxJointActorIndex::eACTOR1) { - auto beg = _mWrappedJoints1.begin(); - auto end = _mWrappedJoints1.end(); + auto beg = _mWrappedJoints1.begin(); + auto end = _mWrappedJoints1.end(); auto iter = find(beg, end, &joint); if (iter == end) _mWrappedJoints1.push_back(&const_cast(joint)); } else { - auto beg = _mWrappedJoints0.begin(); - auto end = _mWrappedJoints0.end(); + auto beg = _mWrappedJoints0.begin(); + auto end = _mWrappedJoints0.end(); auto iter = find(beg, end, &joint); if (iter == end) _mWrappedJoints0.push_back(&const_cast(joint)); } @@ -317,13 +317,13 @@ void PhysXSharedBody::addJoint(const PhysXJoint &joint, const PxJointActorIndex: void PhysXSharedBody::removeJoint(const PhysXJoint &joint, const PxJointActorIndex::Enum index) { if (index == PxJointActorIndex::eACTOR1) { - auto beg = _mWrappedJoints1.begin(); - auto end = _mWrappedJoints1.end(); + auto beg = _mWrappedJoints1.begin(); + auto end = _mWrappedJoints1.end(); auto iter = find(beg, end, &joint); if (iter != end) _mWrappedJoints1.erase(iter); } else { - auto beg = _mWrappedJoints0.begin(); - auto end = _mWrappedJoints0.end(); + auto beg = _mWrappedJoints0.begin(); + auto end = _mWrappedJoints0.end(); auto iter = find(beg, end, &joint); if (iter != end) _mWrappedJoints0.erase(iter); } diff --git a/native/cocos/physics/physx/PhysXSharedBody.h b/native/cocos/physics/physx/PhysXSharedBody.h index 313b57582d..f3639d215e 100644 --- a/native/cocos/physics/physx/PhysXSharedBody.h +++ b/native/cocos/physics/physx/PhysXSharedBody.h @@ -43,62 +43,62 @@ class PhysXRigidBody; class PhysXSharedBody final { public: static PhysXSharedBody *getSharedBody(const Node *node, PhysXWorld *world, PhysXRigidBody *body); - PhysXSharedBody() = delete; + PhysXSharedBody() = delete; PhysXSharedBody(const PhysXSharedBody &other) = delete; - PhysXSharedBody(PhysXSharedBody &&other) = delete; - void reference(bool v); - void enabled(bool v); - inline bool isInWorld() { return _mIndex >= 0; } - inline bool isStatic() { return static_cast(_mType) & static_cast(ERigidBodyType::STATIC); } - inline bool isKinematic() { return static_cast(_mType) & static_cast(ERigidBodyType::KINEMATIC); } - inline bool isStaticOrKinematic() { return static_cast(_mType) & static_cast(ERigidBodyType::STATIC) || static_cast(_mType) & static_cast(ERigidBodyType::KINEMATIC); } - inline bool isDynamic() { return !isStaticOrKinematic(); } - inline Node * getNode() const { return _mNode; } + PhysXSharedBody(PhysXSharedBody &&other) = delete; + void reference(bool v); + void enabled(bool v); + inline bool isInWorld() { return _mIndex >= 0; } + inline bool isStatic() { return static_cast(_mType) & static_cast(ERigidBodyType::STATIC); } + inline bool isKinematic() { return static_cast(_mType) & static_cast(ERigidBodyType::KINEMATIC); } + inline bool isStaticOrKinematic() { return static_cast(_mType) & static_cast(ERigidBodyType::STATIC) || static_cast(_mType) & static_cast(ERigidBodyType::KINEMATIC); } + inline bool isDynamic() { return !isStaticOrKinematic(); } + inline Node *getNode() const { return _mNode; } inline PhysXWorld &getWorld() const { return *_mWrappedWorld; } union UActor { - uintptr_t ptr; - physx::PxRigidActor * rigidActor; - physx::PxRigidStatic * rigidStatic; + uintptr_t ptr; + physx::PxRigidActor *rigidActor; + physx::PxRigidStatic *rigidStatic; physx::PxRigidDynamic *rigidDynamic; }; - UActor getImpl(); - void setType(ERigidBodyType v); - void setMass(float v); - void syncScale(); - void syncSceneToPhysics(); - void syncSceneWithCheck(); - void syncPhysicsToScene(); - void updateCenterOfMass(); - void addShape(const PhysXShape &shape); - void removeShape(const PhysXShape &shape); - void addJoint(const PhysXJoint &joint, physx::PxJointActorIndex::Enum index); - void removeJoint(const PhysXJoint &joint, physx::PxJointActorIndex::Enum index); - void setCollisionFilter(const physx::PxFilterData &data); - void clearForces(); - void clearVelocity(); - void setGroup(uint32_t v); - void setMask(uint32_t v); + UActor getImpl(); + void setType(ERigidBodyType v); + void setMass(float v); + void syncScale(); + void syncSceneToPhysics(); + void syncSceneWithCheck(); + void syncPhysicsToScene(); + void updateCenterOfMass(); + void addShape(const PhysXShape &shape); + void removeShape(const PhysXShape &shape); + void addJoint(const PhysXJoint &joint, physx::PxJointActorIndex::Enum index); + void removeJoint(const PhysXJoint &joint, physx::PxJointActorIndex::Enum index); + void setCollisionFilter(const physx::PxFilterData &data); + void clearForces(); + void clearVelocity(); + void setGroup(uint32_t v); + void setMask(uint32_t v); inline uint32_t getGroup() const { return _mFilterData.word0; } inline uint32_t getMask() const { return _mFilterData.word1; } private: static ccstd::unordered_map sharedBodesMap; - const uint32_t _mID; - uint8_t _mRef; - bool _mIsStatic; - ERigidBodyType _mType; - float _mMass; - int _mIndex; - physx::PxFilterData _mFilterData; - Node * _mNode; - UActor _mImpl; - physx::PxRigidStatic * _mStaticActor; - physx::PxRigidDynamic * _mDynamicActor; - PhysXWorld * _mWrappedWorld; - PhysXRigidBody * _mWrappedBody; - ccstd::vector _mWrappedShapes; - ccstd::vector _mWrappedJoints0; - ccstd::vector _mWrappedJoints1; + const uint32_t _mID; + uint8_t _mRef; + bool _mIsStatic; + ERigidBodyType _mType; + float _mMass; + int _mIndex; + physx::PxFilterData _mFilterData; + Node *_mNode; + UActor _mImpl; + physx::PxRigidStatic *_mStaticActor; + physx::PxRigidDynamic *_mDynamicActor; + PhysXWorld *_mWrappedWorld; + PhysXRigidBody *_mWrappedBody; + ccstd::vector _mWrappedShapes; + ccstd::vector _mWrappedJoints0; + ccstd::vector _mWrappedJoints1; PhysXSharedBody(Node *node, PhysXWorld *world, PhysXRigidBody *body); ~PhysXSharedBody(); void initActor(); diff --git a/native/cocos/physics/physx/PhysXUtils.cpp b/native/cocos/physics/physx/PhysXUtils.cpp index 228911d76c..f489f9c9ea 100644 --- a/native/cocos/physics/physx/PhysXUtils.cpp +++ b/native/cocos/physics/physx/PhysXUtils.cpp @@ -39,7 +39,7 @@ void pxSetFromTwoVectors(physx::PxQuat &out, const physx::PxVec3 &a, const physx out = physx::PxQuat{physx::PxIdentity}; } else { physx::PxVec3 c = a.cross(b); - out = physx::PxQuat{c.x, c.y, c.z, 1 + dot}; + out = physx::PxQuat{c.x, c.y, c.z, 1 + dot}; out.normalize(); } } diff --git a/native/cocos/physics/physx/PhysXWorld.cpp b/native/cocos/physics/physx/PhysXWorld.cpp index 9ce7fb5efc..f099ab0ba0 100644 --- a/native/cocos/physics/physx/PhysXWorld.cpp +++ b/native/cocos/physics/physx/PhysXWorld.cpp @@ -53,7 +53,7 @@ physx::PxPhysics &PhysXWorld::getPhysics() { PhysXWorld::PhysXWorld() { instance = this; - static physx::PxDefaultAllocator gAllocator; + static physx::PxDefaultAllocator gAllocator; static physx::PxDefaultErrorCallback gErrorCallback; _mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); physx::PxTolerancesScale scale{}; @@ -61,7 +61,7 @@ PhysXWorld::PhysXWorld() { physx::PxPvd *pvd = nullptr; #ifdef CC_DEBUG - pvd = _mPvd = physx::PxCreatePvd(*_mFoundation); + pvd = _mPvd = physx::PxCreatePvd(*_mFoundation); physx::PxPvdTransport *transport = physx::PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 10); _mPvd->connect(*transport, physx::PxPvdInstrumentationFlag::eALL); #endif @@ -72,14 +72,14 @@ PhysXWorld::PhysXWorld() { _mEventMgr = ccnew PhysXEventManager(); physx::PxSceneDesc sceneDesc(_mPhysics->getTolerancesScale()); - sceneDesc.gravity = physx::PxVec3(0.0F, -10.0F, 0.0F); - sceneDesc.cpuDispatcher = _mDispatcher; - sceneDesc.kineKineFilteringMode = physx::PxPairFilteringMode::eKEEP; + sceneDesc.gravity = physx::PxVec3(0.0F, -10.0F, 0.0F); + sceneDesc.cpuDispatcher = _mDispatcher; + sceneDesc.kineKineFilteringMode = physx::PxPairFilteringMode::eKEEP; sceneDesc.staticKineFilteringMode = physx::PxPairFilteringMode::eKEEP; sceneDesc.flags |= physx::PxSceneFlag::eENABLE_CCD; - sceneDesc.filterShader = simpleFilterShader; + sceneDesc.filterShader = simpleFilterShader; sceneDesc.simulationEventCallback = &_mEventMgr->getEventCallback(); - _mScene = _mPhysics->createScene(sceneDesc); + _mScene = _mPhysics->createScene(sceneDesc); _mCollisionMatrix[0] = 1; @@ -126,49 +126,49 @@ void PhysXWorld::setCollisionMatrix(uint32_t index, uint32_t mask) { uintptr_t PhysXWorld::createConvex(ConvexDesc &desc) { physx::PxConvexMeshDesc convexDesc; - convexDesc.points.count = desc.positionLength; - convexDesc.points.stride = sizeof(physx::PxVec3); - convexDesc.points.data = static_cast(desc.positions); - convexDesc.flags = physx::PxConvexFlag::eCOMPUTE_CONVEX; + convexDesc.points.count = desc.positionLength; + convexDesc.points.stride = sizeof(physx::PxVec3); + convexDesc.points.data = static_cast(desc.positions); + convexDesc.flags = physx::PxConvexFlag::eCOMPUTE_CONVEX; physx::PxConvexMesh *convexMesh = getCooking().createConvexMesh(convexDesc, PxGetPhysics().getPhysicsInsertionCallback()); return reinterpret_cast(convexMesh); } uintptr_t PhysXWorld::createTrimesh(TrimeshDesc &desc) { physx::PxTriangleMeshDesc meshDesc; - meshDesc.points.count = desc.positionLength; - meshDesc.points.stride = sizeof(physx::PxVec3); - meshDesc.points.data = static_cast(desc.positions); + meshDesc.points.count = desc.positionLength; + meshDesc.points.stride = sizeof(physx::PxVec3); + meshDesc.points.data = static_cast(desc.positions); meshDesc.triangles.count = desc.triangleLength; if (desc.isU16) { meshDesc.triangles.stride = 3 * sizeof(physx::PxU16); - meshDesc.triangles.data = static_cast(desc.triangles); - meshDesc.flags = physx::PxMeshFlag::e16_BIT_INDICES; + meshDesc.triangles.data = static_cast(desc.triangles); + meshDesc.flags = physx::PxMeshFlag::e16_BIT_INDICES; } else { meshDesc.triangles.stride = 3 * sizeof(physx::PxU32); - meshDesc.triangles.data = static_cast(desc.triangles); + meshDesc.triangles.data = static_cast(desc.triangles); } physx::PxTriangleMesh *triangleMesh = getCooking().createTriangleMesh(meshDesc, PxGetPhysics().getPhysicsInsertionCallback()); return reinterpret_cast(triangleMesh); } uintptr_t PhysXWorld::createHeightField(HeightFieldDesc &desc) { - const auto rows = desc.rows; - const auto columns = desc.columns; - const physx::PxU32 counts = rows * columns; - auto * samples = ccnew physx::PxHeightFieldSample[counts]; + const auto rows = desc.rows; + const auto columns = desc.columns; + const physx::PxU32 counts = rows * columns; + auto *samples = ccnew physx::PxHeightFieldSample[counts]; for (physx::PxU32 r = 0; r < rows; r++) { for (physx::PxU32 c = 0; c < columns; c++) { - const auto index = c + r * columns; - auto v = (static_cast(desc.samples))[index]; + const auto index = c + r * columns; + auto v = (static_cast(desc.samples))[index]; samples[index].height = v; } } physx::PxHeightFieldDesc hfDesc; - hfDesc.nbRows = rows; - hfDesc.nbColumns = columns; - hfDesc.samples.data = samples; - hfDesc.samples.stride = sizeof(physx::PxHeightFieldSample); + hfDesc.nbRows = rows; + hfDesc.nbColumns = columns; + hfDesc.samples.data = samples; + hfDesc.samples.stride = sizeof(physx::PxHeightFieldSample); physx::PxHeightField *hf = getCooking().createHeightField(hfDesc, PxGetPhysics().getPhysicsInsertionCallback()); delete[] samples; return reinterpret_cast(hf); @@ -177,7 +177,7 @@ uintptr_t PhysXWorld::createHeightField(HeightFieldDesc &desc) { uintptr_t PhysXWorld::createMaterial(uint16_t id, float f, float df, float r, uint8_t m0, uint8_t m1) { physx::PxMaterial *mat; - auto & m = getPxMaterialMap(); + auto &m = getPxMaterialMap(); if (m.find(id) == m.end()) { mat = PxGetPhysics().createMaterial(f, df, r); // add reference count avoid auto releasing by physx @@ -227,8 +227,8 @@ void PhysXWorld::setAllowSleep(bool val) { } void PhysXWorld::addActor(const PhysXSharedBody &sb) { - auto beg = _mSharedBodies.begin(); - auto end = _mSharedBodies.end(); + auto beg = _mSharedBodies.begin(); + auto end = _mSharedBodies.end(); auto iter = find(beg, end, &sb); if (iter == end) { _mScene->addActor(*(const_cast(sb).getImpl().rigidActor)); @@ -237,8 +237,8 @@ void PhysXWorld::addActor(const PhysXSharedBody &sb) { } void PhysXWorld::removeActor(const PhysXSharedBody &sb) { - auto beg = _mSharedBodies.begin(); - auto end = _mSharedBodies.end(); + auto beg = _mSharedBodies.begin(); + auto end = _mSharedBodies.end(); auto iter = find(beg, end, &sb); if (iter != end) { _mScene->removeActor(*(const_cast(sb).getImpl().rigidActor), true); @@ -248,19 +248,19 @@ void PhysXWorld::removeActor(const PhysXSharedBody &sb) { bool PhysXWorld::raycast(RaycastOptions &opt) { physx::PxQueryCache *cache = nullptr; - const auto o = opt.origin; - const auto ud = opt.unitDir; - physx::PxVec3 origin{o.x, o.y, o.z}; - physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; + const auto o = opt.origin; + const auto ud = opt.unitDir; + physx::PxVec3 origin{o.x, o.y, o.z}; + physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; unitDir.normalize(); - physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; + physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; physx::PxSceneQueryFilterData filterData; filterData.data.word0 = opt.mask; filterData.data.word3 = QUERY_FILTER | (opt.queryTrigger ? 0 : QUERY_CHECK_TRIGGER); - filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; - auto & hitBuffer = getPxRaycastHitBuffer(); - bool result = false; - const auto nbTouches = physx::PxSceneQueryExt::raycastMultiple( + filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; + auto &hitBuffer = getPxRaycastHitBuffer(); + bool result = false; + const auto nbTouches = physx::PxSceneQueryExt::raycastMultiple( getScene(), origin, unitDir, opt.distance, flags, hitBuffer.data(), static_cast(hitBuffer.size()), result, filterData, &getQueryFilterShader(), cache); if (nbTouches == 0 || nbTouches == -1) return false; @@ -269,7 +269,7 @@ bool PhysXWorld::raycast(RaycastOptions &opt) { for (physx::PxI32 i = 0; i < nbTouches; i++) { const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(hitBuffer[i].shape)); if (shapeIter == getPxShapeMap().end()) return false; - r[i].shape = shapeIter->second; + r[i].shape = shapeIter->second; r[i].distance = hitBuffer[i].distance; pxSetVec3Ext(r[i].hitNormal, hitBuffer[i].normal); pxSetVec3Ext(r[i].hitPoint, hitBuffer[i].position); @@ -283,26 +283,26 @@ ccstd::vector &PhysXWorld::raycastResult() { } bool PhysXWorld::raycastClosest(RaycastOptions &opt) { - physx::PxRaycastHit hit; + physx::PxRaycastHit hit; physx::PxQueryCache *cache = nullptr; - const auto o = opt.origin; - const auto ud = opt.unitDir; - physx::PxVec3 origin{o.x, o.y, o.z}; - physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; + const auto o = opt.origin; + const auto ud = opt.unitDir; + physx::PxVec3 origin{o.x, o.y, o.z}; + physx::PxVec3 unitDir{ud.x, ud.y, ud.z}; unitDir.normalize(); - physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; + physx::PxHitFlags flags = physx::PxHitFlag::ePOSITION | physx::PxHitFlag::eNORMAL; physx::PxSceneQueryFilterData filterData; filterData.data.word0 = opt.mask; filterData.data.word3 = QUERY_FILTER | (opt.queryTrigger ? 0 : QUERY_CHECK_TRIGGER) | QUERY_SINGLE_HIT; - filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; - const auto result = physx::PxSceneQueryExt::raycastSingle( + filterData.flags = physx::PxQueryFlag::eSTATIC | physx::PxQueryFlag::eDYNAMIC | physx::PxQueryFlag::ePREFILTER; + const auto result = physx::PxSceneQueryExt::raycastSingle( getScene(), origin, unitDir, opt.distance, flags, hit, filterData, &getQueryFilterShader(), cache); if (result) { - auto & r = raycastClosestResult(); + auto &r = raycastClosestResult(); const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(hit.shape)); if (shapeIter == getPxShapeMap().end()) return false; - r.shape = shapeIter->second; + r.shape = shapeIter->second; r.distance = hit.distance; pxSetVec3Ext(r.hitPoint, hit.position); pxSetVec3Ext(r.hitNormal, hit.normal); diff --git a/native/cocos/physics/physx/PhysXWorld.h b/native/cocos/physics/physx/PhysXWorld.h index 0fe5650d9a..5fa77eea85 100644 --- a/native/cocos/physics/physx/PhysXWorld.h +++ b/native/cocos/physics/physx/PhysXWorld.h @@ -41,26 +41,26 @@ namespace physics { class PhysXWorld final : virtual public IPhysicsWorld { public: - static PhysXWorld & getInstance(); + static PhysXWorld &getInstance(); static physx::PxFoundation &getFundation(); - static physx::PxCooking & getCooking(); - static physx::PxPhysics & getPhysics(); + static physx::PxCooking &getCooking(); + static physx::PxPhysics &getPhysics(); PhysXWorld(); ~PhysXWorld() override; - void step(float fixedTimeStep) override; - void setGravity(float x, float y, float z) override; - void setAllowSleep(bool v) override; - void emitEvents() override; - void setCollisionMatrix(uint32_t index, uint32_t mask) override; - bool raycast(RaycastOptions &opt) override; - bool raycastClosest(RaycastOptions &opt) override; - ccstd::vector & raycastResult() override; - RaycastResult & raycastClosestResult() override; - uintptr_t createConvex(ConvexDesc &desc) override; - uintptr_t createTrimesh(TrimeshDesc &desc) override; - uintptr_t createHeightField(HeightFieldDesc &desc) override; - uintptr_t createMaterial(uint16_t id, float f, float df, float r, - uint8_t m0, uint8_t m1) override; + void step(float fixedTimeStep) override; + void setGravity(float x, float y, float z) override; + void setAllowSleep(bool v) override; + void emitEvents() override; + void setCollisionMatrix(uint32_t index, uint32_t mask) override; + bool raycast(RaycastOptions &opt) override; + bool raycastClosest(RaycastOptions &opt) override; + ccstd::vector &raycastResult() override; + RaycastResult &raycastClosestResult() override; + uintptr_t createConvex(ConvexDesc &desc) override; + uintptr_t createTrimesh(TrimeshDesc &desc) override; + uintptr_t createHeightField(HeightFieldDesc &desc) override; + uintptr_t createMaterial(uint16_t id, float f, float df, float r, + uint8_t m0, uint8_t m1) override; inline ccstd::vector> &getTriggerEventPairs() override { return _mEventMgr->getTriggerPairs(); } @@ -72,29 +72,29 @@ public: void destroy() override; inline PhysXSharedBody *getSharedBody( - const Node * node, + const Node *node, PhysXRigidBody *const body = nullptr) { return PhysXSharedBody::getSharedBody(node, this, body); } inline physx::PxScene &getScene() const { return *_mScene; } - uint32_t getMaskByIndex(uint32_t i); - void syncPhysicsToScene(); - void addActor(const PhysXSharedBody &sb); - void removeActor(const PhysXSharedBody &sb); + uint32_t getMaskByIndex(uint32_t i); + void syncPhysicsToScene(); + void addActor(const PhysXSharedBody &sb); + void removeActor(const PhysXSharedBody &sb); private: - static PhysXWorld * instance; + static PhysXWorld *instance; physx::PxFoundation *_mFoundation; - physx::PxCooking * _mCooking; - physx::PxPhysics * _mPhysics; + physx::PxCooking *_mCooking; + physx::PxPhysics *_mPhysics; #ifdef CC_DEBUG physx::PxPvd *_mPvd; #endif - physx::PxDefaultCpuDispatcher * _mDispatcher; - physx::PxScene * _mScene; - PhysXEventManager * _mEventMgr; - uint32_t _mCollisionMatrix[31]; + physx::PxDefaultCpuDispatcher *_mDispatcher; + physx::PxScene *_mScene; + PhysXEventManager *_mEventMgr; + uint32_t _mCollisionMatrix[31]; ccstd::vector _mSharedBodies; }; diff --git a/native/cocos/physics/physx/joints/PhysXDistance.cpp b/native/cocos/physics/physx/joints/PhysXDistance.cpp index 2b85e556e5..4217dcd15a 100644 --- a/native/cocos/physics/physx/joints/PhysXDistance.cpp +++ b/native/cocos/physics/physx/joints/PhysXDistance.cpp @@ -59,7 +59,7 @@ void PhysXDistance::updateScale1() { void PhysXDistance::updatePose() { physx::PxTransform pose0{physx::PxIdentity}; physx::PxTransform pose1{physx::PxIdentity}; - auto * node0 = _mSharedBody->getNode(); + auto *node0 = _mSharedBody->getNode(); node0->updateWorldTransform(); pose0.p = _mPivotA * node0->getWorldScale(); _mJoint->setLocalPose(physx::PxJointActorIndex::eACTOR0, pose0); diff --git a/native/cocos/physics/physx/joints/PhysXDistance.h b/native/cocos/physics/physx/joints/PhysXDistance.h index 75e209b182..180755a92e 100644 --- a/native/cocos/physics/physx/joints/PhysXDistance.h +++ b/native/cocos/physics/physx/joints/PhysXDistance.h @@ -40,8 +40,8 @@ public: void updateScale1() override; private: - void onComponentSet() override; - void updatePose(); + void onComponentSet() override; + void updatePose(); physx::PxVec3 _mPivotA; physx::PxVec3 _mPivotB; }; diff --git a/native/cocos/physics/physx/joints/PhysXJoint.cpp b/native/cocos/physics/physx/joints/PhysXJoint.cpp index 75037efb2f..018b06f783 100644 --- a/native/cocos/physics/physx/joints/PhysXJoint.cpp +++ b/native/cocos/physics/physx/joints/PhysXJoint.cpp @@ -34,7 +34,7 @@ namespace physics { physx::PxRigidActor *PhysXJoint::tempRigidActor = nullptr; void PhysXJoint::initialize(Node *node) { - auto &ins = PhysXWorld::getInstance(); + auto &ins = PhysXWorld::getInstance(); _mSharedBody = ins.getSharedBody(node); _mSharedBody->reference(true); onComponentSet(); @@ -62,7 +62,7 @@ void PhysXJoint::onDestroy() { void PhysXJoint::setConnectedBody(uintptr_t v) { if (v) { - auto &ins = PhysXWorld::getInstance(); + auto &ins = PhysXWorld::getInstance(); _mConnectedBody = ins.getSharedBody(reinterpret_cast(v)); } else { _mConnectedBody = nullptr; diff --git a/native/cocos/physics/physx/joints/PhysXJoint.h b/native/cocos/physics/physx/joints/PhysXJoint.h index 3cd36556fb..3ff193475d 100644 --- a/native/cocos/physics/physx/joints/PhysXJoint.h +++ b/native/cocos/physics/physx/joints/PhysXJoint.h @@ -40,24 +40,24 @@ class PhysXJoint : virtual public IBaseJoint { public: ~PhysXJoint() override = default; - inline uintptr_t getImpl() override { return reinterpret_cast(this); } - void initialize(Node *node) override; - void onEnable() override; - void onDisable() override; - void onDestroy() override; - void setConnectedBody(uintptr_t v) override; - void setEnableCollision(bool v) override; - virtual void updateScale0() = 0; - virtual void updateScale1() = 0; + inline uintptr_t getImpl() override { return reinterpret_cast(this); } + void initialize(Node *node) override; + void onEnable() override; + void onDisable() override; + void onDestroy() override; + void setConnectedBody(uintptr_t v) override; + void setEnableCollision(bool v) override; + virtual void updateScale0() = 0; + virtual void updateScale1() = 0; static physx::PxRigidActor &getTempRigidActor(); - static void releaseTempRigidActor(); + static void releaseTempRigidActor(); protected: - physx::PxJoint * _mJoint{nullptr}; + physx::PxJoint *_mJoint{nullptr}; PhysXSharedBody *_mSharedBody{nullptr}; PhysXSharedBody *_mConnectedBody{nullptr}; - bool _mEnableCollision{false}; - virtual void onComponentSet() = 0; + bool _mEnableCollision{false}; + virtual void onComponentSet() = 0; private: static physx::PxRigidActor *tempRigidActor; diff --git a/native/cocos/physics/physx/joints/PhysXRevolute.cpp b/native/cocos/physics/physx/joints/PhysXRevolute.cpp index 952de3f93b..18a04f8263 100644 --- a/native/cocos/physics/physx/joints/PhysXRevolute.cpp +++ b/native/cocos/physics/physx/joints/PhysXRevolute.cpp @@ -65,7 +65,7 @@ void PhysXRevolute::updateScale1() { void PhysXRevolute::updatePose() { physx::PxTransform pose0{physx::PxIdentity}; physx::PxTransform pose1{physx::PxIdentity}; - auto * node0 = _mSharedBody->getNode(); + auto *node0 = _mSharedBody->getNode(); node0->updateWorldTransform(); pose0.p = _mPivotA * node0->getWorldScale(); pxSetFromTwoVectors(pose0.q, physx::PxVec3{1.F, 0.F, 0.F}, _mAxis); diff --git a/native/cocos/physics/physx/joints/PhysXRevolute.h b/native/cocos/physics/physx/joints/PhysXRevolute.h index c22929b1bb..3c6ddf0e9e 100644 --- a/native/cocos/physics/physx/joints/PhysXRevolute.h +++ b/native/cocos/physics/physx/joints/PhysXRevolute.h @@ -41,8 +41,8 @@ public: void updateScale1() override; private: - void onComponentSet() override; - void updatePose(); + void onComponentSet() override; + void updatePose(); physx::PxVec3 _mPivotA; physx::PxVec3 _mPivotB; physx::PxVec3 _mAxis; diff --git a/native/cocos/physics/physx/shapes/PhysXBox.cpp b/native/cocos/physics/physx/shapes/PhysXBox.cpp index 98a8cea54e..7d34886fc2 100644 --- a/native/cocos/physics/physx/shapes/PhysXBox.cpp +++ b/native/cocos/physics/physx/shapes/PhysXBox.cpp @@ -52,8 +52,8 @@ void PhysXBox::updateScale() { } void PhysXBox::updateGeometry() { - auto *node = getSharedBody().getNode(); - auto &geo = getPxGeometry(); + auto *node = getSharedBody().getNode(); + auto &geo = getPxGeometry(); geo.halfExtents = _mHalfExtents; node->updateWorldTransform(); geo.halfExtents *= node->getWorldScale(); diff --git a/native/cocos/physics/physx/shapes/PhysXBox.h b/native/cocos/physics/physx/shapes/PhysXBox.h index 7a817510b5..b897ddb56e 100644 --- a/native/cocos/physics/physx/shapes/PhysXBox.h +++ b/native/cocos/physics/physx/shapes/PhysXBox.h @@ -39,8 +39,8 @@ public: private: physx::PxVec3 _mHalfExtents; - void updateGeometry(); - void onComponentSet() override; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXCapsule.cpp b/native/cocos/physics/physx/shapes/PhysXCapsule.cpp index d2584de50f..50764b979c 100644 --- a/native/cocos/physics/physx/shapes/PhysXCapsule.cpp +++ b/native/cocos/physics/physx/shapes/PhysXCapsule.cpp @@ -66,29 +66,29 @@ void PhysXCapsule::updateScale() { void PhysXCapsule::updateGeometry() { auto *node = getSharedBody().getNode(); - auto &geo = getPxGeometry(); - float rs = 1.F; - float hs = 1.F; + auto &geo = getPxGeometry(); + float rs = 1.F; + float hs = 1.F; node->updateWorldTransform(); switch (_mDirection) { case EAxisDirection::X_AXIS: - hs = physx::PxAbs(node->getWorldScale().x); - rs = pxAbsMax(node->getWorldScale().y, node->getWorldScale().z); + hs = physx::PxAbs(node->getWorldScale().x); + rs = pxAbsMax(node->getWorldScale().y, node->getWorldScale().z); _mRotation = physx::PxQuat{physx::PxIdentity}; break; case EAxisDirection::Z_AXIS: - hs = physx::PxAbs(node->getWorldScale().z); - rs = pxAbsMax(node->getWorldScale().x, node->getWorldScale().y); + hs = physx::PxAbs(node->getWorldScale().z); + rs = pxAbsMax(node->getWorldScale().x, node->getWorldScale().y); _mRotation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 1.F, 0.F}); break; case EAxisDirection::Y_AXIS: default: - hs = physx::PxAbs(node->getWorldScale().y); - rs = pxAbsMax(node->getWorldScale().x, node->getWorldScale().z); + hs = physx::PxAbs(node->getWorldScale().y); + rs = pxAbsMax(node->getWorldScale().x, node->getWorldScale().z); _mRotation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 0.F, 1.F}); break; } - geo.radius = physx::PxMax(physx::PxAbs(_mRadius * rs), PX_NORMALIZATION_EPSILON); + geo.radius = physx::PxMax(physx::PxAbs(_mRadius * rs), PX_NORMALIZATION_EPSILON); geo.halfHeight = physx::PxMax(physx::PxAbs(_mCylinderHeight / 2 * hs), PX_NORMALIZATION_EPSILON); } diff --git a/native/cocos/physics/physx/shapes/PhysXCapsule.h b/native/cocos/physics/physx/shapes/PhysXCapsule.h index 8da114f02e..aaadf2b011 100644 --- a/native/cocos/physics/physx/shapes/PhysXCapsule.h +++ b/native/cocos/physics/physx/shapes/PhysXCapsule.h @@ -40,11 +40,11 @@ public: void updateScale() override; private: - float _mRadius; - float _mCylinderHeight; + float _mRadius; + float _mCylinderHeight; EAxisDirection _mDirection; - void updateGeometry(); - void onComponentSet() override; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXCone.cpp b/native/cocos/physics/physx/shapes/PhysXCone.cpp index ddfdd30d70..e51a763273 100644 --- a/native/cocos/physics/physx/shapes/PhysXCone.cpp +++ b/native/cocos/physics/physx/shapes/PhysXCone.cpp @@ -53,8 +53,8 @@ void PhysXCone::onComponentSet() { } void PhysXCone::setCone(float r, float h, EAxisDirection d) { - _mData.radius = r; - _mData.height = h; + _mData.radius = r; + _mData.height = h; _mData.direction = d; updateGeometry(); } @@ -62,7 +62,7 @@ void PhysXCone::setCone(float r, float h, EAxisDirection d) { void PhysXCone::updateGeometry() { if (!_mShape) return; static physx::PxMeshScale scale; - auto * node = getSharedBody().getNode(); + auto *node = getSharedBody().getNode(); node->updateWorldTransform(); pxSetVec3Ext(scale.scale, node->getWorldScale()); scale.scale.y *= std::max(0.0001F, _mData.height / 2); diff --git a/native/cocos/physics/physx/shapes/PhysXCone.h b/native/cocos/physics/physx/shapes/PhysXCone.h index b86969f082..d5ec7ad017 100644 --- a/native/cocos/physics/physx/shapes/PhysXCone.h +++ b/native/cocos/physics/physx/shapes/PhysXCone.h @@ -39,16 +39,16 @@ public: void updateScale() override; struct Cone { - float radius; - float height; + float radius; + float height; EAxisDirection direction; }; private: physx::PxConvexMesh *_mMesh; - Cone _mData; - void updateGeometry(); - void onComponentSet() override; + Cone _mData; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXCylinder.cpp b/native/cocos/physics/physx/shapes/PhysXCylinder.cpp index 5bb8fd492a..a4d20c714e 100644 --- a/native/cocos/physics/physx/shapes/PhysXCylinder.cpp +++ b/native/cocos/physics/physx/shapes/PhysXCylinder.cpp @@ -54,8 +54,8 @@ void PhysXCylinder::onComponentSet() { } void PhysXCylinder::setCylinder(float r, float h, EAxisDirection d) { - _mData.radius = r; - _mData.height = h; + _mData.radius = r; + _mData.height = h; _mData.direction = d; updateGeometry(); } @@ -63,7 +63,7 @@ void PhysXCylinder::setCylinder(float r, float h, EAxisDirection d) { void PhysXCylinder::updateGeometry() { if (!_mShape) return; static physx::PxMeshScale scale; - auto * node = getSharedBody().getNode(); + auto *node = getSharedBody().getNode(); node->updateWorldTransform(); pxSetVec3Ext(scale.scale, node->getWorldScale()); scale.scale.y *= std::max(0.0001F, _mData.height / 2); diff --git a/native/cocos/physics/physx/shapes/PhysXCylinder.h b/native/cocos/physics/physx/shapes/PhysXCylinder.h index e045644c41..deee2f243b 100644 --- a/native/cocos/physics/physx/shapes/PhysXCylinder.h +++ b/native/cocos/physics/physx/shapes/PhysXCylinder.h @@ -39,16 +39,16 @@ public: void updateScale() override; struct Cylinder { - float radius; - float height; + float radius; + float height; EAxisDirection direction; }; private: physx::PxConvexMesh *_mMesh; - Cylinder _mData; - void updateGeometry(); - void onComponentSet() override; + Cylinder _mData; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXPlane.cpp b/native/cocos/physics/physx/shapes/PhysXPlane.cpp index 4ff587a34e..112418bc47 100644 --- a/native/cocos/physics/physx/shapes/PhysXPlane.cpp +++ b/native/cocos/physics/physx/shapes/PhysXPlane.cpp @@ -54,8 +54,8 @@ void PhysXPlane::updateScale() { } void PhysXPlane::updateCenter() { - auto * node = getSharedBody().getNode(); - auto & geo = getPxGeometry(); + auto* node = getSharedBody().getNode(); + auto& geo = getPxGeometry(); physx::PxTransform local; pxSetFromTwoVectors(local.q, physx::PxVec3{1.F, 0.F, 0.F}, _mNormal); local.p = _mNormal * _mConstant + _mCenter; diff --git a/native/cocos/physics/physx/shapes/PhysXPlane.h b/native/cocos/physics/physx/shapes/PhysXPlane.h index b36ef6f96f..34a6c3647e 100644 --- a/native/cocos/physics/physx/shapes/PhysXPlane.h +++ b/native/cocos/physics/physx/shapes/PhysXPlane.h @@ -41,8 +41,8 @@ public: private: physx::PxVec3 _mNormal; physx::PxReal _mConstant; - void updateCenter() override; - void onComponentSet() override; + void updateCenter() override; + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXShape.cpp b/native/cocos/physics/physx/shapes/PhysXShape.cpp index 3104ae32f1..de26012df7 100644 --- a/native/cocos/physics/physx/shapes/PhysXShape.cpp +++ b/native/cocos/physics/physx/shapes/PhysXShape.cpp @@ -34,7 +34,7 @@ namespace physics { void PhysXShape::initialize(Node *node) { PhysXWorld &ins = PhysXWorld::getInstance(); - _mSharedBody = ins.getSharedBody(node); + _mSharedBody = ins.getSharedBody(node); getSharedBody().reference(true); onComponentSet(); insertToShapeMap(); @@ -123,7 +123,7 @@ void PhysXShape::updateFilterData(const physx::PxFilterData &data) { void PhysXShape::updateCenter() { if (!_mShape) return; - auto &sb = getSharedBody(); + auto &sb = getSharedBody(); auto *node = sb.getNode(); node->updateWorldTransform(); physx::PxTransform local{_mCenter * node->getWorldScale(), _mRotation}; diff --git a/native/cocos/physics/physx/shapes/PhysXShape.h b/native/cocos/physics/physx/shapes/PhysXShape.h index 0218deb449..043f3c19ee 100644 --- a/native/cocos/physics/physx/shapes/PhysXShape.h +++ b/native/cocos/physics/physx/shapes/PhysXShape.h @@ -47,42 +47,42 @@ class PhysXShape : virtual public IBaseShape { public: ~PhysXShape() override = default; - inline uintptr_t getImpl() override { return reinterpret_cast(this); } - void initialize(Node *node) override; - void onEnable() override; - void onDisable() override; - void onDestroy() override; - void setMaterial(uint16_t id, float f, float df, float r, - uint8_t m0, uint8_t m1) override; - void setAsTrigger(bool v) override; - void setCenter(float x, float y, float z) override; - geometry::AABB & getAABB() override; - geometry::Sphere & getBoundingSphere() override; - void updateEventListener(EShapeFilterFlag flag) override; - uint32_t getGroup() override; - void setGroup(uint32_t g) override; - uint32_t getMask() override; - void setMask(uint32_t m) override; - virtual void updateScale() = 0; - inline physx::PxVec3 & getCenter() { return _mCenter; } - inline physx::PxShape & getShape() const { return *_mShape; } + inline uintptr_t getImpl() override { return reinterpret_cast(this); } + void initialize(Node *node) override; + void onEnable() override; + void onDisable() override; + void onDestroy() override; + void setMaterial(uint16_t id, float f, float df, float r, + uint8_t m0, uint8_t m1) override; + void setAsTrigger(bool v) override; + void setCenter(float x, float y, float z) override; + geometry::AABB &getAABB() override; + geometry::Sphere &getBoundingSphere() override; + void updateEventListener(EShapeFilterFlag flag) override; + uint32_t getGroup() override; + void setGroup(uint32_t g) override; + uint32_t getMask() override; + void setMask(uint32_t m) override; + virtual void updateScale() = 0; + inline physx::PxVec3 &getCenter() { return _mCenter; } + inline physx::PxShape &getShape() const { return *_mShape; } inline PhysXSharedBody &getSharedBody() const { return *_mSharedBody; } - inline bool isTrigger() const { + inline bool isTrigger() const { return getShape().getFlags().isSet(physx::PxShapeFlag::eTRIGGER_SHAPE); } void updateFilterData(const physx::PxFilterData &data); protected: PhysXSharedBody *_mSharedBody{nullptr}; - physx::PxShape * _mShape{nullptr}; - physx::PxVec3 _mCenter; - physx::PxQuat _mRotation; - uint8_t _mFlag{0}; - bool _mEnabled{false}; - virtual void updateCenter(); - virtual void onComponentSet() = 0; - virtual void insertToShapeMap(); - virtual void eraseFromShapeMap(); + physx::PxShape *_mShape{nullptr}; + physx::PxVec3 _mCenter; + physx::PxQuat _mRotation; + uint8_t _mFlag{0}; + bool _mEnabled{false}; + virtual void updateCenter(); + virtual void onComponentSet() = 0; + virtual void insertToShapeMap(); + virtual void eraseFromShapeMap(); }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXSphere.cpp b/native/cocos/physics/physx/shapes/PhysXSphere.cpp index b8ffe59f67..377cb0b4c5 100644 --- a/native/cocos/physics/physx/shapes/PhysXSphere.cpp +++ b/native/cocos/physics/physx/shapes/PhysXSphere.cpp @@ -53,10 +53,10 @@ void PhysXSphere::updateScale() { void PhysXSphere::updateGeometry() { physx::PxVec3 scale; - auto * node = getSharedBody().getNode(); + auto *node = getSharedBody().getNode(); node->updateWorldTransform(); pxSetVec3Ext(scale, node->getWorldScale()); - auto &geo = getPxGeometry(); + auto &geo = getPxGeometry(); geo.radius = physx::PxMax(_mRadius * scale.abs().maxElement(), PX_NORMALIZATION_EPSILON); } diff --git a/native/cocos/physics/physx/shapes/PhysXSphere.h b/native/cocos/physics/physx/shapes/PhysXSphere.h index 4bedde1ef7..8a49051228 100644 --- a/native/cocos/physics/physx/shapes/PhysXSphere.h +++ b/native/cocos/physics/physx/shapes/PhysXSphere.h @@ -39,8 +39,8 @@ public: private: float _mRadius; - void updateGeometry(); - void onComponentSet() override; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXTerrain.cpp b/native/cocos/physics/physx/shapes/PhysXTerrain.cpp index 7bb8caa27b..000c9068ea 100644 --- a/native/cocos/physics/physx/shapes/PhysXTerrain.cpp +++ b/native/cocos/physics/physx/shapes/PhysXTerrain.cpp @@ -40,9 +40,9 @@ PhysXTerrain::PhysXTerrain() : _mTerrain(nullptr), void PhysXTerrain::setTerrain(uintptr_t handle, float rs, float cs, float hs) { if (_mShape) return; if (reinterpret_cast(_mTerrain) == handle) return; - _mTerrain = reinterpret_cast(handle); - _mRowScale = rs; - _mColScale = cs; + _mTerrain = reinterpret_cast(handle); + _mRowScale = rs; + _mColScale = cs; _mHeightScale = hs; if (_mSharedBody && _mTerrain) { onComponentSet(); @@ -56,11 +56,11 @@ void PhysXTerrain::setTerrain(uintptr_t handle, float rs, float cs, float hs) { void PhysXTerrain::onComponentSet() { if (_mTerrain) { physx::PxHeightFieldGeometry geom; - geom.rowScale = _mRowScale; + geom.rowScale = _mRowScale; geom.columnScale = _mColScale; geom.heightScale = _mHeightScale; geom.heightField = _mTerrain; - _mShape = PxGetPhysics().createShape(geom, getDefaultMaterial(), true); + _mShape = PxGetPhysics().createShape(geom, getDefaultMaterial(), true); } } diff --git a/native/cocos/physics/physx/shapes/PhysXTerrain.h b/native/cocos/physics/physx/shapes/PhysXTerrain.h index de801a3658..b76f2c1e60 100644 --- a/native/cocos/physics/physx/shapes/PhysXTerrain.h +++ b/native/cocos/physics/physx/shapes/PhysXTerrain.h @@ -41,11 +41,11 @@ public: private: physx::PxHeightField *_mTerrain; - float _mRowScale; - float _mColScale; - float _mHeightScale; - bool _mIsTrigger; - void onComponentSet() override; + float _mRowScale; + float _mColScale; + float _mHeightScale; + bool _mIsTrigger; + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp b/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp index 19ba92b628..f770e2b12f 100644 --- a/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp +++ b/native/cocos/physics/physx/shapes/PhysXTrimesh.cpp @@ -78,7 +78,7 @@ void PhysXTrimesh::updateScale() { void PhysXTrimesh::updateGeometry() { static physx::PxMeshScale scale; scale.rotation = physx::PxQuat{physx::PxIdentity}; - auto *node = getSharedBody().getNode(); + auto *node = getSharedBody().getNode(); node->updateWorldTransform(); pxSetVec3Ext(scale.scale, node->getWorldScale()); const auto &type = _mShape->getGeometryType(); diff --git a/native/cocos/physics/physx/shapes/PhysXTrimesh.h b/native/cocos/physics/physx/shapes/PhysXTrimesh.h index 3863853523..a875fb0c8b 100644 --- a/native/cocos/physics/physx/shapes/PhysXTrimesh.h +++ b/native/cocos/physics/physx/shapes/PhysXTrimesh.h @@ -40,11 +40,11 @@ public: void setAsTrigger(bool v) override; private: - bool _mConvex; + bool _mConvex; uintptr_t _mMeshHandle; - bool _mIsTrigger; - void updateGeometry(); - void onComponentSet() override; + bool _mIsTrigger; + void updateGeometry(); + void onComponentSet() override; }; } // namespace physics diff --git a/native/cocos/physics/sdk/Joint.h b/native/cocos/physics/sdk/Joint.h index 4cfae1ad38..2bcbbdfaee 100644 --- a/native/cocos/physics/sdk/Joint.h +++ b/native/cocos/physics/sdk/Joint.h @@ -40,12 +40,12 @@ CLASS(); \ ~CLASS() override; \ uintptr_t getImpl() override; \ - void initialize(Node *node) override; \ - void onEnable() override; \ - void onDisable() override; \ - void onDestroy() override; \ - void setEnableCollision(bool v) override; \ - void setConnectedBody(uintptr_t v) override; + void initialize(Node *node) override; \ + void onEnable() override; \ + void onDisable() override; \ + void onDestroy() override; \ + void setEnableCollision(bool v) override; \ + void setConnectedBody(uintptr_t v) override; namespace cc { namespace physics { @@ -54,12 +54,12 @@ CC_PHYSICS_JOINT_CLASS(RevoluteJoint) void setPivotA(float x, float y, float z) override; void setPivotB(float x, float y, float z) override; void setAxis(float x, float y, float z) override; -}; +}; // namespace physics CC_PHYSICS_JOINT_CLASS(DistanceJoint) void setPivotA(float x, float y, float z) override; void setPivotB(float x, float y, float z) override; -}; +}; // namespace cc } // namespace physics } // namespace cc diff --git a/native/cocos/physics/sdk/RigidBody.h b/native/cocos/physics/sdk/RigidBody.h index 2a04d5c199..554e2ccadf 100644 --- a/native/cocos/physics/sdk/RigidBody.h +++ b/native/cocos/physics/sdk/RigidBody.h @@ -37,43 +37,43 @@ public: ~RigidBody() override; inline uintptr_t getImpl() override { return _impl->getImpl(); }; inline uintptr_t getNodeHandle() override { return _impl->getNodeHandle(); }; - void initialize(Node *node, ERigidBodyType t, uint32_t g) override; - void onEnable() override; - void onDisable() override; - void onDestroy() override; - bool isAwake() override; - bool isSleepy() override; - bool isSleeping() override; - void setType(ERigidBodyType v) override; - void setMass(float v) override; - void setLinearDamping(float v) override; - void setAngularDamping(float v) override; - void useGravity(bool v) override; - void useCCD(bool v) override; - void setLinearFactor(float x, float y, float z) override; - void setAngularFactor(float x, float y, float z) override; - void setAllowSleep(bool v) override; - void wakeUp() override; - void sleep() override; - void clearState() override; - void clearForces() override; - void clearVelocity() override; - void setSleepThreshold(float v) override; - float getSleepThreshold() override; - cc::Vec3 getLinearVelocity() override; - void setLinearVelocity(float x, float y, float z) override; - cc::Vec3 getAngularVelocity() override; - void setAngularVelocity(float x, float y, float z) override; - void applyForce(float x, float y, float z, float rx, float ry, float rz) override; - void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) override; - void applyImpulse(float x, float y, float z, float rx, float ry, float rz) override; - void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) override; - void applyTorque(float x, float y, float z) override; - void applyLocalTorque(float x, float y, float z) override; - uint32_t getGroup() override; - void setGroup(uint32_t g) override; - uint32_t getMask() override; - void setMask(uint32_t m) override; + void initialize(Node *node, ERigidBodyType t, uint32_t g) override; + void onEnable() override; + void onDisable() override; + void onDestroy() override; + bool isAwake() override; + bool isSleepy() override; + bool isSleeping() override; + void setType(ERigidBodyType v) override; + void setMass(float v) override; + void setLinearDamping(float v) override; + void setAngularDamping(float v) override; + void useGravity(bool v) override; + void useCCD(bool v) override; + void setLinearFactor(float x, float y, float z) override; + void setAngularFactor(float x, float y, float z) override; + void setAllowSleep(bool v) override; + void wakeUp() override; + void sleep() override; + void clearState() override; + void clearForces() override; + void clearVelocity() override; + void setSleepThreshold(float v) override; + float getSleepThreshold() override; + cc::Vec3 getLinearVelocity() override; + void setLinearVelocity(float x, float y, float z) override; + cc::Vec3 getAngularVelocity() override; + void setAngularVelocity(float x, float y, float z) override; + void applyForce(float x, float y, float z, float rx, float ry, float rz) override; + void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) override; + void applyImpulse(float x, float y, float z, float rx, float ry, float rz) override; + void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) override; + void applyTorque(float x, float y, float z) override; + void applyLocalTorque(float x, float y, float z) override; + uint32_t getGroup() override; + void setGroup(uint32_t g) override; + uint32_t getMask() override; + void setMask(uint32_t m) override; private: std::unique_ptr _impl; diff --git a/native/cocos/physics/sdk/Shape.h b/native/cocos/physics/sdk/Shape.h index 113775a61a..33e6787f83 100644 --- a/native/cocos/physics/sdk/Shape.h +++ b/native/cocos/physics/sdk/Shape.h @@ -32,30 +32,30 @@ #include "core/geometry/Sphere.h" #include "physics/spec/IShape.h" -#define CC_PHYSICS_SHAPE_CLASS(CLASS) \ - class CC_DLL CLASS final : public I##CLASS { \ - protected: \ - std::unique_ptr _impl; \ - \ - public: \ - CLASS(); \ - ~CLASS() override; \ - uintptr_t getImpl() override; \ - void initialize(Node *node) override; \ - void onEnable() override; \ - void onDisable() override; \ - void onDestroy() override; \ - void setMaterial(uint16_t ID, float f, float df, float r, \ - uint8_t m0, uint8_t m1) override; \ - void setAsTrigger(bool v) override; \ - void setCenter(float x, float y, float z) override; \ - void updateEventListener(EShapeFilterFlag v) override; \ - geometry::AABB & getAABB() override; \ - geometry::Sphere &getBoundingSphere() override; \ - uint32_t getGroup() override; \ - void setGroup(uint32_t g) override; \ - uint32_t getMask() override; \ - void setMask(uint32_t m) override; +#define CC_PHYSICS_SHAPE_CLASS(CLASS) \ + class CC_DLL CLASS final : public I##CLASS { \ + protected: \ + std::unique_ptr _impl; \ + \ + public: \ + CLASS(); \ + ~CLASS() override; \ + uintptr_t getImpl() override; \ + void initialize(Node *node) override; \ + void onEnable() override; \ + void onDisable() override; \ + void onDestroy() override; \ + void setMaterial(uint16_t ID, float f, float df, float r, \ + uint8_t m0, uint8_t m1) override; \ + void setAsTrigger(bool v) override; \ + void setCenter(float x, float y, float z) override; \ + void updateEventListener(EShapeFilterFlag v) override; \ + geometry::AABB &getAABB() override; \ + geometry::Sphere &getBoundingSphere() override; \ + uint32_t getGroup() override; \ + void setGroup(uint32_t g) override; \ + uint32_t getMask() override; \ + void setMask(uint32_t m) override; namespace cc { namespace physics { diff --git a/native/cocos/physics/sdk/World.h b/native/cocos/physics/sdk/World.h index ee0308f48f..2bdec4a340 100644 --- a/native/cocos/physics/sdk/World.h +++ b/native/cocos/physics/sdk/World.h @@ -35,25 +35,25 @@ class CC_DLL World final : public IPhysicsWorld { public: World(); ~World() override; - void setGravity(float x, float y, float z) override; - void setAllowSleep(bool v) override; - void step(float fixedTimeStep) override; - void emitEvents() override; - void syncSceneToPhysics() override; - void syncSceneWithCheck() override; - void setCollisionMatrix(uint32_t i, uint32_t m) override; + void setGravity(float x, float y, float z) override; + void setAllowSleep(bool v) override; + void step(float fixedTimeStep) override; + void emitEvents() override; + void syncSceneToPhysics() override; + void syncSceneWithCheck() override; + void setCollisionMatrix(uint32_t i, uint32_t m) override; ccstd::vector> &getTriggerEventPairs() override; ccstd::vector> &getContactEventPairs() override; - bool raycast(RaycastOptions &opt) override; - bool raycastClosest(RaycastOptions &opt) override; - ccstd::vector & raycastResult() override; - RaycastResult & raycastClosestResult() override; - uintptr_t createConvex(ConvexDesc &desc) override; - uintptr_t createTrimesh(TrimeshDesc &desc) override; - uintptr_t createHeightField(HeightFieldDesc &desc) override; - uintptr_t createMaterial(uint16_t id, float f, float df, float r, - uint8_t m0, uint8_t m1) override; - void destroy() override; + bool raycast(RaycastOptions &opt) override; + bool raycastClosest(RaycastOptions &opt) override; + ccstd::vector &raycastResult() override; + RaycastResult &raycastClosestResult() override; + uintptr_t createConvex(ConvexDesc &desc) override; + uintptr_t createTrimesh(TrimeshDesc &desc) override; + uintptr_t createHeightField(HeightFieldDesc &desc) override; + uintptr_t createMaterial(uint16_t id, float f, float df, float r, + uint8_t m0, uint8_t m1) override; + void destroy() override; private: std::unique_ptr _impl; diff --git a/native/cocos/physics/spec/IBody.h b/native/cocos/physics/spec/IBody.h index c044ab3e46..56ad648fab 100644 --- a/native/cocos/physics/spec/IBody.h +++ b/native/cocos/physics/spec/IBody.h @@ -33,50 +33,50 @@ namespace cc { namespace physics { enum class ERigidBodyType : uint8_t { - DYNAMIC = 1, - STATIC = 2, + DYNAMIC = 1, + STATIC = 2, KINEMATIC = 4, }; class IRigidBody : public ILifecycle { public: - ~IRigidBody() override = default; - virtual uintptr_t getImpl() = 0; - virtual uintptr_t getNodeHandle() = 0; - virtual void initialize(Node *node, ERigidBodyType t, uint32_t g) = 0; - virtual bool isAwake() = 0; - virtual bool isSleepy() = 0; - virtual bool isSleeping() = 0; - virtual void setType(ERigidBodyType v) = 0; - virtual void setMass(float v) = 0; - virtual void setLinearDamping(float v) = 0; - virtual void setAngularDamping(float v) = 0; - virtual void useGravity(bool v) = 0; - virtual void useCCD(bool v) = 0; - virtual void setLinearFactor(float x, float y, float z) = 0; - virtual void setAngularFactor(float x, float y, float z) = 0; - virtual void setAllowSleep(bool v) = 0; - virtual void wakeUp() = 0; - virtual void sleep() = 0; - virtual void clearState() = 0; - virtual void clearForces() = 0; - virtual void clearVelocity() = 0; - virtual void setSleepThreshold(float v) = 0; - virtual float getSleepThreshold() = 0; - virtual cc::Vec3 getLinearVelocity() = 0; - virtual void setLinearVelocity(float x, float y, float z) = 0; - virtual cc::Vec3 getAngularVelocity() = 0; - virtual void setAngularVelocity(float x, float y, float z) = 0; - virtual void applyForce(float x, float y, float z, float rx, float ry, float rz) = 0; - virtual void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) = 0; - virtual void applyImpulse(float x, float y, float z, float rx, float ry, float rz) = 0; - virtual void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) = 0; - virtual void applyTorque(float x, float y, float z) = 0; - virtual void applyLocalTorque(float x, float y, float z) = 0; - virtual uint32_t getGroup() = 0; - virtual void setGroup(uint32_t g) = 0; - virtual uint32_t getMask() = 0; - virtual void setMask(uint32_t m) = 0; + ~IRigidBody() override = default; + virtual uintptr_t getImpl() = 0; + virtual uintptr_t getNodeHandle() = 0; + virtual void initialize(Node *node, ERigidBodyType t, uint32_t g) = 0; + virtual bool isAwake() = 0; + virtual bool isSleepy() = 0; + virtual bool isSleeping() = 0; + virtual void setType(ERigidBodyType v) = 0; + virtual void setMass(float v) = 0; + virtual void setLinearDamping(float v) = 0; + virtual void setAngularDamping(float v) = 0; + virtual void useGravity(bool v) = 0; + virtual void useCCD(bool v) = 0; + virtual void setLinearFactor(float x, float y, float z) = 0; + virtual void setAngularFactor(float x, float y, float z) = 0; + virtual void setAllowSleep(bool v) = 0; + virtual void wakeUp() = 0; + virtual void sleep() = 0; + virtual void clearState() = 0; + virtual void clearForces() = 0; + virtual void clearVelocity() = 0; + virtual void setSleepThreshold(float v) = 0; + virtual float getSleepThreshold() = 0; + virtual cc::Vec3 getLinearVelocity() = 0; + virtual void setLinearVelocity(float x, float y, float z) = 0; + virtual cc::Vec3 getAngularVelocity() = 0; + virtual void setAngularVelocity(float x, float y, float z) = 0; + virtual void applyForce(float x, float y, float z, float rx, float ry, float rz) = 0; + virtual void applyLocalForce(float x, float y, float z, float rx, float ry, float rz) = 0; + virtual void applyImpulse(float x, float y, float z, float rx, float ry, float rz) = 0; + virtual void applyLocalImpulse(float x, float y, float z, float rx, float ry, float rz) = 0; + virtual void applyTorque(float x, float y, float z) = 0; + virtual void applyLocalTorque(float x, float y, float z) = 0; + virtual uint32_t getGroup() = 0; + virtual void setGroup(uint32_t g) = 0; + virtual uint32_t getMask() = 0; + virtual void setMask(uint32_t m) = 0; }; } // namespace physics diff --git a/native/cocos/physics/spec/IJoint.h b/native/cocos/physics/spec/IJoint.h index 673a085fab..874bb7c59b 100644 --- a/native/cocos/physics/spec/IJoint.h +++ b/native/cocos/physics/spec/IJoint.h @@ -34,26 +34,26 @@ namespace physics { class IBaseJoint : virtual public ILifecycle { public: - ~IBaseJoint() override = default; - virtual void initialize(Node *node) = 0; - virtual uintptr_t getImpl() = 0; - virtual void setEnableCollision(bool v) = 0; - virtual void setConnectedBody(uintptr_t v) = 0; + ~IBaseJoint() override = default; + virtual void initialize(Node *node) = 0; + virtual uintptr_t getImpl() = 0; + virtual void setEnableCollision(bool v) = 0; + virtual void setConnectedBody(uintptr_t v) = 0; }; class IDistanceJoint : virtual public IBaseJoint { public: - ~IDistanceJoint() override = default; + ~IDistanceJoint() override = default; virtual void setPivotA(float x, float y, float z) = 0; virtual void setPivotB(float x, float y, float z) = 0; }; class IRevoluteJoint : virtual public IBaseJoint { public: - ~IRevoluteJoint() override = default; + ~IRevoluteJoint() override = default; virtual void setPivotA(float x, float y, float z) = 0; virtual void setPivotB(float x, float y, float z) = 0; - virtual void setAxis(float x, float y, float z) = 0; + virtual void setAxis(float x, float y, float z) = 0; }; } // namespace physics diff --git a/native/cocos/physics/spec/ILifecycle.h b/native/cocos/physics/spec/ILifecycle.h index ab26be8d07..331c6b3680 100644 --- a/native/cocos/physics/spec/ILifecycle.h +++ b/native/cocos/physics/spec/ILifecycle.h @@ -32,8 +32,8 @@ namespace cc { namespace physics { class ILifecycle { public: - virtual ~ILifecycle() = default; - virtual void onEnable() = 0; + virtual ~ILifecycle() = default; + virtual void onEnable() = 0; virtual void onDisable() = 0; virtual void onDestroy() = 0; }; diff --git a/native/cocos/physics/spec/IShape.h b/native/cocos/physics/spec/IShape.h index 90c6f7af54..2b34fee7a4 100644 --- a/native/cocos/physics/spec/IShape.h +++ b/native/cocos/physics/spec/IShape.h @@ -41,10 +41,10 @@ enum class EAxisDirection : uint8_t { }; enum class EShapeFilterFlag : uint8_t { - NONE = 0, - IS_TRIGGER = 1 << 0, - NEED_EVENT = 1 << 1, - NEED_CONTACT_DATA = 1 << 2, + NONE = 0, + IS_TRIGGER = 1 << 0, + NEED_EVENT = 1 << 1, + NEED_CONTACT_DATA = 1 << 2, DETECT_CONTACT_CCD = 1 << 3, }; @@ -52,19 +52,19 @@ class IBaseShape : virtual public ILifecycle { public: ~IBaseShape() override = default; ; - virtual void initialize(Node *node) = 0; - virtual uintptr_t getImpl() = 0; - virtual void setMaterial(uint16_t id, float f, float df, float r, - uint8_t m0, uint8_t m1) = 0; - virtual void setAsTrigger(bool v) = 0; - virtual void setCenter(float x, float y, float z) = 0; - virtual geometry::AABB & getAABB() = 0; - virtual geometry::Sphere &getBoundingSphere() = 0; - virtual void updateEventListener(EShapeFilterFlag flag) = 0; - virtual uint32_t getGroup() = 0; - virtual void setGroup(uint32_t g) = 0; - virtual uint32_t getMask() = 0; - virtual void setMask(uint32_t m) = 0; + virtual void initialize(Node *node) = 0; + virtual uintptr_t getImpl() = 0; + virtual void setMaterial(uint16_t id, float f, float df, float r, + uint8_t m0, uint8_t m1) = 0; + virtual void setAsTrigger(bool v) = 0; + virtual void setCenter(float x, float y, float z) = 0; + virtual geometry::AABB &getAABB() = 0; + virtual geometry::Sphere &getBoundingSphere() = 0; + virtual void updateEventListener(EShapeFilterFlag flag) = 0; + virtual uint32_t getGroup() = 0; + virtual void setGroup(uint32_t g) = 0; + virtual uint32_t getMask() = 0; + virtual void setMask(uint32_t m) = 0; }; class ISphereShape : virtual public IBaseShape { @@ -85,8 +85,8 @@ class ICapsuleShape : virtual public IBaseShape { public: ~ICapsuleShape() override = default; ; - virtual void setRadius(float v) = 0; - virtual void setCylinderHeight(float v) = 0; + virtual void setRadius(float v) = 0; + virtual void setCylinderHeight(float v) = 0; virtual void setDirection(EAxisDirection v) = 0; }; @@ -94,7 +94,7 @@ class ICylinderShape : virtual public IBaseShape { public: ~ICylinderShape() override = default; ; - virtual void setConvex(uintptr_t v) = 0; + virtual void setConvex(uintptr_t v) = 0; virtual void setCylinder(float r, float h, EAxisDirection d) = 0; }; @@ -102,7 +102,7 @@ class IConeShape : virtual public IBaseShape { public: ~IConeShape() override = default; ; - virtual void setConvex(uintptr_t v) = 0; + virtual void setConvex(uintptr_t v) = 0; virtual void setCone(float r, float h, EAxisDirection d) = 0; }; @@ -110,7 +110,7 @@ class IPlaneShape : virtual public IBaseShape { public: ~IPlaneShape() override = default; ; - virtual void setConstant(float v) = 0; + virtual void setConstant(float v) = 0; virtual void setNormal(float x, float y, float z) = 0; }; @@ -119,7 +119,7 @@ public: ~ITrimeshShape() override = default; ; virtual void setMesh(uintptr_t v) = 0; - virtual void useConvex(bool v) = 0; + virtual void useConvex(bool v) = 0; }; class ITerrainShape : virtual public IBaseShape { diff --git a/native/cocos/physics/spec/IWorld.h b/native/cocos/physics/spec/IWorld.h index 6bb47a0455..15eafafbb5 100644 --- a/native/cocos/physics/spec/IWorld.h +++ b/native/cocos/physics/spec/IWorld.h @@ -36,14 +36,14 @@ namespace physics { enum class ETouchState : uint8_t { ENTER = 0, - STAY = 1, - EXIT = 2, + STAY = 1, + EXIT = 2, }; struct TriggerEventPair { - uintptr_t shapeA; - uintptr_t shapeB; - ETouchState state; + uintptr_t shapeA; + uintptr_t shapeB; + ETouchState state; static constexpr uint8_t COUNT = 3; TriggerEventPair(const uintptr_t a, const uintptr_t b) : shapeA(a), @@ -52,21 +52,21 @@ struct TriggerEventPair { }; struct ContactPoint { - Vec3 position; - float separation; - Vec3 normal; - uint32_t internalFaceIndex0; - Vec3 impulse; - uint32_t internalFaceIndex1; + Vec3 position; + float separation; + Vec3 normal; + uint32_t internalFaceIndex0; + Vec3 impulse; + uint32_t internalFaceIndex1; static constexpr uint8_t COUNT = 12; }; struct ContactEventPair { - uintptr_t shapeA; - uintptr_t shapeB; - ETouchState state; + uintptr_t shapeA; + uintptr_t shapeB; + ETouchState state; ccstd::vector contacts; - static constexpr uint8_t COUNT = 4; + static constexpr uint8_t COUNT = 4; ContactEventPair(const uintptr_t a, const uintptr_t b) : shapeA(a), shapeB(b), @@ -74,35 +74,35 @@ struct ContactEventPair { }; struct ConvexDesc { - void * positions; + void *positions; uint32_t positionLength; }; struct TrimeshDesc : ConvexDesc { - void * triangles; + void *triangles; uint32_t triangleLength; - bool isU16; + bool isU16; }; struct HeightFieldDesc { uint32_t rows; uint32_t columns; - void * samples; + void *samples; }; struct RaycastOptions { - Vec3 origin; - float distance; - Vec3 unitDir; + Vec3 origin; + float distance; + Vec3 unitDir; uint32_t mask; - bool queryTrigger; + bool queryTrigger; }; struct RaycastResult { uintptr_t shape{0}; - Vec3 hitPoint; - float distance; - Vec3 hitNormal; + Vec3 hitPoint; + float distance; + Vec3 hitNormal; RaycastResult() = default; }; @@ -110,25 +110,25 @@ class IPhysicsWorld { public: virtual ~IPhysicsWorld() = default; ; - virtual void setGravity(float x, float y, float z) = 0; - virtual void setAllowSleep(bool v) = 0; - virtual void step(float s) = 0; - virtual void emitEvents() = 0; - virtual void syncSceneToPhysics() = 0; - virtual void syncSceneWithCheck() = 0; - virtual void destroy() = 0; - virtual void setCollisionMatrix(uint32_t i, uint32_t m) = 0; - virtual ccstd::vector> &getTriggerEventPairs() = 0; - virtual ccstd::vector> &getContactEventPairs() = 0; - virtual bool raycast(RaycastOptions &opt) = 0; - virtual bool raycastClosest(RaycastOptions &opt) = 0; - virtual ccstd::vector & raycastResult() = 0; - virtual RaycastResult & raycastClosestResult() = 0; - virtual uintptr_t createConvex(ConvexDesc &desc) = 0; - virtual uintptr_t createTrimesh(TrimeshDesc &desc) = 0; - virtual uintptr_t createHeightField(HeightFieldDesc &desc) = 0; - virtual uintptr_t createMaterial(uint16_t id, float f, float df, float r, - uint8_t m0, uint8_t m1) = 0; + virtual void setGravity(float x, float y, float z) = 0; + virtual void setAllowSleep(bool v) = 0; + virtual void step(float s) = 0; + virtual void emitEvents() = 0; + virtual void syncSceneToPhysics() = 0; + virtual void syncSceneWithCheck() = 0; + virtual void destroy() = 0; + virtual void setCollisionMatrix(uint32_t i, uint32_t m) = 0; + virtual ccstd::vector> &getTriggerEventPairs() = 0; + virtual ccstd::vector> &getContactEventPairs() = 0; + virtual bool raycast(RaycastOptions &opt) = 0; + virtual bool raycastClosest(RaycastOptions &opt) = 0; + virtual ccstd::vector &raycastResult() = 0; + virtual RaycastResult &raycastClosestResult() = 0; + virtual uintptr_t createConvex(ConvexDesc &desc) = 0; + virtual uintptr_t createTrimesh(TrimeshDesc &desc) = 0; + virtual uintptr_t createHeightField(HeightFieldDesc &desc) = 0; + virtual uintptr_t createMaterial(uint16_t id, float f, float df, float r, + uint8_t m0, uint8_t m1) = 0; }; } // namespace physics diff --git a/native/cocos/platform/BasePlatform.h b/native/cocos/platform/BasePlatform.h index 5a9eb1dc12..88c0881ee2 100644 --- a/native/cocos/platform/BasePlatform.h +++ b/native/cocos/platform/BasePlatform.h @@ -85,7 +85,7 @@ public: /** * @brief Set touch event handling callback function. */ - using HandleTouchEventCallback = std::function; + using HandleTouchEventCallback = std::function; virtual void setHandleTouchEventCallback(HandleTouchEventCallback cb) = 0; /** @@ -107,7 +107,7 @@ public: * @param task : Tasks running in platform threads * @param fps : Task call frequency */ - using ThreadCallback = std::function; + using ThreadCallback = std::function; virtual void runInPlatformThread(const ThreadCallback &task) = 0; /** * @brief Get task call frequency. @@ -161,9 +161,9 @@ public: } private: - static BasePlatform* createDefaultPlatform(); + static BasePlatform *createDefaultPlatform(); - static BasePlatform* _currentPlatform; // NOLINT(readability-identifier-naming) + static BasePlatform *_currentPlatform; // NOLINT(readability-identifier-naming) std::vector _osInterfaces; CC_DISALLOW_COPY_MOVE_ASSIGN(BasePlatform); }; diff --git a/native/cocos/platform/FileUtils.cpp b/native/cocos/platform/FileUtils.cpp index 060589da26..f8ccfedca5 100644 --- a/native/cocos/platform/FileUtils.cpp +++ b/native/cocos/platform/FileUtils.cpp @@ -72,20 +72,20 @@ using SAXResult = enum { class DictMaker : public SAXDelegator { public: - SAXResult _resultType{SAX_RESULT_NONE}; - ValueMap _rootDict; + SAXResult _resultType{SAX_RESULT_NONE}; + ValueMap _rootDict; ValueVector _rootArray; ccstd::string _curKey; ///< parsed key ccstd::string _curValue; // parsed value - SAXState _state{SAX_NONE}; + SAXState _state{SAX_NONE}; - ValueMap * _curDict; + ValueMap *_curDict; ValueVector *_curArray; - std::stack _dictStack; + std::stack _dictStack; std::stack _arrayStack; - std::stack _stateStack; + std::stack _stateStack; DictMaker() = default; @@ -147,9 +147,9 @@ public: } else if (SAX_DICT == preState) { // add a new dictionary into the pre dictionary CC_ASSERT(!_dictStack.empty()); // The state is wrong. - ValueMap *preDict = _dictStack.top(); + ValueMap *preDict = _dictStack.top(); (*preDict)[_curKey] = Value(ValueMap()); - _curDict = &(*preDict)[_curKey].asValueMap(); + _curDict = &(*preDict)[_curKey].asValueMap(); } // record the dict state @@ -176,7 +176,7 @@ public: if (preState == SAX_DICT) { (*_curDict)[_curKey] = Value(ValueVector()); - _curArray = &(*_curDict)[_curKey].asValueVector(); + _curArray = &(*_curDict)[_curKey].asValueVector(); } else if (preState == SAX_ARRAY) { CC_ASSERT(!_arrayStack.empty()); // The state is wrong! ValueVector *preArray = _arrayStack.top(); @@ -193,7 +193,7 @@ public: void endElement(void *ctx, const char *name) override { CC_UNUSED_PARAM(ctx); - SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); + SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); const ccstd::string sName(const_cast(name)); if (sName == "dict") { _stateStack.pop(); @@ -250,8 +250,8 @@ public: return; } - SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); - const ccstd::string text = ccstd::string(const_cast(ch), len); + SAXState curState = _stateStack.empty() ? SAX_DICT : _stateStack.top(); + const ccstd::string text = ccstd::string(const_cast(ch), len); switch (_state) { case SAX_KEY: @@ -291,7 +291,7 @@ ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { ValueVector FileUtils::getValueVectorFromFile(const ccstd::string &filename) { const ccstd::string fullPath = fullPathForFilename(filename); - DictMaker tMaker; + DictMaker tMaker; return tMaker.arrayWithContentsOfFile(fullPath); } @@ -388,24 +388,24 @@ bool FileUtils::writeValueVectorToFile(const ValueVector &vecData, const ccstd:: static tinyxml2::XMLElement *generateElementForObject(const Value &value, tinyxml2::XMLDocument *doc) { // NOLINT(misc-no-recursion) // object is String if (value.getType() == Value::Type::STRING) { - tinyxml2::XMLElement *node = doc->NewElement("string"); - tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("string"); + tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } // object is integer if (value.getType() == Value::Type::INTEGER) { - tinyxml2::XMLElement *node = doc->NewElement("integer"); - tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("integer"); + tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } // object is real if (value.getType() == Value::Type::FLOAT || value.getType() == Value::Type::DOUBLE) { - tinyxml2::XMLElement *node = doc->NewElement("real"); - tinyxml2::XMLText * content = doc->NewText(value.asString().c_str()); + tinyxml2::XMLElement *node = doc->NewElement("real"); + tinyxml2::XMLText *content = doc->NewText(value.asString().c_str()); node->LinkEndChild(content); return node; } @@ -468,10 +468,10 @@ static tinyxml2::XMLElement *generateElementForArray(const ValueVector &array, t #else /* The subclass FileUtilsApple should override these two method. */ -ValueMap FileUtils::getValueMapFromFile(const ccstd::string &filename) { return ValueMap(); } -ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { return ValueMap(); } +ValueMap FileUtils::getValueMapFromFile(const ccstd::string &filename) { return ValueMap(); } +ValueMap FileUtils::getValueMapFromData(const char *filedata, int filesize) { return ValueMap(); } ValueVector FileUtils::getValueVectorFromFile(const ccstd::string &filename) { return ValueVector(); } -bool FileUtils::writeToFile(const ValueMap &dict, const ccstd::string &fullPath) { return false; } +bool FileUtils::writeToFile(const ValueMap &dict, const ccstd::string &fullPath) { return false; } #endif /* (CC_PLATFORM != CC_PLATFORM_MAC_IOS) && (CC_PLATFORM != CC_PLATFORM_MAC_OSX) */ @@ -492,7 +492,7 @@ FileUtils::FileUtils() = default; FileUtils::~FileUtils() = default; bool FileUtils::writeStringToFile(const ccstd::string &dataStr, const ccstd::string &fullPath) { - Data data; + Data data; auto *dataP = const_cast(dataStr.data()); data.fastSet(reinterpret_cast(dataP), static_cast(dataStr.size())); @@ -504,7 +504,7 @@ bool FileUtils::writeStringToFile(const ccstd::string &dataStr, const ccstd::str } bool FileUtils::writeDataToFile(const Data &data, const ccstd::string &fullPath) { - size_t size = 0; + size_t size = 0; const char *mode = "wb"; CC_ASSERT(!fullPath.empty() && data.getSize() != 0); @@ -590,8 +590,8 @@ FileUtils::Status FileUtils::getContents(const ccstd::string &filename, Resizabl unsigned char *FileUtils::getFileDataFromZip(const ccstd::string &zipFilePath, const ccstd::string &filename, uint32_t *size) { unsigned char *buffer = nullptr; - unzFile file = nullptr; - *size = 0; + unzFile file = nullptr; + *size = 0; do { CC_BREAK_IF(zipFilePath.empty()); @@ -603,7 +603,7 @@ unsigned char *FileUtils::getFileDataFromZip(const ccstd::string &zipFilePath, c int ret = unzLocateFile(file, filename.c_str(), nullptr); CC_BREAK_IF(UNZ_OK != ret); - char filePathA[260]; + char filePathA[260]; unz_file_info fileInfo; ret = unzGetCurrentFileInfo(file, &fileInfo, filePathA, sizeof(filePathA), nullptr, 0, nullptr, 0); CC_BREAK_IF(UNZ_OK != ret); @@ -611,7 +611,7 @@ unsigned char *FileUtils::getFileDataFromZip(const ccstd::string &zipFilePath, c ret = unzOpenCurrentFile(file); CC_BREAK_IF(UNZ_OK != ret); - buffer = static_cast(malloc(fileInfo.uncompressed_size)); + buffer = static_cast(malloc(fileInfo.uncompressed_size)); int CC_UNUSED readedSize = unzReadCurrentFile(file, buffer, static_cast(fileInfo.uncompressed_size)); CC_ASSERT(readedSize == 0 || readedSize == (int)fileInfo.uncompressed_size); @@ -629,10 +629,10 @@ unsigned char *FileUtils::getFileDataFromZip(const ccstd::string &zipFilePath, c ccstd::string FileUtils::getPathForFilename(const ccstd::string &filename, const ccstd::string &searchPath) const { ccstd::string file{filename}; ccstd::string filePath; - size_t pos = filename.find_last_of('/'); + size_t pos = filename.find_last_of('/'); if (pos != ccstd::string::npos) { filePath = filename.substr(0, pos + 1); - file = filename.substr(pos + 1); + file = filename.substr(pos + 1); } // searchPath + file_path @@ -710,7 +710,7 @@ void FileUtils::setDefaultResourceRootPath(const ccstd::string &path) { void FileUtils::setSearchPaths(const ccstd::vector &searchPaths) { bool existDefaultRootPath = false; - _originalSearchPaths = searchPaths; + _originalSearchPaths = searchPaths; _fullPathCache.clear(); _searchPathArray.clear(); @@ -811,7 +811,7 @@ bool FileUtils::isDirectoryExist(const ccstd::string &dirPath) const { } ccstd::vector FileUtils::listFiles(const ccstd::string &dirPath) const { - ccstd::string fullpath = fullPathForFilename(dirPath); + ccstd::string fullpath = fullPathForFilename(dirPath); ccstd::vector files; if (isDirectoryExist(fullpath)) { tinydir_dir dir; @@ -835,7 +835,7 @@ ccstd::vector FileUtils::listFiles(const ccstd::string &dirPath) #ifdef UNICODE std::wstring path = file.path; - length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); + length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); ccstd::string filepath; if (length > 0) { filepath.resize(length); @@ -884,7 +884,7 @@ void FileUtils::listFilesRecursively(const ccstd::string &dirPath, ccstd::vector #ifdef UNICODE std::wstring path = file.path; - length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); + length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL); ccstd::string filepath; if (length > 0) { filepath.resize(length); @@ -990,9 +990,9 @@ bool FileUtils::createDirectory(const ccstd::string &path) { } // Split the path - size_t start = 0; - size_t found = path.find_first_of("/\\", start); - ccstd::string subpath; + size_t start = 0; + size_t found = path.find_first_of("/\\", start); + ccstd::string subpath; ccstd::vector dirs; if (found != ccstd::string::npos) { @@ -1124,7 +1124,7 @@ long FileUtils::getFileSize(const ccstd::string &filepath) { //NOLINT(google-run ccstd::string FileUtils::getFileExtension(const ccstd::string &filePath) const { ccstd::string fileExtension; - size_t pos = filePath.find_last_of('.'); + size_t pos = filePath.find_last_of('.'); if (pos != ccstd::string::npos) { fileExtension = filePath.substr(pos, filePath.length()); @@ -1142,7 +1142,7 @@ void FileUtils::valueVectorCompact(ValueVector &valueVector) { ccstd::string FileUtils::getFileDir(const ccstd::string &path) { ccstd::string ret; - size_t pos = path.rfind('/'); + size_t pos = path.rfind('/'); if (pos != ccstd::string::npos) { ret = path.substr(0, pos); } diff --git a/native/cocos/platform/FileUtils.h b/native/cocos/platform/FileUtils.h index 4e679436f4..659e9e43ee 100644 --- a/native/cocos/platform/FileUtils.h +++ b/native/cocos/platform/FileUtils.h @@ -42,9 +42,9 @@ namespace cc { class ResizableBuffer { public: - ~ResizableBuffer() = default; - virtual void resize(size_t size) = 0; - virtual void *buffer() const = 0; + ~ResizableBuffer() = default; + virtual void resize(size_t size) = 0; + virtual void *buffer() const = 0; }; template @@ -93,7 +93,7 @@ public: size_t oldSize = _buffer->getSize(); if (oldSize != size) { // need to take buffer ownership for outer memory control - auto *old = _buffer->takeBuffer(); + auto *old = _buffer->takeBuffer(); void *buffer = realloc(old, size); if (buffer) { _buffer->fastSet(static_cast(buffer), static_cast(size)); @@ -157,13 +157,13 @@ public: virtual Data getDataFromFile(const ccstd::string &filename); enum class Status { - OK = 0, - NOT_EXISTS = 1, // File not exists - OPEN_FAILED = 2, // Open file failed. - READ_FAILED = 3, // Read failed - NOT_INITIALIZED = 4, // FileUtils is not initializes - TOO_LARGE = 5, // The file is too large (great than 2^32-1) - OBTAIN_SIZE_FAILED = 6 // Failed to obtain the file size. + OK = 0, + NOT_EXISTS = 1, // File not exists + OPEN_FAILED = 2, // Open file failed. + READ_FAILED = 3, // Read failed + NOT_INITIALIZED = 4, // FileUtils is not initializes + TOO_LARGE = 5, // The file is too large (great than 2^32-1) + OBTAIN_SIZE_FAILED = 6 // Failed to obtain the file size. }; /** diff --git a/native/cocos/platform/IEventDispatch.h b/native/cocos/platform/IEventDispatch.h index b37a11de38..e40f6f2c77 100644 --- a/native/cocos/platform/IEventDispatch.h +++ b/native/cocos/platform/IEventDispatch.h @@ -38,7 +38,7 @@ public: /** * Dispatch event interface. */ - virtual void dispatchEvent(const OSEvent &ev) = 0; + virtual void dispatchEvent(const OSEvent& ev) = 0; /** * Dispatch touch event interface. */ diff --git a/native/cocos/platform/Image.cpp b/native/cocos/platform/Image.cpp index bba572e6a0..816a56cdf4 100644 --- a/native/cocos/platform/Image.cpp +++ b/native/cocos/platform/Image.cpp @@ -77,14 +77,14 @@ const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff; // Values taken from PVRTexture.h from http://www.imgtec.com enum class PVR2TextureFlag { - MIPMAP = (1 << 8), // has mip map levels - TWIDDLE = (1 << 9), // is twiddled - BUMPMAP = (1 << 10), // has normals encoded for a bump map - TILING = (1 << 11), // is bordered for tiled pvr - CUBEMAP = (1 << 12), // is a cubemap/skybox + MIPMAP = (1 << 8), // has mip map levels + TWIDDLE = (1 << 9), // is twiddled + BUMPMAP = (1 << 10), // has normals encoded for a bump map + TILING = (1 << 11), // is bordered for tiled pvr + CUBEMAP = (1 << 12), // is a cubemap/skybox FALSE_MIP_COL = (1 << 13), // are there false colored MIP levels - VOLUME = (1 << 14), // is this a volume texture - ALPHA = (1 << 15), // v2.1 is there transparency info in the texture + VOLUME = (1 << 14), // is this a volume texture + ALPHA = (1 << 15), // v2.1 is there transparency info in the texture VERTICAL_FLIP = (1 << 16), // v2.1 is the texture vertically flipped }; @@ -108,48 +108,48 @@ enum class PVR2TexturePixelFormat : unsigned char { // v3 enum class PVR3TexturePixelFormat : uint64_t { - PVRTC2BPP_RGB = 0ULL, - PVRTC2BPP_RGBA = 1ULL, - PVRTC4BPP_RGB = 2ULL, - PVRTC4BPP_RGBA = 3ULL, - PVRTC2_2BPP_RGBA = 4ULL, - PVRTC2_4BPP_RGBA = 5ULL, - ETC1 = 6ULL, - DXT1 = 7ULL, - DXT2 = 8ULL, - DXT3 = 9ULL, - DXT4 = 10ULL, - DXT5 = 11ULL, - BC1 = 7ULL, - BC2 = 9ULL, - BC3 = 11ULL, - BC4 = 12ULL, - BC5 = 13ULL, - BC6 = 14ULL, - BC7 = 15ULL, - UYVY = 16ULL, - YUY2 = 17ULL, - B_W1BPP = 18ULL, - R9G9B9E5 = 19ULL, - RGBG8888 = 20ULL, - GRGB8888 = 21ULL, - ETC2_RGB = 22ULL, - ETC2_RGBA = 23ULL, - ETC2_RGBA1 = 24ULL, - EAC_R11_UNSIGNED = 25ULL, - EAC_R11_SIGNED = 26ULL, + PVRTC2BPP_RGB = 0ULL, + PVRTC2BPP_RGBA = 1ULL, + PVRTC4BPP_RGB = 2ULL, + PVRTC4BPP_RGBA = 3ULL, + PVRTC2_2BPP_RGBA = 4ULL, + PVRTC2_4BPP_RGBA = 5ULL, + ETC1 = 6ULL, + DXT1 = 7ULL, + DXT2 = 8ULL, + DXT3 = 9ULL, + DXT4 = 10ULL, + DXT5 = 11ULL, + BC1 = 7ULL, + BC2 = 9ULL, + BC3 = 11ULL, + BC4 = 12ULL, + BC5 = 13ULL, + BC6 = 14ULL, + BC7 = 15ULL, + UYVY = 16ULL, + YUY2 = 17ULL, + B_W1BPP = 18ULL, + R9G9B9E5 = 19ULL, + RGBG8888 = 20ULL, + GRGB8888 = 21ULL, + ETC2_RGB = 22ULL, + ETC2_RGBA = 23ULL, + ETC2_RGBA1 = 24ULL, + EAC_R11_UNSIGNED = 25ULL, + EAC_R11_SIGNED = 26ULL, EAC_R_G11_UNSIGNED = 27ULL, - EAC_R_G11_SIGNED = 28ULL, + EAC_R_G11_SIGNED = 28ULL, BGRA8888 = 0x0808080861726762ULL, RGBA8888 = 0x0808080861626772ULL, RGBA4444 = 0x0404040461626772ULL, RGBA5551 = 0x0105050561626772ULL, - RGB565 = 0x0005060500626772ULL, - RGB888 = 0x0008080800626772ULL, - A8 = 0x0000000800000061ULL, - L8 = 0x000000080000006cULL, - LA88 = 0x000008080000616cULL, + RGB565 = 0x0005060500626772ULL, + RGB888 = 0x0008080800626772ULL, + A8 = 0x0000000800000061ULL, + L8 = 0x000000080000006cULL, + LA88 = 0x000008080000616cULL, }; // v2 @@ -170,11 +170,11 @@ const _pixel2_formathash::value_type V2_PIXEL_FORMATHASH_VALUE[] = { _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, gfx::Format::PVRTC_RGBA4), }; -const int PVR2_MAX_TABLE_ELEMENTS = sizeof(V2_PIXEL_FORMATHASH_VALUE) / sizeof(V2_PIXEL_FORMATHASH_VALUE[0]); +const int PVR2_MAX_TABLE_ELEMENTS = sizeof(V2_PIXEL_FORMATHASH_VALUE) / sizeof(V2_PIXEL_FORMATHASH_VALUE[0]); const _pixel2_formathash V2_PIXEL_FORMATHASH(V2_PIXEL_FORMATHASH_VALUE, V2_PIXEL_FORMATHASH_VALUE + PVR2_MAX_TABLE_ELEMENTS); // v3 -using _pixel3_formathash = const ccstd::unordered_map; +using _pixel3_formathash = const ccstd::unordered_map; _pixel3_formathash::value_type v3PixelFormathashValue[] = { _pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, gfx::Format::BGRA8), _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, gfx::Format::RGBA8), @@ -242,8 +242,8 @@ using PVRv3TexHeader = struct { namespace { using tImageSource = struct { const unsigned char *data; - uint32_t size; - int offset; + uint32_t size; + int offset; }; #ifdef CC_USE_PNG @@ -293,7 +293,7 @@ bool Image::initWithImageData(const unsigned char *data, uint32_t dataLen) { CC_BREAK_IF(!data || dataLen <= 0); unsigned char *unpackedData = nullptr; - uint32_t unpackedLen = 0; + uint32_t unpackedLen = 0; //detect and unzip the compress file if (ZipUtils::isCCZBuffer(data, dataLen)) { @@ -302,7 +302,7 @@ bool Image::initWithImageData(const unsigned char *data, uint32_t dataLen) { unpackedLen = ZipUtils::inflateMemory(const_cast(data), dataLen, &unpackedData); } else { unpackedData = const_cast(data); - unpackedLen = dataLen; + unpackedLen = dataLen; } _fileType = detectFormat(unpackedData, unpackedLen); @@ -473,8 +473,8 @@ namespace { */ #if CC_USE_JPEG struct MyErrorMgr { - struct jpeg_error_mgr pub; /* "public" fields */ - jmp_buf setjmp_buffer; /* for return to caller */ + struct jpeg_error_mgr pub; /* "public" fields */ + jmp_buf setjmp_buffer; /* for return to caller */ }; using MyErrorPtr = struct MyErrorMgr *; @@ -514,12 +514,12 @@ bool Image::initWithJpgData(const unsigned char *data, uint32_t dataLen) { struct MyErrorMgr jerr; /* libjpeg data structure for storing one row, that is, scanline of an image */ JSAMPROW rowPointer[1] = {nullptr}; - uint32_t location = 0; + uint32_t location = 0; bool ret = false; do { /* We set up the normal JPEG error routines, then override error_exit. */ - cinfo.err = jpeg_std_error(&jerr.pub); + cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = myErrorExit; /* Establish the setjmp return context for MyErrorExit to use. */ if (setjmp(jerr.setjmp_buffer)) { @@ -548,7 +548,7 @@ bool Image::initWithJpgData(const unsigned char *data, uint32_t dataLen) { _renderFormat = gfx::Format::L8; } else { cinfo.out_color_space = JCS_RGB; - _renderFormat = gfx::Format::RGB8; + _renderFormat = gfx::Format::RGB8; } /* Start decompression jpeg here */ @@ -556,10 +556,10 @@ bool Image::initWithJpgData(const unsigned char *data, uint32_t dataLen) { /* init image info */ _isCompressed = false; - _width = cinfo.output_width; - _height = cinfo.output_height; - _dataLen = cinfo.output_width * cinfo.output_height * cinfo.output_components; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _width = cinfo.output_width; + _height = cinfo.output_height; + _dataLen = cinfo.output_width * cinfo.output_height * cinfo.output_components; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); CC_BREAK_IF(!_data); /* now actually read the jpeg into the raw buffer */ @@ -589,10 +589,10 @@ bool Image::initWithPngData(const unsigned char *data, uint32_t dataLen) { #if CC_USE_PNG // length of bytes to check if it is a valid png file #define PNGSIGSIZE 8 - bool ret = false; - png_byte header[PNGSIGSIZE] = {0}; - png_structp pngPtr = nullptr; - png_infop infoPtr = nullptr; + bool ret = false; + png_byte header[PNGSIGSIZE] = {0}; + png_structp pngPtr = nullptr; + png_infop infoPtr = nullptr; do { // png header len is 8 bytes @@ -614,8 +614,8 @@ bool Image::initWithPngData(const unsigned char *data, uint32_t dataLen) { // set the read call back function tImageSource imageSource; - imageSource.data = const_cast(data); - imageSource.size = dataLen; + imageSource.data = const_cast(data); + imageSource.size = dataLen; imageSource.offset = 0; png_set_read_fn(pngPtr, &imageSource, pngReadCallback); @@ -624,10 +624,10 @@ bool Image::initWithPngData(const unsigned char *data, uint32_t dataLen) { // read png file info png_read_info(pngPtr, infoPtr); - _isCompressed = false; - _width = png_get_image_width(pngPtr, infoPtr); - _height = png_get_image_height(pngPtr, infoPtr); - png_byte bitDepth = png_get_bit_depth(pngPtr, infoPtr); + _isCompressed = false; + _width = png_get_image_width(pngPtr, infoPtr); + _height = png_get_image_height(pngPtr, infoPtr); + png_byte bitDepth = png_get_bit_depth(pngPtr, infoPtr); png_uint_32 colorType = png_get_color_type(pngPtr, infoPtr); //CC_LOG_DEBUG("color type %u", color_type); @@ -678,12 +678,12 @@ bool Image::initWithPngData(const unsigned char *data, uint32_t dataLen) { // read png data png_size_t rowbytes; - auto * rowPointers = static_cast(malloc(sizeof(png_bytep) * _height)); + auto *rowPointers = static_cast(malloc(sizeof(png_bytep) * _height)); rowbytes = png_get_rowbytes(pngPtr, infoPtr); _dataLen = static_cast(rowbytes * _height); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); if (!_data) { if (rowPointers != nullptr) { free(rowPointers); @@ -712,7 +712,7 @@ bool Image::initWithPngData(const unsigned char *data, uint32_t dataLen) { } bool Image::initWithPVRv2Data(const unsigned char *data, uint32_t dataLen) { - int width = 0; + int width = 0; int height = 0; //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader @@ -723,9 +723,9 @@ bool Image::initWithPVRv2Data(const unsigned char *data, uint32_t dataLen) { return false; } - unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); - auto formatFlags = static_cast(flags & PVR_TEXTURE_FLAG_TYPE_MASK); - bool flipped = (flags & static_cast(PVR2TextureFlag::VERTICAL_FLIP)) != 0; + unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags); + auto formatFlags = static_cast(flags & PVR_TEXTURE_FLAG_TYPE_MASK); + bool flipped = (flags & static_cast(PVR2TextureFlag::VERTICAL_FLIP)) != 0; if (flipped) { CC_LOG_DEBUG("initWithPVRv2Data: WARNING: Image is flipped. Regenerate it using PVRTexTool"); } @@ -744,13 +744,13 @@ bool Image::initWithPVRv2Data(const unsigned char *data, uint32_t dataLen) { _renderFormat = it->second; //Get size of mipmap - _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); - _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); + _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); + _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); _isCompressed = true; //Move by size of header _dataLen = dataLen - sizeof(PVRv2TexHeader); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, const_cast(data) + sizeof(PVRv2TexHeader), _dataLen); return true; @@ -788,12 +788,12 @@ bool Image::initWithPVRv3Data(const unsigned char *data, uint32_t dataLen) { _renderFormat = it->second; // sizing - _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); - _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); + _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); + _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); _isCompressed = true; _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen); return true; @@ -807,8 +807,8 @@ bool Image::initWithETCData(const unsigned char *data, uint32_t dataLen) { return false; } - _width = etc1_pkm_get_width(header); - _height = etc1_pkm_get_height(header); + _width = etc1_pkm_get_width(header); + _height = etc1_pkm_get_height(header); _isCompressed = true; if (0 == _width || 0 == _height) { @@ -816,8 +816,8 @@ bool Image::initWithETCData(const unsigned char *data, uint32_t dataLen) { } _renderFormat = gfx::Format::ETC_RGB8; - _dataLen = dataLen - ETC_PKM_HEADER_SIZE; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _dataLen = dataLen - ETC_PKM_HEADER_SIZE; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast(data) + ETC_PKM_HEADER_SIZE, _dataLen); return true; } @@ -830,8 +830,8 @@ bool Image::initWithETC2Data(const unsigned char *data, uint32_t dataLen) { return false; } - _width = etc2_pkm_get_width(header); - _height = etc2_pkm_get_height(header); + _width = etc2_pkm_get_width(header); + _height = etc2_pkm_get_height(header); _isCompressed = true; if (0 == _width || 0 == _height) { @@ -846,7 +846,7 @@ bool Image::initWithETC2Data(const unsigned char *data, uint32_t dataLen) { } _dataLen = dataLen - ETC2_PKM_HEADER_SIZE; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast(data) + ETC2_PKM_HEADER_SIZE, _dataLen); return true; } @@ -859,8 +859,8 @@ bool Image::initWithASTCData(const unsigned char *data, uint32_t dataLen) { return false; } - _width = astcGetWidth(header); - _height = astcGetHeight(header); + _width = astcGetWidth(header); + _height = astcGetHeight(header); _isCompressed = true; if (0 == _width || 0 == _height) { @@ -870,7 +870,7 @@ bool Image::initWithASTCData(const unsigned char *data, uint32_t dataLen) { _renderFormat = getASTCFormat(header); _dataLen = dataLen - ASTC_HEADER_SIZE; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); memcpy(_data, static_cast(data) + ASTC_HEADER_SIZE, _dataLen); // if (_data == nullptr) { // CCLOG("initWithASTCData: ERROR: Image _data is null!"); @@ -895,17 +895,17 @@ bool Image::initWithWebpData(const unsigned char *data, uint32_t dataLen) { if (config.input.width == 0 || config.input.height == 0) break; config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB; - _renderFormat = config.input.has_alpha ? gfx::Format::RGBA8 : gfx::Format::RGB8; - _width = config.input.width; - _height = config.input.height; - _isCompressed = false; + _renderFormat = config.input.has_alpha ? gfx::Format::RGBA8 : gfx::Format::RGB8; + _width = config.input.width; + _height = config.input.height; + _isCompressed = false; _dataLen = _width * _height * (config.input.has_alpha ? 4 : 3); - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); - config.output.u.RGBA.rgba = static_cast(_data); - config.output.u.RGBA.stride = _width * (config.input.has_alpha ? 4 : 3); - config.output.u.RGBA.size = _dataLen; + config.output.u.RGBA.rgba = static_cast(_data); + config.output.u.RGBA.stride = _width * (config.input.has_alpha ? 4 : 3); + config.output.u.RGBA.size = _dataLen; config.output.is_external_memory = 1; if (WebPDecode(static_cast(data), dataLen, &config) != VP8_STATUS_OK) { @@ -925,15 +925,15 @@ bool Image::initWithRawData(const unsigned char *data, uint32_t /*dataLen*/, int do { CC_BREAK_IF(0 == width || 0 == height); - _height = height; - _width = width; + _height = height; + _width = width; _renderFormat = gfx::Format::RGBA8; _isCompressed = false; // only RGBA8888 supported int bytesPerComponent = 4; - _dataLen = height * width * bytesPerComponent; - _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); + _dataLen = height * width * bytesPerComponent; + _data = static_cast(malloc(_dataLen * sizeof(unsigned char))); CC_BREAK_IF(!_data); memcpy(_data, data, _dataLen); diff --git a/native/cocos/platform/Image.h b/native/cocos/platform/Image.h index 0ac2ef2bd7..6516bcaf2e 100644 --- a/native/cocos/platform/Image.h +++ b/native/cocos/platform/Image.h @@ -69,17 +69,17 @@ public: // data will be free outside. inline void takeData(unsigned char **outData) { *outData = _data; - _data = nullptr; + _data = nullptr; } // Getters inline unsigned char *getData() const { return _data; } - inline uint32_t getDataLen() const { return _dataLen; } - inline Format getFileType() const { return _fileType; } - inline gfx::Format getRenderFormat() const { return _renderFormat; } - inline int getWidth() const { return _width; } - inline int getHeight() const { return _height; } - inline ccstd::string getFilePath() const { return _filePath; } + inline uint32_t getDataLen() const { return _dataLen; } + inline Format getFileType() const { return _fileType; } + inline gfx::Format getRenderFormat() const { return _renderFormat; } + inline int getWidth() const { return _width; } + inline int getHeight() const { return _height; } + inline ccstd::string getFilePath() const { return _filePath; } inline bool isCompressed() const { return _isCompressed; } @@ -94,23 +94,23 @@ protected: bool initWithETC2Data(const unsigned char *data, uint32_t dataLen); bool initWithASTCData(const unsigned char *data, uint32_t dataLen); - unsigned char *_data = nullptr; - uint32_t _dataLen = 0; - int _width = 0; - int _height = 0; - Format _fileType = Format::UNKNOWN; - gfx::Format _renderFormat; - ccstd::string _filePath; - bool _isCompressed = false; + unsigned char *_data = nullptr; + uint32_t _dataLen = 0; + int _width = 0; + int _height = 0; + Format _fileType = Format::UNKNOWN; + gfx::Format _renderFormat; + ccstd::string _filePath; + bool _isCompressed = false; static Format detectFormat(const unsigned char *data, uint32_t dataLen); - static bool isPng(const unsigned char *data, uint32_t dataLen); - static bool isJpg(const unsigned char *data, uint32_t dataLen); - static bool isWebp(const unsigned char *data, uint32_t dataLen); - static bool isPvr(const unsigned char *data, uint32_t dataLen); - static bool isEtc(const unsigned char *data, uint32_t dataLen); - static bool isEtc2(const unsigned char *data, uint32_t dataLen); - static bool isASTC(const unsigned char *data, uint32_t detaLen); + static bool isPng(const unsigned char *data, uint32_t dataLen); + static bool isJpg(const unsigned char *data, uint32_t dataLen); + static bool isWebp(const unsigned char *data, uint32_t dataLen); + static bool isPvr(const unsigned char *data, uint32_t dataLen); + static bool isEtc(const unsigned char *data, uint32_t dataLen); + static bool isEtc2(const unsigned char *data, uint32_t dataLen); + static bool isASTC(const unsigned char *data, uint32_t detaLen); static gfx::Format getASTCFormat(const unsigned char *pHeader); diff --git a/native/cocos/platform/SAXParser.cpp b/native/cocos/platform/SAXParser.cpp index 949b833817..2a8f1a5982 100644 --- a/native/cocos/platform/SAXParser.cpp +++ b/native/cocos/platform/SAXParser.cpp @@ -104,7 +104,7 @@ bool SAXParser::parse(const char *xmlData, size_t dataLength) { } bool SAXParser::parse(const ccstd::string &filename) { - bool ret = false; + bool ret = false; Data data = FileUtils::getInstance()->getDataFromFile(filename); if (!data.isNull()) { ret = parse((const char *)data.getBytes(), data.getSize()); diff --git a/native/cocos/platform/SDLHelper.cpp b/native/cocos/platform/SDLHelper.cpp index 752834e5fd..804e86e02d 100644 --- a/native/cocos/platform/SDLHelper.cpp +++ b/native/cocos/platform/SDLHelper.cpp @@ -180,15 +180,15 @@ void SDLHelper::dispatchWindowEvent(const SDL_WindowEvent &wevent) { break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { - ev.type = WindowEvent::Type::SIZE_CHANGED; - ev.width = wevent.data1; + ev.type = WindowEvent::Type::SIZE_CHANGED; + ev.width = wevent.data1; ev.height = wevent.data2; _delegate->dispatchEvent(ev); break; } case SDL_WINDOWEVENT_RESIZED: { - ev.type = WindowEvent::Type::RESIZED; - ev.width = wevent.data1; + ev.type = WindowEvent::Type::RESIZED; + ev.width = wevent.data1; ev.height = wevent.data2; _delegate->dispatchEvent(ev); break; @@ -216,8 +216,8 @@ void SDLHelper::dispatchWindowEvent(const SDL_WindowEvent &wevent) { } void SDLHelper::dispatchSDLEvent(const SDL_Event &sdlEvent, bool *quit) { - cc::TouchEvent touch; - cc::MouseEvent mouse; + cc::TouchEvent touch; + cc::MouseEvent mouse; cc::KeyboardEvent keyboard; switch (sdlEvent.type) { case SDL_QUIT: { @@ -234,88 +234,88 @@ void SDLHelper::dispatchSDLEvent(const SDL_Event &sdlEvent, bool *quit) { break; } case SDL_MOUSEBUTTONDOWN: { - int width = 0; + int width = 0; int height = 0; SDL_GetWindowSize(_handle, &width, &height); const SDL_MouseButtonEvent &event = sdlEvent.button; if (0 > event.x || event.x > width || 0 > event.y || event.y > height) { break; } - mouse.type = MouseEvent::Type::DOWN; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); + mouse.type = MouseEvent::Type::DOWN; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); mouse.button = event.button - 1; _delegate->dispatchEvent(mouse); break; } case SDL_MOUSEBUTTONUP: { const SDL_MouseButtonEvent &event = sdlEvent.button; - mouse.type = MouseEvent::Type::UP; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = event.button - 1; + mouse.type = MouseEvent::Type::UP; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = event.button - 1; _delegate->dispatchEvent(mouse); break; } case SDL_MOUSEMOTION: { const SDL_MouseMotionEvent &event = sdlEvent.motion; - mouse.type = MouseEvent::Type::MOVE; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = 0; + mouse.type = MouseEvent::Type::MOVE; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; _delegate->dispatchEvent(mouse); break; } case SDL_MOUSEWHEEL: { const SDL_MouseWheelEvent &event = sdlEvent.wheel; - mouse.type = MouseEvent::Type::WHEEL; - mouse.x = static_cast(event.x); - mouse.y = static_cast(event.y); - mouse.button = 0; //TODO: direction + mouse.type = MouseEvent::Type::WHEEL; + mouse.x = static_cast(event.x); + mouse.y = static_cast(event.y); + mouse.button = 0; //TODO: direction _delegate->dispatchEvent(mouse); break; } case SDL_FINGERUP: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::ENDED; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + touch.type = TouchEvent::Type::ENDED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; _delegate->dispatchTouchEvent(touch); break; } case SDL_FINGERDOWN: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::BEGAN; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + touch.type = TouchEvent::Type::BEGAN; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; _delegate->dispatchTouchEvent(touch); break; } case SDL_FINGERMOTION: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; - touch.type = TouchEvent::Type::MOVED; - touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; + touch.type = TouchEvent::Type::MOVED; + touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; _delegate->dispatchTouchEvent(touch); break; } case SDL_KEYDOWN: { const SDL_KeyboardEvent &event = sdlEvent.key; - auto mode = event.keysym.mod; - keyboard.action = KeyboardEvent::Action::PRESS; - keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); - keyboard.altKeyActive = mode & KMOD_ALT; - keyboard.ctrlKeyActive = mode & KMOD_CTRL; - keyboard.shiftKeyActive = mode & KMOD_SHIFT; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::PRESS; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); _delegate->dispatchEvent(keyboard); break; } case SDL_KEYUP: { const SDL_KeyboardEvent &event = sdlEvent.key; - auto mode = event.keysym.mod; - keyboard.action = KeyboardEvent::Action::RELEASE; - keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); - keyboard.altKeyActive = mode & KMOD_ALT; - keyboard.ctrlKeyActive = mode & KMOD_CTRL; - keyboard.shiftKeyActive = mode & KMOD_SHIFT; + auto mode = event.keysym.mod; + keyboard.action = KeyboardEvent::Action::RELEASE; + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); + keyboard.altKeyActive = mode & KMOD_ALT; + keyboard.ctrlKeyActive = mode & KMOD_CTRL; + keyboard.shiftKeyActive = mode & KMOD_SHIFT; _delegate->dispatchEvent(keyboard); break; } @@ -326,7 +326,7 @@ void SDLHelper::dispatchSDLEvent(const SDL_Event &sdlEvent, bool *quit) { void SDLHelper::pollEvent(bool *quit) { SDL_Event sdlEvent; - int cnt = 0; + int cnt = 0; while ((cnt = SDL_PollEvent(&sdlEvent)) != 0) { dispatchSDLEvent(sdlEvent, quit); if (*quit) { @@ -357,7 +357,7 @@ bool SDLHelper::createWindow(const char *title, } // Create window int sdlFlags = windowFlagsToSDLWindowFlag(flags); - _handle = SDL_CreateWindow(title, x, y, w, h, sdlFlags); + _handle = SDL_CreateWindow(title, x, y, w, h, sdlFlags); if (_handle == nullptr) { // Display error message CC_LOG_ERROR("Window could not be created! SDL_Error: %s\n", SDL_GetError()); diff --git a/native/cocos/platform/SDLHelper.h b/native/cocos/platform/SDLHelper.h index 50ae40f128..bbf64303c1 100644 --- a/native/cocos/platform/SDLHelper.h +++ b/native/cocos/platform/SDLHelper.h @@ -39,7 +39,7 @@ public: SDLHelper(IEventDispatch* delegate); ~SDLHelper(); - int init(); + int init(); void swapWindow(); bool createWindow(const char* title, int w, int h, int flags); @@ -47,7 +47,7 @@ public: int x, int y, int w, int h, int flags); - void pollEvent(bool* quit); + void pollEvent(bool* quit); uintptr_t getWindowHandler() const; #if (CC_PLATFORM == CC_PLATFORM_LINUX) uintptr_t getDisplay() const; @@ -55,10 +55,10 @@ public: void setCursorEnabled(bool value); private: - void dispatchSDLEvent(const SDL_Event& sdlEvent, bool* quit); - void dispatchWindowEvent(const SDL_WindowEvent& wevent); - bool _isWindowCreated{false}; - IEventDispatch* _delegate{nullptr}; + void dispatchSDLEvent(const SDL_Event& sdlEvent, bool* quit); + void dispatchWindowEvent(const SDL_WindowEvent& wevent); + bool _isWindowCreated{false}; + IEventDispatch* _delegate{nullptr}; struct SDL_Window* _handle{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/UniversalPlatform.cpp b/native/cocos/platform/UniversalPlatform.cpp index 7514a46682..4542cfac51 100644 --- a/native/cocos/platform/UniversalPlatform.cpp +++ b/native/cocos/platform/UniversalPlatform.cpp @@ -27,8 +27,8 @@ #include "platform/interfaces/OSInterface.h" -extern int cocos_main(int argc, const char** argv); // NOLINT(readability-identifier-naming) -extern void cocos_destory(); // NOLINT(readability-identifier-naming) +extern int cocos_main(int argc, const char** argv); // NOLINT(readability-identifier-naming) +extern void cocos_destory(); // NOLINT(readability-identifier-naming) namespace cc { UniversalPlatform::OSType UniversalPlatform::getOSType() const { diff --git a/native/cocos/platform/UniversalPlatform.h b/native/cocos/platform/UniversalPlatform.h index ed742542b2..7adcf077b4 100644 --- a/native/cocos/platform/UniversalPlatform.h +++ b/native/cocos/platform/UniversalPlatform.h @@ -61,7 +61,7 @@ public: /** * @brief Implement dispatch touch event interface. */ - void dispatchTouchEvent(const TouchEvent& ev) override; + void dispatchTouchEvent(const TouchEvent &ev) override; /** * @brief Implement handle default event interface. */ @@ -113,9 +113,9 @@ private: int32_t _fps{60}; - HandleEventCallback _handleEventCallback{nullptr}; + HandleEventCallback _handleEventCallback{nullptr}; HandleTouchEventCallback _handleTouchEventCallback{nullptr}; - HandleEventCallback _handleDefaultEventCallback{nullptr}; + HandleEventCallback _handleDefaultEventCallback{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index d2989dd3be..0d157726af 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -42,454 +42,458 @@ #include "java/jni/JniHelper.h" #include "game-activity/native_app_glue/android_native_app_glue.h" - #include "bindings/event/EventDispatcher.h" #include "paddleboat.h" +#define ABORT_GAME \ + { \ + CC_LOG_ERROR("*** GAME ABORTING."); \ + *((volatile char *)0) = 'a'; \ + } -#define ABORT_GAME { CC_LOG_ERROR("*** GAME ABORTING."); *((volatile char*)0) = 'a'; } - -#define ABORT_IF(cond) { if (!(cond)) { CC_LOG_ERROR("ASSERTION FAILED: %s", #cond); \ - ABORT_GAME; } } +#define ABORT_IF(cond) \ + { \ + if (!(cond)) { \ + CC_LOG_ERROR("ASSERTION FAILED: %s", #cond); \ + ABORT_GAME; \ + } \ + } #define INPUT_ACTION_COUNT 6 - extern int cocos_main(int argc, const char **argv); // NOLINT(readability-identifier-naming) namespace cc { - struct cc::TouchEvent touchEvent; - struct cc::KeyboardEvent keyboardEvent; - static uint32_t prevButtonsDown = 0; +struct cc::TouchEvent touchEvent; +struct cc::KeyboardEvent keyboardEvent; +static uint32_t prevButtonsDown = 0; - struct InputAction { - uint32_t buttonMask{0}; - int32_t actionCode{-1}; - }; +struct InputAction { + uint32_t buttonMask{0}; + int32_t actionCode{-1}; +}; - static const InputAction PADDLEBOAT_ACTIONS[INPUT_ACTION_COUNT] = { - {PADDLEBOAT_BUTTON_A, static_cast(KeyCode::ENTER)}, - {PADDLEBOAT_BUTTON_B, static_cast(KeyCode::ESCAPE)}, - {PADDLEBOAT_BUTTON_DPAD_UP, static_cast(KeyCode::DPAD_UP)}, - {PADDLEBOAT_BUTTON_DPAD_LEFT, static_cast(KeyCode::DPAD_LEFT)}, - {PADDLEBOAT_BUTTON_DPAD_DOWN, static_cast(KeyCode::DPAD_DOWN)}, - {PADDLEBOAT_BUTTON_DPAD_RIGHT, static_cast(KeyCode::DPAD_RIGHT)} - }; - static bool keyState[INPUT_ACTION_COUNT] = {false}; +static const InputAction PADDLEBOAT_ACTIONS[INPUT_ACTION_COUNT] = { + {PADDLEBOAT_BUTTON_A, static_cast(KeyCode::ENTER)}, + {PADDLEBOAT_BUTTON_B, static_cast(KeyCode::ESCAPE)}, + {PADDLEBOAT_BUTTON_DPAD_UP, static_cast(KeyCode::DPAD_UP)}, + {PADDLEBOAT_BUTTON_DPAD_LEFT, static_cast(KeyCode::DPAD_LEFT)}, + {PADDLEBOAT_BUTTON_DPAD_DOWN, static_cast(KeyCode::DPAD_DOWN)}, + {PADDLEBOAT_BUTTON_DPAD_RIGHT, static_cast(KeyCode::DPAD_RIGHT)}}; +static bool keyState[INPUT_ACTION_COUNT] = {false}; - extern void gameControllerStatusCallback(int32_t controllerIndex, - Paddleboat_ControllerStatus status, - void *userData); +extern void gameControllerStatusCallback(int32_t controllerIndex, + Paddleboat_ControllerStatus status, + void *userData); - class GameInputProxy { - public: - explicit GameInputProxy(AndroidPlatform *platform) { - _androidPlatform = platform; - if (0 != platform->_app->activity->vm->AttachCurrentThread(&_jniEnv, nullptr)) { - CC_LOG_FATAL("*** FATAL ERROR: Failed to attach thread to JNI."); - ABORT_GAME - } - ABORT_IF(_jniEnv != nullptr) - - Paddleboat_init(_jniEnv, platform->_app->activity->javaGameActivity); - Paddleboat_setControllerStatusCallback(gameControllerStatusCallback, this); - // This is needed to allow controller events through to us. - // By default, only touch-screen events are passed through, to match the - // behaviour of NativeActivity. - android_app_set_motion_event_filter(platform->_app, nullptr); - - // Flags to control how the IME behaves. - static constexpr int INPUTTYPE_DOT_TYPE_CLASS_TEXT = 1; - static constexpr int IME_ACTION_NONE = 1; - static constexpr int IME_FLAG_NO_FULLSCREEN = 33554432; - - GameActivity_setImeEditorInfo(platform->_app->activity, INPUTTYPE_DOT_TYPE_CLASS_TEXT, - IME_ACTION_NONE, IME_FLAG_NO_FULLSCREEN); +class GameInputProxy { +public: + explicit GameInputProxy(AndroidPlatform *platform) { + _androidPlatform = platform; + if (0 != platform->_app->activity->vm->AttachCurrentThread(&_jniEnv, nullptr)) { + CC_LOG_FATAL("*** FATAL ERROR: Failed to attach thread to JNI."); + ABORT_GAME } + ABORT_IF(_jniEnv != nullptr) - ~GameInputProxy() { - Paddleboat_setControllerStatusCallback(nullptr, nullptr); - Paddleboat_destroy(_jniEnv); - if (_jniEnv) { - CC_LOG_INFO("Detaching current thread from JNI."); - _androidPlatform->_app->activity->vm->DetachCurrentThread(); - CC_LOG_INFO("Current thread detached from JNI."); - _jniEnv = nullptr; - } + Paddleboat_init(_jniEnv, platform->_app->activity->javaGameActivity); + Paddleboat_setControllerStatusCallback(gameControllerStatusCallback, this); + // This is needed to allow controller events through to us. + // By default, only touch-screen events are passed through, to match the + // behaviour of NativeActivity. + android_app_set_motion_event_filter(platform->_app, nullptr); + + // Flags to control how the IME behaves. + static constexpr int INPUTTYPE_DOT_TYPE_CLASS_TEXT = 1; + static constexpr int IME_ACTION_NONE = 1; + static constexpr int IME_FLAG_NO_FULLSCREEN = 33554432; + + GameActivity_setImeEditorInfo(platform->_app->activity, INPUTTYPE_DOT_TYPE_CLASS_TEXT, + IME_ACTION_NONE, IME_FLAG_NO_FULLSCREEN); + } + + ~GameInputProxy() { + Paddleboat_setControllerStatusCallback(nullptr, nullptr); + Paddleboat_destroy(_jniEnv); + if (_jniEnv) { + CC_LOG_INFO("Detaching current thread from JNI."); + _androidPlatform->_app->activity->vm->DetachCurrentThread(); + CC_LOG_INFO("Current thread detached from JNI."); + _jniEnv = nullptr; } + } - void handleInput() { - Paddleboat_update(_jniEnv); - // If we get any key or motion events that were handled by a game controller, - // read controller data and cook it into an event - bool controllerEvent = false; + void handleInput() { + Paddleboat_update(_jniEnv); + // If we get any key or motion events that were handled by a game controller, + // read controller data and cook it into an event + bool controllerEvent = false; - // Swap input buffers so we don't miss any events while processing inputBuffer. - android_input_buffer *inputBuffer = android_app_swap_input_buffers( - _androidPlatform->_app); - // Early exit if no events. - if (inputBuffer == nullptr) return; + // Swap input buffers so we don't miss any events while processing inputBuffer. + android_input_buffer *inputBuffer = android_app_swap_input_buffers( + _androidPlatform->_app); + // Early exit if no events. + if (inputBuffer == nullptr) return; - if (inputBuffer->keyEventsCount != 0) { - for (uint64_t i = 0; i < inputBuffer->keyEventsCount; ++i) { - GameActivityKeyEvent *keyEvent = &inputBuffer->keyEvents[i]; - if (Paddleboat_processGameActivityKeyInputEvent(keyEvent, - sizeof(GameActivityKeyEvent))) { - controllerEvent = true; - } else { - cookGameActivityKeyEvent(keyEvent); - } - } - android_app_clear_key_events(inputBuffer); - } - if (inputBuffer->motionEventsCount != 0) { - for (uint64_t i = 0; i < inputBuffer->motionEventsCount; ++i) { - GameActivityMotionEvent *motionEvent = &inputBuffer->motionEvents[i]; - - if (Paddleboat_processGameActivityMotionInputEvent(motionEvent, - sizeof(GameActivityMotionEvent))) { - controllerEvent = true; - } else { - // Didn't belong to a game controller, process it ourselves if it is a touch event - cookGameActivityMotionEvent(motionEvent); - } - } - android_app_clear_motion_events(inputBuffer); - } - - if (controllerEvent) { - cookGameControllerEvent(_gameControllerIndex); - } - } - - bool cookGameControllerEvent(const int32_t gameControllerIndex) { - int addedControllerEvent = 0; - if (gameControllerIndex >= 0) { - Paddleboat_Controller_Data controllerData; - if (Paddleboat_getControllerData(gameControllerIndex, &controllerData) == - PADDLEBOAT_NO_ERROR) { - // Generate events from buttons - for (auto inputAction : PADDLEBOAT_ACTIONS) { - if (controllerData.buttonsDown & inputAction.buttonMask) { - reportKeyState(inputAction.actionCode, true); - addedControllerEvent = 1; - } else if (prevButtonsDown & inputAction.buttonMask) { - reportKeyState(inputAction.actionCode, false); - addedControllerEvent = 1; - } - } - - // Update our prev variable so we can detect delta changes from down to up - prevButtonsDown = controllerData.buttonsDown; - } - } - return (addedControllerEvent != 0); - } - - bool cookGameActivityMotionEvent(GameActivityMotionEvent *motionEvent) { - if (motionEvent->pointerCount > 0) { - int action = motionEvent->action; - int actionMasked = action & AMOTION_EVENT_ACTION_MASK; - - if (actionMasked == AMOTION_EVENT_ACTION_DOWN || - actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { - touchEvent.type = cc::TouchEvent::Type::BEGAN; - } else if (actionMasked == AMOTION_EVENT_ACTION_UP || - actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { - touchEvent.type = cc::TouchEvent::Type::ENDED; - } else if (actionMasked == AMOTION_EVENT_ACTION_CANCEL) { - touchEvent.type = cc::TouchEvent::Type::CANCELLED; - } else if (actionMasked == AMOTION_EVENT_ACTION_MOVE) { - touchEvent.type = cc::TouchEvent::Type::MOVED; + if (inputBuffer->keyEventsCount != 0) { + for (uint64_t i = 0; i < inputBuffer->keyEventsCount; ++i) { + GameActivityKeyEvent *keyEvent = &inputBuffer->keyEvents[i]; + if (Paddleboat_processGameActivityKeyInputEvent(keyEvent, + sizeof(GameActivityKeyEvent))) { + controllerEvent = true; } else { - return false; + cookGameActivityKeyEvent(keyEvent); } + } + android_app_clear_key_events(inputBuffer); + } + if (inputBuffer->motionEventsCount != 0) { + for (uint64_t i = 0; i < inputBuffer->motionEventsCount; ++i) { + GameActivityMotionEvent *motionEvent = &inputBuffer->motionEvents[i]; - for (int i = 0; i < motionEvent->pointerCount; i++) { - int id = motionEvent->pointers[i].id; - float x = GameActivityPointerAxes_getX(&motionEvent->pointers[i]); - float y = GameActivityPointerAxes_getY(&motionEvent->pointers[i]); - touchEvent.touches.emplace_back(x, y, id); + if (Paddleboat_processGameActivityMotionInputEvent(motionEvent, + sizeof(GameActivityMotionEvent))) { + controllerEvent = true; + } else { + // Didn't belong to a game controller, process it ourselves if it is a touch event + cookGameActivityMotionEvent(motionEvent); } - _androidPlatform->dispatchEvent(touchEvent); - touchEvent.touches.clear(); - return true; } - return false; + android_app_clear_motion_events(inputBuffer); } - bool cookGameActivityKeyEvent(GameActivityKeyEvent *keyEvent) { - if (keyEvent->keyCode == AKEYCODE_BACK && 0 == keyEvent->action) { - // back key was pressed - keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; - keyboardEvent.key = static_cast(KeyCode::MOBILE_BACK); - _androidPlatform->dispatchEvent(keyboardEvent); - return true; - } - return false; + if (controllerEvent) { + cookGameControllerEvent(_gameControllerIndex); } + } - void reportKeyState(int keyCode, bool state) { - bool wentDown = !keyState[keyCode] && state; - bool wentUp = keyState[keyCode] && !state; - keyState[keyCode] = state; - - if (wentUp) { - keyboardEvent.key = keyCode; - keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; - _androidPlatform->dispatchEvent(keyboardEvent); - } else if (wentDown) { - keyboardEvent.key = keyCode; - keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; - _androidPlatform->dispatchEvent(keyboardEvent); - } - } - - int32_t getActiveGameControllerIndex() const { - return _gameControllerIndex; - } - - void setActiveGameControllerIndex(const int32_t controllerIndex) { - _gameControllerIndex = controllerIndex; - } - - void handleAppCommand(int32_t cmd) { - switch (cmd) { - case APP_CMD_SAVE_STATE: - // The system has asked us to save our current state. - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_SAVE_STATE"); - break; - case APP_CMD_INIT_WINDOW: { - _hasWindow = true; - // We have a window! - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_INIT_WINDOW"); - if (!_running) { - _running = true; - _androidPlatform->run(0, nullptr); - } else { - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args->ptrVal = reinterpret_cast(_androidPlatform->getWindowHandler()); - _androidPlatform->dispatchEvent(event); + bool cookGameControllerEvent(const int32_t gameControllerIndex) { + int addedControllerEvent = 0; + if (gameControllerIndex >= 0) { + Paddleboat_Controller_Data controllerData; + if (Paddleboat_getControllerData(gameControllerIndex, &controllerData) == + PADDLEBOAT_NO_ERROR) { + // Generate events from buttons + for (auto inputAction : PADDLEBOAT_ACTIONS) { + if (controllerData.buttonsDown & inputAction.buttonMask) { + reportKeyState(inputAction.actionCode, true); + addedControllerEvent = 1; + } else if (prevButtonsDown & inputAction.buttonMask) { + reportKeyState(inputAction.actionCode, false); + addedControllerEvent = 1; } - break; } - case APP_CMD_TERM_WINDOW: { - _hasWindow = false; - // The window is going away -- kill the surface - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_TERM_WINDOW"); + + // Update our prev variable so we can detect delta changes from down to up + prevButtonsDown = controllerData.buttonsDown; + } + } + return (addedControllerEvent != 0); + } + + bool cookGameActivityMotionEvent(GameActivityMotionEvent *motionEvent) { + if (motionEvent->pointerCount > 0) { + int action = motionEvent->action; + int actionMasked = action & AMOTION_EVENT_ACTION_MASK; + + if (actionMasked == AMOTION_EVENT_ACTION_DOWN || + actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { + touchEvent.type = cc::TouchEvent::Type::BEGAN; + } else if (actionMasked == AMOTION_EVENT_ACTION_UP || + actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { + touchEvent.type = cc::TouchEvent::Type::ENDED; + } else if (actionMasked == AMOTION_EVENT_ACTION_CANCEL) { + touchEvent.type = cc::TouchEvent::Type::CANCELLED; + } else if (actionMasked == AMOTION_EVENT_ACTION_MOVE) { + touchEvent.type = cc::TouchEvent::Type::MOVED; + } else { + return false; + } + + for (int i = 0; i < motionEvent->pointerCount; i++) { + int id = motionEvent->pointers[i].id; + float x = GameActivityPointerAxes_getX(&motionEvent->pointers[i]); + float y = GameActivityPointerAxes_getY(&motionEvent->pointers[i]); + touchEvent.touches.emplace_back(x, y, id); + } + _androidPlatform->dispatchEvent(touchEvent); + touchEvent.touches.clear(); + return true; + } + return false; + } + + bool cookGameActivityKeyEvent(GameActivityKeyEvent *keyEvent) { + if (keyEvent->keyCode == AKEYCODE_BACK && 0 == keyEvent->action) { + // back key was pressed + keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; + keyboardEvent.key = static_cast(KeyCode::MOBILE_BACK); + _androidPlatform->dispatchEvent(keyboardEvent); + return true; + } + return false; + } + + void reportKeyState(int keyCode, bool state) { + bool wentDown = !keyState[keyCode] && state; + bool wentUp = keyState[keyCode] && !state; + keyState[keyCode] = state; + + if (wentUp) { + keyboardEvent.key = keyCode; + keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; + _androidPlatform->dispatchEvent(keyboardEvent); + } else if (wentDown) { + keyboardEvent.key = keyCode; + keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; + _androidPlatform->dispatchEvent(keyboardEvent); + } + } + + int32_t getActiveGameControllerIndex() const { + return _gameControllerIndex; + } + + void setActiveGameControllerIndex(const int32_t controllerIndex) { + _gameControllerIndex = controllerIndex; + } + + void handleAppCommand(int32_t cmd) { + switch (cmd) { + case APP_CMD_SAVE_STATE: + // The system has asked us to save our current state. + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_SAVE_STATE"); + break; + case APP_CMD_INIT_WINDOW: { + _hasWindow = true; + // We have a window! + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_INIT_WINDOW"); + if (!_running) { + _running = true; + _androidPlatform->run(0, nullptr); + } else { cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; + event.name = EVENT_RECREATE_WINDOW; event.args->ptrVal = reinterpret_cast(_androidPlatform->getWindowHandler()); _androidPlatform->dispatchEvent(event); - break; } - case APP_CMD_GAINED_FOCUS: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_GAINED_FOCUS"); - break; - case APP_CMD_LOST_FOCUS: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_LOST_FOCUS"); - break; - case APP_CMD_PAUSE: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_PAUSE"); - break; - case APP_CMD_RESUME: { - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_RESUME"); - break; - } - case APP_CMD_DESTROY: { - WindowEvent ev; - ev.type = WindowEvent::Type::CLOSE; - _androidPlatform->dispatchEvent(ev); - break; - } - case APP_CMD_STOP: { - _isVisible = false; - Paddleboat_onStop(_jniEnv); - WindowEvent ev; - ev.type = WindowEvent::Type::HIDDEN; - _androidPlatform->dispatchEvent(ev); - break; - } - case APP_CMD_START: { - _isVisible = true; - Paddleboat_onStart(_jniEnv); - WindowEvent ev; - ev.type = WindowEvent::Type::SHOW; - _androidPlatform->dispatchEvent(ev); - break; - } - case APP_CMD_WINDOW_RESIZED: - case APP_CMD_CONFIG_CHANGED: - // Window was resized or some other configuration changed. - // Note: we don't handle this event because we check the surface dimensions - // every frame, so that's how we know it was resized. If you are NOT doing that, - // then you need to handle this event! - break; - case APP_CMD_LOW_MEMORY: { - // system told us we have low memory. So if we are not visible, let's - // cooperate by deallocating all of our graphic resources. - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_LOW_MEMORY"); - DeviceEvent ev; - ev.type = DeviceEvent::Type::DEVICE_MEMORY; - _androidPlatform->dispatchEvent(ev); - break; - } - case APP_CMD_CONTENT_RECT_CHANGED: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_CONTENT_RECT_CHANGED"); - break; - case APP_CMD_WINDOW_REDRAW_NEEDED: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_WINDOW_REDRAW_NEEDED"); - break; - case APP_CMD_WINDOW_INSETS_CHANGED: - CC_LOG_DEBUG("AndroidPlatform: APP_CMD_WINDOW_INSETS_CHANGED"); -// ARect insets; -// // Log all the insets types -// for (int type = 0; type < GAMECOMMON_INSETS_TYPE_COUNT; ++type) { -// GameActivity_getWindowInsets(_app->activity, (GameCommonInsetsType)type, &insets); -// } - break; - default: - CC_LOG_DEBUG("AndroidPlatform: (unknown command)."); - break; + break; } + case APP_CMD_TERM_WINDOW: { + _hasWindow = false; + // The window is going away -- kill the surface + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_TERM_WINDOW"); + cc::CustomEvent event; + event.name = EVENT_DESTROY_WINDOW; + event.args->ptrVal = reinterpret_cast(_androidPlatform->getWindowHandler()); + _androidPlatform->dispatchEvent(event); + break; + } + case APP_CMD_GAINED_FOCUS: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_GAINED_FOCUS"); + break; + case APP_CMD_LOST_FOCUS: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_LOST_FOCUS"); + break; + case APP_CMD_PAUSE: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_PAUSE"); + break; + case APP_CMD_RESUME: { + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_RESUME"); + break; + } + case APP_CMD_DESTROY: { + WindowEvent ev; + ev.type = WindowEvent::Type::CLOSE; + _androidPlatform->dispatchEvent(ev); + break; + } + case APP_CMD_STOP: { + _isVisible = false; + Paddleboat_onStop(_jniEnv); + WindowEvent ev; + ev.type = WindowEvent::Type::HIDDEN; + _androidPlatform->dispatchEvent(ev); + break; + } + case APP_CMD_START: { + _isVisible = true; + Paddleboat_onStart(_jniEnv); + WindowEvent ev; + ev.type = WindowEvent::Type::SHOW; + _androidPlatform->dispatchEvent(ev); + break; + } + case APP_CMD_WINDOW_RESIZED: + case APP_CMD_CONFIG_CHANGED: + // Window was resized or some other configuration changed. + // Note: we don't handle this event because we check the surface dimensions + // every frame, so that's how we know it was resized. If you are NOT doing that, + // then you need to handle this event! + break; + case APP_CMD_LOW_MEMORY: { + // system told us we have low memory. So if we are not visible, let's + // cooperate by deallocating all of our graphic resources. + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_LOW_MEMORY"); + DeviceEvent ev; + ev.type = DeviceEvent::Type::DEVICE_MEMORY; + _androidPlatform->dispatchEvent(ev); + break; + } + case APP_CMD_CONTENT_RECT_CHANGED: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_CONTENT_RECT_CHANGED"); + break; + case APP_CMD_WINDOW_REDRAW_NEEDED: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_WINDOW_REDRAW_NEEDED"); + break; + case APP_CMD_WINDOW_INSETS_CHANGED: + CC_LOG_DEBUG("AndroidPlatform: APP_CMD_WINDOW_INSETS_CHANGED"); + // ARect insets; + // // Log all the insets types + // for (int type = 0; type < GAMECOMMON_INSETS_TYPE_COUNT; ++type) { + // GameActivity_getWindowInsets(_app->activity, (GameCommonInsetsType)type, &insets); + // } + break; + default: + CC_LOG_DEBUG("AndroidPlatform: (unknown command)."); + break; } - - bool isAnimating() const { - return _isVisible && _hasWindow; - } - - private: - AndroidPlatform *_androidPlatform{nullptr}; - JNIEnv *_jniEnv{nullptr};// JNI environment - int32_t _gameControllerIndex{-1};// Most recently connected game controller index - bool _running{false}; - bool _isVisible{false}; - bool _hasWindow{false}; - }; - - static void handleCmdProxy(struct android_app *app, int32_t cmd) { - auto *proxy = static_cast(app->userData); - proxy->handleAppCommand(cmd); } - void gameControllerStatusCallback(const int32_t controllerIndex, - const Paddleboat_ControllerStatus status, - void *userData) { - auto *inputProxy = static_cast(userData); - if (inputProxy) { - // Always make the most recently connected controller the active one - if (status == PADDLEBOAT_CONTROLLER_JUST_CONNECTED) { - inputProxy->setActiveGameControllerIndex(controllerIndex); - } else if (status == PADDLEBOAT_CONTROLLER_JUST_DISCONNECTED) { - // We only care if the controller that disconnected was the one - // we are currently using - if (controllerIndex == inputProxy->getActiveGameControllerIndex()) { - // Default to no fallback controller, loop and look for another connected - // one - int32_t newControllerIndex = -1; + bool isAnimating() const { + return _isVisible && _hasWindow; + } - for (int32_t i = 0; i < PADDLEBOAT_MAX_CONTROLLERS; ++i) { - if (i != controllerIndex && - Paddleboat_getControllerStatus(i) == PADDLEBOAT_CONTROLLER_ACTIVE) { - newControllerIndex = i; - break; - } +private: + AndroidPlatform *_androidPlatform{nullptr}; + JNIEnv *_jniEnv{nullptr}; // JNI environment + int32_t _gameControllerIndex{-1}; // Most recently connected game controller index + bool _running{false}; + bool _isVisible{false}; + bool _hasWindow{false}; +}; + +static void handleCmdProxy(struct android_app *app, int32_t cmd) { + auto *proxy = static_cast(app->userData); + proxy->handleAppCommand(cmd); +} + +void gameControllerStatusCallback(const int32_t controllerIndex, + const Paddleboat_ControllerStatus status, + void *userData) { + auto *inputProxy = static_cast(userData); + if (inputProxy) { + // Always make the most recently connected controller the active one + if (status == PADDLEBOAT_CONTROLLER_JUST_CONNECTED) { + inputProxy->setActiveGameControllerIndex(controllerIndex); + } else if (status == PADDLEBOAT_CONTROLLER_JUST_DISCONNECTED) { + // We only care if the controller that disconnected was the one + // we are currently using + if (controllerIndex == inputProxy->getActiveGameControllerIndex()) { + // Default to no fallback controller, loop and look for another connected + // one + int32_t newControllerIndex = -1; + + for (int32_t i = 0; i < PADDLEBOAT_MAX_CONTROLLERS; ++i) { + if (i != controllerIndex && + Paddleboat_getControllerStatus(i) == PADDLEBOAT_CONTROLLER_ACTIVE) { + newControllerIndex = i; + break; } - inputProxy->setActiveGameControllerIndex(newControllerIndex); } + inputProxy->setActiveGameControllerIndex(newControllerIndex); } } } +} - AndroidPlatform::~AndroidPlatform() { - CC_SAFE_DELETE(_inputProxy) +AndroidPlatform::~AndroidPlatform() { + CC_SAFE_DELETE(_inputProxy) +} + +int AndroidPlatform::init() { + _inputProxy = new GameInputProxy(this); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + registerInterface(std::make_shared()); + + return 0; +} + +int AndroidPlatform::getSdkVersion() const { + return AConfiguration_getSdkVersion(_app->config); +} + +int32_t AndroidPlatform::run(int argc, const char **argv) { + if (cocos_main(argc, argv) != 0) { + return -1; } + return 0; +} - int AndroidPlatform::init() { - _inputProxy = new GameInputProxy(this); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); - registerInterface(std::make_shared()); +uintptr_t AndroidPlatform::getWindowHandler() const { + return reinterpret_cast(_app->window); +} - return 0; - } +int32_t AndroidPlatform::loop() { + _app->userData = _inputProxy; + _app->onAppCmd = handleCmdProxy; - int AndroidPlatform::getSdkVersion() const { - return AConfiguration_getSdkVersion(_app->config); - } + while (true) { + int events; + struct android_poll_source *source; - int32_t AndroidPlatform::run(int argc, const char **argv) { - if (cocos_main(argc, argv) != 0) { - return -1; - } - return 0; - } - - uintptr_t AndroidPlatform::getWindowHandler() const { - return reinterpret_cast(_app->window); - } - - int32_t AndroidPlatform::loop() { - _app->userData = _inputProxy; - _app->onAppCmd = handleCmdProxy; - - while (true) { - int events; - struct android_poll_source *source; - - // If not animating, block until we get an event; if animating, don't block. - while ((ALooper_pollAll(_inputProxy->isAnimating() ? 0 : -1, nullptr, &events, - reinterpret_cast(&source))) >= 0) { - - // process event - if (source != nullptr) { - source->process(_app, source); - } - - // are we exiting? - if (_app->destroyRequested) { - return 0; - } + // If not animating, block until we get an event; if animating, don't block. + while ((ALooper_pollAll(_inputProxy->isAnimating() ? 0 : -1, nullptr, &events, + reinterpret_cast(&source))) >= 0) { + // process event + if (source != nullptr) { + source->process(_app, source); } - _inputProxy->handleInput(); - runTask(); - flushTasksOnGameThreadJNI(); - if (_inputProxy->isAnimating()) { - flushTasksOnGameThreadAtForegroundJNI(); + // are we exiting? + if (_app->destroyRequested) { + return 0; } } - } + _inputProxy->handleInput(); + runTask(); - void AndroidPlatform::pollEvent() { - // + flushTasksOnGameThreadJNI(); + if (_inputProxy->isAnimating()) { + flushTasksOnGameThreadAtForegroundJNI(); + } } +} - void *AndroidPlatform::getActivity() { - return _app->activity->javaGameActivity; - } +void AndroidPlatform::pollEvent() { + // +} - void *AndroidPlatform::getEnv() { - return JniHelper::getEnv(); - } +void *AndroidPlatform::getActivity() { + return _app->activity->javaGameActivity; +} - int32_t AndroidPlatform::getWidth() const { - return ANativeWindow_getWidth(_app->window); - } +void *AndroidPlatform::getEnv() { + return JniHelper::getEnv(); +} - int32_t AndroidPlatform::getHeight() const { - return ANativeWindow_getHeight(_app->window); - } +int32_t AndroidPlatform::getWidth() const { + return ANativeWindow_getWidth(_app->window); +} - void AndroidPlatform::setAndroidApp(android_app *app) { - _app = app; - } +int32_t AndroidPlatform::getHeight() const { + return ANativeWindow_getHeight(_app->window); +} + +void AndroidPlatform::setAndroidApp(android_app *app) { + _app = app; +} } // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.h b/native/cocos/platform/android/AndroidPlatform.h index f1e559115f..100e27bc67 100644 --- a/native/cocos/platform/android/AndroidPlatform.h +++ b/native/cocos/platform/android/AndroidPlatform.h @@ -30,40 +30,40 @@ struct android_app; namespace cc { - class GameInputProxy; +class GameInputProxy; - class CC_DLL AndroidPlatform : public UniversalPlatform { - public: - AndroidPlatform() = default; +class CC_DLL AndroidPlatform : public UniversalPlatform { +public: + AndroidPlatform() = default; - ~AndroidPlatform() override; + ~AndroidPlatform() override; - int init() override; + int init() override; - void pollEvent() override; + void pollEvent() override; - int32_t run(int argc, const char **argv) override; + int32_t run(int argc, const char **argv) override; - int getSdkVersion() const override; + int getSdkVersion() const override; - int32_t loop() override; + int32_t loop() override; - void *getActivity(); + void *getActivity(); - static void *getEnv(); + static void *getEnv(); - uintptr_t getWindowHandler() const; + uintptr_t getWindowHandler() const; - int32_t getWidth() const; + int32_t getWidth() const; - int32_t getHeight() const; + int32_t getHeight() const; - void setAndroidApp(android_app *app); + void setAndroidApp(android_app *app); - private: - GameInputProxy *_inputProxy{nullptr}; - android_app *_app{nullptr}; +private: + GameInputProxy *_inputProxy{nullptr}; + android_app *_app{nullptr}; - friend class GameInputProxy; - }; + friend class GameInputProxy; +}; } // namespace cc diff --git a/native/cocos/platform/android/FileUtils-android.cpp b/native/cocos/platform/android/FileUtils-android.cpp index 609afda1cf..6a3ec073e6 100644 --- a/native/cocos/platform/android/FileUtils-android.cpp +++ b/native/cocos/platform/android/FileUtils-android.cpp @@ -49,7 +49,7 @@ namespace cc { AAssetManager *FileUtilsAndroid::assetmanager = nullptr; -ZipFile * FileUtilsAndroid::obbfile = nullptr; +ZipFile *FileUtilsAndroid::obbfile = nullptr; void FileUtilsAndroid::setassetmanager(AAssetManager *a) { if (nullptr == a) { @@ -186,7 +186,7 @@ FileUtils::Status FileUtilsAndroid::getContents(const ccstd::string &filename, R } ccstd::string relativePath; - size_t position = fullPath.find(ASSETS_FOLDER_NAME); + size_t position = fullPath.find(ASSETS_FOLDER_NAME); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it relativePath += fullPath.substr(strlen(ASSETS_FOLDER_NAME)); diff --git a/native/cocos/platform/android/FileUtils-android.h b/native/cocos/platform/android/FileUtils-android.h index 3b93663422..96e2c32e7d 100644 --- a/native/cocos/platform/android/FileUtils-android.h +++ b/native/cocos/platform/android/FileUtils-android.h @@ -54,23 +54,23 @@ public: */ ~FileUtilsAndroid() override; - static void setassetmanager(AAssetManager *a); + static void setassetmanager(AAssetManager *a); static AAssetManager *getAssetManager() { return assetmanager; } - static ZipFile * getObbFile() { return obbfile; } + static ZipFile *getObbFile() { return obbfile; } /* override functions */ - bool init() override; + bool init() override; FileUtils::Status getContents(const ccstd::string &filename, ResizableBuffer *buffer) override; ccstd::string getWritablePath() const override; - bool isAbsolutePath(const ccstd::string &strPath) const override; + bool isAbsolutePath(const ccstd::string &strPath) const override; private: bool isFileExistInternal(const ccstd::string &strFilePath) const override; bool isDirectoryExistInternal(const ccstd::string &dirPath) const override; static AAssetManager *assetmanager; - static ZipFile * obbfile; + static ZipFile *obbfile; }; // end of platform group diff --git a/native/cocos/platform/android/jni/JniCocosEntry.cpp b/native/cocos/platform/android/jni/JniCocosEntry.cpp index 77f0d489a9..07b38844e2 100644 --- a/native/cocos/platform/android/jni/JniCocosEntry.cpp +++ b/native/cocos/platform/android/jni/JniCocosEntry.cpp @@ -30,7 +30,6 @@ #include "platform/java/jni/JniHelper.h" #include "game-activity/native_app_glue/android_native_app_glue.h" - extern "C" { void android_main(struct android_app *app) { @@ -43,10 +42,8 @@ void android_main(struct android_app *app) { platform->loop(); } - //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *env, jobject obj, jobject activity) { cc::JniHelper::init(env, activity); } - } diff --git a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp index 4c19132b82..af64096510 100644 --- a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp +++ b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp @@ -36,8 +36,8 @@ extern "C" { JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_nativeOnSizeChanged(JNIEnv *env, jobject thiz, jint width, jint height) { cc::WindowEvent ev; - ev.type = cc::WindowEvent::Type::SIZE_CHANGED; - ev.width = width; + ev.type = cc::WindowEvent::Type::SIZE_CHANGED; + ev.width = width; ev.height = height; JNI_NATIVE_GLUE()->dispatchEvent(ev); } diff --git a/native/cocos/platform/android/modules/Screen.cpp b/native/cocos/platform/android/modules/Screen.cpp index 2eb19a4887..5d8cd5d4fb 100644 --- a/native/cocos/platform/android/modules/Screen.cpp +++ b/native/cocos/platform/android/modules/Screen.cpp @@ -39,7 +39,7 @@ int Screen::getDPI() const { int32_t density = AConfiguration_getDensity(config); AConfiguration_delete(config); const int stdDpi = 160; - dpi = density * stdDpi; + dpi = density * stdDpi; } return dpi; } diff --git a/native/cocos/platform/apple/FileUtils-apple.h b/native/cocos/platform/apple/FileUtils-apple.h index b1082667d6..ea2355c69d 100644 --- a/native/cocos/platform/apple/FileUtils-apple.h +++ b/native/cocos/platform/apple/FileUtils-apple.h @@ -53,7 +53,7 @@ public: virtual ValueMap getValueMapFromFile(const ccstd::string &filename) override; virtual ValueMap getValueMapFromData(const char *filedata, int filesize) override; - virtual bool writeToFile(const ValueMap &dict, const ccstd::string &fullPath) override; + virtual bool writeToFile(const ValueMap &dict, const ccstd::string &fullPath) override; virtual ValueVector getValueVectorFromFile(const ccstd::string &filename) override; #if CC_FILEUTILS_APPLE_ENABLE_OBJC diff --git a/native/cocos/platform/apple/JsbBridge.mm b/native/cocos/platform/apple/JsbBridge.mm index 96e1c3cd07..ed0ecd5d57 100644 --- a/native/cocos/platform/apple/JsbBridge.mm +++ b/native/cocos/platform/apple/JsbBridge.mm @@ -29,9 +29,9 @@ #include "cocos/bindings/manual/JavaScriptObjCBridge.h" bool callPlatformStringMethod(const ccstd::string &arg0, const ccstd::string &arg1) { - NSString *oc_arg0 = [NSString stringWithCString:arg0.c_str() encoding:NSUTF8StringEncoding]; - NSString *oc_arg1 = [NSString stringWithCString:arg1.c_str() encoding:NSUTF8StringEncoding]; - JsbBridge *m = [JsbBridge sharedInstance]; + NSString *oc_arg0 = [NSString stringWithCString:arg0.c_str() encoding:NSUTF8StringEncoding]; + NSString *oc_arg1 = [NSString stringWithCString:arg1.c_str() encoding:NSUTF8StringEncoding]; + JsbBridge *m = [JsbBridge sharedInstance]; [m callByScript:oc_arg0 arg1:oc_arg1]; return true; } diff --git a/native/cocos/platform/apple/JsbBridgeWrapper.mm b/native/cocos/platform/apple/JsbBridgeWrapper.mm index 0aa71d6f72..4c91b6654c 100644 --- a/native/cocos/platform/apple/JsbBridgeWrapper.mm +++ b/native/cocos/platform/apple/JsbBridgeWrapper.mm @@ -33,7 +33,7 @@ } static JsbBridgeWrapper* instance = nil; -static ICallback cb = ^void(NSString* _event, NSString* _arg) { +static ICallback cb = ^void(NSString* _event, NSString* _arg) { [[JsbBridgeWrapper sharedInstance] triggerEvent:_event arg:_arg]; }; + (instancetype)sharedInstance { @@ -72,7 +72,7 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { listener(arg); } } -- (void)removeAllListenersForEvent:(NSString *)eventName { +- (void)removeAllListenersForEvent:(NSString*)eventName { if (![cbDictionnary objectForKey:eventName]) { return; } @@ -99,7 +99,7 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { [jb sendToScript:eventName]; } - (id)init { - self = [super init]; + self = [super init]; cbDictionnary = [NSMutableDictionary new]; jb = [JsbBridge sharedInstance]; [jb setCallback:cb]; @@ -113,4 +113,3 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { [super dealloc]; } @end - diff --git a/native/cocos/platform/apple/Reachability.cpp b/native/cocos/platform/apple/Reachability.cpp index c2a952623f..de20820e0e 100644 --- a/native/cocos/platform/apple/Reachability.cpp +++ b/native/cocos/platform/apple/Reachability.cpp @@ -106,7 +106,7 @@ cc::Reachability::NetworkStatus getNetworkStatusForFlags(SCNetworkReachabilityFl namespace cc { Reachability *Reachability::createWithHostName(const ccstd::string &hostName) { - Reachability * returnValue = nullptr; + Reachability *returnValue = nullptr; SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(nullptr, hostName.c_str()); if (reachability != nullptr) { returnValue = ccnew Reachability(); @@ -142,7 +142,7 @@ Reachability *Reachability::createWithAddress(const struct sockaddr *hostAddress Reachability *Reachability::createForInternetConnection() { struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; return createWithAddress((const struct sockaddr *)&zeroAddress); @@ -175,8 +175,8 @@ bool Reachability::startNotifier(const ReachabilityCallback &cb, void *userData) _callback = cb; _userData = userData; - bool returnValue = false; - SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr}; + bool returnValue = false; + SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr}; if (SCNetworkReachabilitySetCallback(_reachabilityRef, onReachabilityCallback, &context)) { if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { @@ -206,7 +206,7 @@ bool Reachability::isConnectionRequired() const { Reachability::NetworkStatus Reachability::getCurrentReachabilityStatus() const { CC_ASSERT(_reachabilityRef != nullptr); - NetworkStatus returnValue = NetworkStatus::NOT_REACHABLE; + NetworkStatus returnValue = NetworkStatus::NOT_REACHABLE; SCNetworkReachabilityFlags flags; if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags)) { diff --git a/native/cocos/platform/apple/Reachability.h b/native/cocos/platform/apple/Reachability.h index fe4a6e31d0..07f5a83153 100644 --- a/native/cocos/platform/apple/Reachability.h +++ b/native/cocos/platform/apple/Reachability.h @@ -79,8 +79,8 @@ private: static void onReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info); - ReachabilityCallback _callback; - void * _userData; + ReachabilityCallback _callback; + void *_userData; SCNetworkReachabilityRef _reachabilityRef; }; diff --git a/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h index c27d1b9308..11eb29eeb2 100644 --- a/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.h @@ -42,37 +42,37 @@ namespace cc { class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: using Size = ccstd::array; - using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineJoin) override; - void rect(float x, float y, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineJoin) override; + void rect(float x, float y, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void updateData() override {} + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void updateData() override {} private: void fillData(); diff --git a/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm index db9f108fee..7262a06624 100644 --- a/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm +++ b/native/cocos/platform/apple/modules/CanvasRenderingContext2DDelegate.mm @@ -28,7 +28,6 @@ #include "base/csscolorparser.h" #include "math/Math.h" - #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_platform.h" @@ -53,13 +52,13 @@ #include @interface CanvasRenderingContext2DDelegateImpl : NSObject { - NSFont * _font; + NSFont *_font; NSMutableDictionary *_tokenAttributesDict; - NSString * _fontName; - CGFloat _fontSize; - CGFloat _width; - CGFloat _height; - CGContextRef _context; + NSString *_fontName; + CGFloat _fontSize; + CGFloat _width; + CGFloat _height; + CGContextRef _context; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX NSGraphicsContext *_currentGraphicsContext; @@ -69,47 +68,47 @@ #endif CGColorSpaceRef _colorSpace; - cc::Data _imageData; - NSBezierPath * _path; + cc::Data _imageData; + NSBezierPath *_path; - cc::ICanvasRenderingContext2D::TextAlign _textAlign; - cc::ICanvasRenderingContext2D::TextBaseline _textBaseLine; + cc::ICanvasRenderingContext2D::TextAlign _textAlign; + cc::ICanvasRenderingContext2D::TextBaseline _textBaseLine; ccstd::array _fillStyle; ccstd::array _strokeStyle; - float _lineWidth; - bool _bold; + float _lineWidth; + bool _bold; } -@property (nonatomic, strong) NSFont * font; +@property (nonatomic, strong) NSFont *font; @property (nonatomic, strong) NSMutableDictionary *tokenAttributesDict; -@property (nonatomic, strong) NSString * fontName; -@property (nonatomic, assign) cc::ICanvasRenderingContext2D::TextAlign textAlign; -@property (nonatomic, assign) cc::ICanvasRenderingContext2D::TextBaseline textBaseLine; -@property (nonatomic, assign) float lineWidth; +@property (nonatomic, strong) NSString *fontName; +@property (nonatomic, assign) cc::ICanvasRenderingContext2D::TextAlign textAlign; +@property (nonatomic, assign) cc::ICanvasRenderingContext2D::TextBaseline textBaseLine; +@property (nonatomic, assign) float lineWidth; @end @implementation CanvasRenderingContext2DDelegateImpl -@synthesize font = _font; +@synthesize font = _font; @synthesize tokenAttributesDict = _tokenAttributesDict; -@synthesize fontName = _fontName; -@synthesize textAlign = _textAlign; -@synthesize textBaseLine = _textBaseLine; -@synthesize lineWidth = _lineWidth; +@synthesize fontName = _fontName; +@synthesize textAlign = _textAlign; +@synthesize textBaseLine = _textBaseLine; +@synthesize lineWidth = _lineWidth; - (id)init { if (self = [super init]) { - _lineWidth = 0; - _textAlign = cc::ICanvasRenderingContext2D::TextAlign::LEFT; + _lineWidth = 0; + _textAlign = cc::ICanvasRenderingContext2D::TextAlign::LEFT; _textBaseLine = cc::ICanvasRenderingContext2D::TextBaseline::BOTTOM; _width = _height = 0; - _context = nil; - _colorSpace = nil; + _context = nil; + _colorSpace = nil; #if CC_PLATFORM == CC_PLATFORM_MAC_OSX _currentGraphicsContext = nil; - _oldGraphicsContext = nil; + _oldGraphicsContext = nil; #endif _path = [NSBezierPath bezierPath]; [_path retain]; @@ -120,9 +119,9 @@ } - (void)dealloc { - self.font = nil; + self.font = nil; self.tokenAttributesDict = nil; - self.fontName = nil; + self.fontName = nil; CGColorSpaceRelease(_colorSpace); // release the context CGContextRelease(_context); @@ -151,7 +150,7 @@ if (font == nil) { const auto &familyMap = getFontFamilyNameMap(); - auto iter = familyMap.find([_fontName UTF8String]); + auto iter = familyMap.find([_fontName UTF8String]); if (iter != familyMap.end()) { font = [[NSFontManager sharedFontManager] fontWithFamily:[NSString stringWithUTF8String:iter->second.c_str()] @@ -204,13 +203,13 @@ - (void)updateFontWithName:(NSString *)fontName fontSize:(CGFloat)fontSize bold:(bool)bold { _fontSize = fontSize; - _bold = bold; + _bold = bold; self.fontName = fontName; - self.font = [self _createSystemFont]; + self.font = [self _createSystemFont]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [paragraphStyle setAlignment:NSTextAlignmentCenter]; // color @@ -228,9 +227,9 @@ - (void)recreateBufferWithWidth:(NSInteger)width height:(NSInteger)height { _width = width = width > 0 ? width : 1; - _height = height = height > 0 ? height : 1; - NSUInteger textureSize = width * height * 4; - unsigned char *data = (unsigned char *)malloc(sizeof(unsigned char) * textureSize); + _height = height = height > 0 ? height : 1; + NSUInteger textureSize = width * height * 4; + unsigned char *data = (unsigned char *)malloc(sizeof(unsigned char) * textureSize); memset(data, 0, textureSize); _imageData.fastSet(data, static_cast(textureSize)); @@ -248,7 +247,7 @@ // draw text _colorSpace = CGColorSpaceCreateDeviceRGB(); - _context = CGBitmapContextCreate(data, + _context = CGBitmapContextCreate(data, width, height, 8, @@ -277,12 +276,12 @@ attributes:_tokenAttributesDict] autorelease]; NSSize textRect = NSZeroSize; - textRect.width = CGFLOAT_MAX; + textRect.width = CGFLOAT_MAX; textRect.height = CGFLOAT_MAX; NSSize dim = [stringWithAttributes boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)context:nil].size; - dim.width = ceilf(dim.width); + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; @@ -334,7 +333,7 @@ NSPoint drawPoint = [self convertDrawPoint:NSMakePoint(x, y) text:text]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [_tokenAttributesDict removeObjectForKey:NSStrokeColorAttributeName]; @@ -367,7 +366,7 @@ NSPoint drawPoint = [self convertDrawPoint:NSMakePoint(x, y) text:text]; NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; + paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; [_tokenAttributesDict removeObjectForKey:NSForegroundColorAttributeName]; @@ -422,9 +421,9 @@ if (_imageData.isNull()) return; - rect.origin.x = floor(rect.origin.x); - rect.origin.y = floor(rect.origin.y); - rect.size.width = floor(rect.size.width); + rect.origin.x = floor(rect.origin.x); + rect.origin.y = floor(rect.origin.y); + rect.size.width = floor(rect.size.width); rect.size.height = floor(rect.size.height); if (rect.origin.x < 0) rect.origin.x = 0; @@ -637,7 +636,7 @@ void CanvasRenderingContext2DDelegate::unMultiplyAlpha(unsigned char *ptr, uint3 for (int i = 0; i < size; i += 4) { alpha = (float)ptr[i + 3]; if (alpha > 0) { - ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); } diff --git a/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp index cf8bb3b6f1..a08292fbef 100644 --- a/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.cpp @@ -85,10 +85,10 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measure } void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, - float fontSize, - bool bold, - bool italic, - bool oblique, + float fontSize, + bool bold, + bool italic, + bool oblique, bool /* smallCaps */) { } diff --git a/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h index 8a5e5776c4..41c61e8255 100644 --- a/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/empty/modules/CanvasRenderingContext2DDelegate.h @@ -39,42 +39,42 @@ namespace cc { class CC_DLL CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: - using Point = ccstd::array; - using Vec2 = ccstd::array; - using Size = ccstd::array; + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; using Color4F = ccstd::array; - using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineCap) override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - void rect(float x, float y, float w, float h) override; - void updateData() override {} + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + void updateData() override {} private: int32_t _x{0}; @@ -82,20 +82,20 @@ private: int32_t _lineCap{0}; int32_t _lineJoin{0}; - cc::Data _imageData; + cc::Data _imageData; ccstd::string _curFontPath; - int _savedDC{0}; - float _lineWidth{0.0F}; - float _bufferWidth{0.0F}; - float _bufferHeight{0.0F}; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; - ccstd::string _fontName; - int _fontSize{0}; - Size _textSize; - TextAlign _textAlign{TextAlign::CENTER}; - TextBaseline _textBaseLine{TextBaseline::TOP}; - unsigned long _fillStyle{0}; - unsigned long _strokeStyle{0}; + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + unsigned long _fillStyle{0}; + unsigned long _strokeStyle{0}; }; } // namespace cc diff --git a/native/cocos/platform/empty/modules/Screen.cpp b/native/cocos/platform/empty/modules/Screen.cpp index cfcd85923b..3f63d0f7a0 100644 --- a/native/cocos/platform/empty/modules/Screen.cpp +++ b/native/cocos/platform/empty/modules/Screen.cpp @@ -52,15 +52,15 @@ Vec4 Screen::getSafeAreaEdge() const { bool Screen::isDisplayStats() { se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void Screen::setDisplayStats(bool isShow) { se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); se::ScriptEngine::getInstance()->evalString(commandBuf); } diff --git a/native/cocos/platform/empty/modules/Screen.h b/native/cocos/platform/empty/modules/Screen.h index 505fcfce0a..0180869a4b 100644 --- a/native/cocos/platform/empty/modules/Screen.h +++ b/native/cocos/platform/empty/modules/Screen.h @@ -31,11 +31,11 @@ namespace cc { class CC_DLL Screen : public IScreen { public: - int getDPI() const override; - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool value) override; + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** @brief Get current display stats. @return bool, is displaying stats or not. diff --git a/native/cocos/platform/empty/modules/System.cpp b/native/cocos/platform/empty/modules/System.cpp index 82f2f84186..10ecb4fca4 100644 --- a/native/cocos/platform/empty/modules/System.cpp +++ b/native/cocos/platform/empty/modules/System.cpp @@ -53,8 +53,8 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - static char code[3] = {0}; - char * pLanguageName = getenv("LANG"); + static char code[3] = {0}; + char *pLanguageName = getenv("LANG"); if (!pLanguageName) { return "en"; } diff --git a/native/cocos/platform/interfaces/OSInterface.cpp b/native/cocos/platform/interfaces/OSInterface.cpp index 19d23ccaa6..82006a9137 100644 --- a/native/cocos/platform/interfaces/OSInterface.cpp +++ b/native/cocos/platform/interfaces/OSInterface.cpp @@ -42,7 +42,7 @@ void OSInterface::dispatchEvent(const OSEvent &ev) { } } -void OSInterface::dispatchTouchEvent(const TouchEvent& ev) { +void OSInterface::dispatchTouchEvent(const TouchEvent &ev) { if (_evDispatchInterface) { _evDispatchInterface->dispatchTouchEvent(ev); } diff --git a/native/cocos/platform/interfaces/OSInterface.h b/native/cocos/platform/interfaces/OSInterface.h index 0553c5ebe9..bde1a288cc 100644 --- a/native/cocos/platform/interfaces/OSInterface.h +++ b/native/cocos/platform/interfaces/OSInterface.h @@ -57,7 +57,7 @@ public: @brief Dispatch touch event. @param type : Touch event */ - void dispatchTouchEvent(const TouchEvent& ev); + void dispatchTouchEvent(const TouchEvent &ev); protected: IEventDispatch *_evDispatchInterface{nullptr}; diff --git a/native/cocos/platform/interfaces/modules/IAccelerometer.h b/native/cocos/platform/interfaces/modules/IAccelerometer.h index 1806be0591..13fb543ce7 100644 --- a/native/cocos/platform/interfaces/modules/IAccelerometer.h +++ b/native/cocos/platform/interfaces/modules/IAccelerometer.h @@ -41,7 +41,7 @@ public: float accelerationIncludingGravityZ = 0.0F; float rotationRateAlpha = 0.0F; - float rotationRateBeta = 0.0F; + float rotationRateBeta = 0.0F; float rotationRateGamma = 0.0F; }; @@ -59,7 +59,6 @@ public: * Gets the motion value of current device. */ virtual const MotionValue &getDeviceMotionValue() = 0; - }; } // namespace cc diff --git a/native/cocos/platform/interfaces/modules/IBattery.h b/native/cocos/platform/interfaces/modules/IBattery.h index 6c6b685879..1c50ee21f6 100644 --- a/native/cocos/platform/interfaces/modules/IBattery.h +++ b/native/cocos/platform/interfaces/modules/IBattery.h @@ -36,7 +36,6 @@ public: * @return 0.0 ~ 1.0 */ virtual float getBatteryLevel() const = 0; - }; } // namespace cc diff --git a/native/cocos/platform/interfaces/modules/IScreen.h b/native/cocos/platform/interfaces/modules/IScreen.h index 70e4489aa5..f4aee63bf4 100644 --- a/native/cocos/platform/interfaces/modules/IScreen.h +++ b/native/cocos/platform/interfaces/modules/IScreen.h @@ -31,15 +31,15 @@ namespace cc { class CC_DLL IScreen : public OSInterface { public: - virtual int getDPI() const = 0; + virtual int getDPI() const = 0; virtual float getDevicePixelRatio() const = 0; // https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation enum class Orientation { - PORTRAIT = 0, - LANDSCAPE_LEFT = -90, + PORTRAIT = 0, + LANDSCAPE_LEFT = -90, PORTRAIT_UPSIDE_DOWN = 180, - LANDSCAPE_RIGHT = 90 + LANDSCAPE_RIGHT = 90 }; virtual Orientation getDeviceOrientation() const = 0; @@ -62,6 +62,5 @@ public: virtual void setKeepScreenOn(bool keepScreenOn) = 0; virtual Vec4 getSafeAreaEdge() const = 0; - }; } // namespace cc diff --git a/native/cocos/platform/interfaces/modules/ISystem.cpp b/native/cocos/platform/interfaces/modules/ISystem.cpp index 1321cdda70..bab73f06d1 100644 --- a/native/cocos/platform/interfaces/modules/ISystem.cpp +++ b/native/cocos/platform/interfaces/modules/ISystem.cpp @@ -29,8 +29,8 @@ namespace cc { ISystem::~ISystem() = default; ccstd::string ISystem::getCurrentLanguageToString() { - LanguageType language = getCurrentLanguage(); - ccstd::string languageStr = ""; // NOLINT + LanguageType language = getCurrentLanguage(); + ccstd::string languageStr = ""; // NOLINT switch (language) { case ISystem::LanguageType::ENGLISH: languageStr = "en"; diff --git a/native/cocos/platform/interfaces/modules/ISystem.h b/native/cocos/platform/interfaces/modules/ISystem.h index ce8b6fdbad..07f74335f6 100644 --- a/native/cocos/platform/interfaces/modules/ISystem.h +++ b/native/cocos/platform/interfaces/modules/ISystem.h @@ -71,10 +71,10 @@ public: virtual OSType getOSType() const = 0; // - virtual ccstd::string getDeviceModel() const = 0; - virtual LanguageType getCurrentLanguage() const = 0; + virtual ccstd::string getDeviceModel() const = 0; + virtual LanguageType getCurrentLanguage() const = 0; virtual ccstd::string getCurrentLanguageCode() const = 0; - virtual ccstd::string getSystemVersion() const = 0; + virtual ccstd::string getSystemVersion() const = 0; virtual ccstd::string getCurrentLanguageToString(); diff --git a/native/cocos/platform/interfaces/modules/ISystemWindow.h b/native/cocos/platform/interfaces/modules/ISystemWindow.h index d5b7db73c2..f729a51097 100644 --- a/native/cocos/platform/interfaces/modules/ISystemWindow.h +++ b/native/cocos/platform/interfaces/modules/ISystemWindow.h @@ -34,32 +34,32 @@ namespace cc { class CC_DLL ISystemWindow : public OSInterface { public: - using Size = cc::Vec2; + using Size = cc::Vec2; using WindowFlags = enum { /* !!! FIXME: change this to name = (1<; +using Vec2 = ccstd::array; using Color4F = ccstd::array; namespace cc { @@ -162,14 +162,14 @@ void CanvasRenderingContext2D::fetchData() { void CanvasRenderingContext2D::setWidth(float width) { //SE_LOGD("CanvasRenderingContext2D::set__width: %f\n", width); if (math::IsEqualF(width, _width)) return; - _width = width; + _width = width; _isBufferSizeDirty = true; } void CanvasRenderingContext2D::setHeight(float height) { //SE_LOGD("CanvasRenderingContext2D::set__height: %f\n", height); if (math::IsEqualF(height, _height)) return; - _height = height; + _height = height; _isBufferSizeDirty = true; } @@ -220,16 +220,16 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { _font = font; ccstd::string boldStr; - ccstd::string fontName = "Arial"; + ccstd::string fontName = "Arial"; ccstd::string fontSizeStr = "30"; // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); + boldStr = results[1].str(); fontSizeStr = results[2].str(); - fontName = results[5].str(); + fontName = results[5].str(); } auto fontSize = static_cast(atof(fontSizeStr.c_str())); @@ -241,16 +241,16 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { _font = font; ccstd::string boldStr; - ccstd::string fontName = "Arial"; + ccstd::string fontName = "Arial"; ccstd::string fontSizeStr = "30"; // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); + boldStr = results[1].str(); fontSizeStr = results[2].str(); - fontName = results[5].str(); + fontName = results[5].str(); } bool isItalic = font.find("italic", 0) != ccstd::string::npos; auto fontSize = static_cast(atof(fontSizeStr.c_str())); @@ -261,9 +261,9 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { if (_font != font) { _font = font; - ccstd::string fontName = "sans-serif"; - ccstd::string fontSizeStr = "30"; - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + ccstd::string fontName = "sans-serif"; + ccstd::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { fontSizeStr = results[2].str(); @@ -271,25 +271,25 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { // support get font name contain space,example `times new roman` // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - ccstd::string tmp(results[4].str()); + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + ccstd::string tmp(results[4].str()); if (std::regex_match(tmp, fontResults, fontRe)) { //fontName = results[4].str(); } } - bool isBold = font.find("bold", 0) != ccstd::string::npos; - bool isItalic = font.find("italic", 0) != ccstd::string::npos; + bool isBold = font.find("bold", 0) != ccstd::string::npos; + bool isItalic = font.find("italic", 0) != ccstd::string::npos; float fontSize = static_cast(atof(fontSizeStr.c_str())); //SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, !boldStr.empty()); _delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false); } #elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS if (_font != font) { - _font = font; - ccstd::string fontName = "sans-serif"; - ccstd::string fontSizeStr = "30"; - std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); + _font = font; + ccstd::string fontName = "sans-serif"; + ccstd::string fontSizeStr = "30"; + std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { fontSizeStr = results[2].str(); @@ -297,18 +297,18 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { // support get font name contain space,example `times new roman` // if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif std::match_results fontResults; - std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); - ccstd::string tmp(results[4].str()); + std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))"); + ccstd::string tmp(results[4].str()); if (std::regex_match(tmp, fontResults, fontRe)) { fontName = results[4].str(); } } - double fontSize = atof(fontSizeStr.c_str()); - bool isBold = font.find("bold", 0) != ccstd::string::npos; - bool isItalic = font.find("italic", 0) != ccstd::string::npos; - bool isSmallCaps = font.find("small-caps", 0) != ccstd::string::npos; - bool isOblique = font.find("oblique", 0) != ccstd::string::npos; + double fontSize = atof(fontSizeStr.c_str()); + bool isBold = font.find("bold", 0) != ccstd::string::npos; + bool isItalic = font.find("italic", 0) != ccstd::string::npos; + bool isSmallCaps = font.find("small-caps", 0) != ccstd::string::npos; + bool isOblique = font.find("oblique", 0) != ccstd::string::npos; //font-style: italic, oblique, normal //font-weight: normal, bold //font-variant: normal, small-caps @@ -319,19 +319,19 @@ void CanvasRenderingContext2D::setFont(const ccstd::string &font) { _font = font; ccstd::string boldStr; - ccstd::string fontName = "Arial"; + ccstd::string fontName = "Arial"; ccstd::string fontSizeStr = "30"; // support get font name from `60px American` or `60px "American abc-abc_abc"` - std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); + std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)"); std::match_results results; if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) { - boldStr = results[1].str(); + boldStr = results[1].str(); fontSizeStr = results[2].str(); - fontName = results[5].str(); + fontName = results[5].str(); } float fontSize = atof(fontSizeStr.c_str()); - bool isBold = !boldStr.empty(); + bool isBold = !boldStr.empty(); _delegate->updateFont(fontName, static_cast(fontSize), isBold, false, false, false); } #endif diff --git a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h index f64229752c..c58c444560 100644 --- a/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h +++ b/native/cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h @@ -46,11 +46,11 @@ public: void clearRect(float x, float y, float width, float height) override; void fillRect(float x, float y, float width, float height) override; - void fillText(const ccstd::string &text, float x, float y, float maxWidth) override; - void strokeText(const ccstd::string &text, float x, float y, float maxWidth) override; - Size measureText(const ccstd::string &text) override; + void fillText(const ccstd::string &text, float x, float y, float maxWidth) override; + void strokeText(const ccstd::string &text, float x, float y, float maxWidth) override; + Size measureText(const ccstd::string &text) override; ICanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1) override; - void save() override; + void save() override; // Paths void beginPath() override; void closePath() override; @@ -93,17 +93,17 @@ private: void recreateBufferIfNeeded() override; public: - float _width = 0.0F; + float _width = 0.0F; float _height = 0.0F; // Line styles - float _lineWidth = 1.0F; - ccstd::string _lineJoin = "miter"; - ccstd::string _lineCap = "butt"; + float _lineWidth = 1.0F; + ccstd::string _lineJoin = "miter"; + ccstd::string _lineCap = "butt"; // Text styles - ccstd::string _font = "10px sans-serif"; - ccstd::string _textAlign = "start"; + ccstd::string _font = "10px sans-serif"; + ccstd::string _textAlign = "start"; ccstd::string _textBaseline = "alphabetic"; // Fill and stroke styles diff --git a/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h index 797a6547ad..1a466ccff4 100644 --- a/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h +++ b/native/cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h @@ -31,13 +31,12 @@ #include "math/Geometry.h" #include "platform/interfaces/OSInterface.h" - namespace cc { class CC_DLL ICanvasGradient { public: - ICanvasGradient() = default; - virtual ~ICanvasGradient() = default; // NOLINT(performance-trivially-destructible) + ICanvasGradient() = default; + virtual ~ICanvasGradient() = default; // NOLINT(performance-trivially-destructible) virtual void addColorStop(float offset, const ccstd::string &color) = 0; }; @@ -58,70 +57,70 @@ public: class Delegate { public: - using Size = ccstd::array; - virtual ~Delegate() = default; - virtual void recreateBuffer(float w, float h) = 0; - virtual void beginPath() = 0; - virtual void closePath() = 0; - virtual void moveTo(float x, float y) = 0; - virtual void lineTo(float x, float y) = 0; - virtual void stroke() = 0; - virtual void saveContext() = 0; - virtual void restoreContext() = 0; - virtual void clearRect(float /*x*/, float /*y*/, float w, float h) = 0; - virtual void fill() = 0; - virtual void rect(float x, float y, float w, float h) = 0; - virtual void setLineCap(const ccstd::string &lineCap) = 0; - virtual void setLineJoin(const ccstd::string &lineCap) = 0; - virtual void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) = 0; - virtual void fillRect(float x, float y, float w, float h) = 0; - virtual void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) = 0; - virtual void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) = 0; - virtual Size measureText(const ccstd::string &text) = 0; - virtual void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) = 0; - virtual void setTextAlign(TextAlign align) = 0; - virtual void setTextBaseline(TextBaseline baseline) = 0; - virtual void setFillStyle(float r, float g, float b, float a) = 0; - virtual void setStrokeStyle(float r, float g, float b, float a) = 0; - virtual void setLineWidth(float lineWidth) = 0; - virtual const cc::Data &getDataRef() const = 0; - virtual void updateData() = 0; + using Size = ccstd::array; + virtual ~Delegate() = default; + virtual void recreateBuffer(float w, float h) = 0; + virtual void beginPath() = 0; + virtual void closePath() = 0; + virtual void moveTo(float x, float y) = 0; + virtual void lineTo(float x, float y) = 0; + virtual void stroke() = 0; + virtual void saveContext() = 0; + virtual void restoreContext() = 0; + virtual void clearRect(float /*x*/, float /*y*/, float w, float h) = 0; + virtual void fill() = 0; + virtual void rect(float x, float y, float w, float h) = 0; + virtual void setLineCap(const ccstd::string &lineCap) = 0; + virtual void setLineJoin(const ccstd::string &lineCap) = 0; + virtual void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) = 0; + virtual void fillRect(float x, float y, float w, float h) = 0; + virtual void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) = 0; + virtual void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) = 0; + virtual Size measureText(const ccstd::string &text) = 0; + virtual void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) = 0; + virtual void setTextAlign(TextAlign align) = 0; + virtual void setTextBaseline(TextBaseline baseline) = 0; + virtual void setFillStyle(float r, float g, float b, float a) = 0; + virtual void setStrokeStyle(float r, float g, float b, float a) = 0; + virtual void setLineWidth(float lineWidth) = 0; + virtual const cc::Data &getDataRef() const = 0; + virtual void updateData() = 0; }; //static OSInterface::Ptr getInterface(); // Rect - virtual void rect(float x, float y, float width, float height) = 0; + virtual void rect(float x, float y, float width, float height) = 0; virtual void clearRect(float x, float y, float width, float height) = 0; - virtual void fillRect(float x, float y, float width, float height) = 0; + virtual void fillRect(float x, float y, float width, float height) = 0; - virtual void fillText(const ccstd::string &text, float x, float y, float maxWidth) = 0; - virtual void strokeText(const ccstd::string &text, float x, float y, float maxWidth) = 0; - virtual Size measureText(const ccstd::string &text) = 0; - virtual ICanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1) = 0; - virtual void save() = 0; + virtual void fillText(const ccstd::string &text, float x, float y, float maxWidth) = 0; + virtual void strokeText(const ccstd::string &text, float x, float y, float maxWidth) = 0; + virtual Size measureText(const ccstd::string &text) = 0; + virtual ICanvasGradient *createLinearGradient(float x0, float y0, float x1, float y1) = 0; + virtual void save() = 0; // Paths - virtual void beginPath() = 0; - virtual void closePath() = 0; + virtual void beginPath() = 0; + virtual void closePath() = 0; virtual void moveTo(float x, float y) = 0; virtual void lineTo(float x, float y) = 0; - virtual void fill() = 0; - virtual void stroke() = 0; - virtual void restore() = 0; + virtual void fill() = 0; + virtual void stroke() = 0; + virtual void restore() = 0; // callback - using CanvasBufferUpdatedCallback = std::function; + using CanvasBufferUpdatedCallback = std::function; virtual void setCanvasBufferUpdatedCallback(const CanvasBufferUpdatedCallback &cb) = 0; // functions for properties - virtual void setWidth(float width) = 0; - virtual void setHeight(float height) = 0; - virtual void setLineWidth(float lineWidth) = 0; - virtual void setLineJoin(const ccstd::string &lineJoin) = 0; - virtual void setLineCap(const ccstd::string &lineCap) = 0; - virtual void setFont(const ccstd::string &font) = 0; - virtual void setTextAlign(const ccstd::string &textAlign) = 0; - virtual void setTextBaseline(const ccstd::string &textBaseline) = 0; - virtual void setFillStyle(const ccstd::string &fillStyle) = 0; - virtual void setStrokeStyle(const ccstd::string &strokeStyle) = 0; + virtual void setWidth(float width) = 0; + virtual void setHeight(float height) = 0; + virtual void setLineWidth(float lineWidth) = 0; + virtual void setLineJoin(const ccstd::string &lineJoin) = 0; + virtual void setLineCap(const ccstd::string &lineCap) = 0; + virtual void setFont(const ccstd::string &font) = 0; + virtual void setTextAlign(const ccstd::string &textAlign) = 0; + virtual void setTextBaseline(const ccstd::string &textBaseline) = 0; + virtual void setFillStyle(const ccstd::string &fillStyle) = 0; + virtual void setStrokeStyle(const ccstd::string &strokeStyle) = 0; virtual void setGlobalCompositeOperation(const ccstd::string &globalCompositeOperation) = 0; // fill image data into Context2D @@ -129,10 +128,10 @@ public: // transform virtual void translate(float x, float y) = 0; - virtual void scale(float x, float y) = 0; - virtual void rotate(float angle) = 0; + virtual void scale(float x, float y) = 0; + virtual void rotate(float angle) = 0; - virtual void transform(float a, float b, float c, float d, float e, float f) = 0; + virtual void transform(float a, float b, float c, float d, float e, float f) = 0; virtual void setTransform(float a, float b, float c, float d, float e, float f) = 0; virtual void fetchData() = 0; diff --git a/native/cocos/platform/ios/AppDelegateBridge.mm b/native/cocos/platform/ios/AppDelegateBridge.mm index 5b691b56b8..dd38ffa408 100644 --- a/native/cocos/platform/ios/AppDelegateBridge.mm +++ b/native/cocos/platform/ios/AppDelegateBridge.mm @@ -59,10 +59,9 @@ cc::IOSPlatform *_platform = nullptr; _platform->dispatchEvent(ev); } - - (float)getPixelRatio { - cc::BasePlatform* platform = cc::BasePlatform::getPlatform(); - cc::IScreen* screenIntf = platform->getInterface(); + cc::BasePlatform *platform = cc::BasePlatform::getPlatform(); + cc::IScreen *screenIntf = platform->getInterface(); return (float)screenIntf->getDevicePixelRatio(); } @@ -88,9 +87,9 @@ cc::IOSPlatform *_platform = nullptr; break; } cc::DeviceEvent ev; - cc::BasePlatform* platform = cc::BasePlatform::getPlatform(); - cc::IScreen* screenIntf = platform->getInterface(); - ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; + cc::BasePlatform *platform = cc::BasePlatform::getPlatform(); + cc::IScreen *screenIntf = platform->getInterface(); + ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; ev.args[0].intVal = static_cast(screenIntf->getDeviceOrientation()); _platform->dispatchEvent(ev); @@ -115,4 +114,3 @@ cc::IOSPlatform *_platform = nullptr; } @end - diff --git a/native/cocos/platform/ios/IOSPlatform.h b/native/cocos/platform/ios/IOSPlatform.h index 0cad5cf330..6ba4b308b0 100644 --- a/native/cocos/platform/ios/IOSPlatform.h +++ b/native/cocos/platform/ios/IOSPlatform.h @@ -50,7 +50,7 @@ public: */ int32_t loop() override; - void setFps(int32_t fps) override; + void setFps(int32_t fps) override; int32_t getFps() const override; void onPause() override; diff --git a/native/cocos/platform/ios/IOSPlatform.mm b/native/cocos/platform/ios/IOSPlatform.mm index 75df1419b8..fb96ad980a 100644 --- a/native/cocos/platform/ios/IOSPlatform.mm +++ b/native/cocos/platform/ios/IOSPlatform.mm @@ -37,12 +37,12 @@ #include "modules/SystemWindow.h" #include "modules/Vibrator.h" -extern int cocos_main(int argc, const char** argv); +extern int cocos_main(int argc, const char **argv); @interface MyTimer : NSObject { cc::IOSPlatform *_platform; - CADisplayLink * _displayLink; - int _fps; + CADisplayLink *_displayLink; + int _fps; } - (instancetype)initWithApp:(cc::IOSPlatform *)platform fps:(int)fps; - (void)start; @@ -55,9 +55,9 @@ extern int cocos_main(int argc, const char** argv); - (instancetype)initWithApp:(cc::IOSPlatform *)platform fps:(int)fps { if (self = [super init]) { - _fps = fps; - _platform = platform; - _displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderScene:)]; + _fps = fps; + _platform = platform; + _displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderScene:)]; _displayLink.preferredFramesPerSecond = _fps; } return self; @@ -115,7 +115,7 @@ int32_t IOSPlatform::loop() { return 0; } -int32_t IOSPlatform::run(int argc, const char** argv) { +int32_t IOSPlatform::run(int argc, const char **argv) { return 0; } @@ -129,7 +129,7 @@ int32_t IOSPlatform::getFps() const { void IOSPlatform::onPause() { [_timer pause]; - + cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::HIDDEN; dispatchEvent(ev); @@ -137,7 +137,7 @@ void IOSPlatform::onPause() { void IOSPlatform::onResume() { [_timer resume]; - + cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::SHOW; dispatchEvent(ev); diff --git a/native/cocos/platform/ios/View.mm b/native/cocos/platform/ios/View.mm index e247db21f1..b62e22ccf2 100644 --- a/native/cocos/platform/ios/View.mm +++ b/native/cocos/platform/ios/View.mm @@ -33,7 +33,7 @@ namespace { } // namespace @implementation View { - cc::IOSPlatform* _platform; + cc::IOSPlatform *_platform; } @synthesize preventTouch; @@ -48,7 +48,7 @@ namespace { } #endif -- (void)dispatchTouchEvent:(cc::TouchEvent::Type)type withEvent:(NSSet*) touches { +- (void)dispatchTouchEvent:(cc::TouchEvent::Type)type withEvent:(NSSet *)touches { cc::TouchEvent touchEvent; touchEvent.type = type; for (UITouch *touch in touches) { @@ -61,20 +61,20 @@ namespace { } - (id)initWithFrame:(CGRect)frame { - _platform = reinterpret_cast(cc::BasePlatform::getPlatform()); + _platform = reinterpret_cast(cc::BasePlatform::getPlatform()); #ifdef CC_USE_METAL if (self = [super initWithFrame:frame]) { self.preventTouch = FALSE; - float pixelRatio = [[UIScreen mainScreen] nativeScale]; - CGSize size = CGSizeMake(static_cast(frame.size.width * pixelRatio), - static_cast(frame.size.height * pixelRatio)); + float pixelRatio = [[UIScreen mainScreen] nativeScale]; + CGSize size = CGSizeMake(static_cast(frame.size.width * pixelRatio), + static_cast(frame.size.height * pixelRatio)); self.contentScaleFactor = pixelRatio; // Config metal layer CAMetalLayer *layer = (CAMetalLayer *)self.layer; - layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; layer.device = self.device = MTLCreateSystemDefaultDevice(); - layer.drawableSize = size; + layer.drawableSize = size; } #else if (self = [super initWithFrame:frame]) { diff --git a/native/cocos/platform/ios/modules/Accelerometer.mm b/native/cocos/platform/ios/modules/Accelerometer.mm index 18d4e68613..92ba0715c0 100644 --- a/native/cocos/platform/ios/modules/Accelerometer.mm +++ b/native/cocos/platform/ios/modules/Accelerometer.mm @@ -31,14 +31,14 @@ #include #include "platform/interfaces/modules/IAccelerometer.h" -static const float g = 9.80665; +static const float g = 9.80665; static const float radToDeg = (180 / M_PI); @interface CCMotionDispatcher : NSObject { - CMMotionManager * _motionManager; + CMMotionManager *_motionManager; cc::IAccelerometer::MotionValue _motionValue; - float _interval; // unit: seconds - bool _enabled; + float _interval; // unit: seconds + bool _enabled; } + (id)sharedMotionDispatcher; @@ -62,8 +62,8 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; - (id)init { if ((self = [super init])) { - _enabled = false; - _interval = 1.0f / 60.0f; + _enabled = false; + _interval = 1.0f / 60.0f; _motionManager = [[CMMotionManager alloc] init]; } return self; @@ -117,7 +117,7 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; - (const cc::IAccelerometer::MotionValue &)getMotionValue { if (_motionManager.isDeviceMotionAvailable) { - CMDeviceMotion *motion = _motionManager.deviceMotion; + CMDeviceMotion *motion = _motionManager.deviceMotion; _motionValue.accelerationX = motion.userAcceleration.x * g; _motionValue.accelerationY = motion.userAcceleration.y * g; _motionValue.accelerationZ = motion.userAcceleration.z * g; @@ -127,10 +127,10 @@ static CCMotionDispatcher *__motionDispatcher = nullptr; _motionValue.accelerationIncludingGravityZ = (motion.userAcceleration.z + motion.gravity.z) * g; _motionValue.rotationRateAlpha = motion.rotationRate.x * radToDeg; - _motionValue.rotationRateBeta = motion.rotationRate.y * radToDeg; + _motionValue.rotationRateBeta = motion.rotationRate.y * radToDeg; _motionValue.rotationRateGamma = motion.rotationRate.z * radToDeg; } else { - CMAccelerometerData *acc = _motionManager.accelerometerData; + CMAccelerometerData *acc = _motionManager.accelerometerData; _motionValue.accelerationIncludingGravityX = acc.acceleration.x * g; _motionValue.accelerationIncludingGravityY = acc.acceleration.y * g; _motionValue.accelerationIncludingGravityZ = acc.acceleration.z * g; diff --git a/native/cocos/platform/ios/modules/Network.mm b/native/cocos/platform/ios/modules/Network.mm index 2562f51ea5..1911fd23c6 100644 --- a/native/cocos/platform/ios/modules/Network.mm +++ b/native/cocos/platform/ios/modules/Network.mm @@ -37,7 +37,7 @@ INetwork::NetworkType Network::getNetworkType() const { __reachability->addRef(); } - NetworkType ret = NetworkType::NONE; + NetworkType ret = NetworkType::NONE; Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); switch (status) { case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: diff --git a/native/cocos/platform/ios/modules/Screen.h b/native/cocos/platform/ios/modules/Screen.h index 8972457542..cf98b84441 100644 --- a/native/cocos/platform/ios/modules/Screen.h +++ b/native/cocos/platform/ios/modules/Screen.h @@ -31,11 +31,11 @@ namespace cc { class Screen : public IScreen { public: - int getDPI() const override; - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool value) override; + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** * @brief Get current display stats. * @return bool, is displaying stats or not. diff --git a/native/cocos/platform/ios/modules/Screen.mm b/native/cocos/platform/ios/modules/Screen.mm index afdd015554..dddd32f87b 100644 --- a/native/cocos/platform/ios/modules/Screen.mm +++ b/native/cocos/platform/ios/modules/Screen.mm @@ -99,18 +99,17 @@ Vec4 Screen::getSafeAreaEdge() const { bool Screen::isDisplayStats() { se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void Screen::setDisplayStats(bool isShow) { se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); se::ScriptEngine::getInstance()->evalString(commandBuf); } - } // namespace cc diff --git a/native/cocos/platform/ios/modules/System.mm b/native/cocos/platform/ios/modules/System.mm index c94374a8a5..7225a6db0a 100644 --- a/native/cocos/platform/ios/modules/System.mm +++ b/native/cocos/platform/ios/modules/System.mm @@ -26,13 +26,11 @@ #include "platform/ios/modules/System.h" #import - #include #include #include #include - namespace cc { using OSType = System::OSType; @@ -48,13 +46,13 @@ ccstd::string System::getDeviceModel() const { System::LanguageType System::getCurrentLanguage() const { // get the current language and country config - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; - NSString * currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString *languageCode = [temp objectForKey:NSLocaleLanguageCode]; if ([languageCode isEqualToString:@"zh"]) return LanguageType::CHINESE; if ([languageCode isEqualToString:@"en"]) return LanguageType::ENGLISH; @@ -79,9 +77,9 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; - NSString * currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; return [currentLanguage UTF8String]; } @@ -91,9 +89,9 @@ ccstd::string System::getSystemVersion() const { } bool System::openURL(const ccstd::string &url) { - NSString * msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; - NSURL * nsUrl = [NSURL URLWithString:msg]; - __block BOOL flag = false; + NSString *msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL *nsUrl = [NSURL URLWithString:msg]; + __block BOOL flag = false; [[UIApplication sharedApplication] openURL:nsUrl options:@{} completionHandler:^(BOOL success) { diff --git a/native/cocos/platform/ios/modules/SystemWindow.mm b/native/cocos/platform/ios/modules/SystemWindow.mm index 6f86c1c2e8..aa8c8fd121 100644 --- a/native/cocos/platform/ios/modules/SystemWindow.mm +++ b/native/cocos/platform/ios/modules/SystemWindow.mm @@ -26,7 +26,6 @@ #include "platform/ios/modules/SystemWindow.h" #import - namespace { } @@ -35,13 +34,12 @@ namespace cc { SystemWindow::~SystemWindow() = default; - void SystemWindow::setCursorEnabled(bool value) { } void SystemWindow::copyTextToClipboard(const std::string& text) { UIPasteboard* pasteboard = [UIPasteboard generalPasteboard]; - pasteboard.string = [NSString stringWithCString:text.c_str() encoding:NSUTF8StringEncoding]; + pasteboard.string = [NSString stringWithCString:text.c_str() encoding:NSUTF8StringEncoding]; } uintptr_t SystemWindow::getWindowHandler() const { @@ -53,5 +51,4 @@ SystemWindow::Size SystemWindow::getViewSize() const { return Size{static_cast(bounds.size.width), static_cast(bounds.size.height)}; } - -} +} // namespace cc diff --git a/native/cocos/platform/ios/modules/Vibrator.mm b/native/cocos/platform/ios/modules/Vibrator.mm index 76ad44eb68..8152623bab 100644 --- a/native/cocos/platform/ios/modules/Vibrator.mm +++ b/native/cocos/platform/ios/modules/Vibrator.mm @@ -33,4 +33,4 @@ void Vibrator::vibrate(float duration) { CC_UNUSED_PARAM(duration); } -} \ No newline at end of file +} // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp index f8b2199e6c..932aa110ac 100644 --- a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp +++ b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp @@ -29,8 +29,8 @@ #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/glue/JniNativeGlue.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include "platform/android/AndroidPlatform.h" -#include "platform/BasePlatform.h" + #include "platform/android/AndroidPlatform.h" + #include "platform/BasePlatform.h" #endif extern "C" { @@ -49,7 +49,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosOrientationHelper_nativeOnOrienta } cc::DeviceEvent ev; - ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; + ev.type = cc::DeviceEvent::Type::DEVICE_ORIENTATION; ev.args[0].intVal = orientation; #if CC_PLATFORM == CC_PLATFORM_ANDROID auto *platform = cc::BasePlatform::getPlatform(); diff --git a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp index 3eb5fe5a4b..d00f2c4ef1 100644 --- a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp @@ -52,12 +52,12 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEn //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNIEnv *env, jobject obj, - jintArray ids, + jintArray ids, jfloatArray xs, jfloatArray ys) { touchEvent.type = cc::TouchEvent::Type::MOVED; - int size = env->GetArrayLength(ids); - jint id[size]; + int size = env->GetArrayLength(ids); + jint id[size]; jfloat x[size]; jfloat y[size]; @@ -74,12 +74,12 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNI //NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(JNIEnv *env, jobject obj, - jintArray ids, + jintArray ids, jfloatArray xs, jfloatArray ys) { touchEvent.type = cc::TouchEvent::Type::CANCELLED; - int size = env->GetArrayLength(ids); - jint id[size]; + int size = env->GetArrayLength(ids); + jint id[size]; jfloat x[size]; jfloat y[size]; diff --git a/native/cocos/platform/java/jni/JniHelper.cpp b/native/cocos/platform/java/jni/JniHelper.cpp index 5299f4c2c7..a858d4c385 100644 --- a/native/cocos/platform/java/jni/JniHelper.cpp +++ b/native/cocos/platform/java/jni/JniHelper.cpp @@ -48,7 +48,7 @@ #endif namespace { -pthread_key_t g_key; // NOLINT(readability-identifier-naming) +pthread_key_t g_key; // NOLINT(readability-identifier-naming) class JClassWrapper final { public: explicit JClassWrapper(jclass kls) { @@ -117,11 +117,11 @@ void cbDetachCurrentThread(void * /*a*/) { } namespace cc { -jmethodID JniHelper::loadclassMethodMethodId = nullptr; -jobject JniHelper::classloader = nullptr; -std::function JniHelper::classloaderCallback = nullptr; -jobject JniHelper::sActivity = nullptr; -JavaVM * JniHelper::sJavaVM = nullptr; +jmethodID JniHelper::loadclassMethodMethodId = nullptr; +jobject JniHelper::classloader = nullptr; +std::function JniHelper::classloaderCallback = nullptr; +jobject JniHelper::sActivity = nullptr; +JavaVM *JniHelper::sJavaVM = nullptr; JavaVM *JniHelper::getJavaVM() { pthread_t thisthread = pthread_self(); @@ -212,9 +212,9 @@ bool JniHelper::setClassLoaderFrom(jobject activityinstance) { return false; } - JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(klassLoader); + JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(klassLoader); JniHelper::loadclassMethodMethodId = loadClass.methodID; - JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); + JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); if (JniHelper::classloaderCallback != nullptr) { JniHelper::classloaderCallback(); } @@ -258,9 +258,9 @@ bool JniHelper::setClassLoaderFrom(jobject activityinstance) { #endif bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, - const char * className, - const char * methodName, - const char * paramCode) { + const char *className, + const char *methodName, + const char *paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { @@ -287,17 +287,17 @@ bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, return false; } - methodinfo.classID = classID; - methodinfo.env = env; + methodinfo.classID = classID; + methodinfo.env = env; methodinfo.methodID = methodID; return true; } //NOLINTNEXTLINE bool JniHelper::getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, - const char * className, - const char * methodName, - const char * paramCode) { + const char *className, + const char *methodName, + const char *paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { @@ -323,17 +323,17 @@ bool JniHelper::getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, return false; } - methodinfo.classID = classID; - methodinfo.env = env; + methodinfo.classID = classID; + methodinfo.env = env; methodinfo.methodID = methodID; return true; } bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, - const char * className, - const char * methodName, - const char * paramCode) { + const char *className, + const char *methodName, + const char *paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { @@ -359,8 +359,8 @@ bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, return false; } - methodinfo.classID = classID; - methodinfo.env = env; + methodinfo.classID = classID; + methodinfo.env = env; methodinfo.methodID = methodID; return true; @@ -396,8 +396,8 @@ jstring JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodI } jobject JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const std::vector &x) { - jclass stringClass = _getClassID("java/lang/String"); - jobjectArray ret = t->env->NewObjectArray(x.size(), stringClass, nullptr); + jclass stringClass = _getClassID("java/lang/String"); + jobjectArray ret = t->env->NewObjectArray(x.size(), stringClass, nullptr); for (auto i = 0; i < x.size(); i++) { jstring jstr = cc::StringUtils::newStringUTFJNI(t->env, x[i]); t->env->SetObjectArrayElement(ret, i, jstr); diff --git a/native/cocos/platform/java/jni/JniHelper.h b/native/cocos/platform/java/jni/JniHelper.h index 6146c01604..ede044741d 100644 --- a/native/cocos/platform/java/jni/JniHelper.h +++ b/native/cocos/platform/java/jni/JniHelper.h @@ -63,8 +63,8 @@ struct android_app; namespace cc { using JniMethodInfo = struct JniMethodInfo_ { //NOLINT(readability-identifier-naming) - JNIEnv * env; - jclass classID; + JNIEnv *env; + jclass classID; jmethodID methodID; }; @@ -75,32 +75,32 @@ public: static JavaVM *getJavaVM(); static JNIEnv *getEnv(); static jobject getActivity(); - static void init(JNIEnv *env, jobject activity); + static void init(JNIEnv *env, jobject activity); //NOLINTNEXTLINE static bool getStaticMethodInfo(JniMethodInfo &methodInfo, - const char * className, - const char * methodName, - const char * paramCode); + const char *className, + const char *methodName, + const char *paramCode); //NOLINTNEXTLINE static bool getMethodInfo(JniMethodInfo &methodInfo, - const char * className, - const char * methodName, - const char * paramCode); + const char *className, + const char *methodName, + const char *paramCode); static ccstd::string jstring2string(jstring str); - static jmethodID loadclassMethodMethodId; - static jobject classloader; + static jmethodID loadclassMethodMethodId; + static jobject classloader; static std::function classloaderCallback; template static jobject newObject(const ccstd::string &className, Ts... xs) { - jobject ret = nullptr; + jobject ret = nullptr; static const char *methodName = ""; - cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; + cc::JniMethodInfo t; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName, signature.c_str())) { LocalRefMapType localRefs; ret = t.env->NewObject(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -115,12 +115,12 @@ public: } template - static void callObjectVoidMethod(jobject object, + static void callObjectVoidMethod(jobject object, const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; t.env->CallVoidMethod(object, t.methodID, convert(&localRefs, &t, xs)...); @@ -135,13 +135,13 @@ public: } template - static float callObjectFloatMethod(jobject object, + static float callObjectFloatMethod(jobject object, const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - float ret = 0.0F; + float ret = 0.0F; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")F"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")F"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallFloatMethod(object, t.methodID, convert(&localRefs, &t, xs)...); @@ -157,13 +157,13 @@ public: } template - static jlong callObjectLongMethod(jobject object, + static jlong callObjectLongMethod(jobject object, const std::string &className, const std::string &methodName, Ts... xs) { - jlong ret = 0; + jlong ret = 0; cc::JniMethodInfo t; - std::string signature = "(" + std::string(getJNISignature(xs...)) + ")J"; + std::string signature = "(" + std::string(getJNISignature(xs...)) + ")J"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallLongMethod(object, t.methodID, convert(&localRefs, &t, xs)...); @@ -179,13 +179,13 @@ public: } template - static jbyteArray callObjectByteArrayMethod(jobject object, + static jbyteArray callObjectByteArrayMethod(jobject object, const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - jbyteArray ret = nullptr; + jbyteArray ret = nullptr; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[B"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[B"; if (cc::JniHelper::getMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = static_cast(t.env->CallObjectMethod(object, t.methodID, convert(&localRefs, &t, xs)...)); @@ -205,7 +205,7 @@ public: const ccstd::string &methodName, Ts... xs) { cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")V"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; t.env->CallStaticVoidMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -223,9 +223,9 @@ public: static bool callStaticBooleanMethod(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - jboolean jret = JNI_FALSE; + jboolean jret = JNI_FALSE; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")Z"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")Z"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; jret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -244,9 +244,9 @@ public: static int callStaticIntMethod(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - jint ret = 0; + jint ret = 0; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")I"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")I"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticIntMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -265,9 +265,9 @@ public: static float callStaticFloatMethod(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - jfloat ret = 0.0; + jfloat ret = 0.0; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")F"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticFloatMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -286,12 +286,12 @@ public: static float *callStaticFloatArrayMethod(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - static float ret[32]; + static float ret[32]; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[F"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto * array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto *array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len <= 32) { @@ -317,19 +317,19 @@ public: static Vec3 callStaticVec3Method(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - Vec3 ret; + Vec3 ret; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[F"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")[F"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto * array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto *array = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); jsize len = t.env->GetArrayLength(array); if (len == 3) { jfloat *elems = t.env->GetFloatArrayElements(array, nullptr); - ret.x = elems[0]; - ret.y = elems[1]; - ret.z = elems[2]; + ret.x = elems[0]; + ret.y = elems[1]; + ret.z = elems[2]; t.env->ReleaseFloatArrayElements(array, elems, 0); } CLEAR_EXCEPTON(t.env); @@ -348,9 +348,9 @@ public: static double callStaticDoubleMethod(const ccstd::string &className, const ccstd::string &methodName, Ts... xs) { - jdouble ret = 0.0; + jdouble ret = 0.0; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")D"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")D"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; ret = t.env->CallStaticDoubleMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...); @@ -372,10 +372,10 @@ public: ccstd::string ret; cc::JniMethodInfo t; - ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; + ccstd::string signature = "(" + ccstd::string(getJNISignature(xs...)) + ")Ljava/lang/String;"; if (cc::JniHelper::getStaticMethodInfo(t, className.c_str(), methodName.c_str(), signature.c_str())) { LocalRefMapType localRefs; - auto * jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); + auto *jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, convert(&localRefs, &t, xs)...)); CLEAR_EXCEPTON(t.env); ret = cc::JniHelper::jstring2string(jret); ccDeleteLocalRef(t.env, jret); @@ -394,9 +394,9 @@ private: static JNIEnv *cacheEnv(); //NOLINTNEXTLINE static bool getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, - const char * className, - const char * methodName, - const char * paramCode); + const char *className, + const char *methodName, + const char *paramCode); static jstring convert(LocalRefMapType *localRefs, cc::JniMethodInfo *t, const char *x); diff --git a/native/cocos/platform/java/jni/JniImp.cpp b/native/cocos/platform/java/jni/JniImp.cpp index 607e57a752..d00fda0165 100644 --- a/native/cocos/platform/java/jni/JniImp.cpp +++ b/native/cocos/platform/java/jni/JniImp.cpp @@ -60,19 +60,19 @@ ccstd::string getObbFilePathJNI() { int getObbAssetFileDescriptorJNI(const ccstd::string &path, int64_t *startOffset, int64_t *size) { JniMethodInfo methodInfo; - int fd = 0; + int fd = 0; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_HELPER, "getObbAssetFileDescriptor", "(Ljava/lang/String;)[J")) { - jstring stringArg = methodInfo.env->NewStringUTF(path.c_str()); - auto * newArray = static_cast(methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg)); - jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); + jstring stringArg = methodInfo.env->NewStringUTF(path.c_str()); + auto *newArray = static_cast(methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, stringArg)); + jsize theArrayLen = methodInfo.env->GetArrayLength(newArray); if (3 == theArrayLen) { - jboolean copy = JNI_FALSE; - jlong * array = methodInfo.env->GetLongArrayElements(newArray, ©); - fd = static_cast(array[0]); - *startOffset = array[1]; - *size = array[2]; + jboolean copy = JNI_FALSE; + jlong *array = methodInfo.env->GetLongArrayElements(newArray, ©); + fd = static_cast(array[0]); + *startOffset = array[1]; + *size = array[2]; methodInfo.env->ReleaseLongArrayElements(newArray, array, 0); } diff --git a/native/cocos/platform/java/jni/JniImp.h b/native/cocos/platform/java/jni/JniImp.h index 9a7b71b904..c18bd741ac 100644 --- a/native/cocos/platform/java/jni/JniImp.h +++ b/native/cocos/platform/java/jni/JniImp.h @@ -28,21 +28,21 @@ #include "base/std/container/string.h" extern ccstd::string getObbFilePathJNI(); -extern int getObbAssetFileDescriptorJNI(const ccstd::string &path, int64_t *startOffset, int64_t *size); +extern int getObbAssetFileDescriptorJNI(const ccstd::string &path, int64_t *startOffset, int64_t *size); extern ccstd::string getCurrentLanguageJNI(); extern ccstd::string getCurrentLanguageCodeJNI(); extern ccstd::string getSystemVersionJNI(); -extern bool openURLJNI(const ccstd::string &url); -extern void copyTextToClipboardJNI(const ccstd::string &text); +extern bool openURLJNI(const ccstd::string &url); +extern void copyTextToClipboardJNI(const ccstd::string &text); extern ccstd::string getDeviceModelJNI(); -extern int getDPIJNI(); -extern void setVibrateJNI(float duration); -extern int getNetworkTypeJNI(); -extern float * getSafeAreaEdgeJNI(); -extern int getDeviceRotationJNI(); -extern float getBatteryLevelJNI(); -extern void flushTasksOnGameThreadJNI(); -extern void flushTasksOnGameThreadAtForegroundJNI(); -extern void setAccelerometerEnabledJNI(bool isEnabled); -extern void setAccelerometerIntervalJNI(float interval); -extern float * getDeviceMotionValueJNI(); \ No newline at end of file +extern int getDPIJNI(); +extern void setVibrateJNI(float duration); +extern int getNetworkTypeJNI(); +extern float *getSafeAreaEdgeJNI(); +extern int getDeviceRotationJNI(); +extern float getBatteryLevelJNI(); +extern void flushTasksOnGameThreadJNI(); +extern void flushTasksOnGameThreadAtForegroundJNI(); +extern void setAccelerometerEnabledJNI(bool isEnabled); +extern void setAccelerometerIntervalJNI(float interval); +extern float *getDeviceMotionValueJNI(); \ No newline at end of file diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp index b2d47cd54b..f92dbc6b86 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp @@ -135,7 +135,7 @@ void JniNativeGlue::writeCommandAsync(JniCommand cmd) { void JniNativeGlue::writeCommandSync(JniCommand cmd) { std::promise fu; - CommandMsg msg{.cmd = cmd, .callback = [&fu]() { + CommandMsg msg{.cmd = cmd, .callback = [&fu]() { fu.set_value(); }}; _messagePipe->writeCommand(&msg, sizeof(msg)); @@ -190,7 +190,7 @@ void JniNativeGlue::onLowMemory() { void JniNativeGlue::execCommand() { static CommandMsg msg; - static bool runInLowRate{false}; + static bool runInLowRate{false}; runInLowRate = !_animating || JniCommand::JNI_CMD_PAUSE == _appState; if (readCommandWithTimeout(&msg, runInLowRate ? 50 : 0) > 0) { @@ -208,7 +208,7 @@ void JniNativeGlue::preExecCmd(JniCommand cmd) { case JniCommand::JNI_CMD_INIT_WINDOW: { LOGV("JNI_CMD_INIT_WINDOW"); _animating = true; - _window = _pendingWindow; + _window = _pendingWindow; } break; case JniCommand::JNI_CMD_TERM_WINDOW: LOGV("JNI_CMD_TERM_WINDOW"); @@ -237,13 +237,13 @@ void JniNativeGlue::engineHandleCmd(JniCommand cmd) { return; } cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; + event.name = EVENT_RECREATE_WINDOW; event.args->ptrVal = reinterpret_cast(getWindowHandler()); dispatchEvent(event); } break; case JniCommand::JNI_CMD_TERM_WINDOW: { cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; + event.name = EVENT_DESTROY_WINDOW; event.args->ptrVal = reinterpret_cast(getWindowHandler()); dispatchEvent(event); } break; @@ -296,7 +296,7 @@ int32_t JniNativeGlue::getWidth() const { #if (CC_PLATFORM == CC_PLATFORM_ANDROID) width = ANativeWindow_getWidth(_window); #elif (CC_PLATFORM == CC_PLATFORM_OHOS) - width = NativeLayerHandle(_window, NativeLayerOps::GET_WIDTH); + width = NativeLayerHandle(_window, NativeLayerOps::GET_WIDTH); #endif } return width; diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.h b/native/cocos/platform/java/jni/glue/JniNativeGlue.h index fb4a879a0b..3b3f9be93a 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.h +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.h @@ -36,18 +36,18 @@ #include using ResourceManagerType = AAssetManager; -using NativeWindowType = ANativeWindow; +using NativeWindowType = ANativeWindow; #elif (CC_PLATFORM == CC_PLATFORM_OHOS) #include #include using ResourceManagerType = ResourceManager; -using NativeWindowType = NativeLayer; +using NativeWindowType = NativeLayer; #endif using NativeActivity = void*; //jobject -using NativeEnv = void*; //jnienv +using NativeEnv = void*; //jnienv namespace cc { @@ -71,22 +71,22 @@ public: virtual void start(int argc, const char** argv); - void setWindowHandler(NativeWindowType* window); + void setWindowHandler(NativeWindowType* window); NativeWindowType* getWindowHandler(); - void setActivityGetter(std::function); + void setActivityGetter(std::function); void* getActivity(); - void setEnvGetter(std::function); + void setEnvGetter(std::function); void* getEnv(); - void setResourceManager(ResourceManagerType* resourceManager); + void setResourceManager(ResourceManagerType* resourceManager); ResourceManagerType* getResourceManager(); void setSdkVersion(int sdkVersion); - int getSdkVersion() const; + int getSdkVersion() const; - void setObbPath(const std::string& path); + void setObbPath(const std::string& path); std::string getObbPath() const; bool isRunning() const; @@ -96,13 +96,13 @@ public: void flushTasksOnGameThread() const; struct CommandMsg { - JniCommand cmd; + JniCommand cmd; std::function callback; }; void writeCommandAsync(JniCommand cmd); void writeCommandSync(JniCommand cmd); - int readCommand(CommandMsg* msg); - int readCommandWithTimeout(CommandMsg* cmd, int delayMS); + int readCommand(CommandMsg* msg); + int readCommandWithTimeout(CommandMsg* cmd, int delayMS); void setEventDispatch(IEventDispatch* eventDispatcher); void dispatchEvent(const OSEvent& ev); @@ -125,19 +125,19 @@ private: void postExecCmd(JniCommand cmd); bool _running{false}; - int _sdkVersion{0}; + int _sdkVersion{0}; bool _animating{false}; - std::promise _threadPromise; - std::string _obbPath; - ResourceManagerType* _resourceManager{nullptr}; - NativeWindowType* _window{nullptr}; - NativeWindowType* _pendingWindow{nullptr}; - JniCommand _appState{JniCommand::JNI_CMD_UNKNOW}; - IEventDispatch* _eventDispatcher{nullptr}; + std::promise _threadPromise; + std::string _obbPath; + ResourceManagerType* _resourceManager{nullptr}; + NativeWindowType* _window{nullptr}; + NativeWindowType* _pendingWindow{nullptr}; + JniCommand _appState{JniCommand::JNI_CMD_UNKNOW}; + IEventDispatch* _eventDispatcher{nullptr}; std::unique_ptr _messagePipe{nullptr}; - std::function _envGetter; + std::function _envGetter; std::function _activityGetter; }; diff --git a/native/cocos/platform/java/jni/glue/MessagePipe.cpp b/native/cocos/platform/java/jni/glue/MessagePipe.cpp index ef39b9505d..fabcab6063 100644 --- a/native/cocos/platform/java/jni/glue/MessagePipe.cpp +++ b/native/cocos/platform/java/jni/glue/MessagePipe.cpp @@ -37,7 +37,7 @@ MessagePipe::MessagePipe() { LOGV("Can not create pipe: %s", strerror(errno)); } - _pipeRead = messagePipe[0]; + _pipeRead = messagePipe[0]; _pipeWrite = messagePipe[1]; if (fcntl(_pipeRead, F_SETFL, O_NONBLOCK) < 0) { @@ -60,7 +60,7 @@ int MessagePipe::readCommand(int8_t &cmd) const { int MessagePipe::readCommandWithTimeout(void *msg, int32_t size, int delayMS) { if (delayMS > 0) { - static fd_set fdSet; + static fd_set fdSet; static timeval timeout; timeout = {delayMS / 1000, (delayMS % 1000) * 1000}; diff --git a/native/cocos/platform/java/jni/glue/MessagePipe.h b/native/cocos/platform/java/jni/glue/MessagePipe.h index 2ca16aa8b8..2dee2f30ef 100644 --- a/native/cocos/platform/java/jni/glue/MessagePipe.h +++ b/native/cocos/platform/java/jni/glue/MessagePipe.h @@ -36,13 +36,13 @@ public: ~MessagePipe(); void writeCommand(int8_t cmd) const; - int readCommand(int8_t &cmd) const; + int readCommand(int8_t &cmd) const; void writeCommand(void *msg, int32_t size) const; - int readCommand(void *msg, int32_t size) const; - int readCommandWithTimeout(void *msg, int32_t size, int delayMS); + int readCommand(void *msg, int32_t size) const; + int readCommandWithTimeout(void *msg, int32_t size, int delayMS); private: - int _pipeRead = 0; + int _pipeRead = 0; int _pipeWrite = 0; }; diff --git a/native/cocos/platform/java/modules/Accelerometer.cpp b/native/cocos/platform/java/modules/Accelerometer.cpp index 073718511b..144785ef71 100644 --- a/native/cocos/platform/java/modules/Accelerometer.cpp +++ b/native/cocos/platform/java/modules/Accelerometer.cpp @@ -38,7 +38,7 @@ void Accelerometer::setAccelerometerInterval(float interval) { const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() { static MotionValue motionValue; - float * v = getDeviceMotionValueJNI(); + float *v = getDeviceMotionValueJNI(); if (v) { motionValue.accelerationIncludingGravityX = v[0]; @@ -50,7 +50,7 @@ const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() { motionValue.accelerationZ = v[5]; motionValue.rotationRateAlpha = v[6]; - motionValue.rotationRateBeta = v[7]; + motionValue.rotationRateBeta = v[7]; motionValue.rotationRateGamma = v[8]; } else { memset(&motionValue, 0, sizeof(motionValue)); diff --git a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp index 8d7c77ba5d..cf0731f536 100644 --- a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.cpp @@ -40,7 +40,7 @@ namespace { namespace cc { CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { jobject obj = JniHelper::newObject(JCLS_CANVASIMPL); - _obj = JniHelper::getEnv()->NewGlobalRef(obj); + _obj = JniHelper::getEnv()->NewGlobalRef(obj); ccDeleteLocalRef(JniHelper::getEnv(), obj); } @@ -49,7 +49,7 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; @@ -155,7 +155,7 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measure return ccstd::array{0.0F, 0.0F}; } float measureText1 = JniHelper::callObjectFloatMethod(_obj, JCLS_CANVASIMPL, "measureText", text); - Size size{measureText1, 0.0F}; + Size size{measureText1, 0.0F}; return size; } @@ -209,7 +209,7 @@ void CanvasRenderingContext2DDelegate::fillImageData(const Data &imageData, floa } void CanvasRenderingContext2DDelegate::updateData() { - jobject bmpObj = nullptr; + jobject bmpObj = nullptr; JniMethodInfo methodInfo; #if (CC_PLATFORM == CC_PLATFORM_ANDROID) if (JniHelper::getMethodInfo(methodInfo, JCLS_CANVASIMPL, "getBitmap", "()Landroid/graphics/Bitmap;")) { @@ -246,7 +246,7 @@ void CanvasRenderingContext2DDelegate::updateData() { uint32_t size = bmpInfo.stride * bmpInfo.height; #else OhosPixelMapInfo bmpInfo; - void * pixelData = nullptr; + void *pixelData = nullptr; if (GetImageInfo(env, bmpObj, bmpInfo) == OHOS_IMAGE_RESULT_SUCCESS && bmpInfo.width > 0 && @@ -290,7 +290,7 @@ void CanvasRenderingContext2DDelegate::unMultiplyAlpha(unsigned char *ptr, uint3 for (int i = 0; i < size; i += 4) { alpha = static_cast(ptr[i + 3]); if (alpha > 0) { - ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); + ptr[i] = CLAMP((int)((float)ptr[i] / alpha * 255), 255); ptr[i + 1] = CLAMP((int)((float)ptr[i + 1] / alpha * 255), 255); ptr[i + 2] = CLAMP((int)((float)ptr[i + 2] / alpha * 255), 255); } diff --git a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h index ee63aac5f7..cc8dba0688 100644 --- a/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/java/modules/CanvasRenderingContext2DDelegate.h @@ -51,38 +51,38 @@ namespace cc { class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: using Size = ccstd::array; - using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineJoin) override; - void rect(float x, float y, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineJoin) override; + void rect(float x, float y, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void updateData() override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void updateData() override; private: void unMultiplyAlpha(unsigned char *ptr, uint32_t size); @@ -90,9 +90,9 @@ private: public: private: jobject _obj = nullptr; - Data _data; - float _bufferWidth = 0.0F; - float _bufferHeight = 0.0F; + Data _data; + float _bufferWidth = 0.0F; + float _bufferHeight = 0.0F; }; } // namespace cc diff --git a/native/cocos/platform/java/modules/CommonScreen.cpp b/native/cocos/platform/java/modules/CommonScreen.cpp index 89a18d5319..ee6de65a7e 100644 --- a/native/cocos/platform/java/modules/CommonScreen.cpp +++ b/native/cocos/platform/java/modules/CommonScreen.cpp @@ -87,15 +87,15 @@ Vec4 CommonScreen::getSafeAreaEdge() const { bool CommonScreen::isDisplayStats() { //NOLINT se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void CommonScreen::setDisplayStats(bool isShow) { //NOLINT se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); se::ScriptEngine::getInstance()->evalString(commandBuf); } diff --git a/native/cocos/platform/java/modules/CommonScreen.h b/native/cocos/platform/java/modules/CommonScreen.h index 5be098d732..639bfd4fce 100644 --- a/native/cocos/platform/java/modules/CommonScreen.h +++ b/native/cocos/platform/java/modules/CommonScreen.h @@ -31,10 +31,10 @@ namespace cc { class CommonScreen : public IScreen { public: - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool keepScreenOn) override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool keepScreenOn) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** @brief Get current display stats. @return bool, is displaying stats or not. diff --git a/native/cocos/platform/java/modules/CommonSystem.cpp b/native/cocos/platform/java/modules/CommonSystem.cpp index aa69713b25..6da4c25105 100644 --- a/native/cocos/platform/java/modules/CommonSystem.cpp +++ b/native/cocos/platform/java/modules/CommonSystem.cpp @@ -28,7 +28,7 @@ #include "platform/java/jni/JniImp.h" namespace cc { -CommonSystem::CommonSystem() = default; +CommonSystem::CommonSystem() = default; CommonSystem::~CommonSystem() = default; ccstd::string CommonSystem::getDeviceModel() const { @@ -36,9 +36,9 @@ ccstd::string CommonSystem::getDeviceModel() const { } CommonSystem::LanguageType CommonSystem::getCurrentLanguage() const { - ccstd::string languageName = getCurrentLanguageJNI(); - const char * pLanguageName = languageName.c_str(); - LanguageType ret = LanguageType::ENGLISH; + ccstd::string languageName = getCurrentLanguageJNI(); + const char *pLanguageName = languageName.c_str(); + LanguageType ret = LanguageType::ENGLISH; if (0 == strcmp("zh", pLanguageName)) { ret = LanguageType::CHINESE; diff --git a/native/cocos/platform/java/modules/SystemWindow.cpp b/native/cocos/platform/java/modules/SystemWindow.cpp index b6f820b21d..ad9464bd09 100644 --- a/native/cocos/platform/java/modules/SystemWindow.cpp +++ b/native/cocos/platform/java/modules/SystemWindow.cpp @@ -30,7 +30,7 @@ #include #include #if (CC_PLATFORM == CC_PLATFORM_ANDROID) -#include "android/AndroidPlatform.h" + #include "android/AndroidPlatform.h" #endif #include "BasePlatform.h" diff --git a/native/cocos/platform/java/modules/SystemWindow.h b/native/cocos/platform/java/modules/SystemWindow.h index bdc80c2e5a..3303369733 100644 --- a/native/cocos/platform/java/modules/SystemWindow.h +++ b/native/cocos/platform/java/modules/SystemWindow.h @@ -36,10 +36,10 @@ public: /** @brief enable/disable(lock) the cursor, default is enabled */ - void setCursorEnabled(bool value) override; - void copyTextToClipboard(const std::string& text) override; + void setCursorEnabled(bool value) override; + void copyTextToClipboard(const std::string& text) override; uintptr_t getWindowHandler() const override; - Size getViewSize() const override; + Size getViewSize() const override; }; } // namespace cc diff --git a/native/cocos/platform/linux/FileUtils-linux.cpp b/native/cocos/platform/linux/FileUtils-linux.cpp index 00c54ae8e7..453d2aae58 100644 --- a/native/cocos/platform/linux/FileUtils-linux.cpp +++ b/native/cocos/platform/linux/FileUtils-linux.cpp @@ -52,20 +52,20 @@ FileUtils *FileUtils::getInstance() { bool FileUtilsLinux::init() { // get application path - char fullpath[256] = {0}; - ssize_t length = readlink("/proc/self/exe", fullpath, sizeof(fullpath) - 1); + char fullpath[256] = {0}; + ssize_t length = readlink("/proc/self/exe", fullpath, sizeof(fullpath) - 1); if (length <= 0) { return false; } - fullpath[length] = '\0'; + fullpath[length] = '\0'; ccstd::string appPath = fullpath; - _defaultResRootPath = appPath.substr(0, appPath.find_last_of('/')); + _defaultResRootPath = appPath.substr(0, appPath.find_last_of('/')); _defaultResRootPath.append(CC_RESOURCE_FOLDER_LINUX); // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. - const char * xdg_config_path = getenv("XDG_CONFIG_HOME"); + const char *xdg_config_path = getenv("XDG_CONFIG_HOME"); ccstd::string xdgConfigPath; if (xdg_config_path == nullptr) { xdgConfigPath = getenv("HOME"); diff --git a/native/cocos/platform/linux/FileUtils-linux.h b/native/cocos/platform/linux/FileUtils-linux.h index 0cc908c83e..8afcaf4245 100644 --- a/native/cocos/platform/linux/FileUtils-linux.h +++ b/native/cocos/platform/linux/FileUtils-linux.h @@ -30,9 +30,9 @@ namespace cc { class CC_DLL FileUtilsLinux : public FileUtils { public: friend class FileUtils; - bool isFileExistInternal(const ccstd::string &filename) const override; + bool isFileExistInternal(const ccstd::string &filename) const override; ccstd::string getWritablePath() const override; - bool init() override; + bool init() override; private: ccstd::string _writablePath; diff --git a/native/cocos/platform/linux/LinuxPlatform.cpp b/native/cocos/platform/linux/LinuxPlatform.cpp index 246b031cb9..5a2db81f9e 100644 --- a/native/cocos/platform/linux/LinuxPlatform.cpp +++ b/native/cocos/platform/linux/LinuxPlatform.cpp @@ -62,7 +62,7 @@ int32_t LinuxPlatform::init() { } static long getCurrentMillSecond() { - long lLastTime; + long lLastTime; struct timeval stCurrentTime; gettimeofday(&stCurrentTime, NULL); @@ -71,14 +71,14 @@ static long getCurrentMillSecond() { } int32_t LinuxPlatform::loop() { - long lastTime = 0L; - long curTime = 0L; + long lastTime = 0L; + long curTime = 0L; long desiredInterval = 0L; - long actualInterval = 0L; + long actualInterval = 0L; onResume(); while (!_quit) { - curTime = getCurrentMillSecond(); - desiredInterval = static_cast(1000.0 / getFps()); + curTime = getCurrentMillSecond(); + desiredInterval = static_cast(1000.0 / getFps()); _window->pollEvent(&_quit); actualInterval = curTime - lastTime; if (actualInterval >= desiredInterval) { diff --git a/native/cocos/platform/linux/LinuxPlatform.h b/native/cocos/platform/linux/LinuxPlatform.h index b418a7b78e..a56855f1e0 100644 --- a/native/cocos/platform/linux/LinuxPlatform.h +++ b/native/cocos/platform/linux/LinuxPlatform.h @@ -44,7 +44,7 @@ public: int32_t loop() override; private: - bool _quit{false}; + bool _quit{false}; std::shared_ptr _window{nullptr}; }; diff --git a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp index 190cc75ec3..9685c014fa 100644 --- a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.cpp @@ -50,13 +50,13 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; } - auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); - auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); memset(data, 0x00, textureSize); _imageData.fastSet((uint8_t *)data, textureSize); @@ -69,7 +69,7 @@ void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { } //Screen *scr = DefaultScreenOfDisplay(_dis); _pixmap = XCreatePixmap(_dis, _win, w, h, 32); - _gc = XCreateGC(_dis, _pixmap, 0, 0); + _gc = XCreateGC(_dis, _pixmap, 0, 0); } void CanvasRenderingContext2DDelegate::beginPath() { @@ -131,10 +131,10 @@ void CanvasRenderingContext2DDelegate::fillText(const ccstd::string &text, float XSetForeground(_dis, _gc, 0xff000000 | _fillStyle); XSetFont(_dis, _gc, _font->fid); XDrawString(_dis, _pixmap, _gc, offsetPoint[0], offsetPoint[1], text.c_str(), (int)(text.length())); - XImage * image = XGetImage(_dis, _pixmap, 0, 0, _bufferWidth, _bufferHeight, AllPlanes, ZPixmap); - int width = image->width; - int height = image->height; - unsigned char *data = _imageData.getBytes(); + XImage *image = XGetImage(_dis, _pixmap, 0, 0, _bufferWidth, _bufferHeight, AllPlanes, ZPixmap); + int width = image->width; + int height = image->height; + unsigned char *data = _imageData.getBytes(); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { *(((int *)data + (y * width) + x)) = static_cast(XGetPixel(image, x, y)); @@ -151,9 +151,9 @@ void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, flo CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const ccstd::string &text) { if (text.empty()) return ccstd::array{0.0f, 0.0f}; - int font_ascent = 0; - int font_descent = 0; - int direction = 0; + int font_ascent = 0; + int font_descent = 0; + int direction = 0; XCharStruct overall; XQueryTextExtents(_dis, _font->fid, text.c_str(), text.length(), &direction, &font_ascent, &font_descent, &overall); return ccstd::array{static_cast(overall.width), @@ -161,18 +161,18 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measure } void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, - float fontSize, - bool bold, - bool italic, - bool oblique, + float fontSize, + bool bold, + bool italic, + bool oblique, bool /* smallCaps */) { do { _fontName = fontName; _fontSize = static_cast(fontSize); /// TODO(bug):Remove default settings - ccstd::string fontName = "helvetica"; // default - char serv[1024] = {0}; - ccstd::string slant = ""; + ccstd::string fontName = "helvetica"; // default + char serv[1024] = {0}; + ccstd::string slant = ""; if (italic) { slant = "*I"; } else if (oblique) { @@ -191,8 +191,8 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, _font = XLoadQueryFont(_dis, serv); if (!_font) { static int fontSizes[] = {8, 10, 12, 14, 18, 24}; - int i = 0; - int size = sizeof(fontSizes) / sizeof(fontSizes[0]); + int i = 0; + int size = sizeof(fontSizes) / sizeof(fontSizes[0]); for (i = 0; i < size; ++i) { if (_fontSize < fontSizes[i]) { break; @@ -272,9 +272,9 @@ void CanvasRenderingContext2DDelegate::fillTextureData() { } ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text) { - int font_ascent = 0; - int font_descent = 0; - int direction = 0; + int font_ascent = 0; + int font_descent = 0; + int direction = 0; XCharStruct overall; XQueryTextExtents(_dis, _font->fid, text.c_str(), text.length(), &direction, &font_ascent, &font_descent, &overall); int width = overall.width; diff --git a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h index b667a63370..abdea28fdb 100644 --- a/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/linux/modules/CanvasRenderingContext2DDelegate.h @@ -43,60 +43,60 @@ namespace cc { class CC_DLL CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: - using Point = ccstd::array; - using Vec2 = ccstd::array; - using Size = ccstd::array; + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; using Color4F = ccstd::array; - using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineCap) override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - void rect(float x, float y, float w, float h) override; - void updateData() override {} + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + void updateData() override {} private: - static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); - void removeCustomFont(); - int drawText(const ccstd::string &text, int x, int y); - Size sizeWithText(const wchar_t *pszText, int nLen); - void prepareBitmap(int nWidth, int nHeight); - void deleteBitmap(); - void fillTextureData(); + static wchar_t *utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const ccstd::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); ccstd::array convertDrawPoint(Point point, const ccstd::string &text); public: - Display * _dis{nullptr}; - int _screen{0}; - Drawable _win{0}; - Drawable _pixmap{0}; + Display *_dis{nullptr}; + int _screen{0}; + Drawable _win{0}; + Drawable _pixmap{0}; XFontStruct *_font{0}; - GC _gc; + GC _gc; private: int32_t _x{0}; @@ -105,20 +105,20 @@ private: int32_t _lineJoin{0}; private: - cc::Data _imageData; + cc::Data _imageData; ccstd::string _curFontPath; - int _savedDC{0}; - float _lineWidth{0.0F}; - float _bufferWidth{0.0F}; - float _bufferHeight{0.0F}; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; - ccstd::string _fontName; - int _fontSize{0}; - Size _textSize; - TextAlign _textAlign{TextAlign::CENTER}; - TextBaseline _textBaseLine{TextBaseline::TOP}; - unsigned long _fillStyle{0}; - unsigned long _strokeStyle{0}; + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + unsigned long _fillStyle{0}; + unsigned long _strokeStyle{0}; }; } // namespace cc diff --git a/native/cocos/platform/linux/modules/Screen.cpp b/native/cocos/platform/linux/modules/Screen.cpp index cafc6a32e9..8e57117975 100644 --- a/native/cocos/platform/linux/modules/Screen.cpp +++ b/native/cocos/platform/linux/modules/Screen.cpp @@ -37,9 +37,9 @@ int Screen::getDPI() const { static int dpi = -1; if (dpi == -1) { Display *dpy; - char * displayname = NULL; - int scr = 0; /* Screen number */ - dpy = XOpenDisplay(displayname); + char *displayname = NULL; + int scr = 0; /* Screen number */ + dpy = XOpenDisplay(displayname); /* * there are 2.54 centimeters to an inch; so there are 25.4 millimeters. * @@ -49,7 +49,7 @@ int Screen::getDPI() const { */ double xres = ((((double)DisplayWidth(dpy, scr)) * 25.4) / ((double)DisplayWidthMM(dpy, scr))); - dpi = (int)(xres + 0.5); + dpi = (int)(xres + 0.5); //printf("dpi = %d\n", dpi); XCloseDisplay(dpy); } @@ -74,15 +74,15 @@ Vec4 Screen::getSafeAreaEdge() const { bool Screen::isDisplayStats() { se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void Screen::setDisplayStats(bool isShow) { se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); se::ScriptEngine::getInstance()->evalString(commandBuf); } diff --git a/native/cocos/platform/linux/modules/Screen.h b/native/cocos/platform/linux/modules/Screen.h index dfb833859b..f52c31b2f8 100644 --- a/native/cocos/platform/linux/modules/Screen.h +++ b/native/cocos/platform/linux/modules/Screen.h @@ -31,11 +31,11 @@ namespace cc { class CC_DLL Screen : public IScreen { public: - int getDPI() const override; - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool value) override; + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** @brief Get current display stats. @return bool, is displaying stats or not. diff --git a/native/cocos/platform/linux/modules/System.cpp b/native/cocos/platform/linux/modules/System.cpp index 42ed503bbc..85c60d4bc7 100644 --- a/native/cocos/platform/linux/modules/System.cpp +++ b/native/cocos/platform/linux/modules/System.cpp @@ -53,8 +53,8 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - static char code[3] = {0}; - char * pLanguageName = getenv("LANG"); + static char code[3] = {0}; + char *pLanguageName = getenv("LANG"); if (!pLanguageName) { return "en"; } diff --git a/native/cocos/platform/linux/modules/SystemWindow.cpp b/native/cocos/platform/linux/modules/SystemWindow.cpp index a535bfa2c4..918531e3c2 100644 --- a/native/cocos/platform/linux/modules/SystemWindow.cpp +++ b/native/cocos/platform/linux/modules/SystemWindow.cpp @@ -40,7 +40,6 @@ namespace cc { SystemWindow::SystemWindow(IEventDispatch *delegate) : _sdl(std::make_unique(delegate)) { - } SystemWindow::~SystemWindow() { @@ -61,7 +60,7 @@ void SystemWindow::swapWindow() { bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { _sdl->createWindow(title, w, h, flags); - _width = w; + _width = w; _height = h; return true; } @@ -71,7 +70,7 @@ bool SystemWindow::createWindow(const char *title, int h, int flags) { // Create window _sdl->createWindow(title, x, y, w, h, flags); - _width = w; + _width = w; _height = h; return true; } diff --git a/native/cocos/platform/linux/modules/SystemWindow.h b/native/cocos/platform/linux/modules/SystemWindow.h index 05cbcd592b..8396c28975 100644 --- a/native/cocos/platform/linux/modules/SystemWindow.h +++ b/native/cocos/platform/linux/modules/SystemWindow.h @@ -36,15 +36,15 @@ public: explicit SystemWindow(IEventDispatch* delegate); ~SystemWindow() override; - int init(); - void swapWindow(); - void pollEvent(bool* quit); + int init(); + void swapWindow(); + void pollEvent(bool* quit); - bool createWindow(const char* title, - int w, int h, int flags) override; - bool createWindow(const char* title, - int x, int y, int w, - int h, int flags) override; + bool createWindow(const char* title, + int w, int h, int flags) override; + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; uintptr_t getWindowHandler() const override; uintptr_t getDisplay() const; Size getViewSize() const override; diff --git a/native/cocos/platform/mac/AppDelegate.mm b/native/cocos/platform/mac/AppDelegate.mm index 2105174c9e..1ac21523b7 100644 --- a/native/cocos/platform/mac/AppDelegate.mm +++ b/native/cocos/platform/mac/AppDelegate.mm @@ -30,7 +30,6 @@ #include "cocos/bindings/event/EventDispatcher.h" #include "platform/mac/MacPlatform.h" - @interface AppDelegate () { NSWindow* _window; // Game* _game; @@ -41,13 +40,13 @@ @implementation AppDelegate - (void)createLeftBottomWindow:(NSString*)title width:(int)w height:(int)h { - [self createWindow :title xPos:0 yPos:0 width:w height:h]; + [self createWindow:title xPos:0 yPos:0 width:w height:h]; } - (void)createWindow:(NSString*)title xPos:(int)x yPos:(int)y width:(int)w height:(int)h { _window.title = title; - NSRect rect = NSMakeRect(x, y, w, h); - _window = [[NSWindow alloc] initWithContentRect:rect + NSRect rect = NSMakeRect(x, y, w, h); + _window = [[NSWindow alloc] initWithContentRect:rect styleMask:NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; @@ -56,8 +55,8 @@ return; } ViewController* viewController = [[ViewController alloc] initWithSize:rect]; - _window.contentViewController = viewController; - _window.contentView = viewController.view; + _window.contentViewController = viewController; + _window.contentView = viewController.view; [_window.contentView setWantsBestResolutionOpenGLSurface:YES]; [_window makeKeyAndOrderFront:nil]; [[NSNotificationCenter defaultCenter] addObserver:self diff --git a/native/cocos/platform/mac/KeyCodeHelper.cpp b/native/cocos/platform/mac/KeyCodeHelper.cpp index 50ca0726ec..49832e7251 100644 --- a/native/cocos/platform/mac/KeyCodeHelper.cpp +++ b/native/cocos/platform/mac/KeyCodeHelper.cpp @@ -159,12 +159,12 @@ namespace { // Modifier Key State -bool stateShiftLeft = false; -bool stateShiftRight = false; -bool stateControlLeft = false; +bool stateShiftLeft = false; +bool stateShiftRight = false; +bool stateControlLeft = false; bool stateControlRight = false; -bool stateOptionLeft = false; -bool stateOptionRight = false; +bool stateOptionLeft = false; +bool stateOptionRight = false; // Refer to https://github.com/glfw/glfw/blob/master/src/cocoa_window.m. int keyCodes[0xff + 1] = {-1}; @@ -352,7 +352,7 @@ int translateKeycode(int keyCode) { if (keyCode < 0 || keyCode > 0xff) return -1; - int key = keyCodes[keyCode]; + int key = keyCodes[keyCode]; int keyInWeb = -1; if (key >= GLFW_KEY_0 && key <= GLFW_KEY_9) keyInWeb = key; diff --git a/native/cocos/platform/mac/KeyCodeHelper.h b/native/cocos/platform/mac/KeyCodeHelper.h index 1251dea2e1..275613fa51 100644 --- a/native/cocos/platform/mac/KeyCodeHelper.h +++ b/native/cocos/platform/mac/KeyCodeHelper.h @@ -26,6 +26,6 @@ #import "cocos/bindings/event/EventDispatcher.h" #pragma once -extern int translateKeycode(int); -extern void updateModifierKeyState(int keyCodeInWeb); +extern int translateKeycode(int); +extern void updateModifierKeyState(int keyCodeInWeb); extern cc::KeyboardEvent::Action getModifierKeyAction(int keyCodeInWeb); diff --git a/native/cocos/platform/mac/MacPlatform.h b/native/cocos/platform/mac/MacPlatform.h index 29d22b82b7..1be9fa9eed 100644 --- a/native/cocos/platform/mac/MacPlatform.h +++ b/native/cocos/platform/mac/MacPlatform.h @@ -49,7 +49,7 @@ public: * @brief Implement the main logic of the base platform. */ int32_t loop() override; - void setFps(int32_t fps) override; + void setFps(int32_t fps) override; int32_t getFps() const override; void onPause() override; diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 586208b7c1..300cc79dab 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -37,12 +37,12 @@ #import -extern int cocos_main(int argc, const char** argv); +extern int cocos_main(int argc, const char **argv); @interface MyTimer : NSObject { cc::MacPlatform *_platform; - NSTimer * _timer; - int _fps; + NSTimer *_timer; + int _fps; } - (instancetype)initWithApp:(cc::MacPlatform *)platform fps:(int)fps; - (void)start; @@ -122,7 +122,7 @@ int32_t MacPlatform::loop(void) { return cocos_main(0, nullptr); } -int32_t MacPlatform::run(int argc, const char** argv) { +int32_t MacPlatform::run(int argc, const char **argv) { id delegate = [[AppDelegate alloc] init]; NSApplication.sharedApplication.delegate = delegate; return NSApplicationMain(argc, argv); @@ -138,7 +138,7 @@ int32_t MacPlatform::getFps() const { void MacPlatform::onPause() { [_timer pause]; - + cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::HIDDEN; dispatchEvent(ev); @@ -146,7 +146,7 @@ void MacPlatform::onPause() { void MacPlatform::onResume() { [_timer resume]; - + cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::SHOW; dispatchEvent(ev); diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index 6746e6ded5..316f3c745f 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -33,15 +33,15 @@ #import "platform/mac/AppDelegate.h" @implementation View { - cc::MouseEvent _mouseEvent; + cc::MouseEvent _mouseEvent; cc::KeyboardEvent _keyboardEvent; - AppDelegate* _delegate; + AppDelegate *_delegate; } - (CALayer *)makeBackingLayer { - CAMetalLayer *layer = [CAMetalLayer layer]; - layer.delegate = self; - layer.autoresizingMask = true; + CAMetalLayer *layer = [CAMetalLayer layer]; + layer.delegate = self; + layer.autoresizingMask = true; layer.needsDisplayOnBoundsChange = true; return layer; } @@ -50,21 +50,21 @@ if (self = [super initWithFrame:frameRect]) { [self.window makeFirstResponder:self]; _delegate = [[NSApplication sharedApplication] delegate]; - int pixelRatio = [[NSScreen mainScreen] backingScaleFactor]; - CGSize size = CGSizeMake(frameRect.size.width * pixelRatio, frameRect.size.height * pixelRatio); + int pixelRatio = [[NSScreen mainScreen] backingScaleFactor]; + CGSize size = CGSizeMake(frameRect.size.width * pixelRatio, frameRect.size.height * pixelRatio); // Create CAMetalLayer self.wantsLayer = YES; // Config metal layer CAMetalLayer *layer = (CAMetalLayer *)self.layer; - layer.drawableSize = size; - layer.pixelFormat = MTLPixelFormatBGRA8Unorm; - layer.device = self.device = [MTLCreateSystemDefaultDevice() autorelease]; - layer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable; + layer.drawableSize = size; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + layer.device = self.device = [MTLCreateSystemDefaultDevice() autorelease]; + layer.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable; self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize; - self.layerContentsPlacement = NSViewLayerContentsPlacementScaleProportionallyToFill; - + self.layerContentsPlacement = NSViewLayerContentsPlacementScaleProportionallyToFill; + // Add tracking area to receive mouse move events. - NSRect rect = {0, 0, size.width, size.height}; + NSRect rect = {0, 0, size.width, size.height}; NSTrackingArea *trackingArea = [[[NSTrackingArea alloc] initWithRect:rect options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect) owner:self @@ -99,7 +99,6 @@ layer.drawableSize = nativeSize; [self viewDidChangeBackingProperties]; - if (cc::EventDispatcher::initialized()) { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::RESIZED; @@ -118,7 +117,7 @@ } - (void)keyDown:(NSEvent *)event { - _keyboardEvent.key = translateKeycode(event.keyCode); + _keyboardEvent.key = translateKeycode(event.keyCode); _keyboardEvent.action = [event isARepeat] ? cc::KeyboardEvent::Action::REPEAT : cc::KeyboardEvent::Action::PRESS; [self setModifierFlags:event]; @@ -126,7 +125,7 @@ } - (void)keyUp:(NSEvent *)event { - _keyboardEvent.key = translateKeycode(event.keyCode); + _keyboardEvent.key = translateKeycode(event.keyCode); _keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; [self setModifierFlags:event]; [_delegate dispatchEvent:_keyboardEvent]; @@ -136,7 +135,7 @@ int keyCode = translateKeycode(event.keyCode); updateModifierKeyState(keyCode); auto action = getModifierKeyAction(keyCode); - + // NOTE: in some cases, flagsChanged event may return some wrong keyCodes // For example: // - when you long press the capslock key, you may get the keyCode -1 @@ -226,10 +225,10 @@ } if (fabs(deltaX) > 0.0 || fabs(deltaY) > 0.0) { - _mouseEvent.type = cc::MouseEvent::Type::WHEEL; + _mouseEvent.type = cc::MouseEvent::Type::WHEEL; _mouseEvent.button = 0; - _mouseEvent.x = deltaX; - _mouseEvent.y = deltaY; + _mouseEvent.x = deltaX; + _mouseEvent.y = deltaY; [_delegate dispatchEvent:_mouseEvent]; } } @@ -251,13 +250,13 @@ } - (void)sendMouseEvent:(int)button type:(cc::MouseEvent::Type)type event:(NSEvent *)event { - const NSRect contentRect = [self frame]; - const NSPoint pos = [event locationInWindow]; + const NSRect contentRect = [self frame]; + const NSPoint pos = [event locationInWindow]; - _mouseEvent.type = type; + _mouseEvent.type = type; _mouseEvent.button = button; - _mouseEvent.x = pos.x; - _mouseEvent.y = contentRect.size.height - pos.y; + _mouseEvent.x = pos.x; + _mouseEvent.y = contentRect.size.height - pos.y; [_delegate dispatchEvent:_mouseEvent]; } diff --git a/native/cocos/platform/mac/ViewController.mm b/native/cocos/platform/mac/ViewController.mm index 890256a0a3..925afd886c 100644 --- a/native/cocos/platform/mac/ViewController.mm +++ b/native/cocos/platform/mac/ViewController.mm @@ -26,8 +26,7 @@ #import "ViewController.h" #import "platform/mac/View.h" -@implementation ViewController -{ +@implementation ViewController { View* _view; } diff --git a/native/cocos/platform/mac/modules/Network.mm b/native/cocos/platform/mac/modules/Network.mm index e0e73141ca..be638fcbbc 100644 --- a/native/cocos/platform/mac/modules/Network.mm +++ b/native/cocos/platform/mac/modules/Network.mm @@ -29,7 +29,6 @@ #include #include "platform/apple/Reachability.h" - namespace cc { INetwork::NetworkType Network::getNetworkType() const { @@ -39,7 +38,7 @@ INetwork::NetworkType Network::getNetworkType() const { __reachability->addRef(); } - NetworkType ret = NetworkType::NONE; + NetworkType ret = NetworkType::NONE; Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus(); switch (status) { case Reachability::NetworkStatus::REACHABLE_VIA_WIFI: diff --git a/native/cocos/platform/mac/modules/Screen.h b/native/cocos/platform/mac/modules/Screen.h index 3709b2abdc..a7ef519151 100644 --- a/native/cocos/platform/mac/modules/Screen.h +++ b/native/cocos/platform/mac/modules/Screen.h @@ -31,11 +31,11 @@ namespace cc { class Screen : public IScreen { public: - int getDPI() const override; - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool value) override; + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** @brief Get current display stats. @return bool, is displaying stats or not. diff --git a/native/cocos/platform/mac/modules/Screen.mm b/native/cocos/platform/mac/modules/Screen.mm index 3eee5dfe98..fcedd5b18f 100644 --- a/native/cocos/platform/mac/modules/Screen.mm +++ b/native/cocos/platform/mac/modules/Screen.mm @@ -35,10 +35,10 @@ namespace cc { int Screen::getDPI() const { - NSScreen * screen = [NSScreen mainScreen]; - NSDictionary *description = [screen deviceDescription]; - NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; - CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); + NSScreen *screen = [NSScreen mainScreen]; + NSDictionary *description = [screen deviceDescription]; + NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; + CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); } @@ -61,15 +61,15 @@ Vec4 Screen::getSafeAreaEdge() const { bool Screen::isDisplayStats() { se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void Screen::setDisplayStats(bool isShow) { se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); se::ScriptEngine::getInstance()->evalString(commandBuf); } diff --git a/native/cocos/platform/mac/modules/System.mm b/native/cocos/platform/mac/modules/System.mm index 585f46c94d..c638530f5f 100644 --- a/native/cocos/platform/mac/modules/System.mm +++ b/native/cocos/platform/mac/modules/System.mm @@ -26,13 +26,11 @@ #include "platform/mac/modules/System.h" #import - #include #include #include #include - namespace cc { using OSType = System::OSType; @@ -48,13 +46,13 @@ ccstd::string System::getDeviceModel() const { System::LanguageType System::getCurrentLanguage() const { // get the current language and country config - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; - NSString * currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; // get the current language code.(such as English is "en", Chinese is "zh" and so on) - NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; - NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; + NSDictionary *temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; + NSString *languageCode = [temp objectForKey:NSLocaleLanguageCode]; if ([languageCode isEqualToString:@"zh"]) return LanguageType::CHINESE; if ([languageCode isEqualToString:@"en"]) return LanguageType::ENGLISH; @@ -79,22 +77,22 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSArray * languages = [defaults objectForKey:@"AppleLanguages"]; - NSString * currentLanguage = [languages objectAtIndex:0]; + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *languages = [defaults objectForKey:@"AppleLanguages"]; + NSString *currentLanguage = [languages objectAtIndex:0]; return [currentLanguage UTF8String]; } ccstd::string System::getSystemVersion() const { - NSOperatingSystemVersion v = NSProcessInfo.processInfo.operatingSystemVersion; - char version[50] = {0}; + NSOperatingSystemVersion v = NSProcessInfo.processInfo.operatingSystemVersion; + char version[50] = {0}; snprintf(version, sizeof(version), "%d.%d.%d", (int)v.majorVersion, (int)v.minorVersion, (int)v.patchVersion); return version; } bool System::openURL(const ccstd::string &url) { - NSString *msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; - NSURL * nsUrl = [NSURL URLWithString:msg]; + NSString *msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding]; + NSURL *nsUrl = [NSURL URLWithString:msg]; return [[NSWorkspace sharedWorkspace] openURL:nsUrl]; } } // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h index 45436d49b5..b55fabfd40 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.h +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -54,6 +54,6 @@ public: private: int32_t _width{0}; int32_t _height{0}; - bool _isWindowCreated{false}; + bool _isWindowCreated{false}; }; } // namespace cc diff --git a/native/cocos/platform/mac/modules/SystemWindow.mm b/native/cocos/platform/mac/modules/SystemWindow.mm index 1431e2ea19..0277947063 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.mm +++ b/native/cocos/platform/mac/modules/SystemWindow.mm @@ -27,7 +27,6 @@ #import #include "platform/mac/AppDelegate.h" - namespace { } @@ -38,16 +37,16 @@ SystemWindow::SystemWindow() = default; SystemWindow::~SystemWindow() = default; -bool SystemWindow::createWindow(const char* title, +bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { - if(_isWindowCreated) { + if (_isWindowCreated) { return true; } _isWindowCreated = true; - _width = w; - _height = h; + _width = w; + _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; - NSString * aString = [NSString stringWithUTF8String:title]; + NSString *aString = [NSString stringWithUTF8String:title]; [delegate createLeftBottomWindow:aString width:w height:h]; return true; } @@ -55,14 +54,14 @@ bool SystemWindow::createWindow(const char* title, bool SystemWindow::createWindow(const char *title, int x, int y, int w, int h, int flags) { - if(_isWindowCreated) { + if (_isWindowCreated) { return true; } _isWindowCreated = true; - _width = w; - _height = h; + _width = w; + _height = h; AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; - NSString * aString = [NSString stringWithUTF8String:title]; + NSString *aString = [NSString stringWithUTF8String:title]; [delegate createWindow:aString xPos:x yPos:y width:w height:h]; return true; } @@ -86,4 +85,4 @@ SystemWindow::Size SystemWindow::getViewSize() const { return Size{static_cast(_width), static_cast(_height)}; } -} +} // namespace cc diff --git a/native/cocos/platform/mac/modules/Vibrator.mm b/native/cocos/platform/mac/modules/Vibrator.mm index a9254c79e9..a63433363b 100644 --- a/native/cocos/platform/mac/modules/Vibrator.mm +++ b/native/cocos/platform/mac/modules/Vibrator.mm @@ -33,4 +33,4 @@ void Vibrator::vibrate(float duration) { CC_UNUSED_PARAM(duration); } -} +} // namespace cc diff --git a/native/cocos/platform/ohos/FileUtils-ohos.cpp b/native/cocos/platform/ohos/FileUtils-ohos.cpp index 4f6f13c297..88747da4c5 100644 --- a/native/cocos/platform/ohos/FileUtils-ohos.cpp +++ b/native/cocos/platform/ohos/FileUtils-ohos.cpp @@ -44,7 +44,7 @@ namespace cc { ResourceManager *FileUtilsOHOS::ohosResourceMgr = {}; -ccstd::string FileUtilsOHOS::ohosAssetPath = {}; +ccstd::string FileUtilsOHOS::ohosAssetPath = {}; namespace { @@ -61,9 +61,9 @@ void printRawfiles(ResourceManager *mgr, const ccstd::string &path) { if (dir) { auto fileCnt = GetRawFileCount(dir); for (auto i = 0; i < fileCnt; i++) { - ccstd::string subFile = GetRawFileName(dir, i); - auto newPath = path + "/" + subFile; // NOLINT - auto debugPtr = newPath.c_str(); + ccstd::string subFile = GetRawFileName(dir, i); + auto newPath = path + "/" + subFile; // NOLINT + auto debugPtr = newPath.c_str(); HILOG_ERROR(LOG_APP, " find path %{public}s", newPath.c_str()); printRawfiles(mgr, newPath); } @@ -127,7 +127,7 @@ FileUtils::Status FileUtilsOHOS::getContents(const ccstd::string &filename, Resi } ccstd::string relativePath; - size_t position = fullPath.find(ASSETS_FOLDER_NAME); + size_t position = fullPath.find(ASSETS_FOLDER_NAME); if (0 == position) { // "@assets/" is at the beginning of the path and we don't want it relativePath = rawfilePrefix + fullPath.substr(strlen(ASSETS_FOLDER_NAME)); @@ -179,7 +179,7 @@ ccstd::string FileUtilsOHOS::getWritablePath() const { bool FileUtilsOHOS::isFileExistInternal(const ccstd::string &strFilePath) const { if (strFilePath.empty()) return false; - auto filePath = strFilePath; + auto filePath = strFilePath; auto fileFound = false; if (strFilePath[0] == '/') { // absolute path @@ -239,14 +239,14 @@ ccstd::string FileUtilsOHOS::expandPath(const ccstd::string &input, bool *isRawF } std::pair> FileUtilsOHOS::getFd(const ccstd::string &path) const { - bool isRawFile = false; - const auto fullpath = expandPath(path, &isRawFile); + bool isRawFile = false; + const auto fullpath = expandPath(path, &isRawFile); if (isRawFile) { RawFile *rf = OpenRawFile(ohosResourceMgr, fullpath.c_str()); // FIXME: try reuse file - const auto bufSize = GetRawFileSize(rf); - auto fileCache = ccstd::vector(bufSize); - auto * buf = fileCache.data(); + const auto bufSize = GetRawFileSize(rf); + auto fileCache = ccstd::vector(bufSize); + auto *buf = fileCache.data(); // Fill buffer const auto readBytes = ReadRawFile(rf, buf, bufSize); assert(readBytes == bufSize); // read failure ? diff --git a/native/cocos/platform/ohos/FileUtils-ohos.h b/native/cocos/platform/ohos/FileUtils-ohos.h index 486ebe01cf..7784fdda55 100644 --- a/native/cocos/platform/ohos/FileUtils-ohos.h +++ b/native/cocos/platform/ohos/FileUtils-ohos.h @@ -65,7 +65,7 @@ private: /* weak ref, do not need release */ static ResourceManager *ohosResourceMgr; - static ccstd::string ohosAssetPath; + static ccstd::string ohosAssetPath; friend class FileUtils; }; diff --git a/native/cocos/platform/ohos/OhosPlatform.h b/native/cocos/platform/ohos/OhosPlatform.h index d643776cae..d6e74b68a1 100644 --- a/native/cocos/platform/ohos/OhosPlatform.h +++ b/native/cocos/platform/ohos/OhosPlatform.h @@ -33,9 +33,9 @@ class CC_DLL OhosPlatform : public UniversalPlatform { public: OhosPlatform(); int init() override; - void pollEvent() override; + void pollEvent() override; int32_t run(int argc, const char **argv) override; - int getSdkVersion() const override; + int getSdkVersion() const override; int32_t loop() override; private: diff --git a/native/cocos/platform/ohos/View.cpp b/native/cocos/platform/ohos/View.cpp index 67c25f26cb..732cab98ff 100644 --- a/native/cocos/platform/ohos/View.cpp +++ b/native/cocos/platform/ohos/View.cpp @@ -45,14 +45,14 @@ void View::engineHandleCmd(int cmd) { return; } else { cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; + event.name = EVENT_RECREATE_WINDOW; event.args->ptrVal = cocosApp.pendingWindow; cc::EventDispatcher::dispatchCustomEvent(event); } break; case ABILITY_CMD_TERM_WINDOW: { cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; + event.name = EVENT_DESTROY_WINDOW; event.args->ptrVal = cocosApp.pendingWindow; cc::EventDispatcher::dispatchCustomEvent(event); } break; diff --git a/native/cocos/platform/ohos/jni/JniCocosAbility.cpp b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp index 23f9b512d5..0ce7a8aab7 100644 --- a/native/cocos/platform/ohos/jni/JniCocosAbility.cpp +++ b/native/cocos/platform/ohos/jni/JniCocosAbility.cpp @@ -59,17 +59,17 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onCreateNative(JNIEn ResourceManager *objResourceManager = InitNativeResourceManager(env, resourceManager); JNI_NATIVE_GLUE()->setResourceManager(objResourceManager); - jboolean isCopy = false; + jboolean isCopy = false; ccstd::string assetPathClone; - const char * assetPathStr = env->GetStringUTFChars(assetPath, &isCopy); - assetPathClone = assetPathStr; + const char *assetPathStr = env->GetStringUTFChars(assetPath, &isCopy); + assetPathClone = assetPathStr; if (isCopy) { env->ReleaseStringUTFChars(assetPath, assetPathStr); assetPathStr = nullptr; } ccstd::string moduleName{"entry"}; - const char * moduleNameStr = env->GetStringUTFChars(moduleNameJ, &isCopy); - moduleName = moduleNameStr; + const char *moduleNameStr = env->GetStringUTFChars(moduleNameJ, &isCopy); + moduleName = moduleNameStr; if (isCopy) { env->ReleaseStringUTFChars(moduleNameJ, moduleNameStr); moduleNameStr = nullptr; @@ -116,7 +116,7 @@ Java_com_cocos_lib_CocosAbilitySlice_onWindowFocusChangedNative(JNIEnv *env, job JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_setRawfilePrefix(JNIEnv *env, jobject obj, jstring prefixJ) { //NOLINT JNI function name - jboolean isCopy = false; + jboolean isCopy = false; const char *prefix = env->GetStringUTFChars(prefixJ, &isCopy); cc::FileUtilsOHOS::setRawfilePrefix(prefix); if (isCopy) { diff --git a/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp index 58b8e86582..b835926c61 100644 --- a/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp +++ b/native/cocos/platform/ohos/jni/JniCocosSurfaceView.cpp @@ -31,16 +31,16 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosAbilitySlice_onOrientationChangedNative(JNIEnv *env, jobject obj, jint orientation, jint width, jint height) { //NOLINT JNI function name static jint pOrientation = 0; - static jint pWidth = 0; - static jint pHeight = 0; + static jint pWidth = 0; + static jint pHeight = 0; if (pOrientation != orientation || pWidth != width || pHeight != height) { cc::WindowEvent ev; - ev.type = cc::WindowEvent::Type::SIZE_CHANGED; - ev.width = width; + ev.type = cc::WindowEvent::Type::SIZE_CHANGED; + ev.width = width; ev.height = height; JNI_NATIVE_GLUE()->dispatchEvent(ev); pOrientation = orientation; - pHeight = height; - pWidth = width; + pHeight = height; + pWidth = width; } } \ No newline at end of file diff --git a/native/cocos/platform/ohos/modules/System.cpp b/native/cocos/platform/ohos/modules/System.cpp index c20f4314f6..9396039d91 100644 --- a/native/cocos/platform/ohos/modules/System.cpp +++ b/native/cocos/platform/ohos/modules/System.cpp @@ -26,7 +26,7 @@ #include "platform/ohos/modules/System.h" namespace cc { -System::System() = default; +System::System() = default; System::~System() = default; System::OSType System::getOSType() const { diff --git a/native/cocos/platform/qnx/FileUtils-qnx.cpp b/native/cocos/platform/qnx/FileUtils-qnx.cpp index cf2e3e77dd..412b7ffa60 100644 --- a/native/cocos/platform/qnx/FileUtils-qnx.cpp +++ b/native/cocos/platform/qnx/FileUtils-qnx.cpp @@ -67,7 +67,7 @@ bool FileUtilsQNX::init() { _defaultResRootPath += CC_RESOURCE_FOLDER_LINUX; // Set writable path to $XDG_CONFIG_HOME or ~/.config// if $XDG_CONFIG_HOME not exists. - const char * xdg_config_path = getenv("XDG_CONFIG_HOME"); + const char *xdg_config_path = getenv("XDG_CONFIG_HOME"); ccstd::string xdgConfigPath; if (xdg_config_path == NULL) { xdg_config_path = getenv("HOME"); diff --git a/native/cocos/platform/qnx/FileUtils-qnx.h b/native/cocos/platform/qnx/FileUtils-qnx.h index c98c05541f..38d29f0b20 100644 --- a/native/cocos/platform/qnx/FileUtils-qnx.h +++ b/native/cocos/platform/qnx/FileUtils-qnx.h @@ -30,9 +30,9 @@ namespace cc { class CC_DLL FileUtilsQNX : public FileUtils { public: friend class FileUtils; - bool isFileExistInternal(const ccstd::string &filename) const override; + bool isFileExistInternal(const ccstd::string &filename) const override; ccstd::string getWritablePath() const override; - bool init() override; + bool init() override; private: ccstd::string _writablePath; diff --git a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp index 8f5e7770d9..6ce6fef76e 100644 --- a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.cpp @@ -41,7 +41,7 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint8_t *p; for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { - p = buf + (totalWidth * offsetY + offsetX) * 4; + p = buf + (totalWidth * offsetY + offsetX) * 4; *p++ = r; *p++ = g; *p++ = b; @@ -54,7 +54,7 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, namespace cc { //static const char gdefaultFontName[] = "-*-helvetica-medium-o-*-*-24-*-*-*-*-*-iso8859-*"; //static const char gdefaultFontName[] = "lucidasanstypewriter-bold-24"; -static const char gdefaultFontName[] = "lucidasans-24"; +static const char gdefaultFontName[] = "lucidasans-24"; static const char gdefaultFontName1[] = "lucidasans"; CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { @@ -72,13 +72,13 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; } - auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); - auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(int8_t) * textureSize)); memset(data, 0x00, textureSize); _imageData.fastSet((unsigned char *)data, textureSize); @@ -89,7 +89,7 @@ void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { cairo_surface_destroy(_surface); } _surface = cairo_image_surface_create_for_data((unsigned char *)data, CAIRO_FORMAT_ARGB32, _bufferWidth, _bufferHeight, _bufferWidth * 4); - _cr = cairo_create(_surface); + _cr = cairo_create(_surface); } void CanvasRenderingContext2DDelegate::beginPath() { @@ -169,16 +169,16 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measure } void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, - float fontSize, - bool bold, - bool italic, - bool oblique, + float fontSize, + bool bold, + bool italic, + bool oblique, bool /* smallCaps */) { do { - _fontName = fontName; - _fontSize = static_cast(fontSize); + _fontName = fontName; + _fontSize = static_cast(fontSize); cairo_font_weight_t fontWeight = bold ? CAIRO_FONT_WEIGHT_BOLD : CAIRO_FONT_WEIGHT_NORMAL; - cairo_font_slant_t fontSlant = CAIRO_FONT_SLANT_NORMAL; + cairo_font_slant_t fontSlant = CAIRO_FONT_SLANT_NORMAL; if (italic) { fontSlant = CAIRO_FONT_SLANT_ITALIC; } else if (oblique) { @@ -238,9 +238,9 @@ void CanvasRenderingContext2DDelegate::fillTextureData() { } ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text) { - int font_ascent = 0; - int font_descent = 0; - int direction = 0; + int font_ascent = 0; + int font_descent = 0; + int direction = 0; cairo_text_extents_t extents; cairo_text_extents(_cr, text.c_str(), &extents); diff --git a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h index 0fbb02134b..9fa40a243f 100644 --- a/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/qnx/modules/CanvasRenderingContext2DDelegate.h @@ -41,71 +41,71 @@ namespace cc { class CC_DLL CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: - using Point = ccstd::array; - using Vec2 = ccstd::array; - using Size = ccstd::array; + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; using Color4F = ccstd::array; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineCap) override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - void rect(float x, float y, float w, float h) override; - void updateData() override {} + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + void updateData() override {} private: - static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); - void removeCustomFont(); - int drawText(const ccstd::string &text, int x, int y); - Size sizeWithText(const wchar_t *pszText, int nLen); - void prepareBitmap(int nWidth, int nHeight); - void deleteBitmap(); - void fillTextureData(); + static wchar_t *utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const ccstd::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); ccstd::array convertDrawPoint(Point point, const ccstd::string &text); public: cairo_surface_t *_surface{nullptr}; - cairo_t * _cr{nullptr}; + cairo_t *_cr{nullptr}; private: - cc::Data _imageData; + cc::Data _imageData; ccstd::string _curFontPath; - int _savedDC{0}; - float _lineWidth{0.0F}; - float _bufferWidth{0.0F}; - float _bufferHeight{0.0F}; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; - ccstd::string _fontName; - int _fontSize{0}; - Size _textSize; - TextAlign _textAlign{TextAlign::CENTER}; - TextBaseline _textBaseLine{TextBaseline::TOP}; - Color4F _fillStyle; - Color4F _strokeStyle; + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + Color4F _fillStyle; + Color4F _strokeStyle; }; } // namespace cc diff --git a/native/cocos/platform/qnx/modules/System.cpp b/native/cocos/platform/qnx/modules/System.cpp index 46e84cc07c..8af64388bd 100644 --- a/native/cocos/platform/qnx/modules/System.cpp +++ b/native/cocos/platform/qnx/modules/System.cpp @@ -53,8 +53,8 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - static char code[3] = {0}; - char * pLanguageName = getenv("LANG"); + static char code[3] = {0}; + char *pLanguageName = getenv("LANG"); if (!pLanguageName) { return "en"; } diff --git a/native/cocos/platform/qnx/modules/SystemWindow.cpp b/native/cocos/platform/qnx/modules/SystemWindow.cpp index a39d0729c9..a963d3247e 100644 --- a/native/cocos/platform/qnx/modules/SystemWindow.cpp +++ b/native/cocos/platform/qnx/modules/SystemWindow.cpp @@ -52,7 +52,7 @@ SystemWindow::~SystemWindow() { bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { - _width = w; + _width = w; _height = h; createWindow(title, 0, 0, w, h, flags); return true; @@ -64,7 +64,7 @@ bool SystemWindow::createWindow(const char *title, if (_screenWin) { return true; } - _width = w; + _width = w; _height = h; //Create the screen context @@ -84,7 +84,7 @@ bool SystemWindow::createWindow(const char *title, screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_FORMAT, (const int[]){SCREEN_FORMAT_RGBX8888}); #ifdef CC_USE_GLES3 screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_USAGE, (const int[]){SCREEN_USAGE_OPENGL_ES3}); -#elif CC_USE_GLES2 +#elif CC_USE_GLES2 screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_USAGE, (const int[]){SCREEN_USAGE_OPENGL_ES2}); #endif @@ -96,7 +96,7 @@ bool SystemWindow::createWindow(const char *title, } int size[2] = {w, h}; /* size of the window on screen */ - rc = screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_SIZE, size); + rc = screen_set_window_property_iv(_screenWin, SCREEN_PROPERTY_SIZE, size); if (rc) { perror("screen_set_window_property_iv(SCREEN_PROPERTY_POSITION)"); return EXIT_FAILURE; diff --git a/native/cocos/platform/win32/FileUtils-win32.cpp b/native/cocos/platform/win32/FileUtils-win32.cpp index f5e2f501da..8fd380d059 100644 --- a/native/cocos/platform/win32/FileUtils-win32.cpp +++ b/native/cocos/platform/win32/FileUtils-win32.cpp @@ -38,7 +38,7 @@ using namespace std; namespace cc { - #define CC_MAX_PATH 512 +#define CC_MAX_PATH 512 // The root path of resources, the character encoding is UTF-8. // UTF-8 is the only encoding supported by cocos2d-x API. @@ -47,7 +47,7 @@ static ccstd::string s_resourcePath = ""; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt static inline ccstd::string convertPathFormatToUnixStyle(const ccstd::string &path) { ccstd::string ret = path; - size_t len = ret.length(); + size_t len = ret.length(); for (size_t i = 0; i < len; ++i) { if (ret[i] == '\\') { ret[i] = '/'; @@ -66,7 +66,7 @@ static void _checkPath() { WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); char utf8ExeDir[CC_MAX_PATH] = {0}; - int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, static_cast(pUtf16DirEnd - pUtf16ExePath + 1), utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); + int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, static_cast(pUtf16DirEnd - pUtf16ExePath + 1), utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); } @@ -113,7 +113,7 @@ long FileUtilsWin32::getFileSize(const ccstd::string &filepath) { } LARGE_INTEGER size; size.HighPart = fad.nFileSizeHigh; - size.LowPart = fad.nFileSizeLow; + size.LowPart = fad.nFileSizeLow; return (long)size.QuadPart; } @@ -152,7 +152,7 @@ FileUtils::Status FileUtilsWin32::getContents(const ccstd::string &filename, Res return FileUtils::Status::OPEN_FAILED; DWORD hi; - auto size = ::GetFileSize(fileHandle, &hi); + auto size = ::GetFileSize(fileHandle, &hi); if (hi > 0) { ::CloseHandle(fileHandle); return FileUtils::Status::TOO_LARGE; @@ -164,8 +164,8 @@ FileUtils::Status FileUtilsWin32::getContents(const ccstd::string &filename, Res } buffer->resize(size); - DWORD sizeRead = 0; - BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); + DWORD sizeRead = 0; + BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); ::CloseHandle(fileHandle); if (!successed) { @@ -177,7 +177,7 @@ FileUtils::Status FileUtilsWin32::getContents(const ccstd::string &filename, Res } ccstd::string FileUtilsWin32::getPathForFilename(const ccstd::string &filename, const ccstd::string &searchPath) const { - ccstd::string unixFileName = convertPathFormatToUnixStyle(filename); + ccstd::string unixFileName = convertPathFormatToUnixStyle(filename); ccstd::string unixSearchPath = convertPathFormatToUnixStyle(searchPath); return FileUtils::getPathForFilename(unixFileName, unixSearchPath); @@ -185,7 +185,7 @@ ccstd::string FileUtilsWin32::getPathForFilename(const ccstd::string &filename, ccstd::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const ccstd::string &strDirectory, const ccstd::string &strFilename) const { ccstd::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); - ccstd::string unixFilename = convertPathFormatToUnixStyle(strFilename); + ccstd::string unixFilename = convertPathFormatToUnixStyle(strFilename); return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename); } @@ -202,7 +202,7 @@ string FileUtilsWin32::getWritablePath() const { // Debug app uses executable directory; Non-debug app uses local app data directory //#ifndef _DEBUG // Get filename of executable only, e.g. MyGame.exe - WCHAR * base_name = wcsrchr(full_path, '\\'); + WCHAR *base_name = wcsrchr(full_path, '\\'); wstring retPath; if (base_name) { WCHAR app_data_path[CC_MAX_PATH + 1]; @@ -264,7 +264,7 @@ bool FileUtilsWin32::renameFile(const ccstd::string &path, const ccstd::string & ccstd::string oldPath = path + oldname; ccstd::string newPath = path + name; - std::regex pat("\\/"); + std::regex pat("\\/"); ccstd::string _old = std::regex_replace(oldPath, pat, "\\"); ccstd::string _new = std::regex_replace(newPath, pat, "\\"); @@ -280,9 +280,9 @@ bool FileUtilsWin32::createDirectory(const ccstd::string &dirPath) { std::wstring path = StringUtf8ToWideChar(dirPath); // Split the path - size_t start = 0; - size_t found = path.find_first_of(L"/\\", start); - std::wstring subpath; + size_t start = 0; + size_t found = path.find_first_of(L"/\\", start); + std::wstring subpath; ccstd::vector dirs; if (found != std::wstring::npos) { @@ -320,7 +320,7 @@ bool FileUtilsWin32::createDirectory(const ccstd::string &dirPath) { } bool FileUtilsWin32::removeFile(const ccstd::string &filepath) { - std::regex pat("\\/"); + std::regex pat("\\/"); ccstd::string win32path = std::regex_replace(filepath, pat, "\\"); if (DeleteFile(StringUtf8ToWideChar(win32path).c_str())) { @@ -332,11 +332,11 @@ bool FileUtilsWin32::removeFile(const ccstd::string &filepath) { } bool FileUtilsWin32::removeDirectory(const ccstd::string &dirPath) { - std::wstring wpath = StringUtf8ToWideChar(dirPath); - std::wstring files = wpath + L"*.*"; + std::wstring wpath = StringUtf8ToWideChar(dirPath); + std::wstring files = wpath + L"*.*"; WIN32_FIND_DATA wfd; - HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); - bool ret = true; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; if (search != INVALID_HANDLE_VALUE) { BOOL find = true; while (find) { diff --git a/native/cocos/platform/win32/FileUtils-win32.h b/native/cocos/platform/win32/FileUtils-win32.h index 3b29db428f..9f657c11c8 100644 --- a/native/cocos/platform/win32/FileUtils-win32.h +++ b/native/cocos/platform/win32/FileUtils-win32.h @@ -48,11 +48,11 @@ class CC_DLL FileUtilsWin32 : public FileUtils { public: /* override functions */ - bool init(); + bool init(); virtual ccstd::string getWritablePath() const override; - virtual bool isAbsolutePath(const ccstd::string &strPath) const override; + virtual bool isAbsolutePath(const ccstd::string &strPath) const override; virtual ccstd::string getSuitableFOpen(const ccstd::string &filenameUtf8) const override; - virtual long getFileSize(const ccstd::string &filepath); + virtual long getFileSize(const ccstd::string &filepath); protected: virtual bool isFileExistInternal(const ccstd::string &strFilePath) const override; diff --git a/native/cocos/platform/win32/Utils-win32.cpp b/native/cocos/platform/win32/Utils-win32.cpp index 838236e603..427cb43cca 100644 --- a/native/cocos/platform/win32/Utils-win32.cpp +++ b/native/cocos/platform/win32/Utils-win32.cpp @@ -39,7 +39,7 @@ std::wstring StringUtf8ToWideChar(const ccstd::string &strUtf8) { int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); if (nNum) { WCHAR *wideCharString = ccnew WCHAR[nNum + 1]; - wideCharString[0] = 0; + wideCharString[0] = 0; nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); @@ -58,7 +58,7 @@ ccstd::string StringWideCharToUtf8(const std::wstring &strWideChar) { int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); if (nNum) { char *utf8String = ccnew char[nNum + 1]; - utf8String[0] = 0; + utf8String[0] = 0; nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); @@ -76,10 +76,10 @@ ccstd::string UTF8StringToMultiByte(const ccstd::string &strUtf8) { ccstd::string ret; if (!strUtf8.empty()) { std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); - int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); if (nNum) { char *ansiString = ccnew char[nNum + 1]; - ansiString[0] = 0; + ansiString[0] = 0; nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); diff --git a/native/cocos/platform/win32/Utils-win32.h b/native/cocos/platform/win32/Utils-win32.h index e2f6b30023..b377f8a438 100644 --- a/native/cocos/platform/win32/Utils-win32.h +++ b/native/cocos/platform/win32/Utils-win32.h @@ -34,7 +34,7 @@ namespace cc { -std::wstring CC_DLL StringUtf8ToWideChar(const ccstd::string &strUtf8); +std::wstring CC_DLL StringUtf8ToWideChar(const ccstd::string &strUtf8); ccstd::string CC_DLL StringWideCharToUtf8(const std::wstring &strWideChar); ccstd::string CC_DLL UTF8StringToMultiByte(const ccstd::string &strUtf8); diff --git a/native/cocos/platform/win32/WindowsPlatform.cpp b/native/cocos/platform/win32/WindowsPlatform.cpp index 4ffda82553..153de0682d 100644 --- a/native/cocos/platform/win32/WindowsPlatform.cpp +++ b/native/cocos/platform/win32/WindowsPlatform.cpp @@ -58,11 +58,11 @@ void PVRFrameEnableControlWindow(bool bEnable) { return; } - const WCHAR *wszValue = L"hide_gui"; - const WCHAR *wszNewData = (bEnable) ? L"NO" : L"YES"; - WCHAR wszOldData[256] = {0}; - DWORD dwSize = sizeof(wszOldData); - LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); + const WCHAR *wszValue = L"hide_gui"; + const WCHAR *wszNewData = (bEnable) ? L"NO" : L"YES"; + WCHAR wszOldData[256] = {0}; + DWORD dwSize = sizeof(wszOldData); + LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); if (ERROR_FILE_NOT_FOUND == status // the key not exist || (ERROR_SUCCESS == status // or the hide_gui value is exist && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal @@ -80,7 +80,6 @@ namespace cc { WindowsPlatform::WindowsPlatform() { } WindowsPlatform::~WindowsPlatform() { - #ifdef USE_WIN32_CONSOLE FreeConsole(); #endif @@ -112,15 +111,15 @@ int32_t WindowsPlatform::loop() { /////////////////////////////////////////////////////////////////////////// /////////////// changing timer resolution /////////////////////////////////////////////////////////////////////////// - UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution + UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution TIMECAPS tc; - UINT wTimerRes = 0; + UINT wTimerRes = 0; if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) { wTimerRes = std::min(std::max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax); timeBeginPeriod(wTimerRes); } - float dt = 0.f; + float dt = 0.f; const DWORD _16ms = 16; // Main message loop: @@ -128,9 +127,9 @@ int32_t WindowsPlatform::loop() { LARGE_INTEGER nLast; LARGE_INTEGER nNow; - LONGLONG actualInterval = 0LL; // actual frame internal + LONGLONG actualInterval = 0LL; // actual frame internal LONGLONG desiredInterval = 0LL; // desired frame internal, 1 / fps - LONG waitMS = 0L; + LONG waitMS = 0L; QueryPerformanceCounter(&nLast); QueryPerformanceFrequency(&nFreq); diff --git a/native/cocos/platform/win32/WindowsPlatform.h b/native/cocos/platform/win32/WindowsPlatform.h index 0c9bd01e69..98d6ed4dbe 100644 --- a/native/cocos/platform/win32/WindowsPlatform.h +++ b/native/cocos/platform/win32/WindowsPlatform.h @@ -46,7 +46,7 @@ public: private: std::shared_ptr _window{nullptr}; - bool _quit{false}; + bool _quit{false}; }; } // namespace cc diff --git a/native/cocos/platform/win32/compat/stdint.h b/native/cocos/platform/win32/compat/stdint.h index 3afa0e5b14..b51b64670b 100644 --- a/native/cocos/platform/win32/compat/stdint.h +++ b/native/cocos/platform/win32/compat/stdint.h @@ -98,54 +98,54 @@ extern "C" { // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) -typedef signed char int8_t; -typedef signed short int16_t; -typedef signed int int32_t; -typedef unsigned char uint8_t; +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef unsigned char uint8_t; typedef unsigned short uint16_t; -typedef unsigned int uint32_t; +typedef unsigned int uint32_t; #else -typedef signed __int8 int8_t; -typedef signed __int16 int16_t; -typedef signed __int32 int32_t; -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; +typedef signed __int8 int8_t; +typedef signed __int16 int16_t; +typedef signed __int32 int32_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; #endif -typedef signed __int64 int64_t; +typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ -typedef signed __int64 intptr_t; +typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ -typedef _W64 signed int intptr_t; +typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; +typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types diff --git a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp index 24582ab617..22c5b79096 100644 --- a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.cpp @@ -36,7 +36,7 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, uint8_t *p; for (uint32_t offsetY = y0; offsetY < y1; ++offsetY) { for (uint32_t offsetX = x; offsetX < (x + width); ++offsetX) { - p = buf + (totalWidth * offsetY + offsetX) * 4; + p = buf + (totalWidth * offsetY + offsetX) * 4; *p++ = r; *p++ = g; *p++ = b; @@ -49,7 +49,7 @@ void fillRectWithColor(uint8_t *buf, uint32_t totalWidth, uint32_t totalHeight, namespace cc { CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { HDC hdc = GetDC(_wnd); - _DC = CreateCompatibleDC(hdc); + _DC = CreateCompatibleDC(hdc); ReleaseDC(_wnd, hdc); } @@ -61,15 +61,15 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { deleteBitmap(); return; } - auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); - auto *data = static_cast(malloc(sizeof(uint8_t) * textureSize)); + auto textureSize = static_cast(_bufferWidth * _bufferHeight * 4); + auto *data = static_cast(malloc(sizeof(uint8_t) * textureSize)); memset(data, 0x00, textureSize); _imageData.fastSet(data, textureSize); @@ -158,7 +158,7 @@ void CanvasRenderingContext2DDelegate::fillText(const ccstd::string &text, float return; } - SIZE textSize = {0, 0}; + SIZE textSize = {0, 0}; Point offsetPoint = convertDrawPoint(Point{x, y}, text); drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]); @@ -175,17 +175,17 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measure if (text.empty()) return ccstd::array{0.0f, 0.0f}; - int bufferLen = 0; + int bufferLen = 0; wchar_t *pwszBuffer = CanvasRenderingContext2DDelegate::utf8ToUtf16(text, &bufferLen); - Size size = sizeWithText(pwszBuffer, bufferLen); + Size size = sizeWithText(pwszBuffer, bufferLen); //SE_LOGD("CanvasRenderingContext2DImpl::measureText: %s, %d, %d\n", text.c_str(), size.cx, size.cy); CC_SAFE_DELETE_ARRAY(pwszBuffer); return size; } void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, - float fontSize, - bool bold, + float fontSize, + bool bold, bool /* italic */, bool /* oblique */, bool /* smallCaps */) { @@ -193,17 +193,17 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, _fontName = fontName; _fontSize = static_cast(fontSize); ccstd::string fontPath; - LOGFONTA tFont = {0}; + LOGFONTA tFont = {0}; if (!_fontName.empty()) { // firstly, try to create font from ttf file const auto &fontInfoMap = getFontFamilyNameMap(); - auto iter = fontInfoMap.find(_fontName); + auto iter = fontInfoMap.find(_fontName); if (iter != fontInfoMap.end()) { - fontPath = iter->second; + fontPath = iter->second; ccstd::string tmpFontPath = fontPath; - size_t nFindPos = tmpFontPath.rfind("/"); - tmpFontPath = &tmpFontPath[nFindPos + 1]; - nFindPos = tmpFontPath.rfind("."); + size_t nFindPos = tmpFontPath.rfind("/"); + tmpFontPath = &tmpFontPath[nFindPos + 1]; + nFindPos = tmpFontPath.rfind("."); // IDEA: draw ttf failed if font file name not equal font face name // for example: "DejaVuSansMono-Oblique" not equal "DejaVu Sans Mono" when using DejaVuSansMono-Oblique.ttf _fontName = tmpFontPath.substr(0, nFindPos); @@ -236,7 +236,7 @@ void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, removeCustomFont(); if (!fontPath.empty()) { - _curFontPath = fontPath; + _curFontPath = fontPath; wchar_t *pwszBuffer = utf8ToUtf16(_curFontPath); if (pwszBuffer) { if (AddFontResource(pwszBuffer)) { @@ -291,9 +291,9 @@ wchar_t *CanvasRenderingContext2DDelegate::utf8ToUtf16(const ccstd::string &str, if (str.empty()) { break; } - int nLen = static_cast(str.size()); + int nLen = static_cast(str.size()); int nBufLen = nLen + 1; - pwszBuffer = ccnew wchar_t[nBufLen]; + pwszBuffer = ccnew wchar_t[nBufLen]; CC_BREAK_IF(!pwszBuffer); memset(pwszBuffer, 0, sizeof(wchar_t) * nBufLen); // str.size() not equal actuallyLen for Chinese char @@ -326,7 +326,7 @@ void CanvasRenderingContext2DDelegate::removeCustomFont() { // x, y offset value int CanvasRenderingContext2DDelegate::drawText(const ccstd::string &text, int x, int y) { - int nRet = 0; + int nRet = 0; wchar_t *pwszBuffer = nullptr; do { CC_BREAK_IF(text.empty()); @@ -334,7 +334,7 @@ int CanvasRenderingContext2DDelegate::drawText(const ccstd::string &text, int x, DWORD dwFmt = DT_SINGLELINE | DT_NOPREFIX; int bufferLen = 0; - pwszBuffer = utf8ToUtf16(text, &bufferLen); + pwszBuffer = utf8ToUtf16(text, &bufferLen); Size newSize = sizeWithText(pwszBuffer, bufferLen); @@ -342,7 +342,7 @@ int CanvasRenderingContext2DDelegate::drawText(const ccstd::string &text, int x, RECT rcText = {0}; - rcText.right = static_cast(newSize[0]); + rcText.right = static_cast(newSize[0]); rcText.bottom = static_cast(newSize[1]); LONG offsetX = x; @@ -369,7 +369,7 @@ CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWit do { CC_BREAK_IF(!pszText || nLen <= 0); - RECT rc = {0, 0, 0, 0}; + RECT rc = {0, 0, 0, 0}; DWORD dwCalcFmt = DT_CALCRECT | DT_NOPREFIX; // measure text size @@ -401,7 +401,7 @@ void CanvasRenderingContext2DDelegate::deleteBitmap() { void CanvasRenderingContext2DDelegate::fillTextureData() { do { - auto dataLen = static_cast(_bufferWidth * _bufferHeight * 4); + auto dataLen = static_cast(_bufferWidth * _bufferHeight * 4); auto *dataBuf = static_cast(malloc(sizeof(unsigned char) * dataLen)); CC_BREAK_IF(!dataBuf); unsigned char *imageBuf = _imageData.getBytes(); @@ -410,8 +410,8 @@ void CanvasRenderingContext2DDelegate::fillTextureData() { struct { BITMAPINFOHEADER bmiHeader; - int mask[4]; - } bi = {0}; + int mask[4]; + } bi = {0}; bi.bmiHeader.biSize = sizeof(bi.bmiHeader); CC_BREAK_IF(!GetDIBits(_DC, _bmp, 0, 0, nullptr, (LPBITMAPINFO)&bi, DIB_RGB_COLORS)); @@ -421,14 +421,14 @@ void CanvasRenderingContext2DDelegate::fillTextureData() { GetDIBits(_DC, _bmp, 0, static_cast(_bufferHeight), dataBuf, (LPBITMAPINFO)&bi, DIB_RGB_COLORS); - uint8_t r = static_cast(round(_fillStyle[0] * 255)); - uint8_t g = static_cast(round(_fillStyle[1] * 255)); - uint8_t b = static_cast(round(_fillStyle[2] * 255)); - COLORREF textColor = (b << 16 | g << 8 | r) & 0x00ffffff; - COLORREF *pPixel = nullptr; - COLORREF *pImage = nullptr; - int bufferHeight = static_cast(_bufferHeight); - int bufferWidth = static_cast(_bufferWidth); + uint8_t r = static_cast(round(_fillStyle[0] * 255)); + uint8_t g = static_cast(round(_fillStyle[1] * 255)); + uint8_t b = static_cast(round(_fillStyle[2] * 255)); + COLORREF textColor = (b << 16 | g << 8 | r) & 0x00ffffff; + COLORREF *pPixel = nullptr; + COLORREF *pImage = nullptr; + int bufferHeight = static_cast(_bufferHeight); + int bufferWidth = static_cast(_bufferWidth); for (int y = 0; y < bufferHeight; ++y) { pPixel = (COLORREF *)dataBuf + y * bufferWidth; pImage = (COLORREF *)imageBuf + y * bufferWidth; diff --git a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h index dab38997f4..607f5746ab 100644 --- a/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/win32/modules/CanvasRenderingContext2DDelegate.h @@ -41,76 +41,76 @@ namespace cc { class CC_DLL CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: - using Point = ccstd::array; - using Vec2 = ccstd::array; - using Size = ccstd::array; + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; using Color4F = ccstd::array; - using TextAlign = ICanvasRenderingContext2D::TextAlign; + using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(float r, float g, float b, float a) override; - void setStrokeStyle(float r, float g, float b, float a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(float r, float g, float b, float a) override; + void setStrokeStyle(float r, float g, float b, float a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineCap) override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - void rect(float x, float y, float w, float h) override; - void updateData() override {} + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + void rect(float x, float y, float w, float h) override; + void updateData() override {} private: - static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); - void removeCustomFont(); - int drawText(const ccstd::string &text, int x, int y); - Size sizeWithText(const wchar_t *pszText, int nLen); - void prepareBitmap(int nWidth, int nHeight); - void deleteBitmap(); - void fillTextureData(); + static wchar_t *utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const ccstd::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); ccstd::array convertDrawPoint(Point point, const ccstd::string &text); public: - HDC _DC{nullptr}; + HDC _DC{nullptr}; HBITMAP _bmp{nullptr}; private: - cc::Data _imageData; - HFONT _font{static_cast(GetStockObject(DEFAULT_GUI_FONT))}; - HWND _wnd{nullptr}; - HPEN _hpen; - PAINTSTRUCT _paintStruct; + cc::Data _imageData; + HFONT _font{static_cast(GetStockObject(DEFAULT_GUI_FONT))}; + HWND _wnd{nullptr}; + HPEN _hpen; + PAINTSTRUCT _paintStruct; ccstd::string _curFontPath; - int _savedDC{0}; - float _lineWidth{0.0F}; - float _bufferWidth{0.0F}; - float _bufferHeight{0.0F}; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; - ccstd::string _fontName; - int _fontSize{0}; - Size _textSize; - TextAlign _textAlign{TextAlign::CENTER}; - TextBaseline _textBaseLine{TextBaseline::TOP}; - Color4F _fillStyle; - Color4F _strokeStyle; + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + Color4F _fillStyle; + Color4F _strokeStyle; TEXTMETRIC _tm; }; diff --git a/native/cocos/platform/win32/modules/Screen.cpp b/native/cocos/platform/win32/modules/Screen.cpp index 7db05413a0..9de94ca2d1 100644 --- a/native/cocos/platform/win32/modules/Screen.cpp +++ b/native/cocos/platform/win32/modules/Screen.cpp @@ -35,8 +35,8 @@ int Screen::getDPI() const { static int dpi = -1; if (dpi == -1) { HDC hScreenDC = GetDC(nullptr); - int PixelsX = GetDeviceCaps(hScreenDC, HORZRES); - int MMX = GetDeviceCaps(hScreenDC, HORZSIZE); + int PixelsX = GetDeviceCaps(hScreenDC, HORZRES); + int MMX = GetDeviceCaps(hScreenDC, HORZSIZE); ReleaseDC(nullptr, hScreenDC); dpi = static_cast(254.0f * PixelsX / MMX / 10); } @@ -61,15 +61,15 @@ Vec4 Screen::getSafeAreaEdge() const { bool Screen::isDisplayStats() { se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.profiler.isShowingStats();"; + se::Value ret; + char commandBuf[100] = "cc.profiler.isShowingStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } void Screen::setDisplayStats(bool isShow) { se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();"); se::ScriptEngine::getInstance()->evalString(commandBuf); } diff --git a/native/cocos/platform/win32/modules/Screen.h b/native/cocos/platform/win32/modules/Screen.h index 337ad7daf3..563f4553ea 100644 --- a/native/cocos/platform/win32/modules/Screen.h +++ b/native/cocos/platform/win32/modules/Screen.h @@ -31,11 +31,11 @@ namespace cc { class CC_DLL Screen : public IScreen { public: - int getDPI() const override; - float getDevicePixelRatio() const override; - void setKeepScreenOn(bool value) override; + int getDPI() const override; + float getDevicePixelRatio() const override; + void setKeepScreenOn(bool value) override; Orientation getDeviceOrientation() const override; - Vec4 getSafeAreaEdge() const override; + Vec4 getSafeAreaEdge() const override; /** @brief Get current display stats. @return bool, is displaying stats or not. diff --git a/native/cocos/platform/win32/modules/System.cpp b/native/cocos/platform/win32/modules/System.cpp index 7a5b6738b0..e82bb49888 100644 --- a/native/cocos/platform/win32/modules/System.cpp +++ b/native/cocos/platform/win32/modules/System.cpp @@ -41,7 +41,7 @@ ccstd::string System::getDeviceModel() const { System::LanguageType System::getCurrentLanguage() const { LanguageType ret = LanguageType::ENGLISH; - LCID localeID = GetUserDefaultLCID(); + LCID localeID = GetUserDefaultLCID(); unsigned short primaryLanguageID = localeID & 0xFF; switch (primaryLanguageID) { @@ -108,9 +108,9 @@ System::LanguageType System::getCurrentLanguage() const { } ccstd::string System::getCurrentLanguageCode() const { - LANGID lid = GetUserDefaultUILanguage(); + LANGID lid = GetUserDefaultUILanguage(); const LCID locale_id = MAKELCID(lid, SORT_DEFAULT); - int length = GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, nullptr, 0); + int length = GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, nullptr, 0); char *tempCode = ccnew char[length]; GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, tempCode, length); @@ -121,8 +121,8 @@ ccstd::string System::getCurrentLanguageCode() const { } ccstd::string System::getSystemVersion() const { - char buff[256] = {0}; - HMODULE handle = GetModuleHandleW(L"ntdll.dll"); + char buff[256] = {0}; + HMODULE handle = GetModuleHandleW(L"ntdll.dll"); if (handle) { typedef NTSTATUS(WINAPI * RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); RtlGetVersionPtr getVersionPtr = (RtlGetVersionPtr)GetProcAddress(handle, "RtlGetVersion"); @@ -138,8 +138,8 @@ ccstd::string System::getSystemVersion() const { } bool System::openURL(const ccstd::string &url) { - WCHAR *temp = ccnew WCHAR[url.size() + 1]; - int urlSize = static_cast(url.size() + 1); + WCHAR *temp = ccnew WCHAR[url.size() + 1]; + int urlSize = static_cast(url.size() + 1); MultiByteToWideChar(CP_UTF8, 0, url.c_str(), urlSize, temp, urlSize); HINSTANCE r = ShellExecuteW(NULL, L"open", temp, NULL, NULL, SW_SHOWNORMAL); delete[] temp; diff --git a/native/cocos/platform/win32/modules/SystemWindow.cpp b/native/cocos/platform/win32/modules/SystemWindow.cpp index fc434767a7..55e79ca653 100644 --- a/native/cocos/platform/win32/modules/SystemWindow.cpp +++ b/native/cocos/platform/win32/modules/SystemWindow.cpp @@ -35,7 +35,6 @@ namespace cc { SystemWindow::SystemWindow(IEventDispatch *delegate) : _sdl(std::make_unique(delegate)) { - } SystemWindow::~SystemWindow() { @@ -56,7 +55,7 @@ void SystemWindow::swapWindow() { bool SystemWindow::createWindow(const char *title, int w, int h, int flags) { _sdl->createWindow(title, w, h, flags); - _width = w; + _width = w; _height = h; return true; } @@ -65,7 +64,7 @@ bool SystemWindow::createWindow(const char *title, int x, int y, int w, int h, int flags) { _sdl->createWindow(title, x, y, w, h, flags); - _width = w; + _width = w; _height = h; return true; } diff --git a/native/cocos/platform/win32/modules/SystemWindow.h b/native/cocos/platform/win32/modules/SystemWindow.h index 23087a1156..5dcb87efa2 100644 --- a/native/cocos/platform/win32/modules/SystemWindow.h +++ b/native/cocos/platform/win32/modules/SystemWindow.h @@ -36,15 +36,15 @@ public: explicit SystemWindow(IEventDispatch* delegate); ~SystemWindow() override; - int init(); - void pollEvent(bool* quit); - void swapWindow(); - - bool createWindow(const char* title, - int w, int h, int flags) override; - bool createWindow(const char* title, - int x, int y, int w, - int h, int flags) override; + int init(); + void pollEvent(bool* quit); + void swapWindow(); + + bool createWindow(const char* title, + int w, int h, int flags) override; + bool createWindow(const char* title, + int x, int y, int w, + int h, int flags) override; uintptr_t getWindowHandler() const override; Size getViewSize() const override; /* diff --git a/native/cocos/primitive/Box.cpp b/native/cocos/primitive/Box.cpp index 0693a34f0a..90d5e06ead 100644 --- a/native/cocos/primitive/Box.cpp +++ b/native/cocos/primitive/Box.cpp @@ -67,27 +67,27 @@ IGeometry box(const cc::optional &options) { ccstd::vector corners{Vec3{-hw, -hh, hl}, Vec3{hw, -hh, hl}, Vec3{hw, hh, hl}, Vec3{-hw, hh, hl}, Vec3{hw, -hh, -hl}, Vec3{-hw, -hh, -hl}, Vec3{-hw, hh, -hl}, Vec3{hw, hh, -hl}}; - ccstd::vector positions; - ccstd::vector normals; - ccstd::vector uvs; - ccstd::vector tangents; + ccstd::vector positions; + ccstd::vector normals; + ccstd::vector uvs; + ccstd::vector tangents; ccstd::vector indices; - const Vec3 minPos(-hw, -hh, -hl); - const Vec3 maxPos(hw, hh, hl); - float boundingRadius{static_cast(sqrt(hw * hw + hh * hh + hl * hl))}; + const Vec3 minPos(-hw, -hh, -hl); + const Vec3 maxPos(hw, hh, hl); + float boundingRadius{static_cast(sqrt(hw * hw + hh * hh + hl * hl))}; auto buildPlane = [&](uint32_t side, uint32_t uSegments, uint32_t vSegments) { - float u = 0; - float v = 0; - const auto offset = static_cast(positions.size() / 3); - const ccstd::vector faceAxe = FACE_AXES[side]; - const ccstd::vector faceNormal = FACE_NORMALS[side]; - const ccstd::vector faceTangent = FACE_TANGENTS[side]; + float u = 0; + float v = 0; + const auto offset = static_cast(positions.size() / 3); + const ccstd::vector faceAxe = FACE_AXES[side]; + const ccstd::vector faceNormal = FACE_NORMALS[side]; + const ccstd::vector faceTangent = FACE_TANGENTS[side]; for (index_t iy = 0; iy <= vSegments; ++iy) { for (index_t ix = 0; ix <= uSegments; ++ix) { - u = static_cast(ix) / static_cast(uSegments); - v = static_cast(iy) / static_cast(vSegments); + u = static_cast(ix) / static_cast(uSegments); + v = static_cast(iy) / static_cast(vSegments); Vec3 temp1 = corners[faceAxe[0]].lerp(corners[faceAxe[1]], u); Vec3 temp2 = corners[faceAxe[0]].lerp(corners[faceAxe[2]], v); temp2.subtract(corners[faceAxe[0]]); @@ -108,11 +108,11 @@ IGeometry box(const cc::optional &options) { tangents.emplace_back(faceTangent[3]); if ((ix < uSegments) && (iy < vSegments)) { - auto uSeg1 = uSegments + 1; - const auto a = ix + iy * uSeg1; - const auto b = ix + (iy + 1) * uSeg1; - const auto c = (ix + 1) + (iy + 1) * uSeg1; - const auto d = (ix + 1) + iy * uSeg1; + auto uSeg1 = uSegments + 1; + const auto a = ix + iy * uSeg1; + const auto b = ix + (iy + 1) * uSeg1; + const auto c = (ix + 1) + (iy + 1) * uSeg1; + const auto d = (ix + 1) + iy * uSeg1; indices.emplace_back(offset + a); indices.emplace_back(offset + d); @@ -134,14 +134,14 @@ IGeometry box(const cc::optional &options) { buildPlane(2, ws, ls); // TOP IGeometry info; - info.positions = positions; - info.normals = normals; - info.uvs = uvs; - info.tangents = tangents; + info.positions = positions; + info.normals = normals; + info.uvs = uvs; + info.tangents = tangents; info.boundingRadius = boundingRadius; - info.minPos = minPos; - info.maxPos = maxPos; - info.indices = indices; + info.minPos = minPos; + info.maxPos = maxPos; + info.indices = indices; return info; } diff --git a/native/cocos/primitive/Capsule.cpp b/native/cocos/primitive/Capsule.cpp index c313a64784..29fc8dc174 100644 --- a/native/cocos/primitive/Capsule.cpp +++ b/native/cocos/primitive/Capsule.cpp @@ -28,32 +28,32 @@ namespace cc { IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::optional &opts) { - const float torsoHeight = height - radiusTop - radiusBottom; - const uint32_t sides = opts.has_value() ? opts->sides : 32; + const float torsoHeight = height - radiusTop - radiusBottom; + const uint32_t sides = opts.has_value() ? opts->sides : 32; const uint32_t heightSegments = opts.has_value() ? opts->heightSegments : 32; - const float bottomProp = radiusBottom / height; - const float torProp = torsoHeight / height; - const float topProp = radiusTop / height; + const float bottomProp = radiusBottom / height; + const float torProp = torsoHeight / height; + const float topProp = radiusTop / height; const uint32_t bottomSegments = floor(static_cast(heightSegments) * bottomProp); - const uint32_t topSegments = floor(static_cast(heightSegments) * topProp); - const uint32_t torSegments = floor(static_cast(heightSegments) * torProp); - const float topOffset = torsoHeight + radiusBottom - height / 2; - const float torOffset = radiusBottom - height / 2; - const float bottomOffset = radiusBottom - height / 2; + const uint32_t topSegments = floor(static_cast(heightSegments) * topProp); + const uint32_t torSegments = floor(static_cast(heightSegments) * torProp); + const float topOffset = torsoHeight + radiusBottom - height / 2; + const float torOffset = radiusBottom - height / 2; + const float bottomOffset = radiusBottom - height / 2; const float arc = opts.has_value() ? opts->arc : math::PI_2; // calculate vertex count - ccstd::vector positions; - ccstd::vector normals; - ccstd::vector uvs; + ccstd::vector positions; + ccstd::vector normals; + ccstd::vector uvs; ccstd::vector indices; - const float maxRadius = std::max(radiusTop, radiusBottom); - const Vec3 minPos(-maxRadius, -height / 2, -maxRadius); - const Vec3 maxPos(maxRadius, height / 2, maxRadius); - const float boundingRadius = height / 2; + const float maxRadius = std::max(radiusTop, radiusBottom); + const Vec3 minPos(-maxRadius, -height / 2, -maxRadius); + const Vec3 maxPos(maxRadius, height / 2, maxRadius); + const float boundingRadius = height / 2; - uint32_t index = 0; + uint32_t index = 0; ccstd::vector> indexArray; // ======================= @@ -66,12 +66,12 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o // generate positions, normals and uvs for (uint32_t y = 0; y <= torSegments; y++) { ccstd::vector indexRow; - const float lat = static_cast(y) / static_cast(torSegments); - const float radius = lat * (radiusTop - radiusBottom) + radiusBottom; + const float lat = static_cast(y) / static_cast(torSegments); + const float radius = lat * (radiusTop - radiusBottom) + radiusBottom; for (uint32_t x = 0; x <= sides; ++x) { - const float u = static_cast(x) / static_cast(sides); - const float v = lat * torProp + bottomProp; + const float u = static_cast(x) / static_cast(sides); + const float v = lat * torProp + bottomProp; const float theta = u * arc - (arc / 4); const float sinTheta = sin(theta); @@ -128,12 +128,12 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o auto generateBottom = [&]() { for (uint32_t lat = 0; lat <= bottomSegments; ++lat) { - float theta = static_cast(lat) * math::PI / static_cast(bottomSegments) / 2; + float theta = static_cast(lat) * math::PI / static_cast(bottomSegments) / 2; float sinTheta = sin(theta); float cosTheta = -cos(theta); for (uint32_t lon = 0; lon <= sides; ++lon) { - const float phi = static_cast(lon) * math::PI_2 / static_cast(sides) - math::PI / 2; + const float phi = static_cast(lon) * math::PI_2 / static_cast(sides) - math::PI / 2; const float sinPhi = sin(phi); const float cosPhi = cos(phi); @@ -155,10 +155,10 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o if ((lat < bottomSegments) && (lon < sides)) { const uint32_t seg1 = sides + 1; - const uint32_t a = seg1 * lat + lon; - const uint32_t b = seg1 * (lat + 1) + lon; - const uint32_t c = seg1 * (lat + 1) + lon + 1; - const uint32_t d = seg1 * lat + lon + 1; + const uint32_t a = seg1 * lat + lon; + const uint32_t b = seg1 * (lat + 1) + lon; + const uint32_t c = seg1 * (lat + 1) + lon + 1; + const uint32_t d = seg1 * lat + lon + 1; indices.emplace_back(a); indices.emplace_back(d); @@ -176,19 +176,19 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o auto generateTop = [&]() { for (uint32_t lat = 0; lat <= topSegments; ++lat) { - const float theta = static_cast(lat) * math::PI / static_cast(topSegments) / 2 + math::PI / 2; + const float theta = static_cast(lat) * math::PI / static_cast(topSegments) / 2 + math::PI / 2; const float sinTheta = sin(theta); const float cosTheta = -cos(theta); for (uint32_t lon = 0; lon <= sides; ++lon) { - const float phi = static_cast(lon) * 2 * math::PI / static_cast(sides) - math::PI / 2; + const float phi = static_cast(lon) * 2 * math::PI / static_cast(sides) - math::PI / 2; const float sinPhi = sin(phi); const float cosPhi = cos(phi); - const float x = sinPhi * sinTheta; - const float y = cosTheta; - const float z = cosPhi * sinTheta; - const float u = static_cast(lon) / static_cast(sides); - const float v = static_cast(lat) / static_cast(heightSegments) + (1 - topProp); + const float x = sinPhi * sinTheta; + const float y = cosTheta; + const float z = cosPhi * sinTheta; + const float u = static_cast(lon) / static_cast(sides); + const float v = static_cast(lat) / static_cast(heightSegments) + (1 - topProp); positions.emplace_back(x * radiusTop); positions.emplace_back(y * radiusTop + topOffset); @@ -202,10 +202,10 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o if ((lat < topSegments) && (lon < sides)) { const uint32_t seg1 = sides + 1; - const uint32_t a = seg1 * lat + lon + indexArray[torSegments][sides] + 1; - const uint32_t b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1; - const uint32_t c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1; - const uint32_t d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1; + const uint32_t a = seg1 * lat + lon + indexArray[torSegments][sides] + 1; + const uint32_t b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1; + const uint32_t c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1; + const uint32_t d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1; indices.emplace_back(a); indices.emplace_back(d); @@ -226,13 +226,13 @@ IGeometry capsule(float radiusTop, float radiusBottom, float height, const cc::o generateTop(); IGeometry info; - info.positions = positions; - info.normals = normals; - info.uvs = uvs; + info.positions = positions; + info.normals = normals; + info.uvs = uvs; info.boundingRadius = boundingRadius; - info.minPos = minPos; - info.maxPos = maxPos; - info.indices = indices; + info.minPos = minPos; + info.maxPos = maxPos; + info.indices = indices; return info; } diff --git a/native/cocos/primitive/Capsule.h b/native/cocos/primitive/Capsule.h index 6c6af2f458..8389705d75 100644 --- a/native/cocos/primitive/Capsule.h +++ b/native/cocos/primitive/Capsule.h @@ -36,8 +36,8 @@ namespace cc { struct ICapsuleOptions { uint32_t sides{32}; uint32_t heightSegments{32}; - bool capped{true}; - float arc{math::PI_2}; + bool capped{true}; + float arc{math::PI_2}; }; /** diff --git a/native/cocos/primitive/Circle.cpp b/native/cocos/primitive/Circle.cpp index e10000f9ce..f98a08ba88 100644 --- a/native/cocos/primitive/Circle.cpp +++ b/native/cocos/primitive/Circle.cpp @@ -29,24 +29,24 @@ namespace cc { IGeometry circle(cc::optional &options) { if (!options.has_value()) options = ICircleOptions(); - const uint32_t segments = options->segments; + const uint32_t segments = options->segments; ccstd::vector positions(3 * (segments + 1)); positions[0] = 0; positions[1] = 0; positions[2] = 0; ccstd::vector indices(1 + segments * 2); - indices[0] = 0; + indices[0] = 0; const float step = math::PI * 2 / static_cast(segments); for (uint32_t iSegment = 0; iSegment < segments; ++iSegment) { - const float angle = step * static_cast(iSegment); - const float x = cos(angle); - const float y = sin(angle); - const uint32_t p = (iSegment + 1) * 3; - positions[p + 0] = x; - positions[p + 1] = y; - positions[p + 2] = 0; - const uint32_t i = iSegment * 2; - indices[1 + (i)] = iSegment + 1; + const float angle = step * static_cast(iSegment); + const float x = cos(angle); + const float y = sin(angle); + const uint32_t p = (iSegment + 1) * 3; + positions[p + 0] = x; + positions[p + 1] = y; + positions[p + 2] = 0; + const uint32_t i = iSegment * 2; + indices[1 + (i)] = iSegment + 1; indices[1 + (i + 1)] = iSegment + 2; } if (segments > 0) { @@ -54,12 +54,12 @@ IGeometry circle(cc::optional &options) { } IGeometry info; - info.positions = positions; + info.positions = positions; info.boundingRadius = 1; - info.minPos = Vec3(1, 1, 0); - info.maxPos = Vec3(-1, -1, 0); - info.indices = indices; - info.primitiveMode = gfx::PrimitiveMode::TRIANGLE_FAN; + info.minPos = Vec3(1, 1, 0); + info.maxPos = Vec3(-1, -1, 0); + info.indices = indices; + info.primitiveMode = gfx::PrimitiveMode::TRIANGLE_FAN; return info; } } // namespace cc \ No newline at end of file diff --git a/native/cocos/primitive/Cylinder.cpp b/native/cocos/primitive/Cylinder.cpp index 3be61f614d..d7bb363567 100644 --- a/native/cocos/primitive/Cylinder.cpp +++ b/native/cocos/primitive/Cylinder.cpp @@ -32,11 +32,11 @@ float sign(float v) { } IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc::optional &opts) { - const float halfHeight = height * 0.5F; + const float halfHeight = height * 0.5F; const uint32_t radialSegments = opts.has_value() ? opts->radialSegments : 32; const uint32_t heightSegments = opts.has_value() ? opts->heightSegments : 1; - const bool capped = opts.has_value() ? opts->capped : true; - const float arc = opts.has_value() ? opts->arc : math::PI_2; + const bool capped = opts.has_value() ? opts->capped : true; + const float arc = opts.has_value() ? opts->arc : math::PI_2; uint32_t cntCap = 0; if (capped) { @@ -62,15 +62,15 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: } ccstd::vector indices(indexCount); - ccstd::vector positions(vertCount * 3); - ccstd::vector normals(vertCount * 3); - ccstd::vector uvs(vertCount * 2); - const float maxRadius = std::max(radiusTop, radiusBottom); - const Vec3 minPos(-maxRadius, -halfHeight, -maxRadius); - const Vec3 maxPos(maxRadius, halfHeight, maxRadius); - const float boundingRadius = sqrt(maxRadius * maxRadius + halfHeight * halfHeight); + ccstd::vector positions(vertCount * 3); + ccstd::vector normals(vertCount * 3); + ccstd::vector uvs(vertCount * 2); + const float maxRadius = std::max(radiusTop, radiusBottom); + const Vec3 minPos(-maxRadius, -halfHeight, -maxRadius); + const Vec3 maxPos(maxRadius, halfHeight, maxRadius); + const float boundingRadius = sqrt(maxRadius * maxRadius + halfHeight * halfHeight); - uint32_t index = 0; + uint32_t index = 0; uint32_t indexOffset = 0; // ======================= @@ -86,20 +86,20 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: // generate positions, normals and uvs for (uint32_t y = 0; y <= heightSegments; y++) { ccstd::vector indexRow; - const float v = static_cast(y) / static_cast(heightSegments); + const float v = static_cast(y) / static_cast(heightSegments); // calculate the radius of the current row const float radius = v * r + radiusBottom; for (uint32_t x = 0; x <= radialSegments; ++x) { - const float u = static_cast(x) / static_cast(radialSegments); + const float u = static_cast(x) / static_cast(radialSegments); const float theta = u * arc; const float sinTheta = sin(theta); const float cosTheta = cos(theta); // vertex - positions[3 * index] = radius * sinTheta; + positions[3 * index] = radius * sinTheta; positions[3 * index + 1] = v * height - halfHeight; positions[3 * index + 2] = radius * cosTheta; @@ -107,12 +107,12 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: Vec3 temp1(sinTheta, -slope, cosTheta); temp1.normalize(); - normals[3 * index] = temp1.x; + normals[3 * index] = temp1.x; normals[3 * index + 1] = temp1.y; normals[3 * index + 2] = temp1.z; // uv - uvs[2 * index] = fmod((1 - u) * 2.0F, 1.0F); + uvs[2 * index] = fmod((1 - u) * 2.0F, 1.0F); uvs[2 * index + 1] = v; // save index of vertex in respective row @@ -156,7 +156,7 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: auto generateCap = [&](bool top) { const float radius = top ? radiusTop : radiusBottom; - const float sign = top ? 1 : -1; + const float sign = top ? 1 : -1; // save the index of the first center vertex const uint32_t centerIndexStart = index; @@ -167,17 +167,17 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: for (uint32_t x = 1; x <= radialSegments; ++x) { // vertex - positions[3 * index] = 0; + positions[3 * index] = 0; positions[3 * index + 1] = halfHeight * sign; positions[3 * index + 2] = 0; // // normal - normals[3 * index] = 0; + normals[3 * index] = 0; normals[3 * index + 1] = sign; normals[3 * index + 2] = 0; // uv - uvs[2 * index] = 0.5; + uvs[2 * index] = 0.5; uvs[2 * index + 1] = 0.5; // increase index @@ -190,24 +190,24 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: // now we generate the surrounding positions, normals and uvs for (uint32_t x = 0; x <= radialSegments; ++x) { - const float u = static_cast(x) / static_cast(radialSegments); + const float u = static_cast(x) / static_cast(radialSegments); const float theta = u * arc; const float cosTheta = cos(theta); const float sinTheta = sin(theta); // vertex - positions[3 * index] = radius * sinTheta; + positions[3 * index] = radius * sinTheta; positions[3 * index + 1] = halfHeight * sign; positions[3 * index + 2] = radius * cosTheta; // normal - normals[3 * index] = 0; + normals[3 * index] = 0; normals[3 * index + 1] = sign; normals[3 * index + 2] = 0; // uv - uvs[2 * index] = 0.5F - (sinTheta * 0.5F * sign); + uvs[2 * index] = 0.5F - (sinTheta * 0.5F * sign); uvs[2 * index + 1] = 0.5F + (cosTheta * 0.5F); // increase index @@ -253,13 +253,13 @@ IGeometry cylinder(float radiusTop, float radiusBottom, float height, const cc:: } IGeometry info; - info.positions = positions; - info.normals = normals; - info.uvs = uvs; + info.positions = positions; + info.normals = normals; + info.uvs = uvs; info.boundingRadius = boundingRadius; - info.minPos = minPos; - info.maxPos = maxPos; - info.indices = indices; + info.minPos = minPos; + info.maxPos = maxPos; + info.indices = indices; return info; } diff --git a/native/cocos/primitive/Cylinder.h b/native/cocos/primitive/Cylinder.h index 73448a5727..7a6e5acf9e 100644 --- a/native/cocos/primitive/Cylinder.h +++ b/native/cocos/primitive/Cylinder.h @@ -38,8 +38,8 @@ namespace cc { struct ICylinderOptions : public IGeometryOptions { uint32_t radialSegments{32}; uint32_t heightSegments{1}; - bool capped{true}; - float arc{math::PI_2}; + bool capped{true}; + float arc{math::PI_2}; }; /** diff --git a/native/cocos/primitive/Plane.cpp b/native/cocos/primitive/Plane.cpp index 396aa5f610..d1e3bad0be 100644 --- a/native/cocos/primitive/Plane.cpp +++ b/native/cocos/primitive/Plane.cpp @@ -31,20 +31,20 @@ IGeometry plane(cc::optional options) { if (!options.has_value()) { options = IPlaneOptions(); } - const float width = options->width; - const float length = options->length; + const float width = options->width; + const float length = options->length; const uint32_t uSegments = options->widthSegments; const uint32_t vSegments = options->lengthSegments; const float hw = width * 0.5F; const float hl = length * 0.5F; - ccstd::vector positions; - ccstd::vector uvs; + ccstd::vector positions; + ccstd::vector uvs; ccstd::vector indices; - const Vec3 minPos(-hw, 0, -hl); - const Vec3 maxPos(hw, 0, hl); - const float boundingRadius = sqrt(width * width + length * length); + const Vec3 minPos(-hw, 0, -hl); + const Vec3 maxPos(hw, 0, hl); + const float boundingRadius = sqrt(width * width + length * length); Vec3 c00(-hw, 0, hl); Vec3 c10(hw, 0, hl); @@ -70,10 +70,10 @@ IGeometry plane(cc::optional options) { if ((x < uSegments) && (y < vSegments)) { const uint32_t uSeg1 = uSegments + 1; - const uint32_t a = x + y * uSeg1; - const uint32_t b = x + (y + 1) * uSeg1; - const uint32_t c = (x + 1) + (y + 1) * uSeg1; - const uint32_t d = (x + 1) + y * uSeg1; + const uint32_t a = x + y * uSeg1; + const uint32_t b = x + (y + 1) * uSeg1; + const uint32_t c = (x + 1) + (y + 1) * uSeg1; + const uint32_t d = (x + 1) + y * uSeg1; indices.emplace_back(a); indices.emplace_back(d); @@ -86,14 +86,14 @@ IGeometry plane(cc::optional options) { } IGeometry result; - result.positions = positions; + result.positions = positions; result.boundingRadius = boundingRadius; - result.minPos = minPos; - result.maxPos = maxPos; - result.indices = indices; + result.minPos = minPos; + result.maxPos = maxPos; + result.indices = indices; if (options->includeNormal) { - const uint32_t nVertex = (vSegments + 1) * (uSegments + 1); + const uint32_t nVertex = (vSegments + 1) * (uSegments + 1); ccstd::vector normals(3 * nVertex); for (uint32_t i = 0; i < nVertex; ++i) { normals[i * 3 + 0] = 0; diff --git a/native/cocos/primitive/Primitive.h b/native/cocos/primitive/Primitive.h index d22a46b2a1..02140ec104 100644 --- a/native/cocos/primitive/Primitive.h +++ b/native/cocos/primitive/Primitive.h @@ -43,14 +43,14 @@ namespace cc { using PrimitiveOptions = cc::variant; enum class PrimitiveType { - BOX = 0, - SPHERE = 1, + BOX = 0, + SPHERE = 1, CYLINDER = 2, - CONE = 3, - CAPSULE = 4, - TORUS = 5, - PLANE = 6, - QUAD = 7, + CONE = 3, + CAPSULE = 4, + TORUS = 5, + PLANE = 6, + QUAD = 7, }; /** diff --git a/native/cocos/primitive/PrimitiveDefine.h b/native/cocos/primitive/PrimitiveDefine.h index 2a00624267..3e089910fd 100644 --- a/native/cocos/primitive/PrimitiveDefine.h +++ b/native/cocos/primitive/PrimitiveDefine.h @@ -57,7 +57,7 @@ struct IGeometryOptions { }; struct CustomAttribute { - gfx::Attribute attr; + gfx::Attribute attr; ccstd::vector values; }; @@ -175,7 +175,7 @@ struct IGeometry { struct DynamicCustomAttribute { gfx::Attribute attr; - Float32Array values; + Float32Array values; }; /** diff --git a/native/cocos/primitive/Quad.cpp b/native/cocos/primitive/Quad.cpp index 06d3a6498f..e87a1a2ddf 100644 --- a/native/cocos/primitive/Quad.cpp +++ b/native/cocos/primitive/Quad.cpp @@ -30,11 +30,11 @@ IGeometry quad(cc::optional options) { options = IGeometryOptions(); } IGeometry result; - result.positions = ccstd::vector{-0.5, -0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0}; + result.positions = ccstd::vector{-0.5, -0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0}; result.boundingRadius = sqrt(0.5 * 0.5 + 0.5 * 0.5); - result.minPos = Vec3(-0.5, -0.5, 0); - result.maxPos = Vec3(0.5, 0.5, 0); - result.indices = ccstd::vector{0, 3, 1, 3, 2, 1}; + result.minPos = Vec3(-0.5, -0.5, 0); + result.maxPos = Vec3(0.5, 0.5, 0); + result.indices = ccstd::vector{0, 3, 1, 3, 2, 1}; if (options->includeNormal) { result.normals = ccstd::vector{ 0, 0, 1, diff --git a/native/cocos/primitive/Sphere.cpp b/native/cocos/primitive/Sphere.cpp index 77d2cd1904..7bb30fb85d 100644 --- a/native/cocos/primitive/Sphere.cpp +++ b/native/cocos/primitive/Sphere.cpp @@ -32,21 +32,21 @@ IGeometry sphere(float radius, const cc::optional &opts) { // lat === latitude // lon === longitude - ccstd::vector positions; - ccstd::vector normals; - ccstd::vector uvs; + ccstd::vector positions; + ccstd::vector normals; + ccstd::vector uvs; ccstd::vector indices; - const Vec3 minPos(-radius, -radius, -radius); - const Vec3 maxPos(radius, radius, radius); - const float boundingRadius = radius; + const Vec3 minPos(-radius, -radius, -radius); + const Vec3 maxPos(radius, radius, radius); + const float boundingRadius = radius; for (uint32_t lat = 0; lat <= segments; lat++) { - const float theta = static_cast(lat) * math::PI / static_cast(segments); + const float theta = static_cast(lat) * math::PI / static_cast(segments); const float sinTheta = sin(theta); const float cosTheta = -cos(theta); for (uint32_t lon = 0; lon <= segments; ++lon) { - const float phi = static_cast(lon) * 2.F * math::PI / static_cast(segments) - math::PI / 2.F; + const float phi = static_cast(lon) * 2.F * math::PI / static_cast(segments) - math::PI / 2.F; const float sinPhi = sin(phi); const float cosPhi = cos(phi); @@ -69,10 +69,10 @@ IGeometry sphere(float radius, const cc::optional &opts) { if ((lat < segments) && (lon < segments)) { const uint32_t seg1 = segments + 1; - const uint32_t a = seg1 * lat + lon; - const uint32_t b = seg1 * (lat + 1) + lon; - const uint32_t c = seg1 * (lat + 1) + lon + 1; - const uint32_t d = seg1 * lat + lon + 1; + const uint32_t a = seg1 * lat + lon; + const uint32_t b = seg1 * (lat + 1) + lon; + const uint32_t c = seg1 * (lat + 1) + lon + 1; + const uint32_t d = seg1 * lat + lon + 1; indices.emplace_back(a); indices.emplace_back(d); @@ -86,13 +86,13 @@ IGeometry sphere(float radius, const cc::optional &opts) { } IGeometry info; - info.positions = positions; - info.normals = normals; - info.uvs = uvs; + info.positions = positions; + info.normals = normals; + info.uvs = uvs; info.boundingRadius = boundingRadius; - info.minPos = minPos; - info.maxPos = maxPos; - info.indices = indices; + info.minPos = minPos; + info.maxPos = maxPos; + info.indices = indices; return info; } diff --git a/native/cocos/primitive/Torus.cpp b/native/cocos/primitive/Torus.cpp index eaf649acdd..bafe8e8d23 100644 --- a/native/cocos/primitive/Torus.cpp +++ b/native/cocos/primitive/Torus.cpp @@ -27,17 +27,17 @@ namespace cc { IGeometry torus(float radius, float tube, const cc::optional &opts) { - const uint32_t radialSegments = opts.has_value() ? opts->radialSegments : 32; + const uint32_t radialSegments = opts.has_value() ? opts->radialSegments : 32; const uint32_t tubularSegments = opts.has_value() ? opts->tubularSegments : 32; - const float arc = opts.has_value() ? opts->arc : math::PI_2; + const float arc = opts.has_value() ? opts->arc : math::PI_2; - ccstd::vector positions; - ccstd::vector normals; - ccstd::vector uvs; + ccstd::vector positions; + ccstd::vector normals; + ccstd::vector uvs; ccstd::vector indices; - const Vec3 minPos(-radius - tube, -tube, -radius - tube); - const Vec3 maxPos(radius + tube, tube, radius + tube); - const float boundingRadius = radius + tube; + const Vec3 minPos(-radius - tube, -tube, -radius - tube); + const Vec3 maxPos(radius + tube, tube, radius + tube); + const float boundingRadius = radius + tube; for (uint32_t j = 0; j <= radialSegments; j++) { for (uint32_t i = 0; i <= tubularSegments; i++) { @@ -69,10 +69,10 @@ IGeometry torus(float radius, float tube, const cc::optional &opt if ((i < tubularSegments) && (j < radialSegments)) { const uint32_t seg1 = tubularSegments + 1; - const uint32_t a = seg1 * j + i; - const uint32_t b = seg1 * (j + 1) + i; - const uint32_t c = seg1 * (j + 1) + i + 1; - const uint32_t d = seg1 * j + i + 1; + const uint32_t a = seg1 * j + i; + const uint32_t b = seg1 * (j + 1) + i; + const uint32_t c = seg1 * (j + 1) + i + 1; + const uint32_t d = seg1 * j + i + 1; indices.emplace_back(a); indices.emplace_back(d); @@ -86,13 +86,13 @@ IGeometry torus(float radius, float tube, const cc::optional &opt } IGeometry info; - info.positions = positions; - info.normals = normals; - info.uvs = uvs; + info.positions = positions; + info.normals = normals; + info.uvs = uvs; info.boundingRadius = boundingRadius; - info.minPos = minPos; - info.maxPos = maxPos; - info.indices = indices; + info.minPos = minPos; + info.maxPos = maxPos; + info.indices = indices; return info; } diff --git a/native/cocos/primitive/Torus.h b/native/cocos/primitive/Torus.h index b210bd9958..f6c2722812 100644 --- a/native/cocos/primitive/Torus.h +++ b/native/cocos/primitive/Torus.h @@ -34,7 +34,7 @@ namespace cc { struct ITorusOptions { uint32_t radialSegments{32}; uint32_t tubularSegments{32}; - float arc{math::PI_2}; + float arc{math::PI_2}; }; /** diff --git a/native/cocos/primitive/Transform.cpp b/native/cocos/primitive/Transform.cpp index 151347ae78..b6cda26338 100644 --- a/native/cocos/primitive/Transform.cpp +++ b/native/cocos/primitive/Transform.cpp @@ -101,8 +101,8 @@ IGeometry wireframed(IGeometry &geometry) { } // const offsets = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ] ]; - ccstd::vector> offsets{{0, 1}, {1, 2}, {2, 0}}; - ccstd::vector lines; + ccstd::vector> offsets{{0, 1}, {1, 2}, {2, 0}}; + ccstd::vector lines; ccstd::unordered_map lineIDs; for (uint32_t i = 0; i < indices->size(); i += 3) { for (uint32_t k = 0; k < 3; ++k) { @@ -119,7 +119,7 @@ IGeometry wireframed(IGeometry &geometry) { } } - geometry.indices = lines; + geometry.indices = lines; geometry.primitiveMode = gfx::PrimitiveMode::LINE_LIST; return geometry; diff --git a/native/cocos/profiler/DebugRenderer.cpp b/native/cocos/profiler/DebugRenderer.cpp index 4e7e3f81de..007b7e22ce 100644 --- a/native/cocos/profiler/DebugRenderer.cpp +++ b/native/cocos/profiler/DebugRenderer.cpp @@ -45,8 +45,8 @@ namespace cc { -constexpr uint32_t DEBUG_FONT_SIZE = 10U; -constexpr uint32_t DEBUG_MAX_CHARACTERS = 10000U; +constexpr uint32_t DEBUG_FONT_SIZE = 10U; +constexpr uint32_t DEBUG_MAX_CHARACTERS = 10000U; constexpr uint32_t DEBUG_VERTICES_PER_CHAR = 6U; inline uint32_t getFontIndex(bool bold, bool italic) { @@ -82,8 +82,8 @@ struct DebugVertex { DebugVertex(const Vec2 &pos, const Vec2 &tuv, gfx::Color clr) : position(pos), uv(tuv), color(clr) {} - Vec2 position; - Vec2 uv; + Vec2 position; + Vec2 uv; gfx::Color color; }; @@ -94,7 +94,7 @@ struct DebugBatch { info.bindings.push_back({0, gfx::DescriptorType::SAMPLER_TEXTURE, 1, gfx::ShaderStageFlagBit::FRAGMENT}); descriptorSetLayout = device->createDescriptorSetLayout(info); - descriptorSet = device->createDescriptorSet({descriptorSetLayout}); + descriptorSet = device->createDescriptorSet({descriptorSetLayout}); auto *sampler = device->getSampler({ gfx::Filter::LINEAR, @@ -119,11 +119,11 @@ struct DebugBatch { return bold == b && italic == i && texture == tex; } - std::vector vertices; - bool bold{false}; - bool italic{false}; - gfx::Texture * texture{nullptr}; - gfx::DescriptorSet * descriptorSet{nullptr}; + std::vector vertices; + bool bold{false}; + bool italic{false}; + gfx::Texture *texture{nullptr}; + gfx::DescriptorSet *descriptorSet{nullptr}; gfx::DescriptorSetLayout *descriptorSetLayout{nullptr}; }; @@ -131,7 +131,7 @@ class DebugVertexBuffer { public: inline void init(gfx::Device *device, uint32_t maxVertices, const gfx::AttributeList &attributes) { _maxVertices = maxVertices; - _buffer = device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, + _buffer = device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, static_cast(_maxVertices * sizeof(DebugVertex)), static_cast(sizeof(DebugVertex))}); @@ -154,7 +154,7 @@ public: } const auto count = std::min(static_cast(vertices.size()), _maxVertices); - const auto size = static_cast(count * sizeof(DebugVertex)); + const auto size = static_cast(count * sizeof(DebugVertex)); _buffer->update(&vertices[0], size); } @@ -193,10 +193,10 @@ public: } private: - uint32_t _maxVertices{0U}; + uint32_t _maxVertices{0U}; std::vector _batches; - gfx::Buffer * _buffer{nullptr}; - gfx::InputAssembler * _inputAssembler{nullptr}; + gfx::Buffer *_buffer{nullptr}; + gfx::InputAssembler *_inputAssembler{nullptr}; friend class DebugRenderer; }; @@ -232,14 +232,14 @@ void DebugRenderer::activate(gfx::Device *device, const DebugRendererInfo &info) _buffer = ccnew DebugVertexBuffer(); _buffer->init(_device, info.maxCharacters * DEBUG_VERTICES_PER_CHAR, ATTRIBUTES); - const auto *window = CC_CURRENT_ENGINE()->getInterface(); - const auto width = window->getViewSize().x * Device::getDevicePixelRatio(); - auto fontSize = static_cast(width / 800.0F * info.fontSize); - fontSize = fontSize < 10U ? 10U : (fontSize > 20U ? 20U : fontSize); + const auto *window = CC_CURRENT_ENGINE()->getInterface(); + const auto width = window->getViewSize().x * Device::getDevicePixelRatio(); + auto fontSize = static_cast(width / 800.0F * info.fontSize); + fontSize = fontSize < 10U ? 10U : (fontSize > 20U ? 20U : fontSize); for (auto i = 0U; i < _fonts.size(); i++) { - _fonts[i].font = ccnew FreeTypeFont(getFontPath(i)); - _fonts[i].face = _fonts[i].font->createFace(FontFaceInfo(fontSize)); + _fonts[i].font = ccnew FreeTypeFont(getFontPath(i)); + _fonts[i].face = _fonts[i].font->createFace(FontFaceInfo(fontSize)); _fonts[i].invTextureSize = {1.0F / _fonts[i].face->getTextureWidth(), 1.0F / _fonts[i].face->getTextureHeight()}; } } @@ -252,7 +252,7 @@ void DebugRenderer::render(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdB _buffer->update(); - const auto &pass = sceneData->getDebugRendererPass(); + const auto &pass = sceneData->getDebugRendererPass(); const auto &shader = sceneData->getDebugRendererShader(); auto *pso = pipeline::PipelineStateManager::getOrCreatePipelineState(pass, shader, _buffer->_inputAssembler, renderPass); @@ -289,24 +289,24 @@ void DebugRenderer::destroy() { } void DebugRenderer::addText(const ccstd::string &text, const Vec2 &screenPos, const DebugTextInfo &info) { - uint32_t index = getFontIndex(info.bold, info.italic); - auto & fontInfo = _fonts[index]; - auto * face = fontInfo.face; + uint32_t index = getFontIndex(info.bold, info.italic); + auto &fontInfo = _fonts[index]; + auto *face = fontInfo.face; if (!_buffer || !face || text.empty()) { return; } std::u32string unicodeText; - bool success = StringUtils::UTF8ToUTF32(text, unicodeText); + bool success = StringUtils::UTF8ToUTF32(text, unicodeText); if (!success) { return; } - auto offsetX = screenPos.x; - auto offsetY = screenPos.y; - const auto scale = info.scale; - const auto lineHeight = face->getLineHeight() * scale; + auto offsetX = screenPos.x; + auto offsetY = screenPos.y; + const auto scale = info.scale; + const auto lineHeight = face->getLineHeight() * scale; const auto &invTextureSize = fontInfo.invTextureSize; for (char32_t code : unicodeText) { @@ -360,8 +360,8 @@ void DebugRenderer::addText(const ccstd::string &text, const Vec2 &screenPos, co } uint32_t DebugRenderer::getLineHeight(bool bold, bool italic) { - uint32_t index = getFontIndex(bold, italic); - auto & fontInfo = _fonts[index]; + uint32_t index = getFontIndex(bold, italic); + auto &fontInfo = _fonts[index]; if (fontInfo.face) { return fontInfo.face->getLineHeight(); diff --git a/native/cocos/profiler/DebugRenderer.h b/native/cocos/profiler/DebugRenderer.h index 814dbeac90..885de6e18e 100644 --- a/native/cocos/profiler/DebugRenderer.h +++ b/native/cocos/profiler/DebugRenderer.h @@ -58,32 +58,32 @@ struct DebugTextInfo { DebugTextInfo() = default; gfx::Color color{1.0F, 1.0F, 1.0F, 1.0F}; - bool bold{false}; - bool italic{false}; - bool shadow{false}; - uint32_t shadowThickness{1U}; + bool bold{false}; + bool italic{false}; + bool shadow{false}; + uint32_t shadowThickness{1U}; gfx::Color shadowColor{0.0F, 0.0F, 0.0F, 1.0F}; - float scale{1.0F}; + float scale{1.0F}; }; struct DebugFontInfo { - Font * font{nullptr}; + Font *font{nullptr}; FontFace *face{nullptr}; - Vec2 invTextureSize{0.0F, 0.0F}; + Vec2 invTextureSize{0.0F, 0.0F}; }; constexpr uint32_t DEBUG_FONT_COUNT = 4U; -using DebugFontArray = ccstd::array; +using DebugFontArray = ccstd::array; class DebugRenderer { public: DebugRenderer(const DebugRenderer &) = delete; - DebugRenderer(DebugRenderer &&) = delete; + DebugRenderer(DebugRenderer &&) = delete; DebugRenderer &operator=(const DebugRenderer &) = delete; DebugRenderer &operator=(DebugRenderer &&) = delete; static DebugRenderer *getInstance(); - static void destroyInstance(); + static void destroyInstance(); void activate(gfx::Device *device, const DebugRendererInfo &info = DebugRendererInfo()); void render(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, pipeline::PipelineSceneData *sceneData); @@ -92,16 +92,16 @@ public: void addText(const ccstd::string &text, const Vec2 &screenPos, const DebugTextInfo &info = DebugTextInfo()); private: - DebugRenderer() = default; + DebugRenderer() = default; ~DebugRenderer() = default; static void addQuad(DebugBatch &batch, const Vec4 &rect, const Vec4 &uv, gfx::Color color); - uint32_t getLineHeight(bool bold = false, bool italic = false); + uint32_t getLineHeight(bool bold = false, bool italic = false); static DebugRenderer *instance; - gfx::Device * _device{nullptr}; - DebugVertexBuffer * _buffer{nullptr}; - DebugFontArray _fonts; + gfx::Device *_device{nullptr}; + DebugVertexBuffer *_buffer{nullptr}; + DebugFontArray _fonts; friend class Profiler; }; diff --git a/native/cocos/profiler/GameStats.h b/native/cocos/profiler/GameStats.h index c5c63e9e62..d65da9a94b 100644 --- a/native/cocos/profiler/GameStats.h +++ b/native/cocos/profiler/GameStats.h @@ -70,8 +70,8 @@ struct TimeCounter { inline void onFrameBegin() { // reset current frame - max = 0U; - time = 0U; + max = 0U; + time = 0U; count = 0U; } @@ -90,18 +90,18 @@ struct TimeCounter { inline void onIntervalUpdate() { // update display data - frameMaxDisplay = intervalMax; - frameTimeDisplay = framesOfInterval ? intervalTime / framesOfInterval : 0U; + frameMaxDisplay = intervalMax; + frameTimeDisplay = framesOfInterval ? intervalTime / framesOfInterval : 0U; frameCountDisplay = framesOfInterval ? intervalCount / framesOfInterval : 0U; - totalMaxDisplay = totalMax; - totalTimeDisplay = totalTime; + totalMaxDisplay = totalMax; + totalTimeDisplay = totalTime; totalCountDisplay = totalCount; // reset interval data - intervalMax = 0U; - intervalTime = 0U; - intervalCount = 0U; + intervalMax = 0U; + intervalTime = 0U; + intervalCount = 0U; framesOfInterval = 0U; } }; @@ -112,9 +112,9 @@ struct MemoryCounter { uint64_t totalMax{0U}; // max memory during whole time inline void operator=(uint64_t value) { - total = value; + total = value; totalMax = std::max(totalMax, total); - count = 1; + count = 1; } inline void operator+=(uint64_t value) { @@ -135,7 +135,7 @@ struct ObjectCounter { uint32_t totalMax{0U}; // max count during whole time inline void operator=(uint32_t value) { - total = value; + total = value; totalMax = std::max(totalMax, total); } @@ -159,19 +159,19 @@ struct ObjectCounter { // assume update in main thread only. struct CoreStats { - uint32_t fps{0U}; - float frameTime{0.0F}; + uint32_t fps{0U}; + float frameTime{0.0F}; ccstd::string gfx; - bool multiThread{true}; - bool occlusionQuery{false}; - bool shadowMap{false}; - uint32_t screenWidth{0U}; - uint32_t screenHeight{0U}; + bool multiThread{true}; + bool occlusionQuery{false}; + bool shadowMap{false}; + uint32_t screenWidth{0U}; + uint32_t screenHeight{0U}; }; struct MemoryStats { // memory stats - std::mutex mutex; + std::mutex mutex; ccstd::unordered_map memories; inline void update(const ccstd::string &name, uint64_t value) { diff --git a/native/cocos/profiler/Profiler.cpp b/native/cocos/profiler/Profiler.cpp index afe52e756b..a89239911c 100644 --- a/native/cocos/profiler/Profiler.cpp +++ b/native/cocos/profiler/Profiler.cpp @@ -51,19 +51,19 @@ public: : _parent(parent), _name(std::move(name)) {} ~ProfilerBlock(); - inline void begin() { _timer.reset(); } - inline void end() { _item += _timer.getMicroseconds(); } + inline void begin() { _timer.reset(); } + inline void end() { _item += _timer.getMicroseconds(); } ProfilerBlock *getOrCreateChild(const ccstd::string &name); - void onFrameBegin(); - void onFrameEnd(); - void doIntervalUpdate(); + void onFrameBegin(); + void onFrameEnd(); + void doIntervalUpdate(); private: - ProfilerBlock * _parent{nullptr}; + ProfilerBlock *_parent{nullptr}; std::vector _children; - utils::Timer _timer; - ccstd::string _name; - TimeCounter _item; + utils::Timer _timer; + ccstd::string _name; + TimeCounter _item; friend class Profiler; }; @@ -115,7 +115,7 @@ void ProfilerBlock::doIntervalUpdate() { //NOLINT(misc-no-recursion) struct ProfilerBlockDepth { ProfilerBlock *block{nullptr}; - uint32_t depth{0U}; + uint32_t depth{0U}; }; /** @@ -139,8 +139,8 @@ void Profiler::destroyInstance() { Profiler::Profiler() { _mainThreadId = std::this_thread::get_id(); - _root = ccnew ProfilerBlock(nullptr, "MainThread"); - _current = _root; + _root = ccnew ProfilerBlock(nullptr, "MainThread"); + _current = _root; } Profiler::~Profiler() { @@ -197,21 +197,21 @@ void Profiler::update() { } void Profiler::doIntervalUpdate() { - const auto *pipeline = Root::getInstance()->getPipeline(); - const auto *root = Root::getInstance(); + const auto *pipeline = Root::getInstance()->getPipeline(); + const auto *root = Root::getInstance(); const auto *sceneData = pipeline->getPipelineSceneData(); - const auto *shadows = sceneData->getShadows(); - const auto *window = CC_CURRENT_ENGINE()->getInterface(); - const auto viewSize = window->getViewSize() * Device::getDevicePixelRatio(); + const auto *shadows = sceneData->getShadows(); + const auto *window = CC_CURRENT_ENGINE()->getInterface(); + const auto viewSize = window->getViewSize() * Device::getDevicePixelRatio(); - _coreStats.fps = root->getFps(); - _coreStats.frameTime = root->getFrameTime() * 1000.0F; - _coreStats.gfx = gfx::DeviceManager::getGFXName(); - _coreStats.multiThread = gfx::DeviceManager::isDetachDeviceThread(); + _coreStats.fps = root->getFps(); + _coreStats.frameTime = root->getFrameTime() * 1000.0F; + _coreStats.gfx = gfx::DeviceManager::getGFXName(); + _coreStats.multiThread = gfx::DeviceManager::isDetachDeviceThread(); _coreStats.occlusionQuery = pipeline->isOcclusionQueryEnabled(); - _coreStats.shadowMap = shadows != nullptr && shadows->isEnabled() && shadows->getType() == scene::ShadowType::SHADOW_MAP; - _coreStats.screenWidth = static_cast(viewSize.x); - _coreStats.screenHeight = static_cast(viewSize.y); + _coreStats.shadowMap = shadows != nullptr && shadows->isEnabled() && shadows->getType() == scene::ShadowType::SHADOW_MAP; + _coreStats.screenWidth = static_cast(viewSize.x); + _coreStats.screenHeight = static_cast(viewSize.y); } void Profiler::doFrameUpdate() { @@ -227,19 +227,19 @@ void Profiler::doFrameUpdate() { } void Profiler::printStats() { - auto * renderer = CC_DEBUG_RENDERER; - const auto *window = CC_CURRENT_ENGINE()->getInterface(); - const auto viewSize = window->getViewSize() * Device::getDevicePixelRatio(); - const auto width = viewSize.x; - const auto lineHeight = renderer->getLineHeight(); - const auto columnWidth = width / 12.0F; // divide column numbers - const auto leftOffset = width * 0.01F; - float lines = 1.0F; - float leftLines = 1.0F; - float rightLines = 1.0F; + auto *renderer = CC_DEBUG_RENDERER; + const auto *window = CC_CURRENT_ENGINE()->getInterface(); + const auto viewSize = window->getViewSize() * Device::getDevicePixelRatio(); + const auto width = viewSize.x; + const auto lineHeight = renderer->getLineHeight(); + const auto columnWidth = width / 12.0F; // divide column numbers + const auto leftOffset = width * 0.01F; + float lines = 1.0F; + float leftLines = 1.0F; + float rightLines = 1.0F; - const DebugTextInfo coreInfo = {{1.0F, 0.0F, 0.0F, 1.0F}, true, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}; - const DebugTextInfo titleInfo = {{1.0F, 1.0F, 0.0F, 1.0F}, true, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}; + const DebugTextInfo coreInfo = {{1.0F, 0.0F, 0.0F, 1.0F}, true, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}; + const DebugTextInfo titleInfo = {{1.0F, 1.0F, 0.0F, 1.0F}, true, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}; const DebugTextInfo textInfos[2] = { {{1.0F, 1.0F, 1.0F, 1.0F}, false, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}, {{0.8F, 0.8F, 0.8F, 1.0F}, false, false, true, 1U, {0.0F, 0.0F, 0.0F, 1.0F}, 1.0F}, @@ -247,7 +247,7 @@ void Profiler::printStats() { if (isEnabled(ShowOption::CORE_STATS)) { float coreOffset = columnWidth * 2.0F; - auto coreStats = StringUtil::format( + auto coreStats = StringUtil::format( "FPS: %u " "Frame: %.1fms " "GFX: %s " @@ -272,9 +272,9 @@ void Profiler::printStats() { } if (isEnabled(ShowOption::OBJECT_STATS)) { - leftLines = lines; - float yOffset = lineHeight * leftLines; - float countOffset = columnWidth * 2; + leftLines = lines; + float yOffset = lineHeight * leftLines; + float countOffset = columnWidth * 2; float totalMaxOffset = columnWidth * 3; renderer->addText("ObjectStats", {leftOffset, yOffset}, titleInfo); @@ -284,7 +284,7 @@ void Profiler::printStats() { for (auto &iter : _objectStats.renders) { auto &item = iter.second; - yOffset = lineHeight * leftLines; + yOffset = lineHeight * leftLines; renderer->addText(iter.first, {leftOffset, yOffset}, textInfos[0]); renderer->addText(StringUtil::format("%u", item.lastTotal), {countOffset, yOffset}, textInfos[0]); @@ -294,7 +294,7 @@ void Profiler::printStats() { for (auto &iter : _objectStats.objects) { auto &item = iter.second; - yOffset = lineHeight * leftLines; + yOffset = lineHeight * leftLines; renderer->addText(iter.first, {leftOffset, yOffset}, textInfos[0]); renderer->addText(StringUtil::format("%u", item.lastTotal), {countOffset, yOffset}, textInfos[0]); @@ -306,11 +306,11 @@ void Profiler::printStats() { } if (isEnabled(ShowOption::MEMORY_STATS)) { - rightLines = lines; - float yOffset = lineHeight * rightLines; - float memoryOffset = width * 0.5F; - float totalOffset = memoryOffset + columnWidth * 2; - float countOffset = memoryOffset + columnWidth * 3; + rightLines = lines; + float yOffset = lineHeight * rightLines; + float memoryOffset = width * 0.5F; + float totalOffset = memoryOffset + columnWidth * 2; + float countOffset = memoryOffset + columnWidth * 3; float totalMaxOffset = memoryOffset + columnWidth * 4; renderer->addText("MemoryStats", {memoryOffset, yOffset}, titleInfo); @@ -327,7 +327,7 @@ void Profiler::printStats() { for (auto &iter : memories) { auto &item = iter.second; - yOffset = lineHeight * rightLines; + yOffset = lineHeight * rightLines; renderer->addText(iter.first, {memoryOffset, yOffset}, textInfos[0]); renderer->addText(StatsUtil::formatBytes(item.total), {totalOffset, yOffset}, textInfos[0]); @@ -340,15 +340,15 @@ void Profiler::printStats() { } if (isEnabled(ShowOption::PERFORMANCE_STATS)) { - lines = std::max(leftLines, rightLines); - float yOffset = lineHeight * lines; - float frameTimeOffset = columnWidth * 4; - float frameMaxOffset = columnWidth * 5; - float frameCountOffset = columnWidth * 6; + lines = std::max(leftLines, rightLines); + float yOffset = lineHeight * lines; + float frameTimeOffset = columnWidth * 4; + float frameMaxOffset = columnWidth * 5; + float frameCountOffset = columnWidth * 6; float frameAgerageOffset = columnWidth * 7; - float totalTimeOffset = columnWidth * 8; - float totalMaxOffset = columnWidth * 9; - float totalCountOffset = columnWidth * 10; + float totalTimeOffset = columnWidth * 8; + float totalMaxOffset = columnWidth * 9; + float totalCountOffset = columnWidth * 10; float totalAgerageOffset = columnWidth * 11; renderer->addText("PerformanceStats", {leftOffset, yOffset}, titleInfo); @@ -369,9 +369,9 @@ void Profiler::printStats() { uint32_t colorIndex = 0; for (auto &iter : blocks) { - yOffset = lineHeight * lines; + yOffset = lineHeight * lines; const auto *block = iter.block; - const auto &item = block->_item; + const auto &item = block->_item; uint64_t frameAverageDisplay = item.frameCountDisplay ? item.frameTimeDisplay / item.frameCountDisplay : 0U; uint64_t totalAverageDisplay = item.totalCountDisplay ? item.totalTimeDisplay / item.totalCountDisplay : 0U; diff --git a/native/cocos/profiler/Profiler.h b/native/cocos/profiler/Profiler.h index b9478a0593..39fda15684 100644 --- a/native/cocos/profiler/Profiler.h +++ b/native/cocos/profiler/Profiler.h @@ -36,11 +36,11 @@ class ProfilerBlock; struct ProfilerBlockDepth; enum class ShowOption : uint32_t { - CORE_STATS = 0x01, - MEMORY_STATS = 0x02, - OBJECT_STATS = 0x04, + CORE_STATS = 0x01, + MEMORY_STATS = 0x02, + OBJECT_STATS = 0x04, PERFORMANCE_STATS = 0x08, - ALL = CORE_STATS | MEMORY_STATS | OBJECT_STATS | PERFORMANCE_STATS, + ALL = CORE_STATS | MEMORY_STATS | OBJECT_STATS | PERFORMANCE_STATS, }; /** @@ -49,12 +49,12 @@ enum class ShowOption : uint32_t { class Profiler { public: Profiler(const Profiler &) = delete; - Profiler(Profiler &&) = delete; + Profiler(Profiler &&) = delete; Profiler &operator=(const Profiler &) = delete; Profiler &operator=(Profiler &&) = delete; static Profiler *getInstance(); - static void destroyInstance(); + static void destroyInstance(); void setEnable(ShowOption option, bool b = true); bool isEnabled(ShowOption option) const; @@ -63,7 +63,7 @@ public: void endFrame(); void update(); - inline bool isMainThread() const { return _mainThreadId == std::this_thread::get_id(); } + inline bool isMainThread() const { return _mainThreadId == std::this_thread::get_id(); } inline MemoryStats &getMemoryStats() { return _memoryStats; } inline ObjectStats &getObjectStats() { return _objectStats; } @@ -71,23 +71,23 @@ private: Profiler(); ~Profiler(); - void doIntervalUpdate(); + void doIntervalUpdate(); static void doFrameUpdate(); - void printStats(); + void printStats(); void beginBlock(const ccstd::string &name); void endBlock(); void gatherBlocks(ProfilerBlock *parent, uint32_t depth, std::vector &outBlocks); static Profiler *instance; - uint32_t _options{static_cast(ShowOption::ALL)}; - utils::Timer _timer; - CoreStats _coreStats; - MemoryStats _memoryStats; - ObjectStats _objectStats; - ProfilerBlock * _root{nullptr}; - ProfilerBlock * _current{nullptr}; - std::thread::id _mainThreadId; + uint32_t _options{static_cast(ShowOption::ALL)}; + utils::Timer _timer; + CoreStats _coreStats; + MemoryStats _memoryStats; + ObjectStats _objectStats; + ProfilerBlock *_root{nullptr}; + ProfilerBlock *_current{nullptr}; + std::thread::id _mainThreadId; friend class AutoProfiler; }; diff --git a/native/cocos/renderer/core/MaterialInstance.cpp b/native/cocos/renderer/core/MaterialInstance.cpp index 0254711886..cfebda62d0 100644 --- a/native/cocos/renderer/core/MaterialInstance.cpp +++ b/native/cocos/renderer/core/MaterialInstance.cpp @@ -63,7 +63,7 @@ bool MaterialInstance::destroy() { ccstd::vector> MaterialInstance::createPasses() { ccstd::vector> passes; - auto & parentPasses = _parent->getPasses(); + auto &parentPasses = _parent->getPasses(); passes.reserve(parentPasses->size()); for (auto &parentPass : *parentPasses) { diff --git a/native/cocos/renderer/core/PassInstance.cpp b/native/cocos/renderer/core/PassInstance.cpp index 222f351756..77cadd3a16 100644 --- a/native/cocos/renderer/core/PassInstance.cpp +++ b/native/cocos/renderer/core/PassInstance.cpp @@ -35,13 +35,13 @@ namespace cc { PassInstance::PassInstance(scene::Pass *parent, MaterialInstance *owner) : Super(parent->getRoot()), _parent(parent), _owner(owner) { doInit(_parent->getPassInfoFull()); for (const auto &b : _shaderInfo->blocks) { - scene::IBlockRef & block = _blocks[b.binding]; + scene::IBlockRef &block = _blocks[b.binding]; const scene::IBlockRef &parentBlock = _parent->getBlocks()[b.binding]; CC_ASSERT(block.count == parentBlock.count); memcpy(block.data, parentBlock.data, parentBlock.count * 4); } - _rootBufferDirty = true; + _rootBufferDirty = true; gfx::DescriptorSet *parentDescriptorSet = _parent->getDescriptorSet(); for (const auto &samplerTexture : _shaderInfo->samplerTextures) { for (uint32_t i = 0; i < samplerTexture.count; ++i) { @@ -89,8 +89,8 @@ void PassInstance::endChangeStatesSilently() { void PassInstance::syncBatchingScheme() { _defines["USE_INSTANCING"] = false; - _defines["USE_BATCHING"] = false; - _batchingScheme = scene::BatchingSchemes::NONE; + _defines["USE_BATCHING"] = false; + _batchingScheme = scene::BatchingSchemes::NONE; } void PassInstance::onStateChange() { diff --git a/native/cocos/renderer/core/PassInstance.h b/native/cocos/renderer/core/PassInstance.h index dd89ea8c67..dddcdc8d4f 100644 --- a/native/cocos/renderer/core/PassInstance.h +++ b/native/cocos/renderer/core/PassInstance.h @@ -78,7 +78,7 @@ private: IntrusivePtr _parent; // Weak reference. MaterialInstance *_owner{nullptr}; - bool _dontNotify{false}; + bool _dontNotify{false}; }; } // namespace cc diff --git a/native/cocos/renderer/core/PassUtils.cpp b/native/cocos/renderer/core/PassUtils.cpp index 2efb31fc2b..b426603eda 100644 --- a/native/cocos/renderer/core/PassUtils.cpp +++ b/native/cocos/renderer/core/PassUtils.cpp @@ -104,8 +104,8 @@ const ccstd::unordered_map type2writer = { CC_LOG_ERROR("type2writer unknown type"); }}, {gfx::Type::INT, [](float *a, const MaterialProperty &v, index_t idx) { - const int32_t *p = cc::get_if(&v); - const float * pFloat = nullptr; + const int32_t *p = cc::get_if(&v); + const float *pFloat = nullptr; if (p != nullptr) { a[idx] = static_cast(*p); } else { @@ -119,26 +119,26 @@ const ccstd::unordered_map type2writer = { {gfx::Type::INT2, [](float *a, const MaterialProperty &v, index_t idx) { const auto *p = cc::get_if(&v); CC_ASSERT(p != nullptr); - a[idx] = p->x; + a[idx] = p->x; a[idx + 1] = p->y; }}, {gfx::Type::INT3, [](float *a, const MaterialProperty &v, index_t idx) { const auto *p = cc::get_if(&v); CC_ASSERT(p != nullptr); - a[idx] = p->x; + a[idx] = p->x; a[idx + 1] = p->y; a[idx + 2] = p->z; }}, {gfx::Type::INT4, [](float *a, const MaterialProperty &v, index_t idx) { const auto *p = cc::get_if(&v); CC_ASSERT(p != nullptr); - a[idx] = p->x; + a[idx] = p->x; a[idx + 1] = p->y; a[idx + 2] = p->z; a[idx + 3] = p->w; }}, {gfx::Type::FLOAT, [](float *a, const MaterialProperty &v, index_t idx) { - const float * p = cc::get_if(&v); + const float *p = cc::get_if(&v); const int32_t *pInt = nullptr; if (p != nullptr) { a[idx] = *p; @@ -153,20 +153,20 @@ const ccstd::unordered_map type2writer = { {gfx::Type::FLOAT2, [](float *a, const MaterialProperty &v, index_t idx) { const auto *p = cc::get_if(&v); CC_ASSERT(p != nullptr); - a[idx] = p->x; + a[idx] = p->x; a[idx + 1] = p->y; }}, {gfx::Type::FLOAT3, [](float *a, const MaterialProperty &v, index_t idx) { if (cc::holds_alternative(v)) { const auto &vec3 = cc::get(v); - a[idx] = vec3.x; - a[idx + 1] = vec3.y; - a[idx + 2] = vec3.z; + a[idx] = vec3.x; + a[idx + 1] = vec3.y; + a[idx + 2] = vec3.z; } else if (cc::holds_alternative(v)) { const auto &vec4 = cc::get(v); - a[idx] = vec4.x; - a[idx + 1] = vec4.y; - a[idx + 2] = vec4.z; + a[idx] = vec4.x; + a[idx + 1] = vec4.y; + a[idx + 2] = vec4.z; } else { CC_ASSERT(false); } @@ -174,23 +174,23 @@ const ccstd::unordered_map type2writer = { {gfx::Type::FLOAT4, [](float *a, const MaterialProperty &v, index_t idx) { if (cc::holds_alternative(v)) { const auto &vec4 = cc::get(v); - a[idx] = vec4.x; - a[idx + 1] = vec4.y; - a[idx + 2] = vec4.z; - a[idx + 3] = vec4.w; + a[idx] = vec4.x; + a[idx + 1] = vec4.y; + a[idx + 2] = vec4.z; + a[idx + 3] = vec4.w; } else if (cc::holds_alternative(v)) { const auto &color = cc::get(v); - Vec4 colorFloat{color.toVec4()}; - a[idx] = colorFloat.x; + Vec4 colorFloat{color.toVec4()}; + a[idx] = colorFloat.x; a[idx + 1] = colorFloat.y; a[idx + 2] = colorFloat.z; a[idx + 3] = colorFloat.w; } else if (cc::holds_alternative(v)) { const auto &quat = cc::get(v); - a[idx] = quat.x; - a[idx + 1] = quat.y; - a[idx + 2] = quat.z; - a[idx + 3] = quat.w; + a[idx] = quat.x; + a[idx + 1] = quat.y; + a[idx + 2] = quat.z; + a[idx + 3] = quat.w; } else { CC_ASSERT(false); } @@ -256,7 +256,7 @@ bool overrideMacros(MacroRecord &target, const MacroRecord &source) { for (const auto &p : source) { if (target[p.first] != p.second) { target[p.first] = p.second; - isDifferent = true; + isDifferent = true; } } return isDifferent; @@ -264,7 +264,7 @@ bool overrideMacros(MacroRecord &target, const MacroRecord &source) { MaterialProperty toMaterialProperty(gfx::Type type, const ccstd::vector &vec) { MaterialProperty ret; - size_t size = vec.size(); + size_t size = vec.size(); switch (type) { case gfx::Type::FLOAT: diff --git a/native/cocos/renderer/core/PassUtils.h b/native/cocos/renderer/core/PassUtils.h index 23dacc0655..fb9c2cb27d 100644 --- a/native/cocos/renderer/core/PassUtils.h +++ b/native/cocos/renderer/core/PassUtils.h @@ -46,10 +46,10 @@ namespace cc { class TextureBase; -constexpr uint32_t TYPE_MASK = 0xfc000000; // 6 bits => 64 types +constexpr uint32_t TYPE_MASK = 0xfc000000; // 6 bits => 64 types constexpr uint32_t BINDING_MASK = 0x03f00000; // 6 bits => 64 bindings -constexpr uint32_t COUNT_MASK = 0x000ff000; // 8 bits => 256 vectors -constexpr uint32_t OFFSET_MASK = 0x00000fff; // 12 bits => 1024 vectors +constexpr uint32_t COUNT_MASK = 0x000ff000; // 8 bits => 256 vectors +constexpr uint32_t OFFSET_MASK = 0x00000fff; // 12 bits => 1024 vectors constexpr uint32_t genHandle(uint32_t binding, gfx::Type type, uint32_t count, uint32_t offset = 0) { return ((static_cast(type) << 26) & TYPE_MASK) | @@ -59,10 +59,10 @@ constexpr uint32_t genHandle(uint32_t binding, gfx::Type type, uint32_t count, u } constexpr gfx::Type getTypeFromHandle(uint32_t handle) { return static_cast((handle & TYPE_MASK) >> 26); } -constexpr uint32_t getBindingFromHandle(uint32_t handle) { return (handle & BINDING_MASK) >> 20; } -constexpr uint32_t getCountFromHandle(uint32_t handle) { return (handle & COUNT_MASK) >> 12; } -constexpr uint32_t getOffsetFromHandle(uint32_t handle) { return (handle & OFFSET_MASK); } -constexpr uint32_t customizeType(uint32_t handle, gfx::Type type) { +constexpr uint32_t getBindingFromHandle(uint32_t handle) { return (handle & BINDING_MASK) >> 20; } +constexpr uint32_t getCountFromHandle(uint32_t handle) { return (handle & COUNT_MASK) >> 12; } +constexpr uint32_t getOffsetFromHandle(uint32_t handle) { return (handle & OFFSET_MASK); } +constexpr uint32_t customizeType(uint32_t handle, gfx::Type type) { return (handle & ~TYPE_MASK) | ((static_cast(type) << 26) & TYPE_MASK); } @@ -95,7 +95,7 @@ extern const ccstd::unordered_map type2writer; * @param type The type of the uniform */ const ccstd::vector &getDefaultFloatArrayFromType(gfx::Type type); -const ccstd::string & getDefaultStringFromType(gfx::Type type); +const ccstd::string &getDefaultStringFromType(gfx::Type type); /** * @en Combination of preprocess macros diff --git a/native/cocos/renderer/core/ProgramLib.cpp b/native/cocos/renderer/core/ProgramLib.cpp index ff26a83c97..5eb4f61f39 100644 --- a/native/cocos/renderer/core/ProgramLib.cpp +++ b/native/cocos/renderer/core/ProgramLib.cpp @@ -86,14 +86,14 @@ ccstd::string mapDefine(const IDefineInfo &info, const cc::optional prepareDefines(const MacroRecord &records, const ccstd::vector &defList) { ccstd::vector macros{}; for (const auto &tmp : defList) { - const auto &name = tmp.name; - auto it = records.find(name); - auto value = mapDefine(tmp, it == records.end() ? cc::nullopt : cc::optional(it->second)); - bool isDefault = it == records.end() || (cc::holds_alternative(it->second) && cc::get(it->second) == "0"); + const auto &name = tmp.name; + auto it = records.find(name); + auto value = mapDefine(tmp, it == records.end() ? cc::nullopt : cc::optional(it->second)); + bool isDefault = it == records.end() || (cc::holds_alternative(it->second) && cc::get(it->second) == "0"); macros.emplace_back(); - auto &info = macros.back(); - info.name = name; - info.value = value; + auto &info = macros.back(); + info.name = name; + info.value = value; info.isDefault = isDefault; } return macros; @@ -123,8 +123,8 @@ void insertBuiltinBindings(const IProgramInfo &tmpl, ITemplateInfo &tmplInfo, co CC_LOG_WARNING("builtin UBO '%s' not available !", b.name.c_str()); continue; } - const auto &info = infoIt->second; - const auto bindingsIter = std::find_if(source.bindings.begin(), source.bindings.end(), [&info](const auto &bd) -> bool { return bd.binding == info.binding; }); + const auto &info = infoIt->second; + const auto bindingsIter = std::find_if(source.bindings.begin(), source.bindings.end(), [&info](const auto &bd) -> bool { return bd.binding == info.binding; }); if (bindingsIter == source.bindings.end()) { CC_LOG_WARNING("builtin UBO '%s' not available !", b.name.c_str()); continue; @@ -146,8 +146,8 @@ void insertBuiltinBindings(const IProgramInfo &tmpl, ITemplateInfo &tmplInfo, co CC_LOG_WARNING("builtin samplerTexture '%s' not available !", s.name.c_str()); continue; } - const auto &info = infoIt->second; - const auto binding = std::find_if(source.bindings.begin(), source.bindings.end(), [&info](const auto &bd) { + const auto &info = infoIt->second; + const auto binding = std::find_if(source.bindings.begin(), source.bindings.end(), [&info](const auto &bd) { return bd.binding == info.binding; }); if (binding == source.bindings.end() || !(binding->descriptorType & gfx::DESCRIPTOR_SAMPLER_TYPE)) { @@ -181,7 +181,7 @@ auto genHandles(const IProgramInfo &tmpl) { // block member handles for (const auto &block : tmpl.blocks) { const auto members = block.members; - uint32_t offset = 0; + uint32_t offset = 0; for (const auto &uniform : members) { handleMap[uniform.name] = genHandle(block.binding, uniform.type, @@ -214,8 +214,8 @@ bool dependencyCheck(const ccstd::vector &dependencies, const Mac ccstd::vector getActiveAttributes(const IProgramInfo &tmpl, const ITemplateInfo &tmplInfo, const MacroRecord &defines) { ccstd::vector out{}; - const auto & attributes = tmpl.attributes; - const auto & gfxAttributes = tmplInfo.gfxAttributes; + const auto &attributes = tmpl.attributes; + const auto &gfxAttributes = tmplInfo.gfxAttributes; for (auto i = 0; i < attributes.size(); i++) { if (!dependencyCheck(attributes[i].defines, defines)) { continue; @@ -244,31 +244,31 @@ const char *getDeviceShaderVersion(const gfx::Device *device) { static void copyDefines(const ccstd::vector &from, ccstd::vector &to) { to.resize(from.size()); for (size_t i = 0, len = from.size(); i < len; ++i) { - to[i].name = from[i].name; - to[i].type = from[i].type; - to[i].range = from[i].range; - to[i].options = from[i].options; + to[i].name = from[i].name; + to[i].type = from[i].type; + to[i].range = from[i].range; + to[i].options = from[i].options; to[i].defaultVal = from[i].defaultVal; } } // IProgramInfo void IProgramInfo::copyFrom(const IShaderInfo &o) { - name = o.name; - hash = o.hash; - glsl4 = o.glsl4; - glsl3 = o.glsl3; - glsl1 = o.glsl1; + name = o.name; + hash = o.hash; + glsl4 = o.glsl4; + glsl3 = o.glsl3; + glsl1 = o.glsl1; builtins = o.builtins; copyDefines(o.defines, defines); - blocks = o.blocks; + blocks = o.blocks; samplerTextures = o.samplerTextures; - attributes = o.attributes; - samplers = o.samplers; - textures = o.textures; - buffers = o.buffers; - images = o.images; - subpassInputs = o.subpassInputs; + attributes = o.attributes; + samplers = o.samplers; + textures = o.textures; + buffers = o.buffers; + images = o.images; + subpassInputs = o.subpassInputs; } ProgramLib::ProgramLib() = default; @@ -296,7 +296,7 @@ void ProgramLib::destroyInstance() { void ProgramLib::registerEffect(EffectAsset *effect) { for (auto &shader : effect->_shaders) { - auto *tmpl = define(shader); + auto *tmpl = define(shader); tmpl->effectName = effect->getName(); } @@ -325,8 +325,8 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { int32_t cnt = 1; if (def.type == "number") { auto &range = def.range.value(); - cnt = getBitCount(range[1] - range[0] + 1); // inclusive on both ends - def.map = [=](const MacroValue &value) -> int32_t { + cnt = getBitCount(range[1] - range[0] + 1); // inclusive on both ends + def.map = [=](const MacroValue &value) -> int32_t { if (cc::holds_alternative(value)) { return cc::get(value) - range[0]; } @@ -337,7 +337,7 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { return 0; }; } else if (def.type == "string") { - cnt = getBitCount(static_cast(def.options.value().size())); + cnt = getBitCount(static_cast(def.options.value().size())); def.map = [=](const MacroValue &value) -> int32_t { const auto *pValue = cc::get_if(&value); if (pValue != nullptr) { @@ -383,16 +383,16 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { ITemplateInfo tmplInfo{}; // cache material-specific descriptor set layout tmplInfo.samplerStartBinding = static_cast(tmpl.blocks.size()); - tmplInfo.bindings = {}; - tmplInfo.blockSizes = {}; + tmplInfo.bindings = {}; + tmplInfo.blockSizes = {}; for (const auto &block : tmpl.blocks) { tmplInfo.blockSizes.emplace_back(getSize(block)); tmplInfo.bindings.emplace_back(); - auto &bindingsInfo = tmplInfo.bindings.back(); - bindingsInfo.binding = static_cast(block.binding); + auto &bindingsInfo = tmplInfo.bindings.back(); + bindingsInfo.binding = static_cast(block.binding); bindingsInfo.descriptorType = gfx::DescriptorType::UNIFORM_BUFFER; - bindingsInfo.count = 1; - bindingsInfo.stageFlags = block.stageFlags; + bindingsInfo.count = 1; + bindingsInfo.stageFlags = block.stageFlags; ccstd::vector uniforms; { // construct uniforms @@ -400,34 +400,34 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { for (const auto &member : block.members) { uniforms.emplace_back(); auto &info = uniforms.back(); - info.name = member.name; - info.type = member.type; + info.name = member.name; + info.type = member.type; info.count = member.count; } } tmplInfo.shaderInfo.blocks.emplace_back(); - auto &blocksInfo = tmplInfo.shaderInfo.blocks.back(); - blocksInfo.set = static_cast(pipeline::SetIndex::MATERIAL); + auto &blocksInfo = tmplInfo.shaderInfo.blocks.back(); + blocksInfo.set = static_cast(pipeline::SetIndex::MATERIAL); blocksInfo.binding = static_cast(block.binding); - blocksInfo.name = block.name; + blocksInfo.name = block.name; blocksInfo.members = uniforms; - blocksInfo.count = 1; // effect compiler guarantees block count = 1 + blocksInfo.count = 1; // effect compiler guarantees block count = 1 } for (const auto &samplerTexture : tmpl.samplerTextures) { tmplInfo.bindings.emplace_back(); - auto &descriptorLayoutBindingInfo = tmplInfo.bindings.back(); - descriptorLayoutBindingInfo.binding = static_cast(samplerTexture.binding); + auto &descriptorLayoutBindingInfo = tmplInfo.bindings.back(); + descriptorLayoutBindingInfo.binding = static_cast(samplerTexture.binding); descriptorLayoutBindingInfo.descriptorType = gfx::DescriptorType::SAMPLER_TEXTURE; - descriptorLayoutBindingInfo.count = samplerTexture.count; - descriptorLayoutBindingInfo.stageFlags = samplerTexture.stageFlags; + descriptorLayoutBindingInfo.count = samplerTexture.count; + descriptorLayoutBindingInfo.stageFlags = samplerTexture.stageFlags; tmplInfo.shaderInfo.samplerTextures.emplace_back(); - auto &samplerTextureInfo = tmplInfo.shaderInfo.samplerTextures.back(); - samplerTextureInfo.set = static_cast(pipeline::SetIndex::MATERIAL); + auto &samplerTextureInfo = tmplInfo.shaderInfo.samplerTextures.back(); + samplerTextureInfo.set = static_cast(pipeline::SetIndex::MATERIAL); samplerTextureInfo.binding = static_cast(samplerTexture.binding); - samplerTextureInfo.name = samplerTexture.name; - samplerTextureInfo.type = samplerTexture.type; - samplerTextureInfo.count = samplerTexture.count; + samplerTextureInfo.name = samplerTexture.name; + samplerTextureInfo.type = samplerTexture.type; + samplerTextureInfo.count = samplerTexture.count; } for (const auto &sampler : tmpl.samplers) { @@ -509,26 +509,26 @@ IProgramInfo *ProgramLib::define(IShaderInfo &shader) { tmplInfo.gfxAttributes = {}; for (auto &attr : tmpl.attributes) { tmplInfo.gfxAttributes.emplace_back(); - auto &info = tmplInfo.gfxAttributes.back(); - info.name = attr.name; - info.format = attr.format; + auto &info = tmplInfo.gfxAttributes.back(); + info.name = attr.name; + info.format = attr.format; info.isNormalized = attr.isNormalized; - info.stream = 0; - info.isInstanced = attr.isInstanced; - info.location = attr.location; + info.stream = 0; + info.isInstanced = attr.isInstanced; + info.location = attr.location; } insertBuiltinBindings(tmpl, tmplInfo, pipeline::localDescriptorSetLayout, "locals", nullptr); tmplInfo.shaderInfo.stages.emplace_back(); - auto &vertexShaderInfo = tmplInfo.shaderInfo.stages.back(); - vertexShaderInfo.stage = gfx::ShaderStageFlagBit::VERTEX; + auto &vertexShaderInfo = tmplInfo.shaderInfo.stages.back(); + vertexShaderInfo.stage = gfx::ShaderStageFlagBit::VERTEX; vertexShaderInfo.source = ""; tmplInfo.shaderInfo.stages.emplace_back(); - auto &fragmentShaderInfo = tmplInfo.shaderInfo.stages.back(); - fragmentShaderInfo.stage = gfx::ShaderStageFlagBit::FRAGMENT; + auto &fragmentShaderInfo = tmplInfo.shaderInfo.stages.back(); + fragmentShaderInfo.stage = gfx::ShaderStageFlagBit::FRAGMENT; fragmentShaderInfo.source = ""; - tmplInfo.handleMap = genHandles(tmpl); - tmplInfo.setLayouts = {}; + tmplInfo.handleMap = genHandles(tmpl); + tmplInfo.setLayouts = {}; _templateInfos[tmpl.hash] = tmplInfo; } @@ -555,7 +555,7 @@ IProgramInfo *ProgramLib::getTemplate(const ccstd::string &name) { ITemplateInfo *ProgramLib::getTemplateInfo(const ccstd::string &name) { auto it = _templates.find(name); CC_ASSERT(it != _templates.end()); - auto hash = it->second.hash; + auto hash = it->second.hash; auto itInfo = _templateInfos.find(hash); return itInfo != _templateInfos.end() ? &itInfo->second : nullptr; } @@ -568,8 +568,8 @@ ITemplateInfo *ProgramLib::getTemplateInfo(const ccstd::string &name) { gfx::DescriptorSetLayout *ProgramLib::getDescriptorSetLayout(gfx::Device *device, const ccstd::string &name, bool isLocal) { auto itTmpl = _templates.find(name); CC_ASSERT(itTmpl != _templates.end()); - const auto &tmpl = itTmpl->second; - auto itTplInfo = _templateInfos.find(tmpl.hash); + const auto &tmpl = itTmpl->second; + auto itTplInfo = _templateInfos.find(tmpl.hash); if (itTplInfo == _templateInfos.end()) { return nullptr; } @@ -589,7 +589,7 @@ gfx::DescriptorSetLayout *ProgramLib::getDescriptorSetLayout(gfx::Device *device ccstd::string ProgramLib::getKey(const ccstd::string &name, const MacroRecord &defines) { auto itTpl = _templates.find(name); CC_ASSERT(itTpl != _templates.end()); - auto &tmpl = itTpl->second; + auto &tmpl = itTpl->second; auto &tmplDefs = tmpl.defines; if (tmpl.uber) { std::stringstream key; @@ -598,24 +598,24 @@ ccstd::string ProgramLib::getKey(const ccstd::string &name, const MacroRecord &d if (itDef == defines.end() || !tmplDef.map) { continue; } - const auto &value = itDef->second; - auto mapped = tmplDef.map(value); - auto offset = tmplDef.offset; + const auto &value = itDef->second; + auto mapped = tmplDef.map(value); + auto offset = tmplDef.offset; key << offset << mapped << "|"; } ccstd::string ret{key.str() + std::to_string(tmpl.hash)}; return ret; } - uint32_t key = 0; + uint32_t key = 0; std::stringstream ss; for (auto &tmplDef : tmplDefs) { auto itDef = defines.find(tmplDef.name); if (itDef == defines.end() || !tmplDef.map) { continue; } - const auto &value = itDef->second; - auto mapped = tmplDef.map(value); - auto offset = tmplDef.offset; + const auto &value = itDef->second; + auto mapped = tmplDef.map(value); + auto offset = tmplDef.offset; key |= (mapped << offset); } ss << std::hex << key << "|" << std::to_string(tmpl.hash); @@ -670,8 +670,8 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & auto itTpl = _templates.find(name); CC_ASSERT(itTpl != _templates.end()); - const auto &tmpl = itTpl->second; - const auto itTplInfo = _templateInfos.find(tmpl.hash); + const auto &tmpl = itTpl->second; + const auto itTplInfo = _templateInfos.find(tmpl.hash); CC_ASSERT(itTplInfo != _templateInfos.end()); auto &tmplInfo = itTplInfo->second; @@ -683,15 +683,15 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & } ccstd::vector macroArray = prepareDefines(defines, tmpl.defines); - std::stringstream ss; + std::stringstream ss; ss << std::endl; for (const auto &m : macroArray) { ss << "#define " << m.name << " " << m.value << std::endl; } auto prefix = pipeline->getConstantMacros() + tmpl.constantMacros + ss.str(); - const IShaderSource *src = &tmpl.glsl3; - const auto * deviceShaderVersion = getDeviceShaderVersion(device); + const IShaderSource *src = &tmpl.glsl3; + const auto *deviceShaderVersion = getDeviceShaderVersion(device); if (deviceShaderVersion) { src = tmpl.getSource(deviceShaderVersion); } else { @@ -706,7 +706,7 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & tmplInfo.shaderInfo.name = getShaderInstanceName(name, macroArray); auto *shader = device->createShader(tmplInfo.shaderInfo); - _cache[key] = shader; + _cache[key] = shader; CC_LOG_DEBUG("ProgramLib::_cache[%s]=%p, defines: %d", key.c_str(), shader, defines.size()); return shader; } diff --git a/native/cocos/renderer/core/ProgramLib.h b/native/cocos/renderer/core/ProgramLib.h index 5c8962ca1c..7950a60630 100644 --- a/native/cocos/renderer/core/ProgramLib.h +++ b/native/cocos/renderer/core/ProgramLib.h @@ -47,30 +47,30 @@ class PipelineRuntime; struct IDefineRecord : public IDefineInfo { std::function map{nullptr}; - int32_t offset{0}; + int32_t offset{0}; }; struct IMacroInfo { ccstd::string name; ccstd::string value; - bool isDefault{false}; + bool isDefault{false}; }; struct ITemplateInfo { - ccstd::vector gfxAttributes; - gfx::ShaderInfo shaderInfo; - ccstd::vector blockSizes; - RefVector setLayouts; - IntrusivePtr pipelineLayout; - Record handleMap; + ccstd::vector gfxAttributes; + gfx::ShaderInfo shaderInfo; + ccstd::vector blockSizes; + RefVector setLayouts; + IntrusivePtr pipelineLayout; + Record handleMap; ccstd::vector bindings; - int32_t samplerStartBinding{-1}; + int32_t samplerStartBinding{-1}; }; struct IProgramInfo : public IShaderInfo { - ccstd::string effectName; + ccstd::string effectName; ccstd::vector defines; - ccstd::string constantMacros; - bool uber{false}; // macro number exceeds default limits, will fallback to string hash + ccstd::string constantMacros; + bool uber{false}; // macro number exceeds default limits, will fallback to string hash void copyFrom(const IShaderInfo &o); }; @@ -84,7 +84,7 @@ const char *getDeviceShaderVersion(const gfx::Device *device); class ProgramLib final { public: static ProgramLib *getInstance(); - static void destroyInstance(); + static void destroyInstance(); void registerEffect(EffectAsset *effect); @@ -160,10 +160,10 @@ private: ProgramLib(); ~ProgramLib(); - static ProgramLib * instance; - Record _templates; // per shader + static ProgramLib *instance; + Record _templates; // per shader Record> _cache; - Record _templateInfos; + Record _templateInfos; }; } // namespace cc diff --git a/native/cocos/renderer/core/TextureBufferPool.cpp b/native/cocos/renderer/core/TextureBufferPool.cpp index 6954a196a9..4f9a2b91bb 100644 --- a/native/cocos/renderer/core/TextureBufferPool.cpp +++ b/native/cocos/renderer/core/TextureBufferPool.cpp @@ -48,12 +48,12 @@ TextureBufferPool::~TextureBufferPool() = default; void TextureBufferPool::initialize(const ITextureBufferPoolInfo &info) { const auto &formatInfo = gfx::GFX_FORMAT_INFOS[static_cast(info.format)]; - _format = info.format; - _formatSize = formatInfo.size; - _channels = formatInfo.count; - _roundUpFn = info.roundUpFn.has_value() ? info.roundUpFn.value() : nullptr; - _alignment = info.alignment.has_value() ? info.alignment.value() : 1; - _useMcDonaldAlloc = info.alignment.has_value() && info.alignment.value(); + _format = info.format; + _formatSize = formatInfo.size; + _channels = formatInfo.count; + _roundUpFn = info.roundUpFn.has_value() ? info.roundUpFn.value() : nullptr; + _alignment = info.alignment.has_value() ? info.alignment.value() : 1; + _useMcDonaldAlloc = info.alignment.has_value() && info.alignment.value(); } void TextureBufferPool::destroy() { @@ -69,7 +69,7 @@ ITextureBufferHandle TextureBufferPool::alloc(uint32_t size) { return mcDonaldAlloc(size); } - size = roundUp(size, _alignment); + size = roundUp(size, _alignment); index_t index = CC_INVALID_INDEX; index_t start = CC_INVALID_INDEX; if (start < 0) { @@ -85,30 +85,30 @@ ITextureBufferHandle TextureBufferPool::alloc(uint32_t size) { chunk.start += static_cast(size); ITextureBufferHandle handle; handle.chunkIdx = index; - handle.start = start; - handle.end = static_cast(start + size); - handle.texture = chunk.texture; + handle.start = start; + handle.end = static_cast(start + size); + handle.texture = chunk.texture; _handles.emplace_back(handle); return handle; } // create a new one - auto targetSize = static_cast(std::sqrt(size / _formatSize)); - uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); - auto newChunk = _chunks[createChunk(texLength)]; + auto targetSize = static_cast(std::sqrt(size / _formatSize)); + uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); + auto newChunk = _chunks[createChunk(texLength)]; newChunk.start += static_cast(size); ITextureBufferHandle texHandle; texHandle.chunkIdx = static_cast(_chunkCount - 1); - texHandle.start = 0; - texHandle.end = static_cast(size); - texHandle.texture = newChunk.texture; + texHandle.start = 0; + texHandle.end = static_cast(size); + texHandle.texture = newChunk.texture; _handles.emplace_back(texHandle); return texHandle; } ITextureBufferHandle TextureBufferPool::alloc(uint32_t size, index_t chunkIdx) { - size = roundUp(size, _alignment); + size = roundUp(size, _alignment); index_t index = chunkIdx; index_t start = findAvailableSpace(size, index); @@ -125,24 +125,24 @@ ITextureBufferHandle TextureBufferPool::alloc(uint32_t size, index_t chunkIdx) { chunk.start += static_cast(size); ITextureBufferHandle handle; handle.chunkIdx = index; - handle.start = start; - handle.end = static_cast(start + size); - handle.texture = chunk.texture; + handle.start = start; + handle.end = static_cast(start + size); + handle.texture = chunk.texture; _handles.emplace_back(handle); return handle; } // create a new one - auto targetSize = static_cast(std::sqrt(size / _formatSize)); - uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); - auto newChunk = _chunks[createChunk(texLength)]; + auto targetSize = static_cast(std::sqrt(size / _formatSize)); + uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); + auto newChunk = _chunks[createChunk(texLength)]; newChunk.start += static_cast(size); ITextureBufferHandle texHandle; texHandle.chunkIdx = static_cast(_chunkCount - 1); - texHandle.start = 0; - texHandle.end = static_cast(size); - texHandle.texture = newChunk.texture; + texHandle.start = 0; + texHandle.end = static_cast(size); + texHandle.texture = newChunk.texture; _handles.emplace_back(texHandle); return texHandle; } @@ -165,30 +165,30 @@ uint32_t TextureBufferPool::createChunk(uint32_t length) { length}); ITextureBuffer chunk; - chunk.texture = texture; - chunk.size = texSize; - chunk.start = 0; - chunk.end = static_cast(texSize); + chunk.texture = texture; + chunk.size = texSize; + chunk.start = 0; + chunk.end = static_cast(texSize); _chunks[_chunkCount] = chunk; return _chunkCount++; } void TextureBufferPool::update(const ITextureBufferHandle &handle, ArrayBuffer *buffer) { - gfx::BufferDataList buffers; - uint8_t * bufferData = buffer->getData(); + gfx::BufferDataList buffers; + uint8_t *bufferData = buffer->getData(); gfx::BufferTextureCopyList regions; - auto start = static_cast(handle.start / _formatSize); + auto start = static_cast(handle.start / _formatSize); uint32_t remainSize = buffer->byteLength() / _formatSize; - int32_t offsetX = start % static_cast(handle.texture->getWidth()); - int32_t offsetY = std::floor(start / handle.texture->getWidth()); - uint32_t copySize = std::min(handle.texture->getWidth() - offsetX, remainSize); - uint32_t begin = 0; + int32_t offsetX = start % static_cast(handle.texture->getWidth()); + int32_t offsetY = std::floor(start / handle.texture->getWidth()); + uint32_t copySize = std::min(handle.texture->getWidth() - offsetX, remainSize); + uint32_t begin = 0; if (offsetX > 0) { - _region0.texOffset.x = offsetX; - _region0.texOffset.y = offsetY; - _region0.texExtent.width = copySize; + _region0.texOffset.x = offsetX; + _region0.texOffset.y = offsetY; + _region0.texExtent.width = copySize; _region0.texExtent.height = 1; buffers.emplace_back(bufferData + begin * _formatSize); regions.emplace_back(_region0); @@ -203,12 +203,12 @@ void TextureBufferPool::update(const ITextureBufferHandle &handle, ArrayBuffer * _region1.texOffset.y = offsetY; if (remainSize > handle.texture->getWidth()) { - _region1.texExtent.width = handle.texture->getWidth(); + _region1.texExtent.width = handle.texture->getWidth(); _region1.texExtent.height = std::floor(remainSize / handle.texture->getWidth()); - copySize = _region1.texExtent.width * _region1.texExtent.height; + copySize = _region1.texExtent.width * _region1.texExtent.height; } else { - copySize = remainSize; - _region1.texExtent.width = copySize; + copySize = remainSize; + _region1.texExtent.width = copySize; _region1.texExtent.height = 1; } @@ -222,9 +222,9 @@ void TextureBufferPool::update(const ITextureBufferHandle &handle, ArrayBuffer * } if (remainSize > 0) { - _region2.texOffset.x = offsetX; - _region2.texOffset.y = offsetY; - _region2.texExtent.width = remainSize; + _region2.texOffset.x = offsetX; + _region2.texOffset.y = offsetY; + _region2.texExtent.width = remainSize; _region2.texExtent.height = 1; buffers.emplace_back(bufferData + begin * _formatSize); @@ -234,9 +234,9 @@ void TextureBufferPool::update(const ITextureBufferHandle &handle, ArrayBuffer * } index_t TextureBufferPool::findAvailableSpace(uint32_t size, index_t chunkIdx) const { - auto chunk = _chunks[chunkIdx]; - bool isFound = false; - index_t start = chunk.start; + auto chunk = _chunks[chunkIdx]; + bool isFound = false; + index_t start = chunk.start; if ((start + size) <= chunk.size) { isFound = true; } else { @@ -265,9 +265,9 @@ index_t TextureBufferPool::findAvailableSpace(uint32_t size, index_t chunkIdx) c ITextureBufferHandle TextureBufferPool::mcDonaldAlloc(uint32_t size) { size = roundUp(size, _alignment); for (index_t i = 0; i < _chunkCount; ++i) { - auto chunk = _chunks[i]; - bool isFound = false; - index_t start = chunk.start; + auto chunk = _chunks[i]; + bool isFound = false; + index_t start = chunk.start; if ((start + size) <= chunk.end) { isFound = true; } else if (start > chunk.end) { @@ -275,14 +275,14 @@ ITextureBufferHandle TextureBufferPool::mcDonaldAlloc(uint32_t size) { isFound = true; } else if (size <= chunk.end) { // Try to find from head again. - start = 0; + start = 0; chunk.start = 0; - isFound = true; + isFound = true; } } else if (start == chunk.end) { - start = 0; + start = 0; chunk.start = 0; - chunk.end = static_cast(chunk.size); + chunk.end = static_cast(chunk.size); if (size <= chunk.end) { isFound = true; } @@ -292,24 +292,24 @@ ITextureBufferHandle TextureBufferPool::mcDonaldAlloc(uint32_t size) { ITextureBufferHandle handle; handle.chunkIdx = i; - handle.start = start; - handle.end = static_cast(size); - handle.texture = chunk.texture; + handle.start = start; + handle.end = static_cast(size); + handle.texture = chunk.texture; _handles.emplace_back(handle); return handle; } } // create a new one - auto targetSize = static_cast(std::sqrt(size / _formatSize)); - uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); - auto newChunk = _chunks[createChunk(texLength)]; + auto targetSize = static_cast(std::sqrt(size / _formatSize)); + uint32_t texLength = _roundUpFn ? _roundUpFn(targetSize, _formatSize) : std::max(1024, static_cast(utils::nextPOT(targetSize))); + auto newChunk = _chunks[createChunk(texLength)]; newChunk.start += static_cast(size); ITextureBufferHandle texHandle; texHandle.chunkIdx = static_cast(_chunkCount); - texHandle.start = 0; - texHandle.end = static_cast(size), - texHandle.texture = newChunk.texture; + texHandle.start = 0; + texHandle.end = static_cast(size), + texHandle.texture = newChunk.texture; _handles.emplace_back(texHandle); return texHandle; } diff --git a/native/cocos/renderer/core/TextureBufferPool.h b/native/cocos/renderer/core/TextureBufferPool.h index 57aff51438..ba8dd585a5 100644 --- a/native/cocos/renderer/core/TextureBufferPool.h +++ b/native/cocos/renderer/core/TextureBufferPool.h @@ -35,15 +35,15 @@ using roundUpType = std::function; struct ITextureBuffer { gfx::Texture *texture{nullptr}; - uint32_t size{0}; - index_t start{0}; - index_t end{0}; + uint32_t size{0}; + index_t start{0}; + index_t end{0}; }; struct ITextureBufferHandle { - index_t chunkIdx{0}; - index_t start{0}; - index_t end{0}; + index_t chunkIdx{0}; + index_t start{0}; + index_t end{0}; gfx::Texture *texture{nullptr}; bool operator==(const ITextureBufferHandle &handle) const { @@ -52,10 +52,10 @@ struct ITextureBufferHandle { }; struct ITextureBufferPoolInfo { - gfx::Format format{gfx::Format::UNKNOWN}; // target texture format - cc::optional inOrderFree; // will the handles be freed exactly in the order of their allocation? - cc::optional alignment; // the data alignment for each handle allocated, in bytes - cc::optional roundUpFn; // given a target size, how will the actual texture size round up? + gfx::Format format{gfx::Format::UNKNOWN}; // target texture format + cc::optional inOrderFree; // will the handles be freed exactly in the order of their allocation? + cc::optional alignment; // the data alignment for each handle allocated, in bytes + cc::optional roundUpFn; // given a target size, how will the actual texture size round up? }; class TextureBufferPool : public RefCounted { @@ -64,14 +64,14 @@ public: explicit TextureBufferPool(gfx::Device *device); ~TextureBufferPool() override; - void initialize(const ITextureBufferPoolInfo &info); - void destroy(); + void initialize(const ITextureBufferPoolInfo &info); + void destroy(); ITextureBufferHandle alloc(uint32_t size); ITextureBufferHandle alloc(uint32_t size, index_t chunkIdx); - void free(const ITextureBufferHandle &handle); + void free(const ITextureBufferHandle &handle); uint32_t createChunk(uint32_t length); - void update(const ITextureBufferHandle &handle, ArrayBuffer *buffer); + void update(const ITextureBufferHandle &handle, ArrayBuffer *buffer); private: index_t findAvailableSpace(uint32_t size, index_t chunkIdx) const; @@ -79,19 +79,19 @@ private: // [McDonald 12] Efficient Buffer Management ITextureBufferHandle mcDonaldAlloc(uint32_t size); - gfx::Device * _device{nullptr}; - gfx::Format _format{gfx::Format::UNKNOWN}; - uint32_t _formatSize{0}; - ccstd::vector _chunks; - uint32_t _chunkCount{0}; + gfx::Device *_device{nullptr}; + gfx::Format _format{gfx::Format::UNKNOWN}; + uint32_t _formatSize{0}; + ccstd::vector _chunks; + uint32_t _chunkCount{0}; ccstd::vector _handles; - gfx::BufferTextureCopy _region0; - gfx::BufferTextureCopy _region1; - gfx::BufferTextureCopy _region2; - roundUpType _roundUpFn{nullptr}; - bool _useMcDonaldAlloc{false}; - uint32_t _channels{4}; - uint32_t _alignment{1}; + gfx::BufferTextureCopy _region0; + gfx::BufferTextureCopy _region1; + gfx::BufferTextureCopy _region2; + roundUpType _roundUpFn{nullptr}; + bool _useMcDonaldAlloc{false}; + uint32_t _channels{4}; + uint32_t _alignment{1}; CC_DISALLOW_COPY_MOVE_ASSIGN(TextureBufferPool); }; diff --git a/native/cocos/renderer/frame-graph/Blackboard.h b/native/cocos/renderer/frame-graph/Blackboard.h index f55617dd1b..e14bb67214 100644 --- a/native/cocos/renderer/frame-graph/Blackboard.h +++ b/native/cocos/renderer/frame-graph/Blackboard.h @@ -35,18 +35,18 @@ namespace framegraph { template class Blackboard final { public: - Blackboard() = default; - ~Blackboard() = default; - Blackboard(const Blackboard &) = delete; + Blackboard() = default; + ~Blackboard() = default; + Blackboard(const Blackboard &) = delete; Blackboard(Blackboard &&) noexcept = delete; Blackboard &operator=(const Blackboard &) = delete; Blackboard &operator=(Blackboard &&) noexcept = delete; inline ValueType &operator[](const KeyType &name) noexcept; - inline void put(const KeyType &name, ValueType handle) noexcept; - inline ValueType get(const KeyType &name) const noexcept; - inline void clear() noexcept; - inline bool has(const KeyType &name) const noexcept; + inline void put(const KeyType &name, ValueType handle) noexcept; + inline ValueType get(const KeyType &name) const noexcept; + inline void clear() noexcept; + inline bool has(const KeyType &name) const noexcept; private: using Container = ccstd::unordered_map; diff --git a/native/cocos/renderer/frame-graph/CallbackPass.h b/native/cocos/renderer/frame-graph/CallbackPass.h index 97eb6686a9..87fc0849a3 100644 --- a/native/cocos/renderer/frame-graph/CallbackPass.h +++ b/native/cocos/renderer/frame-graph/CallbackPass.h @@ -32,9 +32,9 @@ namespace framegraph { class Executable { public: - Executable() noexcept = default; - virtual ~Executable() = default; - Executable(const Executable &) = delete; + Executable() noexcept = default; + virtual ~Executable() = default; + Executable(const Executable &) = delete; Executable(Executable &&) noexcept = delete; Executable &operator=(const Executable &) = delete; Executable &operator=(Executable &&) noexcept = delete; @@ -50,12 +50,12 @@ public: explicit CallbackPass(ExecuteMethod &execute) noexcept; explicit CallbackPass(ExecuteMethod &&execute) noexcept; - void execute(const DevicePassResourceTable &resourceTable) noexcept override; + void execute(const DevicePassResourceTable &resourceTable) noexcept override; inline const Data &getData() const noexcept { return _data; } - inline Data & getData() noexcept { return _data; } + inline Data &getData() noexcept { return _data; } private: - Data _data; + Data _data; ExecuteMethod _execute; }; diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index 0c9b374213..5d0619bb0b 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -101,7 +101,7 @@ DevicePass::DevicePass(const FrameGraph &graph, ccstd::vector const CC_ASSERT(resource); _attachments.emplace_back(); - _attachments.back().attachment = attachment; + _attachments.back().attachment = attachment; _attachments.back().renderTarget = resource; renderTargets.emplace_back(resource); } @@ -117,12 +117,12 @@ void DevicePass::execute() { begin(cmdBuff); for (uint32_t i = 0; i < utils::toUint(_subpasses.size()); ++i) { - Subpass &subpass = _subpasses[i]; + Subpass &subpass = _subpasses[i]; _resourceTable._subpassIndex = i; for (LogicPass &pass : subpass.logicPasses) { gfx::Viewport &viewport = pass.customViewport ? pass.viewport : _viewport; - gfx::Rect & scissor = pass.customViewport ? pass.scissor : _scissor; + gfx::Rect &scissor = pass.customViewport ? pass.scissor : _scissor; if (viewport != _curViewport) { cmdBuff->setViewport(viewport); @@ -148,11 +148,11 @@ void DevicePass::append(const FrameGraph &graph, const PassNode *passNode, ccstd do { subpass.logicPasses.emplace_back(); - LogicPass &logicPass = subpass.logicPasses.back(); - logicPass.pass = passNode->_pass.get(); + LogicPass &logicPass = subpass.logicPasses.back(); + logicPass.pass = passNode->_pass.get(); logicPass.customViewport = passNode->_customViewport; - logicPass.viewport = passNode->_viewport; - logicPass.scissor = passNode->_scissor; + logicPass.viewport = passNode->_viewport; + logicPass.scissor = passNode->_scissor; for (const auto &attachment : passNode->_attachments) { append(graph, attachment, attachments, &subpass.desc, passNode->_reads); @@ -177,7 +177,7 @@ void DevicePass::append(const FrameGraph &graph, const PassNode *passNode, ccstd void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &attachment, ccstd::vector *attachments, gfx::SubpassInfo *subpass, const ccstd::vector &reads) { RenderTargetAttachment::Usage usage{attachment.desc.usage}; - uint32_t slot{attachment.desc.slot}; + uint32_t slot{attachment.desc.slot}; if (attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { // should fetch actual color slot from current subpass slot = subpass->colors.size() > attachment.desc.slot ? subpass->colors[attachment.desc.slot] : gfx::INVALID_BINDING; @@ -210,7 +210,7 @@ void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &a if (resourceNodeA.virtualResource == resourceNodeB.virtualResource) { output = &*it; if (attachment.storeOp != gfx::StoreOp::DISCARD) { - output->storeOp = attachment.storeOp; + output->storeOp = attachment.storeOp; output->desc.endAccesses = attachment.desc.endAccesses; } if (std::find(reads.begin(), reads.end(), output->textureHandle) != reads.end()) { @@ -243,10 +243,10 @@ void DevicePass::append(const FrameGraph &graph, const RenderTargetAttachment &a void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { if (_attachments.empty()) return; - gfx::RenderPassInfo rpInfo; - gfx::FramebufferInfo fboInfo; - float clearDepth = 1.F; - uint32_t clearStencil = 0; + gfx::RenderPassInfo rpInfo; + gfx::FramebufferInfo fboInfo; + float clearDepth = 1.F; + uint32_t clearStencil = 0; static ccstd::vector clearColors; clearColors.clear(); @@ -262,7 +262,7 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { if (hasDefaultViewport) { _viewport = {}; - _scissor = {0, 0, UINT_MAX, UINT_MAX}; + _scissor = {0, 0, UINT_MAX, UINT_MAX}; } else { // if all passes use customize viewport _scissor = {INT_MAX, INT_MAX, 0, 0}; @@ -281,26 +281,26 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { gfx::Texture *attachment = attachElem.renderTarget; if (attachElem.attachment.desc.usage == RenderTargetAttachment::Usage::COLOR) { rpInfo.colorAttachments.emplace_back(); - auto &attachmentInfo = rpInfo.colorAttachments.back(); - attachmentInfo.format = attachment->getFormat(); - attachmentInfo.loadOp = attachElem.attachment.desc.loadOp; - attachmentInfo.storeOp = attachElem.attachment.storeOp; - attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); + auto &attachmentInfo = rpInfo.colorAttachments.back(); + attachmentInfo.format = attachment->getFormat(); + attachmentInfo.loadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.storeOp = attachElem.attachment.storeOp; + attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; fboInfo.colorTextures.push_back(attachElem.renderTarget); clearColors.emplace_back(attachElem.attachment.desc.clearColor); } else { - auto &attachmentInfo = rpInfo.depthStencilAttachment; - attachmentInfo.format = attachment->getFormat(); - attachmentInfo.depthLoadOp = attachElem.attachment.desc.loadOp; - attachmentInfo.stencilLoadOp = attachElem.attachment.desc.loadOp; - attachmentInfo.depthStoreOp = attachElem.attachment.storeOp; - attachmentInfo.stencilStoreOp = attachElem.attachment.storeOp; - attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); + auto &attachmentInfo = rpInfo.depthStencilAttachment; + attachmentInfo.format = attachment->getFormat(); + attachmentInfo.depthLoadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.stencilLoadOp = attachElem.attachment.desc.loadOp; + attachmentInfo.depthStoreOp = attachElem.attachment.storeOp; + attachmentInfo.stencilStoreOp = attachElem.attachment.storeOp; + attachmentInfo.barrier = gfx::Device::getInstance()->getGeneralBarrier({attachElem.attachment.desc.beginAccesses, attachElem.attachment.desc.endAccesses}); attachmentInfo.isGeneralLayout = attachElem.attachment.isGeneralLayout; - fboInfo.depthStencilTexture = attachElem.renderTarget; - clearDepth = attachElem.attachment.desc.clearDepth; - clearStencil = attachElem.attachment.desc.clearStencil; + fboInfo.depthStencilTexture = attachElem.renderTarget; + clearDepth = attachElem.attachment.desc.clearDepth; + clearStencil = attachElem.attachment.desc.clearStencil; } if (hasDefaultViewport) { _viewport.width = _scissor.width = std::min(_scissor.width, attachment->getWidth()); @@ -317,12 +317,12 @@ void DevicePass::begin(gfx::CommandBuffer *cmdBuff) { _resourceTable._renderPass = _renderPass.get(); fboInfo.renderPass = _renderPass.get(); - _fbo = Framebuffer(fboInfo); + _fbo = Framebuffer(fboInfo); _fbo.createTransient(); cmdBuff->beginRenderPass(_renderPass.get(), _fbo.get(), _scissor, clearColors.data(), clearDepth, clearStencil); _curViewport = _viewport; - _curScissor = _scissor; + _curScissor = _scissor; } void DevicePass::next(gfx::CommandBuffer *cmdBuff) noexcept { diff --git a/native/cocos/renderer/frame-graph/DevicePass.h b/native/cocos/renderer/frame-graph/DevicePass.h index aa6d93701c..b7555b9199 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.h +++ b/native/cocos/renderer/frame-graph/DevicePass.h @@ -38,8 +38,8 @@ public: DevicePass() = delete; DevicePass(const FrameGraph &graph, ccstd::vector const &subpassNodes); DevicePass(const DevicePass &) = delete; - DevicePass(DevicePass &&) = delete; - ~DevicePass() = default; + DevicePass(DevicePass &&) = delete; + ~DevicePass() = default; DevicePass &operator=(const DevicePass &) = delete; DevicePass &operator=(DevicePass &&) = delete; @@ -47,20 +47,20 @@ public: private: struct LogicPass final { - Executable * pass{nullptr}; - bool customViewport{false}; + Executable *pass{nullptr}; + bool customViewport{false}; gfx::Viewport viewport; - gfx::Rect scissor; + gfx::Rect scissor; }; struct Subpass final { ccstd::vector logicPasses{}; - gfx::SubpassInfo desc; + gfx::SubpassInfo desc; }; struct Attachment final { RenderTargetAttachment attachment; - gfx::Texture * renderTarget{nullptr}; + gfx::Texture *renderTarget{nullptr}; }; void append(const FrameGraph &graph, const PassNode *passNode, ccstd::vector *attachments); @@ -70,17 +70,17 @@ private: void next(gfx::CommandBuffer *cmdBuff) noexcept; void end(gfx::CommandBuffer *cmdBuff); - ccstd::vector _subpasses{}; + ccstd::vector _subpasses{}; ccstd::vector _attachments{}; - uint16_t _usedRenderTargetSlotMask{0}; - DevicePassResourceTable _resourceTable; + uint16_t _usedRenderTargetSlotMask{0}; + DevicePassResourceTable _resourceTable; gfx::Viewport _viewport; - gfx::Rect _scissor; + gfx::Rect _scissor; gfx::Viewport _curViewport; - gfx::Rect _curScissor; - RenderPass _renderPass; - Framebuffer _fbo; + gfx::Rect _curScissor; + RenderPass _renderPass; + Framebuffer _fbo; }; } // namespace framegraph diff --git a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp index a653ed24e2..9605e4cbc6 100644 --- a/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp +++ b/native/cocos/renderer/frame-graph/DevicePassResourceTable.cpp @@ -37,8 +37,8 @@ gfx::GFXObject *DevicePassResourceTable::get(const ResourceDictionary &from, Han return it == from.cend() ? nullptr : it->second; } -void DevicePassResourceTable::extract(const FrameGraph & graph, - const PassNode * passNode, +void DevicePassResourceTable::extract(const FrameGraph &graph, + const PassNode *passNode, ccstd::vector const &renderTargets) noexcept { do { extract(graph, passNode->_reads, _reads, false, renderTargets); @@ -48,10 +48,10 @@ void DevicePassResourceTable::extract(const FrameGraph & } while (passNode); } -void DevicePassResourceTable::extract(const FrameGraph & graph, - ccstd::vector const & from, - ResourceDictionary & to, - bool ignoreRenderTarget, +void DevicePassResourceTable::extract(const FrameGraph &graph, + ccstd::vector const &from, + ResourceDictionary &to, + bool ignoreRenderTarget, ccstd::vector const &renderTargets) noexcept { std::for_each(from.cbegin(), from.cend(), [&](const Handle handle) { if (to.find(handle) != to.cend()) { diff --git a/native/cocos/renderer/frame-graph/DevicePassResourceTable.h b/native/cocos/renderer/frame-graph/DevicePassResourceTable.h index 9a82137bfa..ed3d886192 100644 --- a/native/cocos/renderer/frame-graph/DevicePassResourceTable.h +++ b/native/cocos/renderer/frame-graph/DevicePassResourceTable.h @@ -39,10 +39,10 @@ class DevicePass; class DevicePassResourceTable final { public: - DevicePassResourceTable() = default; - ~DevicePassResourceTable() = default; + DevicePassResourceTable() = default; + ~DevicePassResourceTable() = default; DevicePassResourceTable(const DevicePassResourceTable &) = delete; - DevicePassResourceTable(DevicePassResourceTable &&) = delete; + DevicePassResourceTable(DevicePassResourceTable &&) = delete; DevicePassResourceTable &operator=(const DevicePassResourceTable &) = delete; DevicePassResourceTable &operator=(DevicePassResourceTable &&) = delete; @@ -55,20 +55,20 @@ public: getWrite(TypedHandle handle) const noexcept; gfx::RenderPass *getRenderPass() const { return _renderPass; } - uint32_t getSubpassIndex() const { return _subpassIndex; } + uint32_t getSubpassIndex() const { return _subpassIndex; } private: using ResourceDictionary = ccstd::unordered_map; static gfx::GFXObject *get(const ResourceDictionary &from, Handle handle) noexcept; - void extract(const FrameGraph &graph, const PassNode *passNode, ccstd::vector const &renderTargets) noexcept; - static void extract(const FrameGraph &graph, ccstd::vector const &from, ResourceDictionary &to, bool ignoreRenderTarget, ccstd::vector const &renderTargets) noexcept; + void extract(const FrameGraph &graph, const PassNode *passNode, ccstd::vector const &renderTargets) noexcept; + static void extract(const FrameGraph &graph, ccstd::vector const &from, ResourceDictionary &to, bool ignoreRenderTarget, ccstd::vector const &renderTargets) noexcept; ResourceDictionary _reads{}; ResourceDictionary _writes{}; gfx::RenderPass *_renderPass{nullptr}; - uint32_t _subpassIndex{0U}; + uint32_t _subpassIndex{0U}; friend class DevicePass; }; diff --git a/native/cocos/renderer/frame-graph/FrameGraph.cpp b/native/cocos/renderer/frame-graph/FrameGraph.cpp index cd7e34c2ff..91103b6bc0 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.cpp +++ b/native/cocos/renderer/frame-graph/FrameGraph.cpp @@ -76,7 +76,7 @@ void FrameGraph::present(const TextureHandle &input, gfx::Texture *target, bool auto name = FrameGraph::stringToHandle(StringUtil::format("Present Target %d", target->getTypedID()).c_str()); presentTargets.emplace(std::piecewise_construct, std::forward_as_tuple(target->getTypedID()), std::forward_as_tuple(name, Texture{target})); } - auto & resourceInfo{presentTargets[target->getTypedID()]}; + auto &resourceInfo{presentTargets[target->getTypedID()]}; TextureHandle output{getBlackboard().get(resourceInfo.first)}; if (!output.isValid()) { output = importExternal(resourceInfo.first, resourceInfo.second); @@ -92,9 +92,9 @@ void FrameGraph::present(const TextureHandle &input, gfx::Texture *target, bool gfx::Texture *input = table.getRead(data.input); if (input && input != target) { gfx::TextureBlit region; - region.srcExtent.width = input->getWidth(); + region.srcExtent.width = input->getWidth(); region.srcExtent.height = input->getHeight(); - region.dstExtent.width = target->getWidth(); + region.dstExtent.width = target->getWidth(); region.dstExtent.height = target->getHeight(); cmdBuff->blitTexture(input, target, ®ion, 1, gfx::Filter::POINT); } @@ -152,16 +152,16 @@ void FrameGraph::gc(uint32_t const unusedFrameCount) noexcept { void FrameGraph::move(const TextureHandle from, const TextureHandle to, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition) noexcept { const ResourceNode &fromResourceNode = getResourceNode(from); - const ResourceNode &toResourceNode = getResourceNode(to); + const ResourceNode &toResourceNode = getResourceNode(to); CC_ASSERT(!fromResourceNode.virtualResource->isImported()); CC_ASSERT(fromResourceNode.writer); CC_ASSERT(!toResourceNode.writer); - const gfx::TextureInfo &toTextureDesc = static_cast *>(toResourceNode.virtualResource)->get().getDesc(); - uint32_t const toTextureWidth = toTextureDesc.width >> mipmapLevel; - uint32_t const toTextureHeight = toTextureDesc.height >> mipmapLevel; - uint32_t const toTextureDepth = toTextureDesc.depth >> mipmapLevel; + const gfx::TextureInfo &toTextureDesc = static_cast *>(toResourceNode.virtualResource)->get().getDesc(); + uint32_t const toTextureWidth = toTextureDesc.width >> mipmapLevel; + uint32_t const toTextureHeight = toTextureDesc.height >> mipmapLevel; + uint32_t const toTextureDepth = toTextureDesc.depth >> mipmapLevel; CC_ASSERT(toTextureWidth && toTextureHeight && toTextureDepth); CC_ASSERT(toTextureDesc.levelCount > mipmapLevel && toTextureDesc.layerCount > arrayPosition); @@ -208,7 +208,7 @@ Handle FrameGraph::createResourceNode(VirtualResource *const virtualResource) { const size_t index = _resourceNodes.size(); ResourceNode resourceNode; resourceNode.virtualResource = virtualResource; - resourceNode.version = virtualResource->_version; + resourceNode.version = virtualResource->_version; _resourceNodes.emplace_back(resourceNode); return Handle{static_cast(index)}; @@ -301,9 +301,9 @@ void FrameGraph::computeResourceLifetime() { } void FrameGraph::mergePassNodes() noexcept { - const size_t count = _passNodes.size(); - size_t currentPassId = 0; - size_t lastPassId = 0; + const size_t count = _passNodes.size(); + size_t currentPassId = 0; + size_t lastPassId = 0; while (currentPassId < count) { const auto ¤tPassNode = _passNodes[currentPassId]; @@ -336,19 +336,19 @@ void FrameGraph::mergePassNodes() noexcept { ++distance; } - prevPassNode->_next = currentPassNode.get(); - currentPassNode->_head = lastPassNode.get(); + prevPassNode->_next = currentPassNode.get(); + currentPassNode->_head = lastPassNode.get(); currentPassNode->_distanceToHead = distance; - currentPassNode->_refCount = 0; + currentPassNode->_refCount = 0; const size_t attachmentCount = lastPassNode->_attachments.size(); for (size_t i = 0; i < attachmentCount; ++i) { - const RenderTargetAttachment &attachmentInLastPassNode = lastPassNode->_attachments[i]; + const RenderTargetAttachment &attachmentInLastPassNode = lastPassNode->_attachments[i]; const RenderTargetAttachment &attachmentInCurrentPassNode = currentPassNode->_attachments[i]; ResourceNode &resourceNode = _resourceNodes[attachmentInLastPassNode.textureHandle]; - uint16_t & writeCount = resourceNode.virtualResource->_writerCount; + uint16_t &writeCount = resourceNode.virtualResource->_writerCount; CC_ASSERT(writeCount > 1); --writeCount; @@ -362,7 +362,7 @@ void FrameGraph::mergePassNodes() noexcept { } void FrameGraph::computeStoreActionAndMemoryless() { - ID passId = 0; + ID passId = 0; bool lastPassSubpassEnable = false; for (const auto &passNode : _passNodes) { @@ -406,7 +406,7 @@ void FrameGraph::computeStoreActionAndMemoryless() { CC_ASSERT(resourceNodePrevVersion); if (resourceNodePrevVersion->writer->_devicePassId == passNode->_devicePassId) { - attachment.desc.loadOp = gfx::LoadOp::DISCARD; + attachment.desc.loadOp = gfx::LoadOp::DISCARD; resourceNodePrevVersion->writer->getRenderTargetAttachment(*this, resourceNodePrevVersion->virtualResource)->storeOp = gfx::StoreOp::DISCARD; } } @@ -426,7 +426,7 @@ void FrameGraph::computeStoreActionAndMemoryless() { for (VirtualResource *const renderTarget : renderTargets) { const gfx::TextureInfo &textureDesc = static_cast *>(renderTarget)->get().getDesc(); - renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored; + renderTarget->_memoryless = renderTarget->_neverLoaded && renderTarget->_neverStored; renderTarget->_memorylessMSAA = textureDesc.samples != gfx::SampleCount::ONE && renderTarget->_writerCount < 2; } } @@ -626,7 +626,7 @@ void FrameGraph::exportGraphViz(const ccstd::string &path) { for (const RenderTargetAttachment &attachment : passNode->_attachments) { const ResourceNode *readResourceNode = &_resourceNodes[attachment.textureHandle]; - uint16_t const distanceToHead = readResourceNode->writer->_distanceToHead; + uint16_t const distanceToHead = readResourceNode->writer->_distanceToHead; if (readResourceNode->writer && readResourceNode->writer->_head) { const Handle resourceNodeHandleHead = readResourceNode->writer->_head->getWriteResourceNodeHandle(*this, readResourceNode->virtualResource); diff --git a/native/cocos/renderer/frame-graph/FrameGraph.h b/native/cocos/renderer/frame-graph/FrameGraph.h index abe9102a4e..a28791e625 100644 --- a/native/cocos/renderer/frame-graph/FrameGraph.h +++ b/native/cocos/renderer/frame-graph/FrameGraph.h @@ -42,22 +42,22 @@ class FrameGraph final { public: using ResourceHandleBlackboard = Blackboard; - FrameGraph() = default; - ~FrameGraph() = default; - FrameGraph(const FrameGraph &) = delete; + FrameGraph() = default; + ~FrameGraph() = default; + FrameGraph(const FrameGraph &) = delete; FrameGraph(FrameGraph &&) noexcept = delete; FrameGraph &operator=(const FrameGraph &) = delete; FrameGraph &operator=(FrameGraph &&) noexcept = delete; static StringHandle stringToHandle(const char *name); - static const char * handleToString(const StringHandle &handle) noexcept; + static const char *handleToString(const StringHandle &handle) noexcept; - void present(const TextureHandle &input, gfx::Texture *target, bool useMoveSemantic = true); - void presentLastVersion(const VirtualResource *virtualResource, gfx::Texture *target, bool useMoveSemantic = true); - void presentFromBlackboard(const StringHandle &inputName, gfx::Texture *target, bool useMoveSemantic = true); - void compile(); - void execute() noexcept; - void reset() noexcept; + void present(const TextureHandle &input, gfx::Texture *target, bool useMoveSemantic = true); + void presentLastVersion(const VirtualResource *virtualResource, gfx::Texture *target, bool useMoveSemantic = true); + void presentFromBlackboard(const StringHandle &inputName, gfx::Texture *target, bool useMoveSemantic = true); + void compile(); + void execute() noexcept; + void reset() noexcept; static void gc(uint32_t unusedFrameCount = 30) noexcept; template @@ -67,34 +67,34 @@ public: TypedHandle create(const StringHandle &name, const DescriptorType &desc) noexcept; template TypedHandle importExternal(const StringHandle &name, ResourceType &resource) noexcept; - void move(TextureHandle from, TextureHandle to, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition) noexcept; + void move(TextureHandle from, TextureHandle to, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition) noexcept; - inline ResourceNode & getResourceNode(const Handle handle) noexcept { return _resourceNodes[handle]; } - inline const ResourceNode & getResourceNode(const Handle handle) const noexcept { return _resourceNodes[handle]; } + inline ResourceNode &getResourceNode(const Handle handle) noexcept { return _resourceNodes[handle]; } + inline const ResourceNode &getResourceNode(const Handle handle) const noexcept { return _resourceNodes[handle]; } inline ResourceHandleBlackboard &getBlackboard() noexcept { return _blackboard; } - void exportGraphViz(const ccstd::string &path); + void exportGraphViz(const ccstd::string &path); inline void enableMerge(bool enable) noexcept; - bool hasPass(StringHandle handle); + bool hasPass(StringHandle handle); private: - Handle create(VirtualResource *virtualResource); - PassNode & createPassNode(PassInsertPoint insertPoint, const StringHandle &name, Executable *pass); - Handle createResourceNode(VirtualResource *virtualResource); - void sort() noexcept; - void cull(); - void computeResourceLifetime(); - void mergePassNodes() noexcept; - void computeStoreActionAndMemoryless(); - void generateDevicePasses(); + Handle create(VirtualResource *virtualResource); + PassNode &createPassNode(PassInsertPoint insertPoint, const StringHandle &name, Executable *pass); + Handle createResourceNode(VirtualResource *virtualResource); + void sort() noexcept; + void cull(); + void computeResourceLifetime(); + void mergePassNodes() noexcept; + void computeStoreActionAndMemoryless(); + void generateDevicePasses(); ResourceNode *getResourceNode(const VirtualResource *virtualResource, uint8_t version) noexcept; - ccstd::vector> _passNodes{}; - ccstd::vector _resourceNodes{}; + ccstd::vector> _passNodes{}; + ccstd::vector _resourceNodes{}; ccstd::vector> _virtualResources{}; - ccstd::vector> _devicePasses{}; - ResourceHandleBlackboard _blackboard; - bool _merge{true}; + ccstd::vector> _devicePasses{}; + ResourceHandleBlackboard _blackboard; + bool _merge{true}; friend class PassNode; friend class PassNodeBuilder; @@ -105,8 +105,8 @@ private: template const CallbackPass &FrameGraph::addPass(const PassInsertPoint insertPoint, const StringHandle &name, SetupMethod setup, ExecuteMethod &&execute) noexcept { static_assert(sizeof(ExecuteMethod) < 1024, "Execute() lambda is capturing too much data."); - auto *const pass = ccnew CallbackPass(std::forward(execute)); - PassNode & passNode = createPassNode(insertPoint, name, pass); + auto *const pass = ccnew CallbackPass(std::forward(execute)); + PassNode &passNode = createPassNode(insertPoint, name, pass); PassNodeBuilder builder(*this, passNode); setup(builder, pass->getData()); return *pass; diff --git a/native/cocos/renderer/frame-graph/Handle.h b/native/cocos/renderer/frame-graph/Handle.h index da25385e3c..6b8e1d966e 100644 --- a/native/cocos/renderer/frame-graph/Handle.h +++ b/native/cocos/renderer/frame-graph/Handle.h @@ -31,9 +31,9 @@ namespace cc { namespace framegraph { -using Handle = cc::IndexHandle; +using Handle = cc::IndexHandle; using StringHandle = cc::StringHandle; -using StringPool = cc::StringPool; +using StringPool = cc::StringPool; template class TypedHandle final : public Handle { diff --git a/native/cocos/renderer/frame-graph/PassInsertPointManager.h b/native/cocos/renderer/frame-graph/PassInsertPointManager.h index a3300ba5a6..b64019e823 100644 --- a/native/cocos/renderer/frame-graph/PassInsertPointManager.h +++ b/native/cocos/renderer/frame-graph/PassInsertPointManager.h @@ -35,7 +35,7 @@ using PassInsertPoint = uint16_t; class PassInsertPointManager final { public: - PassInsertPointManager(const PassInsertPointManager &) = delete; + PassInsertPointManager(const PassInsertPointManager &) = delete; PassInsertPointManager(PassInsertPointManager &&) noexcept = delete; PassInsertPointManager &operator=(const PassInsertPointManager &) = delete; PassInsertPointManager &operator=(PassInsertPointManager &&) noexcept = delete; @@ -46,12 +46,12 @@ public: PassInsertPoint get(const char *name) const; private: - PassInsertPointManager() = default; + PassInsertPointManager() = default; ~PassInsertPointManager() = default; inline PassInsertPoint get(StringHandle name) const; - StringPool _stringPool; + StringPool _stringPool; ccstd::vector _insertPoints{}; }; diff --git a/native/cocos/renderer/frame-graph/PassNode.cpp b/native/cocos/renderer/frame-graph/PassNode.cpp index c624b975f7..d8511e5dae 100644 --- a/native/cocos/renderer/frame-graph/PassNode.cpp +++ b/native/cocos/renderer/frame-graph/PassNode.cpp @@ -58,10 +58,10 @@ Handle PassNode::write(FrameGraph &graph, const Handle &output) { const ResourceNode &nodeOldVersion = graph.getResourceNode(output); nodeOldVersion.virtualResource->newVersion(); - _sideEffect = _sideEffect || nodeOldVersion.virtualResource->isImported(); - const Handle handle = graph.createResourceNode(nodeOldVersion.virtualResource); + _sideEffect = _sideEffect || nodeOldVersion.virtualResource->isImported(); + const Handle handle = graph.createResourceNode(nodeOldVersion.virtualResource); ResourceNode &nodeNewVersion = graph.getResourceNode(handle); - nodeNewVersion.writer = this; + nodeNewVersion.writer = this; _writes.push_back(handle); return handle; } diff --git a/native/cocos/renderer/frame-graph/PassNode.h b/native/cocos/renderer/frame-graph/PassNode.h index 0911f2edde..e4e7ee0c42 100644 --- a/native/cocos/renderer/frame-graph/PassNode.h +++ b/native/cocos/renderer/frame-graph/PassNode.h @@ -41,52 +41,52 @@ class FrameGraph; class PassNode final { public: PassNode(PassInsertPoint inserPoint, StringHandle name, const ID &id, Executable *pass); - ~PassNode() = default; + ~PassNode() = default; PassNode(PassNode &&) noexcept = default; - PassNode(const PassNode &) = delete; + PassNode(const PassNode &) = delete; PassNode &operator=(const PassNode &) = delete; PassNode &operator=(PassNode &&) noexcept = delete; - Handle read(FrameGraph &graph, const Handle &input); - Handle write(FrameGraph &graph, const Handle &output); - void createRenderTargetAttachment(RenderTargetAttachment &&attachment); + Handle read(FrameGraph &graph, const Handle &input); + Handle write(FrameGraph &graph, const Handle &output); + void createRenderTargetAttachment(RenderTargetAttachment &&attachment); inline void sideEffect(); inline void subpass(bool end, bool clearActionIgnorable); inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor); private: - bool canMerge(const FrameGraph &graph, const PassNode &passNode) const; + bool canMerge(const FrameGraph &graph, const PassNode &passNode) const; RenderTargetAttachment *getRenderTargetAttachment(const Handle &handle); RenderTargetAttachment *getRenderTargetAttachment(const FrameGraph &graph, const VirtualResource *resource); - void requestTransientResources(); - void releaseTransientResources(); - void setDevicePassId(ID id); - Handle getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *resource) const; + void requestTransientResources(); + void releaseTransientResources(); + void setDevicePassId(ID id); + Handle getWriteResourceNodeHandle(const FrameGraph &graph, const VirtualResource *resource) const; - std::unique_ptr _pass{nullptr}; - ccstd::vector _reads{}; - ccstd::vector _writes{}; + std::unique_ptr _pass{nullptr}; + ccstd::vector _reads{}; + ccstd::vector _writes{}; ccstd::vector _attachments{}; - ccstd::vector _resourceRequestArray{}; - ccstd::vector _resourceReleaseArray{}; - const StringHandle _name; - uint32_t _refCount{0}; - PassNode * _head{nullptr}; - PassNode * _next{nullptr}; - uint16_t _distanceToHead{0}; - uint16_t _usedRenderTargetSlotMask{0}; - ID const _id{0}; - ID _devicePassId{0}; - const PassInsertPoint _insertPoint{0}; - bool _sideEffect{false}; - bool _subpass{false}; - bool _subpassEnd{false}; - bool _hasClearedAttachment{false}; - bool _clearActionIgnorable{false}; + ccstd::vector _resourceRequestArray{}; + ccstd::vector _resourceReleaseArray{}; + const StringHandle _name; + uint32_t _refCount{0}; + PassNode *_head{nullptr}; + PassNode *_next{nullptr}; + uint16_t _distanceToHead{0}; + uint16_t _usedRenderTargetSlotMask{0}; + ID const _id{0}; + ID _devicePassId{0}; + const PassInsertPoint _insertPoint{0}; + bool _sideEffect{false}; + bool _subpass{false}; + bool _subpassEnd{false}; + bool _hasClearedAttachment{false}; + bool _clearActionIgnorable{false}; - bool _customViewport{false}; + bool _customViewport{false}; gfx::Viewport _viewport; - gfx::Rect _scissor; + gfx::Rect _scissor; friend class FrameGraph; friend class DevicePass; @@ -100,15 +100,15 @@ void PassNode::sideEffect() { } void PassNode::subpass(bool end, bool clearActionIgnorable) { - _subpass = true; - _subpassEnd = end; + _subpass = true; + _subpassEnd = end; _clearActionIgnorable = clearActionIgnorable; } void PassNode::setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) { _customViewport = true; - _viewport = viewport; - _scissor = scissor; + _viewport = viewport; + _scissor = scissor; } } // namespace framegraph diff --git a/native/cocos/renderer/frame-graph/PassNodeBuilder.cpp b/native/cocos/renderer/frame-graph/PassNodeBuilder.cpp index bc55250a18..54c58027bc 100644 --- a/native/cocos/renderer/frame-graph/PassNodeBuilder.cpp +++ b/native/cocos/renderer/frame-graph/PassNodeBuilder.cpp @@ -39,13 +39,13 @@ Handle PassNodeBuilder::read(const Handle &input) const noexcept { } TextureHandle PassNodeBuilder::write(const TextureHandle &output, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept { - const TextureHandle handle(_passNode.write(_graph, output)); + const TextureHandle handle(_passNode.write(_graph, output)); RenderTargetAttachment attachment; attachment.textureHandle = handle; - attachment.desc = attachmentDesc; - attachment.level = mipmapLevel; - attachment.layer = faceId; - attachment.index = arrayPosition; + attachment.desc = attachmentDesc; + attachment.level = mipmapLevel; + attachment.layer = faceId; + attachment.index = arrayPosition; _passNode.createRenderTargetAttachment(std::forward(attachment)); if (attachmentDesc.loadOp == gfx::LoadOp::LOAD) { diff --git a/native/cocos/renderer/frame-graph/PassNodeBuilder.h b/native/cocos/renderer/frame-graph/PassNodeBuilder.h index a594c14301..31298e82f4 100644 --- a/native/cocos/renderer/frame-graph/PassNodeBuilder.h +++ b/native/cocos/renderer/frame-graph/PassNodeBuilder.h @@ -33,10 +33,10 @@ namespace framegraph { class PassNodeBuilder final { public: PassNodeBuilder(FrameGraph &graph, PassNode &passNode) noexcept; - PassNodeBuilder() = delete; - ~PassNodeBuilder() = default; + PassNodeBuilder() = delete; + ~PassNodeBuilder() = default; PassNodeBuilder(const PassNodeBuilder &) = delete; - PassNodeBuilder(PassNodeBuilder &&) = delete; + PassNodeBuilder(PassNodeBuilder &&) = delete; PassNodeBuilder &operator=(const PassNodeBuilder &) = delete; PassNodeBuilder &operator=(PassNodeBuilder &&) = delete; @@ -48,22 +48,22 @@ public: TypedHandle read(TypedHandle const &input) const noexcept; template TypedHandle write(TypedHandle const &output) const noexcept; - TextureHandle write(const TextureHandle &output, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept; - TextureHandle write(const TextureHandle &output, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept; + TextureHandle write(const TextureHandle &output, uint8_t mipmapLevel, uint8_t faceId, uint8_t arrayPosition, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept; + TextureHandle write(const TextureHandle &output, const RenderTargetAttachment::Descriptor &attachmentDesc) const noexcept; inline void sideEffect() const noexcept; inline void subpass(bool end = false, bool clearActionIgnorable = true) const noexcept; inline void setViewport(const gfx::Rect &scissor) noexcept; inline void setViewport(const gfx::Viewport &viewport, const gfx::Rect &scissor) noexcept; - void writeToBlackboard(const StringHandle &name, const Handle &handle) const noexcept; + void writeToBlackboard(const StringHandle &name, const Handle &handle) const noexcept; Handle readFromBlackboard(const StringHandle &name) const noexcept; private: Handle read(const Handle &input) const noexcept; FrameGraph &_graph; - PassNode & _passNode; + PassNode &_passNode; }; ////////////////////////////////////////////////////////////////////////// diff --git a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h index ef673f3909..e27ab7b5a7 100644 --- a/native/cocos/renderer/frame-graph/RenderTargetAttachment.h +++ b/native/cocos/renderer/frame-graph/RenderTargetAttachment.h @@ -32,8 +32,8 @@ namespace framegraph { struct RenderTargetAttachment final { using StoreOp = gfx::StoreOp; - using LoadOp = gfx::LoadOp; - using Color = gfx::Color; + using LoadOp = gfx::LoadOp; + using Color = gfx::Color; enum class Usage : uint8_t { COLOR, @@ -43,12 +43,12 @@ struct RenderTargetAttachment final { }; struct Descriptor final { - Usage usage{Usage::COLOR}; + Usage usage{Usage::COLOR}; uint8_t slot{0xff}; uint8_t writeMask{0xff}; - LoadOp loadOp{LoadOp::DISCARD}; - Color clearColor; - float clearDepth{1.F}; + LoadOp loadOp{LoadOp::DISCARD}; + Color clearColor; + float clearDepth{1.F}; uint8_t clearStencil{0U}; gfx::AccessFlags beginAccesses{gfx::AccessFlagBit::NONE}; @@ -62,12 +62,12 @@ struct RenderTargetAttachment final { static constexpr uint8_t DEPTH_STENCIL_SLOT_START{13}; TextureHandle textureHandle{}; - Descriptor desc; - uint8_t level{0}; - uint8_t layer{0}; - uint8_t index{0}; - StoreOp storeOp{StoreOp::DISCARD}; - bool isGeneralLayout{false}; + Descriptor desc; + uint8_t level{0}; + uint8_t layer{0}; + uint8_t index{0}; + StoreOp storeOp{StoreOp::DISCARD}; + bool isGeneralLayout{false}; }; inline bool RenderTargetAttachment::Sorter::operator()(const RenderTargetAttachment &a1, const RenderTargetAttachment &a2) const noexcept { diff --git a/native/cocos/renderer/frame-graph/Resource.h b/native/cocos/renderer/frame-graph/Resource.h index 0cff12ba34..55c195118e 100644 --- a/native/cocos/renderer/frame-graph/Resource.h +++ b/native/cocos/renderer/frame-graph/Resource.h @@ -51,14 +51,14 @@ template > class Resource final { public: - using Allocator = ResourceAllocator; + using Allocator = ResourceAllocator; using DeviceResource = DeviceResourceType; - using Descriptor = DescriptorType; + using Descriptor = DescriptorType; Resource() = default; explicit Resource(const Descriptor &desc); - ~Resource() = default; - Resource(const Resource &) = default; + ~Resource() = default; + Resource(const Resource &) = default; Resource(Resource &&) noexcept = default; Resource &operator=(const Resource &) = default; Resource &operator=(Resource &&) noexcept = default; @@ -66,15 +66,15 @@ public: void createTransient() noexcept; void createPersistent() noexcept; - void destroyTransient() noexcept; - void destroyPersistent() noexcept; + void destroyTransient() noexcept; + void destroyPersistent() noexcept; inline DeviceResourceType *get() const noexcept; - inline const Descriptor & getDesc() const noexcept; + inline const Descriptor &getDesc() const noexcept; private: explicit Resource(DeviceResourceType *external); - Descriptor _desc; + Descriptor _desc; DeviceResourceType *_deviceObject{nullptr}; friend class FrameGraph; @@ -138,7 +138,7 @@ const DescriptorType &Resourcecreate##Type(desc); \ } \ }; \ - using Type = Resource; \ + using Type = Resource; \ using Type##Handle = TypedHandle; \ template <> \ struct ResourceTypeLookupTable final { \ diff --git a/native/cocos/renderer/frame-graph/ResourceAllocator.h b/native/cocos/renderer/frame-graph/ResourceAllocator.h index 53c76d014c..2dc6dbd385 100644 --- a/native/cocos/renderer/frame-graph/ResourceAllocator.h +++ b/native/cocos/renderer/frame-graph/ResourceAllocator.h @@ -38,26 +38,26 @@ class ResourceAllocator final { public: using DeviceResourceCreator = DeviceResourceCreatorType; - ResourceAllocator(const ResourceAllocator &) = delete; + ResourceAllocator(const ResourceAllocator &) = delete; ResourceAllocator(ResourceAllocator &&) noexcept = delete; ResourceAllocator &operator=(const ResourceAllocator &) = delete; ResourceAllocator &operator=(ResourceAllocator &&) noexcept = delete; static ResourceAllocator &getInstance() noexcept; - DeviceResourceType * alloc(const DescriptorType &desc) noexcept; - void free(DeviceResourceType *resource) noexcept; - inline void tick() noexcept; - void gc(uint32_t unusedFrameCount) noexcept; + DeviceResourceType *alloc(const DescriptorType &desc) noexcept; + void free(DeviceResourceType *resource) noexcept; + inline void tick() noexcept; + void gc(uint32_t unusedFrameCount) noexcept; private: using DeviceResourcePool = ccstd::vector; ResourceAllocator() noexcept = default; - ~ResourceAllocator() = default; + ~ResourceAllocator() = default; ccstd::unordered_map> _pool{}; - ccstd::unordered_map _ages{}; - uint64_t _age{0}; + ccstd::unordered_map _ages{}; + uint64_t _age{0}; }; ////////////////////////////////////////////////////////////////////////// @@ -154,26 +154,26 @@ class ResourceAllocator; ResourceAllocator() noexcept = default; - ~ResourceAllocator() = default; + ~ResourceAllocator() = default; - std::unordered_map _pool{}; + std::unordered_map _pool{}; std::unordered_map _ages{}; - uint64_t _age{0}; + uint64_t _age{0}; }; ////////////////////////////////////////////////////////////////////////// @@ -187,7 +187,7 @@ ResourceAllocator DeviceResourceType *ResourceAllocator::alloc(const gfx::FramebufferInfo &desc) noexcept { - size_t hash = gfx::Hasher()(desc); + size_t hash = gfx::Hasher()(desc); DeviceResourcePool &pool{_pool[hash]}; DeviceResourceType *resource{nullptr}; diff --git a/native/cocos/renderer/frame-graph/ResourceEntry.h b/native/cocos/renderer/frame-graph/ResourceEntry.h index a128cdbdf3..5553d6c97a 100644 --- a/native/cocos/renderer/frame-graph/ResourceEntry.h +++ b/native/cocos/renderer/frame-graph/ResourceEntry.h @@ -35,15 +35,15 @@ class ResourceEntry final : public VirtualResource { public: explicit ResourceEntry(StringHandle name, ID id, const typename ResourceType::Descriptor &desc) noexcept; ResourceEntry(StringHandle name, ID id, const ResourceType &resource) noexcept; - ResourceEntry() = delete; - ~ResourceEntry() override = default; - ResourceEntry(const ResourceEntry &) = delete; + ResourceEntry() = delete; + ~ResourceEntry() override = default; + ResourceEntry(const ResourceEntry &) = delete; ResourceEntry(ResourceEntry &&) noexcept = delete; ResourceEntry &operator=(const ResourceEntry &) = delete; ResourceEntry &operator=(ResourceEntry &&) noexcept = delete; - void request() noexcept override; - void release() noexcept override; + void request() noexcept override; + void release() noexcept override; typename ResourceType::DeviceResource *getDeviceResource() const noexcept override; inline const ResourceType &get() const noexcept { return _resource; } diff --git a/native/cocos/renderer/frame-graph/ResourceNode.h b/native/cocos/renderer/frame-graph/ResourceNode.h index e95193a808..88c7bee29f 100644 --- a/native/cocos/renderer/frame-graph/ResourceNode.h +++ b/native/cocos/renderer/frame-graph/ResourceNode.h @@ -32,9 +32,9 @@ namespace framegraph { struct ResourceNode final { VirtualResource *virtualResource{nullptr}; - PassNode * writer{nullptr}; - uint32_t readerCount{0}; - uint8_t version{0}; + PassNode *writer{nullptr}; + uint32_t readerCount{0}; + uint8_t version{0}; }; } // namespace framegraph diff --git a/native/cocos/renderer/frame-graph/VirtualResource.cpp b/native/cocos/renderer/frame-graph/VirtualResource.cpp index e623e19794..53a6fdcc92 100644 --- a/native/cocos/renderer/frame-graph/VirtualResource.cpp +++ b/native/cocos/renderer/frame-graph/VirtualResource.cpp @@ -37,7 +37,7 @@ VirtualResource::VirtualResource(const StringHandle name, ID const id, bool cons void VirtualResource::updateLifetime(PassNode *const passNode) noexcept { _firstUsePass = _firstUsePass ? _firstUsePass : passNode; - _lastUsePass = passNode; + _lastUsePass = passNode; } } // namespace framegraph diff --git a/native/cocos/renderer/frame-graph/VirtualResource.h b/native/cocos/renderer/frame-graph/VirtualResource.h index c45fc092af..7a4020ea3c 100644 --- a/native/cocos/renderer/frame-graph/VirtualResource.h +++ b/native/cocos/renderer/frame-graph/VirtualResource.h @@ -38,34 +38,34 @@ using ID = uint16_t; class VirtualResource { public: VirtualResource(StringHandle name, ID id, bool imported) noexcept; - VirtualResource() noexcept = delete; - virtual ~VirtualResource() = default; - VirtualResource(const VirtualResource &) = delete; + VirtualResource() noexcept = delete; + virtual ~VirtualResource() = default; + VirtualResource(const VirtualResource &) = delete; VirtualResource(VirtualResource &&) noexcept = delete; VirtualResource &operator=(const VirtualResource &) = delete; VirtualResource &operator=(VirtualResource &&) noexcept = delete; virtual void request() noexcept = 0; virtual void release() noexcept = 0; - bool isImported() const noexcept { return _imported; } - void updateLifetime(PassNode *passNode) noexcept; - void newVersion() noexcept { ++_version; } + bool isImported() const noexcept { return _imported; } + void updateLifetime(PassNode *passNode) noexcept; + void newVersion() noexcept { ++_version; } virtual gfx::GFXObject *getDeviceResource() const noexcept = 0; private: - PassNode * _firstUsePass{nullptr}; - PassNode * _lastUsePass{nullptr}; + PassNode *_firstUsePass{nullptr}; + PassNode *_lastUsePass{nullptr}; const StringHandle _name; - uint32_t _refCount{0}; - uint16_t _writerCount{0}; - ID _id{0}; - uint8_t _version{0}; - bool const _imported{false}; - bool _neverLoaded{true}; - bool _neverStored{true}; - bool _memoryless{false}; - bool _memorylessMSAA{false}; + uint32_t _refCount{0}; + uint16_t _writerCount{0}; + ID _id{0}; + uint8_t _version{0}; + bool const _imported{false}; + bool _neverLoaded{true}; + bool _neverStored{true}; + bool _memoryless{false}; + bool _memorylessMSAA{false}; friend class FrameGraph; }; diff --git a/native/cocos/renderer/gfx-agent/BufferAgent.cpp b/native/cocos/renderer/gfx-agent/BufferAgent.cpp index 0c64203fce..3f8ef82282 100644 --- a/native/cocos/renderer/gfx-agent/BufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/BufferAgent.cpp @@ -67,7 +67,7 @@ void BufferAgent::doInit(const BufferInfo &info) { void BufferAgent::doInit(const BufferViewInfo &info) { BufferViewInfo actorInfo = info; - actorInfo.buffer = static_cast(info.buffer)->getActor(); + actorInfo.buffer = static_cast(info.buffer)->getActor(); // buffer views don't need staging buffers @@ -116,7 +116,7 @@ void BufferAgent::doResize(uint32_t size, uint32_t /*count*/) { } void BufferAgent::doDestroy() { - auto * mq = DeviceAgent::getInstance()->getMessageQueue(); + auto *mq = DeviceAgent::getInstance()->getMessageQueue(); uint8_t **oldStagingBuffers{nullptr}; if (!_stagingBuffers.empty()) { oldStagingBuffers = mq->allocate(DeviceAgent::MAX_FRAME_INDEX); @@ -142,8 +142,8 @@ void BufferAgent::doDestroy() { void BufferAgent::update(const void *buffer, uint32_t size) { uint8_t *actorBuffer{nullptr}; - bool needFreeing{false}; - auto * mq{DeviceAgent::getInstance()->getMessageQueue()}; + bool needFreeing{false}; + auto *mq{DeviceAgent::getInstance()->getMessageQueue()}; getActorBuffer(this, mq, size, &actorBuffer, &needFreeing); memcpy(actorBuffer, buffer, size); @@ -163,7 +163,7 @@ void BufferAgent::update(const void *buffer, uint32_t size) { void BufferAgent::getActorBuffer(const BufferAgent *buffer, MessageQueue *mq, uint32_t size, uint8_t **pActorBuffer, bool *pNeedFreeing) { if (!buffer->_stagingBuffers.empty()) { // for frequent updates on big buffers uint32_t frameIndex = DeviceAgent::getInstance()->getCurrentIndex(); - *pActorBuffer = buffer->_stagingBuffers[frameIndex]; + *pActorBuffer = buffer->_stagingBuffers[frameIndex]; } else if (size > STAGING_BUFFER_THRESHOLD) { // less frequent updates on big buffers *pActorBuffer = reinterpret_cast(malloc(size)); *pNeedFreeing = true; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 852e3dc0ae..61fda2088f 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -55,7 +55,7 @@ void CommandBufferAgent::flushCommands(uint32_t count, CommandBufferAgent *const return; } - uint32_t jobThreadCount = JobSystem::getInstance()->threadCount(); + uint32_t jobThreadCount = JobSystem::getInstance()->threadCount(); uint32_t workForThisThread = (count - 1) / jobThreadCount + 1; // ceil(count / jobThreadCount) if (count > workForThisThread + 1 && multiThreaded) { // more than one job to dispatch @@ -104,7 +104,7 @@ void CommandBufferAgent::destroyMessageQueue() { CC_FREE_ALIGN(_messageQueue); _messageQueue = nullptr; } - + DeviceAgent::getInstance()->_cmdBuffRefs.erase(this); } @@ -120,7 +120,7 @@ void CommandBufferAgent::doInit(const CommandBufferInfo &info) { initMessageQueue(); CommandBufferInfo actorInfo = info; - actorInfo.queue = static_cast(info.queue)->getActor(); + actorInfo.queue = static_cast(info.queue)->getActor(); ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), CommandBufferInit, @@ -168,8 +168,8 @@ void CommandBufferAgent::beginRenderPass(RenderPass *renderPass, Framebuffer *fb if (!cc::gfx::Device::getInstance()->isRendererAvailable()) { return; } - auto attachmentCount = utils::toUint(renderPass->getColorAttachments().size()); - Color *actorColors = nullptr; + auto attachmentCount = utils::toUint(renderPass->getColorAttachments().size()); + Color *actorColors = nullptr; if (attachmentCount) { actorColors = _messageQueue->allocate(attachmentCount); memcpy(actorColors, colors, sizeof(Color) * attachmentCount); @@ -380,7 +380,7 @@ void CommandBufferAgent::updateBuffer(Buffer *buff, const void *data, uint32_t s auto *bufferAgent = static_cast(buff); uint8_t *actorBuffer{nullptr}; - bool needFreeing{false}; + bool needFreeing{false}; BufferAgent::getActorBuffer(bufferAgent, _messageQueue, size, &actorBuffer, &needFreeing); memcpy(actorBuffer, data, size); @@ -435,7 +435,7 @@ void CommandBufferAgent::dispatch(const DispatchInfo &info) { void CommandBufferAgent::pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { TextureBarrier **actorTextureBarriers = nullptr; - Texture ** actorTextures = nullptr; + Texture **actorTextures = nullptr; if (textureBarrierCount) { actorTextureBarriers = _messageQueue->allocate(textureBarrierCount); diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h index 98eed5818e..fbdeede31d 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h @@ -84,8 +84,8 @@ protected: void doInit(const CommandBufferInfo &info) override; void doDestroy() override; - void initMessageQueue(); - void destroyMessageQueue(); + void initMessageQueue(); + void destroyMessageQueue(); MessageQueue *_messageQueue = nullptr; }; diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index f7ce02a2f9..df0fc65e2b 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -67,14 +67,14 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { return false; } - _api = _actor->getGfxAPI(); + _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); - _queue = ccnew QueueAgent(_actor->getQueue()); - _queryPool = ccnew QueryPoolAgent(_actor->getQueryPool()); - _cmdBuff = ccnew CommandBufferAgent(_actor->getCommandBuffer()); - _renderer = _actor->getRenderer(); - _vendor = _actor->getVendor(); - _caps = _actor->_caps; + _queue = ccnew QueueAgent(_actor->getQueue()); + _queryPool = ccnew QueryPoolAgent(_actor->getQueryPool()); + _cmdBuff = ccnew CommandBufferAgent(_actor->getCommandBuffer()); + _renderer = _actor->getRenderer(); + _vendor = _actor->getVendor(); + _caps = _actor->_caps; memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); memcpy(_formatFeatures.data(), _actor->_formatFeatures.data(), static_cast(Format::COUNT) * sizeof(FormatFeatureBit)); @@ -292,7 +292,7 @@ void doBufferTextureCopy(const uint8_t *const *buffers, Texture *texture, const //TODO(PatriceJiang): in C++17 replace with:*allocator = ccnew ThreadSafeLinearAllocator(totalSize); auto *memory = CC_MALLOC_ALIGN(sizeof(ThreadSafeLinearAllocator), alignof(ThreadSafeLinearAllocator)); auto *allocator = ccnew_placement(memory) ThreadSafeLinearAllocator(totalSize); - + auto *actorRegions = allocator->allocate(count); memcpy(actorRegions, regions, count * sizeof(BufferTextureCopy)); @@ -319,10 +319,10 @@ void doBufferTextureCopy(const uint8_t *const *buffers, Texture *texture, const { actor->copyBuffersToTexture(buffers, dst, regions, count); // TODO(PatriceJiang): C++17 replace with: delete allocator; - if (allocator) { - allocator->~ThreadSafeLinearAllocator(); - CC_FREE_ALIGN(allocator); - } + if (allocator) { + allocator->~ThreadSafeLinearAllocator(); + CC_FREE_ALIGN(allocator); + } }); } @@ -382,8 +382,8 @@ void DeviceAgent::getQueryPoolResults(QueryPool *queryPool) { actor->getQueryPoolResults(queryPool); }); - auto * actorQueryPoolAgent = static_cast(actorQueryPool); - auto * queryPoolAgent = static_cast(queryPool); + auto *actorQueryPoolAgent = static_cast(actorQueryPool); + auto *queryPoolAgent = static_cast(queryPool); std::lock_guard lock(actorQueryPoolAgent->_mutex); queryPoolAgent->_results = actorQueryPoolAgent->_results; } diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index 62e590a35e..2377d1bd30 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -41,9 +41,9 @@ class CommandBufferAgent; class CC_DLL DeviceAgent final : public Agent { public: - static DeviceAgent * getInstance(); + static DeviceAgent *getInstance(); static constexpr uint32_t MAX_CPU_FRAME_AHEAD = 1; - static constexpr uint32_t MAX_FRAME_INDEX = MAX_CPU_FRAME_AHEAD + 1; + static constexpr uint32_t MAX_FRAME_INDEX = MAX_CPU_FRAME_AHEAD + 1; ~DeviceAgent() override; @@ -68,36 +68,36 @@ public: void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; - Sampler * getSampler(const SamplerInfo &info) override; + Sampler *getSampler(const SamplerInfo &info) override; GeneralBarrier *getGeneralBarrier(const GeneralBarrierInfo &info) override; TextureBarrier *getTextureBarrier(const TextureBarrierInfo &info) override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; - void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; - void getQueryPoolResults(QueryPool *queryPool) override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } - uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } - uint32_t getNumInstances() const override { return _actor->getNumInstances(); } - uint32_t getNumTris() const override { return _actor->getNumTris(); } + uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } + uint32_t getNumInstances() const override { return _actor->getNumInstances(); } + uint32_t getNumTris() const override { return _actor->getNumTris(); } uint32_t getCurrentIndex() const { return _currentIndex; } - void setMultithreaded(bool multithreaded); + void setMultithreaded(bool multithreaded); inline MessageQueue *getMessageQueue() const { return _mainMessageQueue; } @@ -112,10 +112,10 @@ protected: bool doInit(const DeviceInfo &info) override; void doDestroy() override; - bool _multithreaded{false}; + bool _multithreaded{false}; MessageQueue *_mainMessageQueue{nullptr}; - uint32_t _currentIndex = 0U; + uint32_t _currentIndex = 0U; Semaphore _frameBoundarySemaphore{MAX_CPU_FRAME_AHEAD}; ccstd::unordered_set _cmdBuffRefs; diff --git a/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp b/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp index 635e506496..5478014b4c 100644 --- a/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp +++ b/native/cocos/renderer/gfx-agent/PipelineStateAgent.cpp @@ -51,8 +51,8 @@ PipelineStateAgent::~PipelineStateAgent() { void PipelineStateAgent::doInit(const PipelineStateInfo &info) { PipelineStateInfo actorInfo = info; - actorInfo.shader = static_cast(info.shader)->getActor(); - actorInfo.pipelineLayout = static_cast(info.pipelineLayout)->getActor(); + actorInfo.shader = static_cast(info.shader)->getActor(); + actorInfo.pipelineLayout = static_cast(info.pipelineLayout)->getActor(); if (info.renderPass) actorInfo.renderPass = static_cast(info.renderPass)->getActor(); ENQUEUE_MESSAGE_2( diff --git a/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp b/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp index 715fb04e10..928972c2af 100644 --- a/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp +++ b/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp @@ -35,8 +35,8 @@ namespace gfx { QueryPoolAgent::QueryPoolAgent(QueryPool *actor) : Agent(actor) { - _typedID = actor->getTypedID(); - _type = actor->getType(); + _typedID = actor->getTypedID(); + _type = actor->getType(); _maxQueryObjects = actor->getMaxQueryObjects(); } diff --git a/native/cocos/renderer/gfx-agent/QueueAgent.cpp b/native/cocos/renderer/gfx-agent/QueueAgent.cpp index 6ab01b9650..79372e08e0 100644 --- a/native/cocos/renderer/gfx-agent/QueueAgent.cpp +++ b/native/cocos/renderer/gfx-agent/QueueAgent.cpp @@ -72,8 +72,8 @@ void QueueAgent::doDestroy() { void QueueAgent::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { if (!count) return; - MessageQueue *msgQ = DeviceAgent::getInstance()->getMessageQueue(); - auto ** actorCmdBuffs = msgQ->allocate(count); + MessageQueue *msgQ = DeviceAgent::getInstance()->getMessageQueue(); + auto **actorCmdBuffs = msgQ->allocate(count); for (uint32_t i = 0U; i < count; ++i) { actorCmdBuffs[i] = static_cast(cmdBuffs[i])->getActor(); } diff --git a/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp b/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp index 78af3a9bd2..794e72b12f 100644 --- a/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp +++ b/native/cocos/renderer/gfx-agent/SwapchainAgent.cpp @@ -34,7 +34,7 @@ namespace gfx { SwapchainAgent::SwapchainAgent(Swapchain *actor) : Agent(actor) { - _typedID = actor->getTypedID(); + _typedID = actor->getTypedID(); _preRotationEnabled = static_cast(actor)->_preRotationEnabled; } @@ -68,9 +68,9 @@ void SwapchainAgent::doInit(const SwapchainInfo &info) { SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = _actor->getColorTexture()->getFormat(); - textureInfo.width = _actor->getWidth(); - textureInfo.height = _actor->getHeight(); + textureInfo.format = _actor->getColorTexture()->getFormat(); + textureInfo.width = _actor->getWidth(); + textureInfo.height = _actor->getHeight(); initTexture(textureInfo, _colorTexture); textureInfo.format = _actor->getDepthStencilTexture()->getFormat(); @@ -81,7 +81,7 @@ void SwapchainAgent::doInit(const SwapchainInfo &info) { void SwapchainAgent::doDestroy() { _depthStencilTexture = nullptr; - _colorTexture = nullptr; + _colorTexture = nullptr; ENQUEUE_MESSAGE_1( DeviceAgent::getInstance()->getMessageQueue(), SwapchainDestroy, @@ -106,7 +106,7 @@ void SwapchainAgent::doResize(uint32_t width, uint32_t height, SurfaceTransform mq->kickAndWait(); - auto *colorTexture = static_cast(_colorTexture.get()); + auto *colorTexture = static_cast(_colorTexture.get()); auto *depthStencilTexture = static_cast(_depthStencilTexture.get()); colorTexture->_info.width = depthStencilTexture->_info.width = _actor->getWidth(); colorTexture->_info.height = depthStencilTexture->_info.height = _actor->getHeight(); diff --git a/native/cocos/renderer/gfx-agent/TextureAgent.cpp b/native/cocos/renderer/gfx-agent/TextureAgent.cpp index c615f8a1de..15faaae43e 100644 --- a/native/cocos/renderer/gfx-agent/TextureAgent.cpp +++ b/native/cocos/renderer/gfx-agent/TextureAgent.cpp @@ -63,7 +63,7 @@ void TextureAgent::doInit(const TextureInfo &info) { void TextureAgent::doInit(const TextureViewInfo &info) { TextureViewInfo actorInfo = info; - actorInfo.texture = static_cast(info.texture)->getActor(); + actorInfo.texture = static_cast(info.texture)->getActor(); ENQUEUE_MESSAGE_2( DeviceAgent::getInstance()->getMessageQueue(), diff --git a/native/cocos/renderer/gfx-base/GFXBuffer.cpp b/native/cocos/renderer/gfx-base/GFXBuffer.cpp index d5fdfa839f..3530a906b8 100644 --- a/native/cocos/renderer/gfx-base/GFXBuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXBuffer.cpp @@ -40,24 +40,24 @@ size_t Buffer::computeHash(const BufferInfo &info) { } void Buffer::initialize(const BufferInfo &info) { - _usage = info.usage; + _usage = info.usage; _memUsage = info.memUsage; - _size = info.size; - _flags = info.flags; - _stride = std::max(info.stride, 1U); - _count = _size / _stride; + _size = info.size; + _flags = info.flags; + _stride = std::max(info.stride, 1U); + _count = _size / _stride; doInit(info); } void Buffer::initialize(const BufferViewInfo &info) { - _usage = info.buffer->getUsage(); + _usage = info.buffer->getUsage(); _memUsage = info.buffer->getMemUsage(); - _flags = info.buffer->getFlags(); - _offset = info.offset; + _flags = info.buffer->getFlags(); + _offset = info.offset; _size = _stride = info.range; - _count = 1U; - _isBufferView = true; + _count = 1U; + _isBufferView = true; doInit(info); } @@ -73,7 +73,7 @@ void Buffer::resize(uint32_t size) { uint32_t count = size / _stride; doResize(size, count); - _size = size; + _size = size; _count = count; } } diff --git a/native/cocos/renderer/gfx-base/GFXBuffer.h b/native/cocos/renderer/gfx-base/GFXBuffer.h index d605835a75..ff4da00a6e 100644 --- a/native/cocos/renderer/gfx-base/GFXBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXBuffer.h @@ -49,26 +49,26 @@ public: inline BufferUsage getUsage() const { return _usage; } inline MemoryUsage getMemUsage() const { return _memUsage; } - inline uint32_t getStride() const { return _stride; } - inline uint32_t getCount() const { return _count; } - inline uint32_t getSize() const { return _size; } + inline uint32_t getStride() const { return _stride; } + inline uint32_t getCount() const { return _count; } + inline uint32_t getSize() const { return _size; } inline BufferFlags getFlags() const { return _flags; } - inline bool isBufferView() const { return _isBufferView; } + inline bool isBufferView() const { return _isBufferView; } protected: - virtual void doInit(const BufferInfo &info) = 0; - virtual void doInit(const BufferViewInfo &info) = 0; + virtual void doInit(const BufferInfo &info) = 0; + virtual void doInit(const BufferViewInfo &info) = 0; virtual void doResize(uint32_t size, uint32_t count) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - BufferUsage _usage = BufferUsageBit::NONE; - MemoryUsage _memUsage = MemoryUsageBit::NONE; - uint32_t _stride = 0U; - uint32_t _count = 0U; - uint32_t _size = 0U; - uint32_t _offset = 0U; - BufferFlags _flags = BufferFlagBit::NONE; - bool _isBufferView = false; + BufferUsage _usage = BufferUsageBit::NONE; + MemoryUsage _memUsage = MemoryUsageBit::NONE; + uint32_t _stride = 0U; + uint32_t _count = 0U; + uint32_t _size = 0U; + uint32_t _offset = 0U; + BufferFlags _flags = BufferFlagBit::NONE; + bool _isBufferView = false; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.cpp b/native/cocos/renderer/gfx-base/GFXCommandBuffer.cpp index 5fece62f54..cfd50f5cb7 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.cpp @@ -36,7 +36,7 @@ CommandBuffer::CommandBuffer() CommandBuffer::~CommandBuffer() = default; void CommandBuffer::initialize(const CommandBufferInfo &info) { - _type = info.type; + _type = info.type; _queue = info.queue; doInit(info); @@ -45,7 +45,7 @@ void CommandBuffer::initialize(const CommandBufferInfo &info) { void CommandBuffer::destroy() { doDestroy(); - _type = CommandBufferType::PRIMARY; + _type = CommandBufferType::PRIMARY; _queue = nullptr; } diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index 6568c85bae..14e389aeb9 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -43,32 +43,32 @@ public: void initialize(const CommandBufferInfo &info); void destroy(); - virtual void begin(RenderPass *renderPass, uint32_t subpass, Framebuffer *frameBuffer) = 0; - virtual void end() = 0; + virtual void begin(RenderPass *renderPass, uint32_t subpass, Framebuffer *frameBuffer) = 0; + virtual void end() = 0; virtual void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const *secondaryCBs, uint32_t secondaryCBCount) = 0; - virtual void endRenderPass() = 0; - virtual void bindPipelineState(PipelineState *pso) = 0; - virtual void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) = 0; - virtual void bindInputAssembler(InputAssembler *ia) = 0; - virtual void setViewport(const Viewport &vp) = 0; - virtual void setScissor(const Rect &rect) = 0; - virtual void setLineWidth(float width) = 0; - virtual void setDepthBias(float constant, float clamp, float slope) = 0; - virtual void setBlendConstants(const Color &constants) = 0; - virtual void setDepthBound(float minBounds, float maxBounds) = 0; - virtual void setStencilWriteMask(StencilFace face, uint32_t mask) = 0; - virtual void setStencilCompareMask(StencilFace face, uint32_t ref, uint32_t mask) = 0; - virtual void nextSubpass() = 0; - virtual void draw(const DrawInfo &info) = 0; - virtual void updateBuffer(Buffer *buff, const void *data, uint32_t size) = 0; - virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) = 0; - virtual void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) = 0; - virtual void execute(CommandBuffer *const *cmdBuffs, uint32_t count) = 0; - virtual void dispatch(const DispatchInfo &info) = 0; - virtual void pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) = 0; - virtual void beginQuery(QueryPool *queryPool, uint32_t id) = 0; - virtual void endQuery(QueryPool *queryPool, uint32_t id) = 0; - virtual void resetQueryPool(QueryPool *queryPool) = 0; + virtual void endRenderPass() = 0; + virtual void bindPipelineState(PipelineState *pso) = 0; + virtual void bindDescriptorSet(uint32_t set, DescriptorSet *descriptorSet, uint32_t dynamicOffsetCount, const uint32_t *dynamicOffsets) = 0; + virtual void bindInputAssembler(InputAssembler *ia) = 0; + virtual void setViewport(const Viewport &vp) = 0; + virtual void setScissor(const Rect &rect) = 0; + virtual void setLineWidth(float width) = 0; + virtual void setDepthBias(float constant, float clamp, float slope) = 0; + virtual void setBlendConstants(const Color &constants) = 0; + virtual void setDepthBound(float minBounds, float maxBounds) = 0; + virtual void setStencilWriteMask(StencilFace face, uint32_t mask) = 0; + virtual void setStencilCompareMask(StencilFace face, uint32_t ref, uint32_t mask) = 0; + virtual void nextSubpass() = 0; + virtual void draw(const DrawInfo &info) = 0; + virtual void updateBuffer(Buffer *buff, const void *data, uint32_t size) = 0; + virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint32_t count) = 0; + virtual void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) = 0; + virtual void execute(CommandBuffer *const *cmdBuffs, uint32_t count) = 0; + virtual void dispatch(const DispatchInfo &info) = 0; + virtual void pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) = 0; + virtual void beginQuery(QueryPool *queryPool, uint32_t id) = 0; + virtual void endQuery(QueryPool *queryPool, uint32_t id) = 0; + virtual void resetQueryPool(QueryPool *queryPool) = 0; virtual void completeQueryPool(QueryPool *queryPool) {} inline void begin(); @@ -94,7 +94,7 @@ public: inline void pipelineBarrier(const GeneralBarrier *barrier); inline void pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrierList &textureBarriers, const TextureList &textures); - inline Queue * getQueue() const { return _queue; } + inline Queue *getQueue() const { return _queue; } inline CommandBufferType getType() const { return _type; } virtual uint32_t getNumDrawCalls() const { return _numDrawCalls; } @@ -103,10 +103,10 @@ public: protected: virtual void doInit(const CommandBufferInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - Queue * _queue = nullptr; - CommandBufferType _type = CommandBufferType::PRIMARY; + Queue *_queue = nullptr; + CommandBufferType _type = CommandBufferType::PRIMARY; uint32_t _numDrawCalls = 0; uint32_t _numInstances = 0; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 5eee56ba87..9fec323a84 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -80,22 +80,22 @@ class Window; class Context; using TextureBarrierList = ccstd::vector; -using BufferDataList = ccstd::vector; -using BufferSrcList = ccstd::vector; -using CommandBufferList = ccstd::vector; -using QueryPoolList = ccstd::vector; -using IndexList = ccstd::vector; +using BufferDataList = ccstd::vector; +using BufferSrcList = ccstd::vector; +using CommandBufferList = ccstd::vector; +using QueryPoolList = ccstd::vector; +using IndexList = ccstd::vector; -constexpr uint32_t MAX_ATTACHMENTS = 4U; -constexpr uint32_t INVALID_BINDING = ~0U; +constexpr uint32_t MAX_ATTACHMENTS = 4U; +constexpr uint32_t INVALID_BINDING = ~0U; constexpr uint32_t SUBPASS_EXTERNAL = ~0U; // Although the standard is not limited, some devices do not support up to 65536 queries constexpr uint32_t DEFAULT_MAX_QUERY_OBJECTS = 32767; -using BufferList = ccstd::vector; -using TextureList = ccstd::vector; -using SamplerList = ccstd::vector; +using BufferList = ccstd::vector; +using TextureList = ccstd::vector; +using SamplerList = ccstd::vector; using DescriptorSetLayoutList = ccstd::vector; enum class ObjectType : uint32_t { @@ -403,14 +403,14 @@ bool isSampledImage(Type type); bool isStorageImage(Type type); enum class BufferUsageBit : uint32_t { - NONE = 0, + NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, - INDEX = 0x4, - VERTEX = 0x8, - UNIFORM = 0x10, - STORAGE = 0x20, - INDIRECT = 0x40, + INDEX = 0x4, + VERTEX = 0x8, + UNIFORM = 0x10, + STORAGE = 0x20, + INDIRECT = 0x40, }; using BufferUsage = BufferUsageBit; CC_ENUM_BITWISE_OPERATORS(BufferUsageBit); @@ -422,8 +422,8 @@ using BufferFlags = BufferFlagBit; CC_ENUM_BITWISE_OPERATORS(BufferFlagBit); enum class MemoryAccessBit : uint32_t { - NONE = 0, - READ_ONLY = 0x1, + NONE = 0, + READ_ONLY = 0x1, WRITE_ONLY = 0x2, READ_WRITE = READ_ONLY | WRITE_ONLY, }; @@ -431,9 +431,9 @@ using MemoryAccess = MemoryAccessBit; CC_ENUM_BITWISE_OPERATORS(MemoryAccessBit); enum class MemoryUsageBit : uint32_t { - NONE = 0, + NONE = 0, DEVICE = 0x1, // for rarely-updated resources, use MemoryUsageBit::DEVICE - HOST = 0x2, // for frequently-updated resources, use MemoryUsageBit::DEVICE | MemoryUsageBit::HOST + HOST = 0x2, // for frequently-updated resources, use MemoryUsageBit::DEVICE | MemoryUsageBit::HOST }; using MemoryUsage = MemoryUsageBit; CC_ENUM_BITWISE_OPERATORS(MemoryUsageBit); @@ -449,32 +449,32 @@ enum class TextureType : uint32_t { CC_ENUM_CONVERSION_OPERATOR(TextureType); enum class TextureUsageBit : uint32_t { - NONE = 0, - TRANSFER_SRC = 0x1, - TRANSFER_DST = 0x2, - SAMPLED = 0x4, - STORAGE = 0x8, - COLOR_ATTACHMENT = 0x10, + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + SAMPLED = 0x4, + STORAGE = 0x8, + COLOR_ATTACHMENT = 0x10, DEPTH_STENCIL_ATTACHMENT = 0x20, - INPUT_ATTACHMENT = 0x40, + INPUT_ATTACHMENT = 0x40, }; using TextureUsage = TextureUsageBit; CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); enum class TextureFlagBit : uint32_t { - NONE = 0, - GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter + NONE = 0, + GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); enum class FormatFeatureBit : uint32_t { - NONE = 0, - RENDER_TARGET = 0x1, // Allow usages as render pass attachments - SAMPLED_TEXTURE = 0x2, // Allow sampled reads in shaders - LINEAR_FILTER = 0x4, // Allow linear filtering when sampling in shaders or blitting - STORAGE_TEXTURE = 0x8, // Allow storage reads & writes in shaders + NONE = 0, + RENDER_TARGET = 0x1, // Allow usages as render pass attachments + SAMPLED_TEXTURE = 0x2, // Allow sampled reads in shaders + LINEAR_FILTER = 0x4, // Allow linear filtering when sampling in shaders or blitting + STORAGE_TEXTURE = 0x8, // Allow storage reads & writes in shaders VERTEX_ATTRIBUTE = 0x10, // Allow usages as vertex input attributes }; using FormatFeature = FormatFeatureBit; @@ -583,23 +583,23 @@ CC_ENUM_CONVERSION_OPERATOR(BlendOp); enum class ColorMask : uint32_t { NONE = 0x0, - R = 0x1, - G = 0x2, - B = 0x4, - A = 0x8, - ALL = R | G | B | A, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, }; CC_ENUM_BITWISE_OPERATORS(ColorMask); enum class ShaderStageFlagBit : uint32_t { - NONE = 0x0, - VERTEX = 0x1, - CONTROL = 0x2, + NONE = 0x0, + VERTEX = 0x1, + CONTROL = 0x2, EVALUATION = 0x4, - GEOMETRY = 0x8, - FRAGMENT = 0x10, - COMPUTE = 0x20, - ALL = 0x3f, + GEOMETRY = 0x8, + FRAGMENT = 0x10, + COMPUTE = 0x20, + ALL = 0x3f, }; using ShaderStageFlags = ShaderStageFlagBit; CC_ENUM_BITWISE_OPERATORS(ShaderStageFlagBit); @@ -621,35 +621,35 @@ enum class AccessFlagBit : uint32_t { NONE = 0, // Read accesses - INDIRECT_BUFFER = 1 << 0, // Read as an indirect buffer for drawing or dispatch - INDEX_BUFFER = 1 << 1, // Read as an index buffer for drawing - VERTEX_BUFFER = 1 << 2, // Read as a vertex buffer for drawing - VERTEX_SHADER_READ_UNIFORM_BUFFER = 1 << 3, // Read as a uniform buffer in a vertex shader - VERTEX_SHADER_READ_TEXTURE = 1 << 4, // Read as a sampled image/uniform texel buffer in a vertex shader - VERTEX_SHADER_READ_OTHER = 1 << 5, // Read as any other resource in a vertex shader - FRAGMENT_SHADER_READ_UNIFORM_BUFFER = 1 << 6, // Read as a uniform buffer in a fragment shader - FRAGMENT_SHADER_READ_TEXTURE = 1 << 7, // Read as a sampled image/uniform texel buffer in a fragment shader - FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT = 1 << 8, // Read as an input attachment with a color format in a fragment shader - FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT = 1 << 9, // Read as an input attachment with a depth/stencil format in a fragment shader - FRAGMENT_SHADER_READ_OTHER = 1 << 10, // Read as any other resource in a fragment shader - COLOR_ATTACHMENT_READ = 1 << 11, // Read by standard blending/logic operations or subpass load operations - DEPTH_STENCIL_ATTACHMENT_READ = 1 << 12, // Read by depth/stencil tests or subpass load operations - COMPUTE_SHADER_READ_UNIFORM_BUFFER = 1 << 13, // Read as a uniform buffer in a compute shader - COMPUTE_SHADER_READ_TEXTURE = 1 << 14, // Read as a sampled image/uniform texel buffer in a compute shader - COMPUTE_SHADER_READ_OTHER = 1 << 15, // Read as any other resource in a compute shader - TRANSFER_READ = 1 << 16, // Read as the source of a transfer operation - HOST_READ = 1 << 17, // Read on the host - PRESENT = 1 << 18, // Read by the presentation engine + INDIRECT_BUFFER = 1 << 0, // Read as an indirect buffer for drawing or dispatch + INDEX_BUFFER = 1 << 1, // Read as an index buffer for drawing + VERTEX_BUFFER = 1 << 2, // Read as a vertex buffer for drawing + VERTEX_SHADER_READ_UNIFORM_BUFFER = 1 << 3, // Read as a uniform buffer in a vertex shader + VERTEX_SHADER_READ_TEXTURE = 1 << 4, // Read as a sampled image/uniform texel buffer in a vertex shader + VERTEX_SHADER_READ_OTHER = 1 << 5, // Read as any other resource in a vertex shader + FRAGMENT_SHADER_READ_UNIFORM_BUFFER = 1 << 6, // Read as a uniform buffer in a fragment shader + FRAGMENT_SHADER_READ_TEXTURE = 1 << 7, // Read as a sampled image/uniform texel buffer in a fragment shader + FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT = 1 << 8, // Read as an input attachment with a color format in a fragment shader + FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT = 1 << 9, // Read as an input attachment with a depth/stencil format in a fragment shader + FRAGMENT_SHADER_READ_OTHER = 1 << 10, // Read as any other resource in a fragment shader + COLOR_ATTACHMENT_READ = 1 << 11, // Read by standard blending/logic operations or subpass load operations + DEPTH_STENCIL_ATTACHMENT_READ = 1 << 12, // Read by depth/stencil tests or subpass load operations + COMPUTE_SHADER_READ_UNIFORM_BUFFER = 1 << 13, // Read as a uniform buffer in a compute shader + COMPUTE_SHADER_READ_TEXTURE = 1 << 14, // Read as a sampled image/uniform texel buffer in a compute shader + COMPUTE_SHADER_READ_OTHER = 1 << 15, // Read as any other resource in a compute shader + TRANSFER_READ = 1 << 16, // Read as the source of a transfer operation + HOST_READ = 1 << 17, // Read on the host + PRESENT = 1 << 18, // Read by the presentation engine // Write accesses - VERTEX_SHADER_WRITE = 1 << 19, // Written as any resource in a vertex shader - FRAGMENT_SHADER_WRITE = 1 << 20, // Written as any resource in a fragment shader - COLOR_ATTACHMENT_WRITE = 1 << 21, // Written as a color attachment during rendering, or via a subpass store op + VERTEX_SHADER_WRITE = 1 << 19, // Written as any resource in a vertex shader + FRAGMENT_SHADER_WRITE = 1 << 20, // Written as any resource in a fragment shader + COLOR_ATTACHMENT_WRITE = 1 << 21, // Written as a color attachment during rendering, or via a subpass store op DEPTH_STENCIL_ATTACHMENT_WRITE = 1 << 22, // Written as a depth/stencil attachment during rendering, or via a subpass store op - COMPUTE_SHADER_WRITE = 1 << 23, // Written as any resource in a compute shader - TRANSFER_WRITE = 1 << 24, // Written as the destination of a transfer operation - HOST_PREINITIALIZED = 1 << 25, // Data pre-filled by host before device access starts - HOST_WRITE = 1 << 26, // Written on the host + COMPUTE_SHADER_WRITE = 1 << 23, // Written as any resource in a compute shader + TRANSFER_WRITE = 1 << 24, // Written as the destination of a transfer operation + HOST_PREINITIALIZED = 1 << 25, // Data pre-filled by host before device access starts + HOST_WRITE = 1 << 26, // Written on the host }; CC_ENUM_BITWISE_OPERATORS(AccessFlagBit); using AccessFlags = AccessFlagBit; @@ -710,12 +710,12 @@ enum class CullMode : uint32_t { CC_ENUM_CONVERSION_OPERATOR(CullMode); enum class DynamicStateFlagBit : uint32_t { - NONE = 0x0, - LINE_WIDTH = 0x1, - DEPTH_BIAS = 0x2, - BLEND_CONSTANTS = 0x4, - DEPTH_BOUNDS = 0x8, - STENCIL_WRITE_MASK = 0x10, + NONE = 0x0, + LINE_WIDTH = 0x1, + DEPTH_BIAS = 0x2, + BLEND_CONSTANTS = 0x4, + DEPTH_BOUNDS = 0x8, + STENCIL_WRITE_MASK = 0x10, STENCIL_COMPARE_MASK = 0x20, }; using DynamicStateFlags = DynamicStateFlagBit; @@ -725,22 +725,22 @@ using DynamicStateList = ccstd::vector; enum class StencilFace : uint32_t { FRONT = 0x1, - BACK = 0x2, - ALL = 0x3, + BACK = 0x2, + ALL = 0x3, }; CC_ENUM_BITWISE_OPERATORS(StencilFace); enum class DescriptorType : uint32_t { - UNKNOWN = 0, - UNIFORM_BUFFER = 0x1, + UNKNOWN = 0, + UNIFORM_BUFFER = 0x1, DYNAMIC_UNIFORM_BUFFER = 0x2, - STORAGE_BUFFER = 0x4, + STORAGE_BUFFER = 0x4, DYNAMIC_STORAGE_BUFFER = 0x8, - SAMPLER_TEXTURE = 0x10, - SAMPLER = 0x20, - TEXTURE = 0x40, - STORAGE_IMAGE = 0x80, - INPUT_ATTACHMENT = 0x100, + SAMPLER_TEXTURE = 0x10, + SAMPLER = 0x20, + TEXTURE = 0x40, + STORAGE_IMAGE = 0x80, + INPUT_ATTACHMENT = 0x100, }; CC_ENUM_BITWISE_OPERATORS(DescriptorType); @@ -765,12 +765,12 @@ enum class CommandBufferType : uint32_t { CC_ENUM_CONVERSION_OPERATOR(CommandBufferType); enum class ClearFlagBit : uint32_t { - NONE = 0, - COLOR = 0x1, - DEPTH = 0x2, - STENCIL = 0x4, + NONE = 0, + COLOR = 0x1, + DEPTH = 0x2, + STENCIL = 0x4, DEPTH_STENCIL = DEPTH | STENCIL, - ALL = COLOR | DEPTH | STENCIL, + ALL = COLOR | DEPTH | STENCIL, }; using ClearFlags = ClearFlagBit; CC_ENUM_BITWISE_OPERATORS(ClearFlagBit); @@ -807,8 +807,8 @@ struct DeviceCaps { uint32_t maxComputeSharedMemorySize{0}; uint32_t maxComputeWorkGroupInvocations{0}; - Size maxComputeWorkGroupSize; - Size maxComputeWorkGroupCount; + Size maxComputeWorkGroupSize; + Size maxComputeWorkGroupCount; bool supportQuery{false}; @@ -828,8 +828,8 @@ struct Offset { }; struct Rect { - int32_t x{0}; - int32_t y{0}; + int32_t x{0}; + int32_t y{0}; uint32_t width{0}; uint32_t height{0}; @@ -863,31 +863,31 @@ struct TextureSubresRange { struct TextureCopy { TextureSubresLayers srcSubres; - Offset srcOffset; + Offset srcOffset; TextureSubresLayers dstSubres; - Offset dstOffset; - Extent extent; + Offset dstOffset; + Extent extent; EXPOSE_COPY_FN(TextureCopy) }; struct TextureBlit { TextureSubresLayers srcSubres; - Offset srcOffset; - Extent srcExtent; + Offset srcOffset; + Extent srcExtent; TextureSubresLayers dstSubres; - Offset dstOffset; - Extent dstExtent; + Offset dstOffset; + Extent dstExtent; EXPOSE_COPY_FN(TextureBlit) }; using TextureBlitList = ccstd::vector; struct BufferTextureCopy { - uint32_t buffStride{0}; - uint32_t buffTexHeight{0}; - Offset texOffset; - Extent texExtent; + uint32_t buffStride{0}; + uint32_t buffTexHeight{0}; + Offset texOffset; + Extent texExtent; TextureSubresLayers texSubres; EXPOSE_COPY_FN(BufferTextureCopy) @@ -895,12 +895,12 @@ struct BufferTextureCopy { using BufferTextureCopyList = ccstd::vector; struct Viewport { - int32_t left{0}; - int32_t top{0}; + int32_t left{0}; + int32_t top{0}; uint32_t width{0}; uint32_t height{0}; - float minDepth{0.F}; - float maxDepth{1.F}; + float minDepth{0.F}; + float maxDepth{1.F}; EXPOSE_COPY_FN(Viewport) }; @@ -945,7 +945,7 @@ struct BindingMappingInfo { }; struct SwapchainInfo { - void * windowHandle{nullptr}; // @ts-overrides { type: 'HTMLCanvasElement' } + void *windowHandle{nullptr}; // @ts-overrides { type: 'HTMLCanvasElement' } VsyncMode vsyncMode{VsyncMode::ON}; uint32_t width{0}; @@ -963,16 +963,16 @@ struct DeviceInfo { struct ALIGNAS(8) BufferInfo { BufferUsage usage{BufferUsageBit::NONE}; MemoryUsage memUsage{MemoryUsageBit::NONE}; - uint32_t size{0}; - uint32_t stride{1}; // in bytes + uint32_t size{0}; + uint32_t stride{1}; // in bytes BufferFlags flags{BufferFlagBit::NONE}; - uint32_t _padding{0}; + uint32_t _padding{0}; EXPOSE_COPY_FN(BufferInfo) }; struct BufferViewInfo { - Buffer * buffer{nullptr}; + Buffer *buffer{nullptr}; uint32_t offset{0}; uint32_t range{0}; @@ -984,7 +984,7 @@ struct DrawInfo { uint32_t firstVertex{0}; uint32_t indexCount{0}; uint32_t firstIndex{0}; - int32_t vertexOffset{0}; + int32_t vertexOffset{0}; uint32_t instanceCount{0}; uint32_t firstInstance{0}; @@ -998,7 +998,7 @@ struct DispatchInfo { uint32_t groupCountY{0}; uint32_t groupCountZ{0}; - Buffer * indirectBuffer{nullptr}; // @ts-nullable + Buffer *indirectBuffer{nullptr}; // @ts-nullable uint32_t indirectOffset{0}; EXPOSE_COPY_FN(DispatchInfo) @@ -1013,17 +1013,17 @@ struct IndirectBuffer { }; struct ALIGNAS(8) TextureInfo { - TextureType type{TextureType::TEX2D}; + TextureType type{TextureType::TEX2D}; TextureUsage usage{TextureUsageBit::NONE}; - Format format{Format::UNKNOWN}; - uint32_t width{0}; - uint32_t height{0}; + Format format{Format::UNKNOWN}; + uint32_t width{0}; + uint32_t height{0}; TextureFlags flags{TextureFlagBit::NONE}; - uint32_t layerCount{1}; - uint32_t levelCount{1}; - SampleCount samples{SampleCount::ONE}; - uint32_t depth{1}; - void * externalRes{nullptr}; // CVPixelBuffer for Metal, EGLImage for GLES + uint32_t layerCount{1}; + uint32_t levelCount{1}; + SampleCount samples{SampleCount::ONE}; + uint32_t depth{1}; + void *externalRes{nullptr}; // CVPixelBuffer for Metal, EGLImage for GLES #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; #endif @@ -1032,13 +1032,13 @@ struct ALIGNAS(8) TextureInfo { }; struct ALIGNAS(8) TextureViewInfo { - Texture * texture{nullptr}; + Texture *texture{nullptr}; TextureType type{TextureType::TEX2D}; - Format format{Format::UNKNOWN}; - uint32_t baseLevel{0}; - uint32_t levelCount{1}; - uint32_t baseLayer{0}; - uint32_t layerCount{1}; + Format format{Format::UNKNOWN}; + uint32_t baseLevel{0}; + uint32_t levelCount{1}; + uint32_t baseLayer{0}; + uint32_t layerCount{1}; #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; #endif @@ -1047,13 +1047,13 @@ struct ALIGNAS(8) TextureViewInfo { }; struct ALIGNAS(8) SamplerInfo { - Filter minFilter{Filter::LINEAR}; - Filter magFilter{Filter::LINEAR}; - Filter mipFilter{Filter::NONE}; - Address addressU{Address::WRAP}; - Address addressV{Address::WRAP}; - Address addressW{Address::WRAP}; - uint32_t maxAnisotropy{0}; + Filter minFilter{Filter::LINEAR}; + Filter magFilter{Filter::LINEAR}; + Filter mipFilter{Filter::NONE}; + Address addressU{Address::WRAP}; + Address addressV{Address::WRAP}; + Address addressW{Address::WRAP}; + uint32_t maxAnisotropy{0}; ComparisonFunc cmpFunc{ComparisonFunc::ALWAYS}; EXPOSE_COPY_FN(SamplerInfo) @@ -1061,8 +1061,8 @@ struct ALIGNAS(8) SamplerInfo { struct Uniform { ccstd::string name; - Type type{Type::UNKNOWN}; - uint32_t count{0}; + Type type{Type::UNKNOWN}; + uint32_t count{0}; EXPOSE_COPY_FN(Uniform) }; @@ -1070,11 +1070,11 @@ struct Uniform { using UniformList = ccstd::vector; struct UniformBlock { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - UniformList members; - uint32_t count{0}; + UniformList members; + uint32_t count{0}; EXPOSE_COPY_FN(UniformBlock) }; @@ -1082,11 +1082,11 @@ struct UniformBlock { using UniformBlockList = ccstd::vector; struct UniformSamplerTexture { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - Type type{Type::UNKNOWN}; - uint32_t count{0}; + Type type{Type::UNKNOWN}; + uint32_t count{0}; EXPOSE_COPY_FN(UniformSamplerTexture) }; @@ -1094,10 +1094,10 @@ struct UniformSamplerTexture { using UniformSamplerTextureList = ccstd::vector; struct UniformSampler { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - uint32_t count{0}; + uint32_t count{0}; EXPOSE_COPY_FN(UniformSampler) }; @@ -1105,11 +1105,11 @@ struct UniformSampler { using UniformSamplerList = ccstd::vector; struct UniformTexture { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - Type type{Type::UNKNOWN}; - uint32_t count{0}; + Type type{Type::UNKNOWN}; + uint32_t count{0}; EXPOSE_COPY_FN(UniformTexture) }; @@ -1117,12 +1117,12 @@ struct UniformTexture { using UniformTextureList = ccstd::vector; struct UniformStorageImage { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - Type type{Type::UNKNOWN}; - uint32_t count{0}; - MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; + Type type{Type::UNKNOWN}; + uint32_t count{0}; + MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; EXPOSE_COPY_FN(UniformStorageImage) }; @@ -1130,11 +1130,11 @@ struct UniformStorageImage { using UniformStorageImageList = ccstd::vector; struct UniformStorageBuffer { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - uint32_t count{0}; - MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; + uint32_t count{0}; + MemoryAccess memoryAccess{MemoryAccessBit::READ_WRITE}; EXPOSE_COPY_FN(UniformStorageBuffer) }; @@ -1142,10 +1142,10 @@ struct UniformStorageBuffer { using UniformStorageBufferList = ccstd::vector; struct UniformInputAttachment { - uint32_t set{0}; - uint32_t binding{0}; + uint32_t set{0}; + uint32_t binding{0}; ccstd::string name; - uint32_t count{0}; + uint32_t count{0}; EXPOSE_COPY_FN(UniformInputAttachment) }; @@ -1154,7 +1154,7 @@ using UniformInputAttachmentList = ccstd::vector; struct ShaderStage { ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; - ccstd::string source; + ccstd::string source; EXPOSE_COPY_FN(ShaderStage) }; @@ -1163,27 +1163,27 @@ using ShaderStageList = ccstd::vector; struct Attribute { ccstd::string name; - Format format{Format::UNKNOWN}; - bool isNormalized{false}; - uint32_t stream{0}; - bool isInstanced{false}; - uint32_t location{0}; + Format format{Format::UNKNOWN}; + bool isNormalized{false}; + uint32_t stream{0}; + bool isInstanced{false}; + uint32_t location{0}; EXPOSE_COPY_FN(Attribute) }; using AttributeList = ccstd::vector; -constexpr const char *ATTR_NAME_POSITION = "a_position"; -constexpr const char *ATTR_NAME_NORMAL = "a_normal"; -constexpr const char *ATTR_NAME_TANGENT = "a_tangent"; -constexpr const char *ATTR_NAME_BITANGENT = "a_bitangent"; -constexpr const char *ATTR_NAME_WEIGHTS = "a_weights"; -constexpr const char *ATTR_NAME_JOINTS = "a_joints"; -constexpr const char *ATTR_NAME_COLOR = "a_color"; -constexpr const char *ATTR_NAME_COLOR1 = "a_color1"; -constexpr const char *ATTR_NAME_COLOR2 = "a_color2"; -constexpr const char *ATTR_NAME_TEX_COORD = "a_texCoord"; +constexpr const char *ATTR_NAME_POSITION = "a_position"; +constexpr const char *ATTR_NAME_NORMAL = "a_normal"; +constexpr const char *ATTR_NAME_TANGENT = "a_tangent"; +constexpr const char *ATTR_NAME_BITANGENT = "a_bitangent"; +constexpr const char *ATTR_NAME_WEIGHTS = "a_weights"; +constexpr const char *ATTR_NAME_JOINTS = "a_joints"; +constexpr const char *ATTR_NAME_COLOR = "a_color"; +constexpr const char *ATTR_NAME_COLOR1 = "a_color1"; +constexpr const char *ATTR_NAME_COLOR2 = "a_color2"; +constexpr const char *ATTR_NAME_TEX_COORD = "a_texCoord"; constexpr const char *ATTR_NAME_TEX_COORD1 = "a_texCoord1"; constexpr const char *ATTR_NAME_TEX_COORD2 = "a_texCoord2"; constexpr const char *ATTR_NAME_TEX_COORD3 = "a_texCoord3"; @@ -1192,19 +1192,19 @@ constexpr const char *ATTR_NAME_TEX_COORD5 = "a_texCoord5"; constexpr const char *ATTR_NAME_TEX_COORD6 = "a_texCoord6"; constexpr const char *ATTR_NAME_TEX_COORD7 = "a_texCoord7"; constexpr const char *ATTR_NAME_TEX_COORD8 = "a_texCoord8"; -constexpr const char *ATTR_NAME_BATCH_ID = "a_batch_id"; -constexpr const char *ATTR_NAME_BATCH_UV = "a_batch_uv"; +constexpr const char *ATTR_NAME_BATCH_ID = "a_batch_id"; +constexpr const char *ATTR_NAME_BATCH_UV = "a_batch_uv"; struct ShaderInfo { - ccstd::string name; - ShaderStageList stages; - AttributeList attributes; - UniformBlockList blocks; - UniformStorageBufferList buffers; - UniformSamplerTextureList samplerTextures; - UniformSamplerList samplers; - UniformTextureList textures; - UniformStorageImageList images; + ccstd::string name; + ShaderStageList stages; + AttributeList attributes; + UniformBlockList blocks; + UniformStorageBufferList buffers; + UniformSamplerTextureList samplerTextures; + UniformSamplerList samplers; + UniformTextureList textures; + UniformStorageImageList images; UniformInputAttachmentList subpassInputs; EXPOSE_COPY_FN(ShaderInfo) @@ -1212,20 +1212,20 @@ struct ShaderInfo { struct InputAssemblerInfo { AttributeList attributes; - BufferList vertexBuffers; - Buffer * indexBuffer{nullptr}; // @ts-nullable - Buffer * indirectBuffer{nullptr}; // @ts-nullable + BufferList vertexBuffers; + Buffer *indexBuffer{nullptr}; // @ts-nullable + Buffer *indirectBuffer{nullptr}; // @ts-nullable EXPOSE_COPY_FN(InputAssemblerInfo) }; struct ALIGNAS(8) ColorAttachment { - Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; - LoadOp loadOp{LoadOp::CLEAR}; - StoreOp storeOp{StoreOp::STORE}; + Format format{Format::UNKNOWN}; + SampleCount sampleCount{SampleCount::ONE}; + LoadOp loadOp{LoadOp::CLEAR}; + StoreOp storeOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; - uint32_t isGeneralLayout{0}; // @ts-boolean + uint32_t isGeneralLayout{0}; // @ts-boolean #if CC_CPU_ARCH == CC_CPU_ARCH_64 uint32_t _padding{0}; #endif @@ -1236,14 +1236,14 @@ struct ALIGNAS(8) ColorAttachment { using ColorAttachmentList = ccstd::vector; struct ALIGNAS(8) DepthStencilAttachment { - Format format{Format::UNKNOWN}; - SampleCount sampleCount{SampleCount::ONE}; - LoadOp depthLoadOp{LoadOp::CLEAR}; - StoreOp depthStoreOp{StoreOp::STORE}; - LoadOp stencilLoadOp{LoadOp::CLEAR}; - StoreOp stencilStoreOp{StoreOp::STORE}; + Format format{Format::UNKNOWN}; + SampleCount sampleCount{SampleCount::ONE}; + LoadOp depthLoadOp{LoadOp::CLEAR}; + StoreOp depthStoreOp{StoreOp::STORE}; + LoadOp stencilLoadOp{LoadOp::CLEAR}; + StoreOp stencilStoreOp{StoreOp::STORE}; GeneralBarrier *barrier{nullptr}; - uint32_t isGeneralLayout{0}; // @ts-boolean + uint32_t isGeneralLayout{0}; // @ts-boolean #if CC_CPU_ARCH == CC_CPU_ARCH_64 uint32_t _padding{0}; #endif @@ -1257,8 +1257,8 @@ struct SubpassInfo { IndexList resolves; IndexList preserves; - uint32_t depthStencil{INVALID_BINDING}; - uint32_t depthStencilResolve{INVALID_BINDING}; + uint32_t depthStencil{INVALID_BINDING}; + uint32_t depthStencilResolve{INVALID_BINDING}; ResolveMode depthResolveMode{ResolveMode::NONE}; ResolveMode stencilResolveMode{ResolveMode::NONE}; @@ -1268,8 +1268,8 @@ struct SubpassInfo { using SubpassInfoList = ccstd::vector; struct ALIGNAS(8) SubpassDependency { - uint32_t srcSubpass{0}; - uint32_t dstSubpass{0}; + uint32_t srcSubpass{0}; + uint32_t dstSubpass{0}; GeneralBarrier *barrier{nullptr}; #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; @@ -1281,10 +1281,10 @@ struct ALIGNAS(8) SubpassDependency { using SubpassDependencyList = ccstd::vector; struct RenderPassInfo { - ColorAttachmentList colorAttachments; + ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; - SubpassInfoList subpasses; - SubpassDependencyList dependencies; + SubpassInfoList subpasses; + SubpassDependencyList dependencies; EXPOSE_COPY_FN(RenderPassInfo) }; @@ -1313,17 +1313,17 @@ using TextureBarrierInfoList = ccstd::vector; struct FramebufferInfo { RenderPass *renderPass{nullptr}; TextureList colorTextures; - Texture * depthStencilTexture{nullptr}; // @ts-nullable + Texture *depthStencilTexture{nullptr}; // @ts-nullable EXPOSE_COPY_FN(FramebufferInfo) }; struct DescriptorSetLayoutBinding { - uint32_t binding{INVALID_BINDING}; - DescriptorType descriptorType{DescriptorType::UNKNOWN}; - uint32_t count{0}; + uint32_t binding{INVALID_BINDING}; + DescriptorType descriptorType{DescriptorType::UNKNOWN}; + uint32_t count{0}; ShaderStageFlags stageFlags{ShaderStageFlagBit::NONE}; - SamplerList immutableSamplers; + SamplerList immutableSamplers; EXPOSE_COPY_FN(DescriptorSetLayoutBinding) }; @@ -1355,18 +1355,18 @@ struct InputState { // The memory layout of this structure should exactly match a plain `Uint32Array` struct RasterizerState { - uint32_t isDiscard{0}; // @ts-boolean + uint32_t isDiscard{0}; // @ts-boolean PolygonMode polygonMode{PolygonMode::FILL}; - ShadeModel shadeModel{ShadeModel::GOURAND}; - CullMode cullMode{CullMode::BACK}; - uint32_t isFrontFaceCCW{1}; // @ts-boolean - uint32_t depthBiasEnabled{0}; // @ts-boolean - float depthBias{0.F}; - float depthBiasClamp{0.F}; - float depthBiasSlop{0.F}; - uint32_t isDepthClip{1}; // @ts-boolean - uint32_t isMultisample{0}; // @ts-boolean - float lineWidth{1.F}; + ShadeModel shadeModel{ShadeModel::GOURAND}; + CullMode cullMode{CullMode::BACK}; + uint32_t isFrontFaceCCW{1}; // @ts-boolean + uint32_t depthBiasEnabled{0}; // @ts-boolean + float depthBias{0.F}; + float depthBiasClamp{0.F}; + float depthBiasSlop{0.F}; + uint32_t isDepthClip{1}; // @ts-boolean + uint32_t isMultisample{0}; // @ts-boolean + float lineWidth{1.F}; void reset() { *this = RasterizerState(); @@ -1377,25 +1377,25 @@ struct RasterizerState { // The memory layout of this structure should exactly match a plain `Uint32Array` struct DepthStencilState { - uint32_t depthTest{1}; // @ts-boolean - uint32_t depthWrite{1}; // @ts-boolean + uint32_t depthTest{1}; // @ts-boolean + uint32_t depthWrite{1}; // @ts-boolean ComparisonFunc depthFunc{ComparisonFunc::LESS}; - uint32_t stencilTestFront{0}; // @ts-boolean + uint32_t stencilTestFront{0}; // @ts-boolean ComparisonFunc stencilFuncFront{ComparisonFunc::ALWAYS}; - uint32_t stencilReadMaskFront{0xffffffff}; - uint32_t stencilWriteMaskFront{0xffffffff}; - StencilOp stencilFailOpFront{StencilOp::KEEP}; - StencilOp stencilZFailOpFront{StencilOp::KEEP}; - StencilOp stencilPassOpFront{StencilOp::KEEP}; - uint32_t stencilRefFront{1}; - uint32_t stencilTestBack{0}; // @ts-boolean + uint32_t stencilReadMaskFront{0xffffffff}; + uint32_t stencilWriteMaskFront{0xffffffff}; + StencilOp stencilFailOpFront{StencilOp::KEEP}; + StencilOp stencilZFailOpFront{StencilOp::KEEP}; + StencilOp stencilPassOpFront{StencilOp::KEEP}; + uint32_t stencilRefFront{1}; + uint32_t stencilTestBack{0}; // @ts-boolean ComparisonFunc stencilFuncBack{ComparisonFunc::ALWAYS}; - uint32_t stencilReadMaskBack{0xffffffff}; - uint32_t stencilWriteMaskBack{0xffffffff}; - StencilOp stencilFailOpBack{StencilOp::KEEP}; - StencilOp stencilZFailOpBack{StencilOp::KEEP}; - StencilOp stencilPassOpBack{StencilOp::KEEP}; - uint32_t stencilRefBack{1}; + uint32_t stencilReadMaskBack{0xffffffff}; + uint32_t stencilWriteMaskBack{0xffffffff}; + StencilOp stencilFailOpBack{StencilOp::KEEP}; + StencilOp stencilZFailOpBack{StencilOp::KEEP}; + StencilOp stencilPassOpBack{StencilOp::KEEP}; + uint32_t stencilRefBack{1}; void reset() { *this = DepthStencilState(); @@ -1405,14 +1405,14 @@ struct DepthStencilState { }; struct BlendTarget { - uint32_t blend{0}; // @ts-boolean + uint32_t blend{0}; // @ts-boolean BlendFactor blendSrc{BlendFactor::ONE}; BlendFactor blendDst{BlendFactor::ZERO}; - BlendOp blendEq{BlendOp::ADD}; + BlendOp blendEq{BlendOp::ADD}; BlendFactor blendSrcAlpha{BlendFactor::ONE}; BlendFactor blendDstAlpha{BlendFactor::ZERO}; - BlendOp blendAlphaEq{BlendOp::ADD}; - ColorMask blendColorMask{ColorMask::ALL}; + BlendOp blendAlphaEq{BlendOp::ADD}; + ColorMask blendColorMask{ColorMask::ALL}; void reset() { *this = BlendTarget(); @@ -1425,9 +1425,9 @@ using BlendTargetList = ccstd::vector; // The memory layout of this structure should exactly match a plain `Uint32Array` struct BlendState { - uint32_t isA2C{0}; // @ts-boolean - uint32_t isIndepend{0}; // @ts-boolean - Color blendColor; + uint32_t isA2C{0}; // @ts-boolean + uint32_t isIndepend{0}; // @ts-boolean + Color blendColor; BlendTargetList targets{1}; void setTarget(index_t index, const BlendTarget &target) { @@ -1447,23 +1447,23 @@ struct BlendState { }; struct PipelineStateInfo { - Shader * shader{nullptr}; - PipelineLayout * pipelineLayout{nullptr}; - RenderPass * renderPass{nullptr}; - InputState inputState; - RasterizerState rasterizerState; + Shader *shader{nullptr}; + PipelineLayout *pipelineLayout{nullptr}; + RenderPass *renderPass{nullptr}; + InputState inputState; + RasterizerState rasterizerState; DepthStencilState depthStencilState; - BlendState blendState; - PrimitiveMode primitive{PrimitiveMode::TRIANGLE_LIST}; + BlendState blendState; + PrimitiveMode primitive{PrimitiveMode::TRIANGLE_LIST}; DynamicStateFlags dynamicStates{DynamicStateFlagBit::NONE}; PipelineBindPoint bindPoint{PipelineBindPoint::GRAPHICS}; - uint32_t subpass{0}; + uint32_t subpass{0}; EXPOSE_COPY_FN(PipelineStateInfo) }; struct CommandBufferInfo { - Queue * queue{nullptr}; + Queue *queue{nullptr}; CommandBufferType type{CommandBufferType::PRIMARY}; EXPOSE_COPY_FN(CommandBufferInfo) @@ -1477,21 +1477,21 @@ struct QueueInfo { struct QueryPoolInfo { QueryType type{QueryType::OCCLUSION}; - uint32_t maxQueryObjects{DEFAULT_MAX_QUERY_OBJECTS}; - bool forceWait{true}; + uint32_t maxQueryObjects{DEFAULT_MAX_QUERY_OBJECTS}; + bool forceWait{true}; EXPOSE_COPY_FN(QueryPoolInfo) }; struct FormatInfo { const ccstd::string name; - const uint32_t size{0}; - const uint32_t count{0}; - const FormatType type{FormatType::NONE}; - const bool hasAlpha{false}; - const bool hasDepth{false}; - const bool hasStencil{false}; - const bool isCompressed{false}; + const uint32_t size{0}; + const uint32_t count{0}; + const FormatType type{FormatType::NONE}; + const bool hasAlpha{false}; + const bool hasDepth{false}; + const bool hasStencil{false}; + const bool isCompressed{false}; }; struct MemoryStatus { @@ -1511,14 +1511,14 @@ struct DynamicStencilStates { struct DynamicStates { Viewport viewport; - Rect scissor; - Color blendConstant; - float lineWidth{1.F}; - float depthBiasConstant{0.F}; - float depthBiasClamp{0.F}; - float depthBiasSlope{0.F}; - float depthMinBounds{0.F}; - float depthMaxBounds{0.F}; + Rect scissor; + Color blendConstant; + float lineWidth{1.F}; + float depthBiasConstant{0.F}; + float depthBiasClamp{0.F}; + float depthBiasSlope{0.F}; + float depthMinBounds{0.F}; + float depthMaxBounds{0.F}; DynamicStencilStates stencilStatesFront; DynamicStencilStates stencilStatesBack; diff --git a/native/cocos/renderer/gfx-base/GFXDef.cpp b/native/cocos/renderer/gfx-base/GFXDef.cpp index f13aaa4058..24d32c31da 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.cpp +++ b/native/cocos/renderer/gfx-base/GFXDef.cpp @@ -121,7 +121,7 @@ size_t Hasher::operator()(const FramebufferInfo &info) const { } else { seed = info.colorTextures.size() * 3; } - for (auto* colorTexture : info.colorTextures) { + for (auto *colorTexture : info.colorTextures) { boost::hash_combine(seed, colorTexture); boost::hash_combine(seed, colorTexture->getRaw()); boost::hash_combine(seed, colorTexture->getHash()); @@ -132,7 +132,7 @@ size_t Hasher::operator()(const FramebufferInfo &info) const { bool operator==(const FramebufferInfo &lhs, const FramebufferInfo &rhs) { // render pass is mostly irrelevant bool res = false; - res = lhs.colorTextures == rhs.colorTextures; + res = lhs.colorTextures == rhs.colorTextures; if (res) { res = lhs.depthStencilTexture == rhs.depthStencilTexture; @@ -610,7 +610,7 @@ uint32_t formatSurfaceSize(Format format, uint32_t width, uint32_t height, uint3 for (uint32_t i = 0; i < mips; ++i) { size += formatSize(format, width, height, depth); - width = std::max(width >> 1, 1U); + width = std::max(width >> 1, 1U); height = std::max(height >> 1, 1U); } diff --git a/native/cocos/renderer/gfx-base/GFXDef.h b/native/cocos/renderer/gfx-base/GFXDef.h index d27b6132f6..ea50ad5dcc 100644 --- a/native/cocos/renderer/gfx-base/GFXDef.h +++ b/native/cocos/renderer/gfx-base/GFXDef.h @@ -38,8 +38,8 @@ struct Hasher final { size_t operator()(const T &info) const; }; template ::value>> size_t hash_value(const T &info) { return Hasher()(info); } // NOLINT(readability-identifier-naming) -#define DEFINE_CMP_OP(type) \ - bool operator==(const type &lhs, const type &rhs); \ +#define DEFINE_CMP_OP(type) \ + bool operator==(const type &lhs, const type &rhs); \ inline bool operator!=(const type &lhs, const type &rhs) { return !(lhs == rhs); } DEFINE_CMP_OP(DepthStencilAttachment) @@ -64,7 +64,7 @@ DEFINE_CMP_OP(TextureBarrierInfo) class Executable { public: - virtual ~Executable() = default; + virtual ~Executable() = default; virtual void execute() = 0; }; @@ -84,9 +84,9 @@ private: struct SwapchainTextureInfo final { Swapchain *swapchain{nullptr}; - Format format{Format::UNKNOWN}; - uint32_t width{0}; - uint32_t height{0}; + Format format{Format::UNKNOWN}; + uint32_t width{0}; + uint32_t height{0}; }; constexpr TextureUsage TEXTURE_USAGE_TRANSIENT = static_cast( diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp b/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp index e712af3f2e..903fa45a9c 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.cpp @@ -39,7 +39,7 @@ DescriptorSet::~DescriptorSet() = default; void DescriptorSet::initialize(const DescriptorSetInfo &info) { CC_ASSERT(info.layout); - _layout = info.layout; + _layout = info.layout; uint32_t descriptorCount = _layout->getDescriptorCount(); _buffers.resize(descriptorCount); _textures.resize(descriptorCount); @@ -62,7 +62,7 @@ void DescriptorSet::bindBuffer(uint32_t binding, Buffer *buffer, uint32_t index) const uint32_t descriptorIndex = _layout->getDescriptorIndices()[binding]; if (_buffers[descriptorIndex + index] != buffer) { _buffers[descriptorIndex + index] = buffer; - _isDirty = true; + _isDirty = true; } } @@ -70,7 +70,7 @@ void DescriptorSet::bindTexture(uint32_t binding, Texture *texture, uint32_t ind const uint32_t descriptorIndex = _layout->getDescriptorIndices()[binding]; if (_textures[descriptorIndex + index] != texture) { _textures[descriptorIndex + index] = texture; - _isDirty = true; + _isDirty = true; } } @@ -78,7 +78,7 @@ void DescriptorSet::bindSampler(uint32_t binding, Sampler *sampler, uint32_t ind const uint32_t descriptorIndex = _layout->getDescriptorIndices()[binding]; if (_samplers[descriptorIndex + index] != sampler) { _samplers[descriptorIndex + index] = sampler; - _isDirty = true; + _isDirty = true; } } diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h index 1fdcb7463d..273d6e42f8 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSet.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSet.h @@ -50,27 +50,27 @@ public: bool bindTextureJSB(uint32_t binding, Texture *texture, uint32_t index); bool bindSamplerJSB(uint32_t binding, Sampler *sampler, uint32_t index); - Buffer * getBuffer(uint32_t binding, uint32_t index) const; + Buffer *getBuffer(uint32_t binding, uint32_t index) const; Texture *getTexture(uint32_t binding, uint32_t index) const; Sampler *getSampler(uint32_t binding, uint32_t index) const; inline DescriptorSetLayout *getLayout() { return _layout; } - inline void bindBuffer(uint32_t binding, Buffer *buffer) { bindBuffer(binding, buffer, 0U); } - inline void bindTexture(uint32_t binding, Texture *texture) { bindTexture(binding, texture, 0U); } - inline void bindSampler(uint32_t binding, Sampler *sampler) { bindSampler(binding, sampler, 0U); } - inline Buffer * getBuffer(uint32_t binding) const { return getBuffer(binding, 0U); } + inline void bindBuffer(uint32_t binding, Buffer *buffer) { bindBuffer(binding, buffer, 0U); } + inline void bindTexture(uint32_t binding, Texture *texture) { bindTexture(binding, texture, 0U); } + inline void bindSampler(uint32_t binding, Sampler *sampler) { bindSampler(binding, sampler, 0U); } + inline Buffer *getBuffer(uint32_t binding) const { return getBuffer(binding, 0U); } inline Texture *getTexture(uint32_t binding) const { return getTexture(binding, 0U); } inline Sampler *getSampler(uint32_t binding) const { return getSampler(binding, 0U); } protected: virtual void doInit(const DescriptorSetInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; DescriptorSetLayout *_layout = nullptr; - BufferList _buffers; - TextureList _textures; - SamplerList _samplers; + BufferList _buffers; + TextureList _textures; + SamplerList _samplers; bool _isDirty = false; }; diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.cpp index 1b2b90f85e..fec61bf227 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.cpp @@ -38,12 +38,12 @@ DescriptorSetLayout::DescriptorSetLayout() DescriptorSetLayout::~DescriptorSetLayout() = default; void DescriptorSetLayout::initialize(const DescriptorSetLayoutInfo &info) { - _bindings = info.bindings; + _bindings = info.bindings; auto bindingCount = utils::toUint(_bindings.size()); - _descriptorCount = 0U; + _descriptorCount = 0U; if (bindingCount) { - uint32_t maxBinding = 0U; + uint32_t maxBinding = 0U; ccstd::vector flattenedIndices(bindingCount); for (uint32_t i = 0U; i < bindingCount; i++) { const DescriptorSetLayoutBinding &binding = _bindings[i]; @@ -56,8 +56,8 @@ void DescriptorSetLayout::initialize(const DescriptorSetLayoutInfo &info) { _descriptorIndices.resize(maxBinding + 1, INVALID_BINDING); for (uint32_t i = 0U; i < bindingCount; i++) { const DescriptorSetLayoutBinding &binding = _bindings[i]; - _bindingIndices[binding.binding] = i; - _descriptorIndices[binding.binding] = flattenedIndices[i]; + _bindingIndices[binding.binding] = i; + _descriptorIndices[binding.binding] = flattenedIndices[i]; if (hasFlag(DESCRIPTOR_DYNAMIC_TYPE, binding.descriptorType)) { for (uint32_t j = 0U; j < binding.count; ++j) { _dynamicBindings.push_back(binding.binding); diff --git a/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.h b/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.h index 92aaa2863b..6d0c50662a 100644 --- a/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-base/GFXDescriptorSetLayout.h @@ -40,20 +40,20 @@ public: void destroy(); inline const DescriptorSetLayoutBindingList &getBindings() const { return _bindings; } - inline const ccstd::vector & getDynamicBindings() const { return _dynamicBindings; } - inline const ccstd::vector & getBindingIndices() const { return _bindingIndices; } - inline const ccstd::vector & getDescriptorIndices() const { return _descriptorIndices; } - inline uint32_t getDescriptorCount() const { return _descriptorCount; } + inline const ccstd::vector &getDynamicBindings() const { return _dynamicBindings; } + inline const ccstd::vector &getBindingIndices() const { return _bindingIndices; } + inline const ccstd::vector &getDescriptorIndices() const { return _descriptorIndices; } + inline uint32_t getDescriptorCount() const { return _descriptorCount; } protected: virtual void doInit(const DescriptorSetLayoutInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; DescriptorSetLayoutBindingList _bindings; - uint32_t _descriptorCount = 0U; - ccstd::vector _bindingIndices; - ccstd::vector _descriptorIndices; - ccstd::vector _dynamicBindings; + uint32_t _descriptorCount = 0U; + ccstd::vector _bindingIndices; + ccstd::vector _descriptorIndices; + ccstd::vector _dynamicBindings; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 2484c2928f..80f34909a5 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -59,55 +59,55 @@ public: void destroy(); virtual void acquire(Swapchain *const *swapchains, uint32_t count) = 0; - virtual void present() = 0; + virtual void present() = 0; virtual void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) {} virtual MemoryStatus &getMemoryStatus() { return _memoryStatus; } - virtual uint32_t getNumDrawCalls() const { return _numDrawCalls; } - virtual uint32_t getNumInstances() const { return _numInstances; } - virtual uint32_t getNumTris() const { return _numTriangles; } + virtual uint32_t getNumDrawCalls() const { return _numDrawCalls; } + virtual uint32_t getNumInstances() const { return _numInstances; } + virtual uint32_t getNumTris() const { return _numTriangles; } - inline CommandBuffer * createCommandBuffer(const CommandBufferInfo &info); - inline Queue * createQueue(const QueueInfo &info); - inline QueryPool * createQueryPool(const QueryPoolInfo &info); - inline Swapchain * createSwapchain(const SwapchainInfo &info); - inline Buffer * createBuffer(const BufferInfo &info); - inline Buffer * createBuffer(const BufferViewInfo &info); - inline Texture * createTexture(const TextureInfo &info); - inline Texture * createTexture(const TextureViewInfo &info); - inline Shader * createShader(const ShaderInfo &info); - inline InputAssembler * createInputAssembler(const InputAssemblerInfo &info); - inline RenderPass * createRenderPass(const RenderPassInfo &info); - inline Framebuffer * createFramebuffer(const FramebufferInfo &info); - inline DescriptorSet * createDescriptorSet(const DescriptorSetInfo &info); + inline CommandBuffer *createCommandBuffer(const CommandBufferInfo &info); + inline Queue *createQueue(const QueueInfo &info); + inline QueryPool *createQueryPool(const QueryPoolInfo &info); + inline Swapchain *createSwapchain(const SwapchainInfo &info); + inline Buffer *createBuffer(const BufferInfo &info); + inline Buffer *createBuffer(const BufferViewInfo &info); + inline Texture *createTexture(const TextureInfo &info); + inline Texture *createTexture(const TextureViewInfo &info); + inline Shader *createShader(const ShaderInfo &info); + inline InputAssembler *createInputAssembler(const InputAssemblerInfo &info); + inline RenderPass *createRenderPass(const RenderPassInfo &info); + inline Framebuffer *createFramebuffer(const FramebufferInfo &info); + inline DescriptorSet *createDescriptorSet(const DescriptorSetInfo &info); inline DescriptorSetLayout *createDescriptorSetLayout(const DescriptorSetLayoutInfo &info); - inline PipelineLayout * createPipelineLayout(const PipelineLayoutInfo &info); - inline PipelineState * createPipelineState(const PipelineStateInfo &info); + inline PipelineLayout *createPipelineLayout(const PipelineLayoutInfo &info); + inline PipelineState *createPipelineState(const PipelineStateInfo &info); - virtual Sampler * getSampler(const SamplerInfo &info); + virtual Sampler *getSampler(const SamplerInfo &info); virtual GeneralBarrier *getGeneralBarrier(const GeneralBarrierInfo &info); virtual TextureBarrier *getTextureBarrier(const TextureBarrierInfo &info); virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) = 0; - virtual void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) = 0; - virtual void getQueryPoolResults(QueryPool *queryPool) = 0; + virtual void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) = 0; + virtual void getQueryPoolResults(QueryPool *queryPool) = 0; inline void copyTextureToBuffers(Texture *src, BufferSrcList &buffers, const BufferTextureCopyList ®ions); inline void copyBuffersToTexture(const BufferDataList &buffers, Texture *dst, const BufferTextureCopyList ®ions); inline void flushCommands(const ccstd::vector &cmdBuffs); inline void acquire(const ccstd::vector &swapchains); - inline Queue * getQueue() const { return _queue; } - inline QueryPool * getQueryPool() const { return _queryPool; } - inline CommandBuffer * getCommandBuffer() const { return _cmdBuff; } - inline const DeviceCaps & getCapabilities() const { return _caps; } - inline API getGfxAPI() const { return _api; } + inline Queue *getQueue() const { return _queue; } + inline QueryPool *getQueryPool() const { return _queryPool; } + inline CommandBuffer *getCommandBuffer() const { return _cmdBuff; } + inline const DeviceCaps &getCapabilities() const { return _caps; } + inline API getGfxAPI() const { return _api; } inline const ccstd::string &getDeviceName() const { return _deviceName; } inline const ccstd::string &getRenderer() const { return _renderer; } inline const ccstd::string &getVendor() const { return _vendor; } - inline bool hasFeature(Feature feature) const { return _features[toNumber(feature)]; } - inline FormatFeature getFormatFeatures(Format format) const { return _formatFeatures[toNumber(format)]; } + inline bool hasFeature(Feature feature) const { return _features[toNumber(feature)]; } + inline FormatFeature getFormatFeatures(Format format) const { return _formatFeatures[toNumber(format)]; } inline const BindingMappingInfo &bindingMappingInfo() const { return _bindingMappingInfo; } @@ -133,60 +133,60 @@ protected: void createSurface(void *windowHandle); virtual bool doInit(const DeviceInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - virtual CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) = 0; - virtual Queue * createQueue() = 0; - virtual QueryPool * createQueryPool() = 0; - virtual Swapchain * createSwapchain() = 0; - virtual Buffer * createBuffer() = 0; - virtual Texture * createTexture() = 0; - virtual Shader * createShader() = 0; - virtual InputAssembler * createInputAssembler() = 0; - virtual RenderPass * createRenderPass() = 0; - virtual Framebuffer * createFramebuffer() = 0; - virtual DescriptorSet * createDescriptorSet() = 0; - virtual DescriptorSetLayout *createDescriptorSetLayout() = 0; - virtual PipelineLayout * createPipelineLayout() = 0; - virtual PipelineState * createPipelineState() = 0; + virtual CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) = 0; + virtual Queue *createQueue() = 0; + virtual QueryPool *createQueryPool() = 0; + virtual Swapchain *createSwapchain() = 0; + virtual Buffer *createBuffer() = 0; + virtual Texture *createTexture() = 0; + virtual Shader *createShader() = 0; + virtual InputAssembler *createInputAssembler() = 0; + virtual RenderPass *createRenderPass() = 0; + virtual Framebuffer *createFramebuffer() = 0; + virtual DescriptorSet *createDescriptorSet() = 0; + virtual DescriptorSetLayout *createDescriptorSetLayout() = 0; + virtual PipelineLayout *createPipelineLayout() = 0; + virtual PipelineState *createPipelineState() = 0; - virtual Sampler * createSampler(const SamplerInfo &info) { return ccnew Sampler(info); } + virtual Sampler *createSampler(const SamplerInfo &info) { return ccnew Sampler(info); } virtual GeneralBarrier *createGeneralBarrier(const GeneralBarrierInfo &info) { return ccnew GeneralBarrier(info); } virtual TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) { return ccnew TextureBarrier(info); } // For context switching between threads virtual void bindContext(bool bound) {} - ccstd::string _deviceName; - ccstd::string _renderer; - ccstd::string _vendor; - ccstd::string _version; - API _api{API::UNKNOWN}; - DeviceCaps _caps; + ccstd::string _deviceName; + ccstd::string _renderer; + ccstd::string _vendor; + ccstd::string _version; + API _api{API::UNKNOWN}; + DeviceCaps _caps; BindingMappingInfo _bindingMappingInfo; bool _multithreadedCommandRecording{true}; - ccstd::array(Feature::COUNT)> _features; + ccstd::array(Feature::COUNT)> _features; ccstd::array(Format::COUNT)> _formatFeatures; - Queue * _queue{nullptr}; - QueryPool * _queryPool{nullptr}; + Queue *_queue{nullptr}; + QueryPool *_queryPool{nullptr}; CommandBuffer *_cmdBuff{nullptr}; - Executable * _onAcquire{nullptr}; + Executable *_onAcquire{nullptr}; - uint32_t _numDrawCalls{0U}; - uint32_t _numInstances{0U}; - uint32_t _numTriangles{0U}; + uint32_t _numDrawCalls{0U}; + uint32_t _numInstances{0U}; + uint32_t _numTriangles{0U}; MemoryStatus _memoryStatus; - ccstd::unordered_map> _samplers; + ccstd::unordered_map> _samplers; ccstd::unordered_map> _generalBarriers; ccstd::unordered_map> _textureBarriers; private: ccstd::vector _swapchains; // weak reference - bool _rendererAvailable{false}; + bool _rendererAvailable{false}; }; ////////////////////////////////////////////////////////////////////////// diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp index 66e7586e1e..5c7ec5238e 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp @@ -41,8 +41,8 @@ size_t Framebuffer::computeHash(const FramebufferInfo &info) { } void Framebuffer::initialize(const FramebufferInfo &info) { - _renderPass = info.renderPass; - _colorTextures = info.colorTextures; + _renderPass = info.renderPass; + _colorTextures = info.colorTextures; _depthStencilTexture = info.depthStencilTexture; doInit(info); diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.h b/native/cocos/renderer/gfx-base/GFXFramebuffer.h index b66caec9e5..654348ecad 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.h +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.h @@ -41,17 +41,17 @@ public: void initialize(const FramebufferInfo &info); void destroy(); - inline RenderPass * getRenderPass() const { return _renderPass; } + inline RenderPass *getRenderPass() const { return _renderPass; } inline const TextureList &getColorTextures() const { return _colorTextures; } - inline Texture * getDepthStencilTexture() const { return _depthStencilTexture; } + inline Texture *getDepthStencilTexture() const { return _depthStencilTexture; } protected: virtual void doInit(const FramebufferInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; RenderPass *_renderPass = nullptr; TextureList _colorTextures; - Texture * _depthStencilTexture = nullptr; + Texture *_depthStencilTexture = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp b/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp index c751182911..0b8daad279 100644 --- a/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp +++ b/native/cocos/renderer/gfx-base/GFXInputAssembler.cpp @@ -52,9 +52,9 @@ size_t InputAssembler::computeAttributesHash() const { } void InputAssembler::initialize(const InputAssemblerInfo &info) { - _attributes = info.attributes; - _vertexBuffers = info.vertexBuffers; - _indexBuffer = info.indexBuffer; + _attributes = info.attributes; + _vertexBuffers = info.vertexBuffers; + _indexBuffer = info.indexBuffer; _indirectBuffer = info.indirectBuffer; _attributesHash = computeAttributesHash(); @@ -62,8 +62,8 @@ void InputAssembler::initialize(const InputAssemblerInfo &info) { _drawInfo.indexCount = _indexBuffer->getCount(); _drawInfo.firstIndex = 0; } else if (!_vertexBuffers.empty()) { - _drawInfo.vertexCount = _vertexBuffers[0]->getCount(); - _drawInfo.firstVertex = 0; + _drawInfo.vertexCount = _vertexBuffers[0]->getCount(); + _drawInfo.firstVertex = 0; _drawInfo.vertexOffset = 0; } @@ -77,7 +77,7 @@ void InputAssembler::destroy() { _attributesHash = 0U; _vertexBuffers.clear(); - _indexBuffer = nullptr; + _indexBuffer = nullptr; _indirectBuffer = nullptr; _drawInfo = DrawInfo(); diff --git a/native/cocos/renderer/gfx-base/GFXInputAssembler.h b/native/cocos/renderer/gfx-base/GFXInputAssembler.h index 455a9695b3..041b51dad9 100644 --- a/native/cocos/renderer/gfx-base/GFXInputAssembler.h +++ b/native/cocos/renderer/gfx-base/GFXInputAssembler.h @@ -40,13 +40,13 @@ public: void destroy(); inline const AttributeList &getAttributes() const { return _attributes; } - inline const BufferList & getVertexBuffers() const { return _vertexBuffers; } - inline Buffer * getIndexBuffer() const { return _indexBuffer; } - inline Buffer * getIndirectBuffer() const { return _indirectBuffer; } - inline size_t getAttributesHash() const { return _attributesHash; } + inline const BufferList &getVertexBuffers() const { return _vertexBuffers; } + inline Buffer *getIndexBuffer() const { return _indexBuffer; } + inline Buffer *getIndirectBuffer() const { return _indirectBuffer; } + inline size_t getAttributesHash() const { return _attributesHash; } inline const DrawInfo &getDrawInfo() const { return _drawInfo; } - inline void setDrawInfo(const DrawInfo &info) { _drawInfo = info; } + inline void setDrawInfo(const DrawInfo &info) { _drawInfo = info; } inline void setVertexCount(uint32_t count) { _drawInfo.vertexCount = count; } inline void setFirstVertex(uint32_t first) { _drawInfo.firstVertex = first; } @@ -66,16 +66,16 @@ public: protected: virtual void doInit(const InputAssemblerInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; size_t computeAttributesHash() const; AttributeList _attributes; - size_t _attributesHash = 0; + size_t _attributesHash = 0; BufferList _vertexBuffers; - Buffer * _indexBuffer{nullptr}; - Buffer * _indirectBuffer{nullptr}; + Buffer *_indexBuffer{nullptr}; + Buffer *_indirectBuffer{nullptr}; DrawInfo _drawInfo; }; diff --git a/native/cocos/renderer/gfx-base/GFXObject.h b/native/cocos/renderer/gfx-base/GFXObject.h index 37d8016e1f..a23093f42a 100644 --- a/native/cocos/renderer/gfx-base/GFXObject.h +++ b/native/cocos/renderer/gfx-base/GFXObject.h @@ -35,8 +35,8 @@ public: virtual ~GFXObject() = default; inline ObjectType getObjectType() const { return _objectType; } - inline uint32_t getObjectID() const { return _objectID; } - inline uint32_t getTypedID() const { return _typedID; } + inline uint32_t getObjectID() const { return _objectID; } + inline uint32_t getTypedID() const { return _typedID; } protected: template @@ -46,7 +46,7 @@ protected: } ObjectType _objectType = ObjectType::UNKNOWN; - uint32_t _objectID = 0U; + uint32_t _objectID = 0U; uint32_t _typedID = 0U; // inited by sub-classes }; diff --git a/native/cocos/renderer/gfx-base/GFXPipelineLayout.h b/native/cocos/renderer/gfx-base/GFXPipelineLayout.h index 429bf0e9c2..ff7ea4ecd0 100644 --- a/native/cocos/renderer/gfx-base/GFXPipelineLayout.h +++ b/native/cocos/renderer/gfx-base/GFXPipelineLayout.h @@ -43,7 +43,7 @@ public: protected: virtual void doInit(const PipelineLayoutInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; DescriptorSetLayoutList _setLayouts; }; diff --git a/native/cocos/renderer/gfx-base/GFXPipelineState.cpp b/native/cocos/renderer/gfx-base/GFXPipelineState.cpp index c0f50beec4..92020a8a5f 100644 --- a/native/cocos/renderer/gfx-base/GFXPipelineState.cpp +++ b/native/cocos/renderer/gfx-base/GFXPipelineState.cpp @@ -36,17 +36,17 @@ PipelineState::PipelineState() PipelineState::~PipelineState() = default; void PipelineState::initialize(const PipelineStateInfo &info) { - _primitive = info.primitive; - _shader = info.shader; - _inputState = info.inputState; - _rasterizerState = info.rasterizerState; + _primitive = info.primitive; + _shader = info.shader; + _inputState = info.inputState; + _rasterizerState = info.rasterizerState; _depthStencilState = info.depthStencilState; - _bindPoint = info.bindPoint; - _blendState = info.blendState; - _dynamicStates = info.dynamicStates; - _renderPass = info.renderPass; - _subpass = info.subpass; - _pipelineLayout = info.pipelineLayout; + _bindPoint = info.bindPoint; + _blendState = info.blendState; + _dynamicStates = info.dynamicStates; + _renderPass = info.renderPass; + _subpass = info.subpass; + _pipelineLayout = info.pipelineLayout; doInit(info); } @@ -54,8 +54,8 @@ void PipelineState::initialize(const PipelineStateInfo &info) { void PipelineState::destroy() { doDestroy(); - _shader = nullptr; - _renderPass = nullptr; + _shader = nullptr; + _renderPass = nullptr; _pipelineLayout = nullptr; } diff --git a/native/cocos/renderer/gfx-base/GFXPipelineState.h b/native/cocos/renderer/gfx-base/GFXPipelineState.h index 65c1921a33..92e3c5ddbe 100644 --- a/native/cocos/renderer/gfx-base/GFXPipelineState.h +++ b/native/cocos/renderer/gfx-base/GFXPipelineState.h @@ -39,32 +39,32 @@ public: void initialize(const PipelineStateInfo &info); void destroy(); - inline Shader * getShader() const { return _shader; } - inline PipelineBindPoint getBindPoint() const { return _bindPoint; } - inline PrimitiveMode getPrimitive() const { return _primitive; } - inline DynamicStateFlags getDynamicStates() const { return _dynamicStates; } - inline const InputState & getInputState() const { return _inputState; } - inline const RasterizerState & getRasterizerState() const { return _rasterizerState; } + inline Shader *getShader() const { return _shader; } + inline PipelineBindPoint getBindPoint() const { return _bindPoint; } + inline PrimitiveMode getPrimitive() const { return _primitive; } + inline DynamicStateFlags getDynamicStates() const { return _dynamicStates; } + inline const InputState &getInputState() const { return _inputState; } + inline const RasterizerState &getRasterizerState() const { return _rasterizerState; } inline const DepthStencilState &getDepthStencilState() const { return _depthStencilState; } - inline const BlendState & getBlendState() const { return _blendState; } - inline const RenderPass * getRenderPass() const { return _renderPass; } - inline const PipelineLayout * getPipelineLayout() const { return _pipelineLayout; } + inline const BlendState &getBlendState() const { return _blendState; } + inline const RenderPass *getRenderPass() const { return _renderPass; } + inline const PipelineLayout *getPipelineLayout() const { return _pipelineLayout; } protected: virtual void doInit(const PipelineStateInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - Shader * _shader = nullptr; - PipelineBindPoint _bindPoint = PipelineBindPoint::GRAPHICS; - PrimitiveMode _primitive = PrimitiveMode::TRIANGLE_LIST; + Shader *_shader = nullptr; + PipelineBindPoint _bindPoint = PipelineBindPoint::GRAPHICS; + PrimitiveMode _primitive = PrimitiveMode::TRIANGLE_LIST; DynamicStateFlags _dynamicStates = DynamicStateFlags::NONE; - InputState _inputState; - RasterizerState _rasterizerState; + InputState _inputState; + RasterizerState _rasterizerState; DepthStencilState _depthStencilState; - BlendState _blendState; - RenderPass * _renderPass = nullptr; - uint32_t _subpass = 0U; - PipelineLayout * _pipelineLayout = nullptr; + BlendState _blendState; + RenderPass *_renderPass = nullptr; + uint32_t _subpass = 0U; + PipelineLayout *_pipelineLayout = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXQueryPool.cpp b/native/cocos/renderer/gfx-base/GFXQueryPool.cpp index 9a612771eb..e25b3373be 100644 --- a/native/cocos/renderer/gfx-base/GFXQueryPool.cpp +++ b/native/cocos/renderer/gfx-base/GFXQueryPool.cpp @@ -35,9 +35,9 @@ QueryPool::QueryPool() QueryPool::~QueryPool() = default; void QueryPool::initialize(const QueryPoolInfo &info) { - _type = info.type; + _type = info.type; _maxQueryObjects = info.maxQueryObjects; - _forceWait = info.forceWait; + _forceWait = info.forceWait; doInit(info); } @@ -45,7 +45,7 @@ void QueryPool::initialize(const QueryPoolInfo &info) { void QueryPool::destroy() { doDestroy(); - _type = QueryType::OCCLUSION; + _type = QueryType::OCCLUSION; _maxQueryObjects = 0; } diff --git a/native/cocos/renderer/gfx-base/GFXQueryPool.h b/native/cocos/renderer/gfx-base/GFXQueryPool.h index de2580a979..adbba02809 100644 --- a/native/cocos/renderer/gfx-base/GFXQueryPool.h +++ b/native/cocos/renderer/gfx-base/GFXQueryPool.h @@ -54,20 +54,20 @@ public: void initialize(const QueryPoolInfo &info); void destroy(); - inline bool hasResult(uint32_t id) { return _results.count(id) != 0; } - inline uint64_t getResult(uint32_t id) { return _results[id]; } + inline bool hasResult(uint32_t id) { return _results.count(id) != 0; } + inline uint64_t getResult(uint32_t id) { return _results[id]; } inline QueryType getType() const { return _type; } - inline uint32_t getMaxQueryObjects() const { return _maxQueryObjects; } - inline bool getForceWait() const { return _forceWait; } + inline uint32_t getMaxQueryObjects() const { return _maxQueryObjects; } + inline bool getForceWait() const { return _forceWait; } protected: virtual void doInit(const QueryPoolInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - QueryType _type{QueryType::OCCLUSION}; - uint32_t _maxQueryObjects{0}; - bool _forceWait{true}; - std::mutex _mutex; + QueryType _type{QueryType::OCCLUSION}; + uint32_t _maxQueryObjects{0}; + bool _forceWait{true}; + std::mutex _mutex; ccstd::unordered_map _results; }; diff --git a/native/cocos/renderer/gfx-base/GFXQueue.h b/native/cocos/renderer/gfx-base/GFXQueue.h index 359acedc9f..dde0f63adb 100644 --- a/native/cocos/renderer/gfx-base/GFXQueue.h +++ b/native/cocos/renderer/gfx-base/GFXQueue.h @@ -48,7 +48,7 @@ public: protected: virtual void doInit(const QueueInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; QueueType _type = QueueType::GRAPHICS; }; diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 992a008477..0fac51f72b 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -59,11 +59,11 @@ size_t RenderPass::computeHash(const RenderPassInfo &info) { } void RenderPass::initialize(const RenderPassInfo &info) { - _colorAttachments = info.colorAttachments; + _colorAttachments = info.colorAttachments; _depthStencilAttachment = info.depthStencilAttachment; - _subpasses = info.subpasses; - _dependencies = info.dependencies; - _hash = computeHash(); + _subpasses = info.subpasses; + _dependencies = info.dependencies; + _hash = computeHash(); doInit(info); } diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.h b/native/cocos/renderer/gfx-base/GFXRenderPass.h index 703314fa1a..657f23eb3a 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.h +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.h @@ -41,23 +41,23 @@ public: void initialize(const RenderPassInfo &info); void destroy(); - inline const ColorAttachmentList & getColorAttachments() const { return _colorAttachments; } + inline const ColorAttachmentList &getColorAttachments() const { return _colorAttachments; } inline const DepthStencilAttachment &getDepthStencilAttachment() const { return _depthStencilAttachment; } - inline const SubpassInfoList & getSubpasses() const { return _subpasses; } - inline const SubpassDependencyList & getDependencies() const { return _dependencies; } - inline size_t getHash() const { return _hash; } + inline const SubpassInfoList &getSubpasses() const { return _subpasses; } + inline const SubpassDependencyList &getDependencies() const { return _dependencies; } + inline size_t getHash() const { return _hash; } protected: size_t computeHash(); virtual void doInit(const RenderPassInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - ColorAttachmentList _colorAttachments; + ColorAttachmentList _colorAttachments; DepthStencilAttachment _depthStencilAttachment; - SubpassInfoList _subpasses; - SubpassDependencyList _dependencies; - size_t _hash = 0; + SubpassInfoList _subpasses; + SubpassDependencyList _dependencies; + size_t _hash = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXShader.cpp b/native/cocos/renderer/gfx-base/GFXShader.cpp index f35372e2a0..0dfdf87392 100644 --- a/native/cocos/renderer/gfx-base/GFXShader.cpp +++ b/native/cocos/renderer/gfx-base/GFXShader.cpp @@ -37,16 +37,16 @@ Shader::Shader() Shader::~Shader() = default; void Shader::initialize(const ShaderInfo &info) { - _name = info.name; - _stages = info.stages; - _attributes = info.attributes; - _blocks = info.blocks; - _buffers = info.buffers; + _name = info.name; + _stages = info.stages; + _attributes = info.attributes; + _blocks = info.blocks; + _buffers = info.buffers; _samplerTextures = info.samplerTextures; - _samplers = info.samplers; - _textures = info.textures; - _images = info.images; - _subpassInputs = info.subpassInputs; + _samplers = info.samplers; + _textures = info.textures; + _images = info.images; + _subpassInputs = info.subpassInputs; doInit(info); } diff --git a/native/cocos/renderer/gfx-base/GFXShader.h b/native/cocos/renderer/gfx-base/GFXShader.h index 793e6822b7..b6c7ea68ee 100644 --- a/native/cocos/renderer/gfx-base/GFXShader.h +++ b/native/cocos/renderer/gfx-base/GFXShader.h @@ -39,30 +39,30 @@ public: void initialize(const ShaderInfo &info); void destroy(); - inline const ccstd::string & getName() const { return _name; } - inline const ShaderStageList & getStages() const { return _stages; } - inline const AttributeList & getAttributes() const { return _attributes; } - inline const UniformBlockList & getBlocks() const { return _blocks; } - inline const UniformStorageBufferList & getBuffers() const { return _buffers; } - inline const UniformSamplerTextureList & getSamplerTextures() const { return _samplerTextures; } - inline const UniformSamplerList & getSamplers() const { return _samplers; } - inline const UniformTextureList & getTextures() const { return _textures; } - inline const UniformStorageImageList & getImages() const { return _images; } + inline const ccstd::string &getName() const { return _name; } + inline const ShaderStageList &getStages() const { return _stages; } + inline const AttributeList &getAttributes() const { return _attributes; } + inline const UniformBlockList &getBlocks() const { return _blocks; } + inline const UniformStorageBufferList &getBuffers() const { return _buffers; } + inline const UniformSamplerTextureList &getSamplerTextures() const { return _samplerTextures; } + inline const UniformSamplerList &getSamplers() const { return _samplers; } + inline const UniformTextureList &getTextures() const { return _textures; } + inline const UniformStorageImageList &getImages() const { return _images; } inline const UniformInputAttachmentList &getSubpassInputs() const { return _subpassInputs; } protected: virtual void doInit(const ShaderInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doDestroy() = 0; - ccstd::string _name; - ShaderStageList _stages; - AttributeList _attributes; - UniformBlockList _blocks; - UniformStorageBufferList _buffers; - UniformSamplerTextureList _samplerTextures; - UniformSamplerList _samplers; - UniformTextureList _textures; - UniformStorageImageList _images; + ccstd::string _name; + ShaderStageList _stages; + AttributeList _attributes; + UniformBlockList _blocks; + UniformStorageBufferList _buffers; + UniformSamplerTextureList _samplerTextures; + UniformSamplerList _samplers; + UniformTextureList _textures; + UniformStorageImageList _images; UniformInputAttachmentList _subpassInputs; }; diff --git a/native/cocos/renderer/gfx-base/GFXSwapchain.cpp b/native/cocos/renderer/gfx-base/GFXSwapchain.cpp index 083d755864..a6277691a2 100644 --- a/native/cocos/renderer/gfx-base/GFXSwapchain.cpp +++ b/native/cocos/renderer/gfx-base/GFXSwapchain.cpp @@ -38,7 +38,7 @@ void Swapchain::initialize(const SwapchainInfo &info) { CC_ASSERT(info.windowHandle); _windowHandle = info.windowHandle; - _vsyncMode = info.vsyncMode; + _vsyncMode = info.vsyncMode; doInit(info); } diff --git a/native/cocos/renderer/gfx-base/GFXSwapchain.h b/native/cocos/renderer/gfx-base/GFXSwapchain.h index 02e4f1588a..a6fa56de2d 100644 --- a/native/cocos/renderer/gfx-base/GFXSwapchain.h +++ b/native/cocos/renderer/gfx-base/GFXSwapchain.h @@ -55,29 +55,29 @@ public: inline void destroySurface(); inline void createSurface(void *windowHandle); - inline void * getWindowHandle() const { return _windowHandle; } + inline void *getWindowHandle() const { return _windowHandle; } inline VsyncMode getVSyncMode() const { return _vsyncMode; } inline Texture *getColorTexture() const { return _colorTexture; } inline Texture *getDepthStencilTexture() const { return _depthStencilTexture; } inline SurfaceTransform getSurfaceTransform() const { return _transform; } - inline uint32_t getWidth() const { return _colorTexture->getWidth(); } - inline uint32_t getHeight() const { return _colorTexture->getHeight(); } + inline uint32_t getWidth() const { return _colorTexture->getWidth(); } + inline uint32_t getHeight() const { return _colorTexture->getHeight(); } protected: - virtual void doInit(const SwapchainInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doInit(const SwapchainInfo &info) = 0; + virtual void doDestroy() = 0; virtual void doResize(uint32_t width, uint32_t height, SurfaceTransform transform) = 0; - virtual void doDestroySurface() = 0; - virtual void doCreateSurface(void *windowHandle) = 0; + virtual void doDestroySurface() = 0; + virtual void doCreateSurface(void *windowHandle) = 0; static inline void initTexture(const SwapchainTextureInfo &info, Texture *texture); - void * _windowHandle{nullptr}; - VsyncMode _vsyncMode{VsyncMode::RELAXED}; + void *_windowHandle{nullptr}; + VsyncMode _vsyncMode{VsyncMode::RELAXED}; SurfaceTransform _transform{SurfaceTransform::IDENTITY}; - bool _preRotationEnabled{false}; + bool _preRotationEnabled{false}; IntrusivePtr _colorTexture; IntrusivePtr _depthStencilTexture; diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index 9eef8b444d..b6e7960162 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -57,24 +57,24 @@ void Texture::initialize(const TextureInfo &info) { _size = formatSize(_info.format, _info.width, _info.height, _info.depth); _hash = computeHash(info); - _viewInfo.texture = this; - _viewInfo.format = _info.format; - _viewInfo.type = _info.type; - _viewInfo.baseLayer = 0; + _viewInfo.texture = this; + _viewInfo.format = _info.format; + _viewInfo.type = _info.type; + _viewInfo.baseLayer = 0; _viewInfo.layerCount = _info.layerCount; - _viewInfo.baseLevel = 0; + _viewInfo.baseLevel = 0; _viewInfo.levelCount = _info.levelCount; doInit(info); } void Texture::initialize(const TextureViewInfo &info) { - _info = info.texture->getInfo(); + _info = info.texture->getInfo(); _viewInfo = info; _isTextureView = true; - _size = formatSize(_info.format, _info.width, _info.height, _info.depth); - _hash = computeHash(info); + _size = formatSize(_info.format, _info.width, _info.height, _info.depth); + _hash = computeHash(info); doInit(info); } @@ -94,17 +94,17 @@ void Texture::resize(uint32_t width, uint32_t height) { uint32_t size = formatSize(_info.format, width, height, _info.depth); doResize(width, height, size); - _info.width = width; + _info.width = width; _info.height = height; - _size = size; - _hash = computeHash(this); + _size = size; + _hash = computeHash(this); } } void Texture::destroy() { doDestroy(); - _info = TextureInfo(); + _info = TextureInfo(); _viewInfo = TextureViewInfo(); _isTextureView = false; @@ -114,29 +114,29 @@ void Texture::destroy() { ///////////////////////////// Swapchain Specific ///////////////////////////// void Texture::initialize(const SwapchainTextureInfo &info, Texture *out) { - out->_info.type = TextureType::TEX2D; - out->_info.format = info.format; - out->_info.width = info.width; - out->_info.height = info.height; + out->_info.type = TextureType::TEX2D; + out->_info.format = info.format; + out->_info.width = info.width; + out->_info.height = info.height; out->_info.layerCount = 1; out->_info.levelCount = 1; - out->_info.depth = 1; - out->_info.samples = SampleCount::ONE; - out->_info.flags = TextureFlagBit::NONE; - out->_info.usage = GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth - ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT - : TextureUsageBit::COLOR_ATTACHMENT; + out->_info.depth = 1; + out->_info.samples = SampleCount::ONE; + out->_info.flags = TextureFlagBit::NONE; + out->_info.usage = GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth + ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT + : TextureUsageBit::COLOR_ATTACHMENT; out->_swapchain = info.swapchain; - out->_size = formatSize(info.format, info.width, info.height, 1); - out->_hash = computeHash(out); + out->_size = formatSize(info.format, info.width, info.height, 1); + out->_hash = computeHash(out); - out->_viewInfo.texture = out; - out->_viewInfo.format = out->_info.format; - out->_viewInfo.type = out->_info.type; - out->_viewInfo.baseLayer = 0; + out->_viewInfo.texture = out; + out->_viewInfo.format = out->_info.format; + out->_viewInfo.type = out->_info.type; + out->_viewInfo.baseLayer = 0; out->_viewInfo.layerCount = out->_info.layerCount; - out->_viewInfo.baseLevel = 0; + out->_viewInfo.baseLevel = 0; out->_viewInfo.levelCount = out->_info.levelCount; out->doInit(info); diff --git a/native/cocos/renderer/gfx-base/GFXTexture.h b/native/cocos/renderer/gfx-base/GFXTexture.h index 5fbcb8d267..1b0832e728 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.h +++ b/native/cocos/renderer/gfx-base/GFXTexture.h @@ -44,15 +44,15 @@ public: void resize(uint32_t width, uint32_t height); void destroy(); - inline const TextureInfo & getInfo() const { return _info; } + inline const TextureInfo &getInfo() const { return _info; } inline const TextureViewInfo &getViewInfo() const { return _viewInfo; } - inline bool isTextureView() const { return _isTextureView; } + inline bool isTextureView() const { return _isTextureView; } inline uint32_t getSize() const { return _size; } - inline size_t getHash() const { return _hash; } + inline size_t getHash() const { return _hash; } // convenient getter for common usages - inline Format getFormat() const { return _info.format; } + inline Format getFormat() const { return _info.format; } inline uint32_t getWidth() const { return _info.width; } inline uint32_t getHeight() const { return _info.height; } @@ -61,22 +61,22 @@ public: protected: friend class Swapchain; - virtual void doInit(const TextureInfo &info) = 0; - virtual void doInit(const TextureViewInfo &info) = 0; - virtual void doDestroy() = 0; + virtual void doInit(const TextureInfo &info) = 0; + virtual void doInit(const TextureViewInfo &info) = 0; + virtual void doDestroy() = 0; virtual void doResize(uint32_t width, uint32_t height, uint32_t size) = 0; static size_t computeHash(const Texture *texture); - static void initialize(const SwapchainTextureInfo &info, Texture *out); - virtual void doInit(const SwapchainTextureInfo &info) = 0; + static void initialize(const SwapchainTextureInfo &info, Texture *out); + virtual void doInit(const SwapchainTextureInfo &info) = 0; - TextureInfo _info; + TextureInfo _info; TextureViewInfo _viewInfo; Swapchain *_swapchain{nullptr}; - bool _isTextureView{false}; - uint32_t _size{0U}; - size_t _hash{0U}; + bool _isTextureView{false}; + uint32_t _size{0U}; + size_t _hash{0U}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp index 0c2ef15741..7edd4f9154 100644 --- a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp @@ -77,9 +77,9 @@ glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { // https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.pdf struct Id { - uint32_t opcode{0}; - uint32_t typeId{0}; - uint32_t storageClass{0}; + uint32_t opcode{0}; + uint32_t typeId{0}; + uint32_t storageClass{0}; uint32_t *pLocation{nullptr}; }; } // namespace @@ -90,8 +90,8 @@ void SPIRVUtils::initialize(int vulkanMinorVersion) { glslang::InitializeProcess(); _clientInputSemanticsVersion = 100 + vulkanMinorVersion * 10; - _clientVersion = getClientVersion(vulkanMinorVersion); - _targetVersion = getTargetVersion(vulkanMinorVersion); + _clientVersion = getClientVersion(vulkanMinorVersion); + _targetVersion = getTargetVersion(vulkanMinorVersion); } void SPIRVUtils::destroy() { @@ -100,7 +100,7 @@ void SPIRVUtils::destroy() { } void SPIRVUtils::compileGLSL(ShaderStageFlagBit type, const ccstd::string &source) { - EShLanguage stage = getShaderStage(type); + EShLanguage stage = getShaderStage(type); const char *string = source.c_str(); _shader = std::make_unique(stage); @@ -127,7 +127,7 @@ void SPIRVUtils::compileGLSL(ShaderStageFlagBit type, const ccstd::string &sourc spv::SpvBuildLogger logger; glslang::SpvOptions spvOptions; spvOptions.disableOptimizer = false; - spvOptions.optimizeSize = true; + spvOptions.optimizeSize = true; #if CC_DEBUG > 0 //spvOptions.validate = true; #else @@ -137,12 +137,12 @@ void SPIRVUtils::compileGLSL(ShaderStageFlagBit type, const ccstd::string &sourc } void SPIRVUtils::compressInputLocations(gfx::AttributeList &attributes) { - static ccstd::vector ids; + static ccstd::vector ids; static ccstd::vector activeLocations; static ccstd::vector newLocations; - uint32_t *code = _output.data(); - uint32_t codeSize = utils::toUint(_output.size()); + uint32_t *code = _output.data(); + uint32_t codeSize = utils::toUint(_output.size()); CC_ASSERT(code[0] == SpvMagicNumber); @@ -151,7 +151,7 @@ void SPIRVUtils::compressInputLocations(gfx::AttributeList &attributes) { uint32_t *insn = code + 5; while (insn != code + codeSize) { - auto opcode = static_cast(insn[0]); + auto opcode = static_cast(insn[0]); auto wordCount = static_cast(insn[0] >> 16); switch (opcode) { @@ -175,8 +175,8 @@ void SPIRVUtils::compressInputLocations(gfx::AttributeList &attributes) { CC_ASSERT(id < idBound); CC_ASSERT(ids[id].opcode == 0); - ids[id].opcode = opcode; - ids[id].typeId = insn[1]; + ids[id].opcode = opcode; + ids[id].typeId = insn[1]; ids[id].storageClass = insn[3]; } break; } @@ -192,7 +192,7 @@ void SPIRVUtils::compressInputLocations(gfx::AttributeList &attributes) { activeLocations.push_back(_program->getPipeInput(i).getType()->getQualifier().layoutLocation); } - uint32_t location = 0; + uint32_t location = 0; uint32_t unusedLocation = activeCount; newLocations.assign(attributes.size(), UINT_MAX); @@ -212,7 +212,7 @@ void SPIRVUtils::compressInputLocations(gfx::AttributeList &attributes) { for (size_t i = 0; i < attributes.size(); ++i) { if (attributes[i].location == oldLocation) { newLocations[i] = *id.pLocation; - found = true; + found = true; break; } } diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.h b/native/cocos/renderer/gfx-base/SPIRVUtils.h index 2501a2f3f1..b4be54a5c8 100644 --- a/native/cocos/renderer/gfx-base/SPIRVUtils.h +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.h @@ -53,13 +53,13 @@ public: } private: - int _clientInputSemanticsVersion{0}; - glslang::EShTargetClientVersion _clientVersion{glslang::EShTargetClientVersion::EShTargetVulkan_1_0}; + int _clientInputSemanticsVersion{0}; + glslang::EShTargetClientVersion _clientVersion{glslang::EShTargetClientVersion::EShTargetVulkan_1_0}; glslang::EShTargetLanguageVersion _targetVersion{glslang::EShTargetLanguageVersion::EShTargetSpv_1_0}; - std::unique_ptr _shader{nullptr}; + std::unique_ptr _shader{nullptr}; std::unique_ptr _program{nullptr}; - ccstd::vector _output; + ccstd::vector _output; static SPIRVUtils instance; }; diff --git a/native/cocos/renderer/gfx-base/states/GFXGeneralBarrier.h b/native/cocos/renderer/gfx-base/states/GFXGeneralBarrier.h index 00432f1818..c2336e7fd9 100644 --- a/native/cocos/renderer/gfx-base/states/GFXGeneralBarrier.h +++ b/native/cocos/renderer/gfx-base/states/GFXGeneralBarrier.h @@ -37,11 +37,11 @@ public: static size_t computeHash(const GeneralBarrierInfo &info); inline const GeneralBarrierInfo &getInfo() const { return _info; } - inline const size_t & getHash() const { return _hash; } + inline const size_t &getHash() const { return _hash; } protected: GeneralBarrierInfo _info; - size_t _hash{0U}; + size_t _hash{0U}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/states/GFXSampler.cpp b/native/cocos/renderer/gfx-base/states/GFXSampler.cpp index 19dd265892..472e9ebd2f 100644 --- a/native/cocos/renderer/gfx-base/states/GFXSampler.cpp +++ b/native/cocos/renderer/gfx-base/states/GFXSampler.cpp @@ -40,14 +40,14 @@ size_t Sampler::computeHash(const SamplerInfo &info) { SamplerInfo Sampler::unpackFromHash(size_t hash) { SamplerInfo info; - info.minFilter = static_cast((hash & ((1 << 2) - 1)) >> 0); - info.magFilter = static_cast((hash & ((1 << 2) - 1)) >> 2); - info.mipFilter = static_cast((hash & ((1 << 2) - 1)) >> 4); - info.addressU = static_cast
((hash & ((1 << 2) - 1)) >> 6); - info.addressV = static_cast
((hash & ((1 << 2) - 1)) >> 8); - info.addressW = static_cast
((hash & ((1 << 2) - 1)) >> 10); + info.minFilter = static_cast((hash & ((1 << 2) - 1)) >> 0); + info.magFilter = static_cast((hash & ((1 << 2) - 1)) >> 2); + info.mipFilter = static_cast((hash & ((1 << 2) - 1)) >> 4); + info.addressU = static_cast
((hash & ((1 << 2) - 1)) >> 6); + info.addressV = static_cast
((hash & ((1 << 2) - 1)) >> 8); + info.addressW = static_cast
((hash & ((1 << 2) - 1)) >> 10); info.maxAnisotropy = (hash & ((1 << 4) - 1)) >> 12; - info.cmpFunc = static_cast((hash & ((1 << 3) - 1)) >> 16); + info.cmpFunc = static_cast((hash & ((1 << 3) - 1)) >> 16); return info; } diff --git a/native/cocos/renderer/gfx-base/states/GFXSampler.h b/native/cocos/renderer/gfx-base/states/GFXSampler.h index 34651f5bf6..1346986f4c 100644 --- a/native/cocos/renderer/gfx-base/states/GFXSampler.h +++ b/native/cocos/renderer/gfx-base/states/GFXSampler.h @@ -35,15 +35,15 @@ class CC_DLL Sampler : public GFXObject { public: explicit Sampler(const SamplerInfo &info); - static size_t computeHash(const SamplerInfo &info); + static size_t computeHash(const SamplerInfo &info); static SamplerInfo unpackFromHash(size_t hash); inline const SamplerInfo &getInfo() const { return _info; } - inline const size_t & getHash() const { return _hash; } + inline const size_t &getHash() const { return _hash; } protected: SamplerInfo _info; - size_t _hash{0U}; + size_t _hash{0U}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h index 29157266a4..9982b7ae26 100644 --- a/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h +++ b/native/cocos/renderer/gfx-base/states/GFXTextureBarrier.h @@ -37,11 +37,11 @@ public: static size_t computeHash(const TextureBarrierInfo &info); inline const TextureBarrierInfo &getInfo() const { return _info; } - inline const size_t & getHash() const { return _hash; } + inline const size_t &getHash() const { return _hash; } protected: TextureBarrierInfo _info; - size_t _hash{0U}; + size_t _hash{0U}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp index b3b1b4bce6..c64f274bd8 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp @@ -61,19 +61,19 @@ EmptyDevice::~EmptyDevice() { bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); + _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _cmdBuff = createCommandBuffer(cmdBuffInfo); _formatFeatures.fill(static_cast(-1)); // allow all usages for all formats _formatFeatures[toNumber(Format::UNKNOWN)] = FormatFeature::NONE; - _formatFeatures[toNumber(Format::COUNT)] = FormatFeature::NONE; + _formatFeatures[toNumber(Format::COUNT)] = FormatFeature::NONE; CC_LOG_INFO("Empty device initialized."); diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.h b/native/cocos/renderer/gfx-empty/EmptyDevice.h index e4f3efc216..ed351fe07f 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.h +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.h @@ -58,20 +58,20 @@ public: void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool emptyhas) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool emptyhas) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; diff --git a/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp b/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp index 99203ddcbc..7a7b0cf50a 100644 --- a/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp +++ b/native/cocos/renderer/gfx-empty/EmptySwapchain.cpp @@ -30,14 +30,14 @@ namespace cc { namespace gfx { void EmptySwapchain::doInit(const SwapchainInfo &info) { - _colorTexture = ccnew EmptyTexture; + _colorTexture = ccnew EmptyTexture; _depthStencilTexture = ccnew EmptyTexture; SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = Format::RGBA8; - textureInfo.width = info.width; - textureInfo.height = info.height; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; initTexture(textureInfo, _colorTexture); textureInfo.format = Format::DEPTH_STENCIL; diff --git a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h index 5cbdfd089f..767951a122 100644 --- a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h +++ b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h @@ -64,13 +64,13 @@ enum class GLESCmdType : uint8_t { struct GLESBindingMapping { ccstd::vector blockOffsets; ccstd::vector samplerTextureOffsets; - uint32_t flexibleSet{0}; + uint32_t flexibleSet{0}; }; class GLESCmd { public: GLESCmdType type; - uint32_t refCount = 0; + uint32_t refCount = 0; explicit GLESCmd(GLESCmdType type) : type(type) {} virtual ~GLESCmd() = default; @@ -84,8 +84,8 @@ template ::v class CommandPool { public: CommandPool() : _freeCmds(INITIAL_CAPACITY) { - _frees = ccnew T *[INITIAL_CAPACITY]; - _count = INITIAL_CAPACITY; + _frees = ccnew T *[INITIAL_CAPACITY]; + _count = INITIAL_CAPACITY; _freeIdx = INITIAL_CAPACITY - 1; for (uint32_t i = 0; i < _count; ++i) { _frees[i] = ccnew T; @@ -106,9 +106,9 @@ public: T *alloc() { if (_freeIdx < 0) { - T ** oldFrees = _frees; - uint32_t size = _count * 2; - _frees = ccnew T *[size]; + T **oldFrees = _frees; + uint32_t size = _count * 2; + _frees = ccnew T *[size]; uint32_t increase = size - _count; for (uint32_t i = 0; i < increase; ++i) { _frees[i] = ccnew T; @@ -122,7 +122,7 @@ public: _freeIdx += static_cast(increase); } - T *cmd = _frees[_freeIdx]; + T *cmd = _frees[_freeIdx]; _frees[_freeIdx--] = nullptr; ++cmd->refCount; return cmd; @@ -153,10 +153,10 @@ public: } protected: - T ** _frees = nullptr; - uint32_t _count = 0; + T **_frees = nullptr; + uint32_t _count = 0; CachedArray _freeCmds; - int _freeIdx = 0; + int _freeIdx = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles-common/eglw.cpp b/native/cocos/renderer/gfx-gles-common/eglw.cpp index f42f565aea..eb856329ef 100644 --- a/native/cocos/renderer/gfx-gles-common/eglw.cpp +++ b/native/cocos/renderer/gfx-gles-common/eglw.cpp @@ -37,42 +37,42 @@ PFNEGLGETPROCADDRESSPROC eglGetProcAddress; /* EGL_VERSION_1_0 */ -PFNEGLCHOOSECONFIGPROC eglChooseConfig; -PFNEGLCOPYBUFFERSPROC eglCopyBuffers; -PFNEGLCREATECONTEXTPROC eglCreateContext; +PFNEGLCHOOSECONFIGPROC eglChooseConfig; +PFNEGLCOPYBUFFERSPROC eglCopyBuffers; +PFNEGLCREATECONTEXTPROC eglCreateContext; PFNEGLCREATEPBUFFERSURFACEPROC eglCreatePbufferSurface; -PFNEGLCREATEPIXMAPSURFACEPROC eglCreatePixmapSurface; -PFNEGLCREATEWINDOWSURFACEPROC eglCreateWindowSurface; -PFNEGLDESTROYCONTEXTPROC eglDestroyContext; -PFNEGLDESTROYSURFACEPROC eglDestroySurface; -PFNEGLGETCONFIGATTRIBPROC eglGetConfigAttrib; -PFNEGLGETCONFIGSPROC eglGetConfigs; -PFNEGLGETCURRENTDISPLAYPROC eglGetCurrentDisplay; -PFNEGLGETCURRENTSURFACEPROC eglGetCurrentSurface; -PFNEGLGETDISPLAYPROC eglGetDisplay; -PFNEGLGETERRORPROC eglGetError; -PFNEGLINITIALIZEPROC eglInitialize; -PFNEGLMAKECURRENTPROC eglMakeCurrent; -PFNEGLQUERYCONTEXTPROC eglQueryContext; -PFNEGLQUERYSTRINGPROC eglQueryString; -PFNEGLQUERYSURFACEPROC eglQuerySurface; -PFNEGLSWAPBUFFERSPROC eglSwapBuffers; -PFNEGLTERMINATEPROC eglTerminate; -PFNEGLWAITGLPROC eglWaitGL; -PFNEGLWAITNATIVEPROC eglWaitNative; +PFNEGLCREATEPIXMAPSURFACEPROC eglCreatePixmapSurface; +PFNEGLCREATEWINDOWSURFACEPROC eglCreateWindowSurface; +PFNEGLDESTROYCONTEXTPROC eglDestroyContext; +PFNEGLDESTROYSURFACEPROC eglDestroySurface; +PFNEGLGETCONFIGATTRIBPROC eglGetConfigAttrib; +PFNEGLGETCONFIGSPROC eglGetConfigs; +PFNEGLGETCURRENTDISPLAYPROC eglGetCurrentDisplay; +PFNEGLGETCURRENTSURFACEPROC eglGetCurrentSurface; +PFNEGLGETDISPLAYPROC eglGetDisplay; +PFNEGLGETERRORPROC eglGetError; +PFNEGLINITIALIZEPROC eglInitialize; +PFNEGLMAKECURRENTPROC eglMakeCurrent; +PFNEGLQUERYCONTEXTPROC eglQueryContext; +PFNEGLQUERYSTRINGPROC eglQueryString; +PFNEGLQUERYSURFACEPROC eglQuerySurface; +PFNEGLSWAPBUFFERSPROC eglSwapBuffers; +PFNEGLTERMINATEPROC eglTerminate; +PFNEGLWAITGLPROC eglWaitGL; +PFNEGLWAITNATIVEPROC eglWaitNative; /* EGL_VERSION_1_1 */ -PFNEGLBINDTEXIMAGEPROC eglBindTexImage; +PFNEGLBINDTEXIMAGEPROC eglBindTexImage; PFNEGLRELEASETEXIMAGEPROC eglReleaseTexImage; -PFNEGLSURFACEATTRIBPROC eglSurfaceAttrib; -PFNEGLSWAPINTERVALPROC eglSwapInterval; +PFNEGLSURFACEATTRIBPROC eglSurfaceAttrib; +PFNEGLSWAPINTERVALPROC eglSwapInterval; /* EGL_VERSION_1_2 */ -PFNEGLBINDAPIPROC eglBindAPI; -PFNEGLQUERYAPIPROC eglQueryAPI; +PFNEGLBINDAPIPROC eglBindAPI; +PFNEGLQUERYAPIPROC eglQueryAPI; PFNEGLCREATEPBUFFERFROMCLIENTBUFFERPROC eglCreatePbufferFromClientBuffer; -PFNEGLRELEASETHREADPROC eglReleaseThread; -PFNEGLWAITCLIENTPROC eglWaitClient; +PFNEGLRELEASETHREADPROC eglReleaseThread; +PFNEGLWAITCLIENTPROC eglWaitClient; /* EGL_VERSION_1_3 */ @@ -80,15 +80,15 @@ PFNEGLWAITCLIENTPROC eglWaitClient; PFNEGLGETCURRENTCONTEXTPROC eglGetCurrentContext; /* EGL_VERSION_1_5 */ -PFNEGLCREATESYNCPROC eglCreateSync; -PFNEGLDESTROYSYNCPROC eglDestroySync; +PFNEGLCREATESYNCPROC eglCreateSync; +PFNEGLDESTROYSYNCPROC eglDestroySync; PFNEGLCLIENTWAITSYNCPROC eglClientWaitSync; -PFNEGLGETSYNCATTRIBPROC eglGetSyncAttrib; +PFNEGLGETSYNCATTRIBPROC eglGetSyncAttrib; -PFNEGLCREATEIMAGEPROC eglCreateImage; +PFNEGLCREATEIMAGEPROC eglCreateImage; PFNEGLDESTROYIMAGEPROC eglDestroyImage; -PFNEGLGETPLATFORMDISPLAYPROC eglGetPlatformDisplay; +PFNEGLGETPLATFORMDISPLAYPROC eglGetPlatformDisplay; PFNEGLCREATEPLATFORMWINDOWSURFACEPROC eglCreatePlatformWindowSurface; PFNEGLCREATEPLATFORMPIXMAPSURFACEPROC eglCreatePlatformPixmapSurface; @@ -116,10 +116,10 @@ PFNEGLPRESENTATIONTIMEANDROIDPROC eglPresentationTimeANDROID; #if defined(EGL_ANDROID_get_frame_timestamps) PFNEGLGETCOMPOSITORTIMINGSUPPORTEDANDROIDPROC eglGetCompositorTimingSupportedANDROID; -PFNEGLGETCOMPOSITORTIMINGANDROIDPROC eglGetCompositorTimingANDROID; -PFNEGLGETNEXTFRAMEIDANDROIDPROC eglGetNextFrameIdANDROID; -PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC eglGetFrameTimestampSupportedANDROID; -PFNEGLGETFRAMETIMESTAMPSANDROIDPROC eglGetFrameTimestampsANDROID; +PFNEGLGETCOMPOSITORTIMINGANDROIDPROC eglGetCompositorTimingANDROID; +PFNEGLGETNEXTFRAMEIDANDROIDPROC eglGetNextFrameIdANDROID; +PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC eglGetFrameTimestampSupportedANDROID; +PFNEGLGETFRAMETIMESTAMPSANDROIDPROC eglGetFrameTimestampsANDROID; #endif /* defined(EGL_ANDROID_get_frame_timestamps) */ #if defined(EGL_ANGLE_query_surface_pointer) @@ -135,30 +135,30 @@ PFNEGLCLIENTSIGNALSYNCEXTPROC eglClientSignalSyncEXT; #endif /* defined(EGL_EXT_client_sync) */ #if defined(EGL_EXT_device_base) -PFNEGLQUERYDEVICEATTRIBEXTPROC eglQueryDeviceAttribEXT; -PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; -PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; +PFNEGLQUERYDEVICEATTRIBEXTPROC eglQueryDeviceAttribEXT; +PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; +PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; PFNEGLQUERYDISPLAYATTRIBEXTPROC eglQueryDisplayAttribEXT; #endif /* defined(EGL_EXT_device_base) */ #if defined(EGL_EXT_image_dma_buf_import_modifiers) -PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; +PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; PFNEGLQUERYDMABUFMODIFIERSEXTPROC eglQueryDmaBufModifiersEXT; #endif /* defined(EGL_EXT_image_dma_buf_import_modifiers) */ #if defined(EGL_EXT_output_base) -PFNEGLGETOUTPUTLAYERSEXTPROC eglGetOutputLayersEXT; -PFNEGLGETOUTPUTPORTSEXTPROC eglGetOutputPortsEXT; -PFNEGLOUTPUTLAYERATTRIBEXTPROC eglOutputLayerAttribEXT; +PFNEGLGETOUTPUTLAYERSEXTPROC eglGetOutputLayersEXT; +PFNEGLGETOUTPUTPORTSEXTPROC eglGetOutputPortsEXT; +PFNEGLOUTPUTLAYERATTRIBEXTPROC eglOutputLayerAttribEXT; PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC eglQueryOutputLayerAttribEXT; PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC eglQueryOutputLayerStringEXT; -PFNEGLOUTPUTPORTATTRIBEXTPROC eglOutputPortAttribEXT; -PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC eglQueryOutputPortAttribEXT; -PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC eglQueryOutputPortStringEXT; +PFNEGLOUTPUTPORTATTRIBEXTPROC eglOutputPortAttribEXT; +PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC eglQueryOutputPortAttribEXT; +PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC eglQueryOutputPortStringEXT; #endif /* defined(EGL_EXT_output_base) */ #if defined(EGL_EXT_platform_base) -PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; +PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT; PFNEGLCREATEPLATFORMPIXMAPSURFACEEXTPROC eglCreatePlatformPixmapSurfaceEXT; #endif /* defined(EGL_EXT_platform_base) */ @@ -185,8 +185,8 @@ PFNEGLCREATESYNC64KHRPROC eglCreateSync64KHR; #if defined(EGL_KHR_debug) PFNEGLDEBUGMESSAGECONTROLKHRPROC eglDebugMessageControlKHR; -PFNEGLQUERYDEBUGKHRPROC eglQueryDebugKHR; -PFNEGLLABELOBJECTKHRPROC eglLabelObjectKHR; +PFNEGLQUERYDEBUGKHRPROC eglQueryDebugKHR; +PFNEGLLABELOBJECTKHRPROC eglLabelObjectKHR; #endif /* defined(EGL_KHR_debug) */ #if defined(EGL_KHR_display_reference) @@ -194,19 +194,19 @@ PFNEGLQUERYDISPLAYATTRIBKHRPROC eglQueryDisplayAttribKHR; #endif /* defined(EGL_KHR_display_reference) */ #if defined(EGL_KHR_fence_sync) -PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR; -PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR; +PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR; +PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR; PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR; -PFNEGLGETSYNCATTRIBKHRPROC eglGetSyncAttribKHR; +PFNEGLGETSYNCATTRIBKHRPROC eglGetSyncAttribKHR; #endif /* defined(EGL_KHR_fence_sync) */ #if defined(EGL_KHR_image) -PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; +PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR; #endif /* defined(EGL_KHR_image) */ #if defined(EGL_KHR_lock_surface) -PFNEGLLOCKSURFACEKHRPROC eglLockSurfaceKHR; +PFNEGLLOCKSURFACEKHRPROC eglLockSurfaceKHR; PFNEGLUNLOCKSURFACEKHRPROC eglUnlockSurfaceKHR; #endif /* defined(EGL_KHR_lock_surface) */ @@ -223,29 +223,29 @@ PFNEGLSIGNALSYNCKHRPROC eglSignalSyncKHR; #endif /* defined(EGL_KHR_reusable_sync) */ #if defined(EGL_KHR_stream) -PFNEGLCREATESTREAMKHRPROC eglCreateStreamKHR; -PFNEGLDESTROYSTREAMKHRPROC eglDestroyStreamKHR; -PFNEGLSTREAMATTRIBKHRPROC eglStreamAttribKHR; -PFNEGLQUERYSTREAMKHRPROC eglQueryStreamKHR; +PFNEGLCREATESTREAMKHRPROC eglCreateStreamKHR; +PFNEGLDESTROYSTREAMKHRPROC eglDestroyStreamKHR; +PFNEGLSTREAMATTRIBKHRPROC eglStreamAttribKHR; +PFNEGLQUERYSTREAMKHRPROC eglQueryStreamKHR; PFNEGLQUERYSTREAMU64KHRPROC eglQueryStreamu64KHR; #endif /* defined(EGL_KHR_stream) */ #if defined(EGL_KHR_stream_attrib) -PFNEGLCREATESTREAMATTRIBKHRPROC eglCreateStreamAttribKHR; -PFNEGLSETSTREAMATTRIBKHRPROC eglSetStreamAttribKHR; -PFNEGLQUERYSTREAMATTRIBKHRPROC eglQueryStreamAttribKHR; +PFNEGLCREATESTREAMATTRIBKHRPROC eglCreateStreamAttribKHR; +PFNEGLSETSTREAMATTRIBKHRPROC eglSetStreamAttribKHR; +PFNEGLQUERYSTREAMATTRIBKHRPROC eglQueryStreamAttribKHR; PFNEGLSTREAMCONSUMERACQUIREATTRIBKHRPROC eglStreamConsumerAcquireAttribKHR; PFNEGLSTREAMCONSUMERRELEASEATTRIBKHRPROC eglStreamConsumerReleaseAttribKHR; #endif /* defined(EGL_KHR_stream_attrib) */ #if defined(EGL_KHR_stream_consumer_gltexture) PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC eglStreamConsumerGLTextureExternalKHR; -PFNEGLSTREAMCONSUMERACQUIREKHRPROC eglStreamConsumerAcquireKHR; -PFNEGLSTREAMCONSUMERRELEASEKHRPROC eglStreamConsumerReleaseKHR; +PFNEGLSTREAMCONSUMERACQUIREKHRPROC eglStreamConsumerAcquireKHR; +PFNEGLSTREAMCONSUMERRELEASEKHRPROC eglStreamConsumerReleaseKHR; #endif /* defined(EGL_KHR_stream_consumer_gltexture) */ #if defined(EGL_KHR_stream_cross_process_fd) -PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC eglGetStreamFileDescriptorKHR; +PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC eglGetStreamFileDescriptorKHR; PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC eglCreateStreamFromFileDescriptorKHR; #endif /* defined(EGL_KHR_stream_cross_process_fd) */ @@ -272,12 +272,12 @@ PFNEGLEXPORTDRMIMAGEMESAPROC eglExportDRMImageMESA; #if defined(EGL_MESA_image_dma_buf_export) PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC eglExportDMABUFImageQueryMESA; -PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA; +PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA; #endif /* defined(EGL_MESA_image_dma_buf_export) */ #if defined(EGL_MESA_query_driver) PFNEGLGETDISPLAYDRIVERCONFIGPROC eglGetDisplayDriverConfig; -PFNEGLGETDISPLAYDRIVERNAMEPROC eglGetDisplayDriverName; +PFNEGLGETDISPLAYDRIVERNAMEPROC eglGetDisplayDriverName; #endif /* defined(EGL_MESA_query_driver) */ #if defined(EGL_NOK_swap_region) @@ -290,8 +290,8 @@ PFNEGLSWAPBUFFERSREGION2NOKPROC eglSwapBuffersRegion2NOK; #if defined(EGL_NV_native_query) PFNEGLQUERYNATIVEDISPLAYNVPROC eglQueryNativeDisplayNV; -PFNEGLQUERYNATIVEWINDOWNVPROC eglQueryNativeWindowNV; -PFNEGLQUERYNATIVEPIXMAPNVPROC eglQueryNativePixmapNV; +PFNEGLQUERYNATIVEWINDOWNVPROC eglQueryNativeWindowNV; +PFNEGLQUERYNATIVEPIXMAPNVPROC eglQueryNativePixmapNV; #endif /* defined(EGL_NV_native_query) */ #if defined(EGL_NV_post_sub_buffer) @@ -304,9 +304,9 @@ PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALATTRIBSNVPROC eglStreamConsumerGLTextureExt #if defined(EGL_NV_stream_consumer_eglimage) PFNEGLSTREAMIMAGECONSUMERCONNECTNVPROC eglStreamImageConsumerConnectNV; -PFNEGLQUERYSTREAMCONSUMEREVENTNVPROC eglQueryStreamConsumerEventNV; -PFNEGLSTREAMACQUIREIMAGENVPROC eglStreamAcquireImageNV; -PFNEGLSTREAMRELEASEIMAGENVPROC eglStreamReleaseImageNV; +PFNEGLQUERYSTREAMCONSUMEREVENTNVPROC eglQueryStreamConsumerEventNV; +PFNEGLSTREAMACQUIREIMAGENVPROC eglStreamAcquireImageNV; +PFNEGLSTREAMRELEASEIMAGENVPROC eglStreamReleaseImageNV; #endif /* defined(EGL_NV_stream_consumer_eglimage) */ #if defined(EGL_NV_stream_flush) @@ -314,8 +314,8 @@ PFNEGLSTREAMFLUSHNVPROC eglStreamFlushNV; #endif /* defined(EGL_NV_stream_flush) */ #if defined(EGL_NV_stream_metadata) -PFNEGLQUERYDISPLAYATTRIBNVPROC eglQueryDisplayAttribNV; -PFNEGLSETSTREAMMETADATANVPROC eglSetStreamMetadataNV; +PFNEGLQUERYDISPLAYATTRIBNVPROC eglQueryDisplayAttribNV; +PFNEGLSETSTREAMMETADATANVPROC eglSetStreamMetadataNV; PFNEGLQUERYSTREAMMETADATANVPROC eglQueryStreamMetadataNV; #endif /* defined(EGL_NV_stream_metadata) */ @@ -329,32 +329,32 @@ PFNEGLCREATESTREAMSYNCNVPROC eglCreateStreamSyncNV; #if defined(EGL_NV_sync) PFNEGLCREATEFENCESYNCNVPROC eglCreateFenceSyncNV; -PFNEGLDESTROYSYNCNVPROC eglDestroySyncNV; -PFNEGLFENCENVPROC eglFenceNV; -PFNEGLCLIENTWAITSYNCNVPROC eglClientWaitSyncNV; -PFNEGLSIGNALSYNCNVPROC eglSignalSyncNV; -PFNEGLGETSYNCATTRIBNVPROC eglGetSyncAttribNV; +PFNEGLDESTROYSYNCNVPROC eglDestroySyncNV; +PFNEGLFENCENVPROC eglFenceNV; +PFNEGLCLIENTWAITSYNCNVPROC eglClientWaitSyncNV; +PFNEGLSIGNALSYNCNVPROC eglSignalSyncNV; +PFNEGLGETSYNCATTRIBNVPROC eglGetSyncAttribNV; #endif /* defined(EGL_NV_sync) */ #if defined(EGL_NV_system_time) PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV; -PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; +PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; #endif /* defined(EGL_NV_system_time) */ #if defined(EGL_EXT_compositor) -PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC eglCompositorSetContextListEXT; +PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC eglCompositorSetContextListEXT; PFNEGLCOMPOSITORSETCONTEXTATTRIBUTESEXTPROC eglCompositorSetContextAttributesEXT; -PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC eglCompositorSetWindowListEXT; -PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC eglCompositorSetWindowAttributesEXT; -PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC eglCompositorBindTexWindowEXT; -PFNEGLCOMPOSITORSETSIZEEXTPROC eglCompositorSetSizeEXT; -PFNEGLCOMPOSITORSWAPPOLICYEXTPROC eglCompositorSwapPolicyEXT; +PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC eglCompositorSetWindowListEXT; +PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC eglCompositorSetWindowAttributesEXT; +PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC eglCompositorBindTexWindowEXT; +PFNEGLCOMPOSITORSETSIZEEXTPROC eglCompositorSetSizeEXT; +PFNEGLCOMPOSITORSWAPPOLICYEXTPROC eglCompositorSwapPolicyEXT; #endif /* defined(EGL_EXT_compositor) */ #if defined(EGL_WL_bind_wayland_display) -PFNEGLBINDWAYLANDDISPLAYWLPROC eglBindWaylandDisplayWL; +PFNEGLBINDWAYLANDDISPLAYWLPROC eglBindWaylandDisplayWL; PFNEGLUNBINDWAYLANDDISPLAYWLPROC eglUnbindWaylandDisplayWL; -PFNEGLQUERYWAYLANDBUFFERWLPROC eglQueryWaylandBufferWL; +PFNEGLQUERYWAYLANDBUFFERWLPROC eglQueryWaylandBufferWL; #endif /* defined(EGL_WL_bind_wayland_display) */ #if defined(EGL_WL_create_wayland_buffer_from_image) @@ -384,42 +384,42 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { eglGetProcAddress = reinterpret_cast(eglwLoad("eglGetProcAddress")); /* EGL_VERSION_1_0 */ - eglChooseConfig = reinterpret_cast(eglwLoad("eglChooseConfig")); - eglCopyBuffers = reinterpret_cast(eglwLoad("eglCopyBuffers")); - eglCreateContext = reinterpret_cast(eglwLoad("eglCreateContext")); + eglChooseConfig = reinterpret_cast(eglwLoad("eglChooseConfig")); + eglCopyBuffers = reinterpret_cast(eglwLoad("eglCopyBuffers")); + eglCreateContext = reinterpret_cast(eglwLoad("eglCreateContext")); eglCreatePbufferSurface = reinterpret_cast(eglwLoad("eglCreatePbufferSurface")); - eglCreatePixmapSurface = reinterpret_cast(eglwLoad("eglCreatePixmapSurface")); - eglCreateWindowSurface = reinterpret_cast(eglwLoad("eglCreateWindowSurface")); - eglDestroyContext = reinterpret_cast(eglwLoad("eglDestroyContext")); - eglDestroySurface = reinterpret_cast(eglwLoad("eglDestroySurface")); - eglGetConfigAttrib = reinterpret_cast(eglwLoad("eglGetConfigAttrib")); - eglGetConfigs = reinterpret_cast(eglwLoad("eglGetConfigs")); - eglGetCurrentDisplay = reinterpret_cast(eglwLoad("eglGetCurrentDisplay")); - eglGetCurrentSurface = reinterpret_cast(eglwLoad("eglGetCurrentSurface")); - eglGetDisplay = reinterpret_cast(eglwLoad("eglGetDisplay")); - eglGetError = reinterpret_cast(eglwLoad("eglGetError")); - eglInitialize = reinterpret_cast(eglwLoad("eglInitialize")); - eglMakeCurrent = reinterpret_cast(eglwLoad("eglMakeCurrent")); - eglQueryContext = reinterpret_cast(eglwLoad("eglQueryContext")); - eglQueryString = reinterpret_cast(eglwLoad("eglQueryString")); - eglQuerySurface = reinterpret_cast(eglwLoad("eglQuerySurface")); - eglSwapBuffers = reinterpret_cast(eglwLoad("eglSwapBuffers")); - eglTerminate = reinterpret_cast(eglwLoad("eglTerminate")); - eglWaitGL = reinterpret_cast(eglwLoad("eglWaitGL")); - eglWaitNative = reinterpret_cast(eglwLoad("eglWaitNative")); + eglCreatePixmapSurface = reinterpret_cast(eglwLoad("eglCreatePixmapSurface")); + eglCreateWindowSurface = reinterpret_cast(eglwLoad("eglCreateWindowSurface")); + eglDestroyContext = reinterpret_cast(eglwLoad("eglDestroyContext")); + eglDestroySurface = reinterpret_cast(eglwLoad("eglDestroySurface")); + eglGetConfigAttrib = reinterpret_cast(eglwLoad("eglGetConfigAttrib")); + eglGetConfigs = reinterpret_cast(eglwLoad("eglGetConfigs")); + eglGetCurrentDisplay = reinterpret_cast(eglwLoad("eglGetCurrentDisplay")); + eglGetCurrentSurface = reinterpret_cast(eglwLoad("eglGetCurrentSurface")); + eglGetDisplay = reinterpret_cast(eglwLoad("eglGetDisplay")); + eglGetError = reinterpret_cast(eglwLoad("eglGetError")); + eglInitialize = reinterpret_cast(eglwLoad("eglInitialize")); + eglMakeCurrent = reinterpret_cast(eglwLoad("eglMakeCurrent")); + eglQueryContext = reinterpret_cast(eglwLoad("eglQueryContext")); + eglQueryString = reinterpret_cast(eglwLoad("eglQueryString")); + eglQuerySurface = reinterpret_cast(eglwLoad("eglQuerySurface")); + eglSwapBuffers = reinterpret_cast(eglwLoad("eglSwapBuffers")); + eglTerminate = reinterpret_cast(eglwLoad("eglTerminate")); + eglWaitGL = reinterpret_cast(eglwLoad("eglWaitGL")); + eglWaitNative = reinterpret_cast(eglwLoad("eglWaitNative")); /* EGL_VERSION_1_1 */ - eglBindTexImage = reinterpret_cast(eglwLoad("eglBindTexImage")); + eglBindTexImage = reinterpret_cast(eglwLoad("eglBindTexImage")); eglReleaseTexImage = reinterpret_cast(eglwLoad("eglReleaseTexImage")); - eglSurfaceAttrib = reinterpret_cast(eglwLoad("eglSurfaceAttrib")); - eglSwapInterval = reinterpret_cast(eglwLoad("eglSwapInterval")); + eglSurfaceAttrib = reinterpret_cast(eglwLoad("eglSurfaceAttrib")); + eglSwapInterval = reinterpret_cast(eglwLoad("eglSwapInterval")); /* EGL_VERSION_1_2 */ - eglBindAPI = reinterpret_cast(eglwLoad("eglBindAPI")); - eglQueryAPI = reinterpret_cast(eglwLoad("eglQueryAPI")); + eglBindAPI = reinterpret_cast(eglwLoad("eglBindAPI")); + eglQueryAPI = reinterpret_cast(eglwLoad("eglQueryAPI")); eglCreatePbufferFromClientBuffer = reinterpret_cast(eglwLoad("eglCreatePbufferFromClientBuffer")); - eglReleaseThread = reinterpret_cast(eglwLoad("eglReleaseThread")); - eglWaitClient = reinterpret_cast(eglwLoad("eglWaitClient")); + eglReleaseThread = reinterpret_cast(eglwLoad("eglReleaseThread")); + eglWaitClient = reinterpret_cast(eglwLoad("eglWaitClient")); /* EGL_VERSION_1_3 */ @@ -427,15 +427,15 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { eglGetCurrentContext = reinterpret_cast(eglwLoad("eglGetCurrentContext")); /* EGL_VERSION_1_5 */ - eglCreateSync = reinterpret_cast(eglwLoad("eglCreateSync")); - eglDestroySync = reinterpret_cast(eglwLoad("eglDestroySync")); + eglCreateSync = reinterpret_cast(eglwLoad("eglCreateSync")); + eglDestroySync = reinterpret_cast(eglwLoad("eglDestroySync")); eglClientWaitSync = reinterpret_cast(eglwLoad("eglClientWaitSync")); - eglGetSyncAttrib = reinterpret_cast(eglwLoad("eglGetSyncAttrib")); + eglGetSyncAttrib = reinterpret_cast(eglwLoad("eglGetSyncAttrib")); - eglCreateImage = reinterpret_cast(eglwLoad("eglCreateImage")); + eglCreateImage = reinterpret_cast(eglwLoad("eglCreateImage")); eglDestroyImage = reinterpret_cast(eglwLoad("eglDestroyImage")); - eglGetPlatformDisplay = reinterpret_cast(eglwLoad("eglGetPlatformDisplay")); + eglGetPlatformDisplay = reinterpret_cast(eglwLoad("eglGetPlatformDisplay")); eglCreatePlatformWindowSurface = reinterpret_cast(eglwLoad("eglCreatePlatformWindowSurface")); eglCreatePlatformPixmapSurface = reinterpret_cast(eglwLoad("eglCreatePlatformPixmapSurface")); @@ -463,10 +463,10 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_ANDROID_get_frame_timestamps) eglGetCompositorTimingSupportedANDROID = reinterpret_cast(eglwLoad("eglGetCompositorTimingSupportedANDROID")); - eglGetCompositorTimingANDROID = reinterpret_cast(eglwLoad("eglGetCompositorTimingANDROID")); - eglGetNextFrameIdANDROID = reinterpret_cast(eglwLoad("eglGetNextFrameIdANDROID")); - eglGetFrameTimestampSupportedANDROID = reinterpret_cast(eglwLoad("eglGetFrameTimestampSupportedANDROID")); - eglGetFrameTimestampsANDROID = reinterpret_cast(eglwLoad("eglGetFrameTimestampsANDROID")); + eglGetCompositorTimingANDROID = reinterpret_cast(eglwLoad("eglGetCompositorTimingANDROID")); + eglGetNextFrameIdANDROID = reinterpret_cast(eglwLoad("eglGetNextFrameIdANDROID")); + eglGetFrameTimestampSupportedANDROID = reinterpret_cast(eglwLoad("eglGetFrameTimestampSupportedANDROID")); + eglGetFrameTimestampsANDROID = reinterpret_cast(eglwLoad("eglGetFrameTimestampsANDROID")); #endif /* defined(EGL_ANDROID_get_frame_timestamps) */ #if defined(EGL_ANGLE_query_surface_pointer) @@ -482,30 +482,30 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #endif /* defined(EGL_EXT_client_sync) */ #if defined(EGL_EXT_device_base) - eglQueryDeviceAttribEXT = reinterpret_cast(eglwLoad("eglQueryDeviceAttribEXT")); - eglQueryDeviceStringEXT = reinterpret_cast(eglwLoad("eglQueryDeviceStringEXT")); - eglQueryDevicesEXT = reinterpret_cast(eglwLoad("eglQueryDevicesEXT")); + eglQueryDeviceAttribEXT = reinterpret_cast(eglwLoad("eglQueryDeviceAttribEXT")); + eglQueryDeviceStringEXT = reinterpret_cast(eglwLoad("eglQueryDeviceStringEXT")); + eglQueryDevicesEXT = reinterpret_cast(eglwLoad("eglQueryDevicesEXT")); eglQueryDisplayAttribEXT = reinterpret_cast(eglwLoad("eglQueryDisplayAttribEXT")); #endif /* defined(EGL_EXT_device_base) */ #if defined(EGL_EXT_image_dma_buf_import_modifiers) - eglQueryDmaBufFormatsEXT = reinterpret_cast(eglwLoad("eglQueryDmaBufFormatsEXT")); + eglQueryDmaBufFormatsEXT = reinterpret_cast(eglwLoad("eglQueryDmaBufFormatsEXT")); eglQueryDmaBufModifiersEXT = reinterpret_cast(eglwLoad("eglQueryDmaBufModifiersEXT")); #endif /* defined(EGL_EXT_image_dma_buf_import_modifiers) */ #if defined(EGL_EXT_output_base) - eglGetOutputLayersEXT = reinterpret_cast(eglwLoad("eglGetOutputLayersEXT")); - eglGetOutputPortsEXT = reinterpret_cast(eglwLoad("eglGetOutputPortsEXT")); - eglOutputLayerAttribEXT = reinterpret_cast(eglwLoad("eglOutputLayerAttribEXT")); + eglGetOutputLayersEXT = reinterpret_cast(eglwLoad("eglGetOutputLayersEXT")); + eglGetOutputPortsEXT = reinterpret_cast(eglwLoad("eglGetOutputPortsEXT")); + eglOutputLayerAttribEXT = reinterpret_cast(eglwLoad("eglOutputLayerAttribEXT")); eglQueryOutputLayerAttribEXT = reinterpret_cast(eglwLoad("eglQueryOutputLayerAttribEXT")); eglQueryOutputLayerStringEXT = reinterpret_cast(eglwLoad("eglQueryOutputLayerStringEXT")); - eglOutputPortAttribEXT = reinterpret_cast(eglwLoad("eglOutputPortAttribEXT")); - eglQueryOutputPortAttribEXT = reinterpret_cast(eglwLoad("eglQueryOutputPortAttribEXT")); - eglQueryOutputPortStringEXT = reinterpret_cast(eglwLoad("eglQueryOutputPortStringEXT")); + eglOutputPortAttribEXT = reinterpret_cast(eglwLoad("eglOutputPortAttribEXT")); + eglQueryOutputPortAttribEXT = reinterpret_cast(eglwLoad("eglQueryOutputPortAttribEXT")); + eglQueryOutputPortStringEXT = reinterpret_cast(eglwLoad("eglQueryOutputPortStringEXT")); #endif /* defined(EGL_EXT_output_base) */ #if defined(EGL_EXT_platform_base) - eglGetPlatformDisplayEXT = reinterpret_cast(eglwLoad("eglGetPlatformDisplayEXT")); + eglGetPlatformDisplayEXT = reinterpret_cast(eglwLoad("eglGetPlatformDisplayEXT")); eglCreatePlatformWindowSurfaceEXT = reinterpret_cast(eglwLoad("eglCreatePlatformWindowSurfaceEXT")); eglCreatePlatformPixmapSurfaceEXT = reinterpret_cast(eglwLoad("eglCreatePlatformPixmapSurfaceEXT")); #endif /* defined(EGL_EXT_platform_base) */ @@ -532,8 +532,8 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_KHR_debug) eglDebugMessageControlKHR = reinterpret_cast(eglwLoad("eglDebugMessageControlKHR")); - eglQueryDebugKHR = reinterpret_cast(eglwLoad("eglQueryDebugKHR")); - eglLabelObjectKHR = reinterpret_cast(eglwLoad("eglLabelObjectKHR")); + eglQueryDebugKHR = reinterpret_cast(eglwLoad("eglQueryDebugKHR")); + eglLabelObjectKHR = reinterpret_cast(eglwLoad("eglLabelObjectKHR")); #endif /* defined(EGL_KHR_debug) */ #if defined(EGL_KHR_display_reference) @@ -541,19 +541,19 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #endif /* defined(EGL_KHR_display_reference) */ #if defined(EGL_KHR_fence_sync) - eglCreateSyncKHR = reinterpret_cast(eglwLoad("eglCreateSyncKHR")); - eglDestroySyncKHR = reinterpret_cast(eglwLoad("eglDestroySyncKHR")); + eglCreateSyncKHR = reinterpret_cast(eglwLoad("eglCreateSyncKHR")); + eglDestroySyncKHR = reinterpret_cast(eglwLoad("eglDestroySyncKHR")); eglClientWaitSyncKHR = reinterpret_cast(eglwLoad("eglClientWaitSyncKHR")); - eglGetSyncAttribKHR = reinterpret_cast(eglwLoad("eglGetSyncAttribKHR")); + eglGetSyncAttribKHR = reinterpret_cast(eglwLoad("eglGetSyncAttribKHR")); #endif /* defined(EGL_KHR_fence_sync) */ #if defined(EGL_KHR_image) - eglCreateImageKHR = reinterpret_cast(eglwLoad("eglCreateImageKHR")); + eglCreateImageKHR = reinterpret_cast(eglwLoad("eglCreateImageKHR")); eglDestroyImageKHR = reinterpret_cast(eglwLoad("eglDestroyImageKHR")); #endif /* defined(EGL_KHR_image) */ #if defined(EGL_KHR_lock_surface) - eglLockSurfaceKHR = reinterpret_cast(eglwLoad("eglLockSurfaceKHR")); + eglLockSurfaceKHR = reinterpret_cast(eglwLoad("eglLockSurfaceKHR")); eglUnlockSurfaceKHR = reinterpret_cast(eglwLoad("eglUnlockSurfaceKHR")); #endif /* defined(EGL_KHR_lock_surface) */ @@ -570,29 +570,29 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #endif /* defined(EGL_KHR_reusable_sync) */ #if defined(EGL_KHR_stream) - eglCreateStreamKHR = reinterpret_cast(eglwLoad("eglCreateStreamKHR")); - eglDestroyStreamKHR = reinterpret_cast(eglwLoad("eglDestroyStreamKHR")); - eglStreamAttribKHR = reinterpret_cast(eglwLoad("eglStreamAttribKHR")); - eglQueryStreamKHR = reinterpret_cast(eglwLoad("eglQueryStreamKHR")); + eglCreateStreamKHR = reinterpret_cast(eglwLoad("eglCreateStreamKHR")); + eglDestroyStreamKHR = reinterpret_cast(eglwLoad("eglDestroyStreamKHR")); + eglStreamAttribKHR = reinterpret_cast(eglwLoad("eglStreamAttribKHR")); + eglQueryStreamKHR = reinterpret_cast(eglwLoad("eglQueryStreamKHR")); eglQueryStreamu64KHR = reinterpret_cast(eglwLoad("eglQueryStreamu64KHR")); #endif /* defined(EGL_KHR_stream) */ #if defined(EGL_KHR_stream_attrib) - eglCreateStreamAttribKHR = reinterpret_cast(eglwLoad("eglCreateStreamAttribKHR")); - eglSetStreamAttribKHR = reinterpret_cast(eglwLoad("eglSetStreamAttribKHR")); - eglQueryStreamAttribKHR = reinterpret_cast(eglwLoad("eglQueryStreamAttribKHR")); + eglCreateStreamAttribKHR = reinterpret_cast(eglwLoad("eglCreateStreamAttribKHR")); + eglSetStreamAttribKHR = reinterpret_cast(eglwLoad("eglSetStreamAttribKHR")); + eglQueryStreamAttribKHR = reinterpret_cast(eglwLoad("eglQueryStreamAttribKHR")); eglStreamConsumerAcquireAttribKHR = reinterpret_cast(eglwLoad("eglStreamConsumerAcquireAttribKHR")); eglStreamConsumerReleaseAttribKHR = reinterpret_cast(eglwLoad("eglStreamConsumerReleaseAttribKHR")); #endif /* defined(EGL_KHR_stream_attrib) */ #if defined(EGL_KHR_stream_consumer_gltexture) eglStreamConsumerGLTextureExternalKHR = reinterpret_cast(eglwLoad("eglStreamConsumerGLTextureExternalKHR")); - eglStreamConsumerAcquireKHR = reinterpret_cast(eglwLoad("eglStreamConsumerAcquireKHR")); - eglStreamConsumerReleaseKHR = reinterpret_cast(eglwLoad("eglStreamConsumerReleaseKHR")); + eglStreamConsumerAcquireKHR = reinterpret_cast(eglwLoad("eglStreamConsumerAcquireKHR")); + eglStreamConsumerReleaseKHR = reinterpret_cast(eglwLoad("eglStreamConsumerReleaseKHR")); #endif /* defined(EGL_KHR_stream_consumer_gltexture) */ #if defined(EGL_KHR_stream_cross_process_fd) - eglGetStreamFileDescriptorKHR = reinterpret_cast(eglwLoad("eglGetStreamFileDescriptorKHR")); + eglGetStreamFileDescriptorKHR = reinterpret_cast(eglwLoad("eglGetStreamFileDescriptorKHR")); eglCreateStreamFromFileDescriptorKHR = reinterpret_cast(eglwLoad("eglCreateStreamFromFileDescriptorKHR")); #endif /* defined(EGL_KHR_stream_cross_process_fd) */ @@ -619,12 +619,12 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_MESA_image_dma_buf_export) eglExportDMABUFImageQueryMESA = reinterpret_cast(eglwLoad("eglExportDMABUFImageQueryMESA")); - eglExportDMABUFImageMESA = reinterpret_cast(eglwLoad("eglExportDMABUFImageMESA")); + eglExportDMABUFImageMESA = reinterpret_cast(eglwLoad("eglExportDMABUFImageMESA")); #endif /* defined(EGL_MESA_image_dma_buf_export) */ #if defined(EGL_MESA_query_driver) eglGetDisplayDriverConfig = reinterpret_cast(eglwLoad("eglGetDisplayDriverConfig")); - eglGetDisplayDriverName = reinterpret_cast(eglwLoad("eglGetDisplayDriverName")); + eglGetDisplayDriverName = reinterpret_cast(eglwLoad("eglGetDisplayDriverName")); #endif /* defined(EGL_MESA_query_driver) */ #if defined(EGL_NOK_swap_region) @@ -637,8 +637,8 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_NV_native_query) eglQueryNativeDisplayNV = reinterpret_cast(eglwLoad("eglQueryNativeDisplayNV")); - eglQueryNativeWindowNV = reinterpret_cast(eglwLoad("eglQueryNativeWindowNV")); - eglQueryNativePixmapNV = reinterpret_cast(eglwLoad("eglQueryNativePixmapNV")); + eglQueryNativeWindowNV = reinterpret_cast(eglwLoad("eglQueryNativeWindowNV")); + eglQueryNativePixmapNV = reinterpret_cast(eglwLoad("eglQueryNativePixmapNV")); #endif /* defined(EGL_NV_native_query) */ #if defined(EGL_NV_post_sub_buffer) @@ -651,9 +651,9 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_NV_stream_consumer_eglimage) eglStreamImageConsumerConnectNV = reinterpret_cast(eglwLoad("eglStreamImageConsumerConnectNV")); - eglQueryStreamConsumerEventNV = reinterpret_cast(eglwLoad("eglQueryStreamConsumerEventNV")); - eglStreamAcquireImageNV = reinterpret_cast(eglwLoad("eglStreamAcquireImageNV")); - eglStreamReleaseImageNV = reinterpret_cast(eglwLoad("eglStreamReleaseImageNV")); + eglQueryStreamConsumerEventNV = reinterpret_cast(eglwLoad("eglQueryStreamConsumerEventNV")); + eglStreamAcquireImageNV = reinterpret_cast(eglwLoad("eglStreamAcquireImageNV")); + eglStreamReleaseImageNV = reinterpret_cast(eglwLoad("eglStreamReleaseImageNV")); #endif /* defined(EGL_NV_stream_consumer_eglimage) */ #if defined(EGL_NV_stream_flush) @@ -661,8 +661,8 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #endif /* defined(EGL_NV_stream_flush) */ #if defined(EGL_NV_stream_metadata) - eglQueryDisplayAttribNV = reinterpret_cast(eglwLoad("eglQueryDisplayAttribNV")); - eglSetStreamMetadataNV = reinterpret_cast(eglwLoad("eglSetStreamMetadataNV")); + eglQueryDisplayAttribNV = reinterpret_cast(eglwLoad("eglQueryDisplayAttribNV")); + eglSetStreamMetadataNV = reinterpret_cast(eglwLoad("eglSetStreamMetadataNV")); eglQueryStreamMetadataNV = reinterpret_cast(eglwLoad("eglQueryStreamMetadataNV")); #endif /* defined(EGL_NV_stream_metadata) */ @@ -676,32 +676,32 @@ void eglwLoadProcs(PFNEGLWLOADPROC eglwLoad) { #if defined(EGL_NV_sync) eglCreateFenceSyncNV = reinterpret_cast(eglwLoad("eglCreateFenceSyncNV")); - eglDestroySyncNV = reinterpret_cast(eglwLoad("eglDestroySyncNV")); - eglFenceNV = reinterpret_cast(eglwLoad("eglFenceNV")); - eglClientWaitSyncNV = reinterpret_cast(eglwLoad("eglClientWaitSyncNV")); - eglSignalSyncNV = reinterpret_cast(eglwLoad("eglSignalSyncNV")); - eglGetSyncAttribNV = reinterpret_cast(eglwLoad("eglGetSyncAttribNV")); + eglDestroySyncNV = reinterpret_cast(eglwLoad("eglDestroySyncNV")); + eglFenceNV = reinterpret_cast(eglwLoad("eglFenceNV")); + eglClientWaitSyncNV = reinterpret_cast(eglwLoad("eglClientWaitSyncNV")); + eglSignalSyncNV = reinterpret_cast(eglwLoad("eglSignalSyncNV")); + eglGetSyncAttribNV = reinterpret_cast(eglwLoad("eglGetSyncAttribNV")); #endif /* defined(EGL_NV_sync) */ #if defined(EGL_NV_system_time) eglGetSystemTimeFrequencyNV = reinterpret_cast(eglwLoad("eglGetSystemTimeFrequencyNV")); - eglGetSystemTimeNV = reinterpret_cast(eglwLoad("eglGetSystemTimeNV")); + eglGetSystemTimeNV = reinterpret_cast(eglwLoad("eglGetSystemTimeNV")); #endif /* defined(EGL_NV_system_time) */ #if defined(EGL_EXT_compositor) - eglCompositorSetContextListEXT = reinterpret_cast(eglwLoad("eglCompositorSetContextListEXT")); + eglCompositorSetContextListEXT = reinterpret_cast(eglwLoad("eglCompositorSetContextListEXT")); eglCompositorSetContextAttributesEXT = reinterpret_cast(eglwLoad("eglCompositorSetContextAttributesEXT")); - eglCompositorSetWindowListEXT = reinterpret_cast(eglwLoad("eglCompositorSetWindowListEXT")); - eglCompositorSetWindowAttributesEXT = reinterpret_cast(eglwLoad("eglCompositorSetWindowAttributesEXT")); - eglCompositorBindTexWindowEXT = reinterpret_cast(eglwLoad("eglCompositorBindTexWindowEXT")); - eglCompositorSetSizeEXT = reinterpret_cast(eglwLoad("eglCompositorSetSizeEXT")); - eglCompositorSwapPolicyEXT = reinterpret_cast(eglwLoad("eglCompositorSwapPolicyEXT")); + eglCompositorSetWindowListEXT = reinterpret_cast(eglwLoad("eglCompositorSetWindowListEXT")); + eglCompositorSetWindowAttributesEXT = reinterpret_cast(eglwLoad("eglCompositorSetWindowAttributesEXT")); + eglCompositorBindTexWindowEXT = reinterpret_cast(eglwLoad("eglCompositorBindTexWindowEXT")); + eglCompositorSetSizeEXT = reinterpret_cast(eglwLoad("eglCompositorSetSizeEXT")); + eglCompositorSwapPolicyEXT = reinterpret_cast(eglwLoad("eglCompositorSwapPolicyEXT")); #endif /* defined(EGL_EXT_compositor) */ #if defined(EGL_WL_bind_wayland_display) - eglBindWaylandDisplayWL = reinterpret_cast(eglwLoad("eglBindWaylandDisplayWL")); + eglBindWaylandDisplayWL = reinterpret_cast(eglwLoad("eglBindWaylandDisplayWL")); eglUnbindWaylandDisplayWL = reinterpret_cast(eglwLoad("eglUnbindWaylandDisplayWL")); - eglQueryWaylandBufferWL = reinterpret_cast(eglwLoad("eglQueryWaylandBufferWL")); + eglQueryWaylandBufferWL = reinterpret_cast(eglwLoad("eglQueryWaylandBufferWL")); #endif /* defined(EGL_WL_bind_wayland_display) */ #if defined(EGL_WL_create_wayland_buffer_from_image) diff --git a/native/cocos/renderer/gfx-gles-common/eglw.h b/native/cocos/renderer/gfx-gles-common/eglw.h index 54e6a3aee6..fed3bc2582 100644 --- a/native/cocos/renderer/gfx-gles-common/eglw.h +++ b/native/cocos/renderer/gfx-gles-common/eglw.h @@ -46,42 +46,42 @@ extern PFNEGLGETPROCADDRESSPROC eglGetProcAddress; /* EGL_VERSION_1_0 */ -extern PFNEGLCHOOSECONFIGPROC eglChooseConfig; -extern PFNEGLCOPYBUFFERSPROC eglCopyBuffers; -extern PFNEGLCREATECONTEXTPROC eglCreateContext; +extern PFNEGLCHOOSECONFIGPROC eglChooseConfig; +extern PFNEGLCOPYBUFFERSPROC eglCopyBuffers; +extern PFNEGLCREATECONTEXTPROC eglCreateContext; extern PFNEGLCREATEPBUFFERSURFACEPROC eglCreatePbufferSurface; -extern PFNEGLCREATEPIXMAPSURFACEPROC eglCreatePixmapSurface; -extern PFNEGLCREATEWINDOWSURFACEPROC eglCreateWindowSurface; -extern PFNEGLDESTROYCONTEXTPROC eglDestroyContext; -extern PFNEGLDESTROYSURFACEPROC eglDestroySurface; -extern PFNEGLGETCONFIGATTRIBPROC eglGetConfigAttrib; -extern PFNEGLGETCONFIGSPROC eglGetConfigs; -extern PFNEGLGETCURRENTDISPLAYPROC eglGetCurrentDisplay; -extern PFNEGLGETCURRENTSURFACEPROC eglGetCurrentSurface; -extern PFNEGLGETDISPLAYPROC eglGetDisplay; -extern PFNEGLGETERRORPROC eglGetError; -extern PFNEGLINITIALIZEPROC eglInitialize; -extern PFNEGLMAKECURRENTPROC eglMakeCurrent; -extern PFNEGLQUERYCONTEXTPROC eglQueryContext; -extern PFNEGLQUERYSTRINGPROC eglQueryString; -extern PFNEGLQUERYSURFACEPROC eglQuerySurface; -extern PFNEGLSWAPBUFFERSPROC eglSwapBuffers; -extern PFNEGLTERMINATEPROC eglTerminate; -extern PFNEGLWAITGLPROC eglWaitGL; -extern PFNEGLWAITNATIVEPROC eglWaitNative; +extern PFNEGLCREATEPIXMAPSURFACEPROC eglCreatePixmapSurface; +extern PFNEGLCREATEWINDOWSURFACEPROC eglCreateWindowSurface; +extern PFNEGLDESTROYCONTEXTPROC eglDestroyContext; +extern PFNEGLDESTROYSURFACEPROC eglDestroySurface; +extern PFNEGLGETCONFIGATTRIBPROC eglGetConfigAttrib; +extern PFNEGLGETCONFIGSPROC eglGetConfigs; +extern PFNEGLGETCURRENTDISPLAYPROC eglGetCurrentDisplay; +extern PFNEGLGETCURRENTSURFACEPROC eglGetCurrentSurface; +extern PFNEGLGETDISPLAYPROC eglGetDisplay; +extern PFNEGLGETERRORPROC eglGetError; +extern PFNEGLINITIALIZEPROC eglInitialize; +extern PFNEGLMAKECURRENTPROC eglMakeCurrent; +extern PFNEGLQUERYCONTEXTPROC eglQueryContext; +extern PFNEGLQUERYSTRINGPROC eglQueryString; +extern PFNEGLQUERYSURFACEPROC eglQuerySurface; +extern PFNEGLSWAPBUFFERSPROC eglSwapBuffers; +extern PFNEGLTERMINATEPROC eglTerminate; +extern PFNEGLWAITGLPROC eglWaitGL; +extern PFNEGLWAITNATIVEPROC eglWaitNative; /* EGL_VERSION_1_1 */ -extern PFNEGLBINDTEXIMAGEPROC eglBindTexImage; +extern PFNEGLBINDTEXIMAGEPROC eglBindTexImage; extern PFNEGLRELEASETEXIMAGEPROC eglReleaseTexImage; -extern PFNEGLSURFACEATTRIBPROC eglSurfaceAttrib; -extern PFNEGLSWAPINTERVALPROC eglSwapInterval; +extern PFNEGLSURFACEATTRIBPROC eglSurfaceAttrib; +extern PFNEGLSWAPINTERVALPROC eglSwapInterval; /* EGL_VERSION_1_2 */ -extern PFNEGLBINDAPIPROC eglBindAPI; -extern PFNEGLQUERYAPIPROC eglQueryAPI; +extern PFNEGLBINDAPIPROC eglBindAPI; +extern PFNEGLQUERYAPIPROC eglQueryAPI; extern PFNEGLCREATEPBUFFERFROMCLIENTBUFFERPROC eglCreatePbufferFromClientBuffer; -extern PFNEGLRELEASETHREADPROC eglReleaseThread; -extern PFNEGLWAITCLIENTPROC eglWaitClient; +extern PFNEGLRELEASETHREADPROC eglReleaseThread; +extern PFNEGLWAITCLIENTPROC eglWaitClient; /* EGL_VERSION_1_3 */ @@ -89,15 +89,15 @@ extern PFNEGLWAITCLIENTPROC eglWaitClient; extern PFNEGLGETCURRENTCONTEXTPROC eglGetCurrentContext; /* EGL_VERSION_1_5 */ -extern PFNEGLCREATESYNCPROC eglCreateSync; -extern PFNEGLDESTROYSYNCPROC eglDestroySync; +extern PFNEGLCREATESYNCPROC eglCreateSync; +extern PFNEGLDESTROYSYNCPROC eglDestroySync; extern PFNEGLCLIENTWAITSYNCPROC eglClientWaitSync; -extern PFNEGLGETSYNCATTRIBPROC eglGetSyncAttrib; +extern PFNEGLGETSYNCATTRIBPROC eglGetSyncAttrib; -extern PFNEGLCREATEIMAGEPROC eglCreateImage; +extern PFNEGLCREATEIMAGEPROC eglCreateImage; extern PFNEGLDESTROYIMAGEPROC eglDestroyImage; -extern PFNEGLGETPLATFORMDISPLAYPROC eglGetPlatformDisplay; +extern PFNEGLGETPLATFORMDISPLAYPROC eglGetPlatformDisplay; extern PFNEGLCREATEPLATFORMWINDOWSURFACEPROC eglCreatePlatformWindowSurface; extern PFNEGLCREATEPLATFORMPIXMAPSURFACEPROC eglCreatePlatformPixmapSurface; @@ -125,10 +125,10 @@ extern PFNEGLPRESENTATIONTIMEANDROIDPROC eglPresentationTimeANDROID; #if defined(EGL_ANDROID_get_frame_timestamps) extern PFNEGLGETCOMPOSITORTIMINGSUPPORTEDANDROIDPROC eglGetCompositorTimingSupportedANDROID; -extern PFNEGLGETCOMPOSITORTIMINGANDROIDPROC eglGetCompositorTimingANDROID; -extern PFNEGLGETNEXTFRAMEIDANDROIDPROC eglGetNextFrameIdANDROID; -extern PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC eglGetFrameTimestampSupportedANDROID; -extern PFNEGLGETFRAMETIMESTAMPSANDROIDPROC eglGetFrameTimestampsANDROID; +extern PFNEGLGETCOMPOSITORTIMINGANDROIDPROC eglGetCompositorTimingANDROID; +extern PFNEGLGETNEXTFRAMEIDANDROIDPROC eglGetNextFrameIdANDROID; +extern PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC eglGetFrameTimestampSupportedANDROID; +extern PFNEGLGETFRAMETIMESTAMPSANDROIDPROC eglGetFrameTimestampsANDROID; #endif /* defined(EGL_ANDROID_get_frame_timestamps) */ #if defined(EGL_ANGLE_query_surface_pointer) @@ -144,30 +144,30 @@ extern PFNEGLCLIENTSIGNALSYNCEXTPROC eglClientSignalSyncEXT; #endif /* defined(EGL_EXT_client_sync) */ #if defined(EGL_EXT_device_base) -extern PFNEGLQUERYDEVICEATTRIBEXTPROC eglQueryDeviceAttribEXT; -extern PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; -extern PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; +extern PFNEGLQUERYDEVICEATTRIBEXTPROC eglQueryDeviceAttribEXT; +extern PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; +extern PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; extern PFNEGLQUERYDISPLAYATTRIBEXTPROC eglQueryDisplayAttribEXT; #endif /* defined(EGL_EXT_device_base) */ #if defined(EGL_EXT_image_dma_buf_import_modifiers) -extern PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; +extern PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; extern PFNEGLQUERYDMABUFMODIFIERSEXTPROC eglQueryDmaBufModifiersEXT; #endif /* defined(EGL_EXT_image_dma_buf_import_modifiers) */ #if defined(EGL_EXT_output_base) -extern PFNEGLGETOUTPUTLAYERSEXTPROC eglGetOutputLayersEXT; -extern PFNEGLGETOUTPUTPORTSEXTPROC eglGetOutputPortsEXT; -extern PFNEGLOUTPUTLAYERATTRIBEXTPROC eglOutputLayerAttribEXT; +extern PFNEGLGETOUTPUTLAYERSEXTPROC eglGetOutputLayersEXT; +extern PFNEGLGETOUTPUTPORTSEXTPROC eglGetOutputPortsEXT; +extern PFNEGLOUTPUTLAYERATTRIBEXTPROC eglOutputLayerAttribEXT; extern PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC eglQueryOutputLayerAttribEXT; extern PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC eglQueryOutputLayerStringEXT; -extern PFNEGLOUTPUTPORTATTRIBEXTPROC eglOutputPortAttribEXT; -extern PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC eglQueryOutputPortAttribEXT; -extern PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC eglQueryOutputPortStringEXT; +extern PFNEGLOUTPUTPORTATTRIBEXTPROC eglOutputPortAttribEXT; +extern PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC eglQueryOutputPortAttribEXT; +extern PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC eglQueryOutputPortStringEXT; #endif /* defined(EGL_EXT_output_base) */ #if defined(EGL_EXT_platform_base) -extern PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; +extern PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; extern PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC eglCreatePlatformWindowSurfaceEXT; extern PFNEGLCREATEPLATFORMPIXMAPSURFACEEXTPROC eglCreatePlatformPixmapSurfaceEXT; #endif /* defined(EGL_EXT_platform_base) */ @@ -194,8 +194,8 @@ extern PFNEGLCREATESYNC64KHRPROC eglCreateSync64KHR; #if defined(EGL_KHR_debug) extern PFNEGLDEBUGMESSAGECONTROLKHRPROC eglDebugMessageControlKHR; -extern PFNEGLQUERYDEBUGKHRPROC eglQueryDebugKHR; -extern PFNEGLLABELOBJECTKHRPROC eglLabelObjectKHR; +extern PFNEGLQUERYDEBUGKHRPROC eglQueryDebugKHR; +extern PFNEGLLABELOBJECTKHRPROC eglLabelObjectKHR; #endif /* defined(EGL_KHR_debug) */ #if defined(EGL_KHR_display_reference) @@ -203,19 +203,19 @@ extern PFNEGLQUERYDISPLAYATTRIBKHRPROC eglQueryDisplayAttribKHR; #endif /* defined(EGL_KHR_display_reference) */ #if defined(EGL_KHR_fence_sync) -extern PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR; -extern PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR; +extern PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR; +extern PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR; extern PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR; -extern PFNEGLGETSYNCATTRIBKHRPROC eglGetSyncAttribKHR; +extern PFNEGLGETSYNCATTRIBKHRPROC eglGetSyncAttribKHR; #endif /* defined(EGL_KHR_fence_sync) */ #if defined(EGL_KHR_image) -extern PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; +extern PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; extern PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR; #endif /* defined(EGL_KHR_image) */ #if defined(EGL_KHR_lock_surface) -extern PFNEGLLOCKSURFACEKHRPROC eglLockSurfaceKHR; +extern PFNEGLLOCKSURFACEKHRPROC eglLockSurfaceKHR; extern PFNEGLUNLOCKSURFACEKHRPROC eglUnlockSurfaceKHR; #endif /* defined(EGL_KHR_lock_surface) */ @@ -232,29 +232,29 @@ extern PFNEGLSIGNALSYNCKHRPROC eglSignalSyncKHR; #endif /* defined(EGL_KHR_reusable_sync) */ #if defined(EGL_KHR_stream) -extern PFNEGLCREATESTREAMKHRPROC eglCreateStreamKHR; -extern PFNEGLDESTROYSTREAMKHRPROC eglDestroyStreamKHR; -extern PFNEGLSTREAMATTRIBKHRPROC eglStreamAttribKHR; -extern PFNEGLQUERYSTREAMKHRPROC eglQueryStreamKHR; +extern PFNEGLCREATESTREAMKHRPROC eglCreateStreamKHR; +extern PFNEGLDESTROYSTREAMKHRPROC eglDestroyStreamKHR; +extern PFNEGLSTREAMATTRIBKHRPROC eglStreamAttribKHR; +extern PFNEGLQUERYSTREAMKHRPROC eglQueryStreamKHR; extern PFNEGLQUERYSTREAMU64KHRPROC eglQueryStreamu64KHR; #endif /* defined(EGL_KHR_stream) */ #if defined(EGL_KHR_stream_attrib) -extern PFNEGLCREATESTREAMATTRIBKHRPROC eglCreateStreamAttribKHR; -extern PFNEGLSETSTREAMATTRIBKHRPROC eglSetStreamAttribKHR; -extern PFNEGLQUERYSTREAMATTRIBKHRPROC eglQueryStreamAttribKHR; +extern PFNEGLCREATESTREAMATTRIBKHRPROC eglCreateStreamAttribKHR; +extern PFNEGLSETSTREAMATTRIBKHRPROC eglSetStreamAttribKHR; +extern PFNEGLQUERYSTREAMATTRIBKHRPROC eglQueryStreamAttribKHR; extern PFNEGLSTREAMCONSUMERACQUIREATTRIBKHRPROC eglStreamConsumerAcquireAttribKHR; extern PFNEGLSTREAMCONSUMERRELEASEATTRIBKHRPROC eglStreamConsumerReleaseAttribKHR; #endif /* defined(EGL_KHR_stream_attrib) */ #if defined(EGL_KHR_stream_consumer_gltexture) extern PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC eglStreamConsumerGLTextureExternalKHR; -extern PFNEGLSTREAMCONSUMERACQUIREKHRPROC eglStreamConsumerAcquireKHR; -extern PFNEGLSTREAMCONSUMERRELEASEKHRPROC eglStreamConsumerReleaseKHR; +extern PFNEGLSTREAMCONSUMERACQUIREKHRPROC eglStreamConsumerAcquireKHR; +extern PFNEGLSTREAMCONSUMERRELEASEKHRPROC eglStreamConsumerReleaseKHR; #endif /* defined(EGL_KHR_stream_consumer_gltexture) */ #if defined(EGL_KHR_stream_cross_process_fd) -extern PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC eglGetStreamFileDescriptorKHR; +extern PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC eglGetStreamFileDescriptorKHR; extern PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC eglCreateStreamFromFileDescriptorKHR; #endif /* defined(EGL_KHR_stream_cross_process_fd) */ @@ -281,12 +281,12 @@ extern PFNEGLEXPORTDRMIMAGEMESAPROC eglExportDRMImageMESA; #if defined(EGL_MESA_image_dma_buf_export) extern PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC eglExportDMABUFImageQueryMESA; -extern PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA; +extern PFNEGLEXPORTDMABUFIMAGEMESAPROC eglExportDMABUFImageMESA; #endif /* defined(EGL_MESA_image_dma_buf_export) */ #if defined(EGL_MESA_query_driver) extern PFNEGLGETDISPLAYDRIVERCONFIGPROC eglGetDisplayDriverConfig; -extern PFNEGLGETDISPLAYDRIVERNAMEPROC eglGetDisplayDriverName; +extern PFNEGLGETDISPLAYDRIVERNAMEPROC eglGetDisplayDriverName; #endif /* defined(EGL_MESA_query_driver) */ #if defined(EGL_NOK_swap_region) @@ -299,8 +299,8 @@ extern PFNEGLSWAPBUFFERSREGION2NOKPROC eglSwapBuffersRegion2NOK; #if defined(EGL_NV_native_query) extern PFNEGLQUERYNATIVEDISPLAYNVPROC eglQueryNativeDisplayNV; -extern PFNEGLQUERYNATIVEWINDOWNVPROC eglQueryNativeWindowNV; -extern PFNEGLQUERYNATIVEPIXMAPNVPROC eglQueryNativePixmapNV; +extern PFNEGLQUERYNATIVEWINDOWNVPROC eglQueryNativeWindowNV; +extern PFNEGLQUERYNATIVEPIXMAPNVPROC eglQueryNativePixmapNV; #endif /* defined(EGL_NV_native_query) */ #if defined(EGL_NV_post_sub_buffer) @@ -313,9 +313,9 @@ extern PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALATTRIBSNVPROC eglStreamConsumerGLTex #if defined(EGL_NV_stream_consumer_eglimage) extern PFNEGLSTREAMIMAGECONSUMERCONNECTNVPROC eglStreamImageConsumerConnectNV; -extern PFNEGLQUERYSTREAMCONSUMEREVENTNVPROC eglQueryStreamConsumerEventNV; -extern PFNEGLSTREAMACQUIREIMAGENVPROC eglStreamAcquireImageNV; -extern PFNEGLSTREAMRELEASEIMAGENVPROC eglStreamReleaseImageNV; +extern PFNEGLQUERYSTREAMCONSUMEREVENTNVPROC eglQueryStreamConsumerEventNV; +extern PFNEGLSTREAMACQUIREIMAGENVPROC eglStreamAcquireImageNV; +extern PFNEGLSTREAMRELEASEIMAGENVPROC eglStreamReleaseImageNV; #endif /* defined(EGL_NV_stream_consumer_eglimage) */ #if defined(EGL_NV_stream_flush) @@ -323,8 +323,8 @@ extern PFNEGLSTREAMFLUSHNVPROC eglStreamFlushNV; #endif /* defined(EGL_NV_stream_flush) */ #if defined(EGL_NV_stream_metadata) -extern PFNEGLQUERYDISPLAYATTRIBNVPROC eglQueryDisplayAttribNV; -extern PFNEGLSETSTREAMMETADATANVPROC eglSetStreamMetadataNV; +extern PFNEGLQUERYDISPLAYATTRIBNVPROC eglQueryDisplayAttribNV; +extern PFNEGLSETSTREAMMETADATANVPROC eglSetStreamMetadataNV; extern PFNEGLQUERYSTREAMMETADATANVPROC eglQueryStreamMetadataNV; #endif /* defined(EGL_NV_stream_metadata) */ @@ -338,32 +338,32 @@ extern PFNEGLCREATESTREAMSYNCNVPROC eglCreateStreamSyncNV; #if defined(EGL_NV_sync) extern PFNEGLCREATEFENCESYNCNVPROC eglCreateFenceSyncNV; -extern PFNEGLDESTROYSYNCNVPROC eglDestroySyncNV; -extern PFNEGLFENCENVPROC eglFenceNV; -extern PFNEGLCLIENTWAITSYNCNVPROC eglClientWaitSyncNV; -extern PFNEGLSIGNALSYNCNVPROC eglSignalSyncNV; -extern PFNEGLGETSYNCATTRIBNVPROC eglGetSyncAttribNV; +extern PFNEGLDESTROYSYNCNVPROC eglDestroySyncNV; +extern PFNEGLFENCENVPROC eglFenceNV; +extern PFNEGLCLIENTWAITSYNCNVPROC eglClientWaitSyncNV; +extern PFNEGLSIGNALSYNCNVPROC eglSignalSyncNV; +extern PFNEGLGETSYNCATTRIBNVPROC eglGetSyncAttribNV; #endif /* defined(EGL_NV_sync) */ #if defined(EGL_NV_system_time) extern PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV; -extern PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; +extern PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV; #endif /* defined(EGL_NV_system_time) */ #if defined(EGL_EXT_compositor) -extern PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC eglCompositorSetContextListEXT; +extern PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC eglCompositorSetContextListEXT; extern PFNEGLCOMPOSITORSETCONTEXTATTRIBUTESEXTPROC eglCompositorSetContextAttributesEXT; -extern PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC eglCompositorSetWindowListEXT; -extern PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC eglCompositorSetWindowAttributesEXT; -extern PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC eglCompositorBindTexWindowEXT; -extern PFNEGLCOMPOSITORSETSIZEEXTPROC eglCompositorSetSizeEXT; -extern PFNEGLCOMPOSITORSWAPPOLICYEXTPROC eglCompositorSwapPolicyEXT; +extern PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC eglCompositorSetWindowListEXT; +extern PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC eglCompositorSetWindowAttributesEXT; +extern PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC eglCompositorBindTexWindowEXT; +extern PFNEGLCOMPOSITORSETSIZEEXTPROC eglCompositorSetSizeEXT; +extern PFNEGLCOMPOSITORSWAPPOLICYEXTPROC eglCompositorSwapPolicyEXT; #endif /* defined(EGL_EXT_compositor) */ #if defined(EGL_WL_bind_wayland_display) -extern PFNEGLBINDWAYLANDDISPLAYWLPROC eglBindWaylandDisplayWL; +extern PFNEGLBINDWAYLANDDISPLAYWLPROC eglBindWaylandDisplayWL; extern PFNEGLUNBINDWAYLANDDISPLAYWLPROC eglUnbindWaylandDisplayWL; -extern PFNEGLQUERYWAYLANDBUFFERWLPROC eglQueryWaylandBufferWL; +extern PFNEGLQUERYWAYLANDBUFFERWLPROC eglQueryWaylandBufferWL; #endif /* defined(EGL_WL_bind_wayland_display) */ #if defined(EGL_WL_create_wayland_buffer_from_image) diff --git a/native/cocos/renderer/gfx-gles-common/gles2w.cpp b/native/cocos/renderer/gfx-gles-common/gles2w.cpp index 57daf8841d..5de399af9e 100644 --- a/native/cocos/renderer/gfx-gles-common/gles2w.cpp +++ b/native/cocos/renderer/gfx-gles-common/gles2w.cpp @@ -46,166 +46,166 @@ /* GLES2W_GENERATE_GLES_DEFINITION */ /* GL_ES_VERSION_2_0 */ -PFNGLACTIVETEXTUREPROC glActiveTexture; -PFNGLATTACHSHADERPROC glAttachShader; -PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; -PFNGLBINDBUFFERPROC glBindBuffer; -PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; -PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; -PFNGLBINDTEXTUREPROC glBindTexture; -PFNGLBLENDCOLORPROC glBlendColor; -PFNGLBLENDEQUATIONPROC glBlendEquation; -PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; -PFNGLBLENDFUNCPROC glBlendFunc; -PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; -PFNGLBUFFERDATAPROC glBufferData; -PFNGLBUFFERSUBDATAPROC glBufferSubData; -PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; -PFNGLCLEARPROC glClear; -PFNGLCLEARCOLORPROC glClearColor; -PFNGLCLEARDEPTHFPROC glClearDepthf; -PFNGLCLEARSTENCILPROC glClearStencil; -PFNGLCOLORMASKPROC glColorMask; -PFNGLCOMPILESHADERPROC glCompileShader; -PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; -PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; -PFNGLCOPYTEXIMAGE2DPROC glCopyTexImage2D; -PFNGLCOPYTEXSUBIMAGE2DPROC glCopyTexSubImage2D; -PFNGLCREATEPROGRAMPROC glCreateProgram; -PFNGLCREATESHADERPROC glCreateShader; -PFNGLCULLFACEPROC glCullFace; -PFNGLDELETEBUFFERSPROC glDeleteBuffers; -PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; -PFNGLDELETEPROGRAMPROC glDeleteProgram; -PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; -PFNGLDELETESHADERPROC glDeleteShader; -PFNGLDELETETEXTURESPROC glDeleteTextures; -PFNGLDEPTHFUNCPROC glDepthFunc; -PFNGLDEPTHMASKPROC glDepthMask; -PFNGLDEPTHRANGEFPROC glDepthRangef; -PFNGLDETACHSHADERPROC glDetachShader; -PFNGLDISABLEPROC glDisable; -PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; -PFNGLDRAWARRAYSPROC glDrawArrays; -PFNGLDRAWELEMENTSPROC glDrawElements; -PFNGLENABLEPROC glEnable; -PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; -PFNGLFINISHPROC glFinish; -PFNGLFLUSHPROC glFlush; -PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; -PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; -PFNGLFRONTFACEPROC glFrontFace; -PFNGLGENBUFFERSPROC glGenBuffers; -PFNGLGENERATEMIPMAPPROC glGenerateMipmap; -PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; -PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; -PFNGLGENTEXTURESPROC glGenTextures; -PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; -PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; -PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; -PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; -PFNGLGETBOOLEANVPROC glGetBooleanv; -PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; -PFNGLGETERRORPROC glGetError; -PFNGLGETFLOATVPROC glGetFloatv; +PFNGLACTIVETEXTUREPROC glActiveTexture; +PFNGLATTACHSHADERPROC glAttachShader; +PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; +PFNGLBINDBUFFERPROC glBindBuffer; +PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; +PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; +PFNGLBINDTEXTUREPROC glBindTexture; +PFNGLBLENDCOLORPROC glBlendColor; +PFNGLBLENDEQUATIONPROC glBlendEquation; +PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; +PFNGLBLENDFUNCPROC glBlendFunc; +PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; +PFNGLBUFFERDATAPROC glBufferData; +PFNGLBUFFERSUBDATAPROC glBufferSubData; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; +PFNGLCLEARPROC glClear; +PFNGLCLEARCOLORPROC glClearColor; +PFNGLCLEARDEPTHFPROC glClearDepthf; +PFNGLCLEARSTENCILPROC glClearStencil; +PFNGLCOLORMASKPROC glColorMask; +PFNGLCOMPILESHADERPROC glCompileShader; +PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; +PFNGLCOPYTEXIMAGE2DPROC glCopyTexImage2D; +PFNGLCOPYTEXSUBIMAGE2DPROC glCopyTexSubImage2D; +PFNGLCREATEPROGRAMPROC glCreateProgram; +PFNGLCREATESHADERPROC glCreateShader; +PFNGLCULLFACEPROC glCullFace; +PFNGLDELETEBUFFERSPROC glDeleteBuffers; +PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; +PFNGLDELETEPROGRAMPROC glDeleteProgram; +PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; +PFNGLDELETESHADERPROC glDeleteShader; +PFNGLDELETETEXTURESPROC glDeleteTextures; +PFNGLDEPTHFUNCPROC glDepthFunc; +PFNGLDEPTHMASKPROC glDepthMask; +PFNGLDEPTHRANGEFPROC glDepthRangef; +PFNGLDETACHSHADERPROC glDetachShader; +PFNGLDISABLEPROC glDisable; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; +PFNGLDRAWARRAYSPROC glDrawArrays; +PFNGLDRAWELEMENTSPROC glDrawElements; +PFNGLENABLEPROC glEnable; +PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; +PFNGLFINISHPROC glFinish; +PFNGLFLUSHPROC glFlush; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; +PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; +PFNGLFRONTFACEPROC glFrontFace; +PFNGLGENBUFFERSPROC glGenBuffers; +PFNGLGENERATEMIPMAPPROC glGenerateMipmap; +PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; +PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; +PFNGLGENTEXTURESPROC glGenTextures; +PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; +PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; +PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; +PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; +PFNGLGETBOOLEANVPROC glGetBooleanv; +PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; +PFNGLGETERRORPROC glGetError; +PFNGLGETFLOATVPROC glGetFloatv; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetFramebufferAttachmentParameteriv; -PFNGLGETINTEGERVPROC glGetIntegerv; -PFNGLGETPROGRAMIVPROC glGetProgramiv; -PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; -PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; -PFNGLGETSHADERIVPROC glGetShaderiv; -PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; -PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; -PFNGLGETSHADERSOURCEPROC glGetShaderSource; -PFNGLGETSTRINGPROC glGetString; -PFNGLGETTEXPARAMETERFVPROC glGetTexParameterfv; -PFNGLGETTEXPARAMETERIVPROC glGetTexParameteriv; -PFNGLGETUNIFORMFVPROC glGetUniformfv; -PFNGLGETUNIFORMIVPROC glGetUniformiv; -PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; -PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; -PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; -PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; -PFNGLHINTPROC glHint; -PFNGLISBUFFERPROC glIsBuffer; -PFNGLISENABLEDPROC glIsEnabled; -PFNGLISFRAMEBUFFERPROC glIsFramebuffer; -PFNGLISPROGRAMPROC glIsProgram; -PFNGLISRENDERBUFFERPROC glIsRenderbuffer; -PFNGLISSHADERPROC glIsShader; -PFNGLISTEXTUREPROC glIsTexture; -PFNGLLINEWIDTHPROC glLineWidth; -PFNGLLINKPROGRAMPROC glLinkProgram; -PFNGLPIXELSTOREIPROC glPixelStorei; -PFNGLPOLYGONOFFSETPROC glPolygonOffset; -PFNGLREADPIXELSPROC glReadPixels; -PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; -PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; -PFNGLSAMPLECOVERAGEPROC glSampleCoverage; -PFNGLSCISSORPROC glScissor; -PFNGLSHADERBINARYPROC glShaderBinary; -PFNGLSHADERSOURCEPROC glShaderSource; -PFNGLSTENCILFUNCPROC glStencilFunc; -PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; -PFNGLSTENCILMASKPROC glStencilMask; -PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; -PFNGLSTENCILOPPROC glStencilOp; -PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; -PFNGLTEXIMAGE2DPROC glTexImage2D; -PFNGLTEXPARAMETERFPROC glTexParameterf; -PFNGLTEXPARAMETERFVPROC glTexParameterfv; -PFNGLTEXPARAMETERIPROC glTexParameteri; -PFNGLTEXPARAMETERIVPROC glTexParameteriv; -PFNGLTEXSUBIMAGE2DPROC glTexSubImage2D; -PFNGLUNIFORM1FPROC glUniform1f; -PFNGLUNIFORM1FVPROC glUniform1fv; -PFNGLUNIFORM1IPROC glUniform1i; -PFNGLUNIFORM1IVPROC glUniform1iv; -PFNGLUNIFORM2FPROC glUniform2f; -PFNGLUNIFORM2FVPROC glUniform2fv; -PFNGLUNIFORM2IPROC glUniform2i; -PFNGLUNIFORM2IVPROC glUniform2iv; -PFNGLUNIFORM3FPROC glUniform3f; -PFNGLUNIFORM3FVPROC glUniform3fv; -PFNGLUNIFORM3IPROC glUniform3i; -PFNGLUNIFORM3IVPROC glUniform3iv; -PFNGLUNIFORM4FPROC glUniform4f; -PFNGLUNIFORM4FVPROC glUniform4fv; -PFNGLUNIFORM4IPROC glUniform4i; -PFNGLUNIFORM4IVPROC glUniform4iv; -PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; -PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; -PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; -PFNGLUSEPROGRAMPROC glUseProgram; -PFNGLVALIDATEPROGRAMPROC glValidateProgram; -PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; -PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; -PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; -PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; -PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; -PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; -PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; -PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; -PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; -PFNGLVIEWPORTPROC glViewport; +PFNGLGETINTEGERVPROC glGetIntegerv; +PFNGLGETPROGRAMIVPROC glGetProgramiv; +PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; +PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; +PFNGLGETSHADERIVPROC glGetShaderiv; +PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; +PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; +PFNGLGETSHADERSOURCEPROC glGetShaderSource; +PFNGLGETSTRINGPROC glGetString; +PFNGLGETTEXPARAMETERFVPROC glGetTexParameterfv; +PFNGLGETTEXPARAMETERIVPROC glGetTexParameteriv; +PFNGLGETUNIFORMFVPROC glGetUniformfv; +PFNGLGETUNIFORMIVPROC glGetUniformiv; +PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; +PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; +PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; +PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; +PFNGLHINTPROC glHint; +PFNGLISBUFFERPROC glIsBuffer; +PFNGLISENABLEDPROC glIsEnabled; +PFNGLISFRAMEBUFFERPROC glIsFramebuffer; +PFNGLISPROGRAMPROC glIsProgram; +PFNGLISRENDERBUFFERPROC glIsRenderbuffer; +PFNGLISSHADERPROC glIsShader; +PFNGLISTEXTUREPROC glIsTexture; +PFNGLLINEWIDTHPROC glLineWidth; +PFNGLLINKPROGRAMPROC glLinkProgram; +PFNGLPIXELSTOREIPROC glPixelStorei; +PFNGLPOLYGONOFFSETPROC glPolygonOffset; +PFNGLREADPIXELSPROC glReadPixels; +PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; +PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; +PFNGLSAMPLECOVERAGEPROC glSampleCoverage; +PFNGLSCISSORPROC glScissor; +PFNGLSHADERBINARYPROC glShaderBinary; +PFNGLSHADERSOURCEPROC glShaderSource; +PFNGLSTENCILFUNCPROC glStencilFunc; +PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; +PFNGLSTENCILMASKPROC glStencilMask; +PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; +PFNGLSTENCILOPPROC glStencilOp; +PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; +PFNGLTEXIMAGE2DPROC glTexImage2D; +PFNGLTEXPARAMETERFPROC glTexParameterf; +PFNGLTEXPARAMETERFVPROC glTexParameterfv; +PFNGLTEXPARAMETERIPROC glTexParameteri; +PFNGLTEXPARAMETERIVPROC glTexParameteriv; +PFNGLTEXSUBIMAGE2DPROC glTexSubImage2D; +PFNGLUNIFORM1FPROC glUniform1f; +PFNGLUNIFORM1FVPROC glUniform1fv; +PFNGLUNIFORM1IPROC glUniform1i; +PFNGLUNIFORM1IVPROC glUniform1iv; +PFNGLUNIFORM2FPROC glUniform2f; +PFNGLUNIFORM2FVPROC glUniform2fv; +PFNGLUNIFORM2IPROC glUniform2i; +PFNGLUNIFORM2IVPROC glUniform2iv; +PFNGLUNIFORM3FPROC glUniform3f; +PFNGLUNIFORM3FVPROC glUniform3fv; +PFNGLUNIFORM3IPROC glUniform3i; +PFNGLUNIFORM3IVPROC glUniform3iv; +PFNGLUNIFORM4FPROC glUniform4f; +PFNGLUNIFORM4FVPROC glUniform4fv; +PFNGLUNIFORM4IPROC glUniform4i; +PFNGLUNIFORM4IVPROC glUniform4iv; +PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; +PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; +PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; +PFNGLUSEPROGRAMPROC glUseProgram; +PFNGLVALIDATEPROGRAMPROC glValidateProgram; +PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; +PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; +PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; +PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; +PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; +PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; +PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; +PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; +PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; +PFNGLVIEWPORTPROC glViewport; #if defined(GL_AMD_framebuffer_multisample_advanced) -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glRenderbufferStorageMultisampleAdvancedAMD; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glRenderbufferStorageMultisampleAdvancedAMD; PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glNamedRenderbufferStorageMultisampleAdvancedAMD; #endif /* defined(GL_AMD_framebuffer_multisample_advanced) */ #if defined(GL_AMD_performance_monitor) -PFNGLGETPERFMONITORGROUPSAMDPROC glGetPerfMonitorGroupsAMD; -PFNGLGETPERFMONITORCOUNTERSAMDPROC glGetPerfMonitorCountersAMD; -PFNGLGETPERFMONITORGROUPSTRINGAMDPROC glGetPerfMonitorGroupStringAMD; +PFNGLGETPERFMONITORGROUPSAMDPROC glGetPerfMonitorGroupsAMD; +PFNGLGETPERFMONITORCOUNTERSAMDPROC glGetPerfMonitorCountersAMD; +PFNGLGETPERFMONITORGROUPSTRINGAMDPROC glGetPerfMonitorGroupStringAMD; PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC glGetPerfMonitorCounterStringAMD; -PFNGLGETPERFMONITORCOUNTERINFOAMDPROC glGetPerfMonitorCounterInfoAMD; -PFNGLGENPERFMONITORSAMDPROC glGenPerfMonitorsAMD; -PFNGLDELETEPERFMONITORSAMDPROC glDeletePerfMonitorsAMD; -PFNGLSELECTPERFMONITORCOUNTERSAMDPROC glSelectPerfMonitorCountersAMD; -PFNGLBEGINPERFMONITORAMDPROC glBeginPerfMonitorAMD; -PFNGLENDPERFMONITORAMDPROC glEndPerfMonitorAMD; -PFNGLGETPERFMONITORCOUNTERDATAAMDPROC glGetPerfMonitorCounterDataAMD; +PFNGLGETPERFMONITORCOUNTERINFOAMDPROC glGetPerfMonitorCounterInfoAMD; +PFNGLGENPERFMONITORSAMDPROC glGenPerfMonitorsAMD; +PFNGLDELETEPERFMONITORSAMDPROC glDeletePerfMonitorsAMD; +PFNGLSELECTPERFMONITORCOUNTERSAMDPROC glSelectPerfMonitorCountersAMD; +PFNGLBEGINPERFMONITORAMDPROC glBeginPerfMonitorAMD; +PFNGLENDPERFMONITORAMDPROC glEndPerfMonitorAMD; +PFNGLGETPERFMONITORCOUNTERDATAAMDPROC glGetPerfMonitorCounterDataAMD; #endif /* defined(GL_AMD_performance_monitor) */ #if defined(GL_ANGLE_framebuffer_blit) @@ -217,9 +217,9 @@ PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC glRenderbufferStorageMultisampleANG #endif /* defined(GL_ANGLE_framebuffer_multisample) */ #if defined(GL_ANGLE_instanced_arrays) -PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE; +PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE; PFNGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstancedANGLE; -PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE; +PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE; #endif /* defined(GL_ANGLE_instanced_arrays) */ #if defined(GL_ANGLE_translated_shader_source) @@ -232,17 +232,17 @@ PFNGLCOPYTEXTURELEVELSAPPLEPROC glCopyTextureLevelsAPPLE; #if defined(GL_APPLE_framebuffer_multisample) PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC glRenderbufferStorageMultisampleAPPLE; -PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC glResolveMultisampleFramebufferAPPLE; +PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC glResolveMultisampleFramebufferAPPLE; #endif /* defined(GL_APPLE_framebuffer_multisample) */ #if defined(GL_APPLE_sync) -PFNGLFENCESYNCAPPLEPROC glFenceSyncAPPLE; -PFNGLISSYNCAPPLEPROC glIsSyncAPPLE; -PFNGLDELETESYNCAPPLEPROC glDeleteSyncAPPLE; +PFNGLFENCESYNCAPPLEPROC glFenceSyncAPPLE; +PFNGLISSYNCAPPLEPROC glIsSyncAPPLE; +PFNGLDELETESYNCAPPLEPROC glDeleteSyncAPPLE; PFNGLCLIENTWAITSYNCAPPLEPROC glClientWaitSyncAPPLE; -PFNGLWAITSYNCAPPLEPROC glWaitSyncAPPLE; -PFNGLGETINTEGER64VAPPLEPROC glGetInteger64vAPPLE; -PFNGLGETSYNCIVAPPLEPROC glGetSyncivAPPLE; +PFNGLWAITSYNCAPPLEPROC glWaitSyncAPPLE; +PFNGLGETINTEGER64VAPPLEPROC glGetInteger64vAPPLE; +PFNGLGETSYNCIVAPPLEPROC glGetSyncivAPPLE; #endif /* defined(GL_APPLE_sync) */ #if defined(GL_EXT_EGL_image_storage) @@ -252,16 +252,16 @@ PFNGLEGLIMAGETARGETTEXTURESTORAGEEXTPROC glEGLImageTargetTextureStorageEXT; #endif /* defined(GL_EXT_EGL_image_storage) */ #if defined(GL_EXT_base_instance) -PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC glDrawArraysInstancedBaseInstanceEXT; -PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC glDrawElementsInstancedBaseInstanceEXT; +PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC glDrawArraysInstancedBaseInstanceEXT; +PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC glDrawElementsInstancedBaseInstanceEXT; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC glDrawElementsInstancedBaseVertexBaseInstanceEXT; #endif /* defined(GL_EXT_base_instance) */ #if defined(GL_EXT_blend_func_extended) -PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC glBindFragDataLocationIndexedEXT; -PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocationEXT; +PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC glBindFragDataLocationIndexedEXT; +PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocationEXT; PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC glGetProgramResourceLocationIndexEXT; -PFNGLGETFRAGDATAINDEXEXTPROC glGetFragDataIndexEXT; +PFNGLGETFRAGDATAINDEXEXTPROC glGetFragDataIndexEXT; #endif /* defined(GL_EXT_blend_func_extended) */ #if defined(GL_EXT_buffer_storage) @@ -269,7 +269,7 @@ PFNGLBUFFERSTORAGEEXTPROC glBufferStorageEXT; #endif /* defined(GL_EXT_buffer_storage) */ #if defined(GL_EXT_clear_texture) -PFNGLCLEARTEXIMAGEEXTPROC glClearTexImageEXT; +PFNGLCLEARTEXIMAGEEXTPROC glClearTexImageEXT; PFNGLCLEARTEXSUBIMAGEEXTPROC glClearTexSubImageEXT; #endif /* defined(GL_EXT_clear_texture) */ @@ -282,14 +282,14 @@ PFNGLCOPYIMAGESUBDATAEXTPROC glCopyImageSubDataEXT; #endif /* defined(GL_EXT_copy_image) */ #if defined(GL_EXT_debug_label) -PFNGLLABELOBJECTEXTPROC glLabelObjectEXT; +PFNGLLABELOBJECTEXTPROC glLabelObjectEXT; PFNGLGETOBJECTLABELEXTPROC glGetObjectLabelEXT; #endif /* defined(GL_EXT_debug_label) */ #if defined(GL_EXT_debug_marker) PFNGLINSERTEVENTMARKEREXTPROC glInsertEventMarkerEXT; -PFNGLPUSHGROUPMARKEREXTPROC glPushGroupMarkerEXT; -PFNGLPOPGROUPMARKEREXTPROC glPopGroupMarkerEXT; +PFNGLPUSHGROUPMARKEREXTPROC glPushGroupMarkerEXT; +PFNGLPOPGROUPMARKEREXTPROC glPopGroupMarkerEXT; #endif /* defined(GL_EXT_debug_marker) */ #if defined(GL_EXT_discard_framebuffer) @@ -297,18 +297,18 @@ PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT; #endif /* defined(GL_EXT_discard_framebuffer) */ #if defined(GL_EXT_disjoint_timer_query) -PFNGLGENQUERIESEXTPROC glGenQueriesEXT; -PFNGLDELETEQUERIESEXTPROC glDeleteQueriesEXT; -PFNGLISQUERYEXTPROC glIsQueryEXT; -PFNGLBEGINQUERYEXTPROC glBeginQueryEXT; -PFNGLENDQUERYEXTPROC glEndQueryEXT; -PFNGLQUERYCOUNTEREXTPROC glQueryCounterEXT; -PFNGLGETQUERYIVEXTPROC glGetQueryivEXT; -PFNGLGETQUERYOBJECTIVEXTPROC glGetQueryObjectivEXT; -PFNGLGETQUERYOBJECTUIVEXTPROC glGetQueryObjectuivEXT; -PFNGLGETQUERYOBJECTI64VEXTPROC glGetQueryObjecti64vEXT; +PFNGLGENQUERIESEXTPROC glGenQueriesEXT; +PFNGLDELETEQUERIESEXTPROC glDeleteQueriesEXT; +PFNGLISQUERYEXTPROC glIsQueryEXT; +PFNGLBEGINQUERYEXTPROC glBeginQueryEXT; +PFNGLENDQUERYEXTPROC glEndQueryEXT; +PFNGLQUERYCOUNTEREXTPROC glQueryCounterEXT; +PFNGLGETQUERYIVEXTPROC glGetQueryivEXT; +PFNGLGETQUERYOBJECTIVEXTPROC glGetQueryObjectivEXT; +PFNGLGETQUERYOBJECTUIVEXTPROC glGetQueryObjectuivEXT; +PFNGLGETQUERYOBJECTI64VEXTPROC glGetQueryObjecti64vEXT; PFNGLGETQUERYOBJECTUI64VEXTPROC glGetQueryObjectui64vEXT; -PFNGLGETINTEGER64VEXTPROC glGetInteger64vEXT; +PFNGLGETINTEGER64VEXTPROC glGetInteger64vEXT; #endif /* defined(GL_EXT_disjoint_timer_query) */ #if defined(GL_EXT_draw_buffers) @@ -316,35 +316,35 @@ PFNGLDRAWBUFFERSEXTPROC glDrawBuffersEXT; #endif /* defined(GL_EXT_draw_buffers) */ #if defined(GL_EXT_draw_buffers_indexed) -PFNGLENABLEIEXTPROC glEnableiEXT; -PFNGLDISABLEIEXTPROC glDisableiEXT; -PFNGLBLENDEQUATIONIEXTPROC glBlendEquationiEXT; +PFNGLENABLEIEXTPROC glEnableiEXT; +PFNGLDISABLEIEXTPROC glDisableiEXT; +PFNGLBLENDEQUATIONIEXTPROC glBlendEquationiEXT; PFNGLBLENDEQUATIONSEPARATEIEXTPROC glBlendEquationSeparateiEXT; -PFNGLBLENDFUNCIEXTPROC glBlendFunciEXT; -PFNGLBLENDFUNCSEPARATEIEXTPROC glBlendFuncSeparateiEXT; -PFNGLCOLORMASKIEXTPROC glColorMaskiEXT; -PFNGLISENABLEDIEXTPROC glIsEnablediEXT; +PFNGLBLENDFUNCIEXTPROC glBlendFunciEXT; +PFNGLBLENDFUNCSEPARATEIEXTPROC glBlendFuncSeparateiEXT; +PFNGLCOLORMASKIEXTPROC glColorMaskiEXT; +PFNGLISENABLEDIEXTPROC glIsEnablediEXT; #endif /* defined(GL_EXT_draw_buffers_indexed) */ #if defined(GL_EXT_draw_elements_base_vertex) -PFNGLDRAWELEMENTSBASEVERTEXEXTPROC glDrawElementsBaseVertexEXT; -PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC glDrawRangeElementsBaseVertexEXT; +PFNGLDRAWELEMENTSBASEVERTEXEXTPROC glDrawElementsBaseVertexEXT; +PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC glDrawRangeElementsBaseVertexEXT; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC glDrawElementsInstancedBaseVertexEXT; -PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC glMultiDrawElementsBaseVertexEXT; +PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC glMultiDrawElementsBaseVertexEXT; #endif /* defined(GL_EXT_draw_elements_base_vertex) */ #if defined(GL_EXT_draw_instanced) -PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstancedEXT; +PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstancedEXT; PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstancedEXT; #endif /* defined(GL_EXT_draw_instanced) */ #if defined(GL_EXT_draw_transform_feedback) -PFNGLDRAWTRANSFORMFEEDBACKEXTPROC glDrawTransformFeedbackEXT; +PFNGLDRAWTRANSFORMFEEDBACKEXTPROC glDrawTransformFeedbackEXT; PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDEXTPROC glDrawTransformFeedbackInstancedEXT; #endif /* defined(GL_EXT_draw_transform_feedback) */ #if defined(GL_EXT_external_buffer) -PFNGLBUFFERSTORAGEEXTERNALEXTPROC glBufferStorageExternalEXT; +PFNGLBUFFERSTORAGEEXTERNALEXTPROC glBufferStorageExternalEXT; PFNGLNAMEDBUFFERSTORAGEEXTERNALEXTPROC glNamedBufferStorageExternalEXT; #endif /* defined(GL_EXT_external_buffer) */ @@ -357,29 +357,29 @@ PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisorEXT; #endif /* defined(GL_EXT_instanced_arrays) */ #if defined(GL_EXT_map_buffer_range) -PFNGLMAPBUFFERRANGEEXTPROC glMapBufferRangeEXT; +PFNGLMAPBUFFERRANGEEXTPROC glMapBufferRangeEXT; PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC glFlushMappedBufferRangeEXT; #endif /* defined(GL_EXT_map_buffer_range) */ #if defined(GL_EXT_memory_object) -PFNGLGETUNSIGNEDBYTEVEXTPROC glGetUnsignedBytevEXT; -PFNGLGETUNSIGNEDBYTEI_VEXTPROC glGetUnsignedBytei_vEXT; -PFNGLDELETEMEMORYOBJECTSEXTPROC glDeleteMemoryObjectsEXT; -PFNGLISMEMORYOBJECTEXTPROC glIsMemoryObjectEXT; -PFNGLCREATEMEMORYOBJECTSEXTPROC glCreateMemoryObjectsEXT; -PFNGLMEMORYOBJECTPARAMETERIVEXTPROC glMemoryObjectParameterivEXT; +PFNGLGETUNSIGNEDBYTEVEXTPROC glGetUnsignedBytevEXT; +PFNGLGETUNSIGNEDBYTEI_VEXTPROC glGetUnsignedBytei_vEXT; +PFNGLDELETEMEMORYOBJECTSEXTPROC glDeleteMemoryObjectsEXT; +PFNGLISMEMORYOBJECTEXTPROC glIsMemoryObjectEXT; +PFNGLCREATEMEMORYOBJECTSEXTPROC glCreateMemoryObjectsEXT; +PFNGLMEMORYOBJECTPARAMETERIVEXTPROC glMemoryObjectParameterivEXT; PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC glGetMemoryObjectParameterivEXT; -PFNGLTEXSTORAGEMEM2DEXTPROC glTexStorageMem2DEXT; +PFNGLTEXSTORAGEMEM2DEXTPROC glTexStorageMem2DEXT; PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC glTexStorageMem2DMultisampleEXT; -PFNGLTEXSTORAGEMEM3DEXTPROC glTexStorageMem3DEXT; +PFNGLTEXSTORAGEMEM3DEXTPROC glTexStorageMem3DEXT; PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC glTexStorageMem3DMultisampleEXT; -PFNGLBUFFERSTORAGEMEMEXTPROC glBufferStorageMemEXT; +PFNGLBUFFERSTORAGEMEMEXTPROC glBufferStorageMemEXT; -PFNGLTEXTURESTORAGEMEM2DEXTPROC glTextureStorageMem2DEXT; +PFNGLTEXTURESTORAGEMEM2DEXTPROC glTextureStorageMem2DEXT; PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC glTextureStorageMem2DMultisampleEXT; -PFNGLTEXTURESTORAGEMEM3DEXTPROC glTextureStorageMem3DEXT; +PFNGLTEXTURESTORAGEMEM3DEXTPROC glTextureStorageMem3DEXT; PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC glTextureStorageMem3DMultisampleEXT; -PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC glNamedBufferStorageMemEXT; +PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC glNamedBufferStorageMemEXT; #endif /* defined(GL_EXT_memory_object) */ #if defined(GL_EXT_memory_object_fd) @@ -388,28 +388,28 @@ PFNGLIMPORTMEMORYFDEXTPROC glImportMemoryFdEXT; #if defined(GL_EXT_memory_object_win32) PFNGLIMPORTMEMORYWIN32HANDLEEXTPROC glImportMemoryWin32HandleEXT; -PFNGLIMPORTMEMORYWIN32NAMEEXTPROC glImportMemoryWin32NameEXT; +PFNGLIMPORTMEMORYWIN32NAMEEXTPROC glImportMemoryWin32NameEXT; #endif /* defined(GL_EXT_memory_object_win32) */ #if defined(GL_EXT_multi_draw_arrays) -PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArraysEXT; +PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArraysEXT; PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElementsEXT; #endif /* defined(GL_EXT_multi_draw_arrays) */ #if defined(GL_EXT_multi_draw_indirect) -PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC glMultiDrawArraysIndirectEXT; +PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC glMultiDrawArraysIndirectEXT; PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC glMultiDrawElementsIndirectEXT; #endif /* defined(GL_EXT_multi_draw_indirect) */ #if defined(GL_EXT_multisampled_render_to_texture) -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT; PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC glFramebufferTexture2DMultisampleEXT; #endif /* defined(GL_EXT_multisampled_render_to_texture) */ #if defined(GL_EXT_multiview_draw_buffers) -PFNGLREADBUFFERINDEXEDEXTPROC glReadBufferIndexedEXT; +PFNGLREADBUFFERINDEXEDEXTPROC glReadBufferIndexedEXT; PFNGLDRAWBUFFERSINDEXEDEXTPROC glDrawBuffersIndexedEXT; -PFNGLGETINTEGERI_VEXTPROC glGetIntegeri_vEXT; +PFNGLGETINTEGERI_VEXTPROC glGetIntegeri_vEXT; #endif /* defined(GL_EXT_multiview_draw_buffers) */ #if defined(GL_EXT_polygon_offset_clamp) @@ -426,19 +426,19 @@ PFNGLRASTERSAMPLESEXTPROC glRasterSamplesEXT; #if defined(GL_EXT_robustness) PFNGLGETGRAPHICSRESETSTATUSEXTPROC glGetGraphicsResetStatusEXT; -PFNGLREADNPIXELSEXTPROC glReadnPixelsEXT; -PFNGLGETNUNIFORMFVEXTPROC glGetnUniformfvEXT; -PFNGLGETNUNIFORMIVEXTPROC glGetnUniformivEXT; +PFNGLREADNPIXELSEXTPROC glReadnPixelsEXT; +PFNGLGETNUNIFORMFVEXTPROC glGetnUniformfvEXT; +PFNGLGETNUNIFORMIVEXTPROC glGetnUniformivEXT; #endif /* defined(GL_EXT_robustness) */ #if defined(GL_EXT_semaphore) -PFNGLGENSEMAPHORESEXTPROC glGenSemaphoresEXT; -PFNGLDELETESEMAPHORESEXTPROC glDeleteSemaphoresEXT; -PFNGLISSEMAPHOREEXTPROC glIsSemaphoreEXT; -PFNGLSEMAPHOREPARAMETERUI64VEXTPROC glSemaphoreParameterui64vEXT; +PFNGLGENSEMAPHORESEXTPROC glGenSemaphoresEXT; +PFNGLDELETESEMAPHORESEXTPROC glDeleteSemaphoresEXT; +PFNGLISSEMAPHOREEXTPROC glIsSemaphoreEXT; +PFNGLSEMAPHOREPARAMETERUI64VEXTPROC glSemaphoreParameterui64vEXT; PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC glGetSemaphoreParameterui64vEXT; -PFNGLWAITSEMAPHOREEXTPROC glWaitSemaphoreEXT; -PFNGLSIGNALSEMAPHOREEXTPROC glSignalSemaphoreEXT; +PFNGLWAITSEMAPHOREEXTPROC glWaitSemaphoreEXT; +PFNGLSIGNALSEMAPHOREEXTPROC glSignalSemaphoreEXT; #endif /* defined(GL_EXT_semaphore) */ #if defined(GL_EXT_semaphore_fd) @@ -447,49 +447,49 @@ PFNGLIMPORTSEMAPHOREFDEXTPROC glImportSemaphoreFdEXT; #if defined(GL_EXT_semaphore_win32) PFNGLIMPORTSEMAPHOREWIN32HANDLEEXTPROC glImportSemaphoreWin32HandleEXT; -PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC glImportSemaphoreWin32NameEXT; +PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC glImportSemaphoreWin32NameEXT; #endif /* defined(GL_EXT_semaphore_win32) */ #if defined(GL_EXT_separate_shader_objects) -PFNGLACTIVESHADERPROGRAMEXTPROC glActiveShaderProgramEXT; -PFNGLBINDPROGRAMPIPELINEEXTPROC glBindProgramPipelineEXT; -PFNGLCREATESHADERPROGRAMVEXTPROC glCreateShaderProgramvEXT; -PFNGLDELETEPROGRAMPIPELINESEXTPROC glDeleteProgramPipelinesEXT; -PFNGLGENPROGRAMPIPELINESEXTPROC glGenProgramPipelinesEXT; +PFNGLACTIVESHADERPROGRAMEXTPROC glActiveShaderProgramEXT; +PFNGLBINDPROGRAMPIPELINEEXTPROC glBindProgramPipelineEXT; +PFNGLCREATESHADERPROGRAMVEXTPROC glCreateShaderProgramvEXT; +PFNGLDELETEPROGRAMPIPELINESEXTPROC glDeleteProgramPipelinesEXT; +PFNGLGENPROGRAMPIPELINESEXTPROC glGenProgramPipelinesEXT; PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC glGetProgramPipelineInfoLogEXT; -PFNGLGETPROGRAMPIPELINEIVEXTPROC glGetProgramPipelineivEXT; -PFNGLISPROGRAMPIPELINEEXTPROC glIsProgramPipelineEXT; -PFNGLPROGRAMPARAMETERIEXTPROC glProgramParameteriEXT; -PFNGLPROGRAMUNIFORM1FEXTPROC glProgramUniform1fEXT; -PFNGLPROGRAMUNIFORM1FVEXTPROC glProgramUniform1fvEXT; -PFNGLPROGRAMUNIFORM1IEXTPROC glProgramUniform1iEXT; -PFNGLPROGRAMUNIFORM1IVEXTPROC glProgramUniform1ivEXT; -PFNGLPROGRAMUNIFORM2FEXTPROC glProgramUniform2fEXT; -PFNGLPROGRAMUNIFORM2FVEXTPROC glProgramUniform2fvEXT; -PFNGLPROGRAMUNIFORM2IEXTPROC glProgramUniform2iEXT; -PFNGLPROGRAMUNIFORM2IVEXTPROC glProgramUniform2ivEXT; -PFNGLPROGRAMUNIFORM3FEXTPROC glProgramUniform3fEXT; -PFNGLPROGRAMUNIFORM3FVEXTPROC glProgramUniform3fvEXT; -PFNGLPROGRAMUNIFORM3IEXTPROC glProgramUniform3iEXT; -PFNGLPROGRAMUNIFORM3IVEXTPROC glProgramUniform3ivEXT; -PFNGLPROGRAMUNIFORM4FEXTPROC glProgramUniform4fEXT; -PFNGLPROGRAMUNIFORM4FVEXTPROC glProgramUniform4fvEXT; -PFNGLPROGRAMUNIFORM4IEXTPROC glProgramUniform4iEXT; -PFNGLPROGRAMUNIFORM4IVEXTPROC glProgramUniform4ivEXT; -PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC glProgramUniformMatrix2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC glProgramUniformMatrix3fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC glProgramUniformMatrix4fvEXT; -PFNGLUSEPROGRAMSTAGESEXTPROC glUseProgramStagesEXT; -PFNGLVALIDATEPROGRAMPIPELINEEXTPROC glValidateProgramPipelineEXT; +PFNGLGETPROGRAMPIPELINEIVEXTPROC glGetProgramPipelineivEXT; +PFNGLISPROGRAMPIPELINEEXTPROC glIsProgramPipelineEXT; +PFNGLPROGRAMPARAMETERIEXTPROC glProgramParameteriEXT; +PFNGLPROGRAMUNIFORM1FEXTPROC glProgramUniform1fEXT; +PFNGLPROGRAMUNIFORM1FVEXTPROC glProgramUniform1fvEXT; +PFNGLPROGRAMUNIFORM1IEXTPROC glProgramUniform1iEXT; +PFNGLPROGRAMUNIFORM1IVEXTPROC glProgramUniform1ivEXT; +PFNGLPROGRAMUNIFORM2FEXTPROC glProgramUniform2fEXT; +PFNGLPROGRAMUNIFORM2FVEXTPROC glProgramUniform2fvEXT; +PFNGLPROGRAMUNIFORM2IEXTPROC glProgramUniform2iEXT; +PFNGLPROGRAMUNIFORM2IVEXTPROC glProgramUniform2ivEXT; +PFNGLPROGRAMUNIFORM3FEXTPROC glProgramUniform3fEXT; +PFNGLPROGRAMUNIFORM3FVEXTPROC glProgramUniform3fvEXT; +PFNGLPROGRAMUNIFORM3IEXTPROC glProgramUniform3iEXT; +PFNGLPROGRAMUNIFORM3IVEXTPROC glProgramUniform3ivEXT; +PFNGLPROGRAMUNIFORM4FEXTPROC glProgramUniform4fEXT; +PFNGLPROGRAMUNIFORM4FVEXTPROC glProgramUniform4fvEXT; +PFNGLPROGRAMUNIFORM4IEXTPROC glProgramUniform4iEXT; +PFNGLPROGRAMUNIFORM4IVEXTPROC glProgramUniform4ivEXT; +PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC glProgramUniformMatrix2fvEXT; +PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC glProgramUniformMatrix3fvEXT; +PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC glProgramUniformMatrix4fvEXT; +PFNGLUSEPROGRAMSTAGESEXTPROC glUseProgramStagesEXT; +PFNGLVALIDATEPROGRAMPIPELINEEXTPROC glValidateProgramPipelineEXT; -PFNGLPROGRAMUNIFORM1UIEXTPROC glProgramUniform1uiEXT; -PFNGLPROGRAMUNIFORM2UIEXTPROC glProgramUniform2uiEXT; -PFNGLPROGRAMUNIFORM3UIEXTPROC glProgramUniform3uiEXT; -PFNGLPROGRAMUNIFORM4UIEXTPROC glProgramUniform4uiEXT; -PFNGLPROGRAMUNIFORM1UIVEXTPROC glProgramUniform1uivEXT; -PFNGLPROGRAMUNIFORM2UIVEXTPROC glProgramUniform2uivEXT; -PFNGLPROGRAMUNIFORM3UIVEXTPROC glProgramUniform3uivEXT; -PFNGLPROGRAMUNIFORM4UIVEXTPROC glProgramUniform4uivEXT; +PFNGLPROGRAMUNIFORM1UIEXTPROC glProgramUniform1uiEXT; +PFNGLPROGRAMUNIFORM2UIEXTPROC glProgramUniform2uiEXT; +PFNGLPROGRAMUNIFORM3UIEXTPROC glProgramUniform3uiEXT; +PFNGLPROGRAMUNIFORM4UIEXTPROC glProgramUniform4uiEXT; +PFNGLPROGRAMUNIFORM1UIVEXTPROC glProgramUniform1uivEXT; +PFNGLPROGRAMUNIFORM2UIVEXTPROC glProgramUniform2uivEXT; +PFNGLPROGRAMUNIFORM3UIVEXTPROC glProgramUniform3uivEXT; +PFNGLPROGRAMUNIFORM4UIVEXTPROC glProgramUniform4uivEXT; PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC glProgramUniformMatrix2x3fvEXT; PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC glProgramUniformMatrix3x2fvEXT; PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC glProgramUniformMatrix2x4fvEXT; @@ -503,9 +503,9 @@ PFNGLFRAMEBUFFERFETCHBARRIEREXTPROC glFramebufferFetchBarrierEXT; #endif /* defined(GL_EXT_shader_framebuffer_fetch_non_coherent) */ #if defined(GL_EXT_shader_pixel_local_storage2) -PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glFramebufferPixelLocalStorageSizeEXT; +PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glFramebufferPixelLocalStorageSizeEXT; PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glGetFramebufferPixelLocalStorageSizeEXT; -PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC glClearPixelLocalStorageuiEXT; +PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC glClearPixelLocalStorageuiEXT; #endif /* defined(GL_EXT_shader_pixel_local_storage2) */ #if defined(GL_EXT_sparse_texture) @@ -517,18 +517,18 @@ PFNGLPATCHPARAMETERIEXTPROC glPatchParameteriEXT; #endif /* defined(GL_EXT_tessellation_shader) */ #if defined(GL_EXT_texture_border_clamp) -PFNGLTEXPARAMETERIIVEXTPROC glTexParameterIivEXT; -PFNGLTEXPARAMETERIUIVEXTPROC glTexParameterIuivEXT; -PFNGLGETTEXPARAMETERIIVEXTPROC glGetTexParameterIivEXT; -PFNGLGETTEXPARAMETERIUIVEXTPROC glGetTexParameterIuivEXT; -PFNGLSAMPLERPARAMETERIIVEXTPROC glSamplerParameterIivEXT; -PFNGLSAMPLERPARAMETERIUIVEXTPROC glSamplerParameterIuivEXT; -PFNGLGETSAMPLERPARAMETERIIVEXTPROC glGetSamplerParameterIivEXT; +PFNGLTEXPARAMETERIIVEXTPROC glTexParameterIivEXT; +PFNGLTEXPARAMETERIUIVEXTPROC glTexParameterIuivEXT; +PFNGLGETTEXPARAMETERIIVEXTPROC glGetTexParameterIivEXT; +PFNGLGETTEXPARAMETERIUIVEXTPROC glGetTexParameterIuivEXT; +PFNGLSAMPLERPARAMETERIIVEXTPROC glSamplerParameterIivEXT; +PFNGLSAMPLERPARAMETERIUIVEXTPROC glSamplerParameterIuivEXT; +PFNGLGETSAMPLERPARAMETERIIVEXTPROC glGetSamplerParameterIivEXT; PFNGLGETSAMPLERPARAMETERIUIVEXTPROC glGetSamplerParameterIuivEXT; #endif /* defined(GL_EXT_texture_border_clamp) */ #if defined(GL_EXT_texture_buffer) -PFNGLTEXBUFFEREXTPROC glTexBufferEXT; +PFNGLTEXBUFFEREXTPROC glTexBufferEXT; PFNGLTEXBUFFERRANGEEXTPROC glTexBufferRangeEXT; #endif /* defined(GL_EXT_texture_buffer) */ @@ -547,8 +547,8 @@ PFNGLTEXTUREVIEWEXTPROC glTextureViewEXT; #endif /* defined(GL_EXT_texture_view) */ #if defined(GL_NV_timeline_semaphore) -PFNGLCREATESEMAPHORESNVPROC glCreateSemaphoresNV; -PFNGLSEMAPHOREPARAMETERIVNVPROC glSemaphoreParameterivNV; +PFNGLCREATESEMAPHORESNVPROC glCreateSemaphoresNV; +PFNGLSEMAPHOREPARAMETERIVNVPROC glSemaphoreParameterivNV; PFNGLGETSEMAPHOREPARAMETERIVNVPROC glGetSemaphoreParameterivNV; #endif /* defined(GL_NV_timeline_semaphore) */ @@ -562,21 +562,21 @@ PFNGLWINDOWRECTANGLESEXTPROC glWindowRectanglesEXT; #endif /* defined(GL_EXT_window_rectangles) */ #if defined(GL_IMG_bindless_texture) -PFNGLGETTEXTUREHANDLEIMGPROC glGetTextureHandleIMG; -PFNGLGETTEXTURESAMPLERHANDLEIMGPROC glGetTextureSamplerHandleIMG; -PFNGLUNIFORMHANDLEUI64IMGPROC glUniformHandleui64IMG; -PFNGLUNIFORMHANDLEUI64VIMGPROC glUniformHandleui64vIMG; -PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC glProgramUniformHandleui64IMG; +PFNGLGETTEXTUREHANDLEIMGPROC glGetTextureHandleIMG; +PFNGLGETTEXTURESAMPLERHANDLEIMGPROC glGetTextureSamplerHandleIMG; +PFNGLUNIFORMHANDLEUI64IMGPROC glUniformHandleui64IMG; +PFNGLUNIFORMHANDLEUI64VIMGPROC glUniformHandleui64vIMG; +PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC glProgramUniformHandleui64IMG; PFNGLPROGRAMUNIFORMHANDLEUI64VIMGPROC glProgramUniformHandleui64vIMG; #endif /* defined(GL_IMG_bindless_texture) */ #if defined(GL_IMG_framebuffer_downsample) -PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC glFramebufferTexture2DDownsampleIMG; +PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC glFramebufferTexture2DDownsampleIMG; PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC glFramebufferTextureLayerDownsampleIMG; #endif /* defined(GL_IMG_framebuffer_downsample) */ #if defined(GL_IMG_multisampled_render_to_texture) -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC glRenderbufferStorageMultisampleIMG; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC glRenderbufferStorageMultisampleIMG; PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC glFramebufferTexture2DMultisampleIMG; #endif /* defined(GL_IMG_multisampled_render_to_texture) */ @@ -585,16 +585,16 @@ PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC glApplyFramebufferAttachmentCMAAINT #endif /* defined(GL_INTEL_framebuffer_CMAA) */ #if defined(GL_INTEL_performance_query) -PFNGLBEGINPERFQUERYINTELPROC glBeginPerfQueryINTEL; -PFNGLCREATEPERFQUERYINTELPROC glCreatePerfQueryINTEL; -PFNGLDELETEPERFQUERYINTELPROC glDeletePerfQueryINTEL; -PFNGLENDPERFQUERYINTELPROC glEndPerfQueryINTEL; -PFNGLGETFIRSTPERFQUERYIDINTELPROC glGetFirstPerfQueryIdINTEL; -PFNGLGETNEXTPERFQUERYIDINTELPROC glGetNextPerfQueryIdINTEL; -PFNGLGETPERFCOUNTERINFOINTELPROC glGetPerfCounterInfoINTEL; -PFNGLGETPERFQUERYDATAINTELPROC glGetPerfQueryDataINTEL; +PFNGLBEGINPERFQUERYINTELPROC glBeginPerfQueryINTEL; +PFNGLCREATEPERFQUERYINTELPROC glCreatePerfQueryINTEL; +PFNGLDELETEPERFQUERYINTELPROC glDeletePerfQueryINTEL; +PFNGLENDPERFQUERYINTELPROC glEndPerfQueryINTEL; +PFNGLGETFIRSTPERFQUERYIDINTELPROC glGetFirstPerfQueryIdINTEL; +PFNGLGETNEXTPERFQUERYIDINTELPROC glGetNextPerfQueryIdINTEL; +PFNGLGETPERFCOUNTERINFOINTELPROC glGetPerfCounterInfoINTEL; +PFNGLGETPERFQUERYDATAINTELPROC glGetPerfQueryDataINTEL; PFNGLGETPERFQUERYIDBYNAMEINTELPROC glGetPerfQueryIdByNameINTEL; -PFNGLGETPERFQUERYINFOINTELPROC glGetPerfQueryInfoINTEL; +PFNGLGETPERFQUERYINFOINTELPROC glGetPerfQueryInfoINTEL; #endif /* defined(GL_INTEL_performance_query) */ #if defined(GL_KHR_blend_equation_advanced) @@ -602,25 +602,25 @@ PFNGLBLENDBARRIERKHRPROC glBlendBarrierKHR; #endif /* defined(GL_KHR_blend_equation_advanced) */ #if defined(GL_KHR_debug) -PFNGLDEBUGMESSAGECONTROLKHRPROC glDebugMessageControlKHR; -PFNGLDEBUGMESSAGEINSERTKHRPROC glDebugMessageInsertKHR; +PFNGLDEBUGMESSAGECONTROLKHRPROC glDebugMessageControlKHR; +PFNGLDEBUGMESSAGEINSERTKHRPROC glDebugMessageInsertKHR; PFNGLDEBUGMESSAGECALLBACKKHRPROC glDebugMessageCallbackKHR; -PFNGLGETDEBUGMESSAGELOGKHRPROC glGetDebugMessageLogKHR; -PFNGLPUSHDEBUGGROUPKHRPROC glPushDebugGroupKHR; -PFNGLPOPDEBUGGROUPKHRPROC glPopDebugGroupKHR; -PFNGLOBJECTLABELKHRPROC glObjectLabelKHR; -PFNGLGETOBJECTLABELKHRPROC glGetObjectLabelKHR; -PFNGLOBJECTPTRLABELKHRPROC glObjectPtrLabelKHR; -PFNGLGETOBJECTPTRLABELKHRPROC glGetObjectPtrLabelKHR; -PFNGLGETPOINTERVKHRPROC glGetPointervKHR; +PFNGLGETDEBUGMESSAGELOGKHRPROC glGetDebugMessageLogKHR; +PFNGLPUSHDEBUGGROUPKHRPROC glPushDebugGroupKHR; +PFNGLPOPDEBUGGROUPKHRPROC glPopDebugGroupKHR; +PFNGLOBJECTLABELKHRPROC glObjectLabelKHR; +PFNGLGETOBJECTLABELKHRPROC glGetObjectLabelKHR; +PFNGLOBJECTPTRLABELKHRPROC glObjectPtrLabelKHR; +PFNGLGETOBJECTPTRLABELKHRPROC glGetObjectPtrLabelKHR; +PFNGLGETPOINTERVKHRPROC glGetPointervKHR; #endif /* defined(GL_KHR_debug) */ #if defined(GL_KHR_robustness) PFNGLGETGRAPHICSRESETSTATUSKHRPROC glGetGraphicsResetStatusKHR; -PFNGLREADNPIXELSKHRPROC glReadnPixelsKHR; -PFNGLGETNUNIFORMFVKHRPROC glGetnUniformfvKHR; -PFNGLGETNUNIFORMIVKHRPROC glGetnUniformivKHR; -PFNGLGETNUNIFORMUIVKHRPROC glGetnUniformuivKHR; +PFNGLREADNPIXELSKHRPROC glReadnPixelsKHR; +PFNGLGETNUNIFORMFVKHRPROC glGetnUniformfvKHR; +PFNGLGETNUNIFORMIVKHRPROC glGetnUniformivKHR; +PFNGLGETNUNIFORMUIVKHRPROC glGetnUniformuivKHR; #endif /* defined(GL_KHR_robustness) */ #if defined(GL_KHR_parallel_shader_compile) @@ -628,29 +628,29 @@ PFNGLMAXSHADERCOMPILERTHREADSKHRPROC glMaxShaderCompilerThreadsKHR; #endif /* defined(GL_KHR_parallel_shader_compile) */ #if defined(GL_MESA_framebuffer_flip_y) -PFNGLFRAMEBUFFERPARAMETERIMESAPROC glFramebufferParameteriMESA; +PFNGLFRAMEBUFFERPARAMETERIMESAPROC glFramebufferParameteriMESA; PFNGLGETFRAMEBUFFERPARAMETERIVMESAPROC glGetFramebufferParameterivMESA; #endif /* defined(GL_MESA_framebuffer_flip_y) */ #if defined(GL_NV_bindless_texture) -PFNGLGETTEXTUREHANDLENVPROC glGetTextureHandleNV; -PFNGLGETTEXTURESAMPLERHANDLENVPROC glGetTextureSamplerHandleNV; -PFNGLMAKETEXTUREHANDLERESIDENTNVPROC glMakeTextureHandleResidentNV; +PFNGLGETTEXTUREHANDLENVPROC glGetTextureHandleNV; +PFNGLGETTEXTURESAMPLERHANDLENVPROC glGetTextureSamplerHandleNV; +PFNGLMAKETEXTUREHANDLERESIDENTNVPROC glMakeTextureHandleResidentNV; PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC glMakeTextureHandleNonResidentNV; -PFNGLGETIMAGEHANDLENVPROC glGetImageHandleNV; -PFNGLMAKEIMAGEHANDLERESIDENTNVPROC glMakeImageHandleResidentNV; -PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC glMakeImageHandleNonResidentNV; -PFNGLUNIFORMHANDLEUI64NVPROC glUniformHandleui64NV; -PFNGLUNIFORMHANDLEUI64VNVPROC glUniformHandleui64vNV; -PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC glProgramUniformHandleui64NV; -PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC glProgramUniformHandleui64vNV; -PFNGLISTEXTUREHANDLERESIDENTNVPROC glIsTextureHandleResidentNV; -PFNGLISIMAGEHANDLERESIDENTNVPROC glIsImageHandleResidentNV; +PFNGLGETIMAGEHANDLENVPROC glGetImageHandleNV; +PFNGLMAKEIMAGEHANDLERESIDENTNVPROC glMakeImageHandleResidentNV; +PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC glMakeImageHandleNonResidentNV; +PFNGLUNIFORMHANDLEUI64NVPROC glUniformHandleui64NV; +PFNGLUNIFORMHANDLEUI64VNVPROC glUniformHandleui64vNV; +PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC glProgramUniformHandleui64NV; +PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC glProgramUniformHandleui64vNV; +PFNGLISTEXTUREHANDLERESIDENTNVPROC glIsTextureHandleResidentNV; +PFNGLISIMAGEHANDLERESIDENTNVPROC glIsImageHandleResidentNV; #endif /* defined(GL_NV_bindless_texture) */ #if defined(GL_NV_blend_equation_advanced) PFNGLBLENDPARAMETERINVPROC glBlendParameteriNV; -PFNGLBLENDBARRIERNVPROC glBlendBarrierNV; +PFNGLBLENDBARRIERNVPROC glBlendBarrierNV; #endif /* defined(GL_NV_blend_equation_advanced) */ #if defined(GL_NV_clip_space_w_scaling) @@ -659,7 +659,7 @@ PFNGLVIEWPORTPOSITIONWSCALENVPROC glViewportPositionWScaleNV; #if defined(GL_NV_conditional_render) PFNGLBEGINCONDITIONALRENDERNVPROC glBeginConditionalRenderNV; -PFNGLENDCONDITIONALRENDERNVPROC glEndConditionalRenderNV; +PFNGLENDCONDITIONALRENDERNVPROC glEndConditionalRenderNV; #endif /* defined(GL_NV_conditional_render) */ #if defined(GL_NV_conservative_raster) @@ -675,7 +675,7 @@ PFNGLCOPYBUFFERSUBDATANVPROC glCopyBufferSubDataNV; #endif /* defined(GL_NV_copy_buffer) */ #if defined(GL_NV_coverage_sample) -PFNGLCOVERAGEMASKNVPROC glCoverageMaskNV; +PFNGLCOVERAGEMASKNVPROC glCoverageMaskNV; PFNGLCOVERAGEOPERATIONNVPROC glCoverageOperationNV; #endif /* defined(GL_NV_coverage_sample) */ @@ -684,26 +684,26 @@ PFNGLDRAWBUFFERSNVPROC glDrawBuffersNV; #endif /* defined(GL_NV_draw_buffers) */ #if defined(GL_NV_draw_instanced) -PFNGLDRAWARRAYSINSTANCEDNVPROC glDrawArraysInstancedNV; +PFNGLDRAWARRAYSINSTANCEDNVPROC glDrawArraysInstancedNV; PFNGLDRAWELEMENTSINSTANCEDNVPROC glDrawElementsInstancedNV; #endif /* defined(GL_NV_draw_instanced) */ #if defined(GL_NV_draw_vulkan_image) -PFNGLDRAWVKIMAGENVPROC glDrawVkImageNV; -PFNGLGETVKPROCADDRNVPROC glGetVkProcAddrNV; -PFNGLWAITVKSEMAPHORENVPROC glWaitVkSemaphoreNV; +PFNGLDRAWVKIMAGENVPROC glDrawVkImageNV; +PFNGLGETVKPROCADDRNVPROC glGetVkProcAddrNV; +PFNGLWAITVKSEMAPHORENVPROC glWaitVkSemaphoreNV; PFNGLSIGNALVKSEMAPHORENVPROC glSignalVkSemaphoreNV; -PFNGLSIGNALVKFENCENVPROC glSignalVkFenceNV; +PFNGLSIGNALVKFENCENVPROC glSignalVkFenceNV; #endif /* defined(GL_NV_draw_vulkan_image) */ #if defined(GL_NV_fence) PFNGLDELETEFENCESNVPROC glDeleteFencesNV; -PFNGLGENFENCESNVPROC glGenFencesNV; -PFNGLISFENCENVPROC glIsFenceNV; -PFNGLTESTFENCENVPROC glTestFenceNV; -PFNGLGETFENCEIVNVPROC glGetFenceivNV; -PFNGLFINISHFENCENVPROC glFinishFenceNV; -PFNGLSETFENCENVPROC glSetFenceNV; +PFNGLGENFENCESNVPROC glGenFencesNV; +PFNGLISFENCENVPROC glIsFenceNV; +PFNGLTESTFENCENVPROC glTestFenceNV; +PFNGLGETFENCEIVNVPROC glGetFenceivNV; +PFNGLFINISHFENCENVPROC glFinishFenceNV; +PFNGLSETFENCENVPROC glSetFenceNV; #endif /* defined(GL_NV_fence) */ #if defined(GL_NV_fragment_coverage_to_color) @@ -715,9 +715,9 @@ PFNGLBLITFRAMEBUFFERNVPROC glBlitFramebufferNV; #endif /* defined(GL_NV_framebuffer_blit) */ #if defined(GL_NV_framebuffer_mixed_samples) -PFNGLCOVERAGEMODULATIONTABLENVPROC glCoverageModulationTableNV; +PFNGLCOVERAGEMODULATIONTABLENVPROC glCoverageModulationTableNV; PFNGLGETCOVERAGEMODULATIONTABLENVPROC glGetCoverageModulationTableNV; -PFNGLCOVERAGEMODULATIONNVPROC glCoverageModulationNV; +PFNGLCOVERAGEMODULATIONNVPROC glCoverageModulationNV; #endif /* defined(GL_NV_framebuffer_mixed_samples) */ #if defined(GL_NV_framebuffer_multisample) @@ -725,36 +725,36 @@ PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC glRenderbufferStorageMultisampleNV; #endif /* defined(GL_NV_framebuffer_multisample) */ #if defined(GL_NV_gpu_shader5) -PFNGLUNIFORM1I64NVPROC glUniform1i64NV; -PFNGLUNIFORM2I64NVPROC glUniform2i64NV; -PFNGLUNIFORM3I64NVPROC glUniform3i64NV; -PFNGLUNIFORM4I64NVPROC glUniform4i64NV; -PFNGLUNIFORM1I64VNVPROC glUniform1i64vNV; -PFNGLUNIFORM2I64VNVPROC glUniform2i64vNV; -PFNGLUNIFORM3I64VNVPROC glUniform3i64vNV; -PFNGLUNIFORM4I64VNVPROC glUniform4i64vNV; -PFNGLUNIFORM1UI64NVPROC glUniform1ui64NV; -PFNGLUNIFORM2UI64NVPROC glUniform2ui64NV; -PFNGLUNIFORM3UI64NVPROC glUniform3ui64NV; -PFNGLUNIFORM4UI64NVPROC glUniform4ui64NV; -PFNGLUNIFORM1UI64VNVPROC glUniform1ui64vNV; -PFNGLUNIFORM2UI64VNVPROC glUniform2ui64vNV; -PFNGLUNIFORM3UI64VNVPROC glUniform3ui64vNV; -PFNGLUNIFORM4UI64VNVPROC glUniform4ui64vNV; +PFNGLUNIFORM1I64NVPROC glUniform1i64NV; +PFNGLUNIFORM2I64NVPROC glUniform2i64NV; +PFNGLUNIFORM3I64NVPROC glUniform3i64NV; +PFNGLUNIFORM4I64NVPROC glUniform4i64NV; +PFNGLUNIFORM1I64VNVPROC glUniform1i64vNV; +PFNGLUNIFORM2I64VNVPROC glUniform2i64vNV; +PFNGLUNIFORM3I64VNVPROC glUniform3i64vNV; +PFNGLUNIFORM4I64VNVPROC glUniform4i64vNV; +PFNGLUNIFORM1UI64NVPROC glUniform1ui64NV; +PFNGLUNIFORM2UI64NVPROC glUniform2ui64NV; +PFNGLUNIFORM3UI64NVPROC glUniform3ui64NV; +PFNGLUNIFORM4UI64NVPROC glUniform4ui64NV; +PFNGLUNIFORM1UI64VNVPROC glUniform1ui64vNV; +PFNGLUNIFORM2UI64VNVPROC glUniform2ui64vNV; +PFNGLUNIFORM3UI64VNVPROC glUniform3ui64vNV; +PFNGLUNIFORM4UI64VNVPROC glUniform4ui64vNV; PFNGLGETUNIFORMI64VNVPROC glGetUniformi64vNV; -PFNGLPROGRAMUNIFORM1I64NVPROC glProgramUniform1i64NV; -PFNGLPROGRAMUNIFORM2I64NVPROC glProgramUniform2i64NV; -PFNGLPROGRAMUNIFORM3I64NVPROC glProgramUniform3i64NV; -PFNGLPROGRAMUNIFORM4I64NVPROC glProgramUniform4i64NV; -PFNGLPROGRAMUNIFORM1I64VNVPROC glProgramUniform1i64vNV; -PFNGLPROGRAMUNIFORM2I64VNVPROC glProgramUniform2i64vNV; -PFNGLPROGRAMUNIFORM3I64VNVPROC glProgramUniform3i64vNV; -PFNGLPROGRAMUNIFORM4I64VNVPROC glProgramUniform4i64vNV; -PFNGLPROGRAMUNIFORM1UI64NVPROC glProgramUniform1ui64NV; -PFNGLPROGRAMUNIFORM2UI64NVPROC glProgramUniform2ui64NV; -PFNGLPROGRAMUNIFORM3UI64NVPROC glProgramUniform3ui64NV; -PFNGLPROGRAMUNIFORM4UI64NVPROC glProgramUniform4ui64NV; +PFNGLPROGRAMUNIFORM1I64NVPROC glProgramUniform1i64NV; +PFNGLPROGRAMUNIFORM2I64NVPROC glProgramUniform2i64NV; +PFNGLPROGRAMUNIFORM3I64NVPROC glProgramUniform3i64NV; +PFNGLPROGRAMUNIFORM4I64NVPROC glProgramUniform4i64NV; +PFNGLPROGRAMUNIFORM1I64VNVPROC glProgramUniform1i64vNV; +PFNGLPROGRAMUNIFORM2I64VNVPROC glProgramUniform2i64vNV; +PFNGLPROGRAMUNIFORM3I64VNVPROC glProgramUniform3i64vNV; +PFNGLPROGRAMUNIFORM4I64VNVPROC glProgramUniform4i64vNV; +PFNGLPROGRAMUNIFORM1UI64NVPROC glProgramUniform1ui64NV; +PFNGLPROGRAMUNIFORM2UI64NVPROC glProgramUniform2ui64NV; +PFNGLPROGRAMUNIFORM3UI64NVPROC glProgramUniform3ui64NV; +PFNGLPROGRAMUNIFORM4UI64NVPROC glProgramUniform4ui64NV; PFNGLPROGRAMUNIFORM1UI64VNVPROC glProgramUniform1ui64vNV; PFNGLPROGRAMUNIFORM2UI64VNVPROC glProgramUniform2ui64vNV; PFNGLPROGRAMUNIFORM3UI64VNVPROC glProgramUniform3ui64vNV; @@ -771,26 +771,26 @@ PFNGLGETINTERNALFORMATSAMPLEIVNVPROC glGetInternalformatSampleivNV; #if defined(GL_NV_memory_attachment) PFNGLGETMEMORYOBJECTDETACHEDRESOURCESUIVNVPROC glGetMemoryObjectDetachedResourcesuivNV; -PFNGLRESETMEMORYOBJECTPARAMETERNVPROC glResetMemoryObjectParameterNV; -PFNGLTEXATTACHMEMORYNVPROC glTexAttachMemoryNV; -PFNGLBUFFERATTACHMEMORYNVPROC glBufferAttachMemoryNV; +PFNGLRESETMEMORYOBJECTPARAMETERNVPROC glResetMemoryObjectParameterNV; +PFNGLTEXATTACHMEMORYNVPROC glTexAttachMemoryNV; +PFNGLBUFFERATTACHMEMORYNVPROC glBufferAttachMemoryNV; -PFNGLTEXTUREATTACHMEMORYNVPROC glTextureAttachMemoryNV; +PFNGLTEXTUREATTACHMEMORYNVPROC glTextureAttachMemoryNV; PFNGLNAMEDBUFFERATTACHMEMORYNVPROC glNamedBufferAttachMemoryNV; #endif /* defined(GL_NV_memory_attachment) */ #if defined(GL_NV_memory_object_sparse) PFNGLBUFFERPAGECOMMITMENTMEMNVPROC glBufferPageCommitmentMemNV; -PFNGLTEXPAGECOMMITMENTMEMNVPROC glTexPageCommitmentMemNV; +PFNGLTEXPAGECOMMITMENTMEMNVPROC glTexPageCommitmentMemNV; PFNGLNAMEDBUFFERPAGECOMMITMENTMEMNVPROC glNamedBufferPageCommitmentMemNV; -PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC glTexturePageCommitmentMemNV; +PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC glTexturePageCommitmentMemNV; #endif /* defined(GL_NV_memory_object_sparse) */ #if defined(GL_NV_mesh_shader) -PFNGLDRAWMESHTASKSNVPROC glDrawMeshTasksNV; -PFNGLDRAWMESHTASKSINDIRECTNVPROC glDrawMeshTasksIndirectNV; -PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC glMultiDrawMeshTasksIndirectNV; +PFNGLDRAWMESHTASKSNVPROC glDrawMeshTasksNV; +PFNGLDRAWMESHTASKSINDIRECTNVPROC glDrawMeshTasksIndirectNV; +PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC glMultiDrawMeshTasksIndirectNV; PFNGLMULTIDRAWMESHTASKSINDIRECTCOUNTNVPROC glMultiDrawMeshTasksIndirectCountNV; #endif /* defined(GL_NV_mesh_shader) */ @@ -804,85 +804,85 @@ PFNGLUNIFORMMATRIX4X3FVNVPROC glUniformMatrix4x3fvNV; #endif /* defined(GL_NV_non_square_matrices) */ #if defined(GL_NV_path_rendering) -PFNGLGENPATHSNVPROC glGenPathsNV; -PFNGLDELETEPATHSNVPROC glDeletePathsNV; -PFNGLISPATHNVPROC glIsPathNV; -PFNGLPATHCOMMANDSNVPROC glPathCommandsNV; -PFNGLPATHCOORDSNVPROC glPathCoordsNV; -PFNGLPATHSUBCOMMANDSNVPROC glPathSubCommandsNV; -PFNGLPATHSUBCOORDSNVPROC glPathSubCoordsNV; -PFNGLPATHSTRINGNVPROC glPathStringNV; -PFNGLPATHGLYPHSNVPROC glPathGlyphsNV; -PFNGLPATHGLYPHRANGENVPROC glPathGlyphRangeNV; -PFNGLWEIGHTPATHSNVPROC glWeightPathsNV; -PFNGLCOPYPATHNVPROC glCopyPathNV; -PFNGLINTERPOLATEPATHSNVPROC glInterpolatePathsNV; -PFNGLTRANSFORMPATHNVPROC glTransformPathNV; -PFNGLPATHPARAMETERIVNVPROC glPathParameterivNV; -PFNGLPATHPARAMETERINVPROC glPathParameteriNV; -PFNGLPATHPARAMETERFVNVPROC glPathParameterfvNV; -PFNGLPATHPARAMETERFNVPROC glPathParameterfNV; -PFNGLPATHDASHARRAYNVPROC glPathDashArrayNV; -PFNGLPATHSTENCILFUNCNVPROC glPathStencilFuncNV; -PFNGLPATHSTENCILDEPTHOFFSETNVPROC glPathStencilDepthOffsetNV; -PFNGLSTENCILFILLPATHNVPROC glStencilFillPathNV; -PFNGLSTENCILSTROKEPATHNVPROC glStencilStrokePathNV; -PFNGLSTENCILFILLPATHINSTANCEDNVPROC glStencilFillPathInstancedNV; +PFNGLGENPATHSNVPROC glGenPathsNV; +PFNGLDELETEPATHSNVPROC glDeletePathsNV; +PFNGLISPATHNVPROC glIsPathNV; +PFNGLPATHCOMMANDSNVPROC glPathCommandsNV; +PFNGLPATHCOORDSNVPROC glPathCoordsNV; +PFNGLPATHSUBCOMMANDSNVPROC glPathSubCommandsNV; +PFNGLPATHSUBCOORDSNVPROC glPathSubCoordsNV; +PFNGLPATHSTRINGNVPROC glPathStringNV; +PFNGLPATHGLYPHSNVPROC glPathGlyphsNV; +PFNGLPATHGLYPHRANGENVPROC glPathGlyphRangeNV; +PFNGLWEIGHTPATHSNVPROC glWeightPathsNV; +PFNGLCOPYPATHNVPROC glCopyPathNV; +PFNGLINTERPOLATEPATHSNVPROC glInterpolatePathsNV; +PFNGLTRANSFORMPATHNVPROC glTransformPathNV; +PFNGLPATHPARAMETERIVNVPROC glPathParameterivNV; +PFNGLPATHPARAMETERINVPROC glPathParameteriNV; +PFNGLPATHPARAMETERFVNVPROC glPathParameterfvNV; +PFNGLPATHPARAMETERFNVPROC glPathParameterfNV; +PFNGLPATHDASHARRAYNVPROC glPathDashArrayNV; +PFNGLPATHSTENCILFUNCNVPROC glPathStencilFuncNV; +PFNGLPATHSTENCILDEPTHOFFSETNVPROC glPathStencilDepthOffsetNV; +PFNGLSTENCILFILLPATHNVPROC glStencilFillPathNV; +PFNGLSTENCILSTROKEPATHNVPROC glStencilStrokePathNV; +PFNGLSTENCILFILLPATHINSTANCEDNVPROC glStencilFillPathInstancedNV; PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC glStencilStrokePathInstancedNV; -PFNGLPATHCOVERDEPTHFUNCNVPROC glPathCoverDepthFuncNV; -PFNGLCOVERFILLPATHNVPROC glCoverFillPathNV; -PFNGLCOVERSTROKEPATHNVPROC glCoverStrokePathNV; -PFNGLCOVERFILLPATHINSTANCEDNVPROC glCoverFillPathInstancedNV; -PFNGLCOVERSTROKEPATHINSTANCEDNVPROC glCoverStrokePathInstancedNV; -PFNGLGETPATHPARAMETERIVNVPROC glGetPathParameterivNV; -PFNGLGETPATHPARAMETERFVNVPROC glGetPathParameterfvNV; -PFNGLGETPATHCOMMANDSNVPROC glGetPathCommandsNV; -PFNGLGETPATHCOORDSNVPROC glGetPathCoordsNV; -PFNGLGETPATHDASHARRAYNVPROC glGetPathDashArrayNV; -PFNGLGETPATHMETRICSNVPROC glGetPathMetricsNV; -PFNGLGETPATHMETRICRANGENVPROC glGetPathMetricRangeNV; -PFNGLGETPATHSPACINGNVPROC glGetPathSpacingNV; -PFNGLISPOINTINFILLPATHNVPROC glIsPointInFillPathNV; -PFNGLISPOINTINSTROKEPATHNVPROC glIsPointInStrokePathNV; -PFNGLGETPATHLENGTHNVPROC glGetPathLengthNV; -PFNGLPOINTALONGPATHNVPROC glPointAlongPathNV; +PFNGLPATHCOVERDEPTHFUNCNVPROC glPathCoverDepthFuncNV; +PFNGLCOVERFILLPATHNVPROC glCoverFillPathNV; +PFNGLCOVERSTROKEPATHNVPROC glCoverStrokePathNV; +PFNGLCOVERFILLPATHINSTANCEDNVPROC glCoverFillPathInstancedNV; +PFNGLCOVERSTROKEPATHINSTANCEDNVPROC glCoverStrokePathInstancedNV; +PFNGLGETPATHPARAMETERIVNVPROC glGetPathParameterivNV; +PFNGLGETPATHPARAMETERFVNVPROC glGetPathParameterfvNV; +PFNGLGETPATHCOMMANDSNVPROC glGetPathCommandsNV; +PFNGLGETPATHCOORDSNVPROC glGetPathCoordsNV; +PFNGLGETPATHDASHARRAYNVPROC glGetPathDashArrayNV; +PFNGLGETPATHMETRICSNVPROC glGetPathMetricsNV; +PFNGLGETPATHMETRICRANGENVPROC glGetPathMetricRangeNV; +PFNGLGETPATHSPACINGNVPROC glGetPathSpacingNV; +PFNGLISPOINTINFILLPATHNVPROC glIsPointInFillPathNV; +PFNGLISPOINTINSTROKEPATHNVPROC glIsPointInStrokePathNV; +PFNGLGETPATHLENGTHNVPROC glGetPathLengthNV; +PFNGLPOINTALONGPATHNVPROC glPointAlongPathNV; -PFNGLMATRIXLOAD3X2FNVPROC glMatrixLoad3x2fNV; -PFNGLMATRIXLOAD3X3FNVPROC glMatrixLoad3x3fNV; -PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC glMatrixLoadTranspose3x3fNV; -PFNGLMATRIXMULT3X2FNVPROC glMatrixMult3x2fNV; -PFNGLMATRIXMULT3X3FNVPROC glMatrixMult3x3fNV; -PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC glMatrixMultTranspose3x3fNV; -PFNGLSTENCILTHENCOVERFILLPATHNVPROC glStencilThenCoverFillPathNV; -PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC glStencilThenCoverStrokePathNV; -PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC glStencilThenCoverFillPathInstancedNV; +PFNGLMATRIXLOAD3X2FNVPROC glMatrixLoad3x2fNV; +PFNGLMATRIXLOAD3X3FNVPROC glMatrixLoad3x3fNV; +PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC glMatrixLoadTranspose3x3fNV; +PFNGLMATRIXMULT3X2FNVPROC glMatrixMult3x2fNV; +PFNGLMATRIXMULT3X3FNVPROC glMatrixMult3x3fNV; +PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC glMatrixMultTranspose3x3fNV; +PFNGLSTENCILTHENCOVERFILLPATHNVPROC glStencilThenCoverFillPathNV; +PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC glStencilThenCoverStrokePathNV; +PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC glStencilThenCoverFillPathInstancedNV; PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC glStencilThenCoverStrokePathInstancedNV; -PFNGLPATHGLYPHINDEXRANGENVPROC glPathGlyphIndexRangeNV; +PFNGLPATHGLYPHINDEXRANGENVPROC glPathGlyphIndexRangeNV; -PFNGLPATHGLYPHINDEXARRAYNVPROC glPathGlyphIndexArrayNV; -PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC glPathMemoryGlyphIndexArrayNV; +PFNGLPATHGLYPHINDEXARRAYNVPROC glPathGlyphIndexArrayNV; +PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC glPathMemoryGlyphIndexArrayNV; PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC glProgramPathFragmentInputGenNV; -PFNGLGETPROGRAMRESOURCEFVNVPROC glGetProgramResourcefvNV; +PFNGLGETPROGRAMRESOURCEFVNVPROC glGetProgramResourcefvNV; -PFNGLMATRIXFRUSTUMEXTPROC glMatrixFrustumEXT; -PFNGLMATRIXLOADIDENTITYEXTPROC glMatrixLoadIdentityEXT; +PFNGLMATRIXFRUSTUMEXTPROC glMatrixFrustumEXT; +PFNGLMATRIXLOADIDENTITYEXTPROC glMatrixLoadIdentityEXT; PFNGLMATRIXLOADTRANSPOSEFEXTPROC glMatrixLoadTransposefEXT; PFNGLMATRIXLOADTRANSPOSEDEXTPROC glMatrixLoadTransposedEXT; -PFNGLMATRIXLOADFEXTPROC glMatrixLoadfEXT; -PFNGLMATRIXLOADDEXTPROC glMatrixLoaddEXT; +PFNGLMATRIXLOADFEXTPROC glMatrixLoadfEXT; +PFNGLMATRIXLOADDEXTPROC glMatrixLoaddEXT; PFNGLMATRIXMULTTRANSPOSEFEXTPROC glMatrixMultTransposefEXT; PFNGLMATRIXMULTTRANSPOSEDEXTPROC glMatrixMultTransposedEXT; -PFNGLMATRIXMULTFEXTPROC glMatrixMultfEXT; -PFNGLMATRIXMULTDEXTPROC glMatrixMultdEXT; -PFNGLMATRIXORTHOEXTPROC glMatrixOrthoEXT; -PFNGLMATRIXPOPEXTPROC glMatrixPopEXT; -PFNGLMATRIXPUSHEXTPROC glMatrixPushEXT; -PFNGLMATRIXROTATEFEXTPROC glMatrixRotatefEXT; -PFNGLMATRIXROTATEDEXTPROC glMatrixRotatedEXT; -PFNGLMATRIXSCALEFEXTPROC glMatrixScalefEXT; -PFNGLMATRIXSCALEDEXTPROC glMatrixScaledEXT; -PFNGLMATRIXTRANSLATEFEXTPROC glMatrixTranslatefEXT; -PFNGLMATRIXTRANSLATEDEXTPROC glMatrixTranslatedEXT; +PFNGLMATRIXMULTFEXTPROC glMatrixMultfEXT; +PFNGLMATRIXMULTDEXTPROC glMatrixMultdEXT; +PFNGLMATRIXORTHOEXTPROC glMatrixOrthoEXT; +PFNGLMATRIXPOPEXTPROC glMatrixPopEXT; +PFNGLMATRIXPUSHEXTPROC glMatrixPushEXT; +PFNGLMATRIXROTATEFEXTPROC glMatrixRotatefEXT; +PFNGLMATRIXROTATEDEXTPROC glMatrixRotatedEXT; +PFNGLMATRIXSCALEFEXTPROC glMatrixScalefEXT; +PFNGLMATRIXSCALEDEXTPROC glMatrixScaledEXT; +PFNGLMATRIXTRANSLATEFEXTPROC glMatrixTranslatefEXT; +PFNGLMATRIXTRANSLATEDEXTPROC glMatrixTranslatedEXT; #endif /* defined(GL_NV_path_rendering) */ #if defined(GL_NV_polygon_mode) @@ -894,39 +894,39 @@ PFNGLREADBUFFERNVPROC glReadBufferNV; #endif /* defined(GL_NV_read_buffer) */ #if defined(GL_NV_sample_locations) -PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glFramebufferSampleLocationsfvNV; +PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glFramebufferSampleLocationsfvNV; PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glNamedFramebufferSampleLocationsfvNV; -PFNGLRESOLVEDEPTHVALUESNVPROC glResolveDepthValuesNV; +PFNGLRESOLVEDEPTHVALUESNVPROC glResolveDepthValuesNV; #endif /* defined(GL_NV_sample_locations) */ #if defined(GL_NV_scissor_exclusive) -PFNGLSCISSOREXCLUSIVENVPROC glScissorExclusiveNV; +PFNGLSCISSOREXCLUSIVENVPROC glScissorExclusiveNV; PFNGLSCISSOREXCLUSIVEARRAYVNVPROC glScissorExclusiveArrayvNV; #endif /* defined(GL_NV_scissor_exclusive) */ #if defined(GL_NV_shading_rate_image) -PFNGLBINDSHADINGRATEIMAGENVPROC glBindShadingRateImageNV; -PFNGLGETSHADINGRATEIMAGEPALETTENVPROC glGetShadingRateImagePaletteNV; +PFNGLBINDSHADINGRATEIMAGENVPROC glBindShadingRateImageNV; +PFNGLGETSHADINGRATEIMAGEPALETTENVPROC glGetShadingRateImagePaletteNV; PFNGLGETSHADINGRATESAMPLELOCATIONIVNVPROC glGetShadingRateSampleLocationivNV; -PFNGLSHADINGRATEIMAGEBARRIERNVPROC glShadingRateImageBarrierNV; -PFNGLSHADINGRATEIMAGEPALETTENVPROC glShadingRateImagePaletteNV; -PFNGLSHADINGRATESAMPLEORDERNVPROC glShadingRateSampleOrderNV; -PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC glShadingRateSampleOrderCustomNV; +PFNGLSHADINGRATEIMAGEBARRIERNVPROC glShadingRateImageBarrierNV; +PFNGLSHADINGRATEIMAGEPALETTENVPROC glShadingRateImagePaletteNV; +PFNGLSHADINGRATESAMPLEORDERNVPROC glShadingRateSampleOrderNV; +PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC glShadingRateSampleOrderCustomNV; #endif /* defined(GL_NV_shading_rate_image) */ #if defined(GL_NV_viewport_array) -PFNGLVIEWPORTARRAYVNVPROC glViewportArrayvNV; -PFNGLVIEWPORTINDEXEDFNVPROC glViewportIndexedfNV; -PFNGLVIEWPORTINDEXEDFVNVPROC glViewportIndexedfvNV; -PFNGLSCISSORARRAYVNVPROC glScissorArrayvNV; -PFNGLSCISSORINDEXEDNVPROC glScissorIndexedNV; -PFNGLSCISSORINDEXEDVNVPROC glScissorIndexedvNV; -PFNGLDEPTHRANGEARRAYFVNVPROC glDepthRangeArrayfvNV; +PFNGLVIEWPORTARRAYVNVPROC glViewportArrayvNV; +PFNGLVIEWPORTINDEXEDFNVPROC glViewportIndexedfNV; +PFNGLVIEWPORTINDEXEDFVNVPROC glViewportIndexedfvNV; +PFNGLSCISSORARRAYVNVPROC glScissorArrayvNV; +PFNGLSCISSORINDEXEDNVPROC glScissorIndexedNV; +PFNGLSCISSORINDEXEDVNVPROC glScissorIndexedvNV; +PFNGLDEPTHRANGEARRAYFVNVPROC glDepthRangeArrayfvNV; PFNGLDEPTHRANGEINDEXEDFNVPROC glDepthRangeIndexedfNV; -PFNGLGETFLOATI_VNVPROC glGetFloati_vNV; -PFNGLENABLEINVPROC glEnableiNV; -PFNGLDISABLEINVPROC glDisableiNV; -PFNGLISENABLEDINVPROC glIsEnablediNV; +PFNGLGETFLOATI_VNVPROC glGetFloati_vNV; +PFNGLENABLEINVPROC glEnableiNV; +PFNGLDISABLEINVPROC glDisableiNV; +PFNGLISENABLEDINVPROC glIsEnablediNV; #endif /* defined(GL_NV_viewport_array) */ #if defined(GL_NV_viewport_swizzle) @@ -934,7 +934,7 @@ PFNGLVIEWPORTSWIZZLENVPROC glViewportSwizzleNV; #endif /* defined(GL_NV_viewport_swizzle) */ #if defined(GL_OES_EGL_image) -PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; +PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC glEGLImageTargetRenderbufferStorageOES; #endif /* defined(GL_OES_EGL_image) */ @@ -943,19 +943,19 @@ PFNGLCOPYIMAGESUBDATAOESPROC glCopyImageSubDataOES; #endif /* defined(GL_OES_copy_image) */ #if defined(GL_OES_draw_buffers_indexed) -PFNGLENABLEIOESPROC glEnableiOES; -PFNGLDISABLEIOESPROC glDisableiOES; -PFNGLBLENDEQUATIONIOESPROC glBlendEquationiOES; +PFNGLENABLEIOESPROC glEnableiOES; +PFNGLDISABLEIOESPROC glDisableiOES; +PFNGLBLENDEQUATIONIOESPROC glBlendEquationiOES; PFNGLBLENDEQUATIONSEPARATEIOESPROC glBlendEquationSeparateiOES; -PFNGLBLENDFUNCIOESPROC glBlendFunciOES; -PFNGLBLENDFUNCSEPARATEIOESPROC glBlendFuncSeparateiOES; -PFNGLCOLORMASKIOESPROC glColorMaskiOES; -PFNGLISENABLEDIOESPROC glIsEnablediOES; +PFNGLBLENDFUNCIOESPROC glBlendFunciOES; +PFNGLBLENDFUNCSEPARATEIOESPROC glBlendFuncSeparateiOES; +PFNGLCOLORMASKIOESPROC glColorMaskiOES; +PFNGLISENABLEDIOESPROC glIsEnablediOES; #endif /* defined(GL_OES_draw_buffers_indexed) */ #if defined(GL_OES_draw_elements_base_vertex) -PFNGLDRAWELEMENTSBASEVERTEXOESPROC glDrawElementsBaseVertexOES; -PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC glDrawRangeElementsBaseVertexOES; +PFNGLDRAWELEMENTSBASEVERTEXOESPROC glDrawElementsBaseVertexOES; +PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC glDrawRangeElementsBaseVertexOES; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC glDrawElementsInstancedBaseVertexOES; #endif /* defined(GL_OES_draw_elements_base_vertex) */ @@ -965,12 +965,12 @@ PFNGLFRAMEBUFFERTEXTUREOESPROC glFramebufferTextureOES; #if defined(GL_OES_get_program_binary) PFNGLGETPROGRAMBINARYOESPROC glGetProgramBinaryOES; -PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES; +PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES; #endif /* defined(GL_OES_get_program_binary) */ #if defined(GL_OES_mapbuffer) -PFNGLMAPBUFFEROESPROC glMapBufferOES; -PFNGLUNMAPBUFFEROESPROC glUnmapBufferOES; +PFNGLMAPBUFFEROESPROC glMapBufferOES; +PFNGLUNMAPBUFFEROESPROC glUnmapBufferOES; PFNGLGETBUFFERPOINTERVOESPROC glGetBufferPointervOES; #endif /* defined(GL_OES_mapbuffer) */ @@ -987,27 +987,27 @@ PFNGLPATCHPARAMETERIOESPROC glPatchParameteriOES; #endif /* defined(GL_OES_tessellation_shader) */ #if defined(GL_OES_texture_3D) -PFNGLTEXIMAGE3DOESPROC glTexImage3DOES; -PFNGLTEXSUBIMAGE3DOESPROC glTexSubImage3DOES; -PFNGLCOPYTEXSUBIMAGE3DOESPROC glCopyTexSubImage3DOES; -PFNGLCOMPRESSEDTEXIMAGE3DOESPROC glCompressedTexImage3DOES; +PFNGLTEXIMAGE3DOESPROC glTexImage3DOES; +PFNGLTEXSUBIMAGE3DOESPROC glTexSubImage3DOES; +PFNGLCOPYTEXSUBIMAGE3DOESPROC glCopyTexSubImage3DOES; +PFNGLCOMPRESSEDTEXIMAGE3DOESPROC glCompressedTexImage3DOES; PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC glCompressedTexSubImage3DOES; -PFNGLFRAMEBUFFERTEXTURE3DOESPROC glFramebufferTexture3DOES; +PFNGLFRAMEBUFFERTEXTURE3DOESPROC glFramebufferTexture3DOES; #endif /* defined(GL_OES_texture_3D) */ #if defined(GL_OES_texture_border_clamp) -PFNGLTEXPARAMETERIIVOESPROC glTexParameterIivOES; -PFNGLTEXPARAMETERIUIVOESPROC glTexParameterIuivOES; -PFNGLGETTEXPARAMETERIIVOESPROC glGetTexParameterIivOES; -PFNGLGETTEXPARAMETERIUIVOESPROC glGetTexParameterIuivOES; -PFNGLSAMPLERPARAMETERIIVOESPROC glSamplerParameterIivOES; -PFNGLSAMPLERPARAMETERIUIVOESPROC glSamplerParameterIuivOES; -PFNGLGETSAMPLERPARAMETERIIVOESPROC glGetSamplerParameterIivOES; +PFNGLTEXPARAMETERIIVOESPROC glTexParameterIivOES; +PFNGLTEXPARAMETERIUIVOESPROC glTexParameterIuivOES; +PFNGLGETTEXPARAMETERIIVOESPROC glGetTexParameterIivOES; +PFNGLGETTEXPARAMETERIUIVOESPROC glGetTexParameterIuivOES; +PFNGLSAMPLERPARAMETERIIVOESPROC glSamplerParameterIivOES; +PFNGLSAMPLERPARAMETERIUIVOESPROC glSamplerParameterIuivOES; +PFNGLGETSAMPLERPARAMETERIIVOESPROC glGetSamplerParameterIivOES; PFNGLGETSAMPLERPARAMETERIUIVOESPROC glGetSamplerParameterIuivOES; #endif /* defined(GL_OES_texture_border_clamp) */ #if defined(GL_OES_texture_buffer) -PFNGLTEXBUFFEROESPROC glTexBufferOES; +PFNGLTEXBUFFEROESPROC glTexBufferOES; PFNGLTEXBUFFERRANGEOESPROC glTexBufferRangeOES; #endif /* defined(GL_OES_texture_buffer) */ @@ -1020,22 +1020,22 @@ PFNGLTEXTUREVIEWOESPROC glTextureViewOES; #endif /* defined(GL_OES_texture_view) */ #if defined(GL_OES_vertex_array_object) -PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; +PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES; -PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; -PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; +PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; +PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; #endif /* defined(GL_OES_vertex_array_object) */ #if defined(GL_OES_viewport_array) -PFNGLVIEWPORTARRAYVOESPROC glViewportArrayvOES; -PFNGLVIEWPORTINDEXEDFOESPROC glViewportIndexedfOES; -PFNGLVIEWPORTINDEXEDFVOESPROC glViewportIndexedfvOES; -PFNGLSCISSORARRAYVOESPROC glScissorArrayvOES; -PFNGLSCISSORINDEXEDOESPROC glScissorIndexedOES; -PFNGLSCISSORINDEXEDVOESPROC glScissorIndexedvOES; -PFNGLDEPTHRANGEARRAYFVOESPROC glDepthRangeArrayfvOES; +PFNGLVIEWPORTARRAYVOESPROC glViewportArrayvOES; +PFNGLVIEWPORTINDEXEDFOESPROC glViewportIndexedfOES; +PFNGLVIEWPORTINDEXEDFVOESPROC glViewportIndexedfvOES; +PFNGLSCISSORARRAYVOESPROC glScissorArrayvOES; +PFNGLSCISSORINDEXEDOESPROC glScissorIndexedOES; +PFNGLSCISSORINDEXEDVOESPROC glScissorIndexedvOES; +PFNGLDEPTHRANGEARRAYFVOESPROC glDepthRangeArrayfvOES; PFNGLDEPTHRANGEINDEXEDFOESPROC glDepthRangeIndexedfOES; -PFNGLGETFLOATI_VOESPROC glGetFloati_vOES; +PFNGLGETFLOATI_VOESPROC glGetFloati_vOES; #endif /* defined(GL_OES_viewport_array) */ #if defined(GL_OVR_multiview) @@ -1051,37 +1051,37 @@ PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM; #endif /* defined(GL_QCOM_alpha_test) */ #if defined(GL_QCOM_driver_control) -PFNGLGETDRIVERCONTROLSQCOMPROC glGetDriverControlsQCOM; +PFNGLGETDRIVERCONTROLSQCOMPROC glGetDriverControlsQCOM; PFNGLGETDRIVERCONTROLSTRINGQCOMPROC glGetDriverControlStringQCOM; -PFNGLENABLEDRIVERCONTROLQCOMPROC glEnableDriverControlQCOM; -PFNGLDISABLEDRIVERCONTROLQCOMPROC glDisableDriverControlQCOM; +PFNGLENABLEDRIVERCONTROLQCOMPROC glEnableDriverControlQCOM; +PFNGLDISABLEDRIVERCONTROLQCOMPROC glDisableDriverControlQCOM; #endif /* defined(GL_QCOM_driver_control) */ #if defined(GL_QCOM_extended_get) -PFNGLEXTGETTEXTURESQCOMPROC glExtGetTexturesQCOM; -PFNGLEXTGETBUFFERSQCOMPROC glExtGetBuffersQCOM; -PFNGLEXTGETRENDERBUFFERSQCOMPROC glExtGetRenderbuffersQCOM; -PFNGLEXTGETFRAMEBUFFERSQCOMPROC glExtGetFramebuffersQCOM; -PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC glExtGetTexLevelParameterivQCOM; +PFNGLEXTGETTEXTURESQCOMPROC glExtGetTexturesQCOM; +PFNGLEXTGETBUFFERSQCOMPROC glExtGetBuffersQCOM; +PFNGLEXTGETRENDERBUFFERSQCOMPROC glExtGetRenderbuffersQCOM; +PFNGLEXTGETFRAMEBUFFERSQCOMPROC glExtGetFramebuffersQCOM; +PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC glExtGetTexLevelParameterivQCOM; PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC glExtTexObjectStateOverrideiQCOM; -PFNGLEXTGETTEXSUBIMAGEQCOMPROC glExtGetTexSubImageQCOM; -PFNGLEXTGETBUFFERPOINTERVQCOMPROC glExtGetBufferPointervQCOM; +PFNGLEXTGETTEXSUBIMAGEQCOMPROC glExtGetTexSubImageQCOM; +PFNGLEXTGETBUFFERPOINTERVQCOMPROC glExtGetBufferPointervQCOM; #endif /* defined(GL_QCOM_extended_get) */ #if defined(GL_QCOM_extended_get2) -PFNGLEXTGETSHADERSQCOMPROC glExtGetShadersQCOM; -PFNGLEXTGETPROGRAMSQCOMPROC glExtGetProgramsQCOM; -PFNGLEXTISPROGRAMBINARYQCOMPROC glExtIsProgramBinaryQCOM; +PFNGLEXTGETSHADERSQCOMPROC glExtGetShadersQCOM; +PFNGLEXTGETPROGRAMSQCOMPROC glExtGetProgramsQCOM; +PFNGLEXTISPROGRAMBINARYQCOMPROC glExtIsProgramBinaryQCOM; PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC glExtGetProgramBinarySourceQCOM; #endif /* defined(GL_QCOM_extended_get2) */ #if defined(GL_QCOM_framebuffer_foveated) -PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC glFramebufferFoveationConfigQCOM; +PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC glFramebufferFoveationConfigQCOM; PFNGLFRAMEBUFFERFOVEATIONPARAMETERSQCOMPROC glFramebufferFoveationParametersQCOM; #endif /* defined(GL_QCOM_framebuffer_foveated) */ #if defined(GL_QCOM_motion_estimation) -PFNGLTEXESTIMATEMOTIONQCOMPROC glTexEstimateMotionQCOM; +PFNGLTEXESTIMATEMOTIONQCOMPROC glTexEstimateMotionQCOM; PFNGLTEXESTIMATEMOTIONREGIONSQCOMPROC glTexEstimateMotionRegionsQCOM; #endif /* defined(GL_QCOM_motion_estimation) */ @@ -1103,7 +1103,7 @@ PFNGLSHADINGRATEQCOMPROC glShadingRateQCOM; #if defined(GL_QCOM_tiled_rendering) PFNGLSTARTTILINGQCOMPROC glStartTilingQCOM; -PFNGLENDTILINGQCOMPROC glEndTilingQCOM; +PFNGLENDTILINGQCOMPROC glEndTilingQCOM; #endif /* defined(GL_QCOM_tiled_rendering) */ /* GLES2W_GENERATE_GLES_DEFINITION */ @@ -1125,166 +1125,166 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { /* GLES2W_GENERATE_GLES_LOAD */ /* GL_ES_VERSION_2_0 */ - glActiveTexture = reinterpret_cast(gles2wLoad("glActiveTexture")); - glAttachShader = reinterpret_cast(gles2wLoad("glAttachShader")); - glBindAttribLocation = reinterpret_cast(gles2wLoad("glBindAttribLocation")); - glBindBuffer = reinterpret_cast(gles2wLoad("glBindBuffer")); - glBindFramebuffer = reinterpret_cast(gles2wLoad("glBindFramebuffer")); - glBindRenderbuffer = reinterpret_cast(gles2wLoad("glBindRenderbuffer")); - glBindTexture = reinterpret_cast(gles2wLoad("glBindTexture")); - glBlendColor = reinterpret_cast(gles2wLoad("glBlendColor")); - glBlendEquation = reinterpret_cast(gles2wLoad("glBlendEquation")); - glBlendEquationSeparate = reinterpret_cast(gles2wLoad("glBlendEquationSeparate")); - glBlendFunc = reinterpret_cast(gles2wLoad("glBlendFunc")); - glBlendFuncSeparate = reinterpret_cast(gles2wLoad("glBlendFuncSeparate")); - glBufferData = reinterpret_cast(gles2wLoad("glBufferData")); - glBufferSubData = reinterpret_cast(gles2wLoad("glBufferSubData")); - glCheckFramebufferStatus = reinterpret_cast(gles2wLoad("glCheckFramebufferStatus")); - glClear = reinterpret_cast(gles2wLoad("glClear")); - glClearColor = reinterpret_cast(gles2wLoad("glClearColor")); - glClearDepthf = reinterpret_cast(gles2wLoad("glClearDepthf")); - glClearStencil = reinterpret_cast(gles2wLoad("glClearStencil")); - glColorMask = reinterpret_cast(gles2wLoad("glColorMask")); - glCompileShader = reinterpret_cast(gles2wLoad("glCompileShader")); - glCompressedTexImage2D = reinterpret_cast(gles2wLoad("glCompressedTexImage2D")); - glCompressedTexSubImage2D = reinterpret_cast(gles2wLoad("glCompressedTexSubImage2D")); - glCopyTexImage2D = reinterpret_cast(gles2wLoad("glCopyTexImage2D")); - glCopyTexSubImage2D = reinterpret_cast(gles2wLoad("glCopyTexSubImage2D")); - glCreateProgram = reinterpret_cast(gles2wLoad("glCreateProgram")); - glCreateShader = reinterpret_cast(gles2wLoad("glCreateShader")); - glCullFace = reinterpret_cast(gles2wLoad("glCullFace")); - glDeleteBuffers = reinterpret_cast(gles2wLoad("glDeleteBuffers")); - glDeleteFramebuffers = reinterpret_cast(gles2wLoad("glDeleteFramebuffers")); - glDeleteProgram = reinterpret_cast(gles2wLoad("glDeleteProgram")); - glDeleteRenderbuffers = reinterpret_cast(gles2wLoad("glDeleteRenderbuffers")); - glDeleteShader = reinterpret_cast(gles2wLoad("glDeleteShader")); - glDeleteTextures = reinterpret_cast(gles2wLoad("glDeleteTextures")); - glDepthFunc = reinterpret_cast(gles2wLoad("glDepthFunc")); - glDepthMask = reinterpret_cast(gles2wLoad("glDepthMask")); - glDepthRangef = reinterpret_cast(gles2wLoad("glDepthRangef")); - glDetachShader = reinterpret_cast(gles2wLoad("glDetachShader")); - glDisable = reinterpret_cast(gles2wLoad("glDisable")); - glDisableVertexAttribArray = reinterpret_cast(gles2wLoad("glDisableVertexAttribArray")); - glDrawArrays = reinterpret_cast(gles2wLoad("glDrawArrays")); - glDrawElements = reinterpret_cast(gles2wLoad("glDrawElements")); - glEnable = reinterpret_cast(gles2wLoad("glEnable")); - glEnableVertexAttribArray = reinterpret_cast(gles2wLoad("glEnableVertexAttribArray")); - glFinish = reinterpret_cast(gles2wLoad("glFinish")); - glFlush = reinterpret_cast(gles2wLoad("glFlush")); - glFramebufferRenderbuffer = reinterpret_cast(gles2wLoad("glFramebufferRenderbuffer")); - glFramebufferTexture2D = reinterpret_cast(gles2wLoad("glFramebufferTexture2D")); - glFrontFace = reinterpret_cast(gles2wLoad("glFrontFace")); - glGenBuffers = reinterpret_cast(gles2wLoad("glGenBuffers")); - glGenerateMipmap = reinterpret_cast(gles2wLoad("glGenerateMipmap")); - glGenFramebuffers = reinterpret_cast(gles2wLoad("glGenFramebuffers")); - glGenRenderbuffers = reinterpret_cast(gles2wLoad("glGenRenderbuffers")); - glGenTextures = reinterpret_cast(gles2wLoad("glGenTextures")); - glGetActiveAttrib = reinterpret_cast(gles2wLoad("glGetActiveAttrib")); - glGetActiveUniform = reinterpret_cast(gles2wLoad("glGetActiveUniform")); - glGetAttachedShaders = reinterpret_cast(gles2wLoad("glGetAttachedShaders")); - glGetAttribLocation = reinterpret_cast(gles2wLoad("glGetAttribLocation")); - glGetBooleanv = reinterpret_cast(gles2wLoad("glGetBooleanv")); - glGetBufferParameteriv = reinterpret_cast(gles2wLoad("glGetBufferParameteriv")); - glGetError = reinterpret_cast(gles2wLoad("glGetError")); - glGetFloatv = reinterpret_cast(gles2wLoad("glGetFloatv")); + glActiveTexture = reinterpret_cast(gles2wLoad("glActiveTexture")); + glAttachShader = reinterpret_cast(gles2wLoad("glAttachShader")); + glBindAttribLocation = reinterpret_cast(gles2wLoad("glBindAttribLocation")); + glBindBuffer = reinterpret_cast(gles2wLoad("glBindBuffer")); + glBindFramebuffer = reinterpret_cast(gles2wLoad("glBindFramebuffer")); + glBindRenderbuffer = reinterpret_cast(gles2wLoad("glBindRenderbuffer")); + glBindTexture = reinterpret_cast(gles2wLoad("glBindTexture")); + glBlendColor = reinterpret_cast(gles2wLoad("glBlendColor")); + glBlendEquation = reinterpret_cast(gles2wLoad("glBlendEquation")); + glBlendEquationSeparate = reinterpret_cast(gles2wLoad("glBlendEquationSeparate")); + glBlendFunc = reinterpret_cast(gles2wLoad("glBlendFunc")); + glBlendFuncSeparate = reinterpret_cast(gles2wLoad("glBlendFuncSeparate")); + glBufferData = reinterpret_cast(gles2wLoad("glBufferData")); + glBufferSubData = reinterpret_cast(gles2wLoad("glBufferSubData")); + glCheckFramebufferStatus = reinterpret_cast(gles2wLoad("glCheckFramebufferStatus")); + glClear = reinterpret_cast(gles2wLoad("glClear")); + glClearColor = reinterpret_cast(gles2wLoad("glClearColor")); + glClearDepthf = reinterpret_cast(gles2wLoad("glClearDepthf")); + glClearStencil = reinterpret_cast(gles2wLoad("glClearStencil")); + glColorMask = reinterpret_cast(gles2wLoad("glColorMask")); + glCompileShader = reinterpret_cast(gles2wLoad("glCompileShader")); + glCompressedTexImage2D = reinterpret_cast(gles2wLoad("glCompressedTexImage2D")); + glCompressedTexSubImage2D = reinterpret_cast(gles2wLoad("glCompressedTexSubImage2D")); + glCopyTexImage2D = reinterpret_cast(gles2wLoad("glCopyTexImage2D")); + glCopyTexSubImage2D = reinterpret_cast(gles2wLoad("glCopyTexSubImage2D")); + glCreateProgram = reinterpret_cast(gles2wLoad("glCreateProgram")); + glCreateShader = reinterpret_cast(gles2wLoad("glCreateShader")); + glCullFace = reinterpret_cast(gles2wLoad("glCullFace")); + glDeleteBuffers = reinterpret_cast(gles2wLoad("glDeleteBuffers")); + glDeleteFramebuffers = reinterpret_cast(gles2wLoad("glDeleteFramebuffers")); + glDeleteProgram = reinterpret_cast(gles2wLoad("glDeleteProgram")); + glDeleteRenderbuffers = reinterpret_cast(gles2wLoad("glDeleteRenderbuffers")); + glDeleteShader = reinterpret_cast(gles2wLoad("glDeleteShader")); + glDeleteTextures = reinterpret_cast(gles2wLoad("glDeleteTextures")); + glDepthFunc = reinterpret_cast(gles2wLoad("glDepthFunc")); + glDepthMask = reinterpret_cast(gles2wLoad("glDepthMask")); + glDepthRangef = reinterpret_cast(gles2wLoad("glDepthRangef")); + glDetachShader = reinterpret_cast(gles2wLoad("glDetachShader")); + glDisable = reinterpret_cast(gles2wLoad("glDisable")); + glDisableVertexAttribArray = reinterpret_cast(gles2wLoad("glDisableVertexAttribArray")); + glDrawArrays = reinterpret_cast(gles2wLoad("glDrawArrays")); + glDrawElements = reinterpret_cast(gles2wLoad("glDrawElements")); + glEnable = reinterpret_cast(gles2wLoad("glEnable")); + glEnableVertexAttribArray = reinterpret_cast(gles2wLoad("glEnableVertexAttribArray")); + glFinish = reinterpret_cast(gles2wLoad("glFinish")); + glFlush = reinterpret_cast(gles2wLoad("glFlush")); + glFramebufferRenderbuffer = reinterpret_cast(gles2wLoad("glFramebufferRenderbuffer")); + glFramebufferTexture2D = reinterpret_cast(gles2wLoad("glFramebufferTexture2D")); + glFrontFace = reinterpret_cast(gles2wLoad("glFrontFace")); + glGenBuffers = reinterpret_cast(gles2wLoad("glGenBuffers")); + glGenerateMipmap = reinterpret_cast(gles2wLoad("glGenerateMipmap")); + glGenFramebuffers = reinterpret_cast(gles2wLoad("glGenFramebuffers")); + glGenRenderbuffers = reinterpret_cast(gles2wLoad("glGenRenderbuffers")); + glGenTextures = reinterpret_cast(gles2wLoad("glGenTextures")); + glGetActiveAttrib = reinterpret_cast(gles2wLoad("glGetActiveAttrib")); + glGetActiveUniform = reinterpret_cast(gles2wLoad("glGetActiveUniform")); + glGetAttachedShaders = reinterpret_cast(gles2wLoad("glGetAttachedShaders")); + glGetAttribLocation = reinterpret_cast(gles2wLoad("glGetAttribLocation")); + glGetBooleanv = reinterpret_cast(gles2wLoad("glGetBooleanv")); + glGetBufferParameteriv = reinterpret_cast(gles2wLoad("glGetBufferParameteriv")); + glGetError = reinterpret_cast(gles2wLoad("glGetError")); + glGetFloatv = reinterpret_cast(gles2wLoad("glGetFloatv")); glGetFramebufferAttachmentParameteriv = reinterpret_cast(gles2wLoad("glGetFramebufferAttachmentParameteriv")); - glGetIntegerv = reinterpret_cast(gles2wLoad("glGetIntegerv")); - glGetProgramiv = reinterpret_cast(gles2wLoad("glGetProgramiv")); - glGetProgramInfoLog = reinterpret_cast(gles2wLoad("glGetProgramInfoLog")); - glGetRenderbufferParameteriv = reinterpret_cast(gles2wLoad("glGetRenderbufferParameteriv")); - glGetShaderiv = reinterpret_cast(gles2wLoad("glGetShaderiv")); - glGetShaderInfoLog = reinterpret_cast(gles2wLoad("glGetShaderInfoLog")); - glGetShaderPrecisionFormat = reinterpret_cast(gles2wLoad("glGetShaderPrecisionFormat")); - glGetShaderSource = reinterpret_cast(gles2wLoad("glGetShaderSource")); - glGetString = reinterpret_cast(gles2wLoad("glGetString")); - glGetTexParameterfv = reinterpret_cast(gles2wLoad("glGetTexParameterfv")); - glGetTexParameteriv = reinterpret_cast(gles2wLoad("glGetTexParameteriv")); - glGetUniformfv = reinterpret_cast(gles2wLoad("glGetUniformfv")); - glGetUniformiv = reinterpret_cast(gles2wLoad("glGetUniformiv")); - glGetUniformLocation = reinterpret_cast(gles2wLoad("glGetUniformLocation")); - glGetVertexAttribfv = reinterpret_cast(gles2wLoad("glGetVertexAttribfv")); - glGetVertexAttribiv = reinterpret_cast(gles2wLoad("glGetVertexAttribiv")); - glGetVertexAttribPointerv = reinterpret_cast(gles2wLoad("glGetVertexAttribPointerv")); - glHint = reinterpret_cast(gles2wLoad("glHint")); - glIsBuffer = reinterpret_cast(gles2wLoad("glIsBuffer")); - glIsEnabled = reinterpret_cast(gles2wLoad("glIsEnabled")); - glIsFramebuffer = reinterpret_cast(gles2wLoad("glIsFramebuffer")); - glIsProgram = reinterpret_cast(gles2wLoad("glIsProgram")); - glIsRenderbuffer = reinterpret_cast(gles2wLoad("glIsRenderbuffer")); - glIsShader = reinterpret_cast(gles2wLoad("glIsShader")); - glIsTexture = reinterpret_cast(gles2wLoad("glIsTexture")); - glLineWidth = reinterpret_cast(gles2wLoad("glLineWidth")); - glLinkProgram = reinterpret_cast(gles2wLoad("glLinkProgram")); - glPixelStorei = reinterpret_cast(gles2wLoad("glPixelStorei")); - glPolygonOffset = reinterpret_cast(gles2wLoad("glPolygonOffset")); - glReadPixels = reinterpret_cast(gles2wLoad("glReadPixels")); - glReleaseShaderCompiler = reinterpret_cast(gles2wLoad("glReleaseShaderCompiler")); - glRenderbufferStorage = reinterpret_cast(gles2wLoad("glRenderbufferStorage")); - glSampleCoverage = reinterpret_cast(gles2wLoad("glSampleCoverage")); - glScissor = reinterpret_cast(gles2wLoad("glScissor")); - glShaderBinary = reinterpret_cast(gles2wLoad("glShaderBinary")); - glShaderSource = reinterpret_cast(gles2wLoad("glShaderSource")); - glStencilFunc = reinterpret_cast(gles2wLoad("glStencilFunc")); - glStencilFuncSeparate = reinterpret_cast(gles2wLoad("glStencilFuncSeparate")); - glStencilMask = reinterpret_cast(gles2wLoad("glStencilMask")); - glStencilMaskSeparate = reinterpret_cast(gles2wLoad("glStencilMaskSeparate")); - glStencilOp = reinterpret_cast(gles2wLoad("glStencilOp")); - glStencilOpSeparate = reinterpret_cast(gles2wLoad("glStencilOpSeparate")); - glTexImage2D = reinterpret_cast(gles2wLoad("glTexImage2D")); - glTexParameterf = reinterpret_cast(gles2wLoad("glTexParameterf")); - glTexParameterfv = reinterpret_cast(gles2wLoad("glTexParameterfv")); - glTexParameteri = reinterpret_cast(gles2wLoad("glTexParameteri")); - glTexParameteriv = reinterpret_cast(gles2wLoad("glTexParameteriv")); - glTexSubImage2D = reinterpret_cast(gles2wLoad("glTexSubImage2D")); - glUniform1f = reinterpret_cast(gles2wLoad("glUniform1f")); - glUniform1fv = reinterpret_cast(gles2wLoad("glUniform1fv")); - glUniform1i = reinterpret_cast(gles2wLoad("glUniform1i")); - glUniform1iv = reinterpret_cast(gles2wLoad("glUniform1iv")); - glUniform2f = reinterpret_cast(gles2wLoad("glUniform2f")); - glUniform2fv = reinterpret_cast(gles2wLoad("glUniform2fv")); - glUniform2i = reinterpret_cast(gles2wLoad("glUniform2i")); - glUniform2iv = reinterpret_cast(gles2wLoad("glUniform2iv")); - glUniform3f = reinterpret_cast(gles2wLoad("glUniform3f")); - glUniform3fv = reinterpret_cast(gles2wLoad("glUniform3fv")); - glUniform3i = reinterpret_cast(gles2wLoad("glUniform3i")); - glUniform3iv = reinterpret_cast(gles2wLoad("glUniform3iv")); - glUniform4f = reinterpret_cast(gles2wLoad("glUniform4f")); - glUniform4fv = reinterpret_cast(gles2wLoad("glUniform4fv")); - glUniform4i = reinterpret_cast(gles2wLoad("glUniform4i")); - glUniform4iv = reinterpret_cast(gles2wLoad("glUniform4iv")); - glUniformMatrix2fv = reinterpret_cast(gles2wLoad("glUniformMatrix2fv")); - glUniformMatrix3fv = reinterpret_cast(gles2wLoad("glUniformMatrix3fv")); - glUniformMatrix4fv = reinterpret_cast(gles2wLoad("glUniformMatrix4fv")); - glUseProgram = reinterpret_cast(gles2wLoad("glUseProgram")); - glValidateProgram = reinterpret_cast(gles2wLoad("glValidateProgram")); - glVertexAttrib1f = reinterpret_cast(gles2wLoad("glVertexAttrib1f")); - glVertexAttrib1fv = reinterpret_cast(gles2wLoad("glVertexAttrib1fv")); - glVertexAttrib2f = reinterpret_cast(gles2wLoad("glVertexAttrib2f")); - glVertexAttrib2fv = reinterpret_cast(gles2wLoad("glVertexAttrib2fv")); - glVertexAttrib3f = reinterpret_cast(gles2wLoad("glVertexAttrib3f")); - glVertexAttrib3fv = reinterpret_cast(gles2wLoad("glVertexAttrib3fv")); - glVertexAttrib4f = reinterpret_cast(gles2wLoad("glVertexAttrib4f")); - glVertexAttrib4fv = reinterpret_cast(gles2wLoad("glVertexAttrib4fv")); - glVertexAttribPointer = reinterpret_cast(gles2wLoad("glVertexAttribPointer")); - glViewport = reinterpret_cast(gles2wLoad("glViewport")); + glGetIntegerv = reinterpret_cast(gles2wLoad("glGetIntegerv")); + glGetProgramiv = reinterpret_cast(gles2wLoad("glGetProgramiv")); + glGetProgramInfoLog = reinterpret_cast(gles2wLoad("glGetProgramInfoLog")); + glGetRenderbufferParameteriv = reinterpret_cast(gles2wLoad("glGetRenderbufferParameteriv")); + glGetShaderiv = reinterpret_cast(gles2wLoad("glGetShaderiv")); + glGetShaderInfoLog = reinterpret_cast(gles2wLoad("glGetShaderInfoLog")); + glGetShaderPrecisionFormat = reinterpret_cast(gles2wLoad("glGetShaderPrecisionFormat")); + glGetShaderSource = reinterpret_cast(gles2wLoad("glGetShaderSource")); + glGetString = reinterpret_cast(gles2wLoad("glGetString")); + glGetTexParameterfv = reinterpret_cast(gles2wLoad("glGetTexParameterfv")); + glGetTexParameteriv = reinterpret_cast(gles2wLoad("glGetTexParameteriv")); + glGetUniformfv = reinterpret_cast(gles2wLoad("glGetUniformfv")); + glGetUniformiv = reinterpret_cast(gles2wLoad("glGetUniformiv")); + glGetUniformLocation = reinterpret_cast(gles2wLoad("glGetUniformLocation")); + glGetVertexAttribfv = reinterpret_cast(gles2wLoad("glGetVertexAttribfv")); + glGetVertexAttribiv = reinterpret_cast(gles2wLoad("glGetVertexAttribiv")); + glGetVertexAttribPointerv = reinterpret_cast(gles2wLoad("glGetVertexAttribPointerv")); + glHint = reinterpret_cast(gles2wLoad("glHint")); + glIsBuffer = reinterpret_cast(gles2wLoad("glIsBuffer")); + glIsEnabled = reinterpret_cast(gles2wLoad("glIsEnabled")); + glIsFramebuffer = reinterpret_cast(gles2wLoad("glIsFramebuffer")); + glIsProgram = reinterpret_cast(gles2wLoad("glIsProgram")); + glIsRenderbuffer = reinterpret_cast(gles2wLoad("glIsRenderbuffer")); + glIsShader = reinterpret_cast(gles2wLoad("glIsShader")); + glIsTexture = reinterpret_cast(gles2wLoad("glIsTexture")); + glLineWidth = reinterpret_cast(gles2wLoad("glLineWidth")); + glLinkProgram = reinterpret_cast(gles2wLoad("glLinkProgram")); + glPixelStorei = reinterpret_cast(gles2wLoad("glPixelStorei")); + glPolygonOffset = reinterpret_cast(gles2wLoad("glPolygonOffset")); + glReadPixels = reinterpret_cast(gles2wLoad("glReadPixels")); + glReleaseShaderCompiler = reinterpret_cast(gles2wLoad("glReleaseShaderCompiler")); + glRenderbufferStorage = reinterpret_cast(gles2wLoad("glRenderbufferStorage")); + glSampleCoverage = reinterpret_cast(gles2wLoad("glSampleCoverage")); + glScissor = reinterpret_cast(gles2wLoad("glScissor")); + glShaderBinary = reinterpret_cast(gles2wLoad("glShaderBinary")); + glShaderSource = reinterpret_cast(gles2wLoad("glShaderSource")); + glStencilFunc = reinterpret_cast(gles2wLoad("glStencilFunc")); + glStencilFuncSeparate = reinterpret_cast(gles2wLoad("glStencilFuncSeparate")); + glStencilMask = reinterpret_cast(gles2wLoad("glStencilMask")); + glStencilMaskSeparate = reinterpret_cast(gles2wLoad("glStencilMaskSeparate")); + glStencilOp = reinterpret_cast(gles2wLoad("glStencilOp")); + glStencilOpSeparate = reinterpret_cast(gles2wLoad("glStencilOpSeparate")); + glTexImage2D = reinterpret_cast(gles2wLoad("glTexImage2D")); + glTexParameterf = reinterpret_cast(gles2wLoad("glTexParameterf")); + glTexParameterfv = reinterpret_cast(gles2wLoad("glTexParameterfv")); + glTexParameteri = reinterpret_cast(gles2wLoad("glTexParameteri")); + glTexParameteriv = reinterpret_cast(gles2wLoad("glTexParameteriv")); + glTexSubImage2D = reinterpret_cast(gles2wLoad("glTexSubImage2D")); + glUniform1f = reinterpret_cast(gles2wLoad("glUniform1f")); + glUniform1fv = reinterpret_cast(gles2wLoad("glUniform1fv")); + glUniform1i = reinterpret_cast(gles2wLoad("glUniform1i")); + glUniform1iv = reinterpret_cast(gles2wLoad("glUniform1iv")); + glUniform2f = reinterpret_cast(gles2wLoad("glUniform2f")); + glUniform2fv = reinterpret_cast(gles2wLoad("glUniform2fv")); + glUniform2i = reinterpret_cast(gles2wLoad("glUniform2i")); + glUniform2iv = reinterpret_cast(gles2wLoad("glUniform2iv")); + glUniform3f = reinterpret_cast(gles2wLoad("glUniform3f")); + glUniform3fv = reinterpret_cast(gles2wLoad("glUniform3fv")); + glUniform3i = reinterpret_cast(gles2wLoad("glUniform3i")); + glUniform3iv = reinterpret_cast(gles2wLoad("glUniform3iv")); + glUniform4f = reinterpret_cast(gles2wLoad("glUniform4f")); + glUniform4fv = reinterpret_cast(gles2wLoad("glUniform4fv")); + glUniform4i = reinterpret_cast(gles2wLoad("glUniform4i")); + glUniform4iv = reinterpret_cast(gles2wLoad("glUniform4iv")); + glUniformMatrix2fv = reinterpret_cast(gles2wLoad("glUniformMatrix2fv")); + glUniformMatrix3fv = reinterpret_cast(gles2wLoad("glUniformMatrix3fv")); + glUniformMatrix4fv = reinterpret_cast(gles2wLoad("glUniformMatrix4fv")); + glUseProgram = reinterpret_cast(gles2wLoad("glUseProgram")); + glValidateProgram = reinterpret_cast(gles2wLoad("glValidateProgram")); + glVertexAttrib1f = reinterpret_cast(gles2wLoad("glVertexAttrib1f")); + glVertexAttrib1fv = reinterpret_cast(gles2wLoad("glVertexAttrib1fv")); + glVertexAttrib2f = reinterpret_cast(gles2wLoad("glVertexAttrib2f")); + glVertexAttrib2fv = reinterpret_cast(gles2wLoad("glVertexAttrib2fv")); + glVertexAttrib3f = reinterpret_cast(gles2wLoad("glVertexAttrib3f")); + glVertexAttrib3fv = reinterpret_cast(gles2wLoad("glVertexAttrib3fv")); + glVertexAttrib4f = reinterpret_cast(gles2wLoad("glVertexAttrib4f")); + glVertexAttrib4fv = reinterpret_cast(gles2wLoad("glVertexAttrib4fv")); + glVertexAttribPointer = reinterpret_cast(gles2wLoad("glVertexAttribPointer")); + glViewport = reinterpret_cast(gles2wLoad("glViewport")); #if defined(GL_AMD_framebuffer_multisample_advanced) - glRenderbufferStorageMultisampleAdvancedAMD = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleAdvancedAMD")); + glRenderbufferStorageMultisampleAdvancedAMD = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleAdvancedAMD")); glNamedRenderbufferStorageMultisampleAdvancedAMD = reinterpret_cast(gles2wLoad("glNamedRenderbufferStorageMultisampleAdvancedAMD")); #endif /* defined(GL_AMD_framebuffer_multisample_advanced) */ #if defined(GL_AMD_performance_monitor) - glGetPerfMonitorGroupsAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorGroupsAMD")); - glGetPerfMonitorCountersAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCountersAMD")); - glGetPerfMonitorGroupStringAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorGroupStringAMD")); + glGetPerfMonitorGroupsAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorGroupsAMD")); + glGetPerfMonitorCountersAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCountersAMD")); + glGetPerfMonitorGroupStringAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorGroupStringAMD")); glGetPerfMonitorCounterStringAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCounterStringAMD")); - glGetPerfMonitorCounterInfoAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCounterInfoAMD")); - glGenPerfMonitorsAMD = reinterpret_cast(gles2wLoad("glGenPerfMonitorsAMD")); - glDeletePerfMonitorsAMD = reinterpret_cast(gles2wLoad("glDeletePerfMonitorsAMD")); - glSelectPerfMonitorCountersAMD = reinterpret_cast(gles2wLoad("glSelectPerfMonitorCountersAMD")); - glBeginPerfMonitorAMD = reinterpret_cast(gles2wLoad("glBeginPerfMonitorAMD")); - glEndPerfMonitorAMD = reinterpret_cast(gles2wLoad("glEndPerfMonitorAMD")); - glGetPerfMonitorCounterDataAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCounterDataAMD")); + glGetPerfMonitorCounterInfoAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCounterInfoAMD")); + glGenPerfMonitorsAMD = reinterpret_cast(gles2wLoad("glGenPerfMonitorsAMD")); + glDeletePerfMonitorsAMD = reinterpret_cast(gles2wLoad("glDeletePerfMonitorsAMD")); + glSelectPerfMonitorCountersAMD = reinterpret_cast(gles2wLoad("glSelectPerfMonitorCountersAMD")); + glBeginPerfMonitorAMD = reinterpret_cast(gles2wLoad("glBeginPerfMonitorAMD")); + glEndPerfMonitorAMD = reinterpret_cast(gles2wLoad("glEndPerfMonitorAMD")); + glGetPerfMonitorCounterDataAMD = reinterpret_cast(gles2wLoad("glGetPerfMonitorCounterDataAMD")); #endif /* defined(GL_AMD_performance_monitor) */ #if defined(GL_ANGLE_framebuffer_blit) @@ -1296,9 +1296,9 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_ANGLE_framebuffer_multisample) */ #if defined(GL_ANGLE_instanced_arrays) - glDrawArraysInstancedANGLE = reinterpret_cast(gles2wLoad("glDrawArraysInstancedANGLE")); + glDrawArraysInstancedANGLE = reinterpret_cast(gles2wLoad("glDrawArraysInstancedANGLE")); glDrawElementsInstancedANGLE = reinterpret_cast(gles2wLoad("glDrawElementsInstancedANGLE")); - glVertexAttribDivisorANGLE = reinterpret_cast(gles2wLoad("glVertexAttribDivisorANGLE")); + glVertexAttribDivisorANGLE = reinterpret_cast(gles2wLoad("glVertexAttribDivisorANGLE")); #endif /* defined(GL_ANGLE_instanced_arrays) */ #if defined(GL_ANGLE_translated_shader_source) @@ -1311,17 +1311,17 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_APPLE_framebuffer_multisample) glRenderbufferStorageMultisampleAPPLE = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleAPPLE")); - glResolveMultisampleFramebufferAPPLE = reinterpret_cast(gles2wLoad("glResolveMultisampleFramebufferAPPLE")); + glResolveMultisampleFramebufferAPPLE = reinterpret_cast(gles2wLoad("glResolveMultisampleFramebufferAPPLE")); #endif /* defined(GL_APPLE_framebuffer_multisample) */ #if defined(GL_APPLE_sync) - glFenceSyncAPPLE = reinterpret_cast(gles2wLoad("glFenceSyncAPPLE")); - glIsSyncAPPLE = reinterpret_cast(gles2wLoad("glIsSyncAPPLE")); - glDeleteSyncAPPLE = reinterpret_cast(gles2wLoad("glDeleteSyncAPPLE")); + glFenceSyncAPPLE = reinterpret_cast(gles2wLoad("glFenceSyncAPPLE")); + glIsSyncAPPLE = reinterpret_cast(gles2wLoad("glIsSyncAPPLE")); + glDeleteSyncAPPLE = reinterpret_cast(gles2wLoad("glDeleteSyncAPPLE")); glClientWaitSyncAPPLE = reinterpret_cast(gles2wLoad("glClientWaitSyncAPPLE")); - glWaitSyncAPPLE = reinterpret_cast(gles2wLoad("glWaitSyncAPPLE")); - glGetInteger64vAPPLE = reinterpret_cast(gles2wLoad("glGetInteger64vAPPLE")); - glGetSyncivAPPLE = reinterpret_cast(gles2wLoad("glGetSyncivAPPLE")); + glWaitSyncAPPLE = reinterpret_cast(gles2wLoad("glWaitSyncAPPLE")); + glGetInteger64vAPPLE = reinterpret_cast(gles2wLoad("glGetInteger64vAPPLE")); + glGetSyncivAPPLE = reinterpret_cast(gles2wLoad("glGetSyncivAPPLE")); #endif /* defined(GL_APPLE_sync) */ #if defined(GL_EXT_EGL_image_storage) @@ -1331,16 +1331,16 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_EGL_image_storage) */ #if defined(GL_EXT_base_instance) - glDrawArraysInstancedBaseInstanceEXT = reinterpret_cast(gles2wLoad("glDrawArraysInstancedBaseInstanceEXT")); - glDrawElementsInstancedBaseInstanceEXT = reinterpret_cast(gles2wLoad("glDrawElementsInstancedBaseInstanceEXT")); + glDrawArraysInstancedBaseInstanceEXT = reinterpret_cast(gles2wLoad("glDrawArraysInstancedBaseInstanceEXT")); + glDrawElementsInstancedBaseInstanceEXT = reinterpret_cast(gles2wLoad("glDrawElementsInstancedBaseInstanceEXT")); glDrawElementsInstancedBaseVertexBaseInstanceEXT = reinterpret_cast(gles2wLoad("glDrawElementsInstancedBaseVertexBaseInstanceEXT")); #endif /* defined(GL_EXT_base_instance) */ #if defined(GL_EXT_blend_func_extended) - glBindFragDataLocationIndexedEXT = reinterpret_cast(gles2wLoad("glBindFragDataLocationIndexedEXT")); - glBindFragDataLocationEXT = reinterpret_cast(gles2wLoad("glBindFragDataLocationEXT")); + glBindFragDataLocationIndexedEXT = reinterpret_cast(gles2wLoad("glBindFragDataLocationIndexedEXT")); + glBindFragDataLocationEXT = reinterpret_cast(gles2wLoad("glBindFragDataLocationEXT")); glGetProgramResourceLocationIndexEXT = reinterpret_cast(gles2wLoad("glGetProgramResourceLocationIndexEXT")); - glGetFragDataIndexEXT = reinterpret_cast(gles2wLoad("glGetFragDataIndexEXT")); + glGetFragDataIndexEXT = reinterpret_cast(gles2wLoad("glGetFragDataIndexEXT")); #endif /* defined(GL_EXT_blend_func_extended) */ #if defined(GL_EXT_buffer_storage) @@ -1348,7 +1348,7 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_buffer_storage) */ #if defined(GL_EXT_clear_texture) - glClearTexImageEXT = reinterpret_cast(gles2wLoad("glClearTexImageEXT")); + glClearTexImageEXT = reinterpret_cast(gles2wLoad("glClearTexImageEXT")); glClearTexSubImageEXT = reinterpret_cast(gles2wLoad("glClearTexSubImageEXT")); #endif /* defined(GL_EXT_clear_texture) */ @@ -1361,14 +1361,14 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_copy_image) */ #if defined(GL_EXT_debug_label) - glLabelObjectEXT = reinterpret_cast(gles2wLoad("glLabelObjectEXT")); + glLabelObjectEXT = reinterpret_cast(gles2wLoad("glLabelObjectEXT")); glGetObjectLabelEXT = reinterpret_cast(gles2wLoad("glGetObjectLabelEXT")); #endif /* defined(GL_EXT_debug_label) */ #if defined(GL_EXT_debug_marker) glInsertEventMarkerEXT = reinterpret_cast(gles2wLoad("glInsertEventMarkerEXT")); - glPushGroupMarkerEXT = reinterpret_cast(gles2wLoad("glPushGroupMarkerEXT")); - glPopGroupMarkerEXT = reinterpret_cast(gles2wLoad("glPopGroupMarkerEXT")); + glPushGroupMarkerEXT = reinterpret_cast(gles2wLoad("glPushGroupMarkerEXT")); + glPopGroupMarkerEXT = reinterpret_cast(gles2wLoad("glPopGroupMarkerEXT")); #endif /* defined(GL_EXT_debug_marker) */ #if defined(GL_EXT_discard_framebuffer) @@ -1376,18 +1376,18 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_discard_framebuffer) */ #if defined(GL_EXT_disjoint_timer_query) - glGenQueriesEXT = reinterpret_cast(gles2wLoad("glGenQueriesEXT")); - glDeleteQueriesEXT = reinterpret_cast(gles2wLoad("glDeleteQueriesEXT")); - glIsQueryEXT = reinterpret_cast(gles2wLoad("glIsQueryEXT")); - glBeginQueryEXT = reinterpret_cast(gles2wLoad("glBeginQueryEXT")); - glEndQueryEXT = reinterpret_cast(gles2wLoad("glEndQueryEXT")); - glQueryCounterEXT = reinterpret_cast(gles2wLoad("glQueryCounterEXT")); - glGetQueryivEXT = reinterpret_cast(gles2wLoad("glGetQueryivEXT")); - glGetQueryObjectivEXT = reinterpret_cast(gles2wLoad("glGetQueryObjectivEXT")); - glGetQueryObjectuivEXT = reinterpret_cast(gles2wLoad("glGetQueryObjectuivEXT")); - glGetQueryObjecti64vEXT = reinterpret_cast(gles2wLoad("glGetQueryObjecti64vEXT")); + glGenQueriesEXT = reinterpret_cast(gles2wLoad("glGenQueriesEXT")); + glDeleteQueriesEXT = reinterpret_cast(gles2wLoad("glDeleteQueriesEXT")); + glIsQueryEXT = reinterpret_cast(gles2wLoad("glIsQueryEXT")); + glBeginQueryEXT = reinterpret_cast(gles2wLoad("glBeginQueryEXT")); + glEndQueryEXT = reinterpret_cast(gles2wLoad("glEndQueryEXT")); + glQueryCounterEXT = reinterpret_cast(gles2wLoad("glQueryCounterEXT")); + glGetQueryivEXT = reinterpret_cast(gles2wLoad("glGetQueryivEXT")); + glGetQueryObjectivEXT = reinterpret_cast(gles2wLoad("glGetQueryObjectivEXT")); + glGetQueryObjectuivEXT = reinterpret_cast(gles2wLoad("glGetQueryObjectuivEXT")); + glGetQueryObjecti64vEXT = reinterpret_cast(gles2wLoad("glGetQueryObjecti64vEXT")); glGetQueryObjectui64vEXT = reinterpret_cast(gles2wLoad("glGetQueryObjectui64vEXT")); - glGetInteger64vEXT = reinterpret_cast(gles2wLoad("glGetInteger64vEXT")); + glGetInteger64vEXT = reinterpret_cast(gles2wLoad("glGetInteger64vEXT")); #endif /* defined(GL_EXT_disjoint_timer_query) */ #if defined(GL_EXT_draw_buffers) @@ -1395,35 +1395,35 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_draw_buffers) */ #if defined(GL_EXT_draw_buffers_indexed) - glEnableiEXT = reinterpret_cast(gles2wLoad("glEnableiEXT")); - glDisableiEXT = reinterpret_cast(gles2wLoad("glDisableiEXT")); - glBlendEquationiEXT = reinterpret_cast(gles2wLoad("glBlendEquationiEXT")); + glEnableiEXT = reinterpret_cast(gles2wLoad("glEnableiEXT")); + glDisableiEXT = reinterpret_cast(gles2wLoad("glDisableiEXT")); + glBlendEquationiEXT = reinterpret_cast(gles2wLoad("glBlendEquationiEXT")); glBlendEquationSeparateiEXT = reinterpret_cast(gles2wLoad("glBlendEquationSeparateiEXT")); - glBlendFunciEXT = reinterpret_cast(gles2wLoad("glBlendFunciEXT")); - glBlendFuncSeparateiEXT = reinterpret_cast(gles2wLoad("glBlendFuncSeparateiEXT")); - glColorMaskiEXT = reinterpret_cast(gles2wLoad("glColorMaskiEXT")); - glIsEnablediEXT = reinterpret_cast(gles2wLoad("glIsEnablediEXT")); + glBlendFunciEXT = reinterpret_cast(gles2wLoad("glBlendFunciEXT")); + glBlendFuncSeparateiEXT = reinterpret_cast(gles2wLoad("glBlendFuncSeparateiEXT")); + glColorMaskiEXT = reinterpret_cast(gles2wLoad("glColorMaskiEXT")); + glIsEnablediEXT = reinterpret_cast(gles2wLoad("glIsEnablediEXT")); #endif /* defined(GL_EXT_draw_buffers_indexed) */ #if defined(GL_EXT_draw_elements_base_vertex) - glDrawElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glDrawElementsBaseVertexEXT")); - glDrawRangeElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glDrawRangeElementsBaseVertexEXT")); + glDrawElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glDrawElementsBaseVertexEXT")); + glDrawRangeElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glDrawRangeElementsBaseVertexEXT")); glDrawElementsInstancedBaseVertexEXT = reinterpret_cast(gles2wLoad("glDrawElementsInstancedBaseVertexEXT")); - glMultiDrawElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glMultiDrawElementsBaseVertexEXT")); + glMultiDrawElementsBaseVertexEXT = reinterpret_cast(gles2wLoad("glMultiDrawElementsBaseVertexEXT")); #endif /* defined(GL_EXT_draw_elements_base_vertex) */ #if defined(GL_EXT_draw_instanced) - glDrawArraysInstancedEXT = reinterpret_cast(gles2wLoad("glDrawArraysInstancedEXT")); + glDrawArraysInstancedEXT = reinterpret_cast(gles2wLoad("glDrawArraysInstancedEXT")); glDrawElementsInstancedEXT = reinterpret_cast(gles2wLoad("glDrawElementsInstancedEXT")); #endif /* defined(GL_EXT_draw_instanced) */ #if defined(GL_EXT_draw_transform_feedback) - glDrawTransformFeedbackEXT = reinterpret_cast(gles2wLoad("glDrawTransformFeedbackEXT")); + glDrawTransformFeedbackEXT = reinterpret_cast(gles2wLoad("glDrawTransformFeedbackEXT")); glDrawTransformFeedbackInstancedEXT = reinterpret_cast(gles2wLoad("glDrawTransformFeedbackInstancedEXT")); #endif /* defined(GL_EXT_draw_transform_feedback) */ #if defined(GL_EXT_external_buffer) - glBufferStorageExternalEXT = reinterpret_cast(gles2wLoad("glBufferStorageExternalEXT")); + glBufferStorageExternalEXT = reinterpret_cast(gles2wLoad("glBufferStorageExternalEXT")); glNamedBufferStorageExternalEXT = reinterpret_cast(gles2wLoad("glNamedBufferStorageExternalEXT")); #endif /* defined(GL_EXT_external_buffer) */ @@ -1436,29 +1436,29 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_instanced_arrays) */ #if defined(GL_EXT_map_buffer_range) - glMapBufferRangeEXT = reinterpret_cast(gles2wLoad("glMapBufferRangeEXT")); + glMapBufferRangeEXT = reinterpret_cast(gles2wLoad("glMapBufferRangeEXT")); glFlushMappedBufferRangeEXT = reinterpret_cast(gles2wLoad("glFlushMappedBufferRangeEXT")); #endif /* defined(GL_EXT_map_buffer_range) */ #if defined(GL_EXT_memory_object) - glGetUnsignedBytevEXT = reinterpret_cast(gles2wLoad("glGetUnsignedBytevEXT")); - glGetUnsignedBytei_vEXT = reinterpret_cast(gles2wLoad("glGetUnsignedBytei_vEXT")); - glDeleteMemoryObjectsEXT = reinterpret_cast(gles2wLoad("glDeleteMemoryObjectsEXT")); - glIsMemoryObjectEXT = reinterpret_cast(gles2wLoad("glIsMemoryObjectEXT")); - glCreateMemoryObjectsEXT = reinterpret_cast(gles2wLoad("glCreateMemoryObjectsEXT")); - glMemoryObjectParameterivEXT = reinterpret_cast(gles2wLoad("glMemoryObjectParameterivEXT")); + glGetUnsignedBytevEXT = reinterpret_cast(gles2wLoad("glGetUnsignedBytevEXT")); + glGetUnsignedBytei_vEXT = reinterpret_cast(gles2wLoad("glGetUnsignedBytei_vEXT")); + glDeleteMemoryObjectsEXT = reinterpret_cast(gles2wLoad("glDeleteMemoryObjectsEXT")); + glIsMemoryObjectEXT = reinterpret_cast(gles2wLoad("glIsMemoryObjectEXT")); + glCreateMemoryObjectsEXT = reinterpret_cast(gles2wLoad("glCreateMemoryObjectsEXT")); + glMemoryObjectParameterivEXT = reinterpret_cast(gles2wLoad("glMemoryObjectParameterivEXT")); glGetMemoryObjectParameterivEXT = reinterpret_cast(gles2wLoad("glGetMemoryObjectParameterivEXT")); - glTexStorageMem2DEXT = reinterpret_cast(gles2wLoad("glTexStorageMem2DEXT")); + glTexStorageMem2DEXT = reinterpret_cast(gles2wLoad("glTexStorageMem2DEXT")); glTexStorageMem2DMultisampleEXT = reinterpret_cast(gles2wLoad("glTexStorageMem2DMultisampleEXT")); - glTexStorageMem3DEXT = reinterpret_cast(gles2wLoad("glTexStorageMem3DEXT")); + glTexStorageMem3DEXT = reinterpret_cast(gles2wLoad("glTexStorageMem3DEXT")); glTexStorageMem3DMultisampleEXT = reinterpret_cast(gles2wLoad("glTexStorageMem3DMultisampleEXT")); - glBufferStorageMemEXT = reinterpret_cast(gles2wLoad("glBufferStorageMemEXT")); + glBufferStorageMemEXT = reinterpret_cast(gles2wLoad("glBufferStorageMemEXT")); - glTextureStorageMem2DEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem2DEXT")); + glTextureStorageMem2DEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem2DEXT")); glTextureStorageMem2DMultisampleEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem2DMultisampleEXT")); - glTextureStorageMem3DEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem3DEXT")); + glTextureStorageMem3DEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem3DEXT")); glTextureStorageMem3DMultisampleEXT = reinterpret_cast(gles2wLoad("glTextureStorageMem3DMultisampleEXT")); - glNamedBufferStorageMemEXT = reinterpret_cast(gles2wLoad("glNamedBufferStorageMemEXT")); + glNamedBufferStorageMemEXT = reinterpret_cast(gles2wLoad("glNamedBufferStorageMemEXT")); #endif /* defined(GL_EXT_memory_object) */ #if defined(GL_EXT_memory_object_fd) @@ -1467,28 +1467,28 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_EXT_memory_object_win32) glImportMemoryWin32HandleEXT = reinterpret_cast(gles2wLoad("glImportMemoryWin32HandleEXT")); - glImportMemoryWin32NameEXT = reinterpret_cast(gles2wLoad("glImportMemoryWin32NameEXT")); + glImportMemoryWin32NameEXT = reinterpret_cast(gles2wLoad("glImportMemoryWin32NameEXT")); #endif /* defined(GL_EXT_memory_object_win32) */ #if defined(GL_EXT_multi_draw_arrays) - glMultiDrawArraysEXT = reinterpret_cast(gles2wLoad("glMultiDrawArraysEXT")); + glMultiDrawArraysEXT = reinterpret_cast(gles2wLoad("glMultiDrawArraysEXT")); glMultiDrawElementsEXT = reinterpret_cast(gles2wLoad("glMultiDrawElementsEXT")); #endif /* defined(GL_EXT_multi_draw_arrays) */ #if defined(GL_EXT_multi_draw_indirect) - glMultiDrawArraysIndirectEXT = reinterpret_cast(gles2wLoad("glMultiDrawArraysIndirectEXT")); + glMultiDrawArraysIndirectEXT = reinterpret_cast(gles2wLoad("glMultiDrawArraysIndirectEXT")); glMultiDrawElementsIndirectEXT = reinterpret_cast(gles2wLoad("glMultiDrawElementsIndirectEXT")); #endif /* defined(GL_EXT_multi_draw_indirect) */ #if defined(GL_EXT_multisampled_render_to_texture) - glRenderbufferStorageMultisampleEXT = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleEXT")); + glRenderbufferStorageMultisampleEXT = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleEXT")); glFramebufferTexture2DMultisampleEXT = reinterpret_cast(gles2wLoad("glFramebufferTexture2DMultisampleEXT")); #endif /* defined(GL_EXT_multisampled_render_to_texture) */ #if defined(GL_EXT_multiview_draw_buffers) - glReadBufferIndexedEXT = reinterpret_cast(gles2wLoad("glReadBufferIndexedEXT")); + glReadBufferIndexedEXT = reinterpret_cast(gles2wLoad("glReadBufferIndexedEXT")); glDrawBuffersIndexedEXT = reinterpret_cast(gles2wLoad("glDrawBuffersIndexedEXT")); - glGetIntegeri_vEXT = reinterpret_cast(gles2wLoad("glGetIntegeri_vEXT")); + glGetIntegeri_vEXT = reinterpret_cast(gles2wLoad("glGetIntegeri_vEXT")); #endif /* defined(GL_EXT_multiview_draw_buffers) */ #if defined(GL_EXT_polygon_offset_clamp) @@ -1505,19 +1505,19 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_EXT_robustness) glGetGraphicsResetStatusEXT = reinterpret_cast(gles2wLoad("glGetGraphicsResetStatusEXT")); - glReadnPixelsEXT = reinterpret_cast(gles2wLoad("glReadnPixelsEXT")); - glGetnUniformfvEXT = reinterpret_cast(gles2wLoad("glGetnUniformfvEXT")); - glGetnUniformivEXT = reinterpret_cast(gles2wLoad("glGetnUniformivEXT")); + glReadnPixelsEXT = reinterpret_cast(gles2wLoad("glReadnPixelsEXT")); + glGetnUniformfvEXT = reinterpret_cast(gles2wLoad("glGetnUniformfvEXT")); + glGetnUniformivEXT = reinterpret_cast(gles2wLoad("glGetnUniformivEXT")); #endif /* defined(GL_EXT_robustness) */ #if defined(GL_EXT_semaphore) - glGenSemaphoresEXT = reinterpret_cast(gles2wLoad("glGenSemaphoresEXT")); - glDeleteSemaphoresEXT = reinterpret_cast(gles2wLoad("glDeleteSemaphoresEXT")); - glIsSemaphoreEXT = reinterpret_cast(gles2wLoad("glIsSemaphoreEXT")); - glSemaphoreParameterui64vEXT = reinterpret_cast(gles2wLoad("glSemaphoreParameterui64vEXT")); + glGenSemaphoresEXT = reinterpret_cast(gles2wLoad("glGenSemaphoresEXT")); + glDeleteSemaphoresEXT = reinterpret_cast(gles2wLoad("glDeleteSemaphoresEXT")); + glIsSemaphoreEXT = reinterpret_cast(gles2wLoad("glIsSemaphoreEXT")); + glSemaphoreParameterui64vEXT = reinterpret_cast(gles2wLoad("glSemaphoreParameterui64vEXT")); glGetSemaphoreParameterui64vEXT = reinterpret_cast(gles2wLoad("glGetSemaphoreParameterui64vEXT")); - glWaitSemaphoreEXT = reinterpret_cast(gles2wLoad("glWaitSemaphoreEXT")); - glSignalSemaphoreEXT = reinterpret_cast(gles2wLoad("glSignalSemaphoreEXT")); + glWaitSemaphoreEXT = reinterpret_cast(gles2wLoad("glWaitSemaphoreEXT")); + glSignalSemaphoreEXT = reinterpret_cast(gles2wLoad("glSignalSemaphoreEXT")); #endif /* defined(GL_EXT_semaphore) */ #if defined(GL_EXT_semaphore_fd) @@ -1526,49 +1526,49 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_EXT_semaphore_win32) glImportSemaphoreWin32HandleEXT = reinterpret_cast(gles2wLoad("glImportSemaphoreWin32HandleEXT")); - glImportSemaphoreWin32NameEXT = reinterpret_cast(gles2wLoad("glImportSemaphoreWin32NameEXT")); + glImportSemaphoreWin32NameEXT = reinterpret_cast(gles2wLoad("glImportSemaphoreWin32NameEXT")); #endif /* defined(GL_EXT_semaphore_win32) */ #if defined(GL_EXT_separate_shader_objects) - glActiveShaderProgramEXT = reinterpret_cast(gles2wLoad("glActiveShaderProgramEXT")); - glBindProgramPipelineEXT = reinterpret_cast(gles2wLoad("glBindProgramPipelineEXT")); - glCreateShaderProgramvEXT = reinterpret_cast(gles2wLoad("glCreateShaderProgramvEXT")); - glDeleteProgramPipelinesEXT = reinterpret_cast(gles2wLoad("glDeleteProgramPipelinesEXT")); - glGenProgramPipelinesEXT = reinterpret_cast(gles2wLoad("glGenProgramPipelinesEXT")); + glActiveShaderProgramEXT = reinterpret_cast(gles2wLoad("glActiveShaderProgramEXT")); + glBindProgramPipelineEXT = reinterpret_cast(gles2wLoad("glBindProgramPipelineEXT")); + glCreateShaderProgramvEXT = reinterpret_cast(gles2wLoad("glCreateShaderProgramvEXT")); + glDeleteProgramPipelinesEXT = reinterpret_cast(gles2wLoad("glDeleteProgramPipelinesEXT")); + glGenProgramPipelinesEXT = reinterpret_cast(gles2wLoad("glGenProgramPipelinesEXT")); glGetProgramPipelineInfoLogEXT = reinterpret_cast(gles2wLoad("glGetProgramPipelineInfoLogEXT")); - glGetProgramPipelineivEXT = reinterpret_cast(gles2wLoad("glGetProgramPipelineivEXT")); - glIsProgramPipelineEXT = reinterpret_cast(gles2wLoad("glIsProgramPipelineEXT")); - glProgramParameteriEXT = reinterpret_cast(gles2wLoad("glProgramParameteriEXT")); - glProgramUniform1fEXT = reinterpret_cast(gles2wLoad("glProgramUniform1fEXT")); - glProgramUniform1fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform1fvEXT")); - glProgramUniform1iEXT = reinterpret_cast(gles2wLoad("glProgramUniform1iEXT")); - glProgramUniform1ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform1ivEXT")); - glProgramUniform2fEXT = reinterpret_cast(gles2wLoad("glProgramUniform2fEXT")); - glProgramUniform2fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform2fvEXT")); - glProgramUniform2iEXT = reinterpret_cast(gles2wLoad("glProgramUniform2iEXT")); - glProgramUniform2ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform2ivEXT")); - glProgramUniform3fEXT = reinterpret_cast(gles2wLoad("glProgramUniform3fEXT")); - glProgramUniform3fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform3fvEXT")); - glProgramUniform3iEXT = reinterpret_cast(gles2wLoad("glProgramUniform3iEXT")); - glProgramUniform3ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform3ivEXT")); - glProgramUniform4fEXT = reinterpret_cast(gles2wLoad("glProgramUniform4fEXT")); - glProgramUniform4fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform4fvEXT")); - glProgramUniform4iEXT = reinterpret_cast(gles2wLoad("glProgramUniform4iEXT")); - glProgramUniform4ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform4ivEXT")); - glProgramUniformMatrix2fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix2fvEXT")); - glProgramUniformMatrix3fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix3fvEXT")); - glProgramUniformMatrix4fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix4fvEXT")); - glUseProgramStagesEXT = reinterpret_cast(gles2wLoad("glUseProgramStagesEXT")); - glValidateProgramPipelineEXT = reinterpret_cast(gles2wLoad("glValidateProgramPipelineEXT")); + glGetProgramPipelineivEXT = reinterpret_cast(gles2wLoad("glGetProgramPipelineivEXT")); + glIsProgramPipelineEXT = reinterpret_cast(gles2wLoad("glIsProgramPipelineEXT")); + glProgramParameteriEXT = reinterpret_cast(gles2wLoad("glProgramParameteriEXT")); + glProgramUniform1fEXT = reinterpret_cast(gles2wLoad("glProgramUniform1fEXT")); + glProgramUniform1fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform1fvEXT")); + glProgramUniform1iEXT = reinterpret_cast(gles2wLoad("glProgramUniform1iEXT")); + glProgramUniform1ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform1ivEXT")); + glProgramUniform2fEXT = reinterpret_cast(gles2wLoad("glProgramUniform2fEXT")); + glProgramUniform2fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform2fvEXT")); + glProgramUniform2iEXT = reinterpret_cast(gles2wLoad("glProgramUniform2iEXT")); + glProgramUniform2ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform2ivEXT")); + glProgramUniform3fEXT = reinterpret_cast(gles2wLoad("glProgramUniform3fEXT")); + glProgramUniform3fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform3fvEXT")); + glProgramUniform3iEXT = reinterpret_cast(gles2wLoad("glProgramUniform3iEXT")); + glProgramUniform3ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform3ivEXT")); + glProgramUniform4fEXT = reinterpret_cast(gles2wLoad("glProgramUniform4fEXT")); + glProgramUniform4fvEXT = reinterpret_cast(gles2wLoad("glProgramUniform4fvEXT")); + glProgramUniform4iEXT = reinterpret_cast(gles2wLoad("glProgramUniform4iEXT")); + glProgramUniform4ivEXT = reinterpret_cast(gles2wLoad("glProgramUniform4ivEXT")); + glProgramUniformMatrix2fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix2fvEXT")); + glProgramUniformMatrix3fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix3fvEXT")); + glProgramUniformMatrix4fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix4fvEXT")); + glUseProgramStagesEXT = reinterpret_cast(gles2wLoad("glUseProgramStagesEXT")); + glValidateProgramPipelineEXT = reinterpret_cast(gles2wLoad("glValidateProgramPipelineEXT")); - glProgramUniform1uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform1uiEXT")); - glProgramUniform2uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform2uiEXT")); - glProgramUniform3uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform3uiEXT")); - glProgramUniform4uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform4uiEXT")); - glProgramUniform1uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform1uivEXT")); - glProgramUniform2uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform2uivEXT")); - glProgramUniform3uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform3uivEXT")); - glProgramUniform4uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform4uivEXT")); + glProgramUniform1uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform1uiEXT")); + glProgramUniform2uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform2uiEXT")); + glProgramUniform3uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform3uiEXT")); + glProgramUniform4uiEXT = reinterpret_cast(gles2wLoad("glProgramUniform4uiEXT")); + glProgramUniform1uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform1uivEXT")); + glProgramUniform2uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform2uivEXT")); + glProgramUniform3uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform3uivEXT")); + glProgramUniform4uivEXT = reinterpret_cast(gles2wLoad("glProgramUniform4uivEXT")); glProgramUniformMatrix2x3fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix2x3fvEXT")); glProgramUniformMatrix3x2fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix3x2fvEXT")); glProgramUniformMatrix2x4fvEXT = reinterpret_cast(gles2wLoad("glProgramUniformMatrix2x4fvEXT")); @@ -1582,9 +1582,9 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_shader_framebuffer_fetch_non_coherent) */ #if defined(GL_EXT_shader_pixel_local_storage2) - glFramebufferPixelLocalStorageSizeEXT = reinterpret_cast(gles2wLoad("glFramebufferPixelLocalStorageSizeEXT")); + glFramebufferPixelLocalStorageSizeEXT = reinterpret_cast(gles2wLoad("glFramebufferPixelLocalStorageSizeEXT")); glGetFramebufferPixelLocalStorageSizeEXT = reinterpret_cast(gles2wLoad("glGetFramebufferPixelLocalStorageSizeEXT")); - glClearPixelLocalStorageuiEXT = reinterpret_cast(gles2wLoad("glClearPixelLocalStorageuiEXT")); + glClearPixelLocalStorageuiEXT = reinterpret_cast(gles2wLoad("glClearPixelLocalStorageuiEXT")); #endif /* defined(GL_EXT_shader_pixel_local_storage2) */ #if defined(GL_EXT_sparse_texture) @@ -1596,18 +1596,18 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_tessellation_shader) */ #if defined(GL_EXT_texture_border_clamp) - glTexParameterIivEXT = reinterpret_cast(gles2wLoad("glTexParameterIivEXT")); - glTexParameterIuivEXT = reinterpret_cast(gles2wLoad("glTexParameterIuivEXT")); - glGetTexParameterIivEXT = reinterpret_cast(gles2wLoad("glGetTexParameterIivEXT")); - glGetTexParameterIuivEXT = reinterpret_cast(gles2wLoad("glGetTexParameterIuivEXT")); - glSamplerParameterIivEXT = reinterpret_cast(gles2wLoad("glSamplerParameterIivEXT")); - glSamplerParameterIuivEXT = reinterpret_cast(gles2wLoad("glSamplerParameterIuivEXT")); - glGetSamplerParameterIivEXT = reinterpret_cast(gles2wLoad("glGetSamplerParameterIivEXT")); + glTexParameterIivEXT = reinterpret_cast(gles2wLoad("glTexParameterIivEXT")); + glTexParameterIuivEXT = reinterpret_cast(gles2wLoad("glTexParameterIuivEXT")); + glGetTexParameterIivEXT = reinterpret_cast(gles2wLoad("glGetTexParameterIivEXT")); + glGetTexParameterIuivEXT = reinterpret_cast(gles2wLoad("glGetTexParameterIuivEXT")); + glSamplerParameterIivEXT = reinterpret_cast(gles2wLoad("glSamplerParameterIivEXT")); + glSamplerParameterIuivEXT = reinterpret_cast(gles2wLoad("glSamplerParameterIuivEXT")); + glGetSamplerParameterIivEXT = reinterpret_cast(gles2wLoad("glGetSamplerParameterIivEXT")); glGetSamplerParameterIuivEXT = reinterpret_cast(gles2wLoad("glGetSamplerParameterIuivEXT")); #endif /* defined(GL_EXT_texture_border_clamp) */ #if defined(GL_EXT_texture_buffer) - glTexBufferEXT = reinterpret_cast(gles2wLoad("glTexBufferEXT")); + glTexBufferEXT = reinterpret_cast(gles2wLoad("glTexBufferEXT")); glTexBufferRangeEXT = reinterpret_cast(gles2wLoad("glTexBufferRangeEXT")); #endif /* defined(GL_EXT_texture_buffer) */ @@ -1626,8 +1626,8 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_texture_view) */ #if defined(GL_NV_timeline_semaphore) - glCreateSemaphoresNV = reinterpret_cast(gles2wLoad("glCreateSemaphoresNV")); - glSemaphoreParameterivNV = reinterpret_cast(gles2wLoad("glSemaphoreParameterivNV")); + glCreateSemaphoresNV = reinterpret_cast(gles2wLoad("glCreateSemaphoresNV")); + glSemaphoreParameterivNV = reinterpret_cast(gles2wLoad("glSemaphoreParameterivNV")); glGetSemaphoreParameterivNV = reinterpret_cast(gles2wLoad("glGetSemaphoreParameterivNV")); #endif /* defined(GL_NV_timeline_semaphore) */ @@ -1641,21 +1641,21 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_EXT_window_rectangles) */ #if defined(GL_IMG_bindless_texture) - glGetTextureHandleIMG = reinterpret_cast(gles2wLoad("glGetTextureHandleIMG")); - glGetTextureSamplerHandleIMG = reinterpret_cast(gles2wLoad("glGetTextureSamplerHandleIMG")); - glUniformHandleui64IMG = reinterpret_cast(gles2wLoad("glUniformHandleui64IMG")); - glUniformHandleui64vIMG = reinterpret_cast(gles2wLoad("glUniformHandleui64vIMG")); - glProgramUniformHandleui64IMG = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64IMG")); + glGetTextureHandleIMG = reinterpret_cast(gles2wLoad("glGetTextureHandleIMG")); + glGetTextureSamplerHandleIMG = reinterpret_cast(gles2wLoad("glGetTextureSamplerHandleIMG")); + glUniformHandleui64IMG = reinterpret_cast(gles2wLoad("glUniformHandleui64IMG")); + glUniformHandleui64vIMG = reinterpret_cast(gles2wLoad("glUniformHandleui64vIMG")); + glProgramUniformHandleui64IMG = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64IMG")); glProgramUniformHandleui64vIMG = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64vIMG")); #endif /* defined(GL_IMG_bindless_texture) */ #if defined(GL_IMG_framebuffer_downsample) - glFramebufferTexture2DDownsampleIMG = reinterpret_cast(gles2wLoad("glFramebufferTexture2DDownsampleIMG")); + glFramebufferTexture2DDownsampleIMG = reinterpret_cast(gles2wLoad("glFramebufferTexture2DDownsampleIMG")); glFramebufferTextureLayerDownsampleIMG = reinterpret_cast(gles2wLoad("glFramebufferTextureLayerDownsampleIMG")); #endif /* defined(GL_IMG_framebuffer_downsample) */ #if defined(GL_IMG_multisampled_render_to_texture) - glRenderbufferStorageMultisampleIMG = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleIMG")); + glRenderbufferStorageMultisampleIMG = reinterpret_cast(gles2wLoad("glRenderbufferStorageMultisampleIMG")); glFramebufferTexture2DMultisampleIMG = reinterpret_cast(gles2wLoad("glFramebufferTexture2DMultisampleIMG")); #endif /* defined(GL_IMG_multisampled_render_to_texture) */ @@ -1664,16 +1664,16 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_INTEL_framebuffer_CMAA) */ #if defined(GL_INTEL_performance_query) - glBeginPerfQueryINTEL = reinterpret_cast(gles2wLoad("glBeginPerfQueryINTEL")); - glCreatePerfQueryINTEL = reinterpret_cast(gles2wLoad("glCreatePerfQueryINTEL")); - glDeletePerfQueryINTEL = reinterpret_cast(gles2wLoad("glDeletePerfQueryINTEL")); - glEndPerfQueryINTEL = reinterpret_cast(gles2wLoad("glEndPerfQueryINTEL")); - glGetFirstPerfQueryIdINTEL = reinterpret_cast(gles2wLoad("glGetFirstPerfQueryIdINTEL")); - glGetNextPerfQueryIdINTEL = reinterpret_cast(gles2wLoad("glGetNextPerfQueryIdINTEL")); - glGetPerfCounterInfoINTEL = reinterpret_cast(gles2wLoad("glGetPerfCounterInfoINTEL")); - glGetPerfQueryDataINTEL = reinterpret_cast(gles2wLoad("glGetPerfQueryDataINTEL")); + glBeginPerfQueryINTEL = reinterpret_cast(gles2wLoad("glBeginPerfQueryINTEL")); + glCreatePerfQueryINTEL = reinterpret_cast(gles2wLoad("glCreatePerfQueryINTEL")); + glDeletePerfQueryINTEL = reinterpret_cast(gles2wLoad("glDeletePerfQueryINTEL")); + glEndPerfQueryINTEL = reinterpret_cast(gles2wLoad("glEndPerfQueryINTEL")); + glGetFirstPerfQueryIdINTEL = reinterpret_cast(gles2wLoad("glGetFirstPerfQueryIdINTEL")); + glGetNextPerfQueryIdINTEL = reinterpret_cast(gles2wLoad("glGetNextPerfQueryIdINTEL")); + glGetPerfCounterInfoINTEL = reinterpret_cast(gles2wLoad("glGetPerfCounterInfoINTEL")); + glGetPerfQueryDataINTEL = reinterpret_cast(gles2wLoad("glGetPerfQueryDataINTEL")); glGetPerfQueryIdByNameINTEL = reinterpret_cast(gles2wLoad("glGetPerfQueryIdByNameINTEL")); - glGetPerfQueryInfoINTEL = reinterpret_cast(gles2wLoad("glGetPerfQueryInfoINTEL")); + glGetPerfQueryInfoINTEL = reinterpret_cast(gles2wLoad("glGetPerfQueryInfoINTEL")); #endif /* defined(GL_INTEL_performance_query) */ #if defined(GL_KHR_blend_equation_advanced) @@ -1681,25 +1681,25 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_KHR_blend_equation_advanced) */ #if defined(GL_KHR_debug) - glDebugMessageControlKHR = reinterpret_cast(gles2wLoad("glDebugMessageControlKHR")); - glDebugMessageInsertKHR = reinterpret_cast(gles2wLoad("glDebugMessageInsertKHR")); + glDebugMessageControlKHR = reinterpret_cast(gles2wLoad("glDebugMessageControlKHR")); + glDebugMessageInsertKHR = reinterpret_cast(gles2wLoad("glDebugMessageInsertKHR")); glDebugMessageCallbackKHR = reinterpret_cast(gles2wLoad("glDebugMessageCallbackKHR")); - glGetDebugMessageLogKHR = reinterpret_cast(gles2wLoad("glGetDebugMessageLogKHR")); - glPushDebugGroupKHR = reinterpret_cast(gles2wLoad("glPushDebugGroupKHR")); - glPopDebugGroupKHR = reinterpret_cast(gles2wLoad("glPopDebugGroupKHR")); - glObjectLabelKHR = reinterpret_cast(gles2wLoad("glObjectLabelKHR")); - glGetObjectLabelKHR = reinterpret_cast(gles2wLoad("glGetObjectLabelKHR")); - glObjectPtrLabelKHR = reinterpret_cast(gles2wLoad("glObjectPtrLabelKHR")); - glGetObjectPtrLabelKHR = reinterpret_cast(gles2wLoad("glGetObjectPtrLabelKHR")); - glGetPointervKHR = reinterpret_cast(gles2wLoad("glGetPointervKHR")); + glGetDebugMessageLogKHR = reinterpret_cast(gles2wLoad("glGetDebugMessageLogKHR")); + glPushDebugGroupKHR = reinterpret_cast(gles2wLoad("glPushDebugGroupKHR")); + glPopDebugGroupKHR = reinterpret_cast(gles2wLoad("glPopDebugGroupKHR")); + glObjectLabelKHR = reinterpret_cast(gles2wLoad("glObjectLabelKHR")); + glGetObjectLabelKHR = reinterpret_cast(gles2wLoad("glGetObjectLabelKHR")); + glObjectPtrLabelKHR = reinterpret_cast(gles2wLoad("glObjectPtrLabelKHR")); + glGetObjectPtrLabelKHR = reinterpret_cast(gles2wLoad("glGetObjectPtrLabelKHR")); + glGetPointervKHR = reinterpret_cast(gles2wLoad("glGetPointervKHR")); #endif /* defined(GL_KHR_debug) */ #if defined(GL_KHR_robustness) glGetGraphicsResetStatusKHR = reinterpret_cast(gles2wLoad("glGetGraphicsResetStatusKHR")); - glReadnPixelsKHR = reinterpret_cast(gles2wLoad("glReadnPixelsKHR")); - glGetnUniformfvKHR = reinterpret_cast(gles2wLoad("glGetnUniformfvKHR")); - glGetnUniformivKHR = reinterpret_cast(gles2wLoad("glGetnUniformivKHR")); - glGetnUniformuivKHR = reinterpret_cast(gles2wLoad("glGetnUniformuivKHR")); + glReadnPixelsKHR = reinterpret_cast(gles2wLoad("glReadnPixelsKHR")); + glGetnUniformfvKHR = reinterpret_cast(gles2wLoad("glGetnUniformfvKHR")); + glGetnUniformivKHR = reinterpret_cast(gles2wLoad("glGetnUniformivKHR")); + glGetnUniformuivKHR = reinterpret_cast(gles2wLoad("glGetnUniformuivKHR")); #endif /* defined(GL_KHR_robustness) */ #if defined(GL_KHR_parallel_shader_compile) @@ -1707,29 +1707,29 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_KHR_parallel_shader_compile) */ #if defined(GL_MESA_framebuffer_flip_y) - glFramebufferParameteriMESA = reinterpret_cast(gles2wLoad("glFramebufferParameteriMESA")); + glFramebufferParameteriMESA = reinterpret_cast(gles2wLoad("glFramebufferParameteriMESA")); glGetFramebufferParameterivMESA = reinterpret_cast(gles2wLoad("glGetFramebufferParameterivMESA")); #endif /* defined(GL_MESA_framebuffer_flip_y) */ #if defined(GL_NV_bindless_texture) - glGetTextureHandleNV = reinterpret_cast(gles2wLoad("glGetTextureHandleNV")); - glGetTextureSamplerHandleNV = reinterpret_cast(gles2wLoad("glGetTextureSamplerHandleNV")); - glMakeTextureHandleResidentNV = reinterpret_cast(gles2wLoad("glMakeTextureHandleResidentNV")); + glGetTextureHandleNV = reinterpret_cast(gles2wLoad("glGetTextureHandleNV")); + glGetTextureSamplerHandleNV = reinterpret_cast(gles2wLoad("glGetTextureSamplerHandleNV")); + glMakeTextureHandleResidentNV = reinterpret_cast(gles2wLoad("glMakeTextureHandleResidentNV")); glMakeTextureHandleNonResidentNV = reinterpret_cast(gles2wLoad("glMakeTextureHandleNonResidentNV")); - glGetImageHandleNV = reinterpret_cast(gles2wLoad("glGetImageHandleNV")); - glMakeImageHandleResidentNV = reinterpret_cast(gles2wLoad("glMakeImageHandleResidentNV")); - glMakeImageHandleNonResidentNV = reinterpret_cast(gles2wLoad("glMakeImageHandleNonResidentNV")); - glUniformHandleui64NV = reinterpret_cast(gles2wLoad("glUniformHandleui64NV")); - glUniformHandleui64vNV = reinterpret_cast(gles2wLoad("glUniformHandleui64vNV")); - glProgramUniformHandleui64NV = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64NV")); - glProgramUniformHandleui64vNV = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64vNV")); - glIsTextureHandleResidentNV = reinterpret_cast(gles2wLoad("glIsTextureHandleResidentNV")); - glIsImageHandleResidentNV = reinterpret_cast(gles2wLoad("glIsImageHandleResidentNV")); + glGetImageHandleNV = reinterpret_cast(gles2wLoad("glGetImageHandleNV")); + glMakeImageHandleResidentNV = reinterpret_cast(gles2wLoad("glMakeImageHandleResidentNV")); + glMakeImageHandleNonResidentNV = reinterpret_cast(gles2wLoad("glMakeImageHandleNonResidentNV")); + glUniformHandleui64NV = reinterpret_cast(gles2wLoad("glUniformHandleui64NV")); + glUniformHandleui64vNV = reinterpret_cast(gles2wLoad("glUniformHandleui64vNV")); + glProgramUniformHandleui64NV = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64NV")); + glProgramUniformHandleui64vNV = reinterpret_cast(gles2wLoad("glProgramUniformHandleui64vNV")); + glIsTextureHandleResidentNV = reinterpret_cast(gles2wLoad("glIsTextureHandleResidentNV")); + glIsImageHandleResidentNV = reinterpret_cast(gles2wLoad("glIsImageHandleResidentNV")); #endif /* defined(GL_NV_bindless_texture) */ #if defined(GL_NV_blend_equation_advanced) glBlendParameteriNV = reinterpret_cast(gles2wLoad("glBlendParameteriNV")); - glBlendBarrierNV = reinterpret_cast(gles2wLoad("glBlendBarrierNV")); + glBlendBarrierNV = reinterpret_cast(gles2wLoad("glBlendBarrierNV")); #endif /* defined(GL_NV_blend_equation_advanced) */ #if defined(GL_NV_clip_space_w_scaling) @@ -1738,7 +1738,7 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_NV_conditional_render) glBeginConditionalRenderNV = reinterpret_cast(gles2wLoad("glBeginConditionalRenderNV")); - glEndConditionalRenderNV = reinterpret_cast(gles2wLoad("glEndConditionalRenderNV")); + glEndConditionalRenderNV = reinterpret_cast(gles2wLoad("glEndConditionalRenderNV")); #endif /* defined(GL_NV_conditional_render) */ #if defined(GL_NV_conservative_raster) @@ -1754,7 +1754,7 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_copy_buffer) */ #if defined(GL_NV_coverage_sample) - glCoverageMaskNV = reinterpret_cast(gles2wLoad("glCoverageMaskNV")); + glCoverageMaskNV = reinterpret_cast(gles2wLoad("glCoverageMaskNV")); glCoverageOperationNV = reinterpret_cast(gles2wLoad("glCoverageOperationNV")); #endif /* defined(GL_NV_coverage_sample) */ @@ -1763,26 +1763,26 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_draw_buffers) */ #if defined(GL_NV_draw_instanced) - glDrawArraysInstancedNV = reinterpret_cast(gles2wLoad("glDrawArraysInstancedNV")); + glDrawArraysInstancedNV = reinterpret_cast(gles2wLoad("glDrawArraysInstancedNV")); glDrawElementsInstancedNV = reinterpret_cast(gles2wLoad("glDrawElementsInstancedNV")); #endif /* defined(GL_NV_draw_instanced) */ #if defined(GL_NV_draw_vulkan_image) - glDrawVkImageNV = reinterpret_cast(gles2wLoad("glDrawVkImageNV")); - glGetVkProcAddrNV = reinterpret_cast(gles2wLoad("glGetVkProcAddrNV")); - glWaitVkSemaphoreNV = reinterpret_cast(gles2wLoad("glWaitVkSemaphoreNV")); + glDrawVkImageNV = reinterpret_cast(gles2wLoad("glDrawVkImageNV")); + glGetVkProcAddrNV = reinterpret_cast(gles2wLoad("glGetVkProcAddrNV")); + glWaitVkSemaphoreNV = reinterpret_cast(gles2wLoad("glWaitVkSemaphoreNV")); glSignalVkSemaphoreNV = reinterpret_cast(gles2wLoad("glSignalVkSemaphoreNV")); - glSignalVkFenceNV = reinterpret_cast(gles2wLoad("glSignalVkFenceNV")); + glSignalVkFenceNV = reinterpret_cast(gles2wLoad("glSignalVkFenceNV")); #endif /* defined(GL_NV_draw_vulkan_image) */ #if defined(GL_NV_fence) glDeleteFencesNV = reinterpret_cast(gles2wLoad("glDeleteFencesNV")); - glGenFencesNV = reinterpret_cast(gles2wLoad("glGenFencesNV")); - glIsFenceNV = reinterpret_cast(gles2wLoad("glIsFenceNV")); - glTestFenceNV = reinterpret_cast(gles2wLoad("glTestFenceNV")); - glGetFenceivNV = reinterpret_cast(gles2wLoad("glGetFenceivNV")); - glFinishFenceNV = reinterpret_cast(gles2wLoad("glFinishFenceNV")); - glSetFenceNV = reinterpret_cast(gles2wLoad("glSetFenceNV")); + glGenFencesNV = reinterpret_cast(gles2wLoad("glGenFencesNV")); + glIsFenceNV = reinterpret_cast(gles2wLoad("glIsFenceNV")); + glTestFenceNV = reinterpret_cast(gles2wLoad("glTestFenceNV")); + glGetFenceivNV = reinterpret_cast(gles2wLoad("glGetFenceivNV")); + glFinishFenceNV = reinterpret_cast(gles2wLoad("glFinishFenceNV")); + glSetFenceNV = reinterpret_cast(gles2wLoad("glSetFenceNV")); #endif /* defined(GL_NV_fence) */ #if defined(GL_NV_fragment_coverage_to_color) @@ -1794,9 +1794,9 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_framebuffer_blit) */ #if defined(GL_NV_framebuffer_mixed_samples) - glCoverageModulationTableNV = reinterpret_cast(gles2wLoad("glCoverageModulationTableNV")); + glCoverageModulationTableNV = reinterpret_cast(gles2wLoad("glCoverageModulationTableNV")); glGetCoverageModulationTableNV = reinterpret_cast(gles2wLoad("glGetCoverageModulationTableNV")); - glCoverageModulationNV = reinterpret_cast(gles2wLoad("glCoverageModulationNV")); + glCoverageModulationNV = reinterpret_cast(gles2wLoad("glCoverageModulationNV")); #endif /* defined(GL_NV_framebuffer_mixed_samples) */ #if defined(GL_NV_framebuffer_multisample) @@ -1804,36 +1804,36 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_framebuffer_multisample) */ #if defined(GL_NV_gpu_shader5) - glUniform1i64NV = reinterpret_cast(gles2wLoad("glUniform1i64NV")); - glUniform2i64NV = reinterpret_cast(gles2wLoad("glUniform2i64NV")); - glUniform3i64NV = reinterpret_cast(gles2wLoad("glUniform3i64NV")); - glUniform4i64NV = reinterpret_cast(gles2wLoad("glUniform4i64NV")); - glUniform1i64vNV = reinterpret_cast(gles2wLoad("glUniform1i64vNV")); - glUniform2i64vNV = reinterpret_cast(gles2wLoad("glUniform2i64vNV")); - glUniform3i64vNV = reinterpret_cast(gles2wLoad("glUniform3i64vNV")); - glUniform4i64vNV = reinterpret_cast(gles2wLoad("glUniform4i64vNV")); - glUniform1ui64NV = reinterpret_cast(gles2wLoad("glUniform1ui64NV")); - glUniform2ui64NV = reinterpret_cast(gles2wLoad("glUniform2ui64NV")); - glUniform3ui64NV = reinterpret_cast(gles2wLoad("glUniform3ui64NV")); - glUniform4ui64NV = reinterpret_cast(gles2wLoad("glUniform4ui64NV")); - glUniform1ui64vNV = reinterpret_cast(gles2wLoad("glUniform1ui64vNV")); - glUniform2ui64vNV = reinterpret_cast(gles2wLoad("glUniform2ui64vNV")); - glUniform3ui64vNV = reinterpret_cast(gles2wLoad("glUniform3ui64vNV")); - glUniform4ui64vNV = reinterpret_cast(gles2wLoad("glUniform4ui64vNV")); + glUniform1i64NV = reinterpret_cast(gles2wLoad("glUniform1i64NV")); + glUniform2i64NV = reinterpret_cast(gles2wLoad("glUniform2i64NV")); + glUniform3i64NV = reinterpret_cast(gles2wLoad("glUniform3i64NV")); + glUniform4i64NV = reinterpret_cast(gles2wLoad("glUniform4i64NV")); + glUniform1i64vNV = reinterpret_cast(gles2wLoad("glUniform1i64vNV")); + glUniform2i64vNV = reinterpret_cast(gles2wLoad("glUniform2i64vNV")); + glUniform3i64vNV = reinterpret_cast(gles2wLoad("glUniform3i64vNV")); + glUniform4i64vNV = reinterpret_cast(gles2wLoad("glUniform4i64vNV")); + glUniform1ui64NV = reinterpret_cast(gles2wLoad("glUniform1ui64NV")); + glUniform2ui64NV = reinterpret_cast(gles2wLoad("glUniform2ui64NV")); + glUniform3ui64NV = reinterpret_cast(gles2wLoad("glUniform3ui64NV")); + glUniform4ui64NV = reinterpret_cast(gles2wLoad("glUniform4ui64NV")); + glUniform1ui64vNV = reinterpret_cast(gles2wLoad("glUniform1ui64vNV")); + glUniform2ui64vNV = reinterpret_cast(gles2wLoad("glUniform2ui64vNV")); + glUniform3ui64vNV = reinterpret_cast(gles2wLoad("glUniform3ui64vNV")); + glUniform4ui64vNV = reinterpret_cast(gles2wLoad("glUniform4ui64vNV")); glGetUniformi64vNV = reinterpret_cast(gles2wLoad("glGetUniformi64vNV")); - glProgramUniform1i64NV = reinterpret_cast(gles2wLoad("glProgramUniform1i64NV")); - glProgramUniform2i64NV = reinterpret_cast(gles2wLoad("glProgramUniform2i64NV")); - glProgramUniform3i64NV = reinterpret_cast(gles2wLoad("glProgramUniform3i64NV")); - glProgramUniform4i64NV = reinterpret_cast(gles2wLoad("glProgramUniform4i64NV")); - glProgramUniform1i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform1i64vNV")); - glProgramUniform2i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform2i64vNV")); - glProgramUniform3i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform3i64vNV")); - glProgramUniform4i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform4i64vNV")); - glProgramUniform1ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform1ui64NV")); - glProgramUniform2ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform2ui64NV")); - glProgramUniform3ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform3ui64NV")); - glProgramUniform4ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform4ui64NV")); + glProgramUniform1i64NV = reinterpret_cast(gles2wLoad("glProgramUniform1i64NV")); + glProgramUniform2i64NV = reinterpret_cast(gles2wLoad("glProgramUniform2i64NV")); + glProgramUniform3i64NV = reinterpret_cast(gles2wLoad("glProgramUniform3i64NV")); + glProgramUniform4i64NV = reinterpret_cast(gles2wLoad("glProgramUniform4i64NV")); + glProgramUniform1i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform1i64vNV")); + glProgramUniform2i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform2i64vNV")); + glProgramUniform3i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform3i64vNV")); + glProgramUniform4i64vNV = reinterpret_cast(gles2wLoad("glProgramUniform4i64vNV")); + glProgramUniform1ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform1ui64NV")); + glProgramUniform2ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform2ui64NV")); + glProgramUniform3ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform3ui64NV")); + glProgramUniform4ui64NV = reinterpret_cast(gles2wLoad("glProgramUniform4ui64NV")); glProgramUniform1ui64vNV = reinterpret_cast(gles2wLoad("glProgramUniform1ui64vNV")); glProgramUniform2ui64vNV = reinterpret_cast(gles2wLoad("glProgramUniform2ui64vNV")); glProgramUniform3ui64vNV = reinterpret_cast(gles2wLoad("glProgramUniform3ui64vNV")); @@ -1850,26 +1850,26 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_NV_memory_attachment) glGetMemoryObjectDetachedResourcesuivNV = reinterpret_cast(gles2wLoad("glGetMemoryObjectDetachedResourcesuivNV")); - glResetMemoryObjectParameterNV = reinterpret_cast(gles2wLoad("glResetMemoryObjectParameterNV")); - glTexAttachMemoryNV = reinterpret_cast(gles2wLoad("glTexAttachMemoryNV")); - glBufferAttachMemoryNV = reinterpret_cast(gles2wLoad("glBufferAttachMemoryNV")); + glResetMemoryObjectParameterNV = reinterpret_cast(gles2wLoad("glResetMemoryObjectParameterNV")); + glTexAttachMemoryNV = reinterpret_cast(gles2wLoad("glTexAttachMemoryNV")); + glBufferAttachMemoryNV = reinterpret_cast(gles2wLoad("glBufferAttachMemoryNV")); - glTextureAttachMemoryNV = reinterpret_cast(gles2wLoad("glTextureAttachMemoryNV")); + glTextureAttachMemoryNV = reinterpret_cast(gles2wLoad("glTextureAttachMemoryNV")); glNamedBufferAttachMemoryNV = reinterpret_cast(gles2wLoad("glNamedBufferAttachMemoryNV")); #endif /* defined(GL_NV_memory_attachment) */ #if defined(GL_NV_memory_object_sparse) glBufferPageCommitmentMemNV = reinterpret_cast(gles2wLoad("glBufferPageCommitmentMemNV")); - glTexPageCommitmentMemNV = reinterpret_cast(gles2wLoad("glTexPageCommitmentMemNV")); + glTexPageCommitmentMemNV = reinterpret_cast(gles2wLoad("glTexPageCommitmentMemNV")); glNamedBufferPageCommitmentMemNV = reinterpret_cast(gles2wLoad("glNamedBufferPageCommitmentMemNV")); - glTexturePageCommitmentMemNV = reinterpret_cast(gles2wLoad("glTexturePageCommitmentMemNV")); + glTexturePageCommitmentMemNV = reinterpret_cast(gles2wLoad("glTexturePageCommitmentMemNV")); #endif /* defined(GL_NV_memory_object_sparse) */ #if defined(GL_NV_mesh_shader) - glDrawMeshTasksNV = reinterpret_cast(gles2wLoad("glDrawMeshTasksNV")); - glDrawMeshTasksIndirectNV = reinterpret_cast(gles2wLoad("glDrawMeshTasksIndirectNV")); - glMultiDrawMeshTasksIndirectNV = reinterpret_cast(gles2wLoad("glMultiDrawMeshTasksIndirectNV")); + glDrawMeshTasksNV = reinterpret_cast(gles2wLoad("glDrawMeshTasksNV")); + glDrawMeshTasksIndirectNV = reinterpret_cast(gles2wLoad("glDrawMeshTasksIndirectNV")); + glMultiDrawMeshTasksIndirectNV = reinterpret_cast(gles2wLoad("glMultiDrawMeshTasksIndirectNV")); glMultiDrawMeshTasksIndirectCountNV = reinterpret_cast(gles2wLoad("glMultiDrawMeshTasksIndirectCountNV")); #endif /* defined(GL_NV_mesh_shader) */ @@ -1883,85 +1883,85 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_non_square_matrices) */ #if defined(GL_NV_path_rendering) - glGenPathsNV = reinterpret_cast(gles2wLoad("glGenPathsNV")); - glDeletePathsNV = reinterpret_cast(gles2wLoad("glDeletePathsNV")); - glIsPathNV = reinterpret_cast(gles2wLoad("glIsPathNV")); - glPathCommandsNV = reinterpret_cast(gles2wLoad("glPathCommandsNV")); - glPathCoordsNV = reinterpret_cast(gles2wLoad("glPathCoordsNV")); - glPathSubCommandsNV = reinterpret_cast(gles2wLoad("glPathSubCommandsNV")); - glPathSubCoordsNV = reinterpret_cast(gles2wLoad("glPathSubCoordsNV")); - glPathStringNV = reinterpret_cast(gles2wLoad("glPathStringNV")); - glPathGlyphsNV = reinterpret_cast(gles2wLoad("glPathGlyphsNV")); - glPathGlyphRangeNV = reinterpret_cast(gles2wLoad("glPathGlyphRangeNV")); - glWeightPathsNV = reinterpret_cast(gles2wLoad("glWeightPathsNV")); - glCopyPathNV = reinterpret_cast(gles2wLoad("glCopyPathNV")); - glInterpolatePathsNV = reinterpret_cast(gles2wLoad("glInterpolatePathsNV")); - glTransformPathNV = reinterpret_cast(gles2wLoad("glTransformPathNV")); - glPathParameterivNV = reinterpret_cast(gles2wLoad("glPathParameterivNV")); - glPathParameteriNV = reinterpret_cast(gles2wLoad("glPathParameteriNV")); - glPathParameterfvNV = reinterpret_cast(gles2wLoad("glPathParameterfvNV")); - glPathParameterfNV = reinterpret_cast(gles2wLoad("glPathParameterfNV")); - glPathDashArrayNV = reinterpret_cast(gles2wLoad("glPathDashArrayNV")); - glPathStencilFuncNV = reinterpret_cast(gles2wLoad("glPathStencilFuncNV")); - glPathStencilDepthOffsetNV = reinterpret_cast(gles2wLoad("glPathStencilDepthOffsetNV")); - glStencilFillPathNV = reinterpret_cast(gles2wLoad("glStencilFillPathNV")); - glStencilStrokePathNV = reinterpret_cast(gles2wLoad("glStencilStrokePathNV")); - glStencilFillPathInstancedNV = reinterpret_cast(gles2wLoad("glStencilFillPathInstancedNV")); + glGenPathsNV = reinterpret_cast(gles2wLoad("glGenPathsNV")); + glDeletePathsNV = reinterpret_cast(gles2wLoad("glDeletePathsNV")); + glIsPathNV = reinterpret_cast(gles2wLoad("glIsPathNV")); + glPathCommandsNV = reinterpret_cast(gles2wLoad("glPathCommandsNV")); + glPathCoordsNV = reinterpret_cast(gles2wLoad("glPathCoordsNV")); + glPathSubCommandsNV = reinterpret_cast(gles2wLoad("glPathSubCommandsNV")); + glPathSubCoordsNV = reinterpret_cast(gles2wLoad("glPathSubCoordsNV")); + glPathStringNV = reinterpret_cast(gles2wLoad("glPathStringNV")); + glPathGlyphsNV = reinterpret_cast(gles2wLoad("glPathGlyphsNV")); + glPathGlyphRangeNV = reinterpret_cast(gles2wLoad("glPathGlyphRangeNV")); + glWeightPathsNV = reinterpret_cast(gles2wLoad("glWeightPathsNV")); + glCopyPathNV = reinterpret_cast(gles2wLoad("glCopyPathNV")); + glInterpolatePathsNV = reinterpret_cast(gles2wLoad("glInterpolatePathsNV")); + glTransformPathNV = reinterpret_cast(gles2wLoad("glTransformPathNV")); + glPathParameterivNV = reinterpret_cast(gles2wLoad("glPathParameterivNV")); + glPathParameteriNV = reinterpret_cast(gles2wLoad("glPathParameteriNV")); + glPathParameterfvNV = reinterpret_cast(gles2wLoad("glPathParameterfvNV")); + glPathParameterfNV = reinterpret_cast(gles2wLoad("glPathParameterfNV")); + glPathDashArrayNV = reinterpret_cast(gles2wLoad("glPathDashArrayNV")); + glPathStencilFuncNV = reinterpret_cast(gles2wLoad("glPathStencilFuncNV")); + glPathStencilDepthOffsetNV = reinterpret_cast(gles2wLoad("glPathStencilDepthOffsetNV")); + glStencilFillPathNV = reinterpret_cast(gles2wLoad("glStencilFillPathNV")); + glStencilStrokePathNV = reinterpret_cast(gles2wLoad("glStencilStrokePathNV")); + glStencilFillPathInstancedNV = reinterpret_cast(gles2wLoad("glStencilFillPathInstancedNV")); glStencilStrokePathInstancedNV = reinterpret_cast(gles2wLoad("glStencilStrokePathInstancedNV")); - glPathCoverDepthFuncNV = reinterpret_cast(gles2wLoad("glPathCoverDepthFuncNV")); - glCoverFillPathNV = reinterpret_cast(gles2wLoad("glCoverFillPathNV")); - glCoverStrokePathNV = reinterpret_cast(gles2wLoad("glCoverStrokePathNV")); - glCoverFillPathInstancedNV = reinterpret_cast(gles2wLoad("glCoverFillPathInstancedNV")); - glCoverStrokePathInstancedNV = reinterpret_cast(gles2wLoad("glCoverStrokePathInstancedNV")); - glGetPathParameterivNV = reinterpret_cast(gles2wLoad("glGetPathParameterivNV")); - glGetPathParameterfvNV = reinterpret_cast(gles2wLoad("glGetPathParameterfvNV")); - glGetPathCommandsNV = reinterpret_cast(gles2wLoad("glGetPathCommandsNV")); - glGetPathCoordsNV = reinterpret_cast(gles2wLoad("glGetPathCoordsNV")); - glGetPathDashArrayNV = reinterpret_cast(gles2wLoad("glGetPathDashArrayNV")); - glGetPathMetricsNV = reinterpret_cast(gles2wLoad("glGetPathMetricsNV")); - glGetPathMetricRangeNV = reinterpret_cast(gles2wLoad("glGetPathMetricRangeNV")); - glGetPathSpacingNV = reinterpret_cast(gles2wLoad("glGetPathSpacingNV")); - glIsPointInFillPathNV = reinterpret_cast(gles2wLoad("glIsPointInFillPathNV")); - glIsPointInStrokePathNV = reinterpret_cast(gles2wLoad("glIsPointInStrokePathNV")); - glGetPathLengthNV = reinterpret_cast(gles2wLoad("glGetPathLengthNV")); - glPointAlongPathNV = reinterpret_cast(gles2wLoad("glPointAlongPathNV")); + glPathCoverDepthFuncNV = reinterpret_cast(gles2wLoad("glPathCoverDepthFuncNV")); + glCoverFillPathNV = reinterpret_cast(gles2wLoad("glCoverFillPathNV")); + glCoverStrokePathNV = reinterpret_cast(gles2wLoad("glCoverStrokePathNV")); + glCoverFillPathInstancedNV = reinterpret_cast(gles2wLoad("glCoverFillPathInstancedNV")); + glCoverStrokePathInstancedNV = reinterpret_cast(gles2wLoad("glCoverStrokePathInstancedNV")); + glGetPathParameterivNV = reinterpret_cast(gles2wLoad("glGetPathParameterivNV")); + glGetPathParameterfvNV = reinterpret_cast(gles2wLoad("glGetPathParameterfvNV")); + glGetPathCommandsNV = reinterpret_cast(gles2wLoad("glGetPathCommandsNV")); + glGetPathCoordsNV = reinterpret_cast(gles2wLoad("glGetPathCoordsNV")); + glGetPathDashArrayNV = reinterpret_cast(gles2wLoad("glGetPathDashArrayNV")); + glGetPathMetricsNV = reinterpret_cast(gles2wLoad("glGetPathMetricsNV")); + glGetPathMetricRangeNV = reinterpret_cast(gles2wLoad("glGetPathMetricRangeNV")); + glGetPathSpacingNV = reinterpret_cast(gles2wLoad("glGetPathSpacingNV")); + glIsPointInFillPathNV = reinterpret_cast(gles2wLoad("glIsPointInFillPathNV")); + glIsPointInStrokePathNV = reinterpret_cast(gles2wLoad("glIsPointInStrokePathNV")); + glGetPathLengthNV = reinterpret_cast(gles2wLoad("glGetPathLengthNV")); + glPointAlongPathNV = reinterpret_cast(gles2wLoad("glPointAlongPathNV")); - glMatrixLoad3x2fNV = reinterpret_cast(gles2wLoad("glMatrixLoad3x2fNV")); - glMatrixLoad3x3fNV = reinterpret_cast(gles2wLoad("glMatrixLoad3x3fNV")); - glMatrixLoadTranspose3x3fNV = reinterpret_cast(gles2wLoad("glMatrixLoadTranspose3x3fNV")); - glMatrixMult3x2fNV = reinterpret_cast(gles2wLoad("glMatrixMult3x2fNV")); - glMatrixMult3x3fNV = reinterpret_cast(gles2wLoad("glMatrixMult3x3fNV")); - glMatrixMultTranspose3x3fNV = reinterpret_cast(gles2wLoad("glMatrixMultTranspose3x3fNV")); - glStencilThenCoverFillPathNV = reinterpret_cast(gles2wLoad("glStencilThenCoverFillPathNV")); - glStencilThenCoverStrokePathNV = reinterpret_cast(gles2wLoad("glStencilThenCoverStrokePathNV")); - glStencilThenCoverFillPathInstancedNV = reinterpret_cast(gles2wLoad("glStencilThenCoverFillPathInstancedNV")); + glMatrixLoad3x2fNV = reinterpret_cast(gles2wLoad("glMatrixLoad3x2fNV")); + glMatrixLoad3x3fNV = reinterpret_cast(gles2wLoad("glMatrixLoad3x3fNV")); + glMatrixLoadTranspose3x3fNV = reinterpret_cast(gles2wLoad("glMatrixLoadTranspose3x3fNV")); + glMatrixMult3x2fNV = reinterpret_cast(gles2wLoad("glMatrixMult3x2fNV")); + glMatrixMult3x3fNV = reinterpret_cast(gles2wLoad("glMatrixMult3x3fNV")); + glMatrixMultTranspose3x3fNV = reinterpret_cast(gles2wLoad("glMatrixMultTranspose3x3fNV")); + glStencilThenCoverFillPathNV = reinterpret_cast(gles2wLoad("glStencilThenCoverFillPathNV")); + glStencilThenCoverStrokePathNV = reinterpret_cast(gles2wLoad("glStencilThenCoverStrokePathNV")); + glStencilThenCoverFillPathInstancedNV = reinterpret_cast(gles2wLoad("glStencilThenCoverFillPathInstancedNV")); glStencilThenCoverStrokePathInstancedNV = reinterpret_cast(gles2wLoad("glStencilThenCoverStrokePathInstancedNV")); - glPathGlyphIndexRangeNV = reinterpret_cast(gles2wLoad("glPathGlyphIndexRangeNV")); + glPathGlyphIndexRangeNV = reinterpret_cast(gles2wLoad("glPathGlyphIndexRangeNV")); - glPathGlyphIndexArrayNV = reinterpret_cast(gles2wLoad("glPathGlyphIndexArrayNV")); - glPathMemoryGlyphIndexArrayNV = reinterpret_cast(gles2wLoad("glPathMemoryGlyphIndexArrayNV")); + glPathGlyphIndexArrayNV = reinterpret_cast(gles2wLoad("glPathGlyphIndexArrayNV")); + glPathMemoryGlyphIndexArrayNV = reinterpret_cast(gles2wLoad("glPathMemoryGlyphIndexArrayNV")); glProgramPathFragmentInputGenNV = reinterpret_cast(gles2wLoad("glProgramPathFragmentInputGenNV")); - glGetProgramResourcefvNV = reinterpret_cast(gles2wLoad("glGetProgramResourcefvNV")); + glGetProgramResourcefvNV = reinterpret_cast(gles2wLoad("glGetProgramResourcefvNV")); - glMatrixFrustumEXT = reinterpret_cast(gles2wLoad("glMatrixFrustumEXT")); - glMatrixLoadIdentityEXT = reinterpret_cast(gles2wLoad("glMatrixLoadIdentityEXT")); + glMatrixFrustumEXT = reinterpret_cast(gles2wLoad("glMatrixFrustumEXT")); + glMatrixLoadIdentityEXT = reinterpret_cast(gles2wLoad("glMatrixLoadIdentityEXT")); glMatrixLoadTransposefEXT = reinterpret_cast(gles2wLoad("glMatrixLoadTransposefEXT")); glMatrixLoadTransposedEXT = reinterpret_cast(gles2wLoad("glMatrixLoadTransposedEXT")); - glMatrixLoadfEXT = reinterpret_cast(gles2wLoad("glMatrixLoadfEXT")); - glMatrixLoaddEXT = reinterpret_cast(gles2wLoad("glMatrixLoaddEXT")); + glMatrixLoadfEXT = reinterpret_cast(gles2wLoad("glMatrixLoadfEXT")); + glMatrixLoaddEXT = reinterpret_cast(gles2wLoad("glMatrixLoaddEXT")); glMatrixMultTransposefEXT = reinterpret_cast(gles2wLoad("glMatrixMultTransposefEXT")); glMatrixMultTransposedEXT = reinterpret_cast(gles2wLoad("glMatrixMultTransposedEXT")); - glMatrixMultfEXT = reinterpret_cast(gles2wLoad("glMatrixMultfEXT")); - glMatrixMultdEXT = reinterpret_cast(gles2wLoad("glMatrixMultdEXT")); - glMatrixOrthoEXT = reinterpret_cast(gles2wLoad("glMatrixOrthoEXT")); - glMatrixPopEXT = reinterpret_cast(gles2wLoad("glMatrixPopEXT")); - glMatrixPushEXT = reinterpret_cast(gles2wLoad("glMatrixPushEXT")); - glMatrixRotatefEXT = reinterpret_cast(gles2wLoad("glMatrixRotatefEXT")); - glMatrixRotatedEXT = reinterpret_cast(gles2wLoad("glMatrixRotatedEXT")); - glMatrixScalefEXT = reinterpret_cast(gles2wLoad("glMatrixScalefEXT")); - glMatrixScaledEXT = reinterpret_cast(gles2wLoad("glMatrixScaledEXT")); - glMatrixTranslatefEXT = reinterpret_cast(gles2wLoad("glMatrixTranslatefEXT")); - glMatrixTranslatedEXT = reinterpret_cast(gles2wLoad("glMatrixTranslatedEXT")); + glMatrixMultfEXT = reinterpret_cast(gles2wLoad("glMatrixMultfEXT")); + glMatrixMultdEXT = reinterpret_cast(gles2wLoad("glMatrixMultdEXT")); + glMatrixOrthoEXT = reinterpret_cast(gles2wLoad("glMatrixOrthoEXT")); + glMatrixPopEXT = reinterpret_cast(gles2wLoad("glMatrixPopEXT")); + glMatrixPushEXT = reinterpret_cast(gles2wLoad("glMatrixPushEXT")); + glMatrixRotatefEXT = reinterpret_cast(gles2wLoad("glMatrixRotatefEXT")); + glMatrixRotatedEXT = reinterpret_cast(gles2wLoad("glMatrixRotatedEXT")); + glMatrixScalefEXT = reinterpret_cast(gles2wLoad("glMatrixScalefEXT")); + glMatrixScaledEXT = reinterpret_cast(gles2wLoad("glMatrixScaledEXT")); + glMatrixTranslatefEXT = reinterpret_cast(gles2wLoad("glMatrixTranslatefEXT")); + glMatrixTranslatedEXT = reinterpret_cast(gles2wLoad("glMatrixTranslatedEXT")); #endif /* defined(GL_NV_path_rendering) */ #if defined(GL_NV_polygon_mode) @@ -1973,39 +1973,39 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_read_buffer) */ #if defined(GL_NV_sample_locations) - glFramebufferSampleLocationsfvNV = reinterpret_cast(gles2wLoad("glFramebufferSampleLocationsfvNV")); + glFramebufferSampleLocationsfvNV = reinterpret_cast(gles2wLoad("glFramebufferSampleLocationsfvNV")); glNamedFramebufferSampleLocationsfvNV = reinterpret_cast(gles2wLoad("glNamedFramebufferSampleLocationsfvNV")); - glResolveDepthValuesNV = reinterpret_cast(gles2wLoad("glResolveDepthValuesNV")); + glResolveDepthValuesNV = reinterpret_cast(gles2wLoad("glResolveDepthValuesNV")); #endif /* defined(GL_NV_sample_locations) */ #if defined(GL_NV_scissor_exclusive) - glScissorExclusiveNV = reinterpret_cast(gles2wLoad("glScissorExclusiveNV")); + glScissorExclusiveNV = reinterpret_cast(gles2wLoad("glScissorExclusiveNV")); glScissorExclusiveArrayvNV = reinterpret_cast(gles2wLoad("glScissorExclusiveArrayvNV")); #endif /* defined(GL_NV_scissor_exclusive) */ #if defined(GL_NV_shading_rate_image) - glBindShadingRateImageNV = reinterpret_cast(gles2wLoad("glBindShadingRateImageNV")); - glGetShadingRateImagePaletteNV = reinterpret_cast(gles2wLoad("glGetShadingRateImagePaletteNV")); + glBindShadingRateImageNV = reinterpret_cast(gles2wLoad("glBindShadingRateImageNV")); + glGetShadingRateImagePaletteNV = reinterpret_cast(gles2wLoad("glGetShadingRateImagePaletteNV")); glGetShadingRateSampleLocationivNV = reinterpret_cast(gles2wLoad("glGetShadingRateSampleLocationivNV")); - glShadingRateImageBarrierNV = reinterpret_cast(gles2wLoad("glShadingRateImageBarrierNV")); - glShadingRateImagePaletteNV = reinterpret_cast(gles2wLoad("glShadingRateImagePaletteNV")); - glShadingRateSampleOrderNV = reinterpret_cast(gles2wLoad("glShadingRateSampleOrderNV")); - glShadingRateSampleOrderCustomNV = reinterpret_cast(gles2wLoad("glShadingRateSampleOrderCustomNV")); + glShadingRateImageBarrierNV = reinterpret_cast(gles2wLoad("glShadingRateImageBarrierNV")); + glShadingRateImagePaletteNV = reinterpret_cast(gles2wLoad("glShadingRateImagePaletteNV")); + glShadingRateSampleOrderNV = reinterpret_cast(gles2wLoad("glShadingRateSampleOrderNV")); + glShadingRateSampleOrderCustomNV = reinterpret_cast(gles2wLoad("glShadingRateSampleOrderCustomNV")); #endif /* defined(GL_NV_shading_rate_image) */ #if defined(GL_NV_viewport_array) - glViewportArrayvNV = reinterpret_cast(gles2wLoad("glViewportArrayvNV")); - glViewportIndexedfNV = reinterpret_cast(gles2wLoad("glViewportIndexedfNV")); - glViewportIndexedfvNV = reinterpret_cast(gles2wLoad("glViewportIndexedfvNV")); - glScissorArrayvNV = reinterpret_cast(gles2wLoad("glScissorArrayvNV")); - glScissorIndexedNV = reinterpret_cast(gles2wLoad("glScissorIndexedNV")); - glScissorIndexedvNV = reinterpret_cast(gles2wLoad("glScissorIndexedvNV")); - glDepthRangeArrayfvNV = reinterpret_cast(gles2wLoad("glDepthRangeArrayfvNV")); + glViewportArrayvNV = reinterpret_cast(gles2wLoad("glViewportArrayvNV")); + glViewportIndexedfNV = reinterpret_cast(gles2wLoad("glViewportIndexedfNV")); + glViewportIndexedfvNV = reinterpret_cast(gles2wLoad("glViewportIndexedfvNV")); + glScissorArrayvNV = reinterpret_cast(gles2wLoad("glScissorArrayvNV")); + glScissorIndexedNV = reinterpret_cast(gles2wLoad("glScissorIndexedNV")); + glScissorIndexedvNV = reinterpret_cast(gles2wLoad("glScissorIndexedvNV")); + glDepthRangeArrayfvNV = reinterpret_cast(gles2wLoad("glDepthRangeArrayfvNV")); glDepthRangeIndexedfNV = reinterpret_cast(gles2wLoad("glDepthRangeIndexedfNV")); - glGetFloati_vNV = reinterpret_cast(gles2wLoad("glGetFloati_vNV")); - glEnableiNV = reinterpret_cast(gles2wLoad("glEnableiNV")); - glDisableiNV = reinterpret_cast(gles2wLoad("glDisableiNV")); - glIsEnablediNV = reinterpret_cast(gles2wLoad("glIsEnablediNV")); + glGetFloati_vNV = reinterpret_cast(gles2wLoad("glGetFloati_vNV")); + glEnableiNV = reinterpret_cast(gles2wLoad("glEnableiNV")); + glDisableiNV = reinterpret_cast(gles2wLoad("glDisableiNV")); + glIsEnablediNV = reinterpret_cast(gles2wLoad("glIsEnablediNV")); #endif /* defined(GL_NV_viewport_array) */ #if defined(GL_NV_viewport_swizzle) @@ -2013,7 +2013,7 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_NV_viewport_swizzle) */ #if defined(GL_OES_EGL_image) - glEGLImageTargetTexture2DOES = reinterpret_cast(gles2wLoad("glEGLImageTargetTexture2DOES")); + glEGLImageTargetTexture2DOES = reinterpret_cast(gles2wLoad("glEGLImageTargetTexture2DOES")); glEGLImageTargetRenderbufferStorageOES = reinterpret_cast(gles2wLoad("glEGLImageTargetRenderbufferStorageOES")); #endif /* defined(GL_OES_EGL_image) */ @@ -2022,19 +2022,19 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_OES_copy_image) */ #if defined(GL_OES_draw_buffers_indexed) - glEnableiOES = reinterpret_cast(gles2wLoad("glEnableiOES")); - glDisableiOES = reinterpret_cast(gles2wLoad("glDisableiOES")); - glBlendEquationiOES = reinterpret_cast(gles2wLoad("glBlendEquationiOES")); + glEnableiOES = reinterpret_cast(gles2wLoad("glEnableiOES")); + glDisableiOES = reinterpret_cast(gles2wLoad("glDisableiOES")); + glBlendEquationiOES = reinterpret_cast(gles2wLoad("glBlendEquationiOES")); glBlendEquationSeparateiOES = reinterpret_cast(gles2wLoad("glBlendEquationSeparateiOES")); - glBlendFunciOES = reinterpret_cast(gles2wLoad("glBlendFunciOES")); - glBlendFuncSeparateiOES = reinterpret_cast(gles2wLoad("glBlendFuncSeparateiOES")); - glColorMaskiOES = reinterpret_cast(gles2wLoad("glColorMaskiOES")); - glIsEnablediOES = reinterpret_cast(gles2wLoad("glIsEnablediOES")); + glBlendFunciOES = reinterpret_cast(gles2wLoad("glBlendFunciOES")); + glBlendFuncSeparateiOES = reinterpret_cast(gles2wLoad("glBlendFuncSeparateiOES")); + glColorMaskiOES = reinterpret_cast(gles2wLoad("glColorMaskiOES")); + glIsEnablediOES = reinterpret_cast(gles2wLoad("glIsEnablediOES")); #endif /* defined(GL_OES_draw_buffers_indexed) */ #if defined(GL_OES_draw_elements_base_vertex) - glDrawElementsBaseVertexOES = reinterpret_cast(gles2wLoad("glDrawElementsBaseVertexOES")); - glDrawRangeElementsBaseVertexOES = reinterpret_cast(gles2wLoad("glDrawRangeElementsBaseVertexOES")); + glDrawElementsBaseVertexOES = reinterpret_cast(gles2wLoad("glDrawElementsBaseVertexOES")); + glDrawRangeElementsBaseVertexOES = reinterpret_cast(gles2wLoad("glDrawRangeElementsBaseVertexOES")); glDrawElementsInstancedBaseVertexOES = reinterpret_cast(gles2wLoad("glDrawElementsInstancedBaseVertexOES")); #endif /* defined(GL_OES_draw_elements_base_vertex) */ @@ -2044,12 +2044,12 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_OES_get_program_binary) glGetProgramBinaryOES = reinterpret_cast(gles2wLoad("glGetProgramBinaryOES")); - glProgramBinaryOES = reinterpret_cast(gles2wLoad("glProgramBinaryOES")); + glProgramBinaryOES = reinterpret_cast(gles2wLoad("glProgramBinaryOES")); #endif /* defined(GL_OES_get_program_binary) */ #if defined(GL_OES_mapbuffer) - glMapBufferOES = reinterpret_cast(gles2wLoad("glMapBufferOES")); - glUnmapBufferOES = reinterpret_cast(gles2wLoad("glUnmapBufferOES")); + glMapBufferOES = reinterpret_cast(gles2wLoad("glMapBufferOES")); + glUnmapBufferOES = reinterpret_cast(gles2wLoad("glUnmapBufferOES")); glGetBufferPointervOES = reinterpret_cast(gles2wLoad("glGetBufferPointervOES")); #endif /* defined(GL_OES_mapbuffer) */ @@ -2066,27 +2066,27 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_OES_tessellation_shader) */ #if defined(GL_OES_texture_3D) - glTexImage3DOES = reinterpret_cast(gles2wLoad("glTexImage3DOES")); - glTexSubImage3DOES = reinterpret_cast(gles2wLoad("glTexSubImage3DOES")); - glCopyTexSubImage3DOES = reinterpret_cast(gles2wLoad("glCopyTexSubImage3DOES")); - glCompressedTexImage3DOES = reinterpret_cast(gles2wLoad("glCompressedTexImage3DOES")); + glTexImage3DOES = reinterpret_cast(gles2wLoad("glTexImage3DOES")); + glTexSubImage3DOES = reinterpret_cast(gles2wLoad("glTexSubImage3DOES")); + glCopyTexSubImage3DOES = reinterpret_cast(gles2wLoad("glCopyTexSubImage3DOES")); + glCompressedTexImage3DOES = reinterpret_cast(gles2wLoad("glCompressedTexImage3DOES")); glCompressedTexSubImage3DOES = reinterpret_cast(gles2wLoad("glCompressedTexSubImage3DOES")); - glFramebufferTexture3DOES = reinterpret_cast(gles2wLoad("glFramebufferTexture3DOES")); + glFramebufferTexture3DOES = reinterpret_cast(gles2wLoad("glFramebufferTexture3DOES")); #endif /* defined(GL_OES_texture_3D) */ #if defined(GL_OES_texture_border_clamp) - glTexParameterIivOES = reinterpret_cast(gles2wLoad("glTexParameterIivOES")); - glTexParameterIuivOES = reinterpret_cast(gles2wLoad("glTexParameterIuivOES")); - glGetTexParameterIivOES = reinterpret_cast(gles2wLoad("glGetTexParameterIivOES")); - glGetTexParameterIuivOES = reinterpret_cast(gles2wLoad("glGetTexParameterIuivOES")); - glSamplerParameterIivOES = reinterpret_cast(gles2wLoad("glSamplerParameterIivOES")); - glSamplerParameterIuivOES = reinterpret_cast(gles2wLoad("glSamplerParameterIuivOES")); - glGetSamplerParameterIivOES = reinterpret_cast(gles2wLoad("glGetSamplerParameterIivOES")); + glTexParameterIivOES = reinterpret_cast(gles2wLoad("glTexParameterIivOES")); + glTexParameterIuivOES = reinterpret_cast(gles2wLoad("glTexParameterIuivOES")); + glGetTexParameterIivOES = reinterpret_cast(gles2wLoad("glGetTexParameterIivOES")); + glGetTexParameterIuivOES = reinterpret_cast(gles2wLoad("glGetTexParameterIuivOES")); + glSamplerParameterIivOES = reinterpret_cast(gles2wLoad("glSamplerParameterIivOES")); + glSamplerParameterIuivOES = reinterpret_cast(gles2wLoad("glSamplerParameterIuivOES")); + glGetSamplerParameterIivOES = reinterpret_cast(gles2wLoad("glGetSamplerParameterIivOES")); glGetSamplerParameterIuivOES = reinterpret_cast(gles2wLoad("glGetSamplerParameterIuivOES")); #endif /* defined(GL_OES_texture_border_clamp) */ #if defined(GL_OES_texture_buffer) - glTexBufferOES = reinterpret_cast(gles2wLoad("glTexBufferOES")); + glTexBufferOES = reinterpret_cast(gles2wLoad("glTexBufferOES")); glTexBufferRangeOES = reinterpret_cast(gles2wLoad("glTexBufferRangeOES")); #endif /* defined(GL_OES_texture_buffer) */ @@ -2099,22 +2099,22 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_OES_texture_view) */ #if defined(GL_OES_vertex_array_object) - glBindVertexArrayOES = reinterpret_cast(gles2wLoad("glBindVertexArrayOES")); + glBindVertexArrayOES = reinterpret_cast(gles2wLoad("glBindVertexArrayOES")); glDeleteVertexArraysOES = reinterpret_cast(gles2wLoad("glDeleteVertexArraysOES")); - glGenVertexArraysOES = reinterpret_cast(gles2wLoad("glGenVertexArraysOES")); - glIsVertexArrayOES = reinterpret_cast(gles2wLoad("glIsVertexArrayOES")); + glGenVertexArraysOES = reinterpret_cast(gles2wLoad("glGenVertexArraysOES")); + glIsVertexArrayOES = reinterpret_cast(gles2wLoad("glIsVertexArrayOES")); #endif /* defined(GL_OES_vertex_array_object) */ #if defined(GL_OES_viewport_array) - glViewportArrayvOES = reinterpret_cast(gles2wLoad("glViewportArrayvOES")); - glViewportIndexedfOES = reinterpret_cast(gles2wLoad("glViewportIndexedfOES")); - glViewportIndexedfvOES = reinterpret_cast(gles2wLoad("glViewportIndexedfvOES")); - glScissorArrayvOES = reinterpret_cast(gles2wLoad("glScissorArrayvOES")); - glScissorIndexedOES = reinterpret_cast(gles2wLoad("glScissorIndexedOES")); - glScissorIndexedvOES = reinterpret_cast(gles2wLoad("glScissorIndexedvOES")); - glDepthRangeArrayfvOES = reinterpret_cast(gles2wLoad("glDepthRangeArrayfvOES")); + glViewportArrayvOES = reinterpret_cast(gles2wLoad("glViewportArrayvOES")); + glViewportIndexedfOES = reinterpret_cast(gles2wLoad("glViewportIndexedfOES")); + glViewportIndexedfvOES = reinterpret_cast(gles2wLoad("glViewportIndexedfvOES")); + glScissorArrayvOES = reinterpret_cast(gles2wLoad("glScissorArrayvOES")); + glScissorIndexedOES = reinterpret_cast(gles2wLoad("glScissorIndexedOES")); + glScissorIndexedvOES = reinterpret_cast(gles2wLoad("glScissorIndexedvOES")); + glDepthRangeArrayfvOES = reinterpret_cast(gles2wLoad("glDepthRangeArrayfvOES")); glDepthRangeIndexedfOES = reinterpret_cast(gles2wLoad("glDepthRangeIndexedfOES")); - glGetFloati_vOES = reinterpret_cast(gles2wLoad("glGetFloati_vOES")); + glGetFloati_vOES = reinterpret_cast(gles2wLoad("glGetFloati_vOES")); #endif /* defined(GL_OES_viewport_array) */ #if defined(GL_OVR_multiview) @@ -2130,37 +2130,37 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #endif /* defined(GL_QCOM_alpha_test) */ #if defined(GL_QCOM_driver_control) - glGetDriverControlsQCOM = reinterpret_cast(gles2wLoad("glGetDriverControlsQCOM")); + glGetDriverControlsQCOM = reinterpret_cast(gles2wLoad("glGetDriverControlsQCOM")); glGetDriverControlStringQCOM = reinterpret_cast(gles2wLoad("glGetDriverControlStringQCOM")); - glEnableDriverControlQCOM = reinterpret_cast(gles2wLoad("glEnableDriverControlQCOM")); - glDisableDriverControlQCOM = reinterpret_cast(gles2wLoad("glDisableDriverControlQCOM")); + glEnableDriverControlQCOM = reinterpret_cast(gles2wLoad("glEnableDriverControlQCOM")); + glDisableDriverControlQCOM = reinterpret_cast(gles2wLoad("glDisableDriverControlQCOM")); #endif /* defined(GL_QCOM_driver_control) */ #if defined(GL_QCOM_extended_get) - glExtGetTexturesQCOM = reinterpret_cast(gles2wLoad("glExtGetTexturesQCOM")); - glExtGetBuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetBuffersQCOM")); - glExtGetRenderbuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetRenderbuffersQCOM")); - glExtGetFramebuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetFramebuffersQCOM")); - glExtGetTexLevelParameterivQCOM = reinterpret_cast(gles2wLoad("glExtGetTexLevelParameterivQCOM")); + glExtGetTexturesQCOM = reinterpret_cast(gles2wLoad("glExtGetTexturesQCOM")); + glExtGetBuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetBuffersQCOM")); + glExtGetRenderbuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetRenderbuffersQCOM")); + glExtGetFramebuffersQCOM = reinterpret_cast(gles2wLoad("glExtGetFramebuffersQCOM")); + glExtGetTexLevelParameterivQCOM = reinterpret_cast(gles2wLoad("glExtGetTexLevelParameterivQCOM")); glExtTexObjectStateOverrideiQCOM = reinterpret_cast(gles2wLoad("glExtTexObjectStateOverrideiQCOM")); - glExtGetTexSubImageQCOM = reinterpret_cast(gles2wLoad("glExtGetTexSubImageQCOM")); - glExtGetBufferPointervQCOM = reinterpret_cast(gles2wLoad("glExtGetBufferPointervQCOM")); + glExtGetTexSubImageQCOM = reinterpret_cast(gles2wLoad("glExtGetTexSubImageQCOM")); + glExtGetBufferPointervQCOM = reinterpret_cast(gles2wLoad("glExtGetBufferPointervQCOM")); #endif /* defined(GL_QCOM_extended_get) */ #if defined(GL_QCOM_extended_get2) - glExtGetShadersQCOM = reinterpret_cast(gles2wLoad("glExtGetShadersQCOM")); - glExtGetProgramsQCOM = reinterpret_cast(gles2wLoad("glExtGetProgramsQCOM")); - glExtIsProgramBinaryQCOM = reinterpret_cast(gles2wLoad("glExtIsProgramBinaryQCOM")); + glExtGetShadersQCOM = reinterpret_cast(gles2wLoad("glExtGetShadersQCOM")); + glExtGetProgramsQCOM = reinterpret_cast(gles2wLoad("glExtGetProgramsQCOM")); + glExtIsProgramBinaryQCOM = reinterpret_cast(gles2wLoad("glExtIsProgramBinaryQCOM")); glExtGetProgramBinarySourceQCOM = reinterpret_cast(gles2wLoad("glExtGetProgramBinarySourceQCOM")); #endif /* defined(GL_QCOM_extended_get2) */ #if defined(GL_QCOM_framebuffer_foveated) - glFramebufferFoveationConfigQCOM = reinterpret_cast(gles2wLoad("glFramebufferFoveationConfigQCOM")); + glFramebufferFoveationConfigQCOM = reinterpret_cast(gles2wLoad("glFramebufferFoveationConfigQCOM")); glFramebufferFoveationParametersQCOM = reinterpret_cast(gles2wLoad("glFramebufferFoveationParametersQCOM")); #endif /* defined(GL_QCOM_framebuffer_foveated) */ #if defined(GL_QCOM_motion_estimation) - glTexEstimateMotionQCOM = reinterpret_cast(gles2wLoad("glTexEstimateMotionQCOM")); + glTexEstimateMotionQCOM = reinterpret_cast(gles2wLoad("glTexEstimateMotionQCOM")); glTexEstimateMotionRegionsQCOM = reinterpret_cast(gles2wLoad("glTexEstimateMotionRegionsQCOM")); #endif /* defined(GL_QCOM_motion_estimation) */ @@ -2182,7 +2182,7 @@ void gles2wLoadProcs(PFNGLES2WLOADPROC gles2wLoad) { #if defined(GL_QCOM_tiled_rendering) glStartTilingQCOM = reinterpret_cast(gles2wLoad("glStartTilingQCOM")); - glEndTilingQCOM = reinterpret_cast(gles2wLoad("glEndTilingQCOM")); + glEndTilingQCOM = reinterpret_cast(gles2wLoad("glEndTilingQCOM")); #endif /* defined(GL_QCOM_tiled_rendering) */ /* GLES2W_GENERATE_GLES_LOAD */ diff --git a/native/cocos/renderer/gfx-gles-common/gles2w.h b/native/cocos/renderer/gfx-gles-common/gles2w.h index 3a507245d0..ca3bf52779 100644 --- a/native/cocos/renderer/gfx-gles-common/gles2w.h +++ b/native/cocos/renderer/gfx-gles-common/gles2w.h @@ -44,166 +44,166 @@ /* GLES2W_GENERATE_GLES_DECLARATION */ /* GL_ES_VERSION_2_0 */ -extern PFNGLACTIVETEXTUREPROC glActiveTexture; -extern PFNGLATTACHSHADERPROC glAttachShader; -extern PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; -extern PFNGLBINDBUFFERPROC glBindBuffer; -extern PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; -extern PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; -extern PFNGLBINDTEXTUREPROC glBindTexture; -extern PFNGLBLENDCOLORPROC glBlendColor; -extern PFNGLBLENDEQUATIONPROC glBlendEquation; -extern PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; -extern PFNGLBLENDFUNCPROC glBlendFunc; -extern PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; -extern PFNGLBUFFERDATAPROC glBufferData; -extern PFNGLBUFFERSUBDATAPROC glBufferSubData; -extern PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; -extern PFNGLCLEARPROC glClear; -extern PFNGLCLEARCOLORPROC glClearColor; -extern PFNGLCLEARDEPTHFPROC glClearDepthf; -extern PFNGLCLEARSTENCILPROC glClearStencil; -extern PFNGLCOLORMASKPROC glColorMask; -extern PFNGLCOMPILESHADERPROC glCompileShader; -extern PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; -extern PFNGLCOPYTEXIMAGE2DPROC glCopyTexImage2D; -extern PFNGLCOPYTEXSUBIMAGE2DPROC glCopyTexSubImage2D; -extern PFNGLCREATEPROGRAMPROC glCreateProgram; -extern PFNGLCREATESHADERPROC glCreateShader; -extern PFNGLCULLFACEPROC glCullFace; -extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; -extern PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; -extern PFNGLDELETEPROGRAMPROC glDeleteProgram; -extern PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; -extern PFNGLDELETESHADERPROC glDeleteShader; -extern PFNGLDELETETEXTURESPROC glDeleteTextures; -extern PFNGLDEPTHFUNCPROC glDepthFunc; -extern PFNGLDEPTHMASKPROC glDepthMask; -extern PFNGLDEPTHRANGEFPROC glDepthRangef; -extern PFNGLDETACHSHADERPROC glDetachShader; -extern PFNGLDISABLEPROC glDisable; -extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; -extern PFNGLDRAWARRAYSPROC glDrawArrays; -extern PFNGLDRAWELEMENTSPROC glDrawElements; -extern PFNGLENABLEPROC glEnable; -extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; -extern PFNGLFINISHPROC glFinish; -extern PFNGLFLUSHPROC glFlush; -extern PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; -extern PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; -extern PFNGLFRONTFACEPROC glFrontFace; -extern PFNGLGENBUFFERSPROC glGenBuffers; -extern PFNGLGENERATEMIPMAPPROC glGenerateMipmap; -extern PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; -extern PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; -extern PFNGLGENTEXTURESPROC glGenTextures; -extern PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; -extern PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; -extern PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; -extern PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; -extern PFNGLGETBOOLEANVPROC glGetBooleanv; -extern PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; -extern PFNGLGETERRORPROC glGetError; -extern PFNGLGETFLOATVPROC glGetFloatv; +extern PFNGLACTIVETEXTUREPROC glActiveTexture; +extern PFNGLATTACHSHADERPROC glAttachShader; +extern PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; +extern PFNGLBINDBUFFERPROC glBindBuffer; +extern PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; +extern PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; +extern PFNGLBINDTEXTUREPROC glBindTexture; +extern PFNGLBLENDCOLORPROC glBlendColor; +extern PFNGLBLENDEQUATIONPROC glBlendEquation; +extern PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; +extern PFNGLBLENDFUNCPROC glBlendFunc; +extern PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; +extern PFNGLBUFFERDATAPROC glBufferData; +extern PFNGLBUFFERSUBDATAPROC glBufferSubData; +extern PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; +extern PFNGLCLEARPROC glClear; +extern PFNGLCLEARCOLORPROC glClearColor; +extern PFNGLCLEARDEPTHFPROC glClearDepthf; +extern PFNGLCLEARSTENCILPROC glClearStencil; +extern PFNGLCOLORMASKPROC glColorMask; +extern PFNGLCOMPILESHADERPROC glCompileShader; +extern PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; +extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; +extern PFNGLCOPYTEXIMAGE2DPROC glCopyTexImage2D; +extern PFNGLCOPYTEXSUBIMAGE2DPROC glCopyTexSubImage2D; +extern PFNGLCREATEPROGRAMPROC glCreateProgram; +extern PFNGLCREATESHADERPROC glCreateShader; +extern PFNGLCULLFACEPROC glCullFace; +extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; +extern PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; +extern PFNGLDELETEPROGRAMPROC glDeleteProgram; +extern PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; +extern PFNGLDELETESHADERPROC glDeleteShader; +extern PFNGLDELETETEXTURESPROC glDeleteTextures; +extern PFNGLDEPTHFUNCPROC glDepthFunc; +extern PFNGLDEPTHMASKPROC glDepthMask; +extern PFNGLDEPTHRANGEFPROC glDepthRangef; +extern PFNGLDETACHSHADERPROC glDetachShader; +extern PFNGLDISABLEPROC glDisable; +extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; +extern PFNGLDRAWARRAYSPROC glDrawArrays; +extern PFNGLDRAWELEMENTSPROC glDrawElements; +extern PFNGLENABLEPROC glEnable; +extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; +extern PFNGLFINISHPROC glFinish; +extern PFNGLFLUSHPROC glFlush; +extern PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; +extern PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; +extern PFNGLFRONTFACEPROC glFrontFace; +extern PFNGLGENBUFFERSPROC glGenBuffers; +extern PFNGLGENERATEMIPMAPPROC glGenerateMipmap; +extern PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; +extern PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; +extern PFNGLGENTEXTURESPROC glGenTextures; +extern PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; +extern PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; +extern PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; +extern PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; +extern PFNGLGETBOOLEANVPROC glGetBooleanv; +extern PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; +extern PFNGLGETERRORPROC glGetError; +extern PFNGLGETFLOATVPROC glGetFloatv; extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetFramebufferAttachmentParameteriv; -extern PFNGLGETINTEGERVPROC glGetIntegerv; -extern PFNGLGETPROGRAMIVPROC glGetProgramiv; -extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; -extern PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; -extern PFNGLGETSHADERIVPROC glGetShaderiv; -extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; -extern PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; -extern PFNGLGETSHADERSOURCEPROC glGetShaderSource; -extern PFNGLGETSTRINGPROC glGetString; -extern PFNGLGETTEXPARAMETERFVPROC glGetTexParameterfv; -extern PFNGLGETTEXPARAMETERIVPROC glGetTexParameteriv; -extern PFNGLGETUNIFORMFVPROC glGetUniformfv; -extern PFNGLGETUNIFORMIVPROC glGetUniformiv; -extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; -extern PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; -extern PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; -extern PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; -extern PFNGLHINTPROC glHint; -extern PFNGLISBUFFERPROC glIsBuffer; -extern PFNGLISENABLEDPROC glIsEnabled; -extern PFNGLISFRAMEBUFFERPROC glIsFramebuffer; -extern PFNGLISPROGRAMPROC glIsProgram; -extern PFNGLISRENDERBUFFERPROC glIsRenderbuffer; -extern PFNGLISSHADERPROC glIsShader; -extern PFNGLISTEXTUREPROC glIsTexture; -extern PFNGLLINEWIDTHPROC glLineWidth; -extern PFNGLLINKPROGRAMPROC glLinkProgram; -extern PFNGLPIXELSTOREIPROC glPixelStorei; -extern PFNGLPOLYGONOFFSETPROC glPolygonOffset; -extern PFNGLREADPIXELSPROC glReadPixels; -extern PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; -extern PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; -extern PFNGLSAMPLECOVERAGEPROC glSampleCoverage; -extern PFNGLSCISSORPROC glScissor; -extern PFNGLSHADERBINARYPROC glShaderBinary; -extern PFNGLSHADERSOURCEPROC glShaderSource; -extern PFNGLSTENCILFUNCPROC glStencilFunc; -extern PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; -extern PFNGLSTENCILMASKPROC glStencilMask; -extern PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; -extern PFNGLSTENCILOPPROC glStencilOp; -extern PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; -extern PFNGLTEXIMAGE2DPROC glTexImage2D; -extern PFNGLTEXPARAMETERFPROC glTexParameterf; -extern PFNGLTEXPARAMETERFVPROC glTexParameterfv; -extern PFNGLTEXPARAMETERIPROC glTexParameteri; -extern PFNGLTEXPARAMETERIVPROC glTexParameteriv; -extern PFNGLTEXSUBIMAGE2DPROC glTexSubImage2D; -extern PFNGLUNIFORM1FPROC glUniform1f; -extern PFNGLUNIFORM1FVPROC glUniform1fv; -extern PFNGLUNIFORM1IPROC glUniform1i; -extern PFNGLUNIFORM1IVPROC glUniform1iv; -extern PFNGLUNIFORM2FPROC glUniform2f; -extern PFNGLUNIFORM2FVPROC glUniform2fv; -extern PFNGLUNIFORM2IPROC glUniform2i; -extern PFNGLUNIFORM2IVPROC glUniform2iv; -extern PFNGLUNIFORM3FPROC glUniform3f; -extern PFNGLUNIFORM3FVPROC glUniform3fv; -extern PFNGLUNIFORM3IPROC glUniform3i; -extern PFNGLUNIFORM3IVPROC glUniform3iv; -extern PFNGLUNIFORM4FPROC glUniform4f; -extern PFNGLUNIFORM4FVPROC glUniform4fv; -extern PFNGLUNIFORM4IPROC glUniform4i; -extern PFNGLUNIFORM4IVPROC glUniform4iv; -extern PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; -extern PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; -extern PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; -extern PFNGLUSEPROGRAMPROC glUseProgram; -extern PFNGLVALIDATEPROGRAMPROC glValidateProgram; -extern PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; -extern PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; -extern PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; -extern PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; -extern PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; -extern PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; -extern PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; -extern PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; -extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; -extern PFNGLVIEWPORTPROC glViewport; +extern PFNGLGETINTEGERVPROC glGetIntegerv; +extern PFNGLGETPROGRAMIVPROC glGetProgramiv; +extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; +extern PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; +extern PFNGLGETSHADERIVPROC glGetShaderiv; +extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; +extern PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; +extern PFNGLGETSHADERSOURCEPROC glGetShaderSource; +extern PFNGLGETSTRINGPROC glGetString; +extern PFNGLGETTEXPARAMETERFVPROC glGetTexParameterfv; +extern PFNGLGETTEXPARAMETERIVPROC glGetTexParameteriv; +extern PFNGLGETUNIFORMFVPROC glGetUniformfv; +extern PFNGLGETUNIFORMIVPROC glGetUniformiv; +extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; +extern PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; +extern PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; +extern PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; +extern PFNGLHINTPROC glHint; +extern PFNGLISBUFFERPROC glIsBuffer; +extern PFNGLISENABLEDPROC glIsEnabled; +extern PFNGLISFRAMEBUFFERPROC glIsFramebuffer; +extern PFNGLISPROGRAMPROC glIsProgram; +extern PFNGLISRENDERBUFFERPROC glIsRenderbuffer; +extern PFNGLISSHADERPROC glIsShader; +extern PFNGLISTEXTUREPROC glIsTexture; +extern PFNGLLINEWIDTHPROC glLineWidth; +extern PFNGLLINKPROGRAMPROC glLinkProgram; +extern PFNGLPIXELSTOREIPROC glPixelStorei; +extern PFNGLPOLYGONOFFSETPROC glPolygonOffset; +extern PFNGLREADPIXELSPROC glReadPixels; +extern PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; +extern PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; +extern PFNGLSAMPLECOVERAGEPROC glSampleCoverage; +extern PFNGLSCISSORPROC glScissor; +extern PFNGLSHADERBINARYPROC glShaderBinary; +extern PFNGLSHADERSOURCEPROC glShaderSource; +extern PFNGLSTENCILFUNCPROC glStencilFunc; +extern PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; +extern PFNGLSTENCILMASKPROC glStencilMask; +extern PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; +extern PFNGLSTENCILOPPROC glStencilOp; +extern PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; +extern PFNGLTEXIMAGE2DPROC glTexImage2D; +extern PFNGLTEXPARAMETERFPROC glTexParameterf; +extern PFNGLTEXPARAMETERFVPROC glTexParameterfv; +extern PFNGLTEXPARAMETERIPROC glTexParameteri; +extern PFNGLTEXPARAMETERIVPROC glTexParameteriv; +extern PFNGLTEXSUBIMAGE2DPROC glTexSubImage2D; +extern PFNGLUNIFORM1FPROC glUniform1f; +extern PFNGLUNIFORM1FVPROC glUniform1fv; +extern PFNGLUNIFORM1IPROC glUniform1i; +extern PFNGLUNIFORM1IVPROC glUniform1iv; +extern PFNGLUNIFORM2FPROC glUniform2f; +extern PFNGLUNIFORM2FVPROC glUniform2fv; +extern PFNGLUNIFORM2IPROC glUniform2i; +extern PFNGLUNIFORM2IVPROC glUniform2iv; +extern PFNGLUNIFORM3FPROC glUniform3f; +extern PFNGLUNIFORM3FVPROC glUniform3fv; +extern PFNGLUNIFORM3IPROC glUniform3i; +extern PFNGLUNIFORM3IVPROC glUniform3iv; +extern PFNGLUNIFORM4FPROC glUniform4f; +extern PFNGLUNIFORM4FVPROC glUniform4fv; +extern PFNGLUNIFORM4IPROC glUniform4i; +extern PFNGLUNIFORM4IVPROC glUniform4iv; +extern PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; +extern PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; +extern PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; +extern PFNGLUSEPROGRAMPROC glUseProgram; +extern PFNGLVALIDATEPROGRAMPROC glValidateProgram; +extern PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; +extern PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; +extern PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; +extern PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; +extern PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; +extern PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; +extern PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; +extern PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; +extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; +extern PFNGLVIEWPORTPROC glViewport; #if defined(GL_AMD_framebuffer_multisample_advanced) -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glRenderbufferStorageMultisampleAdvancedAMD; +extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glRenderbufferStorageMultisampleAdvancedAMD; extern PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC glNamedRenderbufferStorageMultisampleAdvancedAMD; #endif /* defined(GL_AMD_framebuffer_multisample_advanced) */ #if defined(GL_AMD_performance_monitor) -extern PFNGLGETPERFMONITORGROUPSAMDPROC glGetPerfMonitorGroupsAMD; -extern PFNGLGETPERFMONITORCOUNTERSAMDPROC glGetPerfMonitorCountersAMD; -extern PFNGLGETPERFMONITORGROUPSTRINGAMDPROC glGetPerfMonitorGroupStringAMD; +extern PFNGLGETPERFMONITORGROUPSAMDPROC glGetPerfMonitorGroupsAMD; +extern PFNGLGETPERFMONITORCOUNTERSAMDPROC glGetPerfMonitorCountersAMD; +extern PFNGLGETPERFMONITORGROUPSTRINGAMDPROC glGetPerfMonitorGroupStringAMD; extern PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC glGetPerfMonitorCounterStringAMD; -extern PFNGLGETPERFMONITORCOUNTERINFOAMDPROC glGetPerfMonitorCounterInfoAMD; -extern PFNGLGENPERFMONITORSAMDPROC glGenPerfMonitorsAMD; -extern PFNGLDELETEPERFMONITORSAMDPROC glDeletePerfMonitorsAMD; -extern PFNGLSELECTPERFMONITORCOUNTERSAMDPROC glSelectPerfMonitorCountersAMD; -extern PFNGLBEGINPERFMONITORAMDPROC glBeginPerfMonitorAMD; -extern PFNGLENDPERFMONITORAMDPROC glEndPerfMonitorAMD; -extern PFNGLGETPERFMONITORCOUNTERDATAAMDPROC glGetPerfMonitorCounterDataAMD; +extern PFNGLGETPERFMONITORCOUNTERINFOAMDPROC glGetPerfMonitorCounterInfoAMD; +extern PFNGLGENPERFMONITORSAMDPROC glGenPerfMonitorsAMD; +extern PFNGLDELETEPERFMONITORSAMDPROC glDeletePerfMonitorsAMD; +extern PFNGLSELECTPERFMONITORCOUNTERSAMDPROC glSelectPerfMonitorCountersAMD; +extern PFNGLBEGINPERFMONITORAMDPROC glBeginPerfMonitorAMD; +extern PFNGLENDPERFMONITORAMDPROC glEndPerfMonitorAMD; +extern PFNGLGETPERFMONITORCOUNTERDATAAMDPROC glGetPerfMonitorCounterDataAMD; #endif /* defined(GL_AMD_performance_monitor) */ #if defined(GL_ANGLE_framebuffer_blit) @@ -215,9 +215,9 @@ extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC glRenderbufferStorageMultisa #endif /* defined(GL_ANGLE_framebuffer_multisample) */ #if defined(GL_ANGLE_instanced_arrays) -extern PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE; +extern PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE; extern PFNGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstancedANGLE; -extern PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE; +extern PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE; #endif /* defined(GL_ANGLE_instanced_arrays) */ #if defined(GL_ANGLE_translated_shader_source) @@ -230,17 +230,17 @@ extern PFNGLCOPYTEXTURELEVELSAPPLEPROC glCopyTextureLevelsAPPLE; #if defined(GL_APPLE_framebuffer_multisample) extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC glRenderbufferStorageMultisampleAPPLE; -extern PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC glResolveMultisampleFramebufferAPPLE; +extern PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC glResolveMultisampleFramebufferAPPLE; #endif /* defined(GL_APPLE_framebuffer_multisample) */ #if defined(GL_APPLE_sync) -extern PFNGLFENCESYNCAPPLEPROC glFenceSyncAPPLE; -extern PFNGLISSYNCAPPLEPROC glIsSyncAPPLE; -extern PFNGLDELETESYNCAPPLEPROC glDeleteSyncAPPLE; +extern PFNGLFENCESYNCAPPLEPROC glFenceSyncAPPLE; +extern PFNGLISSYNCAPPLEPROC glIsSyncAPPLE; +extern PFNGLDELETESYNCAPPLEPROC glDeleteSyncAPPLE; extern PFNGLCLIENTWAITSYNCAPPLEPROC glClientWaitSyncAPPLE; -extern PFNGLWAITSYNCAPPLEPROC glWaitSyncAPPLE; -extern PFNGLGETINTEGER64VAPPLEPROC glGetInteger64vAPPLE; -extern PFNGLGETSYNCIVAPPLEPROC glGetSyncivAPPLE; +extern PFNGLWAITSYNCAPPLEPROC glWaitSyncAPPLE; +extern PFNGLGETINTEGER64VAPPLEPROC glGetInteger64vAPPLE; +extern PFNGLGETSYNCIVAPPLEPROC glGetSyncivAPPLE; #endif /* defined(GL_APPLE_sync) */ #if defined(GL_EXT_EGL_image_storage) @@ -250,16 +250,16 @@ extern PFNGLEGLIMAGETARGETTEXTURESTORAGEEXTPROC glEGLImageTargetTextureStorageEX #endif /* defined(GL_EXT_EGL_image_storage) */ #if defined(GL_EXT_base_instance) -extern PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC glDrawArraysInstancedBaseInstanceEXT; -extern PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC glDrawElementsInstancedBaseInstanceEXT; +extern PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC glDrawArraysInstancedBaseInstanceEXT; +extern PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC glDrawElementsInstancedBaseInstanceEXT; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC glDrawElementsInstancedBaseVertexBaseInstanceEXT; #endif /* defined(GL_EXT_base_instance) */ #if defined(GL_EXT_blend_func_extended) -extern PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC glBindFragDataLocationIndexedEXT; -extern PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocationEXT; +extern PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC glBindFragDataLocationIndexedEXT; +extern PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocationEXT; extern PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC glGetProgramResourceLocationIndexEXT; -extern PFNGLGETFRAGDATAINDEXEXTPROC glGetFragDataIndexEXT; +extern PFNGLGETFRAGDATAINDEXEXTPROC glGetFragDataIndexEXT; #endif /* defined(GL_EXT_blend_func_extended) */ #if defined(GL_EXT_buffer_storage) @@ -267,7 +267,7 @@ extern PFNGLBUFFERSTORAGEEXTPROC glBufferStorageEXT; #endif /* defined(GL_EXT_buffer_storage) */ #if defined(GL_EXT_clear_texture) -extern PFNGLCLEARTEXIMAGEEXTPROC glClearTexImageEXT; +extern PFNGLCLEARTEXIMAGEEXTPROC glClearTexImageEXT; extern PFNGLCLEARTEXSUBIMAGEEXTPROC glClearTexSubImageEXT; #endif /* defined(GL_EXT_clear_texture) */ @@ -280,14 +280,14 @@ extern PFNGLCOPYIMAGESUBDATAEXTPROC glCopyImageSubDataEXT; #endif /* defined(GL_EXT_copy_image) */ #if defined(GL_EXT_debug_label) -extern PFNGLLABELOBJECTEXTPROC glLabelObjectEXT; +extern PFNGLLABELOBJECTEXTPROC glLabelObjectEXT; extern PFNGLGETOBJECTLABELEXTPROC glGetObjectLabelEXT; #endif /* defined(GL_EXT_debug_label) */ #if defined(GL_EXT_debug_marker) extern PFNGLINSERTEVENTMARKEREXTPROC glInsertEventMarkerEXT; -extern PFNGLPUSHGROUPMARKEREXTPROC glPushGroupMarkerEXT; -extern PFNGLPOPGROUPMARKEREXTPROC glPopGroupMarkerEXT; +extern PFNGLPUSHGROUPMARKEREXTPROC glPushGroupMarkerEXT; +extern PFNGLPOPGROUPMARKEREXTPROC glPopGroupMarkerEXT; #endif /* defined(GL_EXT_debug_marker) */ #if defined(GL_EXT_discard_framebuffer) @@ -295,18 +295,18 @@ extern PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT; #endif /* defined(GL_EXT_discard_framebuffer) */ #if defined(GL_EXT_disjoint_timer_query) -extern PFNGLGENQUERIESEXTPROC glGenQueriesEXT; -extern PFNGLDELETEQUERIESEXTPROC glDeleteQueriesEXT; -extern PFNGLISQUERYEXTPROC glIsQueryEXT; -extern PFNGLBEGINQUERYEXTPROC glBeginQueryEXT; -extern PFNGLENDQUERYEXTPROC glEndQueryEXT; -extern PFNGLQUERYCOUNTEREXTPROC glQueryCounterEXT; -extern PFNGLGETQUERYIVEXTPROC glGetQueryivEXT; -extern PFNGLGETQUERYOBJECTIVEXTPROC glGetQueryObjectivEXT; -extern PFNGLGETQUERYOBJECTUIVEXTPROC glGetQueryObjectuivEXT; -extern PFNGLGETQUERYOBJECTI64VEXTPROC glGetQueryObjecti64vEXT; +extern PFNGLGENQUERIESEXTPROC glGenQueriesEXT; +extern PFNGLDELETEQUERIESEXTPROC glDeleteQueriesEXT; +extern PFNGLISQUERYEXTPROC glIsQueryEXT; +extern PFNGLBEGINQUERYEXTPROC glBeginQueryEXT; +extern PFNGLENDQUERYEXTPROC glEndQueryEXT; +extern PFNGLQUERYCOUNTEREXTPROC glQueryCounterEXT; +extern PFNGLGETQUERYIVEXTPROC glGetQueryivEXT; +extern PFNGLGETQUERYOBJECTIVEXTPROC glGetQueryObjectivEXT; +extern PFNGLGETQUERYOBJECTUIVEXTPROC glGetQueryObjectuivEXT; +extern PFNGLGETQUERYOBJECTI64VEXTPROC glGetQueryObjecti64vEXT; extern PFNGLGETQUERYOBJECTUI64VEXTPROC glGetQueryObjectui64vEXT; -extern PFNGLGETINTEGER64VEXTPROC glGetInteger64vEXT; +extern PFNGLGETINTEGER64VEXTPROC glGetInteger64vEXT; #endif /* defined(GL_EXT_disjoint_timer_query) */ #if defined(GL_EXT_draw_buffers) @@ -314,35 +314,35 @@ extern PFNGLDRAWBUFFERSEXTPROC glDrawBuffersEXT; #endif /* defined(GL_EXT_draw_buffers) */ #if defined(GL_EXT_draw_buffers_indexed) -extern PFNGLENABLEIEXTPROC glEnableiEXT; -extern PFNGLDISABLEIEXTPROC glDisableiEXT; -extern PFNGLBLENDEQUATIONIEXTPROC glBlendEquationiEXT; +extern PFNGLENABLEIEXTPROC glEnableiEXT; +extern PFNGLDISABLEIEXTPROC glDisableiEXT; +extern PFNGLBLENDEQUATIONIEXTPROC glBlendEquationiEXT; extern PFNGLBLENDEQUATIONSEPARATEIEXTPROC glBlendEquationSeparateiEXT; -extern PFNGLBLENDFUNCIEXTPROC glBlendFunciEXT; -extern PFNGLBLENDFUNCSEPARATEIEXTPROC glBlendFuncSeparateiEXT; -extern PFNGLCOLORMASKIEXTPROC glColorMaskiEXT; -extern PFNGLISENABLEDIEXTPROC glIsEnablediEXT; +extern PFNGLBLENDFUNCIEXTPROC glBlendFunciEXT; +extern PFNGLBLENDFUNCSEPARATEIEXTPROC glBlendFuncSeparateiEXT; +extern PFNGLCOLORMASKIEXTPROC glColorMaskiEXT; +extern PFNGLISENABLEDIEXTPROC glIsEnablediEXT; #endif /* defined(GL_EXT_draw_buffers_indexed) */ #if defined(GL_EXT_draw_elements_base_vertex) -extern PFNGLDRAWELEMENTSBASEVERTEXEXTPROC glDrawElementsBaseVertexEXT; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC glDrawRangeElementsBaseVertexEXT; +extern PFNGLDRAWELEMENTSBASEVERTEXEXTPROC glDrawElementsBaseVertexEXT; +extern PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC glDrawRangeElementsBaseVertexEXT; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC glDrawElementsInstancedBaseVertexEXT; -extern PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC glMultiDrawElementsBaseVertexEXT; +extern PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC glMultiDrawElementsBaseVertexEXT; #endif /* defined(GL_EXT_draw_elements_base_vertex) */ #if defined(GL_EXT_draw_instanced) -extern PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstancedEXT; +extern PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstancedEXT; extern PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstancedEXT; #endif /* defined(GL_EXT_draw_instanced) */ #if defined(GL_EXT_draw_transform_feedback) -extern PFNGLDRAWTRANSFORMFEEDBACKEXTPROC glDrawTransformFeedbackEXT; +extern PFNGLDRAWTRANSFORMFEEDBACKEXTPROC glDrawTransformFeedbackEXT; extern PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDEXTPROC glDrawTransformFeedbackInstancedEXT; #endif /* defined(GL_EXT_draw_transform_feedback) */ #if defined(GL_EXT_external_buffer) -extern PFNGLBUFFERSTORAGEEXTERNALEXTPROC glBufferStorageExternalEXT; +extern PFNGLBUFFERSTORAGEEXTERNALEXTPROC glBufferStorageExternalEXT; extern PFNGLNAMEDBUFFERSTORAGEEXTERNALEXTPROC glNamedBufferStorageExternalEXT; #endif /* defined(GL_EXT_external_buffer) */ @@ -355,29 +355,29 @@ extern PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisorEXT; #endif /* defined(GL_EXT_instanced_arrays) */ #if defined(GL_EXT_map_buffer_range) -extern PFNGLMAPBUFFERRANGEEXTPROC glMapBufferRangeEXT; +extern PFNGLMAPBUFFERRANGEEXTPROC glMapBufferRangeEXT; extern PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC glFlushMappedBufferRangeEXT; #endif /* defined(GL_EXT_map_buffer_range) */ #if defined(GL_EXT_memory_object) -extern PFNGLGETUNSIGNEDBYTEVEXTPROC glGetUnsignedBytevEXT; -extern PFNGLGETUNSIGNEDBYTEI_VEXTPROC glGetUnsignedBytei_vEXT; // NOLINT(readability-identifier-naming) -extern PFNGLDELETEMEMORYOBJECTSEXTPROC glDeleteMemoryObjectsEXT; -extern PFNGLISMEMORYOBJECTEXTPROC glIsMemoryObjectEXT; -extern PFNGLCREATEMEMORYOBJECTSEXTPROC glCreateMemoryObjectsEXT; -extern PFNGLMEMORYOBJECTPARAMETERIVEXTPROC glMemoryObjectParameterivEXT; +extern PFNGLGETUNSIGNEDBYTEVEXTPROC glGetUnsignedBytevEXT; +extern PFNGLGETUNSIGNEDBYTEI_VEXTPROC glGetUnsignedBytei_vEXT; // NOLINT(readability-identifier-naming) +extern PFNGLDELETEMEMORYOBJECTSEXTPROC glDeleteMemoryObjectsEXT; +extern PFNGLISMEMORYOBJECTEXTPROC glIsMemoryObjectEXT; +extern PFNGLCREATEMEMORYOBJECTSEXTPROC glCreateMemoryObjectsEXT; +extern PFNGLMEMORYOBJECTPARAMETERIVEXTPROC glMemoryObjectParameterivEXT; extern PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC glGetMemoryObjectParameterivEXT; -extern PFNGLTEXSTORAGEMEM2DEXTPROC glTexStorageMem2DEXT; +extern PFNGLTEXSTORAGEMEM2DEXTPROC glTexStorageMem2DEXT; extern PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC glTexStorageMem2DMultisampleEXT; -extern PFNGLTEXSTORAGEMEM3DEXTPROC glTexStorageMem3DEXT; +extern PFNGLTEXSTORAGEMEM3DEXTPROC glTexStorageMem3DEXT; extern PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC glTexStorageMem3DMultisampleEXT; -extern PFNGLBUFFERSTORAGEMEMEXTPROC glBufferStorageMemEXT; +extern PFNGLBUFFERSTORAGEMEMEXTPROC glBufferStorageMemEXT; -extern PFNGLTEXTURESTORAGEMEM2DEXTPROC glTextureStorageMem2DEXT; +extern PFNGLTEXTURESTORAGEMEM2DEXTPROC glTextureStorageMem2DEXT; extern PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC glTextureStorageMem2DMultisampleEXT; -extern PFNGLTEXTURESTORAGEMEM3DEXTPROC glTextureStorageMem3DEXT; +extern PFNGLTEXTURESTORAGEMEM3DEXTPROC glTextureStorageMem3DEXT; extern PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC glTextureStorageMem3DMultisampleEXT; -extern PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC glNamedBufferStorageMemEXT; +extern PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC glNamedBufferStorageMemEXT; #endif /* defined(GL_EXT_memory_object) */ #if defined(GL_EXT_memory_object_fd) @@ -386,29 +386,29 @@ extern PFNGLIMPORTMEMORYFDEXTPROC glImportMemoryFdEXT; #if defined(GL_EXT_memory_object_win32) extern PFNGLIMPORTMEMORYWIN32HANDLEEXTPROC glImportMemoryWin32HandleEXT; -extern PFNGLIMPORTMEMORYWIN32NAMEEXTPROC glImportMemoryWin32NameEXT; +extern PFNGLIMPORTMEMORYWIN32NAMEEXTPROC glImportMemoryWin32NameEXT; #endif /* defined(GL_EXT_memory_object_win32) */ #if defined(GL_EXT_multi_draw_arrays) -extern PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArraysEXT; +extern PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArraysEXT; extern PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElementsEXT; #endif /* defined(GL_EXT_multi_draw_arrays) */ #if defined(GL_EXT_multi_draw_indirect) -extern PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC glMultiDrawArraysIndirectEXT; +extern PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC glMultiDrawArraysIndirectEXT; extern PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC glMultiDrawElementsIndirectEXT; #endif /* defined(GL_EXT_multi_draw_indirect) */ #if defined(GL_EXT_multisampled_render_to_texture) -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT; +extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT; extern PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC glFramebufferTexture2DMultisampleEXT; #endif /* defined(GL_EXT_multisampled_render_to_texture) */ #if defined(GL_EXT_multiview_draw_buffers) -extern PFNGLREADBUFFERINDEXEDEXTPROC glReadBufferIndexedEXT; +extern PFNGLREADBUFFERINDEXEDEXTPROC glReadBufferIndexedEXT; extern PFNGLDRAWBUFFERSINDEXEDEXTPROC glDrawBuffersIndexedEXT; -extern PFNGLGETINTEGERI_VEXTPROC glGetIntegeri_vEXT; // NOLINT(readability-identifier-naming) -#endif /* defined(GL_EXT_multiview_draw_buffers) */ +extern PFNGLGETINTEGERI_VEXTPROC glGetIntegeri_vEXT; // NOLINT(readability-identifier-naming) +#endif /* defined(GL_EXT_multiview_draw_buffers) */ #if defined(GL_EXT_polygon_offset_clamp) extern PFNGLPOLYGONOFFSETCLAMPEXTPROC glPolygonOffsetClampEXT; @@ -424,19 +424,19 @@ extern PFNGLRASTERSAMPLESEXTPROC glRasterSamplesEXT; #if defined(GL_EXT_robustness) extern PFNGLGETGRAPHICSRESETSTATUSEXTPROC glGetGraphicsResetStatusEXT; -extern PFNGLREADNPIXELSEXTPROC glReadnPixelsEXT; -extern PFNGLGETNUNIFORMFVEXTPROC glGetnUniformfvEXT; -extern PFNGLGETNUNIFORMIVEXTPROC glGetnUniformivEXT; +extern PFNGLREADNPIXELSEXTPROC glReadnPixelsEXT; +extern PFNGLGETNUNIFORMFVEXTPROC glGetnUniformfvEXT; +extern PFNGLGETNUNIFORMIVEXTPROC glGetnUniformivEXT; #endif /* defined(GL_EXT_robustness) */ #if defined(GL_EXT_semaphore) -extern PFNGLGENSEMAPHORESEXTPROC glGenSemaphoresEXT; -extern PFNGLDELETESEMAPHORESEXTPROC glDeleteSemaphoresEXT; -extern PFNGLISSEMAPHOREEXTPROC glIsSemaphoreEXT; -extern PFNGLSEMAPHOREPARAMETERUI64VEXTPROC glSemaphoreParameterui64vEXT; +extern PFNGLGENSEMAPHORESEXTPROC glGenSemaphoresEXT; +extern PFNGLDELETESEMAPHORESEXTPROC glDeleteSemaphoresEXT; +extern PFNGLISSEMAPHOREEXTPROC glIsSemaphoreEXT; +extern PFNGLSEMAPHOREPARAMETERUI64VEXTPROC glSemaphoreParameterui64vEXT; extern PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC glGetSemaphoreParameterui64vEXT; -extern PFNGLWAITSEMAPHOREEXTPROC glWaitSemaphoreEXT; -extern PFNGLSIGNALSEMAPHOREEXTPROC glSignalSemaphoreEXT; +extern PFNGLWAITSEMAPHOREEXTPROC glWaitSemaphoreEXT; +extern PFNGLSIGNALSEMAPHOREEXTPROC glSignalSemaphoreEXT; #endif /* defined(GL_EXT_semaphore) */ #if defined(GL_EXT_semaphore_fd) @@ -445,49 +445,49 @@ extern PFNGLIMPORTSEMAPHOREFDEXTPROC glImportSemaphoreFdEXT; #if defined(GL_EXT_semaphore_win32) extern PFNGLIMPORTSEMAPHOREWIN32HANDLEEXTPROC glImportSemaphoreWin32HandleEXT; -extern PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC glImportSemaphoreWin32NameEXT; +extern PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC glImportSemaphoreWin32NameEXT; #endif /* defined(GL_EXT_semaphore_win32) */ #if defined(GL_EXT_separate_shader_objects) -extern PFNGLACTIVESHADERPROGRAMEXTPROC glActiveShaderProgramEXT; -extern PFNGLBINDPROGRAMPIPELINEEXTPROC glBindProgramPipelineEXT; -extern PFNGLCREATESHADERPROGRAMVEXTPROC glCreateShaderProgramvEXT; -extern PFNGLDELETEPROGRAMPIPELINESEXTPROC glDeleteProgramPipelinesEXT; -extern PFNGLGENPROGRAMPIPELINESEXTPROC glGenProgramPipelinesEXT; +extern PFNGLACTIVESHADERPROGRAMEXTPROC glActiveShaderProgramEXT; +extern PFNGLBINDPROGRAMPIPELINEEXTPROC glBindProgramPipelineEXT; +extern PFNGLCREATESHADERPROGRAMVEXTPROC glCreateShaderProgramvEXT; +extern PFNGLDELETEPROGRAMPIPELINESEXTPROC glDeleteProgramPipelinesEXT; +extern PFNGLGENPROGRAMPIPELINESEXTPROC glGenProgramPipelinesEXT; extern PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC glGetProgramPipelineInfoLogEXT; -extern PFNGLGETPROGRAMPIPELINEIVEXTPROC glGetProgramPipelineivEXT; -extern PFNGLISPROGRAMPIPELINEEXTPROC glIsProgramPipelineEXT; -extern PFNGLPROGRAMPARAMETERIEXTPROC glProgramParameteriEXT; -extern PFNGLPROGRAMUNIFORM1FEXTPROC glProgramUniform1fEXT; -extern PFNGLPROGRAMUNIFORM1FVEXTPROC glProgramUniform1fvEXT; -extern PFNGLPROGRAMUNIFORM1IEXTPROC glProgramUniform1iEXT; -extern PFNGLPROGRAMUNIFORM1IVEXTPROC glProgramUniform1ivEXT; -extern PFNGLPROGRAMUNIFORM2FEXTPROC glProgramUniform2fEXT; -extern PFNGLPROGRAMUNIFORM2FVEXTPROC glProgramUniform2fvEXT; -extern PFNGLPROGRAMUNIFORM2IEXTPROC glProgramUniform2iEXT; -extern PFNGLPROGRAMUNIFORM2IVEXTPROC glProgramUniform2ivEXT; -extern PFNGLPROGRAMUNIFORM3FEXTPROC glProgramUniform3fEXT; -extern PFNGLPROGRAMUNIFORM3FVEXTPROC glProgramUniform3fvEXT; -extern PFNGLPROGRAMUNIFORM3IEXTPROC glProgramUniform3iEXT; -extern PFNGLPROGRAMUNIFORM3IVEXTPROC glProgramUniform3ivEXT; -extern PFNGLPROGRAMUNIFORM4FEXTPROC glProgramUniform4fEXT; -extern PFNGLPROGRAMUNIFORM4FVEXTPROC glProgramUniform4fvEXT; -extern PFNGLPROGRAMUNIFORM4IEXTPROC glProgramUniform4iEXT; -extern PFNGLPROGRAMUNIFORM4IVEXTPROC glProgramUniform4ivEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC glProgramUniformMatrix2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC glProgramUniformMatrix3fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC glProgramUniformMatrix4fvEXT; -extern PFNGLUSEPROGRAMSTAGESEXTPROC glUseProgramStagesEXT; -extern PFNGLVALIDATEPROGRAMPIPELINEEXTPROC glValidateProgramPipelineEXT; +extern PFNGLGETPROGRAMPIPELINEIVEXTPROC glGetProgramPipelineivEXT; +extern PFNGLISPROGRAMPIPELINEEXTPROC glIsProgramPipelineEXT; +extern PFNGLPROGRAMPARAMETERIEXTPROC glProgramParameteriEXT; +extern PFNGLPROGRAMUNIFORM1FEXTPROC glProgramUniform1fEXT; +extern PFNGLPROGRAMUNIFORM1FVEXTPROC glProgramUniform1fvEXT; +extern PFNGLPROGRAMUNIFORM1IEXTPROC glProgramUniform1iEXT; +extern PFNGLPROGRAMUNIFORM1IVEXTPROC glProgramUniform1ivEXT; +extern PFNGLPROGRAMUNIFORM2FEXTPROC glProgramUniform2fEXT; +extern PFNGLPROGRAMUNIFORM2FVEXTPROC glProgramUniform2fvEXT; +extern PFNGLPROGRAMUNIFORM2IEXTPROC glProgramUniform2iEXT; +extern PFNGLPROGRAMUNIFORM2IVEXTPROC glProgramUniform2ivEXT; +extern PFNGLPROGRAMUNIFORM3FEXTPROC glProgramUniform3fEXT; +extern PFNGLPROGRAMUNIFORM3FVEXTPROC glProgramUniform3fvEXT; +extern PFNGLPROGRAMUNIFORM3IEXTPROC glProgramUniform3iEXT; +extern PFNGLPROGRAMUNIFORM3IVEXTPROC glProgramUniform3ivEXT; +extern PFNGLPROGRAMUNIFORM4FEXTPROC glProgramUniform4fEXT; +extern PFNGLPROGRAMUNIFORM4FVEXTPROC glProgramUniform4fvEXT; +extern PFNGLPROGRAMUNIFORM4IEXTPROC glProgramUniform4iEXT; +extern PFNGLPROGRAMUNIFORM4IVEXTPROC glProgramUniform4ivEXT; +extern PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC glProgramUniformMatrix2fvEXT; +extern PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC glProgramUniformMatrix3fvEXT; +extern PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC glProgramUniformMatrix4fvEXT; +extern PFNGLUSEPROGRAMSTAGESEXTPROC glUseProgramStagesEXT; +extern PFNGLVALIDATEPROGRAMPIPELINEEXTPROC glValidateProgramPipelineEXT; -extern PFNGLPROGRAMUNIFORM1UIEXTPROC glProgramUniform1uiEXT; -extern PFNGLPROGRAMUNIFORM2UIEXTPROC glProgramUniform2uiEXT; -extern PFNGLPROGRAMUNIFORM3UIEXTPROC glProgramUniform3uiEXT; -extern PFNGLPROGRAMUNIFORM4UIEXTPROC glProgramUniform4uiEXT; -extern PFNGLPROGRAMUNIFORM1UIVEXTPROC glProgramUniform1uivEXT; -extern PFNGLPROGRAMUNIFORM2UIVEXTPROC glProgramUniform2uivEXT; -extern PFNGLPROGRAMUNIFORM3UIVEXTPROC glProgramUniform3uivEXT; -extern PFNGLPROGRAMUNIFORM4UIVEXTPROC glProgramUniform4uivEXT; +extern PFNGLPROGRAMUNIFORM1UIEXTPROC glProgramUniform1uiEXT; +extern PFNGLPROGRAMUNIFORM2UIEXTPROC glProgramUniform2uiEXT; +extern PFNGLPROGRAMUNIFORM3UIEXTPROC glProgramUniform3uiEXT; +extern PFNGLPROGRAMUNIFORM4UIEXTPROC glProgramUniform4uiEXT; +extern PFNGLPROGRAMUNIFORM1UIVEXTPROC glProgramUniform1uivEXT; +extern PFNGLPROGRAMUNIFORM2UIVEXTPROC glProgramUniform2uivEXT; +extern PFNGLPROGRAMUNIFORM3UIVEXTPROC glProgramUniform3uivEXT; +extern PFNGLPROGRAMUNIFORM4UIVEXTPROC glProgramUniform4uivEXT; extern PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC glProgramUniformMatrix2x3fvEXT; extern PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC glProgramUniformMatrix3x2fvEXT; extern PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC glProgramUniformMatrix2x4fvEXT; @@ -501,9 +501,9 @@ extern PFNGLFRAMEBUFFERFETCHBARRIEREXTPROC glFramebufferFetchBarrierEXT; #endif /* defined(GL_EXT_shader_framebuffer_fetch_non_coherent) */ #if defined(GL_EXT_shader_pixel_local_storage2) -extern PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glFramebufferPixelLocalStorageSizeEXT; +extern PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glFramebufferPixelLocalStorageSizeEXT; extern PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC glGetFramebufferPixelLocalStorageSizeEXT; -extern PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC glClearPixelLocalStorageuiEXT; +extern PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC glClearPixelLocalStorageuiEXT; #endif /* defined(GL_EXT_shader_pixel_local_storage2) */ #if defined(GL_EXT_sparse_texture) @@ -515,18 +515,18 @@ extern PFNGLPATCHPARAMETERIEXTPROC glPatchParameteriEXT; #endif /* defined(GL_EXT_tessellation_shader) */ #if defined(GL_EXT_texture_border_clamp) -extern PFNGLTEXPARAMETERIIVEXTPROC glTexParameterIivEXT; -extern PFNGLTEXPARAMETERIUIVEXTPROC glTexParameterIuivEXT; -extern PFNGLGETTEXPARAMETERIIVEXTPROC glGetTexParameterIivEXT; -extern PFNGLGETTEXPARAMETERIUIVEXTPROC glGetTexParameterIuivEXT; -extern PFNGLSAMPLERPARAMETERIIVEXTPROC glSamplerParameterIivEXT; -extern PFNGLSAMPLERPARAMETERIUIVEXTPROC glSamplerParameterIuivEXT; -extern PFNGLGETSAMPLERPARAMETERIIVEXTPROC glGetSamplerParameterIivEXT; +extern PFNGLTEXPARAMETERIIVEXTPROC glTexParameterIivEXT; +extern PFNGLTEXPARAMETERIUIVEXTPROC glTexParameterIuivEXT; +extern PFNGLGETTEXPARAMETERIIVEXTPROC glGetTexParameterIivEXT; +extern PFNGLGETTEXPARAMETERIUIVEXTPROC glGetTexParameterIuivEXT; +extern PFNGLSAMPLERPARAMETERIIVEXTPROC glSamplerParameterIivEXT; +extern PFNGLSAMPLERPARAMETERIUIVEXTPROC glSamplerParameterIuivEXT; +extern PFNGLGETSAMPLERPARAMETERIIVEXTPROC glGetSamplerParameterIivEXT; extern PFNGLGETSAMPLERPARAMETERIUIVEXTPROC glGetSamplerParameterIuivEXT; #endif /* defined(GL_EXT_texture_border_clamp) */ #if defined(GL_EXT_texture_buffer) -extern PFNGLTEXBUFFEREXTPROC glTexBufferEXT; +extern PFNGLTEXBUFFEREXTPROC glTexBufferEXT; extern PFNGLTEXBUFFERRANGEEXTPROC glTexBufferRangeEXT; #endif /* defined(GL_EXT_texture_buffer) */ @@ -545,8 +545,8 @@ extern PFNGLTEXTUREVIEWEXTPROC glTextureViewEXT; #endif /* defined(GL_EXT_texture_view) */ #if defined(GL_NV_timeline_semaphore) -extern PFNGLCREATESEMAPHORESNVPROC glCreateSemaphoresNV; -extern PFNGLSEMAPHOREPARAMETERIVNVPROC glSemaphoreParameterivNV; +extern PFNGLCREATESEMAPHORESNVPROC glCreateSemaphoresNV; +extern PFNGLSEMAPHOREPARAMETERIVNVPROC glSemaphoreParameterivNV; extern PFNGLGETSEMAPHOREPARAMETERIVNVPROC glGetSemaphoreParameterivNV; #endif /* defined(GL_NV_timeline_semaphore) */ @@ -560,21 +560,21 @@ extern PFNGLWINDOWRECTANGLESEXTPROC glWindowRectanglesEXT; #endif /* defined(GL_EXT_window_rectangles) */ #if defined(GL_IMG_bindless_texture) -extern PFNGLGETTEXTUREHANDLEIMGPROC glGetTextureHandleIMG; -extern PFNGLGETTEXTURESAMPLERHANDLEIMGPROC glGetTextureSamplerHandleIMG; -extern PFNGLUNIFORMHANDLEUI64IMGPROC glUniformHandleui64IMG; -extern PFNGLUNIFORMHANDLEUI64VIMGPROC glUniformHandleui64vIMG; -extern PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC glProgramUniformHandleui64IMG; +extern PFNGLGETTEXTUREHANDLEIMGPROC glGetTextureHandleIMG; +extern PFNGLGETTEXTURESAMPLERHANDLEIMGPROC glGetTextureSamplerHandleIMG; +extern PFNGLUNIFORMHANDLEUI64IMGPROC glUniformHandleui64IMG; +extern PFNGLUNIFORMHANDLEUI64VIMGPROC glUniformHandleui64vIMG; +extern PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC glProgramUniformHandleui64IMG; extern PFNGLPROGRAMUNIFORMHANDLEUI64VIMGPROC glProgramUniformHandleui64vIMG; #endif /* defined(GL_IMG_bindless_texture) */ #if defined(GL_IMG_framebuffer_downsample) -extern PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC glFramebufferTexture2DDownsampleIMG; +extern PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC glFramebufferTexture2DDownsampleIMG; extern PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC glFramebufferTextureLayerDownsampleIMG; #endif /* defined(GL_IMG_framebuffer_downsample) */ #if defined(GL_IMG_multisampled_render_to_texture) -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC glRenderbufferStorageMultisampleIMG; +extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC glRenderbufferStorageMultisampleIMG; extern PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC glFramebufferTexture2DMultisampleIMG; #endif /* defined(GL_IMG_multisampled_render_to_texture) */ @@ -583,16 +583,16 @@ extern PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC glApplyFramebufferAttachment #endif /* defined(GL_INTEL_framebuffer_CMAA) */ #if defined(GL_INTEL_performance_query) -extern PFNGLBEGINPERFQUERYINTELPROC glBeginPerfQueryINTEL; -extern PFNGLCREATEPERFQUERYINTELPROC glCreatePerfQueryINTEL; -extern PFNGLDELETEPERFQUERYINTELPROC glDeletePerfQueryINTEL; -extern PFNGLENDPERFQUERYINTELPROC glEndPerfQueryINTEL; -extern PFNGLGETFIRSTPERFQUERYIDINTELPROC glGetFirstPerfQueryIdINTEL; -extern PFNGLGETNEXTPERFQUERYIDINTELPROC glGetNextPerfQueryIdINTEL; -extern PFNGLGETPERFCOUNTERINFOINTELPROC glGetPerfCounterInfoINTEL; -extern PFNGLGETPERFQUERYDATAINTELPROC glGetPerfQueryDataINTEL; +extern PFNGLBEGINPERFQUERYINTELPROC glBeginPerfQueryINTEL; +extern PFNGLCREATEPERFQUERYINTELPROC glCreatePerfQueryINTEL; +extern PFNGLDELETEPERFQUERYINTELPROC glDeletePerfQueryINTEL; +extern PFNGLENDPERFQUERYINTELPROC glEndPerfQueryINTEL; +extern PFNGLGETFIRSTPERFQUERYIDINTELPROC glGetFirstPerfQueryIdINTEL; +extern PFNGLGETNEXTPERFQUERYIDINTELPROC glGetNextPerfQueryIdINTEL; +extern PFNGLGETPERFCOUNTERINFOINTELPROC glGetPerfCounterInfoINTEL; +extern PFNGLGETPERFQUERYDATAINTELPROC glGetPerfQueryDataINTEL; extern PFNGLGETPERFQUERYIDBYNAMEINTELPROC glGetPerfQueryIdByNameINTEL; -extern PFNGLGETPERFQUERYINFOINTELPROC glGetPerfQueryInfoINTEL; +extern PFNGLGETPERFQUERYINFOINTELPROC glGetPerfQueryInfoINTEL; #endif /* defined(GL_INTEL_performance_query) */ #if defined(GL_KHR_blend_equation_advanced) @@ -600,25 +600,25 @@ extern PFNGLBLENDBARRIERKHRPROC glBlendBarrierKHR; #endif /* defined(GL_KHR_blend_equation_advanced) */ #if defined(GL_KHR_debug) -extern PFNGLDEBUGMESSAGECONTROLKHRPROC glDebugMessageControlKHR; -extern PFNGLDEBUGMESSAGEINSERTKHRPROC glDebugMessageInsertKHR; +extern PFNGLDEBUGMESSAGECONTROLKHRPROC glDebugMessageControlKHR; +extern PFNGLDEBUGMESSAGEINSERTKHRPROC glDebugMessageInsertKHR; extern PFNGLDEBUGMESSAGECALLBACKKHRPROC glDebugMessageCallbackKHR; -extern PFNGLGETDEBUGMESSAGELOGKHRPROC glGetDebugMessageLogKHR; -extern PFNGLPUSHDEBUGGROUPKHRPROC glPushDebugGroupKHR; -extern PFNGLPOPDEBUGGROUPKHRPROC glPopDebugGroupKHR; -extern PFNGLOBJECTLABELKHRPROC glObjectLabelKHR; -extern PFNGLGETOBJECTLABELKHRPROC glGetObjectLabelKHR; -extern PFNGLOBJECTPTRLABELKHRPROC glObjectPtrLabelKHR; -extern PFNGLGETOBJECTPTRLABELKHRPROC glGetObjectPtrLabelKHR; -extern PFNGLGETPOINTERVKHRPROC glGetPointervKHR; +extern PFNGLGETDEBUGMESSAGELOGKHRPROC glGetDebugMessageLogKHR; +extern PFNGLPUSHDEBUGGROUPKHRPROC glPushDebugGroupKHR; +extern PFNGLPOPDEBUGGROUPKHRPROC glPopDebugGroupKHR; +extern PFNGLOBJECTLABELKHRPROC glObjectLabelKHR; +extern PFNGLGETOBJECTLABELKHRPROC glGetObjectLabelKHR; +extern PFNGLOBJECTPTRLABELKHRPROC glObjectPtrLabelKHR; +extern PFNGLGETOBJECTPTRLABELKHRPROC glGetObjectPtrLabelKHR; +extern PFNGLGETPOINTERVKHRPROC glGetPointervKHR; #endif /* defined(GL_KHR_debug) */ #if defined(GL_KHR_robustness) extern PFNGLGETGRAPHICSRESETSTATUSKHRPROC glGetGraphicsResetStatusKHR; -extern PFNGLREADNPIXELSKHRPROC glReadnPixelsKHR; -extern PFNGLGETNUNIFORMFVKHRPROC glGetnUniformfvKHR; -extern PFNGLGETNUNIFORMIVKHRPROC glGetnUniformivKHR; -extern PFNGLGETNUNIFORMUIVKHRPROC glGetnUniformuivKHR; +extern PFNGLREADNPIXELSKHRPROC glReadnPixelsKHR; +extern PFNGLGETNUNIFORMFVKHRPROC glGetnUniformfvKHR; +extern PFNGLGETNUNIFORMIVKHRPROC glGetnUniformivKHR; +extern PFNGLGETNUNIFORMUIVKHRPROC glGetnUniformuivKHR; #endif /* defined(GL_KHR_robustness) */ #if defined(GL_KHR_parallel_shader_compile) @@ -626,29 +626,29 @@ extern PFNGLMAXSHADERCOMPILERTHREADSKHRPROC glMaxShaderCompilerThreadsKHR; #endif /* defined(GL_KHR_parallel_shader_compile) */ #if defined(GL_MESA_framebuffer_flip_y) -extern PFNGLFRAMEBUFFERPARAMETERIMESAPROC glFramebufferParameteriMESA; +extern PFNGLFRAMEBUFFERPARAMETERIMESAPROC glFramebufferParameteriMESA; extern PFNGLGETFRAMEBUFFERPARAMETERIVMESAPROC glGetFramebufferParameterivMESA; #endif /* defined(GL_MESA_framebuffer_flip_y) */ #if defined(GL_NV_bindless_texture) -extern PFNGLGETTEXTUREHANDLENVPROC glGetTextureHandleNV; -extern PFNGLGETTEXTURESAMPLERHANDLENVPROC glGetTextureSamplerHandleNV; -extern PFNGLMAKETEXTUREHANDLERESIDENTNVPROC glMakeTextureHandleResidentNV; +extern PFNGLGETTEXTUREHANDLENVPROC glGetTextureHandleNV; +extern PFNGLGETTEXTURESAMPLERHANDLENVPROC glGetTextureSamplerHandleNV; +extern PFNGLMAKETEXTUREHANDLERESIDENTNVPROC glMakeTextureHandleResidentNV; extern PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC glMakeTextureHandleNonResidentNV; -extern PFNGLGETIMAGEHANDLENVPROC glGetImageHandleNV; -extern PFNGLMAKEIMAGEHANDLERESIDENTNVPROC glMakeImageHandleResidentNV; -extern PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC glMakeImageHandleNonResidentNV; -extern PFNGLUNIFORMHANDLEUI64NVPROC glUniformHandleui64NV; -extern PFNGLUNIFORMHANDLEUI64VNVPROC glUniformHandleui64vNV; -extern PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC glProgramUniformHandleui64NV; -extern PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC glProgramUniformHandleui64vNV; -extern PFNGLISTEXTUREHANDLERESIDENTNVPROC glIsTextureHandleResidentNV; -extern PFNGLISIMAGEHANDLERESIDENTNVPROC glIsImageHandleResidentNV; +extern PFNGLGETIMAGEHANDLENVPROC glGetImageHandleNV; +extern PFNGLMAKEIMAGEHANDLERESIDENTNVPROC glMakeImageHandleResidentNV; +extern PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC glMakeImageHandleNonResidentNV; +extern PFNGLUNIFORMHANDLEUI64NVPROC glUniformHandleui64NV; +extern PFNGLUNIFORMHANDLEUI64VNVPROC glUniformHandleui64vNV; +extern PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC glProgramUniformHandleui64NV; +extern PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC glProgramUniformHandleui64vNV; +extern PFNGLISTEXTUREHANDLERESIDENTNVPROC glIsTextureHandleResidentNV; +extern PFNGLISIMAGEHANDLERESIDENTNVPROC glIsImageHandleResidentNV; #endif /* defined(GL_NV_bindless_texture) */ #if defined(GL_NV_blend_equation_advanced) extern PFNGLBLENDPARAMETERINVPROC glBlendParameteriNV; -extern PFNGLBLENDBARRIERNVPROC glBlendBarrierNV; +extern PFNGLBLENDBARRIERNVPROC glBlendBarrierNV; #endif /* defined(GL_NV_blend_equation_advanced) */ #if defined(GL_NV_clip_space_w_scaling) @@ -657,7 +657,7 @@ extern PFNGLVIEWPORTPOSITIONWSCALENVPROC glViewportPositionWScaleNV; #if defined(GL_NV_conditional_render) extern PFNGLBEGINCONDITIONALRENDERNVPROC glBeginConditionalRenderNV; -extern PFNGLENDCONDITIONALRENDERNVPROC glEndConditionalRenderNV; +extern PFNGLENDCONDITIONALRENDERNVPROC glEndConditionalRenderNV; #endif /* defined(GL_NV_conditional_render) */ #if defined(GL_NV_conservative_raster) @@ -673,7 +673,7 @@ extern PFNGLCOPYBUFFERSUBDATANVPROC glCopyBufferSubDataNV; #endif /* defined(GL_NV_copy_buffer) */ #if defined(GL_NV_coverage_sample) -extern PFNGLCOVERAGEMASKNVPROC glCoverageMaskNV; +extern PFNGLCOVERAGEMASKNVPROC glCoverageMaskNV; extern PFNGLCOVERAGEOPERATIONNVPROC glCoverageOperationNV; #endif /* defined(GL_NV_coverage_sample) */ @@ -682,26 +682,26 @@ extern PFNGLDRAWBUFFERSNVPROC glDrawBuffersNV; #endif /* defined(GL_NV_draw_buffers) */ #if defined(GL_NV_draw_instanced) -extern PFNGLDRAWARRAYSINSTANCEDNVPROC glDrawArraysInstancedNV; +extern PFNGLDRAWARRAYSINSTANCEDNVPROC glDrawArraysInstancedNV; extern PFNGLDRAWELEMENTSINSTANCEDNVPROC glDrawElementsInstancedNV; #endif /* defined(GL_NV_draw_instanced) */ #if defined(GL_NV_draw_vulkan_image) -extern PFNGLDRAWVKIMAGENVPROC glDrawVkImageNV; -extern PFNGLGETVKPROCADDRNVPROC glGetVkProcAddrNV; -extern PFNGLWAITVKSEMAPHORENVPROC glWaitVkSemaphoreNV; +extern PFNGLDRAWVKIMAGENVPROC glDrawVkImageNV; +extern PFNGLGETVKPROCADDRNVPROC glGetVkProcAddrNV; +extern PFNGLWAITVKSEMAPHORENVPROC glWaitVkSemaphoreNV; extern PFNGLSIGNALVKSEMAPHORENVPROC glSignalVkSemaphoreNV; -extern PFNGLSIGNALVKFENCENVPROC glSignalVkFenceNV; +extern PFNGLSIGNALVKFENCENVPROC glSignalVkFenceNV; #endif /* defined(GL_NV_draw_vulkan_image) */ #if defined(GL_NV_fence) extern PFNGLDELETEFENCESNVPROC glDeleteFencesNV; -extern PFNGLGENFENCESNVPROC glGenFencesNV; -extern PFNGLISFENCENVPROC glIsFenceNV; -extern PFNGLTESTFENCENVPROC glTestFenceNV; -extern PFNGLGETFENCEIVNVPROC glGetFenceivNV; -extern PFNGLFINISHFENCENVPROC glFinishFenceNV; -extern PFNGLSETFENCENVPROC glSetFenceNV; +extern PFNGLGENFENCESNVPROC glGenFencesNV; +extern PFNGLISFENCENVPROC glIsFenceNV; +extern PFNGLTESTFENCENVPROC glTestFenceNV; +extern PFNGLGETFENCEIVNVPROC glGetFenceivNV; +extern PFNGLFINISHFENCENVPROC glFinishFenceNV; +extern PFNGLSETFENCENVPROC glSetFenceNV; #endif /* defined(GL_NV_fence) */ #if defined(GL_NV_fragment_coverage_to_color) @@ -713,9 +713,9 @@ extern PFNGLBLITFRAMEBUFFERNVPROC glBlitFramebufferNV; #endif /* defined(GL_NV_framebuffer_blit) */ #if defined(GL_NV_framebuffer_mixed_samples) -extern PFNGLCOVERAGEMODULATIONTABLENVPROC glCoverageModulationTableNV; +extern PFNGLCOVERAGEMODULATIONTABLENVPROC glCoverageModulationTableNV; extern PFNGLGETCOVERAGEMODULATIONTABLENVPROC glGetCoverageModulationTableNV; -extern PFNGLCOVERAGEMODULATIONNVPROC glCoverageModulationNV; +extern PFNGLCOVERAGEMODULATIONNVPROC glCoverageModulationNV; #endif /* defined(GL_NV_framebuffer_mixed_samples) */ #if defined(GL_NV_framebuffer_multisample) @@ -723,36 +723,36 @@ extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC glRenderbufferStorageMultisampl #endif /* defined(GL_NV_framebuffer_multisample) */ #if defined(GL_NV_gpu_shader5) -extern PFNGLUNIFORM1I64NVPROC glUniform1i64NV; -extern PFNGLUNIFORM2I64NVPROC glUniform2i64NV; -extern PFNGLUNIFORM3I64NVPROC glUniform3i64NV; -extern PFNGLUNIFORM4I64NVPROC glUniform4i64NV; -extern PFNGLUNIFORM1I64VNVPROC glUniform1i64vNV; -extern PFNGLUNIFORM2I64VNVPROC glUniform2i64vNV; -extern PFNGLUNIFORM3I64VNVPROC glUniform3i64vNV; -extern PFNGLUNIFORM4I64VNVPROC glUniform4i64vNV; -extern PFNGLUNIFORM1UI64NVPROC glUniform1ui64NV; -extern PFNGLUNIFORM2UI64NVPROC glUniform2ui64NV; -extern PFNGLUNIFORM3UI64NVPROC glUniform3ui64NV; -extern PFNGLUNIFORM4UI64NVPROC glUniform4ui64NV; -extern PFNGLUNIFORM1UI64VNVPROC glUniform1ui64vNV; -extern PFNGLUNIFORM2UI64VNVPROC glUniform2ui64vNV; -extern PFNGLUNIFORM3UI64VNVPROC glUniform3ui64vNV; -extern PFNGLUNIFORM4UI64VNVPROC glUniform4ui64vNV; +extern PFNGLUNIFORM1I64NVPROC glUniform1i64NV; +extern PFNGLUNIFORM2I64NVPROC glUniform2i64NV; +extern PFNGLUNIFORM3I64NVPROC glUniform3i64NV; +extern PFNGLUNIFORM4I64NVPROC glUniform4i64NV; +extern PFNGLUNIFORM1I64VNVPROC glUniform1i64vNV; +extern PFNGLUNIFORM2I64VNVPROC glUniform2i64vNV; +extern PFNGLUNIFORM3I64VNVPROC glUniform3i64vNV; +extern PFNGLUNIFORM4I64VNVPROC glUniform4i64vNV; +extern PFNGLUNIFORM1UI64NVPROC glUniform1ui64NV; +extern PFNGLUNIFORM2UI64NVPROC glUniform2ui64NV; +extern PFNGLUNIFORM3UI64NVPROC glUniform3ui64NV; +extern PFNGLUNIFORM4UI64NVPROC glUniform4ui64NV; +extern PFNGLUNIFORM1UI64VNVPROC glUniform1ui64vNV; +extern PFNGLUNIFORM2UI64VNVPROC glUniform2ui64vNV; +extern PFNGLUNIFORM3UI64VNVPROC glUniform3ui64vNV; +extern PFNGLUNIFORM4UI64VNVPROC glUniform4ui64vNV; extern PFNGLGETUNIFORMI64VNVPROC glGetUniformi64vNV; -extern PFNGLPROGRAMUNIFORM1I64NVPROC glProgramUniform1i64NV; -extern PFNGLPROGRAMUNIFORM2I64NVPROC glProgramUniform2i64NV; -extern PFNGLPROGRAMUNIFORM3I64NVPROC glProgramUniform3i64NV; -extern PFNGLPROGRAMUNIFORM4I64NVPROC glProgramUniform4i64NV; -extern PFNGLPROGRAMUNIFORM1I64VNVPROC glProgramUniform1i64vNV; -extern PFNGLPROGRAMUNIFORM2I64VNVPROC glProgramUniform2i64vNV; -extern PFNGLPROGRAMUNIFORM3I64VNVPROC glProgramUniform3i64vNV; -extern PFNGLPROGRAMUNIFORM4I64VNVPROC glProgramUniform4i64vNV; -extern PFNGLPROGRAMUNIFORM1UI64NVPROC glProgramUniform1ui64NV; -extern PFNGLPROGRAMUNIFORM2UI64NVPROC glProgramUniform2ui64NV; -extern PFNGLPROGRAMUNIFORM3UI64NVPROC glProgramUniform3ui64NV; -extern PFNGLPROGRAMUNIFORM4UI64NVPROC glProgramUniform4ui64NV; +extern PFNGLPROGRAMUNIFORM1I64NVPROC glProgramUniform1i64NV; +extern PFNGLPROGRAMUNIFORM2I64NVPROC glProgramUniform2i64NV; +extern PFNGLPROGRAMUNIFORM3I64NVPROC glProgramUniform3i64NV; +extern PFNGLPROGRAMUNIFORM4I64NVPROC glProgramUniform4i64NV; +extern PFNGLPROGRAMUNIFORM1I64VNVPROC glProgramUniform1i64vNV; +extern PFNGLPROGRAMUNIFORM2I64VNVPROC glProgramUniform2i64vNV; +extern PFNGLPROGRAMUNIFORM3I64VNVPROC glProgramUniform3i64vNV; +extern PFNGLPROGRAMUNIFORM4I64VNVPROC glProgramUniform4i64vNV; +extern PFNGLPROGRAMUNIFORM1UI64NVPROC glProgramUniform1ui64NV; +extern PFNGLPROGRAMUNIFORM2UI64NVPROC glProgramUniform2ui64NV; +extern PFNGLPROGRAMUNIFORM3UI64NVPROC glProgramUniform3ui64NV; +extern PFNGLPROGRAMUNIFORM4UI64NVPROC glProgramUniform4ui64NV; extern PFNGLPROGRAMUNIFORM1UI64VNVPROC glProgramUniform1ui64vNV; extern PFNGLPROGRAMUNIFORM2UI64VNVPROC glProgramUniform2ui64vNV; extern PFNGLPROGRAMUNIFORM3UI64VNVPROC glProgramUniform3ui64vNV; @@ -769,26 +769,26 @@ extern PFNGLGETINTERNALFORMATSAMPLEIVNVPROC glGetInternalformatSampleivNV; #if defined(GL_NV_memory_attachment) extern PFNGLGETMEMORYOBJECTDETACHEDRESOURCESUIVNVPROC glGetMemoryObjectDetachedResourcesuivNV; -extern PFNGLRESETMEMORYOBJECTPARAMETERNVPROC glResetMemoryObjectParameterNV; -extern PFNGLTEXATTACHMEMORYNVPROC glTexAttachMemoryNV; -extern PFNGLBUFFERATTACHMEMORYNVPROC glBufferAttachMemoryNV; +extern PFNGLRESETMEMORYOBJECTPARAMETERNVPROC glResetMemoryObjectParameterNV; +extern PFNGLTEXATTACHMEMORYNVPROC glTexAttachMemoryNV; +extern PFNGLBUFFERATTACHMEMORYNVPROC glBufferAttachMemoryNV; -extern PFNGLTEXTUREATTACHMEMORYNVPROC glTextureAttachMemoryNV; +extern PFNGLTEXTUREATTACHMEMORYNVPROC glTextureAttachMemoryNV; extern PFNGLNAMEDBUFFERATTACHMEMORYNVPROC glNamedBufferAttachMemoryNV; #endif /* defined(GL_NV_memory_attachment) */ #if defined(GL_NV_memory_object_sparse) extern PFNGLBUFFERPAGECOMMITMENTMEMNVPROC glBufferPageCommitmentMemNV; -extern PFNGLTEXPAGECOMMITMENTMEMNVPROC glTexPageCommitmentMemNV; +extern PFNGLTEXPAGECOMMITMENTMEMNVPROC glTexPageCommitmentMemNV; extern PFNGLNAMEDBUFFERPAGECOMMITMENTMEMNVPROC glNamedBufferPageCommitmentMemNV; -extern PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC glTexturePageCommitmentMemNV; +extern PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC glTexturePageCommitmentMemNV; #endif /* defined(GL_NV_memory_object_sparse) */ #if defined(GL_NV_mesh_shader) -extern PFNGLDRAWMESHTASKSNVPROC glDrawMeshTasksNV; -extern PFNGLDRAWMESHTASKSINDIRECTNVPROC glDrawMeshTasksIndirectNV; -extern PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC glMultiDrawMeshTasksIndirectNV; +extern PFNGLDRAWMESHTASKSNVPROC glDrawMeshTasksNV; +extern PFNGLDRAWMESHTASKSINDIRECTNVPROC glDrawMeshTasksIndirectNV; +extern PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC glMultiDrawMeshTasksIndirectNV; extern PFNGLMULTIDRAWMESHTASKSINDIRECTCOUNTNVPROC glMultiDrawMeshTasksIndirectCountNV; #endif /* defined(GL_NV_mesh_shader) */ @@ -802,85 +802,85 @@ extern PFNGLUNIFORMMATRIX4X3FVNVPROC glUniformMatrix4x3fvNV; #endif /* defined(GL_NV_non_square_matrices) */ #if defined(GL_NV_path_rendering) -extern PFNGLGENPATHSNVPROC glGenPathsNV; -extern PFNGLDELETEPATHSNVPROC glDeletePathsNV; -extern PFNGLISPATHNVPROC glIsPathNV; -extern PFNGLPATHCOMMANDSNVPROC glPathCommandsNV; -extern PFNGLPATHCOORDSNVPROC glPathCoordsNV; -extern PFNGLPATHSUBCOMMANDSNVPROC glPathSubCommandsNV; -extern PFNGLPATHSUBCOORDSNVPROC glPathSubCoordsNV; -extern PFNGLPATHSTRINGNVPROC glPathStringNV; -extern PFNGLPATHGLYPHSNVPROC glPathGlyphsNV; -extern PFNGLPATHGLYPHRANGENVPROC glPathGlyphRangeNV; -extern PFNGLWEIGHTPATHSNVPROC glWeightPathsNV; -extern PFNGLCOPYPATHNVPROC glCopyPathNV; -extern PFNGLINTERPOLATEPATHSNVPROC glInterpolatePathsNV; -extern PFNGLTRANSFORMPATHNVPROC glTransformPathNV; -extern PFNGLPATHPARAMETERIVNVPROC glPathParameterivNV; -extern PFNGLPATHPARAMETERINVPROC glPathParameteriNV; -extern PFNGLPATHPARAMETERFVNVPROC glPathParameterfvNV; -extern PFNGLPATHPARAMETERFNVPROC glPathParameterfNV; -extern PFNGLPATHDASHARRAYNVPROC glPathDashArrayNV; -extern PFNGLPATHSTENCILFUNCNVPROC glPathStencilFuncNV; -extern PFNGLPATHSTENCILDEPTHOFFSETNVPROC glPathStencilDepthOffsetNV; -extern PFNGLSTENCILFILLPATHNVPROC glStencilFillPathNV; -extern PFNGLSTENCILSTROKEPATHNVPROC glStencilStrokePathNV; -extern PFNGLSTENCILFILLPATHINSTANCEDNVPROC glStencilFillPathInstancedNV; +extern PFNGLGENPATHSNVPROC glGenPathsNV; +extern PFNGLDELETEPATHSNVPROC glDeletePathsNV; +extern PFNGLISPATHNVPROC glIsPathNV; +extern PFNGLPATHCOMMANDSNVPROC glPathCommandsNV; +extern PFNGLPATHCOORDSNVPROC glPathCoordsNV; +extern PFNGLPATHSUBCOMMANDSNVPROC glPathSubCommandsNV; +extern PFNGLPATHSUBCOORDSNVPROC glPathSubCoordsNV; +extern PFNGLPATHSTRINGNVPROC glPathStringNV; +extern PFNGLPATHGLYPHSNVPROC glPathGlyphsNV; +extern PFNGLPATHGLYPHRANGENVPROC glPathGlyphRangeNV; +extern PFNGLWEIGHTPATHSNVPROC glWeightPathsNV; +extern PFNGLCOPYPATHNVPROC glCopyPathNV; +extern PFNGLINTERPOLATEPATHSNVPROC glInterpolatePathsNV; +extern PFNGLTRANSFORMPATHNVPROC glTransformPathNV; +extern PFNGLPATHPARAMETERIVNVPROC glPathParameterivNV; +extern PFNGLPATHPARAMETERINVPROC glPathParameteriNV; +extern PFNGLPATHPARAMETERFVNVPROC glPathParameterfvNV; +extern PFNGLPATHPARAMETERFNVPROC glPathParameterfNV; +extern PFNGLPATHDASHARRAYNVPROC glPathDashArrayNV; +extern PFNGLPATHSTENCILFUNCNVPROC glPathStencilFuncNV; +extern PFNGLPATHSTENCILDEPTHOFFSETNVPROC glPathStencilDepthOffsetNV; +extern PFNGLSTENCILFILLPATHNVPROC glStencilFillPathNV; +extern PFNGLSTENCILSTROKEPATHNVPROC glStencilStrokePathNV; +extern PFNGLSTENCILFILLPATHINSTANCEDNVPROC glStencilFillPathInstancedNV; extern PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC glStencilStrokePathInstancedNV; -extern PFNGLPATHCOVERDEPTHFUNCNVPROC glPathCoverDepthFuncNV; -extern PFNGLCOVERFILLPATHNVPROC glCoverFillPathNV; -extern PFNGLCOVERSTROKEPATHNVPROC glCoverStrokePathNV; -extern PFNGLCOVERFILLPATHINSTANCEDNVPROC glCoverFillPathInstancedNV; -extern PFNGLCOVERSTROKEPATHINSTANCEDNVPROC glCoverStrokePathInstancedNV; -extern PFNGLGETPATHPARAMETERIVNVPROC glGetPathParameterivNV; -extern PFNGLGETPATHPARAMETERFVNVPROC glGetPathParameterfvNV; -extern PFNGLGETPATHCOMMANDSNVPROC glGetPathCommandsNV; -extern PFNGLGETPATHCOORDSNVPROC glGetPathCoordsNV; -extern PFNGLGETPATHDASHARRAYNVPROC glGetPathDashArrayNV; -extern PFNGLGETPATHMETRICSNVPROC glGetPathMetricsNV; -extern PFNGLGETPATHMETRICRANGENVPROC glGetPathMetricRangeNV; -extern PFNGLGETPATHSPACINGNVPROC glGetPathSpacingNV; -extern PFNGLISPOINTINFILLPATHNVPROC glIsPointInFillPathNV; -extern PFNGLISPOINTINSTROKEPATHNVPROC glIsPointInStrokePathNV; -extern PFNGLGETPATHLENGTHNVPROC glGetPathLengthNV; -extern PFNGLPOINTALONGPATHNVPROC glPointAlongPathNV; +extern PFNGLPATHCOVERDEPTHFUNCNVPROC glPathCoverDepthFuncNV; +extern PFNGLCOVERFILLPATHNVPROC glCoverFillPathNV; +extern PFNGLCOVERSTROKEPATHNVPROC glCoverStrokePathNV; +extern PFNGLCOVERFILLPATHINSTANCEDNVPROC glCoverFillPathInstancedNV; +extern PFNGLCOVERSTROKEPATHINSTANCEDNVPROC glCoverStrokePathInstancedNV; +extern PFNGLGETPATHPARAMETERIVNVPROC glGetPathParameterivNV; +extern PFNGLGETPATHPARAMETERFVNVPROC glGetPathParameterfvNV; +extern PFNGLGETPATHCOMMANDSNVPROC glGetPathCommandsNV; +extern PFNGLGETPATHCOORDSNVPROC glGetPathCoordsNV; +extern PFNGLGETPATHDASHARRAYNVPROC glGetPathDashArrayNV; +extern PFNGLGETPATHMETRICSNVPROC glGetPathMetricsNV; +extern PFNGLGETPATHMETRICRANGENVPROC glGetPathMetricRangeNV; +extern PFNGLGETPATHSPACINGNVPROC glGetPathSpacingNV; +extern PFNGLISPOINTINFILLPATHNVPROC glIsPointInFillPathNV; +extern PFNGLISPOINTINSTROKEPATHNVPROC glIsPointInStrokePathNV; +extern PFNGLGETPATHLENGTHNVPROC glGetPathLengthNV; +extern PFNGLPOINTALONGPATHNVPROC glPointAlongPathNV; -extern PFNGLMATRIXLOAD3X2FNVPROC glMatrixLoad3x2fNV; -extern PFNGLMATRIXLOAD3X3FNVPROC glMatrixLoad3x3fNV; -extern PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC glMatrixLoadTranspose3x3fNV; -extern PFNGLMATRIXMULT3X2FNVPROC glMatrixMult3x2fNV; -extern PFNGLMATRIXMULT3X3FNVPROC glMatrixMult3x3fNV; -extern PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC glMatrixMultTranspose3x3fNV; -extern PFNGLSTENCILTHENCOVERFILLPATHNVPROC glStencilThenCoverFillPathNV; -extern PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC glStencilThenCoverStrokePathNV; -extern PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC glStencilThenCoverFillPathInstancedNV; +extern PFNGLMATRIXLOAD3X2FNVPROC glMatrixLoad3x2fNV; +extern PFNGLMATRIXLOAD3X3FNVPROC glMatrixLoad3x3fNV; +extern PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC glMatrixLoadTranspose3x3fNV; +extern PFNGLMATRIXMULT3X2FNVPROC glMatrixMult3x2fNV; +extern PFNGLMATRIXMULT3X3FNVPROC glMatrixMult3x3fNV; +extern PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC glMatrixMultTranspose3x3fNV; +extern PFNGLSTENCILTHENCOVERFILLPATHNVPROC glStencilThenCoverFillPathNV; +extern PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC glStencilThenCoverStrokePathNV; +extern PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC glStencilThenCoverFillPathInstancedNV; extern PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC glStencilThenCoverStrokePathInstancedNV; -extern PFNGLPATHGLYPHINDEXRANGENVPROC glPathGlyphIndexRangeNV; +extern PFNGLPATHGLYPHINDEXRANGENVPROC glPathGlyphIndexRangeNV; -extern PFNGLPATHGLYPHINDEXARRAYNVPROC glPathGlyphIndexArrayNV; -extern PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC glPathMemoryGlyphIndexArrayNV; +extern PFNGLPATHGLYPHINDEXARRAYNVPROC glPathGlyphIndexArrayNV; +extern PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC glPathMemoryGlyphIndexArrayNV; extern PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC glProgramPathFragmentInputGenNV; -extern PFNGLGETPROGRAMRESOURCEFVNVPROC glGetProgramResourcefvNV; +extern PFNGLGETPROGRAMRESOURCEFVNVPROC glGetProgramResourcefvNV; -extern PFNGLMATRIXFRUSTUMEXTPROC glMatrixFrustumEXT; -extern PFNGLMATRIXLOADIDENTITYEXTPROC glMatrixLoadIdentityEXT; +extern PFNGLMATRIXFRUSTUMEXTPROC glMatrixFrustumEXT; +extern PFNGLMATRIXLOADIDENTITYEXTPROC glMatrixLoadIdentityEXT; extern PFNGLMATRIXLOADTRANSPOSEFEXTPROC glMatrixLoadTransposefEXT; extern PFNGLMATRIXLOADTRANSPOSEDEXTPROC glMatrixLoadTransposedEXT; -extern PFNGLMATRIXLOADFEXTPROC glMatrixLoadfEXT; -extern PFNGLMATRIXLOADDEXTPROC glMatrixLoaddEXT; +extern PFNGLMATRIXLOADFEXTPROC glMatrixLoadfEXT; +extern PFNGLMATRIXLOADDEXTPROC glMatrixLoaddEXT; extern PFNGLMATRIXMULTTRANSPOSEFEXTPROC glMatrixMultTransposefEXT; extern PFNGLMATRIXMULTTRANSPOSEDEXTPROC glMatrixMultTransposedEXT; -extern PFNGLMATRIXMULTFEXTPROC glMatrixMultfEXT; -extern PFNGLMATRIXMULTDEXTPROC glMatrixMultdEXT; -extern PFNGLMATRIXORTHOEXTPROC glMatrixOrthoEXT; -extern PFNGLMATRIXPOPEXTPROC glMatrixPopEXT; -extern PFNGLMATRIXPUSHEXTPROC glMatrixPushEXT; -extern PFNGLMATRIXROTATEFEXTPROC glMatrixRotatefEXT; -extern PFNGLMATRIXROTATEDEXTPROC glMatrixRotatedEXT; -extern PFNGLMATRIXSCALEFEXTPROC glMatrixScalefEXT; -extern PFNGLMATRIXSCALEDEXTPROC glMatrixScaledEXT; -extern PFNGLMATRIXTRANSLATEFEXTPROC glMatrixTranslatefEXT; -extern PFNGLMATRIXTRANSLATEDEXTPROC glMatrixTranslatedEXT; +extern PFNGLMATRIXMULTFEXTPROC glMatrixMultfEXT; +extern PFNGLMATRIXMULTDEXTPROC glMatrixMultdEXT; +extern PFNGLMATRIXORTHOEXTPROC glMatrixOrthoEXT; +extern PFNGLMATRIXPOPEXTPROC glMatrixPopEXT; +extern PFNGLMATRIXPUSHEXTPROC glMatrixPushEXT; +extern PFNGLMATRIXROTATEFEXTPROC glMatrixRotatefEXT; +extern PFNGLMATRIXROTATEDEXTPROC glMatrixRotatedEXT; +extern PFNGLMATRIXSCALEFEXTPROC glMatrixScalefEXT; +extern PFNGLMATRIXSCALEDEXTPROC glMatrixScaledEXT; +extern PFNGLMATRIXTRANSLATEFEXTPROC glMatrixTranslatefEXT; +extern PFNGLMATRIXTRANSLATEDEXTPROC glMatrixTranslatedEXT; #endif /* defined(GL_NV_path_rendering) */ #if defined(GL_NV_polygon_mode) @@ -892,39 +892,39 @@ extern PFNGLREADBUFFERNVPROC glReadBufferNV; #endif /* defined(GL_NV_read_buffer) */ #if defined(GL_NV_sample_locations) -extern PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glFramebufferSampleLocationsfvNV; +extern PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glFramebufferSampleLocationsfvNV; extern PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC glNamedFramebufferSampleLocationsfvNV; -extern PFNGLRESOLVEDEPTHVALUESNVPROC glResolveDepthValuesNV; +extern PFNGLRESOLVEDEPTHVALUESNVPROC glResolveDepthValuesNV; #endif /* defined(GL_NV_sample_locations) */ #if defined(GL_NV_scissor_exclusive) -extern PFNGLSCISSOREXCLUSIVENVPROC glScissorExclusiveNV; +extern PFNGLSCISSOREXCLUSIVENVPROC glScissorExclusiveNV; extern PFNGLSCISSOREXCLUSIVEARRAYVNVPROC glScissorExclusiveArrayvNV; #endif /* defined(GL_NV_scissor_exclusive) */ #if defined(GL_NV_shading_rate_image) -extern PFNGLBINDSHADINGRATEIMAGENVPROC glBindShadingRateImageNV; -extern PFNGLGETSHADINGRATEIMAGEPALETTENVPROC glGetShadingRateImagePaletteNV; +extern PFNGLBINDSHADINGRATEIMAGENVPROC glBindShadingRateImageNV; +extern PFNGLGETSHADINGRATEIMAGEPALETTENVPROC glGetShadingRateImagePaletteNV; extern PFNGLGETSHADINGRATESAMPLELOCATIONIVNVPROC glGetShadingRateSampleLocationivNV; -extern PFNGLSHADINGRATEIMAGEBARRIERNVPROC glShadingRateImageBarrierNV; -extern PFNGLSHADINGRATEIMAGEPALETTENVPROC glShadingRateImagePaletteNV; -extern PFNGLSHADINGRATESAMPLEORDERNVPROC glShadingRateSampleOrderNV; -extern PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC glShadingRateSampleOrderCustomNV; +extern PFNGLSHADINGRATEIMAGEBARRIERNVPROC glShadingRateImageBarrierNV; +extern PFNGLSHADINGRATEIMAGEPALETTENVPROC glShadingRateImagePaletteNV; +extern PFNGLSHADINGRATESAMPLEORDERNVPROC glShadingRateSampleOrderNV; +extern PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC glShadingRateSampleOrderCustomNV; #endif /* defined(GL_NV_shading_rate_image) */ #if defined(GL_NV_viewport_array) -extern PFNGLVIEWPORTARRAYVNVPROC glViewportArrayvNV; -extern PFNGLVIEWPORTINDEXEDFNVPROC glViewportIndexedfNV; -extern PFNGLVIEWPORTINDEXEDFVNVPROC glViewportIndexedfvNV; -extern PFNGLSCISSORARRAYVNVPROC glScissorArrayvNV; -extern PFNGLSCISSORINDEXEDNVPROC glScissorIndexedNV; -extern PFNGLSCISSORINDEXEDVNVPROC glScissorIndexedvNV; -extern PFNGLDEPTHRANGEARRAYFVNVPROC glDepthRangeArrayfvNV; +extern PFNGLVIEWPORTARRAYVNVPROC glViewportArrayvNV; +extern PFNGLVIEWPORTINDEXEDFNVPROC glViewportIndexedfNV; +extern PFNGLVIEWPORTINDEXEDFVNVPROC glViewportIndexedfvNV; +extern PFNGLSCISSORARRAYVNVPROC glScissorArrayvNV; +extern PFNGLSCISSORINDEXEDNVPROC glScissorIndexedNV; +extern PFNGLSCISSORINDEXEDVNVPROC glScissorIndexedvNV; +extern PFNGLDEPTHRANGEARRAYFVNVPROC glDepthRangeArrayfvNV; extern PFNGLDEPTHRANGEINDEXEDFNVPROC glDepthRangeIndexedfNV; -extern PFNGLGETFLOATI_VNVPROC glGetFloati_vNV; // NOLINT(readability-identifier-naming) -extern PFNGLENABLEINVPROC glEnableiNV; -extern PFNGLDISABLEINVPROC glDisableiNV; -extern PFNGLISENABLEDINVPROC glIsEnablediNV; +extern PFNGLGETFLOATI_VNVPROC glGetFloati_vNV; // NOLINT(readability-identifier-naming) +extern PFNGLENABLEINVPROC glEnableiNV; +extern PFNGLDISABLEINVPROC glDisableiNV; +extern PFNGLISENABLEDINVPROC glIsEnablediNV; #endif /* defined(GL_NV_viewport_array) */ #if defined(GL_NV_viewport_swizzle) @@ -932,7 +932,7 @@ extern PFNGLVIEWPORTSWIZZLENVPROC glViewportSwizzleNV; #endif /* defined(GL_NV_viewport_swizzle) */ #if defined(GL_OES_EGL_image) -extern PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; +extern PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; extern PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC glEGLImageTargetRenderbufferStorageOES; #endif /* defined(GL_OES_EGL_image) */ @@ -941,19 +941,19 @@ extern PFNGLCOPYIMAGESUBDATAOESPROC glCopyImageSubDataOES; #endif /* defined(GL_OES_copy_image) */ #if defined(GL_OES_draw_buffers_indexed) -extern PFNGLENABLEIOESPROC glEnableiOES; -extern PFNGLDISABLEIOESPROC glDisableiOES; -extern PFNGLBLENDEQUATIONIOESPROC glBlendEquationiOES; +extern PFNGLENABLEIOESPROC glEnableiOES; +extern PFNGLDISABLEIOESPROC glDisableiOES; +extern PFNGLBLENDEQUATIONIOESPROC glBlendEquationiOES; extern PFNGLBLENDEQUATIONSEPARATEIOESPROC glBlendEquationSeparateiOES; -extern PFNGLBLENDFUNCIOESPROC glBlendFunciOES; -extern PFNGLBLENDFUNCSEPARATEIOESPROC glBlendFuncSeparateiOES; -extern PFNGLCOLORMASKIOESPROC glColorMaskiOES; -extern PFNGLISENABLEDIOESPROC glIsEnablediOES; +extern PFNGLBLENDFUNCIOESPROC glBlendFunciOES; +extern PFNGLBLENDFUNCSEPARATEIOESPROC glBlendFuncSeparateiOES; +extern PFNGLCOLORMASKIOESPROC glColorMaskiOES; +extern PFNGLISENABLEDIOESPROC glIsEnablediOES; #endif /* defined(GL_OES_draw_buffers_indexed) */ #if defined(GL_OES_draw_elements_base_vertex) -extern PFNGLDRAWELEMENTSBASEVERTEXOESPROC glDrawElementsBaseVertexOES; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC glDrawRangeElementsBaseVertexOES; +extern PFNGLDRAWELEMENTSBASEVERTEXOESPROC glDrawElementsBaseVertexOES; +extern PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC glDrawRangeElementsBaseVertexOES; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC glDrawElementsInstancedBaseVertexOES; #endif /* defined(GL_OES_draw_elements_base_vertex) */ @@ -963,12 +963,12 @@ extern PFNGLFRAMEBUFFERTEXTUREOESPROC glFramebufferTextureOES; #if defined(GL_OES_get_program_binary) extern PFNGLGETPROGRAMBINARYOESPROC glGetProgramBinaryOES; -extern PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES; +extern PFNGLPROGRAMBINARYOESPROC glProgramBinaryOES; #endif /* defined(GL_OES_get_program_binary) */ #if defined(GL_OES_mapbuffer) -extern PFNGLMAPBUFFEROESPROC glMapBufferOES; -extern PFNGLUNMAPBUFFEROESPROC glUnmapBufferOES; +extern PFNGLMAPBUFFEROESPROC glMapBufferOES; +extern PFNGLUNMAPBUFFEROESPROC glUnmapBufferOES; extern PFNGLGETBUFFERPOINTERVOESPROC glGetBufferPointervOES; #endif /* defined(GL_OES_mapbuffer) */ @@ -985,27 +985,27 @@ extern PFNGLPATCHPARAMETERIOESPROC glPatchParameteriOES; #endif /* defined(GL_OES_tessellation_shader) */ #if defined(GL_OES_texture_3D) -extern PFNGLTEXIMAGE3DOESPROC glTexImage3DOES; -extern PFNGLTEXSUBIMAGE3DOESPROC glTexSubImage3DOES; -extern PFNGLCOPYTEXSUBIMAGE3DOESPROC glCopyTexSubImage3DOES; -extern PFNGLCOMPRESSEDTEXIMAGE3DOESPROC glCompressedTexImage3DOES; +extern PFNGLTEXIMAGE3DOESPROC glTexImage3DOES; +extern PFNGLTEXSUBIMAGE3DOESPROC glTexSubImage3DOES; +extern PFNGLCOPYTEXSUBIMAGE3DOESPROC glCopyTexSubImage3DOES; +extern PFNGLCOMPRESSEDTEXIMAGE3DOESPROC glCompressedTexImage3DOES; extern PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC glCompressedTexSubImage3DOES; -extern PFNGLFRAMEBUFFERTEXTURE3DOESPROC glFramebufferTexture3DOES; +extern PFNGLFRAMEBUFFERTEXTURE3DOESPROC glFramebufferTexture3DOES; #endif /* defined(GL_OES_texture_3D) */ #if defined(GL_OES_texture_border_clamp) -extern PFNGLTEXPARAMETERIIVOESPROC glTexParameterIivOES; -extern PFNGLTEXPARAMETERIUIVOESPROC glTexParameterIuivOES; -extern PFNGLGETTEXPARAMETERIIVOESPROC glGetTexParameterIivOES; -extern PFNGLGETTEXPARAMETERIUIVOESPROC glGetTexParameterIuivOES; -extern PFNGLSAMPLERPARAMETERIIVOESPROC glSamplerParameterIivOES; -extern PFNGLSAMPLERPARAMETERIUIVOESPROC glSamplerParameterIuivOES; -extern PFNGLGETSAMPLERPARAMETERIIVOESPROC glGetSamplerParameterIivOES; +extern PFNGLTEXPARAMETERIIVOESPROC glTexParameterIivOES; +extern PFNGLTEXPARAMETERIUIVOESPROC glTexParameterIuivOES; +extern PFNGLGETTEXPARAMETERIIVOESPROC glGetTexParameterIivOES; +extern PFNGLGETTEXPARAMETERIUIVOESPROC glGetTexParameterIuivOES; +extern PFNGLSAMPLERPARAMETERIIVOESPROC glSamplerParameterIivOES; +extern PFNGLSAMPLERPARAMETERIUIVOESPROC glSamplerParameterIuivOES; +extern PFNGLGETSAMPLERPARAMETERIIVOESPROC glGetSamplerParameterIivOES; extern PFNGLGETSAMPLERPARAMETERIUIVOESPROC glGetSamplerParameterIuivOES; #endif /* defined(GL_OES_texture_border_clamp) */ #if defined(GL_OES_texture_buffer) -extern PFNGLTEXBUFFEROESPROC glTexBufferOES; +extern PFNGLTEXBUFFEROESPROC glTexBufferOES; extern PFNGLTEXBUFFERRANGEOESPROC glTexBufferRangeOES; #endif /* defined(GL_OES_texture_buffer) */ @@ -1018,23 +1018,23 @@ extern PFNGLTEXTUREVIEWOESPROC glTextureViewOES; #endif /* defined(GL_OES_texture_view) */ #if defined(GL_OES_vertex_array_object) -extern PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; +extern PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES; extern PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES; -extern PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; -extern PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; +extern PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES; +extern PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES; #endif /* defined(GL_OES_vertex_array_object) */ #if defined(GL_OES_viewport_array) -extern PFNGLVIEWPORTARRAYVOESPROC glViewportArrayvOES; -extern PFNGLVIEWPORTINDEXEDFOESPROC glViewportIndexedfOES; -extern PFNGLVIEWPORTINDEXEDFVOESPROC glViewportIndexedfvOES; -extern PFNGLSCISSORARRAYVOESPROC glScissorArrayvOES; -extern PFNGLSCISSORINDEXEDOESPROC glScissorIndexedOES; -extern PFNGLSCISSORINDEXEDVOESPROC glScissorIndexedvOES; -extern PFNGLDEPTHRANGEARRAYFVOESPROC glDepthRangeArrayfvOES; +extern PFNGLVIEWPORTARRAYVOESPROC glViewportArrayvOES; +extern PFNGLVIEWPORTINDEXEDFOESPROC glViewportIndexedfOES; +extern PFNGLVIEWPORTINDEXEDFVOESPROC glViewportIndexedfvOES; +extern PFNGLSCISSORARRAYVOESPROC glScissorArrayvOES; +extern PFNGLSCISSORINDEXEDOESPROC glScissorIndexedOES; +extern PFNGLSCISSORINDEXEDVOESPROC glScissorIndexedvOES; +extern PFNGLDEPTHRANGEARRAYFVOESPROC glDepthRangeArrayfvOES; extern PFNGLDEPTHRANGEINDEXEDFOESPROC glDepthRangeIndexedfOES; -extern PFNGLGETFLOATI_VOESPROC glGetFloati_vOES; // NOLINT(readability-identifier-naming) -#endif /* defined(GL_OES_viewport_array) */ +extern PFNGLGETFLOATI_VOESPROC glGetFloati_vOES; // NOLINT(readability-identifier-naming) +#endif /* defined(GL_OES_viewport_array) */ #if defined(GL_OVR_multiview) extern PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC glFramebufferTextureMultiviewOVR; @@ -1049,37 +1049,37 @@ extern PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM; #endif /* defined(GL_QCOM_alpha_test) */ #if defined(GL_QCOM_driver_control) -extern PFNGLGETDRIVERCONTROLSQCOMPROC glGetDriverControlsQCOM; +extern PFNGLGETDRIVERCONTROLSQCOMPROC glGetDriverControlsQCOM; extern PFNGLGETDRIVERCONTROLSTRINGQCOMPROC glGetDriverControlStringQCOM; -extern PFNGLENABLEDRIVERCONTROLQCOMPROC glEnableDriverControlQCOM; -extern PFNGLDISABLEDRIVERCONTROLQCOMPROC glDisableDriverControlQCOM; +extern PFNGLENABLEDRIVERCONTROLQCOMPROC glEnableDriverControlQCOM; +extern PFNGLDISABLEDRIVERCONTROLQCOMPROC glDisableDriverControlQCOM; #endif /* defined(GL_QCOM_driver_control) */ #if defined(GL_QCOM_extended_get) -extern PFNGLEXTGETTEXTURESQCOMPROC glExtGetTexturesQCOM; -extern PFNGLEXTGETBUFFERSQCOMPROC glExtGetBuffersQCOM; -extern PFNGLEXTGETRENDERBUFFERSQCOMPROC glExtGetRenderbuffersQCOM; -extern PFNGLEXTGETFRAMEBUFFERSQCOMPROC glExtGetFramebuffersQCOM; -extern PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC glExtGetTexLevelParameterivQCOM; +extern PFNGLEXTGETTEXTURESQCOMPROC glExtGetTexturesQCOM; +extern PFNGLEXTGETBUFFERSQCOMPROC glExtGetBuffersQCOM; +extern PFNGLEXTGETRENDERBUFFERSQCOMPROC glExtGetRenderbuffersQCOM; +extern PFNGLEXTGETFRAMEBUFFERSQCOMPROC glExtGetFramebuffersQCOM; +extern PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC glExtGetTexLevelParameterivQCOM; extern PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC glExtTexObjectStateOverrideiQCOM; -extern PFNGLEXTGETTEXSUBIMAGEQCOMPROC glExtGetTexSubImageQCOM; -extern PFNGLEXTGETBUFFERPOINTERVQCOMPROC glExtGetBufferPointervQCOM; +extern PFNGLEXTGETTEXSUBIMAGEQCOMPROC glExtGetTexSubImageQCOM; +extern PFNGLEXTGETBUFFERPOINTERVQCOMPROC glExtGetBufferPointervQCOM; #endif /* defined(GL_QCOM_extended_get) */ #if defined(GL_QCOM_extended_get2) -extern PFNGLEXTGETSHADERSQCOMPROC glExtGetShadersQCOM; -extern PFNGLEXTGETPROGRAMSQCOMPROC glExtGetProgramsQCOM; -extern PFNGLEXTISPROGRAMBINARYQCOMPROC glExtIsProgramBinaryQCOM; +extern PFNGLEXTGETSHADERSQCOMPROC glExtGetShadersQCOM; +extern PFNGLEXTGETPROGRAMSQCOMPROC glExtGetProgramsQCOM; +extern PFNGLEXTISPROGRAMBINARYQCOMPROC glExtIsProgramBinaryQCOM; extern PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC glExtGetProgramBinarySourceQCOM; #endif /* defined(GL_QCOM_extended_get2) */ #if defined(GL_QCOM_framebuffer_foveated) -extern PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC glFramebufferFoveationConfigQCOM; +extern PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC glFramebufferFoveationConfigQCOM; extern PFNGLFRAMEBUFFERFOVEATIONPARAMETERSQCOMPROC glFramebufferFoveationParametersQCOM; #endif /* defined(GL_QCOM_framebuffer_foveated) */ #if defined(GL_QCOM_motion_estimation) -extern PFNGLTEXESTIMATEMOTIONQCOMPROC glTexEstimateMotionQCOM; +extern PFNGLTEXESTIMATEMOTIONQCOMPROC glTexEstimateMotionQCOM; extern PFNGLTEXESTIMATEMOTIONREGIONSQCOMPROC glTexEstimateMotionRegionsQCOM; #endif /* defined(GL_QCOM_motion_estimation) */ @@ -1101,7 +1101,7 @@ extern PFNGLSHADINGRATEQCOMPROC glShadingRateQCOM; #if defined(GL_QCOM_tiled_rendering) extern PFNGLSTARTTILINGQCOMPROC glStartTilingQCOM; -extern PFNGLENDTILINGQCOMPROC glEndTilingQCOM; +extern PFNGLENDTILINGQCOMPROC glEndTilingQCOM; #endif /* defined(GL_QCOM_tiled_rendering) */ /* GLES2W_GENERATE_GLES_DECLARATION */ diff --git a/native/cocos/renderer/gfx-gles-common/gles3w.cpp b/native/cocos/renderer/gfx-gles-common/gles3w.cpp index c604fc765a..c6517444ff 100644 --- a/native/cocos/renderer/gfx-gles-common/gles3w.cpp +++ b/native/cocos/renderer/gfx-gles-common/gles3w.cpp @@ -34,186 +34,186 @@ /* GLES3W_GENERATE_GLES_DEFINITION */ /* GL_ES_VERSION_3_0 */ -PFNGLREADBUFFERPROC glReadBuffer; -PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; -PFNGLTEXIMAGE3DPROC glTexImage3D; -PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; -PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; -PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; -PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; -PFNGLGENQUERIESPROC glGenQueries; -PFNGLDELETEQUERIESPROC glDeleteQueries; -PFNGLISQUERYPROC glIsQuery; -PFNGLBEGINQUERYPROC glBeginQuery; -PFNGLENDQUERYPROC glEndQuery; -PFNGLGETQUERYIVPROC glGetQueryiv; -PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; -PFNGLUNMAPBUFFERPROC glUnmapBuffer; -PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; -PFNGLDRAWBUFFERSPROC glDrawBuffers; -PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; -PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; -PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; -PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; -PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; -PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; -PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; +PFNGLREADBUFFERPROC glReadBuffer; +PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; +PFNGLTEXIMAGE3DPROC glTexImage3D; +PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; +PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; +PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; +PFNGLGENQUERIESPROC glGenQueries; +PFNGLDELETEQUERIESPROC glDeleteQueries; +PFNGLISQUERYPROC glIsQuery; +PFNGLBEGINQUERYPROC glBeginQuery; +PFNGLENDQUERYPROC glEndQuery; +PFNGLGETQUERYIVPROC glGetQueryiv; +PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; +PFNGLUNMAPBUFFERPROC glUnmapBuffer; +PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; +PFNGLDRAWBUFFERSPROC glDrawBuffers; +PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; +PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; +PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; +PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; +PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; +PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; +PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glRenderbufferStorageMultisample; -PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; -PFNGLMAPBUFFERRANGEPROC glMapBufferRange; -PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; -PFNGLBINDVERTEXARRAYPROC glBindVertexArray; -PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; -PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; -PFNGLISVERTEXARRAYPROC glIsVertexArray; -PFNGLGETINTEGERI_VPROC glGetIntegeri_v; -PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; -PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; -PFNGLBINDBUFFERRANGEPROC glBindBufferRange; -PFNGLBINDBUFFERBASEPROC glBindBufferBase; -PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; -PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; -PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; -PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; -PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; -PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; -PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; -PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; -PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; -PFNGLGETUNIFORMUIVPROC glGetUniformuiv; -PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; -PFNGLUNIFORM1UIPROC glUniform1ui; -PFNGLUNIFORM2UIPROC glUniform2ui; -PFNGLUNIFORM3UIPROC glUniform3ui; -PFNGLUNIFORM4UIPROC glUniform4ui; -PFNGLUNIFORM1UIVPROC glUniform1uiv; -PFNGLUNIFORM2UIVPROC glUniform2uiv; -PFNGLUNIFORM3UIVPROC glUniform3uiv; -PFNGLUNIFORM4UIVPROC glUniform4uiv; -PFNGLCLEARBUFFERIVPROC glClearBufferiv; -PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; -PFNGLCLEARBUFFERFVPROC glClearBufferfv; -PFNGLCLEARBUFFERFIPROC glClearBufferfi; -PFNGLGETSTRINGIPROC glGetStringi; -PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; -PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; -PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; -PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; -PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; -PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; -PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; -PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; -PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; -PFNGLFENCESYNCPROC glFenceSync; -PFNGLISSYNCPROC glIsSync; -PFNGLDELETESYNCPROC glDeleteSync; -PFNGLCLIENTWAITSYNCPROC glClientWaitSync; -PFNGLWAITSYNCPROC glWaitSync; -PFNGLGETINTEGER64VPROC glGetInteger64v; -PFNGLGETSYNCIVPROC glGetSynciv; -PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; -PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; -PFNGLGENSAMPLERSPROC glGenSamplers; -PFNGLDELETESAMPLERSPROC glDeleteSamplers; -PFNGLISSAMPLERPROC glIsSampler; -PFNGLBINDSAMPLERPROC glBindSampler; -PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; -PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; -PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; -PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; -PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; -PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; -PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; -PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; -PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; -PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; -PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; -PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; -PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; -PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; -PFNGLPROGRAMBINARYPROC glProgramBinary; -PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; -PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; -PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; -PFNGLTEXSTORAGE2DPROC glTexStorage2D; -PFNGLTEXSTORAGE3DPROC glTexStorage3D; -PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; +PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; +PFNGLMAPBUFFERRANGEPROC glMapBufferRange; +PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; +PFNGLBINDVERTEXARRAYPROC glBindVertexArray; +PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; +PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; +PFNGLISVERTEXARRAYPROC glIsVertexArray; +PFNGLGETINTEGERI_VPROC glGetIntegeri_v; +PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; +PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; +PFNGLBINDBUFFERRANGEPROC glBindBufferRange; +PFNGLBINDBUFFERBASEPROC glBindBufferBase; +PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; +PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; +PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; +PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; +PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; +PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; +PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; +PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; +PFNGLGETUNIFORMUIVPROC glGetUniformuiv; +PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; +PFNGLUNIFORM1UIPROC glUniform1ui; +PFNGLUNIFORM2UIPROC glUniform2ui; +PFNGLUNIFORM3UIPROC glUniform3ui; +PFNGLUNIFORM4UIPROC glUniform4ui; +PFNGLUNIFORM1UIVPROC glUniform1uiv; +PFNGLUNIFORM2UIVPROC glUniform2uiv; +PFNGLUNIFORM3UIVPROC glUniform3uiv; +PFNGLUNIFORM4UIVPROC glUniform4uiv; +PFNGLCLEARBUFFERIVPROC glClearBufferiv; +PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; +PFNGLCLEARBUFFERFVPROC glClearBufferfv; +PFNGLCLEARBUFFERFIPROC glClearBufferfi; +PFNGLGETSTRINGIPROC glGetStringi; +PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; +PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; +PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; +PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; +PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; +PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; +PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; +PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; +PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; +PFNGLFENCESYNCPROC glFenceSync; +PFNGLISSYNCPROC glIsSync; +PFNGLDELETESYNCPROC glDeleteSync; +PFNGLCLIENTWAITSYNCPROC glClientWaitSync; +PFNGLWAITSYNCPROC glWaitSync; +PFNGLGETINTEGER64VPROC glGetInteger64v; +PFNGLGETSYNCIVPROC glGetSynciv; +PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; +PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; +PFNGLGENSAMPLERSPROC glGenSamplers; +PFNGLDELETESAMPLERSPROC glDeleteSamplers; +PFNGLISSAMPLERPROC glIsSampler; +PFNGLBINDSAMPLERPROC glBindSampler; +PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; +PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; +PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; +PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; +PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; +PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; +PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; +PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; +PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; +PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; +PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; +PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; +PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; +PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; +PFNGLPROGRAMBINARYPROC glProgramBinary; +PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; +PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; +PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; +PFNGLTEXSTORAGE2DPROC glTexStorage2D; +PFNGLTEXSTORAGE3DPROC glTexStorage3D; +PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; /* GL_ES_VERSION_3_1 */ -PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; +PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; PFNGLDISPATCHCOMPUTEINDIRECTPROC glDispatchComputeIndirect; -PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; +PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; PFNGLDRAWELEMENTSINDIRECTPROC glDrawElementsIndirect; -PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; +PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; PFNGLGETFRAMEBUFFERPARAMETERIVPROC glGetFramebufferParameteriv; -PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; -PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; -PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; -PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; +PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; +PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; +PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; +PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; PFNGLGETPROGRAMRESOURCELOCATIONPROC glGetProgramResourceLocation; -PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; -PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; -PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; -PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; -PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; -PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; -PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; -PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; -PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; -PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; -PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; -PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; -PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; -PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; -PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; -PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; -PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; -PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; -PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; -PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; -PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; -PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; -PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; -PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; -PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; -PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; -PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; -PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; -PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; -PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; -PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; -PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; -PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; -PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; -PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; +PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; +PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; +PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; +PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; +PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; +PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; +PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; +PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; +PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; +PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; +PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; +PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; +PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; +PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; +PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; +PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; +PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; +PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; +PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; +PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; +PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; +PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; +PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; +PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; +PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; +PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; +PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; +PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; +PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; +PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; +PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; +PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; +PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; +PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; +PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glProgramUniformMatrix2x3fv; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glProgramUniformMatrix3x2fv; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glProgramUniformMatrix2x4fv; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glProgramUniformMatrix4x2fv; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glProgramUniformMatrix3x4fv; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glProgramUniformMatrix4x3fv; -PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; +PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; PFNGLGETPROGRAMPIPELINEINFOLOGPROC glGetProgramPipelineInfoLog; -PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; -PFNGLGETBOOLEANI_VPROC glGetBooleani_v; -PFNGLMEMORYBARRIERPROC glMemoryBarrier; +PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; +PFNGLGETBOOLEANI_VPROC glGetBooleani_v; +PFNGLMEMORYBARRIERPROC glMemoryBarrier; PFNGLMEMORYBARRIERBYREGIONPROC glMemoryBarrierByRegion; PFNGLTEXSTORAGE2DMULTISAMPLEPROC glTexStorage2DMultisample; -PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; -PFNGLSAMPLEMASKIPROC glSampleMaski; -PFNGLGETTEXLEVELPARAMETERIVPROC glGetTexLevelParameteriv; -PFNGLGETTEXLEVELPARAMETERFVPROC glGetTexLevelParameterfv; +PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; +PFNGLSAMPLEMASKIPROC glSampleMaski; +PFNGLGETTEXLEVELPARAMETERIVPROC glGetTexLevelParameteriv; +PFNGLGETTEXLEVELPARAMETERFVPROC glGetTexLevelParameterfv; -PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; -PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; -PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; -PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; +PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; +PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; +PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; +PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; PFNGLVERTEXBINDINGDIVISORPROC glVertexBindingDivisor; /* GL_ES_VERSION_3_2 */ @@ -221,29 +221,29 @@ PFNGLBLENDBARRIERPROC glBlendBarrier; PFNGLCOPYIMAGESUBDATAPROC glCopyImageSubData; -PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; -PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; +PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; +PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback; -PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; -PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; -PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; -PFNGLOBJECTLABELPROC glObjectLabel; -PFNGLGETOBJECTLABELPROC glGetObjectLabel; -PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; -PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; -PFNGLGETPOINTERVPROC glGetPointerv; +PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; +PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; +PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; +PFNGLOBJECTLABELPROC glObjectLabel; +PFNGLGETOBJECTLABELPROC glGetObjectLabel; +PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; +PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; +PFNGLGETPOINTERVPROC glGetPointerv; -PFNGLENABLEIPROC glEnablei; -PFNGLDISABLEIPROC glDisablei; -PFNGLBLENDEQUATIONIPROC glBlendEquationi; +PFNGLENABLEIPROC glEnablei; +PFNGLDISABLEIPROC glDisablei; +PFNGLBLENDEQUATIONIPROC glBlendEquationi; PFNGLBLENDEQUATIONSEPARATEIPROC glBlendEquationSeparatei; -PFNGLBLENDFUNCIPROC glBlendFunci; -PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; -PFNGLCOLORMASKIPROC glColorMaski; -PFNGLISENABLEDIPROC glIsEnabledi; +PFNGLBLENDFUNCIPROC glBlendFunci; +PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; +PFNGLCOLORMASKIPROC glColorMaski; +PFNGLISENABLEDIPROC glIsEnabledi; -PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; -PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; +PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glDrawElementsInstancedBaseVertex; PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; @@ -251,25 +251,25 @@ PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; PFNGLPRIMITIVEBOUNDINGBOXPROC glPrimitiveBoundingBox; PFNGLGETGRAPHICSRESETSTATUSPROC glGetGraphicsResetStatus; -PFNGLREADNPIXELSPROC glReadnPixels; -PFNGLGETNUNIFORMFVPROC glGetnUniformfv; -PFNGLGETNUNIFORMIVPROC glGetnUniformiv; -PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; +PFNGLREADNPIXELSPROC glReadnPixels; +PFNGLGETNUNIFORMFVPROC glGetnUniformfv; +PFNGLGETNUNIFORMIVPROC glGetnUniformiv; +PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; PFNGLMINSAMPLESHADINGPROC glMinSampleShading; PFNGLPATCHPARAMETERIPROC glPatchParameteri; -PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; -PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; -PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; -PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; -PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; -PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; -PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; +PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; +PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; +PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; +PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; +PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; +PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; +PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; PFNGLGETSAMPLERPARAMETERIUIVPROC glGetSamplerParameterIuiv; -PFNGLTEXBUFFERPROC glTexBuffer; +PFNGLTEXBUFFERPROC glTexBuffer; PFNGLTEXBUFFERRANGEPROC glTexBufferRange; PFNGLTEXSTORAGE3DMULTISAMPLEPROC glTexStorage3DMultisample; @@ -293,186 +293,186 @@ void gles3wLoadProcs(PFNGLES3WLOADPROC gles3wLoad) { /* GLES3W_GENERATE_GLES_LOAD */ /* GL_ES_VERSION_3_0 */ - glReadBuffer = reinterpret_cast(gles3wLoad("glReadBuffer")); - glDrawRangeElements = reinterpret_cast(gles3wLoad("glDrawRangeElements")); - glTexImage3D = reinterpret_cast(gles3wLoad("glTexImage3D")); - glTexSubImage3D = reinterpret_cast(gles3wLoad("glTexSubImage3D")); - glCopyTexSubImage3D = reinterpret_cast(gles3wLoad("glCopyTexSubImage3D")); - glCompressedTexImage3D = reinterpret_cast(gles3wLoad("glCompressedTexImage3D")); - glCompressedTexSubImage3D = reinterpret_cast(gles3wLoad("glCompressedTexSubImage3D")); - glGenQueries = reinterpret_cast(gles3wLoad("glGenQueries")); - glDeleteQueries = reinterpret_cast(gles3wLoad("glDeleteQueries")); - glIsQuery = reinterpret_cast(gles3wLoad("glIsQuery")); - glBeginQuery = reinterpret_cast(gles3wLoad("glBeginQuery")); - glEndQuery = reinterpret_cast(gles3wLoad("glEndQuery")); - glGetQueryiv = reinterpret_cast(gles3wLoad("glGetQueryiv")); - glGetQueryObjectuiv = reinterpret_cast(gles3wLoad("glGetQueryObjectuiv")); - glUnmapBuffer = reinterpret_cast(gles3wLoad("glUnmapBuffer")); - glGetBufferPointerv = reinterpret_cast(gles3wLoad("glGetBufferPointerv")); - glDrawBuffers = reinterpret_cast(gles3wLoad("glDrawBuffers")); - glUniformMatrix2x3fv = reinterpret_cast(gles3wLoad("glUniformMatrix2x3fv")); - glUniformMatrix3x2fv = reinterpret_cast(gles3wLoad("glUniformMatrix3x2fv")); - glUniformMatrix2x4fv = reinterpret_cast(gles3wLoad("glUniformMatrix2x4fv")); - glUniformMatrix4x2fv = reinterpret_cast(gles3wLoad("glUniformMatrix4x2fv")); - glUniformMatrix3x4fv = reinterpret_cast(gles3wLoad("glUniformMatrix3x4fv")); - glUniformMatrix4x3fv = reinterpret_cast(gles3wLoad("glUniformMatrix4x3fv")); - glBlitFramebuffer = reinterpret_cast(gles3wLoad("glBlitFramebuffer")); + glReadBuffer = reinterpret_cast(gles3wLoad("glReadBuffer")); + glDrawRangeElements = reinterpret_cast(gles3wLoad("glDrawRangeElements")); + glTexImage3D = reinterpret_cast(gles3wLoad("glTexImage3D")); + glTexSubImage3D = reinterpret_cast(gles3wLoad("glTexSubImage3D")); + glCopyTexSubImage3D = reinterpret_cast(gles3wLoad("glCopyTexSubImage3D")); + glCompressedTexImage3D = reinterpret_cast(gles3wLoad("glCompressedTexImage3D")); + glCompressedTexSubImage3D = reinterpret_cast(gles3wLoad("glCompressedTexSubImage3D")); + glGenQueries = reinterpret_cast(gles3wLoad("glGenQueries")); + glDeleteQueries = reinterpret_cast(gles3wLoad("glDeleteQueries")); + glIsQuery = reinterpret_cast(gles3wLoad("glIsQuery")); + glBeginQuery = reinterpret_cast(gles3wLoad("glBeginQuery")); + glEndQuery = reinterpret_cast(gles3wLoad("glEndQuery")); + glGetQueryiv = reinterpret_cast(gles3wLoad("glGetQueryiv")); + glGetQueryObjectuiv = reinterpret_cast(gles3wLoad("glGetQueryObjectuiv")); + glUnmapBuffer = reinterpret_cast(gles3wLoad("glUnmapBuffer")); + glGetBufferPointerv = reinterpret_cast(gles3wLoad("glGetBufferPointerv")); + glDrawBuffers = reinterpret_cast(gles3wLoad("glDrawBuffers")); + glUniformMatrix2x3fv = reinterpret_cast(gles3wLoad("glUniformMatrix2x3fv")); + glUniformMatrix3x2fv = reinterpret_cast(gles3wLoad("glUniformMatrix3x2fv")); + glUniformMatrix2x4fv = reinterpret_cast(gles3wLoad("glUniformMatrix2x4fv")); + glUniformMatrix4x2fv = reinterpret_cast(gles3wLoad("glUniformMatrix4x2fv")); + glUniformMatrix3x4fv = reinterpret_cast(gles3wLoad("glUniformMatrix3x4fv")); + glUniformMatrix4x3fv = reinterpret_cast(gles3wLoad("glUniformMatrix4x3fv")); + glBlitFramebuffer = reinterpret_cast(gles3wLoad("glBlitFramebuffer")); glRenderbufferStorageMultisample = reinterpret_cast(gles3wLoad("glRenderbufferStorageMultisample")); - glFramebufferTextureLayer = reinterpret_cast(gles3wLoad("glFramebufferTextureLayer")); - glMapBufferRange = reinterpret_cast(gles3wLoad("glMapBufferRange")); - glFlushMappedBufferRange = reinterpret_cast(gles3wLoad("glFlushMappedBufferRange")); - glBindVertexArray = reinterpret_cast(gles3wLoad("glBindVertexArray")); - glDeleteVertexArrays = reinterpret_cast(gles3wLoad("glDeleteVertexArrays")); - glGenVertexArrays = reinterpret_cast(gles3wLoad("glGenVertexArrays")); - glIsVertexArray = reinterpret_cast(gles3wLoad("glIsVertexArray")); - glGetIntegeri_v = reinterpret_cast(gles3wLoad("glGetIntegeri_v")); - glBeginTransformFeedback = reinterpret_cast(gles3wLoad("glBeginTransformFeedback")); - glEndTransformFeedback = reinterpret_cast(gles3wLoad("glEndTransformFeedback")); - glBindBufferRange = reinterpret_cast(gles3wLoad("glBindBufferRange")); - glBindBufferBase = reinterpret_cast(gles3wLoad("glBindBufferBase")); - glTransformFeedbackVaryings = reinterpret_cast(gles3wLoad("glTransformFeedbackVaryings")); - glGetTransformFeedbackVarying = reinterpret_cast(gles3wLoad("glGetTransformFeedbackVarying")); - glVertexAttribIPointer = reinterpret_cast(gles3wLoad("glVertexAttribIPointer")); - glGetVertexAttribIiv = reinterpret_cast(gles3wLoad("glGetVertexAttribIiv")); - glGetVertexAttribIuiv = reinterpret_cast(gles3wLoad("glGetVertexAttribIuiv")); - glVertexAttribI4i = reinterpret_cast(gles3wLoad("glVertexAttribI4i")); - glVertexAttribI4ui = reinterpret_cast(gles3wLoad("glVertexAttribI4ui")); - glVertexAttribI4iv = reinterpret_cast(gles3wLoad("glVertexAttribI4iv")); - glVertexAttribI4uiv = reinterpret_cast(gles3wLoad("glVertexAttribI4uiv")); - glGetUniformuiv = reinterpret_cast(gles3wLoad("glGetUniformuiv")); - glGetFragDataLocation = reinterpret_cast(gles3wLoad("glGetFragDataLocation")); - glUniform1ui = reinterpret_cast(gles3wLoad("glUniform1ui")); - glUniform2ui = reinterpret_cast(gles3wLoad("glUniform2ui")); - glUniform3ui = reinterpret_cast(gles3wLoad("glUniform3ui")); - glUniform4ui = reinterpret_cast(gles3wLoad("glUniform4ui")); - glUniform1uiv = reinterpret_cast(gles3wLoad("glUniform1uiv")); - glUniform2uiv = reinterpret_cast(gles3wLoad("glUniform2uiv")); - glUniform3uiv = reinterpret_cast(gles3wLoad("glUniform3uiv")); - glUniform4uiv = reinterpret_cast(gles3wLoad("glUniform4uiv")); - glClearBufferiv = reinterpret_cast(gles3wLoad("glClearBufferiv")); - glClearBufferuiv = reinterpret_cast(gles3wLoad("glClearBufferuiv")); - glClearBufferfv = reinterpret_cast(gles3wLoad("glClearBufferfv")); - glClearBufferfi = reinterpret_cast(gles3wLoad("glClearBufferfi")); - glGetStringi = reinterpret_cast(gles3wLoad("glGetStringi")); - glCopyBufferSubData = reinterpret_cast(gles3wLoad("glCopyBufferSubData")); - glGetUniformIndices = reinterpret_cast(gles3wLoad("glGetUniformIndices")); - glGetActiveUniformsiv = reinterpret_cast(gles3wLoad("glGetActiveUniformsiv")); - glGetUniformBlockIndex = reinterpret_cast(gles3wLoad("glGetUniformBlockIndex")); - glGetActiveUniformBlockiv = reinterpret_cast(gles3wLoad("glGetActiveUniformBlockiv")); - glGetActiveUniformBlockName = reinterpret_cast(gles3wLoad("glGetActiveUniformBlockName")); - glUniformBlockBinding = reinterpret_cast(gles3wLoad("glUniformBlockBinding")); - glDrawArraysInstanced = reinterpret_cast(gles3wLoad("glDrawArraysInstanced")); - glDrawElementsInstanced = reinterpret_cast(gles3wLoad("glDrawElementsInstanced")); - glFenceSync = reinterpret_cast(gles3wLoad("glFenceSync")); - glIsSync = reinterpret_cast(gles3wLoad("glIsSync")); - glDeleteSync = reinterpret_cast(gles3wLoad("glDeleteSync")); - glClientWaitSync = reinterpret_cast(gles3wLoad("glClientWaitSync")); - glWaitSync = reinterpret_cast(gles3wLoad("glWaitSync")); - glGetInteger64v = reinterpret_cast(gles3wLoad("glGetInteger64v")); - glGetSynciv = reinterpret_cast(gles3wLoad("glGetSynciv")); - glGetInteger64i_v = reinterpret_cast(gles3wLoad("glGetInteger64i_v")); - glGetBufferParameteri64v = reinterpret_cast(gles3wLoad("glGetBufferParameteri64v")); - glGenSamplers = reinterpret_cast(gles3wLoad("glGenSamplers")); - glDeleteSamplers = reinterpret_cast(gles3wLoad("glDeleteSamplers")); - glIsSampler = reinterpret_cast(gles3wLoad("glIsSampler")); - glBindSampler = reinterpret_cast(gles3wLoad("glBindSampler")); - glSamplerParameteri = reinterpret_cast(gles3wLoad("glSamplerParameteri")); - glSamplerParameteriv = reinterpret_cast(gles3wLoad("glSamplerParameteriv")); - glSamplerParameterf = reinterpret_cast(gles3wLoad("glSamplerParameterf")); - glSamplerParameterfv = reinterpret_cast(gles3wLoad("glSamplerParameterfv")); - glGetSamplerParameteriv = reinterpret_cast(gles3wLoad("glGetSamplerParameteriv")); - glGetSamplerParameterfv = reinterpret_cast(gles3wLoad("glGetSamplerParameterfv")); - glVertexAttribDivisor = reinterpret_cast(gles3wLoad("glVertexAttribDivisor")); - glBindTransformFeedback = reinterpret_cast(gles3wLoad("glBindTransformFeedback")); - glDeleteTransformFeedbacks = reinterpret_cast(gles3wLoad("glDeleteTransformFeedbacks")); - glGenTransformFeedbacks = reinterpret_cast(gles3wLoad("glGenTransformFeedbacks")); - glIsTransformFeedback = reinterpret_cast(gles3wLoad("glIsTransformFeedback")); - glPauseTransformFeedback = reinterpret_cast(gles3wLoad("glPauseTransformFeedback")); - glResumeTransformFeedback = reinterpret_cast(gles3wLoad("glResumeTransformFeedback")); - glGetProgramBinary = reinterpret_cast(gles3wLoad("glGetProgramBinary")); - glProgramBinary = reinterpret_cast(gles3wLoad("glProgramBinary")); - glProgramParameteri = reinterpret_cast(gles3wLoad("glProgramParameteri")); - glInvalidateFramebuffer = reinterpret_cast(gles3wLoad("glInvalidateFramebuffer")); - glInvalidateSubFramebuffer = reinterpret_cast(gles3wLoad("glInvalidateSubFramebuffer")); - glTexStorage2D = reinterpret_cast(gles3wLoad("glTexStorage2D")); - glTexStorage3D = reinterpret_cast(gles3wLoad("glTexStorage3D")); - glGetInternalformativ = reinterpret_cast(gles3wLoad("glGetInternalformativ")); + glFramebufferTextureLayer = reinterpret_cast(gles3wLoad("glFramebufferTextureLayer")); + glMapBufferRange = reinterpret_cast(gles3wLoad("glMapBufferRange")); + glFlushMappedBufferRange = reinterpret_cast(gles3wLoad("glFlushMappedBufferRange")); + glBindVertexArray = reinterpret_cast(gles3wLoad("glBindVertexArray")); + glDeleteVertexArrays = reinterpret_cast(gles3wLoad("glDeleteVertexArrays")); + glGenVertexArrays = reinterpret_cast(gles3wLoad("glGenVertexArrays")); + glIsVertexArray = reinterpret_cast(gles3wLoad("glIsVertexArray")); + glGetIntegeri_v = reinterpret_cast(gles3wLoad("glGetIntegeri_v")); + glBeginTransformFeedback = reinterpret_cast(gles3wLoad("glBeginTransformFeedback")); + glEndTransformFeedback = reinterpret_cast(gles3wLoad("glEndTransformFeedback")); + glBindBufferRange = reinterpret_cast(gles3wLoad("glBindBufferRange")); + glBindBufferBase = reinterpret_cast(gles3wLoad("glBindBufferBase")); + glTransformFeedbackVaryings = reinterpret_cast(gles3wLoad("glTransformFeedbackVaryings")); + glGetTransformFeedbackVarying = reinterpret_cast(gles3wLoad("glGetTransformFeedbackVarying")); + glVertexAttribIPointer = reinterpret_cast(gles3wLoad("glVertexAttribIPointer")); + glGetVertexAttribIiv = reinterpret_cast(gles3wLoad("glGetVertexAttribIiv")); + glGetVertexAttribIuiv = reinterpret_cast(gles3wLoad("glGetVertexAttribIuiv")); + glVertexAttribI4i = reinterpret_cast(gles3wLoad("glVertexAttribI4i")); + glVertexAttribI4ui = reinterpret_cast(gles3wLoad("glVertexAttribI4ui")); + glVertexAttribI4iv = reinterpret_cast(gles3wLoad("glVertexAttribI4iv")); + glVertexAttribI4uiv = reinterpret_cast(gles3wLoad("glVertexAttribI4uiv")); + glGetUniformuiv = reinterpret_cast(gles3wLoad("glGetUniformuiv")); + glGetFragDataLocation = reinterpret_cast(gles3wLoad("glGetFragDataLocation")); + glUniform1ui = reinterpret_cast(gles3wLoad("glUniform1ui")); + glUniform2ui = reinterpret_cast(gles3wLoad("glUniform2ui")); + glUniform3ui = reinterpret_cast(gles3wLoad("glUniform3ui")); + glUniform4ui = reinterpret_cast(gles3wLoad("glUniform4ui")); + glUniform1uiv = reinterpret_cast(gles3wLoad("glUniform1uiv")); + glUniform2uiv = reinterpret_cast(gles3wLoad("glUniform2uiv")); + glUniform3uiv = reinterpret_cast(gles3wLoad("glUniform3uiv")); + glUniform4uiv = reinterpret_cast(gles3wLoad("glUniform4uiv")); + glClearBufferiv = reinterpret_cast(gles3wLoad("glClearBufferiv")); + glClearBufferuiv = reinterpret_cast(gles3wLoad("glClearBufferuiv")); + glClearBufferfv = reinterpret_cast(gles3wLoad("glClearBufferfv")); + glClearBufferfi = reinterpret_cast(gles3wLoad("glClearBufferfi")); + glGetStringi = reinterpret_cast(gles3wLoad("glGetStringi")); + glCopyBufferSubData = reinterpret_cast(gles3wLoad("glCopyBufferSubData")); + glGetUniformIndices = reinterpret_cast(gles3wLoad("glGetUniformIndices")); + glGetActiveUniformsiv = reinterpret_cast(gles3wLoad("glGetActiveUniformsiv")); + glGetUniformBlockIndex = reinterpret_cast(gles3wLoad("glGetUniformBlockIndex")); + glGetActiveUniformBlockiv = reinterpret_cast(gles3wLoad("glGetActiveUniformBlockiv")); + glGetActiveUniformBlockName = reinterpret_cast(gles3wLoad("glGetActiveUniformBlockName")); + glUniformBlockBinding = reinterpret_cast(gles3wLoad("glUniformBlockBinding")); + glDrawArraysInstanced = reinterpret_cast(gles3wLoad("glDrawArraysInstanced")); + glDrawElementsInstanced = reinterpret_cast(gles3wLoad("glDrawElementsInstanced")); + glFenceSync = reinterpret_cast(gles3wLoad("glFenceSync")); + glIsSync = reinterpret_cast(gles3wLoad("glIsSync")); + glDeleteSync = reinterpret_cast(gles3wLoad("glDeleteSync")); + glClientWaitSync = reinterpret_cast(gles3wLoad("glClientWaitSync")); + glWaitSync = reinterpret_cast(gles3wLoad("glWaitSync")); + glGetInteger64v = reinterpret_cast(gles3wLoad("glGetInteger64v")); + glGetSynciv = reinterpret_cast(gles3wLoad("glGetSynciv")); + glGetInteger64i_v = reinterpret_cast(gles3wLoad("glGetInteger64i_v")); + glGetBufferParameteri64v = reinterpret_cast(gles3wLoad("glGetBufferParameteri64v")); + glGenSamplers = reinterpret_cast(gles3wLoad("glGenSamplers")); + glDeleteSamplers = reinterpret_cast(gles3wLoad("glDeleteSamplers")); + glIsSampler = reinterpret_cast(gles3wLoad("glIsSampler")); + glBindSampler = reinterpret_cast(gles3wLoad("glBindSampler")); + glSamplerParameteri = reinterpret_cast(gles3wLoad("glSamplerParameteri")); + glSamplerParameteriv = reinterpret_cast(gles3wLoad("glSamplerParameteriv")); + glSamplerParameterf = reinterpret_cast(gles3wLoad("glSamplerParameterf")); + glSamplerParameterfv = reinterpret_cast(gles3wLoad("glSamplerParameterfv")); + glGetSamplerParameteriv = reinterpret_cast(gles3wLoad("glGetSamplerParameteriv")); + glGetSamplerParameterfv = reinterpret_cast(gles3wLoad("glGetSamplerParameterfv")); + glVertexAttribDivisor = reinterpret_cast(gles3wLoad("glVertexAttribDivisor")); + glBindTransformFeedback = reinterpret_cast(gles3wLoad("glBindTransformFeedback")); + glDeleteTransformFeedbacks = reinterpret_cast(gles3wLoad("glDeleteTransformFeedbacks")); + glGenTransformFeedbacks = reinterpret_cast(gles3wLoad("glGenTransformFeedbacks")); + glIsTransformFeedback = reinterpret_cast(gles3wLoad("glIsTransformFeedback")); + glPauseTransformFeedback = reinterpret_cast(gles3wLoad("glPauseTransformFeedback")); + glResumeTransformFeedback = reinterpret_cast(gles3wLoad("glResumeTransformFeedback")); + glGetProgramBinary = reinterpret_cast(gles3wLoad("glGetProgramBinary")); + glProgramBinary = reinterpret_cast(gles3wLoad("glProgramBinary")); + glProgramParameteri = reinterpret_cast(gles3wLoad("glProgramParameteri")); + glInvalidateFramebuffer = reinterpret_cast(gles3wLoad("glInvalidateFramebuffer")); + glInvalidateSubFramebuffer = reinterpret_cast(gles3wLoad("glInvalidateSubFramebuffer")); + glTexStorage2D = reinterpret_cast(gles3wLoad("glTexStorage2D")); + glTexStorage3D = reinterpret_cast(gles3wLoad("glTexStorage3D")); + glGetInternalformativ = reinterpret_cast(gles3wLoad("glGetInternalformativ")); /* GL_ES_VERSION_3_1 */ - glDispatchCompute = reinterpret_cast(gles3wLoad("glDispatchCompute")); + glDispatchCompute = reinterpret_cast(gles3wLoad("glDispatchCompute")); glDispatchComputeIndirect = reinterpret_cast(gles3wLoad("glDispatchComputeIndirect")); - glDrawArraysIndirect = reinterpret_cast(gles3wLoad("glDrawArraysIndirect")); + glDrawArraysIndirect = reinterpret_cast(gles3wLoad("glDrawArraysIndirect")); glDrawElementsIndirect = reinterpret_cast(gles3wLoad("glDrawElementsIndirect")); - glFramebufferParameteri = reinterpret_cast(gles3wLoad("glFramebufferParameteri")); + glFramebufferParameteri = reinterpret_cast(gles3wLoad("glFramebufferParameteri")); glGetFramebufferParameteriv = reinterpret_cast(gles3wLoad("glGetFramebufferParameteriv")); - glGetProgramInterfaceiv = reinterpret_cast(gles3wLoad("glGetProgramInterfaceiv")); - glGetProgramResourceIndex = reinterpret_cast(gles3wLoad("glGetProgramResourceIndex")); - glGetProgramResourceName = reinterpret_cast(gles3wLoad("glGetProgramResourceName")); - glGetProgramResourceiv = reinterpret_cast(gles3wLoad("glGetProgramResourceiv")); + glGetProgramInterfaceiv = reinterpret_cast(gles3wLoad("glGetProgramInterfaceiv")); + glGetProgramResourceIndex = reinterpret_cast(gles3wLoad("glGetProgramResourceIndex")); + glGetProgramResourceName = reinterpret_cast(gles3wLoad("glGetProgramResourceName")); + glGetProgramResourceiv = reinterpret_cast(gles3wLoad("glGetProgramResourceiv")); glGetProgramResourceLocation = reinterpret_cast(gles3wLoad("glGetProgramResourceLocation")); - glUseProgramStages = reinterpret_cast(gles3wLoad("glUseProgramStages")); - glActiveShaderProgram = reinterpret_cast(gles3wLoad("glActiveShaderProgram")); - glCreateShaderProgramv = reinterpret_cast(gles3wLoad("glCreateShaderProgramv")); - glBindProgramPipeline = reinterpret_cast(gles3wLoad("glBindProgramPipeline")); - glDeleteProgramPipelines = reinterpret_cast(gles3wLoad("glDeleteProgramPipelines")); - glGenProgramPipelines = reinterpret_cast(gles3wLoad("glGenProgramPipelines")); - glIsProgramPipeline = reinterpret_cast(gles3wLoad("glIsProgramPipeline")); - glGetProgramPipelineiv = reinterpret_cast(gles3wLoad("glGetProgramPipelineiv")); - glProgramUniform1i = reinterpret_cast(gles3wLoad("glProgramUniform1i")); - glProgramUniform2i = reinterpret_cast(gles3wLoad("glProgramUniform2i")); - glProgramUniform3i = reinterpret_cast(gles3wLoad("glProgramUniform3i")); - glProgramUniform4i = reinterpret_cast(gles3wLoad("glProgramUniform4i")); - glProgramUniform1ui = reinterpret_cast(gles3wLoad("glProgramUniform1ui")); - glProgramUniform2ui = reinterpret_cast(gles3wLoad("glProgramUniform2ui")); - glProgramUniform3ui = reinterpret_cast(gles3wLoad("glProgramUniform3ui")); - glProgramUniform4ui = reinterpret_cast(gles3wLoad("glProgramUniform4ui")); - glProgramUniform1f = reinterpret_cast(gles3wLoad("glProgramUniform1f")); - glProgramUniform2f = reinterpret_cast(gles3wLoad("glProgramUniform2f")); - glProgramUniform3f = reinterpret_cast(gles3wLoad("glProgramUniform3f")); - glProgramUniform4f = reinterpret_cast(gles3wLoad("glProgramUniform4f")); - glProgramUniform1iv = reinterpret_cast(gles3wLoad("glProgramUniform1iv")); - glProgramUniform2iv = reinterpret_cast(gles3wLoad("glProgramUniform2iv")); - glProgramUniform3iv = reinterpret_cast(gles3wLoad("glProgramUniform3iv")); - glProgramUniform4iv = reinterpret_cast(gles3wLoad("glProgramUniform4iv")); - glProgramUniform1uiv = reinterpret_cast(gles3wLoad("glProgramUniform1uiv")); - glProgramUniform2uiv = reinterpret_cast(gles3wLoad("glProgramUniform2uiv")); - glProgramUniform3uiv = reinterpret_cast(gles3wLoad("glProgramUniform3uiv")); - glProgramUniform4uiv = reinterpret_cast(gles3wLoad("glProgramUniform4uiv")); - glProgramUniform1fv = reinterpret_cast(gles3wLoad("glProgramUniform1fv")); - glProgramUniform2fv = reinterpret_cast(gles3wLoad("glProgramUniform2fv")); - glProgramUniform3fv = reinterpret_cast(gles3wLoad("glProgramUniform3fv")); - glProgramUniform4fv = reinterpret_cast(gles3wLoad("glProgramUniform4fv")); - glProgramUniformMatrix2fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix2fv")); - glProgramUniformMatrix3fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix3fv")); - glProgramUniformMatrix4fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix4fv")); + glUseProgramStages = reinterpret_cast(gles3wLoad("glUseProgramStages")); + glActiveShaderProgram = reinterpret_cast(gles3wLoad("glActiveShaderProgram")); + glCreateShaderProgramv = reinterpret_cast(gles3wLoad("glCreateShaderProgramv")); + glBindProgramPipeline = reinterpret_cast(gles3wLoad("glBindProgramPipeline")); + glDeleteProgramPipelines = reinterpret_cast(gles3wLoad("glDeleteProgramPipelines")); + glGenProgramPipelines = reinterpret_cast(gles3wLoad("glGenProgramPipelines")); + glIsProgramPipeline = reinterpret_cast(gles3wLoad("glIsProgramPipeline")); + glGetProgramPipelineiv = reinterpret_cast(gles3wLoad("glGetProgramPipelineiv")); + glProgramUniform1i = reinterpret_cast(gles3wLoad("glProgramUniform1i")); + glProgramUniform2i = reinterpret_cast(gles3wLoad("glProgramUniform2i")); + glProgramUniform3i = reinterpret_cast(gles3wLoad("glProgramUniform3i")); + glProgramUniform4i = reinterpret_cast(gles3wLoad("glProgramUniform4i")); + glProgramUniform1ui = reinterpret_cast(gles3wLoad("glProgramUniform1ui")); + glProgramUniform2ui = reinterpret_cast(gles3wLoad("glProgramUniform2ui")); + glProgramUniform3ui = reinterpret_cast(gles3wLoad("glProgramUniform3ui")); + glProgramUniform4ui = reinterpret_cast(gles3wLoad("glProgramUniform4ui")); + glProgramUniform1f = reinterpret_cast(gles3wLoad("glProgramUniform1f")); + glProgramUniform2f = reinterpret_cast(gles3wLoad("glProgramUniform2f")); + glProgramUniform3f = reinterpret_cast(gles3wLoad("glProgramUniform3f")); + glProgramUniform4f = reinterpret_cast(gles3wLoad("glProgramUniform4f")); + glProgramUniform1iv = reinterpret_cast(gles3wLoad("glProgramUniform1iv")); + glProgramUniform2iv = reinterpret_cast(gles3wLoad("glProgramUniform2iv")); + glProgramUniform3iv = reinterpret_cast(gles3wLoad("glProgramUniform3iv")); + glProgramUniform4iv = reinterpret_cast(gles3wLoad("glProgramUniform4iv")); + glProgramUniform1uiv = reinterpret_cast(gles3wLoad("glProgramUniform1uiv")); + glProgramUniform2uiv = reinterpret_cast(gles3wLoad("glProgramUniform2uiv")); + glProgramUniform3uiv = reinterpret_cast(gles3wLoad("glProgramUniform3uiv")); + glProgramUniform4uiv = reinterpret_cast(gles3wLoad("glProgramUniform4uiv")); + glProgramUniform1fv = reinterpret_cast(gles3wLoad("glProgramUniform1fv")); + glProgramUniform2fv = reinterpret_cast(gles3wLoad("glProgramUniform2fv")); + glProgramUniform3fv = reinterpret_cast(gles3wLoad("glProgramUniform3fv")); + glProgramUniform4fv = reinterpret_cast(gles3wLoad("glProgramUniform4fv")); + glProgramUniformMatrix2fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix2fv")); + glProgramUniformMatrix3fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix3fv")); + glProgramUniformMatrix4fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix4fv")); glProgramUniformMatrix2x3fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix2x3fv")); glProgramUniformMatrix3x2fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix3x2fv")); glProgramUniformMatrix2x4fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix2x4fv")); glProgramUniformMatrix4x2fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix4x2fv")); glProgramUniformMatrix3x4fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix3x4fv")); glProgramUniformMatrix4x3fv = reinterpret_cast(gles3wLoad("glProgramUniformMatrix4x3fv")); - glValidateProgramPipeline = reinterpret_cast(gles3wLoad("glValidateProgramPipeline")); + glValidateProgramPipeline = reinterpret_cast(gles3wLoad("glValidateProgramPipeline")); glGetProgramPipelineInfoLog = reinterpret_cast(gles3wLoad("glGetProgramPipelineInfoLog")); - glBindImageTexture = reinterpret_cast(gles3wLoad("glBindImageTexture")); - glGetBooleani_v = reinterpret_cast(gles3wLoad("glGetBooleani_v")); - glMemoryBarrier = reinterpret_cast(gles3wLoad("glMemoryBarrier")); + glBindImageTexture = reinterpret_cast(gles3wLoad("glBindImageTexture")); + glGetBooleani_v = reinterpret_cast(gles3wLoad("glGetBooleani_v")); + glMemoryBarrier = reinterpret_cast(gles3wLoad("glMemoryBarrier")); glMemoryBarrierByRegion = reinterpret_cast(gles3wLoad("glMemoryBarrierByRegion")); glTexStorage2DMultisample = reinterpret_cast(gles3wLoad("glTexStorage2DMultisample")); - glGetMultisamplefv = reinterpret_cast(gles3wLoad("glGetMultisamplefv")); - glSampleMaski = reinterpret_cast(gles3wLoad("glSampleMaski")); - glGetTexLevelParameteriv = reinterpret_cast(gles3wLoad("glGetTexLevelParameteriv")); - glGetTexLevelParameterfv = reinterpret_cast(gles3wLoad("glGetTexLevelParameterfv")); + glGetMultisamplefv = reinterpret_cast(gles3wLoad("glGetMultisamplefv")); + glSampleMaski = reinterpret_cast(gles3wLoad("glSampleMaski")); + glGetTexLevelParameteriv = reinterpret_cast(gles3wLoad("glGetTexLevelParameteriv")); + glGetTexLevelParameterfv = reinterpret_cast(gles3wLoad("glGetTexLevelParameterfv")); - glBindVertexBuffer = reinterpret_cast(gles3wLoad("glBindVertexBuffer")); - glVertexAttribFormat = reinterpret_cast(gles3wLoad("glVertexAttribFormat")); - glVertexAttribIFormat = reinterpret_cast(gles3wLoad("glVertexAttribIFormat")); - glVertexAttribBinding = reinterpret_cast(gles3wLoad("glVertexAttribBinding")); + glBindVertexBuffer = reinterpret_cast(gles3wLoad("glBindVertexBuffer")); + glVertexAttribFormat = reinterpret_cast(gles3wLoad("glVertexAttribFormat")); + glVertexAttribIFormat = reinterpret_cast(gles3wLoad("glVertexAttribIFormat")); + glVertexAttribBinding = reinterpret_cast(gles3wLoad("glVertexAttribBinding")); glVertexBindingDivisor = reinterpret_cast(gles3wLoad("glVertexBindingDivisor")); /* GL_ES_VERSION_3_2 */ @@ -480,29 +480,29 @@ void gles3wLoadProcs(PFNGLES3WLOADPROC gles3wLoad) { glCopyImageSubData = reinterpret_cast(gles3wLoad("glCopyImageSubData")); - glDebugMessageControl = reinterpret_cast(gles3wLoad("glDebugMessageControl")); - glDebugMessageInsert = reinterpret_cast(gles3wLoad("glDebugMessageInsert")); + glDebugMessageControl = reinterpret_cast(gles3wLoad("glDebugMessageControl")); + glDebugMessageInsert = reinterpret_cast(gles3wLoad("glDebugMessageInsert")); glDebugMessageCallback = reinterpret_cast(gles3wLoad("glDebugMessageCallback")); - glGetDebugMessageLog = reinterpret_cast(gles3wLoad("glGetDebugMessageLog")); - glPushDebugGroup = reinterpret_cast(gles3wLoad("glPushDebugGroup")); - glPopDebugGroup = reinterpret_cast(gles3wLoad("glPopDebugGroup")); - glObjectLabel = reinterpret_cast(gles3wLoad("glObjectLabel")); - glGetObjectLabel = reinterpret_cast(gles3wLoad("glGetObjectLabel")); - glObjectPtrLabel = reinterpret_cast(gles3wLoad("glObjectPtrLabel")); - glGetObjectPtrLabel = reinterpret_cast(gles3wLoad("glGetObjectPtrLabel")); - glGetPointerv = reinterpret_cast(gles3wLoad("glGetPointerv")); + glGetDebugMessageLog = reinterpret_cast(gles3wLoad("glGetDebugMessageLog")); + glPushDebugGroup = reinterpret_cast(gles3wLoad("glPushDebugGroup")); + glPopDebugGroup = reinterpret_cast(gles3wLoad("glPopDebugGroup")); + glObjectLabel = reinterpret_cast(gles3wLoad("glObjectLabel")); + glGetObjectLabel = reinterpret_cast(gles3wLoad("glGetObjectLabel")); + glObjectPtrLabel = reinterpret_cast(gles3wLoad("glObjectPtrLabel")); + glGetObjectPtrLabel = reinterpret_cast(gles3wLoad("glGetObjectPtrLabel")); + glGetPointerv = reinterpret_cast(gles3wLoad("glGetPointerv")); - glEnablei = reinterpret_cast(gles3wLoad("glEnablei")); - glDisablei = reinterpret_cast(gles3wLoad("glDisablei")); - glBlendEquationi = reinterpret_cast(gles3wLoad("glBlendEquationi")); + glEnablei = reinterpret_cast(gles3wLoad("glEnablei")); + glDisablei = reinterpret_cast(gles3wLoad("glDisablei")); + glBlendEquationi = reinterpret_cast(gles3wLoad("glBlendEquationi")); glBlendEquationSeparatei = reinterpret_cast(gles3wLoad("glBlendEquationSeparatei")); - glBlendFunci = reinterpret_cast(gles3wLoad("glBlendFunci")); - glBlendFuncSeparatei = reinterpret_cast(gles3wLoad("glBlendFuncSeparatei")); - glColorMaski = reinterpret_cast(gles3wLoad("glColorMaski")); - glIsEnabledi = reinterpret_cast(gles3wLoad("glIsEnabledi")); + glBlendFunci = reinterpret_cast(gles3wLoad("glBlendFunci")); + glBlendFuncSeparatei = reinterpret_cast(gles3wLoad("glBlendFuncSeparatei")); + glColorMaski = reinterpret_cast(gles3wLoad("glColorMaski")); + glIsEnabledi = reinterpret_cast(gles3wLoad("glIsEnabledi")); - glDrawElementsBaseVertex = reinterpret_cast(gles3wLoad("glDrawElementsBaseVertex")); - glDrawRangeElementsBaseVertex = reinterpret_cast(gles3wLoad("glDrawRangeElementsBaseVertex")); + glDrawElementsBaseVertex = reinterpret_cast(gles3wLoad("glDrawElementsBaseVertex")); + glDrawRangeElementsBaseVertex = reinterpret_cast(gles3wLoad("glDrawRangeElementsBaseVertex")); glDrawElementsInstancedBaseVertex = reinterpret_cast(gles3wLoad("glDrawElementsInstancedBaseVertex")); glFramebufferTexture = reinterpret_cast(gles3wLoad("glFramebufferTexture")); @@ -510,25 +510,25 @@ void gles3wLoadProcs(PFNGLES3WLOADPROC gles3wLoad) { glPrimitiveBoundingBox = reinterpret_cast(gles3wLoad("glPrimitiveBoundingBox")); glGetGraphicsResetStatus = reinterpret_cast(gles3wLoad("glGetGraphicsResetStatus")); - glReadnPixels = reinterpret_cast(gles3wLoad("glReadnPixels")); - glGetnUniformfv = reinterpret_cast(gles3wLoad("glGetnUniformfv")); - glGetnUniformiv = reinterpret_cast(gles3wLoad("glGetnUniformiv")); - glGetnUniformuiv = reinterpret_cast(gles3wLoad("glGetnUniformuiv")); + glReadnPixels = reinterpret_cast(gles3wLoad("glReadnPixels")); + glGetnUniformfv = reinterpret_cast(gles3wLoad("glGetnUniformfv")); + glGetnUniformiv = reinterpret_cast(gles3wLoad("glGetnUniformiv")); + glGetnUniformuiv = reinterpret_cast(gles3wLoad("glGetnUniformuiv")); glMinSampleShading = reinterpret_cast(gles3wLoad("glMinSampleShading")); glPatchParameteri = reinterpret_cast(gles3wLoad("glPatchParameteri")); - glTexParameterIiv = reinterpret_cast(gles3wLoad("glTexParameterIiv")); - glTexParameterIuiv = reinterpret_cast(gles3wLoad("glTexParameterIuiv")); - glGetTexParameterIiv = reinterpret_cast(gles3wLoad("glGetTexParameterIiv")); - glGetTexParameterIuiv = reinterpret_cast(gles3wLoad("glGetTexParameterIuiv")); - glSamplerParameterIiv = reinterpret_cast(gles3wLoad("glSamplerParameterIiv")); - glSamplerParameterIuiv = reinterpret_cast(gles3wLoad("glSamplerParameterIuiv")); - glGetSamplerParameterIiv = reinterpret_cast(gles3wLoad("glGetSamplerParameterIiv")); + glTexParameterIiv = reinterpret_cast(gles3wLoad("glTexParameterIiv")); + glTexParameterIuiv = reinterpret_cast(gles3wLoad("glTexParameterIuiv")); + glGetTexParameterIiv = reinterpret_cast(gles3wLoad("glGetTexParameterIiv")); + glGetTexParameterIuiv = reinterpret_cast(gles3wLoad("glGetTexParameterIuiv")); + glSamplerParameterIiv = reinterpret_cast(gles3wLoad("glSamplerParameterIiv")); + glSamplerParameterIuiv = reinterpret_cast(gles3wLoad("glSamplerParameterIuiv")); + glGetSamplerParameterIiv = reinterpret_cast(gles3wLoad("glGetSamplerParameterIiv")); glGetSamplerParameterIuiv = reinterpret_cast(gles3wLoad("glGetSamplerParameterIuiv")); - glTexBuffer = reinterpret_cast(gles3wLoad("glTexBuffer")); + glTexBuffer = reinterpret_cast(gles3wLoad("glTexBuffer")); glTexBufferRange = reinterpret_cast(gles3wLoad("glTexBufferRange")); glTexStorage3DMultisample = reinterpret_cast(gles3wLoad("glTexStorage3DMultisample")); diff --git a/native/cocos/renderer/gfx-gles-common/gles3w.h b/native/cocos/renderer/gfx-gles-common/gles3w.h index 00c23d3759..e5addbb397 100644 --- a/native/cocos/renderer/gfx-gles-common/gles3w.h +++ b/native/cocos/renderer/gfx-gles-common/gles3w.h @@ -37,186 +37,186 @@ /* GLES3W_GENERATE_GLES_DECLARATION */ /* GL_ES_VERSION_3_0 */ -extern PFNGLREADBUFFERPROC glReadBuffer; -extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; -extern PFNGLTEXIMAGE3DPROC glTexImage3D; -extern PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; -extern PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; -extern PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; -extern PFNGLGENQUERIESPROC glGenQueries; -extern PFNGLDELETEQUERIESPROC glDeleteQueries; -extern PFNGLISQUERYPROC glIsQuery; -extern PFNGLBEGINQUERYPROC glBeginQuery; -extern PFNGLENDQUERYPROC glEndQuery; -extern PFNGLGETQUERYIVPROC glGetQueryiv; -extern PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; -extern PFNGLUNMAPBUFFERPROC glUnmapBuffer; -extern PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; -extern PFNGLDRAWBUFFERSPROC glDrawBuffers; -extern PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; -extern PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; -extern PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; -extern PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; -extern PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; -extern PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; -extern PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; +extern PFNGLREADBUFFERPROC glReadBuffer; +extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; +extern PFNGLTEXIMAGE3DPROC glTexImage3D; +extern PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; +extern PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; +extern PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; +extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; +extern PFNGLGENQUERIESPROC glGenQueries; +extern PFNGLDELETEQUERIESPROC glDeleteQueries; +extern PFNGLISQUERYPROC glIsQuery; +extern PFNGLBEGINQUERYPROC glBeginQuery; +extern PFNGLENDQUERYPROC glEndQuery; +extern PFNGLGETQUERYIVPROC glGetQueryiv; +extern PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; +extern PFNGLUNMAPBUFFERPROC glUnmapBuffer; +extern PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; +extern PFNGLDRAWBUFFERSPROC glDrawBuffers; +extern PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; +extern PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; +extern PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; +extern PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; +extern PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; +extern PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; +extern PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glRenderbufferStorageMultisample; -extern PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; -extern PFNGLMAPBUFFERRANGEPROC glMapBufferRange; -extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; -extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray; -extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; -extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; -extern PFNGLISVERTEXARRAYPROC glIsVertexArray; -extern PFNGLGETINTEGERI_VPROC glGetIntegeri_v; // NOLINT(readability-identifier-naming) -extern PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; -extern PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; -extern PFNGLBINDBUFFERRANGEPROC glBindBufferRange; -extern PFNGLBINDBUFFERBASEPROC glBindBufferBase; -extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; -extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; -extern PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; -extern PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; -extern PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; -extern PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; -extern PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; -extern PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; -extern PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; -extern PFNGLGETUNIFORMUIVPROC glGetUniformuiv; -extern PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; -extern PFNGLUNIFORM1UIPROC glUniform1ui; -extern PFNGLUNIFORM2UIPROC glUniform2ui; -extern PFNGLUNIFORM3UIPROC glUniform3ui; -extern PFNGLUNIFORM4UIPROC glUniform4ui; -extern PFNGLUNIFORM1UIVPROC glUniform1uiv; -extern PFNGLUNIFORM2UIVPROC glUniform2uiv; -extern PFNGLUNIFORM3UIVPROC glUniform3uiv; -extern PFNGLUNIFORM4UIVPROC glUniform4uiv; -extern PFNGLCLEARBUFFERIVPROC glClearBufferiv; -extern PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; -extern PFNGLCLEARBUFFERFVPROC glClearBufferfv; -extern PFNGLCLEARBUFFERFIPROC glClearBufferfi; -extern PFNGLGETSTRINGIPROC glGetStringi; -extern PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; -extern PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; -extern PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; -extern PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; -extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; -extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; -extern PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; -extern PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; -extern PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; -extern PFNGLFENCESYNCPROC glFenceSync; -extern PFNGLISSYNCPROC glIsSync; -extern PFNGLDELETESYNCPROC glDeleteSync; -extern PFNGLCLIENTWAITSYNCPROC glClientWaitSync; -extern PFNGLWAITSYNCPROC glWaitSync; -extern PFNGLGETINTEGER64VPROC glGetInteger64v; -extern PFNGLGETSYNCIVPROC glGetSynciv; -extern PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; // NOLINT(readability-identifier-naming) -extern PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; -extern PFNGLGENSAMPLERSPROC glGenSamplers; -extern PFNGLDELETESAMPLERSPROC glDeleteSamplers; -extern PFNGLISSAMPLERPROC glIsSampler; -extern PFNGLBINDSAMPLERPROC glBindSampler; -extern PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; -extern PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; -extern PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; -extern PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; -extern PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; -extern PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; -extern PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; -extern PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; -extern PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; -extern PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; -extern PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; -extern PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; -extern PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; -extern PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; -extern PFNGLPROGRAMBINARYPROC glProgramBinary; -extern PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; -extern PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; -extern PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; -extern PFNGLTEXSTORAGE2DPROC glTexStorage2D; -extern PFNGLTEXSTORAGE3DPROC glTexStorage3D; -extern PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; +extern PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; +extern PFNGLMAPBUFFERRANGEPROC glMapBufferRange; +extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; +extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray; +extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; +extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; +extern PFNGLISVERTEXARRAYPROC glIsVertexArray; +extern PFNGLGETINTEGERI_VPROC glGetIntegeri_v; // NOLINT(readability-identifier-naming) +extern PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; +extern PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; +extern PFNGLBINDBUFFERRANGEPROC glBindBufferRange; +extern PFNGLBINDBUFFERBASEPROC glBindBufferBase; +extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; +extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; +extern PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; +extern PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; +extern PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; +extern PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; +extern PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; +extern PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; +extern PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; +extern PFNGLGETUNIFORMUIVPROC glGetUniformuiv; +extern PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; +extern PFNGLUNIFORM1UIPROC glUniform1ui; +extern PFNGLUNIFORM2UIPROC glUniform2ui; +extern PFNGLUNIFORM3UIPROC glUniform3ui; +extern PFNGLUNIFORM4UIPROC glUniform4ui; +extern PFNGLUNIFORM1UIVPROC glUniform1uiv; +extern PFNGLUNIFORM2UIVPROC glUniform2uiv; +extern PFNGLUNIFORM3UIVPROC glUniform3uiv; +extern PFNGLUNIFORM4UIVPROC glUniform4uiv; +extern PFNGLCLEARBUFFERIVPROC glClearBufferiv; +extern PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; +extern PFNGLCLEARBUFFERFVPROC glClearBufferfv; +extern PFNGLCLEARBUFFERFIPROC glClearBufferfi; +extern PFNGLGETSTRINGIPROC glGetStringi; +extern PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; +extern PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; +extern PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; +extern PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; +extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; +extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; +extern PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; +extern PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; +extern PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; +extern PFNGLFENCESYNCPROC glFenceSync; +extern PFNGLISSYNCPROC glIsSync; +extern PFNGLDELETESYNCPROC glDeleteSync; +extern PFNGLCLIENTWAITSYNCPROC glClientWaitSync; +extern PFNGLWAITSYNCPROC glWaitSync; +extern PFNGLGETINTEGER64VPROC glGetInteger64v; +extern PFNGLGETSYNCIVPROC glGetSynciv; +extern PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; // NOLINT(readability-identifier-naming) +extern PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; +extern PFNGLGENSAMPLERSPROC glGenSamplers; +extern PFNGLDELETESAMPLERSPROC glDeleteSamplers; +extern PFNGLISSAMPLERPROC glIsSampler; +extern PFNGLBINDSAMPLERPROC glBindSampler; +extern PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; +extern PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; +extern PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; +extern PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; +extern PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; +extern PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; +extern PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; +extern PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; +extern PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; +extern PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; +extern PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; +extern PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; +extern PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; +extern PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; +extern PFNGLPROGRAMBINARYPROC glProgramBinary; +extern PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; +extern PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; +extern PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; +extern PFNGLTEXSTORAGE2DPROC glTexStorage2D; +extern PFNGLTEXSTORAGE3DPROC glTexStorage3D; +extern PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; /* GL_ES_VERSION_3_1 */ -extern PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; +extern PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; extern PFNGLDISPATCHCOMPUTEINDIRECTPROC glDispatchComputeIndirect; -extern PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; +extern PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; extern PFNGLDRAWELEMENTSINDIRECTPROC glDrawElementsIndirect; -extern PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; +extern PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; extern PFNGLGETFRAMEBUFFERPARAMETERIVPROC glGetFramebufferParameteriv; -extern PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; -extern PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; -extern PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; -extern PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; +extern PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; +extern PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; +extern PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; +extern PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; extern PFNGLGETPROGRAMRESOURCELOCATIONPROC glGetProgramResourceLocation; -extern PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; -extern PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; -extern PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; -extern PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; -extern PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; -extern PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; -extern PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; -extern PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; -extern PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; -extern PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; -extern PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; -extern PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; -extern PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; -extern PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; -extern PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; -extern PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; -extern PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; -extern PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; -extern PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; -extern PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; -extern PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; -extern PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; -extern PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; -extern PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; -extern PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; -extern PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; -extern PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; -extern PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; -extern PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; -extern PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; -extern PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; -extern PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; -extern PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; -extern PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; -extern PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; +extern PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; +extern PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; +extern PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; +extern PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; +extern PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; +extern PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; +extern PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; +extern PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; +extern PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; +extern PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; +extern PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; +extern PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; +extern PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; +extern PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; +extern PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; +extern PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; +extern PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; +extern PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; +extern PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; +extern PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; +extern PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; +extern PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; +extern PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; +extern PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; +extern PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; +extern PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; +extern PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; +extern PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; +extern PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; +extern PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; +extern PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; +extern PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; +extern PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; +extern PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; +extern PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; extern PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glProgramUniformMatrix2x3fv; extern PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glProgramUniformMatrix3x2fv; extern PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glProgramUniformMatrix2x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glProgramUniformMatrix4x2fv; extern PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glProgramUniformMatrix3x4fv; extern PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glProgramUniformMatrix4x3fv; -extern PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; +extern PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; extern PFNGLGETPROGRAMPIPELINEINFOLOGPROC glGetProgramPipelineInfoLog; -extern PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; -extern PFNGLGETBOOLEANI_VPROC glGetBooleani_v; // NOLINT(readability-identifier-naming) -extern PFNGLMEMORYBARRIERPROC glMemoryBarrier; +extern PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; +extern PFNGLGETBOOLEANI_VPROC glGetBooleani_v; // NOLINT(readability-identifier-naming) +extern PFNGLMEMORYBARRIERPROC glMemoryBarrier; extern PFNGLMEMORYBARRIERBYREGIONPROC glMemoryBarrierByRegion; extern PFNGLTEXSTORAGE2DMULTISAMPLEPROC glTexStorage2DMultisample; -extern PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; -extern PFNGLSAMPLEMASKIPROC glSampleMaski; -extern PFNGLGETTEXLEVELPARAMETERIVPROC glGetTexLevelParameteriv; -extern PFNGLGETTEXLEVELPARAMETERFVPROC glGetTexLevelParameterfv; +extern PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; +extern PFNGLSAMPLEMASKIPROC glSampleMaski; +extern PFNGLGETTEXLEVELPARAMETERIVPROC glGetTexLevelParameteriv; +extern PFNGLGETTEXLEVELPARAMETERFVPROC glGetTexLevelParameterfv; -extern PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; -extern PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; -extern PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; -extern PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; +extern PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; +extern PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; +extern PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; +extern PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; extern PFNGLVERTEXBINDINGDIVISORPROC glVertexBindingDivisor; /* GL_ES_VERSION_3_2 */ @@ -224,29 +224,29 @@ extern PFNGLBLENDBARRIERPROC glBlendBarrier; extern PFNGLCOPYIMAGESUBDATAPROC glCopyImageSubData; -extern PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; -extern PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; +extern PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; +extern PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; extern PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback; -extern PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; -extern PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; -extern PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; -extern PFNGLOBJECTLABELPROC glObjectLabel; -extern PFNGLGETOBJECTLABELPROC glGetObjectLabel; -extern PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; -extern PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; -extern PFNGLGETPOINTERVPROC glGetPointerv; +extern PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; +extern PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; +extern PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; +extern PFNGLOBJECTLABELPROC glObjectLabel; +extern PFNGLGETOBJECTLABELPROC glGetObjectLabel; +extern PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; +extern PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; +extern PFNGLGETPOINTERVPROC glGetPointerv; -extern PFNGLENABLEIPROC glEnablei; -extern PFNGLDISABLEIPROC glDisablei; -extern PFNGLBLENDEQUATIONIPROC glBlendEquationi; +extern PFNGLENABLEIPROC glEnablei; +extern PFNGLDISABLEIPROC glDisablei; +extern PFNGLBLENDEQUATIONIPROC glBlendEquationi; extern PFNGLBLENDEQUATIONSEPARATEIPROC glBlendEquationSeparatei; -extern PFNGLBLENDFUNCIPROC glBlendFunci; -extern PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; -extern PFNGLCOLORMASKIPROC glColorMaski; -extern PFNGLISENABLEDIPROC glIsEnabledi; +extern PFNGLBLENDFUNCIPROC glBlendFunci; +extern PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; +extern PFNGLCOLORMASKIPROC glColorMaski; +extern PFNGLISENABLEDIPROC glIsEnabledi; -extern PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; +extern PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; +extern PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glDrawElementsInstancedBaseVertex; extern PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; @@ -254,25 +254,25 @@ extern PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; extern PFNGLPRIMITIVEBOUNDINGBOXPROC glPrimitiveBoundingBox; extern PFNGLGETGRAPHICSRESETSTATUSPROC glGetGraphicsResetStatus; -extern PFNGLREADNPIXELSPROC glReadnPixels; -extern PFNGLGETNUNIFORMFVPROC glGetnUniformfv; -extern PFNGLGETNUNIFORMIVPROC glGetnUniformiv; -extern PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; +extern PFNGLREADNPIXELSPROC glReadnPixels; +extern PFNGLGETNUNIFORMFVPROC glGetnUniformfv; +extern PFNGLGETNUNIFORMIVPROC glGetnUniformiv; +extern PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; extern PFNGLMINSAMPLESHADINGPROC glMinSampleShading; extern PFNGLPATCHPARAMETERIPROC glPatchParameteri; -extern PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; -extern PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; -extern PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; -extern PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; -extern PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; -extern PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; -extern PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; +extern PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; +extern PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; +extern PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; +extern PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; +extern PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; +extern PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; +extern PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; extern PFNGLGETSAMPLERPARAMETERIUIVPROC glGetSamplerParameterIuiv; -extern PFNGLTEXBUFFERPROC glTexBuffer; +extern PFNGLTEXBUFFERPROC glTexBuffer; extern PFNGLTEXBUFFERRANGEPROC glTexBufferRange; extern PFNGLTEXSTORAGE3DMULTISAMPLEPROC glTexStorage3DMultisample; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Buffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2Buffer.cpp index 8d784f35d5..6deded086e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Buffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Buffer.cpp @@ -42,12 +42,12 @@ GLES2Buffer::~GLES2Buffer() { } void GLES2Buffer::doInit(const BufferInfo & /*info*/) { - _gpuBuffer = ccnew GLES2GPUBuffer; - _gpuBuffer->usage = _usage; + _gpuBuffer = ccnew GLES2GPUBuffer; + _gpuBuffer->usage = _usage; _gpuBuffer->memUsage = _memUsage; - _gpuBuffer->size = _size; - _gpuBuffer->stride = _stride; - _gpuBuffer->count = _count; + _gpuBuffer->size = _size; + _gpuBuffer->stride = _stride; + _gpuBuffer->count = _count; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { _gpuBuffer->indirects.resize(_count); @@ -59,11 +59,11 @@ void GLES2Buffer::doInit(const BufferInfo & /*info*/) { } void GLES2Buffer::doInit(const BufferViewInfo &info) { - auto *buffer = static_cast(info.buffer); - _gpuBufferView = ccnew GLES2GPUBufferView; + auto *buffer = static_cast(info.buffer); + _gpuBufferView = ccnew GLES2GPUBufferView; _gpuBufferView->gpuBuffer = buffer->gpuBuffer(); - _gpuBufferView->range = _size; - _gpuBufferView->offset = info.offset; + _gpuBufferView->range = _size; + _gpuBufferView->offset = info.offset; } void GLES2Buffer::doDestroy() { @@ -81,7 +81,7 @@ void GLES2Buffer::doDestroy() { void GLES2Buffer::doResize(uint32_t size, uint32_t count) { GLES2Device::getInstance()->getMemoryStatus().bufferSize -= _size; CC_PROFILE_MEMORY_DEC(Buffer, _size); - _gpuBuffer->size = size; + _gpuBuffer->size = size; _gpuBuffer->count = count; cmdFuncGLES2ResizeBuffer(GLES2Device::getInstance(), _gpuBuffer); GLES2Device::getInstance()->getMemoryStatus().bufferSize += size; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Buffer.h b/native/cocos/renderer/gfx-gles2/GLES2Buffer.h index e3046d5695..2f8466a614 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Buffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Buffer.h @@ -41,7 +41,7 @@ public: void update(const void *buffer, uint32_t size) override; - inline GLES2GPUBuffer * gpuBuffer() const { return _gpuBuffer; } + inline GLES2GPUBuffer *gpuBuffer() const { return _gpuBuffer; } inline GLES2GPUBufferView *gpuBufferView() const { return _gpuBufferView; } protected: @@ -50,7 +50,7 @@ protected: void doDestroy() override; void doResize(uint32_t size, uint32_t count) override; - GLES2GPUBuffer * _gpuBuffer = nullptr; + GLES2GPUBuffer *_gpuBuffer = nullptr; GLES2GPUBufferView *_gpuBufferView = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp index a293d11a8f..025586f7a4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.cpp @@ -49,10 +49,10 @@ GLES2CommandBuffer::~GLES2CommandBuffer() { } void GLES2CommandBuffer::doInit(const CommandBufferInfo &info) { - _type = info.type; + _type = info.type; _queue = info.queue; - _cmdAllocator = ccnew GLES2GPUCommandAllocator; + _cmdAllocator = ccnew GLES2GPUCommandAllocator; _curCmdPackage = ccnew GLES2CmdPackage; size_t setCount = GLES2Device::getInstance()->bindingMappingInfo().setIndices.size(); @@ -113,18 +113,18 @@ void GLES2CommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb _curSubpassIdx = 0U; GLES2CmdBeginRenderPass *cmd = _cmdAllocator->beginRenderPassCmdPool.alloc(); - cmd->subpassIdx = _curSubpassIdx; - cmd->gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); - cmd->gpuFBO = static_cast(fbo)->gpuFBO(); - cmd->renderArea = renderArea; - size_t numClearColors = cmd->gpuRenderPass->colorAttachments.size(); + cmd->subpassIdx = _curSubpassIdx; + cmd->gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); + cmd->gpuFBO = static_cast(fbo)->gpuFBO(); + cmd->renderArea = renderArea; + size_t numClearColors = cmd->gpuRenderPass->colorAttachments.size(); memcpy(cmd->clearColors, colors, numClearColors * sizeof(Color)); - cmd->clearDepth = depth; + cmd->clearDepth = depth; cmd->clearStencil = stencil; _curCmdPackage->beginRenderPassCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); _curDynamicStates.viewport = {renderArea.x, renderArea.y, renderArea.width, renderArea.height}; - _curDynamicStates.scissor = renderArea; + _curDynamicStates.scissor = renderArea; } void GLES2CommandBuffer::endRenderPass() { @@ -134,7 +134,7 @@ void GLES2CommandBuffer::endRenderPass() { void GLES2CommandBuffer::nextSubpass() { _curCmdPackage->cmds.push(GLESCmdType::END_RENDER_PASS); GLES2CmdBeginRenderPass *cmd = _cmdAllocator->beginRenderPassCmdPool.alloc(); - cmd->subpassIdx = ++_curSubpassIdx; + cmd->subpassIdx = ++_curSubpassIdx; _curCmdPackage->beginRenderPassCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); } @@ -143,7 +143,7 @@ void GLES2CommandBuffer::bindPipelineState(PipelineState *pso) { GLES2GPUPipelineState *gpuPipelineState = static_cast(pso)->gpuPipelineState(); if (_curGPUPipelineState != gpuPipelineState) { _curGPUPipelineState = gpuPipelineState; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -153,7 +153,7 @@ void GLES2CommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descript GLES2GPUDescriptorSet *gpuDescriptorSet = static_cast(descriptorSet)->gpuDescriptorSet(); if (_curGPUDescriptorSets[set] != gpuDescriptorSet) { _curGPUDescriptorSets[set] = gpuDescriptorSet; - _isStateInvalid = true; + _isStateInvalid = true; } if (dynamicOffsetCount) { _curDynamicOffsets[set].assign(dynamicOffsets, dynamicOffsets + dynamicOffsetCount); @@ -166,7 +166,7 @@ void GLES2CommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descript void GLES2CommandBuffer::bindInputAssembler(InputAssembler *ia) { _curGPUInputAssember = static_cast(ia)->gpuInputAssembler(); - _isStateInvalid = true; + _isStateInvalid = true; } void GLES2CommandBuffer::setViewport(const Viewport &vp) { @@ -177,7 +177,7 @@ void GLES2CommandBuffer::setViewport(const Viewport &vp) { math::IsNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || math::IsNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { _curDynamicStates.viewport = vp; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -187,14 +187,14 @@ void GLES2CommandBuffer::setScissor(const Rect &rect) { (_curDynamicStates.scissor.width != rect.width) || (_curDynamicStates.scissor.height != rect.height)) { _curDynamicStates.scissor = rect; - _isStateInvalid = true; + _isStateInvalid = true; } } void GLES2CommandBuffer::setLineWidth(float width) { if (math::IsNotEqualF(_curDynamicStates.lineWidth, width)) { _curDynamicStates.lineWidth = width; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -203,9 +203,9 @@ void GLES2CommandBuffer::setDepthBias(float constant, float clamp, float slope) math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; - _curDynamicStates.depthBiasClamp = clamp; - _curDynamicStates.depthBiasSlope = slope; - _isStateInvalid = true; + _curDynamicStates.depthBiasClamp = clamp; + _curDynamicStates.depthBiasSlope = slope; + _isStateInvalid = true; } } @@ -218,7 +218,7 @@ void GLES2CommandBuffer::setBlendConstants(const Color &constants) { _curDynamicStates.blendConstant.y = constants.y; _curDynamicStates.blendConstant.z = constants.z; _curDynamicStates.blendConstant.w = constants.w; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -227,7 +227,7 @@ void GLES2CommandBuffer::setDepthBound(float minBounds, float maxBounds) { math::IsNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { _curDynamicStates.depthMinBounds = minBounds; _curDynamicStates.depthMaxBounds = maxBounds; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -235,7 +235,7 @@ void GLES2CommandBuffer::setStencilWriteMask(StencilFace face, uint32_t mask) { auto update = [&](DynamicStencilStates &stencilState) { if (stencilState.writeMask != mask) { stencilState.writeMask = mask; - _isStateInvalid = true; + _isStateInvalid = true; } }; if (hasFlag(face, StencilFace::FRONT)) update(_curDynamicStates.stencilStatesFront); @@ -246,9 +246,9 @@ void GLES2CommandBuffer::setStencilCompareMask(StencilFace face, uint32_t ref, u auto update = [&](DynamicStencilStates &stencilState) { if ((stencilState.reference != ref) || (stencilState.compareMask != mask)) { - stencilState.reference = ref; + stencilState.reference = ref; stencilState.compareMask = mask; - _isStateInvalid = true; + _isStateInvalid = true; } }; if (hasFlag(face, StencilFace::FRONT)) update(_curDynamicStates.stencilStatesFront); @@ -262,7 +262,7 @@ void GLES2CommandBuffer::draw(const DrawInfo &info) { } GLES2CmdDraw *cmd = _cmdAllocator->drawCmdPool.alloc(); - cmd->drawInfo = info; + cmd->drawInfo = info; _curCmdPackage->drawCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::DRAW); @@ -290,9 +290,9 @@ void GLES2CommandBuffer::updateBuffer(Buffer *buff, const void *data, uint32_t s GLES2GPUBuffer *gpuBuffer = static_cast(buff)->gpuBuffer(); if (gpuBuffer) { GLES2CmdUpdateBuffer *cmd = _cmdAllocator->updateBufferCmdPool.alloc(); - cmd->gpuBuffer = gpuBuffer; - cmd->size = size; - cmd->buffer = static_cast(data); + cmd->gpuBuffer = gpuBuffer; + cmd->size = size; + cmd->buffer = static_cast(data); _curCmdPackage->updateBufferCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::UPDATE_BUFFER); @@ -303,10 +303,10 @@ void GLES2CommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex GLES2GPUTexture *gpuTexture = static_cast(texture)->gpuTexture(); if (gpuTexture) { GLES2CmdCopyBufferToTexture *cmd = _cmdAllocator->copyBufferToTextureCmdPool.alloc(); - cmd->gpuTexture = gpuTexture; - cmd->regions = regions; - cmd->count = count; - cmd->buffers = buffers; + cmd->gpuTexture = gpuTexture; + cmd->regions = regions; + cmd->count = count; + cmd->buffers = buffers; _curCmdPackage->copyBufferToTextureCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::COPY_BUFFER_TO_TEXTURE); @@ -318,8 +318,8 @@ void GLES2CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); if (dstTexture) cmd->gpuTextureDst = static_cast(dstTexture)->gpuTexture(); cmd->regions = regions; - cmd->count = count; - cmd->filter = filter; + cmd->count = count; + cmd->filter = filter; _curCmdPackage->blitTextureCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BLIT_TEXTURE); @@ -329,7 +329,7 @@ void GLES2CommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) CC_ASSERT(false); // Command 'execute' must be recorded in primary command buffers. for (uint32_t i = 0; i < count; ++i) { - auto * cmdBuff = static_cast(cmdBuffs[i]); + auto *cmdBuff = static_cast(cmdBuffs[i]); GLES2CmdPackage *cmdPackage = cmdBuff->_pendingPackages.front(); for (uint32_t j = 0; j < cmdPackage->beginRenderPassCmds.size(); ++j) { @@ -381,7 +381,7 @@ void GLES2CommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) void GLES2CommandBuffer::bindStates() { GLES2CmdBindStates *cmd = _cmdAllocator->bindStatesCmdPool.alloc(); - cmd->gpuPipelineState = _curGPUPipelineState; + cmd->gpuPipelineState = _curGPUPipelineState; cmd->gpuInputAssembler = _curGPUInputAssember; cmd->gpuDescriptorSets = _curGPUDescriptorSets; diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index 8831b9ab30..a25a80167e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -78,16 +78,16 @@ protected: virtual void bindStates(); - GLES2GPUCommandAllocator * _cmdAllocator = nullptr; - GLES2CmdPackage * _curCmdPackage = nullptr; + GLES2GPUCommandAllocator *_cmdAllocator = nullptr; + GLES2CmdPackage *_curCmdPackage = nullptr; ccstd::queue _pendingPackages, _freePackages; - uint32_t _curSubpassIdx = 0U; - GLES2GPUPipelineState * _curGPUPipelineState = nullptr; + uint32_t _curSubpassIdx = 0U; + GLES2GPUPipelineState *_curGPUPipelineState = nullptr; ccstd::vector _curGPUDescriptorSets; ccstd::vector> _curDynamicOffsets; - GLES2GPUInputAssembler * _curGPUInputAssember = nullptr; - DynamicStates _curDynamicStates; + GLES2GPUInputAssembler *_curGPUInputAssember = nullptr; + DynamicStates _curDynamicStates; bool _isStateInvalid = false; }; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index 1a6fda0cfe..09ded8fc9e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -423,7 +423,7 @@ const GLenum GLES2_BLEND_FACTORS[] = { void cmdFuncGLES2CreateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { GLES2ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; - GLenum glUsage = (hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); + GLenum glUsage = (hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (hasFlag(gpuBuffer->usage, BufferUsageBit::VERTEX)) { gpuBuffer->glTarget = GL_ARRAY_BUFFER; @@ -470,7 +470,7 @@ void cmdFuncGLES2CreateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { } else if ((hasFlag(gpuBuffer->usage, BufferUsageBit::UNIFORM)) || (hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_DST)) || (hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_SRC))) { - gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); + gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); gpuBuffer->glTarget = GL_NONE; } else { CC_ASSERT(false); @@ -514,7 +514,7 @@ void cmdFuncGLES2DestroyBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { GLES2ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; - GLenum glUsage = (hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); + GLenum glUsage = (hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (hasFlag(gpuBuffer->usage, BufferUsageBit::VERTEX)) { gpuBuffer->glTarget = GL_ARRAY_BUFFER; @@ -563,7 +563,7 @@ void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { if (gpuBuffer->buffer) { CC_FREE(gpuBuffer->buffer); } - gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); + gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); gpuBuffer->glTarget = GL_NONE; } else { CC_ASSERT(false); @@ -572,8 +572,8 @@ void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { } void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - gpuTexture->glFormat = mapGLFormat(gpuTexture->format); - gpuTexture->glType = formatToGLType(gpuTexture->format); + gpuTexture->glFormat = mapGLFormat(gpuTexture->format); + gpuTexture->glType = formatToGLType(gpuTexture->format); gpuTexture->glInternalFmt = gpuTexture->glFormat; if (gpuTexture->samples > SampleCount::ONE) { @@ -582,7 +582,7 @@ void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); auto requestedSampleCount = static_cast(gpuTexture->samples); - gpuTexture->glSamples = std::min(maxSamples, requestedSampleCount); + gpuTexture->glSamples = std::min(maxSamples, requestedSampleCount); // skip multi-sampled attachment resources if we can use auto resolve if (gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { @@ -858,21 +858,21 @@ void cmdFuncGLES2DestroySampler(GLES2Device *device, GLES2GPUSampler *gpuSampler } void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { - GLenum glShaderType = 0; + GLenum glShaderType = 0; ccstd::string shaderTypeStr; - GLint status; + GLint status; for (size_t i = 0; i < gpuShader->gpuStages.size(); ++i) { GLES2GPUShaderStage &gpuStage = gpuShader->gpuStages[i]; switch (gpuStage.type) { case ShaderStageFlagBit::VERTEX: { - glShaderType = GL_VERTEX_SHADER; + glShaderType = GL_VERTEX_SHADER; shaderTypeStr = "Vertex Shader"; break; } case ShaderStageFlagBit::FRAGMENT: { - glShaderType = GL_FRAGMENT_SHADER; + glShaderType = GL_FRAGMENT_SHADER; shaderTypeStr = "Fragment Shader"; break; } @@ -944,14 +944,14 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { CC_LOG_INFO("Shader '%s' compilation succeeded.", gpuShader->name.c_str()); GLint attrMaxLength = 0; - GLint attrCount = 0; + GLint attrCount = 0; GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &attrMaxLength)); GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_ACTIVE_ATTRIBUTES, &attrCount)); - GLchar glName[256]; + GLchar glName[256]; GLsizei glLength; GLsizei glSize; - GLenum glType; + GLenum glType; gpuShader->glInputs.resize(attrCount); for (GLint i = 0; i < attrCount; ++i) { @@ -964,14 +964,14 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { glName[offset - glName] = '\0'; } - gpuInput.glLoc = glGetAttribLocation(gpuShader->glProgram, glName); + gpuInput.glLoc = glGetAttribLocation(gpuShader->glProgram, glName); gpuInput.binding = gpuInput.glLoc; - gpuInput.name = glName; - gpuInput.type = mapType(glType); - gpuInput.stride = glTypeSize(glType); - gpuInput.count = glSize; - gpuInput.size = gpuInput.stride * gpuInput.count; - gpuInput.glType = glType; + gpuInput.name = glName; + gpuInput.type = mapType(glType); + gpuInput.stride = glTypeSize(glType); + gpuInput.count = glSize; + gpuInput.size = gpuInput.stride * gpuInput.count; + gpuInput.glType = glType; } // create uniform blocks @@ -980,25 +980,25 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { for (size_t i = 0; i < gpuShader->glBlocks.size(); ++i) { GLES2GPUUniformBlock &gpuBlock = gpuShader->glBlocks[i]; - UniformBlock & block = gpuShader->blocks[i]; + UniformBlock &block = gpuShader->blocks[i]; - gpuBlock.name = block.name; - gpuBlock.set = block.set; + gpuBlock.name = block.name; + gpuBlock.set = block.set; gpuBlock.binding = block.binding; gpuBlock.glUniforms.resize(block.members.size()); for (size_t j = 0; j < gpuBlock.glUniforms.size(); ++j) { GLES2GPUUniform &gpuUniform = gpuBlock.glUniforms[j]; - Uniform & uniform = block.members[j]; + Uniform &uniform = block.members[j]; gpuUniform.binding = INVALID_BINDING; - gpuUniform.name = uniform.name; - gpuUniform.type = uniform.type; - gpuUniform.stride = getTypeSize(uniform.type); - gpuUniform.count = uniform.count; - gpuUniform.size = gpuUniform.stride * gpuUniform.count; - gpuUniform.glType = mapGLType(gpuUniform.type); - gpuUniform.glLoc = -1; + gpuUniform.name = uniform.name; + gpuUniform.type = uniform.type; + gpuUniform.stride = getTypeSize(uniform.type); + gpuUniform.count = uniform.count; + gpuUniform.size = gpuUniform.stride * gpuUniform.count; + gpuUniform.glType = mapGLType(gpuUniform.type); + gpuUniform.glLoc = -1; } } } // if @@ -1007,12 +1007,12 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { gpuShader->samplerTextures.emplace_back(); - auto &samplerTexture = gpuShader->samplerTextures.back(); - samplerTexture.name = subpassInput.name; - samplerTexture.set = subpassInput.set; + auto &samplerTexture = gpuShader->samplerTextures.back(); + samplerTexture.name = subpassInput.name; + samplerTexture.set = subpassInput.set; samplerTexture.binding = subpassInput.binding; - samplerTexture.count = subpassInput.count; - samplerTexture.type = Type::SAMPLER2D; + samplerTexture.count = subpassInput.count; + samplerTexture.type = Type::SAMPLER2D; } } @@ -1021,14 +1021,14 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { gpuShader->glSamplerTextures.resize(gpuShader->samplerTextures.size()); for (size_t i = 0; i < gpuShader->glSamplerTextures.size(); ++i) { - UniformSamplerTexture & samplerTexture = gpuShader->samplerTextures[i]; + UniformSamplerTexture &samplerTexture = gpuShader->samplerTextures[i]; GLES2GPUUniformSamplerTexture &gpuSamplerTexture = gpuShader->glSamplerTextures[i]; - gpuSamplerTexture.set = samplerTexture.set; - gpuSamplerTexture.binding = samplerTexture.binding; - gpuSamplerTexture.name = samplerTexture.name; - gpuSamplerTexture.count = samplerTexture.count; - gpuSamplerTexture.glType = mapGLType(samplerTexture.type); - gpuSamplerTexture.glLoc = -1; + gpuSamplerTexture.set = samplerTexture.set; + gpuSamplerTexture.binding = samplerTexture.binding; + gpuSamplerTexture.name = samplerTexture.name; + gpuSamplerTexture.count = samplerTexture.count; + gpuSamplerTexture.glType = mapGLType(samplerTexture.type); + gpuSamplerTexture.glLoc = -1; } } @@ -1059,7 +1059,7 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { if (glUniform.name == name) { glUniform.glLoc = glGetUniformLocation(gpuShader->glProgram, glName); glUniform.count = glSize; - glUniform.size = glUniform.stride * glUniform.count; + glUniform.size = glUniform.stride * glUniform.count; glBlock.glActiveUniforms.emplace_back(glUniform); auto &activeUniform = glBlock.glActiveUniforms.back(); @@ -1081,16 +1081,16 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { gpuBlock.size += gpuUniform.size; } for (uint32_t i = 0; i < gpuBlock.glActiveUniforms.size(); ++i) { - auto & activeUniform = gpuBlock.glActiveUniforms[i]; - uint32_t index = gpuBlock.activeUniformIndices[i]; - activeUniform.offset = gpuBlock.glUniforms[index].offset; + auto &activeUniform = gpuBlock.glActiveUniforms[i]; + uint32_t index = gpuBlock.activeUniformIndices[i]; + activeUniform.offset = gpuBlock.glUniforms[index].offset; } } // texture unit index mapping optimization - ccstd::vector glActiveSamplerTextures; - ccstd::vector glActiveSamplerLocations; - const GLESBindingMapping & bindingMappings = device->bindingMappings(); + ccstd::vector glActiveSamplerTextures; + ccstd::vector glActiveSamplerLocations; + const GLESBindingMapping &bindingMappings = device->bindingMappings(); ccstd::unordered_map &texUnitCacheMap = device->stateCache()->texUnitCacheMap; // sampler bindings in the flexible set comes strictly after buffer bindings @@ -1106,7 +1106,7 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { for (uint32_t i = 0U; i < gpuShader->samplerTextures.size(); i++) { const UniformSamplerTexture &samplerTexture = gpuShader->samplerTextures[i]; - GLint glLoc = glGetUniformLocation(gpuShader->glProgram, samplerTexture.name.c_str()); + GLint glLoc = glGetUniformLocation(gpuShader->glProgram, samplerTexture.name.c_str()); if (glLoc >= 0) { glActiveSamplerTextures.push_back(gpuShader->glSamplerTextures[i]); glActiveSamplerLocations.push_back(glLoc); @@ -1126,7 +1126,7 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { GLES2GPUUniformSamplerTexture &glSamplerTexture = glActiveSamplerTextures[i]; if (texUnitCacheMap.count(glSamplerTexture.name)) { - uint32_t cachedUnit = texUnitCacheMap[glSamplerTexture.name]; + uint32_t cachedUnit = texUnitCacheMap[glSamplerTexture.name]; glSamplerTexture.glLoc = glActiveSamplerLocations[i]; for (uint32_t t = 0U; t < glSamplerTexture.count; t++) { while (usedTexUnits[cachedUnit]) { // the shader already compiles so we should be safe to do this here @@ -1188,7 +1188,7 @@ void cmdFuncGLES2DestroyShader(GLES2Device *device, GLES2GPUShader *gpuShader) { if (device->stateCache()->glProgram == gpuShader->glProgram) { GL_CHECK(glUseProgram(0)); device->stateCache()->glProgram = 0; - gfxStateCache.gpuPipelineState = nullptr; + gfxStateCache.gpuPipelineState = nullptr; } GL_CHECK(glDeleteProgram(gpuShader->glProgram)); gpuShader->glProgram = 0; @@ -1256,22 +1256,22 @@ void cmdFuncGLES2CreateInputAssembler(GLES2Device *device, GLES2GPUInputAssemble gpuInputAssembler->glAttribs.resize(gpuInputAssembler->attributes.size()); for (size_t i = 0; i < gpuInputAssembler->glAttribs.size(); ++i) { GLES2GPUAttribute &gpuAttribute = gpuInputAssembler->glAttribs[i]; - const Attribute & attrib = gpuInputAssembler->attributes[i]; + const Attribute &attrib = gpuInputAssembler->attributes[i]; auto *gpuVB = static_cast(gpuInputAssembler->gpuVertexBuffers[attrib.stream]); - gpuAttribute.name = attrib.name; - gpuAttribute.glType = formatToGLType(attrib.format); - gpuAttribute.size = GFX_FORMAT_INFOS[static_cast(attrib.format)].size; - gpuAttribute.count = GFX_FORMAT_INFOS[static_cast(attrib.format)].count; + gpuAttribute.name = attrib.name; + gpuAttribute.glType = formatToGLType(attrib.format); + gpuAttribute.size = GFX_FORMAT_INFOS[static_cast(attrib.format)].size; + gpuAttribute.count = GFX_FORMAT_INFOS[static_cast(attrib.format)].count; gpuAttribute.componentCount = glComponentCount(gpuAttribute.glType); - gpuAttribute.isNormalized = attrib.isNormalized; - gpuAttribute.isInstanced = attrib.isInstanced; - gpuAttribute.offset = streamOffsets[attrib.stream]; + gpuAttribute.isNormalized = attrib.isNormalized; + gpuAttribute.isInstanced = attrib.isInstanced; + gpuAttribute.offset = streamOffsets[attrib.stream]; if (gpuVB) { gpuAttribute.glBuffer = gpuVB->glBuffer; - gpuAttribute.stride = gpuVB->stride; + gpuAttribute.stride = gpuVB->stride; } streamOffsets[attrib.stream] += gpuAttribute.size; } @@ -1282,7 +1282,7 @@ void cmdFuncGLES2DestroyInputAssembler(GLES2Device *device, GLES2GPUInputAssembl for (auto it = gpuInputAssembler->glVAOs.begin(); it != gpuInputAssembler->glVAOs.end(); ++it) { if (device->stateCache()->glVAO == it->second) { GL_CHECK(glBindVertexArrayOES(0)); - device->stateCache()->glVAO = 0; + device->stateCache()->glVAO = 0; gfxStateCache.gpuInputAssembler = nullptr; } GL_CHECK(glDeleteVertexArraysOES(1, &it->second)); @@ -1290,14 +1290,14 @@ void cmdFuncGLES2DestroyInputAssembler(GLES2Device *device, GLES2GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -static GLES2GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES2Device * device, +static GLES2GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES2Device *device, const ccstd::vector &attachments, const uint32_t *colors, size_t colorCount, const GLES2GPUTexture *depthStencil, - const uint32_t * resolves = nullptr, + const uint32_t *resolves = nullptr, const GLES2GPUTexture *depthStencilResolve = nullptr, - GLbitfield * resolveMask = nullptr) { - static ccstd::vector drawBuffers; - GLES2GPUStateCache * cache = device->stateCache(); + GLbitfield *resolveMask = nullptr) { + static ccstd::vector drawBuffers; + GLES2GPUStateCache *cache = device->stateCache(); GLES2GPUFramebuffer::GLFramebufferInfo res; GL_CHECK(glGenFramebuffers(1, &res.glFramebuffer)); @@ -1309,10 +1309,10 @@ static GLES2GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES2Device * drawBuffers.clear(); auto supportLevel = device->constantRegistry()->mMSRT; - bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); + bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); for (size_t j = 0; j < colorCount; ++j) { - GLES2GPUTexture *gpuColorTexture = attachments[colors[j]]; + GLES2GPUTexture *gpuColorTexture = attachments[colors[j]]; GLES2GPUTexture *gpuResolveTexture = resolves ? attachments[resolves[j]] : nullptr; drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); @@ -1332,7 +1332,7 @@ static GLES2GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES2Device * GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); } - res.width = std::min(res.width, gpuColorTexture->width); + res.width = std::min(res.width, gpuColorTexture->width); res.height = std::min(res.height, gpuColorTexture->height); } if (depthStencil) { @@ -1347,7 +1347,7 @@ static GLES2GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES2Device * // fallback to blit-based manual resolve if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; - res.width = std::min(res.width, depthStencil->width); + res.width = std::min(res.width, depthStencil->width); res.height = std::min(res.height, depthStencil->height); } @@ -1423,7 +1423,7 @@ static void doCreateFramebufferInstance(GLES2Device *device, GLES2GPUFramebuffer outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), colors.size(), depthStencilTexture, resolves, depthStencilResolveTexture, &outFBO->resolveMask)); if (outFBO->resolveMask) { - size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; GLES2GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, resolves, resolveCount)}; if (!resolveSwapchain) { outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture)); @@ -1445,7 +1445,7 @@ void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpu for (auto &subpass : gpuFBO->gpuRenderPass->subpasses) { if (subpass.inputs.size() == 4) { gpuFBO->uberOnChipOutput = subpass.inputs.back(); - gpuFBO->uberFinalOutput = subpass.colors.back(); + gpuFBO->uberFinalOutput = subpass.colors.back(); break; } } @@ -1488,7 +1488,7 @@ void GLES2GPUFramebuffer::GLFramebuffer::destroy(GLES2GPUStateCache *cache, GLES } void cmdFuncGLES2DestroyFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO) { - auto *cache = device->stateCache(); + auto *cache = device->stateCache(); auto *framebufferCacheMap = device->framebufferCacheMap(); for (auto &instance : gpuFBO->instances) { @@ -1505,29 +1505,29 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 const Rect *renderArea, const Color *clearColors, float clearDepth, uint32_t clearStencil) { static ccstd::vector invalidAttachments; - GLES2GPUStateCache *cache = device->stateCache(); - GLES2ObjectCache & gfxStateCache = cache->gfxStateCache; + GLES2GPUStateCache *cache = device->stateCache(); + GLES2ObjectCache &gfxStateCache = cache->gfxStateCache; Rect realRenderArea; gfxStateCache.subpassIdx = subpassIdx; if (subpassIdx) { - gpuRenderPass = gfxStateCache.gpuRenderPass; + gpuRenderPass = gfxStateCache.gpuRenderPass; gpuFramebuffer = gfxStateCache.gpuFramebuffer; realRenderArea = gfxStateCache.renderArea; - clearColors = gfxStateCache.clearColors.data(); - clearDepth = gfxStateCache.clearDepth; - clearStencil = gfxStateCache.clearStencil; + clearColors = gfxStateCache.clearColors.data(); + clearDepth = gfxStateCache.clearDepth; + clearStencil = gfxStateCache.clearStencil; } else { - realRenderArea.x = renderArea->x; - realRenderArea.y = renderArea->y; - realRenderArea.width = renderArea->width << gpuFramebuffer->lodLevel; + realRenderArea.x = renderArea->x; + realRenderArea.y = renderArea->y; + realRenderArea.width = renderArea->width << gpuFramebuffer->lodLevel; realRenderArea.height = renderArea->height << gpuFramebuffer->lodLevel; - gfxStateCache.gpuRenderPass = gpuRenderPass; + gfxStateCache.gpuRenderPass = gpuRenderPass; gfxStateCache.gpuFramebuffer = gpuFramebuffer; - gfxStateCache.renderArea = realRenderArea; + gfxStateCache.renderArea = realRenderArea; gfxStateCache.clearColors.assign(clearColors, clearColors + gpuRenderPass->colorAttachments.size()); - gfxStateCache.clearDepth = clearDepth; + gfxStateCache.clearDepth = clearDepth; gfxStateCache.clearStencil = clearStencil; } @@ -1548,9 +1548,9 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 cache->viewport.width != realRenderArea.width || cache->viewport.height != realRenderArea.height) { GL_CHECK(glViewport(realRenderArea.x, realRenderArea.y, realRenderArea.width, realRenderArea.height)); - cache->viewport.left = realRenderArea.x; - cache->viewport.top = realRenderArea.y; - cache->viewport.width = realRenderArea.width; + cache->viewport.left = realRenderArea.x; + cache->viewport.top = realRenderArea.y; + cache->viewport.width = realRenderArea.width; cache->viewport.height = realRenderArea.height; } @@ -1561,7 +1561,7 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 } GLbitfield glClears = 0; - bool maskSet = false; + bool maskSet = false; invalidAttachments.clear(); auto performLoadOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { @@ -1597,12 +1597,12 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 auto performDepthStencilLoadOp = [&](uint32_t attachmentIndex, bool skipLoad) { if (attachmentIndex != INVALID_BINDING && !skipLoad) { - LoadOp depthLoadOp = gpuRenderPass->depthStencilAttachment.depthLoadOp; + LoadOp depthLoadOp = gpuRenderPass->depthStencilAttachment.depthLoadOp; LoadOp stencilLoadOp = gpuRenderPass->depthStencilAttachment.stencilLoadOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { depthLoadOp = stencilLoadOp = gpuRenderPass->colorAttachments[attachmentIndex].loadOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; + hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } switch (depthLoadOp) { @@ -1687,7 +1687,7 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 performLoadOp(attachmentIndex, glAttachmentIndex++); } auto depthIndex = gpuRenderPass->subpasses[subpassIdx].depthStencil; - bool skipLoad = depthIndex == INVALID_BINDING || gpuRenderPass->statistics[depthIndex].loadSubpass != subpassIdx; + bool skipLoad = depthIndex == INVALID_BINDING || gpuRenderPass->statistics[depthIndex].loadSubpass != subpassIdx; performDepthStencilLoadOp(depthIndex, skipLoad); } } @@ -1696,16 +1696,16 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, GLES2 void cmdFuncGLES2EndRenderPass(GLES2Device *device) { static ccstd::vector invalidAttachments; - GLES2GPUStateCache * cache = device->stateCache(); - GLES2ObjectCache & gfxStateCache = cache->gfxStateCache; - GLES2GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; - GLES2GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - const auto & instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; - const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); - bool skipDiscard = false; + GLES2GPUStateCache *cache = device->stateCache(); + GLES2ObjectCache &gfxStateCache = cache->gfxStateCache; + GLES2GPURenderPass *gpuRenderPass = gfxStateCache.gpuRenderPass; + GLES2GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; + const auto &instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; + const SubpassInfo &subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; + bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); + bool skipDiscard = false; invalidAttachments.clear(); auto performStoreOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { @@ -1725,12 +1725,12 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { auto performDepthStencilStoreOp = [&](uint32_t attachmentIndex, bool skipStore) { if (attachmentIndex != INVALID_BINDING && !skipStore) { - StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; + StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; StoreOp stencilStoreOp = gpuRenderPass->depthStencilAttachment.stencilStoreOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { depthStoreOp = stencilStoreOp = gpuRenderPass->colorAttachments[attachmentIndex].storeOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; + hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { @@ -1769,9 +1769,9 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { GLES2GPUTexture *srcTexture = gpuFramebuffer->gpuColorTextures[subpass.colors[i]]; GLES2GPUTexture *dstTexture = gpuFramebuffer->gpuColorTextures[subpass.resolves[i]]; - region.srcExtent.width = srcTexture->width; + region.srcExtent.width = srcTexture->width; region.srcExtent.height = srcTexture->height; - region.dstExtent.width = dstTexture->width; + region.dstExtent.width = dstTexture->width; region.dstExtent.height = dstTexture->height; device->blitManager()->draw(srcTexture, dstTexture, ®ion, 1, Filter::POINT); } @@ -1785,9 +1785,9 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { ? gpuFramebuffer->gpuColorTextures[subpass.depthStencilResolve] : gpuFramebuffer->gpuDepthStencilTexture; - region.srcExtent.width = srcTexture->width; + region.srcExtent.width = srcTexture->width; region.srcExtent.height = srcTexture->height; - region.dstExtent.width = dstTexture->width; + region.dstExtent.width = dstTexture->width; region.dstExtent.height = dstTexture->height; device->blitManager()->draw(srcTexture, dstTexture, ®ion, 1, Filter::POINT); } @@ -1805,8 +1805,8 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { if (gpuFramebuffer->uberOnChipOutput != INVALID_BINDING) { TextureBlit region; - auto * blitSrc = gpuFramebuffer->gpuColorTextures[gpuFramebuffer->uberOnChipOutput]; - auto * blitDst = gpuFramebuffer->gpuColorTextures[gpuFramebuffer->uberFinalOutput]; + auto *blitSrc = gpuFramebuffer->gpuColorTextures[gpuFramebuffer->uberOnChipOutput]; + auto *blitDst = gpuFramebuffer->gpuColorTextures[gpuFramebuffer->uberFinalOutput]; region.srcExtent.width = region.dstExtent.width = blitSrc->width; region.srcExtent.height = region.dstExtent.height = blitSrc->height; cmdFuncGLES2BlitTexture(device, blitSrc, blitDst, ®ion, 1, Filter::POINT); @@ -1836,21 +1836,21 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli const DynamicStates *dynamicStates) { GLES2ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; - GLES2GPUStateCache *cache = device->stateCache(); - bool isShaderChanged = false; - GLenum glWrapS = 0U; - GLenum glWrapT = 0U; - GLenum glMinFilter = 0U; + GLES2GPUStateCache *cache = device->stateCache(); + bool isShaderChanged = false; + GLenum glWrapS = 0U; + GLenum glWrapT = 0U; + GLenum glMinFilter = 0U; if (gpuPipelineState && gpuPipelineState != gfxStateCache.gpuPipelineState) { gfxStateCache.gpuPipelineState = gpuPipelineState; - gfxStateCache.glPrimitive = gpuPipelineState->glPrimitive; + gfxStateCache.glPrimitive = gpuPipelineState->glPrimitive; if (gpuPipelineState->gpuShader) { if (cache->glProgram != gpuPipelineState->gpuShader->glProgram) { GL_CHECK(glUseProgram(gpuPipelineState->gpuShader->glProgram)); cache->glProgram = gpuPipelineState->gpuShader->glProgram; - isShaderChanged = true; + isShaderChanged = true; } } @@ -1933,8 +1933,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_CMP_FUNCS[(int)gpuPipelineState->dss.stencilFuncFront], gpuPipelineState->dss.stencilRefFront, gpuPipelineState->dss.stencilReadMaskFront)); - cache->dss.stencilFuncFront = gpuPipelineState->dss.stencilFuncFront; - cache->dss.stencilRefFront = gpuPipelineState->dss.stencilRefFront; + cache->dss.stencilFuncFront = gpuPipelineState->dss.stencilFuncFront; + cache->dss.stencilRefFront = gpuPipelineState->dss.stencilRefFront; cache->dss.stencilReadMaskFront = gpuPipelineState->dss.stencilReadMaskFront; } if (cache->dss.stencilFailOpFront != gpuPipelineState->dss.stencilFailOpFront || @@ -1944,9 +1944,9 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilFailOpFront], GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilZFailOpFront], GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilPassOpFront])); - cache->dss.stencilFailOpFront = gpuPipelineState->dss.stencilFailOpFront; + cache->dss.stencilFailOpFront = gpuPipelineState->dss.stencilFailOpFront; cache->dss.stencilZFailOpFront = gpuPipelineState->dss.stencilZFailOpFront; - cache->dss.stencilPassOpFront = gpuPipelineState->dss.stencilPassOpFront; + cache->dss.stencilPassOpFront = gpuPipelineState->dss.stencilPassOpFront; } if (cache->dss.stencilWriteMaskFront != gpuPipelineState->dss.stencilWriteMaskFront) { GL_CHECK(glStencilMaskSeparate(GL_FRONT, gpuPipelineState->dss.stencilWriteMaskFront)); @@ -1961,8 +1961,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_CMP_FUNCS[(int)gpuPipelineState->dss.stencilFuncBack], gpuPipelineState->dss.stencilRefBack, gpuPipelineState->dss.stencilReadMaskBack)); - cache->dss.stencilFuncBack = gpuPipelineState->dss.stencilFuncBack; - cache->dss.stencilRefBack = gpuPipelineState->dss.stencilRefBack; + cache->dss.stencilFuncBack = gpuPipelineState->dss.stencilFuncBack; + cache->dss.stencilRefBack = gpuPipelineState->dss.stencilRefBack; cache->dss.stencilReadMaskBack = gpuPipelineState->dss.stencilReadMaskBack; } if (cache->dss.stencilFailOpBack != gpuPipelineState->dss.stencilFailOpBack || @@ -1972,9 +1972,9 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilFailOpBack], GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilZFailOpBack], GLES2_STENCIL_OPS[(int)gpuPipelineState->dss.stencilPassOpBack])); - cache->dss.stencilFailOpBack = gpuPipelineState->dss.stencilFailOpBack; + cache->dss.stencilFailOpBack = gpuPipelineState->dss.stencilFailOpBack; cache->dss.stencilZFailOpBack = gpuPipelineState->dss.stencilZFailOpBack; - cache->dss.stencilPassOpBack = gpuPipelineState->dss.stencilPassOpBack; + cache->dss.stencilPassOpBack = gpuPipelineState->dss.stencilPassOpBack; } if (cache->dss.stencilWriteMaskBack != gpuPipelineState->dss.stencilWriteMaskBack) { GL_CHECK(glStencilMaskSeparate(GL_BACK, gpuPipelineState->dss.stencilWriteMaskBack)); @@ -2002,8 +2002,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } if (!gpuPipelineState->bs.targets.empty()) { - BlendTarget & cacheTarget = cache->bs.targets[0]; - const BlendTarget &target = gpuPipelineState->bs.targets[0]; + BlendTarget &cacheTarget = cache->bs.targets[0]; + const BlendTarget &target = gpuPipelineState->bs.targets[0]; if (cacheTarget.blend != target.blend) { if (!cacheTarget.blend) { GL_CHECK(glEnable(GL_BLEND)); @@ -2016,7 +2016,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli cacheTarget.blendAlphaEq != target.blendAlphaEq) { GL_CHECK(glBlendEquationSeparate(GLES2_BLEND_OPS[(int)target.blendEq], GLES2_BLEND_OPS[(int)target.blendAlphaEq])); - cacheTarget.blendEq = target.blendEq; + cacheTarget.blendEq = target.blendEq; cacheTarget.blendAlphaEq = target.blendAlphaEq; } if (cacheTarget.blendSrc != target.blendSrc || @@ -2027,8 +2027,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_BLEND_FACTORS[(int)target.blendDst], GLES2_BLEND_FACTORS[(int)target.blendSrcAlpha], GLES2_BLEND_FACTORS[(int)target.blendDstAlpha])); - cacheTarget.blendSrc = target.blendSrc; - cacheTarget.blendDst = target.blendDst; + cacheTarget.blendSrc = target.blendSrc; + cacheTarget.blendDst = target.blendDst; cacheTarget.blendSrcAlpha = target.blendSrcAlpha; cacheTarget.blendDstAlpha = target.blendDstAlpha; } @@ -2044,18 +2044,18 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli // bind descriptor sets if (gpuPipelineState && gpuPipelineState->gpuShader && gpuPipelineState->gpuPipelineLayout) { - size_t blockLen{gpuPipelineState->gpuShader->glBlocks.size()}; + size_t blockLen{gpuPipelineState->gpuShader->glBlocks.size()}; const ccstd::vector> &dynamicOffsetIndices{gpuPipelineState->gpuPipelineLayout->dynamicOffsetIndices}; - uint8_t * uniformBuffBase{nullptr}; - uint8_t * uniformBuff{nullptr}; - uint8_t * uniformCachedBuff{nullptr}; + uint8_t *uniformBuffBase{nullptr}; + uint8_t *uniformBuff{nullptr}; + uint8_t *uniformCachedBuff{nullptr}; for (size_t j = 0; j < blockLen; j++) { GLES2GPUUniformBlock &glBlock = gpuPipelineState->gpuShader->glBlocks[j]; const GLES2GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glBlock.set]; - const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBlock.binding); - const GLES2GPUDescriptor & gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBlock.binding); + const GLES2GPUDescriptor &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; if (!gpuDescriptor.gpuBuffer && !gpuDescriptor.gpuBufferView) { // CC_LOG_ERROR("Buffer binding '%s' at set %d binding %d is not bounded", @@ -2063,7 +2063,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli continue; } - uint32_t offset = 0U; + uint32_t offset = 0U; const ccstd::vector &dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set]; if (dynamicOffsetIndexSet.size() > glBlock.binding) { int dynamicOffsetIndex = dynamicOffsetIndexSet[glBlock.binding]; @@ -2078,7 +2078,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } for (auto &gpuUniform : glBlock.glActiveUniforms) { - uniformBuff = uniformBuffBase + gpuUniform.offset; + uniformBuff = uniformBuffBase + gpuUniform.offset; uniformCachedBuff = gpuUniform.buff.data(); switch (gpuUniform.glType) { @@ -2174,8 +2174,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli const GLES2GPUUniformSamplerTexture &glSamplerTexture = gpuPipelineState->gpuShader->glSamplerTextures[j]; const GLES2GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glSamplerTexture.set]; - const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glSamplerTexture.binding); - const GLES2GPUDescriptor * gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glSamplerTexture.binding); + const GLES2GPUDescriptor *gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; for (size_t u = 0; u < glSamplerTexture.units.size(); u++, gpuDescriptor++) { auto unit = static_cast(glSamplerTexture.units[u]); @@ -2187,7 +2187,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } GLES2GPUTexture *gpuTexture = gpuDescriptor->gpuTexture; - GLuint glTexture = gpuTexture->glTexture; + GLuint glTexture = gpuTexture->glTexture; CC_ASSERT(!gpuTexture->glRenderbuffer); // Can not sample renderbuffers! if (cache->glTextures[unit] != glTexture) { @@ -2269,7 +2269,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli (isShaderChanged || gpuInputAssembler != gfxStateCache.gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; if (device->constantRegistry()->useVAO) { - size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; + size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; GLuint glVAO = gpuInputAssembler->glVAOs[hash]; if (!glVAO) { GL_CHECK(glGenVertexArraysOES(1, &glVAO)); @@ -2285,7 +2285,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, gpuAttribute.glBuffer)); for (uint32_t c = 0; c < gpuAttribute.componentCount; ++c) { - GLuint glLoc = gpuInput.glLoc + c; + GLuint glLoc = gpuInput.glLoc + c; uint32_t attribOffset = gpuAttribute.offset + gpuAttribute.size * c; GL_CHECK(glEnableVertexAttribArray(glLoc)); @@ -2312,8 +2312,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GL_CHECK(glBindVertexArrayOES(0)); GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); - cache->glVAO = 0; - cache->glArrayBuffer = 0; + cache->glVAO = 0; + cache->glArrayBuffer = 0; cache->glElementArrayBuffer = 0; } @@ -2336,7 +2336,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } for (uint32_t c = 0; c < gpuAttribute.componentCount; ++c) { - GLuint glLoc = gpuInput.glLoc + c; + GLuint glLoc = gpuInput.glLoc + c; uint32_t attribOffset = gpuAttribute.offset + gpuAttribute.size * c; GL_CHECK(glEnableVertexAttribArray(glLoc)); cache->glEnabledAttribLocs[glLoc] = true; @@ -2386,7 +2386,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli if ((cache->rs.depthBias != dynamicStates->depthBiasConstant) || (cache->rs.depthBiasSlop != dynamicStates->depthBiasSlope)) { GL_CHECK(glPolygonOffset(dynamicStates->depthBiasConstant, dynamicStates->depthBiasSlope)); - cache->rs.depthBias = dynamicStates->depthBiasConstant; + cache->rs.depthBias = dynamicStates->depthBiasConstant; cache->rs.depthBiasSlop = dynamicStates->depthBiasSlope; } break; @@ -2404,7 +2404,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli break; case DynamicStateFlagBit::STENCIL_WRITE_MASK: { const auto &front = dynamicStates->stencilStatesFront; - const auto &back = dynamicStates->stencilStatesBack; + const auto &back = dynamicStates->stencilStatesBack; if (cache->dss.stencilWriteMaskFront != front.writeMask) { GL_CHECK(glStencilMaskSeparate(GL_FRONT, front.writeMask)); cache->dss.stencilWriteMaskFront = front.writeMask; @@ -2416,14 +2416,14 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } break; case DynamicStateFlagBit::STENCIL_COMPARE_MASK: { const auto &front = dynamicStates->stencilStatesFront; - const auto &back = dynamicStates->stencilStatesBack; + const auto &back = dynamicStates->stencilStatesBack; if ((cache->dss.stencilRefFront != front.reference) || (cache->dss.stencilReadMaskFront != front.compareMask)) { GL_CHECK(glStencilFuncSeparate(GL_FRONT, GLES2_CMP_FUNCS[toNumber(cache->dss.stencilFuncFront)], front.reference, front.compareMask)); - cache->dss.stencilRefFront = front.reference; + cache->dss.stencilRefFront = front.reference; cache->dss.stencilReadMaskFront = front.compareMask; } if ((cache->dss.stencilRefBack != back.reference) || @@ -2432,7 +2432,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2_CMP_FUNCS[toNumber(cache->dss.stencilFuncBack)], back.reference, back.compareMask)); - cache->dss.stencilRefBack = back.reference; + cache->dss.stencilRefBack = back.reference; cache->dss.stencilReadMaskBack = back.compareMask; } } break; @@ -2445,10 +2445,10 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli } void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo) { - GLES2ObjectCache & gfxStateCache = device->stateCache()->gfxStateCache; - GLES2GPUPipelineState * gpuPipelineState = gfxStateCache.gpuPipelineState; + GLES2ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; + GLES2GPUPipelineState *gpuPipelineState = gfxStateCache.gpuPipelineState; GLES2GPUInputAssembler *gpuInputAssembler = gfxStateCache.gpuInputAssembler; - GLenum glPrimitive = gfxStateCache.glPrimitive; + GLenum glPrimitive = gfxStateCache.glPrimitive; if (gpuInputAssembler && gpuPipelineState) { if (!gpuInputAssembler->gpuIndirectBuffer) { @@ -2557,8 +2557,8 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const glTexture = gpuTexture->glTexture; } - bool isCompressed = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed; - uint32_t n = 0; + bool isCompressed = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed; + uint32_t n = 0; switch (gpuTexture->glTarget) { case GL_TEXTURE_2D: { @@ -2566,9 +2566,9 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const uint32_t h; for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; - w = region.texExtent.width; - h = region.texExtent.height; - const uint8_t *buff = buffers[n++]; + w = region.texExtent.width; + h = region.texExtent.height; + const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); GL_CHECK(glCompressedTexSubImage2D(GL_TEXTURE_2D, @@ -2596,13 +2596,13 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const uint32_t w; uint32_t h; for (size_t i = 0; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - uint32_t d = region.texSubres.layerCount; - uint32_t layerCount = d + region.texSubres.baseArrayLayer; + const BufferTextureCopy ®ion = regions[i]; + uint32_t d = region.texSubres.layerCount; + uint32_t layerCount = d + region.texSubres.baseArrayLayer; for (uint32_t z = region.texSubres.baseArrayLayer; z < layerCount; ++z) { - w = region.texExtent.width; - h = region.texExtent.height; + w = region.texExtent.width; + h = region.texExtent.height; const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); @@ -2635,10 +2635,10 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const uint32_t d; for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; - w = region.texExtent.width; - h = region.texExtent.height; - d = region.texExtent.depth; - const uint8_t *buff = buffers[n++]; + w = region.texExtent.width; + h = region.texExtent.height; + d = region.texExtent.depth; + const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); GL_CHECK(glCompressedTexSubImage3DOES(GL_TEXTURE_3D, @@ -2669,11 +2669,11 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const uint32_t h; uint32_t f; for (size_t i = 0; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - uint32_t faceCount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + const BufferTextureCopy ®ion = regions[i]; + uint32_t faceCount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < faceCount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; + w = region.texExtent.width; + h = region.texExtent.height; const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); @@ -2711,8 +2711,8 @@ void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, const uint8_t *const void cmdFuncGLES2CopyTextureToBuffers(GLES2Device *device, GLES2GPUTexture *gpuTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { GLuint framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTexture); - auto glFormat = gpuTexture->glFormat; - auto glType = gpuTexture->glType; + auto glFormat = gpuTexture->glFormat; + auto glType = gpuTexture->glType; if (device->stateCache()->glFramebuffer != framebuffer) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, framebuffer)); @@ -2720,7 +2720,7 @@ void cmdFuncGLES2CopyTextureToBuffers(GLES2Device *device, GLES2GPUTexture *gpuT } for (uint32_t i = 0; i < count; ++i) { - auto region = regions[i]; + auto region = regions[i]; uint8_t *copyDst = buffers[i]; GL_CHECK(glReadPixels(region.texOffset.x, region.texOffset.y, region.texExtent.width, region.texExtent.height, glFormat, glType, copyDst)); } @@ -2753,7 +2753,7 @@ void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage) { for (uint32_t i = 0; i < cmdPackage->cmds.size(); ++i) { GLESCmdType cmdType = cmdPackage->cmds[i]; - uint32_t & cmdIdx = cmdIndices[static_cast(cmdType)]; + uint32_t &cmdIdx = cmdIndices[static_cast(cmdType)]; switch (cmdType) { case GLESCmdType::BEGIN_RENDER_PASS: { @@ -2839,8 +2839,8 @@ void GLES2GPUBlitManager::initialize() { )"}); cmdFuncGLES2CreateShader(GLES2Device::getInstance(), &_gpuShader); - _gpuDescriptorSetLayout.descriptorCount = 2; - _gpuDescriptorSetLayout.bindingIndices = {0, 1}; + _gpuDescriptorSetLayout.descriptorCount = 2; + _gpuDescriptorSetLayout.bindingIndices = {0, 1}; _gpuDescriptorSetLayout.descriptorIndices = {0, 1}; _gpuDescriptorSetLayout.bindings.push_back({0, DescriptorType::UNIFORM_BUFFER, 1, ShaderStageFlagBit::VERTEX}); _gpuDescriptorSetLayout.bindings.push_back({1, DescriptorType::SAMPLER_TEXTURE, 1, ShaderStageFlagBit::FRAGMENT}); @@ -2849,17 +2849,17 @@ void GLES2GPUBlitManager::initialize() { _gpuPipelineLayout.dynamicOffsetIndices.emplace_back(); _gpuPipelineLayout.dynamicOffsetOffsets.push_back(0); - _gpuPipelineState.glPrimitive = GL_TRIANGLE_STRIP; - _gpuPipelineState.gpuShader = &_gpuShader; - _gpuPipelineState.dss.depthTest = false; - _gpuPipelineState.dss.depthWrite = false; + _gpuPipelineState.glPrimitive = GL_TRIANGLE_STRIP; + _gpuPipelineState.gpuShader = &_gpuShader; + _gpuPipelineState.dss.depthTest = false; + _gpuPipelineState.dss.depthWrite = false; _gpuPipelineState.gpuPipelineLayout = &_gpuPipelineLayout; - _gpuVertexBuffer.usage = BufferUsage::VERTEX; + _gpuVertexBuffer.usage = BufferUsage::VERTEX; _gpuVertexBuffer.memUsage = MemoryUsage::DEVICE; - _gpuVertexBuffer.size = 16 * sizeof(float); - _gpuVertexBuffer.stride = 4 * sizeof(float); - _gpuVertexBuffer.count = 4; + _gpuVertexBuffer.size = 16 * sizeof(float); + _gpuVertexBuffer.stride = 4 * sizeof(float); + _gpuVertexBuffer.count = 4; cmdFuncGLES2CreateBuffer(GLES2Device::getInstance(), &_gpuVertexBuffer); float data[]{ -1.F, -1.F, 0.F, 0.F, @@ -2881,11 +2881,11 @@ void GLES2GPUBlitManager::initialize() { _gpuLinearSampler.magFilter = Filter::LINEAR; cmdFuncGLES2CreateSampler(GLES2Device::getInstance(), &_gpuLinearSampler); - _gpuUniformBuffer.usage = BufferUsage::UNIFORM; + _gpuUniformBuffer.usage = BufferUsage::UNIFORM; _gpuUniformBuffer.memUsage = MemoryUsage::DEVICE | MemoryUsage::HOST; - _gpuUniformBuffer.size = 8 * sizeof(float); - _gpuUniformBuffer.stride = 8 * sizeof(float); - _gpuUniformBuffer.count = 1; + _gpuUniformBuffer.size = 8 * sizeof(float); + _gpuUniformBuffer.stride = 8 * sizeof(float); + _gpuUniformBuffer.count = 1; cmdFuncGLES2CreateBuffer(GLES2Device::getInstance(), &_gpuUniformBuffer); _gpuDescriptorSet.gpuDescriptors.push_back({DescriptorType::UNIFORM_BUFFER, &_gpuUniformBuffer}); @@ -2910,9 +2910,9 @@ static void ensureScissorRect(GLES2GPUStateCache *cache, int32_t x, int32_t y, u cache->viewport.top > y || cache->viewport.width < width || cache->viewport.height < height) { - cache->viewport.left = std::min(cache->viewport.left, x); - cache->viewport.top = std::min(cache->viewport.top, y); - cache->viewport.width = std::max(cache->viewport.width, width); + cache->viewport.left = std::min(cache->viewport.left, x); + cache->viewport.top = std::min(cache->viewport.top, y); + cache->viewport.width = std::max(cache->viewport.width, width); cache->viewport.height = std::max(cache->viewport.height, height); GL_CHECK(glViewport(cache->viewport.left, cache->viewport.top, cache->viewport.width, cache->viewport.height)); } @@ -2921,9 +2921,9 @@ static void ensureScissorRect(GLES2GPUStateCache *cache, int32_t x, int32_t y, u cache->scissor.y > y || cache->scissor.width < width || cache->scissor.height < height) { - cache->scissor.x = std::min(cache->scissor.x, x); - cache->scissor.y = std::min(cache->scissor.y, y); - cache->scissor.width = std::max(cache->scissor.width, width); + cache->scissor.x = std::min(cache->scissor.x, x); + cache->scissor.y = std::min(cache->scissor.y, y); + cache->scissor.width = std::max(cache->scissor.width, width); cache->scissor.height = std::max(cache->scissor.height, height); GL_CHECK(glScissor(cache->scissor.x, cache->scissor.y, cache->scissor.width, cache->scissor.height)); } @@ -2932,17 +2932,17 @@ static void ensureScissorRect(GLES2GPUStateCache *cache, int32_t x, int32_t y, u void GLES2GPUBlitManager::draw(GLES2GPUTexture *gpuTextureSrc, GLES2GPUTexture *gpuTextureDst, const TextureBlit *regions, uint32_t count, Filter filter) { GLES2GPUDescriptorSet *gpuDescriptorSet = &_gpuDescriptorSet; - GLES2Device * device = GLES2Device::getInstance(); - auto & descriptor = _gpuDescriptorSet.gpuDescriptors.back(); + GLES2Device *device = GLES2Device::getInstance(); + auto &descriptor = _gpuDescriptorSet.gpuDescriptors.back(); descriptor.gpuTexture = gpuTextureSrc; descriptor.gpuSampler = filter == Filter::POINT ? &_gpuPointSampler : &_gpuLinearSampler; for (uint32_t i = 0U; i < count; ++i) { const auto ®ion = regions[i]; - auto srcWidth = static_cast(gpuTextureSrc->width); + auto srcWidth = static_cast(gpuTextureSrc->width); auto srcHeight = static_cast(gpuTextureSrc->height); - auto dstWidth = static_cast(gpuTextureDst->width); + auto dstWidth = static_cast(gpuTextureDst->width); auto dstHeight = static_cast(gpuTextureDst->height); _uniformBuffer[0] = static_cast(region.srcExtent.width) / srcWidth; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.h b/native/cocos/renderer/gfx-gles2/GLES2Commands.h index 7c57112e5b..4ed72b439f 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.h @@ -34,34 +34,34 @@ class GLES2Device; class GLES2CmdBeginRenderPass final : public GLESCmd { public: - GLES2GPURenderPass * gpuRenderPass = nullptr; - GLES2GPUFramebuffer *gpuFBO = nullptr; - Rect renderArea; - Color clearColors[MAX_ATTACHMENTS]; - float clearDepth = 1.0F; - uint32_t clearStencil = 0; - uint32_t subpassIdx = 0U; + GLES2GPURenderPass *gpuRenderPass = nullptr; + GLES2GPUFramebuffer *gpuFBO = nullptr; + Rect renderArea; + Color clearColors[MAX_ATTACHMENTS]; + float clearDepth = 1.0F; + uint32_t clearStencil = 0; + uint32_t subpassIdx = 0U; GLES2CmdBeginRenderPass() : GLESCmd(GLESCmdType::BEGIN_RENDER_PASS) {} void clear() override { - gpuFBO = nullptr; + gpuFBO = nullptr; gpuRenderPass = nullptr; } }; class GLES2CmdBindStates final : public GLESCmd { public: - GLES2GPUPipelineState * gpuPipelineState = nullptr; - GLES2GPUInputAssembler * gpuInputAssembler = nullptr; + GLES2GPUPipelineState *gpuPipelineState = nullptr; + GLES2GPUInputAssembler *gpuInputAssembler = nullptr; ccstd::vector gpuDescriptorSets; - ccstd::vector dynamicOffsets; - DynamicStates dynamicStates; + ccstd::vector dynamicOffsets; + DynamicStates dynamicStates; GLES2CmdBindStates() : GLESCmd(GLESCmdType::BIND_STATES) {} void clear() override { - gpuPipelineState = nullptr; + gpuPipelineState = nullptr; gpuInputAssembler = nullptr; gpuDescriptorSets.clear(); dynamicOffsets.clear(); @@ -79,71 +79,71 @@ public: class GLES2CmdUpdateBuffer final : public GLESCmd { public: GLES2GPUBuffer *gpuBuffer = nullptr; - const uint8_t * buffer = nullptr; - uint32_t size = 0; - uint32_t offset = 0; + const uint8_t *buffer = nullptr; + uint32_t size = 0; + uint32_t offset = 0; GLES2CmdUpdateBuffer() : GLESCmd(GLESCmdType::UPDATE_BUFFER) {} void clear() override { gpuBuffer = nullptr; - buffer = nullptr; + buffer = nullptr; } }; class GLES2CmdCopyBufferToTexture final : public GLESCmd { public: - GLES2GPUTexture * gpuTexture = nullptr; - const BufferTextureCopy *regions = nullptr; - uint32_t count = 0U; - const uint8_t *const * buffers = nullptr; + GLES2GPUTexture *gpuTexture = nullptr; + const BufferTextureCopy *regions = nullptr; + uint32_t count = 0U; + const uint8_t *const *buffers = nullptr; GLES2CmdCopyBufferToTexture() : GLESCmd(GLESCmdType::COPY_BUFFER_TO_TEXTURE) {} void clear() override { gpuTexture = nullptr; - regions = nullptr; - count = 0U; - buffers = nullptr; + regions = nullptr; + count = 0U; + buffers = nullptr; } }; class GLES2CmdBlitTexture final : public GLESCmd { public: - GLES2GPUTexture * gpuTextureSrc = nullptr; - GLES2GPUTexture * gpuTextureDst = nullptr; - const TextureBlit *regions = nullptr; - uint32_t count = 0U; - Filter filter = Filter::POINT; + GLES2GPUTexture *gpuTextureSrc = nullptr; + GLES2GPUTexture *gpuTextureDst = nullptr; + const TextureBlit *regions = nullptr; + uint32_t count = 0U; + Filter filter = Filter::POINT; GLES2CmdBlitTexture() : GLESCmd(GLESCmdType::BLIT_TEXTURE) {} void clear() override { gpuTextureSrc = nullptr; gpuTextureDst = nullptr; - regions = nullptr; - count = 0U; + regions = nullptr; + count = 0U; } }; struct GLES2CmdPackage { - CachedArray cmds; - CachedArray beginRenderPassCmds; - CachedArray bindStatesCmds; - CachedArray drawCmds; - CachedArray updateBufferCmds; + CachedArray cmds; + CachedArray beginRenderPassCmds; + CachedArray bindStatesCmds; + CachedArray drawCmds; + CachedArray updateBufferCmds; CachedArray copyBufferToTextureCmds; - CachedArray blitTextureCmds; + CachedArray blitTextureCmds; }; class GLES2GPUCommandAllocator final { public: - CommandPool beginRenderPassCmdPool; - CommandPool bindStatesCmdPool; - CommandPool drawCmdPool; - CommandPool updateBufferCmdPool; + CommandPool beginRenderPassCmdPool; + CommandPool bindStatesCmdPool; + CommandPool drawCmdPool; + CommandPool updateBufferCmdPool; CommandPool copyBufferToTextureCmdPool; - CommandPool blitTextureCmdPool; + CommandPool blitTextureCmdPool; void clearCmds(GLES2CmdPackage *cmdPackage) { if (cmdPackage->beginRenderPassCmds.size()) { @@ -196,48 +196,48 @@ void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpu void cmdFuncGLES2DestroyFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO); void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint32_t subpassIdx, - GLES2GPURenderPass * gpuRenderPass = nullptr, + GLES2GPURenderPass *gpuRenderPass = nullptr, GLES2GPUFramebuffer *gpuFramebuffer = nullptr, - const Rect * renderArea = nullptr, - const Color * clearColors = nullptr, - float clearDepth = 1.F, - uint32_t clearStencil = 0); + const Rect *renderArea = nullptr, + const Color *clearColors = nullptr, + float clearDepth = 1.F, + uint32_t clearStencil = 0); void cmdFuncGLES2EndRenderPass(GLES2Device *device); -void cmdFuncGLES2BindState(GLES2Device * device, - GLES2GPUPipelineState * gpuPipelineState, - GLES2GPUInputAssembler * gpuInputAssembler, +void cmdFuncGLES2BindState(GLES2Device *device, + GLES2GPUPipelineState *gpuPipelineState, + GLES2GPUInputAssembler *gpuInputAssembler, const GLES2GPUDescriptorSet *const *gpuDescriptorSets, - const uint32_t * dynamicOffsets = nullptr, - const DynamicStates * dynamicStates = nullptr); + const uint32_t *dynamicOffsets = nullptr, + const DynamicStates *dynamicStates = nullptr); void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo); -void cmdFuncGLES2UpdateBuffer(GLES2Device * device, +void cmdFuncGLES2UpdateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer, - const void * buffer, - uint32_t offset, - uint32_t size); + const void *buffer, + uint32_t offset, + uint32_t size); -void cmdFuncGLES2CopyBuffersToTexture(GLES2Device * device, - const uint8_t *const * buffers, - GLES2GPUTexture * gpuTexture, +void cmdFuncGLES2CopyBuffersToTexture(GLES2Device *device, + const uint8_t *const *buffers, + GLES2GPUTexture *gpuTexture, const BufferTextureCopy *regions, - uint32_t count); + uint32_t count); -void cmdFuncGLES2CopyTextureToBuffers(GLES2Device * device, - GLES2GPUTexture * gpuTexture, - uint8_t *const * buffers, +void cmdFuncGLES2CopyTextureToBuffers(GLES2Device *device, + GLES2GPUTexture *gpuTexture, + uint8_t *const *buffers, const BufferTextureCopy *regions, - uint32_t count); + uint32_t count); -void cmdFuncGLES2BlitTexture(GLES2Device * device, - GLES2GPUTexture * gpuTextureSrc, - GLES2GPUTexture * gpuTextureDst, +void cmdFuncGLES2BlitTexture(GLES2Device *device, + GLES2GPUTexture *gpuTextureSrc, + GLES2GPUTexture *gpuTextureDst, const TextureBlit *regions, - uint32_t count, - Filter filter); + uint32_t count, + Filter filter); void cmdFuncGLES2ExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmdPackage); diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp index a2fdab8344..f5112c8896 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSet.cpp @@ -45,8 +45,8 @@ GLES2DescriptorSet::~GLES2DescriptorSet() { void GLES2DescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { const GLES2GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); - const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; - const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); + const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; + const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); _buffers.resize(descriptorCount); _textures.resize(descriptorCount); diff --git a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.cpp b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.cpp index 6f23745c80..9b05bbb121 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2DescriptorSetLayout.cpp @@ -40,11 +40,11 @@ GLES2DescriptorSetLayout::~GLES2DescriptorSetLayout() { } void GLES2DescriptorSetLayout::doInit(const DescriptorSetLayoutInfo & /*info*/) { - _gpuDescriptorSetLayout = ccnew GLES2GPUDescriptorSetLayout; - _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; - _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; + _gpuDescriptorSetLayout = ccnew GLES2GPUDescriptorSetLayout; + _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; + _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; _gpuDescriptorSetLayout->descriptorIndices = _descriptorIndices; - _gpuDescriptorSetLayout->bindings = _bindings; + _gpuDescriptorSetLayout->bindings = _bindings; for (auto &binding : _bindings) { if (hasAnyFlags(binding.descriptorType, DESCRIPTOR_DYNAMIC_TYPE)) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index f744b17503..825612a9d4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -61,7 +61,7 @@ GLES2Device *GLES2Device::getInstance() { } GLES2Device::GLES2Device() { - _api = API::GLES2; + _api = API::GLES2; _deviceName = "GLES2"; GLES2Device::instance = this; @@ -72,11 +72,11 @@ GLES2Device::~GLES2Device() { } bool GLES2Device::doInit(const DeviceInfo & /*info*/) { - _gpuContext = ccnew GLES2GPUContext; - _gpuStateCache = ccnew GLES2GPUStateCache; - _gpuBlitManager = ccnew GLES2GPUBlitManager; - _gpuFramebufferHub = ccnew GLES2GPUFramebufferHub; - _gpuConstantRegistry = ccnew GLES2GPUConstantRegistry; + _gpuContext = ccnew GLES2GPUContext; + _gpuStateCache = ccnew GLES2GPUStateCache; + _gpuBlitManager = ccnew GLES2GPUBlitManager; + _gpuFramebufferHub = ccnew GLES2GPUFramebufferHub; + _gpuConstantRegistry = ccnew GLES2GPUConstantRegistry; _gpuFramebufferCacheMap = ccnew GLES2GPUFramebufferCacheMap(_gpuStateCache); if (!_gpuContext->initialize(_gpuStateCache, _gpuConstantRegistry)) { @@ -90,7 +90,7 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { uint32_t curSet{_bindingMappingInfo.setIndices[i]}; uint32_t prevSet{i ? _bindingMappingInfo.setIndices[i - 1] : curSet}; // accumulate the per set offset according to the specified capacity - _bindingMappings.blockOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxBlockCounts[prevSet]) + _bindingMappings.blockOffsets[prevSet] : 0; + _bindingMappings.blockOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxBlockCounts[prevSet]) + _bindingMappings.blockOffsets[prevSet] : 0; _bindingMappings.samplerTextureOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxSamplerTextureCounts[prevSet]) + _bindingMappings.samplerTextureOffsets[prevSet] : 0; } for (uint32_t curSet : _bindingMappingInfo.setIndices) { @@ -100,7 +100,7 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { _bindingMappings.flexibleSet = _bindingMappingInfo.setIndices.back(); ccstd::string extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); - _extensions = StringUtil::split(extStr, " "); + _extensions = StringUtil::split(extStr, " "); _multithreadedCommandRecording = false; @@ -119,9 +119,9 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { _features[toNumber(Feature::BLEND_MINMAX)] = true; } - _gpuConstantRegistry->useVAO = checkExtension("vertex_array_object"); - _gpuConstantRegistry->useDrawInstanced = checkExtension("draw_instanced"); - _gpuConstantRegistry->useInstancedArrays = checkExtension("instanced_arrays"); + _gpuConstantRegistry->useVAO = checkExtension("vertex_array_object"); + _gpuConstantRegistry->useDrawInstanced = checkExtension("draw_instanced"); + _gpuConstantRegistry->useInstancedArrays = checkExtension("instanced_arrays"); _gpuConstantRegistry->useDiscardFramebuffer = checkExtension("discard_framebuffer"); _features[toNumber(Feature::INSTANCED_ARRAYS)] = _gpuConstantRegistry->useInstancedArrays; @@ -139,16 +139,16 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { if (it != _extensions.end()) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; - fbfLevelStr = "NON_COHERENT_EXT"; + fbfLevelStr = "NON_COHERENT_EXT"; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; - fbfLevelStr = "NON_COHERENT_QCOM"; + fbfLevelStr = "NON_COHERENT_QCOM"; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; - fbfLevelStr = "COHERENT"; + fbfLevelStr = "COHERENT"; } _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = _gpuConstantRegistry->mFBF != FBFSupportLevel::NONE; } @@ -178,8 +178,8 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { } _renderer = reinterpret_cast(glGetString(GL_RENDERER)); - _vendor = reinterpret_cast(glGetString(GL_VENDOR)); - _version = reinterpret_cast(glGetString(GL_VERSION)); + _vendor = reinterpret_cast(glGetString(GL_VENDOR)); + _version = reinterpret_cast(glGetString(GL_VERSION)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast(&_caps.maxVertexAttributes)); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxVertexUniformVectors)); @@ -191,15 +191,15 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); + _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _cmdBuff = createCommandBuffer(cmdBuffInfo); _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxVertexAttributes); _gpuBlitManager->initialize(); @@ -244,7 +244,7 @@ void GLES2Device::acquire(Swapchain *const *swapchains, uint32_t count) { void GLES2Device::present() { CC_PROFILE(GLES2DevicePresent); - auto *queue = static_cast(_queue); + auto *queue = static_cast(_queue); _numDrawCalls = queue->_numDrawCalls; _numInstances = queue->_numInstances; _numTriangles = queue->_numTriangles; @@ -269,15 +269,15 @@ void GLES2Device::initFormatFeature() { const FormatFeature completeFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER; // builtin formatFeatures - _formatFeatures[toNumber(Format::RGB8)] = completeFeature; - _formatFeatures[toNumber(Format::R5G6B5)] = completeFeature; + _formatFeatures[toNumber(Format::RGB8)] = completeFeature; + _formatFeatures[toNumber(Format::R5G6B5)] = completeFeature; _textureExclusive[toNumber(Format::R5G6B5)] = false; - _formatFeatures[toNumber(Format::RGBA8)] = completeFeature; - _formatFeatures[toNumber(Format::RGBA4)] = completeFeature; + _formatFeatures[toNumber(Format::RGBA8)] = completeFeature; + _formatFeatures[toNumber(Format::RGBA4)] = completeFeature; _textureExclusive[toNumber(Format::RGBA4)] = false; - _formatFeatures[toNumber(Format::RGB5A1)] = completeFeature; + _formatFeatures[toNumber(Format::RGB5A1)] = completeFeature; _textureExclusive[toNumber(Format::RGB5A1)] = false; _formatFeatures[toNumber(Format::R8)] |= FormatFeature::VERTEX_ATTRIBUTE; @@ -471,7 +471,7 @@ InputAssembler *GLES2Device::createInputAssembler() { } RenderPass *GLES2Device::createRenderPass() { - return ccnew GLES2RenderPass; + return ccnew GLES2RenderPass; } Framebuffer *GLES2Device::createFramebuffer() { diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 8510cfe66e..77da65d664 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -70,11 +70,11 @@ public: inline const GLESBindingMapping &bindingMappings() const { return _bindingMappings; } - inline GLES2GPUContext * context() const { return _gpuContext; } - inline GLES2GPUStateCache * stateCache() const { return _gpuStateCache; } - inline GLES2GPUBlitManager * blitManager() const { return _gpuBlitManager; } - inline GLES2GPUFramebufferHub * framebufferHub() const { return _gpuFramebufferHub; } - inline GLES2GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } + inline GLES2GPUContext *context() const { return _gpuContext; } + inline GLES2GPUStateCache *stateCache() const { return _gpuStateCache; } + inline GLES2GPUBlitManager *blitManager() const { return _gpuBlitManager; } + inline GLES2GPUFramebufferHub *framebufferHub() const { return _gpuFramebufferHub; } + inline GLES2GPUConstantRegistry *constantRegistry() const { return _gpuConstantRegistry; } inline GLES2GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } inline bool checkExtension(const ccstd::string &extension) const { @@ -93,22 +93,22 @@ protected: GLES2Device(); - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; Sampler *createSampler(const SamplerInfo &info) override; @@ -120,11 +120,11 @@ protected: void initFormatFeature(); - GLES2GPUContext * _gpuContext{nullptr}; - GLES2GPUStateCache * _gpuStateCache{nullptr}; - GLES2GPUBlitManager * _gpuBlitManager{nullptr}; - GLES2GPUFramebufferHub * _gpuFramebufferHub{nullptr}; - GLES2GPUConstantRegistry * _gpuConstantRegistry{nullptr}; + GLES2GPUContext *_gpuContext{nullptr}; + GLES2GPUStateCache *_gpuStateCache{nullptr}; + GLES2GPUBlitManager *_gpuBlitManager{nullptr}; + GLES2GPUFramebufferHub *_gpuFramebufferHub{nullptr}; + GLES2GPUConstantRegistry *_gpuConstantRegistry{nullptr}; GLES2GPUFramebufferCacheMap *_gpuFramebufferCacheMap{nullptr}; ccstd::vector _swapchains; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp index 337a4119be..9f6056e3c2 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp @@ -43,21 +43,21 @@ GLES2Framebuffer::~GLES2Framebuffer() { } void GLES2Framebuffer::doInit(const FramebufferInfo & /*info*/) { - _gpuFBO = ccnew GLES2GPUFramebuffer; + _gpuFBO = ccnew GLES2GPUFramebuffer; _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorTextures.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { - auto *colorTexture = static_cast(_colorTextures[i]); + auto *colorTexture = static_cast(_colorTextures[i]); _gpuFBO->gpuColorTextures[i] = colorTexture->gpuTexture(); - _gpuFBO->lodLevel = colorTexture->getViewInfo().baseLevel; + _gpuFBO->lodLevel = colorTexture->getViewInfo().baseLevel; GLES2Device::getInstance()->framebufferHub()->connect(colorTexture->gpuTexture(), _gpuFBO); } if (_depthStencilTexture) { - auto *depthTexture = static_cast(_depthStencilTexture); + auto *depthTexture = static_cast(_depthStencilTexture); _gpuFBO->gpuDepthStencilTexture = depthTexture->gpuTexture(); - _gpuFBO->lodLevel = depthTexture->getViewInfo().baseLevel; + _gpuFBO->lodLevel = depthTexture->getViewInfo().baseLevel; GLES2Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); } diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp index 61e0b29ff6..8d14fd763b 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp @@ -86,7 +86,7 @@ void GL_APIENTRY GLES2EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum #endif bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstantRegistry *constantRegistry) { - _stateCache = stateCache; + _stateCache = stateCache; _constantRegistry = constantRegistry; if (!gles2wInit()) { @@ -135,7 +135,7 @@ bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstan EGL_SAMPLES, sampleSize, EGL_NONE}; - int numConfig{0}; + int numConfig{0}; ccstd::vector eglConfigs; EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, nullptr, 0, &numConfig)); @@ -153,11 +153,11 @@ bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstan return false; } - EGLint depth{0}; - EGLint stencil{0}; - EGLint sampleBuffers{0}; - EGLint sampleCount{0}; - EGLint params[8]{0}; + EGLint depth{0}; + EGLint stencil{0}; + EGLint sampleBuffers{0}; + EGLint sampleCount{0}; + EGLint params[8]{0}; uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); for (int i = 0; i < numConfig; i++) { @@ -177,7 +177,7 @@ bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstan /*------------------------------------------ANGLE's priority-----------------------------------------------*/ // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha uint64_t currScore{0}; - EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); + EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; currScore |= static_cast(std::min(colorScore, 127)) << 17; @@ -192,12 +192,12 @@ bool GLES2GPUContext::initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstan // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" bool filter = (currScore < lastScore) ^ qualityPreferred; if ((filter && msaaLimit) || (!eglConfig && i == numConfig - 1)) { - eglConfig = eglConfigs[i]; - depth = params[4]; - stencil = params[5]; + eglConfig = eglConfigs[i]; + depth = params[4]; + stencil = params[5]; sampleBuffers = params[6]; - sampleCount = params[7]; - lastScore = currScore; + sampleCount = params[7]; + lastScore = currScore; } } @@ -334,7 +334,7 @@ bool GLES2GPUContext::makeCurrent(EGLSurface drawSurface, EGLSurface readSurface if (succeeded && updateCache) { _eglCurrentDrawSurface = drawSurface; _eglCurrentReadSurface = readSurface; - _eglCurrentContext = context; + _eglCurrentContext = context; } return succeeded; } diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index b80e2161f8..b33bea0543 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -34,11 +34,11 @@ struct GLES2GPUConstantRegistry { size_t currentBoundThreadID{0U}; MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; - FBFSupportLevel mFBF{FBFSupportLevel::NONE}; + FBFSupportLevel mFBF{FBFSupportLevel::NONE}; - bool useVAO = false; - bool useDrawInstanced = false; - bool useInstancedArrays = false; + bool useVAO = false; + bool useDrawInstanced = false; + bool useInstancedArrays = false; bool useDiscardFramebuffer = false; }; @@ -49,10 +49,10 @@ public: bool initialize(GLES2GPUStateCache *stateCache, GLES2GPUConstantRegistry *constantRegistry); void destroy(); - EGLint eglMajorVersion{0}; - EGLint eglMinorVersion{0}; - EGLDisplay eglDisplay{EGL_NO_DISPLAY}; - EGLConfig eglConfig{nullptr}; + EGLint eglMajorVersion{0}; + EGLint eglMinorVersion{0}; + EGLDisplay eglDisplay{EGL_NO_DISPLAY}; + EGLConfig eglConfig{nullptr}; ccstd::vector eglAttributes; EGLSurface eglDefaultSurface{EGL_NO_SURFACE}; @@ -69,17 +69,17 @@ public: } private: - bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); + bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); EGLContext getSharedContext(); - void resetStates() const; + void resetStates() const; // state caches EGLSurface _eglCurrentDrawSurface{EGL_NO_SURFACE}; EGLSurface _eglCurrentReadSurface{EGL_NO_SURFACE}; EGLContext _eglCurrentContext{EGL_NO_CONTEXT}; - EGLint _eglCurrentInterval{0}; + EGLint _eglCurrentInterval{0}; - GLES2GPUStateCache * _stateCache{nullptr}; + GLES2GPUStateCache *_stateCache{nullptr}; GLES2GPUConstantRegistry *_constantRegistry{nullptr}; ccstd::unordered_map _sharedContexts; @@ -88,50 +88,50 @@ private: }; struct GLES2GPUBuffer { - BufferUsage usage = BufferUsage::NONE; - MemoryUsage memUsage = MemoryUsage::NONE; - uint32_t size = 0; - uint32_t stride = 0; - uint32_t count = 0; - GLenum glTarget = 0; - GLuint glBuffer = 0; - uint8_t * buffer = nullptr; + BufferUsage usage = BufferUsage::NONE; + MemoryUsage memUsage = MemoryUsage::NONE; + uint32_t size = 0; + uint32_t stride = 0; + uint32_t count = 0; + GLenum glTarget = 0; + GLuint glBuffer = 0; + uint8_t *buffer = nullptr; DrawInfoList indirects; }; using GLES2GPUBufferList = ccstd::vector; struct GLES2GPUBufferView { GLES2GPUBuffer *gpuBuffer = nullptr; - uint32_t offset = 0U; - uint32_t range = 0U; + uint32_t offset = 0U; + uint32_t range = 0U; }; struct GLES2GPUTexture { - TextureType type{TextureType::TEX2D}; - Format format{Format::UNKNOWN}; - TextureUsage usage{TextureUsageBit::NONE}; - uint32_t width{0}; - uint32_t height{0}; - uint32_t depth{1}; - uint32_t size{0}; - uint32_t arrayLayer{1}; - uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; - TextureFlags flags{TextureFlagBit::NONE}; - bool isPowerOf2{false}; - bool memoryless{false}; - GLenum glTarget{0}; - GLenum glInternalFmt{0}; - GLenum glFormat{0}; - GLenum glType{0}; - GLenum glUsage{0}; - GLint glSamples{0}; - GLuint glTexture{0}; - GLuint glRenderbuffer{0}; - GLenum glWrapS{0}; - GLenum glWrapT{0}; - GLenum glMinFilter{0}; - GLenum glMagFilter{0}; + TextureType type{TextureType::TEX2D}; + Format format{Format::UNKNOWN}; + TextureUsage usage{TextureUsageBit::NONE}; + uint32_t width{0}; + uint32_t height{0}; + uint32_t depth{1}; + uint32_t size{0}; + uint32_t arrayLayer{1}; + uint32_t mipLevel{1}; + SampleCount samples{SampleCount::ONE}; + TextureFlags flags{TextureFlagBit::NONE}; + bool isPowerOf2{false}; + bool memoryless{false}; + GLenum glTarget{0}; + GLenum glInternalFmt{0}; + GLenum glFormat{0}; + GLenum glType{0}; + GLenum glUsage{0}; + GLint glSamples{0}; + GLuint glTexture{0}; + GLuint glRenderbuffer{0}; + GLenum glWrapS{0}; + GLenum glWrapT{0}; + GLenum glMinFilter{0}; + GLenum glMagFilter{0}; GLES2GPUSwapchain *swapchain{nullptr}; }; @@ -141,117 +141,117 @@ struct GLES2GPUSwapchain { #if CC_SWAPPY_ENABLED bool swappyEnabled{false}; #endif - EGLSurface eglSurface{EGL_NO_SURFACE}; - EGLint eglSwapInterval{0}; - GLuint glFramebuffer{0}; + EGLSurface eglSurface{EGL_NO_SURFACE}; + EGLint eglSwapInterval{0}; + GLuint glFramebuffer{0}; GLES2GPUTexture *gpuColorTexture{nullptr}; }; struct GLES2GPUSampler { - Filter minFilter = Filter::NONE; - Filter magFilter = Filter::NONE; - Filter mipFilter = Filter::NONE; - Address addressU = Address::CLAMP; - Address addressV = Address::CLAMP; - Address addressW = Address::CLAMP; - GLenum glMinFilter = 0; - GLenum glMagFilter = 0; - GLenum glWrapS = 0; - GLenum glWrapT = 0; - GLenum glWrapR = 0; + Filter minFilter = Filter::NONE; + Filter magFilter = Filter::NONE; + Filter mipFilter = Filter::NONE; + Address addressU = Address::CLAMP; + Address addressV = Address::CLAMP; + Address addressW = Address::CLAMP; + GLenum glMinFilter = 0; + GLenum glMagFilter = 0; + GLenum glWrapS = 0; + GLenum glWrapT = 0; + GLenum glWrapR = 0; }; struct GLES2GPUInput { - uint32_t binding = 0; + uint32_t binding = 0; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t stride = 0; - uint32_t count = 0; - uint32_t size = 0; - GLenum glType = 0; - GLint glLoc = -1; + Type type = Type::UNKNOWN; + uint32_t stride = 0; + uint32_t count = 0; + uint32_t size = 0; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES2GPUInputList = ccstd::vector; struct GLES2GPUUniform { - uint32_t binding = INVALID_BINDING; - ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t stride = 0; - uint32_t count = 0; - uint32_t size = 0; - uint32_t offset = 0; - GLenum glType = 0; - GLint glLoc = -1; + uint32_t binding = INVALID_BINDING; + ccstd::string name; + Type type = Type::UNKNOWN; + uint32_t stride = 0; + uint32_t count = 0; + uint32_t size = 0; + uint32_t offset = 0; + GLenum glType = 0; + GLint glLoc = -1; ccstd::vector buff; }; using GLES2GPUUniformList = ccstd::vector; struct GLES2GPUUniformBlock { - uint32_t set = 0; - uint32_t binding = 0; - uint32_t idx = 0; - ccstd::string name; - uint32_t size = 0; - GLES2GPUUniformList glUniforms; - GLES2GPUUniformList glActiveUniforms; + uint32_t set = 0; + uint32_t binding = 0; + uint32_t idx = 0; + ccstd::string name; + uint32_t size = 0; + GLES2GPUUniformList glUniforms; + GLES2GPUUniformList glActiveUniforms; ccstd::vector activeUniformIndices; }; using GLES2GPUUniformBlockList = ccstd::vector; struct GLES2GPUUniformSamplerTexture { - uint32_t set = 0; - uint32_t binding = 0; + uint32_t set = 0; + uint32_t binding = 0; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t count = 0U; + Type type = Type::UNKNOWN; + uint32_t count = 0U; ccstd::vector units; - GLenum glType = 0; - GLint glLoc = -1; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES2GPUUniformSamplerTextureList = ccstd::vector; struct GLES2GPUShaderStage { ShaderStageFlagBit type = ShaderStageFlagBit::NONE; - ccstd::string source; - GLuint glShader = 0; + ccstd::string source; + GLuint glShader = 0; }; using GLES2GPUShaderStageList = ccstd::vector; struct GLES2GPUShader { - ccstd::string name; - UniformBlockList blocks; - UniformSamplerTextureList samplerTextures; - UniformInputAttachmentList subpassInputs; - GLuint glProgram = 0; - GLES2GPUShaderStageList gpuStages; - GLES2GPUInputList glInputs; - GLES2GPUUniformBlockList glBlocks; + ccstd::string name; + UniformBlockList blocks; + UniformSamplerTextureList samplerTextures; + UniformInputAttachmentList subpassInputs; + GLuint glProgram = 0; + GLES2GPUShaderStageList gpuStages; + GLES2GPUInputList glInputs; + GLES2GPUUniformBlockList glBlocks; GLES2GPUUniformSamplerTextureList glSamplerTextures; }; struct GLES2GPUAttribute { ccstd::string name; - GLuint glBuffer = 0; - GLenum glType = 0; - uint32_t size = 0; - uint32_t count = 0; - uint32_t stride = 1; - uint32_t componentCount = 1; - bool isNormalized = false; - bool isInstanced = false; - uint32_t offset = 0; + GLuint glBuffer = 0; + GLenum glType = 0; + uint32_t size = 0; + uint32_t count = 0; + uint32_t stride = 1; + uint32_t componentCount = 1; + bool isNormalized = false; + bool isInstanced = false; + uint32_t offset = 0; }; using GLES2GPUAttributeList = ccstd::vector; struct GLES2GPUInputAssembler { - AttributeList attributes; - GLES2GPUBufferList gpuVertexBuffers; - GLES2GPUBuffer * gpuIndexBuffer = nullptr; - GLES2GPUBuffer * gpuIndirectBuffer = nullptr; - GLES2GPUAttributeList glAttribs; - GLenum glIndexType = 0; + AttributeList attributes; + GLES2GPUBufferList gpuVertexBuffers; + GLES2GPUBuffer *gpuIndexBuffer = nullptr; + GLES2GPUBuffer *gpuIndirectBuffer = nullptr; + GLES2GPUAttributeList glAttribs; + GLenum glIndexType = 0; ccstd::unordered_map glVAOs; }; @@ -261,9 +261,9 @@ struct GLES2GPURenderPass { uint32_t storeSubpass{SUBPASS_EXTERNAL}; }; - ColorAttachmentList colorAttachments; + ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; - SubpassInfoList subpasses; + SubpassInfoList subpasses; ccstd::vector statistics; // per attachment }; @@ -273,12 +273,12 @@ class GLES2GPUFramebuffer final { public: GLES2GPURenderPass *gpuRenderPass{nullptr}; GLES2GPUTextureList gpuColorTextures; - GLES2GPUTexture * gpuDepthStencilTexture{nullptr}; - bool usesFBF{false}; - uint32_t lodLevel{0}; + GLES2GPUTexture *gpuDepthStencilTexture{nullptr}; + bool usesFBF{false}; + uint32_t lodLevel{0}; struct GLFramebufferInfo { - GLuint glFramebuffer{0U}; + GLuint glFramebuffer{0U}; uint32_t width{UINT_MAX}; uint32_t height{UINT_MAX}; }; @@ -287,10 +287,10 @@ public: inline void initialize(GLES2GPUSwapchain *sc) { swapchain = sc; } inline void initialize(const GLFramebufferInfo &info) { _glFramebuffer = info.glFramebuffer; - _width = info.width; - _height = info.height; + _width = info.width; + _height = info.height; } - inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } + inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } inline uint32_t getWidth() const { return swapchain ? swapchain->gpuColorTexture->width : _width; } inline uint32_t getHeight() const { return swapchain ? swapchain->gpuColorTexture->height : _height; } @@ -299,7 +299,7 @@ public: GLES2GPUSwapchain *swapchain{nullptr}; private: - GLuint _glFramebuffer{0U}; + GLuint _glFramebuffer{0U}; uint32_t _width{0U}; uint32_t _height{0U}; }; @@ -308,7 +308,7 @@ public: GLFramebuffer framebuffer; // for blit-based manual resolving - GLbitfield resolveMask{0U}; + GLbitfield resolveMask{0U}; GLFramebuffer resolveFramebuffer; }; @@ -316,8 +316,8 @@ public: ccstd::vector instances; ccstd::vector uberColorAttachmentIndices; - uint32_t uberDepthStencil{INVALID_BINDING}; - Framebuffer uberInstance; + uint32_t uberDepthStencil{INVALID_BINDING}; + Framebuffer uberInstance; // the assumed shader output, may differ from actual subpass output // see Feature::INPUT_ATTACHMENT_BENEFIT for more @@ -327,11 +327,11 @@ public: struct GLES2GPUDescriptorSetLayout { DescriptorSetLayoutBindingList bindings; - ccstd::vector dynamicBindings; + ccstd::vector dynamicBindings; ccstd::vector bindingIndices; ccstd::vector descriptorIndices; - uint32_t descriptorCount = 0U; + uint32_t descriptorCount = 0U; }; using GLES2GPUDescriptorSetLayoutList = ccstd::vector; @@ -340,34 +340,34 @@ struct GLES2GPUPipelineLayout { // helper storages ccstd::vector> dynamicOffsetIndices; - ccstd::vector dynamicOffsetOffsets; - ccstd::vector dynamicOffsets; - uint32_t dynamicOffsetCount = 0U; + ccstd::vector dynamicOffsetOffsets; + ccstd::vector dynamicOffsets; + uint32_t dynamicOffsetCount = 0U; }; struct GLES2GPUPipelineState { - GLenum glPrimitive = GL_TRIANGLES; - GLES2GPUShader * gpuShader = nullptr; - RasterizerState rs; - DepthStencilState dss; - BlendState bs; - DynamicStateList dynamicStates; - GLES2GPUPipelineLayout *gpuLayout = nullptr; - GLES2GPURenderPass * gpuRenderPass = nullptr; + GLenum glPrimitive = GL_TRIANGLES; + GLES2GPUShader *gpuShader = nullptr; + RasterizerState rs; + DepthStencilState dss; + BlendState bs; + DynamicStateList dynamicStates; + GLES2GPUPipelineLayout *gpuLayout = nullptr; + GLES2GPURenderPass *gpuRenderPass = nullptr; GLES2GPUPipelineLayout *gpuPipelineLayout = nullptr; }; struct GLES2GPUDescriptor { - DescriptorType type = DescriptorType::UNKNOWN; - GLES2GPUBuffer * gpuBuffer = nullptr; + DescriptorType type = DescriptorType::UNKNOWN; + GLES2GPUBuffer *gpuBuffer = nullptr; GLES2GPUBufferView *gpuBufferView = nullptr; - GLES2GPUTexture * gpuTexture = nullptr; - GLES2GPUSampler * gpuSampler = nullptr; + GLES2GPUTexture *gpuTexture = nullptr; + GLES2GPUSampler *gpuSampler = nullptr; }; using GLES2GPUDescriptorList = ccstd::vector; struct GLES2GPUDescriptorSet { - GLES2GPUDescriptorList gpuDescriptors; + GLES2GPUDescriptorList gpuDescriptors; const ccstd::vector *descriptorIndices = nullptr; }; @@ -376,41 +376,41 @@ public: }; struct GLES2ObjectCache { - uint32_t subpassIdx = 0U; - GLES2GPURenderPass * gpuRenderPass = nullptr; - GLES2GPUFramebuffer * gpuFramebuffer = nullptr; - GLES2GPUPipelineState * gpuPipelineState = nullptr; + uint32_t subpassIdx = 0U; + GLES2GPURenderPass *gpuRenderPass = nullptr; + GLES2GPUFramebuffer *gpuFramebuffer = nullptr; + GLES2GPUPipelineState *gpuPipelineState = nullptr; GLES2GPUInputAssembler *gpuInputAssembler = nullptr; - GLenum glPrimitive = 0; - Rect renderArea; - ColorList clearColors; - float clearDepth = 1.F; - uint32_t clearStencil = 0U; + GLenum glPrimitive = 0; + Rect renderArea; + ColorList clearColors; + float clearDepth = 1.F; + uint32_t clearStencil = 0U; }; class GLES2GPUStateCache { public: - GLuint glArrayBuffer = 0; - GLuint glElementArrayBuffer = 0; - GLuint glUniformBuffer = 0; - GLuint glVAO = 0; - uint32_t texUint = 0; - ccstd::vector glTextures; - GLuint glProgram = 0; - ccstd::vector glEnabledAttribLocs; - ccstd::vector glCurrentAttribLocs; - GLuint glFramebuffer = 0; - GLuint glRenderbuffer = 0; - GLuint glReadFBO = 0; - Viewport viewport; - Rect scissor; - RasterizerState rs; - DepthStencilState dss; - BlendState bs; - bool isCullFaceEnabled = true; - bool isStencilTestEnabled = false; + GLuint glArrayBuffer = 0; + GLuint glElementArrayBuffer = 0; + GLuint glUniformBuffer = 0; + GLuint glVAO = 0; + uint32_t texUint = 0; + ccstd::vector glTextures; + GLuint glProgram = 0; + ccstd::vector glEnabledAttribLocs; + ccstd::vector glCurrentAttribLocs; + GLuint glFramebuffer = 0; + GLuint glRenderbuffer = 0; + GLuint glReadFBO = 0; + Viewport viewport; + Rect scissor; + RasterizerState rs; + DepthStencilState dss; + BlendState bs; + bool isCullFaceEnabled = true; + bool isStencilTestEnabled = false; ccstd::unordered_map texUnitCacheMap; - GLES2ObjectCache gfxStateCache; + GLES2ObjectCache gfxStateCache; void initialize(size_t texUnits, size_t vertexAttributes) { glTextures.resize(texUnits, 0U); @@ -419,32 +419,32 @@ public: } void reset() { - glArrayBuffer = 0; + glArrayBuffer = 0; glElementArrayBuffer = 0; - glUniformBuffer = 0; - glVAO = 0; - texUint = 0; + glUniformBuffer = 0; + glVAO = 0; + texUint = 0; glTextures.assign(glTextures.size(), 0U); glProgram = 0; glEnabledAttribLocs.assign(glEnabledAttribLocs.size(), false); glCurrentAttribLocs.assign(glCurrentAttribLocs.size(), false); - glFramebuffer = 0; - glReadFBO = 0; - isCullFaceEnabled = true; + glFramebuffer = 0; + glReadFBO = 0; + isCullFaceEnabled = true; isStencilTestEnabled = false; viewport = Viewport(); - scissor = Rect(); - rs = RasterizerState(); - dss = DepthStencilState(); - bs = BlendState(); + scissor = Rect(); + rs = RasterizerState(); + dss = DepthStencilState(); + bs = BlendState(); - gfxStateCache.gpuRenderPass = nullptr; - gfxStateCache.gpuFramebuffer = nullptr; - gfxStateCache.gpuPipelineState = nullptr; + gfxStateCache.gpuRenderPass = nullptr; + gfxStateCache.gpuFramebuffer = nullptr; + gfxStateCache.gpuPipelineState = nullptr; gfxStateCache.gpuInputAssembler = nullptr; - gfxStateCache.glPrimitive = 0U; - gfxStateCache.subpassIdx = 0U; + gfxStateCache.glPrimitive = 0U; + gfxStateCache.subpassIdx = 0U; } }; @@ -455,19 +455,19 @@ public: void draw(GLES2GPUTexture *gpuTextureSrc, GLES2GPUTexture *gpuTextureDst, const TextureBlit *regions, uint32_t count, Filter filter); private: - GLES2GPUShader _gpuShader; + GLES2GPUShader _gpuShader; GLES2GPUDescriptorSetLayout _gpuDescriptorSetLayout; - GLES2GPUPipelineLayout _gpuPipelineLayout; - GLES2GPUPipelineState _gpuPipelineState; + GLES2GPUPipelineLayout _gpuPipelineLayout; + GLES2GPUPipelineState _gpuPipelineState; - GLES2GPUBuffer _gpuVertexBuffer; + GLES2GPUBuffer _gpuVertexBuffer; GLES2GPUInputAssembler _gpuInputAssembler; - GLES2GPUSampler _gpuPointSampler; - GLES2GPUSampler _gpuLinearSampler; - GLES2GPUBuffer _gpuUniformBuffer; - GLES2GPUDescriptorSet _gpuDescriptorSet; - DrawInfo _drawInfo; - float _uniformBuffer[8]; + GLES2GPUSampler _gpuPointSampler; + GLES2GPUSampler _gpuLinearSampler; + GLES2GPUBuffer _gpuUniformBuffer; + GLES2GPUDescriptorSet _gpuDescriptorSet; + DrawInfo _drawInfo; + float _uniformBuffer[8]; }; class GLES2GPUFramebufferCacheMap final { @@ -475,9 +475,9 @@ public: explicit GLES2GPUFramebufferCacheMap(GLES2GPUStateCache *cache) : _cache(cache) {} void registerExternal(GLuint glFramebuffer, const GLES2GPUTexture *gpuTexture) { - bool isTexture = gpuTexture->glTexture; + bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; if (!cacheMap[glResource].glFramebuffer) { cacheMap[glResource] = {glFramebuffer, true}; @@ -500,9 +500,9 @@ public: } GLuint getFramebufferFromTexture(const GLES2GPUTexture *gpuTexture) { - bool isTexture = gpuTexture->glTexture; + bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; if (!cacheMap.count(glResource)) { GLuint glFramebuffer = 0U; @@ -540,9 +540,9 @@ public: } void onTextureDestroy(const GLES2GPUTexture *gpuTexture) { - bool isTexture = gpuTexture->glTexture; + bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; if (cacheMap.count(glResource)) { GLuint glFramebuffer = cacheMap[glResource].glFramebuffer; @@ -562,7 +562,7 @@ private: struct FramebufferRecord { GLuint glFramebuffer{0}; - bool isExternal{false}; + bool isExternal{false}; }; using CacheMap = ccstd::unordered_map; CacheMap _renderbufferMap; // renderbuffer -> framebuffer diff --git a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp index 46934b65ef..e7b8f288ff 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2InputAssembler.cpp @@ -42,11 +42,11 @@ GLES2InputAssembler::~GLES2InputAssembler() { } void GLES2InputAssembler::doInit(const InputAssemblerInfo &info) { - _gpuInputAssembler = ccnew GLES2GPUInputAssembler; + _gpuInputAssembler = ccnew GLES2GPUInputAssembler; _gpuInputAssembler->attributes = _attributes; _gpuInputAssembler->gpuVertexBuffers.resize(_vertexBuffers.size()); for (size_t i = 0; i < _gpuInputAssembler->gpuVertexBuffers.size(); ++i) { - auto *vb = static_cast(_vertexBuffers[i]); + auto *vb = static_cast(_vertexBuffers[i]); _gpuInputAssembler->gpuVertexBuffers[i] = vb->gpuBuffer(); } if (info.indexBuffer) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.cpp b/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.cpp index 7ae6e42419..e7a48c21e2 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PipelineLayout.cpp @@ -48,10 +48,10 @@ void GLES2PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { uint32_t offset = 0U; _gpuPipelineLayout->dynamicOffsetIndices.resize(_setLayouts.size()); for (uint32_t i = 0U; i < _setLayouts.size(); i++) { - DescriptorSetLayout * setLayout = _setLayouts[i]; + DescriptorSetLayout *setLayout = _setLayouts[i]; GLES2GPUDescriptorSetLayout *gpuSetLayout = static_cast(setLayout)->gpuDescriptorSetLayout(); - uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); - ccstd::vector & indices = _gpuPipelineLayout->dynamicOffsetIndices[i]; + uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); + ccstd::vector &indices = _gpuPipelineLayout->dynamicOffsetIndices[i]; indices.assign(setLayout->getBindingIndices().size(), -1); for (uint32_t j = 0U; j < dynamicCount; j++) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2PipelineState.cpp b/native/cocos/renderer/gfx-gles2/GLES2PipelineState.cpp index 24c066e46a..10d4bb7549 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PipelineState.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PipelineState.cpp @@ -60,12 +60,12 @@ GLES2PipelineState::~GLES2PipelineState() { } void GLES2PipelineState::doInit(const PipelineStateInfo & /*info*/) { - _gpuPipelineState = ccnew GLES2GPUPipelineState; - _gpuPipelineState->glPrimitive = GLE_S2_PRIMITIVES[static_cast(_primitive)]; - _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); - _gpuPipelineState->rs = _rasterizerState; - _gpuPipelineState->dss = _depthStencilState; - _gpuPipelineState->bs = _blendState; + _gpuPipelineState = ccnew GLES2GPUPipelineState; + _gpuPipelineState->glPrimitive = GLE_S2_PRIMITIVES[static_cast(_primitive)]; + _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _gpuPipelineState->rs = _rasterizerState; + _gpuPipelineState->dss = _depthStencilState; + _gpuPipelineState->bs = _blendState; _gpuPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); if (_renderPass) _gpuPipelineState->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); diff --git a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp index f2094cc36a..401b32afff 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.cpp @@ -63,13 +63,13 @@ void GLES2PrimaryCommandBuffer::end() { void GLES2PrimaryCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const * /*secondaryCBs*/, uint32_t /*secondaryCBCount*/) { _curSubpassIdx = 0U; - GLES2GPURenderPass * gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); + GLES2GPURenderPass *gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); GLES2GPUFramebuffer *gpuFramebuffer = static_cast(fbo)->gpuFBO(); cmdFuncGLES2BeginRenderPass(GLES2Device::getInstance(), _curSubpassIdx, gpuRenderPass, gpuFramebuffer, &renderArea, colors, depth, stencil); _curDynamicStates.viewport = {renderArea.x, renderArea.y, renderArea.width, renderArea.height}; - _curDynamicStates.scissor = renderArea; + _curDynamicStates.scissor = renderArea; } void GLES2PrimaryCommandBuffer::endRenderPass() { @@ -85,7 +85,7 @@ void GLES2PrimaryCommandBuffer::draw(const DrawInfo &info) { CC_PROFILE(GLES2PrimaryCommandBufferDraw); if (_isStateInvalid) { ccstd::vector &dynamicOffsetOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsetOffsets; - ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; + ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; for (size_t i = 0U; i < _curDynamicOffsets.size(); i++) { size_t count = dynamicOffsetOffsets[i + 1] - dynamicOffsetOffsets[i]; // CC_ASSERT(_curDynamicOffsets[i].size() >= count); @@ -183,7 +183,7 @@ void GLES2PrimaryCommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t void GLES2PrimaryCommandBuffer::bindStates() { if (_curGPUPipelineState) { ccstd::vector &dynamicOffsetOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsetOffsets; - ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; + ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; for (size_t i = 0U; i < _curDynamicOffsets.size(); i++) { size_t count = dynamicOffsetOffsets[i + 1] - dynamicOffsetOffsets[i]; // CC_ASSERT(_curDynamicOffsets[i].size() >= count); diff --git a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp index 8638fc8fc1..e9ab718100 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp @@ -41,10 +41,10 @@ GLES2RenderPass::~GLES2RenderPass() { } void GLES2RenderPass::doInit(const RenderPassInfo & /*info*/) { - _gpuRenderPass = ccnew GLES2GPURenderPass; - _gpuRenderPass->colorAttachments = _colorAttachments; + _gpuRenderPass = ccnew GLES2GPURenderPass; + _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; - _gpuRenderPass->subpasses = _subpasses; + _gpuRenderPass->subpasses = _subpasses; // assign a dummy subpass if not specified uint32_t colorCount = utils::toUint(_gpuRenderPass->colorAttachments.size()); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Shader.cpp b/native/cocos/renderer/gfx-gles2/GLES2Shader.cpp index 386930ec47..fe7bad591e 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Shader.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Shader.cpp @@ -41,11 +41,11 @@ GLES2Shader::~GLES2Shader() { } void GLES2Shader::doInit(const ShaderInfo & /*info*/) { - _gpuShader = ccnew GLES2GPUShader; - _gpuShader->name = _name; - _gpuShader->blocks = _blocks; + _gpuShader = ccnew GLES2GPUShader; + _gpuShader->name = _name; + _gpuShader->blocks = _blocks; _gpuShader->samplerTextures = _samplerTextures; - _gpuShader->subpassInputs = _subpassInputs; + _gpuShader->subpassInputs = _subpassInputs; for (const auto &stage : _stages) { _gpuShader->gpuStages.push_back({stage.stage, stage.source}); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp index e2bd89f820..987ad6b5bf 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp @@ -53,8 +53,8 @@ GLES2Swapchain::~GLES2Swapchain() { void GLES2Swapchain::doInit(const SwapchainInfo &info) { const auto *context = GLES2Device::getInstance()->context(); - _gpuSwapchain = ccnew GLES2GPUSwapchain; - auto window = reinterpret_cast(info.windowHandle); //NOLINT[readability-qualified-auto] + _gpuSwapchain = ccnew GLES2GPUSwapchain; + auto window = reinterpret_cast(info.windowHandle); //NOLINT[readability-qualified-auto] #if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS EGLint nFmt; @@ -64,9 +64,9 @@ void GLES2Swapchain::doInit(const SwapchainInfo &info) { } #if CC_SWAPPY_ENABLED - bool enableSwappy = true; - auto* platform = static_cast(cc::BasePlatform::getPlatform()); - enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); + bool enableSwappy = true; + auto *platform = static_cast(cc::BasePlatform::getPlatform()); + enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); int32_t fps = cc::BasePlatform::getPlatform()->getFps(); if (enableSwappy) { if (!fps) @@ -81,7 +81,7 @@ void GLES2Swapchain::doInit(const SwapchainInfo &info) { #endif - auto width = static_cast(info.width); + auto width = static_cast(info.width); auto height = static_cast(info.height); #if CC_PLATFORM == CC_PLATFORM_ANDROID @@ -109,14 +109,14 @@ void GLES2Swapchain::doInit(const SwapchainInfo &info) { ///////////////////// Texture Creation ///////////////////// - _colorTexture = ccnew GLES2Texture; + _colorTexture = ccnew GLES2Texture; _depthStencilTexture = ccnew GLES2Texture; SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = Format::RGBA8; - textureInfo.width = info.width; - textureInfo.height = info.height; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; initTexture(textureInfo, _colorTexture); textureInfo.format = Format::DEPTH_STENCIL; @@ -161,7 +161,7 @@ void GLES2Swapchain::doDestroySurface() { void GLES2Swapchain::doCreateSurface(void *windowHandle) { auto *context = GLES2Device::getInstance()->context(); - auto window = reinterpret_cast(windowHandle); //NOLINT [readability-qualified-auto] + auto window = reinterpret_cast(windowHandle); //NOLINT [readability-qualified-auto] EGLint nFmt = 0; if (eglGetConfigAttrib(context->eglDisplay, context->eglConfig, EGL_NATIVE_VISUAL_ID, &nFmt) == EGL_FALSE) { @@ -169,7 +169,7 @@ void GLES2Swapchain::doCreateSurface(void *windowHandle) { return; } - auto width = static_cast(_colorTexture->getWidth()); + auto width = static_cast(_colorTexture->getWidth()); auto height = static_cast(_colorTexture->getHeight()); CC_UNUSED_PARAM(width); CC_UNUSED_PARAM(height); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp index 8447d3c310..5cdc09da51 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Texture.cpp @@ -43,20 +43,20 @@ GLES2Texture::~GLES2Texture() { } void GLES2Texture::doInit(const TextureInfo & /*info*/) { - _gpuTexture = ccnew GLES2GPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew GLES2GPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; - _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; - _gpuTexture->flags = _info.flags; - _gpuTexture->size = _size; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); - _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); + _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES2CreateTexture(GLES2Device::getInstance(), _gpuTexture); @@ -90,9 +90,9 @@ void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { GLES2Device::getInstance()->getMemoryStatus().textureSize -= _size; CC_PROFILE_MEMORY_DEC(Texture, _size); } - _gpuTexture->width = width; - _gpuTexture->height = height; - _gpuTexture->size = size; + _gpuTexture->width = width; + _gpuTexture->height = height; + _gpuTexture->size = size; _gpuTexture->mipLevel = _info.levelCount; cmdFuncGLES2ResizeTexture(GLES2Device::getInstance(), _gpuTexture); @@ -107,20 +107,20 @@ void GLES2Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { ///////////////////////////// Swapchain Specific ///////////////////////////// void GLES2Texture::doInit(const SwapchainTextureInfo & /*info*/) { - _gpuTexture = ccnew GLES2GPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew GLES2GPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; - _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; - _gpuTexture->flags = _info.flags; - _gpuTexture->size = _size; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; _gpuTexture->memoryless = true; - _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles2/GLES2Wrangler.cpp b/native/cocos/renderer/gfx-gles2/GLES2Wrangler.cpp index 71770476e4..5994119902 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Wrangler.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Wrangler.cpp @@ -29,11 +29,11 @@ #define WIN32_LEAN_AND_MEAN 1 #include -static HMODULE libegl = NULL; +static HMODULE libegl = NULL; static HMODULE libgles = NULL; bool gles2wOpen() { - libegl = LoadLibraryA("libEGL.dll"); + libegl = LoadLibraryA("libEGL.dll"); libgles = LoadLibraryA("libGLESv2.dll"); return (libegl && libgles); } @@ -60,19 +60,19 @@ void *gles2wLoad(const char *proc) { return res; } #elif defined(__EMSCRIPTEN__) -bool gles2wOpen() { return true; } -bool gles2wClose() { return true; } +bool gles2wOpen() { return true; } +bool gles2wClose() { return true; } void *gles2wLoad(const char *proc) { return (void *)eglGetProcAddress(proc); } #else #include -static void *libegl = nullptr; +static void *libegl = nullptr; static void *libgles = nullptr; bool gles2wOpen() { - libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); + libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); #if __OHOS__ libgles = dlopen("libGLESv3.so", RTLD_LAZY | RTLD_GLOBAL); #else diff --git a/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp index 7c53ab6641..ef246f10e5 100644 --- a/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp +++ b/native/cocos/renderer/gfx-gles2/states/GLES2Sampler.cpp @@ -33,13 +33,13 @@ namespace gfx { GLES2Sampler::GLES2Sampler(const SamplerInfo &info) : Sampler(info) { _typedID = generateObjectID(); - _gpuSampler = ccnew GLES2GPUSampler; + _gpuSampler = ccnew GLES2GPUSampler; _gpuSampler->minFilter = _info.minFilter; _gpuSampler->magFilter = _info.magFilter; _gpuSampler->mipFilter = _info.mipFilter; - _gpuSampler->addressU = _info.addressU; - _gpuSampler->addressV = _info.addressV; - _gpuSampler->addressW = _info.addressW; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; cmdFuncGLES2CreateSampler(GLES2Device::getInstance(), _gpuSampler); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Buffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3Buffer.cpp index 0e13cda487..195193d129 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Buffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Buffer.cpp @@ -42,12 +42,12 @@ GLES3Buffer::~GLES3Buffer() { } void GLES3Buffer::doInit(const BufferInfo & /*info*/) { - _gpuBuffer = ccnew GLES3GPUBuffer; - _gpuBuffer->usage = _usage; + _gpuBuffer = ccnew GLES3GPUBuffer; + _gpuBuffer->usage = _usage; _gpuBuffer->memUsage = _memUsage; - _gpuBuffer->size = _size; - _gpuBuffer->stride = _stride; - _gpuBuffer->count = _count; + _gpuBuffer->size = _size; + _gpuBuffer->stride = _stride; + _gpuBuffer->count = _count; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { _gpuBuffer->indirects.resize(_count); @@ -59,17 +59,17 @@ void GLES3Buffer::doInit(const BufferInfo & /*info*/) { } void GLES3Buffer::doInit(const BufferViewInfo &info) { - auto *buffer = static_cast(info.buffer); - _gpuBuffer = ccnew GLES3GPUBuffer; - _gpuBuffer->usage = _usage; - _gpuBuffer->memUsage = _memUsage; - _gpuBuffer->size = _size; - _gpuBuffer->stride = _stride; - _gpuBuffer->count = _count; - _gpuBuffer->glTarget = buffer->_gpuBuffer->glTarget; - _gpuBuffer->glBuffer = buffer->_gpuBuffer->glBuffer; - _gpuBuffer->glOffset = info.offset; - _gpuBuffer->buffer = buffer->_gpuBuffer->buffer; + auto *buffer = static_cast(info.buffer); + _gpuBuffer = ccnew GLES3GPUBuffer; + _gpuBuffer->usage = _usage; + _gpuBuffer->memUsage = _memUsage; + _gpuBuffer->size = _size; + _gpuBuffer->stride = _stride; + _gpuBuffer->count = _count; + _gpuBuffer->glTarget = buffer->_gpuBuffer->glTarget; + _gpuBuffer->glBuffer = buffer->_gpuBuffer->glBuffer; + _gpuBuffer->glOffset = info.offset; + _gpuBuffer->buffer = buffer->_gpuBuffer->buffer; _gpuBuffer->indirects = buffer->_gpuBuffer->indirects; } @@ -89,7 +89,7 @@ void GLES3Buffer::doResize(uint32_t size, uint32_t count) { GLES3Device::getInstance()->getMemoryStatus().bufferSize -= _size; CC_PROFILE_MEMORY_DEC(Buffer, _size); - _gpuBuffer->size = size; + _gpuBuffer->size = size; _gpuBuffer->count = count; cmdFuncGLES3ResizeBuffer(GLES3Device::getInstance(), _gpuBuffer); diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index 3d04777917..f2aeaeeb5f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -51,7 +51,7 @@ GLES3CommandBuffer::~GLES3CommandBuffer() { } void GLES3CommandBuffer::doInit(const CommandBufferInfo & /*info*/) { - _cmdAllocator = ccnew GLES3GPUCommandAllocator; + _cmdAllocator = ccnew GLES3GPUCommandAllocator; _curCmdPackage = ccnew GLES3CmdPackage; size_t setCount = GLES3Device::getInstance()->bindingMappingInfo().setIndices.size(); @@ -113,19 +113,19 @@ void GLES3CommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb _curSubpassIdx = 0U; GLES3CmdBeginRenderPass *cmd = _cmdAllocator->beginRenderPassCmdPool.alloc(); - cmd->subpassIdx = _curSubpassIdx; - cmd->gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); - cmd->gpuFBO = static_cast(fbo)->gpuFBO(); - cmd->renderArea = renderArea; - size_t numClearColors = cmd->gpuRenderPass->colorAttachments.size(); + cmd->subpassIdx = _curSubpassIdx; + cmd->gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); + cmd->gpuFBO = static_cast(fbo)->gpuFBO(); + cmd->renderArea = renderArea; + size_t numClearColors = cmd->gpuRenderPass->colorAttachments.size(); memcpy(cmd->clearColors, colors, numClearColors * sizeof(Color)); - cmd->clearDepth = depth; + cmd->clearDepth = depth; cmd->clearStencil = stencil; _curCmdPackage->beginRenderPassCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); _curDynamicStates.viewport = {renderArea.x, renderArea.y, renderArea.width, renderArea.height}; - _curDynamicStates.scissor = renderArea; + _curDynamicStates.scissor = renderArea; } void GLES3CommandBuffer::endRenderPass() { @@ -135,7 +135,7 @@ void GLES3CommandBuffer::endRenderPass() { void GLES3CommandBuffer::nextSubpass() { _curCmdPackage->cmds.push(GLESCmdType::END_RENDER_PASS); GLES3CmdBeginRenderPass *cmd = _cmdAllocator->beginRenderPassCmdPool.alloc(); - cmd->subpassIdx = ++_curSubpassIdx; + cmd->subpassIdx = ++_curSubpassIdx; _curCmdPackage->beginRenderPassCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BEGIN_RENDER_PASS); } @@ -144,7 +144,7 @@ void GLES3CommandBuffer::bindPipelineState(PipelineState *pso) { GLES3GPUPipelineState *gpuPipelineState = static_cast(pso)->gpuPipelineState(); if (_curGPUPipelineState != gpuPipelineState) { _curGPUPipelineState = gpuPipelineState; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -154,7 +154,7 @@ void GLES3CommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descript GLES3GPUDescriptorSet *gpuDescriptorSet = static_cast(descriptorSet)->gpuDescriptorSet(); if (_curGPUDescriptorSets[set] != gpuDescriptorSet) { _curGPUDescriptorSets[set] = gpuDescriptorSet; - _isStateInvalid = true; + _isStateInvalid = true; } if (dynamicOffsetCount) { _curDynamicOffsets[set].assign(dynamicOffsets, dynamicOffsets + dynamicOffsetCount); @@ -167,7 +167,7 @@ void GLES3CommandBuffer::bindDescriptorSet(uint32_t set, DescriptorSet *descript void GLES3CommandBuffer::bindInputAssembler(InputAssembler *ia) { _curGPUInputAssember = static_cast(ia)->gpuInputAssembler(); - _isStateInvalid = true; + _isStateInvalid = true; } void GLES3CommandBuffer::setViewport(const Viewport &vp) { @@ -178,7 +178,7 @@ void GLES3CommandBuffer::setViewport(const Viewport &vp) { math::IsNotEqualF(_curDynamicStates.viewport.minDepth, vp.minDepth) || math::IsNotEqualF(_curDynamicStates.viewport.maxDepth, vp.maxDepth)) { _curDynamicStates.viewport = vp; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -188,14 +188,14 @@ void GLES3CommandBuffer::setScissor(const Rect &rect) { (_curDynamicStates.scissor.width != rect.width) || (_curDynamicStates.scissor.height != rect.height)) { _curDynamicStates.scissor = rect; - _isStateInvalid = true; + _isStateInvalid = true; } } void GLES3CommandBuffer::setLineWidth(float width) { if (math::IsNotEqualF(_curDynamicStates.lineWidth, width)) { _curDynamicStates.lineWidth = width; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -204,9 +204,9 @@ void GLES3CommandBuffer::setDepthBias(float constant, float clamp, float slope) math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; - _curDynamicStates.depthBiasClamp = clamp; - _curDynamicStates.depthBiasSlope = slope; - _isStateInvalid = true; + _curDynamicStates.depthBiasClamp = clamp; + _curDynamicStates.depthBiasSlope = slope; + _isStateInvalid = true; } } @@ -219,7 +219,7 @@ void GLES3CommandBuffer::setBlendConstants(const Color &constants) { _curDynamicStates.blendConstant.y = constants.y; _curDynamicStates.blendConstant.z = constants.z; _curDynamicStates.blendConstant.w = constants.w; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -228,7 +228,7 @@ void GLES3CommandBuffer::setDepthBound(float minBounds, float maxBounds) { math::IsNotEqualF(_curDynamicStates.depthMaxBounds, maxBounds)) { _curDynamicStates.depthMinBounds = minBounds; _curDynamicStates.depthMaxBounds = maxBounds; - _isStateInvalid = true; + _isStateInvalid = true; } } @@ -236,7 +236,7 @@ void GLES3CommandBuffer::setStencilWriteMask(StencilFace face, uint32_t mask) { auto update = [&](DynamicStencilStates &stencilState) { if (stencilState.writeMask != mask) { stencilState.writeMask = mask; - _isStateInvalid = true; + _isStateInvalid = true; } }; if (hasFlag(face, StencilFace::FRONT)) update(_curDynamicStates.stencilStatesFront); @@ -247,9 +247,9 @@ void GLES3CommandBuffer::setStencilCompareMask(StencilFace face, uint32_t ref, u auto update = [&](DynamicStencilStates &stencilState) { if ((stencilState.reference != ref) || (stencilState.compareMask != mask)) { - stencilState.reference = ref; + stencilState.reference = ref; stencilState.compareMask = mask; - _isStateInvalid = true; + _isStateInvalid = true; } }; if (hasFlag(face, StencilFace::FRONT)) update(_curDynamicStates.stencilStatesFront); @@ -263,7 +263,7 @@ void GLES3CommandBuffer::draw(const DrawInfo &info) { } GLES3CmdDraw *cmd = _cmdAllocator->drawCmdPool.alloc(); - cmd->drawInfo = info; + cmd->drawInfo = info; _curCmdPackage->drawCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::DRAW); @@ -291,9 +291,9 @@ void GLES3CommandBuffer::updateBuffer(Buffer *buff, const void *data, uint32_t s GLES3GPUBuffer *gpuBuffer = static_cast(buff)->gpuBuffer(); if (gpuBuffer) { GLES3CmdUpdateBuffer *cmd = _cmdAllocator->updateBufferCmdPool.alloc(); - cmd->gpuBuffer = gpuBuffer; - cmd->size = size; - cmd->buffer = static_cast(data); + cmd->gpuBuffer = gpuBuffer; + cmd->size = size; + cmd->buffer = static_cast(data); _curCmdPackage->updateBufferCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::UPDATE_BUFFER); @@ -305,8 +305,8 @@ void GLES3CommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c if (srcTexture) cmd->gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); if (dstTexture) cmd->gpuTextureDst = static_cast(dstTexture)->gpuTexture(); cmd->regions = regions; - cmd->count = count; - cmd->filter = filter; + cmd->count = count; + cmd->filter = filter; _curCmdPackage->blitTextureCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BLIT_TEXTURE); @@ -316,10 +316,10 @@ void GLES3CommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex GLES3GPUTexture *gpuTexture = static_cast(texture)->gpuTexture(); if (gpuTexture) { GLES3CmdCopyBufferToTexture *cmd = _cmdAllocator->copyBufferToTextureCmdPool.alloc(); - cmd->gpuTexture = gpuTexture; - cmd->regions = regions; - cmd->count = count; - cmd->buffers = buffers; + cmd->gpuTexture = gpuTexture; + cmd->regions = regions; + cmd->count = count; + cmd->buffers = buffers; _curCmdPackage->copyBufferToTextureCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::COPY_BUFFER_TO_TEXTURE); @@ -330,7 +330,7 @@ void GLES3CommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) CC_ASSERT(false); // Command 'execute' must be recorded in primary command buffers. for (uint32_t i = 0; i < count; ++i) { - auto * cmdBuff = static_cast(cmdBuffs[i]); + auto *cmdBuff = static_cast(cmdBuffs[i]); GLES3CmdPackage *cmdPackage = cmdBuff->_pendingPackages.front(); for (uint32_t j = 0; j < cmdPackage->beginRenderPassCmds.size(); ++j) { @@ -391,9 +391,9 @@ void GLES3CommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) void GLES3CommandBuffer::bindStates() { GLES3CmdBindStates *cmd = _cmdAllocator->bindStatesCmdPool.alloc(); - cmd->gpuPipelineState = _curGPUPipelineState; - cmd->gpuInputAssembler = _curGPUInputAssember; - cmd->gpuDescriptorSets = _curGPUDescriptorSets; + cmd->gpuPipelineState = _curGPUPipelineState; + cmd->gpuInputAssembler = _curGPUInputAssember; + cmd->gpuDescriptorSets = _curGPUDescriptorSets; if (_curGPUPipelineState) { ccstd::vector &dynamicOffsetOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsetOffsets; @@ -435,52 +435,52 @@ void GLES3CommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Te const auto *gpuBarrier = static_cast(barrier)->gpuBarrier(); - GLES3CmdBarrier *cmd = _cmdAllocator->barrierCmdPool.alloc(); - cmd->barriers = gpuBarrier->glBarriers; + GLES3CmdBarrier *cmd = _cmdAllocator->barrierCmdPool.alloc(); + cmd->barriers = gpuBarrier->glBarriers; cmd->barriersByRegion = gpuBarrier->glBarriersByRegion; _curCmdPackage->barrierCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::BARRIER); } void GLES3CommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { - auto * gles3QueryPool = static_cast(queryPool); - GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); - cmd->queryPool = gles3QueryPool; - cmd->type = GLES3QueryType::BEGIN; - cmd->id = id; + auto *gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::BEGIN; + cmd->id = id; _curCmdPackage->queryCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::QUERY); } void GLES3CommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { - auto * gles3QueryPool = static_cast(queryPool); - GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); - cmd->queryPool = gles3QueryPool; - cmd->type = GLES3QueryType::END; - cmd->id = id; + auto *gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::END; + cmd->id = id; _curCmdPackage->queryCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::QUERY); } void GLES3CommandBuffer::resetQueryPool(QueryPool *queryPool) { - auto * gles3QueryPool = static_cast(queryPool); - GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); - cmd->queryPool = gles3QueryPool; - cmd->type = GLES3QueryType::RESET; - cmd->id = 0; + auto *gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::RESET; + cmd->id = 0; _curCmdPackage->queryCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::QUERY); } void GLES3CommandBuffer::getQueryPoolResults(QueryPool *queryPool) { - auto * gles3QueryPool = static_cast(queryPool); - GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); - cmd->queryPool = gles3QueryPool; - cmd->type = GLES3QueryType::GET_RESULTS; - cmd->id = 0; + auto *gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::GET_RESULTS; + cmd->id = 0; _curCmdPackage->queryCmds.push(cmd); _curCmdPackage->cmds.push(GLESCmdType::QUERY); diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index d6a31a8b11..0d14fd8dce 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -81,16 +81,16 @@ protected: virtual void bindStates(); - GLES3GPUCommandAllocator * _cmdAllocator = nullptr; - GLES3CmdPackage * _curCmdPackage = nullptr; + GLES3GPUCommandAllocator *_cmdAllocator = nullptr; + GLES3CmdPackage *_curCmdPackage = nullptr; ccstd::queue _pendingPackages, _freePackages; - uint32_t _curSubpassIdx = 0U; - GLES3GPUPipelineState * _curGPUPipelineState = nullptr; - GLES3GPUInputAssembler * _curGPUInputAssember = nullptr; + uint32_t _curSubpassIdx = 0U; + GLES3GPUPipelineState *_curGPUPipelineState = nullptr; + GLES3GPUInputAssembler *_curGPUInputAssember = nullptr; ccstd::vector _curGPUDescriptorSets; ccstd::vector> _curDynamicOffsets; - DynamicStates _curDynamicStates; + DynamicStates _curDynamicStates; bool _isStateInvalid = false; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 2a975c94ca..4c05bebb79 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -588,7 +588,7 @@ const GLint GL_SAMPLE_COUNT[] = { } // namespace void cmdFuncGLES3CreateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { - GLenum glUsage = hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW; + GLenum glUsage = hasFlag(gpuBuffer->memUsage, MemoryUsageBit::HOST) ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW; GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; if (hasFlag(gpuBuffer->usage, BufferUsageBit::VERTEX)) { @@ -659,7 +659,7 @@ void cmdFuncGLES3CreateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { gpuBuffer->glTarget = GL_NONE; } else if ((hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_DST)) || (hasFlag(gpuBuffer->usage, BufferUsageBit::TRANSFER_SRC))) { - gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); + gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); gpuBuffer->glTarget = GL_NONE; } else { CC_ASSERT(false); @@ -701,7 +701,7 @@ void cmdFuncGLES3DestroyBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { if (ubo[i] == gpuBuffer->glBuffer) { GL_CHECK(glBindBufferBase(GL_UNIFORM_BUFFER, i, 0)); device->stateCache()->glUniformBuffer = 0; - ubo[i] = 0; + ubo[i] = 0; } } if (device->stateCache()->glUniformBuffer == gpuBuffer->glBuffer) { @@ -715,7 +715,7 @@ void cmdFuncGLES3DestroyBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { if (ssbo[i] == gpuBuffer->glBuffer) { GL_CHECK(glBindBufferBase(GL_UNIFORM_BUFFER, i, 0)); device->stateCache()->glShaderStorageBuffer = 0; - ssbo[i] = 0; + ssbo[i] = 0; } } if (device->stateCache()->glShaderStorageBuffer == gpuBuffer->glBuffer) { @@ -791,7 +791,7 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { if (gpuBuffer->buffer) { CC_FREE(gpuBuffer->buffer); } - gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); + gpuBuffer->buffer = static_cast(CC_MALLOC(gpuBuffer->size)); gpuBuffer->glTarget = GL_NONE; } else { CC_ASSERT(false); @@ -803,8 +803,8 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) static ccstd::vector supportedSampleCounts; gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); - gpuTexture->glFormat = mapGLFormat(gpuTexture->format); - gpuTexture->glType = formatToGLType(gpuTexture->format); + gpuTexture->glFormat = mapGLFormat(gpuTexture->format); + gpuTexture->glType = formatToGLType(gpuTexture->format); if (gpuTexture->samples > SampleCount::ONE) { GLint supportedSampleCountCount = 0; @@ -999,26 +999,26 @@ GLuint GLES3GPUSampler::getGLSampler(uint16_t minLod, uint16_t maxLod) { // NOLINTNEXTLINE(google-readability-function-size, readability-function-size) void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { - GLenum glShaderStage = 0; + GLenum glShaderStage = 0; ccstd::string shaderStageStr; - GLint status; + GLint status; for (size_t i = 0; i < gpuShader->gpuStages.size(); ++i) { GLES3GPUShaderStage &gpuStage = gpuShader->gpuStages[i]; switch (gpuStage.type) { case ShaderStageFlagBit::VERTEX: { - glShaderStage = GL_VERTEX_SHADER; + glShaderStage = GL_VERTEX_SHADER; shaderStageStr = "Vertex Shader"; break; } case ShaderStageFlagBit::FRAGMENT: { - glShaderStage = GL_FRAGMENT_SHADER; + glShaderStage = GL_FRAGMENT_SHADER; shaderStageStr = "Fragment Shader"; break; } case ShaderStageFlagBit::COMPUTE: { - glShaderStage = GL_COMPUTE_SHADER; + glShaderStage = GL_COMPUTE_SHADER; shaderStageStr = "Compute Shader"; break; } @@ -1028,9 +1028,9 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { } } GL_CHECK(gpuStage.glShader = glCreateShader(glShaderStage)); - uint32_t version = device->constantRegistry()->glMinorVersion ? 310 : 300; + uint32_t version = device->constantRegistry()->glMinorVersion ? 310 : 300; ccstd::string shaderSource = StringUtil::format("#version %u es\n", version) + gpuStage.source; - const char * source = shaderSource.c_str(); + const char *source = shaderSource.c_str(); GL_CHECK(glShaderSource(gpuStage.glShader, 1, (const GLchar **)&source, nullptr)); GL_CHECK(glCompileShader(gpuStage.glShader)); @@ -1091,14 +1091,14 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { CC_LOG_INFO("Shader '%s' compilation succeeded.", gpuShader->name.c_str()); GLint attrMaxLength = 0; - GLint attrCount = 0; + GLint attrCount = 0; GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &attrMaxLength)); GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_ACTIVE_ATTRIBUTES, &attrCount)); - GLchar glName[256]; + GLchar glName[256]; GLsizei glLength; GLsizei glSize; - GLenum glType; + GLenum glType; gpuShader->glInputs.resize(attrCount); for (GLint i = 0; i < attrCount; ++i) { @@ -1113,11 +1113,11 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { GL_CHECK(gpuInput.glLoc = glGetAttribLocation(gpuShader->glProgram, glName)); gpuInput.binding = gpuInput.glLoc; - gpuInput.name = glName; - gpuInput.type = mapType(glType); - gpuInput.count = glSize; - gpuInput.size = gpuInput.stride * gpuInput.count; - gpuInput.glType = glType; + gpuInput.name = glName; + gpuInput.type = mapType(glType); + gpuInput.count = glSize; + gpuInput.size = gpuInput.stride * gpuInput.count; + gpuInput.glType = glType; } // create buffers @@ -1141,14 +1141,14 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { glName[offset - glName] = '\0'; } - glBlock.name = glName; - glBlock.set = INVALID_BINDING; + glBlock.name = glName; + glBlock.set = INVALID_BINDING; glBlock.binding = INVALID_BINDING; for (size_t b = 0; b < gpuShader->blocks.size(); ++b) { UniformBlock &block = gpuShader->blocks[b]; if (block.name == glBlock.name) { - glBlock.set = block.set; - glBlock.binding = block.binding; + glBlock.set = block.set; + glBlock.binding = block.binding; glBlock.glBinding = block.binding + device->bindingMappings().blockOffsets[block.set]; GL_CHECK(glUniformBlockBinding(gpuShader->glProgram, i, glBlock.glBinding)); break; @@ -1166,14 +1166,14 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { glName[offset - glName] = '\0'; } - glBuffer.name = glName; - glBuffer.set = INVALID_BINDING; - glBuffer.binding = INVALID_BINDING; + glBuffer.name = glName; + glBuffer.set = INVALID_BINDING; + glBuffer.binding = INVALID_BINDING; glBuffer.isStorage = true; for (size_t b = 0; b < gpuShader->buffers.size(); ++b) { UniformStorageBuffer &buffer = gpuShader->buffers[b]; if (buffer.name == glBuffer.name) { - glBuffer.set = buffer.set; + glBuffer.set = buffer.set; glBuffer.binding = buffer.binding; static GLenum prop = GL_BUFFER_BINDING; @@ -1189,12 +1189,12 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { gpuShader->samplerTextures.emplace_back(); - auto &samplerTexture = gpuShader->samplerTextures.back(); - samplerTexture.name = subpassInput.name; - samplerTexture.set = subpassInput.set; + auto &samplerTexture = gpuShader->samplerTextures.back(); + samplerTexture.name = subpassInput.name; + samplerTexture.set = subpassInput.set; samplerTexture.binding = subpassInput.binding; - samplerTexture.count = subpassInput.count; - samplerTexture.type = Type::SAMPLER2D; + samplerTexture.count = subpassInput.count; + samplerTexture.type = Type::SAMPLER2D; } } @@ -1203,22 +1203,22 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { gpuShader->glSamplerTextures.resize(gpuShader->samplerTextures.size()); for (size_t i = 0; i < gpuShader->glSamplerTextures.size(); ++i) { - UniformSamplerTexture & samplerTexture = gpuShader->samplerTextures[i]; + UniformSamplerTexture &samplerTexture = gpuShader->samplerTextures[i]; GLES3GPUUniformSamplerTexture &gpuSamplerTexture = gpuShader->glSamplerTextures[i]; - gpuSamplerTexture.set = samplerTexture.set; - gpuSamplerTexture.binding = samplerTexture.binding; - gpuSamplerTexture.name = samplerTexture.name; - gpuSamplerTexture.type = samplerTexture.type; - gpuSamplerTexture.count = samplerTexture.count; - gpuSamplerTexture.glType = mapGLType(gpuSamplerTexture.type); - gpuSamplerTexture.glLoc = -1; + gpuSamplerTexture.set = samplerTexture.set; + gpuSamplerTexture.binding = samplerTexture.binding; + gpuSamplerTexture.name = samplerTexture.name; + gpuSamplerTexture.type = samplerTexture.type; + gpuSamplerTexture.count = samplerTexture.count; + gpuSamplerTexture.glType = mapGLType(gpuSamplerTexture.type); + gpuSamplerTexture.glLoc = -1; } } // texture unit index mapping optimization - ccstd::vector glActiveSamplerTextures; - ccstd::vector glActiveSamplerLocations; - const GLESBindingMapping & bindingMappings = device->bindingMappings(); + ccstd::vector glActiveSamplerTextures; + ccstd::vector glActiveSamplerLocations; + const GLESBindingMapping &bindingMappings = device->bindingMappings(); ccstd::unordered_map &texUnitCacheMap = device->stateCache()->texUnitCacheMap; // sampler bindings in the flexible set comes strictly after buffer bindings @@ -1234,7 +1234,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { for (uint32_t i = 0U; i < gpuShader->samplerTextures.size(); i++) { const UniformSamplerTexture &samplerTexture = gpuShader->samplerTextures[i]; - GLint glLoc = -1; + GLint glLoc = -1; GL_CHECK(glLoc = glGetUniformLocation(gpuShader->glProgram, samplerTexture.name.c_str())); if (glLoc >= 0) { glActiveSamplerTextures.push_back(gpuShader->glSamplerTextures[i]); @@ -1256,7 +1256,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { GLES3GPUUniformSamplerTexture &glSamplerTexture = glActiveSamplerTextures[i]; if (texUnitCacheMap.count(glSamplerTexture.name)) { - uint32_t cachedUnit = texUnitCacheMap[glSamplerTexture.name]; + uint32_t cachedUnit = texUnitCacheMap[glSamplerTexture.name]; glSamplerTexture.glLoc = glActiveSamplerLocations[i]; for (uint32_t t = 0U; t < glSamplerTexture.count; t++) { while (usedTexUnits[cachedUnit]) { // the shader already compiles so we should be safe to do this here @@ -1305,15 +1305,15 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { if (!gpuShader->images.empty()) { for (size_t i = 0; i < gpuShader->images.size(); ++i) { UniformStorageImage &image = gpuShader->images[i]; - GLint glLoc = -1; + GLint glLoc = -1; GL_CHECK(glLoc = glGetUniformLocation(gpuShader->glProgram, image.name.c_str())); if (glLoc >= 0) { GLES3GPUUniformStorageImage gpuImage; - gpuImage.set = image.set; - gpuImage.binding = image.binding; - gpuImage.name = image.name; - gpuImage.type = image.type; - gpuImage.count = image.count; + gpuImage.set = image.set; + gpuImage.binding = image.binding; + gpuImage.name = image.name; + gpuImage.type = image.type; + gpuImage.count = image.count; gpuImage.glMemoryAccess = GL_MEMORY_ACCESS[toNumber(image.memoryAccess)]; gpuImage.units.resize(gpuImage.count); gpuImage.glLoc = glLoc; @@ -1331,7 +1331,7 @@ void cmdFuncGLES3DestroyShader(GLES3Device *device, GLES3GPUShader *gpuShader) { if (device->stateCache()->glProgram == gpuShader->glProgram) { GL_CHECK(glUseProgram(0)); device->stateCache()->glProgram = 0; - gfxStateCache.gpuPipelineState = nullptr; + gfxStateCache.gpuPipelineState = nullptr; } GL_CHECK(glDeleteProgram(gpuShader->glProgram)); gpuShader->glProgram = 0; @@ -1403,21 +1403,21 @@ void cmdFuncGLES3CreateInputAssembler(GLES3Device *device, GLES3GPUInputAssemble gpuInputAssembler->glAttribs.resize(gpuInputAssembler->attributes.size()); for (size_t i = 0; i < gpuInputAssembler->glAttribs.size(); ++i) { GLES3GPUAttribute &gpuAttribute = gpuInputAssembler->glAttribs[i]; - const Attribute & attrib = gpuInputAssembler->attributes[i]; - auto * gpuVB = static_cast(gpuInputAssembler->gpuVertexBuffers[attrib.stream]); + const Attribute &attrib = gpuInputAssembler->attributes[i]; + auto *gpuVB = static_cast(gpuInputAssembler->gpuVertexBuffers[attrib.stream]); - gpuAttribute.name = attrib.name; - gpuAttribute.glType = formatToGLType(attrib.format); - gpuAttribute.size = GFX_FORMAT_INFOS[static_cast(attrib.format)].size; - gpuAttribute.count = GFX_FORMAT_INFOS[static_cast(attrib.format)].count; + gpuAttribute.name = attrib.name; + gpuAttribute.glType = formatToGLType(attrib.format); + gpuAttribute.size = GFX_FORMAT_INFOS[static_cast(attrib.format)].size; + gpuAttribute.count = GFX_FORMAT_INFOS[static_cast(attrib.format)].count; gpuAttribute.componentCount = glComponentCount(gpuAttribute.glType); - gpuAttribute.isNormalized = attrib.isNormalized; - gpuAttribute.isInstanced = attrib.isInstanced; - gpuAttribute.offset = streamOffsets[attrib.stream]; + gpuAttribute.isNormalized = attrib.isNormalized; + gpuAttribute.isInstanced = attrib.isInstanced; + gpuAttribute.offset = streamOffsets[attrib.stream]; if (gpuVB) { gpuAttribute.glBuffer = gpuVB->glBuffer; - gpuAttribute.stride = gpuVB->stride; + gpuAttribute.stride = gpuVB->stride; } streamOffsets[attrib.stream] += gpuAttribute.size; } @@ -1428,7 +1428,7 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl for (auto it = gpuInputAssembler->glVAOs.begin(); it != gpuInputAssembler->glVAOs.end(); ++it) { if (device->stateCache()->glVAO == it->second) { GL_CHECK(glBindVertexArray(0)); - device->stateCache()->glVAO = 0; + device->stateCache()->glVAO = 0; gfxStateCache.gpuInputAssembler = nullptr; } GL_CHECK(glDeleteVertexArrays(1, &it->second)); @@ -1436,14 +1436,14 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device * device, +static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device *device, const ccstd::vector &attachments, const uint32_t *colors, size_t colorCount, const GLES3GPUTextureView *depthStencilView, - const uint32_t * resolves = nullptr, + const uint32_t *resolves = nullptr, const GLES3GPUTextureView *depthStencilResolveView = nullptr, - GLbitfield * resolveMask = nullptr) { - static ccstd::vector drawBuffers; - GLES3GPUStateCache * cache = device->stateCache(); + GLbitfield *resolveMask = nullptr) { + static ccstd::vector drawBuffers; + GLES3GPUStateCache *cache = device->stateCache(); GLES3GPUFramebuffer::GLFramebufferInfo res; GL_CHECK(glGenFramebuffers(1, &res.glFramebuffer)); @@ -1455,13 +1455,13 @@ static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device * drawBuffers.clear(); auto supportLevel = device->constantRegistry()->mMSRT; - bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); + bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); for (size_t j = 0; j < colorCount; ++j) { - GLES3GPUTextureView *gpuColorTextureView = attachments[colors[j]]; + GLES3GPUTextureView *gpuColorTextureView = attachments[colors[j]]; GLES3GPUTextureView *gpuResolveTextureView = resolves ? attachments[resolves[j]] : nullptr; - GLES3GPUTexture * gpuColorTexture = gpuColorTextureView->gpuTexture; - GLES3GPUTexture * gpuResolveTexture = resolves ? gpuResolveTextureView->gpuTexture : nullptr; + GLES3GPUTexture *gpuColorTexture = gpuColorTextureView->gpuTexture; + GLES3GPUTexture *gpuResolveTexture = resolves ? gpuResolveTextureView->gpuTexture : nullptr; drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); @@ -1483,14 +1483,14 @@ static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device * gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); } } - res.width = std::min(res.width, gpuColorTexture->width); + res.width = std::min(res.width, gpuColorTexture->width); res.height = std::min(res.height, gpuColorTexture->height); } - GLES3GPUTexture *depthStencil = depthStencilView ? depthStencilView->gpuTexture : nullptr; + GLES3GPUTexture *depthStencil = depthStencilView ? depthStencilView->gpuTexture : nullptr; GLES3GPUTexture *depthStencilResolve = depthStencilResolveView ? depthStencilResolveView->gpuTexture : nullptr; if (depthStencil) { - bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; + bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; GLenum glAttachment = hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; if (depthStencil->glTexture) { GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glTexture, depthStencilView->baseLevel)); @@ -1500,7 +1500,7 @@ static GLES3GPUFramebuffer::GLFramebufferInfo doCreateFramebuffer(GLES3Device * // fallback to blit-based manual resolve if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; - res.width = std::min(res.width, depthStencil->width >> depthStencilView->baseLevel); + res.width = std::min(res.width, depthStencil->width >> depthStencilView->baseLevel); res.height = std::min(res.height, depthStencil->height >> depthStencilView->baseLevel); } @@ -1576,7 +1576,7 @@ static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, colors.data(), utils::toUint(colors.size()), depthStencilTextureView, resolves, depthStencilResolveTextureView, &outFBO->resolveMask)); if (outFBO->resolveMask) { - size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? utils::toUint(colors.size()) : 0U; + size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? utils::toUint(colors.size()) : 0U; GLES3GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorViews, resolves, resolveCount)}; if (!resolveSwapchain) { outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorViews, resolves, resolveCount, depthStencilResolveTextureView)); @@ -1598,7 +1598,7 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu for (auto &subpass : gpuFBO->gpuRenderPass->subpasses) { if (subpass.inputs.size() == 4) { gpuFBO->uberOnChipOutput = subpass.inputs.back(); - gpuFBO->uberFinalOutput = subpass.colors.back(); + gpuFBO->uberFinalOutput = subpass.colors.back(); break; } } @@ -1641,7 +1641,7 @@ void GLES3GPUFramebuffer::GLFramebuffer::destroy(GLES3GPUStateCache *cache, GLES } void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { - auto *cache = device->stateCache(); + auto *cache = device->stateCache(); auto *framebufferCacheMap = device->framebufferCacheMap(); for (auto &instance : gpuFBO->instances) { @@ -1749,7 +1749,7 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES switch (type) { case GLES3QueryType::BEGIN: { - auto queryId = queryPool->getIdCount(); + auto queryId = queryPool->getIdCount(); GLuint glQueryId = gpuQueryPool->mapGLQueryId(queryId); if (glQueryId != UINT_MAX) { GL_CHECK(glBeginQuery(GL_ANY_SAMPLES_PASSED, glQueryId)); @@ -1757,7 +1757,7 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES break; } case GLES3QueryType::END: { - auto queryId = queryPool->getIdCount(); + auto queryId = queryPool->getIdCount(); GLuint glQueryId = gpuQueryPool->mapGLQueryId(queryId); if (glQueryId != UINT_MAX) { GL_CHECK(glEndQuery(GL_ANY_SAMPLES_PASSED)); @@ -1770,7 +1770,7 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES break; } case GLES3QueryType::GET_RESULTS: { - auto queryCount = queryPool->getIdCount(); + auto queryCount = queryPool->getIdCount(); ccstd::vector results(queryCount); for (auto queryId = 0U; queryId < queryCount; queryId++) { @@ -1787,7 +1787,7 @@ void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES ccstd::unordered_map mapResults; for (auto queryId = 0U; queryId < queryCount; queryId++) { uint32_t glID = queryPool->getId(queryId); - auto iter = mapResults.find(glID); + auto iter = mapResults.find(glID); if (iter != mapResults.end()) { iter->second += results[queryId]; } else { @@ -1812,22 +1812,22 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 const Color *clearColors, float clearDepth, uint32_t clearStencil) { static ccstd::vector invalidAttachments; - GLES3GPUStateCache *cache = device->stateCache(); - GLES3ObjectCache & gfxStateCache = cache->gfxStateCache; - gfxStateCache.subpassIdx = subpassIdx; + GLES3GPUStateCache *cache = device->stateCache(); + GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; + gfxStateCache.subpassIdx = subpassIdx; if (subpassIdx) { - gpuRenderPass = gfxStateCache.gpuRenderPass; + gpuRenderPass = gfxStateCache.gpuRenderPass; gpuFramebuffer = gfxStateCache.gpuFramebuffer; - renderArea = &gfxStateCache.renderArea; - clearColors = gfxStateCache.clearColors.data(); - clearDepth = gfxStateCache.clearDepth; - clearStencil = gfxStateCache.clearStencil; + renderArea = &gfxStateCache.renderArea; + clearColors = gfxStateCache.clearColors.data(); + clearDepth = gfxStateCache.clearDepth; + clearStencil = gfxStateCache.clearStencil; } else { - gfxStateCache.gpuRenderPass = gpuRenderPass; + gfxStateCache.gpuRenderPass = gpuRenderPass; gfxStateCache.gpuFramebuffer = gpuFramebuffer; - gfxStateCache.renderArea = *renderArea; + gfxStateCache.renderArea = *renderArea; gfxStateCache.clearColors.assign(clearColors, clearColors + gpuRenderPass->colorAttachments.size()); - gfxStateCache.clearDepth = clearDepth; + gfxStateCache.clearDepth = clearDepth; gfxStateCache.clearStencil = clearStencil; } @@ -1848,9 +1848,9 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 cache->viewport.width != renderArea->width || cache->viewport.height != renderArea->height) { GL_CHECK(glViewport(renderArea->x, renderArea->y, renderArea->width, renderArea->height)); - cache->viewport.left = renderArea->x; - cache->viewport.top = renderArea->y; - cache->viewport.width = renderArea->width; + cache->viewport.left = renderArea->x; + cache->viewport.top = renderArea->y; + cache->viewport.width = renderArea->width; cache->viewport.height = renderArea->height; } @@ -1864,7 +1864,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 invalidAttachments.clear(); float fColors[4]{}; - bool maskSet = false; + bool maskSet = false; auto performLoadOp = [&](uint32_t attachmentIndex, uint32_t glAttachmentIndex) { if (attachmentIndex == gpuFramebuffer->uberOnChipOutput) attachmentIndex = gpuFramebuffer->uberFinalOutput; @@ -1901,12 +1901,12 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 auto performDepthStencilLoadOp = [&](uint32_t attachmentIndex, bool skipLoad) { if (attachmentIndex != INVALID_BINDING && !skipLoad) { - LoadOp depthLoadOp = gpuRenderPass->depthStencilAttachment.depthLoadOp; + LoadOp depthLoadOp = gpuRenderPass->depthStencilAttachment.depthLoadOp; LoadOp stencilLoadOp = gpuRenderPass->depthStencilAttachment.stencilLoadOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { depthLoadOp = stencilLoadOp = gpuRenderPass->colorAttachments[attachmentIndex].loadOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; + hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } switch (gpuRenderPass->depthStencilAttachment.depthLoadOp) { case LoadOp::LOAD: break; // GL default behaviour @@ -1990,7 +1990,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3 performLoadOp(attachmentIndex, glAttachmentIndex++); } auto depthIndex = gpuRenderPass->subpasses[subpassIdx].depthStencil; - bool skipLoad = depthIndex == INVALID_BINDING || gpuRenderPass->statistics[depthIndex].loadSubpass != subpassIdx; + bool skipLoad = depthIndex == INVALID_BINDING || gpuRenderPass->statistics[depthIndex].loadSubpass != subpassIdx; performDepthStencilLoadOp(depthIndex, skipLoad); } } @@ -2001,9 +2001,9 @@ static void ensureScissorRect(GLES3GPUStateCache *cache, int32_t x, int32_t y, u cache->scissor.y > y || cache->scissor.width < width || cache->scissor.height < height) { - cache->scissor.x = std::min(cache->scissor.x, x); - cache->scissor.y = std::min(cache->scissor.y, y); - cache->scissor.width = std::max(cache->scissor.width, width); + cache->scissor.x = std::min(cache->scissor.x, x); + cache->scissor.y = std::min(cache->scissor.y, y); + cache->scissor.width = std::max(cache->scissor.width, width); cache->scissor.height = std::max(cache->scissor.height, height); GL_CHECK(glScissor(cache->scissor.x, cache->scissor.y, cache->scissor.width, cache->scissor.height)); } @@ -2012,16 +2012,16 @@ static void ensureScissorRect(GLES3GPUStateCache *cache, int32_t x, int32_t y, u void cmdFuncGLES3EndRenderPass(GLES3Device *device) { static ccstd::vector invalidAttachments; - GLES3GPUStateCache * cache = device->stateCache(); - GLES3ObjectCache & gfxStateCache = cache->gfxStateCache; - GLES3GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; - GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - const auto & instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; - const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; - GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); - GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); - GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; + GLES3GPUStateCache *cache = device->stateCache(); + GLES3ObjectCache &gfxStateCache = cache->gfxStateCache; + GLES3GPURenderPass *gpuRenderPass = gfxStateCache.gpuRenderPass; + GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; + const auto &instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; + const SubpassInfo &subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; + bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; + GLuint glFramebuffer = instance.framebuffer.getFramebuffer(); + GLuint glResolveFramebuffer = instance.resolveFramebuffer.getFramebuffer(); + GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; invalidAttachments.clear(); @@ -2042,12 +2042,12 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { auto performDepthStencilStoreOp = [&](uint32_t attachmentIndex, bool skipStore) { if (attachmentIndex != INVALID_BINDING && !skipStore) { - StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; + StoreOp depthStoreOp = gpuRenderPass->depthStencilAttachment.depthStoreOp; StoreOp stencilStoreOp = gpuRenderPass->depthStencilAttachment.stencilStoreOp; - bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; + bool hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->depthStencilAttachment.format)].hasStencil; if (attachmentIndex < gpuRenderPass->colorAttachments.size()) { depthStoreOp = stencilStoreOp = gpuRenderPass->colorAttachments[attachmentIndex].storeOp; - hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; + hasStencils = GFX_FORMAT_INFOS[toNumber(gpuRenderPass->colorAttachments[attachmentIndex].format)].hasStencil; } switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { @@ -2129,8 +2129,8 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { if (gpuFramebuffer->uberOnChipOutput != INVALID_BINDING) { TextureBlit region; - auto * blitSrc = gpuFramebuffer->gpuColorViews[gpuFramebuffer->uberOnChipOutput]->gpuTexture; - auto * blitDst = gpuFramebuffer->gpuColorViews[gpuFramebuffer->uberFinalOutput]->gpuTexture; + auto *blitSrc = gpuFramebuffer->gpuColorViews[gpuFramebuffer->uberOnChipOutput]->gpuTexture; + auto *blitDst = gpuFramebuffer->gpuColorViews[gpuFramebuffer->uberFinalOutput]->gpuTexture; region.srcExtent.width = region.dstExtent.width = blitSrc->width; region.srcExtent.height = region.dstExtent.height = blitSrc->height; cmdFuncGLES3BlitTexture(device, blitSrc, blitDst, ®ion, 1, Filter::POINT); @@ -2163,18 +2163,18 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUDescriptorSet *const *gpuDescriptorSets, const uint32_t *dynamicOffsets, const DynamicStates *dynamicStates) { GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; - GLES3GPUStateCache *cache = device->stateCache(); - bool isShaderChanged = false; + GLES3GPUStateCache *cache = device->stateCache(); + bool isShaderChanged = false; if (gpuPipelineState && gpuPipelineState != gfxStateCache.gpuPipelineState) { gfxStateCache.gpuPipelineState = gpuPipelineState; - gfxStateCache.glPrimitive = gpuPipelineState->glPrimitive; + gfxStateCache.glPrimitive = gpuPipelineState->glPrimitive; if (gpuPipelineState->gpuShader) { if (cache->glProgram != gpuPipelineState->gpuShader->glProgram) { GL_CHECK(glUseProgram(gpuPipelineState->gpuShader->glProgram)); cache->glProgram = gpuPipelineState->gpuShader->glProgram; - isShaderChanged = true; + isShaderChanged = true; } } @@ -2257,8 +2257,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_CMP_FUNCS[(int)gpuPipelineState->dss.stencilFuncFront], gpuPipelineState->dss.stencilRefFront, gpuPipelineState->dss.stencilReadMaskFront)); - cache->dss.stencilFuncFront = gpuPipelineState->dss.stencilFuncFront; - cache->dss.stencilRefFront = gpuPipelineState->dss.stencilRefFront; + cache->dss.stencilFuncFront = gpuPipelineState->dss.stencilFuncFront; + cache->dss.stencilRefFront = gpuPipelineState->dss.stencilRefFront; cache->dss.stencilReadMaskFront = gpuPipelineState->dss.stencilReadMaskFront; } if (cache->dss.stencilFailOpFront != gpuPipelineState->dss.stencilFailOpFront || @@ -2268,9 +2268,9 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilFailOpFront], GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilZFailOpFront], GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilPassOpFront])); - cache->dss.stencilFailOpFront = gpuPipelineState->dss.stencilFailOpFront; + cache->dss.stencilFailOpFront = gpuPipelineState->dss.stencilFailOpFront; cache->dss.stencilZFailOpFront = gpuPipelineState->dss.stencilZFailOpFront; - cache->dss.stencilPassOpFront = gpuPipelineState->dss.stencilPassOpFront; + cache->dss.stencilPassOpFront = gpuPipelineState->dss.stencilPassOpFront; } if (cache->dss.stencilWriteMaskFront != gpuPipelineState->dss.stencilWriteMaskFront) { GL_CHECK(glStencilMaskSeparate(GL_FRONT, gpuPipelineState->dss.stencilWriteMaskFront)); @@ -2285,8 +2285,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_CMP_FUNCS[(int)gpuPipelineState->dss.stencilFuncBack], gpuPipelineState->dss.stencilRefBack, gpuPipelineState->dss.stencilReadMaskBack)); - cache->dss.stencilFuncBack = gpuPipelineState->dss.stencilFuncBack; - cache->dss.stencilRefBack = gpuPipelineState->dss.stencilRefBack; + cache->dss.stencilFuncBack = gpuPipelineState->dss.stencilFuncBack; + cache->dss.stencilRefBack = gpuPipelineState->dss.stencilRefBack; cache->dss.stencilReadMaskBack = gpuPipelineState->dss.stencilReadMaskBack; } if (cache->dss.stencilFailOpBack != gpuPipelineState->dss.stencilFailOpBack || @@ -2296,9 +2296,9 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilFailOpBack], GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilZFailOpBack], GLES3_STENCIL_OPS[(int)gpuPipelineState->dss.stencilPassOpBack])); - cache->dss.stencilFailOpBack = gpuPipelineState->dss.stencilFailOpBack; + cache->dss.stencilFailOpBack = gpuPipelineState->dss.stencilFailOpBack; cache->dss.stencilZFailOpBack = gpuPipelineState->dss.stencilZFailOpBack; - cache->dss.stencilPassOpBack = gpuPipelineState->dss.stencilPassOpBack; + cache->dss.stencilPassOpBack = gpuPipelineState->dss.stencilPassOpBack; } if (cache->dss.stencilWriteMaskBack != gpuPipelineState->dss.stencilWriteMaskBack) { GL_CHECK(glStencilMaskSeparate(GL_BACK, gpuPipelineState->dss.stencilWriteMaskBack)); @@ -2326,8 +2326,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli } if (!gpuPipelineState->bs.targets.empty()) { - BlendTarget & cacheTarget = cache->bs.targets[0]; - const BlendTarget &target = gpuPipelineState->bs.targets[0]; + BlendTarget &cacheTarget = cache->bs.targets[0]; + const BlendTarget &target = gpuPipelineState->bs.targets[0]; if (cacheTarget.blend != target.blend) { if (!cacheTarget.blend) { GL_CHECK(glEnable(GL_BLEND)); @@ -2340,7 +2340,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli cacheTarget.blendAlphaEq != target.blendAlphaEq) { GL_CHECK(glBlendEquationSeparate(GLES3_BLEND_OPS[(int)target.blendEq], GLES3_BLEND_OPS[(int)target.blendAlphaEq])); - cacheTarget.blendEq = target.blendEq; + cacheTarget.blendEq = target.blendEq; cacheTarget.blendAlphaEq = target.blendAlphaEq; } if (cacheTarget.blendSrc != target.blendSrc || @@ -2351,8 +2351,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_BLEND_FACTORS[(int)target.blendDst], GLES3_BLEND_FACTORS[(int)target.blendSrcAlpha], GLES3_BLEND_FACTORS[(int)target.blendDstAlpha])); - cacheTarget.blendSrc = target.blendSrc; - cacheTarget.blendDst = target.blendDst; + cacheTarget.blendSrc = target.blendSrc; + cacheTarget.blendDst = target.blendDst; cacheTarget.blendSrcAlpha = target.blendSrcAlpha; cacheTarget.blendDstAlpha = target.blendDstAlpha; } @@ -2375,8 +2375,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUUniformBuffer &glBuffer = gpuPipelineState->gpuShader->glBuffers[j]; const GLES3GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glBuffer.set]; - const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBuffer.binding); - const GLES3GPUDescriptor & gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glBuffer.binding); + const GLES3GPUDescriptor &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; if (!gpuDescriptor.gpuBuffer) { //CC_LOG_ERROR("Buffer binding '%s' at set %d binding %d is not bounded", @@ -2387,7 +2387,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli uint32_t offset = gpuDescriptor.gpuBuffer->glOffset; const ccstd::vector &dynamicOffsetSetIndices = dynamicOffsetIndices[glBuffer.set]; - int dynamicOffsetIndex = glBuffer.binding < dynamicOffsetSetIndices.size() ? dynamicOffsetSetIndices[glBuffer.binding] : -1; + int dynamicOffsetIndex = glBuffer.binding < dynamicOffsetSetIndices.size() ? dynamicOffsetSetIndices[glBuffer.binding] : -1; if (dynamicOffsetIndex >= 0) offset += dynamicOffsets[dynamicOffsetIndex]; if (glBuffer.isStorage) { @@ -2400,7 +2400,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, glBuffer.glBinding, gpuDescriptor.gpuBuffer->glBuffer)); } cache->glShaderStorageBuffer = cache->glBindSSBOs[glBuffer.glBinding] = gpuDescriptor.gpuBuffer->glBuffer; - cache->glBindSSBOOffsets[glBuffer.glBinding] = offset; + cache->glBindSSBOOffsets[glBuffer.glBinding] = offset; } } else { if (cache->glBindUBOs[glBuffer.glBinding] != gpuDescriptor.gpuBuffer->glBuffer || @@ -2412,7 +2412,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GL_CHECK(glBindBufferBase(GL_UNIFORM_BUFFER, glBuffer.glBinding, gpuDescriptor.gpuBuffer->glBuffer)); } cache->glUniformBuffer = cache->glBindUBOs[glBuffer.glBinding] = gpuDescriptor.gpuBuffer->glBuffer; - cache->glBindUBOOffsets[glBuffer.glBinding] = offset; + cache->glBindUBOOffsets[glBuffer.glBinding] = offset; } } } @@ -2422,11 +2422,11 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUUniformSamplerTexture &glSamplerTexture = gpuPipelineState->gpuShader->glSamplerTextures[j]; const GLES3GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glSamplerTexture.set]; - const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glSamplerTexture.binding); - const GLES3GPUDescriptor * gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glSamplerTexture.binding); + const GLES3GPUDescriptor *gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; GLES3GPUTextureView *gpuTextureView = nullptr; - GLES3GPUTexture * gpuTexture = nullptr; + GLES3GPUTexture *gpuTexture = nullptr; uint32_t minLod = 0; uint32_t maxLod = 0; @@ -2441,9 +2441,9 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli } gpuTextureView = gpuDescriptor->gpuTextureView; - gpuTexture = gpuTextureView->gpuTexture; - minLod = gpuTextureView->baseLevel; - maxLod = minLod + gpuTextureView->levelCount; + gpuTexture = gpuTextureView->gpuTexture; + minLod = gpuTextureView->baseLevel; + maxLod = minLod + gpuTextureView->levelCount; if (gpuTexture->size > 0) { GLuint glTexture = gpuTexture->glTexture; @@ -2471,8 +2471,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli const GLES3GPUUniformStorageImage &glImage = gpuPipelineState->gpuShader->glImages[j]; const GLES3GPUDescriptorSet *gpuDescriptorSet = gpuDescriptorSets[glImage.set]; - const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glImage.binding); - const GLES3GPUDescriptor * gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const uint32_t descriptorIndex = gpuDescriptorSet->descriptorIndices->at(glImage.binding); + const GLES3GPUDescriptor *gpuDescriptor = &gpuDescriptorSet->gpuDescriptors[descriptorIndex]; GLES3GPUTexture *gpuTexture = nullptr; @@ -2503,7 +2503,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli (isShaderChanged || gpuInputAssembler != gfxStateCache.gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; if (USE_VAO) { - size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; + size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; GLuint glVAO = gpuInputAssembler->glVAOs[hash]; if (!glVAO) { GL_CHECK(glGenVertexArrays(1, &glVAO)); @@ -2519,7 +2519,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, gpuAttribute.glBuffer)); for (uint32_t c = 0; c < gpuAttribute.componentCount; ++c) { - GLuint glLoc = gpuInput.glLoc + c; + GLuint glLoc = gpuInput.glLoc + c; uint32_t attribOffset = gpuAttribute.offset + gpuAttribute.size * c; GL_CHECK(glEnableVertexAttribArray(glLoc)); @@ -2539,8 +2539,8 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GL_CHECK(glBindVertexArray(0)); GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); - cache->glVAO = 0; - cache->glArrayBuffer = 0; + cache->glVAO = 0; + cache->glArrayBuffer = 0; cache->glElementArrayBuffer = 0; } @@ -2563,7 +2563,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli } for (uint32_t c = 0; c < gpuAttribute.componentCount; ++c) { - GLuint glLoc = gpuInput.glLoc + c; + GLuint glLoc = gpuInput.glLoc + c; uint32_t attribOffset = gpuAttribute.offset + gpuAttribute.size * c; GL_CHECK(glEnableVertexAttribArray(glLoc)); cache->glCurrentAttribLocs[glLoc] = true; @@ -2605,7 +2605,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli if ((cache->rs.depthBias != dynamicStates->depthBiasConstant) || (cache->rs.depthBiasSlop != dynamicStates->depthBiasSlope)) { GL_CHECK(glPolygonOffset(dynamicStates->depthBiasConstant, dynamicStates->depthBiasSlope)); - cache->rs.depthBias = dynamicStates->depthBiasConstant; + cache->rs.depthBias = dynamicStates->depthBiasConstant; cache->rs.depthBiasSlop = dynamicStates->depthBiasSlope; } break; @@ -2623,7 +2623,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli break; case DynamicStateFlagBit::STENCIL_WRITE_MASK: { const auto &front = dynamicStates->stencilStatesFront; - const auto &back = dynamicStates->stencilStatesBack; + const auto &back = dynamicStates->stencilStatesBack; if (cache->dss.stencilWriteMaskFront != front.writeMask) { GL_CHECK(glStencilMaskSeparate(GL_FRONT, front.writeMask)); cache->dss.stencilWriteMaskFront = front.writeMask; @@ -2635,14 +2635,14 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli } break; case DynamicStateFlagBit::STENCIL_COMPARE_MASK: { const auto &front = dynamicStates->stencilStatesFront; - const auto &back = dynamicStates->stencilStatesBack; + const auto &back = dynamicStates->stencilStatesBack; if ((cache->dss.stencilRefFront != front.reference) || (cache->dss.stencilReadMaskFront != front.compareMask)) { GL_CHECK(glStencilFuncSeparate(GL_FRONT, GLES3_CMP_FUNCS[toNumber(cache->dss.stencilFuncFront)], front.reference, front.compareMask)); - cache->dss.stencilRefFront = front.reference; + cache->dss.stencilRefFront = front.reference; cache->dss.stencilReadMaskFront = front.compareMask; } if ((cache->dss.stencilRefBack != back.reference) || @@ -2651,7 +2651,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLES3_CMP_FUNCS[toNumber(cache->dss.stencilFuncBack)], back.reference, back.compareMask)); - cache->dss.stencilRefBack = back.reference; + cache->dss.stencilRefBack = back.reference; cache->dss.stencilReadMaskBack = back.compareMask; } } break; @@ -2664,10 +2664,10 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli } void cmdFuncGLES3Draw(GLES3Device *device, const DrawInfo &drawInfo) { - GLES3ObjectCache & gfxStateCache = device->stateCache()->gfxStateCache; - GLES3GPUPipelineState * gpuPipelineState = gfxStateCache.gpuPipelineState; + GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; + GLES3GPUPipelineState *gpuPipelineState = gfxStateCache.gpuPipelineState; GLES3GPUInputAssembler *gpuInputAssembler = gfxStateCache.gpuInputAssembler; - GLenum glPrimitive = gfxStateCache.glPrimitive; + GLenum glPrimitive = gfxStateCache.glPrimitive; if (gpuInputAssembler && gpuPipelineState) { if (!gpuInputAssembler->gpuIndirectBuffer) { @@ -2812,8 +2812,8 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const glTexture = gpuTexture->glTexture; } - bool isCompressed = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed; - uint32_t n = 0; + bool isCompressed = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed; + uint32_t n = 0; switch (gpuTexture->glTarget) { case GL_TEXTURE_2D: { @@ -2821,9 +2821,9 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const uint32_t h; for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; - w = region.texExtent.width; - h = region.texExtent.height; - const uint8_t *buff = buffers[n++]; + w = region.texExtent.width; + h = region.texExtent.height; + const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); GL_CHECK(glCompressedTexSubImage2D(GL_TEXTURE_2D, @@ -2851,13 +2851,13 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const uint32_t w; uint32_t h; for (size_t i = 0; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - uint32_t d = region.texSubres.layerCount; - uint32_t layerCount = d + region.texSubres.baseArrayLayer; + const BufferTextureCopy ®ion = regions[i]; + uint32_t d = region.texSubres.layerCount; + uint32_t layerCount = d + region.texSubres.baseArrayLayer; for (uint32_t z = region.texSubres.baseArrayLayer; z < layerCount; ++z) { - w = region.texExtent.width; - h = region.texExtent.height; + w = region.texExtent.width; + h = region.texExtent.height; const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); @@ -2891,10 +2891,10 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const uint32_t d; for (size_t i = 0; i < count; ++i) { const BufferTextureCopy ®ion = regions[i]; - w = region.texExtent.width; - h = region.texExtent.height; - d = region.texExtent.depth; - const uint8_t *buff = buffers[n++]; + w = region.texExtent.width; + h = region.texExtent.height; + d = region.texExtent.depth; + const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); GL_CHECK(glCompressedTexSubImage3D(GL_TEXTURE_3D, @@ -2925,11 +2925,11 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const uint32_t h; uint32_t f; for (size_t i = 0; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - uint32_t faceCount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + const BufferTextureCopy ®ion = regions[i]; + uint32_t faceCount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < faceCount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; + w = region.texExtent.width; + h = region.texExtent.height; const uint8_t *buff = buffers[n++]; if (isCompressed) { auto memSize = static_cast(formatSize(gpuTexture->format, w, h, 1)); @@ -2969,12 +2969,12 @@ void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, const uint8_t *const void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, GLES3GPUTexture *gpuTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { auto glFormat = gpuTexture->glFormat; - auto glType = gpuTexture->glType; + auto glType = gpuTexture->glType; for (uint32_t i = 0; i < count; ++i) { - auto region = regions[i]; - uint8_t *copyDst = buffers[i]; - auto framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTexture, region.texSubres); + auto region = regions[i]; + uint8_t *copyDst = buffers[i]; + auto framebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTexture, region.texSubres); if (device->stateCache()->glReadFramebuffer != framebuffer) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer)); device->stateCache()->glReadFramebuffer = framebuffer; @@ -2987,7 +2987,7 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc const TextureBlit *regions, uint32_t count, Filter filter) { GLES3GPUStateCache *cache = device->stateCache(); - GLbitfield mask = 0U; + GLbitfield mask = 0U; const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(gpuTextureSrc->format)]; if (info.hasDepth || info.hasStencil) { if (info.hasDepth) mask |= GL_DEPTH_BUFFER_BIT; @@ -3045,7 +3045,7 @@ void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage) { for (uint32_t i = 0; i < cmdPackage->cmds.size(); ++i) { GLESCmdType cmdType = cmdPackage->cmds[i]; - uint32_t & cmdIdx = cmdIndices[static_cast(cmdType)]; + uint32_t &cmdIdx = cmdIndices[static_cast(cmdType)]; switch (cmdType) { case GLESCmdType::BEGIN_RENDER_PASS: { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index f725082014..4ac81309b4 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -35,34 +35,34 @@ class GLES3QueryPool; class GLES3CmdBeginRenderPass final : public GLESCmd { public: - GLES3GPURenderPass * gpuRenderPass = nullptr; - GLES3GPUFramebuffer *gpuFBO = nullptr; - Rect renderArea; - Color clearColors[MAX_ATTACHMENTS]; - float clearDepth = 1.0F; - uint32_t clearStencil = 0U; - uint32_t subpassIdx = 0U; + GLES3GPURenderPass *gpuRenderPass = nullptr; + GLES3GPUFramebuffer *gpuFBO = nullptr; + Rect renderArea; + Color clearColors[MAX_ATTACHMENTS]; + float clearDepth = 1.0F; + uint32_t clearStencil = 0U; + uint32_t subpassIdx = 0U; GLES3CmdBeginRenderPass() : GLESCmd(GLESCmdType::BEGIN_RENDER_PASS) {} void clear() override { gpuRenderPass = nullptr; - gpuFBO = nullptr; + gpuFBO = nullptr; } }; class GLES3CmdBindStates final : public GLESCmd { public: - GLES3GPUPipelineState * gpuPipelineState = nullptr; - GLES3GPUInputAssembler * gpuInputAssembler = nullptr; + GLES3GPUPipelineState *gpuPipelineState = nullptr; + GLES3GPUInputAssembler *gpuInputAssembler = nullptr; ccstd::vector gpuDescriptorSets; - ccstd::vector dynamicOffsets; - DynamicStates dynamicStates; + ccstd::vector dynamicOffsets; + DynamicStates dynamicStates; GLES3CmdBindStates() : GLESCmd(GLESCmdType::BIND_STATES) {} void clear() override { - gpuPipelineState = nullptr; + gpuPipelineState = nullptr; gpuInputAssembler = nullptr; gpuDescriptorSets.clear(); dynamicOffsets.clear(); @@ -90,12 +90,12 @@ public: class GLES3CmdBarrier final : public GLESCmd { public: - GLbitfield barriers = 0U; + GLbitfield barriers = 0U; GLbitfield barriersByRegion = 0U; GLES3CmdBarrier() : GLESCmd(GLESCmdType::BARRIER) {} void clear() override { - barriers = 0U; + barriers = 0U; barriersByRegion = 0U; } }; @@ -103,50 +103,50 @@ public: class GLES3CmdUpdateBuffer final : public GLESCmd { public: GLES3GPUBuffer *gpuBuffer = nullptr; - const uint8_t * buffer = nullptr; - uint32_t size = 0; - uint32_t offset = 0; + const uint8_t *buffer = nullptr; + uint32_t size = 0; + uint32_t offset = 0; GLES3CmdUpdateBuffer() : GLESCmd(GLESCmdType::UPDATE_BUFFER) {} void clear() override { gpuBuffer = nullptr; - buffer = nullptr; + buffer = nullptr; } }; class GLES3CmdCopyBufferToTexture final : public GLESCmd { public: - GLES3GPUTexture * gpuTexture = nullptr; - const BufferTextureCopy *regions = nullptr; - uint32_t count = 0U; - const uint8_t *const * buffers = nullptr; + GLES3GPUTexture *gpuTexture = nullptr; + const BufferTextureCopy *regions = nullptr; + uint32_t count = 0U; + const uint8_t *const *buffers = nullptr; GLES3CmdCopyBufferToTexture() : GLESCmd(GLESCmdType::COPY_BUFFER_TO_TEXTURE) {} void clear() override { gpuTexture = nullptr; - regions = nullptr; - count = 0U; - buffers = nullptr; + regions = nullptr; + count = 0U; + buffers = nullptr; } }; class GLES3CmdBlitTexture final : public GLESCmd { public: - GLES3GPUTexture * gpuTextureSrc = nullptr; - GLES3GPUTexture * gpuTextureDst = nullptr; - const TextureBlit *regions = nullptr; - uint32_t count = 0U; - Filter filter = Filter::POINT; + GLES3GPUTexture *gpuTextureSrc = nullptr; + GLES3GPUTexture *gpuTextureDst = nullptr; + const TextureBlit *regions = nullptr; + uint32_t count = 0U; + Filter filter = Filter::POINT; GLES3CmdBlitTexture() : GLESCmd(GLESCmdType::BLIT_TEXTURE) {} void clear() override { gpuTextureSrc = nullptr; gpuTextureDst = nullptr; - regions = nullptr; - count = 0U; + regions = nullptr; + count = 0U; } }; @@ -160,42 +160,42 @@ enum class GLES3QueryType : uint8_t { class GLES3CmdQuery final : public GLESCmd { public: GLES3QueryPool *queryPool = nullptr; - GLES3QueryType type = GLES3QueryType::BEGIN; - uint32_t id = 0U; + GLES3QueryType type = GLES3QueryType::BEGIN; + uint32_t id = 0U; GLES3CmdQuery() : GLESCmd(GLESCmdType::QUERY) {} void clear() override { queryPool = nullptr; - type = GLES3QueryType::BEGIN; - id = 0U; + type = GLES3QueryType::BEGIN; + id = 0U; } }; struct GLES3CmdPackage { - CachedArray cmds; - CachedArray beginRenderPassCmds; - CachedArray bindStatesCmds; - CachedArray drawCmds; - CachedArray dispatchCmds; - CachedArray barrierCmds; - CachedArray updateBufferCmds; + CachedArray cmds; + CachedArray beginRenderPassCmds; + CachedArray bindStatesCmds; + CachedArray drawCmds; + CachedArray dispatchCmds; + CachedArray barrierCmds; + CachedArray updateBufferCmds; CachedArray copyBufferToTextureCmds; - CachedArray blitTextureCmds; - CachedArray queryCmds; + CachedArray blitTextureCmds; + CachedArray queryCmds; }; class GLES3GPUCommandAllocator final { public: - CommandPool beginRenderPassCmdPool; - CommandPool bindStatesCmdPool; - CommandPool drawCmdPool; - CommandPool dispatchCmdPool; - CommandPool barrierCmdPool; - CommandPool updateBufferCmdPool; + CommandPool beginRenderPassCmdPool; + CommandPool bindStatesCmdPool; + CommandPool drawCmdPool; + CommandPool dispatchCmdPool; + CommandPool barrierCmdPool; + CommandPool updateBufferCmdPool; CommandPool copyBufferToTextureCmdPool; - CommandPool blitTextureCmdPool; - CommandPool queryCmdPool; + CommandPool blitTextureCmdPool; + CommandPool queryCmdPool; void clearCmds(GLES3CmdPackage *cmdPackage) { if (cmdPackage->beginRenderPassCmds.size()) { @@ -263,47 +263,47 @@ void cmdFuncGLES3PrepareSamplerInfo(GLES3Device *device, GLES3GPUSampler *gpuSam void cmdFuncGLES3Query(GLES3Device *device, GLES3QueryPool *query, GLES3QueryType type, uint32_t id); void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, - GLES3GPURenderPass * gpuRenderPass = nullptr, + GLES3GPURenderPass *gpuRenderPass = nullptr, GLES3GPUFramebuffer *gpuFramebuffer = nullptr, - const Rect * renderArea = nullptr, - const Color * clearColors = nullptr, - float clearDepth = 1.F, - uint32_t clearStencil = 0); + const Rect *renderArea = nullptr, + const Color *clearColors = nullptr, + float clearDepth = 1.F, + uint32_t clearStencil = 0); void cmdFuncGLES3EndRenderPass(GLES3Device *device); -void cmdFuncGLES3BindState(GLES3Device * device, - GLES3GPUPipelineState * gpuPipelineState, - GLES3GPUInputAssembler * gpuInputAssembler, +void cmdFuncGLES3BindState(GLES3Device *device, + GLES3GPUPipelineState *gpuPipelineState, + GLES3GPUInputAssembler *gpuInputAssembler, const GLES3GPUDescriptorSet *const *gpuDescriptorSets, - const uint32_t * dynamicOffsets = nullptr, - const DynamicStates * dynamicStates = nullptr); + const uint32_t *dynamicOffsets = nullptr, + const DynamicStates *dynamicStates = nullptr); void cmdFuncGLES3Draw(GLES3Device *device, const DrawInfo &drawInfo); -void cmdFuncGLES3UpdateBuffer(GLES3Device * device, +void cmdFuncGLES3UpdateBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer, - const void * buffer, - uint32_t offset, - uint32_t size); + const void *buffer, + uint32_t offset, + uint32_t size); -void cmdFuncGLES3CopyBuffersToTexture(GLES3Device * device, - const uint8_t *const * buffers, - GLES3GPUTexture * gpuTexture, +void cmdFuncGLES3CopyBuffersToTexture(GLES3Device *device, + const uint8_t *const *buffers, + GLES3GPUTexture *gpuTexture, const BufferTextureCopy *regions, - uint32_t count); -void cmdFuncGLES3CopyTextureToBuffers(GLES3Device * device, - GLES3GPUTexture * gpuTexture, - uint8_t *const * buffers, + uint32_t count); +void cmdFuncGLES3CopyTextureToBuffers(GLES3Device *device, + GLES3GPUTexture *gpuTexture, + uint8_t *const *buffers, const BufferTextureCopy *regions, - uint32_t count); + uint32_t count); -void cmdFuncGLES3BlitTexture(GLES3Device * device, - GLES3GPUTexture * gpuTextureSrc, - GLES3GPUTexture * gpuTextureDst, +void cmdFuncGLES3BlitTexture(GLES3Device *device, + GLES3GPUTexture *gpuTextureSrc, + GLES3GPUTexture *gpuTextureDst, const TextureBlit *regions, - uint32_t count, - Filter filter); + uint32_t count, + Filter filter); void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage); diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp index b7ba200b4d..667ca30038 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSet.cpp @@ -46,8 +46,8 @@ GLES3DescriptorSet::~GLES3DescriptorSet() { void GLES3DescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { const GLES3GPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); - const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; - const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); + const size_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; + const size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); _gpuDescriptorSet = ccnew GLES3GPUDescriptorSet; _gpuDescriptorSet->gpuDescriptors.resize(descriptorCount); diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp index 95a2f936fc..3e166617fb 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp @@ -40,11 +40,11 @@ GLES3DescriptorSetLayout::~GLES3DescriptorSetLayout() { } void GLES3DescriptorSetLayout::doInit(const DescriptorSetLayoutInfo & /*info*/) { - _gpuDescriptorSetLayout = ccnew GLES3GPUDescriptorSetLayout; - _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; - _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; + _gpuDescriptorSetLayout = ccnew GLES3GPUDescriptorSetLayout; + _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; + _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; _gpuDescriptorSetLayout->descriptorIndices = _descriptorIndices; - _gpuDescriptorSetLayout->bindings = _bindings; + _gpuDescriptorSetLayout->bindings = _bindings; for (auto &binding : _bindings) { if (hasAnyFlags(binding.descriptorType, DESCRIPTOR_DYNAMIC_TYPE)) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index cccb3f18c7..36422fea8a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -61,7 +61,7 @@ GLES3Device *GLES3Device::getInstance() { } GLES3Device::GLES3Device() { - _api = API::GLES3; + _api = API::GLES3; _deviceName = "GLES3"; GLES3Device::instance = this; @@ -72,10 +72,10 @@ GLES3Device::~GLES3Device() { } bool GLES3Device::doInit(const DeviceInfo & /*info*/) { - _gpuContext = ccnew GLES3GPUContext; - _gpuStateCache = ccnew GLES3GPUStateCache; - _gpuFramebufferHub = ccnew GLES3GPUFramebufferHub; - _gpuConstantRegistry = ccnew GLES3GPUConstantRegistry; + _gpuContext = ccnew GLES3GPUContext; + _gpuStateCache = ccnew GLES3GPUStateCache; + _gpuFramebufferHub = ccnew GLES3GPUFramebufferHub; + _gpuConstantRegistry = ccnew GLES3GPUConstantRegistry; _gpuFramebufferCacheMap = ccnew GLES3GPUFramebufferCacheMap(_gpuStateCache); if (!_gpuContext->initialize(_gpuStateCache, _gpuConstantRegistry)) { @@ -89,7 +89,7 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { uint32_t curSet{_bindingMappingInfo.setIndices[i]}; uint32_t prevSet{i ? _bindingMappingInfo.setIndices[i - 1] : curSet}; // accumulate the per set offset according to the specified capacity - _bindingMappings.blockOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxBlockCounts[prevSet]) + _bindingMappings.blockOffsets[prevSet] : 0; + _bindingMappings.blockOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxBlockCounts[prevSet]) + _bindingMappings.blockOffsets[prevSet] : 0; _bindingMappings.samplerTextureOffsets[curSet] = i ? static_cast(_bindingMappingInfo.maxSamplerTextureCounts[prevSet]) + _bindingMappings.samplerTextureOffsets[prevSet] : 0; } for (uint32_t curSet : _bindingMappingInfo.setIndices) { @@ -99,16 +99,16 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _bindingMappings.flexibleSet = _bindingMappingInfo.setIndices.back(); ccstd::string extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); - _extensions = StringUtil::split(extStr, " "); + _extensions = StringUtil::split(extStr, " "); initFormatFeature(); _multithreadedCommandRecording = false; - _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; - _features[toNumber(Feature::BLEND_MINMAX)] = true; - _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; if (_gpuConstantRegistry->glMinorVersion) { _features[toNumber(Feature::COMPUTE_SHADER)] = true; @@ -170,8 +170,8 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { } _renderer = reinterpret_cast(glGetString(GL_RENDERER)); - _vendor = reinterpret_cast(glGetString(GL_VENDOR)); - _version = reinterpret_cast(glGetString(GL_VERSION)); + _vendor = reinterpret_cast(glGetString(GL_VENDOR)); + _version = reinterpret_cast(glGetString(GL_VERSION)); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast(&_caps.maxVertexAttributes)); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxVertexUniformVectors)); @@ -205,15 +205,15 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); + _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _cmdBuff = createCommandBuffer(cmdBuffInfo); _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxImageUnits, _caps.maxUniformBufferBindings, _caps.maxShaderStorageBufferBindings, _caps.maxVertexAttributes); @@ -253,7 +253,7 @@ void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { void GLES3Device::present() { CC_PROFILE(GLES3DevicePresent); - auto *queue = static_cast(_queue); + auto *queue = static_cast(_queue); _numDrawCalls = queue->_numDrawCalls; _numInstances = queue->_numInstances; _numTriangles = queue->_numTriangles; @@ -280,132 +280,132 @@ void GLES3Device::initFormatFeature() { // builtin tempFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::RENDER_TARGET | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE | FormatFeature::VERTEX_ATTRIBUTE; - _formatFeatures[toNumber(Format::R8)] = tempFeature; - _formatFeatures[toNumber(Format::RG8)] = tempFeature; - _formatFeatures[toNumber(Format::RGB8)] = tempFeature; + _formatFeatures[toNumber(Format::R8)] = tempFeature; + _formatFeatures[toNumber(Format::RG8)] = tempFeature; + _formatFeatures[toNumber(Format::RGB8)] = tempFeature; _formatFeatures[toNumber(Format::RGBA8)] = tempFeature; tempFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::RENDER_TARGET | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE; - _formatFeatures[toNumber(Format::R8SN)] = tempFeature; - _formatFeatures[toNumber(Format::RG8SN)] = tempFeature; - _formatFeatures[toNumber(Format::RGB8SN)] = tempFeature; + _formatFeatures[toNumber(Format::R8SN)] = tempFeature; + _formatFeatures[toNumber(Format::RG8SN)] = tempFeature; + _formatFeatures[toNumber(Format::RGB8SN)] = tempFeature; _formatFeatures[toNumber(Format::RGBA8SN)] = tempFeature; - _formatFeatures[toNumber(Format::R5G6B5)] = tempFeature; - _formatFeatures[toNumber(Format::RGBA4)] = tempFeature; - _formatFeatures[toNumber(Format::RGB5A1)] = tempFeature; + _formatFeatures[toNumber(Format::R5G6B5)] = tempFeature; + _formatFeatures[toNumber(Format::RGBA4)] = tempFeature; + _formatFeatures[toNumber(Format::RGB5A1)] = tempFeature; _formatFeatures[toNumber(Format::RGB10A2)] = tempFeature; - _formatFeatures[toNumber(Format::SRGB8)] = tempFeature; + _formatFeatures[toNumber(Format::SRGB8)] = tempFeature; _formatFeatures[toNumber(Format::SRGB8_A8)] = tempFeature; _formatFeatures[toNumber(Format::R11G11B10F)] = tempFeature; - _formatFeatures[toNumber(Format::RGB9E5)] = tempFeature; + _formatFeatures[toNumber(Format::RGB9E5)] = tempFeature; - _formatFeatures[toNumber(Format::DEPTH)] = tempFeature; + _formatFeatures[toNumber(Format::DEPTH)] = tempFeature; _formatFeatures[toNumber(Format::DEPTH_STENCIL)] = tempFeature; tempFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::RENDER_TARGET | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE | FormatFeature::VERTEX_ATTRIBUTE; - _formatFeatures[toNumber(Format::R16F)] = tempFeature; - _formatFeatures[toNumber(Format::RG16F)] = tempFeature; - _formatFeatures[toNumber(Format::RGB16F)] = tempFeature; + _formatFeatures[toNumber(Format::R16F)] = tempFeature; + _formatFeatures[toNumber(Format::RG16F)] = tempFeature; + _formatFeatures[toNumber(Format::RGB16F)] = tempFeature; _formatFeatures[toNumber(Format::RGBA16F)] = tempFeature; tempFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::RENDER_TARGET | FormatFeature::STORAGE_TEXTURE | FormatFeature::VERTEX_ATTRIBUTE; - _formatFeatures[toNumber(Format::R32F)] = tempFeature; - _formatFeatures[toNumber(Format::RG32F)] = tempFeature; - _formatFeatures[toNumber(Format::RGB32F)] = tempFeature; + _formatFeatures[toNumber(Format::R32F)] = tempFeature; + _formatFeatures[toNumber(Format::RG32F)] = tempFeature; + _formatFeatures[toNumber(Format::RGB32F)] = tempFeature; _formatFeatures[toNumber(Format::RGBA32F)] = tempFeature; _formatFeatures[toNumber(Format::RGB10A2UI)] = FormatFeature::RENDER_TARGET | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE; tempFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::RENDER_TARGET | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE | FormatFeature::VERTEX_ATTRIBUTE; - _formatFeatures[toNumber(Format::R8I)] = tempFeature; - _formatFeatures[toNumber(Format::R8UI)] = tempFeature; - _formatFeatures[toNumber(Format::R16I)] = tempFeature; + _formatFeatures[toNumber(Format::R8I)] = tempFeature; + _formatFeatures[toNumber(Format::R8UI)] = tempFeature; + _formatFeatures[toNumber(Format::R16I)] = tempFeature; _formatFeatures[toNumber(Format::R16UI)] = tempFeature; - _formatFeatures[toNumber(Format::R32I)] = tempFeature; + _formatFeatures[toNumber(Format::R32I)] = tempFeature; _formatFeatures[toNumber(Format::R32UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG8I)] = tempFeature; - _formatFeatures[toNumber(Format::RG8UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG16I)] = tempFeature; + _formatFeatures[toNumber(Format::RG8I)] = tempFeature; + _formatFeatures[toNumber(Format::RG8UI)] = tempFeature; + _formatFeatures[toNumber(Format::RG16I)] = tempFeature; _formatFeatures[toNumber(Format::RG16UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG32I)] = tempFeature; + _formatFeatures[toNumber(Format::RG32I)] = tempFeature; _formatFeatures[toNumber(Format::RG32UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGB8I)] = tempFeature; - _formatFeatures[toNumber(Format::RGB8UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGB16I)] = tempFeature; + _formatFeatures[toNumber(Format::RGB8I)] = tempFeature; + _formatFeatures[toNumber(Format::RGB8UI)] = tempFeature; + _formatFeatures[toNumber(Format::RGB16I)] = tempFeature; _formatFeatures[toNumber(Format::RGB16UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGB32I)] = tempFeature; + _formatFeatures[toNumber(Format::RGB32I)] = tempFeature; _formatFeatures[toNumber(Format::RGB32UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGBA8I)] = tempFeature; - _formatFeatures[toNumber(Format::RGBA8UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGBA16I)] = tempFeature; + _formatFeatures[toNumber(Format::RGBA8I)] = tempFeature; + _formatFeatures[toNumber(Format::RGBA8UI)] = tempFeature; + _formatFeatures[toNumber(Format::RGBA16I)] = tempFeature; _formatFeatures[toNumber(Format::RGBA16UI)] = tempFeature; - _formatFeatures[toNumber(Format::RGBA32I)] = tempFeature; + _formatFeatures[toNumber(Format::RGBA32I)] = tempFeature; _formatFeatures[toNumber(Format::RGBA32UI)] = tempFeature; - _textureExclusive[toNumber(Format::R8)] = false; - _textureExclusive[toNumber(Format::RG8)] = false; - _textureExclusive[toNumber(Format::RGB8)] = false; + _textureExclusive[toNumber(Format::R8)] = false; + _textureExclusive[toNumber(Format::RG8)] = false; + _textureExclusive[toNumber(Format::RGB8)] = false; _textureExclusive[toNumber(Format::R5G6B5)] = false; - _textureExclusive[toNumber(Format::RGBA4)] = false; + _textureExclusive[toNumber(Format::RGBA4)] = false; - _textureExclusive[toNumber(Format::RGB5A1)] = false; - _textureExclusive[toNumber(Format::RGBA8)] = false; - _textureExclusive[toNumber(Format::RGB10A2)] = false; + _textureExclusive[toNumber(Format::RGB5A1)] = false; + _textureExclusive[toNumber(Format::RGBA8)] = false; + _textureExclusive[toNumber(Format::RGB10A2)] = false; _textureExclusive[toNumber(Format::RGB10A2UI)] = false; - _textureExclusive[toNumber(Format::SRGB8_A8)] = false; + _textureExclusive[toNumber(Format::SRGB8_A8)] = false; - _textureExclusive[toNumber(Format::R8I)] = false; - _textureExclusive[toNumber(Format::R8UI)] = false; - _textureExclusive[toNumber(Format::R16I)] = false; + _textureExclusive[toNumber(Format::R8I)] = false; + _textureExclusive[toNumber(Format::R8UI)] = false; + _textureExclusive[toNumber(Format::R16I)] = false; _textureExclusive[toNumber(Format::R16UI)] = false; - _textureExclusive[toNumber(Format::R32I)] = false; + _textureExclusive[toNumber(Format::R32I)] = false; _textureExclusive[toNumber(Format::R32UI)] = false; - _textureExclusive[toNumber(Format::RG8I)] = false; - _textureExclusive[toNumber(Format::RG8UI)] = false; - _textureExclusive[toNumber(Format::RG16I)] = false; + _textureExclusive[toNumber(Format::RG8I)] = false; + _textureExclusive[toNumber(Format::RG8UI)] = false; + _textureExclusive[toNumber(Format::RG16I)] = false; _textureExclusive[toNumber(Format::RG16UI)] = false; - _textureExclusive[toNumber(Format::RG32I)] = false; + _textureExclusive[toNumber(Format::RG32I)] = false; _textureExclusive[toNumber(Format::RG32UI)] = false; - _textureExclusive[toNumber(Format::RGBA8I)] = false; - _textureExclusive[toNumber(Format::RGBA8UI)] = false; - _textureExclusive[toNumber(Format::RGBA16I)] = false; + _textureExclusive[toNumber(Format::RGBA8I)] = false; + _textureExclusive[toNumber(Format::RGBA8UI)] = false; + _textureExclusive[toNumber(Format::RGBA16I)] = false; _textureExclusive[toNumber(Format::RGBA16UI)] = false; - _textureExclusive[toNumber(Format::RGBA32I)] = false; + _textureExclusive[toNumber(Format::RGBA32I)] = false; _textureExclusive[toNumber(Format::RGBA32UI)] = false; - _textureExclusive[toNumber(Format::DEPTH)] = false; + _textureExclusive[toNumber(Format::DEPTH)] = false; _textureExclusive[toNumber(Format::DEPTH_STENCIL)] = false; if (checkExtension("render_snorm")) { // https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_render_snorm.txt // For 16, see https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_norm16.txt - _textureExclusive[toNumber(Format::R8SN)] = false; - _textureExclusive[toNumber(Format::RG8SN)] = false; - _textureExclusive[toNumber(Format::RGB8SN)] = false; + _textureExclusive[toNumber(Format::R8SN)] = false; + _textureExclusive[toNumber(Format::RG8SN)] = false; + _textureExclusive[toNumber(Format::RGB8SN)] = false; _textureExclusive[toNumber(Format::RGBA8SN)] = false; } if (checkExtension("color_buffer_float")) { - _textureExclusive[toNumber(Format::R32F)] = false; - _textureExclusive[toNumber(Format::RG32F)] = false; - _textureExclusive[toNumber(Format::RGB32F)] = false; + _textureExclusive[toNumber(Format::R32F)] = false; + _textureExclusive[toNumber(Format::RG32F)] = false; + _textureExclusive[toNumber(Format::RGB32F)] = false; _textureExclusive[toNumber(Format::RGBA32F)] = false; } if (checkExtension("color_buffer_half_float")) { - _textureExclusive[toNumber(Format::R16F)] = false; - _textureExclusive[toNumber(Format::RG16F)] = false; - _textureExclusive[toNumber(Format::RGB16F)] = false; + _textureExclusive[toNumber(Format::R16F)] = false; + _textureExclusive[toNumber(Format::RG16F)] = false; + _textureExclusive[toNumber(Format::RGB16F)] = false; _textureExclusive[toNumber(Format::RGBA16F)] = false; } @@ -429,11 +429,11 @@ void GLES3Device::initFormatFeature() { _formatFeatures[toNumber(Format::ETC_RGB8)] = compressedFeature; } - _formatFeatures[toNumber(Format::ETC2_RGB8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_RGBA8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_SRGB8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGB8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGBA8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_SRGB8)] = compressedFeature; _formatFeatures[toNumber(Format::ETC2_SRGB8_A8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = compressedFeature; _formatFeatures[toNumber(Format::ETC2_SRGB8_A1)] = compressedFeature; if (checkExtension("texture_compression_pvrtc")) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 18be30569a..a3fb1bf5c1 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -70,10 +70,10 @@ public: inline const GLESBindingMapping &bindingMappings() const { return _bindingMappings; } - inline GLES3GPUContext * context() const { return _gpuContext; } - inline GLES3GPUStateCache * stateCache() const { return _gpuStateCache; } - inline GLES3GPUFramebufferHub * framebufferHub() const { return _gpuFramebufferHub; } - inline GLES3GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } + inline GLES3GPUContext *context() const { return _gpuContext; } + inline GLES3GPUStateCache *stateCache() const { return _gpuStateCache; } + inline GLES3GPUFramebufferHub *framebufferHub() const { return _gpuFramebufferHub; } + inline GLES3GPUConstantRegistry *constantRegistry() const { return _gpuConstantRegistry; } inline GLES3GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } inline bool checkExtension(const ccstd::string &extension) const { @@ -91,24 +91,24 @@ protected: GLES3Device(); - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; - Sampler * createSampler(const SamplerInfo &info) override; + Sampler *createSampler(const SamplerInfo &info) override; GeneralBarrier *createGeneralBarrier(const GeneralBarrierInfo &info) override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; @@ -119,10 +119,10 @@ protected: void initFormatFeature(); - GLES3GPUContext * _gpuContext{nullptr}; - GLES3GPUStateCache * _gpuStateCache{nullptr}; - GLES3GPUFramebufferHub * _gpuFramebufferHub{nullptr}; - GLES3GPUConstantRegistry * _gpuConstantRegistry{nullptr}; + GLES3GPUContext *_gpuContext{nullptr}; + GLES3GPUStateCache *_gpuStateCache{nullptr}; + GLES3GPUFramebufferHub *_gpuFramebufferHub{nullptr}; + GLES3GPUConstantRegistry *_gpuConstantRegistry{nullptr}; GLES3GPUFramebufferCacheMap *_gpuFramebufferCacheMap{nullptr}; ccstd::vector _swapchains; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp index 2d3d0292f1..f0525ff75a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp @@ -43,18 +43,18 @@ GLES3Framebuffer::~GLES3Framebuffer() { } void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { - _gpuFBO = ccnew GLES3GPUFramebuffer; + _gpuFBO = ccnew GLES3GPUFramebuffer; _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorViews.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { - auto *colorTexture = static_cast(_colorTextures[i]); + auto *colorTexture = static_cast(_colorTextures[i]); _gpuFBO->gpuColorViews[i] = colorTexture->gpuTextureView(); GLES3Device::getInstance()->framebufferHub()->connect(colorTexture->gpuTexture(), _gpuFBO); } if (_depthStencilTexture) { - auto *depthTexture = static_cast(_depthStencilTexture); + auto *depthTexture = static_cast(_depthStencilTexture); _gpuFBO->gpuDepthStencilView = depthTexture->gpuTextureView(); GLES3Device::getInstance()->framebufferHub()->connect(depthTexture->gpuTexture(), _gpuFBO); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index 7f376643ed..68ffb2c962 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -86,7 +86,7 @@ void GL_APIENTRY GLES3EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum #endif bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstantRegistry *constantRegistry) { - _stateCache = stateCache; + _stateCache = stateCache; _constantRegistry = constantRegistry; if (!gles3wInit()) { @@ -135,7 +135,7 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan EGL_SAMPLES, sampleSize, EGL_NONE}; - int numConfig{0}; + int numConfig{0}; ccstd::vector eglConfigs; EGL_CHECK(success = eglChooseConfig(eglDisplay, defaultAttribs, nullptr, 0, &numConfig)); @@ -153,11 +153,11 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan return false; } - EGLint depth{0}; - EGLint stencil{0}; - EGLint sampleBuffers{0}; - EGLint sampleCount{0}; - EGLint params[8]{0}; + EGLint depth{0}; + EGLint stencil{0}; + EGLint sampleBuffers{0}; + EGLint sampleCount{0}; + EGLint params[8]{0}; uint64_t lastScore = qualityPreferred ? std::numeric_limits::min() : std::numeric_limits::max(); for (int i = 0; i < numConfig; i++) { @@ -177,7 +177,7 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan /*------------------------------------------ANGLE's priority-----------------------------------------------*/ // Favor EGLConfigLists by RGB, then Depth, then Non-linear Depth, then Stencil, then Alpha uint64_t currScore{0}; - EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); + EGLint colorScore = std::abs(params[0] - redSize) + std::abs(params[1] - greenSize) + std::abs(params[2] - blueSize); currScore |= static_cast(std::min(std::max(params[6], 0), 15)) << 29; currScore |= static_cast(std::min(std::max(params[7], 0), 31)) << 24; currScore |= static_cast(std::min(colorScore, 127)) << 17; @@ -192,12 +192,12 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan // performancePreferred ? [>=] : [<] , egl configurations store in "ascending order" bool filter = (currScore < lastScore) ^ qualityPreferred; if ((filter && msaaLimit) || (!eglConfig && i == numConfig - 1)) { - eglConfig = eglConfigs[i]; - depth = params[4]; - stencil = params[5]; + eglConfig = eglConfigs[i]; + depth = params[4]; + stencil = params[5]; sampleBuffers = params[6]; - sampleCount = params[7]; - lastScore = currScore; + sampleCount = params[7]; + lastScore = currScore; } } @@ -218,9 +218,9 @@ bool GLES3GPUContext::initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstan eglAttributes.push_back(EGL_NONE); for (int m = 2; m >= 0; --m) { - eglAttributes[3] = m; + eglAttributes[3] = m; eglDefaultContext = eglCreateContext(eglDisplay, eglConfig, nullptr, eglAttributes.data()); - EGLint err = eglGetError(); // QNX throws egl errors on mismatch + EGLint err = eglGetError(); // QNX throws egl errors on mismatch if (eglDefaultContext && err == EGL_SUCCESS) { _constantRegistry->glMinorVersion = m; break; @@ -343,7 +343,7 @@ bool GLES3GPUContext::makeCurrent(EGLSurface drawSurface, EGLSurface readSurface if (succeeded && updateCache) { _eglCurrentDrawSurface = drawSurface; _eglCurrentReadSurface = readSurface; - _eglCurrentContext = context; + _eglCurrentContext = context; } return succeeded; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 21d2a713b8..bd86c08d93 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -35,11 +35,11 @@ namespace cc { namespace gfx { struct GLES3GPUConstantRegistry { - size_t currentBoundThreadID{0U}; + size_t currentBoundThreadID{0U}; uint32_t glMinorVersion{0U}; MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; - FBFSupportLevel mFBF{FBFSupportLevel::NONE}; + FBFSupportLevel mFBF{FBFSupportLevel::NONE}; }; class GLES3GPUStateCache; @@ -49,10 +49,10 @@ public: bool initialize(GLES3GPUStateCache *stateCache, GLES3GPUConstantRegistry *constantRegistry); void destroy(); - EGLint eglMajorVersion{0}; - EGLint eglMinorVersion{0}; - EGLDisplay eglDisplay{EGL_NO_DISPLAY}; - EGLConfig eglConfig{nullptr}; + EGLint eglMajorVersion{0}; + EGLint eglMinorVersion{0}; + EGLDisplay eglDisplay{EGL_NO_DISPLAY}; + EGLConfig eglConfig{nullptr}; ccstd::vector eglAttributes; EGLSurface eglDefaultSurface{EGL_NO_SURFACE}; @@ -69,17 +69,17 @@ public: } private: - bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); + bool makeCurrent(EGLSurface drawSurface, EGLSurface readSurface, EGLContext context, bool updateCache = true); EGLContext getSharedContext(); - void resetStates() const; + void resetStates() const; // state caches EGLSurface _eglCurrentDrawSurface{EGL_NO_SURFACE}; EGLSurface _eglCurrentReadSurface{EGL_NO_SURFACE}; EGLContext _eglCurrentContext{EGL_NO_CONTEXT}; - EGLint _eglCurrentInterval{0}; + EGLint _eglCurrentInterval{0}; - GLES3GPUStateCache * _stateCache{nullptr}; + GLES3GPUStateCache *_stateCache{nullptr}; GLES3GPUConstantRegistry *_constantRegistry{nullptr}; ccstd::unordered_map _sharedContexts; @@ -89,9 +89,9 @@ private: class GLES3GPUQueryPool final { public: - QueryType type{QueryType::OCCLUSION}; - uint32_t maxQueryObjects{0}; - bool forceWait{true}; + QueryType type{QueryType::OCCLUSION}; + uint32_t maxQueryObjects{0}; + bool forceWait{true}; ccstd::vector glQueryIds; inline GLuint mapGLQueryId(uint32_t queryId) { @@ -104,54 +104,54 @@ public: }; struct GLES3GPUBuffer { - BufferUsage usage = BufferUsage::NONE; - MemoryUsage memUsage = MemoryUsage::NONE; - uint32_t size = 0; - uint32_t stride = 0; - uint32_t count = 0; - GLenum glTarget = 0; - GLuint glBuffer = 0; - GLuint glOffset = 0; - uint8_t * buffer = nullptr; + BufferUsage usage = BufferUsage::NONE; + MemoryUsage memUsage = MemoryUsage::NONE; + uint32_t size = 0; + uint32_t stride = 0; + uint32_t count = 0; + GLenum glTarget = 0; + GLuint glBuffer = 0; + GLuint glOffset = 0; + uint8_t *buffer = nullptr; DrawInfoList indirects; }; using GLES3GPUBufferList = ccstd::vector; struct GLES3GPUTexture { - TextureType type{TextureType::TEX2D}; - Format format{Format::UNKNOWN}; - TextureUsage usage{TextureUsageBit::NONE}; - uint32_t width{0}; - uint32_t height{0}; - uint32_t depth{1}; - uint32_t size{0}; - uint32_t arrayLayer{1}; - uint32_t mipLevel{1}; - SampleCount samples{SampleCount::ONE}; - TextureFlags flags{TextureFlagBit::NONE}; - bool isPowerOf2{false}; - bool memoryless{false}; - GLenum glTarget{0}; - GLenum glInternalFmt{0}; - GLenum glFormat{0}; - GLenum glType{0}; - GLenum glUsage{0}; - GLint glSamples{0}; - GLuint glTexture{0}; - GLuint glRenderbuffer{0}; - GLenum glWrapS{0}; - GLenum glWrapT{0}; - GLenum glMinFilter{0}; - GLenum glMagFilter{0}; + TextureType type{TextureType::TEX2D}; + Format format{Format::UNKNOWN}; + TextureUsage usage{TextureUsageBit::NONE}; + uint32_t width{0}; + uint32_t height{0}; + uint32_t depth{1}; + uint32_t size{0}; + uint32_t arrayLayer{1}; + uint32_t mipLevel{1}; + SampleCount samples{SampleCount::ONE}; + TextureFlags flags{TextureFlagBit::NONE}; + bool isPowerOf2{false}; + bool memoryless{false}; + GLenum glTarget{0}; + GLenum glInternalFmt{0}; + GLenum glFormat{0}; + GLenum glType{0}; + GLenum glUsage{0}; + GLint glSamples{0}; + GLuint glTexture{0}; + GLuint glRenderbuffer{0}; + GLenum glWrapS{0}; + GLenum glWrapT{0}; + GLenum glMinFilter{0}; + GLenum glMagFilter{0}; GLES3GPUSwapchain *swapchain{nullptr}; }; struct GLES3GPUTextureView { GLES3GPUTexture *gpuTexture{nullptr}; - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - uint32_t baseLevel = 0U; - uint32_t levelCount = 1U; + TextureType type = TextureType::TEX2D; + Format format = Format::UNKNOWN; + uint32_t baseLevel = 0U; + uint32_t levelCount = 1U; }; using GLES3GPUTextureViewList = ccstd::vector; @@ -160,25 +160,25 @@ struct GLES3GPUSwapchain { #if CC_SWAPPY_ENABLED bool swappyEnabled{false}; #endif - EGLSurface eglSurface{EGL_NO_SURFACE}; - EGLint eglSwapInterval{0}; - GLuint glFramebuffer{0}; + EGLSurface eglSurface{EGL_NO_SURFACE}; + EGLint eglSwapInterval{0}; + GLuint glFramebuffer{0}; GLES3GPUTexture *gpuColorTexture{nullptr}; }; class GLES3GPUSampler final { public: - Filter minFilter = Filter::NONE; - Filter magFilter = Filter::NONE; - Filter mipFilter = Filter::NONE; - Address addressU = Address::CLAMP; - Address addressV = Address::CLAMP; - Address addressW = Address::CLAMP; - GLenum glMinFilter = 0; - GLenum glMagFilter = 0; - GLenum glWrapS = 0; - GLenum glWrapT = 0; - GLenum glWrapR = 0; + Filter minFilter = Filter::NONE; + Filter magFilter = Filter::NONE; + Filter mipFilter = Filter::NONE; + Address addressU = Address::CLAMP; + Address addressV = Address::CLAMP; + Address addressW = Address::CLAMP; + GLenum glMinFilter = 0; + GLenum glMagFilter = 0; + GLenum glWrapS = 0; + GLenum glWrapT = 0; + GLenum glWrapR = 0; ~GLES3GPUSampler() { ccstd::vector glSampelrs; @@ -195,63 +195,63 @@ private: }; struct GLES3GPUInput { - uint32_t binding = 0; + uint32_t binding = 0; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t stride = 0; - uint32_t count = 0; - uint32_t size = 0; - GLenum glType = 0; - GLint glLoc = -1; + Type type = Type::UNKNOWN; + uint32_t stride = 0; + uint32_t count = 0; + uint32_t size = 0; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES3GPUInputList = ccstd::vector; struct GLES3GPUUniform { - uint32_t binding = INVALID_BINDING; + uint32_t binding = INVALID_BINDING; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t stride = 0; - uint32_t count = 0; - uint32_t size = 0; - uint32_t offset = 0; - GLenum glType = 0; - GLint glLoc = -1; + Type type = Type::UNKNOWN; + uint32_t stride = 0; + uint32_t count = 0; + uint32_t size = 0; + uint32_t offset = 0; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES3GPUUniformList = ccstd::vector; struct GLES3GPUUniformBuffer { - uint32_t set = INVALID_BINDING; - uint32_t binding = INVALID_BINDING; + uint32_t set = INVALID_BINDING; + uint32_t binding = INVALID_BINDING; ccstd::string name; - uint32_t size = 0; - uint32_t glBinding = 0xffffffff; - bool isStorage = false; + uint32_t size = 0; + uint32_t glBinding = 0xffffffff; + bool isStorage = false; }; using GLES3GPUUniformBufferList = ccstd::vector; struct GLES3GPUUniformSamplerTexture { - uint32_t set = 0; - uint32_t binding = 0; + uint32_t set = 0; + uint32_t binding = 0; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t count = 0U; + Type type = Type::UNKNOWN; + uint32_t count = 0U; ccstd::vector units; - GLenum glType = 0; - GLint glLoc = -1; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES3GPUUniformSamplerTextureList = ccstd::vector; struct GLES3GPUUniformStorageImage { - uint32_t set = 0; - uint32_t binding = 0; + uint32_t set = 0; + uint32_t binding = 0; ccstd::string name; - Type type = Type::UNKNOWN; - uint32_t count = 0U; + Type type = Type::UNKNOWN; + uint32_t count = 0U; ccstd::vector units; - GLenum glMemoryAccess = GL_READ_WRITE; - GLint glLoc = -1; + GLenum glMemoryAccess = GL_READ_WRITE; + GLint glLoc = -1; }; using GLES3GPUUniformStorageImageList = ccstd::vector; @@ -261,50 +261,50 @@ struct GLES3GPUShaderStage { source(std::move(std::move(s))), glShader(shader) {} ShaderStageFlagBit type; - ccstd::string source; - GLuint glShader = 0; + ccstd::string source; + GLuint glShader = 0; }; using GLES3GPUShaderStageList = ccstd::vector; struct GLES3GPUShader { - ccstd::string name; - UniformBlockList blocks; - UniformStorageBufferList buffers; - UniformSamplerTextureList samplerTextures; - UniformSamplerList samplers; - UniformTextureList textures; - UniformStorageImageList images; + ccstd::string name; + UniformBlockList blocks; + UniformStorageBufferList buffers; + UniformSamplerTextureList samplerTextures; + UniformSamplerList samplers; + UniformTextureList textures; + UniformStorageImageList images; UniformInputAttachmentList subpassInputs; - GLES3GPUShaderStageList gpuStages; - GLuint glProgram = 0; - GLES3GPUInputList glInputs; - GLES3GPUUniformBufferList glBuffers; + GLES3GPUShaderStageList gpuStages; + GLuint glProgram = 0; + GLES3GPUInputList glInputs; + GLES3GPUUniformBufferList glBuffers; GLES3GPUUniformSamplerTextureList glSamplerTextures; - GLES3GPUUniformStorageImageList glImages; + GLES3GPUUniformStorageImageList glImages; }; struct GLES3GPUAttribute { ccstd::string name; - GLuint glBuffer = 0; - GLenum glType = 0; - uint32_t size = 0; - uint32_t count = 0; - uint32_t stride = 1; - uint32_t componentCount = 1; - bool isNormalized = false; - bool isInstanced = false; - uint32_t offset = 0; + GLuint glBuffer = 0; + GLenum glType = 0; + uint32_t size = 0; + uint32_t count = 0; + uint32_t stride = 1; + uint32_t componentCount = 1; + bool isNormalized = false; + bool isInstanced = false; + uint32_t offset = 0; }; using GLES3GPUAttributeList = ccstd::vector; struct GLES3GPUInputAssembler { - AttributeList attributes; - GLES3GPUBufferList gpuVertexBuffers; - GLES3GPUBuffer * gpuIndexBuffer = nullptr; - GLES3GPUBuffer * gpuIndirectBuffer = nullptr; - GLES3GPUAttributeList glAttribs; - GLenum glIndexType = 0; + AttributeList attributes; + GLES3GPUBufferList gpuVertexBuffers; + GLES3GPUBuffer *gpuIndexBuffer = nullptr; + GLES3GPUBuffer *gpuIndirectBuffer = nullptr; + GLES3GPUAttributeList glAttribs; + GLenum glIndexType = 0; ccstd::unordered_map glVAOs; }; @@ -312,7 +312,7 @@ struct GLES3GPUGeneralBarrier { AccessFlags prevAccesses = AccessFlagBit::NONE; AccessFlags nextAccesses = AccessFlagBit::NONE; - GLbitfield glBarriers = 0U; + GLbitfield glBarriers = 0U; GLbitfield glBarriersByRegion = 0U; }; @@ -322,9 +322,9 @@ struct GLES3GPURenderPass { uint32_t storeSubpass{SUBPASS_EXTERNAL}; }; - ColorAttachmentList colorAttachments; + ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; - SubpassInfoList subpasses; + SubpassInfoList subpasses; ccstd::vector statistics; // per attachment @@ -334,13 +334,13 @@ struct GLES3GPURenderPass { class GLES3GPUFramebufferCacheMap; class GLES3GPUFramebuffer final { public: - GLES3GPURenderPass * gpuRenderPass{nullptr}; + GLES3GPURenderPass *gpuRenderPass{nullptr}; GLES3GPUTextureViewList gpuColorViews; - GLES3GPUTextureView * gpuDepthStencilView{nullptr}; - bool usesFBF{false}; + GLES3GPUTextureView *gpuDepthStencilView{nullptr}; + bool usesFBF{false}; struct GLFramebufferInfo { - GLuint glFramebuffer{0U}; + GLuint glFramebuffer{0U}; uint32_t width{UINT_MAX}; uint32_t height{UINT_MAX}; }; @@ -348,10 +348,10 @@ public: inline void initialize(GLES3GPUSwapchain *sc) { swapchain = sc; } inline void initialize(const GLFramebufferInfo &info) { _glFramebuffer = info.glFramebuffer; - _width = info.width; - _height = info.height; + _width = info.width; + _height = info.height; } - inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } + inline GLuint getFramebuffer() const { return swapchain ? swapchain->glFramebuffer : _glFramebuffer; } inline uint32_t getWidth() const { return swapchain ? swapchain->gpuColorTexture->width : _width; } inline uint32_t getHeight() const { return swapchain ? swapchain->gpuColorTexture->height : _height; } @@ -360,7 +360,7 @@ public: GLES3GPUSwapchain *swapchain{nullptr}; private: - GLuint _glFramebuffer{0U}; + GLuint _glFramebuffer{0U}; uint32_t _width{0U}; uint32_t _height{0U}; }; @@ -369,7 +369,7 @@ public: GLFramebuffer framebuffer; // for blit-based manual resolving - GLbitfield resolveMask{0U}; + GLbitfield resolveMask{0U}; GLFramebuffer resolveFramebuffer; }; @@ -377,8 +377,8 @@ public: ccstd::vector instances; ccstd::vector uberColorAttachmentIndices; - uint32_t uberDepthStencil{INVALID_BINDING}; - Framebuffer uberInstance; + uint32_t uberDepthStencil{INVALID_BINDING}; + Framebuffer uberInstance; // the assumed shader output, may differ from actual subpass output // see Feature::INPUT_ATTACHMENT_BENEFIT for more details on this @@ -388,11 +388,11 @@ public: struct GLES3GPUDescriptorSetLayout { DescriptorSetLayoutBindingList bindings; - ccstd::vector dynamicBindings; + ccstd::vector dynamicBindings; ccstd::vector bindingIndices; ccstd::vector descriptorIndices; - uint32_t descriptorCount = 0U; + uint32_t descriptorCount = 0U; }; using GLES3GPUDescriptorSetLayoutList = ccstd::vector; @@ -401,33 +401,33 @@ struct GLES3GPUPipelineLayout { // helper storages ccstd::vector> dynamicOffsetIndices; - ccstd::vector dynamicOffsetOffsets; - ccstd::vector dynamicOffsets; - uint32_t dynamicOffsetCount; + ccstd::vector dynamicOffsetOffsets; + ccstd::vector dynamicOffsets; + uint32_t dynamicOffsetCount; }; struct GLES3GPUPipelineState { - GLenum glPrimitive = GL_TRIANGLES; - GLES3GPUShader * gpuShader = nullptr; - RasterizerState rs; - DepthStencilState dss; - BlendState bs; - DynamicStateList dynamicStates; - GLES3GPUPipelineLayout *gpuLayout = nullptr; - GLES3GPURenderPass * gpuRenderPass = nullptr; + GLenum glPrimitive = GL_TRIANGLES; + GLES3GPUShader *gpuShader = nullptr; + RasterizerState rs; + DepthStencilState dss; + BlendState bs; + DynamicStateList dynamicStates; + GLES3GPUPipelineLayout *gpuLayout = nullptr; + GLES3GPURenderPass *gpuRenderPass = nullptr; GLES3GPUPipelineLayout *gpuPipelineLayout = nullptr; }; struct GLES3GPUDescriptor { - DescriptorType type = DescriptorType::UNKNOWN; - GLES3GPUBuffer * gpuBuffer = nullptr; + DescriptorType type = DescriptorType::UNKNOWN; + GLES3GPUBuffer *gpuBuffer = nullptr; GLES3GPUTextureView *gpuTextureView = nullptr; - GLES3GPUSampler * gpuSampler = nullptr; + GLES3GPUSampler *gpuSampler = nullptr; }; using GLES3GPUDescriptorList = ccstd::vector; struct GLES3GPUDescriptorSet { - GLES3GPUDescriptorList gpuDescriptors; + GLES3GPUDescriptorList gpuDescriptors; const ccstd::vector *descriptorIndices = nullptr; }; @@ -437,53 +437,53 @@ struct GLES3GPUDispatchInfo { uint32_t groupCountZ = 0; GLES3GPUBuffer *indirectBuffer = nullptr; - uint32_t indirectOffset = 0; + uint32_t indirectOffset = 0; }; struct GLES3ObjectCache { - uint32_t subpassIdx = 0U; - GLES3GPURenderPass * gpuRenderPass = nullptr; - GLES3GPUFramebuffer * gpuFramebuffer = nullptr; - GLES3GPUPipelineState * gpuPipelineState = nullptr; + uint32_t subpassIdx = 0U; + GLES3GPURenderPass *gpuRenderPass = nullptr; + GLES3GPUFramebuffer *gpuFramebuffer = nullptr; + GLES3GPUPipelineState *gpuPipelineState = nullptr; GLES3GPUInputAssembler *gpuInputAssembler = nullptr; - GLenum glPrimitive = 0; - Rect renderArea; - ColorList clearColors; - float clearDepth = 1.F; - uint32_t clearStencil = 0U; + GLenum glPrimitive = 0; + Rect renderArea; + ColorList clearColors; + float clearDepth = 1.F; + uint32_t clearStencil = 0U; }; class GLES3GPUStateCache final { public: - GLuint glArrayBuffer = 0; - GLuint glElementArrayBuffer = 0; - GLuint glUniformBuffer = 0; - ccstd::vector glBindUBOs; - ccstd::vector glBindUBOOffsets; - GLuint glShaderStorageBuffer = 0; - ccstd::vector glBindSSBOs; - ccstd::vector glBindSSBOOffsets; - GLuint glDispatchIndirectBuffer = 0; - GLuint glVAO = 0; - uint32_t texUint = 0; - ccstd::vector glTextures; - ccstd::vector glImages; - ccstd::vector glSamplers; - GLuint glProgram = 0; - ccstd::vector glEnabledAttribLocs; - ccstd::vector glCurrentAttribLocs; - GLuint glReadFramebuffer = 0; - GLuint glDrawFramebuffer = 0; - GLuint glRenderbuffer = 0; - Viewport viewport; - Rect scissor; - RasterizerState rs; - DepthStencilState dss; - BlendState bs; - bool isCullFaceEnabled = true; - bool isStencilTestEnabled = false; + GLuint glArrayBuffer = 0; + GLuint glElementArrayBuffer = 0; + GLuint glUniformBuffer = 0; + ccstd::vector glBindUBOs; + ccstd::vector glBindUBOOffsets; + GLuint glShaderStorageBuffer = 0; + ccstd::vector glBindSSBOs; + ccstd::vector glBindSSBOOffsets; + GLuint glDispatchIndirectBuffer = 0; + GLuint glVAO = 0; + uint32_t texUint = 0; + ccstd::vector glTextures; + ccstd::vector glImages; + ccstd::vector glSamplers; + GLuint glProgram = 0; + ccstd::vector glEnabledAttribLocs; + ccstd::vector glCurrentAttribLocs; + GLuint glReadFramebuffer = 0; + GLuint glDrawFramebuffer = 0; + GLuint glRenderbuffer = 0; + Viewport viewport; + Rect scissor; + RasterizerState rs; + DepthStencilState dss; + BlendState bs; + bool isCullFaceEnabled = true; + bool isStencilTestEnabled = false; ccstd::unordered_map texUnitCacheMap; - GLES3ObjectCache gfxStateCache; + GLES3ObjectCache gfxStateCache; void initialize(size_t texUnits, size_t imageUnits, size_t uboBindings, size_t ssboBindings, size_t vertexAttributes) { glBindUBOs.resize(uboBindings, 0U); @@ -501,41 +501,41 @@ public: void reset() { if (!_initialized) return; - glArrayBuffer = 0; + glArrayBuffer = 0; glElementArrayBuffer = 0; - glUniformBuffer = 0; + glUniformBuffer = 0; glBindUBOs.assign(glBindUBOs.size(), 0U); glBindUBOOffsets.assign(glBindUBOOffsets.size(), 0U); glShaderStorageBuffer = 0; glBindSSBOs.assign(glBindSSBOs.size(), 0U); glBindSSBOOffsets.assign(glBindSSBOOffsets.size(), 0U); glDispatchIndirectBuffer = 0; - glVAO = 0; - texUint = 0; + glVAO = 0; + texUint = 0; glTextures.assign(glTextures.size(), 0U); glImages.assign(glImages.size(), 0U); glSamplers.assign(glSamplers.size(), 0U); glProgram = 0; glEnabledAttribLocs.assign(glEnabledAttribLocs.size(), false); glCurrentAttribLocs.assign(glCurrentAttribLocs.size(), false); - glReadFramebuffer = 0; - glDrawFramebuffer = 0; - glRenderbuffer = 0; - isCullFaceEnabled = true; + glReadFramebuffer = 0; + glDrawFramebuffer = 0; + glRenderbuffer = 0; + isCullFaceEnabled = true; isStencilTestEnabled = false; viewport = Viewport(); - scissor = Rect(); - rs = RasterizerState(); - dss = DepthStencilState(); - bs = BlendState(); + scissor = Rect(); + rs = RasterizerState(); + dss = DepthStencilState(); + bs = BlendState(); - gfxStateCache.gpuRenderPass = nullptr; - gfxStateCache.gpuFramebuffer = nullptr; - gfxStateCache.gpuPipelineState = nullptr; + gfxStateCache.gpuRenderPass = nullptr; + gfxStateCache.gpuFramebuffer = nullptr; + gfxStateCache.gpuPipelineState = nullptr; gfxStateCache.gpuInputAssembler = nullptr; - gfxStateCache.glPrimitive = 0U; - gfxStateCache.subpassIdx = 0U; + gfxStateCache.glPrimitive = 0U; + gfxStateCache.subpassIdx = 0U; } private: @@ -547,9 +547,9 @@ public: explicit GLES3GPUFramebufferCacheMap(GLES3GPUStateCache *cache) : _cache(cache) {} void registerExternal(GLuint glFramebuffer, const GLES3GPUTexture *gpuTexture, uint32_t mipLevel) { - bool isTexture = gpuTexture->glTexture; + bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; if (cacheMap[glResource].empty()) cacheMap[glResource].resize(gpuTexture->mipLevel); if (!cacheMap[glResource][mipLevel].glFramebuffer) { @@ -577,10 +577,10 @@ public: } GLuint getFramebufferFromTexture(const GLES3GPUTexture *gpuTexture, const TextureSubresLayers &subres) { - bool isTexture = gpuTexture->glTexture; - GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; - uint32_t mipLevel = isTexture ? subres.mipLevel : 0; + bool isTexture = gpuTexture->glTexture; + GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; + uint32_t mipLevel = isTexture ? subres.mipLevel : 0; if (gpuTexture->swapchain) return gpuTexture->swapchain->glFramebuffer; CC_ASSERT(gpuTexture->glTexture || gpuTexture->glRenderbuffer); @@ -595,8 +595,8 @@ public: _cache->glDrawFramebuffer = glFramebuffer; } - const FormatInfo &info = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)]; - GLenum attachment = GL_COLOR_ATTACHMENT0; + const FormatInfo &info = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)]; + GLenum attachment = GL_COLOR_ATTACHMENT0; if (info.hasStencil) { attachment = GL_DEPTH_STENCIL_ATTACHMENT; } else if (info.hasDepth) { @@ -619,9 +619,9 @@ public: } void onTextureDestroy(const GLES3GPUTexture *gpuTexture) { - bool isTexture = gpuTexture->glTexture; + bool isTexture = gpuTexture->glTexture; GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; - auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + auto &cacheMap = isTexture ? _textureMap : _renderbufferMap; if (cacheMap.count(glResource)) { for (auto &record : cacheMap[glResource]) { @@ -642,7 +642,7 @@ private: struct FramebufferRecord { GLuint glFramebuffer{0}; - bool isExternal{false}; + bool isExternal{false}; }; using CacheMap = ccstd::unordered_map>; CacheMap _renderbufferMap; // renderbuffer -> mip level -> framebuffer diff --git a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp index 017d751ff7..912ebb76a4 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3InputAssembler.cpp @@ -42,11 +42,11 @@ GLES3InputAssembler::~GLES3InputAssembler() { } void GLES3InputAssembler::doInit(const InputAssemblerInfo &info) { - _gpuInputAssembler = ccnew GLES3GPUInputAssembler; + _gpuInputAssembler = ccnew GLES3GPUInputAssembler; _gpuInputAssembler->attributes = _attributes; _gpuInputAssembler->gpuVertexBuffers.resize(_vertexBuffers.size()); for (size_t i = 0; i < _gpuInputAssembler->gpuVertexBuffers.size(); ++i) { - auto *vb = static_cast(_vertexBuffers[i]); + auto *vb = static_cast(_vertexBuffers[i]); _gpuInputAssembler->gpuVertexBuffers[i] = vb->gpuBuffer(); } if (info.indexBuffer) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp index 42a5d22cb0..7aa3d47c4a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp @@ -47,10 +47,10 @@ void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { uint32_t offset = 0U; _gpuPipelineLayout->dynamicOffsetIndices.resize(_setLayouts.size()); for (uint32_t i = 0U; i < _setLayouts.size(); i++) { - DescriptorSetLayout * setLayout = _setLayouts[i]; + DescriptorSetLayout *setLayout = _setLayouts[i]; GLES3GPUDescriptorSetLayout *gpuSetLayout = static_cast(setLayout)->gpuDescriptorSetLayout(); - uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); - ccstd::vector & indices = _gpuPipelineLayout->dynamicOffsetIndices[i]; + uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); + ccstd::vector &indices = _gpuPipelineLayout->dynamicOffsetIndices[i]; indices.assign(setLayout->getBindingIndices().size(), -1); for (uint32_t j = 0U; j < dynamicCount; j++) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp index 774215fce6..f55c9208ee 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp @@ -60,12 +60,12 @@ GLES3PipelineState::~GLES3PipelineState() { } void GLES3PipelineState::doInit(const PipelineStateInfo & /*info*/) { - _gpuPipelineState = ccnew GLES3GPUPipelineState; - _gpuPipelineState->glPrimitive = GLE_S3_PRIMITIVES[static_cast(_primitive)]; - _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); - _gpuPipelineState->rs = _rasterizerState; - _gpuPipelineState->dss = _depthStencilState; - _gpuPipelineState->bs = _blendState; + _gpuPipelineState = ccnew GLES3GPUPipelineState; + _gpuPipelineState->glPrimitive = GLE_S3_PRIMITIVES[static_cast(_primitive)]; + _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _gpuPipelineState->rs = _rasterizerState; + _gpuPipelineState->dss = _depthStencilState; + _gpuPipelineState->bs = _blendState; _gpuPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); if (_renderPass) _gpuPipelineState->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index 5d55000af0..aaf6ba0f09 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -65,14 +65,14 @@ void GLES3PrimaryCommandBuffer::end() { void GLES3PrimaryCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint32_t stencil, CommandBuffer *const * /*secondaryCBs*/, uint32_t /*secondaryCBCount*/) { _curSubpassIdx = 0U; - GLES3GPURenderPass * gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); + GLES3GPURenderPass *gpuRenderPass = static_cast(renderPass)->gpuRenderPass(); GLES3GPUFramebuffer *gpuFramebuffer = static_cast(fbo)->gpuFBO(); cmdFuncGLES3BeginRenderPass(GLES3Device::getInstance(), _curSubpassIdx, gpuRenderPass, gpuFramebuffer, &renderArea, colors, depth, stencil); _curDynamicStates.viewport = {renderArea.x, renderArea.y, renderArea.width, renderArea.height}; - _curDynamicStates.scissor = renderArea; + _curDynamicStates.scissor = renderArea; } void GLES3PrimaryCommandBuffer::endRenderPass() { @@ -199,7 +199,7 @@ void GLES3PrimaryCommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t void GLES3PrimaryCommandBuffer::bindStates() { if (_curGPUPipelineState) { ccstd::vector &dynamicOffsetOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsetOffsets; - ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; + ccstd::vector &dynamicOffsets = _curGPUPipelineState->gpuPipelineLayout->dynamicOffsets; for (size_t i = 0U, len = dynamicOffsetOffsets.size() - 1; i < len; i++) { size_t count = dynamicOffsetOffsets[i + 1] - dynamicOffsetOffsets[i]; // CC_ASSERT(_curDynamicOffsets[i].size() >= count); diff --git a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp index a30c4674ae..c393bee321 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp @@ -42,10 +42,10 @@ GLES3QueryPool::~GLES3QueryPool() { void GLES3QueryPool::doInit(const QueryPoolInfo & /*info*/) { GLES3Device *device = GLES3Device::getInstance(); if (device->getCapabilities().supportQuery) { - _gpuQueryPool = ccnew GLES3GPUQueryPool; - _gpuQueryPool->type = _type; + _gpuQueryPool = ccnew GLES3GPUQueryPool; + _gpuQueryPool->type = _type; _gpuQueryPool->maxQueryObjects = _maxQueryObjects; - _gpuQueryPool->forceWait = _forceWait; + _gpuQueryPool->forceWait = _forceWait; _gpuQueryPool->glQueryIds.resize(_maxQueryObjects, 0U); cmdFuncGLES3CreateQueryPool(device, _gpuQueryPool); diff --git a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h index 18eacfb49f..700b29172d 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h +++ b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h @@ -39,12 +39,12 @@ public: ~GLES3QueryPool() override; inline GLES3GPUQueryPool *gpuQueryPool() const { return _gpuQueryPool; } - inline uint32_t getIdCount() const { return static_cast(_ids.size()); } - inline void clearId() { _ids.clear(); } - inline void addId(uint32_t id) { _ids.push_back(id); } - inline uint32_t getId(uint32_t index) const { return _ids[index]; } - inline std::mutex & getMutex() { return _mutex; } - inline void setResults(ccstd::unordered_map &&results) { _results = results; } + inline uint32_t getIdCount() const { return static_cast(_ids.size()); } + inline void clearId() { _ids.clear(); } + inline void addId(uint32_t id) { _ids.push_back(id); } + inline uint32_t getId(uint32_t index) const { return _ids[index]; } + inline std::mutex &getMutex() { return _mutex; } + inline void setResults(ccstd::unordered_map &&results) { _results = results; } protected: friend class GLES3CommandBuffer; @@ -52,7 +52,7 @@ protected: void doInit(const QueryPoolInfo &info) override; void doDestroy() override; - GLES3GPUQueryPool * _gpuQueryPool = nullptr; + GLES3GPUQueryPool *_gpuQueryPool = nullptr; ccstd::vector _ids; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 69413dd007..52d8cfdde8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -42,10 +42,10 @@ GLES3RenderPass::~GLES3RenderPass() { } void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { - _gpuRenderPass = ccnew GLES3GPURenderPass; - _gpuRenderPass->colorAttachments = _colorAttachments; + _gpuRenderPass = ccnew GLES3GPURenderPass; + _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; - _gpuRenderPass->subpasses = _subpasses; + _gpuRenderPass->subpasses = _subpasses; // assign a dummy subpass if not specified uint32_t colorCount = utils::toUint(_gpuRenderPass->colorAttachments.size()); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp b/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp index e767b94818..57ac91ff37 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp @@ -41,15 +41,15 @@ GLES3Shader::~GLES3Shader() { } void GLES3Shader::doInit(const ShaderInfo & /*info*/) { - _gpuShader = ccnew GLES3GPUShader; - _gpuShader->name = _name; - _gpuShader->blocks = _blocks; - _gpuShader->buffers = _buffers; + _gpuShader = ccnew GLES3GPUShader; + _gpuShader->name = _name; + _gpuShader->blocks = _blocks; + _gpuShader->buffers = _buffers; _gpuShader->samplerTextures = _samplerTextures; - _gpuShader->samplers = _samplers; - _gpuShader->textures = _textures; - _gpuShader->images = _images; - _gpuShader->subpassInputs = _subpassInputs; + _gpuShader->samplers = _samplers; + _gpuShader->textures = _textures; + _gpuShader->images = _images; + _gpuShader->subpassInputs = _subpassInputs; for (const auto &stage : _stages) { GLES3GPUShaderStage gpuShaderStage = {stage.stage, stage.source}; _gpuShader->gpuStages.emplace_back(std::move(gpuShaderStage)); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp index 2821c9be6b..294d8aa548 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -53,7 +53,7 @@ GLES3Swapchain::~GLES3Swapchain() { void GLES3Swapchain::doInit(const SwapchainInfo &info) { const auto *context = GLES3Device::getInstance()->context(); - _gpuSwapchain = ccnew GLES3GPUSwapchain; + _gpuSwapchain = ccnew GLES3GPUSwapchain; #if CC_PLATFORM == CC_PLATFORM_LINUX auto window = reinterpret_cast(info.windowHandle); #else @@ -68,9 +68,9 @@ void GLES3Swapchain::doInit(const SwapchainInfo &info) { } #if CC_SWAPPY_ENABLED - bool enableSwappy = true; - auto* platform = static_cast(cc::BasePlatform::getPlatform()); - enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); + bool enableSwappy = true; + auto *platform = static_cast(cc::BasePlatform::getPlatform()); + enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); int32_t fps = cc::BasePlatform::getPlatform()->getFps(); if (enableSwappy) { if (!fps) @@ -85,7 +85,7 @@ void GLES3Swapchain::doInit(const SwapchainInfo &info) { #endif - auto width = static_cast(info.width); + auto width = static_cast(info.width); auto height = static_cast(info.height); #if CC_PLATFORM == CC_PLATFORM_ANDROID @@ -113,14 +113,14 @@ void GLES3Swapchain::doInit(const SwapchainInfo &info) { ///////////////////// Texture Creation ///////////////////// - _colorTexture = ccnew GLES3Texture; + _colorTexture = ccnew GLES3Texture; _depthStencilTexture = ccnew GLES3Texture; SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = Format::RGBA8; - textureInfo.width = info.width; - textureInfo.height = info.height; + textureInfo.format = Format::RGBA8; + textureInfo.width = info.width; + textureInfo.height = info.height; initTexture(textureInfo, _colorTexture); textureInfo.format = Format::DEPTH_STENCIL; @@ -176,7 +176,7 @@ void GLES3Swapchain::doCreateSurface(void *windowHandle) { return; } - auto width = static_cast(_colorTexture->getWidth()); + auto width = static_cast(_colorTexture->getWidth()); auto height = static_cast(_colorTexture->getHeight()); CC_UNUSED_PARAM(width); CC_UNUSED_PARAM(height); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index e7a325e75c..334a23a666 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -44,20 +44,20 @@ GLES3Texture::~GLES3Texture() { } void GLES3Texture::doInit(const TextureInfo & /*info*/) { - _gpuTexture = ccnew GLES3GPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew GLES3GPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; - _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; - _gpuTexture->flags = _info.flags; - _gpuTexture->size = _size; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; _gpuTexture->isPowerOf2 = math::IsPowerOfTwo(_info.width) && math::IsPowerOfTwo(_info.height); - _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); + _gpuTexture->glTexture = static_cast(reinterpret_cast(_info.externalRes)); cmdFuncGLES3CreateTexture(GLES3Device::getInstance(), _gpuTexture); @@ -81,9 +81,9 @@ void GLES3Texture::doInit(const TextureViewInfo & /*info*/) { void GLES3Texture::createTextureView() { _gpuTextureView->gpuTexture = _gpuTexture; - _gpuTextureView->type = _viewInfo.type; - _gpuTextureView->format = _viewInfo.format; - _gpuTextureView->baseLevel = _viewInfo.baseLevel; + _gpuTextureView->type = _viewInfo.type; + _gpuTextureView->format = _viewInfo.format; + _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; } @@ -110,9 +110,9 @@ void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { CC_PROFILE_MEMORY_DEC(Texture, _size); } - _gpuTexture->width = width; - _gpuTexture->height = height; - _gpuTexture->size = size; + _gpuTexture->width = width; + _gpuTexture->height = height; + _gpuTexture->size = size; _gpuTexture->mipLevel = _info.levelCount; cmdFuncGLES3ResizeTexture(GLES3Device::getInstance(), _gpuTexture); @@ -128,21 +128,21 @@ void GLES3Texture::doResize(uint32_t width, uint32_t height, uint32_t size) { ///////////////////////////// Swapchain Specific ///////////////////////////// void GLES3Texture::doInit(const SwapchainTextureInfo & /*info*/) { - _gpuTexture = ccnew GLES3GPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew GLES3GPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayer = _info.layerCount; - _gpuTexture->mipLevel = _info.levelCount; - _gpuTexture->samples = _info.samples; - _gpuTexture->flags = _info.flags; - _gpuTexture->size = _size; + _gpuTexture->mipLevel = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; _gpuTexture->memoryless = true; - _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); - _gpuTextureView = ccnew GLES3GPUTextureView; + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); + _gpuTextureView = ccnew GLES3GPUTextureView; createTextureView(); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.h b/native/cocos/renderer/gfx-gles3/GLES3Texture.h index 8188c56c81..bef82055d7 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.h @@ -38,7 +38,7 @@ public: GLES3Texture(); ~GLES3Texture() override; - inline GLES3GPUTexture * gpuTexture() const { return _gpuTexture; } + inline GLES3GPUTexture *gpuTexture() const { return _gpuTexture; } inline GLES3GPUTextureView *gpuTextureView() const { return _gpuTextureView; } protected: @@ -50,7 +50,7 @@ protected: void createTextureView(); - GLES3GPUTexture * _gpuTexture = nullptr; + GLES3GPUTexture *_gpuTexture = nullptr; GLES3GPUTextureView *_gpuTextureView = nullptr; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp index 68f11291fa..2f9121480c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp @@ -29,11 +29,11 @@ #define WIN32_LEAN_AND_MEAN 1 #include -static HMODULE libegl = NULL; +static HMODULE libegl = NULL; static HMODULE libgles = NULL; bool gles3wOpen() { - libegl = LoadLibraryA("libEGL.dll"); + libegl = LoadLibraryA("libEGL.dll"); libgles = LoadLibraryA("libGLESv2.dll"); return (libegl && libgles); } @@ -60,19 +60,19 @@ void *gles3wLoad(const char *proc) { return res; } #elif defined(__EMSCRIPTEN__) -bool gles3wOpen() { return true; } -bool gles3wClose() { return true; } +bool gles3wOpen() { return true; } +bool gles3wClose() { return true; } void *gles3wLoad(const char *proc) { return (void *)eglGetProcAddress(proc); } #else #include -static void *libegl = nullptr; +static void *libegl = nullptr; static void *libgles = nullptr; bool gles3wOpen() { - libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); + libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); #if __OHOS__ libgles = dlopen("libGLESv3.so", RTLD_LAZY | RTLD_GLOBAL); #else diff --git a/native/cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.cpp b/native/cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.cpp index 9dcda963d0..a112233cbe 100644 --- a/native/cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.cpp +++ b/native/cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.cpp @@ -33,7 +33,7 @@ namespace gfx { GLES3GeneralBarrier::GLES3GeneralBarrier(const GeneralBarrierInfo &info) : GeneralBarrier(info) { _typedID = generateObjectID(); - _gpuBarrier = ccnew GLES3GPUGeneralBarrier; + _gpuBarrier = ccnew GLES3GPUGeneralBarrier; _gpuBarrier->prevAccesses = info.prevAccesses; _gpuBarrier->nextAccesses = info.nextAccesses; diff --git a/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp index 442ae118a9..e777b372cc 100644 --- a/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp +++ b/native/cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp @@ -33,13 +33,13 @@ namespace gfx { GLES3Sampler::GLES3Sampler(const SamplerInfo &info) : Sampler(info) { _typedID = generateObjectID(); - _gpuSampler = ccnew GLES3GPUSampler; + _gpuSampler = ccnew GLES3GPUSampler; _gpuSampler->minFilter = _info.minFilter; _gpuSampler->magFilter = _info.magFilter; _gpuSampler->mipFilter = _info.mipFilter; - _gpuSampler->addressU = _info.addressU; - _gpuSampler->addressV = _info.addressV; - _gpuSampler->addressW = _info.addressW; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; // GL is not thread-safe, so any actual gl invocations need to be deferred to device thread cmdFuncGLES3PrepareSamplerInfo(GLES3Device::getInstance(), _gpuSampler); diff --git a/native/cocos/renderer/gfx-metal/MTLBuffer.h b/native/cocos/renderer/gfx-metal/MTLBuffer.h index a18d96b1f2..288e6510b3 100644 --- a/native/cocos/renderer/gfx-metal/MTLBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLBuffer.h @@ -42,7 +42,7 @@ public: explicit CCMTLBuffer(); ~CCMTLBuffer(); CCMTLBuffer(const CCMTLBuffer &) = delete; - CCMTLBuffer(CCMTLBuffer &&) = delete; + CCMTLBuffer(CCMTLBuffer &&) = delete; CCMTLBuffer &operator=(const CCMTLBuffer &) = default; CCMTLBuffer &operator=(CCMTLBuffer &&) = delete; @@ -52,9 +52,9 @@ public: id getMTLBuffer() const; - inline CCMTLGPUBuffer * gpuBuffer() { return _gpuBuffer; } - inline MTLIndexType getIndexType() const { return _indexType; } - inline bool isDrawIndirectByIndex() const { return _isDrawIndirectByIndex; } + inline CCMTLGPUBuffer *gpuBuffer() { return _gpuBuffer; } + inline MTLIndexType getIndexType() const { return _indexType; } + inline bool isDrawIndirectByIndex() const { return _isDrawIndirectByIndex; } inline const DrawInfoList &getDrawInfos() const { return _drawInfos; } protected: @@ -66,15 +66,15 @@ protected: bool createMTLBuffer(uint size, MemoryUsage usage); void updateMTLBuffer(const void *buffer, uint offset, uint size); - MTLIndexType _indexType = MTLIndexTypeUInt16; - MTLResourceOptions _mtlResourceOptions = MTLResourceStorageModePrivate; - bool _isIndirectDrawSupported = false; - uint _bufferViewOffset = 0; + MTLIndexType _indexType = MTLIndexTypeUInt16; + MTLResourceOptions _mtlResourceOptions = MTLResourceStorageModePrivate; + bool _isIndirectDrawSupported = false; + uint _bufferViewOffset = 0; - bool _isDrawIndirectByIndex = false; + bool _isDrawIndirectByIndex = false; ccstd::vector _indexedPrimitivesIndirectArguments; - ccstd::vector _primitiveIndirectArguments; - DrawInfoList _drawInfos; + ccstd::vector _primitiveIndirectArguments; + DrawInfoList _drawInfos; CCMTLGPUBuffer *_gpuBuffer = nullptr; }; diff --git a/native/cocos/renderer/gfx-metal/MTLBuffer.mm b/native/cocos/renderer/gfx-metal/MTLBuffer.mm index 87fcb25a68..4427da057f 100644 --- a/native/cocos/renderer/gfx-metal/MTLBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLBuffer.mm @@ -53,7 +53,7 @@ void CCMTLBuffer::doInit(const BufferInfo &info) { _gpuBuffer->size = _size; _gpuBuffer->startOffset = _offset; _gpuBuffer->stride = _stride; - + _isIndirectDrawSupported = CCMTLDevice::getInstance()->isIndirectDrawSupported(); if (hasFlag(_usage, BufferUsage::INDEX)) { switch (_stride) { @@ -83,7 +83,7 @@ void CCMTLBuffer::doInit(const BufferInfo &info) { } void CCMTLBuffer::doInit(const BufferViewInfo &info) { - auto* ccBuffer = static_cast(info.buffer); + auto *ccBuffer = static_cast(info.buffer); _gpuBuffer = ccBuffer->gpuBuffer(); _indexType = ccBuffer->getIndexType(); _mtlResourceOptions = ccBuffer->_mtlResourceOptions; @@ -97,10 +97,10 @@ void CCMTLBuffer::doInit(const BufferViewInfo &info) { } bool CCMTLBuffer::createMTLBuffer(uint size, MemoryUsage usage) { - if(!size) { + if (!size) { return false; } - + _mtlResourceOptions = mu::toMTLResourceOption(usage); if (_gpuBuffer->mtlBuffer) { @@ -109,7 +109,7 @@ bool CCMTLBuffer::createMTLBuffer(uint size, MemoryUsage usage) { std::function destroyFunc = [=]() { if (mtlBuffer) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here -// [mtlBuffer setPurgeableState:MTLPurgeableStateEmpty]; + // [mtlBuffer setPurgeableState:MTLPurgeableStateEmpty]; [mtlBuffer release]; } }; @@ -145,21 +145,21 @@ void CCMTLBuffer::doDestroy() { _drawInfos.clear(); } - if(_gpuBuffer) { + if (_gpuBuffer) { id mtlBuffer = _gpuBuffer->mtlBuffer; _gpuBuffer->mtlBuffer = nil; std::function destroyFunc = [=]() { if (mtlBuffer) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here -// [mtlBuffer setPurgeableState:MTLPurgeableStateEmpty]; + // [mtlBuffer setPurgeableState:MTLPurgeableStateEmpty]; [mtlBuffer release]; } }; //gpu object only CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc); } - + CC_SAFE_DELETE(_gpuBuffer); } @@ -198,7 +198,6 @@ void CCMTLBuffer::update(const void *buffer, uint size) { _isDrawIndirectByIndex = false; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { - uint drawInfoCount = size / _stride; const auto *drawInfo = static_cast(buffer); if (drawInfoCount > 0) { @@ -263,17 +262,17 @@ void CCMTLBuffer::encodeBuffer(CCMTLCommandEncoder &encoder, uint offset, uint b } if (hasFlag(stages, ShaderStageFlagBit::VERTEX)) { - CCMTLRenderCommandEncoder* renderEncoder = static_cast(&encoder); + CCMTLRenderCommandEncoder *renderEncoder = static_cast(&encoder); renderEncoder->setVertexBuffer(_gpuBuffer->mtlBuffer, offset, binding); } if (hasFlag(stages, ShaderStageFlagBit::FRAGMENT)) { - CCMTLRenderCommandEncoder* renderEncoder = static_cast(&encoder); + CCMTLRenderCommandEncoder *renderEncoder = static_cast(&encoder); renderEncoder->setFragmentBuffer(_gpuBuffer->mtlBuffer, offset, binding); } - if(hasFlag(stages, ShaderStageFlagBit::COMPUTE)) { - CCMTLComputeCommandEncoder* computeEncoder = static_cast(&encoder); + if (hasFlag(stages, ShaderStageFlagBit::COMPUTE)) { + CCMTLComputeCommandEncoder *computeEncoder = static_cast(&encoder); computeEncoder->setBuffer(_gpuBuffer->mtlBuffer, offset, binding); } } diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index 6f4e09221b..aee5b57f71 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -49,39 +49,39 @@ public: explicit CCMTLCommandBuffer(); ~CCMTLCommandBuffer(); CCMTLCommandBuffer(const CCMTLCommandBuffer &) = delete; - CCMTLCommandBuffer(CCMTLCommandBuffer &&) = delete; + CCMTLCommandBuffer(CCMTLCommandBuffer &&) = delete; CCMTLCommandBuffer &operator=(const CCMTLCommandBuffer &) = delete; CCMTLCommandBuffer &operator=(CCMTLCommandBuffer &&) = delete; - void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; - void end() override; - void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const *secondaryCBs, uint secondaryCBCount) override; - void endRenderPass() override; - void bindPipelineState(PipelineState *pso) override; - void bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) override; - void bindInputAssembler(InputAssembler *ia) override; - void setViewport(const Viewport &vp) override; - void setScissor(const Rect &rect) override; - void setLineWidth(float width) override; - void setDepthBias(float constant, float clamp, float slope) override; - void setBlendConstants(const Color &constants) override; - void setDepthBound(float minBounds, float maxBounds) override; - void setStencilWriteMask(StencilFace face, uint mask) override; - void setStencilCompareMask(StencilFace face, uint ref, uint mask) override; - void nextSubpass() override; - void draw(const DrawInfo &info) override; - void updateBuffer(Buffer *buff, const void *data, uint size) override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint count) override; - void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) override; - void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; - void dispatch(const DispatchInfo &info) override; - void pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint textureBarrierCount) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count); - void beginQuery(QueryPool *queryPool, uint32_t id) override; - void endQuery(QueryPool *queryPool, uint32_t id) override; - void resetQueryPool(QueryPool *queryPool) override; - void completeQueryPool(QueryPool *queryPool) override; - inline bool isCommandBufferBegan() const { return _commandBufferBegan; } + void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; + void end() override; + void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const *secondaryCBs, uint secondaryCBCount) override; + void endRenderPass() override; + void bindPipelineState(PipelineState *pso) override; + void bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) override; + void bindInputAssembler(InputAssembler *ia) override; + void setViewport(const Viewport &vp) override; + void setScissor(const Rect &rect) override; + void setLineWidth(float width) override; + void setDepthBias(float constant, float clamp, float slope) override; + void setBlendConstants(const Color &constants) override; + void setDepthBound(float minBounds, float maxBounds) override; + void setStencilWriteMask(StencilFace face, uint mask) override; + void setStencilCompareMask(StencilFace face, uint ref, uint mask) override; + void nextSubpass() override; + void draw(const DrawInfo &info) override; + void updateBuffer(Buffer *buff, const void *data, uint size) override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint count) override; + void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) override; + void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; + void dispatch(const DispatchInfo &info) override; + void pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint textureBarrierCount) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count); + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQueryPool(QueryPool *queryPool) override; + void completeQueryPool(QueryPool *queryPool) override; + inline bool isCommandBufferBegan() const { return _commandBufferBegan; } inline CCMTLGPUCommandBufferObject *gpuCommandBufferObj() const { return _gpuCommandBufferObj; } void reset(); @@ -92,25 +92,25 @@ protected: void doInit(const CommandBufferInfo &info) override; void doDestroy() override; - void bindDescriptorSets(); - void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor *descriptor); + void bindDescriptorSets(); + void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor *descriptor); static bool isRenderingEntireDrawable(const Rect &rect, const CCMTLFramebuffer *renderPass); id getMTLCommandBuffer(); ccstd::vector _GPUDescriptorSets; // NOLINT(bugprone-reserved-identifier) - ccstd::vector> _dynamicOffsets; - uint _firstDirtyDescriptorSet = UINT_MAX; + ccstd::vector> _dynamicOffsets; + uint _firstDirtyDescriptorSet = UINT_MAX; - bool _indirectDrawSuppotred = false; - bool _commandBufferBegan = false; - bool _firstRenderPass = true; - CCMTLDevice * _mtlDevice = nullptr; - id _mtlCommandQueue = nil; - CCMTLRenderCommandEncoder _renderEncoder; - CCMTLComputeCommandEncoder _computeEncoder; - id _parallelEncoder = nil; - MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; + bool _indirectDrawSuppotred = false; + bool _commandBufferBegan = false; + bool _firstRenderPass = true; + CCMTLDevice *_mtlDevice = nullptr; + id _mtlCommandQueue = nil; + CCMTLRenderCommandEncoder _renderEncoder; + CCMTLComputeCommandEncoder _computeEncoder; + id _parallelEncoder = nil; + MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; CCMTLGPUCommandBufferObject *_gpuCommandBufferObj = nullptr; diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 6f7979143d..66503d19ec 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -48,8 +48,8 @@ namespace gfx { CCMTLCommandBuffer::CCMTLCommandBuffer() : CommandBuffer(), _mtlDevice(CCMTLDevice::getInstance()) { - _typedID = generateObjectID(); - _mtlCommandQueue = id(_mtlDevice->getMTLCommandQueue()); + _typedID = generateObjectID(); + _mtlCommandQueue = id(_mtlDevice->getMTLCommandQueue()); _indirectDrawSuppotred = _mtlDevice->isIndirectDrawSupported(); const auto setCount = _mtlDevice->bindingMappingInfo().setIndices.size(); @@ -69,8 +69,8 @@ void CCMTLCommandBuffer::doInit(const CommandBufferInfo &info) { void CCMTLCommandBuffer::doDestroy() { CC_SAFE_DELETE(_texCopySemaphore); - if(_commandBufferBegan) { - if(_gpuCommandBufferObj && _gpuCommandBufferObj->mtlCommandBuffer) { + if (_commandBufferBegan) { + if (_gpuCommandBufferObj && _gpuCommandBufferObj->mtlCommandBuffer) { [_gpuCommandBufferObj->mtlCommandBuffer commit]; } _commandBufferBegan = false; @@ -79,19 +79,19 @@ void CCMTLCommandBuffer::doDestroy() { _GPUDescriptorSets.clear(); _dynamicOffsets.clear(); _firstDirtyDescriptorSet = UINT_MAX; - _indirectDrawSuppotred = false; - _mtlDevice = nullptr; - _mtlCommandQueue = nil; - _parallelEncoder = nil; + _indirectDrawSuppotred = false; + _mtlDevice = nullptr; + _mtlCommandQueue = nil; + _parallelEncoder = nil; CC_SAFE_DELETE(_gpuCommandBufferObj); } bool CCMTLCommandBuffer::isRenderingEntireDrawable(const Rect &rect, const CCMTLFramebuffer *fbo) { - const auto& colors = fbo->getColorTextures(); + const auto &colors = fbo->getColorTextures(); bool res = true; - for(size_t i = 0; i < fbo->getColorTextures().size(); ++i) { - if(!(rect.x == 0 && rect.y == 0 && rect.width == colors[i]->getWidth() && rect.height == colors[i]->getHeight())) { + for (size_t i = 0; i < fbo->getColorTextures().size(); ++i) { + if (!(rect.x == 0 && rect.y == 0 && rect.width == colors[i]->getWidth() && rect.height == colors[i]->getHeight())) { res = false; } } @@ -99,7 +99,7 @@ bool CCMTLCommandBuffer::isRenderingEntireDrawable(const Rect &rect, const CCMTL } id CCMTLCommandBuffer::getMTLCommandBuffer() { - if(!_gpuCommandBufferObj->mtlCommandBuffer) { + if (!_gpuCommandBufferObj->mtlCommandBuffer) { auto *mtlQueue = static_cast(_queue)->gpuQueueObj()->mtlCommandQueue; _gpuCommandBufferObj->mtlCommandBuffer = [mtlQueue commandBuffer]; [_gpuCommandBufferObj->mtlCommandBuffer enqueue]; @@ -121,8 +121,8 @@ void CCMTLCommandBuffer::begin(RenderPass *renderPass, uint subpass, Framebuffer dynamicOffset.clear(); } _firstDirtyDescriptorSet = UINT_MAX; - _commandBufferBegan = true; - _firstRenderPass = true; + _commandBufferBegan = true; + _firstRenderPass = true; _colorAppearedBefore.reset(); } @@ -147,20 +147,20 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb } _gpuCommandBufferObj->renderPass = static_cast(renderPass); - _gpuCommandBufferObj->fbo = static_cast(fbo); + _gpuCommandBufferObj->fbo = static_cast(fbo); - auto * ccMtlRenderPass = static_cast(renderPass); - auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen(); - const SubpassInfoList & subpasses = renderPass->getSubpasses(); + auto *ccMtlRenderPass = static_cast(renderPass); + auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen(); + const SubpassInfoList &subpasses = renderPass->getSubpasses(); const ColorAttachmentList &colorAttachments = renderPass->getColorAttachments(); MTLRenderPassDescriptor *mtlRenderPassDescriptor = static_cast(renderPass)->getMTLRenderPassDescriptor(); - const TextureList & colorTextures = fbo->getColorTextures(); - Texture * dsTexture = fbo->getDepthStencilTexture(); - auto * swapchain = static_cast(_gpuCommandBufferObj->fbo->swapChain()); + const TextureList &colorTextures = fbo->getColorTextures(); + Texture *dsTexture = fbo->getDepthStencilTexture(); + auto *swapchain = static_cast(_gpuCommandBufferObj->fbo->swapChain()); // if not rendering to full framebuffer(eg. left top area), draw a quad to pretend viewport clear. - bool renderingFullFramebuffer = isRenderingEntireDrawable(renderArea, static_cast(fbo)); + bool renderingFullFramebuffer = isRenderingEntireDrawable(renderArea, static_cast(fbo)); bool needPartialClear = false; if (subpasses.empty()) { if (dsTexture) { @@ -179,16 +179,16 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb for (size_t i = 0; i < colorAttachments.size(); ++i) { auto *ccMtlTexture = static_cast(colorTextures[i]); ccMtlRenderPass->setColorAttachment(i, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[i].clearColor = mu::toMTLClearColor(colors[i]); - if(!renderingFullFramebuffer) { - if(!_colorAppearedBefore[i]) { - mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); + mtlRenderPassDescriptor.colorAttachments[i].clearColor = mu::toMTLClearColor(colors[i]); + if (!renderingFullFramebuffer) { + if (!_colorAppearedBefore[i]) { + mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); } else { - mtlRenderPassDescriptor.colorAttachments[i].loadAction = MTLLoadActionLoad; + mtlRenderPassDescriptor.colorAttachments[i].loadAction = MTLLoadActionLoad; needPartialClear = colorAttachments[i].loadOp == LoadOp::CLEAR; } } else { - mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); + mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); } _colorAppearedBefore.set(i); mtlRenderPassDescriptor.colorAttachments[i].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[i].storeOp) : MTLStoreActionStore; @@ -204,10 +204,10 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb continue; auto *ccMtlTexture = static_cast(colorTextures[input]); ccMtlRenderPass->setColorAttachment(input, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[input].clearColor = mu::toMTLClearColor(colors[input]); - mtlRenderPassDescriptor.colorAttachments[input].loadAction = mu::toMTLLoadAction(colorAttachments[input].loadOp); + mtlRenderPassDescriptor.colorAttachments[input].clearColor = mu::toMTLClearColor(colors[input]); + mtlRenderPassDescriptor.colorAttachments[input].loadAction = mu::toMTLLoadAction(colorAttachments[input].loadOp); mtlRenderPassDescriptor.colorAttachments[input].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[input].storeOp) : MTLStoreActionStore; - visited[input] = true; + visited[input] = true; } for (size_t j = 0; j < subpasses[i].colors.size(); ++j) { uint32_t color = subpasses[i].colors[j]; @@ -215,45 +215,45 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb continue; auto *ccMtlTexture = static_cast(colorTextures[color]); ccMtlRenderPass->setColorAttachment(color, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[color].clearColor = mu::toMTLClearColor(colors[color]); - if(!renderingFullFramebuffer) { - if(!_colorAppearedBefore[color]) { - mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); + mtlRenderPassDescriptor.colorAttachments[color].clearColor = mu::toMTLClearColor(colors[color]); + if (!renderingFullFramebuffer) { + if (!_colorAppearedBefore[color]) { + mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); } else { - mtlRenderPassDescriptor.colorAttachments[color].loadAction = MTLLoadActionLoad; + mtlRenderPassDescriptor.colorAttachments[color].loadAction = MTLLoadActionLoad; needPartialClear = colorAttachments[color].loadOp == LoadOp::CLEAR; } } else { - mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); + mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); } mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; - visited[color] = true; + visited[color] = true; _colorAppearedBefore.set(color); if (subpasses[i].resolves.size() > j) { - uint32_t resolve = subpasses[i].resolves[j]; - auto * resolveTex = static_cast(colorTextures[resolve]); + uint32_t resolve = subpasses[i].resolves[j]; + auto *resolveTex = static_cast(colorTextures[resolve]); if (resolveTex->textureInfo().samples == SampleCount::ONE) continue; - mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); - mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); + mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; - mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; } } for (size_t j = 0; j < subpasses[i].preserves.size(); ++j) { - uint32_t preserves = subpasses[i].preserves[j]; + uint32_t preserves = subpasses[i].preserves[j]; mtlRenderPassDescriptor.colorAttachments[preserves].storeAction = MTLStoreActionStoreAndMultisampleResolve; } } updateDepthStencilState(ccMtlRenderPass->getCurrentSubpassIndex(), mtlRenderPassDescriptor); } - mtlRenderPassDescriptor.depthAttachment.clearDepth = clampf(depth, 0.0F, 1.0F); + mtlRenderPassDescriptor.depthAttachment.clearDepth = clampf(depth, 0.0F, 1.0F); mtlRenderPassDescriptor.stencilAttachment.clearStencil = stencil; - auto *queryPool = static_cast(_mtlDevice->getQueryPool()); + auto *queryPool = static_cast(_mtlDevice->getQueryPool()); mtlRenderPassDescriptor.visibilityResultBuffer = _mtlDevice->getCapabilities().supportQuery ? queryPool->gpuQueryPool()->visibilityResultBuffer : nil; id mtlCommandBuffer = getMTLCommandBuffer(); @@ -264,7 +264,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb CCMTLCommandBuffer *cmdBuff = (CCMTLCommandBuffer *)secondaryCBs[i]; cmdBuff->_renderEncoder.initialize(_parallelEncoder); cmdBuff->_gpuCommandBufferObj->mtlCommandBuffer = mtlCommandBuffer; - cmdBuff->_gpuCommandBufferObj->isSecondary = true; + cmdBuff->_gpuCommandBufferObj->isSecondary = true; } } else { _renderEncoder.initialize(mtlCommandBuffer, mtlRenderPassDescriptor); @@ -279,13 +279,13 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb Rect scissorArea = renderArea; #if defined(CC_DEBUG) && (CC_DEBUG > 0) const Vec2 renderTargetSize = ccMtlRenderPass->getRenderTargetSizes()[0]; - scissorArea.width = MIN(scissorArea.width, renderTargetSize.x - scissorArea.x); - scissorArea.height = MIN(scissorArea.height, renderTargetSize.y - scissorArea.y); + scissorArea.width = MIN(scissorArea.width, renderTargetSize.x - scissorArea.x); + scissorArea.height = MIN(scissorArea.height, renderTargetSize.y - scissorArea.y); #endif _renderEncoder.setViewport(scissorArea); _renderEncoder.setScissor(scissorArea); - if(_firstRenderPass) { + if (_firstRenderPass) { _firstRenderPass = false; } } @@ -302,29 +302,29 @@ void CCMTLCommandBuffer::endRenderPass() { } void CCMTLCommandBuffer::reset() { - _gpuCommandBufferObj->renderPass = nullptr; - _gpuCommandBufferObj->fbo = nullptr; - _gpuCommandBufferObj->inputAssembler = nullptr; - _gpuCommandBufferObj->pipelineState = nullptr; + _gpuCommandBufferObj->renderPass = nullptr; + _gpuCommandBufferObj->fbo = nullptr; + _gpuCommandBufferObj->inputAssembler = nullptr; + _gpuCommandBufferObj->pipelineState = nullptr; _gpuCommandBufferObj->mtlCommandBuffer = nil; } void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDescriptor *descriptor) { - CCMTLRenderPass * curRenderPass = _gpuCommandBufferObj->renderPass; - CCMTLFramebuffer * curFBO = _gpuCommandBufferObj->fbo; - const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); + CCMTLRenderPass *curRenderPass = _gpuCommandBufferObj->renderPass; + CCMTLFramebuffer *curFBO = _gpuCommandBufferObj->fbo; + const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); - const DepthStencilAttachment& dsAttachment = curRenderPass->getDepthStencilAttachment(); - const SubpassInfo& subpass = subpasses[index]; + const DepthStencilAttachment &dsAttachment = curRenderPass->getDepthStencilAttachment(); + const SubpassInfo &subpass = subpasses[index]; if (subpass.depthStencil != INVALID_BINDING) { const TextureList &colorTextures = curFBO->getColorTextures(); if (subpass.depthStencil >= colorTextures.size()) { - auto *ccMTLTexture = static_cast(curFBO->getDepthStencilTexture()); + auto *ccMTLTexture = static_cast(curFBO->getDepthStencilTexture()); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); if (ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); } else { - auto *ccMTLTexture = static_cast(colorTextures[subpass.depthStencil]); + auto *ccMTLTexture = static_cast(colorTextures[subpass.depthStencil]); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); if (ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); @@ -332,19 +332,19 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe //the first and last time using depth buffer are affected respectively by load and store op. //loadop - if(index == 0) { - descriptor.depthAttachment.loadAction = dsAttachment.depthLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; + if (index == 0) { + descriptor.depthAttachment.loadAction = dsAttachment.depthLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; descriptor.stencilAttachment.loadAction = dsAttachment.stencilLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; } else { - descriptor.depthAttachment.loadAction = MTLLoadActionLoad; + descriptor.depthAttachment.loadAction = MTLLoadActionLoad; descriptor.stencilAttachment.loadAction = MTLLoadActionLoad; } //storeop - if(index == subpasses.size() - 1) { - descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; + if (index == subpasses.size() - 1) { + descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; descriptor.stencilAttachment.storeAction = dsAttachment.stencilStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; } else { - descriptor.depthAttachment.storeAction = MTLStoreActionStore; + descriptor.depthAttachment.storeAction = MTLStoreActionStore; descriptor.stencilAttachment.storeAction = MTLStoreActionStore; } @@ -355,58 +355,57 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe } else { dsResolveTex = static_cast(colorTextures[subpass.depthStencilResolve]); } - descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); - descriptor.depthAttachment.resolveLevel = 0; - descriptor.depthAttachment.resolveSlice = 0; + descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.depthAttachment.resolveLevel = 0; + descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; - descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; + descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); - descriptor.stencilAttachment.resolveLevel = 0; - descriptor.stencilAttachment.resolveSlice = 0; + descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.stencilAttachment.resolveLevel = 0; + descriptor.stencilAttachment.resolveSlice = 0; descriptor.stencilAttachment.resolveDepthPlane = 0; - descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; + descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; descriptor.depthAttachment.depthResolveFilter = mu::toMTLDepthResolveMode(subpass.depthResolveMode); if (@available(iOS 12.0, *)) { descriptor.stencilAttachment.stencilResolveFilter = mu::toMTLStencilResolveMode(subpass.stencilResolveMode); } - if(index == subpasses.size() - 1) { - descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionMultisampleResolve; + if (index == subpasses.size() - 1) { + descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionMultisampleResolve; descriptor.stencilAttachment.storeAction = dsAttachment.stencilStoreOp == StoreOp::STORE ? MTLStoreActionStoreAndMultisampleResolve : MTLStoreActionMultisampleResolve; } else { - descriptor.depthAttachment.storeAction = MTLStoreActionStoreAndMultisampleResolve; + descriptor.depthAttachment.storeAction = MTLStoreActionStoreAndMultisampleResolve; descriptor.stencilAttachment.storeAction = MTLStoreActionStoreAndMultisampleResolve; } - } - } else if(curRenderPass->getDepthStencilAttachment().format != Format::UNKNOWN) { - if(index == 0) { - descriptor.depthAttachment.loadAction = dsAttachment.depthLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; + } else if (curRenderPass->getDepthStencilAttachment().format != Format::UNKNOWN) { + if (index == 0) { + descriptor.depthAttachment.loadAction = dsAttachment.depthLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; descriptor.stencilAttachment.loadAction = dsAttachment.stencilLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear; } else { - descriptor.depthAttachment.loadAction = MTLLoadActionLoad; + descriptor.depthAttachment.loadAction = MTLLoadActionLoad; descriptor.stencilAttachment.loadAction = MTLLoadActionLoad; } //storeop - if(index == subpasses.size() - 1) { - descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; + if (index == subpasses.size() - 1) { + descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; descriptor.stencilAttachment.storeAction = dsAttachment.stencilStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare; } else { - descriptor.depthAttachment.storeAction = MTLStoreActionStore; + descriptor.depthAttachment.storeAction = MTLStoreActionStore; descriptor.stencilAttachment.storeAction = MTLStoreActionStore; } } } void CCMTLCommandBuffer::bindPipelineState(PipelineState *pso) { - PipelineBindPoint bindPoint = pso->getBindPoint(); - CCMTLGPUPipelineState *pplState = nullptr; - auto * ccPipeline = static_cast(pso); + PipelineBindPoint bindPoint = pso->getBindPoint(); + CCMTLGPUPipelineState *pplState = nullptr; + auto *ccPipeline = static_cast(pso); if (bindPoint == PipelineBindPoint::GRAPHICS) { ccPipeline->check(_gpuCommandBufferObj->renderPass); - pplState = ccPipeline->getGPUPipelineState(); + pplState = ccPipeline->getGPUPipelineState(); _mtlPrimitiveType = pplState->primitiveType; _renderEncoder.setCullMode(pplState->cullMode); @@ -497,24 +496,24 @@ void CCMTLCommandBuffer::nextSubpass() { bool setTexNeeded = !mu::isFramebufferFetchSupported(); if (setTexNeeded) { _renderEncoder.endEncoding(); - uint curSubpassIndex = ccRenderpass->getCurrentSubpassIndex(); - auto * mtlRenderPassDescriptor = ccRenderpass->getMTLRenderPassDescriptor(); - const auto &colorAttachments = curRenderPass->getColorAttachments(); - const auto colorAttachmentCount = colorAttachments.size(); - const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); + uint curSubpassIndex = ccRenderpass->getCurrentSubpassIndex(); + auto *mtlRenderPassDescriptor = ccRenderpass->getMTLRenderPassDescriptor(); + const auto &colorAttachments = curRenderPass->getColorAttachments(); + const auto colorAttachmentCount = colorAttachments.size(); + const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); for (size_t slot = 0U; slot < colorAttachmentCount; slot++) { - mtlRenderPassDescriptor.colorAttachments[slot].loadAction = _colorAppearedBefore[slot] ? MTLLoadActionLoad : mu::toMTLLoadAction(colorAttachments[slot].loadOp); + mtlRenderPassDescriptor.colorAttachments[slot].loadAction = _colorAppearedBefore[slot] ? MTLLoadActionLoad : mu::toMTLLoadAction(colorAttachments[slot].loadOp); mtlRenderPassDescriptor.colorAttachments[slot].storeAction = curSubpassIndex == subpasses.size() - 1 ? mu::toMTLStoreAction(colorAttachments[slot].storeOp) : MTLStoreActionStore; _colorAppearedBefore.set(slot); } updateDepthStencilState(curSubpassIndex, mtlRenderPassDescriptor); _renderEncoder.initialize(getMTLCommandBuffer(), ccRenderpass->getMTLRenderPassDescriptor()); - const TextureList & colorTextures = _gpuCommandBufferObj->fbo->getColorTextures(); + const TextureList &colorTextures = _gpuCommandBufferObj->fbo->getColorTextures(); if (!subpasses.empty()) { const auto &inputs = subpasses[curSubpassIndex].inputs; for (size_t i = 0; i < inputs.size(); i++) { - const uint input = inputs[i]; - auto * ccMtlTexture = static_cast(colorTextures[input]); + const uint input = inputs[i]; + auto *ccMtlTexture = static_cast(colorTextures[input]); _renderEncoder.setFragmentTexture(ccMtlTexture->getMTLTexture(), input); } } @@ -528,9 +527,9 @@ void CCMTLCommandBuffer::draw(const DrawInfo &info) { bindDescriptorSets(); } CCMTLInputAssembler *inputAssembler = _gpuCommandBufferObj->inputAssembler; - const auto * indirectBuffer = static_cast(inputAssembler->getIndirectBuffer()); - const auto * indexBuffer = static_cast(inputAssembler->getIndexBuffer()); - auto mtlEncoder = _renderEncoder.getMTLEncoder(); + const auto *indirectBuffer = static_cast(inputAssembler->getIndirectBuffer()); + const auto *indexBuffer = static_cast(inputAssembler->getIndexBuffer()); + auto mtlEncoder = _renderEncoder.getMTLEncoder(); if (indirectBuffer) { const auto indirectMTLBuffer = indirectBuffer->getMTLBuffer(); @@ -550,10 +549,10 @@ void CCMTLCommandBuffer::draw(const DrawInfo &info) { indirectBufferOffset:0]; } } else { - uint stride = indirectBuffer->getStride(); - uint offset = 0; - uint drawInfoCount = indirectBuffer->getCount(); - const auto &drawInfos = indirectBuffer->getDrawInfos(); + uint stride = indirectBuffer->getStride(); + uint offset = 0; + uint drawInfoCount = indirectBuffer->getCount(); + const auto &drawInfos = indirectBuffer->getDrawInfos(); _numDrawCalls += drawInfoCount; for (uint i = 0; i < drawInfoCount; ++i) { @@ -662,41 +661,41 @@ void CCMTLCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex return; } - uint totalSize = 0; - ccstd::vector bufferSize(count); + uint totalSize = 0; + ccstd::vector bufferSize(count); ccstd::vector stagingRegions(count); - auto format = texture->getFormat(); - auto * mtlTexture = static_cast(texture); - auto convertedFormat = mtlTexture->getConvertedFormat(); + auto format = texture->getFormat(); + auto *mtlTexture = static_cast(texture); + auto convertedFormat = mtlTexture->getConvertedFormat(); for (size_t i = 0; i < count; i++) { - const auto ®ion = regions[i]; - auto & stagingRegion = stagingRegions[i]; - auto w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; - auto h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; - bufferSize[i] = w * h; - stagingRegion.sourceBytesPerRow = mu::getBytesPerRow(convertedFormat, w); + const auto ®ion = regions[i]; + auto &stagingRegion = stagingRegions[i]; + auto w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + auto h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + bufferSize[i] = w * h; + stagingRegion.sourceBytesPerRow = mu::getBytesPerRow(convertedFormat, w); stagingRegion.sourceBytesPerImage = formatSize(convertedFormat, w, h, region.texExtent.depth); - stagingRegion.sourceSize = {w, h, region.texExtent.depth}; - stagingRegion.destinationSlice = region.texSubres.baseArrayLayer; - stagingRegion.destinationLevel = region.texSubres.mipLevel; - stagingRegion.destinationOrigin = { + stagingRegion.sourceSize = {w, h, region.texExtent.depth}; + stagingRegion.destinationSlice = region.texSubres.baseArrayLayer; + stagingRegion.destinationLevel = region.texSubres.mipLevel; + stagingRegion.destinationOrigin = { static_cast(region.texOffset.x), static_cast(region.texOffset.y), static_cast(region.texOffset.z)}; totalSize += stagingRegion.sourceBytesPerImage; } - size_t offset = 0; - id encoder = [getMTLCommandBuffer() blitCommandEncoder]; - id dstTexture = mtlTexture->getMTLTexture(); - const bool isArrayTexture = mtlTexture->isArray(); + size_t offset = 0; + id encoder = [getMTLCommandBuffer() blitCommandEncoder]; + id dstTexture = mtlTexture->getMTLTexture(); + const bool isArrayTexture = mtlTexture->isArray(); for (size_t i = 0; i < count; i++) { - const auto &stagingRegion = stagingRegions[i]; - const auto *convertedData = mu::convertData(buffers[i], bufferSize[i], format); - const auto sourceBytesPerImage = isArrayTexture ? stagingRegion.sourceBytesPerImage : 0; - MTLRegion region = {stagingRegion.destinationOrigin, stagingRegion.sourceSize}; - auto bytesPerRow = mtlTexture->isPVRTC() ? 0 : stagingRegion.sourceBytesPerRow; - auto bytesPerImage = mtlTexture->isPVRTC() ? 0 : sourceBytesPerImage; + const auto &stagingRegion = stagingRegions[i]; + const auto *convertedData = mu::convertData(buffers[i], bufferSize[i], format); + const auto sourceBytesPerImage = isArrayTexture ? stagingRegion.sourceBytesPerImage : 0; + MTLRegion region = {stagingRegion.destinationOrigin, stagingRegion.sourceSize}; + auto bytesPerRow = mtlTexture->isPVRTC() ? 0 : stagingRegion.sourceBytesPerRow; + auto bytesPerImage = mtlTexture->isPVRTC() ? 0 : sourceBytesPerImage; [dstTexture replaceRegion:region mipmapLevel:stagingRegion.destinationLevel slice:stagingRegion.destinationSlice @@ -725,30 +724,30 @@ void CCMTLCommandBuffer::execute(CommandBuffer *const *commandBuffs, uint32_t co } void CCMTLCommandBuffer::bindDescriptorSets() { - CCMTLInputAssembler * inputAssembler = _gpuCommandBufferObj->inputAssembler; + CCMTLInputAssembler *inputAssembler = _gpuCommandBufferObj->inputAssembler; CCMTLGPUPipelineState *pipelineStateObj = _gpuCommandBufferObj->pipelineState->getGPUPipelineState(); - const auto & vertexBuffers = inputAssembler->getVertexBuffers(); + const auto &vertexBuffers = inputAssembler->getVertexBuffers(); for (const auto &bindingInfo : pipelineStateObj->vertexBufferBindingInfo) { - auto index = std::get<0>(bindingInfo); + auto index = std::get<0>(bindingInfo); auto stream = std::get<1>(bindingInfo); static_cast(vertexBuffers[stream])->encodeBuffer(_renderEncoder, 0, index, ShaderStageFlagBit::VERTEX); } const auto &dynamicOffsetIndices = pipelineStateObj->gpuPipelineLayout->dynamicOffsetIndices; - const auto &blocks = pipelineStateObj->gpuShader->blocks; + const auto &blocks = pipelineStateObj->gpuShader->blocks; for (const auto &iter : blocks) { const auto &block = iter.second; const auto *gpuDescriptorSet = _GPUDescriptorSets[block.set]; - const auto descriptorIndex = gpuDescriptorSet->descriptorIndices->at(block.binding); - const auto &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const auto descriptorIndex = gpuDescriptorSet->descriptorIndices->at(block.binding); + const auto &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; if (!gpuDescriptor.buffer) { CC_LOG_ERROR("Buffer binding %s at set %d binding %d is not bounded.", block.name.c_str(), block.set, block.binding); continue; } - const auto &dynamicOffset = dynamicOffsetIndices[block.set]; - auto dynamicOffsetIndex = (block.binding < dynamicOffset.size()) ? dynamicOffset[block.binding] : -1; + const auto &dynamicOffset = dynamicOffsetIndices[block.set]; + auto dynamicOffsetIndex = (block.binding < dynamicOffset.size()) ? dynamicOffset[block.binding] : -1; if (gpuDescriptor.buffer) { uint offset = (dynamicOffsetIndex >= 0) ? _dynamicOffsets[block.set][dynamicOffsetIndex] : 0; // compute pipeline and render pipeline mutually exlusive @@ -771,8 +770,8 @@ void CCMTLCommandBuffer::bindDescriptorSets() { const auto &sampler = iter.second; const auto *gpuDescriptorSet = _GPUDescriptorSets[sampler.set]; - const auto descriptorIndex = gpuDescriptorSet->descriptorIndices->at(sampler.binding); - const auto &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; + const auto descriptorIndex = gpuDescriptorSet->descriptorIndices->at(sampler.binding); + const auto &gpuDescriptor = gpuDescriptorSet->gpuDescriptors[descriptorIndex]; if (!gpuDescriptor.texture || !gpuDescriptor.sampler) { CC_LOG_ERROR("Sampler binding %s at set %d binding %d is not bounded.", sampler.name.c_str(), sampler.set, sampler.binding); @@ -820,16 +819,16 @@ void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c //format conversion MTLTextureDescriptor *descriptor = [[MTLTextureDescriptor alloc] init]; - descriptor.width = src.width; - descriptor.height = src.height; - descriptor.depth = src.depth; - descriptor.pixelFormat = dst.pixelFormat; - descriptor.textureType = src.textureType; - descriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead; - descriptor.storageMode = MTLStorageModePrivate; + descriptor.width = src.width; + descriptor.height = src.height; + descriptor.depth = src.depth; + descriptor.pixelFormat = dst.pixelFormat; + descriptor.textureType = src.textureType; + descriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead; + descriptor.storageMode = MTLStorageModePrivate; // 1. format conversion - id formatTex = [mtlDevice newTextureWithDescriptor:descriptor]; + id formatTex = [mtlDevice newTextureWithDescriptor:descriptor]; MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice:mtlDevice srcAlpha:MPSAlphaTypeNonPremultiplied destAlpha:MPSAlphaTypeNonPremultiplied backgroundColor:nil conversionInfo:nil]; [conversion encodeToCommandBuffer:cmdBuffer sourceTexture:src destinationTexture:formatTex]; [conversion release]; @@ -843,12 +842,12 @@ void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c id sizeTex = formatTex; if ([dst width] > [src width] || [dst height] > [src height]) { // 2. size conversion - descriptor.width = dst.width; - descriptor.height = dst.height; - descriptor.depth = dst.depth; + descriptor.width = dst.width; + descriptor.height = dst.height; + descriptor.depth = dst.depth; descriptor.pixelFormat = dst.pixelFormat; descriptor.textureType = dst.textureType; - descriptor.usage = MTLTextureUsageShaderWrite; + descriptor.usage = MTLTextureUsageShaderWrite; sizeTex = [mtlDevice newTextureWithDescriptor:descriptor]; @@ -865,12 +864,12 @@ void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c id encoder = [cmdBuffer blitCommandEncoder]; for (uint i = 0; i < count; ++i) { // source region scale - uint32_t width = (uint32_t)(regions[i].srcExtent.width * scaleFactorW); + uint32_t width = (uint32_t)(regions[i].srcExtent.width * scaleFactorW); uint32_t height = (uint32_t)(regions[i].srcExtent.height * scaleFactorH); - uint32_t depth = (uint32_t)(regions[i].srcExtent.depth * scaleFactorD); - uint32_t x = (uint32_t)(regions[i].srcOffset.x * scaleFactorW); - uint32_t y = (uint32_t)(regions[i].srcOffset.y * scaleFactorH); - uint32_t z = (uint32_t)(regions[i].srcOffset.z * scaleFactorD); + uint32_t depth = (uint32_t)(regions[i].srcExtent.depth * scaleFactorD); + uint32_t x = (uint32_t)(regions[i].srcOffset.x * scaleFactorW); + uint32_t y = (uint32_t)(regions[i].srcOffset.y * scaleFactorH); + uint32_t z = (uint32_t)(regions[i].srcOffset.z * scaleFactorD); [encoder copyFromTexture:sizeTex sourceSlice:regions[i].srcSubres.baseArrayLayer sourceLevel:regions[i].srcSubres.mipLevel @@ -905,19 +904,19 @@ void CCMTLCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Te } void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count) { - auto * ccMTLTexture = static_cast(src); - Format convertedFormat = ccMTLTexture->getConvertedFormat(); - id mtlTexture = ccMTLTexture->getMTLTexture(); + auto *ccMTLTexture = static_cast(src); + Format convertedFormat = ccMTLTexture->getConvertedFormat(); + id mtlTexture = ccMTLTexture->getMTLTexture(); - if([mtlTexture storageMode] == MTLStorageModeShared) { + if ([mtlTexture storageMode] == MTLStorageModeShared) { for (size_t i = 0; i < count; ++i) { - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; - uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); - uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); - const Offset &origin = regions[i].texOffset; - const Extent &extent = regions[i].texExtent; + uint32_t width = regions[i].texExtent.width; + uint32_t height = regions[i].texExtent.height; + uint32_t depth = regions[i].texExtent.depth; + uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); + uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); + const Offset &origin = regions[i].texOffset; + const Extent &extent = regions[i].texExtent; [mtlTexture getBytes:buffers[i] bytesPerRow:bytesPerRow @@ -929,38 +928,38 @@ void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buff } else { id mtlCommandBuffer = getMTLCommandBuffer(); - ccstd::vector> stagingAddrs(count); + ccstd::vector> stagingAddrs(count); for (size_t i = 0; i < count; ++i) { - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; - uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); - uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); - const Offset &origin = regions[i].texOffset; - const Extent &extent = regions[i].texExtent; + uint32_t width = regions[i].texExtent.width; + uint32_t height = regions[i].texExtent.height; + uint32_t depth = regions[i].texExtent.depth; + uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); + uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); + const Offset &origin = regions[i].texOffset; + const Extent &extent = regions[i].texExtent; id encoder = [mtlCommandBuffer blitCommandEncoder]; CCMTLGPUBuffer stagingBuffer; stagingBuffer.size = bytesPerImage; _mtlDevice->gpuStagingBufferPool()->alloc(&stagingBuffer); [encoder copyFromTexture:mtlTexture - sourceSlice:regions[i].texSubres.baseArrayLayer - sourceLevel:regions[i].texSubres.mipLevel - sourceOrigin:MTLOriginMake(origin.x, origin.y, origin.z) - sourceSize:MTLSizeMake(extent.width, extent.height, extent.depth) - toBuffer:stagingBuffer.mtlBuffer - destinationOffset:0 - destinationBytesPerRow:bytesPerRow - destinationBytesPerImage:bytesPerImage]; + sourceSlice:regions[i].texSubres.baseArrayLayer + sourceLevel:regions[i].texSubres.mipLevel + sourceOrigin:MTLOriginMake(origin.x, origin.y, origin.z) + sourceSize:MTLSizeMake(extent.width, extent.height, extent.depth) + toBuffer:stagingBuffer.mtlBuffer + destinationOffset:0 + destinationBytesPerRow:bytesPerRow + destinationBytesPerImage:bytesPerImage]; [encoder endEncoding]; stagingAddrs[i] = {stagingBuffer.mappedData, bytesPerImage}; } - if(!_texCopySemaphore) { + if (!_texCopySemaphore) { _texCopySemaphore = ccnew CCMTLSemaphore(0); } [mtlCommandBuffer addCompletedHandler:^(id commandBuffer) { - for(size_t i = 0; i < count; ++i) { + for (size_t i = 0; i < count; ++i) { memcpy(buffers[i], stagingAddrs[i].first, stagingAddrs[i].second); } _texCopySemaphore->signal(); @@ -973,7 +972,7 @@ void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buff void CCMTLCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { auto *mtlQueryPool = static_cast(queryPool); - auto queryId = static_cast(mtlQueryPool->_ids.size()); + auto queryId = static_cast(mtlQueryPool->_ids.size()); if (queryId < queryPool->getMaxQueryObjects()) { auto *mtlEncoder = _renderEncoder.getMTLEncoder(); @@ -983,7 +982,7 @@ void CCMTLCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { void CCMTLCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { auto *mtlQueryPool = static_cast(queryPool); - auto queryId = static_cast(mtlQueryPool->_ids.size()); + auto queryId = static_cast(mtlQueryPool->_ids.size()); if (queryId < queryPool->getMaxQueryObjects()) { auto *mtlEncoder = _renderEncoder.getMTLEncoder(); @@ -999,7 +998,7 @@ void CCMTLCommandBuffer::resetQueryPool(QueryPool *queryPool) { } void CCMTLCommandBuffer::completeQueryPool(QueryPool *queryPool) { - auto * mtlQueryPool = static_cast(queryPool); + auto *mtlQueryPool = static_cast(queryPool); CCMTLGPUQueryPool *gpuQueryPool = mtlQueryPool->gpuQueryPool(); id mtlCommandBuffer = getMTLCommandBuffer(); diff --git a/native/cocos/renderer/gfx-metal/MTLCommandEncoder.h b/native/cocos/renderer/gfx-metal/MTLCommandEncoder.h index b90c483e28..114221c7ce 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandEncoder.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandEncoder.h @@ -30,7 +30,7 @@ namespace gfx { class CCMTLCommandEncoder { public: - CCMTLCommandEncoder() = default; + CCMTLCommandEncoder() = default; virtual ~CCMTLCommandEncoder() = default; }; diff --git a/native/cocos/renderer/gfx-metal/MTLComputeCommandEncoder.h b/native/cocos/renderer/gfx-metal/MTLComputeCommandEncoder.h index bc73265f31..34a9ca6ea7 100644 --- a/native/cocos/renderer/gfx-metal/MTLComputeCommandEncoder.h +++ b/native/cocos/renderer/gfx-metal/MTLComputeCommandEncoder.h @@ -36,15 +36,15 @@ namespace cc { namespace gfx { class CCMTLComputeCommandEncoder final : public CCMTLCommandEncoder { public: - CCMTLComputeCommandEncoder() = default; - ~CCMTLComputeCommandEncoder() = default; + CCMTLComputeCommandEncoder() = default; + ~CCMTLComputeCommandEncoder() = default; CCMTLComputeCommandEncoder(const CCMTLComputeCommandEncoder &) = delete; - CCMTLComputeCommandEncoder(CCMTLComputeCommandEncoder &&) = delete; + CCMTLComputeCommandEncoder(CCMTLComputeCommandEncoder &&) = delete; CCMTLComputeCommandEncoder &operator=(const CCMTLComputeCommandEncoder &) = delete; CCMTLComputeCommandEncoder &operator=(CCMTLComputeCommandEncoder &&) = delete; void initialize(id commandBuffer) { - _mtlEncoder = [[commandBuffer computeCommandEncoder] retain]; + _mtlEncoder = [[commandBuffer computeCommandEncoder] retain]; _initialized = true; } @@ -72,9 +72,9 @@ public: // GLSL -> SPIRV -> MSL // GLSL shader request to specify the compute thread size, // no such limit in Metal and have to set compute thread size explicity - NSUInteger w = _pipelineState.threadExecutionWidth; - NSUInteger h = _pipelineState.maxTotalThreadsPerThreadgroup / w; - MTLSize threadsPerThreadgroup = MTLSizeMake(w, h, 1); + NSUInteger w = _pipelineState.threadExecutionWidth; + NSUInteger h = _pipelineState.maxTotalThreadsPerThreadgroup / w; + MTLSize threadsPerThreadgroup = MTLSizeMake(w, h, 1); [_mtlEncoder dispatchThreadgroups:groupsPerGrid threadsPerThreadgroup:threadsPerThreadgroup]; } @@ -85,9 +85,9 @@ public: inline void endEncoding() { [_mtlEncoder endEncoding]; [_mtlEncoder release]; - _mtlEncoder = nil; + _mtlEncoder = nil; _pipelineState = nil; - _initialized = false; + _initialized = false; } inline id const getMTLEncoder() { @@ -95,10 +95,10 @@ public: } private: - bool _initialized = false; - MTLSize _resourceSize; - id _mtlEncoder = nil; - id _pipelineState = nil; + bool _initialized = false; + MTLSize _resourceSize; + id _mtlEncoder = nil; + id _pipelineState = nil; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.h b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.h index 5792d55002..46416126e5 100644 --- a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.h +++ b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.h @@ -37,7 +37,7 @@ public: explicit CCMTLDescriptorSet(); ~CCMTLDescriptorSet(); CCMTLDescriptorSet(const CCMTLDescriptorSet &) = delete; - CCMTLDescriptorSet(CCMTLDescriptorSet &&) = delete; + CCMTLDescriptorSet(CCMTLDescriptorSet &&) = delete; CCMTLDescriptorSet &operator=(const CCMTLDescriptorSet &) = delete; CCMTLDescriptorSet &operator=(CCMTLDescriptorSet &&) = delete; diff --git a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm index 78ad18f89e..daf3856b1a 100644 --- a/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm +++ b/native/cocos/renderer/gfx-metal/MTLDescriptorSet.mm @@ -69,23 +69,22 @@ void CCMTLDescriptorSet::update() { _gpuDescriptorSet->gpuDescriptors[i].buffer = static_cast(_buffers[i]); } } else if (hasAnyFlags(descriptors[i].type, DESCRIPTOR_TEXTURE_TYPE)) { - if(!_textures[i] && !_samplers[i]) + if (!_textures[i] && !_samplers[i]) continue; - - Texture* tex = _textures[i]; - if(!tex) + + Texture *tex = _textures[i]; + if (!tex) tex = CCMTLTexture::getDefaultTexture(); _gpuDescriptorSet->gpuDescriptors[i].texture = static_cast(tex); - - Sampler* sampler = _samplers[i]; - if(!sampler) + + Sampler *sampler = _samplers[i]; + if (!sampler) sampler = CCMTLSampler::getDefaultSampler(); _gpuDescriptorSet->gpuDescriptors[i].sampler = static_cast(sampler); - } } _isDirty = false; } } -} -} +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.h b/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.h index 28dbaf7cd4..83ab7af5d7 100644 --- a/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.h +++ b/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.h @@ -36,7 +36,7 @@ public: explicit CCMTLDescriptorSetLayout(); ~CCMTLDescriptorSetLayout(); CCMTLDescriptorSetLayout(const CCMTLDescriptorSetLayout &) = delete; - CCMTLDescriptorSetLayout(CCMTLDescriptorSetLayout &&) = delete; + CCMTLDescriptorSetLayout(CCMTLDescriptorSetLayout &&) = delete; CCMTLDescriptorSetLayout &operator=(const CCMTLDescriptorSetLayout &) = delete; CCMTLDescriptorSetLayout &operator=(CCMTLDescriptorSetLayout &&) = delete; diff --git a/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.mm b/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.mm index c15ba154aa..4e7ba98545 100644 --- a/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.mm +++ b/native/cocos/renderer/gfx-metal/MTLDescriptorSetLayout.mm @@ -33,14 +33,14 @@ CCMTLDescriptorSetLayout::CCMTLDescriptorSetLayout() : DescriptorSetLayout() { _typedID = generateObjectID(); } -CCMTLDescriptorSetLayout::~CCMTLDescriptorSetLayout () { +CCMTLDescriptorSetLayout::~CCMTLDescriptorSetLayout() { destroy(); } void CCMTLDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { _gpuDescriptorSetLayout = ccnew CCMTLGPUDescriptorSetLayout; - _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; + _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; _gpuDescriptorSetLayout->descriptorIndices = _descriptorIndices; _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; _gpuDescriptorSetLayout->bindings = _bindings; diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index 41c2761704..da1e40e898 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -45,7 +45,7 @@ public: ~CCMTLDevice(); CCMTLDevice(const CCMTLDevice &) = delete; - CCMTLDevice(CCMTLDevice &&) = delete; + CCMTLDevice(CCMTLDevice &&) = delete; CCMTLDevice &operator=(const CCMTLDevice &) = delete; CCMTLDevice &operator=(CCMTLDevice &&) = delete; @@ -69,16 +69,16 @@ public: void onPresentCompleted(); - inline void * getMTLCommandQueue() const { return _mtlCommandQueue; } - inline void * getMTLDevice() const { return _mtlDevice; } - inline uint getMaximumSamplerUnits() const { return _maxSamplerUnits; } - inline uint getMaximumColorRenderTargets() const { return _caps.maxColorRenderTargets; } - inline uint getMaximumBufferBindingIndex() const { return _maxBufferBindingIndex; } - inline bool isIndirectCommandBufferSupported() const { return _icbSuppored; } - inline bool isIndirectDrawSupported() const { return _indirectDrawSupported; } + inline void *getMTLCommandQueue() const { return _mtlCommandQueue; } + inline void *getMTLDevice() const { return _mtlDevice; } + inline uint getMaximumSamplerUnits() const { return _maxSamplerUnits; } + inline uint getMaximumColorRenderTargets() const { return _caps.maxColorRenderTargets; } + inline uint getMaximumBufferBindingIndex() const { return _maxBufferBindingIndex; } + inline bool isIndirectCommandBufferSupported() const { return _icbSuppored; } + inline bool isIndirectDrawSupported() const { return _indirectDrawSupported; } inline CCMTLGPUStagingBufferPool *gpuStagingBufferPool() const { return _gpuStagingBufferPools[_currentFrameIndex]; } - inline bool isSamplerDescriptorCompareFunctionSupported() const { return _isSamplerDescriptorCompareFunctionSupported; } - inline uint currentFrameIndex() const { return _currentFrameIndex; } + inline bool isSamplerDescriptorCompareFunctionSupported() const { return _isSamplerDescriptorCompareFunctionSupported; } + inline uint currentFrameIndex() const { return _currentFrameIndex; } inline void registerSwapchain(CCMTLSwapchain *swapchain) { _swapchains.push_back(swapchain); } inline void unRegisterSwapchain(CCMTLSwapchain *swapchain) { @@ -93,44 +93,44 @@ protected: friend class DeviceManager; - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; - Sampler * createSampler(const SamplerInfo &info) override; - Swapchain * createSwapchain() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; - void getQueryPoolResults(QueryPool *queryPool) override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; + Sampler *createSampler(const SamplerInfo &info) override; + Swapchain *createSwapchain() override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + void getQueryPoolResults(QueryPool *queryPool) override; void onMemoryWarning(); void initFormatFeatures(uint family); - void * _mtlCommandQueue = nullptr; - void * _mtlDevice = nullptr; - void * _activeDrawable = nullptr; - unsigned long _mtlFeatureSet = 0; - uint _maxSamplerUnits = 0; - uint _maxBufferBindingIndex = 0; - bool _icbSuppored = false; - bool _indirectDrawSupported = false; - bool _isSamplerDescriptorCompareFunctionSupported = false; + void *_mtlCommandQueue = nullptr; + void *_mtlDevice = nullptr; + void *_activeDrawable = nullptr; + unsigned long _mtlFeatureSet = 0; + uint _maxSamplerUnits = 0; + uint _maxBufferBindingIndex = 0; + bool _icbSuppored = false; + bool _indirectDrawSupported = false; + bool _isSamplerDescriptorCompareFunctionSupported = false; CCMTLGPUStagingBufferPool *_gpuStagingBufferPools[MAX_FRAMES_IN_FLIGHT] = {nullptr}; - uint _currentBufferPoolId = 0; - uint _currentFrameIndex = 0; - CCMTLSemaphore * _inFlightSemaphore = nullptr; - CC_UNUSED uint32_t _memoryAlarmListenerId = 0; + uint _currentBufferPoolId = 0; + uint _currentFrameIndex = 0; + CCMTLSemaphore *_inFlightSemaphore = nullptr; + CC_UNUSED uint32_t _memoryAlarmListenerId = 0; ccstd::vector _swapchains; diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index d469369d67..9c10419386 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -57,13 +57,13 @@ CCMTLDevice *CCMTLDevice::getInstance() { } CCMTLDevice::CCMTLDevice() { - _api = API::METAL; + _api = API::METAL; _deviceName = "Metal"; - _caps.supportQuery = true; - _caps.clipSpaceMinZ = 0.0f; + _caps.supportQuery = true; + _caps.clipSpaceMinZ = 0.0f; _caps.screenSpaceSignY = -1.0f; - _caps.clipSpaceSignY = 1.0f; + _caps.clipSpaceSignY = 1.0f; CCMTLDevice::_instance = this; } @@ -73,28 +73,28 @@ CCMTLDevice::~CCMTLDevice() { } bool CCMTLDevice::doInit(const DeviceInfo &info) { - _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; + _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; _inFlightSemaphore = ccnew CCMTLSemaphore(MAX_FRAMES_IN_FLIGHT); _currentFrameIndex = 0; id mtlDevice = MTLCreateSystemDefaultDevice(); - _mtlDevice = mtlDevice; + _mtlDevice = mtlDevice; - _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); - const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); - _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); + _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); + const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); + _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); _caps.maxVertexAttributes = mu::getMaxVertexAttributes(gpuFamily); _caps.maxTextureUnits = _caps.maxVertexTextureUnits = mu::getMaxEntriesInTextureArgumentTable(gpuFamily); - _maxSamplerUnits = mu::getMaxEntriesInSamplerStateArgumentTable(gpuFamily); - _caps.maxTextureSize = mu::getMaxTexture2DWidthHeight(gpuFamily); - _caps.maxCubeMapTextureSize = mu::getMaxCubeMapTextureWidthHeight(gpuFamily); - _caps.maxColorRenderTargets = mu::getMaxColorRenderTarget(gpuFamily); - _caps.uboOffsetAlignment = mu::getMinBufferOffsetAlignment(gpuFamily); - _caps.maxComputeWorkGroupInvocations = mu::getMaxThreadsPerGroup(gpuFamily); - _caps.maxVertexUniformVectors = 255; //no explicit limit on vertex stage. - _maxBufferBindingIndex = mu::getMaxEntriesInBufferArgumentTable(gpuFamily); - _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); - _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); + _maxSamplerUnits = mu::getMaxEntriesInSamplerStateArgumentTable(gpuFamily); + _caps.maxTextureSize = mu::getMaxTexture2DWidthHeight(gpuFamily); + _caps.maxCubeMapTextureSize = mu::getMaxCubeMapTextureWidthHeight(gpuFamily); + _caps.maxColorRenderTargets = mu::getMaxColorRenderTarget(gpuFamily); + _caps.uboOffsetAlignment = mu::getMinBufferOffsetAlignment(gpuFamily); + _caps.maxComputeWorkGroupInvocations = mu::getMaxThreadsPerGroup(gpuFamily); + _caps.maxVertexUniformVectors = 255; //no explicit limit on vertex stage. + _maxBufferBindingIndex = mu::getMaxEntriesInBufferArgumentTable(gpuFamily); + _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); + _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { _gpuStagingBufferPools[i] = ccnew CCMTLGPUStagingBufferPool(mtlDevice); @@ -120,24 +120,24 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { compressedFormats += "pvrtc "; } - _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; - _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; - _features[toNumber(Feature::BLEND_MINMAX)] = true; - _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; - _features[toNumber(Feature::COMPUTE_SHADER)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); + _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, true}; _queryPool = createQueryPool(queryPoolInfo); CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _cmdBuff = createCommandBuffer(cmdBuffInfo); // _memoryAlarmListenerId = EventDispatcher::addCustomEventListener(EVENT_MEMORY_WARNING, std::bind(&CCMTLDevice::onMemoryWarning, this)); @@ -155,7 +155,7 @@ void CCMTLDevice::doDestroy() { // } CC_SAFE_DELETE(_gpuDeviceObj); - + CC_SAFE_DESTROY_AND_DELETE(_queryPool) CC_SAFE_DESTROY_AND_DELETE(_queue); CC_SAFE_DESTROY_AND_DELETE(_cmdBuff); @@ -179,7 +179,7 @@ void CCMTLDevice::doDestroy() { CCMTLTexture::deleteDefaultTexture(); CCMTLSampler::deleteDefaultSampler(); - CC_ASSERT(!_memoryStatus.bufferSize); // Buffer memory leaked + CC_ASSERT(!_memoryStatus.bufferSize); // Buffer memory leaked CC_ASSERT(!_memoryStatus.textureSize); // Texture memory leaked } @@ -193,7 +193,7 @@ void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { } // Clear queue stats - CCMTLQueue *queue = static_cast(_queue); + CCMTLQueue *queue = static_cast(_queue); queue->gpuQueueObj()->numDrawCalls = 0; queue->gpuQueueObj()->numInstances = 0; queue->gpuQueueObj()->numTriangles = 0; @@ -202,13 +202,13 @@ void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { void CCMTLDevice::present() { CC_PROFILE(CCMTLDevicePresent); CCMTLQueue *queue = (CCMTLQueue *)_queue; - _numDrawCalls = queue->gpuQueueObj()->numDrawCalls; - _numInstances = queue->gpuQueueObj()->numInstances; - _numTriangles = queue->gpuQueueObj()->numTriangles; + _numDrawCalls = queue->gpuQueueObj()->numDrawCalls; + _numInstances = queue->gpuQueueObj()->numInstances; + _numTriangles = queue->gpuQueueObj()->numTriangles; //hold this pointer before update _currentFrameIndex _currentBufferPoolId = _currentFrameIndex; - _currentFrameIndex = (_currentFrameIndex + 1) % MAX_FRAMES_IN_FLIGHT; + _currentFrameIndex = (_currentFrameIndex + 1) % MAX_FRAMES_IN_FLIGHT; ccstd::vector> releaseQ; for (auto *swapchain : _swapchains) { @@ -323,9 +323,9 @@ void CCMTLDevice::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, co void CCMTLDevice::getQueryPoolResults(QueryPool *queryPool) { CC_PROFILE(CCMTLDeviceGetQueryPoolResults); - auto * mtlQueryPool = static_cast(queryPool); + auto *mtlQueryPool = static_cast(queryPool); CCMTLGPUQueryPool *gpuQueryPool = mtlQueryPool->gpuQueryPool(); - auto queryCount = static_cast(mtlQueryPool->_ids.size()); + auto queryCount = static_cast(mtlQueryPool->_ids.size()); CC_ASSERT(queryCount <= mtlQueryPool->getMaxQueryObjects()); // Too many query commands. gpuQueryPool->semaphore->wait(); @@ -333,8 +333,8 @@ void CCMTLDevice::getQueryPoolResults(QueryPool *queryPool) { ccstd::unordered_map mapResults; for (auto queryId = 0U; queryId < queryCount; queryId++) { - uint32_t id = mtlQueryPool->_ids[queryId]; - auto iter = mapResults.find(id); + uint32_t id = mtlQueryPool->_ids[queryId]; + auto iter = mapResults.find(id); if (iter != mapResults.end()) { iter->second += results[queryId]; } else { @@ -358,27 +358,27 @@ void CCMTLDevice::initFormatFeatures(uint gpuFamily) { FormatFeature tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::STORAGE_TEXTURE; - _formatFeatures[toNumber(Format::R8UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG8UI)] = tempFeature; + _formatFeatures[toNumber(Format::R8UI)] = tempFeature; + _formatFeatures[toNumber(Format::RG8UI)] = tempFeature; _formatFeatures[toNumber(Format::RGBA8UI)] = tempFeature; - _formatFeatures[toNumber(Format::R16UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG16UI)] = tempFeature; + _formatFeatures[toNumber(Format::R16UI)] = tempFeature; + _formatFeatures[toNumber(Format::RG16UI)] = tempFeature; _formatFeatures[toNumber(Format::RGBA16UI)] = tempFeature; - _formatFeatures[toNumber(Format::R32F)] = tempFeature; - _formatFeatures[toNumber(Format::RG32F)] = tempFeature; + _formatFeatures[toNumber(Format::R32F)] = tempFeature; + _formatFeatures[toNumber(Format::RG32F)] = tempFeature; _formatFeatures[toNumber(Format::RGBA32F)] = tempFeature; if (mu::isUISamplerSupported(gpuFamily)) { - tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::STORAGE_TEXTURE; - _formatFeatures[toNumber(Format::R32UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG32UI)] = tempFeature; + tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] = tempFeature; + _formatFeatures[toNumber(Format::RG32UI)] = tempFeature; _formatFeatures[toNumber(Format::RGBA32UI)] = tempFeature; } else { - tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::STORAGE_TEXTURE; - _formatFeatures[toNumber(Format::R32UI)] = tempFeature; - _formatFeatures[toNumber(Format::RG32UI)] = tempFeature; + tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::STORAGE_TEXTURE; + _formatFeatures[toNumber(Format::R32UI)] = tempFeature; + _formatFeatures[toNumber(Format::RG32UI)] = tempFeature; _formatFeatures[toNumber(Format::RGBA32UI)] = tempFeature; } @@ -390,85 +390,85 @@ void CCMTLDevice::initFormatFeatures(uint gpuFamily) { tempFeature = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER | FormatFeature::STORAGE_TEXTURE; - _formatFeatures[toNumber(Format::R8SN)] = tempFeature; - _formatFeatures[toNumber(Format::RG8SN)] = tempFeature; + _formatFeatures[toNumber(Format::R8SN)] = tempFeature; + _formatFeatures[toNumber(Format::RG8SN)] = tempFeature; _formatFeatures[toNumber(Format::RGBA8SN)] = tempFeature; - _formatFeatures[toNumber(Format::R8)] = tempFeature; - _formatFeatures[toNumber(Format::RG8)] = tempFeature; + _formatFeatures[toNumber(Format::R8)] = tempFeature; + _formatFeatures[toNumber(Format::RG8)] = tempFeature; _formatFeatures[toNumber(Format::RGBA8)] = tempFeature; - _formatFeatures[toNumber(Format::R16F)] = tempFeature; - _formatFeatures[toNumber(Format::RG16F)] = tempFeature; + _formatFeatures[toNumber(Format::R16F)] = tempFeature; + _formatFeatures[toNumber(Format::RG16F)] = tempFeature; _formatFeatures[toNumber(Format::RGBA16F)] = tempFeature; _formatFeatures[toNumber(Format::R11G11B10F)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; - _formatFeatures[toNumber(Format::RGB9E5)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::RGB9E5)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; if (mu::isDDepthStencilFilterSupported(gpuFamily)) { - _formatFeatures[toNumber(Format::DEPTH)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; + _formatFeatures[toNumber(Format::DEPTH)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; _formatFeatures[toNumber(Format::DEPTH_STENCIL)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE; } else { - _formatFeatures[toNumber(Format::DEPTH)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER; + _formatFeatures[toNumber(Format::DEPTH)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER; _formatFeatures[toNumber(Format::DEPTH_STENCIL)] = FormatFeature::RENDER_TARGET | FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER; } const FormatFeature compressedFeature = FormatFeature::SAMPLED_TEXTURE | FormatFeature::LINEAR_FILTER; if (mu::isPVRTCSuppported(gpuFamily)) { - _formatFeatures[toNumber(Format::PVRTC_RGB2)] = compressedFeature; + _formatFeatures[toNumber(Format::PVRTC_RGB2)] = compressedFeature; _formatFeatures[toNumber(Format::PVRTC_RGBA2)] = compressedFeature; - _formatFeatures[toNumber(Format::PVRTC_RGB4)] = compressedFeature; + _formatFeatures[toNumber(Format::PVRTC_RGB4)] = compressedFeature; _formatFeatures[toNumber(Format::PVRTC_RGBA4)] = compressedFeature; } if (mu::isEAC_ETCCSuppported(gpuFamily)) { - _formatFeatures[toNumber(Format::ETC2_RGB8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_RGBA8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_SRGB8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGB8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGBA8)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_SRGB8)] = compressedFeature; _formatFeatures[toNumber(Format::ETC2_SRGB8_A8)] = compressedFeature; - _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = compressedFeature; + _formatFeatures[toNumber(Format::ETC2_RGB8_A1)] = compressedFeature; _formatFeatures[toNumber(Format::ETC2_SRGB8_A1)] = compressedFeature; } if (mu::isASTCSuppported(gpuFamily)) { - _formatFeatures[toNumber(Format::ASTC_RGBA_4X4)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_5X4)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_5X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_6X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_6X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_8X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_8X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_8X8)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_10X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_RGBA_10X8)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_4X4)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X4)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_5X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_6X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_8X8)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_RGBA_10X8)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_RGBA_10X10)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_RGBA_12X10)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_RGBA_12X12)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_4X4)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_5X4)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_5X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_6X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_6X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_8X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_8X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_8X8)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_10X5)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_10X6)] = compressedFeature; - _formatFeatures[toNumber(Format::ASTC_SRGBA_10X8)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_4X4)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X4)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_5X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_6X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_8X8)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X5)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X6)] = compressedFeature; + _formatFeatures[toNumber(Format::ASTC_SRGBA_10X8)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_SRGBA_10X10)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_SRGBA_12X10)] = compressedFeature; _formatFeatures[toNumber(Format::ASTC_SRGBA_12X12)] = compressedFeature; } if (mu::isBCSupported(gpuFamily)) { - _formatFeatures[toNumber(Format::BC1)] = compressedFeature; - _formatFeatures[toNumber(Format::BC1_ALPHA)] = compressedFeature; - _formatFeatures[toNumber(Format::BC1_SRGB)] = compressedFeature; + _formatFeatures[toNumber(Format::BC1)] = compressedFeature; + _formatFeatures[toNumber(Format::BC1_ALPHA)] = compressedFeature; + _formatFeatures[toNumber(Format::BC1_SRGB)] = compressedFeature; _formatFeatures[toNumber(Format::BC1_SRGB_ALPHA)] = compressedFeature; - _formatFeatures[toNumber(Format::BC2)] = compressedFeature; - _formatFeatures[toNumber(Format::BC2_SRGB)] = compressedFeature; - _formatFeatures[toNumber(Format::BC3)] = compressedFeature; - _formatFeatures[toNumber(Format::BC3_SRGB)] = compressedFeature; + _formatFeatures[toNumber(Format::BC2)] = compressedFeature; + _formatFeatures[toNumber(Format::BC2_SRGB)] = compressedFeature; + _formatFeatures[toNumber(Format::BC3)] = compressedFeature; + _formatFeatures[toNumber(Format::BC3_SRGB)] = compressedFeature; } _formatFeatures[toNumber(Format::R8)] |= FormatFeature::VERTEX_ATTRIBUTE; diff --git a/native/cocos/renderer/gfx-metal/MTLFramebuffer.h b/native/cocos/renderer/gfx-metal/MTLFramebuffer.h index dcdc5239e0..54857b7e3e 100644 --- a/native/cocos/renderer/gfx-metal/MTLFramebuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLFramebuffer.h @@ -35,19 +35,19 @@ public: explicit CCMTLFramebuffer(); ~CCMTLFramebuffer(); CCMTLFramebuffer(const CCMTLFramebuffer &) = delete; - CCMTLFramebuffer(CCMTLFramebuffer &&) = delete; + CCMTLFramebuffer(CCMTLFramebuffer &&) = delete; CCMTLFramebuffer &operator=(const CCMTLFramebuffer &) = delete; CCMTLFramebuffer &operator=(CCMTLFramebuffer &&) = delete; - inline bool isOffscreen() const { return _isOffscreen; } + inline bool isOffscreen() const { return _isOffscreen; } inline CCMTLSwapchain *swapChain() const { return _swapChain; } protected: void doInit(const FramebufferInfo &info) override; void doDestroy() override; - bool _isOffscreen = false; - CCMTLSwapchain *_swapChain = nullptr; + bool _isOffscreen = false; + CCMTLSwapchain *_swapChain = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm index ebb8c29698..bc2d40b280 100644 --- a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm @@ -38,20 +38,20 @@ CCMTLFramebuffer::~CCMTLFramebuffer() { destroy(); } -void CCMTLFramebuffer::doInit(const FramebufferInfo &) { +void CCMTLFramebuffer::doInit(const FramebufferInfo&) { _isOffscreen = true; for (Texture* tex : _colorTextures) { auto* ccTex = static_cast(tex); - if(ccTex->swapChain()) { + if (ccTex->swapChain()) { _swapChain = ccTex->swapChain(); _isOffscreen = false; break; } } - - if(_depthStencilTexture) { + + if (_depthStencilTexture) { auto* ccTex = static_cast(_depthStencilTexture); - if(ccTex->swapChain()) { + if (ccTex->swapChain()) { _swapChain = ccTex->swapChain(); _isOffscreen = false; } diff --git a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index f20d4fdf6a..86b90d9ed4 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -57,43 +57,43 @@ constexpr size_t MAX_COLORATTACHMENTS = 16u; struct CCMTLGPUDescriptorSetLayout { DescriptorSetLayoutBindingList bindings; - ccstd::vector dynamicBindings; - ccstd::vector descriptorIndices; - ccstd::vector bindingIndices; - uint descriptorCount = 0; + ccstd::vector dynamicBindings; + ccstd::vector descriptorIndices; + ccstd::vector bindingIndices; + uint descriptorCount = 0; }; typedef ccstd::vector MTLGPUDescriptorSetLayoutList; struct CCMTLGPUPipelineLayout { - MTLGPUDescriptorSetLayoutList setLayouts; + MTLGPUDescriptorSetLayoutList setLayouts; ccstd::vector> dynamicOffsetIndices; }; struct CCMTLGPUUniformBlock { - ccstd::string name; - uint set = INVALID_BINDING; - uint binding = INVALID_BINDING; - uint mappedBinding = INVALID_BINDING; - ShaderStageFlags stages = ShaderStageFlagBit::NONE; - size_t size = 0; - uint count = 0; + ccstd::string name; + uint set = INVALID_BINDING; + uint binding = INVALID_BINDING; + uint mappedBinding = INVALID_BINDING; + ShaderStageFlags stages = ShaderStageFlagBit::NONE; + size_t size = 0; + uint count = 0; }; struct CCMTLGPUSamplerBlock { - ccstd::string name; - uint set = INVALID_BINDING; - uint binding = INVALID_BINDING; - uint textureBinding = INVALID_BINDING; - uint samplerBinding = INVALID_BINDING; - ShaderStageFlags stages = ShaderStageFlagBit::NONE; - Type type = Type::UNKNOWN; - uint count = 0; + ccstd::string name; + uint set = INVALID_BINDING; + uint binding = INVALID_BINDING; + uint textureBinding = INVALID_BINDING; + uint samplerBinding = INVALID_BINDING; + ShaderStageFlags stages = ShaderStageFlagBit::NONE; + Type type = Type::UNKNOWN; + uint count = 0; }; struct CCMTLGPUSubpassAttachment { ccstd::string name; - uint set = INVALID_BINDING; - uint binding = INVALID_BINDING; + uint set = INVALID_BINDING; + uint binding = INVALID_BINDING; }; struct CCMTLGPUShader { @@ -103,64 +103,64 @@ struct CCMTLGPUShader { ccstd::vector inputs; ccstd::vector outputs; - NSString *shaderSrc = nil; - bool specializeColor = true; + NSString *shaderSrc = nil; + bool specializeColor = true; - uint32_t bufferIndex = 0; + uint32_t bufferIndex = 0; uint32_t samplerIndex = 0; }; struct CCMTLGPUPipelineState { - MTLCullMode cullMode; - MTLWinding winding; - MTLTriangleFillMode fillMode; - MTLDepthClipMode depthClipMode; - MTLPrimitiveType primitiveType; - id mtlRenderPipelineState = nil; - id mtlDepthStencilState = nil; - id mtlComputePipelineState = nil; - uint stencilRefFront = 0; - uint stencilRefBack = 0; + MTLCullMode cullMode; + MTLWinding winding; + MTLTriangleFillMode fillMode; + MTLDepthClipMode depthClipMode; + MTLPrimitiveType primitiveType; + id mtlRenderPipelineState = nil; + id mtlDepthStencilState = nil; + id mtlComputePipelineState = nil; + uint stencilRefFront = 0; + uint stencilRefBack = 0; ccstd::vector> vertexBufferBindingInfo; - const CCMTLGPUPipelineLayout * gpuPipelineLayout = nullptr; - const CCMTLGPUShader * gpuShader = nullptr; + const CCMTLGPUPipelineLayout *gpuPipelineLayout = nullptr; + const CCMTLGPUShader *gpuShader = nullptr; }; struct CCMTLGPUBuffer { - uint stride = 0; - uint count = 0; - uint size = 0; - uint startOffset = 0; - uint8_t * mappedData = nullptr; - id mtlBuffer = nil; + uint stride = 0; + uint count = 0; + uint size = 0; + uint startOffset = 0; + uint8_t *mappedData = nullptr; + id mtlBuffer = nil; }; struct CCMTLGPUTextureObject { - TextureInfo info; + TextureInfo info; id mtlTexture; }; struct CCMTLGPUTextureViewObject { TextureViewInfo viewInfo; - id mtlTextureView; + id mtlTextureView; }; struct CCMTLGPUInputAssembler { - id mtlIndexBuffer = nil; - id mtlIndirectBuffer = nil; + id mtlIndexBuffer = nil; + id mtlIndirectBuffer = nil; ccstd::vector> mtlVertexBufers; }; struct CCMTLGPUDescriptor { - DescriptorType type = DescriptorType::UNKNOWN; - CCMTLBuffer * buffer = nullptr; - CCMTLTexture * texture = nullptr; - CCMTLSampler * sampler = nullptr; + DescriptorType type = DescriptorType::UNKNOWN; + CCMTLBuffer *buffer = nullptr; + CCMTLTexture *texture = nullptr; + CCMTLSampler *sampler = nullptr; }; typedef ccstd::vector MTLGPUDescriptorList; struct CCMTLGPUDescriptorSet { - MTLGPUDescriptorList gpuDescriptors; + MTLGPUDescriptorList gpuDescriptors; const ccstd::vector *descriptorIndices = nullptr; }; @@ -186,13 +186,13 @@ public: } inline void alloc(CCMTLGPUBuffer *gpuBuffer) { alloc(gpuBuffer, 1); } - void alloc(CCMTLGPUBuffer *gpuBuffer, uint alignment) { - size_t bufferCount = _pool.size(); - Buffer *buffer = nullptr; - uint offset = 0; + void alloc(CCMTLGPUBuffer *gpuBuffer, uint alignment) { + size_t bufferCount = _pool.size(); + Buffer *buffer = nullptr; + uint offset = 0; for (size_t idx = 0; idx < bufferCount; idx++) { auto *cur = &_pool[idx]; - offset = mu::alignUp(cur->curOffset, alignment); + offset = mu::alignUp(cur->curOffset, alignment); if (gpuBuffer->size + offset <= [cur->mtlBuffer length]) { buffer = cur; break; @@ -200,7 +200,7 @@ public: } if (!buffer) { uint mbNeeds = mu::roundUp(gpuBuffer->size, MegaBytesToBytes); - mbNeeds = cc::utils::nextPOT(mbNeeds); + mbNeeds = cc::utils::nextPOT(mbNeeds); CC_ASSERT(mbNeeds > gpuBuffer->size / static_cast(MegaBytesToBytes)); _pool.resize(bufferCount + 1); @@ -208,7 +208,7 @@ public: if (_tripleEnabled) { for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { // Create a new buffer with enough capacity to store one instance of the dynamic buffer data - id dataBuffer = [_device newBufferWithLength:mbNeeds * MegaBytesToBytes options:MTLResourceStorageModeShared]; + id dataBuffer = [_device newBufferWithLength:mbNeeds * MegaBytesToBytes options:MTLResourceStorageModeShared]; buffer->dynamicDataBuffers[i] = dataBuffer; } buffer->mtlBuffer = buffer->dynamicDataBuffers[0]; @@ -216,24 +216,24 @@ public: buffer->mtlBuffer = [_device newBufferWithLength:mbNeeds * MegaBytesToBytes options:MTLResourceStorageModeShared]; } buffer->mappedData = (uint8_t *)buffer->mtlBuffer.contents; - offset = 0; + offset = 0; } - gpuBuffer->mtlBuffer = buffer->mtlBuffer; + gpuBuffer->mtlBuffer = buffer->mtlBuffer; gpuBuffer->startOffset = offset; - gpuBuffer->mappedData = buffer->mappedData + offset; - buffer->curOffset = offset + gpuBuffer->size; + gpuBuffer->mappedData = buffer->mappedData + offset; + buffer->curOffset = offset + gpuBuffer->size; } void updateInflightBuffer() { if (_tripleEnabled) { _inflightIndex = ((_inflightIndex + 1) % MAX_FRAMES_IN_FLIGHT); - size_t bufferCount = _pool.size(); - Buffer *buffer = nullptr; + size_t bufferCount = _pool.size(); + Buffer *buffer = nullptr; for (size_t idx = 0; idx < bufferCount; idx++) { - buffer = &_pool[idx]; + buffer = &_pool[idx]; id prevFrameBuffer = buffer->mtlBuffer; - buffer->mtlBuffer = buffer->dynamicDataBuffers[_inflightIndex]; + buffer->mtlBuffer = buffer->dynamicDataBuffers[_inflightIndex]; memcpy((uint8_t *)buffer->mtlBuffer.contents, prevFrameBuffer.contents, buffer->curOffset); buffer->mappedData = (uint8_t *)buffer->mtlBuffer.contents; } @@ -259,25 +259,25 @@ public: protected: struct Buffer { - id mtlBuffer = nil; + id mtlBuffer = nil; ccstd::vector> dynamicDataBuffers{MAX_FRAMES_IN_FLIGHT}; - uint8_t * mappedData = nullptr; - uint curOffset = 0; + uint8_t *mappedData = nullptr; + uint curOffset = 0; }; - bool _tripleEnabled = false; - uint _inflightIndex = 0; - id _device = nil; + bool _tripleEnabled = false; + uint _inflightIndex = 0; + id _device = nil; ccstd::vector _pool; }; struct CCMTLGPUBufferImageCopy { - NSUInteger sourceBytesPerRow = 0; + NSUInteger sourceBytesPerRow = 0; NSUInteger sourceBytesPerImage = 0; - MTLSize sourceSize = {0, 0, 0}; - NSUInteger destinationSlice = 0; - NSUInteger destinationLevel = 0; - MTLOrigin destinationOrigin = {0, 0, 0}; + MTLSize sourceSize = {0, 0, 0}; + NSUInteger destinationSlice = 0; + NSUInteger destinationLevel = 0; + MTLOrigin destinationOrigin = {0, 0, 0}; }; //destroy GPU resource only, delete the owner object mannually. @@ -324,39 +324,39 @@ public: protected: //avoid cross-reference with CCMTLDevice std::function _getFrameIndex; - ccstd::queue _releaseQueue[MAX_FRAMES_IN_FLIGHT]; + ccstd::queue _releaseQueue[MAX_FRAMES_IN_FLIGHT]; }; struct CCMTLGPUSwapChainObject { id currentDrawable = nil; - CAMetalLayer * mtlLayer = nullptr; + CAMetalLayer *mtlLayer = nullptr; }; struct CCMTLGPUQueueObject { id mtlCommandQueue = nil; - uint numDrawCalls = 0; - uint numInstances = 0; - uint numTriangles = 0; + uint numDrawCalls = 0; + uint numInstances = 0; + uint numTriangles = 0; }; struct CCMTLGPUCommandBufferObject { - CCMTLRenderPass * renderPass = nullptr; - CCMTLFramebuffer * fbo = nullptr; - CCMTLInputAssembler *inputAssembler = nullptr; - CCMTLPipelineState * pipelineState = nullptr; + CCMTLRenderPass *renderPass = nullptr; + CCMTLFramebuffer *fbo = nullptr; + CCMTLInputAssembler *inputAssembler = nullptr; + CCMTLPipelineState *pipelineState = nullptr; id mtlCommandBuffer = nil; - bool isSecondary = false; + bool isSecondary = false; }; struct CCMTLGPUDeviceObject { }; struct CCMTLGPUQueryPool { - QueryType type = QueryType::OCCLUSION; - uint32_t maxQueryObjects = 0; - bool forceWait = true; - id visibilityResultBuffer = nil; - CCMTLSemaphore *semaphore = nullptr; + QueryType type = QueryType::OCCLUSION; + uint32_t maxQueryObjects = 0; + bool forceWait = true; + id visibilityResultBuffer = nil; + CCMTLSemaphore *semaphore = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLInputAssembler.h b/native/cocos/renderer/gfx-metal/MTLInputAssembler.h index d2f23a4b18..72c1308b55 100644 --- a/native/cocos/renderer/gfx-metal/MTLInputAssembler.h +++ b/native/cocos/renderer/gfx-metal/MTLInputAssembler.h @@ -37,7 +37,7 @@ public: explicit CCMTLInputAssembler(); ~CCMTLInputAssembler(); CCMTLInputAssembler(const CCMTLInputAssembler &) = delete; - CCMTLInputAssembler(CCMTLInputAssembler &&) = delete; + CCMTLInputAssembler(CCMTLInputAssembler &&) = delete; CCMTLInputAssembler &operator=(const CCMTLInputAssembler &) = delete; CCMTLInputAssembler &operator=(CCMTLInputAssembler &&) = delete; diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineLayout.mm b/native/cocos/renderer/gfx-metal/MTLPipelineLayout.mm index b991cdd3ad..ce50f856e1 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineLayout.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineLayout.mm @@ -62,5 +62,5 @@ void CCMTLPipelineLayout::doDestroy() { CC_SAFE_DELETE(_gpuPipelineLayout); } -} -} +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.h b/native/cocos/renderer/gfx-metal/MTLPipelineState.h index 8ed3e28226..6011f1cf89 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.h +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.h @@ -42,7 +42,7 @@ public: explicit CCMTLPipelineState(); ~CCMTLPipelineState(); CCMTLPipelineState(const CCMTLPipelineState &) = delete; - CCMTLPipelineState(CCMTLPipelineState &&) = delete; + CCMTLPipelineState(CCMTLPipelineState &&) = delete; CCMTLPipelineState &operator=(const CCMTLPipelineState &) = delete; CCMTLPipelineState &operator=(CCMTLPipelineState &&) = delete; @@ -64,11 +64,11 @@ protected: void setBlendStates(MTLRenderPipelineDescriptor *); bool createMTLRenderPipeline(MTLRenderPipelineDescriptor *); - bool _renderPipelineReady = false; - id _mtlRenderPipelineState = nil; - id _mtlDepthStencilState = nil; - id _mtlComputePipeline = nil; - CCMTLGPUPipelineState * _GPUPipelineState = nullptr; + bool _renderPipelineReady = false; + id _mtlRenderPipelineState = nil; + id _mtlDepthStencilState = nil; + id _mtlComputePipeline = nil; + CCMTLGPUPipelineState *_GPUPipelineState = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 4c14a361bb..6e20df3048 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -39,7 +39,6 @@ #import #import - namespace cc { namespace gfx { @@ -59,9 +58,9 @@ void CCMTLPipelineState::doDestroy() { CC_SAFE_DELETE(_GPUPipelineState); id renderPipelineState = _mtlRenderPipelineState; - _mtlRenderPipelineState = nil; - id depthStencilState = _mtlDepthStencilState; - _mtlDepthStencilState = nil; + _mtlRenderPipelineState = nil; + id depthStencilState = _mtlDepthStencilState; + _mtlDepthStencilState = nil; std::function destroyFunc = [=]() { if (renderPipelineState) { @@ -83,15 +82,15 @@ bool CCMTLPipelineState::initRenderPipeline() { return false; } - _GPUPipelineState->mtlDepthStencilState = _mtlDepthStencilState; + _GPUPipelineState->mtlDepthStencilState = _mtlDepthStencilState; _GPUPipelineState->mtlRenderPipelineState = _mtlRenderPipelineState; - _GPUPipelineState->cullMode = static_cast(mu::toMTLCullMode(_rasterizerState.cullMode)); - _GPUPipelineState->fillMode = static_cast(mu::toMTLTriangleFillMode(_rasterizerState.polygonMode)); - _GPUPipelineState->depthClipMode = static_cast(mu::toMTLDepthClipMode(_rasterizerState.isDepthClip != 0)); - _GPUPipelineState->winding = static_cast(mu::toMTLWinding(_rasterizerState.isFrontFaceCCW != 0)); - _GPUPipelineState->stencilRefFront = _depthStencilState.stencilRefFront; - _GPUPipelineState->stencilRefBack = _depthStencilState.stencilRefBack; - _GPUPipelineState->primitiveType = mu::toMTLPrimitiveType(_primitive); + _GPUPipelineState->cullMode = static_cast(mu::toMTLCullMode(_rasterizerState.cullMode)); + _GPUPipelineState->fillMode = static_cast(mu::toMTLTriangleFillMode(_rasterizerState.polygonMode)); + _GPUPipelineState->depthClipMode = static_cast(mu::toMTLDepthClipMode(_rasterizerState.isDepthClip != 0)); + _GPUPipelineState->winding = static_cast(mu::toMTLWinding(_rasterizerState.isFrontFaceCCW != 0)); + _GPUPipelineState->stencilRefFront = _depthStencilState.stencilRefFront; + _GPUPipelineState->stencilRefBack = _depthStencilState.stencilRefBack; + _GPUPipelineState->primitiveType = mu::toMTLPrimitiveType(_primitive); if (_pipelineLayout) _GPUPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(); @@ -124,7 +123,7 @@ bool CCMTLPipelineState::createGPUPipelineState() { return false; } _GPUPipelineState->mtlComputePipelineState = _mtlComputePipeline; - _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _GPUPipelineState->gpuShader = static_cast(_shader)->gpuShader(); if (_pipelineLayout) _GPUPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); } @@ -135,7 +134,7 @@ bool CCMTLPipelineState::createGPUPipelineState() { bool CCMTLPipelineState::createMTLComputePipelineState() { //create with function id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - NSError * err; + NSError *err; _mtlComputePipeline = [mtlDevice newComputePipelineStateWithFunction:((CCMTLShader *)_shader)->getComputeMTLFunction() error:&err]; if (!_mtlComputePipeline) { @@ -160,29 +159,29 @@ bool CCMTLPipelineState::createMTLDepthStencilState() { descriptor.depthCompareFunction = mu::toMTLCompareFunction(_depthStencilState.depthFunc); if (_depthStencilState.stencilTestFront) { - descriptor.frontFaceStencil.stencilCompareFunction = mu::toMTLCompareFunction(_depthStencilState.stencilFuncFront); - descriptor.frontFaceStencil.readMask = _depthStencilState.stencilReadMaskFront; - descriptor.frontFaceStencil.writeMask = _depthStencilState.stencilWriteMaskFront; - descriptor.frontFaceStencil.stencilFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilFailOpFront); - descriptor.frontFaceStencil.depthFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilZFailOpFront); + descriptor.frontFaceStencil.stencilCompareFunction = mu::toMTLCompareFunction(_depthStencilState.stencilFuncFront); + descriptor.frontFaceStencil.readMask = _depthStencilState.stencilReadMaskFront; + descriptor.frontFaceStencil.writeMask = _depthStencilState.stencilWriteMaskFront; + descriptor.frontFaceStencil.stencilFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilFailOpFront); + descriptor.frontFaceStencil.depthFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilZFailOpFront); descriptor.frontFaceStencil.depthStencilPassOperation = mu::toMTLStencilOperation(_depthStencilState.stencilPassOpFront); } else { descriptor.frontFaceStencil = nil; } if (_depthStencilState.stencilTestBack) { - descriptor.backFaceStencil.stencilCompareFunction = mu::toMTLCompareFunction(_depthStencilState.stencilFuncBack); - descriptor.backFaceStencil.readMask = _depthStencilState.stencilReadMaskBack; - descriptor.backFaceStencil.writeMask = _depthStencilState.stencilWriteMaskBack; - descriptor.backFaceStencil.stencilFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilFailOpBack); - descriptor.backFaceStencil.depthFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilZFailOpBack); + descriptor.backFaceStencil.stencilCompareFunction = mu::toMTLCompareFunction(_depthStencilState.stencilFuncBack); + descriptor.backFaceStencil.readMask = _depthStencilState.stencilReadMaskBack; + descriptor.backFaceStencil.writeMask = _depthStencilState.stencilWriteMaskBack; + descriptor.backFaceStencil.stencilFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilFailOpBack); + descriptor.backFaceStencil.depthFailureOperation = mu::toMTLStencilOperation(_depthStencilState.stencilZFailOpBack); descriptor.backFaceStencil.depthStencilPassOperation = mu::toMTLStencilOperation(_depthStencilState.stencilPassOpBack); } else { descriptor.backFaceStencil = nil; } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - _mtlDepthStencilState = [mtlDevice newDepthStencilStateWithDescriptor:descriptor]; + _mtlDepthStencilState = [mtlDevice newDepthStencilStateWithDescriptor:descriptor]; [descriptor release]; if (!_mtlDepthStencilState) { @@ -193,7 +192,7 @@ bool CCMTLPipelineState::createMTLDepthStencilState() { } bool CCMTLPipelineState::createMTLRenderPipelineState() { - bool ret = true; + bool ret = true; MTLRenderPipelineDescriptor *descriptor = [[MTLRenderPipelineDescriptor alloc] init]; if (descriptor == nil) { CC_LOG_ERROR("CCMTLPipelineState: MTLRenderPipelineDescriptor could not be allocated."); @@ -210,21 +209,21 @@ bool CCMTLPipelineState::createMTLRenderPipelineState() { //TODO: reconstruction void CCMTLPipelineState::setVertexDescriptor(MTLRenderPipelineDescriptor *descriptor) { - auto activeAttributes = static_cast(_shader)->getAttributes(); - ccstd::vector> layouts; + auto activeAttributes = static_cast(_shader)->getAttributes(); + ccstd::vector> layouts; ccstd::unordered_map> map; - ccstd::vector streamOffsets(CCMTLDevice::getInstance()->getCapabilities().maxVertexAttributes, 0u); - ccstd::vector activeAttribIdx(activeAttributes.size(), false); + ccstd::vector streamOffsets(CCMTLDevice::getInstance()->getCapabilities().maxVertexAttributes, 0u); + ccstd::vector activeAttribIdx(activeAttributes.size(), false); for (const auto &inputAttrib : _inputState.attributes) { auto bufferIndex = static_cast(_shader)->getAvailableBufferBindingIndex(ShaderStageFlagBit::VERTEX, inputAttrib.stream); for (auto i = 0; i < activeAttributes.size(); i++) { const auto &activeAttribute = activeAttributes[i]; if (inputAttrib.name == activeAttribute.name) { - descriptor.vertexDescriptor.attributes[activeAttribute.location].format = mu::toMTLVertexFormat(inputAttrib.format, inputAttrib.isNormalized); - descriptor.vertexDescriptor.attributes[activeAttribute.location].offset = streamOffsets[inputAttrib.stream]; + descriptor.vertexDescriptor.attributes[activeAttribute.location].format = mu::toMTLVertexFormat(inputAttrib.format, inputAttrib.isNormalized); + descriptor.vertexDescriptor.attributes[activeAttribute.location].offset = streamOffsets[inputAttrib.stream]; descriptor.vertexDescriptor.attributes[activeAttribute.location].bufferIndex = bufferIndex; - auto tuple = std::make_tuple(bufferIndex, inputAttrib.stream); + auto tuple = std::make_tuple(bufferIndex, inputAttrib.stream); if (std::find(layouts.begin(), layouts.end(), tuple) == layouts.end()) layouts.emplace_back(tuple); activeAttribIdx[i] = true; @@ -238,19 +237,19 @@ void CCMTLPipelineState::setVertexDescriptor(MTLRenderPipelineDescriptor *descri for (auto i = 0; i < activeAttribIdx.size(); i++) { if (activeAttribIdx[i]) continue; - const auto &dummy = activeAttributes[i]; - descriptor.vertexDescriptor.attributes[dummy.location].format = MTLVertexFormatFloat; - descriptor.vertexDescriptor.attributes[dummy.location].offset = 0; + const auto &dummy = activeAttributes[i]; + descriptor.vertexDescriptor.attributes[dummy.location].format = MTLVertexFormatFloat; + descriptor.vertexDescriptor.attributes[dummy.location].offset = 0; descriptor.vertexDescriptor.attributes[dummy.location].bufferIndex = static_cast(_shader)->getAvailableBufferBindingIndex(ShaderStageFlagBit::VERTEX, dummy.stream); CC_LOG_WARNING("Attribute %s is missing, add a dummy data for it.", dummy.name.c_str()); } // layouts for (const auto &layout : layouts) { - auto index = std::get<0>(layout); - descriptor.vertexDescriptor.layouts[index].stride = std::get<0>(map[index]); + auto index = std::get<0>(layout); + descriptor.vertexDescriptor.layouts[index].stride = std::get<0>(map[index]); descriptor.vertexDescriptor.layouts[index].stepFunction = std::get<1>(map[index]) ? MTLVertexStepFunctionPerInstance : MTLVertexStepFunctionPerVertex; - descriptor.vertexDescriptor.layouts[index].stepRate = 1; + descriptor.vertexDescriptor.layouts[index].stepRate = 1; //to improve performance: https://developer.apple.com/documentation/metal/mtlpipelinebufferdescriptor?language=objc if (@available(iOS 11.0, macOS 10.13, *)) { descriptor.vertexBuffers[index].mutability = MTLMutabilityImmutable; @@ -261,20 +260,20 @@ void CCMTLPipelineState::setVertexDescriptor(MTLRenderPipelineDescriptor *descri } void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor *descriptor) { - const SubpassInfoList & subpasses = _renderPass->getSubpasses(); + const SubpassInfoList &subpasses = _renderPass->getSubpasses(); const ColorAttachmentList &colorAttachments = _renderPass->getColorAttachments(); - const auto & ccShader = static_cast(_shader); + const auto &ccShader = static_cast(_shader); ccstd::vector bindingIndices; - ccstd::vector bindingOffsets; + ccstd::vector bindingOffsets; const CCMTLGPUShader *gpuShader = ccShader->gpuShader(); - uint32_t outputNum = static_cast(gpuShader->outputs.size()); + uint32_t outputNum = static_cast(gpuShader->outputs.size()); bindingIndices.reserve(outputNum); bindingOffsets.reserve(outputNum); - MTLPixelFormat mtlPixelFormat; + MTLPixelFormat mtlPixelFormat; ccstd::set inputs; - uint32_t depthStencilTexIndex = INVALID_BINDING; + uint32_t depthStencilTexIndex = INVALID_BINDING; if (!subpasses.empty()) { for (size_t passIndex = 0; passIndex < subpasses.size(); ++passIndex) { const SubpassInfo &subpass = subpasses[passIndex]; @@ -282,19 +281,19 @@ void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * uint32_t input = subpass.inputs[i]; if (inputs.find(input) == inputs.end()) { inputs.insert(input); - mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[input].format); + mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[input].format); descriptor.colorAttachments[input].pixelFormat = mtlPixelFormat; } } for (size_t i = 0; i < subpass.colors.size(); ++i) { - uint32_t output = subpass.colors[i]; - mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[output].format); + uint32_t output = subpass.colors[i]; + mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[output].format); descriptor.colorAttachments[output].pixelFormat = mtlPixelFormat; } depthStencilTexIndex = subpass.depthStencil; } - const uint32_t curIndex = static_cast(_renderPass)->getCurrentSubpassIndex(); + const uint32_t curIndex = static_cast(_renderPass)->getCurrentSubpassIndex(); const SubpassInfo &curSubpass = subpasses[curIndex]; for (size_t i = 0; i < curSubpass.colors.size(); ++i) { bindingIndices.emplace_back(i); @@ -302,7 +301,7 @@ void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * } } else { for (size_t i = 0; i < colorAttachments.size(); ++i) { - mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[i].format); + mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[i].format); descriptor.colorAttachments[i].pixelFormat = mtlPixelFormat; bindingIndices.emplace_back(i); bindingOffsets.emplace_back(i); @@ -311,18 +310,18 @@ void CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * } SampleCount sample = SampleCount::ONE; - Format depthStencilFormat; + Format depthStencilFormat; if (depthStencilTexIndex != INVALID_BINDING && depthStencilTexIndex < _renderPass->getColorAttachments().size()) { - sample = _renderPass->getColorAttachments()[depthStencilTexIndex].sampleCount; + sample = _renderPass->getColorAttachments()[depthStencilTexIndex].sampleCount; depthStencilFormat = _renderPass->getColorAttachments()[depthStencilTexIndex].format; } else { - sample = _renderPass->getDepthStencilAttachment().sampleCount; + sample = _renderPass->getDepthStencilAttachment().sampleCount; depthStencilFormat = _renderPass->getDepthStencilAttachment().format; } descriptor.sampleCount = mu::toMTLSampleCount(sample); - auto *ccMTLShader = static_cast(_shader); - descriptor.vertexFunction = ccMTLShader->getVertMTLFunction(); + auto *ccMTLShader = static_cast(_shader); + descriptor.vertexFunction = ccMTLShader->getVertMTLFunction(); descriptor.fragmentFunction = ccMTLShader->getSpecializedFragFunction(bindingIndices.data(), bindingOffsets.data(), static_cast(bindingIndices.size())); mtlPixelFormat = mu::toMTLPixelFormat(depthStencilFormat); @@ -344,17 +343,17 @@ void CCMTLPipelineState::setBlendStates(MTLRenderPipelineDescriptor *descriptor) int i = 0; for (const auto blendTarget : _blendState.targets) { MTLRenderPipelineColorAttachmentDescriptor *colorDescriptor = descriptor.colorAttachments[i]; - colorDescriptor.writeMask = mu::toMTLColorWriteMask(blendTarget.blendColorMask); - colorDescriptor.blendingEnabled = blendTarget.blend != 0; + colorDescriptor.writeMask = mu::toMTLColorWriteMask(blendTarget.blendColorMask); + colorDescriptor.blendingEnabled = blendTarget.blend != 0; if (!blendTarget.blend) continue; - colorDescriptor.sourceRGBBlendFactor = mu::toMTLBlendFactor(blendTarget.blendSrc); - colorDescriptor.destinationRGBBlendFactor = mu::toMTLBlendFactor(blendTarget.blendDst); - colorDescriptor.rgbBlendOperation = mu::toMTLBlendOperation(blendTarget.blendEq); - colorDescriptor.sourceAlphaBlendFactor = mu::toMTLBlendFactor(blendTarget.blendSrcAlpha); + colorDescriptor.sourceRGBBlendFactor = mu::toMTLBlendFactor(blendTarget.blendSrc); + colorDescriptor.destinationRGBBlendFactor = mu::toMTLBlendFactor(blendTarget.blendDst); + colorDescriptor.rgbBlendOperation = mu::toMTLBlendOperation(blendTarget.blendEq); + colorDescriptor.sourceAlphaBlendFactor = mu::toMTLBlendFactor(blendTarget.blendSrcAlpha); colorDescriptor.destinationAlphaBlendFactor = mu::toMTLBlendFactor(blendTarget.blendDstAlpha); - colorDescriptor.alphaBlendOperation = mu::toMTLBlendOperation(blendTarget.blendAlphaEq); + colorDescriptor.alphaBlendOperation = mu::toMTLBlendOperation(blendTarget.blendAlphaEq); ++i; } @@ -362,7 +361,7 @@ void CCMTLPipelineState::setBlendStates(MTLRenderPipelineDescriptor *descriptor) bool CCMTLPipelineState::createMTLRenderPipeline(MTLRenderPipelineDescriptor *descriptor) { id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - NSError * nsError = nil; + NSError *nsError = nil; _mtlRenderPipelineState = [mtlDevice newRenderPipelineStateWithDescriptor:descriptor error:&nsError]; if (!_mtlRenderPipelineState) { CC_LOG_ERROR("Failed to create MTLRenderPipelineState: %s", [nsError.localizedDescription UTF8String]); diff --git a/native/cocos/renderer/gfx-metal/MTLQueryPool.h b/native/cocos/renderer/gfx-metal/MTLQueryPool.h index 10e871026b..c4db7a5399 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueryPool.h +++ b/native/cocos/renderer/gfx-metal/MTLQueryPool.h @@ -46,7 +46,7 @@ protected: void doInit(const QueryPoolInfo &info) override; void doDestroy() override; - CCMTLGPUQueryPool * _gpuQueryPool{nullptr}; + CCMTLGPUQueryPool *_gpuQueryPool{nullptr}; ccstd::vector _ids; }; diff --git a/native/cocos/renderer/gfx-metal/MTLQueryPool.mm b/native/cocos/renderer/gfx-metal/MTLQueryPool.mm index fd11f5a0ce..6dfb42fd9a 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueryPool.mm +++ b/native/cocos/renderer/gfx-metal/MTLQueryPool.mm @@ -43,13 +43,13 @@ CCMTLQueryPool::~CCMTLQueryPool() { } void CCMTLQueryPool::doInit(const QueryPoolInfo& info) { - id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - _gpuQueryPool = ccnew CCMTLGPUQueryPool; - _gpuQueryPool->type = _type; - _gpuQueryPool->maxQueryObjects = _maxQueryObjects; - _gpuQueryPool->forceWait = _forceWait; + id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); + _gpuQueryPool = ccnew CCMTLGPUQueryPool; + _gpuQueryPool->type = _type; + _gpuQueryPool->maxQueryObjects = _maxQueryObjects; + _gpuQueryPool->forceWait = _forceWait; _gpuQueryPool->visibilityResultBuffer = [mtlDevice newBufferWithLength:_maxQueryObjects * sizeof(uint64_t) options:MTLResourceStorageModeShared]; - _gpuQueryPool->semaphore = ccnew CCMTLSemaphore(1); + _gpuQueryPool->semaphore = ccnew CCMTLSemaphore(1); } void CCMTLQueryPool::doDestroy() { @@ -59,7 +59,7 @@ void CCMTLQueryPool::doDestroy() { CC_SAFE_DELETE(_gpuQueryPool->semaphore); } - id mtlBuffer = _gpuQueryPool->visibilityResultBuffer; + id mtlBuffer = _gpuQueryPool->visibilityResultBuffer; _gpuQueryPool->visibilityResultBuffer = nil; auto destroyFunc = [mtlBuffer]() { diff --git a/native/cocos/renderer/gfx-metal/MTLQueue.h b/native/cocos/renderer/gfx-metal/MTLQueue.h index fa279e6ecc..281d1f95aa 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueue.h +++ b/native/cocos/renderer/gfx-metal/MTLQueue.h @@ -37,7 +37,7 @@ public: explicit CCMTLQueue(); ~CCMTLQueue(); CCMTLQueue(const CCMTLQueue &) = delete; - CCMTLQueue(CCMTLQueue &&) = delete; + CCMTLQueue(CCMTLQueue &&) = delete; CCMTLQueue &operator=(const CCMTLQueue &) = delete; CCMTLQueue &operator=(CCMTLQueue &&) = delete; diff --git a/native/cocos/renderer/gfx-metal/MTLQueue.mm b/native/cocos/renderer/gfx-metal/MTLQueue.mm index 3c4ed793af..983d9ee1ee 100644 --- a/native/cocos/renderer/gfx-metal/MTLQueue.mm +++ b/native/cocos/renderer/gfx-metal/MTLQueue.mm @@ -48,24 +48,24 @@ void CCMTLQueue::doInit(const QueueInfo &info) { } void CCMTLQueue::doDestroy() { - if(_gpuQueueObj) { + if (_gpuQueueObj) { id mtlCmdQueue = _gpuQueueObj->mtlCommandQueue; _gpuQueueObj->mtlCommandQueue = nil; - + auto destroyFunc = [mtlCmdQueue]() { - if(mtlCmdQueue) { + if (mtlCmdQueue) { [mtlCmdQueue release]; } }; CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc); - + CC_SAFE_DELETE(_gpuQueueObj); } } void CCMTLQueue::submit(CommandBuffer *const *cmdBuffs, uint count) { for (uint i = 0u; i < count; ++i) { - CCMTLCommandBuffer *cmdBuffer = static_cast(cmdBuffs[i]); + CCMTLCommandBuffer *cmdBuffer = static_cast(cmdBuffs[i]); _gpuQueueObj->numDrawCalls += cmdBuffer->getNumDrawCalls(); _gpuQueueObj->numInstances += cmdBuffer->getNumInstances(); _gpuQueueObj->numTriangles += cmdBuffer->getNumTris(); diff --git a/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h b/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h index 3fea39a9ce..af8ce10012 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h +++ b/native/cocos/renderer/gfx-metal/MTLRenderCommandEncoder.h @@ -42,14 +42,14 @@ struct Color; class CCMTLRenderCommandEncoder final : public CCMTLCommandEncoder { struct BufferBinding final { id buffer; - uint offset = 0; + uint offset = 0; }; public: - CCMTLRenderCommandEncoder() = default; - ~CCMTLRenderCommandEncoder() = default; + CCMTLRenderCommandEncoder() = default; + ~CCMTLRenderCommandEncoder() = default; CCMTLRenderCommandEncoder(const CCMTLRenderCommandEncoder &) = delete; - CCMTLRenderCommandEncoder(CCMTLRenderCommandEncoder &&) = delete; + CCMTLRenderCommandEncoder(CCMTLRenderCommandEncoder &&) = delete; CCMTLRenderCommandEncoder &operator=(const CCMTLRenderCommandEncoder &) = delete; CCMTLRenderCommandEncoder &operator=(CCMTLRenderCommandEncoder &&) = delete; @@ -63,20 +63,20 @@ public: } inline void clearStates() { - _isViewportSet = false; - _isScissorRectSet = false; - _isCullModeSet = false; - _isFrontFacingWinding = false; + _isViewportSet = false; + _isScissorRectSet = false; + _isCullModeSet = false; + _isFrontFacingWinding = false; _isTriangleFillModeSet = false; - _isDepthClipModeSet = false; - _isDepthBiasSet = false; - _isBlendColorSet = false; + _isDepthClipModeSet = false; + _isDepthBiasSet = false; + _isBlendColorSet = false; - _pipelineState = nil; + _pipelineState = nil; _depthStencilState = nil; _frontReferenceValue = UINT_MAX; - _backReferenceValue = UINT_MAX; + _backReferenceValue = UINT_MAX; _vertexBufferMap.clear(); _fragmentBufferMap.clear(); @@ -95,7 +95,7 @@ public: if (_isViewportSet && _viewport == vp) return; - _viewport = vp; + _viewport = vp; _isViewportSet = true; [_mtlEncoder setViewport:mu::toMTLViewport(_viewport)]; } @@ -104,7 +104,7 @@ public: if (_isScissorRectSet && _scissorRect == rect) return; - _scissorRect = rect; + _scissorRect = rect; _isScissorRectSet = true; [_mtlEncoder setScissorRect:mu::toMTLScissorRect(_scissorRect)]; } @@ -113,7 +113,7 @@ public: if (_isCullModeSet && (_cullMode == mode)) return; - _cullMode = mode; + _cullMode = mode; _isCullModeSet = true; [_mtlEncoder setCullMode:mode]; } @@ -122,7 +122,7 @@ public: if (_isFrontFacingWinding && (_frontFacingWinding == winding)) return; - _frontFacingWinding = winding; + _frontFacingWinding = winding; _isFrontFacingWinding = true; [_mtlEncoder setFrontFacingWinding:_frontFacingWinding]; } @@ -133,7 +133,7 @@ public: if (_isDepthClipModeSet && (_depthClipMode == mode)) return; - _depthClipMode = mode; + _depthClipMode = mode; _isDepthClipModeSet = true; [_mtlEncoder setDepthClipMode:_depthClipMode]; } @@ -144,7 +144,7 @@ public: if (_isTriangleFillModeSet && (_triangleFillMode == mode)) return; - _triangleFillMode = mode; + _triangleFillMode = mode; _isTriangleFillModeSet = true; [_mtlEncoder setTriangleFillMode:_triangleFillMode]; } @@ -162,7 +162,7 @@ public: return; _frontReferenceValue = frontReferenceValue; - _backReferenceValue = backReferenceValue; + _backReferenceValue = backReferenceValue; [_mtlEncoder setStencilFrontReferenceValue:_frontReferenceValue backReferenceValue:_backReferenceValue]; } @@ -183,9 +183,9 @@ public: return; } - _depthBias = depthBias; - _clamp = clamp; - _slope = slope; + _depthBias = depthBias; + _clamp = clamp; + _slope = slope; _isDepthBiasSet = true; [_mtlEncoder setDepthBias:_depthBias slopeScale:_slope @@ -196,7 +196,7 @@ public: if (_isBlendColorSet && _blendColor == color) return; - _blendColor = color; + _blendColor = color; _isBlendColorSet = true; [_mtlEncoder setBlendColorRed:_blendColor.x green:_blendColor.y @@ -275,33 +275,33 @@ public: } protected: - bool _isViewportSet = false; - bool _isScissorRectSet = false; - bool _isCullModeSet = false; - bool _isFrontFacingWinding = false; - bool _isTriangleFillModeSet = false; - bool _isDepthClipModeSet = false; - bool _isDepthBiasSet = false; - bool _isBlendColorSet = false; - id _mtlEncoder = nil; - id _pipelineState = nil; - id _depthStencilState = nil; - uint _frontReferenceValue = UINT_MAX; - uint _backReferenceValue = UINT_MAX; - float _depthBias = 0.f; - float _clamp = 0.f; - float _slope = 0.f; - MTLCullMode _cullMode = MTLCullModeNone; - MTLWinding _frontFacingWinding = MTLWindingClockwise; - CC_UNUSED MTLDepthClipMode _depthClipMode = MTLDepthClipModeClip; - MTLTriangleFillMode _triangleFillMode = MTLTriangleFillModeFill; - Viewport _viewport; - Rect _scissorRect; - Color _blendColor; - ccstd::unordered_map _vertexBufferMap; - ccstd::unordered_map _fragmentBufferMap; - ccstd::unordered_map> _vertexTextureMap; - ccstd::unordered_map> _fragmentTextureMap; + bool _isViewportSet = false; + bool _isScissorRectSet = false; + bool _isCullModeSet = false; + bool _isFrontFacingWinding = false; + bool _isTriangleFillModeSet = false; + bool _isDepthClipModeSet = false; + bool _isDepthBiasSet = false; + bool _isBlendColorSet = false; + id _mtlEncoder = nil; + id _pipelineState = nil; + id _depthStencilState = nil; + uint _frontReferenceValue = UINT_MAX; + uint _backReferenceValue = UINT_MAX; + float _depthBias = 0.f; + float _clamp = 0.f; + float _slope = 0.f; + MTLCullMode _cullMode = MTLCullModeNone; + MTLWinding _frontFacingWinding = MTLWindingClockwise; + CC_UNUSED MTLDepthClipMode _depthClipMode = MTLDepthClipModeClip; + MTLTriangleFillMode _triangleFillMode = MTLTriangleFillModeFill; + Viewport _viewport; + Rect _scissorRect; + Color _blendColor; + ccstd::unordered_map _vertexBufferMap; + ccstd::unordered_map _fragmentBufferMap; + ccstd::unordered_map> _vertexTextureMap; + ccstd::unordered_map> _fragmentTextureMap; ccstd::unordered_map> _vertexSamplerMap; ccstd::unordered_map> _fragmentSamplerMap; }; diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.h b/native/cocos/renderer/gfx-metal/MTLRenderPass.h index b2a96c74d7..208af23c1e 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.h +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.h @@ -45,22 +45,22 @@ public: void setColorAttachment(size_t slot, CCMTLTexture *texture, int level); void setDepthStencilAttachment(CCMTLTexture *texture, int level); - inline MTLRenderPassDescriptor * getMTLRenderPassDescriptor() const { return _mtlRenderPassDescriptor; } - inline uint getColorRenderTargetNums() const { return _colorRenderTargetNums; } + inline MTLRenderPassDescriptor *getMTLRenderPassDescriptor() const { return _mtlRenderPassDescriptor; } + inline uint getColorRenderTargetNums() const { return _colorRenderTargetNums; } inline const ccstd::vector &getRenderTargetSizes() const { return _renderTargetSizes; } - inline void nextSubpass() { _currentSubpassIndex++; } - inline uint getCurrentSubpassIndex() { return _currentSubpassIndex; } - inline void reset() { _currentSubpassIndex = 0; } + inline void nextSubpass() { _currentSubpassIndex++; } + inline uint getCurrentSubpassIndex() { return _currentSubpassIndex; } + inline void reset() { _currentSubpassIndex = 0; } protected: void doInit(const RenderPassInfo &info) override; void doDestroy() override; - uint _outputAttachmentOffset = 0; - uint _currentSubpassIndex = 0; + uint _outputAttachmentOffset = 0; + uint _currentSubpassIndex = 0; MTLRenderPassDescriptor *_mtlRenderPassDescriptor = nil; - uint _colorRenderTargetNums = 0; - ccstd::vector _renderTargetSizes; + uint _colorRenderTargetNums = 0; + ccstd::vector _renderTargetSizes; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm index c402a01c29..e280ee727f 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm @@ -42,12 +42,12 @@ CCMTLRenderPass::~CCMTLRenderPass() { destroy(); } -void CCMTLRenderPass::doInit(const RenderPassInfo &info) { +void CCMTLRenderPass::doInit(const RenderPassInfo& info) { _renderTargetSizes.resize(_colorAttachments.size()); _mtlRenderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; uint i = 0; - for (const auto &colorAttachment : _colorAttachments) { + for (const auto& colorAttachment : _colorAttachments) { _mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachment.loadOp); _mtlRenderPassDescriptor.colorAttachments[i].storeAction = mu::toMTLStoreAction(colorAttachment.storeOp); @@ -79,7 +79,7 @@ void CCMTLRenderPass::setColorAttachment(size_t slot, CCMTLTexture* cctex, int l } id texture = nil; - if(cctex->swapChain()) { + if (cctex->swapChain()) { auto* swapchain = static_cast(cctex->swapChain()); texture = swapchain->colorTexture()->getMTLTexture(); } else { @@ -96,9 +96,9 @@ void CCMTLRenderPass::setDepthStencilAttachment(CCMTLTexture* cctex, int level) CC_LOG_ERROR("CCMTLRenderPass: MTLRenderPassDescriptor should not be nullptr."); return; } - + id texture = nil; - if(cctex->swapChain()) { + if (cctex->swapChain()) { auto* swapchain = static_cast(cctex->swapChain()); texture = swapchain->depthStencilTexture()->getMTLTexture(); } else { @@ -107,7 +107,7 @@ void CCMTLRenderPass::setDepthStencilAttachment(CCMTLTexture* cctex, int level) _mtlRenderPassDescriptor.depthAttachment.texture = texture; _mtlRenderPassDescriptor.depthAttachment.level = level; - if(cctex->getFormat() == Format::DEPTH_STENCIL) { + if (cctex->getFormat() == Format::DEPTH_STENCIL) { _mtlRenderPassDescriptor.stencilAttachment.texture = texture; _mtlRenderPassDescriptor.stencilAttachment.level = level; } diff --git a/native/cocos/renderer/gfx-metal/MTLSampler.h b/native/cocos/renderer/gfx-metal/MTLSampler.h index eaaf079386..aa5e6a1048 100644 --- a/native/cocos/renderer/gfx-metal/MTLSampler.h +++ b/native/cocos/renderer/gfx-metal/MTLSampler.h @@ -36,16 +36,16 @@ class CCMTLSampler final : public Sampler { public: explicit CCMTLSampler(const SamplerInfo &info); ~CCMTLSampler(); - CCMTLSampler() = delete; + CCMTLSampler() = delete; CCMTLSampler(const CCMTLSampler &) = delete; - CCMTLSampler(CCMTLSampler &&) = delete; + CCMTLSampler(CCMTLSampler &&) = delete; CCMTLSampler &operator=(const CCMTLSampler &) = delete; CCMTLSampler &operator=(CCMTLSampler &&) = delete; inline id getMTLSamplerState() const { return _mtlSamplerState; } static CCMTLSampler *getDefaultSampler(); - static void deleteDefaultSampler(); + static void deleteDefaultSampler(); protected: id _mtlSamplerState = nil; diff --git a/native/cocos/renderer/gfx-metal/MTLSampler.mm b/native/cocos/renderer/gfx-metal/MTLSampler.mm index 1207b9c89a..15a6d2ebd9 100644 --- a/native/cocos/renderer/gfx-metal/MTLSampler.mm +++ b/native/cocos/renderer/gfx-metal/MTLSampler.mm @@ -37,7 +37,7 @@ CCMTLSampler* defaultSampler = nullptr; CCMTLSampler::CCMTLSampler(const SamplerInfo& info) : Sampler(info) { _typedID = generateObjectID(); - MTLSamplerDescriptor *descriptor = [[MTLSamplerDescriptor alloc] init]; + MTLSamplerDescriptor* descriptor = [[MTLSamplerDescriptor alloc] init]; #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) descriptor.borderColor = MTLSamplerBorderColorTransparentBlack; #endif @@ -71,14 +71,14 @@ CCMTLSampler::~CCMTLSampler() { } CCMTLSampler* CCMTLSampler::getDefaultSampler() { - if(!defaultSampler) { + if (!defaultSampler) { SamplerInfo info; defaultSampler = ccnew CCMTLSampler(info); } return defaultSampler; } -void CCMTLSampler::deleteDefaultSampler(){ - if(defaultSampler){ +void CCMTLSampler::deleteDefaultSampler() { + if (defaultSampler) { delete defaultSampler; defaultSampler = nullptr; } diff --git a/native/cocos/renderer/gfx-metal/MTLSemaphore.h b/native/cocos/renderer/gfx-metal/MTLSemaphore.h index 51057a1917..23cba29b5a 100644 --- a/native/cocos/renderer/gfx-metal/MTLSemaphore.h +++ b/native/cocos/renderer/gfx-metal/MTLSemaphore.h @@ -35,9 +35,9 @@ public: explicit CCMTLSemaphore(uint initialValue) : _semaphoreCount(initialValue) { _semaphore = dispatch_semaphore_create(initialValue); } - ~CCMTLSemaphore() = default; + ~CCMTLSemaphore() = default; CCMTLSemaphore(const CCMTLSemaphore &) = delete; - CCMTLSemaphore(CCMTLSemaphore &&) = delete; + CCMTLSemaphore(CCMTLSemaphore &&) = delete; CCMTLSemaphore &operator=(const CCMTLSemaphore &) = delete; CCMTLSemaphore &operator=(CCMTLSemaphore &&) = delete; @@ -62,8 +62,8 @@ public: } protected: - dispatch_semaphore_t _semaphore = nullptr; - uint _semaphoreCount = 0; + dispatch_semaphore_t _semaphore = nullptr; + uint _semaphoreCount = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLShader.h b/native/cocos/renderer/gfx-metal/MTLShader.h index a561625f94..0ca479e9cd 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.h +++ b/native/cocos/renderer/gfx-metal/MTLShader.h @@ -38,15 +38,15 @@ public: explicit CCMTLShader(); ~CCMTLShader(); CCMTLShader(const CCMTLShader &) = delete; - CCMTLShader(CCMTLShader &&) = delete; + CCMTLShader(CCMTLShader &&) = delete; CCMTLShader &operator=(const CCMTLShader &) = delete; CCMTLShader &operator=(CCMTLShader &&) = delete; - inline id getVertMTLFunction() const { return _vertFunction; } - inline id getFragmentMTLFunction() const { return _fragFunction; } - inline id getComputeMTLFunction() const { return _cmptFunction; } + inline id getVertMTLFunction() const { return _vertFunction; } + inline id getFragmentMTLFunction() const { return _fragFunction; } + inline id getComputeMTLFunction() const { return _cmptFunction; } inline const ccstd::unordered_map &getFragmentSamplerBindings() const { return _mtlFragmentSamplerBindings; } - inline const CCMTLGPUShader * gpuShader() const { return _gpuShader; } + inline const CCMTLGPUShader *gpuShader() const { return _gpuShader; } uint getAvailableBufferBindingIndex(ShaderStageFlagBit stage, uint stream); @@ -80,8 +80,8 @@ protected: NSMutableDictionary> *_specializedFragFuncs = nil; ccstd::unordered_map _mtlFragmentSamplerBindings; - ccstd::vector _availableVertexBufferBindingIndex; - ccstd::vector _availableFragmentBufferBindingIndex; + ccstd::vector _availableVertexBufferBindingIndex; + ccstd::vector _availableFragmentBufferBindingIndex; CCMTLGPUShader *_gpuShader = nullptr; diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 355b97c2e6..2fcd7344fb 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -43,11 +43,11 @@ CCMTLShader::~CCMTLShader() { destroy(); } -void CCMTLShader::doInit(const ShaderInfo &info) { +void CCMTLShader::doInit(const ShaderInfo& info) { _gpuShader = ccnew CCMTLGPUShader; _specializedFragFuncs = [[NSMutableDictionary alloc] init]; - - for (const auto &stage : _stages) { + + for (const auto& stage : _stages) { if (!createMTLFunction(stage)) { destroy(); return; @@ -61,39 +61,39 @@ void CCMTLShader::doInit(const ShaderInfo &info) { void CCMTLShader::doDestroy() { id vertLib = _vertLibrary; - _vertLibrary = nil; + _vertLibrary = nil; id fragLib = _fragLibrary; - _fragLibrary = nil; + _fragLibrary = nil; id cmptLib = _cmptLibrary; - _cmptLibrary = nil; - + _cmptLibrary = nil; + id vertFunc = _vertFunction; - _vertFunction = nil; + _vertFunction = nil; id fragFunc = _fragFunction; - _fragFunction = nil; + _fragFunction = nil; id cmptFunc = _cmptFunction; - _cmptFunction = nil; - - if(_gpuShader) { + _cmptFunction = nil; + + if (_gpuShader) { [_gpuShader->shaderSrc release]; CC_SAFE_DELETE(_gpuShader); } - + // [_specializedFragFuncs release]; NSMutableDictionary>* specFragFuncs = nil; - if(_specializedFragFuncs) { + if (_specializedFragFuncs) { specFragFuncs = _specializedFragFuncs; _specializedFragFuncs = nil; } - + std::function destroyFunc = [=]() { - if([specFragFuncs count] > 0) { + if ([specFragFuncs count] > 0) { for (NSString* key in [specFragFuncs allKeys]) { [[specFragFuncs valueForKey:key] release]; } } [specFragFuncs release]; - + if (vertFunc) { [vertFunc release]; } @@ -103,56 +103,56 @@ void CCMTLShader::doDestroy() { if (cmptFunc) { [cmptFunc release]; } - - if(vertLib) { + + if (vertLib) { [vertLib release]; } - if(fragLib) { + if (fragLib) { [fragLib release]; } - if(cmptLib) { + if (cmptLib) { [cmptLib release]; } }; CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc); } -bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { - bool isVertexShader = false; +bool CCMTLShader::createMTLFunction(const ShaderStage& stage) { + bool isVertexShader = false; bool isFragmentShader = false; - bool isComputeShader = false; + bool isComputeShader = false; if (stage.stage == ShaderStageFlagBit::VERTEX) { isVertexShader = true; } else if (stage.stage == ShaderStageFlagBit::FRAGMENT) { - isFragmentShader = true; + isFragmentShader = true; } else if (stage.stage == ShaderStageFlagBit::COMPUTE) { isComputeShader = true; } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - if(!spirv) { + if (!spirv) { spirv = SPIRVUtils::getInstance(); spirv->initialize(2); // vulkan >= 1.2 spirv >= 1.5 } - + spirv->compileGLSL(stage.stage, "#version 450\n" + stage.source); if (stage.stage == ShaderStageFlagBit::VERTEX) spirv->compressInputLocations(_attributes); - + auto* spvData = spirv->getOutputData(); size_t unitSize = sizeof(std::remove_pointer::type); - ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize()/unitSize, stage.stage, _gpuShader); + ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, _gpuShader); - NSString * rawSrc = [NSString stringWithUTF8String:stage.source.c_str()]; - NSString * shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; - NSError * error = nil; - MTLCompileOptions *opts = [[MTLCompileOptions alloc] init]; + NSString* rawSrc = [NSString stringWithUTF8String:stage.source.c_str()]; + NSString* shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; + NSError* error = nil; + MTLCompileOptions* opts = [[MTLCompileOptions alloc] init]; //opts.languageVersion = MTLLanguageVersion2_3; - id &library = isVertexShader ? _vertLibrary : isFragmentShader ? _fragLibrary : _cmptLibrary; + id& library = isVertexShader ? _vertLibrary : isFragmentShader ? _fragLibrary : _cmptLibrary; ccstd::string shaderStage = isVertexShader ? "vertex" : isFragmentShader ? "fragment" : "compute"; - - if(isFragmentShader) { - if(@available(iOS 11.0, *)) { + + if (isFragmentShader) { + if (@available(iOS 11.0, *)) { library = [mtlDevice newLibraryWithSource:shader options:opts error:&error]; if (!library) { CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); @@ -174,7 +174,7 @@ bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { return false; } } - + [opts release]; if (isVertexShader) { @@ -207,13 +207,13 @@ bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { #ifdef DEBUG_SHADER if (isVertexShader) { _vertGlslShader = stage.source; - _vertMtlShader = mtlShader; + _vertMtlShader = mtlShader; } else if (isFragmenShader) { _fragGlslShader = stage.source; - _fragMtlShader = mtlShader; + _fragMtlShader = mtlShader; } else if (isComputeShader) { _cmptGlslShader = stage.source; - _cmptMtlShader = mtlShader; + _cmptMtlShader = mtlShader; } #endif return true; @@ -224,17 +224,17 @@ id CCMTLShader::getSpecializedFragFunction(uint* index, int* val, u for (size_t i = 0; i < count; i++) { notEvenHash += val[i] * std::pow(10, index[i]); } - NSString *hashStr = [NSString stringWithFormat:@"%d", notEvenHash]; + NSString* hashStr = [NSString stringWithFormat:@"%d", notEvenHash]; id specFunc = [_specializedFragFuncs objectForKey:hashStr]; - - if(!specFunc) { - if(_gpuShader->specializeColor) { + + if (!specFunc) { + if (_gpuShader->specializeColor) { MTLFunctionConstantValues* constantValues = [MTLFunctionConstantValues new]; for (size_t i = 0; i < count; i++) { [constantValues setConstantValue:&val[i] type:MTLDataTypeInt atIndex:index[i]]; } - - NSError * error = nil; + + NSError* error = nil; id specFragFunc = [_fragLibrary newFunctionWithName:@"main0" constantValues:constantValues error:&error]; [constantValues release]; if (!specFragFunc) { @@ -243,17 +243,16 @@ id CCMTLShader::getSpecializedFragFunction(uint* index, int* val, u [_specializedFragFuncs setObject:specFragFunc forKey:hashStr]; } else { NSString* res = nil; - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { NSString* targetStr = [NSString stringWithFormat:@"(indexOffset%u)", static_cast(i)]; NSString* index = [NSString stringWithFormat:@"(%u)", static_cast(i)]; res = [_gpuShader->shaderSrc stringByReplacingOccurrencesOfString:targetStr withString:index]; - } id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); - NSError * error = nil; - MTLCompileOptions *opts = [[MTLCompileOptions alloc] init]; + NSError* error = nil; + MTLCompileOptions* opts = [[MTLCompileOptions alloc] init]; // always current - if(_fragLibrary) { + if (_fragLibrary) { [_fragLibrary release]; } _fragLibrary = [mtlDevice newLibraryWithSource:res options:opts error:&error]; @@ -266,7 +265,7 @@ id CCMTLShader::getSpecializedFragFunction(uint* index, int* val, u [_fragLibrary release]; CC_LOG_ERROR("Can not create fragment function: main0"); } - + [_specializedFragFuncs setObject:_fragFunction forKey:hashStr]; } } @@ -287,11 +286,11 @@ uint CCMTLShader::getAvailableBufferBindingIndex(ShaderStageFlagBit stage, uint } void CCMTLShader::setAvailableBufferBindingIndex() { - uint usedVertexBufferBindingIndexes = 0; + uint usedVertexBufferBindingIndexes = 0; uint usedFragmentBufferBindingIndexes = 0; - uint vertexBindingCount = 0; - uint fragmentBindingCount = 0; - for (const auto &block : _gpuShader->blocks) { + uint vertexBindingCount = 0; + uint fragmentBindingCount = 0; + for (const auto& block : _gpuShader->blocks) { if (hasFlag(block.second.stages, ShaderStageFlagBit::VERTEX)) { vertexBindingCount++; usedVertexBufferBindingIndexes |= 1 << block.second.mappedBinding; @@ -305,9 +304,9 @@ void CCMTLShader::setAvailableBufferBindingIndex() { auto maxBufferBindingIndex = CCMTLDevice::getInstance()->getMaximumBufferBindingIndex(); _availableVertexBufferBindingIndex.resize(maxBufferBindingIndex - vertexBindingCount); _availableFragmentBufferBindingIndex.resize(maxBufferBindingIndex - fragmentBindingCount); - uint availableVertexBufferBit = ~usedVertexBufferBindingIndexes; + uint availableVertexBufferBit = ~usedVertexBufferBindingIndexes; uint availableFragmentBufferBit = ~usedFragmentBufferBindingIndexes; - int theBit = maxBufferBindingIndex - 1; + int theBit = maxBufferBindingIndex - 1; uint i = 0, j = 0; for (; theBit >= 0; theBit--) { if ((availableVertexBufferBit & (1 << theBit))) { diff --git a/native/cocos/renderer/gfx-metal/MTLSwapchain.h b/native/cocos/renderer/gfx-metal/MTLSwapchain.h index 5ce5df9d13..dc2980a2a2 100644 --- a/native/cocos/renderer/gfx-metal/MTLSwapchain.h +++ b/native/cocos/renderer/gfx-metal/MTLSwapchain.h @@ -40,8 +40,8 @@ public: ~CCMTLSwapchain(); inline CCMTLGPUSwapChainObject *gpuSwapChainObj() { return _gpuSwapchainObj; } - CCMTLTexture * colorTexture(); - CCMTLTexture * depthStencilTexture(); + CCMTLTexture *colorTexture(); + CCMTLTexture *depthStencilTexture(); id currentDrawable(); diff --git a/native/cocos/renderer/gfx-metal/MTLSwapchain.mm b/native/cocos/renderer/gfx-metal/MTLSwapchain.mm index ada4a267ff..d6212acf0a 100644 --- a/native/cocos/renderer/gfx-metal/MTLSwapchain.mm +++ b/native/cocos/renderer/gfx-metal/MTLSwapchain.mm @@ -39,11 +39,11 @@ namespace gfx { namespace { #if CC_PLATFORM == CC_PLATFORM_MAC_OSX - using CCView = NSView; +using CCView = NSView; #else - using CCView = UIView; +using CCView = UIView; #endif -}; +}; // namespace CCMTLSwapchain::CCMTLSwapchain() { } @@ -52,18 +52,18 @@ CCMTLSwapchain::~CCMTLSwapchain() { destroy(); } -void CCMTLSwapchain::doInit(const SwapchainInfo &info) { +void CCMTLSwapchain::doInit(const SwapchainInfo& info) { _gpuSwapchainObj = ccnew CCMTLGPUSwapChainObject; //----------------------acquire layer----------------------------------- -#if CC_EDITOR +#if CC_EDITOR CAMetalLayer* layer = (CAMetalLayer*)info.windowHandle; - if(!layer.device) { + if (!layer.device) { layer.device = MTLCreateSystemDefaultDevice(); } #else - auto* view = (CCView*)info.windowHandle; - CAMetalLayer *layer = static_cast(view.layer); + auto *view = (CCView *)info.windowHandle; + CAMetalLayer *layer = static_cast(view.layer); #endif if (layer.pixelFormat == MTLPixelFormatInvalid) { @@ -93,16 +93,16 @@ void CCMTLSwapchain::doInit(const SwapchainInfo &info) { } _gpuSwapchainObj->mtlLayer = layer; -// MTLPixelFormatBGRA8Unorm -// MTLPixelFormatBGRA8Unorm_sRGB -// MTLPixelFormatRGBA16Float -// MTLPixelFormatRGB10A2Unorm (macOS only) -// MTLPixelFormatBGR10A2Unorm (macOS only) -// MTLPixelFormatBGRA10_XR -// MTLPixelFormatBGRA10_XR_sRGB -// MTLPixelFormatBGR10_XR -// MTLPixelFormatBGR10_XR_sRGB - Format colorFmt = Format::BGRA8; + // MTLPixelFormatBGRA8Unorm + // MTLPixelFormatBGRA8Unorm_sRGB + // MTLPixelFormatRGBA16Float + // MTLPixelFormatRGB10A2Unorm (macOS only) + // MTLPixelFormatBGR10A2Unorm (macOS only) + // MTLPixelFormatBGRA10_XR + // MTLPixelFormatBGRA10_XR_sRGB + // MTLPixelFormatBGR10_XR + // MTLPixelFormatBGR10_XR_sRGB + Format colorFmt = Format::BGRA8; Format depthStencilFmt = Format::DEPTH_STENCIL; _colorTexture = ccnew CCMTLTexture; @@ -110,9 +110,9 @@ void CCMTLSwapchain::doInit(const SwapchainInfo &info) { SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = colorFmt; - textureInfo.width = info.width; - textureInfo.height = info.height; + textureInfo.format = colorFmt; + textureInfo.width = info.width; + textureInfo.height = info.height; initTexture(textureInfo, _colorTexture); textureInfo.format = depthStencilFmt; @@ -121,9 +121,9 @@ void CCMTLSwapchain::doInit(const SwapchainInfo &info) { CCMTLDevice::getInstance()->registerSwapchain(this); } -void CCMTLSwapchain::doDestroy(){ +void CCMTLSwapchain::doDestroy() { CCMTLDevice::getInstance()->unRegisterSwapchain(this); - if(_gpuSwapchainObj) { + if (_gpuSwapchainObj) { _gpuSwapchainObj->currentDrawable = nil; _gpuSwapchainObj->mtlLayer = nil; @@ -135,7 +135,7 @@ void CCMTLSwapchain::doDestroy(){ } void CCMTLSwapchain::doDestroySurface() { - if(_gpuSwapchainObj) { + if (_gpuSwapchainObj) { _gpuSwapchainObj->currentDrawable = nil; _gpuSwapchainObj->mtlLayer = nil; } @@ -165,15 +165,14 @@ void CCMTLSwapchain::release() { void CCMTLSwapchain::acquire() { // hang on here if next drawable not available - while(!_gpuSwapchainObj->currentDrawable) { - _gpuSwapchainObj->currentDrawable = [_gpuSwapchainObj->mtlLayer nextDrawable] ; + while (!_gpuSwapchainObj->currentDrawable) { + _gpuSwapchainObj->currentDrawable = [_gpuSwapchainObj->mtlLayer nextDrawable]; static_cast(_colorTexture.get())->update(); } } -void CCMTLSwapchain::doCreateSurface(void *windowHandle) { - +void CCMTLSwapchain::doCreateSurface(void* windowHandle) { } -} -} +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.h b/native/cocos/renderer/gfx-metal/MTLTexture.h index d75c4a90a3..e5f46b1a7b 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.h +++ b/native/cocos/renderer/gfx-metal/MTLTexture.h @@ -40,7 +40,7 @@ public: explicit CCMTLTexture(); ~CCMTLTexture(); CCMTLTexture(const CCMTLTexture &) = delete; - CCMTLTexture(CCMTLTexture &&) = delete; + CCMTLTexture(CCMTLTexture &&) = delete; CCMTLTexture &operator=(const CCMTLTexture &) = delete; CCMTLTexture &operator=(CCMTLTexture &&) = delete; @@ -48,17 +48,17 @@ public: return _isTextureView ? _mtlTextureView : _mtlTexture; } inline Format getConvertedFormat() const { return _convertedFormat; } - inline bool isArray() const { return _isArray; } - inline bool isPVRTC() const { return _isPVRTC; } + inline bool isArray() const { return _isArray; } + inline bool isPVRTC() const { return _isPVRTC; } //update drawable from swapchain. void update(); const TextureInfo &textureInfo(); - CCMTLSwapchain * swapChain(); + CCMTLSwapchain *swapChain(); static CCMTLTexture *getDefaultTexture(); - static void deleteDefaultTexture(); + static void deleteDefaultTexture(); protected: void doInit(const TextureInfo &info) override; @@ -70,10 +70,10 @@ protected: bool createMTLTexture(); Format _convertedFormat = Format::UNKNOWN; - bool _isArray = false; - bool _isPVRTC = false; + bool _isArray = false; + bool _isPVRTC = false; - id _mtlTexture = nil; + id _mtlTexture = nil; id _mtlTextureView = nil; }; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 848f2f63fa..048b7e39f2 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -41,7 +41,7 @@ namespace cc { namespace gfx { namespace { -CCMTLTexture* defaultTexture = nullptr; +CCMTLTexture *defaultTexture = nullptr; } CCMTLTexture::CCMTLTexture() : Texture() { @@ -63,7 +63,7 @@ void CCMTLTexture::doInit(const TextureInfo &info) { _isPVRTC = true; } - if(_info.externalRes) { + if (_info.externalRes) { auto pixelBuffer = static_cast(_info.externalRes); size_t width = CVPixelBufferGetWidth(pixelBuffer); size_t height = CVPixelBufferGetHeight(pixelBuffer); @@ -71,11 +71,11 @@ void CCMTLTexture::doInit(const TextureInfo &info) { CVReturn cvret; CVMetalTextureCacheRef CVMTLTextureCache; cvret = CVMetalTextureCacheCreate( - kCFAllocatorDefault, - nil, - (id)CCMTLDevice::getInstance()->getMTLDevice(), - nil, - &CVMTLTextureCache); + kCFAllocatorDefault, + nil, + (id)CCMTLDevice::getInstance()->getMTLDevice(), + nil, + &CVMTLTextureCache); CC_ASSERT(cvret == kCVReturnSuccess); // Failed to create Metal texture cache. @@ -83,13 +83,13 @@ void CCMTLTexture::doInit(const TextureInfo &info) { MTLPixelFormat mtlFormat = mu::toMTLPixelFormat(_convertedFormat); CVMetalTextureRef CVMTLTexture; cvret = CVMetalTextureCacheCreateTextureFromImage( - kCFAllocatorDefault, - CVMTLTextureCache, - pixelBuffer, nil, - mtlFormat, - width, height, - 0, - &CVMTLTexture); + kCFAllocatorDefault, + CVMTLTextureCache, + pixelBuffer, nil, + mtlFormat, + width, height, + 0, + &CVMTLTexture); CC_ASSERT(cvret == kCVReturnSuccess); // Failed to create CoreVideo Metal texture from image. @@ -121,11 +121,11 @@ void CCMTLTexture::doInit(const TextureViewInfo &info) { } _convertedFormat = mu::convertGFXPixelFormat(_viewInfo.format); auto mtlTextureType = mu::toMTLTextureType(_viewInfo.type); - _mtlTextureView = [static_cast(_viewInfo.texture)->_mtlTexture - newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) - textureType:mtlTextureType - levels:NSMakeRange(_viewInfo.baseLevel, _viewInfo.levelCount) - slices:NSMakeRange(_viewInfo.baseLayer, _viewInfo.layerCount)]; + _mtlTextureView = [static_cast(_viewInfo.texture)->_mtlTexture + newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) + textureType:mtlTextureType + levels:NSMakeRange(_viewInfo.baseLevel, _viewInfo.levelCount) + slices:NSMakeRange(_viewInfo.baseLayer, _viewInfo.layerCount)]; } void CCMTLTexture::doInit(const SwapchainTextureInfo &info) { @@ -133,13 +133,13 @@ void CCMTLTexture::doInit(const SwapchainTextureInfo &info) { if (info.format == Format::DEPTH_STENCIL) { createMTLTexture(); } else { - _mtlTexture = [static_cast(_swapchain)->currentDrawable() texture]; + _mtlTexture = [static_cast(_swapchain)->currentDrawable() texture]; } } void CCMTLTexture::update() { - if(_swapchain) { - id drawable = static_cast(_swapchain)->currentDrawable(); + if (_swapchain) { + id drawable = static_cast(_swapchain)->currentDrawable(); _mtlTexture = drawable ? [drawable texture] : nil; } } @@ -184,19 +184,19 @@ bool CCMTLTexture::createMTLTexture() { descriptor.mipmapLevelCount = _info.levelCount; descriptor.arrayLength = _info.type == TextureType::CUBE ? 1 : _info.layerCount; - if(hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _info.usage) && mu::isImageBlockSupported()) { + if (hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT, _info.usage) && mu::isImageBlockSupported()) { #if MEMLESS_ON // mac SDK mem_less unavailable before 11.0 -#if MAC_MEMORY_LESS_TEXTURE_SUPPORT || CC_PLATFORM == CC_PLATFORM_MAC_IOS + #if MAC_MEMORY_LESS_TEXTURE_SUPPORT || CC_PLATFORM == CC_PLATFORM_MAC_IOS //xcode OS version warning if (@available(macOS 11.0, *)) { descriptor.storageMode = MTLStorageModeMemoryless; } else { descriptor.storageMode = MTLStorageModePrivate; } -#else + #else descriptor.storageMode = MTLStorageModePrivate; -#endif + #endif #else descriptor.storageMode = MTLStorageModePrivate; #endif @@ -210,30 +210,28 @@ bool CCMTLTexture::createMTLTexture() { return _mtlTexture != nil; } -CCMTLSwapchain* CCMTLTexture::swapChain() { - return static_cast(_swapchain); +CCMTLSwapchain *CCMTLTexture::swapChain() { + return static_cast(_swapchain); } -const TextureInfo& CCMTLTexture::textureInfo() { - return _isTextureView ? - static_cast(_viewInfo.texture)->_info : - _info; +const TextureInfo &CCMTLTexture::textureInfo() { + return _isTextureView ? static_cast(_viewInfo.texture)->_info : _info; } void CCMTLTexture::doDestroy() { //decrease only non-swapchain tex and have had been inited. - if(!_swapchain && _mtlTexture) { + if (!_swapchain && _mtlTexture) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= _size; } - if(_swapchain) { + if (_swapchain) { _swapchain = nullptr; _mtlTexture = nil; return; } - id mtlTexure = nil; - if(_isTextureView) { + id mtlTexure = nil; + if (_isTextureView) { mtlTexure = _mtlTextureView; _mtlTextureView = nil; } else { @@ -242,11 +240,11 @@ void CCMTLTexture::doDestroy() { } CC_PROFILE_MEMORY_DEC(Texture, _size); - + std::function destroyFunc = [mtlTexure]() { if (mtlTexure) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here -// [mtlTexure setPurgeableState:MTLPurgeableStateEmpty]; + // [mtlTexure setPurgeableState:MTLPurgeableStateEmpty]; [mtlTexure release]; } }; @@ -255,7 +253,7 @@ void CCMTLTexture::doDestroy() { } void CCMTLTexture::doResize(uint width, uint height, uint size) { - if(_isTextureView) { + if (_isTextureView) { CC_LOG_ERROR("TextureView does not support resize! at %p", this); return; } @@ -276,21 +274,21 @@ void CCMTLTexture::doResize(uint width, uint height, uint size) { CC_LOG_ERROR("CCMTLTexture: create MTLTexture failed when try to resize the texture."); return; } - + // texture is a wrapper of drawable when _swapchain is active, drawable is not a resource alloc by gfx, // but the system so skip here. - if(!_swapchain) { + if (!_swapchain) { CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= oldSize; CCMTLDevice::getInstance()->getMemoryStatus().textureSize += size; CC_PROFILE_MEMORY_DEC(Texture, oldSize); CC_PROFILE_MEMORY_INC(Texture, size); } - + if (oldMTLTexture) { std::function destroyFunc = [=]() { if (oldMTLTexture) { //TODO_Zeqiang: [mac12 | ios15, ...) validate here -// [oldMTLTexture setPurgeableState:MTLPurgeableStateEmpty]; + // [oldMTLTexture setPurgeableState:MTLPurgeableStateEmpty]; [oldMTLTexture release]; } }; @@ -299,28 +297,27 @@ void CCMTLTexture::doResize(uint width, uint height, uint size) { } } -CCMTLTexture* CCMTLTexture::getDefaultTexture() { - if(!defaultTexture) { +CCMTLTexture *CCMTLTexture::getDefaultTexture() { + if (!defaultTexture) { TextureInfo info; info.type = TextureType::TEX2D; info.usage = TextureUsage::SAMPLED; info.format = Format::BGRA8; info.width = 2; info.height = 2; - + defaultTexture = ccnew CCMTLTexture(); defaultTexture->initialize(info); } return defaultTexture; } -void CCMTLTexture::deleteDefaultTexture(){ +void CCMTLTexture::deleteDefaultTexture() { if (defaultTexture) { delete defaultTexture; defaultTexture = nullptr; } } - } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index 113c90d813..06c2acb3f5 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -43,75 +43,75 @@ namespace mu { API_AVAILABLE(ios(12.0)) MTLMultisampleStencilResolveFilter toMTLStencilResolveMode(ResolveMode mode); -MTLResourceOptions toMTLResourceOption(MemoryUsage usage); -MTLLoadAction toMTLLoadAction(LoadOp op); -MTLStoreAction toMTLStoreAction(StoreOp op); -MTLStoreAction toMTLMSAAStoreAction(StoreOp op); -MTLClearColor toMTLClearColor(const Color &clearColor); -MTLVertexFormat toMTLVertexFormat(Format, bool); -MTLPixelFormat toMTLPixelFormat(Format); +MTLResourceOptions toMTLResourceOption(MemoryUsage usage); +MTLLoadAction toMTLLoadAction(LoadOp op); +MTLStoreAction toMTLStoreAction(StoreOp op); +MTLStoreAction toMTLMSAAStoreAction(StoreOp op); +MTLClearColor toMTLClearColor(const Color &clearColor); +MTLVertexFormat toMTLVertexFormat(Format, bool); +MTLPixelFormat toMTLPixelFormat(Format); MTLMultisampleDepthResolveFilter toMTLDepthResolveMode(ResolveMode mode); // Because some pixel format is not supported on metal, so need to convert to supported pixel format. -Format convertGFXPixelFormat(Format); -MTLColorWriteMask toMTLColorWriteMask(ColorMask); -MTLBlendFactor toMTLBlendFactor(BlendFactor); -MTLBlendOperation toMTLBlendOperation(BlendOp); -MTLCullMode toMTLCullMode(CullMode); -MTLWinding toMTLWinding(bool isFrontFaceCCW); -MTLViewport toMTLViewport(const Viewport &); -MTLScissorRect toMTLScissorRect(const Rect &); -MTLTriangleFillMode toMTLTriangleFillMode(PolygonMode); -MTLDepthClipMode toMTLDepthClipMode(bool isClip); -MTLCompareFunction toMTLCompareFunction(ComparisonFunc); -MTLStencilOperation toMTLStencilOperation(StencilOp); -MTLPrimitiveType toMTLPrimitiveType(PrimitiveMode); -MTLTextureUsage toMTLTextureUsage(TextureUsage); -MTLTextureType toMTLTextureType(TextureType type); -NSUInteger toMTLSampleCount(SampleCount); -MTLSamplerAddressMode toMTLSamplerAddressMode(Address); -int toMTLSamplerBorderColor(const Color &); +Format convertGFXPixelFormat(Format); +MTLColorWriteMask toMTLColorWriteMask(ColorMask); +MTLBlendFactor toMTLBlendFactor(BlendFactor); +MTLBlendOperation toMTLBlendOperation(BlendOp); +MTLCullMode toMTLCullMode(CullMode); +MTLWinding toMTLWinding(bool isFrontFaceCCW); +MTLViewport toMTLViewport(const Viewport &); +MTLScissorRect toMTLScissorRect(const Rect &); +MTLTriangleFillMode toMTLTriangleFillMode(PolygonMode); +MTLDepthClipMode toMTLDepthClipMode(bool isClip); +MTLCompareFunction toMTLCompareFunction(ComparisonFunc); +MTLStencilOperation toMTLStencilOperation(StencilOp); +MTLPrimitiveType toMTLPrimitiveType(PrimitiveMode); +MTLTextureUsage toMTLTextureUsage(TextureUsage); +MTLTextureType toMTLTextureType(TextureType type); +NSUInteger toMTLSampleCount(SampleCount); +MTLSamplerAddressMode toMTLSamplerAddressMode(Address); +int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); -MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader); -const uint8_t * convertRGB8ToRGBA8(const uint8_t *source, uint length); -const uint8_t * convertRGB32FToRGBA32F(const uint8_t *source, uint length); -NSUInteger highestSupportedFeatureSet(id device); -uint getGPUFamily(MTLFeatureSet featureSet); -uint getMaxVertexAttributes(uint family); -uint getMaxEntriesInBufferArgumentTable(uint family); -uint getMaxEntriesInTextureArgumentTable(uint family); -uint getMaxEntriesInSamplerStateArgumentTable(uint family); -uint getMaxTexture2DWidthHeight(uint family); -uint getMaxCubeMapTextureWidthHeight(uint family); -uint getMaxColorRenderTarget(uint family); -uint getMinBufferOffsetAlignment(uint family); -uint getMaxThreadsPerGroup(uint family); -bool isPVRTCSuppported(uint family); -bool isEAC_ETCCSuppported(uint family); -bool isASTCSuppported(uint family); -bool isBCSupported(uint family); -bool isColorBufferFloatSupported(uint family); -bool isColorBufferHalfFloatSupported(uint family); -bool isLinearTextureSupported(uint family); -bool isUISamplerSupported(uint family); -bool isRGB10A2UIStorageSupported(uint family); -bool isDDepthStencilFilterSupported(uint family); -bool isIndirectCommandBufferSupported(MTLFeatureSet featureSet); -bool isDepthStencilFormatSupported(id device, Format format, uint family); -MTLPixelFormat getSupportedDepthStencilFormat(id device, uint family, uint &depthBits); -bool isIndirectDrawSupported(uint family); -bool isImageBlockSupported(); -bool isFramebufferFetchSupported(); -ccstd::string featureSetToString(MTLFeatureSet featureSet); -const uint8_t *const convertData(const uint8_t *source, uint length, Format type); -uint getBlockSize(Format format); -uint getBytesPerRow(Format format, uint width); -bool pixelFormatIsColorRenderable(Format format); -bool isSamplerDescriptorCompareFunctionSupported(uint family); -void clearRenderArea(CCMTLDevice *device, id renderEncoder, RenderPass *renderPass, const Rect &renderArea, const Color *colors, float depth, uint stencil); -inline uint alignUp(uint inSize, uint align) { return ((inSize + align - 1) / align) * align; } -void clearUtilResource(); -inline uint roundUp(uint dividend, uint divisor) { return (dividend - 1) / divisor + 1; } +MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); +ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader); +const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint length); +const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint length); +NSUInteger highestSupportedFeatureSet(id device); +uint getGPUFamily(MTLFeatureSet featureSet); +uint getMaxVertexAttributes(uint family); +uint getMaxEntriesInBufferArgumentTable(uint family); +uint getMaxEntriesInTextureArgumentTable(uint family); +uint getMaxEntriesInSamplerStateArgumentTable(uint family); +uint getMaxTexture2DWidthHeight(uint family); +uint getMaxCubeMapTextureWidthHeight(uint family); +uint getMaxColorRenderTarget(uint family); +uint getMinBufferOffsetAlignment(uint family); +uint getMaxThreadsPerGroup(uint family); +bool isPVRTCSuppported(uint family); +bool isEAC_ETCCSuppported(uint family); +bool isASTCSuppported(uint family); +bool isBCSupported(uint family); +bool isColorBufferFloatSupported(uint family); +bool isColorBufferHalfFloatSupported(uint family); +bool isLinearTextureSupported(uint family); +bool isUISamplerSupported(uint family); +bool isRGB10A2UIStorageSupported(uint family); +bool isDDepthStencilFilterSupported(uint family); +bool isIndirectCommandBufferSupported(MTLFeatureSet featureSet); +bool isDepthStencilFormatSupported(id device, Format format, uint family); +MTLPixelFormat getSupportedDepthStencilFormat(id device, uint family, uint &depthBits); +bool isIndirectDrawSupported(uint family); +bool isImageBlockSupported(); +bool isFramebufferFetchSupported(); +ccstd::string featureSetToString(MTLFeatureSet featureSet); +const uint8_t *const convertData(const uint8_t *source, uint length, Format type); +uint getBlockSize(Format format); +uint getBytesPerRow(Format format, uint width); +bool pixelFormatIsColorRenderable(Format format); +bool isSamplerDescriptorCompareFunctionSupported(uint family); +void clearRenderArea(CCMTLDevice *device, id renderEncoder, RenderPass *renderPass, const Rect &renderArea, const Color *colors, float depth, uint stencil); +inline uint alignUp(uint inSize, uint align) { return ((inSize + align - 1) / align) * align; } +void clearUtilResource(); +inline uint roundUp(uint dividend, uint divisor) { return (dividend - 1) / divisor + 1; } } // namespace mu } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 6ab2b88da8..533d511ebe 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -40,8 +40,8 @@ namespace cc { namespace gfx { namespace { -ccstd::unordered_map pipelineMap; -ccstd::unordered_map renderPassMap; +ccstd::unordered_map pipelineMap; +ccstd::unordered_map renderPassMap; EShLanguage getShaderStage(ShaderStageFlagBit type) { switch (type) { @@ -82,8 +82,6 @@ glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { } } - - //See more details at https://developer.apple.com/documentation/metal/mtlfeatureset enum class GPUFamily { Apple1, // A7, @@ -314,58 +312,58 @@ bool isASTCFormat(Format format) { } } -gfx::Shader *createShader(CCMTLDevice *device, CCMTLRenderPass* renderPass) { +gfx::Shader *createShader(CCMTLDevice *device, CCMTLRenderPass *renderPass) { ccstd::string vs = R"( layout(location = 0) in vec2 a_position; void main() { gl_Position = vec4(a_position, 1.0, 1.0); } )"; -// ccstd::string fs = R"( -// precision mediump float; -// layout(set = 0, binding = 0) uniform Color { -// vec4 u_color; -// }; -// layout(location = 0) out vec4 o_color; -// -// void main() { -// o_color = u_color; -// } -// )"; - + // ccstd::string fs = R"( + // precision mediump float; + // layout(set = 0, binding = 0) uniform Color { + // vec4 u_color; + // }; + // layout(location = 0) out vec4 o_color; + // + // void main() { + // o_color = u_color; + // } + // )"; + ccstd::string fs = R"( precision mediump float; layout(set = 0, binding = 0) uniform Color { vec4 u_color; }; )"; - + //TODO_Zeqiang: gather info in framegraph. - if(renderPass->getSubpasses().empty()) { + if (renderPass->getSubpasses().empty()) { for (size_t i = 0; i < renderPass->getColorAttachments().size(); ++i) { fs += "\n layout(location = " + std::to_string(i) + ") out vec4 o_color" + std::to_string(i) + ";"; } - + fs += "\nvoid main() {\n o_color0 = u_color;\n"; - + for (size_t i = 1; i < renderPass->getColorAttachments().size(); ++i) { fs += " o_color" + std::to_string(i) + " = vec4(0.0);\n"; } } else { - const auto& subpasses = renderPass->getSubpasses(); + const auto &subpasses = renderPass->getSubpasses(); for (size_t i = 0; i < subpasses[renderPass->getCurrentSubpassIndex()].colors.size(); ++i) { fs += "\n layout(location = " + std::to_string(i) + ") out vec4 o_color" + std::to_string(i) + ";"; } - + fs += "\nvoid main() {\n o_color0 = u_color;\n"; - + for (size_t i = 1; i < subpasses[renderPass->getCurrentSubpassIndex()].colors.size(); ++i) { fs += " o_color" + std::to_string(i) + " = vec4(0.0);\n"; } } - + fs += "}"; - + gfx::ShaderStageList shaderStageList; gfx::ShaderStage vertexShaderStage; vertexShaderStage.stage = gfx::ShaderStageFlagBit::VERTEX; @@ -390,10 +388,10 @@ gfx::Shader *createShader(CCMTLDevice *device, CCMTLRenderPass* renderPass) { return device->createShader(shaderInfo); } -CCMTLGPUPipelineState *getClearRenderPassPipelineState(CCMTLDevice *device, RenderPass * curPass) { +CCMTLGPUPipelineState *getClearRenderPassPipelineState(CCMTLDevice *device, RenderPass *curPass) { size_t rpHash = curPass->getHash(); const auto iter = pipelineMap.find(rpHash); - if(iter != pipelineMap.end()) { + if (iter != pipelineMap.end()) { auto *ccMtlPiplineState = static_cast(iter->second); return ccMtlPiplineState->getGPUPipelineState(); } @@ -401,23 +399,23 @@ CCMTLGPUPipelineState *getClearRenderPassPipelineState(CCMTLDevice *device, Rend gfx::Attribute position = {"a_position", gfx::Format::RG32F, false, 0, false}; gfx::PipelineStateInfo pipelineInfo; pipelineInfo.primitive = gfx::PrimitiveMode::TRIANGLE_LIST; - pipelineInfo.shader = createShader(device, static_cast(curPass)); + pipelineInfo.shader = createShader(device, static_cast(curPass)); pipelineInfo.inputState = {{position}}; pipelineInfo.renderPass = curPass; DepthStencilState dsState; - dsState.depthWrite = 0; - dsState.depthTest = 1; - dsState.depthFunc = ComparisonFunc::LESS_EQUAL; + dsState.depthWrite = 0; + dsState.depthTest = 1; + dsState.depthFunc = ComparisonFunc::LESS_EQUAL; pipelineInfo.depthStencilState = dsState; PipelineState *pipelineState = device->createPipelineState(std::move(pipelineInfo)); pipelineMap.emplace(std::make_pair(curPass->getHash(), pipelineState)); - ((CCMTLPipelineState*)pipelineState)->check(); + ((CCMTLPipelineState *)pipelineState)->check(); delete pipelineInfo.shader; return static_cast(pipelineState)->getGPUPipelineState(); } -} +} // namespace MTLResourceOptions mu::toMTLResourceOption(MemoryUsage usage) { if (usage & MemoryUsage::HOST && usage & MemoryUsage::DEVICE) @@ -854,10 +852,11 @@ NSUInteger mu::toMTLSampleCount(SampleCount count) { case SampleCount::ONE: return 1; case SampleCount::MULTIPLE_PERFORMANCE: return 2; case SampleCount::MULTIPLE_BALANCE: return 4; - case SampleCount::MULTIPLE_QUALITY: return 8; -// case SampleCount::X16: return 16; -// case SampleCount::X32: return 32; -// case SampleCount::X64: return 64; + case SampleCount::MULTIPLE_QUALITY: + return 8; + // case SampleCount::X16: return 16; + // case SampleCount::X32: return 32; + // case SampleCount::X64: return 64; } } @@ -912,7 +911,7 @@ MTLSamplerMipFilter mu::toMTLSamplerMipFilter(Filter filter) { bool mu::isImageBlockSupported() { //implicit imageblocks - if(!mu::isFramebufferFetchSupported()) { + if (!mu::isFramebufferFetchSupported()) { return false; } #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) //|| TARGET_CPU_ARM64 @@ -931,9 +930,9 @@ bool mu::isFramebufferFetchSupported() { } ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, - ShaderStageFlagBit shaderType, - CCMTLGPUShader *gpuShader) { - CCMTLDevice* device = CCMTLDevice::getInstance(); + ShaderStageFlagBit shaderType, + CCMTLGPUShader *gpuShader) { + CCMTLDevice *device = CCMTLDevice::getInstance(); spirv_cross::CompilerMSL msl(ir, word_count); // The SPIR-V is now parsed, and we can perform reflection on it. @@ -954,7 +953,7 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, #endif options.emulate_subgroups = true; options.pad_fragment_output_components = true; - if(isFramebufferFetchSupported()) { + if (isFramebufferFetchSupported()) { options.use_framebuffer_fetch_subpasses = true; #if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) options.set_msl_version(2, 3, 0); @@ -1002,7 +1001,7 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, if (binding >= maxBufferBindingIndex) { CC_LOG_ERROR("Implementation limits: %s binding at %d, should not use more than %d entries in the buffer argument table", ubo.name.c_str(), binding, maxBufferBindingIndex); } - + uint fakeHash = set * 128 + binding; if (gpuShader->blocks.find(fakeHash) == gpuShader->blocks.end()) { auto mappedBinding = gpuShader->bufferIndex; @@ -1028,7 +1027,7 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, CC_LOG_ERROR("Implementation limits: Should not use more than %d entries in the sampler state argument table", device->getMaximumSamplerUnits()); return ""; } - + // avoid conflict index with input attachments. const uint8_t rtOffsets = executionModel == spv::ExecutionModelFragment ? resources.subpass_inputs.size() : 0; for (const auto &sampler : resources.sampled_images) { @@ -1057,10 +1056,10 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, } } - if(executionModel == spv::ExecutionModelFragment) { + if (executionModel == spv::ExecutionModelFragment) { gpuShader->outputs.resize(resources.stage_outputs.size()); - for(size_t i = 0; i < resources.stage_outputs.size(); i++) { - const auto& stageOutput = resources.stage_outputs[i]; + for (size_t i = 0; i < resources.stage_outputs.size(); i++) { + const auto &stageOutput = resources.stage_outputs[i]; auto set = msl.get_decoration(stageOutput.id, spv::DecorationDescriptorSet); auto attachmentIndex = static_cast(i); msl.set_decoration(stageOutput.id, spv::DecorationLocation, attachmentIndex); @@ -1069,14 +1068,14 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, gpuShader->outputs[i].binding = attachmentIndex; } - if(!resources.subpass_inputs.empty()) { + if (!resources.subpass_inputs.empty()) { gpuShader->inputs.resize(resources.subpass_inputs.size()); - for(size_t i = 0; i < resources.subpass_inputs.size(); i++) { - const auto& attachment = resources.subpass_inputs[i]; + for (size_t i = 0; i < resources.subpass_inputs.size(); i++) { + const auto &attachment = resources.subpass_inputs[i]; gpuShader->inputs[i].name = attachment.name; auto set = msl.get_decoration(attachment.id, spv::DecorationDescriptorSet); auto index = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); - msl.set_decoration(attachment.id, spv::DecorationBinding,index); + msl.set_decoration(attachment.id, spv::DecorationBinding, index); gpuShader->inputs[i].binding = index; gpuShader->inputs[i].set = set; } @@ -1085,11 +1084,11 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, // Compile to MSL, ready to give to metal driver. ccstd::string output = msl.compile(); - if(executionModel == spv::ExecutionModelFragment) { + if (executionModel == spv::ExecutionModelFragment) { // add custom function constant to achieve delay binding for color attachment. auto customCodingPos = output.find("using namespace metal;"); int32_t maxIndex = static_cast(resources.stage_outputs.size() - 1); - for(int i = maxIndex; i >=0; --i) { + for (int i = maxIndex; i >= 0; --i) { ccstd::string indexStr = std::to_string(i); output.insert(customCodingPos, "\nconstant int indexOffset" + indexStr + " [[function_constant(" + indexStr + ")]];\n"); output.replace(output.find("color(" + indexStr + ")"), 8, "color(indexOffset" + indexStr + ")"); @@ -1485,47 +1484,47 @@ bool mu::isIndirectCommandBufferSupported(MTLFeatureSet featureSet) { } bool mu::isDepthStencilFormatSupported(id device, Format format, uint family) { return true; -// GPUFamily gpuFamily = static_cast(family); -// switch (format) { -// case Format::D16: -// switch (gpuFamily) { -// case GPUFamily::Apple1: -// case GPUFamily::Apple2: -// case GPUFamily::Apple3: -// case GPUFamily::Apple4: -// case GPUFamily::Apple5: -// case GPUFamily::Apple6: -// case GPUFamily::Mac1: -// case GPUFamily::Mac2: -// return true; -// } -// case Format::D32F: -// case Format::D32F_S8: -// switch (gpuFamily) { -// case GPUFamily::Apple1: -// case GPUFamily::Apple2: -// case GPUFamily::Apple3: -// case GPUFamily::Apple4: -// case GPUFamily::Apple5: -// case GPUFamily::Apple6: -//#ifdef TARGET_OS_SIMULATOR -// return true; -//#else -// return false; -//#endif -// case GPUFamily::Mac1: -// case GPUFamily::Mac2: -// return true; -// } -// case Format::D24S8: -//#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) -// return [device isDepth24Stencil8PixelFormatSupported]; -//#else -// return false; -//#endif -// default: -// return false; -// } + // GPUFamily gpuFamily = static_cast(family); + // switch (format) { + // case Format::D16: + // switch (gpuFamily) { + // case GPUFamily::Apple1: + // case GPUFamily::Apple2: + // case GPUFamily::Apple3: + // case GPUFamily::Apple4: + // case GPUFamily::Apple5: + // case GPUFamily::Apple6: + // case GPUFamily::Mac1: + // case GPUFamily::Mac2: + // return true; + // } + // case Format::D32F: + // case Format::D32F_S8: + // switch (gpuFamily) { + // case GPUFamily::Apple1: + // case GPUFamily::Apple2: + // case GPUFamily::Apple3: + // case GPUFamily::Apple4: + // case GPUFamily::Apple5: + // case GPUFamily::Apple6: + //#ifdef TARGET_OS_SIMULATOR + // return true; + //#else + // return false; + //#endif + // case GPUFamily::Mac1: + // case GPUFamily::Mac2: + // return true; + // } + // case Format::D24S8: + //#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX) + // return [device isDepth24Stencil8PixelFormatSupported]; + //#else + // return false; + //#endif + // default: + // return false; + // } } bool mu::isIndirectDrawSupported(uint family) { @@ -1758,20 +1757,19 @@ void mu::clearRenderArea(CCMTLDevice *device, id render [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:count]; - } void mu::clearUtilResource() { - if(!renderPassMap.empty()) { - for (auto& pass : renderPassMap) { + if (!renderPassMap.empty()) { + for (auto &pass : renderPassMap) { //TODO: create and destroy not in the same level pass.second->destroy(); delete pass.second; } renderPassMap.clear(); } - if(!pipelineMap.empty()) { - for (auto& pipeline : pipelineMap) { + if (!pipelineMap.empty()) { + for (auto &pipeline : pipelineMap) { pipeline.second->destroy(); delete pipeline.second; } diff --git a/native/cocos/renderer/gfx-validator/BufferValidator.cpp b/native/cocos/renderer/gfx-validator/BufferValidator.cpp index 0afa3ddab3..bdc9f9f8bc 100644 --- a/native/cocos/renderer/gfx-validator/BufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/BufferValidator.cpp @@ -59,8 +59,8 @@ void BufferValidator::doInit(const BufferInfo &info) { CC_ASSERT(info.size); CC_ASSERT(info.size / info.stride * info.stride == info.size); - _initStack = utils::getStacktraceJS(); - _creationFrame = DeviceValidator::getInstance()->currentFrame(); + _initStack = utils::getStacktraceJS(); + _creationFrame = DeviceValidator::getInstance()->currentFrame(); _totalUpdateTimes = 0U; if (hasFlag(info.usage, BufferUsageBit::VERTEX) && !info.stride) { @@ -91,7 +91,7 @@ void BufferValidator::doInit(const BufferViewInfo &info) { /////////// execute /////////// BufferViewInfo actorInfo = info; - actorInfo.buffer = static_cast(info.buffer)->getActor(); + actorInfo.buffer = static_cast(info.buffer)->getActor(); _actor->initialize(actorInfo); } @@ -128,9 +128,9 @@ void BufferValidator::update(const void *buffer, uint32_t size) { CC_ASSERT(buffer); if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { - const auto * drawInfo = static_cast(buffer); + const auto *drawInfo = static_cast(buffer); const size_t drawInfoCount = size / sizeof(DrawInfo); - const bool isIndexed = drawInfoCount > 0 && drawInfo->indexCount > 0; + const bool isIndexed = drawInfoCount > 0 && drawInfo->indexCount > 0; for (size_t i = 1U; i < drawInfoCount; ++i) { if ((++drawInfo)->indexCount > 0 != isIndexed) { // Inconsistent indirect draw infos on using index buffer. diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index a961fa5a89..23a27189e5 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -74,7 +74,7 @@ void CommandBufferValidator::doInit(const CommandBufferInfo &info) { /////////// execute /////////// CommandBufferInfo actorInfo = info; - actorInfo.queue = static_cast(info.queue)->getActor(); + actorInfo.queue = static_cast(info.queue)->getActor(); _actor->initialize(actorInfo); } @@ -100,14 +100,14 @@ void CommandBufferValidator::begin(RenderPass *renderPass, uint32_t subpass, Fra // secondary command buffers enter the render pass right here _insideRenderPass = !!renderPass; - _commandsFlushed = false; + _commandsFlushed = false; _recorder.clear(); _curStates.descriptorSets.assign(_curStates.descriptorSets.size(), nullptr); /////////// execute /////////// - RenderPass * renderPassActor = renderPass ? static_cast(renderPass)->getActor() : nullptr; + RenderPass *renderPassActor = renderPass ? static_cast(renderPass)->getActor() : nullptr; Framebuffer *framebufferActor = framebuffer ? static_cast(framebuffer)->getActor() : nullptr; _actor->begin(renderPassActor, subpass, framebufferActor); @@ -137,7 +137,7 @@ void CommandBufferValidator::beginRenderPass(RenderPass *renderPass, Framebuffer for (size_t i = 0; i < renderPass->getColorAttachments().size(); ++i) { const auto &desc = renderPass->getColorAttachments()[i]; - const auto *tex = fbo->getColorTextures()[i]; + const auto *tex = fbo->getColorTextures()[i]; CC_ASSERT(tex->getFormat() == desc.format); } if (fbo->getDepthStencilTexture()) { @@ -145,14 +145,14 @@ void CommandBufferValidator::beginRenderPass(RenderPass *renderPass, Framebuffer } _insideRenderPass = true; - _curSubpass = 0U; + _curSubpass = 0U; - _curStates.renderPass = renderPass; - _curStates.framebuffer = fbo; - _curStates.renderArea = renderArea; - _curStates.clearDepth = depth; + _curStates.renderPass = renderPass; + _curStates.framebuffer = fbo; + _curStates.renderArea = renderArea; + _curStates.clearDepth = depth; _curStates.clearStencil = stencil; - size_t clearColorCount = renderPass->getColorAttachments().size(); + size_t clearColorCount = renderPass->getColorAttachments().size(); if (clearColorCount) { _curStates.clearColors.assign(colors, colors + clearColorCount); } @@ -174,7 +174,7 @@ void CommandBufferValidator::beginRenderPass(RenderPass *renderPass, Framebuffer } } - RenderPass * renderPassActor = static_cast(renderPass)->getActor(); + RenderPass *renderPassActor = static_cast(renderPass)->getActor(); Framebuffer *framebufferActor = static_cast(fbo)->getActor(); _actor->beginRenderPass(renderPassActor, framebufferActor, renderArea, colors, depth, stencil, actorSecondaryCBs, secondaryCBCount); @@ -301,8 +301,8 @@ void CommandBufferValidator::setDepthBias(float constant, float clamp, float slo CC_ASSERT(isInited()); _curStates.depthBiasConstant = constant; - _curStates.depthBiasClamp = clamp; - _curStates.depthBiasSlope = slope; + _curStates.depthBiasClamp = clamp; + _curStates.depthBiasSlope = slope; /////////// execute /////////// @@ -349,11 +349,11 @@ void CommandBufferValidator::setStencilCompareMask(StencilFace face, uint32_t re CC_ASSERT(isInited()); if (hasFlag(face, StencilFace::FRONT)) { - _curStates.stencilStatesFront.reference = ref; + _curStates.stencilStatesFront.reference = ref; _curStates.stencilStatesFront.compareMask = mask; } if (hasFlag(face, StencilFace::BACK)) { - _curStates.stencilStatesBack.reference = ref; + _curStates.stencilStatesBack.reference = ref; _curStates.stencilStatesBack.compareMask = mask; } @@ -375,7 +375,7 @@ void CommandBufferValidator::draw(const DrawInfo &info) { const auto &psoLayouts = _curStates.pipelineState->getPipelineLayout()->getSetLayouts(); for (size_t i = 0; i < psoLayouts.size(); ++i) { if (!_curStates.descriptorSets[i]) continue; // there may be inactive sets - const auto &dsBindings = _curStates.descriptorSets[i]->getLayout()->getBindings(); + const auto &dsBindings = _curStates.descriptorSets[i]->getLayout()->getBindings(); const auto &psoBindings = psoLayouts[i]->getBindings(); CC_ASSERT(psoBindings.size() == dsBindings.size()); } diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index 7ef259901d..01acfd7c5b 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -83,10 +83,10 @@ protected: void doDestroy() override; CommandBufferStorage _curStates; - CommandRecorder _recorder; + CommandRecorder _recorder; - bool _insideRenderPass{false}; - bool _commandsFlushed{false}; + bool _insideRenderPass{false}; + bool _commandsFlushed{false}; uint32_t _curSubpass{0U}; bool _inited{false}; diff --git a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp index 9f78674b5e..ac729eade0 100644 --- a/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DescriptorSetValidator.cpp @@ -76,7 +76,7 @@ void DescriptorSetValidator::update() { Texture *texture = nullptr; Sampler *sampler = nullptr; - Format format = {}; + Format format = {}; for (size_t i = 0; i < descriptorCount; ++i) { texture = _textures[i]; @@ -112,8 +112,8 @@ void DescriptorSetValidator::bindBuffer(uint32_t binding, Buffer *buffer, uint32 CC_ASSERT(isInited()); CC_ASSERT(buffer && static_cast(buffer)->isInited()); - const ccstd::vector & bindingIndices = _layout->getBindingIndices(); - const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); + const ccstd::vector &bindingIndices = _layout->getBindingIndices(); + const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); CC_ASSERT(binding < bindingIndices.size() && bindingIndices[binding] < bindings.size()); const DescriptorSetLayoutBinding &info = bindings[bindingIndices[binding]]; @@ -141,8 +141,8 @@ void DescriptorSetValidator::bindTexture(uint32_t binding, Texture *texture, uin CC_ASSERT(isInited()); CC_ASSERT(texture && static_cast(texture)->isInited()); - const ccstd::vector & bindingIndices = _layout->getBindingIndices(); - const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); + const ccstd::vector &bindingIndices = _layout->getBindingIndices(); + const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); CC_ASSERT(binding < bindingIndices.size() && bindingIndices[binding] < bindings.size()); const DescriptorSetLayoutBinding &info = bindings[bindingIndices[binding]]; @@ -166,8 +166,8 @@ void DescriptorSetValidator::bindTexture(uint32_t binding, Texture *texture, uin void DescriptorSetValidator::bindSampler(uint32_t binding, Sampler *sampler, uint32_t index) { CC_ASSERT(isInited()); - const ccstd::vector & bindingIndices = _layout->getBindingIndices(); - const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); + const ccstd::vector &bindingIndices = _layout->getBindingIndices(); + const DescriptorSetLayoutBindingList &bindings = _layout->getBindings(); CC_ASSERT(binding < bindingIndices.size() && bindingIndices[binding] < bindings.size()); const DescriptorSetLayoutBinding &info = bindings[bindingIndices[binding]]; diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 2eaf736025..0688da5327 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -49,7 +49,7 @@ namespace cc { namespace gfx { DeviceValidator *DeviceValidator::instance = nullptr; -bool DeviceValidator::allowStacktraceJS{true}; +bool DeviceValidator::allowStacktraceJS{true}; DeviceValidator *DeviceValidator::getInstance() { return DeviceValidator::instance; @@ -78,19 +78,19 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { return false; } - _api = _actor->getGfxAPI(); + _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); - _queue = ccnew QueueValidator(_actor->getQueue()); - _queryPool = ccnew QueryPoolValidator(_actor->getQueryPool()); - _cmdBuff = ccnew CommandBufferValidator(_actor->getCommandBuffer()); - _renderer = _actor->getRenderer(); - _vendor = _actor->getVendor(); - _caps = _actor->_caps; + _queue = ccnew QueueValidator(_actor->getQueue()); + _queryPool = ccnew QueryPoolValidator(_actor->getQueryPool()); + _cmdBuff = ccnew CommandBufferValidator(_actor->getCommandBuffer()); + _renderer = _actor->getRenderer(); + _vendor = _actor->getVendor(); + _caps = _actor->_caps; memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); memcpy(_formatFeatures.data(), _actor->_formatFeatures.data(), static_cast(Format::COUNT) * sizeof(FormatFeatureBit)); - static_cast(_queue)->_inited = true; - static_cast(_queryPool)->_inited = true; + static_cast(_queue)->_inited = true; + static_cast(_queryPool)->_inited = true; static_cast(_cmdBuff)->_queue = _queue; static_cast(_cmdBuff)->initValidator(); @@ -145,7 +145,7 @@ void DeviceValidator::acquire(Swapchain *const *swapchains, uint32_t count) { swapchainActors.resize(count); for (uint32_t i = 0U; i < count; ++i) { - auto *swapchain = static_cast(swapchains[i]); + auto *swapchain = static_cast(swapchains[i]); swapchainActors[i] = swapchain->getActor(); } @@ -160,98 +160,98 @@ void DeviceValidator::present() { } CommandBuffer *DeviceValidator::createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) { - CommandBuffer *actor = _actor->createCommandBuffer(info, hasAgent); + CommandBuffer *actor = _actor->createCommandBuffer(info, hasAgent); CommandBuffer *result = ccnew CommandBufferValidator(actor); DeviceResourceTracker::push(result); return result; } Queue *DeviceValidator::createQueue() { - Queue *actor = _actor->createQueue(); + Queue *actor = _actor->createQueue(); Queue *result = ccnew QueueValidator(actor); DeviceResourceTracker::push(result); return result; } QueryPool *DeviceValidator::createQueryPool() { - QueryPool *actor = _actor->createQueryPool(); + QueryPool *actor = _actor->createQueryPool(); QueryPool *result = ccnew QueryPoolValidator(actor); DeviceResourceTracker::push(result); return result; } Swapchain *DeviceValidator::createSwapchain() { - Swapchain *actor = _actor->createSwapchain(); + Swapchain *actor = _actor->createSwapchain(); Swapchain *result = ccnew SwapchainValidator(actor); DeviceResourceTracker::push(result); return result; } Buffer *DeviceValidator::createBuffer() { - Buffer *actor = _actor->createBuffer(); + Buffer *actor = _actor->createBuffer(); Buffer *result = ccnew BufferValidator(actor); DeviceResourceTracker::push(result); return result; } Texture *DeviceValidator::createTexture() { - Texture *actor = _actor->createTexture(); + Texture *actor = _actor->createTexture(); Texture *result = ccnew TextureValidator(actor); DeviceResourceTracker::push(result); return result; } Shader *DeviceValidator::createShader() { - Shader *actor = _actor->createShader(); + Shader *actor = _actor->createShader(); Shader *result = ccnew ShaderValidator(actor); DeviceResourceTracker::push(result); return result; } InputAssembler *DeviceValidator::createInputAssembler() { - InputAssembler *actor = _actor->createInputAssembler(); + InputAssembler *actor = _actor->createInputAssembler(); InputAssembler *result = ccnew InputAssemblerValidator(actor); DeviceResourceTracker::push(result); return result; } RenderPass *DeviceValidator::createRenderPass() { - RenderPass *actor = _actor->createRenderPass(); + RenderPass *actor = _actor->createRenderPass(); RenderPass *result = ccnew RenderPassValidator(actor); DeviceResourceTracker::push(result); return result; } Framebuffer *DeviceValidator::createFramebuffer() { - Framebuffer *actor = _actor->createFramebuffer(); + Framebuffer *actor = _actor->createFramebuffer(); Framebuffer *result = ccnew FramebufferValidator(actor); DeviceResourceTracker::push(result); return result; } DescriptorSet *DeviceValidator::createDescriptorSet() { - DescriptorSet *actor = _actor->createDescriptorSet(); + DescriptorSet *actor = _actor->createDescriptorSet(); DescriptorSet *result = ccnew DescriptorSetValidator(actor); DeviceResourceTracker::push(result); return result; } DescriptorSetLayout *DeviceValidator::createDescriptorSetLayout() { - DescriptorSetLayout *actor = _actor->createDescriptorSetLayout(); + DescriptorSetLayout *actor = _actor->createDescriptorSetLayout(); DescriptorSetLayout *result = ccnew DescriptorSetLayoutValidator(actor); DeviceResourceTracker::push(result); return result; } PipelineLayout *DeviceValidator::createPipelineLayout() { - PipelineLayout *actor = _actor->createPipelineLayout(); + PipelineLayout *actor = _actor->createPipelineLayout(); PipelineLayout *result = ccnew PipelineLayoutValidator(actor); DeviceResourceTracker::push(result); return result; } PipelineState *DeviceValidator::createPipelineState() { - PipelineState *actor = _actor->createPipelineState(); + PipelineState *actor = _actor->createPipelineState(); PipelineState *result = ccnew PipelineStateValidator(actor); DeviceResourceTracker::push(result); return result; @@ -323,9 +323,9 @@ void DeviceValidator::flushCommands(CommandBuffer *const *cmdBuffs, uint32_t cou cmdBuffActors.resize(count); for (uint32_t i = 0U; i < count; ++i) { - auto *cmdBuff = static_cast(cmdBuffs[i]); + auto *cmdBuff = static_cast(cmdBuffs[i]); cmdBuff->_commandsFlushed = true; - cmdBuffActors[i] = cmdBuff->getActor(); + cmdBuffActors[i] = cmdBuff->getActor(); } _actor->flushCommands(cmdBuffActors.data(), count); @@ -336,8 +336,8 @@ void DeviceValidator::getQueryPoolResults(QueryPool *queryPool) { _actor->getQueryPoolResults(actorQueryPool); - auto * actorQueryPoolValidator = static_cast(actorQueryPool); - auto * queryPoolValidator = static_cast(queryPool); + auto *actorQueryPoolValidator = static_cast(actorQueryPool); + auto *queryPoolValidator = static_cast(queryPool); std::lock_guard lock(actorQueryPoolValidator->_mutex); queryPoolValidator->_results = actorQueryPoolValidator->_results; } diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index 10af0c8fa6..d8b3fdcffe 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -59,37 +59,37 @@ public: void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; - Sampler * getSampler(const SamplerInfo &info) override; - GeneralBarrier * getGeneralBarrier(const GeneralBarrierInfo &info) override; + Sampler *getSampler(const SamplerInfo &info) override; + GeneralBarrier *getGeneralBarrier(const GeneralBarrierInfo &info) override; TextureBarrier *getTextureBarrier(const TextureBarrierInfo &info) override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void getQueryPoolResults(QueryPool *queryPool) override; - void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; + void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } - uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } - uint32_t getNumInstances() const override { return _actor->getNumInstances(); } - uint32_t getNumTris() const override { return _actor->getNumTris(); } + uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } + uint32_t getNumInstances() const override { return _actor->getNumInstances(); } + uint32_t getNumTris() const override { return _actor->getNumTris(); } - inline void enableRecording(bool recording) { _recording = recording; } - inline bool isRecording() const { return _recording; } + inline void enableRecording(bool recording) { _recording = recording; } + inline bool isRecording() const { return _recording; } inline uint64_t currentFrame() const { return _currentFrame; } protected: @@ -104,7 +104,7 @@ protected: void bindContext(bool bound) override { _actor->bindContext(bound); } - bool _recording{false}; + bool _recording{false}; uint64_t _currentFrame{1U}; }; diff --git a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp index 5eb1f7a9e3..9ca0815658 100644 --- a/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/FramebufferValidator.cpp @@ -58,7 +58,7 @@ void FramebufferValidator::doInit(const FramebufferInfo &info) { for (uint32_t i = 0U; i < info.colorTextures.size(); ++i) { const auto &desc = info.renderPass->getColorAttachments()[i]; - const auto *tex = info.colorTextures[i]; + const auto *tex = info.colorTextures[i]; CC_ASSERT(tex && static_cast(tex)->isInited()); CC_ASSERT(hasAnyFlags(tex->getInfo().usage, TextureUsageBit::COLOR_ATTACHMENT | TextureUsageBit::DEPTH_STENCIL_ATTACHMENT)); CC_ASSERT(tex->getFormat() == desc.format); diff --git a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp index 4d558f2047..46c01aedcd 100644 --- a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp +++ b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp @@ -55,8 +55,8 @@ void PipelineStateValidator::doInit(const PipelineStateInfo &info) { /////////// execute /////////// PipelineStateInfo actorInfo = info; - actorInfo.shader = static_cast(info.shader)->getActor(); - actorInfo.pipelineLayout = static_cast(info.pipelineLayout)->getActor(); + actorInfo.shader = static_cast(info.shader)->getActor(); + actorInfo.pipelineLayout = static_cast(info.pipelineLayout)->getActor(); if (info.renderPass) actorInfo.renderPass = static_cast(info.renderPass)->getActor(); _actor->initialize(actorInfo); diff --git a/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp b/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp index 69c437aabb..3e49eb2f87 100644 --- a/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp +++ b/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp @@ -33,8 +33,8 @@ namespace gfx { QueryPoolValidator::QueryPoolValidator(QueryPool *actor) : Agent(actor) { - _typedID = actor->getTypedID(); - _type = actor->getType(); + _typedID = actor->getTypedID(); + _type = actor->getType(); _maxQueryObjects = actor->getMaxQueryObjects(); } diff --git a/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp b/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp index 8bf9b4436a..286d29444b 100644 --- a/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp +++ b/native/cocos/renderer/gfx-validator/SwapchainValidator.cpp @@ -34,7 +34,7 @@ namespace gfx { SwapchainValidator::SwapchainValidator(Swapchain *actor) : Agent(actor) { - _typedID = actor->getTypedID(); + _typedID = actor->getTypedID(); _preRotationEnabled = static_cast(actor)->_preRotationEnabled; } @@ -63,9 +63,9 @@ void SwapchainValidator::doInit(const SwapchainInfo &info) { SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = _actor->getColorTexture()->getFormat(); - textureInfo.width = _actor->getWidth(); - textureInfo.height = _actor->getHeight(); + textureInfo.format = _actor->getColorTexture()->getFormat(); + textureInfo.width = _actor->getWidth(); + textureInfo.height = _actor->getHeight(); initTexture(textureInfo, _colorTexture); textureInfo.format = _actor->getDepthStencilTexture()->getFormat(); @@ -80,7 +80,7 @@ void SwapchainValidator::doDestroy() { /////////// execute /////////// _depthStencilTexture = nullptr; - _colorTexture = nullptr; + _colorTexture = nullptr; _actor->destroy(); } @@ -90,11 +90,11 @@ void SwapchainValidator::doResize(uint32_t width, uint32_t height, SurfaceTransf _actor->resize(width, height, transform); - auto *colorTexture = static_cast(_colorTexture.get()); + auto *colorTexture = static_cast(_colorTexture.get()); auto *depthStencilTexture = static_cast(_depthStencilTexture.get()); colorTexture->_info.width = depthStencilTexture->_info.width = _actor->getWidth(); colorTexture->_info.height = depthStencilTexture->_info.height = _actor->getHeight(); - _transform = _actor->getSurfaceTransform(); + _transform = _actor->getSurfaceTransform(); } void SwapchainValidator::doDestroySurface() { diff --git a/native/cocos/renderer/gfx-validator/TextureValidator.cpp b/native/cocos/renderer/gfx-validator/TextureValidator.cpp index d632e2d487..727cd98e47 100644 --- a/native/cocos/renderer/gfx-validator/TextureValidator.cpp +++ b/native/cocos/renderer/gfx-validator/TextureValidator.cpp @@ -81,14 +81,14 @@ void TextureValidator::doInit(const TextureInfo &info) { void TextureValidator::doInit(const TextureViewInfo &info) { CC_ASSERT(!isInited()); - _inited = true; + _inited = true; _isTextureView = true; CC_ASSERT(info.texture && static_cast(info.texture)->isInited()); /////////// execute /////////// TextureViewInfo actorInfo = info; - actorInfo.texture = static_cast(info.texture)->getActor(); + actorInfo.texture = static_cast(info.texture)->getActor(); _actor->initialize(actorInfo); } diff --git a/native/cocos/renderer/gfx-validator/TextureValidator.h b/native/cocos/renderer/gfx-validator/TextureValidator.h index d1302ef3de..9621ec4348 100644 --- a/native/cocos/renderer/gfx-validator/TextureValidator.h +++ b/native/cocos/renderer/gfx-validator/TextureValidator.h @@ -53,8 +53,8 @@ protected: void doResize(uint32_t width, uint32_t height, uint32_t size) override; uint64_t _lastUpdateFrame{0U}; - bool _ownTheActor{true}; - bool _inited{false}; + bool _ownTheActor{true}; + bool _inited{false}; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp index a06da2d935..5bd98e1040 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp @@ -54,12 +54,12 @@ namespace gfx { void CommandRecorder::recordBeginRenderPass(const RenderPassSnapshot &renderPass) { _renderPassCommands.emplace_back(); RenderPassCommand &command = _renderPassCommands.back(); - command.renderArea = renderPass.renderArea; - command.clearColors = renderPass.clearColors; - command.clearDepth = renderPass.clearDepth; - command.clearStencil = renderPass.clearStencil; + command.renderArea = renderPass.renderArea; + command.clearColors = renderPass.clearColors; + command.clearDepth = renderPass.clearDepth; + command.clearStencil = renderPass.clearStencil; - command.colorAttachments = renderPass.renderPass->getColorAttachments(); + command.colorAttachments = renderPass.renderPass->getColorAttachments(); command.depthStencilAttachment = renderPass.renderPass->getDepthStencilAttachment(); _commands.push_back(CommandType::BEGIN_RENDER_PASS); @@ -67,15 +67,15 @@ void CommandRecorder::recordBeginRenderPass(const RenderPassSnapshot &renderPass void CommandRecorder::recordDrawcall(const DrawcallSnapshot &drawcall) { _drawcallCommands.emplace_back(); - DrawcallCommand &command = _drawcallCommands.back(); - command.inputState = drawcall.pipelineState->getInputState(); - command.rasterizerState = drawcall.pipelineState->getRasterizerState(); + DrawcallCommand &command = _drawcallCommands.back(); + command.inputState = drawcall.pipelineState->getInputState(); + command.rasterizerState = drawcall.pipelineState->getRasterizerState(); command.depthStencilState = drawcall.pipelineState->getDepthStencilState(); - command.blendState = drawcall.pipelineState->getBlendState(); - command.primitive = drawcall.pipelineState->getPrimitive(); - command.dynamicStates = drawcall.pipelineState->getDynamicStates(); - command.bindPoint = drawcall.pipelineState->getBindPoint(); - command.drawInfo = drawcall.inputAssembler->getDrawInfo(); + command.blendState = drawcall.pipelineState->getBlendState(); + command.primitive = drawcall.pipelineState->getPrimitive(); + command.dynamicStates = drawcall.pipelineState->getDynamicStates(); + command.bindPoint = drawcall.pipelineState->getBindPoint(); + command.drawInfo = drawcall.inputAssembler->getDrawInfo(); command.descriptorSets = drawcall.descriptorSets; for (const auto &offsets : drawcall.dynamicOffsets) command.dynamicOffsets.insert(command.dynamicOffsets.end(), offsets.begin(), offsets.end()); diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.h b/native/cocos/renderer/gfx-validator/ValidationUtils.h index a0f0bbd9c4..1fed010b32 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.h +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.h @@ -41,18 +41,18 @@ ccstd::string getStacktraceJS(); namespace gfx { struct RenderPassSnapshot { - RenderPass * renderPass = nullptr; - Framebuffer * framebuffer = nullptr; - Rect renderArea; + RenderPass *renderPass = nullptr; + Framebuffer *framebuffer = nullptr; + Rect renderArea; ccstd::vector clearColors; - float clearDepth = 1.F; - uint32_t clearStencil = 0U; + float clearDepth = 1.F; + uint32_t clearStencil = 0U; }; struct DrawcallSnapshot { - PipelineState * pipelineState; - InputAssembler * inputAssembler; - ccstd::vector descriptorSets; + PipelineState *pipelineState; + InputAssembler *inputAssembler; + ccstd::vector descriptorSets; ccstd::vector> dynamicOffsets; }; @@ -66,8 +66,8 @@ public: void clear(); static ccstd::vector serialize(const CommandRecorder &recorder); - static CommandRecorder deserialize(const ccstd::vector &bytes); - static bool compare(const CommandRecorder &test, const CommandRecorder &baseline); + static CommandRecorder deserialize(const ccstd::vector &bytes); + static bool compare(const CommandRecorder &test, const CommandRecorder &baseline); private: enum class CommandType { @@ -77,36 +77,36 @@ private: }; struct RenderPassCommand { - ColorAttachmentList colorAttachments; + ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; - Rect renderArea; + Rect renderArea; ccstd::vector clearColors; - float clearDepth = 1.F; - uint32_t clearStencil = 0U; + float clearDepth = 1.F; + uint32_t clearStencil = 0U; }; struct DrawcallCommand { - InputState inputState; - RasterizerState rasterizerState; + InputState inputState; + RasterizerState rasterizerState; DepthStencilState depthStencilState; - BlendState blendState; - PrimitiveMode primitive = PrimitiveMode::TRIANGLE_LIST; + BlendState blendState; + PrimitiveMode primitive = PrimitiveMode::TRIANGLE_LIST; DynamicStateFlags dynamicStates = DynamicStateFlagBit::NONE; - PipelineBindPoint bindPoint = PipelineBindPoint::GRAPHICS; + PipelineBindPoint bindPoint = PipelineBindPoint::GRAPHICS; DrawInfo drawInfo; ccstd::vector descriptorSets; - ccstd::vector dynamicOffsets; + ccstd::vector dynamicOffsets; }; - ccstd::vector _commands; + ccstd::vector _commands; ccstd::vector _renderPassCommands; - ccstd::vector _drawcallCommands; + ccstd::vector _drawcallCommands; struct BufferData { - BufferInfo info; + BufferInfo info; ccstd::vector data; }; ccstd::unordered_map _bufferMap; @@ -131,7 +131,7 @@ public: private: struct ResourceRecord { - Resource * resource = nullptr; + Resource *resource = nullptr; ccstd::string initStack; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp index 46d135d414..cb4db023f1 100644 --- a/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKBuffer.cpp @@ -41,12 +41,12 @@ CCVKBuffer::~CCVKBuffer() { } void CCVKBuffer::doInit(const BufferInfo & /*info*/) { - _gpuBuffer = ccnew CCVKGPUBuffer; - _gpuBuffer->usage = _usage; + _gpuBuffer = ccnew CCVKGPUBuffer; + _gpuBuffer->usage = _usage; _gpuBuffer->memUsage = _memUsage; - _gpuBuffer->size = _size; - _gpuBuffer->stride = _stride; - _gpuBuffer->count = _count; + _gpuBuffer->size = _size; + _gpuBuffer->stride = _stride; + _gpuBuffer->count = _count; if (hasFlag(_usage, BufferUsageBit::INDIRECT)) { const size_t drawInfoCount = _size / sizeof(DrawInfo); @@ -63,16 +63,16 @@ void CCVKBuffer::doInit(const BufferInfo & /*info*/) { } void CCVKBuffer::doInit(const BufferViewInfo &info) { - auto *buffer = static_cast(info.buffer); - _gpuBuffer = buffer->gpuBuffer(); + auto *buffer = static_cast(info.buffer); + _gpuBuffer = buffer->gpuBuffer(); _gpuBufferView = ccnew CCVKGPUBufferView; createBufferView(); } void CCVKBuffer::createBufferView() { _gpuBufferView->gpuBuffer = _gpuBuffer; - _gpuBufferView->offset = _offset; - _gpuBufferView->range = _size; + _gpuBufferView->offset = _offset; + _gpuBufferView->range = _size; if (_gpuBufferView->gpuBuffer->vkBuffer) { CCVKDevice::getInstance()->gpuDescriptorHub()->update(_gpuBufferView); } @@ -103,7 +103,7 @@ void CCVKBuffer::doResize(uint32_t size, uint32_t count) { CC_PROFILE_MEMORY_DEC(Buffer, _size); CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuBuffer); - _gpuBuffer->size = size; + _gpuBuffer->size = size; _gpuBuffer->count = count; cmdFuncCCVKCreateBuffer(CCVKDevice::getInstance(), _gpuBuffer); diff --git a/native/cocos/renderer/gfx-vulkan/VKBuffer.h b/native/cocos/renderer/gfx-vulkan/VKBuffer.h index 342f955523..857285945f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKBuffer.h @@ -41,7 +41,7 @@ public: void update(const void *buffer, uint32_t size) override; - inline CCVKGPUBuffer * gpuBuffer() const { return _gpuBuffer; } + inline CCVKGPUBuffer *gpuBuffer() const { return _gpuBuffer; } inline CCVKGPUBufferView *gpuBufferView() const { return _gpuBufferView; } protected: @@ -52,7 +52,7 @@ protected: void createBufferView(); - CCVKGPUBuffer * _gpuBuffer = nullptr; + CCVKGPUBuffer *_gpuBuffer = nullptr; CCVKGPUBufferView *_gpuBufferView = nullptr; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index bad94700b8..ed946134de 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -51,8 +51,8 @@ CCVKCommandBuffer::~CCVKCommandBuffer() { } void CCVKCommandBuffer::doInit(const CommandBufferInfo & /*info*/) { - _gpuCommandBuffer = ccnew CCVKGPUCommandBuffer; - _gpuCommandBuffer->level = mapVkCommandBufferLevel(_type); + _gpuCommandBuffer = ccnew CCVKGPUCommandBuffer; + _gpuCommandBuffer->level = mapVkCommandBufferLevel(_type); _gpuCommandBuffer->queueFamilyIndex = static_cast(_queue)->gpuQueue()->queueFamilyIndex; size_t setCount = CCVKDevice::getInstance()->bindingMappingInfo().setIndices.size(); @@ -86,7 +86,7 @@ void CCVKCommandBuffer::begin(RenderPass *renderPass, uint32_t subpass, Framebuf if (renderPass) { inheritanceInfo.renderPass = static_cast(renderPass)->gpuRenderPass()->vkRenderPass; - inheritanceInfo.subpass = subpass; + inheritanceInfo.subpass = subpass; if (frameBuffer) { CCVKGPUFramebuffer *gpuFBO = static_cast(frameBuffer)->gpuFBO(); if (gpuFBO->isOffscreen) { @@ -108,8 +108,8 @@ void CCVKCommandBuffer::begin(RenderPass *renderPass, uint32_t subpass, Framebuf void CCVKCommandBuffer::end() { if (!_gpuCommandBuffer->began) return; - _curGPUFBO = nullptr; - _curGPUInputAssember = nullptr; + _curGPUFBO = nullptr; + _curGPUInputAssember = nullptr; _curDynamicStates.viewport.width = _curDynamicStates.viewport.height = _curDynamicStates.scissor.width = _curDynamicStates.scissor.height = 0U; VK_CHECK(vkEndCommandBuffer(_gpuCommandBuffer->vkCommandBuffer)); _gpuCommandBuffer->began = false; @@ -131,16 +131,16 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo 0, 1, &vkBarrier, 0, nullptr, 0, nullptr); #endif - _curGPUFBO = static_cast(fbo)->gpuFBO(); + _curGPUFBO = static_cast(fbo)->gpuFBO(); _curGPURenderPass = static_cast(renderPass)->gpuRenderPass(); VkFramebuffer framebuffer{_curGPUFBO->vkFramebuffer}; if (!_curGPUFBO->isOffscreen) { framebuffer = _curGPUFBO->swapchain->vkSwapchainFramebufferListMap[_curGPUFBO][_curGPUFBO->swapchain->curImageIndex]; } - ccstd::vector &clearValues = _curGPURenderPass->clearValues; - bool depthEnabled = _curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN; - size_t attachmentCount = depthEnabled ? clearValues.size() - 1 : clearValues.size(); + ccstd::vector &clearValues = _curGPURenderPass->clearValues; + bool depthEnabled = _curGPURenderPass->depthStencilAttachment.format != Format::UNKNOWN; + size_t attachmentCount = depthEnabled ? clearValues.size() - 1 : clearValues.size(); for (size_t i = 0U; i < attachmentCount; ++i) { clearValues[i].color = {{colors[i].x, colors[i].y, colors[i].z, colors[i].w}}; @@ -157,10 +157,10 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo }; VkRenderPassBeginInfo passBeginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - passBeginInfo.renderPass = _curGPURenderPass->vkRenderPass; - passBeginInfo.framebuffer = framebuffer; - passBeginInfo.clearValueCount = utils::toUint(clearValues.size()); - passBeginInfo.pClearValues = clearValues.data(); + passBeginInfo.renderPass = _curGPURenderPass->vkRenderPass; + passBeginInfo.framebuffer = framebuffer; + passBeginInfo.clearValueCount = utils::toUint(clearValues.size()); + passBeginInfo.pClearValues = clearValues.data(); passBeginInfo.renderArea.offset = {safeArea.x, safeArea.y}; passBeginInfo.renderArea.extent = {safeArea.width, safeArea.height}; @@ -182,8 +182,8 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo void CCVKCommandBuffer::endRenderPass() { vkCmdEndRenderPass(_gpuCommandBuffer->vkCommandBuffer); - CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); - size_t colorAttachmentCount = _curGPURenderPass->colorAttachments.size(); + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + size_t colorAttachmentCount = _curGPURenderPass->colorAttachments.size(); for (size_t i = 0U; i < colorAttachmentCount; ++i) { _curGPUFBO->gpuColorViews[i]->gpuTexture->currentAccessTypes = _curGPURenderPass->getBarrier(i, gpuDevice)->nextAccesses; } @@ -241,7 +241,7 @@ void CCVKCommandBuffer::bindInputAssembler(InputAssembler *ia) { CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); for (uint32_t i = 0U; i < vbCount; ++i) { - gpuInputAssembler->vertexBuffers[i] = gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; + gpuInputAssembler->vertexBuffers[i] = gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; gpuInputAssembler->vertexBufferOffsets[i] = gpuInputAssembler->gpuVertexBuffers[i]->getStartOffset(gpuDevice->curBackBufferIndex); } @@ -287,8 +287,8 @@ void CCVKCommandBuffer::setDepthBias(float constant, float clamp, float slope) { math::IsNotEqualF(_curDynamicStates.depthBiasClamp, clamp) || math::IsNotEqualF(_curDynamicStates.depthBiasSlope, slope)) { _curDynamicStates.depthBiasConstant = constant; - _curDynamicStates.depthBiasClamp = clamp; - _curDynamicStates.depthBiasSlope = slope; + _curDynamicStates.depthBiasClamp = clamp; + _curDynamicStates.depthBiasSlope = slope; vkCmdSetDepthBias(_gpuCommandBuffer->vkCommandBuffer, constant, clamp, slope); } } @@ -317,7 +317,7 @@ void CCVKCommandBuffer::setDepthBound(float minBounds, float maxBounds) { void CCVKCommandBuffer::setStencilWriteMask(StencilFace face, uint32_t mask) { DynamicStencilStates &front = _curDynamicStates.stencilStatesFront; - DynamicStencilStates &back = _curDynamicStates.stencilStatesBack; + DynamicStencilStates &back = _curDynamicStates.stencilStatesBack; if (face == StencilFace::ALL) { if (front.writeMask == mask && back.writeMask == mask) return; front.writeMask = back.writeMask = mask; @@ -335,7 +335,7 @@ void CCVKCommandBuffer::setStencilWriteMask(StencilFace face, uint32_t mask) { void CCVKCommandBuffer::setStencilCompareMask(StencilFace face, uint32_t reference, uint32_t mask) { DynamicStencilStates &front = _curDynamicStates.stencilStatesFront; - DynamicStencilStates &back = _curDynamicStates.stencilStatesBack; + DynamicStencilStates &back = _curDynamicStates.stencilStatesBack; if (face == StencilFace::ALL) { if (front.reference == reference && back.reference == reference && front.compareMask == mask && back.compareMask == mask) return; @@ -371,9 +371,9 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { const auto *gpuIndirectBuffer = _curGPUInputAssember->gpuIndirectBuffer; if (gpuIndirectBuffer) { - uint32_t drawInfoCount = gpuIndirectBuffer->range / gpuIndirectBuffer->gpuBuffer->stride; - CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); - VkDeviceSize offset = gpuIndirectBuffer->getStartOffset(gpuDevice->curBackBufferIndex); + uint32_t drawInfoCount = gpuIndirectBuffer->range / gpuIndirectBuffer->gpuBuffer->stride; + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + VkDeviceSize offset = gpuIndirectBuffer->getStartOffset(gpuDevice->curBackBufferIndex); if (gpuDevice->useMultiDrawIndirect) { if (gpuIndirectBuffer->gpuBuffer->isDrawIndirectByIndex) { vkCmdDrawIndexedIndirect(_gpuCommandBuffer->vkCommandBuffer, @@ -408,8 +408,8 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { } } } else { - uint32_t instanceCount = std::max(info.instanceCount, 1U); - bool hasIndexBuffer = _curGPUInputAssember->gpuIndexBuffer && info.indexCount > 0; + uint32_t instanceCount = std::max(info.instanceCount, 1U); + bool hasIndexBuffer = _curGPUInputAssember->gpuIndexBuffer && info.indexCount > 0; if (hasIndexBuffer) { vkCmdDrawIndexed(_gpuCommandBuffer->vkCommandBuffer, info.indexCount, instanceCount, @@ -470,15 +470,15 @@ void CCVKCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Text } void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { - VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - VkImage srcImage = VK_NULL_HANDLE; - VkImage dstImage = VK_NULL_HANDLE; - VkImageLayout srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - VkImageLayout dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + VkImageAspectFlags srcAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImageAspectFlags dstAspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + VkImage srcImage = VK_NULL_HANDLE; + VkImage dstImage = VK_NULL_HANDLE; + VkImageLayout srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + VkImageLayout dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; CCVKGPUTexture *gpuTextureSrc = static_cast(srcTexture)->gpuTexture(); - srcAspectMask = gpuTextureSrc->aspectMask; + srcAspectMask = gpuTextureSrc->aspectMask; if (gpuTextureSrc->swapchain) { srcImage = gpuTextureSrc->swapchainVkImages[gpuTextureSrc->swapchain->curImageIndex]; } else { @@ -486,16 +486,16 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co } CCVKGPUTexture *gpuTextureDst = static_cast(dstTexture)->gpuTexture(); - dstAspectMask = gpuTextureDst->aspectMask; + dstAspectMask = gpuTextureDst->aspectMask; if (gpuTextureDst->swapchain) { dstImage = gpuTextureDst->swapchainVkImages[gpuTextureDst->swapchain->curImageIndex]; VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = dstImage; + barrier.image = dstImage; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; @@ -508,28 +508,28 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co _blitRegions.resize(count); for (uint32_t i = 0U; i < count; ++i) { - const TextureBlit ®ion = regions[i]; - _blitRegions[i].srcSubresource.aspectMask = srcAspectMask; - _blitRegions[i].srcSubresource.mipLevel = region.srcSubres.mipLevel; + const TextureBlit ®ion = regions[i]; + _blitRegions[i].srcSubresource.aspectMask = srcAspectMask; + _blitRegions[i].srcSubresource.mipLevel = region.srcSubres.mipLevel; _blitRegions[i].srcSubresource.baseArrayLayer = region.srcSubres.baseArrayLayer; - _blitRegions[i].srcSubresource.layerCount = region.srcSubres.layerCount; - _blitRegions[i].srcOffsets[0].x = region.srcOffset.x; - _blitRegions[i].srcOffsets[0].y = region.srcOffset.y; - _blitRegions[i].srcOffsets[0].z = region.srcOffset.z; - _blitRegions[i].srcOffsets[1].x = static_cast(region.srcOffset.x + region.srcExtent.width); - _blitRegions[i].srcOffsets[1].y = static_cast(region.srcOffset.y + region.srcExtent.height); - _blitRegions[i].srcOffsets[1].z = static_cast(region.srcOffset.z + region.srcExtent.depth); + _blitRegions[i].srcSubresource.layerCount = region.srcSubres.layerCount; + _blitRegions[i].srcOffsets[0].x = region.srcOffset.x; + _blitRegions[i].srcOffsets[0].y = region.srcOffset.y; + _blitRegions[i].srcOffsets[0].z = region.srcOffset.z; + _blitRegions[i].srcOffsets[1].x = static_cast(region.srcOffset.x + region.srcExtent.width); + _blitRegions[i].srcOffsets[1].y = static_cast(region.srcOffset.y + region.srcExtent.height); + _blitRegions[i].srcOffsets[1].z = static_cast(region.srcOffset.z + region.srcExtent.depth); - _blitRegions[i].dstSubresource.aspectMask = dstAspectMask; - _blitRegions[i].dstSubresource.mipLevel = region.dstSubres.mipLevel; + _blitRegions[i].dstSubresource.aspectMask = dstAspectMask; + _blitRegions[i].dstSubresource.mipLevel = region.dstSubres.mipLevel; _blitRegions[i].dstSubresource.baseArrayLayer = region.dstSubres.baseArrayLayer; - _blitRegions[i].dstSubresource.layerCount = region.dstSubres.layerCount; - _blitRegions[i].dstOffsets[0].x = region.dstOffset.x; - _blitRegions[i].dstOffsets[0].y = region.dstOffset.y; - _blitRegions[i].dstOffsets[0].z = region.dstOffset.z; - _blitRegions[i].dstOffsets[1].x = static_cast(region.dstOffset.x + region.dstExtent.width); - _blitRegions[i].dstOffsets[1].y = static_cast(region.dstOffset.y + region.dstExtent.height); - _blitRegions[i].dstOffsets[1].z = static_cast(region.dstOffset.z + region.dstExtent.depth); + _blitRegions[i].dstSubresource.layerCount = region.dstSubres.layerCount; + _blitRegions[i].dstOffsets[0].x = region.dstOffset.x; + _blitRegions[i].dstOffsets[0].y = region.dstOffset.y; + _blitRegions[i].dstOffsets[0].z = region.dstOffset.z; + _blitRegions[i].dstOffsets[1].x = static_cast(region.dstOffset.x + region.dstExtent.width); + _blitRegions[i].dstOffsets[1].y = static_cast(region.dstOffset.y + region.dstExtent.height); + _blitRegions[i].dstOffsets[1].z = static_cast(region.dstOffset.z + region.dstExtent.depth); } vkCmdBlitImage(_gpuCommandBuffer->vkCommandBuffer, @@ -539,13 +539,13 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co if (gpuTextureDst->swapchain) { VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = dstImage; + barrier.image = dstImage; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.levelCount = barrier.subresourceRange.layerCount = 1; @@ -556,18 +556,18 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co } void CCVKCommandBuffer::bindDescriptorSets(VkPipelineBindPoint bindPoint) { - CCVKDevice * device = CCVKDevice::getInstance(); - CCVKGPUDevice * gpuDevice = device->gpuDevice(); - CCVKGPUPipelineLayout * pipelineLayout = _curGPUPipelineState->gpuPipelineLayout; + CCVKDevice *device = CCVKDevice::getInstance(); + CCVKGPUDevice *gpuDevice = device->gpuDevice(); + CCVKGPUPipelineLayout *pipelineLayout = _curGPUPipelineState->gpuPipelineLayout; ccstd::vector &dynamicOffsetOffsets = pipelineLayout->dynamicOffsetOffsets; - uint32_t descriptorSetCount = utils::toUint(pipelineLayout->setLayouts.size()); + uint32_t descriptorSetCount = utils::toUint(pipelineLayout->setLayouts.size()); _curDynamicOffsets.resize(pipelineLayout->dynamicOffsetCount); uint32_t dirtyDescriptorSetCount = descriptorSetCount - _firstDirtyDescriptorSet; for (uint32_t i = _firstDirtyDescriptorSet; i < descriptorSetCount; ++i) { if (_curGPUDescriptorSets[i]) { const CCVKGPUDescriptorSet::Instance &instance = _curGPUDescriptorSets[i]->instances[gpuDevice->curBackBufferIndex]; - _curVkDescriptorSets[i] = instance.vkDescriptorSet; + _curVkDescriptorSets[i] = instance.vkDescriptorSet; } else { _curVkDescriptorSets[i] = pipelineLayout->setLayouts[i]->defaultDescriptorSet; } @@ -578,8 +578,8 @@ void CCVKCommandBuffer::bindDescriptorSets(VkPipelineBindPoint bindPoint) { } uint32_t dynamicOffsetStartIndex = dynamicOffsetOffsets[_firstDirtyDescriptorSet]; - uint32_t dynamicOffsetEndIndex = dynamicOffsetOffsets[_firstDirtyDescriptorSet + dirtyDescriptorSetCount]; - uint32_t dynamicOffsetCount = dynamicOffsetEndIndex - dynamicOffsetStartIndex; + uint32_t dynamicOffsetEndIndex = dynamicOffsetOffsets[_firstDirtyDescriptorSet + dirtyDescriptorSetCount]; + uint32_t dynamicOffsetCount = dynamicOffsetEndIndex - dynamicOffsetStartIndex; vkCmdBindDescriptorSets(_gpuCommandBuffer->vkCommandBuffer, bindPoint, pipelineLayout->vkPipelineLayout, _firstDirtyDescriptorSet, dirtyDescriptorSetCount, @@ -595,8 +595,8 @@ void CCVKCommandBuffer::dispatch(const DispatchInfo &info) { } if (info.indirectBuffer) { - CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); - auto * indirectBuffer = static_cast(info.indirectBuffer); + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto *indirectBuffer = static_cast(info.indirectBuffer); vkCmdDispatchIndirect(_gpuCommandBuffer->vkCommandBuffer, indirectBuffer->gpuBuffer()->vkBuffer, indirectBuffer->gpuBufferView()->getStartOffset(gpuDevice->curBackBufferIndex) + info.indirectOffset); } else { @@ -605,17 +605,17 @@ void CCVKCommandBuffer::dispatch(const DispatchInfo &info) { } void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - VkMemoryBarrier const * pMemoryBarrier = nullptr; - uint32_t memoryBarrierCount = 0U; + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkMemoryBarrier const *pMemoryBarrier = nullptr; + uint32_t memoryBarrierCount = 0U; VkImageMemoryBarrier const *pImageMemoryBarriers = nullptr; if (barrier) { const auto *gpuBarrier = static_cast(barrier)->gpuBarrier(); srcStageMask |= gpuBarrier->srcStageMask; dstStageMask |= gpuBarrier->dstStageMask; - pMemoryBarrier = &gpuBarrier->vkBarrier; + pMemoryBarrier = &gpuBarrier->vkBarrier; memoryBarrierCount = 1U; } @@ -625,9 +625,9 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Tex for (uint32_t i = 0U; i < textureBarrierCount; ++i) { const auto *gpuBarrier = static_cast(textureBarriers[i])->gpuBarrier(); - auto * gpuTexture = static_cast(textures[i])->gpuTexture(); + auto *gpuTexture = static_cast(textures[i])->gpuTexture(); - _imageMemoryBarriers[i] = gpuBarrier->vkBarrier; + _imageMemoryBarriers[i] = gpuBarrier->vkBarrier; _imageMemoryBarriers[i].subresourceRange.aspectMask = gpuTexture->aspectMask; if (gpuTexture->swapchain) { _imageMemoryBarriers[i].image = gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex]; @@ -647,9 +647,9 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Tex } void CCVKCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t /*id*/) { - auto * vkQueryPool = static_cast(queryPool); + auto *vkQueryPool = static_cast(queryPool); CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); - auto queryId = static_cast(vkQueryPool->_ids.size()); + auto queryId = static_cast(vkQueryPool->_ids.size()); if (queryId < queryPool->getMaxQueryObjects()) { vkCmdBeginQuery(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->vkPool, queryId, 0); @@ -657,9 +657,9 @@ void CCVKCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t /*id*/) { } void CCVKCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { - auto * vkQueryPool = static_cast(queryPool); + auto *vkQueryPool = static_cast(queryPool); CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); - auto queryId = static_cast(vkQueryPool->_ids.size()); + auto queryId = static_cast(vkQueryPool->_ids.size()); if (queryId < queryPool->getMaxQueryObjects()) { vkCmdEndQuery(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->vkPool, queryId); @@ -668,7 +668,7 @@ void CCVKCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { } void CCVKCommandBuffer::resetQueryPool(QueryPool *queryPool) { - auto * vkQueryPool = static_cast(queryPool); + auto *vkQueryPool = static_cast(queryPool); CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); vkCmdResetQueryPool(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->vkPool, 0, queryPool->getMaxQueryObjects()); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 6d960e1355..ced59a35db 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -77,25 +77,25 @@ protected: CCVKGPUCommandBuffer *_gpuCommandBuffer = nullptr; - CCVKGPUPipelineState * _curGPUPipelineState = nullptr; - ccstd::vector _curGPUDescriptorSets; - ccstd::vector _curVkDescriptorSets; - ccstd::vector _curDynamicOffsets; + CCVKGPUPipelineState *_curGPUPipelineState = nullptr; + ccstd::vector _curGPUDescriptorSets; + ccstd::vector _curVkDescriptorSets; + ccstd::vector _curDynamicOffsets; ccstd::vector> _curDynamicOffsetsArray; - uint32_t _firstDirtyDescriptorSet = UINT_MAX; + uint32_t _firstDirtyDescriptorSet = UINT_MAX; CCVKGPUInputAssembler *_curGPUInputAssember = nullptr; - CCVKGPUFramebuffer * _curGPUFBO = nullptr; - CCVKGPURenderPass * _curGPURenderPass = nullptr; + CCVKGPUFramebuffer *_curGPUFBO = nullptr; + CCVKGPURenderPass *_curGPURenderPass = nullptr; bool _secondaryRP = false; DynamicStates _curDynamicStates; // temp storage - ccstd::vector _blitRegions; + ccstd::vector _blitRegions; ccstd::vector _imageMemoryBarriers; - ccstd::vector _vkCommandBuffers; + ccstd::vector _vkCommandBuffers; ccstd::queue _pendingQueue; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 52d51f0660..262f6b75c9 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -105,9 +105,9 @@ void cmdFuncCCVKGetDeviceQueue(CCVKDevice *device, CCVKGPUQueue *gpuQueue) { void cmdFuncCCVKCreateQueryPool(CCVKDevice *device, CCVKGPUQueryPool *gpuQueryPool) { VkQueryPoolCreateInfo queryPoolInfo = {}; - queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; - queryPoolInfo.queryType = mapVkQueryType(gpuQueryPool->type); - queryPoolInfo.queryCount = gpuQueryPool->maxQueryObjects; + queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; + queryPoolInfo.queryType = mapVkQueryType(gpuQueryPool->type); + queryPoolInfo.queryCount = gpuQueryPool->maxQueryObjects; VK_CHECK(vkCreateQueryPool(device->gpuDevice()->vkDevice, &queryPoolInfo, nullptr, &gpuQueryPool->vkPool)); } @@ -121,9 +121,9 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (hasFlag(gpuTexture->usage, TextureUsageBit::SAMPLED)) gpuTexture->aspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT; auto createFn = [device, gpuTexture](VkImage *pVkImage, VmaAllocation *pVmaAllocation) { - VkFormat vkFormat = mapVkFormat(gpuTexture->format, device->gpuDevice()); + VkFormat vkFormat = mapVkFormat(gpuTexture->format, device->gpuDevice()); VkFormatFeatureFlags features = mapVkFormatFeatureFlags(gpuTexture->usage); - VkFormatProperties formatProperties; + VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(device->gpuContext()->physicalDevice, vkFormat, &formatProperties); if (!(formatProperties.optimalTilingFeatures & features)) { const char *formatName = GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].name.c_str(); @@ -137,15 +137,15 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { } VkImageCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); - createInfo.imageType = mapVkImageType(gpuTexture->type); - createInfo.format = vkFormat; - createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; - createInfo.mipLevels = gpuTexture->mipLevels; - createInfo.arrayLayers = gpuTexture->arrayLayers; - createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, vkFormat, gpuTexture->samples); - createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - createInfo.usage = usageFlags; + createInfo.flags = mapVkImageCreateFlags(gpuTexture->type); + createInfo.imageType = mapVkImageType(gpuTexture->type); + createInfo.format = vkFormat; + createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; + createInfo.mipLevels = gpuTexture->mipLevels; + createInfo.arrayLayers = gpuTexture->arrayLayers; + createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, vkFormat, gpuTexture->samples); + createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + createInfo.usage = usageFlags; createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocInfo{}; @@ -155,8 +155,8 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (ENABLE_LAZY_ALLOCATION && hasAllFlags(TEXTURE_USAGE_TRANSIENT, gpuTexture->usage)) { createInfo.usage = usageFlags | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; - VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, + allocInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; + VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, pVkImage, pVmaAllocation, &res); if (!result) { gpuTexture->memoryless = true; @@ -165,7 +165,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { // feature not present, fallback createInfo.usage = usageFlags; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; } gpuTexture->memoryless = false; @@ -197,14 +197,14 @@ void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTex auto createFn = [device, gpuTextureView](VkImage vkImage, VkImageView *pVkImageView) { VkImageViewCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - createInfo.image = vkImage; - createInfo.viewType = mapVkImageViewType(gpuTextureView->type); - createInfo.format = mapVkFormat(gpuTextureView->format, device->gpuDevice()); - createInfo.subresourceRange.aspectMask = gpuTextureView->gpuTexture->aspectMask; - createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; - createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; + createInfo.image = vkImage; + createInfo.viewType = mapVkImageViewType(gpuTextureView->type); + createInfo.format = mapVkFormat(gpuTextureView->format, device->gpuDevice()); + createInfo.subresourceRange.aspectMask = gpuTextureView->gpuTexture->aspectMask; + createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; + createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; - createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; + createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; VK_CHECK(vkCreateImageView(device->gpuDevice()->vkDevice, &createInfo, nullptr, pVkImageView)); }; @@ -226,20 +226,20 @@ void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTex void cmdFuncCCVKCreateSampler(CCVKDevice *device, CCVKGPUSampler *gpuSampler) { VkSamplerCreateInfo createInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - CCVKGPUContext * context = device->gpuContext(); - float maxAnisotropy = context->physicalDeviceProperties.limits.maxSamplerAnisotropy; + CCVKGPUContext *context = device->gpuContext(); + float maxAnisotropy = context->physicalDeviceProperties.limits.maxSamplerAnisotropy; - createInfo.magFilter = VK_FILTERS[toNumber(gpuSampler->magFilter)]; - createInfo.minFilter = VK_FILTERS[toNumber(gpuSampler->minFilter)]; - createInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODES[toNumber(gpuSampler->mipFilter)]; - createInfo.addressModeU = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressU)]; - createInfo.addressModeV = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressV)]; - createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressW)]; - createInfo.mipLodBias = 0.F; + createInfo.magFilter = VK_FILTERS[toNumber(gpuSampler->magFilter)]; + createInfo.minFilter = VK_FILTERS[toNumber(gpuSampler->minFilter)]; + createInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODES[toNumber(gpuSampler->mipFilter)]; + createInfo.addressModeU = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressU)]; + createInfo.addressModeV = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressV)]; + createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODES[toNumber(gpuSampler->addressW)]; + createInfo.mipLodBias = 0.F; createInfo.anisotropyEnable = gpuSampler->maxAnisotropy && context->physicalDeviceFeatures.samplerAnisotropy; - createInfo.maxAnisotropy = std::min(maxAnisotropy, static_cast(gpuSampler->maxAnisotropy)); - createInfo.compareEnable = gpuSampler->cmpFunc != ComparisonFunc::ALWAYS; - createInfo.compareOp = VK_CMP_FUNCS[toNumber(gpuSampler->cmpFunc)]; + createInfo.maxAnisotropy = std::min(maxAnisotropy, static_cast(gpuSampler->maxAnisotropy)); + createInfo.compareEnable = gpuSampler->cmpFunc != ComparisonFunc::ALWAYS; + createInfo.compareOp = VK_CMP_FUNCS[toNumber(gpuSampler->cmpFunc)]; // From UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping: // Should use image views with baseMipLevel & levelCount in favor of this createInfo.minLod = 0.0; @@ -256,7 +256,7 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { gpuBuffer->instanceSize = 0U; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bufferInfo.size = gpuBuffer->size; + bufferInfo.size = gpuBuffer->size; bufferInfo.usage = mapVkBufferUsageFlagBits(gpuBuffer->usage); VmaAllocationCreateInfo allocInfo{}; @@ -270,9 +270,9 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; } else if (gpuBuffer->memUsage == (MemoryUsage::HOST | MemoryUsage::DEVICE)) { gpuBuffer->instanceSize = roundUp(gpuBuffer->size, device->getCapabilities().uboOffsetAlignment); - bufferInfo.size = gpuBuffer->instanceSize * device->gpuDevice()->backBufferCount; - allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; - allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + bufferInfo.size = gpuBuffer->instanceSize * device->gpuDevice()->backBufferCount; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } @@ -280,7 +280,7 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { VK_CHECK(vmaCreateBuffer(device->gpuDevice()->memoryAllocator, &bufferInfo, &allocInfo, &gpuBuffer->vkBuffer, &gpuBuffer->vmaAllocation, &res)); - gpuBuffer->mappedData = reinterpret_cast(res.pMappedData); + gpuBuffer->mappedData = reinterpret_cast(res.pMappedData); gpuBuffer->startOffset = 0; // we are creating one VkBuffer each for now // add special access types directly from usage @@ -291,25 +291,25 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { struct AttachmentStatistics final { enum class SubpassUsage { - COLOR = 0x1, + COLOR = 0x1, COLOR_RESOLVE = 0x2, - DEPTH = 0x4, + DEPTH = 0x4, DEPTH_RESOLVE = 0x8, - INPUT = 0x10, + INPUT = 0x10, }; struct SubpassRef final { VkImageLayout layout{VK_IMAGE_LAYOUT_UNDEFINED}; - SubpassUsage usage{SubpassUsage::COLOR}; + SubpassUsage usage{SubpassUsage::COLOR}; bool hasDepth() const { return usage == SubpassUsage::DEPTH || usage == SubpassUsage::DEPTH_RESOLVE; } }; - uint32_t loadSubpass{VK_SUBPASS_EXTERNAL}; - uint32_t storeSubpass{VK_SUBPASS_EXTERNAL}; + uint32_t loadSubpass{VK_SUBPASS_EXTERNAL}; + uint32_t storeSubpass{VK_SUBPASS_EXTERNAL}; ccstd::map records; // ordered void clear() { - loadSubpass = VK_SUBPASS_EXTERNAL; + loadSubpass = VK_SUBPASS_EXTERNAL; storeSubpass = VK_SUBPASS_EXTERNAL; records.clear(); } @@ -349,16 +349,16 @@ private: void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRenderPass) { static ccstd::vector depthStencilResolves; - static ccstd::vector attachmentDescriptions; - static ccstd::vector attachmentReferences; - static ccstd::vector subpassDescriptions; - static ccstd::vector beginAccessInfos; - static ccstd::vector endAccessInfos; - static ccstd::vector attachmentStatistics; - static SubpassDependencyManager dependencyManager; + static ccstd::vector attachmentDescriptions; + static ccstd::vector attachmentReferences; + static ccstd::vector subpassDescriptions; + static ccstd::vector beginAccessInfos; + static ccstd::vector endAccessInfos; + static ccstd::vector attachmentStatistics; + static SubpassDependencyManager dependencyManager; const size_t colorAttachmentCount = gpuRenderPass->colorAttachments.size(); - const size_t hasDepth = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; + const size_t hasDepth = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; attachmentDescriptions.assign(colorAttachmentCount + hasDepth, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); gpuRenderPass->clearValues.resize(colorAttachmentCount + hasDepth); beginAccessInfos.resize(colorAttachmentCount + hasDepth); @@ -366,8 +366,8 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (size_t i = 0U; i < colorAttachmentCount; ++i) { const auto &attachment{gpuRenderPass->colorAttachments[i]}; - auto & beginAccessInfo = beginAccessInfos[i]; - auto & endAccessInfo = endAccessInfos[i]; + auto &beginAccessInfo = beginAccessInfos[i]; + auto &endAccessInfo = endAccessInfos[i]; const auto *gpuBarrier{gpuRenderPass->getBarrier(i, device->gpuDevice())}; thsvsGetAccessInfo(utils::toUint(gpuBarrier->prevAccesses.size()), gpuBarrier->prevAccesses.data(), &beginAccessInfo.stageMask, @@ -375,23 +375,23 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende thsvsGetAccessInfo(utils::toUint(gpuBarrier->nextAccesses.size()), gpuBarrier->nextAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); - VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, vkFormat, attachment.sampleCount); + VkFormat vkFormat = mapVkFormat(attachment.format, device->gpuDevice()); + bool hasStencil = GFX_FORMAT_INFOS[toNumber(attachment.format)].hasStencil; + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, vkFormat, attachment.sampleCount); - attachmentDescriptions[i].format = vkFormat; - attachmentDescriptions[i].samples = samples; - attachmentDescriptions[i].loadOp = mapVkLoadOp(attachment.loadOp); - attachmentDescriptions[i].storeOp = mapVkStoreOp(attachment.storeOp); - attachmentDescriptions[i].stencilLoadOp = hasStencil ? attachmentDescriptions[i].loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[i].format = vkFormat; + attachmentDescriptions[i].samples = samples; + attachmentDescriptions[i].loadOp = mapVkLoadOp(attachment.loadOp); + attachmentDescriptions[i].storeOp = mapVkStoreOp(attachment.storeOp); + attachmentDescriptions[i].stencilLoadOp = hasStencil ? attachmentDescriptions[i].loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[i].stencilStoreOp = hasStencil ? attachmentDescriptions[i].storeOp : VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; - attachmentDescriptions[i].finalLayout = endAccessInfo.imageLayout; + attachmentDescriptions[i].initialLayout = attachment.loadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; + attachmentDescriptions[i].finalLayout = endAccessInfo.imageLayout; } if (hasDepth) { const DepthStencilAttachment &depthStencilAttachment = gpuRenderPass->depthStencilAttachment; - CCVKAccessInfo & beginAccessInfo = beginAccessInfos[colorAttachmentCount]; - CCVKAccessInfo & endAccessInfo = endAccessInfos[colorAttachmentCount]; + CCVKAccessInfo &beginAccessInfo = beginAccessInfos[colorAttachmentCount]; + CCVKAccessInfo &endAccessInfo = endAccessInfos[colorAttachmentCount]; const auto *gpuBarrier{gpuRenderPass->getBarrier(colorAttachmentCount, device->gpuDevice())}; thsvsGetAccessInfo(utils::toUint(gpuBarrier->prevAccesses.size()), gpuBarrier->prevAccesses.data(), &beginAccessInfo.stageMask, @@ -399,18 +399,18 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende thsvsGetAccessInfo(utils::toUint(gpuBarrier->nextAccesses.size()), gpuBarrier->nextAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); - VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; - VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, vkFormat, depthStencilAttachment.sampleCount); + VkFormat vkFormat = mapVkFormat(depthStencilAttachment.format, device->gpuDevice()); + bool hasStencil = GFX_FORMAT_INFOS[toNumber(depthStencilAttachment.format)].hasStencil; + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, vkFormat, depthStencilAttachment.sampleCount); - attachmentDescriptions[colorAttachmentCount].format = vkFormat; - attachmentDescriptions[colorAttachmentCount].samples = samples; - attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); - attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); - attachmentDescriptions[colorAttachmentCount].stencilLoadOp = hasStencil ? mapVkLoadOp(depthStencilAttachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescriptions[colorAttachmentCount].format = vkFormat; + attachmentDescriptions[colorAttachmentCount].samples = samples; + attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); + attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); + attachmentDescriptions[colorAttachmentCount].stencilLoadOp = hasStencil ? mapVkLoadOp(depthStencilAttachment.stencilLoadOp) : VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachmentDescriptions[colorAttachmentCount].stencilStoreOp = hasStencil ? mapVkStoreOp(depthStencilAttachment.stencilStoreOp) : VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; - attachmentDescriptions[colorAttachmentCount].finalLayout = endAccessInfo.imageLayout; + attachmentDescriptions[colorAttachmentCount].initialLayout = depthStencilAttachment.depthLoadOp == gfx::LoadOp::DISCARD ? VK_IMAGE_LAYOUT_UNDEFINED : beginAccessInfo.imageLayout; + attachmentDescriptions[colorAttachmentCount].finalLayout = endAccessInfo.imageLayout; } size_t subpassCount = gpuRenderPass->subpasses.size(); @@ -430,9 +430,9 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } } for (uint32_t color : subpassInfo.colors) { - const ColorAttachment & desc = gpuRenderPass->colorAttachments[color]; + const ColorAttachment &desc = gpuRenderPass->colorAttachments[color]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; - VkImageLayout layout = desc.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + VkImageLayout layout = desc.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, color, layout, VK_IMAGE_ASPECT_COLOR_BIT}); sampleCount = std::max(sampleCount, attachment.samples); } @@ -443,45 +443,45 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (subpassInfo.depthStencil != INVALID_BINDING) { Format dsFormat{Format::UNKNOWN}; - bool isGeneralLayout{false}; + bool isGeneralLayout{false}; if (subpassInfo.depthStencil >= colorAttachmentCount) { - const DepthStencilAttachment & desc = gpuRenderPass->depthStencilAttachment; + const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); - isGeneralLayout = desc.isGeneralLayout; - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; + sampleCount = std::max(sampleCount, attachment.samples); } else { - const ColorAttachment & desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; + const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; - isGeneralLayout = desc.isGeneralLayout; - dsFormat = desc.format; - sampleCount = std::max(sampleCount, attachment.samples); + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; + sampleCount = std::max(sampleCount, attachment.samples); } VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencil, layout, aspect}); } if (subpassInfo.depthStencilResolve != INVALID_BINDING) { Format dsFormat{Format::UNKNOWN}; - bool isGeneralLayout{false}; + bool isGeneralLayout{false}; if (subpassInfo.depthStencilResolve >= colorAttachmentCount) { const DepthStencilAttachment &desc = gpuRenderPass->depthStencilAttachment; - isGeneralLayout = desc.isGeneralLayout; - dsFormat = desc.format; + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; } else { const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencilResolve]; - isGeneralLayout = desc.isGeneralLayout; - dsFormat = desc.format; + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; } VkImageAspectFlags aspect = GFX_FORMAT_INFOS[toNumber(dsFormat)].hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencilResolve, layout, aspect}); } @@ -496,17 +496,17 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende const SubpassInfo subpassInfo = gpuRenderPass->subpasses[i]; VkSubpassDescription2 &desc = subpassDescriptions[i]; - desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; if (!subpassInfo.inputs.empty()) { desc.inputAttachmentCount = utils::toUint(subpassInfo.inputs.size()); - desc.pInputAttachments = attachmentReferences.data() + offset; + desc.pInputAttachments = attachmentReferences.data() + offset; offset += subpassInfo.inputs.size(); } if (!subpassInfo.colors.empty()) { desc.colorAttachmentCount = utils::toUint(subpassInfo.colors.size()); - desc.pColorAttachments = attachmentReferences.data() + offset; + desc.pColorAttachments = attachmentReferences.data() + offset; offset += subpassInfo.colors.size(); if (!subpassInfo.resolves.empty()) { desc.pResolveAttachments = attachmentReferences.data() + offset; @@ -516,7 +516,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (!subpassInfo.preserves.empty()) { desc.preserveAttachmentCount = utils::toUint(subpassInfo.preserves.size()); - desc.pPreserveAttachments = subpassInfo.preserves.data(); + desc.pPreserveAttachments = subpassInfo.preserves.data(); } if (subpassInfo.depthStencil != INVALID_BINDING) { @@ -528,7 +528,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (subpassInfo.depthStencilResolve != INVALID_BINDING) { VkSubpassDescriptionDepthStencilResolve &resolveDesc{depthStencilResolves[i]}; - VkResolveModeFlagBits depthResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.depthResolveMode)]; + VkResolveModeFlagBits depthResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.depthResolveMode)]; VkResolveModeFlagBits stencilResolveMode = VK_RESOLVE_MODES[toNumber(subpassInfo.stencilResolveMode)]; if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; @@ -541,10 +541,10 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende stencilResolveMode = VK_RESOLVE_MODE_NONE; } - resolveDesc.depthResolveMode = depthResolveMode; - resolveDesc.stencilResolveMode = stencilResolveMode; + resolveDesc.depthResolveMode = depthResolveMode; + resolveDesc.stencilResolveMode = stencilResolveMode; resolveDesc.pDepthStencilResolveAttachment = attachmentReferences.data() + offset++; - desc.pNext = &resolveDesc; + desc.pNext = &resolveDesc; } } @@ -554,15 +554,15 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende if (dependencyCount) { offset = 0U; VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; - bool hasWriteAccess{false}; + bool hasWriteAccess{false}; for (uint32_t i = 0U; i < dependencyCount; ++i) { const auto &dependency{gpuRenderPass->dependencies[i]}; const auto *gpuBarrier{static_cast(dependency.barrier)->gpuBarrier()}; VkSubpassDependency2 vkDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2}; - vkDependency.srcSubpass = dependency.srcSubpass; - vkDependency.dstSubpass = dependency.dstSubpass; + vkDependency.srcSubpass = dependency.srcSubpass; + vkDependency.dstSubpass = dependency.dstSubpass; vkDependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; thsvsGetAccessInfo( @@ -634,11 +634,11 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende // wait for resources to become available (begin accesses) auto beginDependencyCheck = [](VkSubpassDependency2 &dependency, uint32_t attachment, const AttachmentStatistics::SubpassRef &ref) { const VkAttachmentDescription2 &desc = attachmentDescriptions[attachment]; - const CCVKAccessInfo & info = beginAccessInfos[attachment]; + const CCVKAccessInfo &info = beginAccessInfos[attachment]; if (desc.initialLayout != ref.layout || info.hasWriteAccess || desc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { VkPipelineStageFlagBits dstStage{ref.hasDepth() ? VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT : VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; - VkAccessFlagBits dstAccessRead{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT : VK_ACCESS_COLOR_ATTACHMENT_READ_BIT}; - VkAccessFlagBits dstAccessWrite{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}; + VkAccessFlagBits dstAccessRead{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT : VK_ACCESS_COLOR_ATTACHMENT_READ_BIT}; + VkAccessFlagBits dstAccessWrite{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}; dependency.srcStageMask |= info.stageMask; dependency.dstStageMask |= dstStage; dependency.srcAccessMask |= info.hasWriteAccess ? info.accessMask : 0; @@ -649,16 +649,16 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende return false; }; VkSubpassDependency2 beginDependency; - uint32_t lastLoadSubpass{VK_SUBPASS_EXTERNAL}; - bool beginDependencyValid{false}; + uint32_t lastLoadSubpass{VK_SUBPASS_EXTERNAL}; + bool beginDependencyValid{false}; for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { auto &statistics = attachmentStatistics[i]; if (lastLoadSubpass != statistics.loadSubpass) { if (beginDependencyValid) dependencyManager.append(beginDependency); - beginDependency = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, + beginDependency = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, VK_SUBPASS_EXTERNAL, statistics.loadSubpass, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; - lastLoadSubpass = statistics.loadSubpass; + lastLoadSubpass = statistics.loadSubpass; beginDependencyValid = false; } beginDependencyValid |= beginDependencyCheck(beginDependency, i, statistics.records[statistics.loadSubpass]); @@ -668,10 +668,10 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende // make rendering result visible (end accesses) auto endDependencyCheck = [](VkSubpassDependency2 &dependency, uint32_t attachment, const AttachmentStatistics::SubpassRef &ref) { const VkAttachmentDescription2 &desc = attachmentDescriptions[attachment]; - const CCVKAccessInfo & info = endAccessInfos[attachment]; + const CCVKAccessInfo &info = endAccessInfos[attachment]; if (desc.initialLayout != ref.layout || info.hasWriteAccess || desc.storeOp == VK_ATTACHMENT_STORE_OP_STORE) { VkPipelineStageFlagBits srcStage{ref.hasDepth() ? VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT : VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; - VkAccessFlagBits srcAccess{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}; + VkAccessFlagBits srcAccess{ref.hasDepth() ? VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}; dependency.srcStageMask |= srcStage; dependency.srcAccessMask |= srcAccess; dependency.dstStageMask |= info.stageMask; @@ -681,16 +681,16 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende return false; }; VkSubpassDependency2 endDependency; - uint32_t lastStoreSubpass{VK_SUBPASS_EXTERNAL}; - bool endDependencyValid{false}; + uint32_t lastStoreSubpass{VK_SUBPASS_EXTERNAL}; + bool endDependencyValid{false}; for (uint32_t i = 0U; i < utils ::toUint(colorAttachmentCount + hasDepth); ++i) { auto &statistics = attachmentStatistics[i]; if (lastStoreSubpass != statistics.storeSubpass) { if (endDependencyValid) dependencyManager.append(endDependency); - endDependency = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, + endDependency = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, statistics.storeSubpass, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; - lastStoreSubpass = statistics.storeSubpass; + lastStoreSubpass = statistics.storeSubpass; endDependencyValid = false; } endDependencyValid |= endDependencyCheck(endDependency, i, statistics.records[statistics.storeSubpass]); @@ -710,14 +710,14 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkSubpassDependency2 dependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, srcIdx, dstIdx}; std::tie(dependency.srcStageMask, dependency.srcAccessMask) = mapAccessFlags(srcUsage); std::tie(dependency.dstStageMask, dependency.dstAccessMask) = mapAccessFlags(dstUsage); - dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; return dependency; }; for (size_t i = 0U; i < colorAttachmentCount + hasDepth; ++i) { auto &statistics{attachmentStatistics[i]}; const AttachmentStatistics::SubpassRef *prevRef{nullptr}; - uint32_t prevIdx{0U}; + uint32_t prevIdx{0U}; for (const auto &it : statistics.records) { if (prevRef && prevRef->usage != it.second.usage) { dependencyManager.append(genDependency(prevIdx, prevRef->usage, it.first, it.second.usage)); @@ -730,21 +730,21 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende VkRenderPassCreateInfo2 renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2}; renderPassCreateInfo.attachmentCount = utils::toUint(attachmentDescriptions.size()); - renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); - renderPassCreateInfo.subpassCount = utils::toUint(subpassDescriptions.size()); - renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); + renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); + renderPassCreateInfo.subpassCount = utils::toUint(subpassDescriptions.size()); + renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); renderPassCreateInfo.dependencyCount = utils::toUint(dependencyManager.subpassDependencies.size()); - renderPassCreateInfo.pDependencies = dependencyManager.subpassDependencies.data(); + renderPassCreateInfo.pDependencies = dependencyManager.subpassDependencies.data(); VK_CHECK(device->gpuDevice()->createRenderPass2(device->gpuDevice()->vkDevice, &renderPassCreateInfo, nullptr, &gpuRenderPass->vkRenderPass)); } void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFramebuffer) { - size_t colorViewCount = gpuFramebuffer->gpuColorViews.size(); - bool hasDepth = gpuFramebuffer->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN; + size_t colorViewCount = gpuFramebuffer->gpuColorViews.size(); + bool hasDepth = gpuFramebuffer->gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN; ccstd::vector attachments(colorViewCount + hasDepth); - VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.width = createInfo.height = UINT_MAX; uint32_t swapchainImageIndices = 0; @@ -756,7 +756,7 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra } else { attachments[i] = gpuFramebuffer->gpuColorViews[i]->vkImageView; } - createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuColorViews[i]->gpuTexture->width >> gpuFramebuffer->gpuColorViews[i]->baseLevel)); + createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuColorViews[i]->gpuTexture->width >> gpuFramebuffer->gpuColorViews[i]->baseLevel)); createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuColorViews[i]->gpuTexture->height >> gpuFramebuffer->gpuColorViews[i]->baseLevel)); } if (hasDepth) { @@ -766,25 +766,25 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra } else { attachments[colorViewCount] = gpuFramebuffer->gpuDepthStencilView->vkImageView; } - createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->width >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); + createInfo.width = std::min(createInfo.width, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->width >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); createInfo.height = std::min(createInfo.height, std::max(1U, gpuFramebuffer->gpuDepthStencilView->gpuTexture->height >> gpuFramebuffer->gpuDepthStencilView->baseLevel)); } gpuFramebuffer->isOffscreen = !swapchainImageIndices; - gpuFramebuffer->width = createInfo.width; - gpuFramebuffer->height = createInfo.height; + gpuFramebuffer->width = createInfo.width; + gpuFramebuffer->height = createInfo.height; if (gpuFramebuffer->isOffscreen) { - createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; + createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; createInfo.attachmentCount = utils::toUint(attachments.size()); - createInfo.pAttachments = attachments.data(); - createInfo.layers = 1; + createInfo.pAttachments = attachments.data(); + createInfo.layers = 1; VK_CHECK(vkCreateFramebuffer(device->gpuDevice()->vkDevice, &createInfo, nullptr, &gpuFramebuffer->vkFramebuffer)); } else { // swapchain-related framebuffers need special treatments: rebuild is needed // whenever a user-specified attachment or swapchain itself is changed - FramebufferListMap &fboListMap = gpuFramebuffer->swapchain->vkSwapchainFramebufferListMap; - auto fboListMapIter = fboListMap.find(gpuFramebuffer); + FramebufferListMap &fboListMap = gpuFramebuffer->swapchain->vkSwapchainFramebufferListMap; + auto fboListMapIter = fboListMap.find(gpuFramebuffer); if (fboListMapIter != fboListMap.end() && !fboListMapIter->second.empty()) { return; } @@ -794,10 +794,10 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra } else { fboListMap.emplace(std::piecewise_construct, std::forward_as_tuple(gpuFramebuffer), std::forward_as_tuple(swapchainImageCount)); } - createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; + createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; createInfo.attachmentCount = utils::toUint(attachments.size()); - createInfo.pAttachments = attachments.data(); - createInfo.layers = 1; + createInfo.pAttachments = attachments.data(); + createInfo.layers = 1; for (size_t i = 0U; i < swapchainImageCount; ++i) { for (size_t j = 0U; j < colorViewCount; ++j) { if (swapchainImageIndices & (1 << j)) { @@ -821,7 +821,7 @@ void cmdFuncCCVKCreateShader(CCVKDevice *device, CCVKGPUShader *gpuShader) { VkShaderModuleCreateInfo createInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; createInfo.codeSize = spirv->getOutputSize(); - createInfo.pCode = spirv->getOutputData(); + createInfo.pCode = spirv->getOutputData(); VK_CHECK(vkCreateShaderModule(device->gpuDevice()->vkDevice, &createInfo, nullptr, &stage.vkShader)); } @@ -829,22 +829,22 @@ void cmdFuncCCVKCreateShader(CCVKDevice *device, CCVKGPUShader *gpuShader) { } void cmdFuncCCVKCreateDescriptorSetLayout(CCVKDevice *device, CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout) { - CCVKGPUDevice *gpuDevice = device->gpuDevice(); - size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); + CCVKGPUDevice *gpuDevice = device->gpuDevice(); + size_t bindingCount = gpuDescriptorSetLayout->bindings.size(); gpuDescriptorSetLayout->vkBindings.resize(bindingCount); for (size_t i = 0U; i < bindingCount; ++i) { - const DescriptorSetLayoutBinding &binding = gpuDescriptorSetLayout->bindings[i]; - VkDescriptorSetLayoutBinding & vkBinding = gpuDescriptorSetLayout->vkBindings[i]; - vkBinding.stageFlags = mapVkShaderStageFlags(binding.stageFlags); - vkBinding.descriptorType = mapVkDescriptorType(binding.descriptorType); - vkBinding.binding = binding.binding; - vkBinding.descriptorCount = binding.count; + const DescriptorSetLayoutBinding &binding = gpuDescriptorSetLayout->bindings[i]; + VkDescriptorSetLayoutBinding &vkBinding = gpuDescriptorSetLayout->vkBindings[i]; + vkBinding.stageFlags = mapVkShaderStageFlags(binding.stageFlags); + vkBinding.descriptorType = mapVkDescriptorType(binding.descriptorType); + vkBinding.binding = binding.binding; + vkBinding.descriptorCount = binding.count; } VkDescriptorSetLayoutCreateInfo setCreateInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; setCreateInfo.bindingCount = utils::toUint(bindingCount); - setCreateInfo.pBindings = gpuDescriptorSetLayout->vkBindings.data(); + setCreateInfo.pBindings = gpuDescriptorSetLayout->vkBindings.data(); VK_CHECK(vkCreateDescriptorSetLayout(gpuDevice->vkDevice, &setCreateInfo, nullptr, &gpuDescriptorSetLayout->vkDescriptorSetLayout)); CCVKGPUDescriptorSetPool *pool = gpuDevice->getDescriptorSetPool(gpuDescriptorSetLayout->id); @@ -859,21 +859,21 @@ void cmdFuncCCVKCreateDescriptorSetLayout(CCVKDevice *device, CCVKGPUDescriptorS for (size_t j = 0U, k = 0U; j < bindingCount; ++j) { const VkDescriptorSetLayoutBinding &binding = bindings[j]; if (binding.descriptorType != VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { - entries[j].dstBinding = binding.binding; + entries[j].dstBinding = binding.binding; entries[j].dstArrayElement = 0; entries[j].descriptorCount = binding.descriptorCount; - entries[j].descriptorType = binding.descriptorType; - entries[j].offset = sizeof(CCVKDescriptorInfo) * k; - entries[j].stride = sizeof(CCVKDescriptorInfo); + entries[j].descriptorType = binding.descriptorType; + entries[j].offset = sizeof(CCVKDescriptorInfo) * k; + entries[j].stride = sizeof(CCVKDescriptorInfo); k += binding.descriptorCount; } } VkDescriptorUpdateTemplateCreateInfo createInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO}; - createInfo.descriptorUpdateEntryCount = utils::toUint(bindingCount); - createInfo.pDescriptorUpdateEntries = entries.data(); - createInfo.templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET; - createInfo.descriptorSetLayout = gpuDescriptorSetLayout->vkDescriptorSetLayout; + createInfo.descriptorUpdateEntryCount = utils::toUint(bindingCount); + createInfo.pDescriptorUpdateEntries = entries.data(); + createInfo.templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET; + createInfo.descriptorSetLayout = gpuDescriptorSetLayout->vkDescriptorSetLayout; if (gpuDevice->minorVersion > 0) { VK_CHECK(vkCreateDescriptorUpdateTemplate(gpuDevice->vkDevice, &createInfo, nullptr, &gpuDescriptorSetLayout->vkDescriptorUpdateTemplate)); } else { @@ -883,8 +883,8 @@ void cmdFuncCCVKCreateDescriptorSetLayout(CCVKDevice *device, CCVKGPUDescriptorS } void cmdFuncCCVKCreatePipelineLayout(CCVKDevice *device, CCVKGPUPipelineLayout *gpuPipelineLayout) { - CCVKGPUDevice *gpuDevice = device->gpuDevice(); - size_t layoutCount = gpuPipelineLayout->setLayouts.size(); + CCVKGPUDevice *gpuDevice = device->gpuDevice(); + size_t layoutCount = gpuPipelineLayout->setLayouts.size(); ccstd::vector descriptorSetLayouts(layoutCount); for (uint32_t i = 0; i < layoutCount; ++i) { @@ -893,7 +893,7 @@ void cmdFuncCCVKCreatePipelineLayout(CCVKDevice *device, CCVKGPUPipelineLayout * VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; pipelineLayoutCreateInfo.setLayoutCount = utils::toUint(layoutCount); - pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts.data(); + pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts.data(); VK_CHECK(vkCreatePipelineLayout(gpuDevice->vkDevice, &pipelineLayoutCreateInfo, nullptr, &gpuPipelineLayout->vkPipelineLayout)); } @@ -902,13 +902,13 @@ void cmdFuncCCVKCreateComputePipelineState(CCVKDevice *device, CCVKGPUPipelineSt ///////////////////// Shader Stage ///////////////////// - const auto & stages = gpuPipelineState->gpuShader->gpuStages; + const auto &stages = gpuPipelineState->gpuShader->gpuStages; VkPipelineShaderStageCreateInfo stageInfo{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - stageInfo.stage = mapVkShaderStageFlagBits(stages[0].type); + stageInfo.stage = mapVkShaderStageFlagBits(stages[0].type); stageInfo.module = stages[0].vkShader; - stageInfo.pName = "main"; + stageInfo.pName = "main"; - createInfo.stage = stageInfo; + createInfo.stage = stageInfo; createInfo.layout = gpuPipelineState->gpuPipelineLayout->vkPipelineLayout; ///////////////////// Creation ///////////////////// @@ -918,43 +918,43 @@ void cmdFuncCCVKCreateComputePipelineState(CCVKDevice *device, CCVKGPUPipelineSt } void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineState *gpuPipelineState) { - static ccstd::vector stageInfos; - static ccstd::vector bindingDescriptions; - static ccstd::vector attributeDescriptions; - static ccstd::vector offsets; - static ccstd::vector dynamicStates; + static ccstd::vector stageInfos; + static ccstd::vector bindingDescriptions; + static ccstd::vector attributeDescriptions; + static ccstd::vector offsets; + static ccstd::vector dynamicStates; static ccstd::vector blendTargets; VkGraphicsPipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; ///////////////////// Shader Stage ///////////////////// - const auto & stages = gpuPipelineState->gpuShader->gpuStages; + const auto &stages = gpuPipelineState->gpuShader->gpuStages; const size_t stageCount = stages.size(); stageInfos.resize(stageCount, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}); for (size_t i = 0U; i < stageCount; ++i) { - stageInfos[i].stage = mapVkShaderStageFlagBits(stages[i].type); + stageInfos[i].stage = mapVkShaderStageFlagBits(stages[i].type); stageInfos[i].module = stages[i].vkShader; - stageInfos[i].pName = "main"; + stageInfos[i].pName = "main"; } createInfo.stageCount = utils::toUint(stageCount); - createInfo.pStages = stageInfos.data(); + createInfo.pStages = stageInfos.data(); ///////////////////// Input State ///////////////////// - const AttributeList &attributes = gpuPipelineState->inputState.attributes; - const size_t attributeCount = attributes.size(); - uint32_t bindingCount = 1U; + const AttributeList &attributes = gpuPipelineState->inputState.attributes; + const size_t attributeCount = attributes.size(); + uint32_t bindingCount = 1U; for (size_t i = 0U; i < attributeCount; ++i) { const Attribute &attr = attributes[i]; - bindingCount = std::max(bindingCount, attr.stream + 1); + bindingCount = std::max(bindingCount, attr.stream + 1); } bindingDescriptions.resize(bindingCount); for (uint32_t i = 0U; i < bindingCount; ++i) { - bindingDescriptions[i].binding = i; - bindingDescriptions[i].stride = 0; + bindingDescriptions[i].binding = i; + bindingDescriptions[i].stride = 0; bindingDescriptions[i].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; } for (size_t i = 0U; i < attributeCount; ++i) { @@ -965,8 +965,8 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS } } - const AttributeList &shaderAttrs = gpuPipelineState->gpuShader->attributes; - const size_t shaderAttrCount = shaderAttrs.size(); + const AttributeList &shaderAttrs = gpuPipelineState->gpuShader->attributes; + const size_t shaderAttrCount = shaderAttrs.size(); attributeDescriptions.resize(shaderAttrCount); for (size_t i = 0; i < shaderAttrCount; ++i) { @@ -975,33 +975,33 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS for (const Attribute &attr : attributes) { if (shaderAttrs[i].name == attr.name) { attributeDescriptions[i].location = shaderAttrs[i].location; - attributeDescriptions[i].binding = attr.stream; - attributeDescriptions[i].format = mapVkFormat(attr.format, device->gpuDevice()); - attributeDescriptions[i].offset = offsets[attr.stream]; - attributeFound = true; + attributeDescriptions[i].binding = attr.stream; + attributeDescriptions[i].format = mapVkFormat(attr.format, device->gpuDevice()); + attributeDescriptions[i].offset = offsets[attr.stream]; + attributeFound = true; break; } offsets[attr.stream] += GFX_FORMAT_INFOS[toNumber(attr.format)].size; } if (!attributeFound) { // handle absent attribute attributeDescriptions[i].location = shaderAttrs[i].location; - attributeDescriptions[i].binding = 0; - attributeDescriptions[i].format = mapVkFormat(shaderAttrs[i].format, device->gpuDevice()); - attributeDescriptions[i].offset = 0; // reuse the first attribute as dummy data + attributeDescriptions[i].binding = 0; + attributeDescriptions[i].format = mapVkFormat(shaderAttrs[i].format, device->gpuDevice()); + attributeDescriptions[i].offset = 0; // reuse the first attribute as dummy data } } VkPipelineVertexInputStateCreateInfo vertexInput{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - vertexInput.vertexBindingDescriptionCount = bindingCount; - vertexInput.pVertexBindingDescriptions = bindingDescriptions.data(); + vertexInput.vertexBindingDescriptionCount = bindingCount; + vertexInput.pVertexBindingDescriptions = bindingDescriptions.data(); vertexInput.vertexAttributeDescriptionCount = utils::toUint(shaderAttrCount); - vertexInput.pVertexAttributeDescriptions = attributeDescriptions.data(); - createInfo.pVertexInputState = &vertexInput; + vertexInput.pVertexAttributeDescriptions = attributeDescriptions.data(); + createInfo.pVertexInputState = &vertexInput; ///////////////////// Input Asembly State ///////////////////// VkPipelineInputAssemblyStateCreateInfo inputAssembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - inputAssembly.topology = VK_PRIMITIVE_MODES[toNumber(gpuPipelineState->primitive)]; + inputAssembly.topology = VK_PRIMITIVE_MODES[toNumber(gpuPipelineState->primitive)]; createInfo.pInputAssemblyState = &inputAssembly; ///////////////////// Dynamic State ///////////////////// @@ -1011,15 +1011,15 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS VkPipelineDynamicStateCreateInfo dynamicState{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; dynamicState.dynamicStateCount = utils::toUint(dynamicStates.size()); - dynamicState.pDynamicStates = dynamicStates.data(); - createInfo.pDynamicState = &dynamicState; + dynamicState.pDynamicStates = dynamicStates.data(); + createInfo.pDynamicState = &dynamicState; ///////////////////// Viewport State ///////////////////// VkPipelineViewportStateCreateInfo viewportState{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; viewportState.viewportCount = 1; // dynamic by default - viewportState.scissorCount = 1; // dynamic by default - createInfo.pViewportState = &viewportState; + viewportState.scissorCount = 1; // dynamic by default + createInfo.pViewportState = &viewportState; ///////////////////// Rasterization State ///////////////////// @@ -1027,20 +1027,20 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS //rasterizationState.depthClampEnable; rasterizationState.rasterizerDiscardEnable = gpuPipelineState->rs.isDiscard; - rasterizationState.polygonMode = VK_POLYGON_MODES[toNumber(gpuPipelineState->rs.polygonMode)]; - rasterizationState.cullMode = VK_CULL_MODES[toNumber(gpuPipelineState->rs.cullMode)]; - rasterizationState.frontFace = gpuPipelineState->rs.isFrontFaceCCW ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; - rasterizationState.depthBiasEnable = gpuPipelineState->rs.depthBiasEnabled; + rasterizationState.polygonMode = VK_POLYGON_MODES[toNumber(gpuPipelineState->rs.polygonMode)]; + rasterizationState.cullMode = VK_CULL_MODES[toNumber(gpuPipelineState->rs.cullMode)]; + rasterizationState.frontFace = gpuPipelineState->rs.isFrontFaceCCW ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; + rasterizationState.depthBiasEnable = gpuPipelineState->rs.depthBiasEnabled; rasterizationState.depthBiasConstantFactor = gpuPipelineState->rs.depthBias; - rasterizationState.depthBiasClamp = gpuPipelineState->rs.depthBiasClamp; - rasterizationState.depthBiasSlopeFactor = gpuPipelineState->rs.depthBiasSlop; - rasterizationState.lineWidth = gpuPipelineState->rs.lineWidth; - createInfo.pRasterizationState = &rasterizationState; + rasterizationState.depthBiasClamp = gpuPipelineState->rs.depthBiasClamp; + rasterizationState.depthBiasSlopeFactor = gpuPipelineState->rs.depthBiasSlop; + rasterizationState.lineWidth = gpuPipelineState->rs.lineWidth; + createInfo.pRasterizationState = &rasterizationState; ///////////////////// Multisample State ///////////////////// VkPipelineMultisampleStateCreateInfo multisampleState{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisampleState.rasterizationSamples = gpuPipelineState->gpuRenderPass->sampleCounts[gpuPipelineState->subpass]; + multisampleState.rasterizationSamples = gpuPipelineState->gpuRenderPass->sampleCounts[gpuPipelineState->subpass]; multisampleState.alphaToCoverageEnable = gpuPipelineState->bs.isA2C; //multisampleState.sampleShadingEnable; //multisampleState.minSampleShading; @@ -1051,10 +1051,10 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ///////////////////// Depth Stencil State ///////////////////// VkPipelineDepthStencilStateCreateInfo depthStencilState = {VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - depthStencilState.depthTestEnable = gpuPipelineState->dss.depthTest; - depthStencilState.depthWriteEnable = gpuPipelineState->dss.depthWrite; - depthStencilState.depthCompareOp = VK_CMP_FUNCS[toNumber(gpuPipelineState->dss.depthFunc)]; - depthStencilState.stencilTestEnable = gpuPipelineState->dss.stencilTestFront; + depthStencilState.depthTestEnable = gpuPipelineState->dss.depthTest; + depthStencilState.depthWriteEnable = gpuPipelineState->dss.depthWrite; + depthStencilState.depthCompareOp = VK_CMP_FUNCS[toNumber(gpuPipelineState->dss.depthFunc)]; + depthStencilState.stencilTestEnable = gpuPipelineState->dss.stencilTestFront; depthStencilState.front = { VK_STENCIL_OPS[toNumber(gpuPipelineState->dss.stencilFailOpFront)], @@ -1089,33 +1089,33 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ? gpuPipelineState->bs.targets[0] : gpuPipelineState->bs.targets[i]; - blendTargets[i].blendEnable = target.blend; + blendTargets[i].blendEnable = target.blend; blendTargets[i].srcColorBlendFactor = VK_BLEND_FACTORS[toNumber(target.blendSrc)]; blendTargets[i].dstColorBlendFactor = VK_BLEND_FACTORS[toNumber(target.blendDst)]; - blendTargets[i].colorBlendOp = VK_BLEND_OPS[toNumber(target.blendEq)]; + blendTargets[i].colorBlendOp = VK_BLEND_OPS[toNumber(target.blendEq)]; blendTargets[i].srcAlphaBlendFactor = VK_BLEND_FACTORS[toNumber(target.blendSrcAlpha)]; blendTargets[i].dstAlphaBlendFactor = VK_BLEND_FACTORS[toNumber(target.blendDstAlpha)]; - blendTargets[i].alphaBlendOp = VK_BLEND_OPS[toNumber(target.blendAlphaEq)]; - blendTargets[i].colorWriteMask = mapVkColorComponentFlags(target.blendColorMask); + blendTargets[i].alphaBlendOp = VK_BLEND_OPS[toNumber(target.blendAlphaEq)]; + blendTargets[i].colorWriteMask = mapVkColorComponentFlags(target.blendColorMask); } Color &blendColor = gpuPipelineState->bs.blendColor; VkPipelineColorBlendStateCreateInfo colorBlendState{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; //colorBlendState.logicOpEnable; //colorBlendState.logicOp; - colorBlendState.attachmentCount = utils::toUint(blendTargetCount); - colorBlendState.pAttachments = blendTargets.data(); + colorBlendState.attachmentCount = utils::toUint(blendTargetCount); + colorBlendState.pAttachments = blendTargets.data(); colorBlendState.blendConstants[0] = blendColor.x; colorBlendState.blendConstants[1] = blendColor.y; colorBlendState.blendConstants[2] = blendColor.z; colorBlendState.blendConstants[3] = blendColor.w; - createInfo.pColorBlendState = &colorBlendState; + createInfo.pColorBlendState = &colorBlendState; ///////////////////// References ///////////////////// - createInfo.layout = gpuPipelineState->gpuPipelineLayout->vkPipelineLayout; + createInfo.layout = gpuPipelineState->gpuPipelineLayout->vkPipelineLayout; createInfo.renderPass = gpuPipelineState->gpuRenderPass->vkRenderPass; - createInfo.subpass = gpuPipelineState->subpass; + createInfo.subpass = gpuPipelineState->subpass; ///////////////////// Creation ///////////////////// @@ -1125,9 +1125,9 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS void cmdFuncCCVKCreateGeneralBarrier(CCVKDevice * /*device*/, CCVKGPUGeneralBarrier *gpuGeneralBarrier) { gpuGeneralBarrier->barrier.prevAccessCount = utils::toUint(gpuGeneralBarrier->prevAccesses.size()); - gpuGeneralBarrier->barrier.pPrevAccesses = gpuGeneralBarrier->prevAccesses.data(); + gpuGeneralBarrier->barrier.pPrevAccesses = gpuGeneralBarrier->prevAccesses.data(); gpuGeneralBarrier->barrier.nextAccessCount = utils::toUint(gpuGeneralBarrier->nextAccesses.size()); - gpuGeneralBarrier->barrier.pNextAccesses = gpuGeneralBarrier->nextAccesses.data(); + gpuGeneralBarrier->barrier.pNextAccesses = gpuGeneralBarrier->nextAccesses.data(); thsvsGetVulkanMemoryBarrier(gpuGeneralBarrier->barrier, &gpuGeneralBarrier->srcStageMask, &gpuGeneralBarrier->dstStageMask, &gpuGeneralBarrier->vkBarrier); } @@ -1136,34 +1136,34 @@ void cmdFuncCCVKUpdateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer, const if (!gpuBuffer) return; const void *dataToUpload = nullptr; - size_t sizeToUpload = 0U; + size_t sizeToUpload = 0U; if (hasFlag(gpuBuffer->usage, BufferUsageBit::INDIRECT)) { - size_t drawInfoCount = size / sizeof(DrawInfo); - const auto *drawInfo = static_cast(buffer); + size_t drawInfoCount = size / sizeof(DrawInfo); + const auto *drawInfo = static_cast(buffer); if (drawInfoCount > 0) { if (drawInfo->indexCount) { for (size_t i = 0; i < drawInfoCount; ++i) { - gpuBuffer->indexedIndirectCmds[i].indexCount = drawInfo->indexCount; + gpuBuffer->indexedIndirectCmds[i].indexCount = drawInfo->indexCount; gpuBuffer->indexedIndirectCmds[i].instanceCount = std::max(drawInfo->instanceCount, 1U); - gpuBuffer->indexedIndirectCmds[i].firstIndex = drawInfo->firstIndex; - gpuBuffer->indexedIndirectCmds[i].vertexOffset = drawInfo->vertexOffset; + gpuBuffer->indexedIndirectCmds[i].firstIndex = drawInfo->firstIndex; + gpuBuffer->indexedIndirectCmds[i].vertexOffset = drawInfo->vertexOffset; gpuBuffer->indexedIndirectCmds[i].firstInstance = drawInfo->firstInstance; drawInfo++; } - dataToUpload = gpuBuffer->indexedIndirectCmds.data(); - sizeToUpload = drawInfoCount * sizeof(VkDrawIndexedIndirectCommand); + dataToUpload = gpuBuffer->indexedIndirectCmds.data(); + sizeToUpload = drawInfoCount * sizeof(VkDrawIndexedIndirectCommand); gpuBuffer->isDrawIndirectByIndex = true; } else { for (size_t i = 0; i < drawInfoCount; ++i) { - gpuBuffer->indirectCmds[i].vertexCount = drawInfo->vertexCount; + gpuBuffer->indirectCmds[i].vertexCount = drawInfo->vertexCount; gpuBuffer->indirectCmds[i].instanceCount = std::max(drawInfo->instanceCount, 1U); - gpuBuffer->indirectCmds[i].firstVertex = drawInfo->firstVertex; + gpuBuffer->indirectCmds[i].firstVertex = drawInfo->firstVertex; gpuBuffer->indirectCmds[i].firstInstance = drawInfo->firstInstance; drawInfo++; } - dataToUpload = gpuBuffer->indirectCmds.data(); - sizeToUpload = drawInfoCount * sizeof(VkDrawIndirectCommand); + dataToUpload = gpuBuffer->indirectCmds.data(); + sizeToUpload = drawInfoCount * sizeof(VkDrawIndirectCommand); gpuBuffer->isDrawIndirectByIndex = false; } } @@ -1224,17 +1224,17 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b ccstd::vector &curTypes = gpuTexture->currentAccessTypes; ThsvsImageBarrier barrier{}; - barrier.image = gpuTexture->vkImage; - barrier.discardContents = false; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = gpuTexture->vkImage; + barrier.discardContents = false; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; barrier.subresourceRange.aspectMask = gpuTexture->aspectMask; - barrier.prevAccessCount = utils::toUint(curTypes.size()); - barrier.pPrevAccesses = curTypes.data(); - barrier.nextAccessCount = 1; - barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); + barrier.prevAccessCount = utils::toUint(curTypes.size()); + barrier.pPrevAccesses = curTypes.data(); + barrier.nextAccessCount = 1; + barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); if (gpuTexture->transferAccess != THSVS_ACCESS_TRANSFER_WRITE) { cmdFuncCCVKImageMemoryBarrier(gpuCommandBuffer, barrier); @@ -1252,23 +1252,23 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b for (size_t i = 0U; i < count; ++i) { const BufferTextureCopy ®ion{regions[i]}; - uint32_t regionWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + uint32_t regionWidth = region.buffStride > 0 ? region.buffStride : region.texExtent.width; uint32_t regionHeight = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; - size_t regionSize = formatSize(gpuTexture->format, regionWidth, regionHeight, region.texExtent.depth); + size_t regionSize = formatSize(gpuTexture->format, regionWidth, regionHeight, region.texExtent.depth); // calculate the max height to upload per staging buffer chunk - uint32_t stepHeight = regionHeight; - size_t stepSize = regionSize; + uint32_t stepHeight = regionHeight; + size_t stepSize = regionSize; uint32_t heightAlignment = formatAlignment(gpuTexture->format).second; // for compressed textures while (stepSize > CCVKGPUStagingBufferPool::CHUNK_SIZE) { stepHeight = utils::alignTo((stepHeight - 1) / 2 + 1, heightAlignment); - stepSize = formatSize(gpuTexture->format, regionWidth, stepHeight, region.texExtent.depth); + stepSize = formatSize(gpuTexture->format, regionWidth, stepHeight, region.texExtent.depth); } // upload in chunks for (size_t h = 0U, s = 0U; h < regionHeight; h += stepHeight, s += stepSize) { - auto heightOffset = static_cast(h); - size_t curSize = std::min(regionSize - s, stepSize); + auto heightOffset = static_cast(h); + size_t curSize = std::min(regionSize - s, stepSize); CCVKGPUBuffer stagingBuffer; stagingBuffer.size = curSize; @@ -1276,12 +1276,12 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b memcpy(stagingBuffer.mappedData, buffers[i] + s, curSize); VkBufferImageCopy stagingRegion; - stagingRegion.bufferOffset = stagingBuffer.startOffset; - stagingRegion.bufferRowLength = region.buffStride; + stagingRegion.bufferOffset = stagingBuffer.startOffset; + stagingRegion.bufferRowLength = region.buffStride; stagingRegion.bufferImageHeight = region.buffTexHeight; - stagingRegion.imageSubresource = {gpuTexture->aspectMask, region.texSubres.mipLevel, region.texSubres.baseArrayLayer, region.texSubres.layerCount}; - stagingRegion.imageOffset = {region.texOffset.x, region.texOffset.y + heightOffset, region.texOffset.z}; - stagingRegion.imageExtent = {region.texExtent.width, std::min(stepHeight, regionHeight - heightOffset), region.texExtent.depth}; + stagingRegion.imageSubresource = {gpuTexture->aspectMask, region.texSubres.mipLevel, region.texSubres.baseArrayLayer, region.texSubres.layerCount}; + stagingRegion.imageOffset = {region.texOffset.x, region.texOffset.y + heightOffset, region.texOffset.z}; + stagingRegion.imageExtent = {region.texExtent.width, std::min(stepHeight, regionHeight - heightOffset), region.texExtent.depth}; vkCmdCopyBufferToImage(gpuCommandBuffer->vkCommandBuffer, stagingBuffer.vkBuffer, gpuTexture->vkImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &stagingRegion); @@ -1294,20 +1294,20 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b VkFormatFeatureFlags mipmapFeatures = VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; if (formatProperties.optimalTilingFeatures & mipmapFeatures) { - int width = static_cast(gpuTexture->width); + int width = static_cast(gpuTexture->width); int height = static_cast(gpuTexture->height); VkImageBlit blitInfo{}; - blitInfo.srcSubresource.aspectMask = gpuTexture->aspectMask; - blitInfo.srcSubresource.layerCount = gpuTexture->arrayLayers; - blitInfo.dstSubresource.aspectMask = gpuTexture->aspectMask; - blitInfo.dstSubresource.layerCount = gpuTexture->arrayLayers; - blitInfo.srcOffsets[1] = {width, height, 1}; - blitInfo.dstOffsets[1] = {std::max(width >> 1, 1), std::max(height >> 1, 1), 1}; + blitInfo.srcSubresource.aspectMask = gpuTexture->aspectMask; + blitInfo.srcSubresource.layerCount = gpuTexture->arrayLayers; + blitInfo.dstSubresource.aspectMask = gpuTexture->aspectMask; + blitInfo.dstSubresource.layerCount = gpuTexture->arrayLayers; + blitInfo.srcOffsets[1] = {width, height, 1}; + blitInfo.dstOffsets[1] = {std::max(width >> 1, 1), std::max(height >> 1, 1), 1}; barrier.subresourceRange.levelCount = 1; - barrier.prevAccessCount = 1; - barrier.pPrevAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); - barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); + barrier.prevAccessCount = 1; + barrier.pPrevAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); + barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); for (uint32_t i = 1U; i < gpuTexture->mipLevels; ++i) { barrier.subresourceRange.baseMipLevel = i - 1; @@ -1320,14 +1320,14 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b const int32_t w = blitInfo.srcOffsets[1].x = blitInfo.dstOffsets[1].x; const int32_t h = blitInfo.srcOffsets[1].y = blitInfo.dstOffsets[1].y; - blitInfo.dstOffsets[1].x = std::max(w >> 1, 1); - blitInfo.dstOffsets[1].y = std::max(h >> 1, 1); + blitInfo.dstOffsets[1].x = std::max(w >> 1, 1); + blitInfo.dstOffsets[1].y = std::max(h >> 1, 1); } barrier.subresourceRange.baseMipLevel = 0; - barrier.subresourceRange.levelCount = gpuTexture->mipLevels - 1; - barrier.pPrevAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); - barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); + barrier.subresourceRange.levelCount = gpuTexture->mipLevels - 1; + barrier.pPrevAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); + barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_WRITE); cmdFuncCCVKImageMemoryBarrier(gpuCommandBuffer, barrier); } else { @@ -1346,36 +1346,36 @@ void cmdFuncCCVKCopyTextureToBuffers(CCVKDevice *device, CCVKGPUTexture *srcText ccstd::vector &curTypes = srcTexture->currentAccessTypes; ThsvsImageBarrier barrier{}; - barrier.image = srcTexture->vkImage; - barrier.discardContents = false; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = srcTexture->vkImage; + barrier.discardContents = false; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; barrier.subresourceRange.aspectMask = srcTexture->aspectMask; - barrier.prevAccessCount = utils::toUint(curTypes.size()); - barrier.pPrevAccesses = curTypes.data(); - barrier.nextAccessCount = 1; - barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); + barrier.prevAccessCount = utils::toUint(curTypes.size()); + barrier.pPrevAccesses = curTypes.data(); + barrier.nextAccessCount = 1; + barrier.pNextAccesses = getAccessType(AccessFlagBit::TRANSFER_READ); if (srcTexture->transferAccess != THSVS_ACCESS_TRANSFER_READ) { cmdFuncCCVKImageMemoryBarrier(gpuCommandBuffer, barrier); } ccstd::vector stagingRegions(count); - VkDeviceSize offset = 0; + VkDeviceSize offset = 0; for (size_t i = 0U; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - VkBufferImageCopy & stagingRegion = stagingRegions[i]; - stagingRegion.bufferOffset = destBuffer->startOffset + offset; - stagingRegion.bufferRowLength = region.buffStride; - stagingRegion.bufferImageHeight = region.buffTexHeight; - stagingRegion.imageSubresource = {srcTexture->aspectMask, region.texSubres.mipLevel, region.texSubres.baseArrayLayer, region.texSubres.layerCount}; - stagingRegion.imageOffset = {region.texOffset.x, region.texOffset.y, region.texOffset.z}; - stagingRegion.imageExtent = {region.texExtent.width, region.texExtent.height, region.texExtent.depth}; + const BufferTextureCopy ®ion = regions[i]; + VkBufferImageCopy &stagingRegion = stagingRegions[i]; + stagingRegion.bufferOffset = destBuffer->startOffset + offset; + stagingRegion.bufferRowLength = region.buffStride; + stagingRegion.bufferImageHeight = region.buffTexHeight; + stagingRegion.imageSubresource = {srcTexture->aspectMask, region.texSubres.mipLevel, region.texSubres.baseArrayLayer, region.texSubres.layerCount}; + stagingRegion.imageOffset = {region.texOffset.x, region.texOffset.y, region.texOffset.z}; + stagingRegion.imageExtent = {region.texExtent.width, region.texExtent.height, region.texExtent.depth}; - uint32_t w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; - uint32_t h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + uint32_t w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + uint32_t h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; uint32_t regionSize = formatSize(srcTexture->format, w, h, region.texExtent.depth); offset += regionSize; @@ -1452,8 +1452,8 @@ void cmdFuncCCVKDestroyPipelineState(CCVKGPUDevice *gpuDevice, CCVKGPUPipelineSt } void cmdFuncCCVKImageMemoryBarrier(const CCVKGPUCommandBuffer *gpuCommandBuffer, const ThsvsImageBarrier &imageBarrier) { - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; VkImageMemoryBarrier vkBarrier; @@ -1477,14 +1477,14 @@ void CCVKGPURecycleBin::clear() { case RecycledType::BUFFER: if (res.buffer.vkBuffer) { vmaDestroyBuffer(_device->memoryAllocator, res.buffer.vkBuffer, res.buffer.vmaAllocation); - res.buffer.vkBuffer = VK_NULL_HANDLE; + res.buffer.vkBuffer = VK_NULL_HANDLE; res.buffer.vmaAllocation = VK_NULL_HANDLE; } break; case RecycledType::TEXTURE: if (res.image.vkImage) { vmaDestroyImage(_device->memoryAllocator, res.image.vkImage, res.image.vmaAllocation); - res.image.vkImage = VK_NULL_HANDLE; + res.image.vkImage = VK_NULL_HANDLE; res.image.vmaAllocation = VK_NULL_HANDLE; } break; @@ -1561,8 +1561,8 @@ VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format static ccstd::unordered_map cacheMap; if (!cacheMap.count(format)) { - bool hasDepth = GFX_FORMAT_INFOS[toNumber(format)].hasDepth; - VkImageUsageFlags usages = hasDepth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + bool hasDepth = GFX_FORMAT_INFOS[toNumber(format)].hasDepth; + VkImageUsageFlags usages = hasDepth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; VkImageFormatProperties properties; vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vkFormat, VK_IMAGE_TYPE_2D, @@ -1586,11 +1586,11 @@ VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (_buffersToBeChecked.empty() && _texturesToBeChecked.empty()) return; - static ccstd::vector prevAccesses; - static ccstd::vector nextAccesses; + static ccstd::vector prevAccesses; + static ccstd::vector nextAccesses; static ccstd::vector vkImageBarriers; - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; vkImageBarriers.clear(); prevAccesses.clear(); nextAccesses.clear(); @@ -1605,14 +1605,14 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { gpuBuffer->transferAccess = THSVS_ACCESS_NONE; } - VkMemoryBarrier vkBarrier; + VkMemoryBarrier vkBarrier; VkMemoryBarrier *pVkBarrier = nullptr; if (!prevAccesses.empty()) { ThsvsGlobalBarrier globalBarrier{}; - globalBarrier.prevAccessCount = utils::toUint(prevAccesses.size()); - globalBarrier.pPrevAccesses = prevAccesses.data(); - globalBarrier.nextAccessCount = utils::toUint(nextAccesses.size()); - globalBarrier.pNextAccesses = nextAccesses.data(); + globalBarrier.prevAccessCount = utils::toUint(prevAccesses.size()); + globalBarrier.pPrevAccesses = prevAccesses.data(); + globalBarrier.nextAccessCount = utils::toUint(nextAccesses.size()); + globalBarrier.pNextAccesses = nextAccesses.data(); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; thsvsGetVulkanMemoryBarrier(globalBarrier, &tempSrcStageMask, &tempDstStageMask, &vkBarrier); @@ -1622,23 +1622,23 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { } ThsvsImageBarrier imageBarrier{}; - imageBarrier.discardContents = false; - imageBarrier.prevLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; - imageBarrier.nextLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; - imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.discardContents = false; + imageBarrier.prevLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; + imageBarrier.nextLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; + imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; imageBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - imageBarrier.prevAccessCount = 1; + imageBarrier.prevAccessCount = 1; for (CCVKGPUTexture *gpuTexture : _texturesToBeChecked) { ccstd::vector &render = gpuTexture->renderAccessTypes; if (gpuTexture->transferAccess == THSVS_ACCESS_NONE || render.empty()) continue; - ccstd::vector ¤t = gpuTexture->currentAccessTypes; - imageBarrier.pPrevAccesses = &gpuTexture->transferAccess; - imageBarrier.nextAccessCount = utils::toUint(render.size()); - imageBarrier.pNextAccesses = render.data(); - imageBarrier.image = gpuTexture->vkImage; + ccstd::vector ¤t = gpuTexture->currentAccessTypes; + imageBarrier.pPrevAccesses = &gpuTexture->transferAccess; + imageBarrier.nextAccessCount = utils::toUint(render.size()); + imageBarrier.pNextAccesses = render.data(); + imageBarrier.image = gpuTexture->vkImage; imageBarrier.subresourceRange.aspectMask = gpuTexture->aspectMask; VkPipelineStageFlags tempSrcStageMask = 0; @@ -1687,7 +1687,7 @@ void CCVKGPUBufferHub::flush(CCVKGPUTransportHub *transportHub) { if (buffer.second.canMemcpy) continue; region.srcOffset = buffer.first->getStartOffset(buffer.second.srcIndex); region.dstOffset = buffer.first->getStartOffset(_device->curBackBufferIndex); - region.size = buffer.second.size; + region.size = buffer.second.size; vkCmdCopyBuffer(gpuCommandBuffer->vkCommandBuffer, buffer.first->vkBuffer, buffer.first->vkBuffer, 1, ®ion); } }); diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp index 7bcaf02a23..f89d072acb 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp @@ -46,8 +46,8 @@ CCVKDescriptorSet::~CCVKDescriptorSet() { void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); - uint32_t bindingCount = utils::toUint(gpuDescriptorSetLayout->bindings.size()); - uint32_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; + uint32_t bindingCount = utils::toUint(gpuDescriptorSetLayout->bindings.size()); + uint32_t descriptorCount = gpuDescriptorSetLayout->descriptorCount; _gpuDescriptorSet = ccnew CCVKGPUDescriptorSet; _gpuDescriptorSet->gpuDescriptors.resize(descriptorCount, {}); @@ -57,7 +57,7 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { const DescriptorSetLayoutBinding &binding = gpuDescriptorSetLayout->bindings[i]; for (uint32_t j = 0; j < binding.count; ++j, ++k) { CCVKGPUDescriptor &gpuDescriptor = _gpuDescriptorSet->gpuDescriptors[k]; - gpuDescriptor.type = binding.descriptorType; + gpuDescriptor.type = binding.descriptorType; switch (binding.descriptorType) { case DescriptorType::UNIFORM_BUFFER: case DescriptorType::DYNAMIC_UNIFORM_BUFFER: @@ -89,13 +89,13 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { } } - CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); _gpuDescriptorSet->gpuLayout = gpuDescriptorSetLayout; _gpuDescriptorSet->instances.resize(gpuDevice->backBufferCount); for (uint32_t t = 0U; t < gpuDevice->backBufferCount; ++t) { CCVKGPUDescriptorSet::Instance &instance = _gpuDescriptorSet->instances[t]; - instance.vkDescriptorSet = gpuDevice->getDescriptorSetPool(_gpuDescriptorSet->layoutID)->request(t); + instance.vkDescriptorSet = gpuDevice->getDescriptorSetPool(_gpuDescriptorSet->layoutID)->request(t); instance.descriptorInfos.resize(descriptorCount, {}); for (uint32_t i = 0U, k = 0U; i < bindingCount; ++i) { @@ -104,10 +104,10 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { if (hasFlag(DESCRIPTOR_BUFFER_TYPE, binding.descriptorType)) { instance.descriptorInfos[k].buffer.buffer = gpuDevice->defaultBuffer.vkBuffer; instance.descriptorInfos[k].buffer.offset = gpuDevice->defaultBuffer.getStartOffset(t); - instance.descriptorInfos[k].buffer.range = gpuDevice->defaultBuffer.size; + instance.descriptorInfos[k].buffer.range = gpuDevice->defaultBuffer.size; } else if (hasFlag(DESCRIPTOR_TEXTURE_TYPE, binding.descriptorType)) { - instance.descriptorInfos[k].image.sampler = gpuDevice->defaultSampler.vkSampler; - instance.descriptorInfos[k].image.imageView = gpuDevice->defaultTextureView.vkImageView; + instance.descriptorInfos[k].image.sampler = gpuDevice->defaultSampler.vkSampler; + instance.descriptorInfos[k].image.imageView = gpuDevice->defaultTextureView.vkImageView; instance.descriptorInfos[k].image.imageLayout = hasFlag(binding.descriptorType, DescriptorType::STORAGE_IMAGE) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; @@ -122,11 +122,11 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { for (uint32_t i = 0U, j = 0U; i < bindingCount; i++) { const VkDescriptorSetLayoutBinding &descriptor = gpuDescriptorSetLayout->vkBindings[i]; for (uint32_t k = 0U; k < descriptor.descriptorCount; k++, j++) { - entries[j].dstSet = instance.vkDescriptorSet; - entries[j].dstBinding = descriptor.binding; + entries[j].dstSet = instance.vkDescriptorSet; + entries[j].dstBinding = descriptor.binding; entries[j].dstArrayElement = k; entries[j].descriptorCount = 1; // better not to assume that the descriptor infos would be contiguous - entries[j].descriptorType = descriptor.descriptorType; + entries[j].descriptorType = descriptor.descriptorType; switch (entries[j].descriptorType) { case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: @@ -155,9 +155,9 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { void CCVKDescriptorSet::doDestroy() { if (_gpuDescriptorSet) { - CCVKGPUDevice * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); CCVKGPUDescriptorHub *descriptorHub = CCVKDevice::getInstance()->gpuDescriptorHub(); - uint32_t instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); + uint32_t instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); for (uint32_t t = 0U; t < instanceCount; ++t) { CCVKGPUDescriptorSet::Instance &instance = _gpuDescriptorSet->instances[t]; @@ -191,10 +191,10 @@ void CCVKDescriptorSet::doDestroy() { void CCVKDescriptorSet::update() { if (_isDirty && _gpuDescriptorSet) { - CCVKGPUDescriptorHub * descriptorHub = CCVKDevice::getInstance()->gpuDescriptorHub(); - CCVKGPUBarrierManager *layoutMgr = CCVKDevice::getInstance()->gpuBarrierManager(); - uint32_t descriptorCount = utils::toUint(_gpuDescriptorSet->gpuDescriptors.size()); - uint32_t instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); + CCVKGPUDescriptorHub *descriptorHub = CCVKDevice::getInstance()->gpuDescriptorHub(); + CCVKGPUBarrierManager *layoutMgr = CCVKDevice::getInstance()->gpuBarrierManager(); + uint32_t descriptorCount = utils::toUint(_gpuDescriptorSet->gpuDescriptors.size()); + uint32_t instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); for (size_t i = 0U; i < descriptorCount; i++) { CCVKGPUDescriptor &binding = _gpuDescriptorSet->gpuDescriptors[i]; diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp index a455753615..ce1a4c7adb 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSetLayout.cpp @@ -39,12 +39,12 @@ CCVKDescriptorSetLayout::~CCVKDescriptorSetLayout() { } void CCVKDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo & /*info*/) { - _gpuDescriptorSetLayout = ccnew CCVKGPUDescriptorSetLayout; - _gpuDescriptorSetLayout->id = generateID(); - _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; - _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; + _gpuDescriptorSetLayout = ccnew CCVKGPUDescriptorSetLayout; + _gpuDescriptorSetLayout->id = generateID(); + _gpuDescriptorSetLayout->descriptorCount = _descriptorCount; + _gpuDescriptorSetLayout->bindingIndices = _bindingIndices; _gpuDescriptorSetLayout->descriptorIndices = _descriptorIndices; - _gpuDescriptorSetLayout->bindings = _bindings; + _gpuDescriptorSetLayout->bindings = _bindings; for (auto &binding : _bindings) { if (hasAnyFlags(binding.descriptorType, DESCRIPTOR_DYNAMIC_TYPE)) { diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 13dd57f8db..6fe322dda0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -68,10 +68,10 @@ namespace cc { namespace gfx { static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( - VkDevice device, + VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, - const VkAllocationCallbacks * pAllocator, - VkRenderPass * pRenderPass); + const VkAllocationCallbacks *pAllocator, + VkRenderPass *pRenderPass); CCVKDevice *CCVKDevice::instance = nullptr; @@ -80,14 +80,14 @@ CCVKDevice *CCVKDevice::getInstance() { } CCVKDevice::CCVKDevice() { - _api = API::VULKAN; + _api = API::VULKAN; _deviceName = "Vulkan"; - _caps.supportQuery = true; - _caps.clipSpaceMinZ = 0.0F; + _caps.supportQuery = true; + _caps.clipSpaceMinZ = 0.0F; _caps.screenSpaceSignY = -1.0F; - _caps.clipSpaceSignY = -1.0F; - CCVKDevice::instance = this; + _caps.clipSpaceSignY = -1.0F; + CCVKDevice::instance = this; } CCVKDevice::~CCVKDevice() { @@ -102,13 +102,13 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { } const VkPhysicalDeviceFeatures2 &deviceFeatures2 = _gpuContext->physicalDeviceFeatures2; - const VkPhysicalDeviceFeatures & deviceFeatures = deviceFeatures2.features; + const VkPhysicalDeviceFeatures &deviceFeatures = deviceFeatures2.features; //const VkPhysicalDeviceVulkan11Features &deviceVulkan11Features = _gpuContext->physicalDeviceVulkan11Features; //const VkPhysicalDeviceVulkan12Features &deviceVulkan12Features = _gpuContext->physicalDeviceVulkan12Features; ///////////////////// Device Creation ///////////////////// - _gpuDevice = ccnew CCVKGPUDevice; + _gpuDevice = ccnew CCVKGPUDevice; _gpuDevice->minorVersion = _gpuContext->minorVersion; // only enable the absolute essentials @@ -125,16 +125,16 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { requestedExtensions.push_back(VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME); } - VkPhysicalDeviceFeatures2 requestedFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + VkPhysicalDeviceFeatures2 requestedFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; VkPhysicalDeviceVulkan11Features requestedVulkan11Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; VkPhysicalDeviceVulkan12Features requestedVulkan12Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; // features should be enabled like this: requestedFeatures2.features.textureCompressionASTC_LDR = deviceFeatures.textureCompressionASTC_LDR; - requestedFeatures2.features.textureCompressionBC = deviceFeatures.textureCompressionBC; - requestedFeatures2.features.textureCompressionETC2 = deviceFeatures.textureCompressionETC2; - requestedFeatures2.features.samplerAnisotropy = deviceFeatures.samplerAnisotropy; - requestedFeatures2.features.depthBounds = deviceFeatures.depthBounds; - requestedFeatures2.features.multiDrawIndirect = deviceFeatures.multiDrawIndirect; + requestedFeatures2.features.textureCompressionBC = deviceFeatures.textureCompressionBC; + requestedFeatures2.features.textureCompressionETC2 = deviceFeatures.textureCompressionETC2; + requestedFeatures2.features.samplerAnisotropy = deviceFeatures.samplerAnisotropy; + requestedFeatures2.features.depthBounds = deviceFeatures.depthBounds; + requestedFeatures2.features.multiDrawIndirect = deviceFeatures.multiDrawIndirect; if (_gpuContext->validationEnabled) { requestedLayers.push_back("VK_LAYER_KHRONOS_validation"); @@ -156,7 +156,7 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { SwappyVk_determineDeviceExtensions(_gpuContext->physicalDevice, availableExtensionCount, _gpuDevice->extensions.data(), &swappyRequiredExtensionCount, nullptr); ccstd::vector swappyRequiredExtensions(swappyRequiredExtensionCount); - ccstd::vector swappyRequiredExtensionsData(swappyRequiredExtensionCount * (VK_MAX_EXTENSION_NAME_SIZE + 1)); + ccstd::vector swappyRequiredExtensionsData(swappyRequiredExtensionCount * (VK_MAX_EXTENSION_NAME_SIZE + 1)); for (uint32_t i = 0; i < swappyRequiredExtensionCount; i++) { swappyRequiredExtensions[i] = &swappyRequiredExtensionsData[i * (VK_MAX_EXTENSION_NAME_SIZE + 1)]; } @@ -183,9 +183,9 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { } // prepare the device queues - uint32_t queueFamilyPropertiesCount = utils::toUint(_gpuContext->queueFamilyProperties.size()); + uint32_t queueFamilyPropertiesCount = utils::toUint(_gpuContext->queueFamilyProperties.size()); ccstd::vector queueCreateInfos(queueFamilyPropertiesCount, {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}); - ccstd::vector> queuePriorities(queueFamilyPropertiesCount); + ccstd::vector> queuePriorities(queueFamilyPropertiesCount); for (uint32_t queueFamilyIndex = 0U; queueFamilyIndex < queueFamilyPropertiesCount; ++queueFamilyIndex) { const VkQueueFamilyProperties &queueFamilyProperty = _gpuContext->queueFamilyProperties[queueFamilyIndex]; @@ -195,24 +195,24 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { VkDeviceQueueCreateInfo &queueCreateInfo = queueCreateInfos[queueFamilyIndex]; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; - queueCreateInfo.queueCount = queueFamilyProperty.queueCount; + queueCreateInfo.queueCount = queueFamilyProperty.queueCount; queueCreateInfo.pQueuePriorities = queuePriorities[queueFamilyIndex].data(); } VkDeviceCreateInfo deviceCreateInfo{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - deviceCreateInfo.queueCreateInfoCount = utils::toUint(queueCreateInfos.size()); - deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(); - deviceCreateInfo.enabledLayerCount = utils::toUint(_layers.size()); - deviceCreateInfo.ppEnabledLayerNames = _layers.data(); - deviceCreateInfo.enabledExtensionCount = utils::toUint(_extensions.size()); + deviceCreateInfo.queueCreateInfoCount = utils::toUint(queueCreateInfos.size()); + deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data(); + deviceCreateInfo.enabledLayerCount = utils::toUint(_layers.size()); + deviceCreateInfo.ppEnabledLayerNames = _layers.data(); + deviceCreateInfo.enabledExtensionCount = utils::toUint(_extensions.size()); deviceCreateInfo.ppEnabledExtensionNames = _extensions.data(); if (_gpuDevice->minorVersion < 1 && !_gpuContext->checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { deviceCreateInfo.pEnabledFeatures = &requestedFeatures2.features; } else { deviceCreateInfo.pNext = &requestedFeatures2; if (_gpuDevice->minorVersion >= 2) { - requestedFeatures2.pNext = &requestedVulkan11Features; + requestedFeatures2.pNext = &requestedVulkan11Features; requestedVulkan11Features.pNext = &requestedVulkan12Features; } } @@ -227,7 +227,7 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { auto findPreferredDepthFormat = [this](const VkFormat *formats, uint32_t count, VkFormat *pFormat) { for (uint32_t i = 0; i < count; ++i) { - VkFormat format = formats[i]; + VkFormat format = formats[i]; VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(_gpuContext->physicalDevice, format, &formatProperties); // Format must support depth stencil attachment for optimal tiling @@ -254,11 +254,11 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { }; findPreferredDepthFormat(depthStencilFormatPriorityList, 3, &_gpuDevice->depthStencilFormat); - _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; - _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; - _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; - _features[toNumber(Feature::BLEND_MINMAX)] = true; - _features[toNumber(Feature::COMPUTE_SHADER)] = true; + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; initFormatFeature(); @@ -281,7 +281,7 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { compressedFmts += "pvrtc "; } - _gpuDevice->useMultiDrawIndirect = deviceFeatures.multiDrawIndirect; + _gpuDevice->useMultiDrawIndirect = deviceFeatures.multiDrawIndirect; _gpuDevice->useDescriptorUpdateTemplate = _gpuDevice->minorVersion > 0 || checkExtension(VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME); if (_gpuDevice->minorVersion > 1) { @@ -293,23 +293,23 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { } const VkPhysicalDeviceLimits &limits = _gpuContext->physicalDeviceProperties.limits; - _caps.maxVertexAttributes = limits.maxVertexInputAttributes; - _caps.maxVertexUniformVectors = limits.maxUniformBufferRange / 16; - _caps.maxFragmentUniformVectors = limits.maxUniformBufferRange / 16; - _caps.maxUniformBufferBindings = limits.maxDescriptorSetUniformBuffers; - _caps.maxUniformBlockSize = limits.maxUniformBufferRange; - _caps.maxShaderStorageBlockSize = limits.maxStorageBufferRange; + _caps.maxVertexAttributes = limits.maxVertexInputAttributes; + _caps.maxVertexUniformVectors = limits.maxUniformBufferRange / 16; + _caps.maxFragmentUniformVectors = limits.maxUniformBufferRange / 16; + _caps.maxUniformBufferBindings = limits.maxDescriptorSetUniformBuffers; + _caps.maxUniformBlockSize = limits.maxUniformBufferRange; + _caps.maxShaderStorageBlockSize = limits.maxStorageBufferRange; _caps.maxShaderStorageBufferBindings = limits.maxDescriptorSetStorageBuffers; - _caps.maxTextureUnits = limits.maxDescriptorSetSampledImages; - _caps.maxVertexTextureUnits = limits.maxPerStageDescriptorSampledImages; - _caps.maxTextureSize = limits.maxImageDimension2D; - _caps.maxCubeMapTextureSize = limits.maxImageDimensionCube; - _caps.uboOffsetAlignment = utils::toUint(limits.minUniformBufferOffsetAlignment); + _caps.maxTextureUnits = limits.maxDescriptorSetSampledImages; + _caps.maxVertexTextureUnits = limits.maxPerStageDescriptorSampledImages; + _caps.maxTextureSize = limits.maxImageDimension2D; + _caps.maxCubeMapTextureSize = limits.maxImageDimensionCube; + _caps.uboOffsetAlignment = utils::toUint(limits.minUniformBufferOffsetAlignment); // compute shaders - _caps.maxComputeSharedMemorySize = limits.maxComputeSharedMemorySize; + _caps.maxComputeSharedMemorySize = limits.maxComputeSharedMemorySize; _caps.maxComputeWorkGroupInvocations = limits.maxComputeWorkGroupInvocations; - _caps.maxComputeWorkGroupCount = {limits.maxComputeWorkGroupCount[0], limits.maxComputeWorkGroupCount[1], limits.maxComputeWorkGroupCount[2]}; - _caps.maxComputeWorkGroupSize = {limits.maxComputeWorkGroupSize[0], limits.maxComputeWorkGroupSize[1], limits.maxComputeWorkGroupSize[2]}; + _caps.maxComputeWorkGroupCount = {limits.maxComputeWorkGroupCount[0], limits.maxComputeWorkGroupCount[1], limits.maxComputeWorkGroupCount[2]}; + _caps.maxComputeWorkGroupSize = {limits.maxComputeWorkGroupSize[0], limits.maxComputeWorkGroupSize[1], limits.maxComputeWorkGroupSize[2]}; #if defined(VK_USE_PLATFORM_ANDROID_KHR) // UNASSIGNED-BestPractices-vkCreateComputePipelines-compute-work-group-size _caps.maxComputeWorkGroupInvocations = std::min(_caps.maxComputeWorkGroupInvocations, 64U); @@ -319,56 +319,56 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { QueueInfo queueInfo; queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); + _queue = createQueue(queueInfo); QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS, false}; _queryPool = createQueryPool(queryPoolInfo); CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _cmdBuff = createCommandBuffer(cmdBuffInfo); VmaAllocatorCreateInfo allocatorInfo{}; allocatorInfo.physicalDevice = _gpuContext->physicalDevice; - allocatorInfo.device = _gpuDevice->vkDevice; - allocatorInfo.instance = _gpuContext->vkInstance; + allocatorInfo.device = _gpuDevice->vkDevice; + allocatorInfo.instance = _gpuContext->vkInstance; VmaVulkanFunctions vmaVulkanFunc{}; - vmaVulkanFunc.vkAllocateMemory = vkAllocateMemory; - vmaVulkanFunc.vkBindBufferMemory = vkBindBufferMemory; - vmaVulkanFunc.vkBindImageMemory = vkBindImageMemory; - vmaVulkanFunc.vkCreateBuffer = vkCreateBuffer; - vmaVulkanFunc.vkCreateImage = vkCreateImage; - vmaVulkanFunc.vkDestroyBuffer = vkDestroyBuffer; - vmaVulkanFunc.vkDestroyImage = vkDestroyImage; - vmaVulkanFunc.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges; - vmaVulkanFunc.vkFreeMemory = vkFreeMemory; - vmaVulkanFunc.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements; - vmaVulkanFunc.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements; + vmaVulkanFunc.vkAllocateMemory = vkAllocateMemory; + vmaVulkanFunc.vkBindBufferMemory = vkBindBufferMemory; + vmaVulkanFunc.vkBindImageMemory = vkBindImageMemory; + vmaVulkanFunc.vkCreateBuffer = vkCreateBuffer; + vmaVulkanFunc.vkCreateImage = vkCreateImage; + vmaVulkanFunc.vkDestroyBuffer = vkDestroyBuffer; + vmaVulkanFunc.vkDestroyImage = vkDestroyImage; + vmaVulkanFunc.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges; + vmaVulkanFunc.vkFreeMemory = vkFreeMemory; + vmaVulkanFunc.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements; + vmaVulkanFunc.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements; vmaVulkanFunc.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties; - vmaVulkanFunc.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties; - vmaVulkanFunc.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges; - vmaVulkanFunc.vkMapMemory = vkMapMemory; - vmaVulkanFunc.vkUnmapMemory = vkUnmapMemory; - vmaVulkanFunc.vkCmdCopyBuffer = vkCmdCopyBuffer; + vmaVulkanFunc.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties; + vmaVulkanFunc.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges; + vmaVulkanFunc.vkMapMemory = vkMapMemory; + vmaVulkanFunc.vkUnmapMemory = vkUnmapMemory; + vmaVulkanFunc.vkCmdCopyBuffer = vkCmdCopyBuffer; if (_gpuDevice->minorVersion > 0) { allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; vmaVulkanFunc.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2; - vmaVulkanFunc.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2; - vmaVulkanFunc.vkBindBufferMemory2KHR = vkBindBufferMemory2; - vmaVulkanFunc.vkBindImageMemory2KHR = vkBindImageMemory2; + vmaVulkanFunc.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2; + vmaVulkanFunc.vkBindBufferMemory2KHR = vkBindBufferMemory2; + vmaVulkanFunc.vkBindImageMemory2KHR = vkBindImageMemory2; } else { if (checkExtension(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) && checkExtension(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME)) { allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; vmaVulkanFunc.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR; - vmaVulkanFunc.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR; + vmaVulkanFunc.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR; } if (checkExtension(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME)) { vmaVulkanFunc.vkBindBufferMemory2KHR = vkBindBufferMemory2KHR; - vmaVulkanFunc.vkBindImageMemory2KHR = vkBindImageMemory2KHR; + vmaVulkanFunc.vkBindImageMemory2KHR = vkBindImageMemory2KHR; } } if (checkExtension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { @@ -390,12 +390,12 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { _gpuStagingBufferPools.push_back(ccnew CCVKGPUStagingBufferPool(_gpuDevice)); } - _gpuBufferHub = ccnew CCVKGPUBufferHub(_gpuDevice); - _gpuTransportHub = ccnew CCVKGPUTransportHub(_gpuDevice, static_cast(_queue)->gpuQueue()); - _gpuDescriptorHub = ccnew CCVKGPUDescriptorHub(_gpuDevice); - _gpuSemaphorePool = ccnew CCVKGPUSemaphorePool(_gpuDevice); - _gpuBarrierManager = ccnew CCVKGPUBarrierManager(_gpuDevice); - _gpuFramebufferHub = ccnew CCVKGPUFramebufferHub; + _gpuBufferHub = ccnew CCVKGPUBufferHub(_gpuDevice); + _gpuTransportHub = ccnew CCVKGPUTransportHub(_gpuDevice, static_cast(_queue)->gpuQueue()); + _gpuDescriptorHub = ccnew CCVKGPUDescriptorHub(_gpuDevice); + _gpuSemaphorePool = ccnew CCVKGPUSemaphorePool(_gpuDevice); + _gpuBarrierManager = ccnew CCVKGPUBarrierManager(_gpuDevice); + _gpuFramebufferHub = ccnew CCVKGPUFramebufferHub; _gpuDescriptorSetHub = ccnew CCVKGPUDescriptorSetHub(_gpuDevice); _gpuDescriptorHub->link(_gpuDescriptorSetHub); @@ -403,21 +403,21 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { cmdFuncCCVKCreateSampler(this, &_gpuDevice->defaultSampler); _gpuDevice->defaultTexture.format = Format::RGBA8; - _gpuDevice->defaultTexture.usage = TextureUsageBit::SAMPLED | TextureUsage::STORAGE; + _gpuDevice->defaultTexture.usage = TextureUsageBit::SAMPLED | TextureUsage::STORAGE; _gpuDevice->defaultTexture.width = _gpuDevice->defaultTexture.height = 1U; - _gpuDevice->defaultTexture.size = formatSize(Format::RGBA8, 1U, 1U, 1U); + _gpuDevice->defaultTexture.size = formatSize(Format::RGBA8, 1U, 1U, 1U); cmdFuncCCVKCreateTexture(this, &_gpuDevice->defaultTexture); _gpuDevice->defaultTextureView.gpuTexture = &_gpuDevice->defaultTexture; - _gpuDevice->defaultTextureView.format = Format::RGBA8; + _gpuDevice->defaultTextureView.format = Format::RGBA8; cmdFuncCCVKCreateTextureView(this, &_gpuDevice->defaultTextureView); ThsvsImageBarrier barrier{}; - barrier.nextAccessCount = 1; - barrier.pNextAccesses = getAccessType(AccessFlagBit::VERTEX_SHADER_READ_TEXTURE); - barrier.image = _gpuDevice->defaultTexture.vkImage; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.nextAccessCount = 1; + barrier.pNextAccesses = getAccessType(AccessFlagBit::VERTEX_SHADER_READ_TEXTURE); + barrier.image = _gpuDevice->defaultTexture.vkImage; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; @@ -427,10 +427,10 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { }, true); - _gpuDevice->defaultBuffer.usage = BufferUsage::UNIFORM | BufferUsage::STORAGE; + _gpuDevice->defaultBuffer.usage = BufferUsage::UNIFORM | BufferUsage::STORAGE; _gpuDevice->defaultBuffer.memUsage = MemoryUsage::HOST | MemoryUsage::DEVICE; _gpuDevice->defaultBuffer.size = _gpuDevice->defaultBuffer.stride = 16U; - _gpuDevice->defaultBuffer.count = 1U; + _gpuDevice->defaultBuffer.count = 1U; cmdFuncCCVKCreateBuffer(this, &_gpuDevice->defaultBuffer); getAccessTypes(AccessFlagBit::COLOR_ATTACHMENT_WRITE, _gpuDevice->defaultColorBarrier.nextAccesses); @@ -462,9 +462,9 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { } uint32_t apiVersion = _gpuContext->physicalDeviceProperties.apiVersion; - _renderer = _gpuContext->physicalDeviceProperties.deviceName; - _vendor = mapVendorName(_gpuContext->physicalDeviceProperties.vendorID); - _version = StringUtil::format("%d.%d.%d", VK_VERSION_MAJOR(apiVersion), + _renderer = _gpuContext->physicalDeviceProperties.deviceName; + _vendor = mapVendorName(_gpuContext->physicalDeviceProperties.vendorID); + _version = StringUtil::format("%d.%d.%d", VK_VERSION_MAJOR(apiVersion), VK_VERSION_MINOR(apiVersion), VK_VERSION_PATCH(apiVersion)); CC_LOG_INFO("Vulkan device initialized."); @@ -522,7 +522,7 @@ void CCVKDevice::doDestroy() { if (_gpuDevice->defaultBuffer.vkBuffer) { vmaDestroyBuffer(_gpuDevice->memoryAllocator, _gpuDevice->defaultBuffer.vkBuffer, _gpuDevice->defaultBuffer.vmaAllocation); - _gpuDevice->defaultBuffer.vkBuffer = VK_NULL_HANDLE; + _gpuDevice->defaultBuffer.vkBuffer = VK_NULL_HANDLE; _gpuDevice->defaultBuffer.vmaAllocation = VK_NULL_HANDLE; } if (_gpuDevice->defaultTextureView.vkImageView) { @@ -531,7 +531,7 @@ void CCVKDevice::doDestroy() { } if (_gpuDevice->defaultTexture.vkImage) { vmaDestroyImage(_gpuDevice->memoryAllocator, _gpuDevice->defaultTexture.vkImage, _gpuDevice->defaultTexture.vmaAllocation); - _gpuDevice->defaultTexture.vkImage = VK_NULL_HANDLE; + _gpuDevice->defaultTexture.vkImage = VK_NULL_HANDLE; _gpuDevice->defaultTexture.vmaAllocation = VK_NULL_HANDLE; } cmdFuncCCVKDestroySampler(_gpuDevice, &_gpuDevice->defaultSampler); @@ -566,9 +566,9 @@ void CCVKDevice::doDestroy() { } namespace { -ccstd::vector vkSwapchains; -ccstd::vector vkSwapchainIndices; -ccstd::vector gpuSwapchains; +ccstd::vector vkSwapchains; +ccstd::vector vkSwapchainIndices; +ccstd::vector gpuSwapchains; ccstd::vector vkAcquireBarriers; ccstd::vector vkPresentBarriers; @@ -624,7 +624,7 @@ void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { for (uint32_t i = 0; i < vkSwapchains.size(); ++i) { VkSemaphore acquireSemaphore = _gpuSemaphorePool->alloc(); - VkResult res = vkAcquireNextImageKHR(_gpuDevice->vkDevice, vkSwapchains[i], ~0ULL, + VkResult res = vkAcquireNextImageKHR(_gpuDevice->vkDevice, vkSwapchains[i], ~0ULL, acquireSemaphore, VK_NULL_HANDLE, &vkSwapchainIndices[i]); CC_ASSERT(res == VK_SUCCESS || res == VK_SUBOPTIMAL_KHR); gpuSwapchains[i]->curImageIndex = vkSwapchainIndices[i]; @@ -651,10 +651,10 @@ void CCVKDevice::acquire(Swapchain *const *swapchains, uint32_t count) { void CCVKDevice::present() { CC_PROFILE(CCVKDevicePresent); - auto *queue = static_cast(_queue); - _numDrawCalls = queue->_numDrawCalls; - _numInstances = queue->_numInstances; - _numTriangles = queue->_numTriangles; + auto *queue = static_cast(_queue); + _numDrawCalls = queue->_numDrawCalls; + _numInstances = queue->_numInstances; + _numTriangles = queue->_numTriangles; queue->_numDrawCalls = 0; queue->_numInstances = 0; queue->_numTriangles = 0; @@ -675,10 +675,10 @@ void CCVKDevice::present() { if (!vkSwapchains.empty()) { // don't present if not acquired VkPresentInfoKHR presentInfo{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; presentInfo.waitSemaphoreCount = utils::toUint(queue->gpuQueue()->lastSignaledSemaphores.size()); - presentInfo.pWaitSemaphores = queue->gpuQueue()->lastSignaledSemaphores.data(); - presentInfo.swapchainCount = utils::toUint(vkSwapchains.size()); - presentInfo.pSwapchains = vkSwapchains.data(); - presentInfo.pImageIndices = vkSwapchainIndices.data(); + presentInfo.pWaitSemaphores = queue->gpuQueue()->lastSignaledSemaphores.data(); + presentInfo.swapchainCount = utils::toUint(vkSwapchains.size()); + presentInfo.pSwapchains = vkSwapchains.data(); + presentInfo.pImageIndices = vkSwapchainIndices.data(); VkResult res = vkCCPresentFunc(queue->gpuQueue()->vkQueue, &presentInfo); for (auto *gpuSwapchain : gpuSwapchains) { @@ -699,8 +699,8 @@ void CCVKDevice::present() { gpuStagingBufferPool()->reset(); } -CCVKGPUFencePool * CCVKDevice::gpuFencePool() { return _gpuFencePools[_gpuDevice->curBackBufferIndex]; } -CCVKGPURecycleBin * CCVKDevice::gpuRecycleBin() { return _gpuRecycleBins[_gpuDevice->curBackBufferIndex]; } +CCVKGPUFencePool *CCVKDevice::gpuFencePool() { return _gpuFencePools[_gpuDevice->curBackBufferIndex]; } +CCVKGPURecycleBin *CCVKDevice::gpuRecycleBin() { return _gpuRecycleBins[_gpuDevice->curBackBufferIndex]; } CCVKGPUStagingBufferPool *CCVKDevice::gpuStagingBufferPool() { return _gpuStagingBufferPools[_gpuDevice->curBackBufferIndex]; } void CCVKDevice::waitAllFences() { @@ -733,9 +733,9 @@ void CCVKDevice::updateBackBufferCount(uint32_t backBufferCount) { } void CCVKDevice::initFormatFeature() { - const auto formatLen = static_cast(Format::COUNT); - VkFormatProperties properties = {}; - VkFormat format = {}; + const auto formatLen = static_cast(Format::COUNT); + VkFormatProperties properties = {}; + VkFormat format = {}; VkFormatFeatureFlags formatFeature = {}; for (uint32_t i = toNumber(Format::R8); i < formatLen; ++i) { if (static_cast(i) == Format::ETC_RGB8) continue; @@ -779,7 +779,7 @@ Queue *CCVKDevice::createQueue() { } QueryPool *CCVKDevice::createQueryPool() { - return ccnew CCVKQueryPool; + return ccnew CCVKQueryPool; } Swapchain *CCVKDevice::createSwapchain() { @@ -847,15 +847,15 @@ void CCVKDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *ds void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { CC_PROFILE(CCVKDeviceCopyTextureToBuffers); - uint32_t totalSize = 0U; - Format format = srcTexture->getFormat(); + uint32_t totalSize = 0U; + Format format = srcTexture->getFormat(); ccstd::vector> regionOffsetSizes(count); for (size_t i = 0U; i < count; ++i) { - const BufferTextureCopy ®ion = regions[i]; - uint32_t w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; - uint32_t h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; - uint32_t regionSize = formatSize(format, w, h, region.texExtent.depth); - regionOffsetSizes[i] = {totalSize, regionSize}; + const BufferTextureCopy ®ion = regions[i]; + uint32_t w = region.buffStride > 0 ? region.buffStride : region.texExtent.width; + uint32_t h = region.buffTexHeight > 0 ? region.buffTexHeight : region.texExtent.height; + uint32_t regionSize = formatSize(format, w, h, region.texExtent.depth); + regionOffsetSizes[i] = {totalSize, regionSize}; totalSize += regionSize; } @@ -874,8 +874,8 @@ void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffe true); for (uint32_t i = 0; i < count; ++i) { - uint32_t regionOffset = 0; - uint32_t regionSize = 0; + uint32_t regionOffset = 0; + uint32_t regionSize = 0; std::tie(regionOffset, regionSize) = regionOffsetSizes[i]; memcpy(buffers[i], stagingBuffer.mappedData + regionOffset, regionSize); } @@ -884,13 +884,13 @@ void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffe void CCVKDevice::getQueryPoolResults(QueryPool *queryPool) { CC_PROFILE(CCVKDeviceGetQueryPoolResults); auto *vkQueryPool = static_cast(queryPool); - auto queryCount = static_cast(vkQueryPool->_ids.size()); + auto queryCount = static_cast(vkQueryPool->_ids.size()); CC_ASSERT(queryCount <= vkQueryPool->getMaxQueryObjects()); - const bool bWait = queryPool->getForceWait(); - uint32_t width = bWait ? 1U : 2U; - uint64_t stride = sizeof(uint64_t) * width; - VkQueryResultFlagBits flag = bWait ? VK_QUERY_RESULT_WAIT_BIT : VK_QUERY_RESULT_WITH_AVAILABILITY_BIT; + const bool bWait = queryPool->getForceWait(); + uint32_t width = bWait ? 1U : 2U; + uint64_t stride = sizeof(uint64_t) * width; + VkQueryResultFlagBits flag = bWait ? VK_QUERY_RESULT_WAIT_BIT : VK_QUERY_RESULT_WITH_AVAILABILITY_BIT; ccstd::vector results(queryCount * width, 0ULL); if (queryCount > 0U) { @@ -910,8 +910,8 @@ void CCVKDevice::getQueryPoolResults(QueryPool *queryPool) { for (auto queryId = 0U; queryId < queryCount; queryId++) { uint32_t offset = queryId * width; if (bWait || results[offset + 1] > 0) { - uint32_t id = vkQueryPool->_ids[queryId]; - auto iter = mapResults.find(id); + uint32_t id = vkQueryPool->_ids[queryId]; + auto iter = mapResults.find(id); if (iter != mapResults.end()) { iter->second += results[offset]; } else { @@ -929,32 +929,32 @@ void CCVKDevice::getQueryPoolResults(QueryPool *queryPool) { //////////////////////////// Function Fallbacks ///////////////////////////////////////// static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( - VkDevice device, + VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, - const VkAllocationCallbacks * pAllocator, - VkRenderPass * pRenderPass) { + const VkAllocationCallbacks *pAllocator, + VkRenderPass *pRenderPass) { static ccstd::vector attachmentDescriptions; - static ccstd::vector subpassDescriptions; - static ccstd::vector attachmentReferences; - static ccstd::vector subpassDependencies; - static ccstd::vector inputs; - static ccstd::vector colors; - static ccstd::vector resolves; - static ccstd::vector depths; + static ccstd::vector subpassDescriptions; + static ccstd::vector attachmentReferences; + static ccstd::vector subpassDependencies; + static ccstd::vector inputs; + static ccstd::vector colors; + static ccstd::vector resolves; + static ccstd::vector depths; attachmentDescriptions.resize(pCreateInfo->attachmentCount); for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { - VkAttachmentDescription & desc{attachmentDescriptions[i]}; + VkAttachmentDescription &desc{attachmentDescriptions[i]}; const VkAttachmentDescription2 &desc2{pCreateInfo->pAttachments[i]}; - desc.flags = desc2.flags; - desc.format = desc2.format; - desc.samples = desc2.samples; - desc.loadOp = desc2.loadOp; - desc.storeOp = desc2.storeOp; - desc.stencilLoadOp = desc2.stencilLoadOp; + desc.flags = desc2.flags; + desc.format = desc2.format; + desc.samples = desc2.samples; + desc.loadOp = desc2.loadOp; + desc.storeOp = desc2.storeOp; + desc.stencilLoadOp = desc2.stencilLoadOp; desc.stencilStoreOp = desc2.stencilStoreOp; - desc.initialLayout = desc2.initialLayout; - desc.finalLayout = desc2.finalLayout; + desc.initialLayout = desc2.initialLayout; + desc.finalLayout = desc2.finalLayout; } subpassDescriptions.resize(pCreateInfo->subpassCount); @@ -989,40 +989,40 @@ static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( } } for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { - VkSubpassDescription & desc{subpassDescriptions[i]}; + VkSubpassDescription &desc{subpassDescriptions[i]}; const VkSubpassDescription2 &desc2{pCreateInfo->pSubpasses[i]}; - desc.flags = desc2.flags; - desc.pipelineBindPoint = desc2.pipelineBindPoint; - desc.inputAttachmentCount = desc2.inputAttachmentCount; - desc.pInputAttachments = inputs[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[inputs[i]]; - desc.colorAttachmentCount = desc2.colorAttachmentCount; - desc.pColorAttachments = colors[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[colors[i]]; - desc.pResolveAttachments = resolves[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[resolves[i]]; + desc.flags = desc2.flags; + desc.pipelineBindPoint = desc2.pipelineBindPoint; + desc.inputAttachmentCount = desc2.inputAttachmentCount; + desc.pInputAttachments = inputs[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[inputs[i]]; + desc.colorAttachmentCount = desc2.colorAttachmentCount; + desc.pColorAttachments = colors[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[colors[i]]; + desc.pResolveAttachments = resolves[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[resolves[i]]; desc.pDepthStencilAttachment = depths[i] > attachmentReferences.size() ? nullptr : &attachmentReferences[depths[i]]; desc.preserveAttachmentCount = desc2.preserveAttachmentCount; - desc.pPreserveAttachments = desc2.pPreserveAttachments; + desc.pPreserveAttachments = desc2.pPreserveAttachments; } subpassDependencies.resize(pCreateInfo->dependencyCount); for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { - VkSubpassDependency & desc{subpassDependencies[i]}; + VkSubpassDependency &desc{subpassDependencies[i]}; const VkSubpassDependency2 &desc2{pCreateInfo->pDependencies[i]}; - desc.srcSubpass = desc2.srcSubpass; - desc.dstSubpass = desc2.dstSubpass; - desc.srcStageMask = desc2.srcStageMask; - desc.dstStageMask = desc2.dstStageMask; - desc.srcAccessMask = desc2.srcAccessMask; - desc.dstAccessMask = desc2.dstAccessMask; + desc.srcSubpass = desc2.srcSubpass; + desc.dstSubpass = desc2.dstSubpass; + desc.srcStageMask = desc2.srcStageMask; + desc.dstStageMask = desc2.dstStageMask; + desc.srcAccessMask = desc2.srcAccessMask; + desc.dstAccessMask = desc2.dstAccessMask; desc.dependencyFlags = desc2.dependencyFlags; } VkRenderPassCreateInfo renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; renderPassCreateInfo.attachmentCount = utils::toUint(attachmentDescriptions.size()); - renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); - renderPassCreateInfo.subpassCount = utils::toUint(subpassDescriptions.size()); - renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); + renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); + renderPassCreateInfo.subpassCount = utils::toUint(subpassDescriptions.size()); + renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); renderPassCreateInfo.dependencyCount = utils::toUint(subpassDependencies.size()); - renderPassCreateInfo.pDependencies = subpassDependencies.data(); + renderPassCreateInfo.pDependencies = subpassDependencies.data(); return vkCreateRenderPass(device, &renderPassCreateInfo, pAllocator, pRenderPass); } diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index 1d0a79aa2d..87502ecd3c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -83,21 +83,21 @@ public: }); } - inline CCVKGPUDevice * gpuDevice() const { return _gpuDevice; } + inline CCVKGPUDevice *gpuDevice() const { return _gpuDevice; } inline CCVKGPUContext *gpuContext() { return _gpuContext; } - inline CCVKGPUBufferHub * gpuBufferHub() { return _gpuBufferHub; } - inline CCVKGPUTransportHub * gpuTransportHub() { return _gpuTransportHub; } - inline CCVKGPUDescriptorHub * gpuDescriptorHub() { return _gpuDescriptorHub; } - inline CCVKGPUSemaphorePool * gpuSemaphorePool() { return _gpuSemaphorePool; } - inline CCVKGPUBarrierManager * gpuBarrierManager() { return _gpuBarrierManager; } - inline CCVKGPUFramebufferHub * gpuFramebufferHub() { return _gpuFramebufferHub; } + inline CCVKGPUBufferHub *gpuBufferHub() { return _gpuBufferHub; } + inline CCVKGPUTransportHub *gpuTransportHub() { return _gpuTransportHub; } + inline CCVKGPUDescriptorHub *gpuDescriptorHub() { return _gpuDescriptorHub; } + inline CCVKGPUSemaphorePool *gpuSemaphorePool() { return _gpuSemaphorePool; } + inline CCVKGPUBarrierManager *gpuBarrierManager() { return _gpuBarrierManager; } + inline CCVKGPUFramebufferHub *gpuFramebufferHub() { return _gpuFramebufferHub; } inline CCVKGPUDescriptorSetHub *gpuDescriptorSetHub() { return _gpuDescriptorSetHub; } - CCVKGPUFencePool * gpuFencePool(); - CCVKGPURecycleBin * gpuRecycleBin(); + CCVKGPUFencePool *gpuFencePool(); + CCVKGPURecycleBin *gpuRecycleBin(); CCVKGPUStagingBufferPool *gpuStagingBufferPool(); - void waitAllFences(); + void waitAllFences(); void updateBackBufferCount(uint32_t backBufferCount); @@ -108,24 +108,24 @@ protected: CCVKDevice(); - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - QueryPool * createQueryPool() override; - Swapchain * createSwapchain() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + QueryPool *createQueryPool() override; + Swapchain *createSwapchain() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; - Sampler * createSampler(const SamplerInfo &info) override; + Sampler *createSampler(const SamplerInfo &info) override; GeneralBarrier *createGeneralBarrier(const GeneralBarrierInfo &info) override; TextureBarrier *createTextureBarrier(const TextureBarrierInfo &info) override; @@ -135,20 +135,20 @@ protected: void initFormatFeature(); - CCVKGPUDevice * _gpuDevice = nullptr; - CCVKGPUContext * _gpuContext = nullptr; + CCVKGPUDevice *_gpuDevice = nullptr; + CCVKGPUContext *_gpuContext = nullptr; ccstd::vector _depthStencilTextures; - ccstd::vector _gpuFencePools; - ccstd::vector _gpuRecycleBins; + ccstd::vector _gpuFencePools; + ccstd::vector _gpuRecycleBins; ccstd::vector _gpuStagingBufferPools; - CCVKGPUBufferHub * _gpuBufferHub{nullptr}; - CCVKGPUTransportHub * _gpuTransportHub{nullptr}; - CCVKGPUDescriptorHub * _gpuDescriptorHub{nullptr}; - CCVKGPUSemaphorePool * _gpuSemaphorePool{nullptr}; - CCVKGPUBarrierManager * _gpuBarrierManager{nullptr}; - CCVKGPUFramebufferHub * _gpuFramebufferHub{nullptr}; + CCVKGPUBufferHub *_gpuBufferHub{nullptr}; + CCVKGPUTransportHub *_gpuTransportHub{nullptr}; + CCVKGPUDescriptorHub *_gpuDescriptorHub{nullptr}; + CCVKGPUSemaphorePool *_gpuSemaphorePool{nullptr}; + CCVKGPUBarrierManager *_gpuBarrierManager{nullptr}; + CCVKGPUFramebufferHub *_gpuFramebufferHub{nullptr}; CCVKGPUDescriptorSetHub *_gpuDescriptorSetHub{nullptr}; ccstd::vector _layers; diff --git a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp index ef2b3de3df..c6f87fe07b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKFramebuffer.cpp @@ -41,18 +41,18 @@ CCVKFramebuffer::~CCVKFramebuffer() { } void CCVKFramebuffer::doInit(const FramebufferInfo & /*info*/) { - _gpuFBO = ccnew CCVKGPUFramebuffer; + _gpuFBO = ccnew CCVKGPUFramebuffer; _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorViews.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { - auto *colorTex = static_cast(_colorTextures[i]); + auto *colorTex = static_cast(_colorTextures[i]); _gpuFBO->gpuColorViews[i] = colorTex->gpuTextureView(); CCVKDevice::getInstance()->gpuFramebufferHub()->connect(colorTex->gpuTexture(), _gpuFBO); } if (_depthStencilTexture) { - auto *depthTex = static_cast(_depthStencilTexture); + auto *depthTex = static_cast(_depthStencilTexture); _gpuFBO->gpuDepthStencilView = depthTex->gpuTextureView(); CCVKDevice::getInstance()->gpuFramebufferHub()->connect(depthTex->gpuTexture(), _gpuFBO); } diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp index 1cf9e20b26..369223a784 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKGPUContext.cpp @@ -36,7 +36,7 @@ constexpr uint32_t FORCE_MINOR_VERSION = 0; // 0 for default version, otherwise #define FORCE_DISABLE_VALIDATION 1 #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION -constexpr uint32_t DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled +constexpr uint32_t DISABLE_VALIDATION_ASSERTIONS = 1; // 0 for default behavior, otherwise assertions will be disabled VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT /*messageType*/, const VkDebugUtilsMessengerCallbackDataEXT *callbackData, @@ -206,14 +206,14 @@ bool CCVKGPUContext::initialize() { VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.pEngineName = "Cocos Creator"; - app.apiVersion = apiVersion; + app.apiVersion = apiVersion; VkInstanceCreateInfo instanceInfo{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - instanceInfo.pApplicationInfo = &app; - instanceInfo.enabledExtensionCount = utils::toUint(extensions.size()); + instanceInfo.pApplicationInfo = &app; + instanceInfo.enabledExtensionCount = utils::toUint(extensions.size()); instanceInfo.ppEnabledExtensionNames = extensions.data(); - instanceInfo.enabledLayerCount = utils::toUint(layers.size()); - instanceInfo.ppEnabledLayerNames = layers.data(); + instanceInfo.enabledLayerCount = utils::toUint(layers.size()); + instanceInfo.ppEnabledLayerNames = layers.data(); #if CC_DEBUG > 0 && !FORCE_DISABLE_VALIDATION || FORCE_ENABLE_VALIDATION VkDebugUtilsMessengerCreateInfoEXT debugUtilsCreateInfo{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; @@ -223,7 +223,7 @@ bool CCVKGPUContext::initialize() { VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT; - debugUtilsCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + debugUtilsCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; debugUtilsCreateInfo.pfnUserCallback = debugUtilsMessengerCallback; instanceInfo.pNext = &debugUtilsCreateInfo; @@ -289,7 +289,7 @@ bool CCVKGPUContext::initialize() { deviceIndex = 0; } - physicalDevice = physicalDeviceHandles[deviceIndex]; + physicalDevice = physicalDeviceHandles[deviceIndex]; physicalDeviceProperties = physicalDevicePropertiesList[deviceIndex]; vkGetPhysicalDeviceFeatures(physicalDevice, &physicalDeviceFeatures); @@ -297,9 +297,9 @@ bool CCVKGPUContext::initialize() { minorVersion = VK_VERSION_MINOR(physicalDeviceProperties.apiVersion); if (minorVersion >= 1 || checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { - physicalDeviceFeatures2.pNext = &physicalDeviceVulkan11Features; + physicalDeviceFeatures2.pNext = &physicalDeviceVulkan11Features; physicalDeviceVulkan11Features.pNext = &physicalDeviceVulkan12Features; - physicalDeviceProperties2.pNext = &physicalDeviceDepthStencilResolveProperties; + physicalDeviceProperties2.pNext = &physicalDeviceDepthStencilResolveProperties; if (minorVersion >= 1) { vkGetPhysicalDeviceProperties2(physicalDevice, &physicalDeviceProperties2); vkGetPhysicalDeviceFeatures2(physicalDevice, &physicalDeviceFeatures2); diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index fe71a3b7e0..bd6b4eea5a 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -42,20 +42,20 @@ public: bool initialize(); void destroy(); - VkInstance vkInstance = VK_NULL_HANDLE; + VkInstance vkInstance = VK_NULL_HANDLE; VkDebugUtilsMessengerEXT vkDebugUtilsMessenger = VK_NULL_HANDLE; - VkDebugReportCallbackEXT vkDebugReport = VK_NULL_HANDLE; + VkDebugReportCallbackEXT vkDebugReport = VK_NULL_HANDLE; - VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; - VkPhysicalDeviceFeatures physicalDeviceFeatures{}; - VkPhysicalDeviceFeatures2 physicalDeviceFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - VkPhysicalDeviceVulkan11Features physicalDeviceVulkan11Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features physicalDeviceVulkan12Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; + VkPhysicalDeviceFeatures physicalDeviceFeatures{}; + VkPhysicalDeviceFeatures2 physicalDeviceFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + VkPhysicalDeviceVulkan11Features physicalDeviceVulkan11Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; + VkPhysicalDeviceVulkan12Features physicalDeviceVulkan12Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; VkPhysicalDeviceDepthStencilResolveProperties physicalDeviceDepthStencilResolveProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; - VkPhysicalDeviceProperties physicalDeviceProperties{}; - VkPhysicalDeviceProperties2 physicalDeviceProperties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties{}; - ccstd::vector queueFamilyProperties; + VkPhysicalDeviceProperties physicalDeviceProperties{}; + VkPhysicalDeviceProperties2 physicalDeviceProperties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; + VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties{}; + ccstd::vector queueFamilyProperties; uint32_t majorVersion = 0; uint32_t minorVersion = 0; @@ -76,15 +76,15 @@ public: struct CCVKAccessInfo { VkPipelineStageFlags stageMask{0}; - VkAccessFlags accessMask{0}; - VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; - bool hasWriteAccess{false}; + VkAccessFlags accessMask{0}; + VkImageLayout imageLayout{VK_IMAGE_LAYOUT_UNDEFINED}; + bool hasWriteAccess{false}; }; struct CCVKGPUGeneralBarrier { VkPipelineStageFlags srcStageMask = 0U; VkPipelineStageFlags dstStageMask = 0U; - VkMemoryBarrier vkBarrier{}; + VkMemoryBarrier vkBarrier{}; ccstd::vector prevAccesses; ccstd::vector nextAccesses; @@ -94,15 +94,15 @@ struct CCVKGPUGeneralBarrier { class CCVKGPURenderPass final { public: - ColorAttachmentList colorAttachments; + ColorAttachmentList colorAttachments; DepthStencilAttachment depthStencilAttachment; - SubpassInfoList subpasses; - SubpassDependencyList dependencies; + SubpassInfoList subpasses; + SubpassDependencyList dependencies; VkRenderPass vkRenderPass; // helper storage - ccstd::vector clearValues; + ccstd::vector clearValues; ccstd::vector sampleCounts; // per subpass const CCVKGPUGeneralBarrier *getBarrier(size_t index, CCVKGPUDevice *gpuDevice) const; @@ -111,42 +111,42 @@ public: struct CCVKGPUSwapchain; struct CCVKGPUFramebuffer; struct CCVKGPUTexture { - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - TextureUsage usage = TextureUsageBit::NONE; - uint32_t width = 0U; - uint32_t height = 0U; - uint32_t depth = 1U; - uint32_t size = 0U; - uint32_t arrayLayers = 1U; - uint32_t mipLevels = 1U; - SampleCount samples = SampleCount::ONE; - TextureFlags flags = TextureFlagBit::NONE; - VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - bool memoryless = false; + TextureType type = TextureType::TEX2D; + Format format = Format::UNKNOWN; + TextureUsage usage = TextureUsageBit::NONE; + uint32_t width = 0U; + uint32_t height = 0U; + uint32_t depth = 1U; + uint32_t size = 0U; + uint32_t arrayLayers = 1U; + uint32_t mipLevels = 1U; + SampleCount samples = SampleCount::ONE; + TextureFlags flags = TextureFlagBit::NONE; + VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + bool memoryless = false; - VkImage vkImage = VK_NULL_HANDLE; + VkImage vkImage = VK_NULL_HANDLE; VmaAllocation vmaAllocation = VK_NULL_HANDLE; - CCVKGPUSwapchain * swapchain = nullptr; - ccstd::vector swapchainVkImages; + CCVKGPUSwapchain *swapchain = nullptr; + ccstd::vector swapchainVkImages; ccstd::vector swapchainVmaAllocations; ccstd::vector currentAccessTypes; // for barrier manager ccstd::vector renderAccessTypes; // gathered from descriptor sets - ThsvsAccessType transferAccess = THSVS_ACCESS_NONE; + ThsvsAccessType transferAccess = THSVS_ACCESS_NONE; }; struct CCVKGPUTextureView { CCVKGPUTexture *gpuTexture = nullptr; - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - uint32_t baseLevel = 0U; - uint32_t levelCount = 1U; - uint32_t baseLayer = 0U; - uint32_t layerCount = 1U; + TextureType type = TextureType::TEX2D; + Format format = Format::UNKNOWN; + uint32_t baseLevel = 0U; + uint32_t levelCount = 1U; + uint32_t baseLayer = 0U; + uint32_t layerCount = 1U; ccstd::vector swapchainVkImageViews; @@ -155,43 +155,43 @@ struct CCVKGPUTextureView { }; struct CCVKGPUSampler { - Filter minFilter = Filter::LINEAR; - Filter magFilter = Filter::LINEAR; - Filter mipFilter = Filter::NONE; - Address addressU = Address::WRAP; - Address addressV = Address::WRAP; - Address addressW = Address::WRAP; - uint32_t maxAnisotropy = 0U; - ComparisonFunc cmpFunc = ComparisonFunc::NEVER; + Filter minFilter = Filter::LINEAR; + Filter magFilter = Filter::LINEAR; + Filter mipFilter = Filter::NONE; + Address addressU = Address::WRAP; + Address addressV = Address::WRAP; + Address addressW = Address::WRAP; + uint32_t maxAnisotropy = 0U; + ComparisonFunc cmpFunc = ComparisonFunc::NEVER; // descriptor infos VkSampler vkSampler; }; struct CCVKGPUBuffer { - BufferUsage usage = BufferUsage::NONE; + BufferUsage usage = BufferUsage::NONE; MemoryUsage memUsage = MemoryUsage::NONE; - uint32_t stride = 0U; - uint32_t count = 0U; - void * buffer = nullptr; + uint32_t stride = 0U; + uint32_t count = 0U; + void *buffer = nullptr; - bool isDrawIndirectByIndex = false; - ccstd::vector indirectCmds; + bool isDrawIndirectByIndex = false; + ccstd::vector indirectCmds; ccstd::vector indexedIndirectCmds; - uint8_t * mappedData = nullptr; + uint8_t *mappedData = nullptr; VmaAllocation vmaAllocation = VK_NULL_HANDLE; // descriptor infos - VkBuffer vkBuffer = VK_NULL_HANDLE; + VkBuffer vkBuffer = VK_NULL_HANDLE; VkDeviceSize startOffset = 0U; - VkDeviceSize size = 0U; + VkDeviceSize size = 0U; VkDeviceSize instanceSize = 0U; // per-back-buffer instance // for barrier manager ccstd::vector renderAccessTypes; // gathered from descriptor sets - ThsvsAccessType transferAccess = THSVS_ACCESS_NONE; + ThsvsAccessType transferAccess = THSVS_ACCESS_NONE; VkDeviceSize getStartOffset(uint32_t curBackBufferIndex) const { return startOffset + instanceSize * curBackBufferIndex; @@ -200,8 +200,8 @@ struct CCVKGPUBuffer { struct CCVKGPUBufferView { CCVKGPUBuffer *gpuBuffer = nullptr; - uint32_t offset = 0U; - uint32_t range = 0U; + uint32_t offset = 0U; + uint32_t range = 0U; VkDeviceSize getStartOffset(uint32_t curBackBufferIndex) const { return gpuBuffer->getStartOffset(curBackBufferIndex) + offset; @@ -209,56 +209,56 @@ struct CCVKGPUBufferView { }; struct CCVKGPUFramebuffer { - CCVKGPURenderPass * gpuRenderPass = nullptr; + CCVKGPURenderPass *gpuRenderPass = nullptr; ccstd::vector gpuColorViews; - CCVKGPUTextureView * gpuDepthStencilView = nullptr; - VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; - CCVKGPUSwapchain * swapchain = nullptr; - bool isOffscreen = true; - uint32_t width = 0U; - uint32_t height = 0U; + CCVKGPUTextureView *gpuDepthStencilView = nullptr; + VkFramebuffer vkFramebuffer = VK_NULL_HANDLE; + CCVKGPUSwapchain *swapchain = nullptr; + bool isOffscreen = true; + uint32_t width = 0U; + uint32_t height = 0U; }; -using FramebufferList = ccstd::vector; -using FramebufferListMap = ccstd::unordered_map; +using FramebufferList = ccstd::vector; +using FramebufferListMap = ccstd::unordered_map; using FramebufferListMapIter = FramebufferListMap::iterator; struct CCVKGPUSwapchain { - VkSurfaceKHR vkSurface = VK_NULL_HANDLE; + VkSurfaceKHR vkSurface = VK_NULL_HANDLE; VkSwapchainCreateInfoKHR createInfo{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - uint32_t curImageIndex = 0U; - VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; - FramebufferListMap vkSwapchainFramebufferListMap; + uint32_t curImageIndex = 0U; + VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; + FramebufferListMap vkSwapchainFramebufferListMap; ccstd::vector queueFamilyPresentables; - VkResult lastPresentResult = VK_NOT_READY; + VkResult lastPresentResult = VK_NOT_READY; // external references ccstd::vector swapchainImages; }; struct CCVKGPUCommandBuffer { - VkCommandBuffer vkCommandBuffer = VK_NULL_HANDLE; - VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - uint32_t queueFamilyIndex = 0U; - bool began = false; + VkCommandBuffer vkCommandBuffer = VK_NULL_HANDLE; + VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + uint32_t queueFamilyIndex = 0U; + bool began = false; mutable ccstd::unordered_set recordedBuffers; }; struct CCVKGPUQueue { - QueueType type = QueueType::GRAPHICS; - VkQueue vkQueue = VK_NULL_HANDLE; - uint32_t queueFamilyIndex = 0U; - ccstd::vector possibleQueueFamilyIndices; - ccstd::vector lastSignaledSemaphores; + QueueType type = QueueType::GRAPHICS; + VkQueue vkQueue = VK_NULL_HANDLE; + uint32_t queueFamilyIndex = 0U; + ccstd::vector possibleQueueFamilyIndices; + ccstd::vector lastSignaledSemaphores; ccstd::vector submitStageMasks; - ccstd::vector commandBuffers; + ccstd::vector commandBuffers; }; struct CCVKGPUQueryPool { - QueryType type{QueryType::OCCLUSION}; - uint32_t maxQueryObjects{0}; - bool forceWait{true}; + QueryType type{QueryType::OCCLUSION}; + uint32_t maxQueryObjects{0}; + bool forceWait{true}; VkQueryPool vkPool{VK_NULL_HANDLE}; }; @@ -268,36 +268,36 @@ struct CCVKGPUShaderStage { source(std::move(s)) { } ShaderStageFlagBit type = ShaderStageFlagBit::NONE; - ccstd::string source; - VkShaderModule vkShader = VK_NULL_HANDLE; + ccstd::string source; + VkShaderModule vkShader = VK_NULL_HANDLE; }; struct CCVKGPUShader { - ccstd::string name; - AttributeList attributes; + ccstd::string name; + AttributeList attributes; ccstd::vector gpuStages; }; struct CCVKGPUInputAssembler { - AttributeList attributes; + AttributeList attributes; ccstd::vector gpuVertexBuffers; - CCVKGPUBufferView * gpuIndexBuffer = nullptr; - CCVKGPUBufferView * gpuIndirectBuffer = nullptr; - ccstd::vector vertexBuffers; - ccstd::vector vertexBufferOffsets; + CCVKGPUBufferView *gpuIndexBuffer = nullptr; + CCVKGPUBufferView *gpuIndirectBuffer = nullptr; + ccstd::vector vertexBuffers; + ccstd::vector vertexBufferOffsets; }; union CCVKDescriptorInfo { - VkDescriptorImageInfo image; + VkDescriptorImageInfo image; VkDescriptorBufferInfo buffer; - VkBufferView texelBufferView; + VkBufferView texelBufferView; }; struct CCVKGPUDescriptor { - DescriptorType type = DescriptorType::UNKNOWN; + DescriptorType type = DescriptorType::UNKNOWN; ccstd::vector accessTypes; - CCVKGPUBufferView * gpuBufferView = nullptr; - CCVKGPUTextureView * gpuTextureView = nullptr; - CCVKGPUSampler * gpuSampler = nullptr; + CCVKGPUBufferView *gpuBufferView = nullptr; + CCVKGPUTextureView *gpuTextureView = nullptr; + CCVKGPUSampler *gpuSampler = nullptr; }; struct CCVKGPUDescriptorSetLayout; @@ -308,8 +308,8 @@ struct CCVKGPUDescriptorSet { CCVKGPUDescriptorSetLayout *gpuLayout = nullptr; struct Instance { - VkDescriptorSet vkDescriptorSet = VK_NULL_HANDLE; - ccstd::vector descriptorInfos; + VkDescriptorSet vkDescriptorSet = VK_NULL_HANDLE; + ccstd::vector descriptorInfos; ccstd::vector descriptorUpdateEntries; }; ccstd::vector instances; // per swapchain image @@ -324,22 +324,22 @@ struct CCVKGPUPipelineLayout { // helper storage ccstd::vector dynamicOffsetOffsets; - uint32_t dynamicOffsetCount; + uint32_t dynamicOffsetCount; }; struct CCVKGPUPipelineState { - PipelineBindPoint bindPoint = PipelineBindPoint::GRAPHICS; - PrimitiveMode primitive = PrimitiveMode::TRIANGLE_LIST; - CCVKGPUShader * gpuShader = nullptr; + PipelineBindPoint bindPoint = PipelineBindPoint::GRAPHICS; + PrimitiveMode primitive = PrimitiveMode::TRIANGLE_LIST; + CCVKGPUShader *gpuShader = nullptr; CCVKGPUPipelineLayout *gpuPipelineLayout = nullptr; - InputState inputState; - RasterizerState rs; - DepthStencilState dss; - BlendState bs; - DynamicStateList dynamicStates; - CCVKGPURenderPass * gpuRenderPass = nullptr; - uint32_t subpass = 0U; - VkPipeline vkPipeline = VK_NULL_HANDLE; + InputState inputState; + RasterizerState rs; + DepthStencilState dss; + BlendState bs; + DynamicStateList dynamicStates; + CCVKGPURenderPass *gpuRenderPass = nullptr; + uint32_t subpass = 0U; + VkPipeline vkPipeline = VK_NULL_HANDLE; }; struct CCVKGPUTextureBarrier { @@ -357,12 +357,12 @@ class CCVKGPUCommandBufferPool; class CCVKGPUDescriptorSetPool; class CCVKGPUDevice final { public: - VkDevice vkDevice{VK_NULL_HANDLE}; - ccstd::vector layers; + VkDevice vkDevice{VK_NULL_HANDLE}; + ccstd::vector layers; ccstd::vector extensions; - VmaAllocator memoryAllocator{VK_NULL_HANDLE}; - VkPipelineCache vkPipelineCache{VK_NULL_HANDLE}; - uint32_t minorVersion{0U}; + VmaAllocator memoryAllocator{VK_NULL_HANDLE}; + VkPipelineCache vkPipelineCache{VK_NULL_HANDLE}; + uint32_t minorVersion{0U}; VkFormat depthFormat{VK_FORMAT_UNDEFINED}; VkFormat depthStencilFormat{VK_FORMAT_UNDEFINED}; @@ -376,10 +376,10 @@ public: PFN_vkCreateRenderPass2 createRenderPass2{nullptr}; // for default backup usages - CCVKGPUSampler defaultSampler; - CCVKGPUTexture defaultTexture; + CCVKGPUSampler defaultSampler; + CCVKGPUTexture defaultTexture; CCVKGPUTextureView defaultTextureView; - CCVKGPUBuffer defaultBuffer; + CCVKGPUBuffer defaultBuffer; CCVKGPUGeneralBarrier defaultColorBarrier; CCVKGPUGeneralBarrier defaultDepthStencilBarrier; @@ -421,7 +421,7 @@ public: return _fences[_count++]; } - VkFence fence = VK_NULL_HANDLE; + VkFence fence = VK_NULL_HANDLE; VkFenceCreateInfo createInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; VK_CHECK(vkCreateFence(_device->vkDevice, &createInfo, nullptr, &fence)); _fences.push_back(fence); @@ -446,8 +446,8 @@ public: } private: - CCVKGPUDevice * _device = nullptr; - uint32_t _count = 0U; + CCVKGPUDevice *_device = nullptr; + uint32_t _count = 0U; ccstd::vector _fences; }; @@ -473,7 +473,7 @@ public: return _semaphores[_count++]; } - VkSemaphore semaphore = VK_NULL_HANDLE; + VkSemaphore semaphore = VK_NULL_HANDLE; VkSemaphoreCreateInfo createInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; VK_CHECK(vkCreateSemaphore(_device->vkDevice, &createInfo, nullptr, &semaphore)); _semaphores.push_back(semaphore); @@ -491,8 +491,8 @@ public: } private: - CCVKGPUDevice * _device; - uint32_t _count = 0U; + CCVKGPUDevice *_device; + uint32_t _count = 0U; ccstd::vector _semaphores; }; @@ -524,7 +524,7 @@ public: } void link(CCVKGPUDevice *device, uint32_t maxSetsPerPool, const ccstd::vector &bindings, VkDescriptorSetLayout setLayout) { - _device = device; + _device = device; _maxSetsPerPool = maxSetsPerPool; _setLayouts.insert(_setLayouts.cbegin(), _maxSetsPerPool, setLayout); _fleaMarkets.resize(device->backBufferCount); @@ -554,8 +554,8 @@ public: return output; } - size_t size = _pools.size(); - uint32_t idx = 0U; + size_t size = _pools.size(); + uint32_t idx = 0U; for (; idx < size; idx++) { if (!_pools[idx].freeSets.empty()) { output = _pools[idx].freeSets.back(); @@ -567,9 +567,9 @@ public: if (idx >= size) { VkDescriptorPoolCreateInfo createInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - createInfo.maxSets = _maxSetsPerPool; + createInfo.maxSets = _maxSetsPerPool; createInfo.poolSizeCount = utils::toUint(_poolSizes.size()); - createInfo.pPoolSizes = _poolSizes.data(); + createInfo.pPoolSizes = _poolSizes.data(); VkDescriptorPool descriptorPool = VK_NULL_HANDLE; VK_CHECK(vkCreateDescriptorPool(_device->vkDevice, &createInfo, nullptr, &descriptorPool)); @@ -577,9 +577,9 @@ public: _pools[idx].freeSets.resize(_maxSetsPerPool); VkDescriptorSetAllocateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - info.pSetLayouts = _setLayouts.data(); + info.pSetLayouts = _setLayouts.data(); info.descriptorSetCount = _maxSetsPerPool; - info.descriptorPool = descriptorPool; + info.descriptorPool = descriptorPool; VK_CHECK(vkAllocateDescriptorSets(_device->vkDevice, &info, _pools[idx].freeSets.data())); } @@ -605,33 +605,33 @@ private: CCVKGPUDevice *_device = nullptr; struct DescriptorSetPool { - VkDescriptorPool vkPool = VK_NULL_HANDLE; + VkDescriptorPool vkPool = VK_NULL_HANDLE; ccstd::unordered_set activeSets; - ccstd::vector freeSets; + ccstd::vector freeSets; }; ccstd::vector _pools; ccstd::vector> _fleaMarkets; // per back buffer - ccstd::vector _poolSizes; + ccstd::vector _poolSizes; ccstd::vector _setLayouts; - uint32_t _maxSetsPerPool = 0U; + uint32_t _maxSetsPerPool = 0U; }; struct CCVKGPUDescriptorSetLayout { DescriptorSetLayoutBindingList bindings; - ccstd::vector dynamicBindings; + ccstd::vector dynamicBindings; ccstd::vector vkBindings; - VkDescriptorSetLayout vkDescriptorSetLayout = VK_NULL_HANDLE; - VkDescriptorUpdateTemplate vkDescriptorUpdateTemplate = VK_NULL_HANDLE; - VkDescriptorSet defaultDescriptorSet = VK_NULL_HANDLE; + VkDescriptorSetLayout vkDescriptorSetLayout = VK_NULL_HANDLE; + VkDescriptorUpdateTemplate vkDescriptorUpdateTemplate = VK_NULL_HANDLE; + VkDescriptorSet defaultDescriptorSet = VK_NULL_HANDLE; ccstd::vector bindingIndices; ccstd::vector descriptorIndices; - uint32_t descriptorCount = 0U; + uint32_t descriptorCount = 0U; - uint32_t id = 0U; + uint32_t id = 0U; uint32_t maxSetsPerPool = 10U; }; @@ -675,7 +675,7 @@ public: if (!_pools.count(hash)) { VkCommandPoolCreateInfo createInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; createInfo.queueFamilyIndex = gpuCommandBuffer->queueFamilyIndex; - createInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; + createInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; VK_CHECK(vkCreateCommandPool(_device->vkDevice, &createInfo, nullptr, &_pools[hash].vkCommandPool)); } CommandBufferPool &pool = _pools[hash]; @@ -685,9 +685,9 @@ public: gpuCommandBuffer->vkCommandBuffer = availableList.pop(); } else { VkCommandBufferAllocateInfo allocateInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - allocateInfo.commandPool = pool.vkCommandPool; + allocateInfo.commandPool = pool.vkCommandPool; allocateInfo.commandBufferCount = 1; - allocateInfo.level = gpuCommandBuffer->level; + allocateInfo.level = gpuCommandBuffer->level; VK_CHECK(vkAllocateCommandBuffers(_device->vkDevice, &allocateInfo, &gpuCommandBuffer->vkCommandBuffer)); } } @@ -727,13 +727,13 @@ public: private: struct CommandBufferPool { - VkCommandPool vkCommandPool = VK_NULL_HANDLE; + VkCommandPool vkCommandPool = VK_NULL_HANDLE; CachedArray commandBuffers[2]; CachedArray usedCommandBuffers[2]; }; - CCVKGPUDevice *_device = nullptr; - uint32_t _lastBackBufferIndex = 0U; + CCVKGPUDevice *_device = nullptr; + uint32_t _lastBackBufferIndex = 0U; ccstd::unordered_map _pools; }; @@ -760,12 +760,12 @@ public: void alloc(CCVKGPUBuffer *gpuBuffer, uint32_t alignment) { CC_ASSERT(gpuBuffer->size <= CHUNK_SIZE); - size_t bufferCount = _pool.size(); - Buffer * buffer = nullptr; - VkDeviceSize offset = 0U; + size_t bufferCount = _pool.size(); + Buffer *buffer = nullptr; + VkDeviceSize offset = 0U; for (size_t idx = 0U; idx < bufferCount; idx++) { Buffer *cur = &_pool[idx]; - offset = roundUp(cur->curOffset, alignment); + offset = roundUp(cur->curOffset, alignment); if (CHUNK_SIZE - offset >= gpuBuffer->size) { buffer = cur; break; @@ -775,7 +775,7 @@ public: _pool.resize(bufferCount + 1); buffer = &_pool.back(); VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bufferInfo.size = CHUNK_SIZE; + bufferInfo.size = CHUNK_SIZE; bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo{}; allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; @@ -783,12 +783,12 @@ public: VmaAllocationInfo res; VK_CHECK(vmaCreateBuffer(_device->memoryAllocator, &bufferInfo, &allocInfo, &buffer->vkBuffer, &buffer->vmaAllocation, &res)); buffer->mappedData = reinterpret_cast(res.pMappedData); - offset = 0U; + offset = 0U; } - gpuBuffer->vkBuffer = buffer->vkBuffer; + gpuBuffer->vkBuffer = buffer->vkBuffer; gpuBuffer->startOffset = offset; - gpuBuffer->mappedData = buffer->mappedData + offset; - buffer->curOffset = offset + gpuBuffer->size; + gpuBuffer->mappedData = buffer->mappedData + offset; + buffer->curOffset = offset + gpuBuffer->size; } void reset() { @@ -799,14 +799,14 @@ public: private: struct Buffer { - VkBuffer vkBuffer = VK_NULL_HANDLE; - uint8_t * mappedData = nullptr; + VkBuffer vkBuffer = VK_NULL_HANDLE; + uint8_t *mappedData = nullptr; VmaAllocation vmaAllocation = VK_NULL_HANDLE; VkDeviceSize curOffset = 0U; }; - CCVKGPUDevice * _device = nullptr; + CCVKGPUDevice *_device = nullptr; ccstd::vector _pool; }; @@ -870,8 +870,8 @@ private: using DescriptorSetList = ccstd::unordered_set; - CCVKGPUDevice * _device = nullptr; - ccstd::vector _setsToBeUpdated; + CCVKGPUDevice *_device = nullptr; + ccstd::vector _setsToBeUpdated; PFN_vkUpdateDescriptorSetWithTemplate _updateFn = nullptr; }; @@ -1028,7 +1028,7 @@ private: void doUpdate(const CCVKGPUBufferView *buffer, VkDescriptorBufferInfo *descriptor) { descriptor->buffer = buffer->gpuBuffer->vkBuffer; descriptor->offset = buffer->getStartOffset(_bufferInstanceIndices[descriptor]); - descriptor->range = buffer->range; + descriptor->range = buffer->range; } static void doUpdate(const CCVKGPUTextureView *texture, VkDescriptorImageInfo *descriptor) { @@ -1051,13 +1051,13 @@ private: template struct DescriptorInfo { ccstd::unordered_set sets; - CachedArray descriptors; + CachedArray descriptors; }; - ccstd::unordered_map _bufferInstanceIndices; + ccstd::unordered_map _bufferInstanceIndices; ccstd::unordered_map> _buffers; ccstd::unordered_map> _textures; - ccstd::unordered_map> _samplers; + ccstd::unordered_map> _samplers; CCVKGPUDescriptorSetHub *_descriptorSetHub = nullptr; }; @@ -1087,8 +1087,8 @@ public: } } else { Resource &res = _resources[_count++]; - res.type = RecycledType::TEXTURE; - res.image = {gpuTexture->vkImage, gpuTexture->vmaAllocation}; + res.type = RecycledType::TEXTURE; + res.image = {gpuTexture->vkImage, gpuTexture->vmaAllocation}; } } @@ -1102,8 +1102,8 @@ public: } gpuTextureView->swapchainVkImageViews.clear(); } else { - Resource &res = _resources[_count++]; - res.type = RecycledType::TEXTURE_VIEW; + Resource &res = _resources[_count++]; + res.type = RecycledType::TEXTURE_VIEW; res.vkImageView = gpuTextureView->vkImageView; } } @@ -1116,8 +1116,8 @@ public: _resources.resize(_count * 2); } for (VkFramebuffer vkFramebuffer : list) { - Resource &res = _resources[_count++]; - res.type = RecycledType::FRAMEBUFFER; + Resource &res = _resources[_count++]; + res.type = RecycledType::FRAMEBUFFER; res.vkFramebuffer = vkFramebuffer; } list.clear(); @@ -1126,8 +1126,8 @@ public: if (_resources.size() <= _count) { _resources.resize(_count * 2); } - Resource &res = _resources[_count++]; - res.type = RecycledType::FRAMEBUFFER; + Resource &res = _resources[_count++]; + res.type = RecycledType::FRAMEBUFFER; res.vkFramebuffer = gpuFramebuffer->vkFramebuffer; } } @@ -1138,7 +1138,7 @@ public: _resources.resize(_count * 2); \ } \ Resource &res = _resources[_count++]; \ - res.type = typeValue; \ + res.type = typeValue; \ expr; \ } @@ -1169,11 +1169,11 @@ private: PIPELINE_STATE, }; struct Buffer { - VkBuffer vkBuffer; + VkBuffer vkBuffer; VmaAllocation vmaAllocation; }; struct Image { - VkImage vkImage; + VkImage vkImage; VmaAllocation vmaAllocation; }; struct Resource { @@ -1181,23 +1181,23 @@ private: union { // resizable resources, cannot take over directly // or descriptor sets won't work - Buffer buffer; - Image image; - VkImageView vkImageView; + Buffer buffer; + Image image; + VkImageView vkImageView; VkFramebuffer vkFramebuffer; - CCVKGPURenderPass * gpuRenderPass; - CCVKGPUSampler * gpuSampler; - CCVKGPUShader * gpuShader; - CCVKGPUQueryPool * gpuQueryPool; + CCVKGPURenderPass *gpuRenderPass; + CCVKGPUSampler *gpuSampler; + CCVKGPUShader *gpuShader; + CCVKGPUQueryPool *gpuQueryPool; CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout; - CCVKGPUPipelineLayout * gpuPipelineLayout; - CCVKGPUPipelineState * gpuPipelineState; + CCVKGPUPipelineLayout *gpuPipelineLayout; + CCVKGPUPipelineState *gpuPipelineState; }; }; - CCVKGPUDevice * _device = nullptr; + CCVKGPUDevice *_device = nullptr; ccstd::vector _resources; - size_t _count = 0U; + size_t _count = 0U; }; /** @@ -1210,10 +1210,10 @@ public: CCVKGPUTransportHub(CCVKGPUDevice *device, CCVKGPUQueue *queue) : _device(device), _queue(queue) { - _earlyCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + _earlyCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; _earlyCmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; - _lateCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + _lateCmdBuff.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; _lateCmdBuff.queueFamilyIndex = _queue->queueFamilyIndex; VkFenceCreateInfo createInfo{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; @@ -1236,7 +1236,7 @@ public: template void checkIn(const TFunc &record, bool immediateSubmission = false, bool late = false) { CCVKGPUCommandBufferPool *commandBufferPool = _device->getCommandBufferPool(); - CCVKGPUCommandBuffer * cmdBuff = late ? &_lateCmdBuff : &_earlyCmdBuff; + CCVKGPUCommandBuffer *cmdBuff = late ? &_lateCmdBuff : &_earlyCmdBuff; if (!cmdBuff->vkCommandBuffer) { commandBufferPool->request(cmdBuff); @@ -1251,7 +1251,7 @@ public: VK_CHECK(vkEndCommandBuffer(cmdBuff->vkCommandBuffer)); VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &cmdBuff->vkCommandBuffer; + submitInfo.pCommandBuffers = &cmdBuff->vkCommandBuffer; VK_CHECK(vkQueueSubmit(_queue->vkQueue, 1, &submitInfo, _fence)); VK_CHECK(vkWaitForFences(_device->vkDevice, 1, &_fence, VK_TRUE, DEFAULT_TIMEOUT)); vkResetFences(_device->vkDevice, 1, &_fence); @@ -1274,10 +1274,10 @@ public: private: CCVKGPUDevice *_device = nullptr; - CCVKGPUQueue * _queue = nullptr; + CCVKGPUQueue *_queue = nullptr; CCVKGPUCommandBuffer _earlyCmdBuff; CCVKGPUCommandBuffer _lateCmdBuff; - VkFence _fence = VK_NULL_HANDLE; + VkFence _fence = VK_NULL_HANDLE; }; class CCVKGPUBarrierManager final { @@ -1305,9 +1305,9 @@ public: inline void cancel(CCVKGPUTexture *gpuTexture) { _texturesToBeChecked.erase(gpuTexture); } private: - ccstd::unordered_set _buffersToBeChecked; + ccstd::unordered_set _buffersToBeChecked; ccstd::unordered_set _texturesToBeChecked; - CCVKGPUDevice * _device = nullptr; + CCVKGPUDevice *_device = nullptr; }; /** @@ -1346,9 +1346,9 @@ public: private: struct BufferUpdate { - uint32_t srcIndex = 0U; - size_t size = 0U; - bool canMemcpy = false; + uint32_t srcIndex = 0U; + size_t size = 0U; + bool canMemcpy = false; }; ccstd::vector> _buffersToBeUpdated; diff --git a/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp b/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp index 8c3217b1a4..425de347fd 100644 --- a/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKInputAssembler.cpp @@ -42,12 +42,12 @@ CCVKInputAssembler::~CCVKInputAssembler() { void CCVKInputAssembler::doInit(const InputAssemblerInfo &info) { size_t vbCount = _vertexBuffers.size(); - _gpuInputAssembler = ccnew CCVKGPUInputAssembler; + _gpuInputAssembler = ccnew CCVKGPUInputAssembler; _gpuInputAssembler->attributes = _attributes; _gpuInputAssembler->gpuVertexBuffers.resize(vbCount); for (size_t i = 0U; i < vbCount; ++i) { - auto *vb = static_cast(_vertexBuffers[i]); + auto *vb = static_cast(_vertexBuffers[i]); _gpuInputAssembler->gpuVertexBuffers[i] = vb->gpuBufferView(); } @@ -64,7 +64,7 @@ void CCVKInputAssembler::doInit(const InputAssemblerInfo &info) { CCVKGPUDevice *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); for (size_t i = 0U; i < vbCount; i++) { - _gpuInputAssembler->vertexBuffers[i] = _gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; + _gpuInputAssembler->vertexBuffers[i] = _gpuInputAssembler->gpuVertexBuffers[i]->gpuBuffer->vkBuffer; _gpuInputAssembler->vertexBufferOffsets[i] = _gpuInputAssembler->gpuVertexBuffers[i]->getStartOffset(gpuDevice->curBackBufferIndex); } } diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp b/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp index 0c7c549f6e..a4bbbffb98 100644 --- a/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineLayout.cpp @@ -45,7 +45,7 @@ void CCVKPipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { uint32_t offset = 0U; for (auto *setLayout : _setLayouts) { CCVKGPUDescriptorSetLayout *gpuSetLayout = static_cast(setLayout)->gpuDescriptorSetLayout(); - uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); + uint32_t dynamicCount = utils::toUint(gpuSetLayout->dynamicBindings.size()); _gpuPipelineLayout->dynamicOffsetOffsets.push_back(offset); _gpuPipelineLayout->setLayouts.push_back(gpuSetLayout); offset += dynamicCount; diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp b/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp index 405eb682ee..bc514cce3b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineState.cpp @@ -42,15 +42,15 @@ CCVKPipelineState::~CCVKPipelineState() { } void CCVKPipelineState::doInit(const PipelineStateInfo & /*info*/) { - _gpuPipelineState = ccnew CCVKGPUPipelineState; - _gpuPipelineState->bindPoint = _bindPoint; - _gpuPipelineState->primitive = _primitive; - _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); - _gpuPipelineState->inputState = _inputState; - _gpuPipelineState->rs = _rasterizerState; - _gpuPipelineState->dss = _depthStencilState; - _gpuPipelineState->bs = _blendState; - _gpuPipelineState->subpass = _subpass; + _gpuPipelineState = ccnew CCVKGPUPipelineState; + _gpuPipelineState->bindPoint = _bindPoint; + _gpuPipelineState->primitive = _primitive; + _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + _gpuPipelineState->inputState = _inputState; + _gpuPipelineState->rs = _rasterizerState; + _gpuPipelineState->dss = _depthStencilState; + _gpuPipelineState->bs = _blendState; + _gpuPipelineState->subpass = _subpass; _gpuPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); if (_renderPass) _gpuPipelineState->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); diff --git a/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp b/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp index 578bdb5bfe..8cd8a829c5 100644 --- a/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp @@ -40,11 +40,11 @@ CCVKQueryPool::~CCVKQueryPool() { } void CCVKQueryPool::doInit(const QueryPoolInfo & /*info*/) { - CCVKDevice *device = CCVKDevice::getInstance(); - _gpuQueryPool = ccnew CCVKGPUQueryPool; - _gpuQueryPool->type = _type; + CCVKDevice *device = CCVKDevice::getInstance(); + _gpuQueryPool = ccnew CCVKGPUQueryPool; + _gpuQueryPool->type = _type; _gpuQueryPool->maxQueryObjects = _maxQueryObjects; - _gpuQueryPool->forceWait = _forceWait; + _gpuQueryPool->forceWait = _forceWait; cmdFuncCCVKCreateQueryPool(device, _gpuQueryPool); } diff --git a/native/cocos/renderer/gfx-vulkan/VKQueryPool.h b/native/cocos/renderer/gfx-vulkan/VKQueryPool.h index 3efba1ac90..7be866fb2c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKQueryPool.h +++ b/native/cocos/renderer/gfx-vulkan/VKQueryPool.h @@ -48,7 +48,7 @@ protected: void doInit(const QueryPoolInfo &info) override; void doDestroy() override; - CCVKGPUQueryPool * _gpuQueryPool{nullptr}; + CCVKGPUQueryPool *_gpuQueryPool{nullptr}; ccstd::vector _ids; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKQueue.cpp b/native/cocos/renderer/gfx-vulkan/VKQueue.cpp index 30dedbd601..476304b0e6 100644 --- a/native/cocos/renderer/gfx-vulkan/VKQueue.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKQueue.cpp @@ -42,7 +42,7 @@ CCVKQueue::~CCVKQueue() { } void CCVKQueue::doInit(const QueueInfo & /*info*/) { - _gpuQueue = ccnew CCVKGPUQueue; + _gpuQueue = ccnew CCVKGPUQueue; _gpuQueue->type = _type; cmdFuncCCVKGetDeviceQueue(CCVKDevice::getInstance(), _gpuQueue); } @@ -84,18 +84,18 @@ void CCVKQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { _gpuQueue->commandBuffers.push_back(device->gpuTransportHub()->packageForFlight(true)); } - size_t waitSemaphoreCount = _gpuQueue->lastSignaledSemaphores.size(); - VkSemaphore signal = waitSemaphoreCount ? device->gpuSemaphorePool()->alloc() : VK_NULL_HANDLE; + size_t waitSemaphoreCount = _gpuQueue->lastSignaledSemaphores.size(); + VkSemaphore signal = waitSemaphoreCount ? device->gpuSemaphorePool()->alloc() : VK_NULL_HANDLE; _gpuQueue->submitStageMasks.resize(waitSemaphoreCount, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); VkSubmitInfo submitInfo{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submitInfo.waitSemaphoreCount = utils::toUint(waitSemaphoreCount); - submitInfo.pWaitSemaphores = _gpuQueue->lastSignaledSemaphores.data(); - submitInfo.pWaitDstStageMask = _gpuQueue->submitStageMasks.data(); - submitInfo.commandBufferCount = utils::toUint(_gpuQueue->commandBuffers.size()); - submitInfo.pCommandBuffers = &_gpuQueue->commandBuffers[0]; + submitInfo.waitSemaphoreCount = utils::toUint(waitSemaphoreCount); + submitInfo.pWaitSemaphores = _gpuQueue->lastSignaledSemaphores.data(); + submitInfo.pWaitDstStageMask = _gpuQueue->submitStageMasks.data(); + submitInfo.commandBufferCount = utils::toUint(_gpuQueue->commandBuffers.size()); + submitInfo.pCommandBuffers = &_gpuQueue->commandBuffers[0]; submitInfo.signalSemaphoreCount = waitSemaphoreCount ? 1 : 0; - submitInfo.pSignalSemaphores = &signal; + submitInfo.pSignalSemaphores = &signal; VkFence vkFence = device->gpuFencePool()->alloc(); VK_CHECK(vkQueueSubmit(_gpuQueue->vkQueue, 1, &submitInfo, vkFence)); diff --git a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp index 011cd02494..f88df6d4b0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp @@ -39,11 +39,11 @@ CCVKRenderPass::~CCVKRenderPass() { } void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { - _gpuRenderPass = ccnew CCVKGPURenderPass; - _gpuRenderPass->colorAttachments = _colorAttachments; + _gpuRenderPass = ccnew CCVKGPURenderPass; + _gpuRenderPass->colorAttachments = _colorAttachments; _gpuRenderPass->depthStencilAttachment = _depthStencilAttachment; - _gpuRenderPass->subpasses = _subpasses; - _gpuRenderPass->dependencies = _dependencies; + _gpuRenderPass->subpasses = _subpasses; + _gpuRenderPass->dependencies = _dependencies; // assign a dummy subpass if not specified uint32_t colorCount = utils::toUint(_gpuRenderPass->colorAttachments.size()); diff --git a/native/cocos/renderer/gfx-vulkan/VKShader.cpp b/native/cocos/renderer/gfx-vulkan/VKShader.cpp index b717948037..79ae5cc79d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKShader.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKShader.cpp @@ -41,8 +41,8 @@ CCVKShader::~CCVKShader() { } void CCVKShader::doInit(const ShaderInfo & /*info*/) { - _gpuShader = ccnew CCVKGPUShader; - _gpuShader->name = _name; + _gpuShader = ccnew CCVKGPUShader; + _gpuShader->name = _name; _gpuShader->attributes = _attributes; for (ShaderStage &stage : _stages) { _gpuShader->gpuStages.push_back({stage.stage, stage.source}); diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index cc47c88478..f90fee737f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -42,7 +42,7 @@ namespace cc { namespace gfx { CCVKSwapchain::CCVKSwapchain() { - _typedID = generateObjectID(); + _typedID = generateObjectID(); _preRotationEnabled = ENABLE_PRE_ROTATION; } @@ -51,9 +51,9 @@ CCVKSwapchain::~CCVKSwapchain() { } void CCVKSwapchain::doInit(const SwapchainInfo &info) { - auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); - _gpuSwapchain = ccnew CCVKGPUSwapchain; + _gpuSwapchain = ccnew CCVKGPUSwapchain; gpuDevice->swapchains.insert(_gpuSwapchain); createVkSurface(); @@ -79,7 +79,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { cmdFuncCCVKGetDeviceQueue(CCVKDevice::getInstance(), queue->gpuQueue()); } - Format colorFmt = Format::BGRA8; + Format colorFmt = Format::BGRA8; Format depthStencilFmt = Format::DEPTH_STENCIL; VkSurfaceCapabilitiesKHR surfaceCapabilities{}; @@ -95,21 +95,21 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { ccstd::vector presentModes(presentModeCount); VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(gpuContext->physicalDevice, _gpuSwapchain->vkSurface, &presentModeCount, presentModes.data())); - VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + VkFormat colorFormat = VK_FORMAT_B8G8R8A8_UNORM; + VkColorSpaceKHR colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; // If the surface format list only includes one entry with VK_FORMAT_UNDEFINED, // there is no preferred format, so we assume VK_FORMAT_B8G8R8A8_UNORM if ((surfaceFormatCount == 1) && (surfaceFormats[0].format == VK_FORMAT_UNDEFINED)) { colorFormat = VK_FORMAT_B8G8R8A8_UNORM; - colorSpace = surfaceFormats[0].colorSpace; + colorSpace = surfaceFormats[0].colorSpace; } else { // iterate over the list of available surface format and // check for the presence of VK_FORMAT_B8G8R8A8_UNORM bool imageFormatFound = false; for (VkSurfaceFormatKHR &surfaceFormat : surfaceFormats) { if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) { - colorFormat = surfaceFormat.format; - colorSpace = surfaceFormat.colorSpace; + colorFormat = surfaceFormat.format; + colorSpace = surfaceFormat.colorSpace; imageFormatFound = true; break; } @@ -119,7 +119,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { // select the first available color format if (!imageFormatFound) { colorFormat = surfaceFormats[0].format; - colorSpace = surfaceFormats[0].colorSpace; + colorSpace = surfaceFormats[0].colorSpace; switch (colorFormat) { case VK_FORMAT_R8G8B8A8_UNORM: colorFmt = Format::RGBA8; break; case VK_FORMAT_R8G8B8A8_SRGB: colorFmt = Format::SRGB8_A8; break; @@ -156,7 +156,7 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { // Determine the number of images uint32_t desiredNumberOfSwapchainImages = std::max(gpuDevice->backBufferCount, surfaceCapabilities.minImageCount); - VkExtent2D imageExtent = {1U, 1U}; + VkExtent2D imageExtent = {1U, 1U}; VkSurfaceTransformFlagBitsKHR preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; // Find a supported composite alpha format (not all devices support alpha opaque) @@ -185,28 +185,28 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; } - _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; - _gpuSwapchain->createInfo.minImageCount = desiredNumberOfSwapchainImages; - _gpuSwapchain->createInfo.imageFormat = colorFormat; - _gpuSwapchain->createInfo.imageColorSpace = colorSpace; - _gpuSwapchain->createInfo.imageExtent = imageExtent; - _gpuSwapchain->createInfo.imageUsage = imageUsage; + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.minImageCount = desiredNumberOfSwapchainImages; + _gpuSwapchain->createInfo.imageFormat = colorFormat; + _gpuSwapchain->createInfo.imageColorSpace = colorSpace; + _gpuSwapchain->createInfo.imageExtent = imageExtent; + _gpuSwapchain->createInfo.imageUsage = imageUsage; _gpuSwapchain->createInfo.imageArrayLayers = 1; - _gpuSwapchain->createInfo.preTransform = preTransform; - _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; - _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; - _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area + _gpuSwapchain->createInfo.preTransform = preTransform; + _gpuSwapchain->createInfo.compositeAlpha = compositeAlpha; + _gpuSwapchain->createInfo.presentMode = swapchainPresentMode; + _gpuSwapchain->createInfo.clipped = VK_TRUE; // Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area ///////////////////// Texture Creation ///////////////////// - _colorTexture = ccnew CCVKTexture; + _colorTexture = ccnew CCVKTexture; _depthStencilTexture = ccnew CCVKTexture; SwapchainTextureInfo textureInfo; textureInfo.swapchain = this; - textureInfo.format = colorFmt; - textureInfo.width = info.width; - textureInfo.height = info.height; + textureInfo.format = colorFmt; + textureInfo.width = info.width; + textureInfo.height = info.height; initTexture(textureInfo, _colorTexture); textureInfo.format = depthStencilFmt; @@ -216,8 +216,8 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { // Android Game Frame Pacing:swappy #if CC_SWAPPY_ENABLED - auto * platform = static_cast(cc::BasePlatform::getPlatform()); - int32_t fps = cc::BasePlatform::getPlatform()->getFps(); + auto *platform = static_cast(cc::BasePlatform::getPlatform()); + int32_t fps = cc::BasePlatform::getPlatform()->getFps(); uint64_t frameRefreshIntervalNS; SwappyVk_initAndGetRefreshCycleDuration(static_cast(platform->getEnv()), @@ -239,7 +239,7 @@ void CCVKSwapchain::doDestroy() { CC_SAFE_DESTROY(_depthStencilTexture) CC_SAFE_DESTROY(_colorTexture) - auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); destroySwapchain(gpuDevice); @@ -261,7 +261,7 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { if (_gpuSwapchain->vkSurface == VK_NULL_HANDLE) { // vkSurface will be set to VK_NULL_HANDLE after call doDestroySurface return false; } - auto * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); VkSurfaceCapabilitiesKHR surfaceCapabilities; @@ -270,7 +270,7 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { // surfaceCapabilities.currentExtent seems to remain the same // during any size/orientation change events on android devices // so we prefer the system input (oriented size) here - uint32_t newWidth = width ? width : surfaceCapabilities.currentExtent.width; + uint32_t newWidth = width ? width : surfaceCapabilities.currentExtent.width; uint32_t newHeight = height ? height : surfaceCapabilities.currentExtent.height; VkSurfaceTransformFlagBitsKHR preTransform = surfaceCapabilities.currentTransform; @@ -289,10 +289,10 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { } if (newWidth == static_cast(-1)) { - _gpuSwapchain->createInfo.imageExtent.width = _colorTexture->getWidth(); + _gpuSwapchain->createInfo.imageExtent.width = _colorTexture->getWidth(); _gpuSwapchain->createInfo.imageExtent.height = _colorTexture->getHeight(); } else { - _gpuSwapchain->createInfo.imageExtent.width = newWidth; + _gpuSwapchain->createInfo.imageExtent.width = newWidth; _gpuSwapchain->createInfo.imageExtent.height = newHeight; } @@ -301,9 +301,9 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { return false; } - _transform = mapSurfaceTransform(preTransform); + _transform = mapSurfaceTransform(preTransform); _gpuSwapchain->createInfo.preTransform = preTransform; - _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; + _gpuSwapchain->createInfo.surface = _gpuSwapchain->vkSurface; _gpuSwapchain->createInfo.oldSwapchain = _gpuSwapchain->vkSwapchain; CC_LOG_INFO("Resizing surface: %dx%d, surface rotation: %d degrees", newWidth, newHeight, (uint32_t)_transform * 90); @@ -316,8 +316,8 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { destroySwapchain(gpuDevice); gpuDevice->curBackBufferIndex = 0; - _gpuSwapchain->curImageIndex = 0; - _gpuSwapchain->vkSwapchain = vkSwapchain; + _gpuSwapchain->curImageIndex = 0; + _gpuSwapchain->vkSwapchain = vkSwapchain; uint32_t imageCount; VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, nullptr)); @@ -326,36 +326,36 @@ bool CCVKSwapchain::checkSwapchainStatus(uint32_t width, uint32_t height) { VK_CHECK(vkGetSwapchainImagesKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, &imageCount, _gpuSwapchain->swapchainImages.data())); // should skip size check, since the old swapchain has already been destroyed - static_cast(_colorTexture.get())->_info.width = 1; + static_cast(_colorTexture.get())->_info.width = 1; static_cast(_depthStencilTexture.get())->_info.width = 1; _colorTexture->resize(newWidth, newHeight); _depthStencilTexture->resize(newWidth, newHeight); - bool hasStencil = GFX_FORMAT_INFOS[toNumber(_depthStencilTexture->getFormat())].hasStencil; + bool hasStencil = GFX_FORMAT_INFOS[toNumber(_depthStencilTexture->getFormat())].hasStencil; ccstd::vector barriers(imageCount * 2, VkImageMemoryBarrier{}); - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - ThsvsImageBarrier tempBarrier{}; - tempBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - tempBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - tempBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; - tempBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - VkPipelineStageFlags tempSrcStageMask = 0; - VkPipelineStageFlags tempDstStageMask = 0; - auto * colorGPUTexture = static_cast(_colorTexture.get())->gpuTexture(); - auto * depthStencilGPUTexture = static_cast(_depthStencilTexture.get())->gpuTexture(); + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + ThsvsImageBarrier tempBarrier{}; + tempBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + tempBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + tempBarrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; + tempBarrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; + VkPipelineStageFlags tempSrcStageMask = 0; + VkPipelineStageFlags tempDstStageMask = 0; + auto *colorGPUTexture = static_cast(_colorTexture.get())->gpuTexture(); + auto *depthStencilGPUTexture = static_cast(_depthStencilTexture.get())->gpuTexture(); for (uint32_t i = 0U; i < imageCount; i++) { - tempBarrier.nextAccessCount = 1; - tempBarrier.pNextAccesses = getAccessType(AccessFlagBit::PRESENT); - tempBarrier.image = _gpuSwapchain->swapchainImages[i]; + tempBarrier.nextAccessCount = 1; + tempBarrier.pNextAccesses = getAccessType(AccessFlagBit::PRESENT); + tempBarrier.image = _gpuSwapchain->swapchainImages[i]; tempBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[i]); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; - tempBarrier.nextAccessCount = 1; - tempBarrier.pNextAccesses = getAccessType(AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE); - tempBarrier.image = depthStencilGPUTexture->swapchainVkImages[i]; + tempBarrier.nextAccessCount = 1; + tempBarrier.pNextAccesses = getAccessType(AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE); + tempBarrier.image = depthStencilGPUTexture->swapchainVkImages[i]; tempBarrier.subresourceRange.aspectMask = hasStencil ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; thsvsGetVulkanImageMemoryBarrier(tempBarrier, &tempSrcStageMask, &tempDstStageMask, &barriers[imageCount + i]); srcStageMask |= tempSrcStageMask; @@ -399,7 +399,7 @@ void CCVKSwapchain::destroySwapchain(const CCVKGPUDevice *gpuDevice) { void CCVKSwapchain::doDestroySurface() { if (!_gpuSwapchain || _gpuSwapchain->vkSurface == VK_NULL_HANDLE) return; - const auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + const auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); const auto *gpuContext = CCVKDevice::getInstance()->gpuContext(); CCVKDevice::getInstance()->waitAllFences(); @@ -430,7 +430,7 @@ void CCVKSwapchain::createVkSurface() { #elif defined(VK_USE_PLATFORM_WIN32_KHR) VkWin32SurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; surfaceCreateInfo.hinstance = static_cast(GetModuleHandle(nullptr)); - surfaceCreateInfo.hwnd = reinterpret_cast(_windowHandle); + surfaceCreateInfo.hwnd = reinterpret_cast(_windowHandle); VK_CHECK(vkCreateWin32SurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); #elif defined(VK_USE_PLATFORM_VI_NN) VkViSurfaceCreateInfoNN surfaceCreateInfo{VK_STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN}; @@ -448,7 +448,7 @@ void CCVKSwapchain::createVkSurface() { #elif defined(VK_USE_PLATFORM_XCB_KHR) VkXcbSurfaceCreateInfoKHR surfaceCreateInfo{VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR}; surfaceCreateInfo.connection = nullptr; // TODO - surfaceCreateInfo.window = reinterpret_cast(_windowHandle); + surfaceCreateInfo.window = reinterpret_cast(_windowHandle); VK_CHECK(vkCreateXcbSurfaceKHR(gpuContext->vkInstance, &surfaceCreateInfo, nullptr, &_gpuSwapchain->vkSurface)); #else #pragma error Platform not supported diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index cccd3f3e8d..3f68664b56 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -42,18 +42,18 @@ CCVKTexture::~CCVKTexture() { } void CCVKTexture::doInit(const TextureInfo & /*info*/) { - _gpuTexture = ccnew CCVKGPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew CCVKGPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayers = _info.layerCount; - _gpuTexture->mipLevels = _info.levelCount; - _gpuTexture->samples = _info.samples; - _gpuTexture->flags = _info.flags; - _gpuTexture->size = _size; + _gpuTexture->mipLevels = _info.levelCount; + _gpuTexture->samples = _info.samples; + _gpuTexture->flags = _info.flags; + _gpuTexture->size = _size; cmdFuncCCVKCreateTexture(CCVKDevice::getInstance(), _gpuTexture); @@ -75,11 +75,11 @@ void CCVKTexture::doInit(const TextureViewInfo &info) { void CCVKTexture::createTextureView() { _gpuTextureView->gpuTexture = _gpuTexture; - _gpuTextureView->type = _viewInfo.type; - _gpuTextureView->format = _viewInfo.format; - _gpuTextureView->baseLevel = _viewInfo.baseLevel; + _gpuTextureView->type = _viewInfo.type; + _gpuTextureView->format = _viewInfo.format; + _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; - _gpuTextureView->baseLayer = _viewInfo.baseLayer; + _gpuTextureView->baseLayer = _viewInfo.baseLayer; _gpuTextureView->layerCount = _viewInfo.layerCount; cmdFuncCCVKCreateTextureView(CCVKDevice::getInstance(), _gpuTextureView); } @@ -118,9 +118,9 @@ void CCVKTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuTextureView); CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuTexture); - _gpuTexture->width = width; - _gpuTexture->height = height; - _gpuTexture->size = size; + _gpuTexture->width = width; + _gpuTexture->height = height; + _gpuTexture->size = size; _gpuTexture->mipLevels = _info.levelCount; cmdFuncCCVKCreateTexture(CCVKDevice::getInstance(), _gpuTexture); @@ -138,29 +138,29 @@ void CCVKTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { ///////////////////////////// Swapchain Specific ///////////////////////////// void CCVKTexture::doInit(const SwapchainTextureInfo & /*info*/) { - _gpuTexture = ccnew CCVKGPUTexture; - _gpuTexture->type = _info.type; - _gpuTexture->format = _info.format; - _gpuTexture->usage = _info.usage; - _gpuTexture->width = _info.width; - _gpuTexture->height = _info.height; - _gpuTexture->depth = _info.depth; + _gpuTexture = ccnew CCVKGPUTexture; + _gpuTexture->type = _info.type; + _gpuTexture->format = _info.format; + _gpuTexture->usage = _info.usage; + _gpuTexture->width = _info.width; + _gpuTexture->height = _info.height; + _gpuTexture->depth = _info.depth; _gpuTexture->arrayLayers = _info.layerCount; - _gpuTexture->mipLevels = _info.levelCount; - _gpuTexture->flags = _info.flags; - _gpuTexture->samples = _info.samples; - _gpuTexture->size = _size; + _gpuTexture->mipLevels = _info.levelCount; + _gpuTexture->flags = _info.flags; + _gpuTexture->samples = _info.samples; + _gpuTexture->size = _size; - _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); + _gpuTexture->swapchain = static_cast(_swapchain)->gpuSwapchain(); _gpuTexture->memoryless = true; - _gpuTextureView = ccnew CCVKGPUTextureView; + _gpuTextureView = ccnew CCVKGPUTextureView; _gpuTextureView->gpuTexture = _gpuTexture; - _gpuTextureView->type = _viewInfo.type; - _gpuTextureView->format = _viewInfo.format; - _gpuTextureView->baseLevel = _viewInfo.baseLevel; + _gpuTextureView->type = _viewInfo.type; + _gpuTextureView->format = _viewInfo.format; + _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; - _gpuTextureView->baseLayer = _viewInfo.baseLayer; + _gpuTextureView->baseLayer = _viewInfo.baseLayer; _gpuTextureView->layerCount = _viewInfo.layerCount; } diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.h b/native/cocos/renderer/gfx-vulkan/VKTexture.h index 02d79e23f0..c7bc96c97f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.h +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.h @@ -39,7 +39,7 @@ public: CCVKTexture(); ~CCVKTexture() override; - inline CCVKGPUTexture * gpuTexture() const { return _gpuTexture; } + inline CCVKGPUTexture *gpuTexture() const { return _gpuTexture; } inline CCVKGPUTextureView *gpuTextureView() const { return _gpuTextureView; } protected: @@ -53,7 +53,7 @@ protected: void createTextureView(); - CCVKGPUTexture * _gpuTexture = nullptr; + CCVKGPUTexture *_gpuTexture = nullptr; CCVKGPUTextureView *_gpuTextureView = nullptr; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 595aff2bda..d4c1af55f5 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -244,7 +244,7 @@ VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage) { VkImageAspectFlags mapVkImageAspectFlags(Format format) { VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - const FormatInfo & info = GFX_FORMAT_INFOS[toNumber(format)]; + const FormatInfo &info = GFX_FORMAT_INFOS[toNumber(format)]; if (info.hasDepth) aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if (info.hasStencil) aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; return aspectMask; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 8369b82e6b..4fba30dca9 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -52,50 +52,50 @@ namespace gfx { class CCVKGPUDevice; -VkQueryType mapVkQueryType(QueryType type); -VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice); -VkAttachmentLoadOp mapVkLoadOp(LoadOp loadOp); -VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); +VkQueryType mapVkQueryType(QueryType type); +VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice); +VkAttachmentLoadOp mapVkLoadOp(LoadOp loadOp); +VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); VkBufferUsageFlagBits mapVkBufferUsageFlagBits(BufferUsage usage); -VkImageType mapVkImageType(TextureType type); -VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage); -VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage); -VkImageAspectFlags mapVkImageAspectFlags(Format format); -VkImageCreateFlags mapVkImageCreateFlags(TextureType type); -VkImageViewType mapVkImageViewType(TextureType viewType); -VkCommandBufferLevel mapVkCommandBufferLevel(CommandBufferType type); -VkDescriptorType mapVkDescriptorType(DescriptorType type); +VkImageType mapVkImageType(TextureType type); +VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage); +VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage); +VkImageAspectFlags mapVkImageAspectFlags(Format format); +VkImageCreateFlags mapVkImageCreateFlags(TextureType type); +VkImageViewType mapVkImageViewType(TextureType viewType); +VkCommandBufferLevel mapVkCommandBufferLevel(CommandBufferType type); +VkDescriptorType mapVkDescriptorType(DescriptorType type); VkColorComponentFlags mapVkColorComponentFlags(ColorMask colorMask); VkShaderStageFlagBits mapVkShaderStageFlagBits(ShaderStageFlagBit stage); -VkShaderStageFlags mapVkShaderStageFlags(ShaderStageFlagBit stages); -SurfaceTransform mapSurfaceTransform(VkSurfaceTransformFlagBitsKHR transform); -ccstd::string mapVendorName(uint32_t vendorID); +VkShaderStageFlags mapVkShaderStageFlags(ShaderStageFlagBit stages); +SurfaceTransform mapSurfaceTransform(VkSurfaceTransformFlagBitsKHR transform); +ccstd::string mapVendorName(uint32_t vendorID); -void fullPipelineBarrier(VkCommandBuffer cmdBuff); +void fullPipelineBarrier(VkCommandBuffer cmdBuff); const ThsvsAccessType *getAccessType(AccessFlagBit flag); -void getAccessTypes(AccessFlags flag, ccstd::vector &v); -VkDeviceSize roundUp(VkDeviceSize numToRound, uint32_t multiple); -bool isLayerSupported(const char *required, const ccstd::vector &available); -bool isExtensionSupported(const char *required, const ccstd::vector &available); -bool isFormatSupported(VkPhysicalDevice device, VkFormat format); +void getAccessTypes(AccessFlags flag, ccstd::vector &v); +VkDeviceSize roundUp(VkDeviceSize numToRound, uint32_t multiple); +bool isLayerSupported(const char *required, const ccstd::vector &available); +bool isExtensionSupported(const char *required, const ccstd::vector &available); +bool isFormatSupported(VkPhysicalDevice device, VkFormat format); extern const VkSurfaceTransformFlagsKHR TRANSFORMS_THAT_REQUIRE_FLIPPING; -extern const VkPrimitiveTopology VK_PRIMITIVE_MODES[]; -extern const VkCullModeFlags VK_CULL_MODES[]; -extern const VkPolygonMode VK_POLYGON_MODES[]; -extern const VkCompareOp VK_CMP_FUNCS[]; -extern const VkStencilOp VK_STENCIL_OPS[]; -extern const VkBlendOp VK_BLEND_OPS[]; -extern const VkBlendFactor VK_BLEND_FACTORS[]; -extern const VkFilter VK_FILTERS[]; -extern const VkSamplerMipmapMode VK_SAMPLER_MIPMAP_MODES[]; -extern const VkSamplerAddressMode VK_SAMPLER_ADDRESS_MODES[]; -extern const VkPipelineBindPoint VK_PIPELINE_BIND_POINTS[]; -extern const VkResolveModeFlagBits VK_RESOLVE_MODES[]; -extern const VkImageLayout VK_IMAGE_LAYOUTS[]; -extern const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[]; -extern const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[]; -extern const VkAccessFlags FULL_ACCESS_FLAGS; +extern const VkPrimitiveTopology VK_PRIMITIVE_MODES[]; +extern const VkCullModeFlags VK_CULL_MODES[]; +extern const VkPolygonMode VK_POLYGON_MODES[]; +extern const VkCompareOp VK_CMP_FUNCS[]; +extern const VkStencilOp VK_STENCIL_OPS[]; +extern const VkBlendOp VK_BLEND_OPS[]; +extern const VkBlendFactor VK_BLEND_FACTORS[]; +extern const VkFilter VK_FILTERS[]; +extern const VkSamplerMipmapMode VK_SAMPLER_MIPMAP_MODES[]; +extern const VkSamplerAddressMode VK_SAMPLER_ADDRESS_MODES[]; +extern const VkPipelineBindPoint VK_PIPELINE_BIND_POINTS[]; +extern const VkResolveModeFlagBits VK_RESOLVE_MODES[]; +extern const VkImageLayout VK_IMAGE_LAYOUTS[]; +extern const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[]; +extern const VkSampleCountFlags VK_SAMPLE_COUNT_FLAGS[]; +extern const VkAccessFlags FULL_ACCESS_FLAGS; } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp b/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp index bb423c8566..a3c0bd5bef 100644 --- a/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKSampler.cpp @@ -33,15 +33,15 @@ namespace gfx { CCVKSampler::CCVKSampler(const SamplerInfo &info) : Sampler(info) { _typedID = generateObjectID(); - _gpuSampler = ccnew CCVKGPUSampler; - _gpuSampler->minFilter = _info.minFilter; - _gpuSampler->magFilter = _info.magFilter; - _gpuSampler->mipFilter = _info.mipFilter; - _gpuSampler->addressU = _info.addressU; - _gpuSampler->addressV = _info.addressV; - _gpuSampler->addressW = _info.addressW; + _gpuSampler = ccnew CCVKGPUSampler; + _gpuSampler->minFilter = _info.minFilter; + _gpuSampler->magFilter = _info.magFilter; + _gpuSampler->mipFilter = _info.mipFilter; + _gpuSampler->addressU = _info.addressU; + _gpuSampler->addressV = _info.addressV; + _gpuSampler->addressW = _info.addressW; _gpuSampler->maxAnisotropy = _info.maxAnisotropy; - _gpuSampler->cmpFunc = _info.cmpFunc; + _gpuSampler->cmpFunc = _info.cmpFunc; cmdFuncCCVKCreateSampler(CCVKDevice::getInstance(), _gpuSampler); } diff --git a/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp index d8da3e3ca7..b7beef973d 100644 --- a/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp +++ b/native/cocos/renderer/gfx-vulkan/states/VKTextureBarrier.cpp @@ -38,22 +38,22 @@ CCVKTextureBarrier::CCVKTextureBarrier(const TextureBarrierInfo &info) : Texture getAccessTypes(info.nextAccesses, _gpuBarrier->nextAccesses); _gpuBarrier->barrier.prevAccessCount = utils::toUint(_gpuBarrier->prevAccesses.size()); - _gpuBarrier->barrier.pPrevAccesses = _gpuBarrier->prevAccesses.data(); + _gpuBarrier->barrier.pPrevAccesses = _gpuBarrier->prevAccesses.data(); _gpuBarrier->barrier.nextAccessCount = utils::toUint(_gpuBarrier->nextAccesses.size()); - _gpuBarrier->barrier.pNextAccesses = _gpuBarrier->nextAccesses.data(); + _gpuBarrier->barrier.pNextAccesses = _gpuBarrier->nextAccesses.data(); _gpuBarrier->barrier.prevLayout = _gpuBarrier->barrier.nextLayout = THSVS_IMAGE_LAYOUT_OPTIMAL; - _gpuBarrier->barrier.discardContents = !!info.discardContents; - _gpuBarrier->barrier.subresourceRange.baseMipLevel = 0U; - _gpuBarrier->barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; - _gpuBarrier->barrier.subresourceRange.baseArrayLayer = 0U; - _gpuBarrier->barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - _gpuBarrier->barrier.srcQueueFamilyIndex = info.srcQueue - ? static_cast(info.srcQueue)->gpuQueue()->queueFamilyIndex - : VK_QUEUE_FAMILY_IGNORED; - _gpuBarrier->barrier.dstQueueFamilyIndex = info.dstQueue - ? static_cast(info.dstQueue)->gpuQueue()->queueFamilyIndex - : VK_QUEUE_FAMILY_IGNORED; + _gpuBarrier->barrier.discardContents = !!info.discardContents; + _gpuBarrier->barrier.subresourceRange.baseMipLevel = 0U; + _gpuBarrier->barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; + _gpuBarrier->barrier.subresourceRange.baseArrayLayer = 0U; + _gpuBarrier->barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; + _gpuBarrier->barrier.srcQueueFamilyIndex = info.srcQueue + ? static_cast(info.srcQueue)->gpuQueue()->queueFamilyIndex + : VK_QUEUE_FAMILY_IGNORED; + _gpuBarrier->barrier.dstQueueFamilyIndex = info.dstQueue + ? static_cast(info.dstQueue)->gpuQueue()->queueFamilyIndex + : VK_QUEUE_FAMILY_IGNORED; thsvsGetVulkanImageMemoryBarrier(_gpuBarrier->barrier, &_gpuBarrier->srcStageMask, &_gpuBarrier->dstStageMask, &_gpuBarrier->vkBarrier); } diff --git a/native/cocos/renderer/gfx-vulkan/thsvs_simpler_vulkan_synchronization.h b/native/cocos/renderer/gfx-vulkan/thsvs_simpler_vulkan_synchronization.h index d63b2c2dd9..67d6f07530 100644 --- a/native/cocos/renderer/gfx-vulkan/thsvs_simpler_vulkan_synchronization.h +++ b/native/cocos/renderer/gfx-vulkan/thsvs_simpler_vulkan_synchronization.h @@ -179,104 +179,104 @@ ISSUES ThsvsAccessType defines all potential resource usages in the Vulkan API. */ typedef enum ThsvsAccessType { - THSVS_ACCESS_NONE, // No access. Useful primarily for initialization + THSVS_ACCESS_NONE, // No access. Useful primarily for initialization -// Read access + // Read access // Requires VK_NV_device_generated_commands to be enabled - THSVS_ACCESS_COMMAND_BUFFER_READ_NV, // Command buffer read operation as defined by NV_device_generated_commands - THSVS_ACCESS_INDIRECT_BUFFER, // Read as an indirect buffer for drawing or dispatch - THSVS_ACCESS_INDEX_BUFFER, // Read as an index buffer for drawing - THSVS_ACCESS_VERTEX_BUFFER, // Read as a vertex buffer for drawing - THSVS_ACCESS_VERTEX_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a vertex shader - THSVS_ACCESS_VERTEX_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a vertex shader - THSVS_ACCESS_VERTEX_SHADER_READ_OTHER, // Read as any other resource in a vertex shader - THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a tessellation control shader - THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a tessellation control shader - THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_OTHER, // Read as any other resource in a tessellation control shader - THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a tessellation evaluation shader + THSVS_ACCESS_COMMAND_BUFFER_READ_NV, // Command buffer read operation as defined by NV_device_generated_commands + THSVS_ACCESS_INDIRECT_BUFFER, // Read as an indirect buffer for drawing or dispatch + THSVS_ACCESS_INDEX_BUFFER, // Read as an index buffer for drawing + THSVS_ACCESS_VERTEX_BUFFER, // Read as a vertex buffer for drawing + THSVS_ACCESS_VERTEX_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a vertex shader + THSVS_ACCESS_VERTEX_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a vertex shader + THSVS_ACCESS_VERTEX_SHADER_READ_OTHER, // Read as any other resource in a vertex shader + THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a tessellation control shader + THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a tessellation control shader + THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_OTHER, // Read as any other resource in a tessellation control shader + THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a tessellation evaluation shader THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a tessellation evaluation shader - THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_OTHER, // Read as any other resource in a tessellation evaluation shader - THSVS_ACCESS_GEOMETRY_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a geometry shader - THSVS_ACCESS_GEOMETRY_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER,// Read as a sampled image/uniform texel buffer in a geometry shader - THSVS_ACCESS_GEOMETRY_SHADER_READ_OTHER, // Read as any other resource in a geometry shader - THSVS_ACCESS_TASK_SHADER_READ_UNIFORM_BUFFER_NV, // Read as a uniform buffer in a task shader - THSVS_ACCESS_TASK_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV, // Read as a sampled image/uniform texel buffer in a task shader - THSVS_ACCESS_TASK_SHADER_READ_OTHER_NV, // Read as any other resource in a task shader - THSVS_ACCESS_MESH_SHADER_READ_UNIFORM_BUFFER_NV, // Read as a uniform buffer in a mesh shader - THSVS_ACCESS_MESH_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV, // Read as a sampled image/uniform texel buffer in a mesh shader - THSVS_ACCESS_MESH_SHADER_READ_OTHER_NV, // Read as any other resource in a mesh shader - THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_EXT, // Read as a transform feedback counter buffer - THSVS_ACCESS_FRAGMENT_DENSITY_MAP_READ_EXT, // Read as a fragment density map image - THSVS_ACCESS_SHADING_RATE_READ_NV, // Read as a shading rate image - THSVS_ACCESS_FRAGMENT_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a fragment shader - THSVS_ACCESS_FRAGMENT_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER,// Read as a sampled image/uniform texel buffer in a fragment shader - THSVS_ACCESS_FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT, // Read as an input attachment with a color format in a fragment shader - THSVS_ACCESS_FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT, // Read as an input attachment with a depth/stencil format in a fragment shader - THSVS_ACCESS_FRAGMENT_SHADER_READ_OTHER, // Read as any other resource in a fragment shader - THSVS_ACCESS_COLOR_ATTACHMENT_READ, // Read by standard blending/logic operations or subpass load operations - THSVS_ACCESS_COLOR_ATTACHMENT_ADVANCED_BLENDING_EXT, // Read by advanced blending, standard blending, logic operations, or subpass load operations - THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ, // Read by depth/stencil tests or subpass load operations - THSVS_ACCESS_COMPUTE_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a compute shader - THSVS_ACCESS_COMPUTE_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a compute shader - THSVS_ACCESS_COMPUTE_SHADER_READ_OTHER, // Read as any other resource in a compute shader - THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in any shader - THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER_OR_VERTEX_BUFFER, // Read as a uniform buffer in any shader, or a vertex buffer - THSVS_ACCESS_ANY_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image in any shader - THSVS_ACCESS_ANY_SHADER_READ_OTHER, // Read as any other resource (excluding attachments) in any shader - THSVS_ACCESS_TRANSFER_READ, // Read as the source of a transfer operation - THSVS_ACCESS_HOST_READ, // Read on the host + THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_OTHER, // Read as any other resource in a tessellation evaluation shader + THSVS_ACCESS_GEOMETRY_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a geometry shader + THSVS_ACCESS_GEOMETRY_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a geometry shader + THSVS_ACCESS_GEOMETRY_SHADER_READ_OTHER, // Read as any other resource in a geometry shader + THSVS_ACCESS_TASK_SHADER_READ_UNIFORM_BUFFER_NV, // Read as a uniform buffer in a task shader + THSVS_ACCESS_TASK_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV, // Read as a sampled image/uniform texel buffer in a task shader + THSVS_ACCESS_TASK_SHADER_READ_OTHER_NV, // Read as any other resource in a task shader + THSVS_ACCESS_MESH_SHADER_READ_UNIFORM_BUFFER_NV, // Read as a uniform buffer in a mesh shader + THSVS_ACCESS_MESH_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV, // Read as a sampled image/uniform texel buffer in a mesh shader + THSVS_ACCESS_MESH_SHADER_READ_OTHER_NV, // Read as any other resource in a mesh shader + THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_EXT, // Read as a transform feedback counter buffer + THSVS_ACCESS_FRAGMENT_DENSITY_MAP_READ_EXT, // Read as a fragment density map image + THSVS_ACCESS_SHADING_RATE_READ_NV, // Read as a shading rate image + THSVS_ACCESS_FRAGMENT_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a fragment shader + THSVS_ACCESS_FRAGMENT_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a fragment shader + THSVS_ACCESS_FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT, // Read as an input attachment with a color format in a fragment shader + THSVS_ACCESS_FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT, // Read as an input attachment with a depth/stencil format in a fragment shader + THSVS_ACCESS_FRAGMENT_SHADER_READ_OTHER, // Read as any other resource in a fragment shader + THSVS_ACCESS_COLOR_ATTACHMENT_READ, // Read by standard blending/logic operations or subpass load operations + THSVS_ACCESS_COLOR_ATTACHMENT_ADVANCED_BLENDING_EXT, // Read by advanced blending, standard blending, logic operations, or subpass load operations + THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ, // Read by depth/stencil tests or subpass load operations + THSVS_ACCESS_COMPUTE_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in a compute shader + THSVS_ACCESS_COMPUTE_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image/uniform texel buffer in a compute shader + THSVS_ACCESS_COMPUTE_SHADER_READ_OTHER, // Read as any other resource in a compute shader + THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER, // Read as a uniform buffer in any shader + THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER_OR_VERTEX_BUFFER, // Read as a uniform buffer in any shader, or a vertex buffer + THSVS_ACCESS_ANY_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER, // Read as a sampled image in any shader + THSVS_ACCESS_ANY_SHADER_READ_OTHER, // Read as any other resource (excluding attachments) in any shader + THSVS_ACCESS_TRANSFER_READ, // Read as the source of a transfer operation + THSVS_ACCESS_HOST_READ, // Read on the host // Requires VK_KHR_swapchain to be enabled - THSVS_ACCESS_PRESENT, // Read by the presentation engine (i.e. vkQueuePresentKHR) + THSVS_ACCESS_PRESENT, // Read by the presentation engine (i.e. vkQueuePresentKHR) // Requires VK_EXT_conditional_rendering to be enabled - THSVS_ACCESS_CONDITIONAL_RENDERING_READ_EXT, // Read by conditional rendering + THSVS_ACCESS_CONDITIONAL_RENDERING_READ_EXT, // Read by conditional rendering // Requires VK_NV_ray_tracing to be enabled - THSVS_ACCESS_RAY_TRACING_SHADER_ACCELERATION_STRUCTURE_READ_NV, // Read by a ray tracing shader as an acceleration structure - THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_READ_NV, // Read as an acceleration structure during a build + THSVS_ACCESS_RAY_TRACING_SHADER_ACCELERATION_STRUCTURE_READ_NV, // Read by a ray tracing shader as an acceleration structure + THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_READ_NV, // Read as an acceleration structure during a build // Read accesses end THSVS_END_OF_READ_ACCESS, -// Write access + // Write access // Requires VK_NV_device_generated_commands to be enabled - THSVS_ACCESS_COMMAND_BUFFER_WRITE_NV, // Command buffer write operation - THSVS_ACCESS_VERTEX_SHADER_WRITE, // Written as any resource in a vertex shader - THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_WRITE, // Written as any resource in a tessellation control shader - THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_WRITE, // Written as any resource in a tessellation evaluation shader - THSVS_ACCESS_GEOMETRY_SHADER_WRITE, // Written as any resource in a geometry shader + THSVS_ACCESS_COMMAND_BUFFER_WRITE_NV, // Command buffer write operation + THSVS_ACCESS_VERTEX_SHADER_WRITE, // Written as any resource in a vertex shader + THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_WRITE, // Written as any resource in a tessellation control shader + THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_WRITE, // Written as any resource in a tessellation evaluation shader + THSVS_ACCESS_GEOMETRY_SHADER_WRITE, // Written as any resource in a geometry shader // Requires VK_NV_mesh_shading to be enabled - THSVS_ACCESS_TASK_SHADER_WRITE_NV, // Written as any resource in a task shader - THSVS_ACCESS_MESH_SHADER_WRITE_NV, // Written as any resource in a mesh shader + THSVS_ACCESS_TASK_SHADER_WRITE_NV, // Written as any resource in a task shader + THSVS_ACCESS_MESH_SHADER_WRITE_NV, // Written as any resource in a mesh shader // Requires VK_EXT_transform_feedback to be enabled - THSVS_ACCESS_TRANSFORM_FEEDBACK_WRITE_EXT, // Written as a transform feedback buffer - THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_EXT, // Written as a transform feedback counter buffer + THSVS_ACCESS_TRANSFORM_FEEDBACK_WRITE_EXT, // Written as a transform feedback buffer + THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_EXT, // Written as a transform feedback counter buffer - THSVS_ACCESS_FRAGMENT_SHADER_WRITE, // Written as any resource in a fragment shader - THSVS_ACCESS_COLOR_ATTACHMENT_WRITE, // Written as a color attachment during rendering, or via a subpass store op - THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE, // Written as a depth/stencil attachment during rendering, or via a subpass store op + THSVS_ACCESS_FRAGMENT_SHADER_WRITE, // Written as any resource in a fragment shader + THSVS_ACCESS_COLOR_ATTACHMENT_WRITE, // Written as a color attachment during rendering, or via a subpass store op + THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE, // Written as a depth/stencil attachment during rendering, or via a subpass store op // Requires VK_KHR_maintenance2 to be enabled - THSVS_ACCESS_DEPTH_ATTACHMENT_WRITE_STENCIL_READ_ONLY, // Written as a depth aspect of a depth/stencil attachment during rendering, whilst the stencil aspect is read-only - THSVS_ACCESS_STENCIL_ATTACHMENT_WRITE_DEPTH_READ_ONLY, // Written as a stencil aspect of a depth/stencil attachment during rendering, whilst the depth aspect is read-only + THSVS_ACCESS_DEPTH_ATTACHMENT_WRITE_STENCIL_READ_ONLY, // Written as a depth aspect of a depth/stencil attachment during rendering, whilst the stencil aspect is read-only + THSVS_ACCESS_STENCIL_ATTACHMENT_WRITE_DEPTH_READ_ONLY, // Written as a stencil aspect of a depth/stencil attachment during rendering, whilst the depth aspect is read-only - THSVS_ACCESS_COMPUTE_SHADER_WRITE, // Written as any resource in a compute shader - THSVS_ACCESS_ANY_SHADER_WRITE, // Written as any resource in any shader - THSVS_ACCESS_TRANSFER_WRITE, // Written as the destination of a transfer operation - THSVS_ACCESS_HOST_PREINITIALIZED, // Data pre-filled by host before device access starts - THSVS_ACCESS_HOST_WRITE, // Written on the host + THSVS_ACCESS_COMPUTE_SHADER_WRITE, // Written as any resource in a compute shader + THSVS_ACCESS_ANY_SHADER_WRITE, // Written as any resource in any shader + THSVS_ACCESS_TRANSFER_WRITE, // Written as the destination of a transfer operation + THSVS_ACCESS_HOST_PREINITIALIZED, // Data pre-filled by host before device access starts + THSVS_ACCESS_HOST_WRITE, // Written on the host // Requires VK_NV_ray_tracing to be enabled - THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_WRITE_NV, // Written as an acceleration structure during a build + THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_WRITE_NV, // Written as an acceleration structure during a build - THSVS_ACCESS_COLOR_ATTACHMENT_READ_WRITE, // Read or written as a color attachment during rendering -// General access - THSVS_ACCESS_GENERAL, // Covers any access - useful for debug, generally avoid for performance reasons + THSVS_ACCESS_COLOR_ATTACHMENT_READ_WRITE, // Read or written as a color attachment during rendering + // General access + THSVS_ACCESS_GENERAL, // Covers any access - useful for debug, generally avoid for performance reasons -// Number of access types + // Number of access types THSVS_NUM_ACCESS_TYPES } ThsvsAccessType; @@ -287,8 +287,8 @@ correlated with the access types to map to the correct Vulkan layouts. THSVS_IMAGE_LAYOUT_OPTIMAL is usually preferred. */ typedef enum ThsvsImageLayout { - THSVS_IMAGE_LAYOUT_OPTIMAL, // Choose the most optimal layout for each usage. Performs layout transitions as appropriate for the access. - THSVS_IMAGE_LAYOUT_GENERAL, // Layout accessible by all Vulkan access types on a device - no layout transitions except for presentation + THSVS_IMAGE_LAYOUT_OPTIMAL, // Choose the most optimal layout for each usage. Performs layout transitions as appropriate for the access. + THSVS_IMAGE_LAYOUT_GENERAL, // Layout accessible by all Vulkan access types on a device - no layout transitions except for presentation // Requires VK_KHR_shared_presentable_image to be enabled. Can only be used for shared presentable images (i.e. single-buffered swap chains). THSVS_IMAGE_LAYOUT_GENERAL_AND_PRESENTATION // As GENERAL, but also allows presentation engines to access it - no layout transitions @@ -302,10 +302,10 @@ layouts) then a global barrier should be preferred. Simply define the previous and next access types of resources affected. */ typedef struct ThsvsGlobalBarrier { - uint32_t prevAccessCount; - const ThsvsAccessType* pPrevAccesses; - uint32_t nextAccessCount; - const ThsvsAccessType* pNextAccesses; + uint32_t prevAccessCount; + const ThsvsAccessType* pPrevAccesses; + uint32_t nextAccessCount; + const ThsvsAccessType* pNextAccesses; } ThsvsGlobalBarrier; /* @@ -324,15 +324,15 @@ queue in the destination queue family, with a semaphore guaranteeing execution order between them. */ typedef struct ThsvsBufferBarrier { - uint32_t prevAccessCount; - const ThsvsAccessType* pPrevAccesses; - uint32_t nextAccessCount; - const ThsvsAccessType* pNextAccesses; - uint32_t srcQueueFamilyIndex; - uint32_t dstQueueFamilyIndex; - VkBuffer buffer; - VkDeviceSize offset; - VkDeviceSize size; + uint32_t prevAccessCount; + const ThsvsAccessType* pPrevAccesses; + uint32_t nextAccessCount; + const ThsvsAccessType* pNextAccesses; + uint32_t srcQueueFamilyIndex; + uint32_t dstQueueFamilyIndex; + VkBuffer buffer; + VkDeviceSize offset; + VkDeviceSize size; } ThsvsBufferBarrier; /* @@ -362,16 +362,16 @@ going to be immediately overwritten. A good example of when to use this is when an application re-uses a presented image after vkAcquireNextImageKHR. */ typedef struct ThsvsImageBarrier { - uint32_t prevAccessCount; - const ThsvsAccessType* pPrevAccesses; - uint32_t nextAccessCount; - const ThsvsAccessType* pNextAccesses; - ThsvsImageLayout prevLayout; - ThsvsImageLayout nextLayout; - VkBool32 discardContents; - uint32_t srcQueueFamilyIndex; - uint32_t dstQueueFamilyIndex; - VkImage image; + uint32_t prevAccessCount; + const ThsvsAccessType* pPrevAccesses; + uint32_t nextAccessCount; + const ThsvsAccessType* pNextAccesses; + ThsvsImageLayout prevLayout; + ThsvsImageLayout nextLayout; + VkBool32 discardContents; + uint32_t srcQueueFamilyIndex; + uint32_t dstQueueFamilyIndex; + VkImage image; VkImageSubresourceRange subresourceRange; } ThsvsImageBarrier; @@ -380,12 +380,12 @@ Mapping function that translates a set of accesses into the corresponding pipeline stages, VkAccessFlags, and image layout. */ void thsvsGetAccessInfo( - uint32_t accessCount, + uint32_t accessCount, const ThsvsAccessType* pAccesses, - VkPipelineStageFlags* pStageMask, - VkAccessFlags* pAccessMask, - VkImageLayout* pImageLayout, - bool* pHasWriteAccess); + VkPipelineStageFlags* pStageMask, + VkAccessFlags* pAccessMask, + VkImageLayout* pImageLayout, + bool* pHasWriteAccess); /* Mapping function that translates a global barrier into a set of source and @@ -394,9 +394,9 @@ Vulkan's synchronization methods. */ void thsvsGetVulkanMemoryBarrier( const ThsvsGlobalBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkMemoryBarrier* pVkBarrier); + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkMemoryBarrier* pVkBarrier); /* Mapping function that translates a buffer barrier into a set of source and @@ -405,9 +405,9 @@ with Vulkan's synchronization methods. */ void thsvsGetVulkanBufferMemoryBarrier( const ThsvsBufferBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkBufferMemoryBarrier* pVkBarrier); + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkBufferMemoryBarrier* pVkBarrier); /* Mapping function that translates an image barrier into a set of source and @@ -416,9 +416,9 @@ with Vulkan's synchronization methods. */ void thsvsGetVulkanImageMemoryBarrier( const ThsvsImageBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkImageMemoryBarrier* pVkBarrier); + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkImageMemoryBarrier* pVkBarrier); /* Simplified wrapper around vkCmdPipelineBarrier. @@ -430,12 +430,12 @@ barriers to be passed to vkCmdPipelineBarrier. commandBuffer is passed unmodified to vkCmdPipelineBarrier. */ void thsvsCmdPipelineBarrier( - VkCommandBuffer commandBuffer, + VkCommandBuffer commandBuffer, const ThsvsGlobalBarrier* pGlobalBarrier, - uint32_t bufferBarrierCount, + uint32_t bufferBarrierCount, const ThsvsBufferBarrier* pBufferBarriers, - uint32_t imageBarrierCount, - const ThsvsImageBarrier* pImageBarriers); + uint32_t imageBarrierCount, + const ThsvsImageBarrier* pImageBarriers); /* Wrapper around vkCmdSetEvent. @@ -445,10 +445,10 @@ Sets an event when the accesses defined by pPrevAccesses are completed. commandBuffer and event are passed unmodified to vkCmdSetEvent. */ void thsvsCmdSetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - uint32_t prevAccessCount, - const ThsvsAccessType* pPrevAccesses); + VkCommandBuffer commandBuffer, + VkEvent event, + uint32_t prevAccessCount, + const ThsvsAccessType* pPrevAccesses); /* Wrapper around vkCmdResetEvent. @@ -458,10 +458,10 @@ Resets an event when the accesses defined by pPrevAccesses are completed. commandBuffer and event are passed unmodified to vkCmdResetEvent. */ void thsvsCmdResetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - uint32_t prevAccessCount, - const ThsvsAccessType* pPrevAccesses); + VkCommandBuffer commandBuffer, + VkEvent event, + uint32_t prevAccessCount, + const ThsvsAccessType* pPrevAccesses); /* Simplified wrapper around vkCmdWaitEvents. @@ -474,14 +474,14 @@ commandBuffer, eventCount, and pEvents are passed unmodified to vkCmdWaitEvents. */ void thsvsCmdWaitEvents( - VkCommandBuffer commandBuffer, - uint32_t eventCount, - const VkEvent* pEvents, + VkCommandBuffer commandBuffer, + uint32_t eventCount, + const VkEvent* pEvents, const ThsvsGlobalBarrier* pGlobalBarrier, - uint32_t bufferBarrierCount, + uint32_t bufferBarrierCount, const ThsvsBufferBarrier* pBufferBarriers, - uint32_t imageBarrierCount, - const ThsvsImageBarrier* pImageBarriers); + uint32_t imageBarrierCount, + const ThsvsImageBarrier* pImageBarriers); #endif // THSVS_SIMPLER_VULKAN_SYNCHRONIZATION_H @@ -529,351 +529,348 @@ May consider other allocation strategies in future. // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) - #include + #include #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) - #include + #include #endif -#if defined(THSVS_ERROR_CHECK_ACCESS_TYPE_IN_RANGE) || \ +#if defined(THSVS_ERROR_CHECK_ACCESS_TYPE_IN_RANGE) || \ defined(THSVS_ERROR_CHECK_COULD_USE_GLOBAL_BARRIER) || \ - defined(THSVS_ERROR_CHECK_MIXED_IMAGE_LAYOUT) || \ + defined(THSVS_ERROR_CHECK_MIXED_IMAGE_LAYOUT) || \ defined(THSVS_ERROR_CHECK_POTENTIAL_HAZARD) - #include + #include #endif #if !defined(THSVS_TEMP_ALLOC) -#define THSVS_TEMP_ALLOC(size) (alloca(size)) + #define THSVS_TEMP_ALLOC(size) (alloca(size)) #endif #if !defined(THSVS_TEMP_FREE) -#define THSVS_TEMP_FREE(x) ((void)(x)) + #define THSVS_TEMP_FREE(x) ((void)(x)) #endif typedef struct ThsvsVkAccessInfo { - VkPipelineStageFlags stageMask; - VkAccessFlags accessMask; - VkImageLayout imageLayout; + VkPipelineStageFlags stageMask; + VkAccessFlags accessMask; + VkImageLayout imageLayout; } ThsvsVkAccessInfo; const ThsvsVkAccessInfo ThsvsAccessMap[THSVS_NUM_ACCESS_TYPES] = { // THSVS_ACCESS_NONE - { 0, - 0, - VK_IMAGE_LAYOUT_UNDEFINED}, + {0, + 0, + VK_IMAGE_LAYOUT_UNDEFINED}, -// Read Access + // Read Access // THSVS_ACCESS_COMMAND_BUFFER_READ_NV - { VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV, - VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_NV, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV, + VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_NV, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_INDIRECT_BUFFER - { VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, - VK_ACCESS_INDIRECT_COMMAND_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, + VK_ACCESS_INDIRECT_COMMAND_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_INDEX_BUFFER - { VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - VK_ACCESS_INDEX_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + VK_ACCESS_INDEX_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_VERTEX_BUFFER - { VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_VERTEX_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_VERTEX_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_VERTEX_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_GEOMETRY_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_GEOMETRY_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_GEOMETRY_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TASK_SHADER_READ_UNIFORM_BUFFER_NV - { VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_TASK_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV - { VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_TASK_SHADER_READ_OTHER_NV - { VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_MESH_SHADER_READ_UNIFORM_BUFFER_NV - { VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_MESH_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER_NV - { VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_MESH_SHADER_READ_OTHER_NV - { VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_EXT - { VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, - VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, + VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_FRAGMENT_DENSITY_MAP_READ_EXT - { VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, - VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, - VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT}, + {VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, + VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, + VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT}, // THSVS_ACCESS_SHADING_RATE_READ_NV - { VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV, - VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV, - VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV}, + {VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV, + VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV, + VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV}, // THSVS_ACCESS_FRAGMENT_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_FRAGMENT_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_FRAGMENT_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_COLOR_ATTACHMENT_READ - { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, // THSVS_ACCESS_COLOR_ATTACHMENT_ADVANCED_BLENDING_EXT - { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, // THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ - { VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_COMPUTE_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_COMPUTE_SHADER_READ_SAMPLED_IMAGE_OR_UNIFORM_TEXEL_BUFFER - { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_COMPUTE_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_UNIFORM_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_UNIFORM_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_ANY_SHADER_READ_UNIFORM_BUFFER_OR_VERTEX_BUFFER - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_ANY_SHADER_READ_SAMPLED_IMAGE - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, // THSVS_ACCESS_ANY_SHADER_READ_OTHER - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TRANSFER_READ - { VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL}, + {VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL}, // THSVS_ACCESS_HOST_READ - { VK_PIPELINE_STAGE_HOST_BIT, - VK_ACCESS_HOST_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_HOST_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_PRESENT - { 0, - 0, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR}, + {0, + 0, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR}, // THSVS_ACCESS_CONDITIONAL_RENDERING_READ_EXT - { VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, - VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, + VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_RAY_TRACING_SHADER_ACCELERATION_STRUCTURE_READ_NV - { VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, - VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, + VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_READ_NV - { VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, - VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, + VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_END_OF_READ_ACCESS - { 0, - 0, - VK_IMAGE_LAYOUT_UNDEFINED}, + {0, + 0, + VK_IMAGE_LAYOUT_UNDEFINED}, -// Write access + // Write access // THSVS_ACCESS_COMMAND_BUFFER_WRITE_NV - { VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV, - VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_NV, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV, + VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_NV, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_VERTEX_SHADER_WRITE - { VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TESSELLATION_CONTROL_SHADER_WRITE - { VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TESSELLATION_EVALUATION_SHADER_WRITE - { VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_GEOMETRY_SHADER_WRITE - { VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TASK_SHADER_WRITE_NV - { VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_MESH_SHADER_WRITE_NV - { VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TRANSFORM_FEEDBACK_WRITE_EXT - { VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, - VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, + VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_EXT - { VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, - VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, + VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_FRAGMENT_SHADER_WRITE - { VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_COLOR_ATTACHMENT_WRITE - { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, // THSVS_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE - { VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}, + {VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}, // THSVS_ACCESS_DEPTH_ATTACHMENT_WRITE_STENCIL_READ_ONLY - { VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR}, + {VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR}, // THSVS_ACCESS_STENCIL_ATTACHMENT_WRITE_DEPTH_READ_ONLY - { VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR}, + {VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, + VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR}, // THSVS_ACCESS_COMPUTE_SHADER_WRITE - { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_ANY_SHADER_WRITE - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_SHADER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_TRANSFER_WRITE - { VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL}, + {VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL}, // THSVS_ACCESS_HOST_PREINITIALIZED - { VK_PIPELINE_STAGE_HOST_BIT, - VK_ACCESS_HOST_WRITE_BIT, - VK_IMAGE_LAYOUT_PREINITIALIZED}, + {VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_HOST_WRITE_BIT, + VK_IMAGE_LAYOUT_PREINITIALIZED}, // THSVS_ACCESS_HOST_WRITE - { VK_PIPELINE_STAGE_HOST_BIT, - VK_ACCESS_HOST_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL}, + {VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_HOST_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}, // THSVS_ACCESS_ACCELERATION_STRUCTURE_BUILD_WRITE_NV - { VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, - VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV, - VK_IMAGE_LAYOUT_UNDEFINED}, + {VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, + VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV, + VK_IMAGE_LAYOUT_UNDEFINED}, // THSVS_ACCESS_COLOR_ATTACHMENT_READ_WRITE - { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, // THSVS_ACCESS_GENERAL - { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_IMAGE_LAYOUT_GENERAL} -}; + {VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL}}; void thsvsGetAccessInfo( - uint32_t accessCount, + uint32_t accessCount, const ThsvsAccessType* pAccesses, - VkPipelineStageFlags* pStageMask, - VkAccessFlags* pAccessMask, - VkImageLayout* pImageLayout, - bool* pHasWriteAccess) -{ - *pStageMask = 0; - *pAccessMask = 0; + VkPipelineStageFlags* pStageMask, + VkAccessFlags* pAccessMask, + VkImageLayout* pImageLayout, + bool* pHasWriteAccess) { + *pStageMask = 0; + *pAccessMask = 0; *pImageLayout = VK_IMAGE_LAYOUT_UNDEFINED; *pHasWriteAccess = false; - for (uint32_t i = 0; i < accessCount; ++i) - { + for (uint32_t i = 0; i < accessCount; ++i) { ThsvsAccessType access = pAccesses[i]; const ThsvsVkAccessInfo* pAccessInfo = &ThsvsAccessMap[access]; @@ -907,19 +904,17 @@ void thsvsGetAccessInfo( void thsvsGetVulkanMemoryBarrier( const ThsvsGlobalBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkMemoryBarrier* pVkBarrier) -{ - *pSrcStages = 0; - *pDstStages = 0; - pVkBarrier->sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - pVkBarrier->pNext = NULL; + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkMemoryBarrier* pVkBarrier) { + *pSrcStages = 0; + *pDstStages = 0; + pVkBarrier->sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + pVkBarrier->pNext = NULL; pVkBarrier->srcAccessMask = 0; pVkBarrier->dstAccessMask = 0; - for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) { ThsvsAccessType prevAccess = thBarrier.pPrevAccesses[i]; const ThsvsVkAccessInfo* pPrevAccessInfo = &ThsvsAccessMap[prevAccess]; @@ -940,8 +935,7 @@ void thsvsGetVulkanMemoryBarrier( pVkBarrier->srcAccessMask |= pPrevAccessInfo->accessMask; } - for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) { ThsvsAccessType nextAccess = thBarrier.pNextAccesses[i]; const ThsvsVkAccessInfo* pNextAccessInfo = &ThsvsAccessMap[nextAccess]; @@ -972,28 +966,26 @@ void thsvsGetVulkanMemoryBarrier( void thsvsGetVulkanBufferMemoryBarrier( const ThsvsBufferBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkBufferMemoryBarrier* pVkBarrier) -{ - *pSrcStages = 0; - *pDstStages = 0; - pVkBarrier->sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - pVkBarrier->pNext = NULL; - pVkBarrier->srcAccessMask = 0; - pVkBarrier->dstAccessMask = 0; + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkBufferMemoryBarrier* pVkBarrier) { + *pSrcStages = 0; + *pDstStages = 0; + pVkBarrier->sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + pVkBarrier->pNext = NULL; + pVkBarrier->srcAccessMask = 0; + pVkBarrier->dstAccessMask = 0; pVkBarrier->srcQueueFamilyIndex = thBarrier.srcQueueFamilyIndex; pVkBarrier->dstQueueFamilyIndex = thBarrier.dstQueueFamilyIndex; - pVkBarrier->buffer = thBarrier.buffer; - pVkBarrier->offset = thBarrier.offset; - pVkBarrier->size = thBarrier.size; + pVkBarrier->buffer = thBarrier.buffer; + pVkBarrier->offset = thBarrier.offset; + pVkBarrier->size = thBarrier.size; #ifdef THSVS_ERROR_CHECK_COULD_USE_GLOBAL_BARRIER assert(pVkBarrier->srcQueueFamilyIndex != pVkBarrier->dstQueueFamilyIndex); #endif - for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) { ThsvsAccessType prevAccess = thBarrier.pPrevAccesses[i]; const ThsvsVkAccessInfo* pPrevAccessInfo = &ThsvsAccessMap[prevAccess]; @@ -1014,8 +1006,7 @@ void thsvsGetVulkanBufferMemoryBarrier( pVkBarrier->srcAccessMask |= pPrevAccessInfo->accessMask; } - for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) { ThsvsAccessType nextAccess = thBarrier.pNextAccesses[i]; const ThsvsVkAccessInfo* pNextAccessInfo = &ThsvsAccessMap[nextAccess]; @@ -1047,25 +1038,23 @@ void thsvsGetVulkanBufferMemoryBarrier( void thsvsGetVulkanImageMemoryBarrier( const ThsvsImageBarrier& thBarrier, - VkPipelineStageFlags* pSrcStages, - VkPipelineStageFlags* pDstStages, - VkImageMemoryBarrier* pVkBarrier) -{ - *pSrcStages = 0; - *pDstStages = 0; - pVkBarrier->sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - pVkBarrier->pNext = NULL; - pVkBarrier->srcAccessMask = 0; - pVkBarrier->dstAccessMask = 0; + VkPipelineStageFlags* pSrcStages, + VkPipelineStageFlags* pDstStages, + VkImageMemoryBarrier* pVkBarrier) { + *pSrcStages = 0; + *pDstStages = 0; + pVkBarrier->sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + pVkBarrier->pNext = NULL; + pVkBarrier->srcAccessMask = 0; + pVkBarrier->dstAccessMask = 0; pVkBarrier->srcQueueFamilyIndex = thBarrier.srcQueueFamilyIndex; pVkBarrier->dstQueueFamilyIndex = thBarrier.dstQueueFamilyIndex; - pVkBarrier->image = thBarrier.image; - pVkBarrier->subresourceRange = thBarrier.subresourceRange; - pVkBarrier->oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - pVkBarrier->newLayout = VK_IMAGE_LAYOUT_UNDEFINED; + pVkBarrier->image = thBarrier.image; + pVkBarrier->subresourceRange = thBarrier.subresourceRange; + pVkBarrier->oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + pVkBarrier->newLayout = VK_IMAGE_LAYOUT_UNDEFINED; - for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.prevAccessCount; ++i) { ThsvsAccessType prevAccess = thBarrier.pPrevAccesses[i]; const ThsvsVkAccessInfo* pPrevAccessInfo = &ThsvsAccessMap[prevAccess]; @@ -1085,16 +1074,12 @@ void thsvsGetVulkanImageMemoryBarrier( if (prevAccess > THSVS_END_OF_READ_ACCESS) pVkBarrier->srcAccessMask |= pPrevAccessInfo->accessMask; - if (thBarrier.discardContents == VK_TRUE) - { + if (thBarrier.discardContents == VK_TRUE) { pVkBarrier->oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - } - else - { + } else { VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED; - switch(thBarrier.prevLayout) - { + switch (thBarrier.prevLayout) { case THSVS_IMAGE_LAYOUT_GENERAL: if (prevAccess == THSVS_ACCESS_PRESENT) layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; @@ -1109,7 +1094,6 @@ void thsvsGetVulkanImageMemoryBarrier( break; } - #ifdef THSVS_ERROR_CHECK_MIXED_IMAGE_LAYOUT assert(pVkBarrier->oldLayout == VK_IMAGE_LAYOUT_UNDEFINED || pVkBarrier->oldLayout == layout); @@ -1118,8 +1102,7 @@ void thsvsGetVulkanImageMemoryBarrier( } } - for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) - { + for (uint32_t i = 0; i < thBarrier.nextAccessCount; ++i) { ThsvsAccessType nextAccess = thBarrier.pNextAccesses[i]; const ThsvsVkAccessInfo* pNextAccessInfo = &ThsvsAccessMap[nextAccess]; @@ -1142,8 +1125,7 @@ void thsvsGetVulkanImageMemoryBarrier( pVkBarrier->dstAccessMask |= pNextAccessInfo->accessMask; VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED; - switch(thBarrier.nextLayout) - { + switch (thBarrier.nextLayout) { case THSVS_IMAGE_LAYOUT_GENERAL: if (nextAccess == THSVS_ACCESS_PRESENT) layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; @@ -1178,28 +1160,26 @@ void thsvsGetVulkanImageMemoryBarrier( } void thsvsCmdPipelineBarrier( - VkCommandBuffer commandBuffer, + VkCommandBuffer commandBuffer, const ThsvsGlobalBarrier* pGlobalBarrier, - uint32_t bufferBarrierCount, + uint32_t bufferBarrierCount, const ThsvsBufferBarrier* pBufferBarriers, - uint32_t imageBarrierCount, - const ThsvsImageBarrier* pImageBarriers) -{ - VkMemoryBarrier memoryBarrier; + uint32_t imageBarrierCount, + const ThsvsImageBarrier* pImageBarriers) { + VkMemoryBarrier memoryBarrier; // Vulkan pipeline barrier command parameters // commandBuffer; - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - uint32_t memoryBarrierCount = (pGlobalBarrier != NULL) ? 1 : 0; - VkMemoryBarrier* pMemoryBarriers = (pGlobalBarrier != NULL) ? &memoryBarrier : NULL; - uint32_t bufferMemoryBarrierCount = bufferBarrierCount; - VkBufferMemoryBarrier* pBufferMemoryBarriers = NULL; - uint32_t imageMemoryBarrierCount = imageBarrierCount; - VkImageMemoryBarrier* pImageMemoryBarriers = NULL; + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + uint32_t memoryBarrierCount = (pGlobalBarrier != NULL) ? 1 : 0; + VkMemoryBarrier* pMemoryBarriers = (pGlobalBarrier != NULL) ? &memoryBarrier : NULL; + uint32_t bufferMemoryBarrierCount = bufferBarrierCount; + VkBufferMemoryBarrier* pBufferMemoryBarriers = NULL; + uint32_t imageMemoryBarrierCount = imageBarrierCount; + VkImageMemoryBarrier* pImageMemoryBarriers = NULL; // Global memory barrier - if (pGlobalBarrier != NULL) - { + if (pGlobalBarrier != NULL) { VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; thsvsGetVulkanMemoryBarrier(*pGlobalBarrier, &tempSrcStageMask, &tempDstStageMask, pMemoryBarriers); @@ -1208,14 +1188,12 @@ void thsvsCmdPipelineBarrier( } // Buffer memory barriers - if (bufferBarrierCount > 0) - { + if (bufferBarrierCount > 0) { pBufferMemoryBarriers = (VkBufferMemoryBarrier*)THSVS_TEMP_ALLOC(sizeof(VkBufferMemoryBarrier) * bufferMemoryBarrierCount); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; - for (uint32_t i = 0; i < bufferBarrierCount; ++i) - { + for (uint32_t i = 0; i < bufferBarrierCount; ++i) { thsvsGetVulkanBufferMemoryBarrier(pBufferBarriers[i], &tempSrcStageMask, &tempDstStageMask, &pBufferMemoryBarriers[i]); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; @@ -1223,14 +1201,12 @@ void thsvsCmdPipelineBarrier( } // Image memory barriers - if (imageBarrierCount > 0) - { + if (imageBarrierCount > 0) { pImageMemoryBarriers = (VkImageMemoryBarrier*)THSVS_TEMP_ALLOC(sizeof(VkImageMemoryBarrier) * imageMemoryBarrierCount); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; - for (uint32_t i = 0; i < imageBarrierCount; ++i) - { + for (uint32_t i = 0; i < imageBarrierCount; ++i) { thsvsGetVulkanImageMemoryBarrier(pImageBarriers[i], &tempSrcStageMask, &tempDstStageMask, &pImageMemoryBarriers[i]); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; @@ -1254,15 +1230,13 @@ void thsvsCmdPipelineBarrier( } void thsvsCmdSetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - uint32_t prevAccessCount, - const ThsvsAccessType* pPrevAccesses) -{ + VkCommandBuffer commandBuffer, + VkEvent event, + uint32_t prevAccessCount, + const ThsvsAccessType* pPrevAccesses) { VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - for (uint32_t i = 0; i < prevAccessCount; ++i) - { + for (uint32_t i = 0; i < prevAccessCount; ++i) { ThsvsAccessType prevAccess = pPrevAccesses[i]; const ThsvsVkAccessInfo* pPrevAccessInfo = &ThsvsAccessMap[prevAccess]; @@ -1281,15 +1255,13 @@ void thsvsCmdSetEvent( } void thsvsCmdResetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - uint32_t prevAccessCount, - const ThsvsAccessType* pPrevAccesses) -{ + VkCommandBuffer commandBuffer, + VkEvent event, + uint32_t prevAccessCount, + const ThsvsAccessType* pPrevAccesses) { VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - for (uint32_t i = 0; i < prevAccessCount; ++i) - { + for (uint32_t i = 0; i < prevAccessCount; ++i) { ThsvsAccessType prevAccess = pPrevAccesses[i]; const ThsvsVkAccessInfo* pPrevAccessInfo = &ThsvsAccessMap[prevAccess]; @@ -1308,32 +1280,30 @@ void thsvsCmdResetEvent( } void thsvsCmdWaitEvents( - VkCommandBuffer commandBuffer, - uint32_t eventCount, - const VkEvent* pEvents, + VkCommandBuffer commandBuffer, + uint32_t eventCount, + const VkEvent* pEvents, const ThsvsGlobalBarrier* pGlobalBarrier, - uint32_t bufferBarrierCount, + uint32_t bufferBarrierCount, const ThsvsBufferBarrier* pBufferBarriers, - uint32_t imageBarrierCount, - const ThsvsImageBarrier* pImageBarriers) -{ - VkMemoryBarrier memoryBarrier; + uint32_t imageBarrierCount, + const ThsvsImageBarrier* pImageBarriers) { + VkMemoryBarrier memoryBarrier; // Vulkan pipeline barrier command parameters // commandBuffer; // eventCount; // pEvents; - VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - uint32_t memoryBarrierCount = (pGlobalBarrier != NULL) ? 1 : 0; - VkMemoryBarrier* pMemoryBarriers = (pGlobalBarrier != NULL) ? &memoryBarrier : NULL; - uint32_t bufferMemoryBarrierCount = bufferBarrierCount; - VkBufferMemoryBarrier* pBufferMemoryBarriers = NULL; - uint32_t imageMemoryBarrierCount = imageBarrierCount; - VkImageMemoryBarrier* pImageMemoryBarriers = NULL; + VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + uint32_t memoryBarrierCount = (pGlobalBarrier != NULL) ? 1 : 0; + VkMemoryBarrier* pMemoryBarriers = (pGlobalBarrier != NULL) ? &memoryBarrier : NULL; + uint32_t bufferMemoryBarrierCount = bufferBarrierCount; + VkBufferMemoryBarrier* pBufferMemoryBarriers = NULL; + uint32_t imageMemoryBarrierCount = imageBarrierCount; + VkImageMemoryBarrier* pImageMemoryBarriers = NULL; // Global memory barrier - if (pGlobalBarrier != NULL) - { + if (pGlobalBarrier != NULL) { VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; thsvsGetVulkanMemoryBarrier(*pGlobalBarrier, &tempSrcStageMask, &tempDstStageMask, pMemoryBarriers); @@ -1342,14 +1312,12 @@ void thsvsCmdWaitEvents( } // Buffer memory barriers - if (bufferBarrierCount > 0) - { + if (bufferBarrierCount > 0) { pBufferMemoryBarriers = (VkBufferMemoryBarrier*)THSVS_TEMP_ALLOC(sizeof(VkBufferMemoryBarrier) * bufferMemoryBarrierCount); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; - for (uint32_t i = 0; i < bufferBarrierCount; ++i) - { + for (uint32_t i = 0; i < bufferBarrierCount; ++i) { thsvsGetVulkanBufferMemoryBarrier(pBufferBarriers[i], &tempSrcStageMask, &tempDstStageMask, &pBufferMemoryBarriers[i]); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; @@ -1357,14 +1325,12 @@ void thsvsCmdWaitEvents( } // Image memory barriers - if (imageBarrierCount > 0) - { + if (imageBarrierCount > 0) { pImageMemoryBarriers = (VkImageMemoryBarrier*)THSVS_TEMP_ALLOC(sizeof(VkImageMemoryBarrier) * imageMemoryBarrierCount); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; - for (uint32_t i = 0; i < imageBarrierCount; ++i) - { + for (uint32_t i = 0; i < imageBarrierCount; ++i) { thsvsGetVulkanImageMemoryBarrier(pImageBarriers[i], &tempSrcStageMask, &tempDstStageMask, &pImageMemoryBarriers[i]); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; diff --git a/native/cocos/renderer/gfx-vulkan/vk_mem_alloc.h b/native/cocos/renderer/gfx-vulkan/vk_mem_alloc.h index e71ba77778..c9449357db 100644 --- a/native/cocos/renderer/gfx-vulkan/vk_mem_alloc.h +++ b/native/cocos/renderer/gfx-vulkan/vk_mem_alloc.h @@ -2034,30 +2034,30 @@ available through VmaAllocatorCreateInfo::pRecordSettings. #endif #if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS -extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; -extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; -extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; +extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; +extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; -extern PFN_vkAllocateMemory vkAllocateMemory; -extern PFN_vkFreeMemory vkFreeMemory; -extern PFN_vkMapMemory vkMapMemory; -extern PFN_vkUnmapMemory vkUnmapMemory; -extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; -extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; -extern PFN_vkBindBufferMemory vkBindBufferMemory; -extern PFN_vkBindImageMemory vkBindImageMemory; -extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; -extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; -extern PFN_vkCreateBuffer vkCreateBuffer; -extern PFN_vkDestroyBuffer vkDestroyBuffer; -extern PFN_vkCreateImage vkCreateImage; -extern PFN_vkDestroyImage vkDestroyImage; -extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; +extern PFN_vkAllocateMemory vkAllocateMemory; +extern PFN_vkFreeMemory vkFreeMemory; +extern PFN_vkMapMemory vkMapMemory; +extern PFN_vkUnmapMemory vkUnmapMemory; +extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; +extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; +extern PFN_vkBindBufferMemory vkBindBufferMemory; +extern PFN_vkBindImageMemory vkBindImageMemory; +extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; +extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; +extern PFN_vkCreateBuffer vkCreateBuffer; +extern PFN_vkDestroyBuffer vkDestroyBuffer; +extern PFN_vkCreateImage vkCreateImage; +extern PFN_vkDestroyImage vkDestroyImage; +extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; #if VMA_VULKAN_VERSION >= 1001000 -extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; -extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; -extern PFN_vkBindBufferMemory2 vkBindBufferMemory2; -extern PFN_vkBindImageMemory2 vkBindImageMemory2; +extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; +extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; +extern PFN_vkBindBufferMemory2 vkBindBufferMemory2; +extern PFN_vkBindImageMemory2 vkBindImageMemory2; extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2; #endif // #if VMA_VULKAN_VERSION >= 1001000 #endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES @@ -2199,18 +2199,18 @@ VK_DEFINE_HANDLE(VmaAllocator) /// Callback function called after successful vkAllocateMemory. typedef void(VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryType, + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryType, VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, - VkDeviceSize size, - void *VMA_NULLABLE pUserData); + VkDeviceSize size, + void *VMA_NULLABLE pUserData); /// Callback function called before vkFreeMemory. typedef void(VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryType, + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryType, VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, - VkDeviceSize size, - void *VMA_NULLABLE pUserData); + VkDeviceSize size, + void *VMA_NULLABLE pUserData); /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`. @@ -2350,30 +2350,30 @@ typedef VkFlags VmaAllocatorCreateFlags; Used in VmaAllocatorCreateInfo::pVulkanFunctions. */ typedef struct VmaVulkanFunctions { - PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties; + PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties; PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties; - PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory; - PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory; - PFN_vkMapMemory VMA_NULLABLE vkMapMemory; - PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory; - PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges; - PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges; - PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory; - PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory; - PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements; - PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements; - PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer; - PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer; - PFN_vkCreateImage VMA_NULLABLE vkCreateImage; - PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage; - PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer; + PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory; + PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory; + PFN_vkMapMemory VMA_NULLABLE vkMapMemory; + PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory; + PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges; + PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges; + PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory; + PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory; + PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements; + PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements; + PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer; + PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer; + PFN_vkCreateImage VMA_NULLABLE vkCreateImage; + PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage; + PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer; #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR; - PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR; + PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR; #endif #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR; - PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR; + PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR; #endif #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR; @@ -2535,7 +2535,7 @@ PhysicalDeviceProperties are fetched from physicalDevice by the allocator. You can access it here, without fetching it again on your own. */ VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, const VkPhysicalDeviceProperties *VMA_NULLABLE *VMA_NOT_NULL ppPhysicalDeviceProperties); /** @@ -2543,7 +2543,7 @@ PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator. You can access it here, without fetching it again on your own. */ VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, const VkPhysicalDeviceMemoryProperties *VMA_NULLABLE *VMA_NOT_NULL ppPhysicalDeviceMemoryProperties); /** @@ -2553,8 +2553,8 @@ This is just a convenience function. Same information can be obtained using vmaGetMemoryProperties(). */ VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryTypeIndex, + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryTypeIndex, VkMemoryPropertyFlags *VMA_NOT_NULL pFlags); /** \brief Sets index of the current frame. @@ -2567,7 +2567,7 @@ become lost in the current frame. */ VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( VmaAllocator VMA_NOT_NULL allocator, - uint32_t frameIndex); + uint32_t frameIndex); /** \brief Calculated statistics of memory usage in entire allocator. */ @@ -2604,7 +2604,7 @@ become outdated. */ VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats( VmaAllocator VMA_NOT_NULL allocator, - VmaStats *VMA_NOT_NULL pStats); + VmaStats *VMA_NOT_NULL pStats); /** \brief Statistics of current memory usage and available budget, in bytes, for specific memory heap. */ @@ -2658,7 +2658,7 @@ become outdated. */ VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget( VmaAllocator VMA_NOT_NULL allocator, - VmaBudget *VMA_NOT_NULL pBudget); + VmaBudget *VMA_NOT_NULL pBudget); #ifndef VMA_STATS_STRING_ENABLED #define VMA_STATS_STRING_ENABLED 1 @@ -2672,11 +2672,11 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget( VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( VmaAllocator VMA_NOT_NULL allocator, char *VMA_NULLABLE *VMA_NOT_NULL ppStatsString, - VkBool32 detailedMap); + VkBool32 detailedMap); VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( VmaAllocator VMA_NOT_NULL allocator, - char *VMA_NULLABLE pStatsString); + char *VMA_NULLABLE pStatsString); #endif // #if VMA_STATS_STRING_ENABLED @@ -2934,10 +2934,10 @@ type of resource you want to use it for. Please check parameters of your resource, like image layout (OPTIMAL versus LINEAR) or mip level count. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryTypeBits, + VmaAllocator VMA_NOT_NULL allocator, + uint32_t memoryTypeBits, const VmaAllocationCreateInfo *VMA_NOT_NULL pAllocationCreateInfo, - uint32_t *VMA_NOT_NULL pMemoryTypeIndex); + uint32_t *VMA_NOT_NULL pMemoryTypeIndex); /** \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo. @@ -2952,10 +2952,10 @@ It is just a convenience function, equivalent to calling: - `vkDestroyBuffer` */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( - VmaAllocator VMA_NOT_NULL allocator, - const VkBufferCreateInfo *VMA_NOT_NULL pBufferCreateInfo, + VmaAllocator VMA_NOT_NULL allocator, + const VkBufferCreateInfo *VMA_NOT_NULL pBufferCreateInfo, const VmaAllocationCreateInfo *VMA_NOT_NULL pAllocationCreateInfo, - uint32_t *VMA_NOT_NULL pMemoryTypeIndex); + uint32_t *VMA_NOT_NULL pMemoryTypeIndex); /** \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo. @@ -2970,10 +2970,10 @@ It is just a convenience function, equivalent to calling: - `vkDestroyImage` */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( - VmaAllocator VMA_NOT_NULL allocator, - const VkImageCreateInfo *VMA_NOT_NULL pImageCreateInfo, + VmaAllocator VMA_NOT_NULL allocator, + const VkImageCreateInfo *VMA_NOT_NULL pImageCreateInfo, const VmaAllocationCreateInfo *VMA_NOT_NULL pAllocationCreateInfo, - uint32_t *VMA_NOT_NULL pMemoryTypeIndex); + uint32_t *VMA_NOT_NULL pMemoryTypeIndex); /// Flags to be passed as VmaPoolCreateInfo::flags. typedef enum VmaPoolCreateFlagBits { @@ -3121,7 +3121,7 @@ typedef struct VmaPoolStats { @param[out] pPool Handle to created pool. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, const VmaPoolCreateInfo *VMA_NOT_NULL pCreateInfo, VmaPool VMA_NULLABLE *VMA_NOT_NULL pPool); @@ -3129,7 +3129,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( */ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NULLABLE pool); + VmaPool VMA_NULLABLE pool); /** \brief Retrieves statistics of existing #VmaPool object. @@ -3138,8 +3138,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( @param[out] pPoolStats Statistics of specified pool. */ VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, + VmaAllocator VMA_NOT_NULL allocator, + VmaPool VMA_NOT_NULL pool, VmaPoolStats *VMA_NOT_NULL pPoolStats); /** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now. @@ -3150,8 +3150,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats( */ VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost( VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - size_t *VMA_NULLABLE pLostAllocationCount); + VmaPool VMA_NOT_NULL pool, + size_t *VMA_NULLABLE pLostAllocationCount); /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions. @@ -3177,7 +3177,7 @@ destroyed or its name is changed using vmaSetPoolName(). */ VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, + VmaPool VMA_NOT_NULL pool, const char *VMA_NULLABLE *VMA_NOT_NULL ppName); /** \brief Sets name of a custom pool. @@ -3187,8 +3187,8 @@ Function makes internal copy of the string, so it can be changed or freed immedi */ VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - const char *VMA_NULLABLE pName); + VmaPool VMA_NOT_NULL pool, + const char *VMA_NULLABLE pName); /** \struct VmaAllocation \brief Represents single memory allocation. @@ -3281,11 +3281,11 @@ It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage vmaCreateBuffer(), vmaCreateImage() instead whenever possible. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( - VmaAllocator VMA_NOT_NULL allocator, - const VkMemoryRequirements *VMA_NOT_NULL pVkMemoryRequirements, + VmaAllocator VMA_NOT_NULL allocator, + const VkMemoryRequirements *VMA_NOT_NULL pVkMemoryRequirements, const VmaAllocationCreateInfo *VMA_NOT_NULL pCreateInfo, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL pAllocation, - VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); /** \brief General purpose memory allocation for multiple allocation objects at once. @@ -3307,12 +3307,12 @@ If any allocation fails, all allocations already made within this function call returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( - VmaAllocator VMA_NOT_NULL allocator, - const VkMemoryRequirements *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements, + VmaAllocator VMA_NOT_NULL allocator, + const VkMemoryRequirements *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements, const VmaAllocationCreateInfo *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo, - size_t allocationCount, + size_t allocationCount, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations, - VmaAllocationInfo *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo); /** @param[out] pAllocation Handle to allocated memory. @@ -3321,26 +3321,26 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( You should free the memory using vmaFreeMemory(). */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( - VmaAllocator VMA_NOT_NULL allocator, - VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, + VmaAllocator VMA_NOT_NULL allocator, + VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, const VmaAllocationCreateInfo *VMA_NOT_NULL pCreateInfo, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL pAllocation, - VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); /// Function similar to vmaAllocateMemoryForBuffer(). VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( - VmaAllocator VMA_NOT_NULL allocator, - VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, + VmaAllocator VMA_NOT_NULL allocator, + VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, const VmaAllocationCreateInfo *VMA_NOT_NULL pCreateInfo, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL pAllocation, - VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); /** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage(). Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped. */ VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, const VmaAllocation VMA_NULLABLE allocation); /** \brief Frees memory and destroys multiple allocations. @@ -3355,7 +3355,7 @@ Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entr */ VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( VmaAllocator VMA_NOT_NULL allocator, - size_t allocationCount, + size_t allocationCount, const VmaAllocation VMA_NULLABLE *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations); /** \brief Returns current information about specified allocation and atomically marks it as used in current frame. @@ -3375,8 +3375,8 @@ you can avoid calling it too often. - If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster. */ VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, VmaAllocationInfo *VMA_NOT_NULL pAllocationInfo); /** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame. @@ -3394,7 +3394,7 @@ If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOS this function always returns `VK_TRUE`. */ VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation); /** \brief Sets pUserData in given allocation to new value. @@ -3411,9 +3411,9 @@ allocation's `pUserData`. It is opaque, so you can use it however you want - e.g as a pointer, ordinal number or some handle to you own data. */ VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation, - void *VMA_NULLABLE pUserData); + void *VMA_NULLABLE pUserData); /** \brief Creates new allocation that is in lost state from the beginning. @@ -3468,7 +3468,7 @@ If the allocation is made from a memory types that is not `HOST_COHERENT`, you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation, void *VMA_NULLABLE *VMA_NOT_NULL ppData); @@ -3481,7 +3481,7 @@ If the allocation is made from a memory types that is not `HOST_COHERENT`, you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. */ VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation); /** \brief Flushes memory of given allocation. @@ -3506,10 +3506,10 @@ This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is called, otherwise `VK_SUCCESS`. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize offset, - VkDeviceSize size); + VkDeviceSize offset, + VkDeviceSize size); /** \brief Invalidates memory of given allocation. @@ -3533,10 +3533,10 @@ This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is called, otherwise `VK_SUCCESS`. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize offset, - VkDeviceSize size); + VkDeviceSize offset, + VkDeviceSize size); /** \brief Flushes memory of given set of allocations. @@ -3554,10 +3554,10 @@ called, otherwise `VK_SUCCESS`. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( VmaAllocator VMA_NOT_NULL allocator, - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation VMA_NOT_NULL *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, - const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, - const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); + const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, + const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); /** \brief Invalidates memory of given set of allocations. @@ -3575,10 +3575,10 @@ called, otherwise `VK_SUCCESS`. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( VmaAllocator VMA_NOT_NULL allocator, - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation VMA_NOT_NULL *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, - const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, - const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); + const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, + const VkDeviceSize *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions. @@ -3608,7 +3608,7 @@ VK_DEFINE_HANDLE(VmaDefragmentationContext) /// Flags to be used in vmaDefragmentationBegin(). None at the moment. Reserved for future use. typedef enum VmaDefragmentationFlagBits { - VMA_DEFRAGMENTATION_FLAG_INCREMENTAL = 0x1, + VMA_DEFRAGMENTATION_FLAG_INCREMENTAL = 0x1, VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } VmaDefragmentationFlagBits; typedef VkFlags VmaDefragmentationFlags; @@ -3690,9 +3690,9 @@ typedef struct VmaDefragmentationInfo2 { } VmaDefragmentationInfo2; typedef struct VmaDefragmentationPassMoveInfo { - VmaAllocation VMA_NOT_NULL allocation; + VmaAllocation VMA_NOT_NULL allocation; VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory; - VkDeviceSize offset; + VkDeviceSize offset; } VmaDefragmentationPassMoveInfo; /** \brief Parameters for incremental defragmentation steps. @@ -3700,7 +3700,7 @@ typedef struct VmaDefragmentationPassMoveInfo { To be used with function vmaBeginDefragmentationPass(). */ typedef struct VmaDefragmentationPassInfo { - uint32_t moveCount; + uint32_t moveCount; VmaDefragmentationPassMoveInfo *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(moveCount) pMoves; } VmaDefragmentationPassInfo; @@ -3763,9 +3763,9 @@ For more information and important limitations regarding defragmentation, see do [Defragmentation](@ref defragmentation). */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, const VmaDefragmentationInfo2 *VMA_NOT_NULL pInfo, - VmaDefragmentationStats *VMA_NULLABLE pStats, + VmaDefragmentationStats *VMA_NULLABLE pStats, VmaDefragmentationContext VMA_NULLABLE *VMA_NOT_NULL pContext); /** \brief Ends defragmentation process. @@ -3774,15 +3774,15 @@ Use this function to finish defragmentation started by vmaDefragmentationBegin() It is safe to pass `context == null`. The function then does nothing. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaDefragmentationContext VMA_NULLABLE context); VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NULLABLE context, + VmaAllocator VMA_NOT_NULL allocator, + VmaDefragmentationContext VMA_NULLABLE context, VmaDefragmentationPassInfo *VMA_NOT_NULL pInfo); VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VmaDefragmentationContext VMA_NULLABLE context); /** \brief Deprecated. Compacts memory by moving allocations. @@ -3828,10 +3828,10 @@ For more information, see [Defragmentation](@ref defragmentation) chapter. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment( VmaAllocator VMA_NOT_NULL allocator, const VmaAllocation VMA_NOT_NULL *VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations, - size_t allocationCount, - VkBool32 *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationsChanged, - const VmaDefragmentationInfo *VMA_NULLABLE pDefragmentationInfo, - VmaDefragmentationStats *VMA_NULLABLE pDefragmentationStats); + size_t allocationCount, + VkBool32 *VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationsChanged, + const VmaDefragmentationInfo *VMA_NULLABLE pDefragmentationInfo, + VmaDefragmentationStats *VMA_NULLABLE pDefragmentationStats); /** \brief Binds buffer to allocation. @@ -3846,8 +3846,8 @@ allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from mul It is recommended to use function vmaCreateBuffer() instead of this one. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer); /** \brief Binds buffer to allocation with additional parameters. @@ -3861,11 +3861,11 @@ If `pNext` is not null, #VmaAllocator object must have been created with #VMA_AL or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, - const void *VMA_NULLABLE pNext); + const void *VMA_NULLABLE pNext); /** \brief Binds image to allocation. @@ -3880,8 +3880,8 @@ allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from mul It is recommended to use function vmaCreateImage() instead of this one. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, VkImage VMA_NOT_NULL_NON_DISPATCHABLE image); /** \brief Binds image to allocation with additional parameters. @@ -3895,11 +3895,11 @@ If `pNext` is not null, #VmaAllocator object must have been created with #VMA_AL or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, + VmaAllocator VMA_NOT_NULL allocator, + VmaAllocation VMA_NOT_NULL allocation, + VkDeviceSize allocationLocalOffset, VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, - const void *VMA_NULLABLE pNext); + const void *VMA_NULLABLE pNext); /** @param[out] pBuffer Buffer that was created. @@ -3932,12 +3932,12 @@ although recommended as a good practice, is out of scope of this library and cou by the user as a higher-level logic on top of VMA. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( - VmaAllocator VMA_NOT_NULL allocator, - const VkBufferCreateInfo *VMA_NOT_NULL pBufferCreateInfo, + VmaAllocator VMA_NOT_NULL allocator, + const VkBufferCreateInfo *VMA_NOT_NULL pBufferCreateInfo, const VmaAllocationCreateInfo *VMA_NOT_NULL pAllocationCreateInfo, VkBuffer VMA_NULLABLE_NON_DISPATCHABLE *VMA_NOT_NULL pBuffer, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL pAllocation, - VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); /** \brief Destroys Vulkan buffer and frees allocated memory. @@ -3951,18 +3951,18 @@ vmaFreeMemory(allocator, allocation); It it safe to pass null as buffer and/or allocation. */ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer, - VmaAllocation VMA_NULLABLE allocation); + VmaAllocation VMA_NULLABLE allocation); /// Function similar to vmaCreateBuffer(). VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( - VmaAllocator VMA_NOT_NULL allocator, - const VkImageCreateInfo *VMA_NOT_NULL pImageCreateInfo, + VmaAllocator VMA_NOT_NULL allocator, + const VkImageCreateInfo *VMA_NOT_NULL pImageCreateInfo, const VmaAllocationCreateInfo *VMA_NOT_NULL pAllocationCreateInfo, VkImage VMA_NULLABLE_NON_DISPATCHABLE *VMA_NOT_NULL pImage, VmaAllocation VMA_NULLABLE *VMA_NOT_NULL pAllocation, - VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); + VmaAllocationInfo *VMA_NULLABLE pAllocationInfo); /** \brief Destroys Vulkan image and frees allocated memory. @@ -3976,9 +3976,9 @@ vmaFreeMemory(allocator, allocation); It it safe to pass null as image and/or allocation. */ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( - VmaAllocator VMA_NOT_NULL allocator, + VmaAllocator VMA_NOT_NULL allocator, VkImage VMA_NULLABLE_NON_DISPATCHABLE image, - VmaAllocation VMA_NULLABLE allocation); + VmaAllocation VMA_NULLABLE allocation); #ifdef __cplusplus } @@ -4036,7 +4036,7 @@ internally, like: #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 #if defined(VK_NO_PROTOTYPES) extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; -extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; +extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; #endif #endif @@ -4404,7 +4404,7 @@ static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX; // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666; -static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC; +static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC; static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF; /******************************************************************************* @@ -4415,7 +4415,7 @@ END OF CONFIGURATION static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040; static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080; -static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000; +static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000; static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u; @@ -4425,10 +4425,10 @@ static VkAllocationCallbacks VmaEmptyAllocationCallbacks = { // Returns number of bits set to 1 in (v). static inline uint32_t VmaCountBitsSet(uint32_t v) { uint32_t c = v - ((v >> 1) & 0x55555555); - c = ((c >> 2) & 0x33333333) + (c & 0x33333333); - c = ((c >> 4) + c) & 0x0F0F0F0F; - c = ((c >> 8) + c) & 0x00FF00FF; - c = ((c >> 16) + c) & 0x0000FFFF; + c = ((c >> 2) & 0x33333333) + (c & 0x33333333); + c = ((c >> 4) + c) & 0x0F0F0F0F; + c = ((c >> 8) + c) & 0x00FF00FF; + c = ((c >> 16) + c) & 0x0000FFFF; return c; } @@ -4576,21 +4576,21 @@ static inline bool VmaBlocksOnSamePage( VkDeviceSize resourceBOffset, VkDeviceSize pageSize) { VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0); - VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1; - VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1); - VkDeviceSize resourceBStart = resourceBOffset; + VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1; + VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1); + VkDeviceSize resourceBStart = resourceBOffset; VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1); return resourceAEndPage == resourceBStartPage; } enum VmaSuballocationType { - VMA_SUBALLOCATION_TYPE_FREE = 0, - VMA_SUBALLOCATION_TYPE_UNKNOWN = 1, - VMA_SUBALLOCATION_TYPE_BUFFER = 2, + VMA_SUBALLOCATION_TYPE_FREE = 0, + VMA_SUBALLOCATION_TYPE_UNKNOWN = 1, + VMA_SUBALLOCATION_TYPE_BUFFER = 2, VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3, - VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4, + VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5, - VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF + VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF }; /* @@ -4630,7 +4630,7 @@ static inline bool VmaIsBufferImageGranularityConflict( static void VmaWriteMagicValue(void *pData, VkDeviceSize offset) { #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION - uint32_t * pDst = (uint32_t *)((char *)pData + offset); + uint32_t *pDst = (uint32_t *)((char *)pData + offset); const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); for (size_t i = 0; i < numberCount; ++i, ++pDst) { *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE; @@ -4642,8 +4642,8 @@ static void VmaWriteMagicValue(void *pData, VkDeviceSize offset) { static bool VmaValidateMagicValue(const void *pData, VkDeviceSize offset) { #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION - const uint32_t *pSrc = (const uint32_t *)((const char *)pData + offset); - const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); + const uint32_t *pSrc = (const uint32_t *)((const char *)pData + offset); + const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); for (size_t i = 0; i < numberCount; ++i, ++pSrc) { if (*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE) { return false; @@ -4661,7 +4661,7 @@ static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo &outBuf memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo)); outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size. + outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size. } // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope). @@ -4788,7 +4788,7 @@ static bool VmaValidatePointerArray(uint32_t count, const T *arr) { template static inline void VmaPnextChainPushFront(MainT *mainStruct, NewT *newStruct) { - newStruct->pNext = mainStruct->pNext; + newStruct->pNext = mainStruct->pNext; mainStruct->pNext = newStruct; } @@ -4852,8 +4852,8 @@ static void vma_delete_array(const VkAllocationCallbacks *pAllocationCallbacks, static char *VmaCreateStringCopy(const VkAllocationCallbacks *allocs, const char *srcStr) { if (srcStr != VMA_NULL) { - const size_t len = strlen(srcStr); - char *const result = vma_new_array(allocs, char, len + 1); + const size_t len = strlen(srcStr); + char *const result = vma_new_array(allocs, char, len + 1); memcpy(result, srcStr, len + 1); return result; } else { @@ -4873,13 +4873,13 @@ template class VmaStlAllocator { public: const VkAllocationCallbacks *const m_pCallbacks; - typedef T value_type; + typedef T value_type; VmaStlAllocator(const VkAllocationCallbacks *pCallbacks) : m_pCallbacks(pCallbacks) {} template VmaStlAllocator(const VmaStlAllocator &src) : m_pCallbacks(src.m_pCallbacks) {} - T * allocate(size_t n) { return VmaAllocateArray(m_pCallbacks, n); } + T *allocate(size_t n) { return VmaAllocateArray(m_pCallbacks, n); } void deallocate(T *p, size_t n) { VmaFree(m_pCallbacks, p); } template @@ -4958,9 +4958,9 @@ public: return *this; } - bool empty() const { return m_Count == 0; } - size_t size() const { return m_Count; } - T * data() { return m_pArray; } + bool empty() const { return m_Count == 0; } + size_t size() const { return m_Count; } + T *data() { return m_pArray; } const T *data() const { return m_pArray; } T &operator[](size_t index) { @@ -5003,7 +5003,7 @@ public: } VmaFree(m_Allocator.m_pCallbacks, m_pArray); m_Capacity = newCapacity; - m_pArray = newArray; + m_pArray = newArray; } } @@ -5016,14 +5016,14 @@ public: } if (newCapacity != m_Capacity) { - T *const newArray = newCapacity ? VmaAllocateArray(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL; + T *const newArray = newCapacity ? VmaAllocateArray(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL; const size_t elementsToCopy = VMA_MIN(m_Count, newCount); if (elementsToCopy != 0) { memcpy(newArray, m_pArray, elementsToCopy * sizeof(T)); } VmaFree(m_Allocator.m_pCallbacks, m_pArray); m_Capacity = newCapacity; - m_pArray = newArray; + m_pArray = newArray; } m_Count = newCount; @@ -5079,9 +5079,9 @@ public: private: AllocatorT m_Allocator; - T * m_pArray; - size_t m_Count; - size_t m_Capacity; + T *m_pArray; + size_t m_Count; + size_t m_Capacity; }; template @@ -5110,7 +5110,7 @@ size_t VmaVectorInsertSorted(VectorT &vector, const typename VectorT::value_type template bool VmaVectorRemoveSorted(VectorT &vector, const typename VectorT::value_type &value) { - CmpLess comparator; + CmpLess comparator; typename VectorT::iterator it = VmaBinaryFindFirstNotLess( vector.begin(), vector.end(), @@ -5151,9 +5151,9 @@ public: template VmaSmallVector &operator=(const VmaSmallVector &rhs) = delete; - bool empty() const { return m_Count == 0; } - size_t size() const { return m_Count; } - T * data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } + bool empty() const { return m_Count == 0; } + size_t size() const { return m_Count; } + T *data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } const T *data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } T &operator[](size_t index) { @@ -5258,9 +5258,9 @@ public: iterator end() { return data() + m_Count; } private: - size_t m_Count; - T m_StaticArray[N]; // Used when m_Size <= N - VmaVector m_DynamicArray; // Used when m_Size > N + size_t m_Count; + T m_StaticArray[N]; // Used when m_Size <= N + VmaVector m_DynamicArray; // Used when m_Size > N }; //////////////////////////////////////////////////////////////////////////////// @@ -5278,7 +5278,7 @@ public: VmaPoolAllocator(const VkAllocationCallbacks *pAllocationCallbacks, uint32_t firstBlockCapacity); ~VmaPoolAllocator(); template - T * Alloc(Types... args); + T *Alloc(Types... args); void Free(T *ptr); private: @@ -5288,13 +5288,13 @@ private: }; struct ItemBlock { - Item * pItems; + Item *pItems; uint32_t Capacity; uint32_t FirstFreeIndex; }; - const VkAllocationCallbacks * m_pAllocationCallbacks; - const uint32_t m_FirstBlockCapacity; + const VkAllocationCallbacks *m_pAllocationCallbacks; + const uint32_t m_FirstBlockCapacity; VmaVector > m_ItemBlocks; ItemBlock &CreateNewBlock(); @@ -5321,19 +5321,19 @@ T *VmaPoolAllocator::Alloc(Types... args) { ItemBlock &block = m_ItemBlocks[i]; // This block has some free items: Use first one. if (block.FirstFreeIndex != UINT32_MAX) { - Item *const pItem = &block.pItems[block.FirstFreeIndex]; + Item *const pItem = &block.pItems[block.FirstFreeIndex]; block.FirstFreeIndex = pItem->NextFreeIndex; - T *result = (T *)&pItem->Value; + T *result = (T *)&pItem->Value; new (result) T(std::forward(args)...); // Explicit constructor call. return result; } } // No block has free item: Create new one and use it. - ItemBlock & newBlock = CreateNewBlock(); - Item *const pItem = &newBlock.pItems[0]; + ItemBlock &newBlock = CreateNewBlock(); + Item *const pItem = &newBlock.pItems[0]; newBlock.FirstFreeIndex = pItem->NextFreeIndex; - T *result = (T *)&pItem->Value; + T *result = (T *)&pItem->Value; new (result) T(std::forward(args)...); // Explicit constructor call. return result; } @@ -5351,9 +5351,9 @@ void VmaPoolAllocator::Free(T *ptr) { // Check if pItemPtr is in address range of this block. if ((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity)) { ptr->~T(); // Explicit destructor call. - const uint32_t index = static_cast(pItemPtr - block.pItems); + const uint32_t index = static_cast(pItemPtr - block.pItems); pItemPtr->NextFreeIndex = block.FirstFreeIndex; - block.FirstFreeIndex = index; + block.FirstFreeIndex = index; return; } } @@ -5391,7 +5391,7 @@ template struct VmaListItem { VmaListItem *pPrev; VmaListItem *pNext; - T Value; + T Value; }; // Doubly linked list. @@ -5406,19 +5406,19 @@ public: void Clear(); size_t GetCount() const { return m_Count; } - bool IsEmpty() const { return m_Count == 0; } + bool IsEmpty() const { return m_Count == 0; } - ItemType * Front() { return m_pFront; } + ItemType *Front() { return m_pFront; } const ItemType *Front() const { return m_pFront; } - ItemType * Back() { return m_pBack; } + ItemType *Back() { return m_pBack; } const ItemType *Back() const { return m_pBack; } ItemType *PushBack(); ItemType *PushFront(); ItemType *PushBack(const T &value); ItemType *PushFront(const T &value); - void PopBack(); - void PopFront(); + void PopBack(); + void PopFront(); // Item can be null - it means PushBack. ItemType *InsertBefore(ItemType *pItem); @@ -5432,10 +5432,10 @@ public: private: const VkAllocationCallbacks *const m_pAllocationCallbacks; - VmaPoolAllocator m_ItemAllocator; - ItemType * m_pFront; - ItemType * m_pBack; - size_t m_Count; + VmaPoolAllocator m_ItemAllocator; + ItemType *m_pFront; + ItemType *m_pBack; + size_t m_Count; }; template @@ -5462,24 +5462,24 @@ void VmaRawList::Clear() { pItem = pPrevItem; } m_pFront = VMA_NULL; - m_pBack = VMA_NULL; - m_Count = 0; + m_pBack = VMA_NULL; + m_Count = 0; } } template VmaListItem *VmaRawList::PushBack() { ItemType *const pNewItem = m_ItemAllocator.Alloc(); - pNewItem->pNext = VMA_NULL; + pNewItem->pNext = VMA_NULL; if (IsEmpty()) { pNewItem->pPrev = VMA_NULL; - m_pFront = pNewItem; - m_pBack = pNewItem; - m_Count = 1; + m_pFront = pNewItem; + m_pBack = pNewItem; + m_Count = 1; } else { pNewItem->pPrev = m_pBack; - m_pBack->pNext = pNewItem; - m_pBack = pNewItem; + m_pBack->pNext = pNewItem; + m_pBack = pNewItem; ++m_Count; } return pNewItem; @@ -5488,16 +5488,16 @@ VmaListItem *VmaRawList::PushBack() { template VmaListItem *VmaRawList::PushFront() { ItemType *const pNewItem = m_ItemAllocator.Alloc(); - pNewItem->pPrev = VMA_NULL; + pNewItem->pPrev = VMA_NULL; if (IsEmpty()) { pNewItem->pNext = VMA_NULL; - m_pFront = pNewItem; - m_pBack = pNewItem; - m_Count = 1; + m_pFront = pNewItem; + m_pBack = pNewItem; + m_Count = 1; } else { pNewItem->pNext = m_pFront; m_pFront->pPrev = pNewItem; - m_pFront = pNewItem; + m_pFront = pNewItem; ++m_Count; } return pNewItem; @@ -5506,14 +5506,14 @@ VmaListItem *VmaRawList::PushFront() { template VmaListItem *VmaRawList::PushBack(const T &value) { ItemType *const pNewItem = PushBack(); - pNewItem->Value = value; + pNewItem->Value = value; return pNewItem; } template VmaListItem *VmaRawList::PushFront(const T &value) { ItemType *const pNewItem = PushFront(); - pNewItem->Value = value; + pNewItem->Value = value; return pNewItem; } @@ -5534,7 +5534,7 @@ template void VmaRawList::PopFront() { VMA_HEAVY_ASSERT(m_Count > 0); ItemType *const pFrontItem = m_pFront; - ItemType *const pNextItem = pFrontItem->pNext; + ItemType *const pNextItem = pFrontItem->pNext; if (pNextItem != VMA_NULL) { pNextItem->pPrev = VMA_NULL; } @@ -5570,10 +5570,10 @@ template VmaListItem *VmaRawList::InsertBefore(ItemType *pItem) { if (pItem != VMA_NULL) { ItemType *const prevItem = pItem->pPrev; - ItemType *const newItem = m_ItemAllocator.Alloc(); - newItem->pPrev = prevItem; - newItem->pNext = pItem; - pItem->pPrev = newItem; + ItemType *const newItem = m_ItemAllocator.Alloc(); + newItem->pPrev = prevItem; + newItem->pNext = pItem; + pItem->pPrev = newItem; if (prevItem != VMA_NULL) { prevItem->pNext = newItem; } else { @@ -5590,10 +5590,10 @@ template VmaListItem *VmaRawList::InsertAfter(ItemType *pItem) { if (pItem != VMA_NULL) { ItemType *const nextItem = pItem->pNext; - ItemType *const newItem = m_ItemAllocator.Alloc(); - newItem->pNext = nextItem; - newItem->pPrev = pItem; - pItem->pNext = newItem; + ItemType *const newItem = m_ItemAllocator.Alloc(); + newItem->pNext = nextItem; + newItem->pPrev = pItem; + pItem->pNext = newItem; if (nextItem != VMA_NULL) { nextItem->pPrev = newItem; } else { @@ -5609,14 +5609,14 @@ VmaListItem *VmaRawList::InsertAfter(ItemType *pItem) { template VmaListItem *VmaRawList::InsertBefore(ItemType *pItem, const T &value) { ItemType *const newItem = InsertBefore(pItem); - newItem->Value = value; + newItem->Value = value; return newItem; } template VmaListItem *VmaRawList::InsertAfter(ItemType *pItem, const T &value) { ItemType *const newItem = InsertAfter(pItem); - newItem->Value = value; + newItem->Value = value; return newItem; } @@ -5675,7 +5675,7 @@ public: } private: - VmaRawList * m_pList; + VmaRawList *m_pList; VmaListItem *m_pItem; iterator(VmaRawList *pList, VmaListItem *pItem) : m_pList(pList), @@ -5744,7 +5744,7 @@ public: m_pItem(pItem) { } - const VmaRawList * m_pList; + const VmaRawList *m_pList; const VmaListItem *m_pItem; friend class VmaList; @@ -5752,7 +5752,7 @@ public: VmaList(const AllocatorT &allocator) : m_RawList(allocator.m_pCallbacks) {} - bool empty() const { return m_RawList.IsEmpty(); } + bool empty() const { return m_RawList.IsEmpty(); } size_t size() const { return m_RawList.GetCount(); } iterator begin() { return iterator(&m_RawList, m_RawList.Front()); } @@ -5761,9 +5761,9 @@ public: const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); } const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); } - void clear() { m_RawList.Clear(); } - void push_back(const T &value) { m_RawList.PushBack(value); } - void erase(iterator it) { m_RawList.Remove(it.m_pItem); } + void clear() { m_RawList.Clear(); } + void push_back(const T &value) { m_RawList.PushBack(value); } + void erase(iterator it) { m_RawList.Remove(it.m_pItem); } iterator insert(iterator it, const T &value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); } private: @@ -5790,27 +5790,27 @@ template class VmaIntrusiveLinkedList { public: typedef typename ItemTypeTraits::ItemType ItemType; - static ItemType * GetPrev(const ItemType *item) { return ItemTypeTraits::GetPrev(item); } - static ItemType * GetNext(const ItemType *item) { return ItemTypeTraits::GetNext(item); } + static ItemType *GetPrev(const ItemType *item) { return ItemTypeTraits::GetPrev(item); } + static ItemType *GetNext(const ItemType *item) { return ItemTypeTraits::GetNext(item); } // Movable, not copyable. VmaIntrusiveLinkedList() {} VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList &src) = delete; VmaIntrusiveLinkedList(VmaIntrusiveLinkedList &&src) : m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count) { src.m_Front = src.m_Back = VMA_NULL; - src.m_Count = 0; + src.m_Count = 0; } ~VmaIntrusiveLinkedList() { VMA_HEAVY_ASSERT(IsEmpty()); } VmaIntrusiveLinkedList &operator=(const VmaIntrusiveLinkedList &src) = delete; - VmaIntrusiveLinkedList &operator =(VmaIntrusiveLinkedList &&src) { + VmaIntrusiveLinkedList &operator=(VmaIntrusiveLinkedList &&src) { if (&src != this) { VMA_HEAVY_ASSERT(IsEmpty()); - m_Front = src.m_Front; - m_Back = src.m_Back; - m_Count = src.m_Count; + m_Front = src.m_Front; + m_Back = src.m_Back; + m_Count = src.m_Count; src.m_Front = src.m_Back = VMA_NULL; - src.m_Count = 0; + src.m_Count = 0; } return *this; } @@ -5818,32 +5818,32 @@ public: if (!IsEmpty()) { ItemType *item = m_Back; while (item != VMA_NULL) { - ItemType *const prevItem = ItemTypeTraits::AccessPrev(item); + ItemType *const prevItem = ItemTypeTraits::AccessPrev(item); ItemTypeTraits::AccessPrev(item) = VMA_NULL; ItemTypeTraits::AccessNext(item) = VMA_NULL; - item = prevItem; + item = prevItem; } m_Front = VMA_NULL; - m_Back = VMA_NULL; + m_Back = VMA_NULL; m_Count = 0; } } - size_t GetCount() const { return m_Count; } - bool IsEmpty() const { return m_Count == 0; } - ItemType * Front() { return m_Front; } + size_t GetCount() const { return m_Count; } + bool IsEmpty() const { return m_Count == 0; } + ItemType *Front() { return m_Front; } const ItemType *Front() const { return m_Front; } - ItemType * Back() { return m_Back; } + ItemType *Back() { return m_Back; } const ItemType *Back() const { return m_Back; } - void PushBack(ItemType *item) { + void PushBack(ItemType *item) { VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); if (IsEmpty()) { m_Front = item; - m_Back = item; + m_Back = item; m_Count = 1; } else { - ItemTypeTraits::AccessPrev(item) = m_Back; + ItemTypeTraits::AccessPrev(item) = m_Back; ItemTypeTraits::AccessNext(m_Back) = item; - m_Back = item; + m_Back = item; ++m_Count; } } @@ -5851,12 +5851,12 @@ public: VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); if (IsEmpty()) { m_Front = item; - m_Back = item; + m_Back = item; m_Count = 1; } else { - ItemTypeTraits::AccessNext(item) = m_Front; + ItemTypeTraits::AccessNext(item) = m_Front; ItemTypeTraits::AccessPrev(m_Front) = item; - m_Front = item; + m_Front = item; ++m_Count; } } @@ -5876,7 +5876,7 @@ public: ItemType *PopFront() { VMA_HEAVY_ASSERT(m_Count > 0); ItemType *const frontItem = m_Front; - ItemType *const nextItem = ItemTypeTraits::GetNext(frontItem); + ItemType *const nextItem = ItemTypeTraits::GetNext(frontItem); if (nextItem != VMA_NULL) { ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL; } @@ -5891,9 +5891,9 @@ public: void InsertBefore(ItemType *existingItem, ItemType *newItem) { VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); if (existingItem != VMA_NULL) { - ItemType *const prevItem = ItemTypeTraits::GetPrev(existingItem); - ItemTypeTraits::AccessPrev(newItem) = prevItem; - ItemTypeTraits::AccessNext(newItem) = existingItem; + ItemType *const prevItem = ItemTypeTraits::GetPrev(existingItem); + ItemTypeTraits::AccessPrev(newItem) = prevItem; + ItemTypeTraits::AccessNext(newItem) = existingItem; ItemTypeTraits::AccessPrev(existingItem) = newItem; if (prevItem != VMA_NULL) { ItemTypeTraits::AccessNext(prevItem) = newItem; @@ -5909,9 +5909,9 @@ public: void InsertAfter(ItemType *existingItem, ItemType *newItem) { VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); if (existingItem != VMA_NULL) { - ItemType *const nextItem = ItemTypeTraits::GetNext(existingItem); - ItemTypeTraits::AccessNext(newItem) = nextItem; - ItemTypeTraits::AccessPrev(newItem) = existingItem; + ItemType *const nextItem = ItemTypeTraits::GetNext(existingItem); + ItemTypeTraits::AccessNext(newItem) = nextItem; + ItemTypeTraits::AccessPrev(newItem) = existingItem; ItemTypeTraits::AccessNext(existingItem) = newItem; if (nextItem != VMA_NULL) { ItemTypeTraits::AccessPrev(nextItem) = newItem; @@ -5945,8 +5945,8 @@ public: private: ItemType *m_Front = VMA_NULL; - ItemType *m_Back = VMA_NULL; - size_t m_Count = 0; + ItemType *m_Back = VMA_NULL; + size_t m_Count = 0; }; //////////////////////////////////////////////////////////////////////////////// @@ -6088,7 +6088,7 @@ public: m_Flags{userDataString ? (uint8_t)FLAG_USER_DATA_STRING : (uint8_t)0} { #if VMA_STATS_STRING_ENABLED m_CreationFrameIndex = currentFrameIndex; - m_BufferImageUsage = 0; + m_BufferImageUsage = 0; #endif } @@ -6101,82 +6101,82 @@ public: void InitBlockAllocation( VmaDeviceMemoryBlock *block, - VkDeviceSize offset, - VkDeviceSize alignment, - VkDeviceSize size, - uint32_t memoryTypeIndex, - VmaSuballocationType suballocationType, - bool mapped, - bool canBecomeLost) { + VkDeviceSize offset, + VkDeviceSize alignment, + VkDeviceSize size, + uint32_t memoryTypeIndex, + VmaSuballocationType suballocationType, + bool mapped, + bool canBecomeLost) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(block != VMA_NULL); - m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; - m_Alignment = alignment; - m_Size = size; - m_MemoryTypeIndex = memoryTypeIndex; - m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; - m_SuballocationType = (uint8_t)suballocationType; - m_BlockAllocation.m_Block = block; - m_BlockAllocation.m_Offset = offset; + m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; + m_Alignment = alignment; + m_Size = size; + m_MemoryTypeIndex = memoryTypeIndex; + m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; + m_SuballocationType = (uint8_t)suballocationType; + m_BlockAllocation.m_Block = block; + m_BlockAllocation.m_Offset = offset; m_BlockAllocation.m_CanBecomeLost = canBecomeLost; } void InitLost() { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST); - m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; - m_MemoryTypeIndex = 0; - m_BlockAllocation.m_Block = VMA_NULL; - m_BlockAllocation.m_Offset = 0; + m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; + m_MemoryTypeIndex = 0; + m_BlockAllocation.m_Block = VMA_NULL; + m_BlockAllocation.m_Offset = 0; m_BlockAllocation.m_CanBecomeLost = true; } void ChangeBlockAllocation( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaDeviceMemoryBlock *block, - VkDeviceSize offset); + VkDeviceSize offset); void ChangeOffset(VkDeviceSize newOffset); // pMappedData not null means allocation is created with MAPPED flag. void InitDedicatedAllocation( - uint32_t memoryTypeIndex, - VkDeviceMemory hMemory, + uint32_t memoryTypeIndex, + VkDeviceMemory hMemory, VmaSuballocationType suballocationType, - void * pMappedData, - VkDeviceSize size) { + void *pMappedData, + VkDeviceSize size) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(hMemory != VK_NULL_HANDLE); - m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED; - m_Alignment = 0; - m_Size = size; - m_MemoryTypeIndex = memoryTypeIndex; - m_SuballocationType = (uint8_t)suballocationType; - m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; - m_DedicatedAllocation.m_hMemory = hMemory; + m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED; + m_Alignment = 0; + m_Size = size; + m_MemoryTypeIndex = memoryTypeIndex; + m_SuballocationType = (uint8_t)suballocationType; + m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; + m_DedicatedAllocation.m_hMemory = hMemory; m_DedicatedAllocation.m_pMappedData = pMappedData; - m_DedicatedAllocation.m_Prev = VMA_NULL; - m_DedicatedAllocation.m_Next = VMA_NULL; + m_DedicatedAllocation.m_Prev = VMA_NULL; + m_DedicatedAllocation.m_Next = VMA_NULL; } - ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; } - VkDeviceSize GetAlignment() const { return m_Alignment; } - VkDeviceSize GetSize() const { return m_Size; } - bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; } - void * GetUserData() const { return m_pUserData; } - void SetUserData(VmaAllocator hAllocator, void *pUserData); + ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; } + VkDeviceSize GetAlignment() const { return m_Alignment; } + VkDeviceSize GetSize() const { return m_Size; } + bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; } + void *GetUserData() const { return m_pUserData; } + void SetUserData(VmaAllocator hAllocator, void *pUserData); VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; } VmaDeviceMemoryBlock *GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; } - VkDeviceSize GetOffset() const; + VkDeviceSize GetOffset() const; VkDeviceMemory GetMemory() const; - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } - bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; } - void * GetMappedData() const; - bool CanBecomeLost() const; + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; } + void *GetMappedData() const; + bool CanBecomeLost() const; uint32_t GetLastUseFrameIndex() const { return m_LastUseFrameIndex.load(); @@ -6196,20 +6196,20 @@ public: void DedicatedAllocCalcStatsInfo(VmaStatInfo &outInfo) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED); - outInfo.blockCount = 1; - outInfo.allocationCount = 1; - outInfo.unusedRangeCount = 0; - outInfo.usedBytes = m_Size; - outInfo.unusedBytes = 0; + outInfo.blockCount = 1; + outInfo.allocationCount = 1; + outInfo.unusedRangeCount = 0; + outInfo.usedBytes = m_Size; + outInfo.unusedBytes = 0; outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size; - outInfo.unusedRangeSizeMin = UINT64_MAX; - outInfo.unusedRangeSizeMax = 0; + outInfo.unusedRangeSizeMin = UINT64_MAX; + outInfo.unusedRangeSizeMax = 0; } - void BlockAllocMap(); - void BlockAllocUnmap(); + void BlockAllocMap(); + void BlockAllocUnmap(); VkResult DedicatedAllocMap(VmaAllocator hAllocator, void **ppData); - void DedicatedAllocUnmap(VmaAllocator hAllocator); + void DedicatedAllocUnmap(VmaAllocator hAllocator); #if VMA_STATS_STRING_ENABLED uint32_t GetCreationFrameIndex() const { return m_CreationFrameIndex; } @@ -6224,13 +6224,13 @@ public: #endif private: - VkDeviceSize m_Alignment; - VkDeviceSize m_Size; - void * m_pUserData; + VkDeviceSize m_Alignment; + VkDeviceSize m_Size; + void *m_pUserData; VMA_ATOMIC_UINT32 m_LastUseFrameIndex; - uint32_t m_MemoryTypeIndex; - uint8_t m_Type; // ALLOCATION_TYPE - uint8_t m_SuballocationType; // VmaSuballocationType + uint32_t m_MemoryTypeIndex; + uint8_t m_Type; // ALLOCATION_TYPE + uint8_t m_SuballocationType; // VmaSuballocationType // Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT. // Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory(). uint8_t m_MapCount; @@ -6239,14 +6239,14 @@ private: // Allocation out of VmaDeviceMemoryBlock. struct BlockAllocation { VmaDeviceMemoryBlock *m_Block; - VkDeviceSize m_Offset; - bool m_CanBecomeLost; + VkDeviceSize m_Offset; + bool m_CanBecomeLost; }; // Allocation for an object that has its own private VkDeviceMemory. struct DedicatedAllocation { - VkDeviceMemory m_hMemory; - void * m_pMappedData; // Not null means memory is mapped. + VkDeviceMemory m_hMemory; + void *m_pMappedData; // Not null means memory is mapped. VmaAllocation_T *m_Prev; VmaAllocation_T *m_Next; }; @@ -6270,7 +6270,7 @@ private: struct VmaDedicatedAllocationListItemTraits { typedef VmaAllocation_T ItemType; - static ItemType * GetPrev(const ItemType *item) { + static ItemType *GetPrev(const ItemType *item) { VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); return item->m_DedicatedAllocation.m_Prev; } @@ -6293,9 +6293,9 @@ Represents a region of VmaDeviceMemoryBlock that is either assigned and returned allocated memory block or free. */ struct VmaSuballocation { - VkDeviceSize offset; - VkDeviceSize size; - VmaAllocation hAllocation; + VkDeviceSize offset; + VkDeviceSize size; + VmaAllocation hAllocation; VmaSuballocationType type; }; @@ -6338,13 +6338,13 @@ If canMakeOtherLost was true: the requested allocation to succeed. */ struct VmaAllocationRequest { - VkDeviceSize offset; - VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation. - VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation. + VkDeviceSize offset; + VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation. + VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation. VmaSuballocationList::iterator item; - size_t itemsToMakeLostCount; - void * customData; - VmaAllocationRequestType type; + size_t itemsToMakeLostCount; + void *customData; + VmaAllocationRequestType type; VkDeviceSize CalcCost() const { return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST; @@ -6362,10 +6362,10 @@ public: virtual void Init(VkDeviceSize size) { m_Size = size; } // Validates all data structures inside this object. If not valid, returns false. - virtual bool Validate() const = 0; - VkDeviceSize GetSize() const { return m_Size; } - virtual size_t GetAllocationCount() const = 0; - virtual VkDeviceSize GetSumFreeSize() const = 0; + virtual bool Validate() const = 0; + VkDeviceSize GetSize() const { return m_Size; } + virtual size_t GetAllocationCount() const = 0; + virtual VkDeviceSize GetSumFreeSize() const = 0; virtual VkDeviceSize GetUnusedRangeSizeMax() const = 0; // Returns true if this block is empty - contains only single free suballocation. virtual bool IsEmpty() const = 0; @@ -6382,21 +6382,21 @@ public: // If succeeded, fills pAllocationRequest and returns true. // If failed, returns false. virtual bool CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, VmaSuballocationType allocType, - bool canMakeOtherLost, + bool canMakeOtherLost, // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags. - uint32_t strategy, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) = 0; virtual bool MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest) = 0; virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) = 0; @@ -6406,33 +6406,33 @@ public: // Makes actual allocation based on request. Request must already be checked and valid. virtual void Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation) = 0; + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation) = 0; // Frees suballocation assigned to given memory region. virtual void Free(const VmaAllocation allocation) = 0; - virtual void FreeAtOffset(VkDeviceSize offset) = 0; + virtual void FreeAtOffset(VkDeviceSize offset) = 0; protected: const VkAllocationCallbacks *GetAllocationCallbacks() const { return m_pAllocationCallbacks; } #if VMA_STATS_STRING_ENABLED void PrintDetailedMap_Begin(class VmaJsonWriter &json, - VkDeviceSize unusedBytes, - size_t allocationCount, - size_t unusedRangeCount) const; + VkDeviceSize unusedBytes, + size_t allocationCount, + size_t unusedRangeCount) const; void PrintDetailedMap_Allocation(class VmaJsonWriter &json, - VkDeviceSize offset, - VmaAllocation hAllocation) const; + VkDeviceSize offset, + VmaAllocation hAllocation) const; void PrintDetailedMap_UnusedRange(class VmaJsonWriter &json, - VkDeviceSize offset, - VkDeviceSize size) const; + VkDeviceSize offset, + VkDeviceSize size) const; void PrintDetailedMap_End(class VmaJsonWriter &json) const; #endif private: - VkDeviceSize m_Size; + VkDeviceSize m_Size; const VkAllocationCallbacks *m_pAllocationCallbacks; }; @@ -6451,11 +6451,11 @@ public: virtual ~VmaBlockMetadata_Generic(); virtual void Init(VkDeviceSize size); - virtual bool Validate() const; - virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; } + virtual bool Validate() const; + virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; } virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; } virtual VkDeviceSize GetUnusedRangeSizeMax() const; - virtual bool IsEmpty() const; + virtual bool IsEmpty() const; virtual void CalcAllocationStatInfo(VmaStatInfo &outInfo) const; virtual void AddPoolStats(VmaPoolStats &inoutStats) const; @@ -6465,20 +6465,20 @@ public: #endif virtual bool CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest); virtual bool MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest); virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); @@ -6487,9 +6487,9 @@ public: virtual void Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation); + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation); virtual void Free(const VmaAllocation allocation); virtual void FreeAtOffset(VkDeviceSize offset); @@ -6498,15 +6498,15 @@ public: // For defragmentation bool IsBufferImageGranularityConflictPossible( - VkDeviceSize bufferImageGranularity, + VkDeviceSize bufferImageGranularity, VmaSuballocationType &inOutPrevSuballocType) const; private: friend class VmaDefragmentationAlgorithm_Generic; friend class VmaDefragmentationAlgorithm_Fast; - uint32_t m_FreeCount; - VkDeviceSize m_SumFreeSize; + uint32_t m_FreeCount; + VkDeviceSize m_SumFreeSize; VmaSuballocationList m_Suballocations; // Suballocations that are free and have size greater than certain threshold. // Sorted by size, ascending. @@ -6517,18 +6517,18 @@ private: // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem. // If yes, fills pOffset and returns true. If no, returns false. bool CheckAllocation( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, VmaSuballocationList::const_iterator suballocItem, - bool canMakeOtherLost, - VkDeviceSize * pOffset, - size_t * itemsToMakeLostCount, - VkDeviceSize * pSumFreeSize, - VkDeviceSize * pSumItemSize) const; + bool canMakeOtherLost, + VkDeviceSize *pOffset, + size_t *itemsToMakeLostCount, + VkDeviceSize *pSumFreeSize, + VkDeviceSize *pSumItemSize) const; // Given free suballocation, it merges it with following one, which must also be free. void MergeFreeWithNext(VmaSuballocationList::iterator item); // Releases given suballocation, making it free. @@ -6628,11 +6628,11 @@ public: virtual ~VmaBlockMetadata_Linear(); virtual void Init(VkDeviceSize size); - virtual bool Validate() const; - virtual size_t GetAllocationCount() const; + virtual bool Validate() const; + virtual size_t GetAllocationCount() const; virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; } virtual VkDeviceSize GetUnusedRangeSizeMax() const; - virtual bool IsEmpty() const { return GetAllocationCount() == 0; } + virtual bool IsEmpty() const { return GetAllocationCount() == 0; } virtual void CalcAllocationStatInfo(VmaStatInfo &outInfo) const; virtual void AddPoolStats(VmaPoolStats &inoutStats) const; @@ -6642,20 +6642,20 @@ public: #endif virtual bool CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest); virtual bool MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest); virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); @@ -6664,9 +6664,9 @@ public: virtual void Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation); + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation); virtual void Free(const VmaAllocation allocation); virtual void FreeAtOffset(VkDeviceSize offset); @@ -6696,13 +6696,13 @@ private: SECOND_VECTOR_DOUBLE_STACK, }; - VkDeviceSize m_SumFreeSize; + VkDeviceSize m_SumFreeSize; SuballocationVectorType m_Suballocations0, m_Suballocations1; - uint32_t m_1stVectorIndex; - SECOND_VECTOR_MODE m_2ndVectorMode; + uint32_t m_1stVectorIndex; + SECOND_VECTOR_MODE m_2ndVectorMode; - SuballocationVectorType & AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } - SuballocationVectorType & AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } + SuballocationVectorType &AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } + SuballocationVectorType &AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } const SuballocationVectorType &AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } const SuballocationVectorType &AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } @@ -6717,24 +6717,24 @@ private: void CleanupAfterFree(); bool CreateAllocationRequest_LowerAddress( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest); bool CreateAllocationRequest_UpperAddress( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest); }; @@ -6756,11 +6756,11 @@ public: virtual ~VmaBlockMetadata_Buddy(); virtual void Init(VkDeviceSize size); - virtual bool Validate() const; - virtual size_t GetAllocationCount() const { return m_AllocationCount; } + virtual bool Validate() const; + virtual size_t GetAllocationCount() const { return m_AllocationCount; } virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize + GetUnusableSize(); } virtual VkDeviceSize GetUnusedRangeSizeMax() const; - virtual bool IsEmpty() const { return m_Root->type == Node::TYPE_FREE; } + virtual bool IsEmpty() const { return m_Root->type == Node::TYPE_FREE; } virtual void CalcAllocationStatInfo(VmaStatInfo &outInfo) const; virtual void AddPoolStats(VmaPoolStats &inoutStats) const; @@ -6770,20 +6770,20 @@ public: #endif virtual bool CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest); virtual bool MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest); virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); @@ -6792,20 +6792,20 @@ public: virtual void Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation); + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation); virtual void Free(const VmaAllocation allocation) { FreeAtOffset(allocation, allocation->GetOffset()); } virtual void FreeAtOffset(VkDeviceSize offset) { FreeAtOffset(VMA_NULL, offset); } private: static const VkDeviceSize MIN_NODE_SIZE = 32; - static const size_t MAX_LEVELS = 30; + static const size_t MAX_LEVELS = 30; struct ValidationContext { - size_t calculatedAllocationCount; - size_t calculatedFreeCount; + size_t calculatedAllocationCount; + size_t calculatedFreeCount; VkDeviceSize calculatedSumFreeSize; ValidationContext() : calculatedAllocationCount(0), @@ -6843,7 +6843,7 @@ private: // Size of the memory block aligned down to a power of two. VkDeviceSize m_UsableSize; - uint32_t m_LevelCount; + uint32_t m_LevelCount; Node *m_Root; struct { @@ -6857,10 +6857,10 @@ private: // This includes space wasted due to internal fragmentation. Doesn't include unusable size. VkDeviceSize m_SumFreeSize; - VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; } - void DeleteNode(Node *node); - bool ValidateNode(ValidationContext &ctx, const Node *parent, const Node *curr, uint32_t level, VkDeviceSize levelNodeSize) const; - uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const; + VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; } + void DeleteNode(Node *node); + bool ValidateNode(ValidationContext &ctx, const Node *parent, const Node *curr, uint32_t level, VkDeviceSize levelNodeSize) const; + uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const; inline VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; } // Alloc passed just for validation. Can be null. void FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset); @@ -6899,21 +6899,21 @@ public: // Always call after construction. void Init( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t newMemoryTypeIndex, + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, - VkDeviceSize newSize, - uint32_t id, - uint32_t algorithm); + VkDeviceSize newSize, + uint32_t id, + uint32_t algorithm); // Always call before destruction. void Destroy(VmaAllocator allocator); - VmaPool GetParentPool() const { return m_hParentPool; } + VmaPool GetParentPool() const { return m_hParentPool; } VkDeviceMemory GetDeviceMemory() const { return m_hMemory; } - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } - uint32_t GetId() const { return m_Id; } - void * GetMappedData() const { return m_pMappedData; } + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + uint32_t GetId() const { return m_Id; } + void *GetMappedData() const { return m_pMappedData; } // Validates all data structures inside this object. If not valid, returns false. bool Validate() const; @@ -6922,28 +6922,28 @@ public: // ppData can be null. VkResult Map(VmaAllocator hAllocator, uint32_t count, void **ppData); - void Unmap(VmaAllocator hAllocator, uint32_t count); + void Unmap(VmaAllocator hAllocator, uint32_t count); VkResult WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); VkResult ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); VkResult BindBufferMemory( - const VmaAllocator hAllocator, + const VmaAllocator hAllocator, const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void * pNext); + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void *pNext); VkResult BindImageMemory( - const VmaAllocator hAllocator, + const VmaAllocator hAllocator, const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void * pNext); + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void *pNext); private: - VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. - uint32_t m_MemoryTypeIndex; - uint32_t m_Id; + VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. + uint32_t m_MemoryTypeIndex; + uint32_t m_Id; VkDeviceMemory m_hMemory; /* @@ -6952,17 +6952,17 @@ private: Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex. */ VMA_MUTEX m_Mutex; - uint32_t m_MapCount; - void * m_pMappedData; + uint32_t m_MapCount; + void *m_pMappedData; }; struct VmaDefragmentationMove { - size_t srcBlockIndex; - size_t dstBlockIndex; - VkDeviceSize srcOffset; - VkDeviceSize dstOffset; - VkDeviceSize size; - VmaAllocation hAllocation; + size_t srcBlockIndex; + size_t dstBlockIndex; + VkDeviceSize srcOffset; + VkDeviceSize dstOffset; + VkDeviceSize size; + VmaAllocation hAllocation; VmaDeviceMemoryBlock *pSrcBlock; VmaDeviceMemoryBlock *pDstBlock; }; @@ -6980,28 +6980,28 @@ struct VmaBlockVector { public: VmaBlockVector( VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t memoryTypeIndex, + VmaPool hParentPool, + uint32_t memoryTypeIndex, VkDeviceSize preferredBlockSize, - size_t minBlockCount, - size_t maxBlockCount, + size_t minBlockCount, + size_t maxBlockCount, VkDeviceSize bufferImageGranularity, - uint32_t frameInUseCount, - bool explicitBlockSize, - uint32_t algorithm, - float priority); + uint32_t frameInUseCount, + bool explicitBlockSize, + uint32_t algorithm, + float priority); ~VmaBlockVector(); VkResult CreateMinBlocks(); VmaAllocator GetAllocator() const { return m_hAllocator; } - VmaPool GetParentPool() const { return m_hParentPool; } - bool IsCustomPool() const { return m_hParentPool != VMA_NULL; } - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } + VmaPool GetParentPool() const { return m_hParentPool; } + bool IsCustomPool() const { return m_hParentPool != VMA_NULL; } + uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; } VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } - uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; } - uint32_t GetAlgorithm() const { return m_Algorithm; } + uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; } + uint32_t GetAlgorithm() const { return m_Algorithm; } void GetPoolStats(VmaPoolStats *pStats); @@ -7009,13 +7009,13 @@ public: bool IsCorruptionDetectionEnabled() const; VkResult Allocate( - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations); + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations); void Free(const VmaAllocation hAllocation); @@ -7028,7 +7028,7 @@ public: void MakePoolAllocationsLost( uint32_t currentFrameIndex, - size_t * pLostAllocationCount); + size_t *pLostAllocationCount); VkResult CheckCorruption(); // Saves results in pCtx->res. @@ -7040,8 +7040,8 @@ public: VkCommandBuffer commandBuffer); void DefragmentationEnd( class VmaBlockVectorDefragmentationContext *pCtx, - uint32_t flags, - VmaDefragmentationStats * pStats); + uint32_t flags, + VmaDefragmentationStats *pStats); uint32_t ProcessDefragmentations( class VmaBlockVectorDefragmentationContext *pCtx, @@ -7049,38 +7049,38 @@ public: void CommitDefragmentations( class VmaBlockVectorDefragmentationContext *pCtx, - VmaDefragmentationStats * pStats); + VmaDefragmentationStats *pStats); //////////////////////////////////////////////////////////////////////////////// // To be used only while the m_Mutex is locked. Used during defragmentation. - size_t GetBlockCount() const { return m_Blocks.size(); } + size_t GetBlockCount() const { return m_Blocks.size(); } VmaDeviceMemoryBlock *GetBlock(size_t index) const { return m_Blocks[index]; } - size_t CalcAllocationCount() const; - bool IsBufferImageGranularityConflictPossible() const; + size_t CalcAllocationCount() const; + bool IsBufferImageGranularityConflictPossible() const; private: friend class VmaDefragmentationAlgorithm_Generic; const VmaAllocator m_hAllocator; - const VmaPool m_hParentPool; - const uint32_t m_MemoryTypeIndex; + const VmaPool m_hParentPool; + const uint32_t m_MemoryTypeIndex; const VkDeviceSize m_PreferredBlockSize; - const size_t m_MinBlockCount; - const size_t m_MaxBlockCount; + const size_t m_MinBlockCount; + const size_t m_MaxBlockCount; const VkDeviceSize m_BufferImageGranularity; - const uint32_t m_FrameInUseCount; - const bool m_ExplicitBlockSize; - const uint32_t m_Algorithm; - const float m_Priority; - VMA_RW_MUTEX m_Mutex; + const uint32_t m_FrameInUseCount; + const bool m_ExplicitBlockSize; + const uint32_t m_Algorithm; + const float m_Priority; + VMA_RW_MUTEX m_Mutex; /* There can be at most one allocation that is completely empty (except when minBlockCount > 0) - a hysteresis to avoid pessimistic case of alternating creation and destruction of a VkDeviceMemory. */ bool m_HasEmptyBlock; // Incrementally sorted by sumFreeSize, ascending. VmaVector > m_Blocks; - uint32_t m_NextBlockId; + uint32_t m_NextBlockId; VkDeviceSize CalcMaxBlockSize() const; @@ -7092,36 +7092,36 @@ private: void IncrementallySortBlocks(); VkResult AllocatePage( - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - VmaAllocation * pAllocation); + VmaSuballocationType suballocType, + VmaAllocation *pAllocation); // To be used only without CAN_MAKE_OTHER_LOST flag. VkResult AllocateFromBlock( - VmaDeviceMemoryBlock * pBlock, - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + VmaDeviceMemoryBlock *pBlock, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, VmaAllocationCreateFlags allocFlags, - void * pUserData, - VmaSuballocationType suballocType, - uint32_t strategy, - VmaAllocation * pAllocation); + void *pUserData, + VmaSuballocationType suballocType, + uint32_t strategy, + VmaAllocation *pAllocation); VkResult CreateBlock(VkDeviceSize blockSize, size_t *pNewBlockIndex); // Saves result to pCtx->res. void ApplyDefragmentationMovesCpu( - class VmaBlockVectorDefragmentationContext * pDefragCtx, + class VmaBlockVectorDefragmentationContext *pDefragCtx, const VmaVector > &moves); // Saves result to pCtx->res. void ApplyDefragmentationMovesGpu( - class VmaBlockVectorDefragmentationContext * pDefragCtx, + class VmaBlockVectorDefragmentationContext *pDefragCtx, VmaVector > &moves, - VkCommandBuffer commandBuffer); + VkCommandBuffer commandBuffer); /* Used during defragmentation. pDefragmentationStats is optional. It's in/out @@ -7138,27 +7138,27 @@ public: VmaBlockVector m_BlockVector; VmaPool_T( - VmaAllocator hAllocator, + VmaAllocator hAllocator, const VmaPoolCreateInfo &createInfo, - VkDeviceSize preferredBlockSize); + VkDeviceSize preferredBlockSize); ~VmaPool_T(); uint32_t GetId() const { return m_Id; } - void SetId(uint32_t id) { + void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; } const char *GetName() const { return m_Name; } - void SetName(const char *pName); + void SetName(const char *pName); #if VMA_STATS_STRING_ENABLED //void PrintDetailedMap(class VmaStringBuilder& sb); #endif private: - uint32_t m_Id; - char * m_Name; + uint32_t m_Id; + char *m_Name; VmaPool_T *m_PrevPool = VMA_NULL; VmaPool_T *m_NextPool = VMA_NULL; friend struct VmaPoolListItemTraits; @@ -7166,8 +7166,8 @@ private: struct VmaPoolListItemTraits { typedef VmaPool_T ItemType; - static ItemType * GetPrev(const ItemType *item) { return item->m_PrevPool; } - static ItemType * GetNext(const ItemType *item) { return item->m_NextPool; } + static ItemType *GetPrev(const ItemType *item) { return item->m_PrevPool; } + static ItemType *GetNext(const ItemType *item) { return item->m_NextPool; } static ItemType *&AccessPrev(ItemType *item) { return item->m_PrevPool; } static ItemType *&AccessNext(ItemType *item) { return item->m_NextPool; } }; @@ -7183,9 +7183,9 @@ class VmaDefragmentationAlgorithm { VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm) public: VmaDefragmentationAlgorithm( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaBlockVector *pBlockVector, - uint32_t currentFrameIndex) : m_hAllocator(hAllocator), + uint32_t currentFrameIndex) : m_hAllocator(hAllocator), m_pBlockVector(pBlockVector), m_CurrentFrameIndex(currentFrameIndex) { } @@ -7193,25 +7193,25 @@ public: } virtual void AddAllocation(VmaAllocation hAlloc, VkBool32 *pChanged) = 0; - virtual void AddAll() = 0; + virtual void AddAll() = 0; virtual VkResult Defragment( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - VmaDefragmentationFlags flags) = 0; + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + VmaDefragmentationFlags flags) = 0; - virtual VkDeviceSize GetBytesMoved() const = 0; - virtual uint32_t GetAllocationsMoved() const = 0; + virtual VkDeviceSize GetBytesMoved() const = 0; + virtual uint32_t GetAllocationsMoved() const = 0; protected: - VmaAllocator const m_hAllocator; + VmaAllocator const m_hAllocator; VmaBlockVector *const m_pBlockVector; - const uint32_t m_CurrentFrameIndex; + const uint32_t m_CurrentFrameIndex; struct AllocationInfo { VmaAllocation m_hAllocation; - VkBool32 * m_pChanged; + VkBool32 *m_pChanged; AllocationInfo() : m_hAllocation(VK_NULL_HANDLE), m_pChanged(VMA_NULL) { @@ -7226,10 +7226,10 @@ class VmaDefragmentationAlgorithm_Generic : public VmaDefragmentationAlgorithm { VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Generic) public: VmaDefragmentationAlgorithm_Generic( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaBlockVector *pBlockVector, - uint32_t currentFrameIndex, - bool overlappingMoveSupported); + uint32_t currentFrameIndex, + bool overlappingMoveSupported); virtual ~VmaDefragmentationAlgorithm_Generic(); virtual void AddAllocation(VmaAllocation hAlloc, VkBool32 *pChanged); @@ -7237,19 +7237,19 @@ public: virtual VkResult Defragment( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - VmaDefragmentationFlags flags); + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + VmaDefragmentationFlags flags); virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; } - virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; } + virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; } private: uint32_t m_AllocationCount; - bool m_AllAllocations; + bool m_AllAllocations; VkDeviceSize m_BytesMoved; - uint32_t m_AllocationsMoved; + uint32_t m_AllocationsMoved; struct AllocationInfoSizeGreater { bool operator()(const AllocationInfo &lhs, const AllocationInfo &rhs) const { @@ -7264,9 +7264,9 @@ private: }; struct BlockInfo { - size_t m_OriginalBlockIndex; - VmaDeviceMemoryBlock * m_pBlock; - bool m_HasNonMovableAllocations; + size_t m_OriginalBlockIndex; + VmaDeviceMemoryBlock *m_pBlock; + bool m_HasNonMovableAllocations; VmaVector > m_Allocations; BlockInfo(const VkAllocationCallbacks *pAllocationCallbacks) : m_OriginalBlockIndex(SIZE_MAX), @@ -7276,9 +7276,9 @@ private: } void CalcHasNonMovableAllocations() { - const size_t blockAllocCount = m_pBlock->m_pMetadata->GetAllocationCount(); + const size_t blockAllocCount = m_pBlock->m_pMetadata->GetAllocationCount(); const size_t defragmentAllocCount = m_Allocations.size(); - m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount; + m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount; } void SortAllocationsBySizeDescending() { @@ -7317,13 +7317,13 @@ private: }; typedef VmaVector > BlockInfoVector; - BlockInfoVector m_Blocks; + BlockInfoVector m_Blocks; VkResult DefragmentRound( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - bool freeOldAllocations); + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + bool freeOldAllocations); size_t CalcBlocksWithNonMovableCount() const; @@ -7336,10 +7336,10 @@ class VmaDefragmentationAlgorithm_Fast : public VmaDefragmentationAlgorithm { VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Fast) public: VmaDefragmentationAlgorithm_Fast( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaBlockVector *pBlockVector, - uint32_t currentFrameIndex, - bool overlappingMoveSupported); + uint32_t currentFrameIndex, + bool overlappingMoveSupported); virtual ~VmaDefragmentationAlgorithm_Fast(); virtual void AddAllocation(VmaAllocation hAlloc, VkBool32 *pChanged) { ++m_AllocationCount; } @@ -7347,12 +7347,12 @@ public: virtual VkResult Defragment( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - VmaDefragmentationFlags flags); + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + VmaDefragmentationFlags flags); virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; } - virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; } + virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; } private: struct BlockInfo { @@ -7362,7 +7362,7 @@ private: class FreeSpaceDatabase { public: FreeSpaceDatabase() { - FreeSpace s = {}; + FreeSpace s = {}; s.blockInfoIndex = SIZE_MAX; for (size_t i = 0; i < MAX_COUNT; ++i) { m_FreeSpaces[i] = s; @@ -7390,14 +7390,14 @@ private: if (bestIndex != SIZE_MAX) { m_FreeSpaces[bestIndex].blockInfoIndex = blockInfoIndex; - m_FreeSpaces[bestIndex].offset = offset; - m_FreeSpaces[bestIndex].size = size; + m_FreeSpaces[bestIndex].offset = offset; + m_FreeSpaces[bestIndex].size = size; } } bool Fetch(VkDeviceSize alignment, VkDeviceSize size, size_t &outBlockInfoIndex, VkDeviceSize &outDstOffset) { - size_t bestIndex = SIZE_MAX; + size_t bestIndex = SIZE_MAX; VkDeviceSize bestFreeSpaceAfter = 0; for (size_t i = 0; i < MAX_COUNT; ++i) { // Structure is valid. @@ -7408,7 +7408,7 @@ private: const VkDeviceSize freeSpaceAfter = (m_FreeSpaces[i].offset + m_FreeSpaces[i].size) - (dstOffset + size); if (bestIndex == SIZE_MAX || freeSpaceAfter > bestFreeSpaceAfter) { - bestIndex = i; + bestIndex = i; bestFreeSpaceAfter = freeSpaceAfter; } } @@ -7417,7 +7417,7 @@ private: if (bestIndex != SIZE_MAX) { outBlockInfoIndex = m_FreeSpaces[bestIndex].blockInfoIndex; - outDstOffset = VmaAlignUp(m_FreeSpaces[bestIndex].offset, alignment); + outDstOffset = VmaAlignUp(m_FreeSpaces[bestIndex].offset, alignment); if (bestFreeSpaceAfter >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER) { // Leave this structure for remaining empty space. @@ -7439,7 +7439,7 @@ private: static const size_t MAX_COUNT = 4; struct FreeSpace { - size_t blockInfoIndex; // SIZE_MAX means this structure is invalid. + size_t blockInfoIndex; // SIZE_MAX means this structure is invalid. VkDeviceSize offset; VkDeviceSize size; } m_FreeSpaces[MAX_COUNT]; @@ -7448,10 +7448,10 @@ private: const bool m_OverlappingMoveSupported; uint32_t m_AllocationCount; - bool m_AllAllocations; + bool m_AllAllocations; VkDeviceSize m_BytesMoved; - uint32_t m_AllocationsMoved; + uint32_t m_AllocationsMoved; VmaVector > m_BlockInfos; @@ -7471,23 +7471,23 @@ struct VmaBlockDefragmentationContext { class VmaBlockVectorDefragmentationContext { VMA_CLASS_NO_COPY(VmaBlockVectorDefragmentationContext) public: - VkResult res; - bool mutexLocked; + VkResult res; + bool mutexLocked; VmaVector > blockContexts; - VmaVector > defragmentationMoves; - uint32_t defragmentationMovesProcessed; - uint32_t defragmentationMovesCommitted; - bool hasDefragmentationPlan; + VmaVector > defragmentationMoves; + uint32_t defragmentationMovesProcessed; + uint32_t defragmentationMovesCommitted; + bool hasDefragmentationPlan; VmaBlockVectorDefragmentationContext( - VmaAllocator hAllocator, - VmaPool hCustomPool, // Optional. + VmaAllocator hAllocator, + VmaPool hCustomPool, // Optional. VmaBlockVector *pBlockVector, - uint32_t currFrameIndex); + uint32_t currFrameIndex); ~VmaBlockVectorDefragmentationContext(); - VmaPool GetCustomPool() const { return m_hCustomPool; } - VmaBlockVector * GetBlockVector() const { return m_pBlockVector; } + VmaPool GetCustomPool() const { return m_hCustomPool; } + VmaBlockVector *GetBlockVector() const { return m_pBlockVector; } VmaDefragmentationAlgorithm *GetAlgorithm() const { return m_pAlgorithm; } void AddAllocation(VmaAllocation hAlloc, VkBool32 *pChanged); @@ -7501,17 +7501,17 @@ private: const VmaPool m_hCustomPool; // Redundant, for convenience not to fetch from m_hCustomPool->m_BlockVector or m_hAllocator->m_pBlockVectors. VmaBlockVector *const m_pBlockVector; - const uint32_t m_CurrFrameIndex; + const uint32_t m_CurrFrameIndex; // Owner of this object. VmaDefragmentationAlgorithm *m_pAlgorithm; struct AllocInfo { VmaAllocation hAlloc; - VkBool32 * pChanged; + VkBool32 *pChanged; }; // Used between constructor and Begin. VmaVector > m_Allocations; - bool m_AllAllocations; + bool m_AllAllocations; }; struct VmaDefragmentationContext_T { @@ -7519,17 +7519,17 @@ private: VMA_CLASS_NO_COPY(VmaDefragmentationContext_T) public: VmaDefragmentationContext_T( - VmaAllocator hAllocator, - uint32_t currFrameIndex, - uint32_t flags, + VmaAllocator hAllocator, + uint32_t currFrameIndex, + uint32_t flags, VmaDefragmentationStats *pStats); ~VmaDefragmentationContext_T(); void AddPools(uint32_t poolCount, const VmaPool *pPools); void AddAllocations( - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation *pAllocations, - VkBool32 * pAllocationsChanged); + VkBool32 *pAllocationsChanged); /* Returns: @@ -7546,15 +7546,15 @@ public: VkResult DefragmentPassEnd(); private: - const VmaAllocator m_hAllocator; - const uint32_t m_CurrFrameIndex; - const uint32_t m_Flags; + const VmaAllocator m_hAllocator; + const uint32_t m_CurrFrameIndex; + const uint32_t m_Flags; VmaDefragmentationStats *const m_pStats; VkDeviceSize m_MaxCpuBytesToMove; - uint32_t m_MaxCpuAllocationsToMove; + uint32_t m_MaxCpuAllocationsToMove; VkDeviceSize m_MaxGpuBytesToMove; - uint32_t m_MaxGpuAllocationsToMove; + uint32_t m_MaxGpuAllocationsToMove; // Owner of these objects. VmaBlockVectorDefragmentationContext *m_DefaultPoolContexts[VK_MAX_MEMORY_TYPES]; @@ -7568,92 +7568,92 @@ class VmaRecorder { public: VmaRecorder(); VkResult Init(const VmaRecordSettings &settings, bool useMutex); - void WriteConfiguration( - const VkPhysicalDeviceProperties & devProps, - const VkPhysicalDeviceMemoryProperties &memProps, - uint32_t vulkanApiVersion, - bool dedicatedAllocationExtensionEnabled, - bool bindMemory2ExtensionEnabled, - bool memoryBudgetExtensionEnabled, - bool deviceCoherentMemoryExtensionEnabled); + void WriteConfiguration( + const VkPhysicalDeviceProperties &devProps, + const VkPhysicalDeviceMemoryProperties &memProps, + uint32_t vulkanApiVersion, + bool dedicatedAllocationExtensionEnabled, + bool bindMemory2ExtensionEnabled, + bool memoryBudgetExtensionEnabled, + bool deviceCoherentMemoryExtensionEnabled); ~VmaRecorder(); void RecordCreateAllocator(uint32_t frameIndex); void RecordDestroyAllocator(uint32_t frameIndex); - void RecordCreatePool(uint32_t frameIndex, + void RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo &createInfo, - VmaPool pool); + VmaPool pool); void RecordDestroyPool(uint32_t frameIndex, VmaPool pool); - void RecordAllocateMemory(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, + void RecordAllocateMemory(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation); - void RecordAllocateMemoryPages(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, + VmaAllocation allocation); + void RecordAllocateMemoryPages(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, const VmaAllocationCreateInfo &createInfo, - uint64_t allocationCount, - const VmaAllocation * pAllocations); - void RecordAllocateMemoryForBuffer(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, + uint64_t allocationCount, + const VmaAllocation *pAllocations); + void RecordAllocateMemoryForBuffer(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation); - void RecordAllocateMemoryForImage(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, + VmaAllocation allocation); + void RecordAllocateMemoryForImage(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation); - void RecordFreeMemory(uint32_t frameIndex, + VmaAllocation allocation); + void RecordFreeMemory(uint32_t frameIndex, VmaAllocation allocation); - void RecordFreeMemoryPages(uint32_t frameIndex, - uint64_t allocationCount, + void RecordFreeMemoryPages(uint32_t frameIndex, + uint64_t allocationCount, const VmaAllocation *pAllocations); - void RecordSetAllocationUserData(uint32_t frameIndex, + void RecordSetAllocationUserData(uint32_t frameIndex, VmaAllocation allocation, - const void * pUserData); - void RecordCreateLostAllocation(uint32_t frameIndex, + const void *pUserData); + void RecordCreateLostAllocation(uint32_t frameIndex, VmaAllocation allocation); - void RecordMapMemory(uint32_t frameIndex, + void RecordMapMemory(uint32_t frameIndex, VmaAllocation allocation); - void RecordUnmapMemory(uint32_t frameIndex, + void RecordUnmapMemory(uint32_t frameIndex, VmaAllocation allocation); - void RecordFlushAllocation(uint32_t frameIndex, + void RecordFlushAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); - void RecordInvalidateAllocation(uint32_t frameIndex, + void RecordInvalidateAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); - void RecordCreateBuffer(uint32_t frameIndex, - const VkBufferCreateInfo & bufCreateInfo, + void RecordCreateBuffer(uint32_t frameIndex, + const VkBufferCreateInfo &bufCreateInfo, const VmaAllocationCreateInfo &allocCreateInfo, - VmaAllocation allocation); - void RecordCreateImage(uint32_t frameIndex, - const VkImageCreateInfo & imageCreateInfo, - const VmaAllocationCreateInfo &allocCreateInfo, - VmaAllocation allocation); - void RecordDestroyBuffer(uint32_t frameIndex, - VmaAllocation allocation); - void RecordDestroyImage(uint32_t frameIndex, VmaAllocation allocation); - void RecordTouchAllocation(uint32_t frameIndex, + void RecordCreateImage(uint32_t frameIndex, + const VkImageCreateInfo &imageCreateInfo, + const VmaAllocationCreateInfo &allocCreateInfo, + VmaAllocation allocation); + void RecordDestroyBuffer(uint32_t frameIndex, + VmaAllocation allocation); + void RecordDestroyImage(uint32_t frameIndex, + VmaAllocation allocation); + void RecordTouchAllocation(uint32_t frameIndex, VmaAllocation allocation); - void RecordGetAllocationInfo(uint32_t frameIndex, + void RecordGetAllocationInfo(uint32_t frameIndex, VmaAllocation allocation); void RecordMakePoolAllocationsLost(uint32_t frameIndex, - VmaPool pool); - void RecordDefragmentationBegin(uint32_t frameIndex, + VmaPool pool); + void RecordDefragmentationBegin(uint32_t frameIndex, const VmaDefragmentationInfo2 &info, - VmaDefragmentationContext ctx); - void RecordDefragmentationEnd(uint32_t frameIndex, + VmaDefragmentationContext ctx); + void RecordDefragmentationEnd(uint32_t frameIndex, VmaDefragmentationContext ctx); - void RecordSetPoolName(uint32_t frameIndex, - VmaPool pool, + void RecordSetPoolName(uint32_t frameIndex, + VmaPool pool, const char *name); private: struct CallParams { uint32_t threadId; - double time; + double time; }; class UserDataString { @@ -7662,14 +7662,14 @@ private: const char *GetString() const { return m_Str; } private: - char m_PtrStr[17]; + char m_PtrStr[17]; const char *m_Str; }; - bool m_UseMutex; - VmaRecordFlags m_Flags; - FILE * m_File; - VMA_MUTEX m_FileMutex; + bool m_UseMutex; + VmaRecordFlags m_Flags; + FILE *m_File; + VMA_MUTEX m_FileMutex; std::chrono::time_point m_RecordingStartTime; void GetBasicParams(CallParams &outParams); @@ -7701,10 +7701,10 @@ public: template VmaAllocation Allocate(Types... args); - void Free(VmaAllocation hAlloc); + void Free(VmaAllocation hAlloc); private: - VMA_MUTEX m_Mutex; + VMA_MUTEX m_Mutex; VmaPoolAllocator m_Allocator; }; @@ -7714,19 +7714,19 @@ struct VmaCurrentBudgetData { #if VMA_MEMORY_BUDGET VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch; - VMA_RW_MUTEX m_BudgetMutex; - uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS]; - uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS]; - uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS]; + VMA_RW_MUTEX m_BudgetMutex; + uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS]; + uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS]; + uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS]; #endif // #if VMA_MEMORY_BUDGET VmaCurrentBudgetData() { for (uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex) { - m_BlockBytes[heapIndex] = 0; + m_BlockBytes[heapIndex] = 0; m_AllocationBytes[heapIndex] = 0; #if VMA_MEMORY_BUDGET - m_VulkanUsage[heapIndex] = 0; - m_VulkanBudget[heapIndex] = 0; + m_VulkanUsage[heapIndex] = 0; + m_VulkanBudget[heapIndex] = 0; m_BlockBytesAtBudgetFetch[heapIndex] = 0; #endif } @@ -7756,36 +7756,36 @@ struct VmaCurrentBudgetData { struct VmaAllocator_T { VMA_CLASS_NO_COPY(VmaAllocator_T) public: - bool m_UseMutex; - uint32_t m_VulkanApiVersion; - bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). - bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). - bool m_UseExtMemoryBudget; - bool m_UseAmdDeviceCoherentMemory; - bool m_UseKhrBufferDeviceAddress; - bool m_UseExtMemoryPriority; - VkDevice m_hDevice; - VkInstance m_hInstance; - bool m_AllocationCallbacksSpecified; - VkAllocationCallbacks m_AllocationCallbacks; - VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks; + bool m_UseMutex; + uint32_t m_VulkanApiVersion; + bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). + bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). + bool m_UseExtMemoryBudget; + bool m_UseAmdDeviceCoherentMemory; + bool m_UseKhrBufferDeviceAddress; + bool m_UseExtMemoryPriority; + VkDevice m_hDevice; + VkInstance m_hInstance; + bool m_AllocationCallbacksSpecified; + VkAllocationCallbacks m_AllocationCallbacks; + VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks; VmaAllocationObjectAllocator m_AllocationObjectAllocator; // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size. uint32_t m_HeapSizeLimitMask; - VkPhysicalDeviceProperties m_PhysicalDeviceProperties; + VkPhysicalDeviceProperties m_PhysicalDeviceProperties; VkPhysicalDeviceMemoryProperties m_MemProps; // Default pools. VmaBlockVector *m_pBlockVectors[VK_MAX_MEMORY_TYPES]; typedef VmaIntrusiveLinkedList DedicatedAllocationLinkedList; - DedicatedAllocationLinkedList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES]; - VMA_RW_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES]; + DedicatedAllocationLinkedList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES]; + VMA_RW_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES]; VmaCurrentBudgetData m_Budget; - VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects. + VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects. VmaAllocator_T(const VmaAllocatorCreateInfo *pCreateInfo); VkResult Init(const VmaAllocatorCreateInfo *pCreateInfo); @@ -7834,32 +7834,32 @@ public: #endif void GetBufferMemoryRequirements( - VkBuffer hBuffer, + VkBuffer hBuffer, VkMemoryRequirements &memReq, - bool & requiresDedicatedAllocation, - bool & prefersDedicatedAllocation) const; + bool &requiresDedicatedAllocation, + bool &prefersDedicatedAllocation) const; void GetImageMemoryRequirements( - VkImage hImage, + VkImage hImage, VkMemoryRequirements &memReq, - bool & requiresDedicatedAllocation, - bool & prefersDedicatedAllocation) const; + bool &requiresDedicatedAllocation, + bool &prefersDedicatedAllocation) const; // Main allocation function. VkResult AllocateMemory( - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, // UINT32_MAX when unknown. - VkImage dedicatedImage, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, // UINT32_MAX when unknown. + VkImage dedicatedImage, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations); + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations); // Main deallocation function. void FreeMemory( - size_t allocationCount, + size_t allocationCount, const VmaAllocation *pAllocations); void CalculateStats(VmaStats *pStats); @@ -7873,14 +7873,14 @@ public: VkResult DefragmentationBegin( const VmaDefragmentationInfo2 &info, - VmaDefragmentationStats * pStats, - VmaDefragmentationContext * pContext); + VmaDefragmentationStats *pStats, + VmaDefragmentationContext *pContext); VkResult DefragmentationEnd( VmaDefragmentationContext context); VkResult DefragmentationPassBegin( VmaDefragmentationPassInfo *pInfo, - VmaDefragmentationContext context); + VmaDefragmentationContext context); VkResult DefragmentationPassEnd( VmaDefragmentationContext context); @@ -7888,10 +7888,10 @@ public: bool TouchAllocation(VmaAllocation hAllocation); VkResult CreatePool(const VmaPoolCreateInfo *pCreateInfo, VmaPool *pPool); - void DestroyPool(VmaPool pool); - void GetPoolStats(VmaPool pool, VmaPoolStats *pPoolStats); + void DestroyPool(VmaPool pool); + void GetPoolStats(VmaPool pool, VmaPoolStats *pPoolStats); - void SetCurrentFrameIndex(uint32_t frameIndex); + void SetCurrentFrameIndex(uint32_t frameIndex); uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); } void MakePoolAllocationsLost( @@ -7909,36 +7909,36 @@ public: // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR. VkResult BindVulkanBuffer( VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkBuffer buffer, - const void * pNext); + VkDeviceSize memoryOffset, + VkBuffer buffer, + const void *pNext); // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR. VkResult BindVulkanImage( VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkImage image, - const void * pNext); + VkDeviceSize memoryOffset, + VkImage image, + const void *pNext); VkResult Map(VmaAllocation hAllocation, void **ppData); - void Unmap(VmaAllocation hAllocation); + void Unmap(VmaAllocation hAllocation); VkResult BindBufferMemory( VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void * pNext); + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void *pNext); VkResult BindImageMemory( VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void * pNext); + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void *pNext); VkResult FlushOrInvalidateAllocation( VmaAllocation hAllocation, VkDeviceSize offset, VkDeviceSize size, VMA_CACHE_OPERATION op); VkResult FlushOrInvalidateAllocations( - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation *allocations, const VkDeviceSize *offsets, const VkDeviceSize *sizes, VMA_CACHE_OPERATION op); @@ -7954,11 +7954,11 @@ public: private: VkDeviceSize m_PreferredLargeHeapBlockSize; - VkPhysicalDevice m_PhysicalDevice; + VkPhysicalDevice m_PhysicalDevice; VMA_ATOMIC_UINT32 m_CurrentFrameIndex; VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized. - VMA_RW_MUTEX m_PoolsMutex; + VMA_RW_MUTEX m_PoolsMutex; typedef VmaIntrusiveLinkedList PoolList; // Protected by m_PoolsMutex. PoolList m_Pools; @@ -7990,44 +7990,44 @@ private: VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex); VkResult AllocateMemoryOfType( - VkDeviceSize size, - VkDeviceSize alignment, - bool dedicatedAllocation, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, - VkImage dedicatedImage, + VkDeviceSize size, + VkDeviceSize alignment, + bool dedicatedAllocation, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, + VkImage dedicatedImage, const VmaAllocationCreateInfo &createInfo, - uint32_t memTypeIndex, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations); + uint32_t memTypeIndex, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations); // Helper function only to be used inside AllocateDedicatedMemory. VkResult AllocateDedicatedMemoryPage( - VkDeviceSize size, - VmaSuballocationType suballocType, - uint32_t memTypeIndex, + VkDeviceSize size, + VmaSuballocationType suballocType, + uint32_t memTypeIndex, const VkMemoryAllocateInfo &allocInfo, - bool map, - bool isUserDataString, - void * pUserData, - VmaAllocation * pAllocation); + bool map, + bool isUserDataString, + void *pUserData, + VmaAllocation *pAllocation); // Allocates and registers new VkDeviceMemory specifically for dedicated allocations. VkResult AllocateDedicatedMemory( - VkDeviceSize size, + VkDeviceSize size, VmaSuballocationType suballocType, - uint32_t memTypeIndex, - bool withinBudget, - bool map, - bool isUserDataString, - void * pUserData, - float priority, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, - VkImage dedicatedImage, - size_t allocationCount, - VmaAllocation * pAllocations); + uint32_t memTypeIndex, + bool withinBudget, + bool map, + bool isUserDataString, + void *pUserData, + float priority, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, + VkImage dedicatedImage, + size_t allocationCount, + VmaAllocation *pAllocations); void FreeDedicatedMemory(const VmaAllocation allocation); @@ -8095,7 +8095,7 @@ static void vma_delete_array(VmaAllocator hAllocator, T *ptr, size_t count) { class VmaStringBuilder { public: VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator(alloc->GetAllocationCallbacks())) {} - size_t GetLength() const { return m_Data.size(); } + size_t GetLength() const { return m_Data.size(); } const char *GetData() const { return m_Data.data(); } void Add(char ch) { m_Data.push_back(ch); } @@ -8187,13 +8187,13 @@ private: }; struct StackItem { COLLECTION_TYPE type; - uint32_t valueCount; - bool singleLineMode; + uint32_t valueCount; + bool singleLineMode; }; - VmaStringBuilder & m_SB; + VmaStringBuilder &m_SB; VmaVector > m_Stack; - bool m_InsideString; + bool m_InsideString; void BeginValue(bool isString); void WriteIndent(bool oneLess = false); @@ -8218,8 +8218,8 @@ void VmaJsonWriter::BeginObject(bool singleLine) { m_SB.Add('{'); StackItem item; - item.type = COLLECTION_TYPE_OBJECT; - item.valueCount = 0; + item.type = COLLECTION_TYPE_OBJECT; + item.valueCount = 0; item.singleLineMode = singleLine; m_Stack.push_back(item); } @@ -8241,8 +8241,8 @@ void VmaJsonWriter::BeginArray(bool singleLine) { m_SB.Add('['); StackItem item; - item.type = COLLECTION_TYPE_ARRAY; - item.valueCount = 0; + item.type = COLLECTION_TYPE_ARRAY; + item.valueCount = 0; item.singleLineMode = singleLine; m_Stack.push_back(item); } @@ -8411,9 +8411,9 @@ void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void *pUserData) { } void VmaAllocation_T::ChangeBlockAllocation( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaDeviceMemoryBlock *block, - VkDeviceSize offset) { + VkDeviceSize offset) { VMA_ASSERT(block != VMA_NULL); VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); @@ -8426,7 +8426,7 @@ void VmaAllocation_T::ChangeBlockAllocation( block->Map(hAllocator, mapRefCount, VMA_NULL); } - m_BlockAllocation.m_Block = block; + m_BlockAllocation.m_Block = block; m_BlockAllocation.m_Offset = offset; } @@ -8608,7 +8608,7 @@ VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void **ppDa ppData); if (result == VK_SUCCESS) { m_DedicatedAllocation.m_pMappedData = *ppData; - m_MapCount = 1; + m_MapCount = 1; } return result; } @@ -8687,7 +8687,7 @@ struct VmaSuballocationItemSizeLess { } bool operator()( const VmaSuballocationList::iterator lhs, - VkDeviceSize rhsSize) const { + VkDeviceSize rhsSize) const { return lhs->size < rhsSize; } }; @@ -8702,9 +8702,9 @@ VmaBlockMetadata::VmaBlockMetadata(VmaAllocator hAllocator) : m_Size(0), #if VMA_STATS_STRING_ENABLED void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter &json, - VkDeviceSize unusedBytes, - size_t allocationCount, - size_t unusedRangeCount) const { + VkDeviceSize unusedBytes, + size_t allocationCount, + size_t unusedRangeCount) const { json.BeginObject(); json.WriteString("TotalBytes"); @@ -8724,8 +8724,8 @@ void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter &json, } void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter &json, - VkDeviceSize offset, - VmaAllocation hAllocation) const { + VkDeviceSize offset, + VmaAllocation hAllocation) const { json.BeginObject(true); json.WriteString("Offset"); @@ -8737,8 +8737,8 @@ void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter &json, } void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter &json, - VkDeviceSize offset, - VkDeviceSize size) const { + VkDeviceSize offset, + VkDeviceSize size) const { json.BeginObject(true); json.WriteString("Offset"); @@ -8776,14 +8776,14 @@ VmaBlockMetadata_Generic::~VmaBlockMetadata_Generic() { void VmaBlockMetadata_Generic::Init(VkDeviceSize size) { VmaBlockMetadata::Init(size); - m_FreeCount = 1; + m_FreeCount = 1; m_SumFreeSize = size; VmaSuballocation suballoc = {}; - suballoc.offset = 0; - suballoc.size = size; - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - suballoc.hAllocation = VK_NULL_HANDLE; + suballoc.offset = 0; + suballoc.size = size; + suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + suballoc.hAllocation = VK_NULL_HANDLE; VMA_ASSERT(size > VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER); m_Suballocations.push_back(suballoc); @@ -8883,14 +8883,14 @@ void VmaBlockMetadata_Generic::CalcAllocationStatInfo(VmaStatInfo &outInfo) cons outInfo.blockCount = 1; const uint32_t rangeCount = (uint32_t)m_Suballocations.size(); - outInfo.allocationCount = rangeCount - m_FreeCount; - outInfo.unusedRangeCount = m_FreeCount; + outInfo.allocationCount = rangeCount - m_FreeCount; + outInfo.unusedRangeCount = m_FreeCount; outInfo.unusedBytes = m_SumFreeSize; - outInfo.usedBytes = GetSize() - outInfo.unusedBytes; + outInfo.usedBytes = GetSize() - outInfo.unusedBytes; - outInfo.allocationSizeMin = UINT64_MAX; - outInfo.allocationSizeMax = 0; + outInfo.allocationSizeMin = UINT64_MAX; + outInfo.allocationSizeMax = 0; outInfo.unusedRangeSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMax = 0; @@ -8943,15 +8943,15 @@ void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter &json) const #endif // #if VMA_STATS_STRING_ENABLED bool VmaBlockMetadata_Generic::CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) { VMA_ASSERT(allocSize > 0); VMA_ASSERT(!upperAddress); @@ -9044,9 +9044,9 @@ bool VmaBlockMetadata_Generic::CreateAllocationRequest( if (canMakeOtherLost) { // Brute-force algorithm. TODO: Come up with something better. - bool found = false; + bool found = false; VmaAllocationRequest tmpAllocRequest = {}; - tmpAllocRequest.type = VmaAllocationRequestType::Normal; + tmpAllocRequest.type = VmaAllocationRequestType::Normal; for (VmaSuballocationList::iterator suballocIt = m_Suballocations.begin(); suballocIt != m_Suballocations.end(); ++suballocIt) { @@ -9066,14 +9066,14 @@ bool VmaBlockMetadata_Generic::CreateAllocationRequest( &tmpAllocRequest.sumFreeSize, &tmpAllocRequest.sumItemSize)) { if (strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT) { - *pAllocationRequest = tmpAllocRequest; + *pAllocationRequest = tmpAllocRequest; pAllocationRequest->item = suballocIt; break; } if (!found || tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost()) { - *pAllocationRequest = tmpAllocRequest; + *pAllocationRequest = tmpAllocRequest; pAllocationRequest->item = suballocIt; - found = true; + found = true; } } } @@ -9086,8 +9086,8 @@ bool VmaBlockMetadata_Generic::CreateAllocationRequest( } bool VmaBlockMetadata_Generic::MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest) { VMA_ASSERT(pAllocationRequest && pAllocationRequest->type == VmaAllocationRequestType::Normal); @@ -9149,9 +9149,9 @@ VkResult VmaBlockMetadata_Generic::CheckCorruption(const void *pBlockData) { void VmaBlockMetadata_Generic::Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation) { + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation) { VMA_ASSERT(request.type == VmaAllocationRequestType::Normal); VMA_ASSERT(request.item != m_Suballocations.end()); VmaSuballocation &suballoc = *request.item; @@ -9167,17 +9167,17 @@ void VmaBlockMetadata_Generic::Alloc( // it to become used. UnregisterFreeSuballocation(request.item); - suballoc.offset = request.offset; - suballoc.size = allocSize; - suballoc.type = type; + suballoc.offset = request.offset; + suballoc.size = allocSize; + suballoc.type = type; suballoc.hAllocation = hAllocation; // If there are any free bytes remaining at the end, insert new free suballocation after current one. if (paddingEnd) { - VmaSuballocation paddingSuballoc = {}; - paddingSuballoc.offset = request.offset + allocSize; - paddingSuballoc.size = paddingEnd; - paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + VmaSuballocation paddingSuballoc = {}; + paddingSuballoc.offset = request.offset + allocSize; + paddingSuballoc.size = paddingEnd; + paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; VmaSuballocationList::iterator next = request.item; ++next; const VmaSuballocationList::iterator paddingEndItem = @@ -9188,9 +9188,9 @@ void VmaBlockMetadata_Generic::Alloc( // If there are any free bytes remaining at the beginning, insert new free suballocation before current one. if (paddingBegin) { VmaSuballocation paddingSuballoc = {}; - paddingSuballoc.offset = request.offset - paddingBegin; - paddingSuballoc.size = paddingBegin; - paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + paddingSuballoc.offset = request.offset - paddingBegin; + paddingSuballoc.size = paddingBegin; + paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; const VmaSuballocationList::iterator paddingBeginItem = m_Suballocations.insert(request.item, paddingSuballoc); RegisterFreeSuballocation(paddingBeginItem); @@ -9248,26 +9248,26 @@ bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const { } bool VmaBlockMetadata_Generic::CheckAllocation( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, VmaSuballocationList::const_iterator suballocItem, - bool canMakeOtherLost, - VkDeviceSize * pOffset, - size_t * itemsToMakeLostCount, - VkDeviceSize * pSumFreeSize, - VkDeviceSize * pSumItemSize) const { + bool canMakeOtherLost, + VkDeviceSize *pOffset, + size_t *itemsToMakeLostCount, + VkDeviceSize *pSumFreeSize, + VkDeviceSize *pSumItemSize) const { VMA_ASSERT(allocSize > 0); VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); VMA_ASSERT(suballocItem != m_Suballocations.cend()); VMA_ASSERT(pOffset != VMA_NULL); *itemsToMakeLostCount = 0; - *pSumFreeSize = 0; - *pSumItemSize = 0; + *pSumFreeSize = 0; + *pSumItemSize = 0; if (canMakeOtherLost) { if (suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE) { @@ -9301,8 +9301,8 @@ bool VmaBlockMetadata_Generic::CheckAllocation( // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment) { - bool bufferImageGranularityConflict = false; - VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; + bool bufferImageGranularityConflict = false; + VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; while (prevSuballocItem != m_Suballocations.cbegin()) { --prevSuballocItem; const VmaSuballocation &prevSuballoc = *prevSuballocItem; @@ -9413,8 +9413,8 @@ bool VmaBlockMetadata_Generic::CheckAllocation( // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment) { - bool bufferImageGranularityConflict = false; - VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; + bool bufferImageGranularityConflict = false; + VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; while (prevSuballocItem != m_Suballocations.cbegin()) { --prevSuballocItem; const VmaSuballocation &prevSuballoc = *prevSuballocItem; @@ -9484,8 +9484,8 @@ void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem) { // Change this suballocation to be marked as free. VmaSuballocation &suballoc = *suballocItem; - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - suballoc.hAllocation = VK_NULL_HANDLE; + suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + suballoc.hAllocation = VK_NULL_HANDLE; // Update totals. ++m_FreeCount; @@ -9574,14 +9574,14 @@ void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList: } bool VmaBlockMetadata_Generic::IsBufferImageGranularityConflictPossible( - VkDeviceSize bufferImageGranularity, + VkDeviceSize bufferImageGranularity, VmaSuballocationType &inOutPrevSuballocType) const { if (bufferImageGranularity == 1 || IsEmpty()) { return false; } - VkDeviceSize minAlignment = VK_WHOLE_SIZE; - bool typeConflictFound = false; + VkDeviceSize minAlignment = VK_WHOLE_SIZE; + bool typeConflictFound = false; for (VmaSuballocationList::const_iterator it = m_Suballocations.cbegin(); it != m_Suballocations.cend(); ++it) { @@ -9643,16 +9643,16 @@ bool VmaBlockMetadata_Linear::Validate() const { VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size()); VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size()); - VkDeviceSize sumUsedSize = 0; + VkDeviceSize sumUsedSize = 0; const size_t suballoc1stCount = suballocations1st.size(); - VkDeviceSize offset = VMA_DEBUG_MARGIN; + VkDeviceSize offset = VMA_DEBUG_MARGIN; if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const size_t suballoc2ndCount = suballocations2nd.size(); - size_t nullItem2ndCount = 0; + size_t nullItem2ndCount = 0; for (size_t i = 0; i < suballoc2ndCount; ++i) { const VmaSuballocation &suballoc = suballocations2nd[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE)); VMA_VALIDATE(suballoc.offset >= offset); @@ -9681,7 +9681,7 @@ bool VmaBlockMetadata_Linear::Validate() const { for (size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i) { const VmaSuballocation &suballoc = suballocations1st[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE)); VMA_VALIDATE(suballoc.offset >= offset); @@ -9701,10 +9701,10 @@ bool VmaBlockMetadata_Linear::Validate() const { if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { const size_t suballoc2ndCount = suballocations2nd.size(); - size_t nullItem2ndCount = 0; + size_t nullItem2ndCount = 0; for (size_t i = suballoc2ndCount; i--;) { const VmaSuballocation &suballoc = suballocations2nd[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); + const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE)); VMA_VALIDATE(suballoc.offset >= offset); @@ -9758,7 +9758,7 @@ VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const { const size_t suballocations1stCount = suballocations1st.size(); VMA_ASSERT(suballocations1stCount > m_1stNullItemsBeginCount); const VmaSuballocation &firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; - const VmaSuballocation &lastSuballoc = suballocations1st[suballocations1stCount - 1]; + const VmaSuballocation &lastSuballoc = suballocations1st[suballocations1stCount - 1]; return VMA_MAX( firstSuballoc.offset, size - (lastSuballoc.offset + lastSuballoc.size)); @@ -9771,8 +9771,8 @@ VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const { */ { const SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); - const VmaSuballocation & lastSuballoc2nd = suballocations2nd.back(); - const VmaSuballocation & firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount]; + const VmaSuballocation &lastSuballoc2nd = suballocations2nd.back(); + const VmaSuballocation &firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount]; return firstSuballoc1st.offset - (lastSuballoc2nd.offset + lastSuballoc2nd.size); } break; @@ -9783,8 +9783,8 @@ VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const { */ { const SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); - const VmaSuballocation & topSuballoc2nd = suballocations2nd.back(); - const VmaSuballocation & lastSuballoc1st = suballocations1st.back(); + const VmaSuballocation &topSuballoc2nd = suballocations2nd.back(); + const VmaSuballocation &lastSuballoc1st = suballocations1st.back(); return topSuballoc2nd.offset - (lastSuballoc1st.offset + lastSuballoc1st.size); } break; @@ -9796,18 +9796,18 @@ VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const { } void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo &outInfo) const { - const VkDeviceSize size = GetSize(); + const VkDeviceSize size = GetSize(); const SuballocationVectorType &suballocations1st = AccessSuballocations1st(); const SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); - outInfo.blockCount = 1; - outInfo.allocationCount = (uint32_t)GetAllocationCount(); - outInfo.unusedRangeCount = 0; - outInfo.usedBytes = 0; - outInfo.allocationSizeMin = UINT64_MAX; - outInfo.allocationSizeMax = 0; + outInfo.blockCount = 1; + outInfo.allocationCount = (uint32_t)GetAllocationCount(); + outInfo.unusedRangeCount = 0; + outInfo.usedBytes = 0; + outInfo.allocationSizeMin = UINT64_MAX; + outInfo.allocationSizeMax = 0; outInfo.unusedRangeSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMax = 0; @@ -9815,7 +9815,7 @@ void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo &outInfo) const if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; + size_t nextAlloc2ndIndex = 0; while (lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while (nextAlloc2ndIndex < suballoc2ndCount && @@ -9864,7 +9864,7 @@ void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo &outInfo) const } } - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while (lastOffset < freeSpace1stTo2ndEnd) { @@ -9970,9 +9970,9 @@ void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo &outInfo) const void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats &inoutStats) const { const SuballocationVectorType &suballocations1st = AccessSuballocations1st(); const SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); - const VkDeviceSize size = GetSize(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); + const VkDeviceSize size = GetSize(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); inoutStats.size += size; @@ -9980,7 +9980,7 @@ void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats &inoutStats) const { if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount; + size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount; while (lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while (nextAlloc2ndIndex < suballoc2ndCount && @@ -10025,7 +10025,7 @@ void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats &inoutStats) const { } } - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while (lastOffset < freeSpace1stTo2ndEnd) { @@ -10120,23 +10120,23 @@ void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats &inoutStats) const { #if VMA_STATS_STRING_ENABLED void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter &json) const { - const VkDeviceSize size = GetSize(); + const VkDeviceSize size = GetSize(); const SuballocationVectorType &suballocations1st = AccessSuballocations1st(); const SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); + const size_t suballoc1stCount = suballocations1st.size(); + const size_t suballoc2ndCount = suballocations2nd.size(); // FIRST PASS - size_t unusedRangeCount = 0; - VkDeviceSize usedBytes = 0; + size_t unusedRangeCount = 0; + VkDeviceSize usedBytes = 0; VkDeviceSize lastOffset = 0; size_t alloc2ndCount = 0; if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; + size_t nextAlloc2ndIndex = 0; while (lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while (nextAlloc2ndIndex < suballoc2ndCount && @@ -10176,8 +10176,8 @@ void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter &json) const } } - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; - size_t alloc1stCount = 0; + size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; + size_t alloc1stCount = 0; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while (lastOffset < freeSpace1stTo2ndEnd) { @@ -10267,7 +10267,7 @@ void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter &json) const if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; + size_t nextAlloc2ndIndex = 0; while (lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while (nextAlloc2ndIndex < suballoc2ndCount && @@ -10395,15 +10395,15 @@ void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter &json) const #endif // #if VMA_STATS_STRING_ENABLED bool VmaBlockMetadata_Linear::CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) { VMA_ASSERT(allocSize > 0); VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); @@ -10418,16 +10418,16 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest( } bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) { - const VkDeviceSize size = GetSize(); + const VkDeviceSize size = GetSize(); SuballocationVectorType &suballocations1st = AccessSuballocations1st(); SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); @@ -10443,7 +10443,7 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( VkDeviceSize resultBaseOffset = size - allocSize; if (!suballocations2nd.empty()) { const VmaSuballocation &lastSuballoc = suballocations2nd.back(); - resultBaseOffset = lastSuballoc.offset - allocSize; + resultBaseOffset = lastSuballoc.offset - allocSize; if (allocSize > lastSuballoc.offset) { return false; } @@ -10503,12 +10503,12 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( } // All tests passed: Success. - pAllocationRequest->offset = resultOffset; + pAllocationRequest->offset = resultOffset; pAllocationRequest->sumFreeSize = resultBaseOffset + allocSize - endOf1st; pAllocationRequest->sumItemSize = 0; // pAllocationRequest->item unused. pAllocationRequest->itemsToMakeLostCount = 0; - pAllocationRequest->type = VmaAllocationRequestType::UpperAddress; + pAllocationRequest->type = VmaAllocationRequestType::UpperAddress; return true; } @@ -10516,16 +10516,16 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( } bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) { - const VkDeviceSize size = GetSize(); + const VkDeviceSize size = GetSize(); SuballocationVectorType &suballocations1st = AccessSuballocations1st(); SuballocationVectorType &suballocations2nd = AccessSuballocations2nd(); @@ -10535,7 +10535,7 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( VkDeviceSize resultBaseOffset = 0; if (!suballocations1st.empty()) { const VmaSuballocation &lastSuballoc = suballocations1st.back(); - resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; + resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; } // Start from offset equal to beginning of free space. @@ -10590,11 +10590,11 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( } // All tests passed: Success. - pAllocationRequest->offset = resultOffset; + pAllocationRequest->offset = resultOffset; pAllocationRequest->sumFreeSize = freeSpaceEnd - resultBaseOffset; pAllocationRequest->sumItemSize = 0; // pAllocationRequest->item, customData unused. - pAllocationRequest->type = VmaAllocationRequestType::EndOf1st; + pAllocationRequest->type = VmaAllocationRequestType::EndOf1st; pAllocationRequest->itemsToMakeLostCount = 0; return true; } @@ -10608,7 +10608,7 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( VkDeviceSize resultBaseOffset = 0; if (!suballocations2nd.empty()) { const VmaSuballocation &lastSuballoc = suballocations2nd.back(); - resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; + resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; } // Start from offset equal to beginning of free space. @@ -10643,8 +10643,8 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( } pAllocationRequest->itemsToMakeLostCount = 0; - pAllocationRequest->sumItemSize = 0; - size_t index1st = m_1stNullItemsBeginCount; + pAllocationRequest->sumItemSize = 0; + size_t index1st = m_1stNullItemsBeginCount; if (canMakeOtherLost) { while (index1st < suballocations1st.size() && @@ -10733,8 +10733,8 @@ bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( } bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest) { if (pAllocationRequest->itemsToMakeLostCount == 0) { return true; @@ -10744,8 +10744,8 @@ bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost( // We always start from 1st. SuballocationVectorType *suballocations = &AccessSuballocations1st(); - size_t index = m_1stNullItemsBeginCount; - size_t madeLostCount = 0; + size_t index = m_1stNullItemsBeginCount; + size_t madeLostCount = 0; while (madeLostCount < pAllocationRequest->itemsToMakeLostCount) { if (index == suballocations->size()) { index = 0; @@ -10762,7 +10762,7 @@ bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost( VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE); VMA_ASSERT(suballoc.hAllocation->CanBecomeLost()); if (suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; m_SumFreeSize += suballoc.size; if (suballocations == &AccessSuballocations1st()) { @@ -10793,7 +10793,7 @@ uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE && suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; ++m_1stNullItemsMiddleCount; m_SumFreeSize += suballoc.size; @@ -10807,7 +10807,7 @@ uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE && suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; ++m_2ndNullItemsCount; m_SumFreeSize += suballoc.size; @@ -10858,9 +10858,9 @@ VkResult VmaBlockMetadata_Linear::CheckCorruption(const void *pBlockData) { void VmaBlockMetadata_Linear::Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation) { + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation) { const VmaSuballocation newSuballoc = {request.offset, allocSize, hAllocation, type}; switch (request.type) { @@ -10926,7 +10926,7 @@ void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset) { // First allocation: Mark it as next empty at the beginning. VmaSuballocation &firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; if (firstSuballoc.offset == offset) { - firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; + firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; firstSuballoc.hAllocation = VK_NULL_HANDLE; m_SumFreeSize += firstSuballoc.size; ++m_1stNullItemsBeginCount; @@ -10968,7 +10968,7 @@ void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset) { refSuballoc, VmaSuballocationOffsetLess()); if (it != suballocations1st.end()) { - it->type = VMA_SUBALLOCATION_TYPE_FREE; + it->type = VMA_SUBALLOCATION_TYPE_FREE; it->hAllocation = VK_NULL_HANDLE; ++m_1stNullItemsMiddleCount; m_SumFreeSize += it->size; @@ -10984,7 +10984,7 @@ void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset) { // Rest of members stays uninitialized intentionally for better performance. SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) : VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater()); if (it != suballocations2nd.end()) { - it->type = VMA_SUBALLOCATION_TYPE_FREE; + it->type = VMA_SUBALLOCATION_TYPE_FREE; it->hAllocation = VK_NULL_HANDLE; ++m_2ndNullItemsCount; m_SumFreeSize += it->size; @@ -11009,10 +11009,10 @@ void VmaBlockMetadata_Linear::CleanupAfterFree() { if (IsEmpty()) { suballocations1st.clear(); suballocations2nd.clear(); - m_1stNullItemsBeginCount = 0; + m_1stNullItemsBeginCount = 0; m_1stNullItemsMiddleCount = 0; - m_2ndNullItemsCount = 0; - m_2ndVectorMode = SECOND_VECTOR_EMPTY; + m_2ndNullItemsCount = 0; + m_2ndVectorMode = SECOND_VECTOR_EMPTY; } else { const size_t suballoc1stCount = suballocations1st.size(); const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; @@ -11048,7 +11048,7 @@ void VmaBlockMetadata_Linear::CleanupAfterFree() { if (ShouldCompact1st()) { const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount; - size_t srcIndex = m_1stNullItemsBeginCount; + size_t srcIndex = m_1stNullItemsBeginCount; for (size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex) { while (suballocations1st[srcIndex].hAllocation == VK_NULL_HANDLE) { ++srcIndex; @@ -11059,7 +11059,7 @@ void VmaBlockMetadata_Linear::CleanupAfterFree() { ++srcIndex; } suballocations1st.resize(nonNullItemCount); - m_1stNullItemsBeginCount = 0; + m_1stNullItemsBeginCount = 0; m_1stNullItemsMiddleCount = 0; } @@ -11075,7 +11075,7 @@ void VmaBlockMetadata_Linear::CleanupAfterFree() { if (!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { // Swap 1st with 2nd. Now 2nd is empty. - m_2ndVectorMode = SECOND_VECTOR_EMPTY; + m_2ndVectorMode = SECOND_VECTOR_EMPTY; m_1stNullItemsMiddleCount = m_2ndNullItemsCount; while (m_1stNullItemsBeginCount < suballocations2nd.size() && suballocations2nd[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE) { @@ -11109,7 +11109,7 @@ VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy() { void VmaBlockMetadata_Buddy::Init(VkDeviceSize size) { VmaBlockMetadata::Init(size); - m_UsableSize = VmaPrevPow2(size); + m_UsableSize = VmaPrevPow2(size); m_SumFreeSize = m_UsableSize; // Calculate m_LevelCount. @@ -11119,11 +11119,11 @@ void VmaBlockMetadata_Buddy::Init(VkDeviceSize size) { ++m_LevelCount; } - Node *rootNode = vma_new(GetAllocationCallbacks(), Node)(); + Node *rootNode = vma_new(GetAllocationCallbacks(), Node)(); rootNode->offset = 0; - rootNode->type = Node::TYPE_FREE; + rootNode->type = Node::TYPE_FREE; rootNode->parent = VMA_NULL; - rootNode->buddy = VMA_NULL; + rootNode->buddy = VMA_NULL; m_Root = rootNode; AddToFreeListFront(0, rootNode); @@ -11238,15 +11238,15 @@ void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter &json) const { #endif // #if VMA_STATS_STRING_ENABLED bool VmaBlockMetadata_Buddy::CreateAllocationRequest( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, - VkDeviceSize bufferImageGranularity, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - bool canMakeOtherLost, - uint32_t strategy, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, + VkDeviceSize bufferImageGranularity, + VkDeviceSize allocSize, + VkDeviceSize allocAlignment, + bool upperAddress, + VmaSuballocationType allocType, + bool canMakeOtherLost, + uint32_t strategy, VmaAllocationRequest *pAllocationRequest) { VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm."); @@ -11256,7 +11256,7 @@ bool VmaBlockMetadata_Buddy::CreateAllocationRequest( allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL) { allocAlignment = VMA_MAX(allocAlignment, bufferImageGranularity); - allocSize = VMA_MAX(allocSize, bufferImageGranularity); + allocSize = VMA_MAX(allocSize, bufferImageGranularity); } if (allocSize > m_UsableSize) { @@ -11269,12 +11269,12 @@ bool VmaBlockMetadata_Buddy::CreateAllocationRequest( freeNode != VMA_NULL; freeNode = freeNode->free.next) { if (freeNode->offset % allocAlignment == 0) { - pAllocationRequest->type = VmaAllocationRequestType::Normal; - pAllocationRequest->offset = freeNode->offset; - pAllocationRequest->sumFreeSize = LevelToNodeSize(level); - pAllocationRequest->sumItemSize = 0; + pAllocationRequest->type = VmaAllocationRequestType::Normal; + pAllocationRequest->offset = freeNode->offset; + pAllocationRequest->sumFreeSize = LevelToNodeSize(level); + pAllocationRequest->sumItemSize = 0; pAllocationRequest->itemsToMakeLostCount = 0; - pAllocationRequest->customData = (void *)(uintptr_t)level; + pAllocationRequest->customData = (void *)(uintptr_t)level; return true; } } @@ -11284,8 +11284,8 @@ bool VmaBlockMetadata_Buddy::CreateAllocationRequest( } bool VmaBlockMetadata_Buddy::MakeRequestedAllocationsLost( - uint32_t currentFrameIndex, - uint32_t frameInUseCount, + uint32_t currentFrameIndex, + uint32_t frameInUseCount, VmaAllocationRequest *pAllocationRequest) { /* Lost allocations are not supported in buddy allocator at the moment. @@ -11304,13 +11304,13 @@ uint32_t VmaBlockMetadata_Buddy::MakeAllocationsLost(uint32_t currentFrameIndex, void VmaBlockMetadata_Buddy::Alloc( const VmaAllocationRequest &request, - VmaSuballocationType type, - VkDeviceSize allocSize, - VmaAllocation hAllocation) { + VmaSuballocationType type, + VkDeviceSize allocSize, + VmaAllocation hAllocation) { VMA_ASSERT(request.type == VmaAllocationRequestType::Normal); const uint32_t targetLevel = AllocSizeToLevel(allocSize); - uint32_t currLevel = (uint32_t)(uintptr_t)request.customData; + uint32_t currLevel = (uint32_t)(uintptr_t)request.customData; Node *currNode = m_FreeList[currLevel].front; VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE); @@ -11328,21 +11328,21 @@ void VmaBlockMetadata_Buddy::Alloc( const uint32_t childrenLevel = currLevel + 1; // Create two free sub-nodes. - Node *leftChild = vma_new(GetAllocationCallbacks(), Node)(); + Node *leftChild = vma_new(GetAllocationCallbacks(), Node)(); Node *rightChild = vma_new(GetAllocationCallbacks(), Node)(); leftChild->offset = currNode->offset; - leftChild->type = Node::TYPE_FREE; + leftChild->type = Node::TYPE_FREE; leftChild->parent = currNode; - leftChild->buddy = rightChild; + leftChild->buddy = rightChild; rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel); - rightChild->type = Node::TYPE_FREE; + rightChild->type = Node::TYPE_FREE; rightChild->parent = currNode; - rightChild->buddy = leftChild; + rightChild->buddy = leftChild; // Convert current currNode to split type. - currNode->type = Node::TYPE_SPLIT; + currNode->type = Node::TYPE_SPLIT; currNode->split.leftChild = leftChild; // Add child nodes to free list. Order is important! @@ -11367,7 +11367,7 @@ void VmaBlockMetadata_Buddy::Alloc( RemoveFromFreeList(currLevel, currNode); // Convert to allocation node. - currNode->type = Node::TYPE_ALLOCATION; + currNode->type = Node::TYPE_ALLOCATION; currNode->allocation.alloc = hAllocation; ++m_AllocationCount; @@ -11401,9 +11401,9 @@ bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext &ctx, const Node *pa VMA_VALIDATE(curr->allocation.alloc != VK_NULL_HANDLE); break; case Node::TYPE_SPLIT: { - const uint32_t childrenLevel = level + 1; + const uint32_t childrenLevel = level + 1; const VkDeviceSize childrenLevelNodeSize = levelNodeSize / 2; - const Node *const leftChild = curr->split.leftChild; + const Node *const leftChild = curr->split.leftChild; VMA_VALIDATE(leftChild != VMA_NULL); VMA_VALIDATE(leftChild->offset == curr->offset); if (!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize)) { @@ -11424,7 +11424,7 @@ bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext &ctx, const Node *pa uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const { // I know this could be optimized somehow e.g. by using std::log2p1 from C++20. - uint32_t level = 0; + uint32_t level = 0; VkDeviceSize currLevelNodeSize = m_UsableSize; VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1; while (allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount) { @@ -11437,9 +11437,9 @@ uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const void VmaBlockMetadata_Buddy::FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset) { // Find node and level. - Node * node = m_Root; - VkDeviceSize nodeOffset = 0; - uint32_t level = 0; + Node *node = m_Root; + VkDeviceSize nodeOffset = 0; + uint32_t level = 0; VkDeviceSize levelNodeSize = LevelToNodeSize(0); while (node->type == Node::TYPE_SPLIT) { const VkDeviceSize nextLevelSize = levelNodeSize >> 1; @@ -11505,7 +11505,7 @@ void VmaBlockMetadata_Buddy::CalcAllocationStatInfoNode(VmaStatInfo &outInfo, co } break; case Node::TYPE_SPLIT: { const VkDeviceSize childrenNodeSize = levelNodeSize / 2; - const Node *const leftChild = node->split.leftChild; + const Node *const leftChild = node->split.leftChild; CalcAllocationStatInfoNode(outInfo, leftChild, childrenNodeSize); const Node *const rightChild = leftChild->buddy; CalcAllocationStatInfoNode(outInfo, rightChild, childrenNodeSize); @@ -11526,9 +11526,9 @@ void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node *node) { m_FreeList[level].front = m_FreeList[level].back = node; } else { VMA_ASSERT(frontNode->free.prev == VMA_NULL); - node->free.prev = VMA_NULL; - node->free.next = frontNode; - frontNode->free.prev = node; + node->free.prev = VMA_NULL; + node->free.next = frontNode; + frontNode->free.prev = node; m_FreeList[level].front = node; } } @@ -11572,7 +11572,7 @@ void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter &json, con } break; case Node::TYPE_SPLIT: { const VkDeviceSize childrenNodeSize = levelNodeSize / 2; - const Node *const leftChild = node->split.leftChild; + const Node *const leftChild = node->split.leftChild; PrintDetailedMapNode(json, leftChild, childrenNodeSize); const Node *const rightChild = leftChild->buddy; PrintDetailedMapNode(json, rightChild, childrenNodeSize); @@ -11595,19 +11595,19 @@ VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) : m_pMetadat } void VmaDeviceMemoryBlock::Init( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t newMemoryTypeIndex, + VmaAllocator hAllocator, + VmaPool hParentPool, + uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, - VkDeviceSize newSize, - uint32_t id, - uint32_t algorithm) { + VkDeviceSize newSize, + uint32_t id, + uint32_t algorithm) { VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); - m_hParentPool = hParentPool; + m_hParentPool = hParentPool; m_MemoryTypeIndex = newMemoryTypeIndex; - m_Id = id; - m_hMemory = newMemory; + m_Id = id; + m_hMemory = newMemory; switch (algorithm) { case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT: @@ -11646,8 +11646,8 @@ bool VmaDeviceMemoryBlock::Validate() const { } VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator) { - void * pData = nullptr; - VkResult res = Map(hAllocator, 1, &pData); + void *pData = nullptr; + VkResult res = Map(hAllocator, 1, &pData); if (res != VK_SUCCESS) { return res; } @@ -11710,7 +11710,7 @@ VkResult VmaDeviceMemoryBlock::WriteMagicValueAroundAllocation(VmaAllocator hAll VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN); - void * pData; + void *pData; VkResult res = Map(hAllocator, 1, &pData); if (res != VK_SUCCESS) { return res; @@ -11728,7 +11728,7 @@ VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator h VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN); - void * pData; + void *pData; VkResult res = Map(hAllocator, 1, &pData); if (res != VK_SUCCESS) { return res; @@ -11746,11 +11746,11 @@ VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator h } VkResult VmaDeviceMemoryBlock::BindBufferMemory( - const VmaAllocator hAllocator, + const VmaAllocator hAllocator, const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void *pNext) { VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && hAllocation->GetBlock() == this); VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && @@ -11762,11 +11762,11 @@ VkResult VmaDeviceMemoryBlock::BindBufferMemory( } VkResult VmaDeviceMemoryBlock::BindImageMemory( - const VmaAllocator hAllocator, + const VmaAllocator hAllocator, const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void *pNext) { VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && hAllocation->GetBlock() == this); VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && @@ -11779,7 +11779,7 @@ VkResult VmaDeviceMemoryBlock::BindImageMemory( static void InitStatInfo(VmaStatInfo &outInfo) { memset(&outInfo, 0, sizeof(outInfo)); - outInfo.allocationSizeMin = UINT64_MAX; + outInfo.allocationSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMin = UINT64_MAX; } @@ -11790,21 +11790,21 @@ static void VmaAddStatInfo(VmaStatInfo &inoutInfo, const VmaStatInfo &srcInfo) { inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount; inoutInfo.usedBytes += srcInfo.usedBytes; inoutInfo.unusedBytes += srcInfo.unusedBytes; - inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin); - inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax); + inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin); + inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax); inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin); inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax); } static void VmaPostprocessCalcStatInfo(VmaStatInfo &inoutInfo) { - inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ? VmaRoundDiv(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0; + inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ? VmaRoundDiv(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0; inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ? VmaRoundDiv(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0; } VmaPool_T::VmaPool_T( - VmaAllocator hAllocator, + VmaAllocator hAllocator, const VmaPoolCreateInfo &createInfo, - VkDeviceSize preferredBlockSize) : m_BlockVector(hAllocator, + VkDeviceSize preferredBlockSize) : m_BlockVector(hAllocator, this, // hParentPool createInfo.memoryTypeIndex, createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize, @@ -11840,16 +11840,16 @@ void VmaPool_T::SetName(const char *pName) { VmaBlockVector::VmaBlockVector( VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t memoryTypeIndex, + VmaPool hParentPool, + uint32_t memoryTypeIndex, VkDeviceSize preferredBlockSize, - size_t minBlockCount, - size_t maxBlockCount, + size_t minBlockCount, + size_t maxBlockCount, VkDeviceSize bufferImageGranularity, - uint32_t frameInUseCount, - bool explicitBlockSize, - uint32_t algorithm, - float priority) : m_hAllocator(hAllocator), + uint32_t frameInUseCount, + bool explicitBlockSize, + uint32_t algorithm, + float priority) : m_hAllocator(hAllocator), m_hParentPool(hParentPool), m_MemoryTypeIndex(memoryTypeIndex), m_PreferredBlockSize(preferredBlockSize), @@ -11887,12 +11887,12 @@ void VmaBlockVector::GetPoolStats(VmaPoolStats *pStats) { const size_t blockCount = m_Blocks.size(); - pStats->size = 0; - pStats->unusedSize = 0; - pStats->allocationCount = 0; - pStats->unusedRangeCount = 0; + pStats->size = 0; + pStats->unusedSize = 0; + pStats->allocationCount = 0; + pStats->unusedRangeCount = 0; pStats->unusedRangeSizeMax = 0; - pStats->blockCount = blockCount; + pStats->blockCount = blockCount; for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { const VmaDeviceMemoryBlock *const pBlock = m_Blocks[blockIndex]; @@ -11918,18 +11918,18 @@ bool VmaBlockVector::IsCorruptionDetectionEnabled() const { static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32; VkResult VmaBlockVector::Allocate( - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations) { - size_t allocIndex; + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations) { + size_t allocIndex; VkResult res = VK_SUCCESS; if (IsCorruptionDetectionEnabled()) { - size = VmaAlignUp(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); + size = VmaAlignUp(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); alignment = VmaAlignUp(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); } @@ -11953,8 +11953,8 @@ VkResult VmaBlockVector::Allocate( // Free all already created allocations. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); while (allocIndex--) { - VmaAllocation_T *const alloc = pAllocations[allocIndex]; - const VkDeviceSize allocSize = alloc->GetSize(); + VmaAllocation_T *const alloc = pAllocations[allocIndex]; + const VkDeviceSize allocSize = alloc->GetSize(); Free(alloc); m_hAllocator->m_Budget.RemoveAllocation(heapIndex, allocSize); } @@ -11965,21 +11965,21 @@ VkResult VmaBlockVector::Allocate( } VkResult VmaBlockVector::AllocatePage( - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - VmaAllocation * pAllocation) { - const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; - bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0; - const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; + VmaSuballocationType suballocType, + VmaAllocation *pAllocation) { + const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; + bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0; + const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; VkDeviceSize freeMemory; { - const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); - VmaBudget heapBudget = {}; + const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); + VmaBudget heapBudget = {}; m_hAllocator->GetBudget(&heapBudget, heapIndex, 1); freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0; } @@ -12099,8 +12099,8 @@ VkResult VmaBlockVector::AllocatePage( // 2. Try to create new block. if (canCreateNewBlock) { // Calculate optimal size for new block. - VkDeviceSize newBlockSize = m_PreferredBlockSize; - uint32_t newBlockSizeShift = 0; + VkDeviceSize newBlockSize = m_PreferredBlockSize; + uint32_t newBlockSizeShift = 0; const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3; if (!m_ExplicitBlockSize) { @@ -12117,8 +12117,8 @@ VkResult VmaBlockVector::AllocatePage( } } - size_t newBlockIndex = 0; - VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; + size_t newBlockIndex = 0; + VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize. if (!m_ExplicitBlockSize) { while (res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX) { @@ -12163,8 +12163,8 @@ VkResult VmaBlockVector::AllocatePage( uint32_t tryIndex = 0; for (; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex) { VmaDeviceMemoryBlock *pBestRequestBlock = VMA_NULL; - VmaAllocationRequest bestRequest = {}; - VkDeviceSize bestRequestCost = VK_WHOLE_SIZE; + VmaAllocationRequest bestRequest = {}; + VkDeviceSize bestRequestCost = VK_WHOLE_SIZE; // 1. Search existing allocations. if (strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT) { @@ -12188,8 +12188,8 @@ VkResult VmaBlockVector::AllocatePage( if (pBestRequestBlock == VMA_NULL || currRequestCost < bestRequestCost) { pBestRequestBlock = pCurrBlock; - bestRequest = currRequest; - bestRequestCost = currRequestCost; + bestRequest = currRequest; + bestRequestCost = currRequestCost; if (bestRequestCost == 0) { break; @@ -12220,8 +12220,8 @@ VkResult VmaBlockVector::AllocatePage( currRequestCost < bestRequestCost || strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT) { pBestRequestBlock = pCurrBlock; - bestRequest = currRequest; - bestRequestCost = currRequestCost; + bestRequest = currRequest; + bestRequestCost = currRequestCost; if (bestRequestCost == 0 || strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT) { @@ -12285,8 +12285,8 @@ void VmaBlockVector::Free( bool budgetExceeded = false; { - const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); - VmaBudget heapBudget = {}; + const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); + VmaBudget heapBudget = {}; m_hAllocator->GetBudget(&heapBudget, heapIndex, 1); budgetExceeded = heapBudget.usage >= heapBudget.budget; } @@ -12378,18 +12378,18 @@ void VmaBlockVector::IncrementallySortBlocks() { } VkResult VmaBlockVector::AllocateFromBlock( - VmaDeviceMemoryBlock * pBlock, - uint32_t currentFrameIndex, - VkDeviceSize size, - VkDeviceSize alignment, + VmaDeviceMemoryBlock *pBlock, + uint32_t currentFrameIndex, + VkDeviceSize size, + VkDeviceSize alignment, VmaAllocationCreateFlags allocFlags, - void * pUserData, - VmaSuballocationType suballocType, - uint32_t strategy, - VmaAllocation * pAllocation) { + void *pUserData, + VmaSuballocationType suballocType, + uint32_t strategy, + VmaAllocation *pAllocation) { VMA_ASSERT((allocFlags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) == 0); - const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; - const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; + const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; + const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; VmaAllocationRequest currRequest = {}; @@ -12435,8 +12435,8 @@ VkResult VmaBlockVector::AllocateFromBlock( VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t *pNewBlockIndex) { VkMemoryAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocInfo.memoryTypeIndex = m_MemoryTypeIndex; - allocInfo.allocationSize = blockSize; + allocInfo.memoryTypeIndex = m_MemoryTypeIndex; + allocInfo.allocationSize = blockSize; #if VMA_BUFFER_DEVICE_ADDRESS // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature. @@ -12456,7 +12456,7 @@ VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t *pNewBlockIn #endif // #if VMA_MEMORY_PRIORITY VkDeviceMemory mem = VK_NULL_HANDLE; - VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem); + VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem); if (res < 0) { return res; } @@ -12483,19 +12483,19 @@ VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t *pNewBlockIn } void VmaBlockVector::ApplyDefragmentationMovesCpu( - class VmaBlockVectorDefragmentationContext * pDefragCtx, + class VmaBlockVectorDefragmentationContext *pDefragCtx, const VmaVector > &moves) { - const size_t blockCount = m_Blocks.size(); - const bool isNonCoherent = m_hAllocator->IsMemoryTypeNonCoherent(m_MemoryTypeIndex); + const size_t blockCount = m_Blocks.size(); + const bool isNonCoherent = m_hAllocator->IsMemoryTypeNonCoherent(m_MemoryTypeIndex); enum BLOCK_FLAG { - BLOCK_FLAG_USED = 0x00000001, + BLOCK_FLAG_USED = 0x00000001, BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION = 0x00000002, }; struct BlockInfo { uint32_t flags; - void * pMappedData; + void *pMappedData; }; VmaVector > blockInfo(blockCount, BlockInfo(), VmaStlAllocator(m_hAllocator->GetAllocationCallbacks())); @@ -12513,8 +12513,8 @@ void VmaBlockVector::ApplyDefragmentationMovesCpu( // Go over all blocks. Get mapped pointer or map if necessary. for (size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex) { - BlockInfo & currBlockInfo = blockInfo[blockIndex]; - VmaDeviceMemoryBlock *pBlock = m_Blocks[blockIndex]; + BlockInfo &currBlockInfo = blockInfo[blockIndex]; + VmaDeviceMemoryBlock *pBlock = m_Blocks[blockIndex]; if ((currBlockInfo.flags & BLOCK_FLAG_USED) != 0) { currBlockInfo.pMappedData = pBlock->GetMappedData(); // It is not originally mapped - map it. @@ -12529,8 +12529,8 @@ void VmaBlockVector::ApplyDefragmentationMovesCpu( // Go over all moves. Do actual data transfer. if (pDefragCtx->res == VK_SUCCESS) { - const VkDeviceSize nonCoherentAtomSize = m_hAllocator->m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; - VkMappedMemoryRange memRange = {VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE}; + const VkDeviceSize nonCoherentAtomSize = m_hAllocator->m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; + VkMappedMemoryRange memRange = {VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE}; for (size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex) { const VmaDefragmentationMove &move = moves[moveIndex]; @@ -12543,9 +12543,9 @@ void VmaBlockVector::ApplyDefragmentationMovesCpu( // Invalidate source. if (isNonCoherent) { VmaDeviceMemoryBlock *const pSrcBlock = m_Blocks[move.srcBlockIndex]; - memRange.memory = pSrcBlock->GetDeviceMemory(); - memRange.offset = VmaAlignDown(move.srcOffset, nonCoherentAtomSize); - memRange.size = VMA_MIN( + memRange.memory = pSrcBlock->GetDeviceMemory(); + memRange.offset = VmaAlignDown(move.srcOffset, nonCoherentAtomSize); + memRange.size = VMA_MIN( VmaAlignUp(move.size + (move.srcOffset - memRange.offset), nonCoherentAtomSize), pSrcBlock->m_pMetadata->GetSize() - memRange.offset); (*m_hAllocator->GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange); @@ -12565,9 +12565,9 @@ void VmaBlockVector::ApplyDefragmentationMovesCpu( // Flush destination. if (isNonCoherent) { VmaDeviceMemoryBlock *const pDstBlock = m_Blocks[move.dstBlockIndex]; - memRange.memory = pDstBlock->GetDeviceMemory(); - memRange.offset = VmaAlignDown(move.dstOffset, nonCoherentAtomSize); - memRange.size = VMA_MIN( + memRange.memory = pDstBlock->GetDeviceMemory(); + memRange.offset = VmaAlignDown(move.dstOffset, nonCoherentAtomSize); + memRange.size = VMA_MIN( VmaAlignUp(move.size + (move.dstOffset - memRange.offset), nonCoherentAtomSize), pDstBlock->m_pMetadata->GetSize() - memRange.offset); (*m_hAllocator->GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange); @@ -12587,9 +12587,9 @@ void VmaBlockVector::ApplyDefragmentationMovesCpu( } void VmaBlockVector::ApplyDefragmentationMovesGpu( - class VmaBlockVectorDefragmentationContext * pDefragCtx, + class VmaBlockVectorDefragmentationContext *pDefragCtx, VmaVector > &moves, - VkCommandBuffer commandBuffer) { + VkCommandBuffer commandBuffer) { const size_t blockCount = m_Blocks.size(); pDefragCtx->blockContexts.resize(blockCount); @@ -12617,10 +12617,10 @@ void VmaBlockVector::ApplyDefragmentationMovesGpu( for (size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex) { VmaBlockDefragmentationContext &currBlockCtx = pDefragCtx->blockContexts[blockIndex]; - VmaDeviceMemoryBlock * pBlock = m_Blocks[blockIndex]; + VmaDeviceMemoryBlock *pBlock = m_Blocks[blockIndex]; if ((currBlockCtx.flags & VmaBlockDefragmentationContext::BLOCK_FLAG_USED) != 0) { bufCreateInfo.size = pBlock->m_pMetadata->GetSize(); - pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkCreateBuffer)(m_hAllocator->m_hDevice, &bufCreateInfo, m_hAllocator->GetAllocationCallbacks(), &currBlockCtx.hBuffer); + pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkCreateBuffer)(m_hAllocator->m_hDevice, &bufCreateInfo, m_hAllocator->GetAllocationCallbacks(), &currBlockCtx.hBuffer); if (pDefragCtx->res == VK_SUCCESS) { pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkBindBufferMemory)(m_hAllocator->m_hDevice, currBlockCtx.hBuffer, pBlock->GetDeviceMemory(), 0); } @@ -12798,14 +12798,14 @@ void VmaBlockVector::Defragment( // Defragment. - const VkDeviceSize maxBytesToMove = defragmentOnGpu ? maxGpuBytesToMove : maxCpuBytesToMove; - const uint32_t maxAllocationsToMove = defragmentOnGpu ? maxGpuAllocationsToMove : maxCpuAllocationsToMove; - pCtx->res = pCtx->GetAlgorithm()->Defragment(pCtx->defragmentationMoves, maxBytesToMove, maxAllocationsToMove, flags); + const VkDeviceSize maxBytesToMove = defragmentOnGpu ? maxGpuBytesToMove : maxCpuBytesToMove; + const uint32_t maxAllocationsToMove = defragmentOnGpu ? maxGpuAllocationsToMove : maxCpuAllocationsToMove; + pCtx->res = pCtx->GetAlgorithm()->Defragment(pCtx->defragmentationMoves, maxBytesToMove, maxAllocationsToMove, flags); // Accumulate statistics. if (pStats != VMA_NULL) { - const VkDeviceSize bytesMoved = pCtx->GetAlgorithm()->GetBytesMoved(); - const uint32_t allocationsMoved = pCtx->GetAlgorithm()->GetAllocationsMoved(); + const VkDeviceSize bytesMoved = pCtx->GetAlgorithm()->GetBytesMoved(); + const uint32_t allocationsMoved = pCtx->GetAlgorithm()->GetAllocationsMoved(); pStats->bytesMoved += bytesMoved; pStats->allocationsMoved += allocationsMoved; VMA_ASSERT(bytesMoved <= maxBytesToMove); @@ -12841,8 +12841,8 @@ void VmaBlockVector::Defragment( void VmaBlockVector::DefragmentationEnd( class VmaBlockVectorDefragmentationContext *pCtx, - uint32_t flags, - VmaDefragmentationStats * pStats) { + uint32_t flags, + VmaDefragmentationStats *pStats) { if (flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL && m_hAllocator->m_UseMutex) { VMA_ASSERT(pCtx->mutexLocked == false); @@ -12884,8 +12884,8 @@ uint32_t VmaBlockVector::ProcessDefragmentations( VmaDefragmentationMove &move = pCtx->defragmentationMoves[pCtx->defragmentationMovesProcessed + i]; pMove->allocation = move.hAllocation; - pMove->memory = move.pDstBlock->GetDeviceMemory(); - pMove->offset = move.dstOffset; + pMove->memory = move.pDstBlock->GetDeviceMemory(); + pMove->offset = move.dstOffset; ++pMove; } @@ -12897,7 +12897,7 @@ uint32_t VmaBlockVector::ProcessDefragmentations( void VmaBlockVector::CommitDefragmentations( class VmaBlockVectorDefragmentationContext *pCtx, - VmaDefragmentationStats * pStats) { + VmaDefragmentationStats *pStats) { VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); for (uint32_t i = pCtx->defragmentationMovesCommitted; i < pCtx->defragmentationMovesProcessed; ++i) { @@ -12937,9 +12937,9 @@ bool VmaBlockVector::IsBufferImageGranularityConflictPossible() const { void VmaBlockVector::MakePoolAllocationsLost( uint32_t currentFrameIndex, - size_t * pLostAllocationCount) { + size_t *pLostAllocationCount) { VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); - size_t lostAllocationCount = 0; + size_t lostAllocationCount = 0; for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { VmaDeviceMemoryBlock *const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); @@ -12989,10 +12989,10 @@ void VmaBlockVector::AddStats(VmaStats *pStats) { // VmaDefragmentationAlgorithm_Generic members definition VmaDefragmentationAlgorithm_Generic::VmaDefragmentationAlgorithm_Generic( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaBlockVector *pBlockVector, - uint32_t currentFrameIndex, - bool overlappingMoveSupported) : VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex), + uint32_t currentFrameIndex, + bool overlappingMoveSupported) : VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex), m_AllocationCount(0), m_AllAllocations(false), m_BytesMoved(0), @@ -13001,9 +13001,9 @@ VmaDefragmentationAlgorithm_Generic::VmaDefragmentationAlgorithm_Generic( // Create block info for each block. const size_t blockCount = m_pBlockVector->m_Blocks.size(); for (size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { - BlockInfo *pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks()); + BlockInfo *pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks()); pBlockInfo->m_OriginalBlockIndex = blockIndex; - pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex]; + pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex]; m_Blocks.push_back(pBlockInfo); } @@ -13020,8 +13020,8 @@ VmaDefragmentationAlgorithm_Generic::~VmaDefragmentationAlgorithm_Generic() { void VmaDefragmentationAlgorithm_Generic::AddAllocation(VmaAllocation hAlloc, VkBool32 *pChanged) { // Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost. if (hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST) { - VmaDeviceMemoryBlock * pBlock = hAlloc->GetBlock(); - BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess()); + VmaDeviceMemoryBlock *pBlock = hAlloc->GetBlock(); + BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess()); if (it != m_Blocks.end() && (*it)->m_pBlock == pBlock) { AllocationInfo allocInfo = AllocationInfo(hAlloc, pChanged); (*it)->m_Allocations.push_back(allocInfo); @@ -13035,9 +13035,9 @@ void VmaDefragmentationAlgorithm_Generic::AddAllocation(VmaAllocation hAlloc, Vk VkResult VmaDefragmentationAlgorithm_Generic::DefragmentRound( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - bool freeOldAllocations) { + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + bool freeOldAllocations) { if (m_Blocks.empty()) { return VK_SUCCESS; } @@ -13083,17 +13083,17 @@ VkResult VmaDefragmentationAlgorithm_Generic::DefragmentRound( } } - BlockInfo * pSrcBlockInfo = m_Blocks[srcBlockIndex]; - AllocationInfo &allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex]; + BlockInfo *pSrcBlockInfo = m_Blocks[srcBlockIndex]; + AllocationInfo &allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex]; - const VkDeviceSize size = allocInfo.m_hAllocation->GetSize(); - const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset(); - const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment(); + const VkDeviceSize size = allocInfo.m_hAllocation->GetSize(); + const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset(); + const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment(); const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType(); // 2. Try to find new place for this allocation in preceding or current block. for (size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex) { - BlockInfo * pDstBlockInfo = m_Blocks[dstBlockIndex]; + BlockInfo *pDstBlockInfo = m_Blocks[dstBlockIndex]; VmaAllocationRequest dstAllocRequest; if (pDstBlockInfo->m_pBlock->m_pMetadata->CreateAllocationRequest( m_CurrentFrameIndex, @@ -13117,14 +13117,14 @@ VkResult VmaDefragmentationAlgorithm_Generic::DefragmentRound( } VmaDefragmentationMove move = {}; - move.srcBlockIndex = pSrcBlockInfo->m_OriginalBlockIndex; - move.dstBlockIndex = pDstBlockInfo->m_OriginalBlockIndex; - move.srcOffset = srcOffset; - move.dstOffset = dstAllocRequest.offset; - move.size = size; - move.hAllocation = allocInfo.m_hAllocation; - move.pSrcBlock = pSrcBlockInfo->m_pBlock; - move.pDstBlock = pDstBlockInfo->m_pBlock; + move.srcBlockIndex = pSrcBlockInfo->m_OriginalBlockIndex; + move.dstBlockIndex = pDstBlockInfo->m_OriginalBlockIndex; + move.srcOffset = srcOffset; + move.dstOffset = dstAllocRequest.offset; + move.size = size; + move.hAllocation = allocInfo.m_hAllocation; + move.pSrcBlock = pSrcBlockInfo->m_pBlock; + move.pDstBlock = pDstBlockInfo->m_pBlock; moves.push_back(move); @@ -13179,9 +13179,9 @@ size_t VmaDefragmentationAlgorithm_Generic::CalcBlocksWithNonMovableCount() cons VkResult VmaDefragmentationAlgorithm_Generic::Defragment( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - VmaDefragmentationFlags flags) { + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + VmaDefragmentationFlags flags) { if (!m_AllAllocations && m_AllocationCount == 0) { return VK_SUCCESS; } @@ -13245,10 +13245,10 @@ bool VmaDefragmentationAlgorithm_Generic::MoveMakesSense( // VmaDefragmentationAlgorithm_Fast VmaDefragmentationAlgorithm_Fast::VmaDefragmentationAlgorithm_Fast( - VmaAllocator hAllocator, + VmaAllocator hAllocator, VmaBlockVector *pBlockVector, - uint32_t currentFrameIndex, - bool overlappingMoveSupported) : VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex), + uint32_t currentFrameIndex, + bool overlappingMoveSupported) : VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex), m_OverlappingMoveSupported(overlappingMoveSupported), m_AllocationCount(0), m_AllAllocations(false), @@ -13263,9 +13263,9 @@ VmaDefragmentationAlgorithm_Fast::~VmaDefragmentationAlgorithm_Fast() { VkResult VmaDefragmentationAlgorithm_Fast::Defragment( VmaVector > &moves, - VkDeviceSize maxBytesToMove, - uint32_t maxAllocationsToMove, - VmaDefragmentationFlags flags) { + VkDeviceSize maxBytesToMove, + uint32_t maxAllocationsToMove, + VmaDefragmentationFlags flags) { VMA_ASSERT(m_AllAllocations || m_pBlockVector->CalcAllocationCount() == m_AllocationCount); const size_t blockCount = m_pBlockVector->GetBlockCount(); @@ -13291,23 +13291,23 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( FreeSpaceDatabase freeSpaceDb; - size_t dstBlockInfoIndex = 0; - size_t dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex; - VmaDeviceMemoryBlock * pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex); - VmaBlockMetadata_Generic *pDstMetadata = (VmaBlockMetadata_Generic *)pDstBlock->m_pMetadata; - VkDeviceSize dstBlockSize = pDstMetadata->GetSize(); - VkDeviceSize dstOffset = 0; + size_t dstBlockInfoIndex = 0; + size_t dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex; + VmaDeviceMemoryBlock *pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex); + VmaBlockMetadata_Generic *pDstMetadata = (VmaBlockMetadata_Generic *)pDstBlock->m_pMetadata; + VkDeviceSize dstBlockSize = pDstMetadata->GetSize(); + VkDeviceSize dstOffset = 0; bool end = false; for (size_t srcBlockInfoIndex = 0; !end && srcBlockInfoIndex < blockCount; ++srcBlockInfoIndex) { - const size_t srcOrigBlockIndex = m_BlockInfos[srcBlockInfoIndex].origBlockIndex; - VmaDeviceMemoryBlock *const pSrcBlock = m_pBlockVector->GetBlock(srcOrigBlockIndex); - VmaBlockMetadata_Generic *const pSrcMetadata = (VmaBlockMetadata_Generic *)pSrcBlock->m_pMetadata; + const size_t srcOrigBlockIndex = m_BlockInfos[srcBlockInfoIndex].origBlockIndex; + VmaDeviceMemoryBlock *const pSrcBlock = m_pBlockVector->GetBlock(srcOrigBlockIndex); + VmaBlockMetadata_Generic *const pSrcMetadata = (VmaBlockMetadata_Generic *)pSrcBlock->m_pMetadata; for (VmaSuballocationList::iterator srcSuballocIt = pSrcMetadata->m_Suballocations.begin(); !end && srcSuballocIt != pSrcMetadata->m_Suballocations.end();) { - VmaAllocation_T *const pAlloc = srcSuballocIt->hAllocation; - const VkDeviceSize srcAllocAlignment = pAlloc->GetAlignment(); - const VkDeviceSize srcAllocSize = srcSuballocIt->size; + VmaAllocation_T *const pAlloc = srcSuballocIt->hAllocation; + const VkDeviceSize srcAllocAlignment = pAlloc->GetAlignment(); + const VkDeviceSize srcAllocSize = srcSuballocIt->size; if (m_AllocationsMoved == maxAllocationsToMove || m_BytesMoved + srcAllocSize > maxBytesToMove) { end = true; @@ -13317,13 +13317,13 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( VmaDefragmentationMove move = {}; // Try to place it in one of free spaces from the database. - size_t freeSpaceInfoIndex; + size_t freeSpaceInfoIndex; VkDeviceSize dstAllocOffset; if (freeSpaceDb.Fetch(srcAllocAlignment, srcAllocSize, freeSpaceInfoIndex, dstAllocOffset)) { - size_t freeSpaceOrigBlockIndex = m_BlockInfos[freeSpaceInfoIndex].origBlockIndex; - VmaDeviceMemoryBlock * pFreeSpaceBlock = m_pBlockVector->GetBlock(freeSpaceOrigBlockIndex); - VmaBlockMetadata_Generic *pFreeSpaceMetadata = (VmaBlockMetadata_Generic *)pFreeSpaceBlock->m_pMetadata; + size_t freeSpaceOrigBlockIndex = m_BlockInfos[freeSpaceInfoIndex].origBlockIndex; + VmaDeviceMemoryBlock *pFreeSpaceBlock = m_pBlockVector->GetBlock(freeSpaceOrigBlockIndex); + VmaBlockMetadata_Generic *pFreeSpaceMetadata = (VmaBlockMetadata_Generic *)pFreeSpaceBlock->m_pMetadata; // Same block if (freeSpaceInfoIndex == srcBlockInfoIndex) { @@ -13332,7 +13332,7 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( // MOVE OPTION 1: Move the allocation inside the same block by decreasing offset. VmaSuballocation suballoc = *srcSuballocIt; - suballoc.offset = dstAllocOffset; + suballoc.offset = dstAllocOffset; suballoc.hAllocation->ChangeOffset(dstAllocOffset); m_BytesMoved += srcAllocSize; ++m_AllocationsMoved; @@ -13346,9 +13346,9 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( move.srcBlockIndex = srcOrigBlockIndex; move.dstBlockIndex = freeSpaceOrigBlockIndex; - move.srcOffset = srcAllocOffset; - move.dstOffset = dstAllocOffset; - move.size = srcAllocSize; + move.srcOffset = srcAllocOffset; + move.dstOffset = dstAllocOffset; + move.size = srcAllocSize; moves.push_back(move); } @@ -13359,7 +13359,7 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( VMA_ASSERT(freeSpaceInfoIndex < srcBlockInfoIndex); VmaSuballocation suballoc = *srcSuballocIt; - suballoc.offset = dstAllocOffset; + suballoc.offset = dstAllocOffset; suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pFreeSpaceBlock, dstAllocOffset); m_BytesMoved += srcAllocSize; ++m_AllocationsMoved; @@ -13373,9 +13373,9 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( move.srcBlockIndex = srcOrigBlockIndex; move.dstBlockIndex = freeSpaceOrigBlockIndex; - move.srcOffset = srcAllocOffset; - move.dstOffset = dstAllocOffset; - move.size = srcAllocSize; + move.srcOffset = srcAllocOffset; + move.dstOffset = dstAllocOffset; + move.size = srcAllocSize; moves.push_back(move); } @@ -13390,11 +13390,11 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( ++dstBlockInfoIndex; dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex; - pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex); - pDstMetadata = (VmaBlockMetadata_Generic *)pDstBlock->m_pMetadata; - dstBlockSize = pDstMetadata->GetSize(); - dstOffset = 0; - dstAllocOffset = 0; + pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex); + pDstMetadata = (VmaBlockMetadata_Generic *)pDstBlock->m_pMetadata; + dstBlockSize = pDstMetadata->GetSize(); + dstOffset = 0; + dstAllocOffset = 0; } // Same block @@ -13427,9 +13427,9 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( move.srcBlockIndex = srcOrigBlockIndex; move.dstBlockIndex = dstOrigBlockIndex; - move.srcOffset = srcAllocOffset; - move.dstOffset = dstAllocOffset; - move.size = srcAllocSize; + move.srcOffset = srcAllocOffset; + move.dstOffset = dstAllocOffset; + move.size = srcAllocSize; moves.push_back(move); } @@ -13442,7 +13442,7 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( VMA_ASSERT(dstAllocOffset + srcAllocSize <= dstBlockSize); VmaSuballocation suballoc = *srcSuballocIt; - suballoc.offset = dstAllocOffset; + suballoc.offset = dstAllocOffset; suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlock, dstAllocOffset); dstOffset = dstAllocOffset + srcAllocSize; m_BytesMoved += srcAllocSize; @@ -13457,9 +13457,9 @@ VkResult VmaDefragmentationAlgorithm_Fast::Defragment( move.srcBlockIndex = srcOrigBlockIndex; move.dstBlockIndex = dstOrigBlockIndex; - move.srcOffset = srcAllocOffset; - move.dstOffset = dstAllocOffset; - move.size = srcAllocSize; + move.srcOffset = srcAllocOffset; + move.dstOffset = dstAllocOffset; + move.size = srcAllocSize; moves.push_back(move); } @@ -13479,7 +13479,7 @@ void VmaDefragmentationAlgorithm_Fast::PreprocessMetadata() { for (size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { VmaBlockMetadata_Generic *const pMetadata = (VmaBlockMetadata_Generic *)m_pBlockVector->GetBlock(blockIndex)->m_pMetadata; - pMetadata->m_FreeCount = 0; + pMetadata->m_FreeCount = 0; pMetadata->m_SumFreeSize = pMetadata->GetSize(); pMetadata->m_FreeSuballocationsBySize.clear(); for (VmaSuballocationList::iterator it = pMetadata->m_Suballocations.begin(); @@ -13517,7 +13517,7 @@ void VmaDefragmentationAlgorithm_Fast::PostprocessMetadata() { } // There are some allocations in this block. else { - VkDeviceSize offset = 0; + VkDeviceSize offset = 0; VmaSuballocationList::iterator it; for (it = pMetadata->m_Suballocations.begin(); it != pMetadata->m_Suballocations.end(); @@ -13529,7 +13529,7 @@ void VmaDefragmentationAlgorithm_Fast::PostprocessMetadata() { if (it->offset > offset) { ++pMetadata->m_FreeCount; const VkDeviceSize freeSize = it->offset - offset; - VmaSuballocation suballoc = { + VmaSuballocation suballoc = { offset, // offset freeSize, // size VMA_NULL, // hAllocation @@ -13548,7 +13548,7 @@ void VmaDefragmentationAlgorithm_Fast::PostprocessMetadata() { if (offset < blockSize) { ++pMetadata->m_FreeCount; const VkDeviceSize freeSize = blockSize - offset; - VmaSuballocation suballoc = { + VmaSuballocation suballoc = { offset, // offset freeSize, // size VMA_NULL, // hAllocation @@ -13585,10 +13585,10 @@ void VmaDefragmentationAlgorithm_Fast::InsertSuballoc(VmaBlockMetadata_Generic * // VmaBlockVectorDefragmentationContext VmaBlockVectorDefragmentationContext::VmaBlockVectorDefragmentationContext( - VmaAllocator hAllocator, - VmaPool hCustomPool, + VmaAllocator hAllocator, + VmaPool hCustomPool, VmaBlockVector *pBlockVector, - uint32_t currFrameIndex) : res(VK_SUCCESS), + uint32_t currFrameIndex) : res(VK_SUCCESS), mutexLocked(false), blockContexts(VmaStlAllocator(hAllocator->GetAllocationCallbacks())), defragmentationMoves(VmaStlAllocator(hAllocator->GetAllocationCallbacks())), @@ -13652,9 +13652,9 @@ void VmaBlockVectorDefragmentationContext::Begin(bool overlappingMoveSupported, // VmaDefragmentationContext VmaDefragmentationContext_T::VmaDefragmentationContext_T( - VmaAllocator hAllocator, - uint32_t currFrameIndex, - uint32_t flags, + VmaAllocator hAllocator, + uint32_t currFrameIndex, + uint32_t flags, VmaDefragmentationStats *pStats) : m_hAllocator(hAllocator), m_CurrFrameIndex(currFrameIndex), m_Flags(flags), @@ -13708,9 +13708,9 @@ void VmaDefragmentationContext_T::AddPools(uint32_t poolCount, const VmaPool *pP } void VmaDefragmentationContext_T::AddAllocations( - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation *pAllocations, - VkBool32 * pAllocationsChanged) { + VkBool32 *pAllocationsChanged) { // Dispatch pAllocations among defragmentators. Create them when necessary. for (uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex) { const VmaAllocation hAlloc = pAllocations[allocIndex]; @@ -13745,7 +13745,7 @@ void VmaDefragmentationContext_T::AddAllocations( // This allocation belongs to default pool. else { const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex(); - pBlockVectorDefragCtx = m_DefaultPoolContexts[memTypeIndex]; + pBlockVectorDefragCtx = m_DefaultPoolContexts[memTypeIndex]; if (!pBlockVectorDefragCtx) { pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)( m_hAllocator, @@ -13775,10 +13775,10 @@ VkResult VmaDefragmentationContext_T::Defragment( if (flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL) { // For incremental defragmetnations, we just earmark how much we can move // The real meat is in the defragmentation steps - m_MaxCpuBytesToMove = maxCpuBytesToMove; + m_MaxCpuBytesToMove = maxCpuBytesToMove; m_MaxCpuAllocationsToMove = maxCpuAllocationsToMove; - m_MaxGpuBytesToMove = maxGpuBytesToMove; + m_MaxGpuBytesToMove = maxGpuBytesToMove; m_MaxGpuAllocationsToMove = maxGpuAllocationsToMove; if (m_MaxCpuBytesToMove == 0 && m_MaxCpuAllocationsToMove == 0 && @@ -13789,7 +13789,7 @@ VkResult VmaDefragmentationContext_T::Defragment( } if (commandBuffer == VK_NULL_HANDLE) { - maxGpuBytesToMove = 0; + maxGpuBytesToMove = 0; maxGpuAllocationsToMove = 0; } @@ -13836,7 +13836,7 @@ VkResult VmaDefragmentationContext_T::Defragment( VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassInfo *pInfo) { VmaDefragmentationPassMoveInfo *pCurrentMove = pInfo->pMoves; - uint32_t movesLeft = pInfo->moveCount; + uint32_t movesLeft = pInfo->moveCount; // Process default pools. for (uint32_t memTypeIndex = 0; @@ -13961,7 +13961,7 @@ VmaRecorder::VmaRecorder() : m_UseMutex(true), VkResult VmaRecorder::Init(const VmaRecordSettings &settings, bool useMutex) { m_UseMutex = useMutex; - m_Flags = settings.flags; + m_Flags = settings.flags; #if defined(_WIN32) // Open file for writing. @@ -14036,14 +14036,14 @@ void VmaRecorder::RecordDestroyPool(uint32_t frameIndex, VmaPool pool) { Flush(); } -void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, +void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation) { + VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemory,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, @@ -14060,15 +14060,15 @@ void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex Flush(); } -void VmaRecorder::RecordAllocateMemoryPages(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, +void VmaRecorder::RecordAllocateMemoryPages(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, const VmaAllocationCreateInfo &createInfo, - uint64_t allocationCount, - const VmaAllocation * pAllocations) { + uint64_t allocationCount, + const VmaAllocation *pAllocations) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryPages,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, @@ -14085,16 +14085,16 @@ void VmaRecorder::RecordAllocateMemoryPages(uint32_t frame Flush(); } -void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, +void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation) { + VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForBuffer,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, @@ -14113,16 +14113,16 @@ void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t f Flush(); } -void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex, - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, +void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, const VmaAllocationCreateInfo &createInfo, - VmaAllocation allocation) { + VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForImage,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, @@ -14141,7 +14141,7 @@ void VmaRecorder::RecordAllocateMemoryForImage(uint32_t fr Flush(); } -void VmaRecorder::RecordFreeMemory(uint32_t frameIndex, +void VmaRecorder::RecordFreeMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14152,8 +14152,8 @@ void VmaRecorder::RecordFreeMemory(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordFreeMemoryPages(uint32_t frameIndex, - uint64_t allocationCount, +void VmaRecorder::RecordFreeMemoryPages(uint32_t frameIndex, + uint64_t allocationCount, const VmaAllocation *pAllocations) { CallParams callParams; GetBasicParams(callParams); @@ -14165,13 +14165,13 @@ void VmaRecorder::RecordFreeMemoryPages(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex, +void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex, VmaAllocation allocation, - const void * pUserData) { + const void *pUserData) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr( allocation->IsUserDataString() ? VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT : 0, pUserData); @@ -14181,7 +14181,7 @@ void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex, +void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14192,7 +14192,7 @@ void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordMapMemory(uint32_t frameIndex, +void VmaRecorder::RecordMapMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14203,7 +14203,7 @@ void VmaRecorder::RecordMapMemory(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex, +void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14214,7 +14214,7 @@ void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex, +void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { CallParams callParams; GetBasicParams(callParams); @@ -14227,7 +14227,7 @@ void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex, +void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { CallParams callParams; GetBasicParams(callParams); @@ -14240,14 +14240,14 @@ void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex, - const VkBufferCreateInfo & bufCreateInfo, +void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex, + const VkBufferCreateInfo &bufCreateInfo, const VmaAllocationCreateInfo &allocCreateInfo, - VmaAllocation allocation) { + VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaCreateBuffer,%u,%llu,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, bufCreateInfo.flags, @@ -14265,14 +14265,14 @@ void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordCreateImage(uint32_t frameIndex, - const VkImageCreateInfo & imageCreateInfo, +void VmaRecorder::RecordCreateImage(uint32_t frameIndex, + const VkImageCreateInfo &imageCreateInfo, const VmaAllocationCreateInfo &allocCreateInfo, - VmaAllocation allocation) { + VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); - VmaMutexLock lock(m_FileMutex, m_UseMutex); + VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaCreateImage,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, imageCreateInfo.flags, @@ -14299,7 +14299,7 @@ void VmaRecorder::RecordCreateImage(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex, +void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14310,7 +14310,7 @@ void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordDestroyImage(uint32_t frameIndex, +void VmaRecorder::RecordDestroyImage(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14321,7 +14321,7 @@ void VmaRecorder::RecordDestroyImage(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex, +void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14332,7 +14332,7 @@ void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex, +void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); @@ -14344,7 +14344,7 @@ void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex, } void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex, - VmaPool pool) { + VmaPool pool) { CallParams callParams; GetBasicParams(callParams); @@ -14354,9 +14354,9 @@ void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordDefragmentationBegin(uint32_t frameIndex, +void VmaRecorder::RecordDefragmentationBegin(uint32_t frameIndex, const VmaDefragmentationInfo2 &info, - VmaDefragmentationContext ctx) { + VmaDefragmentationContext ctx) { CallParams callParams; GetBasicParams(callParams); @@ -14376,7 +14376,7 @@ void VmaRecorder::RecordDefragmentationBegin(uint32_t fram Flush(); } -void VmaRecorder::RecordDefragmentationEnd(uint32_t frameIndex, +void VmaRecorder::RecordDefragmentationEnd(uint32_t frameIndex, VmaDefragmentationContext ctx) { CallParams callParams; GetBasicParams(callParams); @@ -14387,8 +14387,8 @@ void VmaRecorder::RecordDefragmentationEnd(uint32_t frameIndex, Flush(); } -void VmaRecorder::RecordSetPoolName(uint32_t frameIndex, - VmaPool pool, +void VmaRecorder::RecordSetPoolName(uint32_t frameIndex, + VmaPool pool, const char *name) { CallParams callParams; GetBasicParams(callParams); @@ -14414,13 +14414,13 @@ VmaRecorder::UserDataString::UserDataString(VmaAllocationCreateFlags allocFlags, } void VmaRecorder::WriteConfiguration( - const VkPhysicalDeviceProperties & devProps, + const VkPhysicalDeviceProperties &devProps, const VkPhysicalDeviceMemoryProperties &memProps, - uint32_t vulkanApiVersion, - bool dedicatedAllocationExtensionEnabled, - bool bindMemory2ExtensionEnabled, - bool memoryBudgetExtensionEnabled, - bool deviceCoherentMemoryExtensionEnabled) { + uint32_t vulkanApiVersion, + bool dedicatedAllocationExtensionEnabled, + bool bindMemory2ExtensionEnabled, + bool memoryBudgetExtensionEnabled, + bool deviceCoherentMemoryExtensionEnabled) { fprintf(m_File, "Config,Begin\n"); fprintf(m_File, "VulkanApiVersion,%u,%u\n", VK_VERSION_MAJOR(vulkanApiVersion), VK_VERSION_MINOR(vulkanApiVersion)); @@ -14472,11 +14472,11 @@ void VmaRecorder::GetBasicParams(CallParams &outParams) { // Use C++11 features to get thread id and convert it to uint32_t. // There is room for optimization since sstream is quite slow. // Is there a better way to convert std::this_thread::get_id() to uint32_t? - std::thread::id thread_id = std::this_thread::get_id(); + std::thread::id thread_id = std::this_thread::get_id(); std::stringstream thread_id_to_string_converter; thread_id_to_string_converter << thread_id; ccstd::string thread_id_as_string = thread_id_to_string_converter.str(); - outParams.threadId = static_cast(std::stoi(thread_id_as_string.c_str())); + outParams.threadId = static_cast(std::stoi(thread_id_as_string.c_str())); #endif auto current_time = std::chrono::high_resolution_clock::now(); @@ -14549,7 +14549,7 @@ VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo *pCreateInfo) : m_Us { if (m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) { m_UseKhrDedicatedAllocation = false; - m_UseKhrBindMemory2 = false; + m_UseKhrBindMemory2 = false; } if (VMA_DEBUG_DETECT_CORRUPTION) { @@ -14605,9 +14605,9 @@ VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo *pCreateInfo) : m_Us memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions)); if (pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL) { - m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData; + m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData; m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate; - m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree; + m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree; } ImportVulkanFunctions(pCreateInfo->pVulkanFunctions); @@ -14663,7 +14663,7 @@ VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo *pCreateInfo) { !VmaStrIsEmpty(pCreateInfo->pRecordSettings->pFilePath)) { #if VMA_RECORDING_ENABLED m_pRecorder = vma_new(this, VmaRecorder)(); - res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex); + res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex); if (res != VK_SUCCESS) { return res; } @@ -14730,31 +14730,31 @@ void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions *pVulkanFunc void VmaAllocator_T::ImportVulkanFunctions_Static() { // Vulkan 1.0 - m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties; + m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties; m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties; - m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; - m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory; - m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory; - m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory; - m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges; - m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges; - m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory; - m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory; - m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements; - m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements; - m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer; - m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer; - m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage; - m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage; - m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer; + m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; + m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory; + m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory; + m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory; + m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges; + m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges; + m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory; + m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory; + m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements; + m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements; + m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer; + m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer; + m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage; + m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage; + m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer; // Vulkan 1.1 #if VMA_VULKAN_VERSION >= 1001000 if (m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) { - m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2; - m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2; - m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2; - m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2; + m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2; + m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2; + m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2; + m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2; m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2; } #endif @@ -14910,24 +14910,24 @@ void VmaAllocator_T::ValidateVulkanFunctions() { } VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex) { - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); - const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; - const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE; + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); + const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; + const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE; return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32); } VkResult VmaAllocator_T::AllocateMemoryOfType( - VkDeviceSize size, - VkDeviceSize alignment, - bool dedicatedAllocation, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, - VkImage dedicatedImage, + VkDeviceSize size, + VkDeviceSize alignment, + bool dedicatedAllocation, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, + VkImage dedicatedImage, const VmaAllocationCreateInfo &createInfo, - uint32_t memTypeIndex, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations) { + uint32_t memTypeIndex, + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations) { VMA_ASSERT(pAllocations != VMA_NULL); VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size); @@ -14947,7 +14947,7 @@ VkResult VmaAllocator_T::AllocateMemoryOfType( VMA_ASSERT(blockVector); const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize(); - bool preferDedicatedMemory = + bool preferDedicatedMemory = VMA_DEBUG_ALWAYS_DEDICATED_MEMORY || dedicatedAllocation || // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size. @@ -15030,24 +15030,24 @@ VkResult VmaAllocator_T::AllocateMemoryOfType( } VkResult VmaAllocator_T::AllocateDedicatedMemory( - VkDeviceSize size, + VkDeviceSize size, VmaSuballocationType suballocType, - uint32_t memTypeIndex, - bool withinBudget, - bool map, - bool isUserDataString, - void * pUserData, - float priority, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, - VkImage dedicatedImage, - size_t allocationCount, - VmaAllocation * pAllocations) { + uint32_t memTypeIndex, + bool withinBudget, + bool map, + bool isUserDataString, + void *pUserData, + float priority, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, + VkImage dedicatedImage, + size_t allocationCount, + VmaAllocation *pAllocations) { VMA_ASSERT(allocationCount > 0 && pAllocations); if (withinBudget) { - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); - VmaBudget heapBudget = {}; + const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); + VmaBudget heapBudget = {}; GetBudget(&heapBudget, heapIndex, 1); if (heapBudget.usage + size * allocationCount > heapBudget.budget) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; @@ -15055,8 +15055,8 @@ VkResult VmaAllocator_T::AllocateDedicatedMemory( } VkMemoryAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocInfo.memoryTypeIndex = memTypeIndex; - allocInfo.allocationSize = size; + allocInfo.memoryTypeIndex = memTypeIndex; + allocInfo.allocationSize = size; #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR}; @@ -15097,7 +15097,7 @@ VkResult VmaAllocator_T::AllocateDedicatedMemory( } #endif // #if VMA_MEMORY_PRIORITY - size_t allocIndex; + size_t allocIndex; VkResult res = VK_SUCCESS; for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) { res = AllocateDedicatedMemoryPage( @@ -15117,7 +15117,7 @@ VkResult VmaAllocator_T::AllocateDedicatedMemory( if (res == VK_SUCCESS) { // Register them in m_DedicatedAllocations. { - VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); + VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); DedicatedAllocationLinkedList &dedicatedAllocations = m_DedicatedAllocations[memTypeIndex]; for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) { dedicatedAllocations.PushBack(pAllocations[allocIndex]); @@ -15128,8 +15128,8 @@ VkResult VmaAllocator_T::AllocateDedicatedMemory( } else { // Free all already created allocations. while (allocIndex--) { - VmaAllocation currAlloc = pAllocations[allocIndex]; - VkDeviceMemory hMemory = currAlloc->GetMemory(); + VmaAllocation currAlloc = pAllocations[allocIndex]; + VkDeviceMemory hMemory = currAlloc->GetMemory(); /* There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory @@ -15154,16 +15154,16 @@ VkResult VmaAllocator_T::AllocateDedicatedMemory( } VkResult VmaAllocator_T::AllocateDedicatedMemoryPage( - VkDeviceSize size, - VmaSuballocationType suballocType, - uint32_t memTypeIndex, + VkDeviceSize size, + VmaSuballocationType suballocType, + uint32_t memTypeIndex, const VkMemoryAllocateInfo &allocInfo, - bool map, - bool isUserDataString, - void * pUserData, - VmaAllocation * pAllocation) { + bool map, + bool isUserDataString, + void *pUserData, + VmaAllocation *pAllocation) { VkDeviceMemory hMemory = VK_NULL_HANDLE; - VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory); + VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory); if (res < 0) { VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); return res; @@ -15196,14 +15196,14 @@ VkResult VmaAllocator_T::AllocateDedicatedMemoryPage( } void VmaAllocator_T::GetBufferMemoryRequirements( - VkBuffer hBuffer, + VkBuffer hBuffer, VkMemoryRequirements &memReq, - bool & requiresDedicatedAllocation, - bool & prefersDedicatedAllocation) const { + bool &requiresDedicatedAllocation, + bool &prefersDedicatedAllocation) const { #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 if (m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) { VkBufferMemoryRequirementsInfo2KHR memReqInfo = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR}; - memReqInfo.buffer = hBuffer; + memReqInfo.buffer = hBuffer; VkMemoryDedicatedRequirementsKHR memDedicatedReq = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR}; @@ -15212,27 +15212,27 @@ void VmaAllocator_T::GetBufferMemoryRequirements( (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); - memReq = memReq2.memoryRequirements; + memReq = memReq2.memoryRequirements; requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); - prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); + prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); } else #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 { (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq); requiresDedicatedAllocation = false; - prefersDedicatedAllocation = false; + prefersDedicatedAllocation = false; } } void VmaAllocator_T::GetImageMemoryRequirements( - VkImage hImage, + VkImage hImage, VkMemoryRequirements &memReq, - bool & requiresDedicatedAllocation, - bool & prefersDedicatedAllocation) const { + bool &requiresDedicatedAllocation, + bool &prefersDedicatedAllocation) const { #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 if (m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) { VkImageMemoryRequirementsInfo2KHR memReqInfo = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR}; - memReqInfo.image = hImage; + memReqInfo.image = hImage; VkMemoryDedicatedRequirementsKHR memDedicatedReq = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR}; @@ -15241,29 +15241,29 @@ void VmaAllocator_T::GetImageMemoryRequirements( (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); - memReq = memReq2.memoryRequirements; + memReq = memReq2.memoryRequirements; requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); - prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); + prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); } else #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 { (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq); requiresDedicatedAllocation = false; - prefersDedicatedAllocation = false; + prefersDedicatedAllocation = false; } } VkResult VmaAllocator_T::AllocateMemory( - const VkMemoryRequirements & vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, - VkBuffer dedicatedBuffer, - VkBufferUsageFlags dedicatedBufferUsage, - VkImage dedicatedImage, + const VkMemoryRequirements &vkMemReq, + bool requiresDedicatedAllocation, + bool prefersDedicatedAllocation, + VkBuffer dedicatedBuffer, + VkBufferUsageFlags dedicatedBufferUsage, + VkImage dedicatedImage, const VmaAllocationCreateInfo &createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation * pAllocations) { + VmaSuballocationType suballocType, + size_t allocationCount, + VmaAllocation *pAllocations) { memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); VMA_ASSERT(VmaIsPow2(vkMemReq.alignment)); @@ -15320,8 +15320,8 @@ VkResult VmaAllocator_T::AllocateMemory( } else { // Bit mask of memory Vulkan types acceptable for this allocation. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits; - uint32_t memTypeIndex = UINT32_MAX; - VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex); + uint32_t memTypeIndex = UINT32_MAX; + VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex); if (res == VK_SUCCESS) { VkDeviceSize alignmentForMemType = VMA_MAX( vkMemReq.alignment, @@ -15388,7 +15388,7 @@ VkResult VmaAllocator_T::AllocateMemory( } void VmaAllocator_T::FreeMemory( - size_t allocationCount, + size_t allocationCount, const VmaAllocation *pAllocations) { VMA_ASSERT(pAllocations); @@ -15404,12 +15404,12 @@ void VmaAllocator_T::FreeMemory( switch (allocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaBlockVector *pBlockVector = VMA_NULL; - VmaPool hPool = allocation->GetBlock()->GetParentPool(); + VmaPool hPool = allocation->GetBlock()->GetParentPool(); if (hPool != VK_NULL_HANDLE) { pBlockVector = &hPool->m_BlockVector; } else { const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); - pBlockVector = m_pBlockVectors[memTypeIndex]; + pBlockVector = m_pBlockVectors[memTypeIndex]; } pBlockVector->Free(allocation); } break; @@ -15454,10 +15454,10 @@ void VmaAllocator_T::CalculateStats(VmaStats *pStats) { // Process dedicated allocations. for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { - const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); - VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); + const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); + VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); DedicatedAllocationLinkedList &dedicatedAllocList = m_DedicatedAllocations[memTypeIndex]; - for (VmaAllocation alloc = dedicatedAllocList.Front(); + for (VmaAllocation alloc = dedicatedAllocList.Front(); alloc != VMA_NULL; alloc = dedicatedAllocList.GetNext(alloc)) { VmaStatInfo allocationStatInfo; alloc->DedicatedAllocCalcStatsInfo(allocationStatInfo); @@ -15483,7 +15483,7 @@ void VmaAllocator_T::GetBudget(VmaBudget *outBudget, uint32_t firstHeap, uint32_ for (uint32_t i = 0; i < heapCount; ++i, ++outBudget) { const uint32_t heapIndex = firstHeap + i; - outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex]; + outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex]; outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; if (m_Budget.m_VulkanUsage[heapIndex] + outBudget->blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]) { @@ -15507,10 +15507,10 @@ void VmaAllocator_T::GetBudget(VmaBudget *outBudget, uint32_t firstHeap, uint32_ for (uint32_t i = 0; i < heapCount; ++i, ++outBudget) { const uint32_t heapIndex = firstHeap + i; - outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex]; + outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex]; outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; - outBudget->usage = outBudget->blockBytes; + outBudget->usage = outBudget->blockBytes; outBudget->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics. } } @@ -15520,8 +15520,8 @@ static const uint32_t VMA_VENDOR_ID_AMD = 4098; VkResult VmaAllocator_T::DefragmentationBegin( const VmaDefragmentationInfo2 &info, - VmaDefragmentationStats * pStats, - VmaDefragmentationContext * pContext) { + VmaDefragmentationStats *pStats, + VmaDefragmentationContext *pContext) { if (info.pAllocationsChanged != VMA_NULL) { memset(info.pAllocationsChanged, 0, info.allocationCount * sizeof(VkBool32)); } @@ -15554,7 +15554,7 @@ VkResult VmaAllocator_T::DefragmentationEnd( VkResult VmaAllocator_T::DefragmentationPassBegin( VmaDefragmentationPassInfo *pInfo, - VmaDefragmentationContext context) { + VmaDefragmentationContext context) { return context->DefragmentPassBegin(pInfo); } VkResult VmaAllocator_T::DefragmentationPassEnd( @@ -15568,24 +15568,24 @@ void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationI Warning: This is a carefully designed algorithm. Do not modify unless you really know what you're doing :) */ - const uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); - uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); + const uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); + uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for (;;) { if (localLastUseFrameIndex == VMA_FRAME_INDEX_LOST) { - pAllocationInfo->memoryType = UINT32_MAX; + pAllocationInfo->memoryType = UINT32_MAX; pAllocationInfo->deviceMemory = VK_NULL_HANDLE; - pAllocationInfo->offset = 0; - pAllocationInfo->size = hAllocation->GetSize(); - pAllocationInfo->pMappedData = VMA_NULL; - pAllocationInfo->pUserData = hAllocation->GetUserData(); + pAllocationInfo->offset = 0; + pAllocationInfo->size = hAllocation->GetSize(); + pAllocationInfo->pMappedData = VMA_NULL; + pAllocationInfo->pUserData = hAllocation->GetUserData(); return; } else if (localLastUseFrameIndex == localCurrFrameIndex) { - pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); + pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); pAllocationInfo->deviceMemory = hAllocation->GetMemory(); - pAllocationInfo->offset = hAllocation->GetOffset(); - pAllocationInfo->size = hAllocation->GetSize(); - pAllocationInfo->pMappedData = VMA_NULL; - pAllocationInfo->pUserData = hAllocation->GetUserData(); + pAllocationInfo->offset = hAllocation->GetOffset(); + pAllocationInfo->size = hAllocation->GetSize(); + pAllocationInfo->pMappedData = VMA_NULL; + pAllocationInfo->pUserData = hAllocation->GetUserData(); return; } else // Last use time earlier than current time. { @@ -15596,7 +15596,7 @@ void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationI } } else { #if VMA_STATS_STRING_ENABLED - uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); + uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for (;;) { VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST); @@ -15611,19 +15611,19 @@ void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationI } #endif - pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); + pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); pAllocationInfo->deviceMemory = hAllocation->GetMemory(); - pAllocationInfo->offset = hAllocation->GetOffset(); - pAllocationInfo->size = hAllocation->GetSize(); - pAllocationInfo->pMappedData = hAllocation->GetMappedData(); - pAllocationInfo->pUserData = hAllocation->GetUserData(); + pAllocationInfo->offset = hAllocation->GetOffset(); + pAllocationInfo->size = hAllocation->GetSize(); + pAllocationInfo->pMappedData = hAllocation->GetMappedData(); + pAllocationInfo->pUserData = hAllocation->GetUserData(); } } bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation) { // This is a stripped-down version of VmaAllocator_T::GetAllocationInfo. if (hAllocation->CanBecomeLost()) { - uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); + uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for (;;) { if (localLastUseFrameIndex == VMA_FRAME_INDEX_LOST) { @@ -15639,7 +15639,7 @@ bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation) { } } else { #if VMA_STATS_STRING_ENABLED - uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); + uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for (;;) { VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST); @@ -15803,7 +15803,7 @@ private: VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo *pAllocateInfo, VkDeviceMemory *pMemory) { AtomicTransactionalIncrement deviceMemoryCountIncrement; - const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount); + const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount); #if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT if (prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount) { return VK_ERROR_TOO_MANY_OBJECTS; @@ -15814,8 +15814,8 @@ VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo *pAlloc // HeapSizeLimit is in effect for this heap. if ((m_HeapSizeLimitMask & (1u << heapIndex)) != 0) { - const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; - VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex]; + const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; + VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex]; for (;;) { const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize; if (blockBytesAfterAllocation > heapSize) { @@ -15866,18 +15866,18 @@ void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, Vk VkResult VmaAllocator_T::BindVulkanBuffer( VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkBuffer buffer, - const void * pNext) { + VkDeviceSize memoryOffset, + VkBuffer buffer, + const void *pNext) { if (pNext != VMA_NULL) { #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 if ((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL) { VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = {VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR}; - bindBufferMemoryInfo.pNext = pNext; - bindBufferMemoryInfo.buffer = buffer; - bindBufferMemoryInfo.memory = memory; - bindBufferMemoryInfo.memoryOffset = memoryOffset; + bindBufferMemoryInfo.pNext = pNext; + bindBufferMemoryInfo.buffer = buffer; + bindBufferMemoryInfo.memory = memory; + bindBufferMemoryInfo.memoryOffset = memoryOffset; return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); } else #endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 @@ -15891,18 +15891,18 @@ VkResult VmaAllocator_T::BindVulkanBuffer( VkResult VmaAllocator_T::BindVulkanImage( VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkImage image, - const void * pNext) { + VkDeviceSize memoryOffset, + VkImage image, + const void *pNext) { if (pNext != VMA_NULL) { #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 if ((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL) { VkBindImageMemoryInfoKHR bindBufferMemoryInfo = {VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR}; - bindBufferMemoryInfo.pNext = pNext; - bindBufferMemoryInfo.image = image; - bindBufferMemoryInfo.memory = memory; - bindBufferMemoryInfo.memoryOffset = memoryOffset; + bindBufferMemoryInfo.pNext = pNext; + bindBufferMemoryInfo.image = image; + bindBufferMemoryInfo.memory = memory; + bindBufferMemoryInfo.memoryOffset = memoryOffset; return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); } else #endif // #if VMA_BIND_MEMORY2 @@ -15922,8 +15922,8 @@ VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void **ppData) { switch (hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaDeviceMemoryBlock *const pBlock = hAllocation->GetBlock(); - char * pBytes = VMA_NULL; - VkResult res = pBlock->Map(this, 1, (void **)&pBytes); + char *pBytes = VMA_NULL; + VkResult res = pBlock->Map(this, 1, (void **)&pBytes); if (res == VK_SUCCESS) { *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset(); hAllocation->BlockAllocMap(); @@ -15955,9 +15955,9 @@ void VmaAllocator_T::Unmap(VmaAllocation hAllocation) { VkResult VmaAllocator_T::BindBufferMemory( VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkBuffer hBuffer, + const void *pNext) { VkResult res = VK_SUCCESS; switch (hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: @@ -15977,9 +15977,9 @@ VkResult VmaAllocator_T::BindBufferMemory( VkResult VmaAllocator_T::BindImageMemory( VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkImage hImage, + const void *pNext) { VkResult res = VK_SUCCESS; switch (hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: @@ -16021,18 +16021,18 @@ VkResult VmaAllocator_T::FlushOrInvalidateAllocation( } VkResult VmaAllocator_T::FlushOrInvalidateAllocations( - uint32_t allocationCount, + uint32_t allocationCount, const VmaAllocation *allocations, const VkDeviceSize *offsets, const VkDeviceSize *sizes, VMA_CACHE_OPERATION op) { - typedef VmaStlAllocator RangeAllocator; + typedef VmaStlAllocator RangeAllocator; typedef VmaSmallVector RangeVector; - RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks())); + RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks())); for (uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex) { - const VmaAllocation alloc = allocations[allocIndex]; - const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0; - const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE; + const VmaAllocation alloc = allocations[allocIndex]; + const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0; + const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE; VkMappedMemoryRange newRange; if (GetFlushOrInvalidateRange(alloc, offset, size, newRange)) { ranges.push_back(newRange); @@ -16061,7 +16061,7 @@ void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation) { const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); { - VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); + VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); DedicatedAllocationLinkedList &dedicatedAllocations = m_DedicatedAllocations[memTypeIndex]; dedicatedAllocations.Remove(allocation); } @@ -16130,11 +16130,11 @@ bool VmaAllocator_T::GetFlushOrInvalidateRange( const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); if (size > 0 && IsMemoryTypeNonCoherent(memTypeIndex)) { const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; - const VkDeviceSize allocationSize = allocation->GetSize(); + const VkDeviceSize allocationSize = allocation->GetSize(); VMA_ASSERT(offset <= allocationSize); - outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - outRange.pNext = VMA_NULL; + outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; + outRange.pNext = VMA_NULL; outRange.memory = allocation->GetMemory(); switch (allocation->GetType()) { @@ -16192,8 +16192,8 @@ void VmaAllocator_T::UpdateVulkanBudget() { VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex); for (uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) { - m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex]; - m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex]; + m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex]; + m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex]; m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load(); // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size. @@ -16216,8 +16216,8 @@ void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pat if (VMA_DEBUG_INITIALIZE_ALLOCATIONS && !hAllocation->CanBecomeLost() && (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { - void * pData = VMA_NULL; - VkResult res = Map(hAllocation, &pData); + void *pData = VMA_NULL; + VkResult res = Map(hAllocation, &pData); if (res == VK_SUCCESS) { memset(pData, (int)pattern, (size_t)hAllocation->GetSize()); FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH); @@ -16242,7 +16242,7 @@ uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits() { void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter &json) { bool dedicatedAllocationsStarted = false; for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { - VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); + VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); DedicatedAllocationLinkedList &dedicatedAllocList = m_DedicatedAllocations[memTypeIndex]; if (!dedicatedAllocList.IsEmpty()) { if (dedicatedAllocationsStarted == false) { @@ -16257,7 +16257,7 @@ void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter &json) { json.BeginArray(); - for (VmaAllocation alloc = dedicatedAllocList.Front(); + for (VmaAllocation alloc = dedicatedAllocList.Front(); alloc != VMA_NULL; alloc = dedicatedAllocList.GetNext(alloc)) { json.BeginObject(true); alloc->PrintParameters(json); @@ -16318,7 +16318,7 @@ void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter &json) { VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator( const VmaAllocatorCreateInfo *pCreateInfo, - VmaAllocator * pAllocator) { + VmaAllocator *pAllocator) { VMA_ASSERT(pCreateInfo && pAllocator); VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 || (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 2)); @@ -16338,28 +16338,28 @@ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator( VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo *pAllocatorInfo) { VMA_ASSERT(allocator && pAllocatorInfo); - pAllocatorInfo->instance = allocator->m_hInstance; + pAllocatorInfo->instance = allocator->m_hInstance; pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice(); - pAllocatorInfo->device = allocator->m_hDevice; + pAllocatorInfo->device = allocator->m_hDevice; } VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( - VmaAllocator allocator, + VmaAllocator allocator, const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties) { VMA_ASSERT(allocator && ppPhysicalDeviceProperties); *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties; } VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( - VmaAllocator allocator, + VmaAllocator allocator, const VkPhysicalDeviceMemoryProperties **ppPhysicalDeviceMemoryProperties) { VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties); *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps; } VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( - VmaAllocator allocator, - uint32_t memoryTypeIndex, + VmaAllocator allocator, + uint32_t memoryTypeIndex, VkMemoryPropertyFlags *pFlags) { VMA_ASSERT(allocator && pFlags); VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount()); @@ -16368,7 +16368,7 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( VmaAllocator allocator, - uint32_t frameIndex) { + uint32_t frameIndex) { VMA_ASSERT(allocator); VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST); @@ -16379,7 +16379,7 @@ VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats( VmaAllocator allocator, - VmaStats * pStats) { + VmaStats *pStats) { VMA_ASSERT(allocator && pStats); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->CalculateStats(pStats); @@ -16387,7 +16387,7 @@ VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats( VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget( VmaAllocator allocator, - VmaBudget * pBudget) { + VmaBudget *pBudget) { VMA_ASSERT(allocator && pBudget); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->GetBudget(pBudget, 0, allocator->GetMemoryHeapCount()); @@ -16397,8 +16397,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget( VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( VmaAllocator allocator, - char ** ppStatsString, - VkBool32 detailedMap) { + char **ppStatsString, + VkBool32 detailedMap) { VMA_ASSERT(allocator && ppStatsString); VMA_DEBUG_GLOBAL_MUTEX_LOCK @@ -16510,18 +16510,18 @@ VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( json.EndObject(); } - const size_t len = sb.GetLength(); - char *const pChars = vma_new_array(allocator, char, len + 1); + const size_t len = sb.GetLength(); + char *const pChars = vma_new_array(allocator, char, len + 1); if (len > 0) { memcpy(pChars, sb.GetData(), len); } - pChars[len] = '\0'; + pChars[len] = '\0'; *ppStatsString = pChars; } VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( VmaAllocator allocator, - char * pStatsString) { + char *pStatsString) { if (pStatsString != VMA_NULL) { VMA_ASSERT(allocator); size_t len = strlen(pStatsString); @@ -16535,10 +16535,10 @@ VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( This function is not protected by any mutex because it just reads immutable data. */ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( - VmaAllocator allocator, - uint32_t memoryTypeBits, + VmaAllocator allocator, + uint32_t memoryTypeBits, const VmaAllocationCreateInfo *pAllocationCreateInfo, - uint32_t * pMemoryTypeIndex) { + uint32_t *pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); @@ -16549,8 +16549,8 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits; } - uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags; - uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags; + uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags; + uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags; uint32_t notPreferredFlags = 0; // Convert usage to requiredFlags and preferredFlags. @@ -16593,7 +16593,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( } *pMemoryTypeIndex = UINT32_MAX; - uint32_t minCost = UINT32_MAX; + uint32_t minCost = UINT32_MAX; for (uint32_t memTypeIndex = 0, memTypeBit = 1; memTypeIndex < allocator->GetMemoryTypeCount(); ++memTypeIndex, memTypeBit <<= 1) { @@ -16621,18 +16621,18 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( - VmaAllocator allocator, - const VkBufferCreateInfo * pBufferCreateInfo, + VmaAllocator allocator, + const VkBufferCreateInfo *pBufferCreateInfo, const VmaAllocationCreateInfo *pAllocationCreateInfo, - uint32_t * pMemoryTypeIndex) { + uint32_t *pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pBufferCreateInfo != VMA_NULL); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); - const VkDevice hDev = allocator->m_hDevice; - VkBuffer hBuffer = VK_NULL_HANDLE; - VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer( + const VkDevice hDev = allocator->m_hDevice; + VkBuffer hBuffer = VK_NULL_HANDLE; + VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer( hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer); if (res == VK_SUCCESS) { VkMemoryRequirements memReq = {}; @@ -16652,18 +16652,18 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( - VmaAllocator allocator, - const VkImageCreateInfo * pImageCreateInfo, + VmaAllocator allocator, + const VkImageCreateInfo *pImageCreateInfo, const VmaAllocationCreateInfo *pAllocationCreateInfo, - uint32_t * pMemoryTypeIndex) { + uint32_t *pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pImageCreateInfo != VMA_NULL); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); - const VkDevice hDev = allocator->m_hDevice; - VkImage hImage = VK_NULL_HANDLE; - VkResult res = allocator->GetVulkanFunctions().vkCreateImage( + const VkDevice hDev = allocator->m_hDevice; + VkImage hImage = VK_NULL_HANDLE; + VkResult res = allocator->GetVulkanFunctions().vkCreateImage( hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage); if (res == VK_SUCCESS) { VkMemoryRequirements memReq = {}; @@ -16683,9 +16683,9 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( - VmaAllocator allocator, + VmaAllocator allocator, const VmaPoolCreateInfo *pCreateInfo, - VmaPool * pPool) { + VmaPool *pPool) { VMA_ASSERT(allocator && pCreateInfo && pPool); VMA_DEBUG_LOG("vmaCreatePool"); @@ -16705,7 +16705,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( VmaAllocator allocator, - VmaPool pool) { + VmaPool pool) { VMA_ASSERT(allocator); if (pool == VK_NULL_HANDLE) { @@ -16726,8 +16726,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( } VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats( - VmaAllocator allocator, - VmaPool pool, + VmaAllocator allocator, + VmaPool pool, VmaPoolStats *pPoolStats) { VMA_ASSERT(allocator && pool && pPoolStats); @@ -16738,8 +16738,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats( VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost( VmaAllocator allocator, - VmaPool pool, - size_t * pLostAllocationCount) { + VmaPool pool, + size_t *pLostAllocationCount) { VMA_ASSERT(allocator && pool); VMA_DEBUG_GLOBAL_MUTEX_LOCK @@ -16765,7 +16765,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocato VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( VmaAllocator allocator, - VmaPool pool, + VmaPool pool, const char **ppName) { VMA_ASSERT(allocator && pool && ppName); @@ -16778,8 +16778,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( VmaAllocator allocator, - VmaPool pool, - const char * pName) { + VmaPool pool, + const char *pName) { VMA_ASSERT(allocator && pool); VMA_DEBUG_LOG("vmaSetPoolName"); @@ -16796,11 +16796,11 @@ VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( - VmaAllocator allocator, - const VkMemoryRequirements * pVkMemoryRequirements, + VmaAllocator allocator, + const VkMemoryRequirements *pVkMemoryRequirements, const VmaAllocationCreateInfo *pCreateInfo, - VmaAllocation * pAllocation, - VmaAllocationInfo * pAllocationInfo) { + VmaAllocation *pAllocation, + VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemory"); @@ -16837,12 +16837,12 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( - VmaAllocator allocator, - const VkMemoryRequirements * pVkMemoryRequirements, + VmaAllocator allocator, + const VkMemoryRequirements *pVkMemoryRequirements, const VmaAllocationCreateInfo *pCreateInfo, - size_t allocationCount, - VmaAllocation * pAllocations, - VmaAllocationInfo * pAllocationInfo) { + size_t allocationCount, + VmaAllocation *pAllocations, + VmaAllocationInfo *pAllocationInfo) { if (allocationCount == 0) { return VK_SUCCESS; } @@ -16886,20 +16886,20 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( - VmaAllocator allocator, - VkBuffer buffer, + VmaAllocator allocator, + VkBuffer buffer, const VmaAllocationCreateInfo *pCreateInfo, - VmaAllocation * pAllocation, - VmaAllocationInfo * pAllocationInfo) { + VmaAllocation *pAllocation, + VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer"); VMA_DEBUG_GLOBAL_MUTEX_LOCK - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; allocator->GetBufferMemoryRequirements(buffer, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); @@ -16936,20 +16936,20 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( - VmaAllocator allocator, - VkImage image, + VmaAllocator allocator, + VkImage image, const VmaAllocationCreateInfo *pCreateInfo, - VmaAllocation * pAllocation, - VmaAllocationInfo * pAllocationInfo) { + VmaAllocation *pAllocation, + VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemoryForImage"); VMA_DEBUG_GLOBAL_MUTEX_LOCK - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; allocator->GetImageMemoryRequirements(image, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); @@ -16985,7 +16985,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( } VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator); @@ -17011,8 +17011,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( } VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( - VmaAllocator allocator, - size_t allocationCount, + VmaAllocator allocator, + size_t allocationCount, const VmaAllocation *pAllocations) { if (allocationCount == 0) { return; @@ -17037,8 +17037,8 @@ VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( } VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( - VmaAllocator allocator, - VmaAllocation allocation, + VmaAllocator allocator, + VmaAllocation allocation, VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && allocation && pAllocationInfo); @@ -17056,7 +17056,7 @@ VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( } VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); @@ -17074,9 +17074,9 @@ VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation( } VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - void * pUserData) { + void *pUserData) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK @@ -17094,7 +17094,7 @@ VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( } VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation *pAllocation) { VMA_ASSERT(allocator && pAllocation); @@ -17112,9 +17112,9 @@ VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - void ** ppData) { + void **ppData) { VMA_ASSERT(allocator && allocation && ppData); VMA_DEBUG_GLOBAL_MUTEX_LOCK @@ -17133,7 +17133,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( } VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); @@ -17191,11 +17191,11 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(VmaAllocator allocat } VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( - VmaAllocator allocator, - uint32_t allocationCount, + VmaAllocator allocator, + uint32_t allocationCount, const VmaAllocation *allocations, - const VkDeviceSize * offsets, - const VkDeviceSize * sizes) { + const VkDeviceSize *offsets, + const VkDeviceSize *sizes) { VMA_ASSERT(allocator); if (allocationCount == 0) { @@ -17220,11 +17220,11 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( - VmaAllocator allocator, - uint32_t allocationCount, + VmaAllocator allocator, + uint32_t allocationCount, const VmaAllocation *allocations, - const VkDeviceSize * offsets, - const VkDeviceSize * sizes) { + const VkDeviceSize *offsets, + const VkDeviceSize *sizes) { VMA_ASSERT(allocator); if (allocationCount == 0) { @@ -17259,29 +17259,29 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(VmaAllocator allocator, u } VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment( - VmaAllocator allocator, - const VmaAllocation * pAllocations, - size_t allocationCount, - VkBool32 * pAllocationsChanged, + VmaAllocator allocator, + const VmaAllocation *pAllocations, + size_t allocationCount, + VkBool32 *pAllocationsChanged, const VmaDefragmentationInfo *pDefragmentationInfo, - VmaDefragmentationStats * pDefragmentationStats) { + VmaDefragmentationStats *pDefragmentationStats) { // Deprecated interface, reimplemented using new one. VmaDefragmentationInfo2 info2 = {}; - info2.allocationCount = (uint32_t)allocationCount; - info2.pAllocations = pAllocations; - info2.pAllocationsChanged = pAllocationsChanged; + info2.allocationCount = (uint32_t)allocationCount; + info2.pAllocations = pAllocations; + info2.pAllocationsChanged = pAllocationsChanged; if (pDefragmentationInfo != VMA_NULL) { info2.maxCpuAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove; - info2.maxCpuBytesToMove = pDefragmentationInfo->maxBytesToMove; + info2.maxCpuBytesToMove = pDefragmentationInfo->maxBytesToMove; } else { info2.maxCpuAllocationsToMove = UINT32_MAX; - info2.maxCpuBytesToMove = VK_WHOLE_SIZE; + info2.maxCpuBytesToMove = VK_WHOLE_SIZE; } // info2.flags, maxGpuAllocationsToMove, maxGpuBytesToMove, commandBuffer deliberately left zero. VmaDefragmentationContext ctx; - VkResult res = vmaDefragmentationBegin(allocator, &info2, pDefragmentationStats, &ctx); + VkResult res = vmaDefragmentationBegin(allocator, &info2, pDefragmentationStats, &ctx); if (res == VK_NOT_READY) { res = vmaDefragmentationEnd(allocator, ctx); } @@ -17289,10 +17289,10 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin( - VmaAllocator allocator, + VmaAllocator allocator, const VmaDefragmentationInfo2 *pInfo, - VmaDefragmentationStats * pStats, - VmaDefragmentationContext * pContext) { + VmaDefragmentationStats *pStats, + VmaDefragmentationContext *pContext) { VMA_ASSERT(allocator && pInfo && pContext); // Degenerate case: Nothing to defragment. @@ -17322,7 +17322,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd( - VmaAllocator allocator, + VmaAllocator allocator, VmaDefragmentationContext context) { VMA_ASSERT(allocator); @@ -17345,8 +17345,8 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( - VmaAllocator allocator, - VmaDefragmentationContext context, + VmaAllocator allocator, + VmaDefragmentationContext context, VmaDefragmentationPassInfo *pInfo) { VMA_ASSERT(allocator); VMA_ASSERT(pInfo); @@ -17363,7 +17363,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( return allocator->DefragmentationPassBegin(pInfo, context); } VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( - VmaAllocator allocator, + VmaAllocator allocator, VmaDefragmentationContext context) { VMA_ASSERT(allocator); @@ -17377,9 +17377,9 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - VkBuffer buffer) { + VkBuffer buffer) { VMA_ASSERT(allocator && allocation && buffer); VMA_DEBUG_LOG("vmaBindBufferMemory"); @@ -17390,11 +17390,11 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - VkDeviceSize allocationLocalOffset, - VkBuffer buffer, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkBuffer buffer, + const void *pNext) { VMA_ASSERT(allocator && allocation && buffer); VMA_DEBUG_LOG("vmaBindBufferMemory2"); @@ -17405,9 +17405,9 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - VkImage image) { + VkImage image) { VMA_ASSERT(allocator && allocation && image); VMA_DEBUG_LOG("vmaBindImageMemory"); @@ -17418,11 +17418,11 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( - VmaAllocator allocator, + VmaAllocator allocator, VmaAllocation allocation, - VkDeviceSize allocationLocalOffset, - VkImage image, - const void * pNext) { + VkDeviceSize allocationLocalOffset, + VkImage image, + const void *pNext) { VMA_ASSERT(allocator && allocation && image); VMA_DEBUG_LOG("vmaBindImageMemory2"); @@ -17433,12 +17433,12 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( - VmaAllocator allocator, - const VkBufferCreateInfo * pBufferCreateInfo, + VmaAllocator allocator, + const VkBufferCreateInfo *pBufferCreateInfo, const VmaAllocationCreateInfo *pAllocationCreateInfo, - VkBuffer * pBuffer, - VmaAllocation * pAllocation, - VmaAllocationInfo * pAllocationInfo) { + VkBuffer *pBuffer, + VmaAllocation *pAllocation, + VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation); if (pBufferCreateInfo->size == 0) { @@ -17454,7 +17454,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( VMA_DEBUG_GLOBAL_MUTEX_LOCK - *pBuffer = VK_NULL_HANDLE; + *pBuffer = VK_NULL_HANDLE; *pAllocation = VK_NULL_HANDLE; // 1. Create VkBuffer. @@ -17464,9 +17464,9 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( pBuffer); if (res >= 0) { // 2. vkGetBufferMemoryRequirements. - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); @@ -17525,8 +17525,8 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( } VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( - VmaAllocator allocator, - VkBuffer buffer, + VmaAllocator allocator, + VkBuffer buffer, VmaAllocation allocation) { VMA_ASSERT(allocator); @@ -17558,12 +17558,12 @@ VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( } VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( - VmaAllocator allocator, - const VkImageCreateInfo * pImageCreateInfo, + VmaAllocator allocator, + const VkImageCreateInfo *pImageCreateInfo, const VmaAllocationCreateInfo *pAllocationCreateInfo, - VkImage * pImage, - VmaAllocation * pAllocation, - VmaAllocationInfo * pAllocationInfo) { + VkImage *pImage, + VmaAllocation *pAllocation, + VmaAllocationInfo *pAllocationInfo) { VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation); if (pImageCreateInfo->extent.width == 0 || @@ -17578,7 +17578,7 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( VMA_DEBUG_GLOBAL_MUTEX_LOCK - *pImage = VK_NULL_HANDLE; + *pImage = VK_NULL_HANDLE; *pAllocation = VK_NULL_HANDLE; // 1. Create VkImage. @@ -17590,9 +17590,9 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ? VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL : VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR; // 2. Allocate memory using allocator. - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; + VkMemoryRequirements vkMemReq = {}; + bool requiresDedicatedAllocation = false; + bool prefersDedicatedAllocation = false; allocator->GetImageMemoryRequirements(*pImage, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); @@ -17650,8 +17650,8 @@ VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( } VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( - VmaAllocator allocator, - VkImage image, + VmaAllocator allocator, + VkImage image, VmaAllocation allocation) { VMA_ASSERT(allocator); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp index 2dd4565042..d18ef27869 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp @@ -54,10 +54,10 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { _size = ceil(info.size / 4.0) * 4; WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = toWGPUBufferUsage(info.usage), - .size = _size, + .nextInChain = nullptr, + .label = nullptr, + .usage = toWGPUBufferUsage(info.usage), + .size = _size, .mappedAtCreation = false, //hasFlag(info.memUsage, MemoryUsageBit::DEVICE), }; @@ -72,13 +72,13 @@ void CCWGPUBuffer::doInit(const BufferInfo &info) { } _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - _internalChanged = true; + _internalChanged = true; } // namespace gfx void CCWGPUBuffer::doInit(const BufferViewInfo &info) { - _gpuBufferObject = ccnew CCWGPUBufferObject; + _gpuBufferObject = ccnew CCWGPUBufferObject; _gpuBufferObject->wgpuBuffer = static_cast(info.buffer)->gpuBufferObject()->wgpuBuffer; - _internalChanged = true; + _internalChanged = true; } void CCWGPUBuffer::doDestroy() { @@ -109,10 +109,10 @@ void CCWGPUBuffer::doResize(uint size, uint count) { _size = ceil(size / 4.0) * 4; WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = toWGPUBufferUsage(_usage), - .size = _size, + .nextInChain = nullptr, + .label = nullptr, + .usage = toWGPUBufferUsage(_usage), + .size = _size, .mappedAtCreation = false, //hasFlag(_memUsage, MemoryUsageBit::DEVICE), }; _gpuBufferObject->wgpuBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); @@ -157,9 +157,9 @@ void CCWGPUBuffer::update(const void *buffer, uint size) { // wgpuCommandEncoderRelease(cmdEncoder); // wgpuCommandBufferRelease(commandBuffer); - size_t offset = _isBufferView ? _offset : 0; + size_t offset = _isBufferView ? _offset : 0; uint32_t alignedSize = ceil(size / 4.0) * 4; - size_t buffSize = alignedSize; + size_t buffSize = alignedSize; wgpuQueueWriteBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, _gpuBufferObject->wgpuBuffer, offset, buffer, buffSize); //wgpuBufferUnmap(_gpuBufferObject->wgpuBuffer); } @@ -167,30 +167,30 @@ void CCWGPUBuffer::update(const void *buffer, uint size) { void CCWGPUBuffer::update(const DrawInfoList &drawInfos) { size_t drawInfoCount = drawInfos.size(); if (drawInfoCount > 0) { - void const *data = nullptr; - size_t offset = _isBufferView ? _offset : 0; - size_t buffSize = 0; + void const *data = nullptr; + size_t offset = _isBufferView ? _offset : 0; + size_t buffSize = 0; //if (hasFlag(_usage, BufferUsageBit::INDIRECT)) if (drawInfos[0].indexCount) { auto &indexedIndirectObjs = _gpuBufferObject->indexedIndirectObjs; for (size_t i = 0; i < drawInfoCount; i++) { - indexedIndirectObjs[i].indexCount = drawInfos[i].indexCount; + indexedIndirectObjs[i].indexCount = drawInfos[i].indexCount; indexedIndirectObjs[i].instanceCount = drawInfos[i].instanceCount /* ? drawInfos[i]->instanceCoun : 1 */; - indexedIndirectObjs[i].firstIndex = drawInfos[i].firstIndex; - indexedIndirectObjs[i].baseVertex = drawInfos[i].vertexOffset; + indexedIndirectObjs[i].firstIndex = drawInfos[i].firstIndex; + indexedIndirectObjs[i].baseVertex = drawInfos[i].vertexOffset; indexedIndirectObjs[i].firstInstance = 0; //check definition of indexedIndirectObj; } - data = indexedIndirectObjs.data(); + data = indexedIndirectObjs.data(); buffSize = indexedIndirectObjs.size() * sizeof(CCWGPUDrawIndexedIndirectObject); } else { auto &indirectObjs = _gpuBufferObject->indirectObjs; for (size_t i = 0; i < drawInfoCount; i++) { - indirectObjs[i].vertexCount = drawInfos[i].vertexCount; + indirectObjs[i].vertexCount = drawInfos[i].vertexCount; indirectObjs[i].instanceCount = drawInfos[i].instanceCount; - indirectObjs[i].firstIndex = drawInfos[i].firstIndex; + indirectObjs[i].firstIndex = drawInfos[i].firstIndex; indirectObjs[i].firstInstance = 0; // check definition of indirectObj; } - data = indirectObjs.data(); + data = indirectObjs.data(); buffSize = indirectObjs.size() * sizeof(CCWGPUDrawIndirectObject); } wgpuQueueWriteBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, _gpuBufferObject->wgpuBuffer, offset, data, buffSize); @@ -211,10 +211,10 @@ void CCWGPUBuffer::stamp() { CCWGPUBuffer *CCWGPUBuffer::defaultUniformBuffer() { if (!anoymous::defaultUniformBuffer) { BufferInfo info = { - .usage = BufferUsageBit::UNIFORM, + .usage = BufferUsageBit::UNIFORM, .memUsage = MemoryUsageBit::DEVICE, - .size = 4, - .flags = BufferFlagBit::NONE, + .size = 4, + .flags = BufferFlagBit::NONE, }; anoymous::defaultUniformBuffer = ccnew CCWGPUBuffer; anoymous::defaultUniformBuffer->initialize(info); @@ -225,10 +225,10 @@ CCWGPUBuffer *CCWGPUBuffer::defaultUniformBuffer() { CCWGPUBuffer *CCWGPUBuffer::defaultStorageBuffer() { if (!anoymous::defaultStorageBuffer) { BufferInfo info = { - .usage = BufferUsageBit::STORAGE, + .usage = BufferUsageBit::STORAGE, .memUsage = MemoryUsageBit::DEVICE, - .size = 4, - .flags = BufferFlagBit::NONE, + .size = 4, + .flags = BufferFlagBit::NONE, }; anoymous::defaultStorageBuffer = ccnew CCWGPUBuffer; anoymous::defaultStorageBuffer->initialize(info); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp index c28df80e77..d6ebb78dc2 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp @@ -51,8 +51,8 @@ CCWGPUCommandBuffer::CCWGPUCommandBuffer() : wrapper(val::object( } void CCWGPUCommandBuffer::doInit(const CommandBufferInfo &info) { - _gpuCommandBufferObj = ccnew CCWGPUCommandBufferObject; - _gpuCommandBufferObj->type = info.type; + _gpuCommandBufferObj = ccnew CCWGPUCommandBufferObject; + _gpuCommandBufferObj->type = info.type; _gpuCommandBufferObj->queue = static_cast(info.queue); } @@ -79,8 +79,8 @@ void CCWGPUCommandBuffer::end() { auto *pipelineState = _gpuCommandBufferObj->stateCache.pipelineState; if (pipelineState) { if (pipelineState->getBindPoint() == PipelineBindPoint::GRAPHICS) { - auto *queue = _gpuCommandBufferObj->queue; - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); + auto *queue = _gpuCommandBufferObj->queue; + auto wgpuCommandBuffer = wgpuCommandEncoderFinish(_gpuCommandBufferObj->wgpuCommandEncoder, nullptr); wgpuQueueSubmit(queue->gpuQueueObject()->wgpuQueue, 1, &wgpuCommandBuffer); wgpuCommandEncoderRelease(_gpuCommandBufferObj->wgpuCommandEncoder); _gpuCommandBufferObj->wgpuCommandEncoder = wgpuDefaultHandle; @@ -97,42 +97,42 @@ void CCWGPUCommandBuffer::end() { } void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const * /*secondaryCBs*/, uint /*secondaryCBCount*/) { - _renderPass = renderPass; + _renderPass = renderPass; _frameBuffer = fbo; CCWGPUFramebuffer *ccFrameBuffer = static_cast(fbo); - const ColorAttachmentList & colorConfigs = renderPass->getColorAttachments(); + const ColorAttachmentList &colorConfigs = renderPass->getColorAttachments(); const DepthStencilAttachment &depthStencilConfig = renderPass->getDepthStencilAttachment(); - const TextureList & textures = ccFrameBuffer->getColorTextures(); - Texture * dsTexture = ccFrameBuffer->getDepthStencilTexture(); - CCWGPUSwapchain * swapchain = ccFrameBuffer->swapchain(); + const TextureList &textures = ccFrameBuffer->getColorTextures(); + Texture *dsTexture = ccFrameBuffer->getDepthStencilTexture(); + CCWGPUSwapchain *swapchain = ccFrameBuffer->swapchain(); - WGPURenderPassDescriptor & renderPassDesc = _gpuCommandBufferObj->renderPassDescriptor; + WGPURenderPassDescriptor &renderPassDesc = _gpuCommandBufferObj->renderPassDescriptor; ccstd::vector colorAttachments; if (colorConfigs.empty()) { - renderPassDesc.nextInChain = nullptr; - renderPassDesc.label = "swapchain"; + renderPassDesc.nextInChain = nullptr; + renderPassDesc.label = "swapchain"; WGPURenderPassColorAttachment color = { - .view = swapchain->gpuSwapchainObject()->swapchainColor->gpuTextureObject()->selfView, - .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa - .loadOp = WGPULoadOp_Clear, //toWGPULoadOp(colorConfigs[0].loadOp), - .storeOp = WGPUStoreOp_Discard, //toWGPUStoreOp(colorConfigs[0].storeOp), - .clearColor = WGPUColor{0.2, 0.2, 0.2, 1.0}, + .view = swapchain->gpuSwapchainObject()->swapchainColor->gpuTextureObject()->selfView, + .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa + .loadOp = WGPULoadOp_Clear, //toWGPULoadOp(colorConfigs[0].loadOp), + .storeOp = WGPUStoreOp_Discard, //toWGPUStoreOp(colorConfigs[0].storeOp), + .clearColor = WGPUColor{0.2, 0.2, 0.2, 1.0}, }; colorAttachments.emplace_back(color); } else { renderPassDesc.nextInChain = nullptr; - renderPassDesc.label = "attachments"; + renderPassDesc.label = "attachments"; for (size_t i = 0; i < colorConfigs.size(); i++) { WGPURenderPassColorAttachment *colorAttchments = ccnew WGPURenderPassColorAttachment[colorConfigs.size()]; - WGPURenderPassColorAttachment color = { - .view = static_cast(textures[i])->gpuTextureObject()->selfView, + WGPURenderPassColorAttachment color = { + .view = static_cast(textures[i])->gpuTextureObject()->selfView, .resolveTarget = nullptr, //TODO_Zeqiang: wgpu offscr msaa - .loadOp = toWGPULoadOp(colorConfigs[i].loadOp), - .storeOp = toWGPUStoreOp(colorConfigs[i].storeOp), - .clearColor = toWGPUColor(colors[i]), + .loadOp = toWGPULoadOp(colorConfigs[i].loadOp), + .storeOp = toWGPUStoreOp(colorConfigs[i].storeOp), + .clearColor = toWGPUColor(colors[i]), }; colorAttachments.emplace_back(color); } @@ -141,14 +141,14 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f ccstd::vector depthStencils; if (dsTexture) { WGPURenderPassDepthStencilAttachment depthStencil = { - .view = static_cast(dsTexture)->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), - .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, - .depthReadOnly = false, - .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), - .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .view = static_cast(dsTexture)->gpuTextureObject()->selfView, + .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), + .clearDepth = depth, + .depthReadOnly = false, + .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), + .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), + .clearStencil = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -157,14 +157,14 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f renderPassDesc.depthStencilAttachment = nullptr; } else { WGPURenderPassDepthStencilAttachment depthStencil = { - .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, - .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), - .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .clearDepth = depth, - .depthReadOnly = false, - .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), - .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .clearStencil = stencil, + .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, + .depthLoadOp = WGPULoadOp_Clear, //toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), + .clearDepth = depth, + .depthReadOnly = false, + .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), + .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), + .clearStencil = stencil, .stencilReadOnly = false, }; depthStencils.emplace_back(depthStencil); @@ -176,9 +176,9 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f _gpuCommandBufferObj->renderPassBegan = true; - renderPassDesc.colorAttachments = colorAttachments.data(); - renderPassDesc.colorAttachmentCount = colorAttachments.size(); - renderPassDesc.depthStencilAttachment = depthStencils.empty() ? nullptr : depthStencils.data(); + renderPassDesc.colorAttachments = colorAttachments.data(); + renderPassDesc.colorAttachmentCount = colorAttachments.size(); + renderPassDesc.depthStencilAttachment = depthStencils.empty() ? nullptr : depthStencils.data(); _gpuCommandBufferObj->wgpuRenderPassEncoder = wgpuCommandEncoderBeginRenderPass(_gpuCommandBufferObj->wgpuCommandEncoder, &renderPassDesc); } // namespace gfx @@ -197,24 +197,24 @@ void CCWGPUCommandBuffer::bindPipelineState(PipelineState *pso) { } void CCWGPUCommandBuffer::bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) { - uint dynOffsetCount = dynamicOffsetCount; - const uint *dynOffsets = dynamicOffsets; - auto & descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; - auto iter = std::find_if(descriptorSets.begin(), descriptorSets.end(), [set](const CCWGPUDescriptorSetObject &descriptorSet) { + uint dynOffsetCount = dynamicOffsetCount; + const uint *dynOffsets = dynamicOffsets; + auto &descriptorSets = _gpuCommandBufferObj->stateCache.descriptorSets; + auto iter = std::find_if(descriptorSets.begin(), descriptorSets.end(), [set](const CCWGPUDescriptorSetObject &descriptorSet) { return descriptorSet.index == set; }); auto *ccDescriptorSet = static_cast(descriptorSet); if (ccDescriptorSet->dynamicOffsetCount() == 0) { dynOffsetCount = 0; - dynOffsets = nullptr; + dynOffsets = nullptr; } CCWGPUDescriptorSetObject dsObj = { - .index = set, - .descriptorSet = ccDescriptorSet, + .index = set, + .descriptorSet = ccDescriptorSet, .dynamicOffsetCount = dynOffsetCount, //dynamicOffsetCount, - .dynamicOffsets = dynOffsets, //dynamicOffsets, + .dynamicOffsets = dynOffsets, //dynamicOffsets, }; if (iter != descriptorSets.end()) { @@ -242,8 +242,8 @@ void CCWGPUCommandBuffer::setLineWidth(float /*width*/) { void CCWGPUCommandBuffer::setDepthBias(float constant, float clamp, float slope) { _gpuCommandBufferObj->stateCache.depthBiasConstant = constant; - _gpuCommandBufferObj->stateCache.depthBiasClamp = clamp; - _gpuCommandBufferObj->stateCache.depthBiasSlope = slope; + _gpuCommandBufferObj->stateCache.depthBiasClamp = clamp; + _gpuCommandBufferObj->stateCache.depthBiasSlope = slope; } void CCWGPUCommandBuffer::setBlendConstants(const Color &constants) { @@ -260,7 +260,7 @@ void CCWGPUCommandBuffer::setStencilWriteMask(StencilFace face, uint mask) { } void CCWGPUCommandBuffer::setStencilCompareMask(StencilFace face, uint ref, uint mask) { - _gpuCommandBufferObj->stateCache.stencilMasks[face].compareRef = ref; + _gpuCommandBufferObj->stateCache.stencilMasks[face].compareRef = ref; _gpuCommandBufferObj->stateCache.stencilMasks[face].compareMask = mask; } @@ -286,9 +286,9 @@ void CCWGPUCommandBuffer::bindStates() { descriptorSets[i].descriptorSet->prepare(); if (descriptorSets[i].descriptorSet->dynamicOffsetCount() != descriptorSets[i].dynamicOffsetCount) { - uint * dynOffsets = dynamicOffsetBuffer; - const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); - uint givenOffsetIndex = 0; + uint *dynOffsets = dynamicOffsetBuffer; + const Pairs &dynamicOffsets = descriptorSets[i].descriptorSet->dynamicOffsets(); + uint givenOffsetIndex = 0; for (size_t j = 0; j < descriptorSets[i].descriptorSet->dynamicOffsetCount(); ++j) { if (j >= descriptorSets[i].dynamicOffsetCount || dynamicOffsets[j].second == 0) { dynOffsets[j] = 0; @@ -354,7 +354,7 @@ void CCWGPUCommandBuffer::bindStates() { pipelineState->gpuPipelineStateObject()->wgpuRenderPipeline); //input assembler - const auto *ia = _gpuCommandBufferObj->stateCache.inputAssembler; + const auto *ia = _gpuCommandBufferObj->stateCache.inputAssembler; const auto &vertexBufferList = ia->getVertexBuffers(); for (size_t i = 0; i < vertexBufferList.size(); i++) { const auto *vertexBuffer = static_cast(vertexBufferList[i]); @@ -374,10 +374,10 @@ void CCWGPUCommandBuffer::bindStates() { buffer = _gpuCommandBufferObj->redundantVertexBufferMap[maxAttrLen]; } else { BufferInfo info = { - .usage = BufferUsageBit::VERTEX, + .usage = BufferUsageBit::VERTEX, .memUsage = MemoryUsageBit::DEVICE, - .size = maxAttrLen, - .flags = BufferFlagBit::NONE, + .size = maxAttrLen, + .flags = BufferFlagBit::NONE, }; buffer = ccnew CCWGPUBuffer; buffer->initialize(info); @@ -404,37 +404,37 @@ void CCWGPUCommandBuffer::bindStates() { wgpuRenderPassEncoderSetBlendConstant(_gpuCommandBufferObj->wgpuRenderPassEncoder, &blendColor); CCWGPUFramebuffer *ccFrameBuffer = static_cast(_frameBuffer); - const TextureList &textures = ccFrameBuffer->getColorTextures(); + const TextureList &textures = ccFrameBuffer->getColorTextures(); // minimum rendertarget w/h - uint32_t rtWidth = std::numeric_limits::max(); + uint32_t rtWidth = std::numeric_limits::max(); uint32_t rtHeight = std::numeric_limits::max(); for (size_t i = 0; i < textures.size(); i++) { - rtWidth = rtWidth > textures[i]->getWidth() ? textures[i]->getWidth() : rtWidth; + rtWidth = rtWidth > textures[i]->getWidth() ? textures[i]->getWidth() : rtWidth; rtHeight = rtHeight > textures[i]->getHeight() ? textures[i]->getHeight() : rtHeight; // printf("w, h %d %d\n", textures[i]->getWidth(), textures[i]->getHeight()); } // printf("minrt %u, %u\n", rtWidth, rtHeight); - const Viewport &vp = _gpuCommandBufferObj->stateCache.viewport; - uint32_t left = vp.left > 0 ? vp.left : 0; - uint32_t top = vp.top > 0 ? vp.top : 0; + const Viewport &vp = _gpuCommandBufferObj->stateCache.viewport; + uint32_t left = vp.left > 0 ? vp.left : 0; + uint32_t top = vp.top > 0 ? vp.top : 0; uint32_t width = vp.left > 0 ? vp.width : vp.width + vp.left; - width = left + width > rtWidth ? rtWidth - left : width; + width = left + width > rtWidth ? rtWidth - left : width; uint32_t height = vp.top > 0 ? vp.height : vp.height + vp.top; - height = top + height > rtHeight ? rtHeight - top : height; + height = top + height > rtHeight ? rtHeight - top : height; // printf("vp %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetViewport(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height, vp.minDepth, vp.maxDepth); const Rect &rect = _gpuCommandBufferObj->stateCache.rect; - left = rect.x > 0 ? rect.x : 0; - top = rect.y > 0 ? rect.y : 0; - width = rect.x > 0 ? rect.width : rect.width + rect.x; - width = left + width > rtWidth ? rtWidth - left : width; - height = rect.y > 0 ? rect.height : rect.height + rect.y; - height = top + height > rtHeight ? rtHeight - top : height; + left = rect.x > 0 ? rect.x : 0; + top = rect.y > 0 ? rect.y : 0; + width = rect.x > 0 ? rect.width : rect.width + rect.x; + width = left + width > rtWidth ? rtWidth - left : width; + height = rect.y > 0 ? rect.height : rect.height + rect.y; + height = top + height > rtHeight ? rtHeight - top : height; // printf("sc %u, %u, %u, %u\n", left, top, width, height); wgpuRenderPassEncoderSetScissorRect(_gpuCommandBufferObj->wgpuRenderPassEncoder, left, top, width, height); @@ -472,8 +472,8 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { auto *ia = static_cast(_gpuCommandBufferObj->stateCache.inputAssembler); if (ia->getIndirectBuffer()) { - auto *indirectBuffer = static_cast(ia->getIndirectBuffer()); - bool multiDrawIndirectSupport = false; + auto *indirectBuffer = static_cast(ia->getIndirectBuffer()); + bool multiDrawIndirectSupport = false; // indirectSupport not support, emscripten webgpu ver < 2021 // https://github.com/gpuweb/gpuweb/issues/1354 @@ -506,7 +506,7 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { } } else { auto *indexBuffer = static_cast(ia->getIndexBuffer()); - bool drawIndexed = indexBuffer && info.indexCount; + bool drawIndexed = indexBuffer && info.indexCount; if (drawIndexed) { wgpuRenderPassEncoderDrawIndexed(_gpuCommandBufferObj->wgpuRenderPassEncoder, @@ -527,23 +527,23 @@ void CCWGPUCommandBuffer::draw(const DrawInfo &info) { void CCWGPUCommandBuffer::updateBuffer(Buffer *buff, const void *data, uint size) { uint32_t alignedSize = ceil(size / 4.0) * 4; - size_t buffSize = alignedSize; + size_t buffSize = alignedSize; WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = WGPUBufferUsage_MapWrite | WGPUBufferUsage_CopySrc, - .size = alignedSize, + .nextInChain = nullptr, + .label = nullptr, + .usage = WGPUBufferUsage_MapWrite | WGPUBufferUsage_CopySrc, + .size = alignedSize, .mappedAtCreation = true, }; WGPUBuffer stagingBuffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - auto * mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, alignedSize); + auto *mappedBuffer = wgpuBufferGetMappedRange(stagingBuffer, 0, alignedSize); memcpy(mappedBuffer, data, size); wgpuBufferUnmap(static_cast(stagingBuffer)); - auto * ccBuffer = static_cast(buff); - size_t offset = ccBuffer->getOffset(); + auto *ccBuffer = static_cast(buff); + size_t offset = ccBuffer->getOffset(); CCWGPUBufferObject *bufferObj = ccBuffer->gpuBufferObject(); @@ -569,28 +569,28 @@ void CCWGPUCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Te }; WGPUImageCopyTexture imageCopyTexture = { - .texture = static_cast(texture)->gpuTextureObject()->wgpuTexture, + .texture = static_cast(texture)->gpuTextureObject()->wgpuTexture, .mipLevel = 0, - .origin = origin, - .aspect = WGPUTextureAspect_All, + .origin = origin, + .aspect = WGPUTextureAspect_All, }; - auto * ccTex = static_cast(texture); - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; + auto *ccTex = static_cast(texture); + uint32_t width = regions[i].texExtent.width; + uint32_t height = regions[i].texExtent.height; + uint32_t depth = regions[i].texExtent.depth; uint32_t bytesPerRow = GFX_FORMAT_INFOS[static_cast(ccTex->getFormat())].size * width; - uint32_t dataSize = bytesPerRow * height * depth; + uint32_t dataSize = bytesPerRow * height * depth; WGPUTextureDataLayout texLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, + .offset = 0, + .bytesPerRow = bytesPerRow, .rowsPerImage = height, }; WGPUExtent3D extent = { - .width = width, - .height = height, + .width = width, + .height = height, .depthOrArrayLayers = depth, }; @@ -610,10 +610,10 @@ void CCWGPUCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, }; WGPUImageCopyTexture imageCopyTextureSrc = { - .texture = srcTex->gpuTextureObject()->wgpuTexture, + .texture = srcTex->gpuTextureObject()->wgpuTexture, .mipLevel = regions[i].srcSubres.mipLevel, - .origin = srcOrigin, - .aspect = WGPUTextureAspect_All, + .origin = srcOrigin, + .aspect = WGPUTextureAspect_All, }; WGPUOrigin3D dstOrigin = { @@ -623,15 +623,15 @@ void CCWGPUCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, }; WGPUImageCopyTexture imageCopyTextureDst = { - .texture = dstTex->gpuTextureObject()->wgpuTexture, + .texture = dstTex->gpuTextureObject()->wgpuTexture, .mipLevel = regions[i].dstSubres.mipLevel, - .origin = dstOrigin, - .aspect = WGPUTextureAspect_All, + .origin = dstOrigin, + .aspect = WGPUTextureAspect_All, }; WGPUExtent3D extent = { - .width = regions[i].dstExtent.width, - .height = regions[i].dstExtent.height, + .width = regions[i].dstExtent.width, + .height = regions[i].dstExtent.height, .depthOrArrayLayers = regions[i].dstExtent.depth, }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h index 5244722ee8..12fe43306a 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.h @@ -95,7 +95,7 @@ protected: CCWGPUCommandBufferObject *_gpuCommandBufferObj = nullptr; - RenderPass * _renderPass = nullptr; + RenderPass *_renderPass = nullptr; Framebuffer *_frameBuffer = nullptr; // command buffer inner impl diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDef.h b/native/cocos/renderer/gfx-wgpu/WGPUDef.h index 82d045461a..917d84ca3e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDef.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDef.h @@ -196,7 +196,7 @@ private: class SPVShaderStageInstance { public: - ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; + ShaderStageFlagBit stage{ShaderStageFlagBit::NONE}; ccstd::vector spv; inline void setStage(ShaderStageFlagBit stageIn) { stage = stageIn; } @@ -216,7 +216,7 @@ public: inline void setImages(UniformStorageImageList images) { info.images = images; } inline void setSubpasses(UniformInputAttachmentList subpassInputs) { info.subpassInputs = subpassInputs; } - ShaderInfo info; + ShaderInfo info; ccstd::vector stages; }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp index 083acb6700..a64723bf58 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSet.cpp @@ -48,17 +48,17 @@ CCWGPUDescriptorSet::CCWGPUDescriptorSet() : wrapper(val::object( void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { _gpuBindGroupObj = ccnew CCWGPUBindGroupObject; - auto * dsLayout = static_cast(_layout); + auto *dsLayout = static_cast(_layout); CCWGPUBindGroupLayoutObject *layoutEntries = dsLayout->gpuLayoutEntryObject(); - const auto & bindings = dsLayout->getBindings(); - CCWGPUDeviceObject * deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); + const auto &bindings = dsLayout->getBindings(); + CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); for (size_t i = 0; i < bindings.size(); i++) { // effect.ts: INPUT_ATTACHMENT as combined texture but no sampler_texture desc type. if (hasFlag(COMBINED_ST_IN_USE, bindings[i].descriptorType)) { //1. texture - CCWGPUTexture * texture = deviceObj->defaultResources.commonTexture; + CCWGPUTexture *texture = deviceObj->defaultResources.commonTexture; WGPUBindGroupEntry texEntry = { - .binding = bindings[i].binding, + .binding = bindings[i].binding, .textureView = texture->gpuTextureObject()->selfView, }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); @@ -66,7 +66,7 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { dsLayout->updateLayout(texEntry.binding, nullptr, texture); // 2. sampler - CCWGPUSampler * sampler = deviceObj->defaultResources.sampler; + CCWGPUSampler *sampler = deviceObj->defaultResources.sampler; WGPUBindGroupEntry smpEntry = { .binding = bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, .sampler = sampler->gpuSampler(), @@ -75,14 +75,14 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { _samplerIdxMap.insert(std::make_pair(bindings[i].binding, _gpuBindGroupObj->bindGroupEntries.size() - 1)); dsLayout->updateLayout(smpEntry.binding, nullptr, nullptr, sampler); } else if (hasFlag(DESCRIPTOR_BUFFER_TYPE, bindings[i].descriptorType)) { - CCWGPUBuffer * buffer = hasFlag(DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::STORAGE_BUFFER, bindings[i].descriptorType) - ? deviceObj->defaultResources.storageBuffer - : deviceObj->defaultResources.uniformBuffer; + CCWGPUBuffer *buffer = hasFlag(DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::STORAGE_BUFFER, bindings[i].descriptorType) + ? deviceObj->defaultResources.storageBuffer + : deviceObj->defaultResources.uniformBuffer; WGPUBindGroupEntry bufferEntry = { .binding = bindings[i].binding, - .buffer = buffer->gpuBufferObject()->wgpuBuffer, - .size = buffer->getSize(), - .offset = buffer->getOffset(), + .buffer = buffer->gpuBufferObject()->wgpuBuffer, + .size = buffer->getSize(), + .offset = buffer->getOffset(), }; if (hasAnyFlags(bindings[i].descriptorType, DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::DYNAMIC_UNIFORM_BUFFER)) { @@ -90,9 +90,9 @@ void CCWGPUDescriptorSet::doInit(const DescriptorSetInfo &info) { } _gpuBindGroupObj->bindGroupEntries.push_back(bufferEntry); } else if (bindings[i].descriptorType == DescriptorType::STORAGE_IMAGE) { - CCWGPUTexture * texture = deviceObj->defaultResources.storageTexture; + CCWGPUTexture *texture = deviceObj->defaultResources.storageTexture; WGPUBindGroupEntry texEntry = { - .binding = bindings[i].binding, + .binding = bindings[i].binding, .textureView = texture->gpuTextureObject()->selfView, }; _gpuBindGroupObj->bindGroupEntries.push_back(texEntry); @@ -116,21 +116,21 @@ void CCWGPUDescriptorSet::update() { if (!_isDirty) { return; } - auto * dsLayout = static_cast(_layout); + auto *dsLayout = static_cast(_layout); const auto &bindings = dsLayout->getBindings(); for (size_t i = 0; i < bindings.size(); i++) { - const auto &binding = bindings[i]; - uint8_t resourceIndex = _layout->getDescriptorIndices()[i]; + const auto &binding = bindings[i]; + uint8_t resourceIndex = _layout->getDescriptorIndices()[i]; if (hasFlag(DESCRIPTOR_BUFFER_TYPE, bindings[i].descriptorType)) { if (_buffers[resourceIndex]) { - auto *buffer = static_cast(_buffers[resourceIndex]); + auto *buffer = static_cast(_buffers[resourceIndex]); auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[i]; buffer->check(); bindGroupEntry.binding = binding.binding; - bindGroupEntry.buffer = buffer->gpuBufferObject()->wgpuBuffer; - bindGroupEntry.offset = buffer->getOffset(); - bindGroupEntry.size = buffer->getSize(); + bindGroupEntry.buffer = buffer->gpuBufferObject()->wgpuBuffer; + bindGroupEntry.offset = buffer->getOffset(); + bindGroupEntry.size = buffer->getSize(); dsLayout->updateLayout(bindGroupEntry.binding, buffer); uint8_t bindIndex = binding.binding; if (hasAnyFlags(binding.descriptorType, DescriptorType::DYNAMIC_STORAGE_BUFFER | DescriptorType::DYNAMIC_UNIFORM_BUFFER)) { @@ -148,16 +148,16 @@ void CCWGPUDescriptorSet::update() { uint8_t textureIdx = texIter != _textureIdxMap.end() ? texIter->second : 255; uint8_t samplerIdx = smpIter != _samplerIdxMap.end() ? smpIter->second : 255; if (textureIdx != 255 && _textures[resourceIndex]) { - auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[textureIdx]; - auto *texture = static_cast(_textures[resourceIndex]); - bindGroupEntry.binding = binding.binding; + auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[textureIdx]; + auto *texture = static_cast(_textures[resourceIndex]); + bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); _gpuBindGroupObj->bindingSet.insert(binding.binding); } if (samplerIdx != 255 && _samplers[resourceIndex]) { - auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[samplerIdx]; - auto *sampler = static_cast(_samplers[resourceIndex]); + auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[samplerIdx]; + auto *sampler = static_cast(_samplers[resourceIndex]); bindGroupEntry.binding = binding.binding + CC_WGPU_MAX_ATTACHMENTS; bindGroupEntry.sampler = sampler->gpuSampler(); dsLayout->updateLayout(bindGroupEntry.binding, nullptr, nullptr, sampler); @@ -165,9 +165,9 @@ void CCWGPUDescriptorSet::update() { } } else if (DescriptorType::STORAGE_IMAGE == bindings[i].descriptorType) { if (_textures[resourceIndex]) { - auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; - auto *texture = static_cast(_textures[resourceIndex]); - bindGroupEntry.binding = binding.binding; + auto &bindGroupEntry = _gpuBindGroupObj->bindGroupEntries[resourceIndex]; + auto *texture = static_cast(_textures[resourceIndex]); + bindGroupEntry.binding = binding.binding; bindGroupEntry.textureView = texture->gpuTextureObject()->selfView; dsLayout->updateLayout(bindGroupEntry.binding, nullptr, texture); } @@ -179,7 +179,7 @@ void CCWGPUDescriptorSet::prepare() { auto buffIter = std::find_if(_buffers.begin(), _buffers.end(), [](const Buffer *buffer) { return buffer ? static_cast(buffer)->internalChanged() : false; }); - auto texIter = std::find_if(_textures.begin(), _textures.end(), [](const Texture *texture) { + auto texIter = std::find_if(_textures.begin(), _textures.end(), [](const Texture *texture) { return texture ? static_cast(texture)->internalChanged() : false; }); @@ -221,10 +221,10 @@ void CCWGPUDescriptorSet::prepare() { } else { WGPUBindGroupDescriptor bindGroupDesc = { .nextInChain = nullptr, - .label = nullptr, - .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, - .entryCount = entries.size(), - .entries = entries.data(), + .label = nullptr, + .layout = dsLayout->gpuLayoutEntryObject()->bindGroupLayout, + .entryCount = entries.size(), + .entries = entries.data(), }; _gpuBindGroupObj->bindgroup = wgpuDeviceCreateBindGroup(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &bindGroupDesc); // _bgl = dsLayout->gpuLayoutEntryObject()->bindGroupLayout; @@ -252,20 +252,20 @@ void *CCWGPUDescriptorSet::defaultBindGroup() { CCWGPUDeviceObject *deviceObj = CCWGPUDevice::getInstance()->gpuDeviceObject(); if (!anoymous::defaultBindGroup) { - CCWGPUBuffer * buffer = deviceObj->defaultResources.uniformBuffer; + CCWGPUBuffer *buffer = deviceObj->defaultResources.uniformBuffer; WGPUBindGroupEntry bufferEntry = { .binding = 0, - .buffer = buffer->gpuBufferObject()->wgpuBuffer, - .size = buffer->getSize(), - .offset = buffer->getOffset(), + .buffer = buffer->gpuBufferObject()->wgpuBuffer, + .size = buffer->getSize(), + .offset = buffer->getOffset(), }; WGPUBindGroupDescriptor bindGroupDesc = { .nextInChain = nullptr, - .label = nullptr, - .layout = static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()), - .entryCount = 1, - .entries = &bufferEntry, + .label = nullptr, + .layout = static_cast(CCWGPUDescriptorSetLayout::defaultBindGroupLayout()), + .entryCount = 1, + .entries = &bufferEntry, }; anoymous::defaultBindGroup = wgpuDeviceCreateBindGroup(deviceObj->wgpuDevice, &bindGroupDesc); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index 9d97dc3636..f26243b36a 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -57,19 +57,19 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { if (hasFlag(COMBINED_ST_IN_USE, _bindings[i].descriptorType)) { // 1. texture WGPUBindGroupLayoutEntry textureLayout = { - .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .texture.sampleType = WGPUTextureSampleType_Float, + .nextInChain = nullptr, + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .texture.sampleType = WGPUTextureSampleType_Float, .texture.viewDimension = WGPUTextureViewDimension_2D, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(textureLayout); // 2. sampler WGPUBindGroupLayoutEntry samplerLayout = { - .nextInChain = nullptr, - .binding = _bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .nextInChain = nullptr, + .binding = _bindings[i].binding + CC_WGPU_MAX_ATTACHMENTS, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), .sampler.type = WGPUSamplerBindingType_Filtering, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(samplerLayout); @@ -79,17 +79,17 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { if (hasFlag(_bindings[i].descriptorType, DescriptorType::STORAGE_BUFFER | DescriptorType::DYNAMIC_STORAGE_BUFFER)) { WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Storage, hasDynamicOffset, 0}, + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Storage, hasDynamicOffset, 0}, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } else if (hasFlag(_bindings[i].descriptorType, DescriptorType::UNIFORM_BUFFER | DescriptorType::DYNAMIC_UNIFORM_BUFFER)) { WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Uniform, hasDynamicOffset, 0}, + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Uniform, hasDynamicOffset, 0}, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } else { @@ -98,16 +98,16 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { } else if (_bindings[i].descriptorType == DescriptorType::SAMPLER) { WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), - .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_Comparison}, + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .sampler = {nullptr, WGPUSamplerBindingType::WGPUSamplerBindingType_Comparison}, }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } else if (_bindings[i].descriptorType == DescriptorType::STORAGE_IMAGE) { WGPUBindGroupLayoutEntry layout = { - .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .nextInChain = nullptr, + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), .storageTexture = { nullptr, WGPUStorageTextureAccess::WGPUStorageTextureAccess_WriteOnly, @@ -119,8 +119,8 @@ void CCWGPUDescriptorSetLayout::doInit(const DescriptorSetLayoutInfo &info) { } else { WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, - .binding = _bindings[i].binding, - .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), + .binding = _bindings[i].binding, + .visibility = toWGPUShaderStageFlag(_bindings[i].stageFlags), }; _gpuLayoutEntryObj->bindGroupLayoutEntries.push_back(layout); } @@ -146,18 +146,18 @@ void CCWGPUDescriptorSetLayout::updateLayout(uint8_t binding, const CCWGPUBuffer } if (tex) { if (tex->getInfo().usage == TextureUsageBit::STORAGE) { - (*iter).storageTexture.nextInChain = nullptr; - (*iter).storageTexture.access = WGPUStorageTextureAccess::WGPUStorageTextureAccess_WriteOnly; - (*iter).storageTexture.format = toWGPUTextureFormat(tex->getFormat()); - TextureType type = tex->isTextureView() ? tex->getViewInfo().type : tex->getInfo().type; + (*iter).storageTexture.nextInChain = nullptr; + (*iter).storageTexture.access = WGPUStorageTextureAccess::WGPUStorageTextureAccess_WriteOnly; + (*iter).storageTexture.format = toWGPUTextureFormat(tex->getFormat()); + TextureType type = tex->isTextureView() ? tex->getViewInfo().type : tex->getInfo().type; (*iter).storageTexture.viewDimension = toWGPUTextureViewDimension(type); } else { - (*iter).texture.nextInChain = nullptr; - (*iter).texture.sampleType = textureSampleTypeTrait(tex->getFormat()); - const CCWGPUTexture *ccTex = static_cast(tex->isTextureView() ? tex->getViewInfo().texture : tex); - TextureType type = ccTex->getViewInfo().type; + (*iter).texture.nextInChain = nullptr; + (*iter).texture.sampleType = textureSampleTypeTrait(tex->getFormat()); + const CCWGPUTexture *ccTex = static_cast(tex->isTextureView() ? tex->getViewInfo().texture : tex); + TextureType type = ccTex->getViewInfo().type; (*iter).texture.viewDimension = toWGPUTextureViewDimension(type); - (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; + (*iter).texture.multisampled = ccTex->getInfo().samples != SampleCount::ONE; } } } @@ -248,7 +248,7 @@ void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { // bindGroupLayoutEntries.end()); size_t hashVal = hash(); - auto iter = layoutPool.find(hashVal); + auto iter = layoutPool.find(hashVal); if (iter != layoutPool.end()) { _gpuLayoutEntryObj->bindGroupLayout = iter->second; return; @@ -272,9 +272,9 @@ void CCWGPUDescriptorSetLayout::prepare(bool forceUpdate) { } else { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, - .entryCount = entries.size(), - .entries = entries.data(), + .label = nullptr, + .entryCount = entries.size(), + .entries = entries.data(), }; _gpuLayoutEntryObj->bindGroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); } @@ -287,16 +287,16 @@ void *CCWGPUDescriptorSetLayout::defaultBindGroupLayout() { // default bindgroupLayout: for empty set WGPUBindGroupLayoutEntry layout = { .nextInChain = nullptr, - .binding = 0, - .visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment | WGPUShaderStage_Compute, - .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Uniform, false, 0}, + .binding = 0, + .visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment | WGPUShaderStage_Compute, + .buffer = {nullptr, WGPUBufferBindingType::WGPUBufferBindingType_Uniform, false, 0}, }; WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = nullptr, - .entryCount = 1, - .entries = &layout, + .label = nullptr, + .entryCount = 1, + .entries = &layout, }; anoymous::defaultBindgroupLayout = wgpuDeviceCreateBindGroupLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp index 0a1512f8bd..005d09213c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.cpp @@ -50,11 +50,11 @@ namespace cc { namespace gfx { struct BufferMapData { - Semaphore * semaphore = nullptr; - WGPUBuffer buffer = wgpuDefaultHandle; + Semaphore *semaphore = nullptr; + WGPUBuffer buffer = wgpuDefaultHandle; emscripten::val *retBuffer = nullptr; - uint64_t size = 0; - bool finished = false; + uint64_t size = 0; + bool finished = false; }; CCWGPUDevice *CCWGPUDevice::instance = nullptr; @@ -69,12 +69,12 @@ CCWGPUDevice *CCWGPUDevice::getInstance() { } CCWGPUDevice::CCWGPUDevice() : wrapper(val::object()) { - _api = API::WEBGPU; - _deviceName = "WebGPU"; - _caps.clipSpaceMinZ = 0.0F; + _api = API::WEBGPU; + _deviceName = "WebGPU"; + _caps.clipSpaceMinZ = 0.0F; _caps.screenSpaceSignY = -1.0F; - _caps.clipSpaceSignY = -1.0F; - instance = this; + _caps.clipSpaceSignY = -1.0F; + instance = this; } CCWGPUDevice::~CCWGPUDevice() { @@ -84,15 +84,15 @@ CCWGPUDevice::~CCWGPUDevice() { } bool CCWGPUDevice::doInit(const DeviceInfo &info) { - _gpuDeviceObj = ccnew CCWGPUDeviceObject; + _gpuDeviceObj = ccnew CCWGPUDeviceObject; _gpuDeviceObj->wgpuDevice = emscripten_webgpu_get_device(); - _gpuDeviceObj->wgpuQueue = wgpuDeviceGetQueue(_gpuDeviceObj->wgpuDevice); + _gpuDeviceObj->wgpuQueue = wgpuDeviceGetQueue(_gpuDeviceObj->wgpuDevice); - _gpuDeviceObj->defaultResources.uniformBuffer = CCWGPUBuffer::defaultUniformBuffer(); - _gpuDeviceObj->defaultResources.storageBuffer = CCWGPUBuffer::defaultStorageBuffer(); - _gpuDeviceObj->defaultResources.commonTexture = CCWGPUTexture::defaultCommonTexture(); + _gpuDeviceObj->defaultResources.uniformBuffer = CCWGPUBuffer::defaultUniformBuffer(); + _gpuDeviceObj->defaultResources.storageBuffer = CCWGPUBuffer::defaultStorageBuffer(); + _gpuDeviceObj->defaultResources.commonTexture = CCWGPUTexture::defaultCommonTexture(); _gpuDeviceObj->defaultResources.storageTexture = CCWGPUTexture::defaultStorageTexture(); - _gpuDeviceObj->defaultResources.sampler = CCWGPUSampler::defaultSampler(); + _gpuDeviceObj->defaultResources.sampler = CCWGPUSampler::defaultSampler(); QueueInfo queueInfo = { .type = QueueType::GRAPHICS, @@ -101,7 +101,7 @@ bool CCWGPUDevice::doInit(const DeviceInfo &info) { CommandBufferInfo cmdInfo = { .queue = _queue, - .type = CommandBufferType::PRIMARY, + .type = CommandBufferType::PRIMARY, }; _cmdBuff = this->Device::createCommandBuffer(cmdInfo); return true; @@ -163,9 +163,9 @@ CommandBuffer *CCWGPUDevice::createCommandBuffer(const CommandBufferInfo &info, } void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { - Format dstFormat = dst->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; - auto * texture = static_cast(dst); + Format dstFormat = dst->getFormat(); + uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + auto *texture = static_cast(dst); for (size_t i = 0; i < count; i++) { uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.height; @@ -173,21 +173,21 @@ void CCWGPUDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture * uint32_t bytesPerRow = pxSize * regions[i].texExtent.width; //it's buffer data layout WGPUTextureDataLayout texDataLayout = { - .offset = 0, - .bytesPerRow = bytesPerRow, + .offset = 0, + .bytesPerRow = bytesPerRow, .rowsPerImage = regions[i].texExtent.height, }; WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, + .width = regions[i].texExtent.width, + .height = regions[i].texExtent.height, .depthOrArrayLayers = regions[i].texExtent.depth, }; WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, + .texture = texture->gpuTextureObject()->wgpuTexture, .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ + .origin = WGPUOrigin3D{ static_cast(regions[i].texOffset.x), static_cast(regions[i].texOffset.y), static_cast(regions[i].texSubres.baseArrayLayer)}, @@ -230,33 +230,33 @@ void onQueueDone(WGPUQueueWorkDoneStatus status, void *userdata) { } emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTextureCopyList ®ions) { - auto * texture = static_cast(src); - Format dstFormat = src->getFormat(); - uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; - auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); + auto *texture = static_cast(src); + Format dstFormat = src->getFormat(); + uint32_t pxSize = GFX_FORMAT_INFOS[static_cast(dstFormat)].size; + auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); uint64_t size = std::accumulate(regions.begin(), regions.end(), 0, [pxSize](uint64_t initVal, const BufferTextureCopy &in) { uint32_t bytesPerRow = (pxSize * in.texExtent.width + 255) / 256 * 256; - uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; + uint32_t bufferSize = bytesPerRow * in.texExtent.height * in.texExtent.depth; return initVal + bufferSize; }); WGPUBufferDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, - .size = size, + .nextInChain = nullptr, + .label = nullptr, + .usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst, + .size = size, .mappedAtCreation = false, }; WGPUBuffer buffer = wgpuDeviceCreateBuffer(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - uint64_t offset = 0; + uint64_t offset = 0; for (size_t i = 0; i < regions.size(); i++) { - uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; + uint32_t bytesPerRow = (pxSize * regions[i].texExtent.width + 255) / 256 * 256; WGPUImageCopyTexture imageCopyTexture = { - .texture = texture->gpuTextureObject()->wgpuTexture, + .texture = texture->gpuTextureObject()->wgpuTexture, .mipLevel = regions[i].texSubres.mipLevel, - .origin = WGPUOrigin3D{ + .origin = WGPUOrigin3D{ static_cast(regions[i].texOffset.x), static_cast(regions[i].texOffset.y), static_cast(regions[i].texOffset.z)}, @@ -264,8 +264,8 @@ emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTex }; WGPUTextureDataLayout texDataLayout = { - .offset = offset, - .bytesPerRow = bytesPerRow, + .offset = offset, + .bytesPerRow = bytesPerRow, .rowsPerImage = regions[i].texExtent.height, }; uint32_t bufferSize = pxSize * regions[i].texExtent.width * regions[i].texExtent.depth; @@ -277,8 +277,8 @@ emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTex }; WGPUExtent3D extent = { - .width = regions[i].texExtent.width, - .height = regions[i].texExtent.height, + .width = regions[i].texExtent.width, + .height = regions[i].texExtent.height, .depthOrArrayLayers = regions[i].texExtent.depth, }; @@ -287,7 +287,7 @@ emscripten::val CCWGPUDevice::copyTextureToBuffers(Texture *src, const BufferTex auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); printf("Q submit\n"); - Semaphore sem{0}; + Semaphore sem{0}; BufferMapData *bufferMapData = ccnew BufferMapData{ &sem, buffer, @@ -337,7 +337,7 @@ void CCWGPUDevice::getQueryPoolResults(QueryPool *queryPool) { void CCWGPUDevice::debug() { auto wgpuCommandEncoder = wgpuDeviceCreateCommandEncoder(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, nullptr); - auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); + auto wgpuCommandBuffer = wgpuCommandEncoderFinish(wgpuCommandEncoder, nullptr); wgpuQueueSubmit(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuQueue, 1, &wgpuCommandBuffer); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h index 6e5d2ae52d..7f9c17dd49 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h @@ -117,9 +117,9 @@ public: Shader *createShader(const SPVShaderInfoInstance &spvInfo); void copyBuffersToTexture(const emscripten::val &v, Texture *dst, const BufferTextureCopyList ®ions) { - uint32_t len = v["length"].as(); + uint32_t len = v["length"].as(); ccstd::vector> lifeProlonger(len); - ccstd::vector buffers; + ccstd::vector buffers; for (size_t i = 0; i < len; i++) { lifeProlonger[i] = EMSArraysToU8Vec(v, i); buffers.push_back(lifeProlonger[i].data()); @@ -135,29 +135,29 @@ protected: CCWGPUDevice(); - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue * createQueue() override; - Buffer * createBuffer() override; - Texture * createTexture() override; - Shader * createShader() override; - InputAssembler * createInputAssembler() override; - RenderPass * createRenderPass() override; - Framebuffer * createFramebuffer() override; - DescriptorSet * createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue *createQueue() override; + Buffer *createBuffer() override; + Texture *createTexture() override; + Shader *createShader() override; + InputAssembler *createInputAssembler() override; + RenderPass *createRenderPass() override; + Framebuffer *createFramebuffer() override; + DescriptorSet *createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout * createPipelineLayout() override; - PipelineState * createPipelineState() override; - Swapchain * createSwapchain() override; - QueryPool * createQueryPool() override; - Sampler * createSampler(const SamplerInfo &info) override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; + Swapchain *createSwapchain() override; + QueryPool *createQueryPool() override; + Sampler *createSampler(const SamplerInfo &info) override; void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; void getQueryPoolResults(QueryPool *queryPool) override; - CCWGPUDeviceObject * _gpuDeviceObj = nullptr; + CCWGPUDeviceObject *_gpuDeviceObj = nullptr; ccstd::vector _swapchains; }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp index 5479d4a66c..156252b5d8 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUFrameBuffer.cpp @@ -35,7 +35,7 @@ CCWGPUFramebuffer::CCWGPUFramebuffer() : wrapper(val::object()) { void CCWGPUFramebuffer::doInit(const FramebufferInfo &info) { for (auto *tex : info.colorTextures) { - auto * ccTex = static_cast(tex); + auto *ccTex = static_cast(tex); CCWGPUSwapchain *swapchain = ccTex->swapchain(); if (swapchain) { _swapchain = swapchain; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUObject.h b/native/cocos/renderer/gfx-wgpu/WGPUObject.h index 250e1494f1..87a491770b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUObject.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUObject.h @@ -60,7 +60,7 @@ struct CCWGPUResource { CCWGPUBuffer *uniformBuffer = nullptr; CCWGPUBuffer *storageBuffer = nullptr; - CCWGPUTexture *commonTexture = nullptr; + CCWGPUTexture *commonTexture = nullptr; CCWGPUTexture *storageTexture = nullptr; CCWGPUSampler *sampler = nullptr; @@ -68,31 +68,31 @@ struct CCWGPUResource { struct CCWGPUDeviceObject { WGPUDevice wgpuDevice = wgpuDefaultHandle; - WGPUQueue wgpuQueue = wgpuDefaultHandle; + WGPUQueue wgpuQueue = wgpuDefaultHandle; CCWGPUResource defaultResources; }; struct CCWGPUSwapchainObject { WGPUSwapChain wgpuSwapChain = wgpuDefaultHandle; - WGPUSurface wgpuSurface = wgpuDefaultHandle; - WGPUInstance wgpuInstance = wgpuDefaultHandle; + WGPUSurface wgpuSurface = wgpuDefaultHandle; + WGPUInstance wgpuInstance = wgpuDefaultHandle; - CCWGPUTexture *swapchainColor = nullptr; + CCWGPUTexture *swapchainColor = nullptr; CCWGPUTexture *swapchainDepthStencil = nullptr; }; struct CCWGPURenderPassObject { - RenderPassInfo info; - ccstd::string label; - uint8_t sampleCount = 1; + RenderPassInfo info; + ccstd::string label; + uint8_t sampleCount = 1; WGPURenderPassDescriptor *wgpuRenderPassDesc = wgpuDefaultHandle; }; struct CCWGPUTextureObject { - WGPUTexture wgpuTexture = wgpuDefaultHandle; + WGPUTexture wgpuTexture = wgpuDefaultHandle; WGPUTextureView wgpuTextureView = wgpuDefaultHandle; - WGPUTextureView selfView = wgpuDefaultHandle; + WGPUTextureView selfView = wgpuDefaultHandle; }; //The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block @@ -104,10 +104,10 @@ struct CCWGPUTextureObject { // drawIndexedIndirectParameters[3] = baseVertex; // drawIndexedIndirectParameters[4] = 0; // firstInstance. Must be 0. struct CCWGPUDrawIndexedIndirectObject { - uint32_t indexCount = 0; + uint32_t indexCount = 0; uint32_t instanceCount = 0; - uint32_t firstIndex = 0; - uint32_t baseVertex = 0; + uint32_t firstIndex = 0; + uint32_t baseVertex = 0; uint32_t firstInstance = 0; }; static_assert(sizeof(CCWGPUDrawIndexedIndirectObject) == 20, "WGPU drawIndexedIndirect structure validation failed!"); @@ -121,45 +121,45 @@ static_assert(sizeof(CCWGPUDrawIndexedIndirectObject) == 20, "WGPU drawIndexedIn // drawIndirectParameters[2] = firstVertex; // drawIndirectParameters[3] = 0; // firstInstance. Must be 0. struct CCWGPUDrawIndirectObject { - uint32_t vertexCount = 0; + uint32_t vertexCount = 0; uint32_t instanceCount = 0; - uint32_t firstIndex = 0; + uint32_t firstIndex = 0; uint32_t firstInstance = 0; }; static_assert(sizeof(CCWGPUDrawIndirectObject) == 16, "WGPU drawIndirect structure validation failed!"); struct CCWGPUBufferObject { - WGPUBuffer wgpuBuffer = wgpuDefaultHandle; + WGPUBuffer wgpuBuffer = wgpuDefaultHandle; ccstd::vector indexedIndirectObjs; - ccstd::vector indirectObjs; - bool mapped = false; - bool hasDynamicOffsets = false; + ccstd::vector indirectObjs; + bool mapped = false; + bool hasDynamicOffsets = false; }; struct CCWGPUSamplerObject { WGPUSampler wgpuSampler = wgpuDefaultHandle; - WGPUAddressMode addressModeU = WGPUAddressMode_Repeat; - WGPUAddressMode addressModeV = WGPUAddressMode_Repeat; - WGPUAddressMode addressModeW = WGPUAddressMode_Repeat; - WGPUFilterMode magFilter = WGPUFilterMode_Linear; - WGPUFilterMode minFilter = WGPUFilterMode_Linear; - WGPUFilterMode mipmapFilter = WGPUFilterMode_Linear; - float lodMinClamp = 0.1f; - float lodMaxClamp = 1000.0f; - WGPUCompareFunction compare = WGPUCompareFunction_Always; - uint16_t maxAnisotropy = 0; + WGPUAddressMode addressModeU = WGPUAddressMode_Repeat; + WGPUAddressMode addressModeV = WGPUAddressMode_Repeat; + WGPUAddressMode addressModeW = WGPUAddressMode_Repeat; + WGPUFilterMode magFilter = WGPUFilterMode_Linear; + WGPUFilterMode minFilter = WGPUFilterMode_Linear; + WGPUFilterMode mipmapFilter = WGPUFilterMode_Linear; + float lodMinClamp = 0.1f; + float lodMaxClamp = 1000.0f; + WGPUCompareFunction compare = WGPUCompareFunction_Always; + uint16_t maxAnisotropy = 0; }; struct CCWGPUBindGroupLayoutObject { - WGPUBindGroupLayout bindGroupLayout = wgpuDefaultHandle; + WGPUBindGroupLayout bindGroupLayout = wgpuDefaultHandle; ccstd::vector bindGroupLayoutEntries; }; struct CCWGPUBindGroupObject { - WGPUBindGroup bindgroup = wgpuDefaultHandle; + WGPUBindGroup bindgroup = wgpuDefaultHandle; ccstd::vector bindGroupEntries; - ccstd::set bindingSet; + ccstd::set bindingSet; }; struct CCWGPUPipelineLayoutObject { @@ -167,18 +167,18 @@ struct CCWGPUPipelineLayoutObject { }; struct CCWGPUPipelineStateObject { - WGPURenderPipeline wgpuRenderPipeline = wgpuDefaultHandle; + WGPURenderPipeline wgpuRenderPipeline = wgpuDefaultHandle; WGPUComputePipeline wgpuComputePipeline = wgpuDefaultHandle; ccstd::vector redundantAttr; - uint32_t maxAttrLength = 0; + uint32_t maxAttrLength = 0; }; struct CCWGPUShaderObject { - ccstd::string name; - WGPUShaderModule wgpuShaderVertexModule = wgpuDefaultHandle; + ccstd::string name; + WGPUShaderModule wgpuShaderVertexModule = wgpuDefaultHandle; WGPUShaderModule wgpuShaderFragmentModule = wgpuDefaultHandle; - WGPUShaderModule wgpuShaderComputeModule = wgpuDefaultHandle; + WGPUShaderModule wgpuShaderComputeModule = wgpuDefaultHandle; }; struct CCWGPUInputAssemblerObject { @@ -187,61 +187,61 @@ struct CCWGPUInputAssemblerObject { struct CCWGPUQueueObject { WGPUQueue wgpuQueue = wgpuDefaultHandle; - QueueType type = QueueType::GRAPHICS; + QueueType type = QueueType::GRAPHICS; }; struct CCWGPUDescriptorSetObject { - uint32_t index = 0; - CCWGPUDescriptorSet *descriptorSet = nullptr; - uint32_t dynamicOffsetCount = 0; - const uint32_t * dynamicOffsets = nullptr; + uint32_t index = 0; + CCWGPUDescriptorSet *descriptorSet = nullptr; + uint32_t dynamicOffsetCount = 0; + const uint32_t *dynamicOffsets = nullptr; }; struct CCWGPUStencilMasks { - uint writeMask = 0; - uint compareRef = 0; + uint writeMask = 0; + uint compareRef = 0; uint compareMask = 0; }; struct CCWGPUStateCache { - CCWGPUPipelineState * pipelineState = nullptr; + CCWGPUPipelineState *pipelineState = nullptr; CCWGPUInputAssembler *inputAssembler = nullptr; float depthBiasConstant = 0.0f; - float depthBiasClamp = 0.0f; - float depthBiasSlope = 0.0f; - float depthMinBound = 0.0f; - float depthMaxBound = 100.0f; + float depthBiasClamp = 0.0f; + float depthBiasSlope = 0.0f; + float depthMinBound = 0.0f; + float depthMaxBound = 100.0f; - Color blendConstants; + Color blendConstants; Viewport viewport; - Rect rect; + Rect rect; - uint32_t minAttachmentWidth = 0; + uint32_t minAttachmentWidth = 0; uint32_t minAttachmentHeight = 0; - ccstd::vector descriptorSets; + ccstd::vector descriptorSets; ccstd::map stencilMasks; }; struct CCWGPUCommandBufferObject { bool renderPassBegan = false; - WGPUCommandEncoder wgpuCommandEncoder = wgpuDefaultHandle; - WGPURenderPassEncoder wgpuRenderPassEncoder = wgpuDefaultHandle; - WGPUComputePassEncoder wgpuComputeEncoder = wgpuDefaultHandle; - CommandBufferType type = CommandBufferType::PRIMARY; - CCWGPUQueue * queue = nullptr; + WGPUCommandEncoder wgpuCommandEncoder = wgpuDefaultHandle; + WGPURenderPassEncoder wgpuRenderPassEncoder = wgpuDefaultHandle; + WGPUComputePassEncoder wgpuComputeEncoder = wgpuDefaultHandle; + CommandBufferType type = CommandBufferType::PRIMARY; + CCWGPUQueue *queue = nullptr; WGPURenderPassDescriptor renderPassDescriptor; - CCWGPUStateCache stateCache; + CCWGPUStateCache stateCache; ccstd::unordered_map redundantVertexBufferMap; }; struct CCWGPUQueryPoolObject { - QueryType type = QueryType::OCCLUSION; - uint32_t maxQueryObjects = 0; + QueryType type = QueryType::OCCLUSION; + uint32_t maxQueryObjects = 0; ccstd::vector idPool; }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp index a3c49f00ec..9727ea1ec5 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineLayout.cpp @@ -61,10 +61,10 @@ void CCWGPUPipelineLayout::prepare(const ccstd::set &setInUse) { } WGPUPipelineLayoutDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, + .nextInChain = nullptr, + .label = nullptr, .bindGroupLayoutCount = layouts.size(), - .bindGroupLayouts = layouts.data(), + .bindGroupLayouts = layouts.data(), }; _gpuPipelineLayoutObj->wgpuPipelineLayout = wgpuDeviceCreatePipelineLayout(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp index 9bfb929ce8..1bf6c6a8eb 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.cpp @@ -49,7 +49,7 @@ void CCWGPUPipelineState::doInit(const PipelineStateInfo &info) { void CCWGPUPipelineState::check(RenderPass *renderPass) { if (_renderPass != renderPass) { - _renderPass = renderPass; + _renderPass = renderPass; _forceUpdate = true; } } @@ -67,44 +67,44 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { return lhs.stream < rhs.stream; }); - auto longestAttr = std::max_element(_inputState.attributes.begin(), _inputState.attributes.end(), [&](const Attribute &lhs, const Attribute &rhs) { + auto longestAttr = std::max_element(_inputState.attributes.begin(), _inputState.attributes.end(), [&](const Attribute &lhs, const Attribute &rhs) { return GFX_FORMAT_INFOS[static_cast(lhs.format)].size < GFX_FORMAT_INFOS[static_cast(rhs.format)].size; }); uint8_t mostToleranceStream = (*longestAttr).stream; const uint8_t streamCount = (*maxStreamAttr).stream + 1; - ccstd::vector vbLayouts(streamCount); + ccstd::vector vbLayouts(streamCount); ccstd::vector> wgpuAttrsVec(streamCount); - const AttributeList &attrs = _shader->getAttributes(); - uint64_t offset[256] = {0}; + const AttributeList &attrs = _shader->getAttributes(); + uint64_t offset[256] = {0}; // ccstd::vector wgpuAttrs; - bool isInstance = attrs.empty() ? false : attrs[0].isInstanced; - uint8_t index = 0; + bool isInstance = attrs.empty() ? false : attrs[0].isInstanced; + uint8_t index = 0; // wgpuAttrsVec[0] ∪ wgpuAttrsVec[1] ∪ ... ∪ wgpuAttrsVec[n] == shader.attrs for (size_t i = 0; i < attrs.size(); i++) { ccstd::string attrName = attrs[i].name; - auto iter = std::find_if(_inputState.attributes.begin(), _inputState.attributes.end(), [attrName](const Attribute &attr) { + auto iter = std::find_if(_inputState.attributes.begin(), _inputState.attributes.end(), [attrName](const Attribute &attr) { return strcmp(attrName.c_str(), attr.name.c_str()) == 0; }); if (iter != _inputState.attributes.end()) { - Format format = (*iter).format; - WGPUVertexAttribute attr = { - .format = toWGPUVertexFormat(format), - .offset = offset[(*iter).stream], + Format format = (*iter).format; + WGPUVertexAttribute attr = { + .format = toWGPUVertexFormat(format), + .offset = offset[(*iter).stream], .shaderLocation = attrs[i].location, }; wgpuAttrsVec[(*iter).stream].push_back(attr); offset[(*iter).stream] += GFX_FORMAT_INFOS[static_cast(format)].size; } else { // all none-input attr are put in 1st buffer layout with offset = 0; - Format format = attrs[i].format; - WGPUVertexAttribute attr = { - .format = toWGPUVertexFormat(format), - .offset = 0, + Format format = attrs[i].format; + WGPUVertexAttribute attr = { + .format = toWGPUVertexFormat(format), + .offset = 0, .shaderLocation = attrs[i].location, }; @@ -123,9 +123,9 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { // input state has attr which shader hasnt. for (size_t i = 0; i < _inputState.attributes.size(); ++i) { - ccstd::string attrName = _inputState.attributes[i].name; - const auto & attribute = _inputState.attributes[i]; - auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { + ccstd::string attrName = _inputState.attributes[i].name; + const auto &attribute = _inputState.attributes[i]; + auto iter = std::find_if(attrs.begin(), attrs.end(), [attrName](const Attribute &attr) { return strcmp(attrName.c_str(), attr.name.c_str()) == 0; }); if (iter == attrs.end()) { @@ -141,10 +141,10 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { for (size_t i = 0; i < wgpuAttrsVec.size(); ++i) { vbLayouts[i] = { - .arrayStride = offset[i], - .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, + .arrayStride = offset[i], + .stepMode = isInstance ? WGPUVertexStepMode_Instance : WGPUVertexStepMode_Vertex, .attributeCount = wgpuAttrsVec[i].size(), - .attributes = wgpuAttrsVec[i].data(), + .attributes = wgpuAttrsVec[i].data(), }; } @@ -157,66 +157,66 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { WGPUVertexState vertexState = { .nextInChain = nullptr, - .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderVertexModule, - .entryPoint = "main", + .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderVertexModule, + .entryPoint = "main", .bufferCount = vbLayouts.size(), - .buffers = vbLayouts.data(), + .buffers = vbLayouts.data(), }; bool stripTopology = (_primitive == PrimitiveMode::LINE_STRIP || _primitive == PrimitiveMode::TRIANGLE_STRIP); WGPUPrimitiveState primitiveState = { - .nextInChain = nullptr, - .topology = toWGPUPrimTopology(_primitive), + .nextInChain = nullptr, + .topology = toWGPUPrimTopology(_primitive), .stripIndexFormat = stripTopology ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Undefined, //TODO_Zeqiang: ??? - .frontFace = _rasterizerState.isFrontFaceCCW ? WGPUFrontFace::WGPUFrontFace_CCW : WGPUFrontFace::WGPUFrontFace_CW, - .cullMode = _rasterizerState.cullMode == CullMode::FRONT ? WGPUCullMode::WGPUCullMode_Front - : _rasterizerState.cullMode == CullMode::BACK ? WGPUCullMode::WGPUCullMode_Back - : WGPUCullMode::WGPUCullMode_None, + .frontFace = _rasterizerState.isFrontFaceCCW ? WGPUFrontFace::WGPUFrontFace_CCW : WGPUFrontFace::WGPUFrontFace_CW, + .cullMode = _rasterizerState.cullMode == CullMode::FRONT ? WGPUCullMode::WGPUCullMode_Front + : _rasterizerState.cullMode == CullMode::BACK ? WGPUCullMode::WGPUCullMode_Back + : WGPUCullMode::WGPUCullMode_None, }; WGPUStencilFaceState stencilFront = { - .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncFront), - .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpFront), + .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncFront), + .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpFront), .depthFailOp = toWGPUStencilOperation(_depthStencilState.stencilZFailOpFront), - .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpFront), + .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpFront), }; WGPUStencilFaceState stencilBack = { - .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncBack), - .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpBack), + .compare = toWGPUCompareFunction(_depthStencilState.stencilFuncBack), + .failOp = toWGPUStencilOperation(_depthStencilState.stencilFailOpBack), .depthFailOp = toWGPUStencilOperation(_depthStencilState.stencilZFailOpBack), - .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpBack), + .passOp = toWGPUStencilOperation(_depthStencilState.stencilPassOpBack), }; WGPUDepthStencilState dsState = { - .nextInChain = nullptr, - .format = toWGPUTextureFormat(dsAttachment.format), - .depthWriteEnabled = _depthStencilState.depthWrite != 0, - .depthCompare = _depthStencilState.depthTest ? toWGPUCompareFunction(_depthStencilState.depthFunc) : WGPUCompareFunction_Undefined, - .stencilFront = stencilFront, - .stencilBack = stencilBack, - .stencilReadMask = _depthStencilState.stencilReadMaskFront, - .stencilWriteMask = _depthStencilState.stencilWriteMaskFront, - .depthBias = static_cast(_rasterizerState.depthBias), + .nextInChain = nullptr, + .format = toWGPUTextureFormat(dsAttachment.format), + .depthWriteEnabled = _depthStencilState.depthWrite != 0, + .depthCompare = _depthStencilState.depthTest ? toWGPUCompareFunction(_depthStencilState.depthFunc) : WGPUCompareFunction_Undefined, + .stencilFront = stencilFront, + .stencilBack = stencilBack, + .stencilReadMask = _depthStencilState.stencilReadMaskFront, + .stencilWriteMask = _depthStencilState.stencilWriteMaskFront, + .depthBias = static_cast(_rasterizerState.depthBias), .depthBiasSlopeScale = _rasterizerState.depthBiasSlop, - .depthBiasClamp = _rasterizerState.depthBiasClamp, + .depthBiasClamp = _rasterizerState.depthBiasClamp, }; WGPUMultisampleState msState = { - .count = static_cast(_renderPass)->gpuRenderPassObject()->sampleCount, - .mask = 0xFFFFFFFF, + .count = static_cast(_renderPass)->gpuRenderPassObject()->sampleCount, + .mask = 0xFFFFFFFF, .alphaToCoverageEnabled = _blendState.isA2C != 0, }; - const ColorAttachmentList & colors = _renderPass->getColorAttachments(); + const ColorAttachmentList &colors = _renderPass->getColorAttachments(); ccstd::vector colorTargetStates(colors.size()); ccstd::vector blendState(colors.size()); for (size_t i = 0, targetIndex = 0; i < colors.size(); i++) { colorTargetStates[i].format = toWGPUTextureFormat(colors[i].format); - blendState[i].color = { + blendState[i].color = { .operation = toWGPUBlendOperation(_blendState.targets[targetIndex].blendEq), .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrc), .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDst), @@ -226,7 +226,7 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { .srcFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendSrcAlpha), .dstFactor = toWGPUBlendFactor(_blendState.targets[targetIndex].blendDstAlpha), }; - colorTargetStates[i].blend = &blendState[i]; + colorTargetStates[i].blend = &blendState[i]; colorTargetStates[i].writeMask = toWGPUColorWriteMask(_blendState.targets[targetIndex].blendColorMask); if (targetIndex < _blendState.targets.size() - 1) { ++targetIndex; @@ -234,10 +234,10 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { } WGPUFragmentState fragmentState = { - .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderFragmentModule, - .entryPoint = "main", + .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderFragmentModule, + .entryPoint = "main", .targetCount = colorTargetStates.size(), - .targets = colorTargetStates.data(), + .targets = colorTargetStates.data(), }; pipelineLayout->prepare(setInUse); @@ -251,28 +251,28 @@ void CCWGPUPipelineState::prepare(const ccstd::set &setInUse) { // } WGPURenderPipelineDescriptor piplineDesc = { - .nextInChain = nullptr, - .label = nullptr, - .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, - .vertex = vertexState, - .primitive = primitiveState, + .nextInChain = nullptr, + .label = nullptr, + .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, + .vertex = vertexState, + .primitive = primitiveState, .depthStencil = dsState.format == WGPUTextureFormat_Undefined ? nullptr : &dsState, - .multisample = msState, - .fragment = &fragmentState, + .multisample = msState, + .fragment = &fragmentState, }; _gpuPipelineStateObj->wgpuRenderPipeline = wgpuDeviceCreateRenderPipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); - _ppl = pipelineLayout; - _forceUpdate = false; + _ppl = pipelineLayout; + _forceUpdate = false; } else if (_bindPoint == PipelineBindPoint::COMPUTE) { if (_gpuPipelineStateObj->wgpuComputePipeline) return; WGPUProgrammableStageDescriptor psDesc = { - .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderComputeModule, + .module = static_cast(_shader)->gpuShaderObject()->wgpuShaderComputeModule, .entryPoint = "main", }; pipelineLayout->prepare(setInUse); WGPUComputePipelineDescriptor piplineDesc = { - .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, + .layout = pipelineLayout->gpuPipelineLayoutObject()->wgpuPipelineLayout, .compute = psDesc, }; _gpuPipelineStateObj->wgpuComputePipeline = wgpuDeviceCreateComputePipeline(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &piplineDesc); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h index 87903dfa66..6fca6fcc2b 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUPipelineState.h @@ -52,8 +52,8 @@ protected: CCWGPUPipelineStateObject *_gpuPipelineStateObj = nullptr; - void *_ppl = nullptr; - bool _forceUpdate = false; + void *_ppl = nullptr; + bool _forceUpdate = false; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp index 79aef6a70c..f154de7953 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.cpp @@ -40,9 +40,9 @@ CCWGPUQueryPool::~CCWGPUQueryPool() { } void CCWGPUQueryPool::doInit(const QueryPoolInfo & /*info*/) { - CCWGPUDevice *device = CCWGPUDevice::getInstance(); - _gpuQueryPool = ccnew CCWGPUQueryPoolObject; - _gpuQueryPool->type = _type; + CCWGPUDevice *device = CCWGPUDevice::getInstance(); + _gpuQueryPool = ccnew CCWGPUQueryPoolObject; + _gpuQueryPool->type = _type; _gpuQueryPool->maxQueryObjects = _maxQueryObjects; _gpuQueryPool->idPool.resize(_maxQueryObjects, 0U); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.h b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.h index 23be96407e..f881a8ca17 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueryPool.h @@ -39,18 +39,18 @@ public: ~CCWGPUQueryPool() override; inline CCWGPUQueryPoolObject *gpuQueryPool() const { return _gpuQueryPool; } - inline uint32_t getIdCount() const { return static_cast(_ids.size()); } - inline void clearId() { _ids.clear(); } - inline void addId(uint32_t id) { _ids.push_back(id); } - inline uint32_t getId(uint32_t index) const { return _ids[index]; } - inline std::mutex & getMutex() { return _mutex; } - inline void setResults(ccstd::unordered_map &&results) { _results = results; } + inline uint32_t getIdCount() const { return static_cast(_ids.size()); } + inline void clearId() { _ids.clear(); } + inline void addId(uint32_t id) { _ids.push_back(id); } + inline uint32_t getId(uint32_t index) const { return _ids[index]; } + inline std::mutex &getMutex() { return _mutex; } + inline void setResults(ccstd::unordered_map &&results) { _results = results; } protected: void doInit(const QueryPoolInfo &info) override; void doDestroy() override; - CCWGPUQueryPoolObject * _gpuQueryPool = nullptr; + CCWGPUQueryPoolObject *_gpuQueryPool = nullptr; ccstd::vector _ids; }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp index e506e6fa46..a25fbdb53a 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp @@ -39,8 +39,8 @@ CCWGPUQueue::CCWGPUQueue() : wrapper(val::object()) { } void CCWGPUQueue::doInit(const QueueInfo &info) { - _gpuQueueObject = ccnew CCWGPUQueueObject; - _gpuQueueObject->type = info.type; + _gpuQueueObject = ccnew CCWGPUQueueObject; + _gpuQueueObject->type = info.type; _gpuQueueObject->wgpuQueue = wgpuDeviceGetQueue(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp index 3d35a8d5e1..e3d1442357 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.cpp @@ -39,8 +39,8 @@ public: explicit CCWGPURenderPassHelper(const RenderPassInfo &info) { SampleCount samples = SampleCount::ONE; for (size_t i = 0; i < info.colorAttachments.size(); i++) { - colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); - colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); + colors[i].loadOp = toWGPULoadOp(info.colorAttachments[i].loadOp); + colors[i].storeOp = toWGPUStoreOp(info.colorAttachments[i].storeOp); colors[i].clearColor = defaultClearColor; // TODO_Zeqaing : subpass if (info.colorAttachments[i].sampleCount != SampleCount::ONE) @@ -48,12 +48,12 @@ public: } // now 1 depth stencil only - depthStencils[0].depthLoadOp = toWGPULoadOp(info.depthStencilAttachment.depthLoadOp); - depthStencils[0].depthStoreOp = toWGPUStoreOp(info.depthStencilAttachment.depthStoreOp); - depthStencils[0].stencilLoadOp = toWGPULoadOp(info.depthStencilAttachment.stencilLoadOp); - depthStencils[0].stencilStoreOp = toWGPUStoreOp(info.depthStencilAttachment.stencilStoreOp); - depthStencils[0].clearDepth = defaultClearDepth; - depthStencils[0].depthReadOnly = false; + depthStencils[0].depthLoadOp = toWGPULoadOp(info.depthStencilAttachment.depthLoadOp); + depthStencils[0].depthStoreOp = toWGPUStoreOp(info.depthStencilAttachment.depthStoreOp); + depthStencils[0].stencilLoadOp = toWGPULoadOp(info.depthStencilAttachment.stencilLoadOp); + depthStencils[0].stencilStoreOp = toWGPUStoreOp(info.depthStencilAttachment.stencilStoreOp); + depthStencils[0].clearDepth = defaultClearDepth; + depthStencils[0].depthReadOnly = false; depthStencils[0].stencilReadOnly = false; if (samples == SampleCount::ONE) samples = info.depthStencilAttachment.sampleCount; @@ -61,8 +61,8 @@ public: renderPassDesc = ccnew WGPURenderPassDescriptor; //TODO_Zeqiang: Metal-like subpass - renderPassDesc->colorAttachmentCount = info.colorAttachments.size(); - renderPassDesc->colorAttachments = colors.data(); + renderPassDesc->colorAttachmentCount = info.colorAttachments.size(); + renderPassDesc->colorAttachments = colors.data(); renderPassDesc->depthStencilAttachment = depthStencils.data(); sampleCount = toWGPUSampleCount(samples); @@ -75,20 +75,20 @@ public: } } - ccstd::array colors; + ccstd::array colors; ccstd::array depthStencils; - WGPURenderPassDescriptor * renderPassDesc = nullptr; - int sampleCount = 1; + WGPURenderPassDescriptor *renderPassDesc = nullptr; + int sampleCount = 1; }; CCWGPURenderPass::CCWGPURenderPass() : wrapper(val::object()) { } void CCWGPURenderPass::doInit(const RenderPassInfo &info) { - _renderPassObject = ccnew CCWGPURenderPassObject(); - _rpHelper = ccnew CCWGPURenderPassHelper(info); + _renderPassObject = ccnew CCWGPURenderPassObject(); + _rpHelper = ccnew CCWGPURenderPassHelper(info); _renderPassObject->wgpuRenderPassDesc = _rpHelper->renderPassDesc; - _renderPassObject->sampleCount = _rpHelper->sampleCount; + _renderPassObject->sampleCount = _rpHelper->sampleCount; } void CCWGPURenderPass::doDestroy() { diff --git a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h index fb35d6a673..1f86efeee6 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h +++ b/native/cocos/renderer/gfx-wgpu/WGPURenderPass.h @@ -47,7 +47,7 @@ protected: void doDestroy() override; CCWGPURenderPassObject *_renderPassObject = nullptr; - CCWGPURenderPassHelper *_rpHelper = nullptr; + CCWGPURenderPassHelper *_rpHelper = nullptr; }; inline CCWGPURenderPass *getThis(CCWGPURenderPass *that) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp index 46cba58cbf..8ef8d292e7 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSampler.cpp @@ -40,17 +40,17 @@ using namespace emscripten; CCWGPUSampler::CCWGPUSampler(const SamplerInfo &info) : wrapper(val::object(), info) { WGPUSamplerDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .addressModeU = toWGPUAddressMode(info.addressU), - .addressModeV = toWGPUAddressMode(info.addressV), - .addressModeW = toWGPUAddressMode(info.addressW), - .magFilter = toWGPUFilterMode(info.magFilter), - .minFilter = toWGPUFilterMode(info.minFilter), - .mipmapFilter = toWGPUFilterMode(info.mipFilter), - .lodMinClamp = 0.0f, - .lodMaxClamp = std::numeric_limits::max(), - .compare = WGPUCompareFunction_Undefined, //toWGPUCompareFunction(info.cmpFunc), + .nextInChain = nullptr, + .label = nullptr, + .addressModeU = toWGPUAddressMode(info.addressU), + .addressModeV = toWGPUAddressMode(info.addressV), + .addressModeW = toWGPUAddressMode(info.addressW), + .magFilter = toWGPUFilterMode(info.magFilter), + .minFilter = toWGPUFilterMode(info.minFilter), + .mipmapFilter = toWGPUFilterMode(info.mipFilter), + .lodMinClamp = 0.0f, + .lodMaxClamp = std::numeric_limits::max(), + .compare = WGPUCompareFunction_Undefined, //toWGPUCompareFunction(info.cmpFunc), .maxAnisotropy = static_cast(info.maxAnisotropy), }; @@ -65,14 +65,14 @@ CCWGPUSampler::~CCWGPUSampler() { CCWGPUSampler *CCWGPUSampler::defaultSampler() { if (!anoymous::defaultSampler) { SamplerInfo info = { - .minFilter = Filter::LINEAR, - .magFilter = Filter::LINEAR, - .mipFilter = Filter::NONE, - .addressU = Address::WRAP, - .addressV = Address::WRAP, - .addressW = Address::WRAP, + .minFilter = Filter::LINEAR, + .magFilter = Filter::LINEAR, + .mipFilter = Filter::NONE, + .addressU = Address::WRAP, + .addressV = Address::WRAP, + .addressW = Address::WRAP, .maxAnisotropy = 0, - .cmpFunc = ComparisonFunc::ALWAYS, + .cmpFunc = ComparisonFunc::ALWAYS, }; anoymous::defaultSampler = ccnew CCWGPUSampler(info); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp index 884aa4fa43..18291820c9 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp @@ -38,33 +38,33 @@ CCWGPUShader::CCWGPUShader() : wrapper(val::object()) { } void CCWGPUShader::initialize(const SPVShaderInfoInstance &spvInfo) { - _gpuShaderObject = ccnew CCWGPUShaderObject; + _gpuShaderObject = ccnew CCWGPUShaderObject; const ShaderInfo &info = spvInfo.info; - _name = info.name; - _stages = info.stages; - _attributes = info.attributes; - _blocks = info.blocks; - _buffers = info.buffers; + _name = info.name; + _stages = info.stages; + _attributes = info.attributes; + _blocks = info.blocks; + _buffers = info.buffers; _samplerTextures = info.samplerTextures; - _samplers = info.samplers; - _textures = info.textures; - _images = info.images; - _subpassInputs = info.subpassInputs; + _samplers = info.samplers; + _textures = info.textures; + _images = info.images; + _subpassInputs = info.subpassInputs; _gpuShaderObject->name = info.name; for (size_t i = 0; i < spvInfo.stages.size(); i++) { - const auto &stage = spvInfo.stages[i]; - auto * spvData = spvInfo.stages[i].spv.data(); - size_t size = spvInfo.stages[i].spv.size(); + const auto &stage = spvInfo.stages[i]; + auto *spvData = spvInfo.stages[i].spv.data(); + size_t size = spvInfo.stages[i].spv.size(); WGPUShaderModuleSPIRVDescriptor spv = {}; - spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; - spv.codeSize = size; - spv.code = spvData; - WGPUShaderModuleDescriptor desc = {}; - desc.nextInChain = reinterpret_cast(&spv); - desc.label = nullptr; + spv.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; + spv.codeSize = size; + spv.code = spvData; + WGPUShaderModuleDescriptor desc = {}; + desc.nextInChain = reinterpret_cast(&spv); + desc.label = nullptr; if (stage.stage == ShaderStageFlagBit::VERTEX) { _gpuShaderObject->wgpuShaderVertexModule = wgpuDeviceCreateShaderModule(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &desc); } else if (stage.stage == ShaderStageFlagBit::FRAGMENT) { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp index 9760665dd2..5fba3a178c 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.cpp @@ -41,12 +41,12 @@ CCWGPUSwapchain::~CCWGPUSwapchain() { void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { WGPUSurfaceDescriptorFromCanvasHTMLSelector canvDesc = {}; - canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; - canvDesc.selector = "canvas"; + canvDesc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector; + canvDesc.selector = "canvas"; WGPUSurfaceDescriptor surfDesc = {}; - surfDesc.nextInChain = reinterpret_cast(&canvDesc); - WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); + surfDesc.nextInChain = reinterpret_cast(&canvDesc); + WGPUSurface surface = wgpuInstanceCreateSurface(nullptr, &surfDesc); WGPUPresentMode presentMode; switch (info.vsyncMode) { @@ -69,32 +69,32 @@ void CCWGPUSwapchain::doInit(const SwapchainInfo &info) { presentMode = WGPUPresentMode_Fifo; } - auto * device = CCWGPUDevice::getInstance(); + auto *device = CCWGPUDevice::getInstance(); WGPUSwapChainDescriptor swapChainDesc; swapChainDesc.nextInChain = nullptr; - swapChainDesc.label = "defaultSwapChain"; - swapChainDesc.usage = WGPUTextureUsage_RenderAttachment; - swapChainDesc.format = WGPUTextureFormat_BGRA8Unorm; - swapChainDesc.width = info.width; - swapChainDesc.height = info.height; + swapChainDesc.label = "defaultSwapChain"; + swapChainDesc.usage = WGPUTextureUsage_RenderAttachment; + swapChainDesc.format = WGPUTextureFormat_BGRA8Unorm; + swapChainDesc.width = info.width; + swapChainDesc.height = info.height; swapChainDesc.presentMode = presentMode; CCWGPUDeviceObject *gpuDeviceObj = device->gpuDeviceObject(); - WGPUSwapChain swapChain = wgpuDeviceCreateSwapChain(gpuDeviceObj->wgpuDevice, surface, &swapChainDesc); - _gpuSwapchainObj = ccnew CCWGPUSwapchainObject; - _gpuSwapchainObj->wgpuSwapChain = swapChain; - _gpuSwapchainObj->wgpuSurface = surface; + WGPUSwapChain swapChain = wgpuDeviceCreateSwapChain(gpuDeviceObj->wgpuDevice, surface, &swapChainDesc); + _gpuSwapchainObj = ccnew CCWGPUSwapchainObject; + _gpuSwapchainObj->wgpuSwapChain = swapChain; + _gpuSwapchainObj->wgpuSurface = surface; SwapchainTextureInfo textureInfo = { .swapchain = this, - .format = Format::BGRA8, - .width = info.width, - .height = info.height, + .format = Format::BGRA8, + .width = info.width, + .height = info.height, }; _colorTexture = _gpuSwapchainObj->swapchainColor = ccnew CCWGPUTexture; initTexture(textureInfo, _gpuSwapchainObj->swapchainColor); - textureInfo.format = Format::DEPTH_STENCIL; + textureInfo.format = Format::DEPTH_STENCIL; _depthStencilTexture = _gpuSwapchainObj->swapchainDepthStencil = ccnew CCWGPUTexture; initTexture(textureInfo, _gpuSwapchainObj->swapchainDepthStencil); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h index 8945583aa8..2d78812b9e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUSwapchain.h @@ -58,7 +58,7 @@ protected: void doCreateSurface(void *windowHandle) override; CCWGPUSwapchainObject *_gpuSwapchainObj = nullptr; - CCWGPUDevice * _device = nullptr; + CCWGPUDevice *_device = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp index e05d8564f0..fadbbd29f9 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.cpp @@ -34,7 +34,7 @@ namespace cc { namespace gfx { namespace anoymous { -CCWGPUTexture *defaultCommonTexture = nullptr; +CCWGPUTexture *defaultCommonTexture = nullptr; CCWGPUTexture *defaultStorageTexture = nullptr; } // namespace anoymous @@ -50,28 +50,28 @@ void CCWGPUTexture::doInit(const TextureInfo &info) { depthOrArrayLayers = 6; } WGPUTextureDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = toWGPUTextureUsage(info.usage), - .dimension = toWGPUTextureDimension(info.type), - .size = {info.width, info.height, depthOrArrayLayers}, - .format = toWGPUTextureFormat(info.format), + .nextInChain = nullptr, + .label = nullptr, + .usage = toWGPUTextureUsage(info.usage), + .dimension = toWGPUTextureDimension(info.type), + .size = {info.width, info.height, depthOrArrayLayers}, + .format = toWGPUTextureFormat(info.format), .mipLevelCount = info.levelCount, - .sampleCount = toWGPUSampleCount(info.samples), + .sampleCount = toWGPUSampleCount(info.samples), }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); WGPUTextureViewDescriptor texViewDesc = { - .nextInChain = nullptr, - .label = nullptr, - .format = descriptor.format, - .dimension = toWGPUTextureViewDimension(info.type), - .baseMipLevel = 0, - .mipLevelCount = _info.levelCount, - .baseArrayLayer = 0, + .nextInChain = nullptr, + .label = nullptr, + .format = descriptor.format, + .dimension = toWGPUTextureViewDimension(info.type), + .baseMipLevel = 0, + .mipLevelCount = _info.levelCount, + .baseArrayLayer = 0, .arrayLayerCount = _info.layerCount, - .aspect = WGPUTextureAspect_All, + .aspect = WGPUTextureAspect_All, }; _gpuTextureObj->selfView = wgpuTextureCreateView(_gpuTextureObj->wgpuTexture, &texViewDesc); @@ -80,21 +80,21 @@ void CCWGPUTexture::doInit(const TextureInfo &info) { void CCWGPUTexture::doInit(const TextureViewInfo &info) { WGPUTextureViewDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .format = toWGPUTextureFormat(info.format), - .dimension = toWGPUTextureViewDimension(info.type), - .baseMipLevel = info.baseLevel, - .mipLevelCount = info.levelCount, - .baseArrayLayer = info.baseLayer, + .nextInChain = nullptr, + .label = nullptr, + .format = toWGPUTextureFormat(info.format), + .dimension = toWGPUTextureViewDimension(info.type), + .baseMipLevel = info.baseLevel, + .mipLevelCount = info.levelCount, + .baseArrayLayer = info.baseLayer, .arrayLayerCount = info.layerCount, - .aspect = textureAspectTrait(info.format), + .aspect = textureAspectTrait(info.format), }; - auto * ccTexture = static_cast(info.texture); - WGPUTexture wgpuTexture = ccTexture->gpuTextureObject()->wgpuTexture; + auto *ccTexture = static_cast(info.texture); + WGPUTexture wgpuTexture = ccTexture->gpuTextureObject()->wgpuTexture; _gpuTextureObj->selfView = _gpuTextureObj->wgpuTextureView = wgpuTextureCreateView(wgpuTexture, &descriptor); - _internalChanged = true; + _internalChanged = true; } void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { @@ -102,28 +102,28 @@ void CCWGPUTexture::doInit(const SwapchainTextureInfo &info) { auto *swapchain = static_cast(_swapchain); if (info.format == Format::DEPTH || info.format == Format::DEPTH_STENCIL) { WGPUTextureDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = WGPUTextureUsage_RenderAttachment, - .dimension = WGPUTextureDimension_2D, - .size = {info.width, info.height, 1}, - .format = toWGPUTextureFormat(info.format), + .nextInChain = nullptr, + .label = nullptr, + .usage = WGPUTextureUsage_RenderAttachment, + .dimension = WGPUTextureDimension_2D, + .size = {info.width, info.height, 1}, + .format = toWGPUTextureFormat(info.format), .mipLevelCount = 1, - .sampleCount = 1, + .sampleCount = 1, }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); - WGPUTextureAspect aspect = info.format == Format::DEPTH ? WGPUTextureAspect_DepthOnly : WGPUTextureAspect_All; + WGPUTextureAspect aspect = info.format == Format::DEPTH ? WGPUTextureAspect_DepthOnly : WGPUTextureAspect_All; WGPUTextureViewDescriptor texViewDesc = { - .nextInChain = nullptr, - .label = nullptr, - .format = descriptor.format, - .dimension = WGPUTextureViewDimension_2D, - .baseMipLevel = 0, - .mipLevelCount = 1, - .baseArrayLayer = 0, + .nextInChain = nullptr, + .label = nullptr, + .format = descriptor.format, + .dimension = WGPUTextureViewDimension_2D, + .baseMipLevel = 0, + .mipLevelCount = 1, + .baseArrayLayer = 0, .arrayLayerCount = 1, - .aspect = aspect, + .aspect = aspect, }; _gpuTextureObj->selfView = wgpuTextureCreateView(_gpuTextureObj->wgpuTexture, &texViewDesc); } else { @@ -172,27 +172,27 @@ void CCWGPUTexture::doResize(uint32_t width, uint32_t height, uint32_t size) { depthOrArrayLayers = 6; } WGPUTextureDescriptor descriptor = { - .nextInChain = nullptr, - .label = nullptr, - .usage = toWGPUTextureUsage(_info.usage), - .dimension = toWGPUTextureDimension(_info.type), - .size = {_info.width, _info.height, depthOrArrayLayers}, - .format = toWGPUTextureFormat(_info.format), + .nextInChain = nullptr, + .label = nullptr, + .usage = toWGPUTextureUsage(_info.usage), + .dimension = toWGPUTextureDimension(_info.type), + .size = {_info.width, _info.height, depthOrArrayLayers}, + .format = toWGPUTextureFormat(_info.format), .mipLevelCount = _info.levelCount, - .sampleCount = toWGPUSampleCount(_info.samples), + .sampleCount = toWGPUSampleCount(_info.samples), }; _gpuTextureObj->wgpuTexture = wgpuDeviceCreateTexture(CCWGPUDevice::getInstance()->gpuDeviceObject()->wgpuDevice, &descriptor); WGPUTextureViewDescriptor texViewDesc = { - .nextInChain = nullptr, - .label = nullptr, - .format = descriptor.format, - .dimension = toWGPUTextureViewDimension(_info.type), - .baseMipLevel = 0, - .mipLevelCount = _info.levelCount, - .baseArrayLayer = 0, + .nextInChain = nullptr, + .label = nullptr, + .format = descriptor.format, + .dimension = toWGPUTextureViewDimension(_info.type), + .baseMipLevel = 0, + .mipLevelCount = _info.levelCount, + .baseArrayLayer = 0, .arrayLayerCount = _info.layerCount, - .aspect = WGPUTextureAspect_All, + .aspect = WGPUTextureAspect_All, }; _gpuTextureObj->selfView = wgpuTextureCreateView(_gpuTextureObj->wgpuTexture, &texViewDesc); @@ -206,16 +206,16 @@ void CCWGPUTexture::stamp() { CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { if (!anoymous::defaultCommonTexture) { TextureInfo info = { - .type = TextureType::TEX2D, - .usage = TextureUsageBit::SAMPLED, - .format = Format::RGBA8, - .width = 2, - .height = 2, - .flags = TextureFlagBit::NONE, - .layerCount = 1, - .levelCount = 1, - .samples = SampleCount::ONE, - .depth = 1, + .type = TextureType::TEX2D, + .usage = TextureUsageBit::SAMPLED, + .format = Format::RGBA8, + .width = 2, + .height = 2, + .flags = TextureFlagBit::NONE, + .layerCount = 1, + .levelCount = 1, + .samples = SampleCount::ONE, + .depth = 1, .externalRes = nullptr, }; anoymous::defaultCommonTexture = ccnew CCWGPUTexture; @@ -228,16 +228,16 @@ CCWGPUTexture *CCWGPUTexture::defaultCommonTexture() { CCWGPUTexture *CCWGPUTexture::defaultStorageTexture() { if (!anoymous::defaultStorageTexture) { TextureInfo info = { - .type = TextureType::TEX2D, - .usage = TextureUsageBit::STORAGE, - .format = Format::RGBA8, - .width = 2, - .height = 2, - .flags = TextureFlagBit::NONE, - .layerCount = 1, - .levelCount = 1, - .samples = SampleCount::ONE, - .depth = 1, + .type = TextureType::TEX2D, + .usage = TextureUsageBit::STORAGE, + .format = Format::RGBA8, + .width = 2, + .height = 2, + .flags = TextureFlagBit::NONE, + .layerCount = 1, + .levelCount = 1, + .samples = SampleCount::ONE, + .depth = 1, .externalRes = nullptr, }; anoymous::defaultStorageTexture = ccnew CCWGPUTexture; diff --git a/native/cocos/renderer/pipeline/BatchedBuffer.cpp b/native/cocos/renderer/pipeline/BatchedBuffer.cpp index 214863156a..994392cd64 100644 --- a/native/cocos/renderer/pipeline/BatchedBuffer.cpp +++ b/native/cocos/renderer/pipeline/BatchedBuffer.cpp @@ -35,7 +35,7 @@ namespace cc { namespace pipeline { ccstd::unordered_map> BatchedBuffer::buffers; -BatchedBuffer * BatchedBuffer::get(scene::Pass *pass) { +BatchedBuffer *BatchedBuffer::get(scene::Pass *pass) { return BatchedBuffer::get(pass, 0); } BatchedBuffer *BatchedBuffer::get(scene::Pass *pass, uint extraKey) { @@ -85,21 +85,21 @@ void BatchedBuffer::destroy() { } void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const scene::Model *model) { - const auto *subMesh = subModel->getSubMesh(); - const auto &flatBuffers = subMesh->getFlatBuffers(); - auto flatBuffersCount = static_cast(flatBuffers.size()); + const auto *subMesh = subModel->getSubMesh(); + const auto &flatBuffers = subMesh->getFlatBuffers(); + auto flatBuffersCount = static_cast(flatBuffers.size()); if (0 == flatBuffersCount) { return; } - const auto & flatBuffer = flatBuffers[0]; - uint vbSize = 0; - uint indexSize = 0; - const auto vbCount = flatBuffer.count; - const auto *const pass = subModel->getPass(passIdx); - auto *const shader = subModel->getShader(passIdx); - auto *const descriptorSet = subModel->getDescriptorSet(); - bool isBatchExist = false; + const auto &flatBuffer = flatBuffers[0]; + uint vbSize = 0; + uint indexSize = 0; + const auto vbCount = flatBuffer.count; + const auto *const pass = subModel->getPass(passIdx); + auto *const shader = subModel->getShader(passIdx); + auto *const descriptorSet = subModel->getDescriptorSet(); + bool isBatchExist = false; for (auto &batch : _batches) { if (batch.vbs.size() == flatBuffersCount && batch.mergeCount < UBOLocalBatched::BATCHING_COUNT) { @@ -114,18 +114,18 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s if (isBatchExist) { for (uint j = 0; j < flatBuffersCount; ++j) { - const auto &flatBuffer = flatBuffers[j]; - auto * batchVB = batch.vbs[j]; - auto * vbData = batch.vbDatas[j]; - const uint vbBufSizeOld = batchVB->getSize(); - vbSize = (vbCount + batch.vbCount) * flatBuffer.stride; + const auto &flatBuffer = flatBuffers[j]; + auto *batchVB = batch.vbs[j]; + auto *vbData = batch.vbDatas[j]; + const uint vbBufSizeOld = batchVB->getSize(); + vbSize = (vbCount + batch.vbCount) * flatBuffer.stride; if (vbSize > vbBufSizeOld) { auto *vbDataNew = static_cast(CC_MALLOC(vbSize)); memcpy(vbDataNew, vbData, vbBufSizeOld); batchVB->resize(vbSize); CC_FREE(vbData); batch.vbDatas[j] = vbDataNew; - vbData = vbDataNew; + vbData = vbDataNew; } auto offset = batch.vbCount * flatBuffer.stride; @@ -133,18 +133,18 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s } auto *indexData = batch.indexData; - indexSize = (vbCount + batch.vbCount) * sizeof(float); + indexSize = (vbCount + batch.vbCount) * sizeof(float); if (indexSize > batch.indexBuffer->getSize()) { auto *newIndexData = static_cast(CC_MALLOC(indexSize)); memcpy(newIndexData, indexData, batch.indexBuffer->getSize()); CC_FREE(indexData); batch.indexData = newIndexData; - indexData = batch.indexData; + indexData = batch.indexData; batch.indexBuffer->resize(indexSize); } - const auto start = batch.vbCount; - const auto end = start + vbCount; + const auto start = batch.vbCount; + const auto end = start + vbCount; const auto mergeCount = batch.mergeCount; if (indexData[start] != static_cast(mergeCount) || indexData[end - 1] != static_cast(mergeCount)) { for (auto j = start; j < end; j++) { @@ -153,15 +153,15 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s } // update world matrix - const auto offset = UBOLocalBatched::MAT_WORLDS_OFFSET + batch.mergeCount * 16; + const auto offset = UBOLocalBatched::MAT_WORLDS_OFFSET + batch.mergeCount * 16; const auto &worldMatrix = model->getTransform()->getWorldMatrix(); memcpy(batch.uboData.data() + offset, worldMatrix.m, sizeof(worldMatrix)); if (!batch.mergeCount) { descriptorSet->bindBuffer(UBOLocalBatched::BINDING, batch.ubo); descriptorSet->update(); - batch.pass = pass; - batch.shader = shader; + batch.pass = pass; + batch.shader = shader; batch.descriptorSet = descriptorSet; } @@ -176,40 +176,40 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s // Create a new batch ccstd::vector vbs(flatBuffersCount, nullptr); - ccstd::vector vbDatas(flatBuffersCount, nullptr); + ccstd::vector vbDatas(flatBuffersCount, nullptr); ccstd::vector totalVBs(flatBuffersCount + 1, nullptr); for (uint i = 0; i < flatBuffersCount; ++i) { const auto &flatBuffer = flatBuffers[i]; - auto * newVB = _device->createBuffer({ + auto *newVB = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, flatBuffer.count * flatBuffer.stride, flatBuffer.stride, }); - auto size = 0U; + auto size = 0U; newVB->update(flatBuffer.buffer.buffer()->getData(), flatBuffer.buffer.buffer()->byteLength()); - vbs[i] = newVB; + vbs[i] = newVB; vbDatas[i] = static_cast(CC_MALLOC(newVB->getSize())); memset(vbDatas[i], 0, newVB->getSize()); totalVBs[i] = newVB; } const auto indexBufferSize = vbCount * sizeof(float); - auto * indexBuffer = _device->createBuffer({ + auto *indexBuffer = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, static_cast(indexBufferSize), sizeof(float), }); - auto * indexData = static_cast(CC_MALLOC(indexBufferSize)); + auto *indexData = static_cast(CC_MALLOC(indexBufferSize)); memset(indexData, 0, indexBufferSize); indexBuffer->update(indexData, static_cast(indexBufferSize)); totalVBs[flatBuffersCount] = indexBuffer; ccstd::vector attributes = subModel->getInputAssembler()->getAttributes(); - gfx::Attribute attrib = { + gfx::Attribute attrib = { "a_dyn_batch_id", gfx::Format::R32F, false, @@ -230,7 +230,7 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s descriptorSet->update(); ccstd::array uboData; - const auto & worldMatrix = model->getTransform()->getWorldMatrix(); + const auto &worldMatrix = model->getTransform()->getWorldMatrix(); memcpy(uboData.data() + UBOLocalBatched::MAT_WORLDS_OFFSET, worldMatrix.m, sizeof(worldMatrix)); BatchedItem item = { std::move(vbs), //vbs @@ -251,7 +251,7 @@ void BatchedBuffer::merge(const scene::SubModel *subModel, uint passIdx, const s void BatchedBuffer::clear() { for (auto &batch : _batches) { - batch.vbCount = 0; + batch.vbCount = 0; batch.mergeCount = 0; batch.ia->setVertexCount(0); } diff --git a/native/cocos/renderer/pipeline/BatchedBuffer.h b/native/cocos/renderer/pipeline/BatchedBuffer.h index 373f26f0eb..6ff38df8a8 100644 --- a/native/cocos/renderer/pipeline/BatchedBuffer.h +++ b/native/cocos/renderer/pipeline/BatchedBuffer.h @@ -39,27 +39,27 @@ class SubModel; namespace pipeline { struct CC_DLL BatchedItem { - gfx::BufferList vbs; - ccstd::vector vbDatas; - gfx::Buffer * indexBuffer = nullptr; - float * indexData = nullptr; - uint vbCount = 0; - uint mergeCount = 0; - gfx::InputAssembler * ia = nullptr; - gfx::Buffer * ubo = nullptr; + gfx::BufferList vbs; + ccstd::vector vbDatas; + gfx::Buffer *indexBuffer = nullptr; + float *indexData = nullptr; + uint vbCount = 0; + uint mergeCount = 0; + gfx::InputAssembler *ia = nullptr; + gfx::Buffer *ubo = nullptr; ccstd::array uboData; - gfx::DescriptorSet * descriptorSet = nullptr; - const scene::Pass * pass = nullptr; - gfx::Shader * shader = nullptr; + gfx::DescriptorSet *descriptorSet = nullptr; + const scene::Pass *pass = nullptr; + gfx::Shader *shader = nullptr; }; -using BatchedItemList = ccstd::vector; +using BatchedItemList = ccstd::vector; using DynamicOffsetList = ccstd::vector; class CC_DLL BatchedBuffer : public RefCounted { public: static BatchedBuffer *get(scene::Pass *pass); static BatchedBuffer *get(scene::Pass *pass, uint extraKey); - static void destroyBatchedBuffer(); + static void destroyBatchedBuffer(); explicit BatchedBuffer(const scene::Pass *pass); ~BatchedBuffer() override; @@ -69,16 +69,16 @@ public: void clear(); void setDynamicOffset(uint idx, uint value); - inline const BatchedItemList & getBatches() const { return _batches; } - inline const scene::Pass * getPass() const { return _pass; } + inline const BatchedItemList &getBatches() const { return _batches; } + inline const scene::Pass *getPass() const { return _pass; } inline const DynamicOffsetList &getDynamicOffset() const { return _dynamicOffsets; } private: static ccstd::unordered_map> buffers; - DynamicOffsetList _dynamicOffsets; - BatchedItemList _batches; - const scene::Pass * _pass = nullptr; - gfx::Device * _device = nullptr; + DynamicOffsetList _dynamicOffsets; + BatchedItemList _batches; + const scene::Pass *_pass = nullptr; + gfx::Device *_device = nullptr; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/ClusterLightCulling.cpp b/native/cocos/renderer/pipeline/ClusterLightCulling.cpp index 21d13e01c0..012be5e137 100644 --- a/native/cocos/renderer/pipeline/ClusterLightCulling.cpp +++ b/native/cocos/renderer/pipeline/ClusterLightCulling.cpp @@ -39,13 +39,13 @@ namespace cc { namespace pipeline { -framegraph::StringHandle fgStrHandleClusterBuffer = framegraph::FrameGraph::stringToHandle("clusterBuffer"); +framegraph::StringHandle fgStrHandleClusterBuffer = framegraph::FrameGraph::stringToHandle("clusterBuffer"); framegraph::StringHandle fgStrHandleClusterGlobalIndexBuffer = framegraph::FrameGraph::stringToHandle("globalIndexBuffer"); -framegraph::StringHandle fgStrHandleClusterLightBuffer = framegraph::FrameGraph::stringToHandle("clusterLightBuffer"); -framegraph::StringHandle fgStrHandleClusterLightIndexBuffer = framegraph::FrameGraph::stringToHandle("lightIndexBuffer"); -framegraph::StringHandle fgStrHandleClusterLightGridBuffer = framegraph::FrameGraph::stringToHandle("lightGridBuffer"); +framegraph::StringHandle fgStrHandleClusterLightBuffer = framegraph::FrameGraph::stringToHandle("clusterLightBuffer"); +framegraph::StringHandle fgStrHandleClusterLightIndexBuffer = framegraph::FrameGraph::stringToHandle("lightIndexBuffer"); +framegraph::StringHandle fgStrHandleClusterLightGridBuffer = framegraph::FrameGraph::stringToHandle("lightGridBuffer"); -framegraph::StringHandle fgStrHandleClusterBuildPass = framegraph::FrameGraph::stringToHandle("clusterBuildPass"); +framegraph::StringHandle fgStrHandleClusterBuildPass = framegraph::FrameGraph::stringToHandle("clusterBuildPass"); framegraph::StringHandle fgStrHandleClusterCullingPass = framegraph::FrameGraph::stringToHandle("clusterCullingPass"); ClusterLightCulling::~ClusterLightCulling() { @@ -93,10 +93,10 @@ void ClusterLightCulling::initialize(gfx::Device *dev) { gfx::BufferFlagBit::NONE, }); - _lightBufferStride = 4 * sizeof(Vec4); + _lightBufferStride = 4 * sizeof(Vec4); _buildingDispatchInfo = {CLUSTERS_X / CLUSTERS_X_THREADS, CLUSTERS_Y / CLUSTERS_Y_THREADS, CLUSTERS_Z / clusterZThreads}; - _resetDispatchInfo = {1, 1, 1}; - _cullingDispatchInfo = {CLUSTERS_X / CLUSTERS_X_THREADS, CLUSTERS_Y / CLUSTERS_Y_THREADS, CLUSTERS_Z / clusterZThreads}; + _resetDispatchInfo = {1, 1, 1}; + _cullingDispatchInfo = {CLUSTERS_X / CLUSTERS_X_THREADS, CLUSTERS_Y / CLUSTERS_Y_THREADS, CLUSTERS_Z / clusterZThreads}; _resetBarrier = _device->getGeneralBarrier({ gfx::AccessFlagBit::COMPUTE_SHADER_WRITE, @@ -115,9 +115,9 @@ void ClusterLightCulling::update() { auto *const sceneData = _pipeline->getPipelineSceneData(); - _constants[NEAR_FAR_OFFSET + 0] = static_cast(_camera->getNearClip()); - _constants[NEAR_FAR_OFFSET + 1] = static_cast(_camera->getFarClip()); - const auto &viewport = _camera->getViewport(); + _constants[NEAR_FAR_OFFSET + 0] = static_cast(_camera->getNearClip()); + _constants[NEAR_FAR_OFFSET + 1] = static_cast(_camera->getFarClip()); + const auto &viewport = _camera->getViewport(); _constants[VIEW_PORT_OFFSET + 0] = viewport.x * static_cast(_camera->getWidth()) * sceneData->getShadingScale(); _constants[VIEW_PORT_OFFSET + 1] = viewport.y * static_cast(_camera->getHeight()) * sceneData->getShadingScale(); _constants[VIEW_PORT_OFFSET + 2] = viewport.z * static_cast(_camera->getWidth()) * sceneData->getShadingScale(); @@ -132,11 +132,11 @@ void ClusterLightCulling::update() { uint cameraIndex = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); if (cameraIndex >= _oldCamProjMats.size()) { _rebuildClusters = true; - uint nextLength = std::max(nextPow2(static_cast(cameraIndex)), uint(1)); + uint nextLength = std::max(nextPow2(static_cast(cameraIndex)), uint(1)); _oldCamProjMats.resize(nextLength, Mat4::ZERO); _oldCamProjMats[cameraIndex] = _camera->getMatProj(); } else { - _rebuildClusters = ClusterLightCulling::isProjMatChange(_camera->getMatProj(), _oldCamProjMats[cameraIndex]); + _rebuildClusters = ClusterLightCulling::isProjMatChange(_camera->getMatProj(), _oldCamProjMats[cameraIndex]); _oldCamProjMats[cameraIndex] = _camera->getMatProj(); } } @@ -148,7 +148,7 @@ void ClusterLightCulling::updateLights() { _validLights.clear(); - geometry::Sphere sphere; + geometry::Sphere sphere; const auto *const scene = _camera->getScene(); for (const auto &light : scene->getSphereLights()) { sphere.setCenter(light->getPosition()); @@ -166,36 +166,36 @@ void ClusterLightCulling::updateLights() { } } - const auto exposure = _camera->getExposure(); - const auto validLightCount = _validLights.size(); - auto *const sceneData = _pipeline->getPipelineSceneData(); + const auto exposure = _camera->getExposure(); + const auto validLightCount = _validLights.size(); + auto *const sceneData = _pipeline->getPipelineSceneData(); if (validLightCount > _lightBufferCount) { _lightBufferResized = true; - _lightBufferCount = nextPow2(static_cast(validLightCount)); + _lightBufferCount = nextPow2(static_cast(validLightCount)); _lightBufferData.resize(16 * _lightBufferCount); } for (unsigned l = 0, offset = 0; l < validLightCount; l++, offset += 16) { - auto * light = _validLights[l]; - const bool isSpotLight = scene::LightType::SPOT == light->getType(); - const auto *spotLight = isSpotLight ? static_cast(light) : nullptr; + auto *light = _validLights[l]; + const bool isSpotLight = scene::LightType::SPOT == light->getType(); + const auto *spotLight = isSpotLight ? static_cast(light) : nullptr; const auto *sphereLight = isSpotLight ? nullptr : static_cast(light); - auto index = offset + UBOForwardLight::LIGHT_POS_OFFSET; - const auto &position = isSpotLight ? spotLight->getPosition() : sphereLight->getPosition(); + auto index = offset + UBOForwardLight::LIGHT_POS_OFFSET; + const auto &position = isSpotLight ? spotLight->getPosition() : sphereLight->getPosition(); _lightBufferData[index++] = position.x; _lightBufferData[index++] = position.y; - _lightBufferData[index] = position.z; + _lightBufferData[index] = position.z; - index = offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET; + index = offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET; _lightBufferData[index++] = isSpotLight ? spotLight->getSize() : sphereLight->getSize(); - _lightBufferData[index] = isSpotLight ? spotLight->getRange() : sphereLight->getRange(); + _lightBufferData[index] = isSpotLight ? spotLight->getRange() : sphereLight->getRange(); - index = offset + UBOForwardLight::LIGHT_COLOR_OFFSET; + index = offset + UBOForwardLight::LIGHT_COLOR_OFFSET; const auto &color = light->getColor(); if (light->isUseColorTemperature()) { - const auto &tempRGB = light->getColorTemperatureRGB(); + const auto &tempRGB = light->getColorTemperatureRGB(); _lightBufferData[index++] = color.x * tempRGB.x; _lightBufferData[index++] = color.y * tempRGB.y; _lightBufferData[index++] = color.z * tempRGB.z; @@ -215,18 +215,18 @@ void ClusterLightCulling::updateLights() { switch (light->getType()) { case scene::LightType::SPHERE: - _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 0; + _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 0; _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; break; case scene::LightType::SPOT: { - _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 1.0F; + _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 1.0F; _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = spotLight->getSpotAngle(); - index = offset + UBOForwardLight::LIGHT_DIR_OFFSET; - const auto &direction = spotLight->getDirection(); + index = offset + UBOForwardLight::LIGHT_DIR_OFFSET; + const auto &direction = spotLight->getDirection(); _lightBufferData[index++] = direction.x; _lightBufferData[index++] = direction.y; - _lightBufferData[index] = direction.z; + _lightBufferData[index] = direction.z; } break; default: break; @@ -335,27 +335,27 @@ void ClusterLightCulling::initBuildingSatge() { // no compute support in GLES2 gfx::ShaderInfo shaderInfo; - shaderInfo.name = "Compute "; + shaderInfo.name = "Compute "; shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getShaderSource(sources)}}; shaderInfo.blocks = { {0, 0, "CCConst", {{"cc_nearFar", gfx::Type::FLOAT4, 1}, {"cc_viewPort", gfx::Type::FLOAT4, 1}, {"cc_matView", gfx::Type::MAT4, 1}, {"cc_matProjInv", gfx::Type::MAT4, 1}}, 1}, }; shaderInfo.buffers = {{0, 1, "b_clustersBuffer", 1, gfx::MemoryAccessBit::WRITE_ONLY}}; - _buildingShader = _device->createShader(shaderInfo); + _buildingShader = _device->createShader(shaderInfo); gfx::DescriptorSetLayoutInfo dslInfo; dslInfo.bindings.push_back({0, gfx::DescriptorType::UNIFORM_BUFFER, 1, gfx::ShaderStageFlagBit::COMPUTE}); dslInfo.bindings.push_back({1, gfx::DescriptorType::STORAGE_BUFFER, 1, gfx::ShaderStageFlagBit::COMPUTE}); _buildingDescriptorSetLayout = _device->createDescriptorSetLayout(dslInfo); - _buildingDescriptorSet = _device->createDescriptorSet({_buildingDescriptorSetLayout}); + _buildingDescriptorSet = _device->createDescriptorSet({_buildingDescriptorSetLayout}); _buildingPipelineLayout = _device->createPipelineLayout({{_buildingDescriptorSetLayout}}); gfx::PipelineStateInfo pipelineInfo; - pipelineInfo.shader = _buildingShader; + pipelineInfo.shader = _buildingShader; pipelineInfo.pipelineLayout = _buildingPipelineLayout; - pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; + pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; _buildingPipelineState = _device->createPipelineState(pipelineInfo); } @@ -387,23 +387,23 @@ void ClusterLightCulling::initResetStage() { // no compute support in GLES2 gfx::ShaderInfo shaderInfo; - shaderInfo.name = "Compute "; - shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getShaderSource(sources)}}; - shaderInfo.buffers = {{0, 0, "b_globalIndexBuffer", 1, gfx::MemoryAccessBit::WRITE_ONLY}}; + shaderInfo.name = "Compute "; + shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getShaderSource(sources)}}; + shaderInfo.buffers = {{0, 0, "b_globalIndexBuffer", 1, gfx::MemoryAccessBit::WRITE_ONLY}}; _resetCounterShader = _device->createShader(shaderInfo); gfx::DescriptorSetLayoutInfo dslInfo; dslInfo.bindings.push_back({0, gfx::DescriptorType::STORAGE_BUFFER, 1, gfx::ShaderStageFlagBit::COMPUTE}); _resetCounterDescriptorSetLayout = _device->createDescriptorSetLayout(dslInfo); - _resetCounterDescriptorSet = _device->createDescriptorSet({_resetCounterDescriptorSetLayout}); + _resetCounterDescriptorSet = _device->createDescriptorSet({_resetCounterDescriptorSetLayout}); _resetCounterPipelineLayout = _device->createPipelineLayout({{_resetCounterDescriptorSetLayout}}); gfx::PipelineStateInfo pipelineInfo; - pipelineInfo.shader = _resetCounterShader; + pipelineInfo.shader = _resetCounterShader; pipelineInfo.pipelineLayout = _resetCounterPipelineLayout; - pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; + pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; _resetCounterPipelineState = _device->createPipelineState(pipelineInfo); } @@ -629,7 +629,7 @@ void ClusterLightCulling::initCullingStage() { // no compute support in GLES2 gfx::ShaderInfo shaderInfo; - shaderInfo.name = "Compute "; + shaderInfo.name = "Compute "; shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getShaderSource(sources)}}; shaderInfo.blocks = { {0, 0, "CCConst", {{"cc_nearFar", gfx::Type::FLOAT4, 1}, {"cc_viewPort", gfx::Type::FLOAT4, 1}, {"cc_matView", gfx::Type::MAT4, 1}, {"cc_matProjInv", gfx::Type::MAT4, 1}}, 1}, @@ -639,7 +639,7 @@ void ClusterLightCulling::initCullingStage() { {0, 3, "b_clusterLightGridBuffer", 1, gfx::MemoryAccessBit::WRITE_ONLY}, {0, 4, "b_clustersBuffer", 1, gfx::MemoryAccessBit::READ_ONLY}, {0, 5, "b_globalIndexBuffer", 1, gfx::MemoryAccessBit::READ_WRITE}}; - _cullingShader = _device->createShader(shaderInfo); + _cullingShader = _device->createShader(shaderInfo); gfx::DescriptorSetLayoutInfo dslInfo; dslInfo.bindings.push_back({0, gfx::DescriptorType::UNIFORM_BUFFER, 1, gfx::ShaderStageFlagBit::COMPUTE}); @@ -650,14 +650,14 @@ void ClusterLightCulling::initCullingStage() { dslInfo.bindings.push_back({5, gfx::DescriptorType::STORAGE_BUFFER, 1, gfx::ShaderStageFlagBit::COMPUTE}); _cullingDescriptorSetLayout = _device->createDescriptorSetLayout(dslInfo); - _cullingDescriptorSet = _device->createDescriptorSet({_cullingDescriptorSetLayout}); + _cullingDescriptorSet = _device->createDescriptorSet({_cullingDescriptorSetLayout}); _cullingPipelineLayout = _device->createPipelineLayout({{_cullingDescriptorSetLayout}}); gfx::PipelineStateInfo pipelineInfo; - pipelineInfo.shader = _cullingShader; + pipelineInfo.shader = _cullingShader; pipelineInfo.pipelineLayout = _cullingPipelineLayout; - pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; + pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; _cullingPipelineState = _device->createPipelineState(pipelineInfo); } @@ -680,12 +680,12 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { uint clusterBufferSize = 2 * sizeof(Vec4) * CLUSTER_COUNT; framegraph::Buffer::Descriptor bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::STORAGE; + bufferInfo.usage = gfx::BufferUsageBit::STORAGE; bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; - bufferInfo.size = clusterBufferSize; - bufferInfo.stride = clusterBufferSize; - bufferInfo.flags = gfx::BufferFlagBit::NONE; - data.clusterBuffer = builder.create(fgStrHandleClusterBuffer, bufferInfo); + bufferInfo.size = clusterBufferSize; + bufferInfo.stride = clusterBufferSize; + bufferInfo.flags = gfx::BufferFlagBit::NONE; + data.clusterBuffer = builder.create(fgStrHandleClusterBuffer, bufferInfo); builder.writeToBlackboard(fgStrHandleClusterBuffer, data.clusterBuffer); } // only rebuild cluster necceray @@ -699,11 +699,11 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { uint atomicIndexBufferSize = sizeof(uint); framegraph::Buffer::Descriptor bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::STORAGE; - bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; - bufferInfo.size = atomicIndexBufferSize; - bufferInfo.stride = atomicIndexBufferSize; - bufferInfo.flags = gfx::BufferFlagBit::NONE; + bufferInfo.usage = gfx::BufferUsageBit::STORAGE; + bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; + bufferInfo.size = atomicIndexBufferSize; + bufferInfo.stride = atomicIndexBufferSize; + bufferInfo.flags = gfx::BufferFlagBit::NONE; data.globalIndexBuffer = builder.create(fgStrHandleClusterGlobalIndexBuffer, bufferInfo); builder.writeToBlackboard(fgStrHandleClusterGlobalIndexBuffer, data.globalIndexBuffer); } @@ -745,12 +745,12 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { data.lightBuffer = framegraph::BufferHandle(builder.readFromBlackboard(fgStrHandleClusterLightBuffer)); if (!data.lightBuffer.isValid() || _lightBufferResized) { framegraph::Buffer::Descriptor bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::STORAGE; + bufferInfo.usage = gfx::BufferUsageBit::STORAGE; bufferInfo.memUsage = gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE; - bufferInfo.size = _lightBufferStride * _lightBufferCount; - bufferInfo.stride = _lightBufferStride; - bufferInfo.flags = gfx::BufferFlagBit::NONE; - data.lightBuffer = builder.create(fgStrHandleClusterLightBuffer, bufferInfo); + bufferInfo.size = _lightBufferStride * _lightBufferCount; + bufferInfo.stride = _lightBufferStride; + bufferInfo.flags = gfx::BufferFlagBit::NONE; + data.lightBuffer = builder.create(fgStrHandleClusterLightBuffer, bufferInfo); builder.writeToBlackboard(fgStrHandleClusterLightBuffer, data.lightBuffer); _lightBufferResized = false; } @@ -763,11 +763,11 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { uint lightIndicesBufferSize = MAX_LIGHTS_PER_CLUSTER * CLUSTER_COUNT * sizeof(int); framegraph::Buffer::Descriptor bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::STORAGE; - bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; - bufferInfo.size = lightIndicesBufferSize; - bufferInfo.stride = lightIndicesBufferSize; - bufferInfo.flags = gfx::BufferFlagBit::NONE; + bufferInfo.usage = gfx::BufferUsageBit::STORAGE; + bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; + bufferInfo.size = lightIndicesBufferSize; + bufferInfo.stride = lightIndicesBufferSize; + bufferInfo.flags = gfx::BufferFlagBit::NONE; data.lightIndexBuffer = builder.create(fgStrHandleClusterLightIndexBuffer, bufferInfo); builder.writeToBlackboard(fgStrHandleClusterLightIndexBuffer, data.lightIndexBuffer); } @@ -780,11 +780,11 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { uint lightGridBufferSize = CLUSTER_COUNT * 4 * sizeof(uint); framegraph::Buffer::Descriptor bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::STORAGE; - bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; - bufferInfo.size = lightGridBufferSize; - bufferInfo.stride = lightGridBufferSize; - bufferInfo.flags = gfx::BufferFlagBit::NONE; + bufferInfo.usage = gfx::BufferUsageBit::STORAGE; + bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; + bufferInfo.size = lightGridBufferSize; + bufferInfo.stride = lightGridBufferSize; + bufferInfo.flags = gfx::BufferFlagBit::NONE; data.lightGridBuffer = builder.create(fgStrHandleClusterLightGridBuffer, bufferInfo); builder.writeToBlackboard(fgStrHandleClusterLightGridBuffer, data.lightGridBuffer); } @@ -819,8 +819,8 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera *camera) { cmdBuff->dispatch(_cullingDispatchInfo); }; - auto *pipeline = static_cast(_pipeline); - uint insertPoint = static_cast(DeferredInsertPoint::DIP_CLUSTER); + auto *pipeline = static_cast(_pipeline); + uint insertPoint = static_cast(DeferredInsertPoint::DIP_CLUSTER); pipeline->getFrameGraph().addPass(insertPoint++, fgStrHandleClusterBuildPass, clusterBuildSetup, clusterBuildExec); pipeline->getFrameGraph().addPass(insertPoint++, fgStrHandleClusterCullingPass, lightCullingSetup, lightCullingExec); } diff --git a/native/cocos/renderer/pipeline/ClusterLightCulling.h b/native/cocos/renderer/pipeline/ClusterLightCulling.h index 0362999e6b..accb5ca4d3 100644 --- a/native/cocos/renderer/pipeline/ClusterLightCulling.h +++ b/native/cocos/renderer/pipeline/ClusterLightCulling.h @@ -100,38 +100,38 @@ private: return false; } - gfx::Device * _device{nullptr}; - scene::Camera * _camera{nullptr}; + gfx::Device *_device{nullptr}; + scene::Camera *_camera{nullptr}; RenderPipeline *_pipeline{nullptr}; - gfx::Shader * _buildingShader{nullptr}; + gfx::Shader *_buildingShader{nullptr}; gfx::DescriptorSetLayout *_buildingDescriptorSetLayout{nullptr}; - gfx::PipelineLayout * _buildingPipelineLayout{nullptr}; - gfx::PipelineState * _buildingPipelineState{nullptr}; - gfx::DescriptorSet * _buildingDescriptorSet{nullptr}; + gfx::PipelineLayout *_buildingPipelineLayout{nullptr}; + gfx::PipelineState *_buildingPipelineState{nullptr}; + gfx::DescriptorSet *_buildingDescriptorSet{nullptr}; - gfx::Shader * _resetCounterShader{nullptr}; + gfx::Shader *_resetCounterShader{nullptr}; gfx::DescriptorSetLayout *_resetCounterDescriptorSetLayout{nullptr}; - gfx::PipelineLayout * _resetCounterPipelineLayout{nullptr}; - gfx::PipelineState * _resetCounterPipelineState{nullptr}; - gfx::DescriptorSet * _resetCounterDescriptorSet{nullptr}; + gfx::PipelineLayout *_resetCounterPipelineLayout{nullptr}; + gfx::PipelineState *_resetCounterPipelineState{nullptr}; + gfx::DescriptorSet *_resetCounterDescriptorSet{nullptr}; - gfx::Shader * _cullingShader{nullptr}; + gfx::Shader *_cullingShader{nullptr}; gfx::DescriptorSetLayout *_cullingDescriptorSetLayout{nullptr}; - gfx::PipelineLayout * _cullingPipelineLayout{nullptr}; - gfx::PipelineState * _cullingPipelineState{nullptr}; - gfx::DescriptorSet * _cullingDescriptorSet{nullptr}; + gfx::PipelineLayout *_cullingPipelineLayout{nullptr}; + gfx::PipelineState *_cullingPipelineState{nullptr}; + gfx::DescriptorSet *_cullingDescriptorSet{nullptr}; - static constexpr uint NEAR_FAR_OFFSET = 0; - static constexpr uint VIEW_PORT_OFFSET = 4; - static constexpr uint MAT_VIEW_OFFSET = 8; + static constexpr uint NEAR_FAR_OFFSET = 0; + static constexpr uint VIEW_PORT_OFFSET = 4; + static constexpr uint MAT_VIEW_OFFSET = 8; static constexpr uint MAT_PROJ_INV_OFFSET = 24; ccstd::array _constants{}; - gfx::Buffer * _constantsBuffer{nullptr}; + gfx::Buffer *_constantsBuffer{nullptr}; ccstd::vector _validLights; - ccstd::vector _lightBufferData; + ccstd::vector _lightBufferData; gfx::GeneralBarrier *_resetBarrier{nullptr}; @@ -139,13 +139,13 @@ private: gfx::DispatchInfo _resetDispatchInfo; gfx::DispatchInfo _cullingDispatchInfo; - bool _lightBufferResized{false}; - uint _lightBufferStride{0}; - uint _lightBufferCount{0}; + bool _lightBufferResized{false}; + uint _lightBufferStride{0}; + uint _lightBufferCount{0}; float _lightMeterScale{10000.0F}; // only rebuild clusters when camera project matrix changed - bool _rebuildClusters{false}; + bool _rebuildClusters{false}; ccstd::vector _oldCamProjMats; bool _initialized{false}; diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index 0b1ca20ef7..e7f388d5bb 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -31,16 +31,16 @@ namespace cc { namespace pipeline { -static uint32_t globalUBOCount = static_cast(PipelineGlobalBindings::SAMPLER_SHADOWMAP); +static uint32_t globalUBOCount = static_cast(PipelineGlobalBindings::SAMPLER_SHADOWMAP); static uint32_t globalSamplerCount = static_cast(PipelineGlobalBindings::COUNT) - globalUBOCount; -static uint32_t localUBOCount = static_cast(ModelLocalBindings::SAMPLER_JOINTS); -static uint32_t localSamplerCount = static_cast(ModelLocalBindings::STORAGE_REFLECTION) - localUBOCount; +static uint32_t localUBOCount = static_cast(ModelLocalBindings::SAMPLER_JOINTS); +static uint32_t localSamplerCount = static_cast(ModelLocalBindings::STORAGE_REFLECTION) - localUBOCount; static uint32_t localStorageImageCount = static_cast(ModelLocalBindings::COUNT) - localUBOCount - localSamplerCount; -uint globalSet = static_cast(SetIndex::GLOBAL); +uint globalSet = static_cast(SetIndex::GLOBAL); uint materialSet = static_cast(SetIndex::MATERIAL); -uint localSet = static_cast(SetIndex::LOCAL); +uint localSet = static_cast(SetIndex::LOCAL); gfx::BindingMappingInfo bindingMappingInfo = { {globalUBOCount, 0, localUBOCount}, // Uniform Buffer Counts @@ -53,9 +53,9 @@ gfx::BindingMappingInfo bindingMappingInfo = { {0, 2, 1}, // Set Order Indices }; -DescriptorSetLayoutInfos globalDescriptorSetLayout; -DescriptorSetLayoutInfos localDescriptorSetLayout; -const ccstd::string UBOGlobal::NAME = "CCGlobal"; +DescriptorSetLayoutInfos globalDescriptorSetLayout; +DescriptorSetLayoutInfos localDescriptorSetLayout; +const ccstd::string UBOGlobal::NAME = "CCGlobal"; const gfx::DescriptorSetLayoutBinding UBOGlobal::DESCRIPTOR = { UBOGlobal::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -75,7 +75,7 @@ const gfx::UniformBlock UBOGlobal::LAYOUT = { 1, }; -const ccstd::string UBOLocalBatched::NAME = "CCLocalBatched"; +const ccstd::string UBOLocalBatched::NAME = "CCLocalBatched"; const gfx::DescriptorSetLayoutBinding UBOLocalBatched::DESCRIPTOR = { UBOLocalBatched::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -93,7 +93,7 @@ const gfx::UniformBlock UBOLocalBatched::LAYOUT = { 1, }; -const ccstd::string UBOCamera::NAME = "CCCamera"; +const ccstd::string UBOCamera::NAME = "CCCamera"; const gfx::DescriptorSetLayoutBinding UBOCamera::DESCRIPTOR = { UBOCamera::BINDING, gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER, @@ -129,7 +129,7 @@ const gfx::UniformBlock UBOCamera::LAYOUT = { 1, }; -const ccstd::string UBOShadow::NAME = "CCShadow"; +const ccstd::string UBOShadow::NAME = "CCShadow"; const gfx::DescriptorSetLayoutBinding UBOShadow::DESCRIPTOR = { UBOShadow::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -157,7 +157,7 @@ const gfx::UniformBlock UBOShadow::LAYOUT = { 1, }; -const ccstd::string UBOLocal::NAME = "CCLocal"; +const ccstd::string UBOLocal::NAME = "CCLocal"; const gfx::DescriptorSetLayoutBinding UBOLocal::DESCRIPTOR = { UBOLocal::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -178,7 +178,7 @@ const gfx::UniformBlock UBOLocal::LAYOUT = { 1, }; -const ccstd::string UBOWorldBound::NAME = "CCWorldBound"; +const ccstd::string UBOWorldBound::NAME = "CCWorldBound"; const gfx::DescriptorSetLayoutBinding UBOWorldBound::DESCRIPTOR = { UBOWorldBound::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -197,7 +197,7 @@ const gfx::UniformBlock UBOWorldBound::LAYOUT = { 1, }; -const ccstd::string UBOForwardLight::NAME = "CCForwardLight"; +const ccstd::string UBOForwardLight::NAME = "CCForwardLight"; const gfx::DescriptorSetLayoutBinding UBOForwardLight::DESCRIPTOR = { UBOForwardLight::BINDING, gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER, @@ -218,7 +218,7 @@ const gfx::UniformBlock UBOForwardLight::LAYOUT = { 1, }; -const ccstd::string UBOSkinningTexture::NAME = "CCSkinningTexture"; +const ccstd::string UBOSkinningTexture::NAME = "CCSkinningTexture"; const gfx::DescriptorSetLayoutBinding UBOSkinningTexture::DESCRIPTOR = { UBOSkinningTexture::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -236,7 +236,7 @@ const gfx::UniformBlock UBOSkinningTexture::LAYOUT = { 1, }; -const ccstd::string UBOSkinningAnimation::NAME = "CCSkinningAnimation"; +const ccstd::string UBOSkinningAnimation::NAME = "CCSkinningAnimation"; const gfx::DescriptorSetLayoutBinding UBOSkinningAnimation::DESCRIPTOR = { UBOSkinningAnimation::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -254,7 +254,7 @@ const gfx::UniformBlock UBOSkinningAnimation::LAYOUT = { 1, }; -const ccstd::string UBOSkinning::NAME = "CCSkinning"; +const ccstd::string UBOSkinning::NAME = "CCSkinning"; const gfx::DescriptorSetLayoutBinding UBOSkinning::DESCRIPTOR = { UBOSkinning::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, @@ -272,10 +272,10 @@ const gfx::UniformBlock UBOSkinning::LAYOUT = { 1, }; -const uint UBOMorph::COUNT_BASE_4_BYTES = static_cast(4 * std::ceil(UBOMorph::MAX_MORPH_TARGET_COUNT / 4) + 4); -const uint UBOMorph::SIZE = UBOMorph::COUNT_BASE_4_BYTES * 4; -const ccstd::string UBOMorph::NAME = "CCMorph"; -const gfx::DescriptorSetLayoutBinding UBOMorph::DESCRIPTOR = { +const uint UBOMorph::COUNT_BASE_4_BYTES = static_cast(4 * std::ceil(UBOMorph::MAX_MORPH_TARGET_COUNT / 4) + 4); +const uint UBOMorph::SIZE = UBOMorph::COUNT_BASE_4_BYTES * 4; +const ccstd::string UBOMorph::NAME = "CCMorph"; +const gfx::DescriptorSetLayoutBinding UBOMorph::DESCRIPTOR = { UBOMorph::BINDING, gfx::DescriptorType::UNIFORM_BUFFER, 1, @@ -293,7 +293,7 @@ const gfx::UniformBlock UBOMorph::LAYOUT = { 1, }; -const ccstd::string UBOUILocal::NAME = "CCUILocal"; +const ccstd::string UBOUILocal::NAME = "CCUILocal"; const gfx::DescriptorSetLayoutBinding UBOUILocal::DESCRIPTOR = { UBOUILocal::BINDING, gfx::DescriptorType::DYNAMIC_UNIFORM_BUFFER, @@ -310,7 +310,7 @@ const gfx::UniformBlock UBOUILocal::LAYOUT = { 1, }; -const ccstd::string SHADOWMAP::NAME = "cc_shadowMap"; +const ccstd::string SHADOWMAP::NAME = "cc_shadowMap"; const gfx::DescriptorSetLayoutBinding SHADOWMAP::DESCRIPTOR = { SHADOWMAP::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -326,7 +326,7 @@ const gfx::UniformSamplerTexture SHADOWMAP::LAYOUT = { 1, }; -const ccstd::string ENVIRONMENT::NAME = "cc_environment"; +const ccstd::string ENVIRONMENT::NAME = "cc_environment"; const gfx::DescriptorSetLayoutBinding ENVIRONMENT::DESCRIPTOR = { ENVIRONMENT::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -342,7 +342,7 @@ const gfx::UniformSamplerTexture ENVIRONMENT::LAYOUT = { 1, }; -const ccstd::string SPOTLIGHTINGMAP::NAME = "cc_spotLightingMap"; +const ccstd::string SPOTLIGHTINGMAP::NAME = "cc_spotLightingMap"; const gfx::DescriptorSetLayoutBinding SPOTLIGHTINGMAP::DESCRIPTOR = { SPOTLIGHTINGMAP::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -358,7 +358,7 @@ const gfx::UniformSamplerTexture SPOTLIGHTINGMAP::LAYOUT = { 1, }; -const ccstd::string DIFFUSEMAP::NAME = "cc_diffuseMap"; +const ccstd::string DIFFUSEMAP::NAME = "cc_diffuseMap"; const gfx::DescriptorSetLayoutBinding DIFFUSEMAP::DESCRIPTOR = { DIFFUSEMAP::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -374,7 +374,7 @@ const gfx::UniformSamplerTexture DIFFUSEMAP::LAYOUT = { 1, }; -const ccstd::string JOINTTEXTURE::NAME = "cc_jointTexture"; +const ccstd::string JOINTTEXTURE::NAME = "cc_jointTexture"; const gfx::DescriptorSetLayoutBinding JOINTTEXTURE::DESCRIPTOR = { JOINTTEXTURE::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -390,7 +390,7 @@ const gfx::UniformSamplerTexture JOINTTEXTURE::LAYOUT = { 1, }; -const ccstd::string POSITIONMORPH::NAME = "cc_PositionDisplacements"; +const ccstd::string POSITIONMORPH::NAME = "cc_PositionDisplacements"; const gfx::DescriptorSetLayoutBinding POSITIONMORPH::DESCRIPTOR = { POSITIONMORPH::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -406,7 +406,7 @@ const gfx::UniformSamplerTexture POSITIONMORPH::LAYOUT = { 1, }; -const ccstd::string NORMALMORPH::NAME = "cc_NormalDisplacements"; +const ccstd::string NORMALMORPH::NAME = "cc_NormalDisplacements"; const gfx::DescriptorSetLayoutBinding NORMALMORPH::DESCRIPTOR = { NORMALMORPH::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -422,7 +422,7 @@ const gfx::UniformSamplerTexture NORMALMORPH::LAYOUT = { 1, }; -const ccstd::string TANGENTMORPH::NAME = "cc_TangentDisplacements"; +const ccstd::string TANGENTMORPH::NAME = "cc_TangentDisplacements"; const gfx::DescriptorSetLayoutBinding TANGENTMORPH::DESCRIPTOR = { TANGENTMORPH::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -438,7 +438,7 @@ const gfx::UniformSamplerTexture TANGENTMORPH::LAYOUT = { 1, }; -const ccstd::string LIGHTMAPTEXTURE::NAME = "cc_lightingMap"; +const ccstd::string LIGHTMAPTEXTURE::NAME = "cc_lightingMap"; const gfx::DescriptorSetLayoutBinding LIGHTMAPTEXTURE::DESCRIPTOR = { LIGHTMAPTEXTURE::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -454,7 +454,7 @@ const gfx::UniformSamplerTexture LIGHTMAPTEXTURE::LAYOUT = { 1, }; -const ccstd::string SPRITETEXTURE::NAME = "cc_spriteTexture"; +const ccstd::string SPRITETEXTURE::NAME = "cc_spriteTexture"; const gfx::DescriptorSetLayoutBinding SPRITETEXTURE::DESCRIPTOR = { SPRITETEXTURE::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -470,7 +470,7 @@ const gfx::UniformSamplerTexture SPRITETEXTURE::LAYOUT = { 1, }; -const ccstd::string REFLECTIONTEXTURE::NAME = "cc_reflectionTexture"; +const ccstd::string REFLECTIONTEXTURE::NAME = "cc_reflectionTexture"; const gfx::DescriptorSetLayoutBinding REFLECTIONTEXTURE::DESCRIPTOR = { REFLECTIONTEXTURE::BINDING, gfx::DescriptorType::SAMPLER_TEXTURE, @@ -486,7 +486,7 @@ const gfx::UniformSamplerTexture REFLECTIONTEXTURE::LAYOUT = { 1, }; -const ccstd::string REFLECTIONSTORAGE::NAME = "cc_reflectionStorage"; +const ccstd::string REFLECTIONSTORAGE::NAME = "cc_reflectionStorage"; const gfx::DescriptorSetLayoutBinding REFLECTIONSTORAGE::DESCRIPTOR = { REFLECTIONSTORAGE::BINDING, gfx::DescriptorType::STORAGE_IMAGE, @@ -524,7 +524,7 @@ bool supportsR32FloatTexture(gfx::Device *device) { } static ccstd::unordered_map phases; //cjh how to clear this global variable when exiting game? -static uint32_t phaseNum = 0; +static uint32_t phaseNum = 0; uint getPhaseID(const ccstd::string &phaseName) { auto iter = phases.find(phaseName); diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index 6ef1642ac3..ece48593b9 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -53,56 +53,56 @@ class RenderFlow; // and the JOINT_UNIFORM_CAPACITY macro in cc-skinning shader header. constexpr int JOINT_UNIFORM_CAPACITY = 30; -constexpr float SHADOW_CAMERA_MAX_FAR = 2000.0F; -const float COEFFICIENT_OF_EXPANSION = 2.0F * sqrtf(3.0F); +constexpr float SHADOW_CAMERA_MAX_FAR = 2000.0F; +const float COEFFICIENT_OF_EXPANSION = 2.0F * sqrtf(3.0F); struct CC_DLL RenderObject { - float depth = 0; + float depth = 0; const scene::Model *model = nullptr; }; using RenderObjectList = ccstd::vector; struct CC_DLL RenderTargetInfo { - uint width = 0; + uint width = 0; uint height = 0; }; struct CC_DLL RenderPass { - uint hash = 0; - float depth = 0; - uint shaderID = 0; - uint passIndex = 0; - const scene::SubModel *subModel = nullptr; + uint hash = 0; + float depth = 0; + uint shaderID = 0; + uint passIndex = 0; + const scene::SubModel *subModel = nullptr; }; using RenderPassList = ccstd::vector; -using ColorDesc = gfx::ColorAttachment; +using ColorDesc = gfx::ColorAttachment; using ColorDescList = ccstd::vector; using DepthStencilDesc = gfx::DepthStencilAttachment; struct CC_DLL RenderPassDesc { - uint index = 0; - ColorDescList colorAttachments; + uint index = 0; + ColorDescList colorAttachments; DepthStencilDesc depthStencilAttachment; }; using RenderPassDescList = ccstd::vector; struct CC_DLL RenderTextureDesc { - ccstd::string name; - gfx::TextureType type = gfx::TextureType::TEX2D; - gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; - gfx::Format format = gfx::Format::UNKNOWN; - int width = -1; - int height = -1; + ccstd::string name; + gfx::TextureType type = gfx::TextureType::TEX2D; + gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; + gfx::Format format = gfx::Format::UNKNOWN; + int width = -1; + int height = -1; }; using RenderTextureDescList = ccstd::vector; struct CC_DLL FrameBufferDesc { - ccstd::string name; - uint renderPass = 0; + ccstd::string name; + uint renderPass = 0; ccstd::vector colorTextures; - ccstd::string depthStencilTexture; + ccstd::string depthStencilTexture; }; using FrameBufferDescList = ccstd::vector; @@ -114,38 +114,38 @@ enum class RenderFlowType : uint8_t { CC_ENUM_CONVERSION_OPERATOR(RenderFlowType) using RenderStageList = ccstd::vector; -using RenderFlowList = ccstd::vector; -using LightList = ccstd::vector; -using UintList = ccstd::vector; +using RenderFlowList = ccstd::vector; +using LightList = ccstd::vector; +using UintList = ccstd::vector; enum class CC_DLL RenderPassStage { DEFAULT = 100, - UI = 200, + UI = 200, }; CC_ENUM_CONVERSION_OPERATOR(RenderPassStage) struct CC_DLL InternalBindingDesc { - gfx::DescriptorType type; - gfx::UniformBlock blockInfo; + gfx::DescriptorType type; + gfx::UniformBlock blockInfo; gfx::UniformSamplerTexture samplerInfo; - Value defaultValue; + Value defaultValue; }; struct CC_DLL InternalBindingInst : public InternalBindingDesc { - gfx::Buffer * buffer = nullptr; + gfx::Buffer *buffer = nullptr; gfx::Sampler *sampler = nullptr; gfx::Texture *texture = nullptr; }; struct CC_DLL RenderQueueCreateInfo { - bool isTransparent = false; - uint phases = 0; + bool isTransparent = false; + uint phases = 0; std::function sortFunc; }; enum class CC_DLL RenderPriority { - MIN = 0, - MAX = 0xff, + MIN = 0, + MAX = 0xff, DEFAULT = 0x80, }; CC_ENUM_CONVERSION_OPERATOR(RenderPriority) @@ -157,8 +157,8 @@ enum class CC_DLL RenderQueueSortMode { CC_ENUM_CONVERSION_OPERATOR(RenderQueueSortMode) struct CC_DLL RenderQueueDesc { - bool isTransparent = false; - RenderQueueSortMode sortMode = RenderQueueSortMode::FRONT_TO_BACK; + bool isTransparent = false; + RenderQueueSortMode sortMode = RenderQueueSortMode::FRONT_TO_BACK; ccstd::vector stages; }; using RenderQueueDescList = ccstd::vector; @@ -265,52 +265,52 @@ extern CC_DLL uint localSet; extern CC_DLL gfx::BindingMappingInfo bindingMappingInfo; struct CC_DLL UBOLocalBatched { - static constexpr uint BATCHING_COUNT = 10; - static constexpr uint MAT_WORLDS_OFFSET = 0; - static constexpr uint COUNT = 16 * UBOLocalBatched::BATCHING_COUNT; - static constexpr uint SIZE = UBOLocalBatched::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); + static constexpr uint BATCHING_COUNT = 10; + static constexpr uint MAT_WORLDS_OFFSET = 0; + static constexpr uint COUNT = 16 * UBOLocalBatched::BATCHING_COUNT; + static constexpr uint SIZE = UBOLocalBatched::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOLocal { - static constexpr uint MAT_WORLD_OFFSET = 0; - static constexpr uint MAT_WORLD_IT_OFFSET = UBOLocal::MAT_WORLD_OFFSET + 16; - static constexpr uint LIGHTINGMAP_UVPARAM = UBOLocal::MAT_WORLD_IT_OFFSET + 16; - static constexpr uint LOCAL_SHADOW_BIAS = UBOLocal::LIGHTINGMAP_UVPARAM + 4; - static constexpr uint COUNT = UBOLocal::LOCAL_SHADOW_BIAS + 4; - static constexpr uint SIZE = UBOLocal::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); + static constexpr uint MAT_WORLD_OFFSET = 0; + static constexpr uint MAT_WORLD_IT_OFFSET = UBOLocal::MAT_WORLD_OFFSET + 16; + static constexpr uint LIGHTINGMAP_UVPARAM = UBOLocal::MAT_WORLD_IT_OFFSET + 16; + static constexpr uint LOCAL_SHADOW_BIAS = UBOLocal::LIGHTINGMAP_UVPARAM + 4; + static constexpr uint COUNT = UBOLocal::LOCAL_SHADOW_BIAS + 4; + static constexpr uint SIZE = UBOLocal::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOWorldBound { - static constexpr uint WORLD_BOUND_CENTER = 0; - static constexpr uint WORLD_BOUND_HALF_EXTENTS = UBOWorldBound::WORLD_BOUND_CENTER + 4; - static constexpr uint COUNT = UBOWorldBound::WORLD_BOUND_HALF_EXTENTS + 4; - static constexpr uint SIZE = UBOWorldBound::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); + static constexpr uint WORLD_BOUND_CENTER = 0; + static constexpr uint WORLD_BOUND_HALF_EXTENTS = UBOWorldBound::WORLD_BOUND_CENTER + 4; + static constexpr uint COUNT = UBOWorldBound::WORLD_BOUND_HALF_EXTENTS + 4; + static constexpr uint SIZE = UBOWorldBound::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOForwardLight { - static constexpr uint LIGHTS_PER_PASS = 1; - static constexpr uint LIGHT_POS_OFFSET = 0; - static constexpr uint LIGHT_COLOR_OFFSET = UBOForwardLight::LIGHT_POS_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; - static constexpr uint LIGHT_SIZE_RANGE_ANGLE_OFFSET = UBOForwardLight::LIGHT_COLOR_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; - static constexpr uint LIGHT_DIR_OFFSET = UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; - static constexpr uint COUNT = UBOForwardLight::LIGHT_DIR_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; - static constexpr uint SIZE = UBOForwardLight::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_FORWARD_LIGHTS); + static constexpr uint LIGHTS_PER_PASS = 1; + static constexpr uint LIGHT_POS_OFFSET = 0; + static constexpr uint LIGHT_COLOR_OFFSET = UBOForwardLight::LIGHT_POS_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; + static constexpr uint LIGHT_SIZE_RANGE_ANGLE_OFFSET = UBOForwardLight::LIGHT_COLOR_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; + static constexpr uint LIGHT_DIR_OFFSET = UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; + static constexpr uint COUNT = UBOForwardLight::LIGHT_DIR_OFFSET + UBOForwardLight::LIGHTS_PER_PASS * 4; + static constexpr uint SIZE = UBOForwardLight::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_FORWARD_LIGHTS); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBODeferredLight { @@ -318,66 +318,66 @@ struct CC_DLL UBODeferredLight { }; struct CC_DLL UBOSkinningTexture { - static constexpr uint JOINTS_TEXTURE_INFO_OFFSET = 0; - static constexpr uint COUNT = UBOSkinningTexture::JOINTS_TEXTURE_INFO_OFFSET + 4; - static constexpr uint SIZE = UBOSkinningTexture::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_TEXTURE); + static constexpr uint JOINTS_TEXTURE_INFO_OFFSET = 0; + static constexpr uint COUNT = UBOSkinningTexture::JOINTS_TEXTURE_INFO_OFFSET + 4; + static constexpr uint SIZE = UBOSkinningTexture::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_TEXTURE); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOSkinningAnimation { - static constexpr uint JOINTS_ANIM_INFO_OFFSET = 0; - static constexpr uint COUNT = UBOSkinningAnimation::JOINTS_ANIM_INFO_OFFSET + 4; - static constexpr uint SIZE = UBOSkinningAnimation::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_ANIMATION); + static constexpr uint JOINTS_ANIM_INFO_OFFSET = 0; + static constexpr uint COUNT = UBOSkinningAnimation::JOINTS_ANIM_INFO_OFFSET + 4; + static constexpr uint SIZE = UBOSkinningAnimation::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_ANIMATION); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOSkinning { - static constexpr uint JOINTS_OFFSET = 0; - static constexpr uint COUNT = UBOSkinning::JOINTS_OFFSET + JOINT_UNIFORM_CAPACITY * 12; - static constexpr uint SIZE = UBOSkinning::COUNT * 4; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_TEXTURE); + static constexpr uint JOINTS_OFFSET = 0; + static constexpr uint COUNT = UBOSkinning::JOINTS_OFFSET + JOINT_UNIFORM_CAPACITY * 12; + static constexpr uint SIZE = UBOSkinning::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_SKINNING_TEXTURE); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOMorph { - static constexpr uint MAX_MORPH_TARGET_COUNT = 60; - static constexpr uint OFFSET_OF_WEIGHTS = 0; - static constexpr uint OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * MAX_MORPH_TARGET_COUNT; - static constexpr uint OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4; - static constexpr uint OFFSET_OF_VERTICES_COUNT = OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4; - static const uint COUNT_BASE_4_BYTES; - static const uint SIZE; - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_MORPH); + static constexpr uint MAX_MORPH_TARGET_COUNT = 60; + static constexpr uint OFFSET_OF_WEIGHTS = 0; + static constexpr uint OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * MAX_MORPH_TARGET_COUNT; + static constexpr uint OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4; + static constexpr uint OFFSET_OF_VERTICES_COUNT = OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4; + static const uint COUNT_BASE_4_BYTES; + static const uint SIZE; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_MORPH); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOUILocal { - static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_UI_LOCAL); + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_UI_LOCAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; enum class CC_DLL ForwardStagePriority { FORWARD = 10, - UI = 20 + UI = 20 }; CC_ENUM_CONVERSION_OPERATOR(ForwardStagePriority) enum class CC_DLL ForwardFlowPriority { - SHADOW = 0, + SHADOW = 0, FORWARD = 1, - UI = 10, + UI = 10, }; CC_ENUM_CONVERSION_OPERATOR(ForwardFlowPriority) @@ -389,103 +389,103 @@ enum class CC_DLL RenderFlowTag { CC_ENUM_CONVERSION_OPERATOR(RenderFlowTag) enum class CC_DLL DeferredStagePriority { - GBUFFER = 10, - LIGHTING = 15, + GBUFFER = 10, + LIGHTING = 15, TRANSPARANT = 18, - BLOOM = 19, + BLOOM = 19, POSTPROCESS = 20, - UI = 30 + UI = 30 }; CC_ENUM_CONVERSION_OPERATOR(DeferredStagePriority) enum class CC_DLL DeferredFlowPriority { SHADOW = 0, - MAIN = 1, - UI = 10 + MAIN = 1, + UI = 10 }; CC_ENUM_CONVERSION_OPERATOR(DeferredFlowPriority) struct CC_DLL UBOGlobal { - static constexpr uint TIME_OFFSET = 0; - static constexpr uint SCREEN_SIZE_OFFSET = UBOGlobal::TIME_OFFSET + 4; - static constexpr uint NATIVE_SIZE_OFFSET = UBOGlobal::SCREEN_SIZE_OFFSET + 4; - static constexpr uint COUNT = UBOGlobal::NATIVE_SIZE_OFFSET + 4; - static constexpr uint SIZE = UBOGlobal::COUNT * 4; - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_GLOBAL); + static constexpr uint TIME_OFFSET = 0; + static constexpr uint SCREEN_SIZE_OFFSET = UBOGlobal::TIME_OFFSET + 4; + static constexpr uint NATIVE_SIZE_OFFSET = UBOGlobal::SCREEN_SIZE_OFFSET + 4; + static constexpr uint COUNT = UBOGlobal::NATIVE_SIZE_OFFSET + 4; + static constexpr uint SIZE = UBOGlobal::COUNT * 4; + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_GLOBAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOCamera { - static constexpr uint MAT_VIEW_OFFSET = 0; - static constexpr uint MAT_VIEW_INV_OFFSET = UBOCamera::MAT_VIEW_OFFSET + 16; - static constexpr uint MAT_PROJ_OFFSET = UBOCamera::MAT_VIEW_INV_OFFSET + 16; - static constexpr uint MAT_PROJ_INV_OFFSET = UBOCamera::MAT_PROJ_OFFSET + 16; - static constexpr uint MAT_VIEW_PROJ_OFFSET = UBOCamera::MAT_PROJ_INV_OFFSET + 16; - static constexpr uint MAT_VIEW_PROJ_INV_OFFSET = UBOCamera::MAT_VIEW_PROJ_OFFSET + 16; - static constexpr uint CAMERA_POS_OFFSET = UBOCamera::MAT_VIEW_PROJ_INV_OFFSET + 16; - static constexpr uint SURFACE_TRANSFORM_OFFSET = UBOCamera::CAMERA_POS_OFFSET + 4; - static constexpr uint SCREEN_SCALE_OFFSET = UBOCamera::SURFACE_TRANSFORM_OFFSET + 4; - static constexpr uint EXPOSURE_OFFSET = UBOCamera::SCREEN_SCALE_OFFSET + 4; - static constexpr uint MAIN_LIT_DIR_OFFSET = UBOCamera::EXPOSURE_OFFSET + 4; - static constexpr uint MAIN_LIT_COLOR_OFFSET = UBOCamera::MAIN_LIT_DIR_OFFSET + 4; - static constexpr uint AMBIENT_SKY_OFFSET = UBOCamera::MAIN_LIT_COLOR_OFFSET + 4; - static constexpr uint AMBIENT_GROUND_OFFSET = UBOCamera::AMBIENT_SKY_OFFSET + 4; - static constexpr uint GLOBAL_FOG_COLOR_OFFSET = UBOCamera::AMBIENT_GROUND_OFFSET + 4; - static constexpr uint GLOBAL_FOG_BASE_OFFSET = UBOCamera::GLOBAL_FOG_COLOR_OFFSET + 4; - static constexpr uint GLOBAL_FOG_ADD_OFFSET = UBOCamera::GLOBAL_FOG_BASE_OFFSET + 4; - static constexpr uint GLOBAL_NEAR_FAR_OFFSET = UBOCamera::GLOBAL_FOG_ADD_OFFSET + 4; - static constexpr uint GLOBAL_VIEW_PORT_OFFSET = UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 4; - static constexpr uint COUNT = UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 4; - static constexpr uint SIZE = UBOCamera::COUNT * 4; - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_CAMERA); + static constexpr uint MAT_VIEW_OFFSET = 0; + static constexpr uint MAT_VIEW_INV_OFFSET = UBOCamera::MAT_VIEW_OFFSET + 16; + static constexpr uint MAT_PROJ_OFFSET = UBOCamera::MAT_VIEW_INV_OFFSET + 16; + static constexpr uint MAT_PROJ_INV_OFFSET = UBOCamera::MAT_PROJ_OFFSET + 16; + static constexpr uint MAT_VIEW_PROJ_OFFSET = UBOCamera::MAT_PROJ_INV_OFFSET + 16; + static constexpr uint MAT_VIEW_PROJ_INV_OFFSET = UBOCamera::MAT_VIEW_PROJ_OFFSET + 16; + static constexpr uint CAMERA_POS_OFFSET = UBOCamera::MAT_VIEW_PROJ_INV_OFFSET + 16; + static constexpr uint SURFACE_TRANSFORM_OFFSET = UBOCamera::CAMERA_POS_OFFSET + 4; + static constexpr uint SCREEN_SCALE_OFFSET = UBOCamera::SURFACE_TRANSFORM_OFFSET + 4; + static constexpr uint EXPOSURE_OFFSET = UBOCamera::SCREEN_SCALE_OFFSET + 4; + static constexpr uint MAIN_LIT_DIR_OFFSET = UBOCamera::EXPOSURE_OFFSET + 4; + static constexpr uint MAIN_LIT_COLOR_OFFSET = UBOCamera::MAIN_LIT_DIR_OFFSET + 4; + static constexpr uint AMBIENT_SKY_OFFSET = UBOCamera::MAIN_LIT_COLOR_OFFSET + 4; + static constexpr uint AMBIENT_GROUND_OFFSET = UBOCamera::AMBIENT_SKY_OFFSET + 4; + static constexpr uint GLOBAL_FOG_COLOR_OFFSET = UBOCamera::AMBIENT_GROUND_OFFSET + 4; + static constexpr uint GLOBAL_FOG_BASE_OFFSET = UBOCamera::GLOBAL_FOG_COLOR_OFFSET + 4; + static constexpr uint GLOBAL_FOG_ADD_OFFSET = UBOCamera::GLOBAL_FOG_BASE_OFFSET + 4; + static constexpr uint GLOBAL_NEAR_FAR_OFFSET = UBOCamera::GLOBAL_FOG_ADD_OFFSET + 4; + static constexpr uint GLOBAL_VIEW_PORT_OFFSET = UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 4; + static constexpr uint COUNT = UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 4; + static constexpr uint SIZE = UBOCamera::COUNT * 4; + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_CAMERA); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL UBOShadow { - static constexpr uint MAT_LIGHT_PLANE_PROJ_OFFSET = 0; - static constexpr uint MAT_LIGHT_VIEW_OFFSET = MAT_LIGHT_PLANE_PROJ_OFFSET + 16; - static constexpr uint MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow::MAT_LIGHT_VIEW_OFFSET + 16; - static constexpr uint SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET + 16; - static constexpr uint SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow::SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; - static constexpr uint SHADOW_PROJ_INFO_OFFSET = UBOShadow::SHADOW_PROJ_DEPTH_INFO_OFFSET + 4; - static constexpr uint SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = UBOShadow::SHADOW_PROJ_INFO_OFFSET + 4; - static constexpr uint SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4; - static constexpr uint SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; - static constexpr uint SHADOW_COLOR_OFFSET = UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; - static constexpr uint PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow::SHADOW_COLOR_OFFSET + 4; - static constexpr uint COUNT = UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; - static constexpr uint SIZE = UBOShadow::COUNT * 4; - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_SHADOW); + static constexpr uint MAT_LIGHT_PLANE_PROJ_OFFSET = 0; + static constexpr uint MAT_LIGHT_VIEW_OFFSET = MAT_LIGHT_PLANE_PROJ_OFFSET + 16; + static constexpr uint MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow::MAT_LIGHT_VIEW_OFFSET + 16; + static constexpr uint SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET + 16; + static constexpr uint SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow::SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; + static constexpr uint SHADOW_PROJ_INFO_OFFSET = UBOShadow::SHADOW_PROJ_DEPTH_INFO_OFFSET + 4; + static constexpr uint SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = UBOShadow::SHADOW_PROJ_INFO_OFFSET + 4; + static constexpr uint SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4; + static constexpr uint SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; + static constexpr uint SHADOW_COLOR_OFFSET = UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; + static constexpr uint PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow::SHADOW_COLOR_OFFSET + 4; + static constexpr uint COUNT = UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; + static constexpr uint SIZE = UBOShadow::COUNT * 4; + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::UBO_SHADOW); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformBlock LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformBlock LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL DescriptorSetLayoutInfos { - gfx::DescriptorSetLayoutBindingList bindings; - ccstd::unordered_map blocks; + gfx::DescriptorSetLayoutBindingList bindings; + ccstd::unordered_map blocks; ccstd::unordered_map samplers; - ccstd::unordered_map storeImages; + ccstd::unordered_map storeImages; }; extern CC_DLL DescriptorSetLayoutInfos globalDescriptorSetLayout; extern CC_DLL DescriptorSetLayoutInfos localDescriptorSetLayout; enum class LayerList : uint { - NONE = 0, + NONE = 0, IGNORE_RAYCAST = (1 << 20), - GIZMOS = (1 << 21), - EDITOR = (1 << 22), - UI_3D = (1 << 23), - SCENE_GIZMO = (1 << 24), - UI_2D = (1 << 25), + GIZMOS = (1 << 21), + EDITOR = (1 << 22), + UI_3D = (1 << 23), + SCENE_GIZMO = (1 << 24), + UI_2D = (1 << 25), PROFILER = (1 << 28), - DEFAULT = (1 << 30), - ALL = 0xffffffff, + DEFAULT = (1 << 30), + ALL = 0xffffffff, }; CC_ENUM_CONVERSION_OPERATOR(LayerList) @@ -502,92 +502,92 @@ bool supportsR32FloatTexture(gfx::Device *device); extern CC_DLL uint skyboxFlag; struct CC_DLL SHADOWMAP { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_SHADOWMAP); + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_SHADOWMAP); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL ENVIRONMENT { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_ENVIRONMENT); + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_ENVIRONMENT); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL SPOTLIGHTINGMAP { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_SPOT_LIGHTING_MAP); + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_SPOT_LIGHTING_MAP); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL DIFFUSEMAP { - static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_DIFFUSEMAP); + static constexpr uint BINDING = static_cast(PipelineGlobalBindings::SAMPLER_DIFFUSEMAP); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL JOINTTEXTURE { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_JOINTS); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_JOINTS); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL POSITIONMORPH { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_POSITION); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_POSITION); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL NORMALMORPH { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_NORMAL); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_NORMAL); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL TANGENTMORPH { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_TANGENT); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_MORPH_TANGENT); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL LIGHTMAPTEXTURE { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_LIGHTMAP); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_LIGHTMAP); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL SPRITETEXTURE { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_SPRITE); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_SPRITE); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL REFLECTIONTEXTURE { - static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_REFLECTION); + static constexpr uint BINDING = static_cast(ModelLocalBindings::SAMPLER_REFLECTION); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformSamplerTexture LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformSamplerTexture LAYOUT; + static const ccstd::string NAME; }; struct CC_DLL REFLECTIONSTORAGE { - static constexpr uint BINDING = static_cast(ModelLocalBindings::STORAGE_REFLECTION); + static constexpr uint BINDING = static_cast(ModelLocalBindings::STORAGE_REFLECTION); static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; - static const gfx::UniformStorageImage LAYOUT; - static const ccstd::string NAME; + static const gfx::UniformStorageImage LAYOUT; + static const ccstd::string NAME; }; -static constexpr uint CLUSTER_LIGHT_BINDING = 4; +static constexpr uint CLUSTER_LIGHT_BINDING = 4; static constexpr uint CLUSTER_LIGHT_INDEX_BINDING = 5; -static constexpr uint CLUSTER_LIGHT_GRID_BINDING = 6; +static constexpr uint CLUSTER_LIGHT_GRID_BINDING = 6; } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/Enum.h b/native/cocos/renderer/pipeline/Enum.h index cebbb567a9..8aa53080b7 100644 --- a/native/cocos/renderer/pipeline/Enum.h +++ b/native/cocos/renderer/pipeline/Enum.h @@ -26,16 +26,16 @@ #pragma once enum class CommonInsertPoint { - DIP_BLOOM = 350, + DIP_BLOOM = 350, DIP_POSTPROCESS = 400, }; enum class DeferredInsertPoint { - DIP_CLUSTER = 80, - DIP_GBUFFER = 100, - DIP_LIGHTING = 200, + DIP_CLUSTER = 80, + DIP_GBUFFER = 100, + DIP_LIGHTING = 200, DIP_TRANSPARENT = 220, - DIP_SSPR = 300, + DIP_SSPR = 300, DIP_INVALID }; diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.cpp b/native/cocos/renderer/pipeline/GeometryRenderer.cpp index 5a31fed8e8..d823afa836 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.cpp +++ b/native/cocos/renderer/pipeline/GeometryRenderer.cpp @@ -50,19 +50,19 @@ namespace pipeline { * [0]: no depthTest * [1]: depthTest */ -constexpr uint32_t GEOMETRY_DEPTH_TYPE_COUNT = 2U; +constexpr uint32_t GEOMETRY_DEPTH_TYPE_COUNT = 2U; constexpr uint32_t GEOMETRY_NO_DEPTH_TEST_PASS_NUM = 1U; -constexpr uint32_t GEOMETRY_DEPTH_TEST_PASS_NUM = 2U; -constexpr uint32_t GEOMETRY_VERTICES_PER_LINE = 2U; -constexpr uint32_t GEOMETRY_VERTICES_PER_TRIANGLE = 3U; -constexpr uint32_t GEOMETRY_MAX_LINES = 10000U; -constexpr uint32_t GEOMETRY_MAX_DASHED_LINES = 10000U; -constexpr uint32_t GEOMETRY_MAX_TRIANGLES = 10000U; +constexpr uint32_t GEOMETRY_DEPTH_TEST_PASS_NUM = 2U; +constexpr uint32_t GEOMETRY_VERTICES_PER_LINE = 2U; +constexpr uint32_t GEOMETRY_VERTICES_PER_TRIANGLE = 3U; +constexpr uint32_t GEOMETRY_MAX_LINES = 10000U; +constexpr uint32_t GEOMETRY_MAX_DASHED_LINES = 10000U; +constexpr uint32_t GEOMETRY_MAX_TRIANGLES = 10000U; enum class GeometryType { - LINE = 0, + LINE = 0, DASHED_LINE = 1, - TRIANGLE = 2, + TRIANGLE = 2, }; struct PosColorVertex { @@ -70,7 +70,7 @@ struct PosColorVertex { PosColorVertex(const Vec3 &pos, gfx::Color clr) : position(pos), color(clr) {} - Vec3 position; + Vec3 position; gfx::Color color; }; @@ -79,8 +79,8 @@ struct PosNormColorVertex { PosNormColorVertex(const Vec3 &pos, const Vec4 &norm, gfx::Color clr) : position(pos), normal(norm), color(clr) {} - Vec3 position; - Vec4 normal; // xyz: normal, w:unlit + Vec3 position; + Vec4 normal; // xyz: normal, w:unlit gfx::Color color; }; @@ -89,7 +89,7 @@ class GeometryVertexBuffer { private: inline void init(gfx::Device *device, uint32_t maxVertices, const gfx::AttributeList &attributes) { _maxVertices = maxVertices; - _buffer = device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, + _buffer = device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, static_cast(maxVertices * sizeof(T)), static_cast(sizeof(T))}); @@ -102,13 +102,13 @@ private: } inline uint32_t getCount() const { return std::min(static_cast(_vertices.size()), _maxVertices); } - inline bool empty() const { return _vertices.empty(); } - inline void reset() { _vertices.clear(); } + inline bool empty() const { return _vertices.empty(); } + inline void reset() { _vertices.clear(); } inline void update() { if (!empty()) { const auto count = getCount(); - const auto size = static_cast(count * sizeof(T)); + const auto size = static_cast(count * sizeof(T)); _buffer->update(&_vertices[0], size); } } @@ -120,17 +120,17 @@ private: CC_PROFILE_MEMORY_DEC(GeometryVertexBuffer, static_cast(_maxVertices * sizeof(T))); } - uint32_t _maxVertices{0}; - ccstd::vector _vertices; - gfx::Buffer * _buffer{nullptr}; + uint32_t _maxVertices{0}; + ccstd::vector _vertices; + gfx::Buffer *_buffer{nullptr}; gfx::InputAssembler *_inputAssembler{nullptr}; friend class GeometryRenderer; }; struct GeometryVertexBuffers { - ccstd::array, GEOMETRY_DEPTH_TYPE_COUNT> lines; - ccstd::array, GEOMETRY_DEPTH_TYPE_COUNT> dashedLines; + ccstd::array, GEOMETRY_DEPTH_TYPE_COUNT> lines; + ccstd::array, GEOMETRY_DEPTH_TYPE_COUNT> dashedLines; ccstd::array, GEOMETRY_DEPTH_TYPE_COUNT> triangles; }; @@ -168,10 +168,10 @@ void GeometryRenderer::activate(gfx::Device *device, const GeometryRendererInfo void GeometryRenderer::render(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, PipelineSceneData *sceneData) { update(); - const auto &passes = sceneData->getGeometryRendererPasses(); + const auto &passes = sceneData->getGeometryRendererPasses(); const auto &shaders = sceneData->getGeometryRendererShaders(); - uint32_t offset = 0U; + uint32_t offset = 0U; const uint32_t passCount[GEOMETRY_DEPTH_TYPE_COUNT] = {GEOMETRY_NO_DEPTH_TEST_PASS_NUM, GEOMETRY_DEPTH_TEST_PASS_NUM}; /** @@ -191,9 +191,9 @@ void GeometryRenderer::render(gfx::RenderPass *renderPass, gfx::CommandBuffer *c drawInfo.vertexCount = lines.getCount(); for (auto p = 0U; p < passCount[i]; p++) { - auto *pass = passes[offset + p]; + auto *pass = passes[offset + p]; auto *shader = shaders[offset + p]; - auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, lines._inputAssembler, renderPass); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, lines._inputAssembler, renderPass); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindInputAssembler(lines._inputAssembler); @@ -211,9 +211,9 @@ void GeometryRenderer::render(gfx::RenderPass *renderPass, gfx::CommandBuffer *c drawInfo.vertexCount = dashedLines.getCount(); for (auto p = 0U; p < passCount[i]; p++) { - auto *pass = passes[offset + p]; + auto *pass = passes[offset + p]; auto *shader = shaders[offset + p]; - auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, dashedLines._inputAssembler, renderPass); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, dashedLines._inputAssembler, renderPass); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindInputAssembler(dashedLines._inputAssembler); @@ -231,9 +231,9 @@ void GeometryRenderer::render(gfx::RenderPass *renderPass, gfx::CommandBuffer *c drawInfo.vertexCount = triangles.getCount(); for (auto p = 0U; p < passCount[i]; p++) { - auto *pass = passes[offset + p]; + auto *pass = passes[offset + p]; auto *shader = shaders[offset + p]; - auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, triangles._inputAssembler, renderPass); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, triangles._inputAssembler, renderPass); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindInputAssembler(triangles._inputAssembler); @@ -324,7 +324,7 @@ void GeometryRenderer::addTriangle(const Vec3 &v0, const Vec3 &v1, const Vec3 &v if (!unlit) { const Vec3 dist1 = v1 - v0; const Vec3 dist2 = v2 - v0; - Vec3 norm; + Vec3 norm; Vec3::crossProduct(dist1, dist2, &norm); norm.normalize(); normal.set(norm.x, norm.y, norm.z, 1.0F); @@ -438,10 +438,10 @@ void GeometryRenderer::addFrustum(const geometry::Frustum &frustum, gfx::Color c } void GeometryRenderer::addCapsule(const Vec3 ¢er, float radius, float height, gfx::Color color, uint32_t segmentsU, uint32_t hemiSegmentsV, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segmentsU); + const auto deltaPhi = math::PI_2 / static_cast(segmentsU); const auto deltaTheta = math::PI_DIV2 / static_cast(hemiSegmentsV); - Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; - Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; + Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; + Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; using CircleList = ccstd::vector; ccstd::vector bottomPoints; @@ -451,15 +451,15 @@ void GeometryRenderer::addCapsule(const Vec3 ¢er, float radius, float height CircleList bottomList; CircleList topList; - float theta = static_cast(i) * deltaTheta; + float theta = static_cast(i) * deltaTheta; float sinTheta = sinf(theta); float cosTheta = cosf(theta); for (auto j = 0U; j < segmentsU + 1; j++) { - float phi = static_cast(j) * deltaPhi; + float phi = static_cast(j) * deltaPhi; float sinPhi = sinf(phi); float cosPhi = cosf(phi); - Vec3 p{radius * sinTheta * cosPhi, radius * cosTheta, radius * sinTheta * sinPhi}; + Vec3 p{radius * sinTheta * cosPhi, radius * cosTheta, radius * sinTheta * sinPhi}; bottomList.emplace_back(bottomCenter + Vec3(p.x, -p.y, p.z)); topList.emplace_back(topCenter + p); @@ -489,7 +489,7 @@ void GeometryRenderer::addCapsule(const Vec3 ¢er, float radius, float height } CircleList &bottomCircle = bottomPoints[hemiSegmentsV]; - CircleList &topCircle = topPoints[hemiSegmentsV]; + CircleList &topCircle = topPoints[hemiSegmentsV]; for (auto j = 0U; j < segmentsU; j++) { addTriangle(topCircle[j], bottomCircle[j + 1], bottomCircle[j], color, wireframe, depthTest, unlit); addTriangle(topCircle[j], topCircle[j + 1], bottomCircle[j + 1], color, wireframe, depthTest, unlit); @@ -497,15 +497,15 @@ void GeometryRenderer::addCapsule(const Vec3 ¢er, float radius, float height } void GeometryRenderer::addCylinder(const Vec3 ¢er, float radius, float height, gfx::Color color, uint32_t segments, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segments); - Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; - Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; + const auto deltaPhi = math::PI_2 / static_cast(segments); + Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; + Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; ccstd::vector bottomPoints; ccstd::vector topPoints; for (auto i = 0U; i < segments + 1; i++) { float phi = static_cast(i) * deltaPhi; - Vec3 p{radius * cosf(phi), 0.0F, radius * sinf(phi)}; + Vec3 p{radius * cosf(phi), 0.0F, radius * sinf(phi)}; bottomPoints.emplace_back(p + bottomCenter); topPoints.emplace_back(p + topCenter); } @@ -530,9 +530,9 @@ void GeometryRenderer::addCylinder(const Vec3 ¢er, float radius, float heigh } void GeometryRenderer::addCone(const Vec3 ¢er, float radius, float height, gfx::Color color, uint32_t segments, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segments); - Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; - Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; + const auto deltaPhi = math::PI_2 / static_cast(segments); + Vec3 bottomCenter{center.x, center.y - height / 2.0F, center.z}; + Vec3 topCenter{center.x, center.y + height / 2.0F, center.z}; ccstd::vector bottomPoints; for (auto i = 0U; i < segments + 1; i++) { @@ -556,7 +556,7 @@ void GeometryRenderer::addCone(const Vec3 ¢er, float radius, float height, g } void GeometryRenderer::addCircle(const Vec3 ¢er, float radius, gfx::Color color, uint32_t segments, bool depthTest, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segments); + const auto deltaPhi = math::PI_2 / static_cast(segments); ccstd::vector points; for (auto i = 0U; i < segments + 1; i++) { @@ -576,9 +576,9 @@ void GeometryRenderer::addCircle(const Vec3 ¢er, float radius, gfx::Color co } void GeometryRenderer::addArc(const Vec3 ¢er, float radius, gfx::Color color, float startAngle, float endAngle, uint32_t segments, bool depthTest, bool useTransform, const Mat4 &transform) { - float startRadian = math::DEG_TO_RAD * startAngle; - float endRadian = math::DEG_TO_RAD * endAngle; - const auto deltaPhi = (endRadian - startRadian) / static_cast(segments); + float startRadian = math::DEG_TO_RAD * startAngle; + float endRadian = math::DEG_TO_RAD * endAngle; + const auto deltaPhi = (endRadian - startRadian) / static_cast(segments); ccstd::vector points; for (auto i = 0U; i < segments + 1; i++) { @@ -606,9 +606,9 @@ void GeometryRenderer::addPolygon(const Vec3 ¢er, float radius, gfx::Color c } void GeometryRenderer::addDisc(const Vec3 ¢er, float radius, gfx::Color color, uint32_t segments, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segments); + const auto deltaPhi = math::PI_2 / static_cast(segments); ccstd::vector points; - Vec3 newCenter = center; + Vec3 newCenter = center; for (auto i = 0U; i < segments + 1; i++) { Vec3 point{radius * cosf(static_cast(i) * deltaPhi), 0.0F, radius * sinf(static_cast(i) * deltaPhi)}; @@ -636,11 +636,11 @@ void GeometryRenderer::addDisc(const Vec3 ¢er, float radius, gfx::Color colo } void GeometryRenderer::addSector(const Vec3 ¢er, float radius, gfx::Color color, float startAngle, float endAngle, uint32_t segments, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - float startRadian = math::DEG_TO_RAD * startAngle; - float endRadian = math::DEG_TO_RAD * endAngle; - const auto deltaPhi = (endRadian - startRadian) / static_cast(segments); + float startRadian = math::DEG_TO_RAD * startAngle; + float endRadian = math::DEG_TO_RAD * endAngle; + const auto deltaPhi = (endRadian - startRadian) / static_cast(segments); ccstd::vector points; - Vec3 newCenter = center; + Vec3 newCenter = center; for (auto i = 0U; i < segments + 1; i++) { Vec3 point{radius * cosf(static_cast(i) * deltaPhi), 0.0F, radius * sinf(static_cast(i) * deltaPhi)}; @@ -668,7 +668,7 @@ void GeometryRenderer::addSector(const Vec3 ¢er, float radius, gfx::Color co } void GeometryRenderer::addSphere(const Vec3 ¢er, float radius, gfx::Color color, uint32_t segmentsU, uint32_t segmentsV, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segmentsU); + const auto deltaPhi = math::PI_2 / static_cast(segmentsU); const auto deltaTheta = math::PI / static_cast(segmentsV); using CircleList = ccstd::vector; @@ -676,15 +676,15 @@ void GeometryRenderer::addSphere(const Vec3 ¢er, float radius, gfx::Color co for (auto i = 0U; i < segmentsV + 1; i++) { CircleList list; - float theta = static_cast(i) * deltaTheta; - float sinTheta = sinf(theta); - float cosTheta = cosf(theta); + float theta = static_cast(i) * deltaTheta; + float sinTheta = sinf(theta); + float cosTheta = cosf(theta); for (auto j = 0U; j < segmentsU + 1; j++) { - float phi = static_cast(j) * deltaPhi; + float phi = static_cast(j) * deltaPhi; float sinPhi = sinf(phi); float cosPhi = cosf(phi); - Vec3 p{radius * sinTheta * cosPhi, radius * cosTheta, radius * sinTheta * sinPhi}; + Vec3 p{radius * sinTheta * cosPhi, radius * cosTheta, radius * sinTheta * sinPhi}; list.emplace_back(center + p); } @@ -709,7 +709,7 @@ void GeometryRenderer::addSphere(const Vec3 ¢er, float radius, gfx::Color co } void GeometryRenderer::addTorus(const Vec3 ¢er, float bigRadius, float radius, gfx::Color color, uint32_t segmentsU, uint32_t segmentsV, bool wireframe, bool depthTest, bool unlit, bool useTransform, const Mat4 &transform) { - const auto deltaPhi = math::PI_2 / static_cast(segmentsU); + const auto deltaPhi = math::PI_2 / static_cast(segmentsU); const auto deltaTheta = math::PI_2 / static_cast(segmentsV); using CircleList = ccstd::vector; @@ -717,15 +717,15 @@ void GeometryRenderer::addTorus(const Vec3 ¢er, float bigRadius, float radiu for (auto i = 0U; i < segmentsU + 1; i++) { CircleList list; - float phi = static_cast(i) * deltaPhi; - float sinPhi = sinf(phi); - float cosPhi = cosf(phi); + float phi = static_cast(i) * deltaPhi; + float sinPhi = sinf(phi); + float cosPhi = cosf(phi); for (auto j = 0U; j < segmentsV + 1; j++) { - float theta = static_cast(j) * deltaTheta; + float theta = static_cast(j) * deltaTheta; float sinTheta = sinf(theta); float cosTheta = cosf(theta); - Vec3 p{(bigRadius + radius * cosTheta) * cosPhi, radius * sinTheta, (bigRadius + radius * cosTheta) * sinPhi}; + Vec3 p{(bigRadius + radius * cosTheta) * cosPhi, radius * sinTheta, (bigRadius + radius * cosTheta) * sinPhi}; list.emplace_back(center + p); } @@ -793,7 +793,7 @@ void GeometryRenderer::addOctahedron(const Vec3 ¢er, float radius, gfx::Colo } void GeometryRenderer::addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, gfx::Color color, uint32_t segments, bool depthTest, bool useTransform, const Mat4 &transform) { - const auto deltaT = 1.0F / static_cast(segments); + const auto deltaT = 1.0F / static_cast(segments); ccstd::vector points; Vec3 newV0 = v0; @@ -825,7 +825,7 @@ void GeometryRenderer::addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, void GeometryRenderer::addSpline(const geometry::Spline &spline, gfx::Color color, uint32_t index, float knotSize, uint32_t segments, bool depthTest) { const auto numPoints = segments + 1; - auto points = spline.getPoints(numPoints, index); + auto points = spline.getPoints(numPoints, index); for (auto i = 0U; i < segments; i++) { addLine(points[i], points[i + 1], color, depthTest); @@ -833,8 +833,8 @@ void GeometryRenderer::addSpline(const geometry::Spline &spline, gfx::Color colo if (knotSize > 0.0F && index == geometry::SPLINE_WHOLE_INDEX) { const gfx::Color crossColor{1.0F - color.x, 1.0F - color.y, 1.0F - color.z, color.w}; - const auto numKnots = spline.getKnotCount(); - const auto & knots = spline.getKnots(); + const auto numKnots = spline.getKnotCount(); + const auto &knots = spline.getKnots(); for (auto i = 0U; i < numKnots; i++) { addCross(knots[i], knotSize, crossColor, depthTest); diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.h b/native/cocos/renderer/pipeline/GeometryRenderer.h index 08f7818ce8..51ed454889 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.h +++ b/native/cocos/renderer/pipeline/GeometryRenderer.h @@ -68,7 +68,7 @@ public: GeometryRenderer(); ~GeometryRenderer() override; GeometryRenderer(const GeometryRenderer &) = delete; - GeometryRenderer(GeometryRenderer &&) = delete; + GeometryRenderer(GeometryRenderer &&) = delete; GeometryRenderer &operator=(const GeometryRenderer &) = delete; GeometryRenderer &operator=(GeometryRenderer &&) = delete; @@ -104,7 +104,7 @@ private: void update(); void reset(); - gfx::Device * _device{nullptr}; + gfx::Device *_device{nullptr}; GeometryVertexBuffers *_buffers{nullptr}; }; diff --git a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp index 278951033a..36dfed3407 100644 --- a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp +++ b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp @@ -34,7 +34,7 @@ namespace pipeline { #define INIT_GLOBAL_DESCSET_LAYOUT(info) \ do { \ - globalDescriptorSetLayout.samplers[info::NAME] = info::LAYOUT; \ + globalDescriptorSetLayout.samplers[info::NAME] = info::LAYOUT; \ globalDescriptorSetLayout.bindings[info::BINDING] = info::DESCRIPTOR; \ } while (0) @@ -117,7 +117,7 @@ gfx::DescriptorSet *GlobalDSManager::getOrCreateDescriptorSet(uint32_t idx) { _descriptorSetMap.emplace(idx, descriptorSet); const auto begin = static_cast(PipelineGlobalBindings::UBO_GLOBAL); - const auto end = static_cast(PipelineGlobalBindings::COUNT); + const auto end = static_cast(PipelineGlobalBindings::COUNT); for (uint i = begin; i < end; ++i) { auto *const buffer = _globalDescriptorSet->getBuffer(i); if (buffer) descriptorSet->bindBuffer(i, buffer); @@ -159,56 +159,56 @@ void GlobalDSManager::destroy() { void GlobalDSManager::setDescriptorSetLayout() { globalDescriptorSetLayout.bindings.resize(static_cast(PipelineGlobalBindings::COUNT)); - globalDescriptorSetLayout.blocks[UBOGlobal::NAME] = UBOGlobal::LAYOUT; - globalDescriptorSetLayout.bindings[UBOGlobal::BINDING] = UBOGlobal::DESCRIPTOR; - globalDescriptorSetLayout.blocks[UBOCamera::NAME] = UBOCamera::LAYOUT; - globalDescriptorSetLayout.bindings[UBOCamera::BINDING] = UBOCamera::DESCRIPTOR; - globalDescriptorSetLayout.blocks[UBOShadow::NAME] = UBOShadow::LAYOUT; - globalDescriptorSetLayout.bindings[UBOShadow::BINDING] = UBOShadow::DESCRIPTOR; - globalDescriptorSetLayout.samplers[SHADOWMAP::NAME] = SHADOWMAP::LAYOUT; - globalDescriptorSetLayout.bindings[SHADOWMAP::BINDING] = SHADOWMAP::DESCRIPTOR; - globalDescriptorSetLayout.samplers[ENVIRONMENT::NAME] = ENVIRONMENT::LAYOUT; - globalDescriptorSetLayout.bindings[ENVIRONMENT::BINDING] = ENVIRONMENT::DESCRIPTOR; - globalDescriptorSetLayout.samplers[SPOTLIGHTINGMAP::NAME] = SPOTLIGHTINGMAP::LAYOUT; + globalDescriptorSetLayout.blocks[UBOGlobal::NAME] = UBOGlobal::LAYOUT; + globalDescriptorSetLayout.bindings[UBOGlobal::BINDING] = UBOGlobal::DESCRIPTOR; + globalDescriptorSetLayout.blocks[UBOCamera::NAME] = UBOCamera::LAYOUT; + globalDescriptorSetLayout.bindings[UBOCamera::BINDING] = UBOCamera::DESCRIPTOR; + globalDescriptorSetLayout.blocks[UBOShadow::NAME] = UBOShadow::LAYOUT; + globalDescriptorSetLayout.bindings[UBOShadow::BINDING] = UBOShadow::DESCRIPTOR; + globalDescriptorSetLayout.samplers[SHADOWMAP::NAME] = SHADOWMAP::LAYOUT; + globalDescriptorSetLayout.bindings[SHADOWMAP::BINDING] = SHADOWMAP::DESCRIPTOR; + globalDescriptorSetLayout.samplers[ENVIRONMENT::NAME] = ENVIRONMENT::LAYOUT; + globalDescriptorSetLayout.bindings[ENVIRONMENT::BINDING] = ENVIRONMENT::DESCRIPTOR; + globalDescriptorSetLayout.samplers[SPOTLIGHTINGMAP::NAME] = SPOTLIGHTINGMAP::LAYOUT; globalDescriptorSetLayout.bindings[SPOTLIGHTINGMAP::BINDING] = SPOTLIGHTINGMAP::DESCRIPTOR; - globalDescriptorSetLayout.samplers[DIFFUSEMAP::NAME] = DIFFUSEMAP::LAYOUT; - globalDescriptorSetLayout.bindings[DIFFUSEMAP::BINDING] = DIFFUSEMAP::DESCRIPTOR; + globalDescriptorSetLayout.samplers[DIFFUSEMAP::NAME] = DIFFUSEMAP::LAYOUT; + globalDescriptorSetLayout.bindings[DIFFUSEMAP::BINDING] = DIFFUSEMAP::DESCRIPTOR; localDescriptorSetLayout.bindings.resize(static_cast(ModelLocalBindings::COUNT)); - localDescriptorSetLayout.blocks[UBOLocalBatched::NAME] = UBOLocalBatched::LAYOUT; - localDescriptorSetLayout.bindings[UBOLocalBatched::BINDING] = UBOLocalBatched::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOLocal::NAME] = UBOLocal::LAYOUT; - localDescriptorSetLayout.bindings[UBOLocal::BINDING] = UBOLocal::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOWorldBound::NAME] = UBOWorldBound::LAYOUT; - localDescriptorSetLayout.bindings[UBOWorldBound::BINDING] = UBOWorldBound::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOForwardLight::NAME] = UBOForwardLight::LAYOUT; - localDescriptorSetLayout.bindings[UBOForwardLight::BINDING] = UBOForwardLight::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOSkinningTexture::NAME] = UBOSkinningTexture::LAYOUT; - localDescriptorSetLayout.bindings[UBOSkinningTexture::BINDING] = UBOSkinningTexture::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOSkinningAnimation::NAME] = UBOSkinningAnimation::LAYOUT; + localDescriptorSetLayout.blocks[UBOLocalBatched::NAME] = UBOLocalBatched::LAYOUT; + localDescriptorSetLayout.bindings[UBOLocalBatched::BINDING] = UBOLocalBatched::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOLocal::NAME] = UBOLocal::LAYOUT; + localDescriptorSetLayout.bindings[UBOLocal::BINDING] = UBOLocal::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOWorldBound::NAME] = UBOWorldBound::LAYOUT; + localDescriptorSetLayout.bindings[UBOWorldBound::BINDING] = UBOWorldBound::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOForwardLight::NAME] = UBOForwardLight::LAYOUT; + localDescriptorSetLayout.bindings[UBOForwardLight::BINDING] = UBOForwardLight::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOSkinningTexture::NAME] = UBOSkinningTexture::LAYOUT; + localDescriptorSetLayout.bindings[UBOSkinningTexture::BINDING] = UBOSkinningTexture::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOSkinningAnimation::NAME] = UBOSkinningAnimation::LAYOUT; localDescriptorSetLayout.bindings[UBOSkinningAnimation::BINDING] = UBOSkinningAnimation::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOSkinning::NAME] = UBOSkinning::LAYOUT; - localDescriptorSetLayout.bindings[UBOSkinning::BINDING] = UBOSkinning::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOMorph::NAME] = UBOMorph::LAYOUT; - localDescriptorSetLayout.bindings[UBOMorph::BINDING] = UBOMorph::DESCRIPTOR; - localDescriptorSetLayout.blocks[UBOUILocal::NAME] = UBOUILocal::LAYOUT; - localDescriptorSetLayout.bindings[UBOUILocal::BINDING] = UBOUILocal::DESCRIPTOR; - localDescriptorSetLayout.samplers[JOINTTEXTURE::NAME] = JOINTTEXTURE::LAYOUT; - localDescriptorSetLayout.bindings[JOINTTEXTURE::BINDING] = JOINTTEXTURE::DESCRIPTOR; - localDescriptorSetLayout.samplers[POSITIONMORPH::NAME] = POSITIONMORPH::LAYOUT; - localDescriptorSetLayout.bindings[POSITIONMORPH::BINDING] = POSITIONMORPH::DESCRIPTOR; - localDescriptorSetLayout.samplers[NORMALMORPH::NAME] = NORMALMORPH::LAYOUT; - localDescriptorSetLayout.bindings[NORMALMORPH::BINDING] = NORMALMORPH::DESCRIPTOR; - localDescriptorSetLayout.samplers[TANGENTMORPH::NAME] = TANGENTMORPH::LAYOUT; - localDescriptorSetLayout.bindings[TANGENTMORPH::BINDING] = TANGENTMORPH::DESCRIPTOR; - localDescriptorSetLayout.samplers[LIGHTMAPTEXTURE::NAME] = LIGHTMAPTEXTURE::LAYOUT; - localDescriptorSetLayout.bindings[LIGHTMAPTEXTURE::BINDING] = LIGHTMAPTEXTURE::DESCRIPTOR; - localDescriptorSetLayout.samplers[SPRITETEXTURE::NAME] = SPRITETEXTURE::LAYOUT; - localDescriptorSetLayout.bindings[SPRITETEXTURE::BINDING] = SPRITETEXTURE::DESCRIPTOR; - localDescriptorSetLayout.samplers[REFLECTIONTEXTURE::NAME] = REFLECTIONTEXTURE::LAYOUT; - localDescriptorSetLayout.bindings[REFLECTIONTEXTURE::BINDING] = REFLECTIONTEXTURE::DESCRIPTOR; - localDescriptorSetLayout.storeImages[REFLECTIONSTORAGE::NAME] = REFLECTIONSTORAGE::LAYOUT; - localDescriptorSetLayout.bindings[REFLECTIONSTORAGE::BINDING] = REFLECTIONSTORAGE::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOSkinning::NAME] = UBOSkinning::LAYOUT; + localDescriptorSetLayout.bindings[UBOSkinning::BINDING] = UBOSkinning::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOMorph::NAME] = UBOMorph::LAYOUT; + localDescriptorSetLayout.bindings[UBOMorph::BINDING] = UBOMorph::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOUILocal::NAME] = UBOUILocal::LAYOUT; + localDescriptorSetLayout.bindings[UBOUILocal::BINDING] = UBOUILocal::DESCRIPTOR; + localDescriptorSetLayout.samplers[JOINTTEXTURE::NAME] = JOINTTEXTURE::LAYOUT; + localDescriptorSetLayout.bindings[JOINTTEXTURE::BINDING] = JOINTTEXTURE::DESCRIPTOR; + localDescriptorSetLayout.samplers[POSITIONMORPH::NAME] = POSITIONMORPH::LAYOUT; + localDescriptorSetLayout.bindings[POSITIONMORPH::BINDING] = POSITIONMORPH::DESCRIPTOR; + localDescriptorSetLayout.samplers[NORMALMORPH::NAME] = NORMALMORPH::LAYOUT; + localDescriptorSetLayout.bindings[NORMALMORPH::BINDING] = NORMALMORPH::DESCRIPTOR; + localDescriptorSetLayout.samplers[TANGENTMORPH::NAME] = TANGENTMORPH::LAYOUT; + localDescriptorSetLayout.bindings[TANGENTMORPH::BINDING] = TANGENTMORPH::DESCRIPTOR; + localDescriptorSetLayout.samplers[LIGHTMAPTEXTURE::NAME] = LIGHTMAPTEXTURE::LAYOUT; + localDescriptorSetLayout.bindings[LIGHTMAPTEXTURE::BINDING] = LIGHTMAPTEXTURE::DESCRIPTOR; + localDescriptorSetLayout.samplers[SPRITETEXTURE::NAME] = SPRITETEXTURE::LAYOUT; + localDescriptorSetLayout.bindings[SPRITETEXTURE::BINDING] = SPRITETEXTURE::DESCRIPTOR; + localDescriptorSetLayout.samplers[REFLECTIONTEXTURE::NAME] = REFLECTIONTEXTURE::LAYOUT; + localDescriptorSetLayout.bindings[REFLECTIONTEXTURE::BINDING] = REFLECTIONTEXTURE::DESCRIPTOR; + localDescriptorSetLayout.storeImages[REFLECTIONSTORAGE::NAME] = REFLECTIONSTORAGE::LAYOUT; + localDescriptorSetLayout.bindings[REFLECTIONSTORAGE::BINDING] = REFLECTIONSTORAGE::DESCRIPTOR; } } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.h b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.h index e6559241bc..2a4732fb04 100644 --- a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.h +++ b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.h @@ -43,33 +43,33 @@ namespace pipeline { class GlobalDSManager final { public: - GlobalDSManager() = default; + GlobalDSManager() = default; ~GlobalDSManager() = default; inline ccstd::unordered_map getDescriptorSetMap() const { return _descriptorSetMap; } - inline gfx::Sampler * getLinearSampler() const { return _linearSampler; } - inline gfx::Sampler * getPointSampler() const { return _pointSampler; } - inline gfx::DescriptorSetLayout * getDescriptorSetLayout() const { return _descriptorSetLayout; } - inline gfx::DescriptorSet * getGlobalDescriptorSet() const { return _globalDescriptorSet; } + inline gfx::Sampler *getLinearSampler() const { return _linearSampler; } + inline gfx::Sampler *getPointSampler() const { return _pointSampler; } + inline gfx::DescriptorSetLayout *getDescriptorSetLayout() const { return _descriptorSetLayout; } + inline gfx::DescriptorSet *getGlobalDescriptorSet() const { return _globalDescriptorSet; } - void activate(gfx::Device *device); - void bindBuffer(uint32_t binding, gfx::Buffer *buffer); - void bindTexture(uint32_t binding, gfx::Texture *texture); - void bindSampler(uint32_t binding, gfx::Sampler *sampler); - void update(); + void activate(gfx::Device *device); + void bindBuffer(uint32_t binding, gfx::Buffer *buffer); + void bindTexture(uint32_t binding, gfx::Texture *texture); + void bindSampler(uint32_t binding, gfx::Sampler *sampler); + void update(); gfx::DescriptorSet *getOrCreateDescriptorSet(uint32_t idx); - void destroy(); + void destroy(); static void setDescriptorSetLayout(); private: - gfx::Device * _device = nullptr; - gfx::Sampler * _linearSampler = nullptr; - gfx::Sampler * _pointSampler = nullptr; - IntrusivePtr _descriptorSetLayout; - gfx::DescriptorSet * _globalDescriptorSet = nullptr; + gfx::Device *_device = nullptr; + gfx::Sampler *_linearSampler = nullptr; + gfx::Sampler *_pointSampler = nullptr; + IntrusivePtr _descriptorSetLayout; + gfx::DescriptorSet *_globalDescriptorSet = nullptr; ccstd::unordered_map _descriptorSetMap{}; - ccstd::vector _shadowUBOs; + ccstd::vector _shadowUBOs; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index b6305a4cc6..ce3eaf0df8 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -34,7 +34,7 @@ namespace cc { namespace pipeline { ccstd::unordered_map> InstancedBuffer::buffers; -InstancedBuffer * InstancedBuffer::get(scene::Pass *pass) { +InstancedBuffer *InstancedBuffer::get(scene::Pass *pass) { return InstancedBuffer::get(pass, 0); } InstancedBuffer *InstancedBuffer::get(scene::Pass *pass, uint extraKey) { @@ -79,14 +79,14 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su } void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *subModel, uint passIdx, gfx::Shader *shaderImplant) { - auto stride = model->getInstancedBufferSize(); + auto stride = model->getInstancedBufferSize(); const auto *instancedBuffer = model->getInstancedBuffer(); if (!stride) return; // we assume per-instance attributes are always present - auto *sourceIA = subModel->getInputAssembler(); + auto *sourceIA = subModel->getInputAssembler(); auto *descriptorSet = subModel->getDescriptorSet(); - auto *lightingMap = descriptorSet->getTexture(LIGHTMAPTEXTURE::BINDING); - auto *shader = shaderImplant; + auto *lightingMap = descriptorSet->getTexture(LIGHTMAPTEXTURE::BINDING); + auto *shader = shaderImplant; if (!shader) { shader = subModel->getShader(passIdx); } @@ -107,7 +107,7 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su if (instance.count >= instance.capacity) { // resize buffers instance.capacity <<= 1; const auto newSize = instance.stride * instance.capacity; - instance.data = static_cast(CC_REALLOC(instance.data, newSize)); + instance.data = static_cast(CC_REALLOC(instance.data, newSize)); instance.vb->resize(newSize); } if (instance.shader != shader) { @@ -122,17 +122,17 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su } // Create a new instance - auto newSize = stride * INITIAL_CAPACITY; - auto *vb = _device->createBuffer({ + auto newSize = stride * INITIAL_CAPACITY; + auto *vb = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, static_cast(newSize), static_cast(stride), }); - auto vertexBuffers = sourceIA->getVertexBuffers(); - auto attributes = sourceIA->getAttributes(); - auto *indexBuffer = sourceIA->getIndexBuffer(); + auto vertexBuffers = sourceIA->getVertexBuffers(); + auto attributes = sourceIA->getAttributes(); + auto *indexBuffer = sourceIA->getIndexBuffer(); for (const auto &attribute : model->getInstanceAttributes()) { attributes.emplace_back(gfx::Attribute{ @@ -148,8 +148,8 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su memcpy(data, instancedBuffer, stride); vertexBuffers.emplace_back(vb); gfx::InputAssemblerInfo iaInfo = {attributes, vertexBuffers, indexBuffer}; - auto * ia = _device->createInputAssembler(iaInfo); - InstancedItem item = {1, INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap}; + auto *ia = _device->createInputAssembler(iaInfo); + InstancedItem item = {1, INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap}; _instances.emplace_back(item); _hasPendingModels = true; } diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.h b/native/cocos/renderer/pipeline/InstancedBuffer.h index 4fbcb59414..bbd2df3b58 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.h +++ b/native/cocos/renderer/pipeline/InstancedBuffer.h @@ -43,26 +43,26 @@ struct PSOInfo; #endif struct CC_DLL InstancedItem { - uint count = 0; - uint capacity = 0; - gfx::Buffer * vb = nullptr; - uint8_t * data = nullptr; - gfx::InputAssembler *ia = nullptr; - uint stride = 0; - gfx::Shader * shader = nullptr; - gfx::DescriptorSet * descriptorSet = nullptr; - gfx::Texture * lightingMap = nullptr; + uint count = 0; + uint capacity = 0; + gfx::Buffer *vb = nullptr; + uint8_t *data = nullptr; + gfx::InputAssembler *ia = nullptr; + uint stride = 0; + gfx::Shader *shader = nullptr; + gfx::DescriptorSet *descriptorSet = nullptr; + gfx::Texture *lightingMap = nullptr; }; using InstancedItemList = ccstd::vector; using DynamicOffsetList = ccstd::vector; class InstancedBuffer : public RefCounted { public: - static constexpr uint INITIAL_CAPACITY = 32; - static constexpr uint MAX_CAPACITY = 1024; + static constexpr uint INITIAL_CAPACITY = 32; + static constexpr uint MAX_CAPACITY = 1024; static InstancedBuffer *get(scene::Pass *pass); static InstancedBuffer *get(scene::Pass *, uint extraKey); - static void destroyInstancedBuffer(); + static void destroyInstancedBuffer(); explicit InstancedBuffer(const scene::Pass *pass); ~InstancedBuffer() override; @@ -75,17 +75,17 @@ public: void setDynamicOffset(uint idx, uint value); inline const InstancedItemList &getInstances() const { return _instances; } - inline const scene::Pass * getPass() const { return _pass; } - inline bool hasPendingModels() const { return _hasPendingModels; } + inline const scene::Pass *getPass() const { return _pass; } + inline bool hasPendingModels() const { return _hasPendingModels; } inline const DynamicOffsetList &dynamicOffsets() const { return _dynamicOffsets; } private: static ccstd::unordered_map> buffers; - InstancedItemList _instances; - const scene::Pass * _pass = nullptr; - bool _hasPendingModels = false; - DynamicOffsetList _dynamicOffsets; - gfx::Device * _device = nullptr; + InstancedItemList _instances; + const scene::Pass *_pass = nullptr; + bool _hasPendingModels = false; + DynamicOffsetList _dynamicOffsets; + gfx::Device *_device = nullptr; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.cpp b/native/cocos/renderer/pipeline/PipelineSceneData.cpp index d3285f2997..4de6dcb833 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.cpp +++ b/native/cocos/renderer/pipeline/PipelineSceneData.cpp @@ -41,11 +41,11 @@ namespace cc { namespace pipeline { PipelineSceneData::PipelineSceneData() { - _fog = ccnew scene::Fog(); // cjh how to delete? + _fog = ccnew scene::Fog(); // cjh how to delete? _ambient = ccnew scene::Ambient(); - _skybox = ccnew scene::Skybox(); - _shadow = ccnew scene::Shadows(); - _octree = ccnew scene::Octree(); + _skybox = ccnew scene::Skybox(); + _shadow = ccnew scene::Shadows(); + _octree = ccnew scene::Octree(); } PipelineSceneData::~PipelineSceneData() { @@ -88,7 +88,7 @@ void PipelineSceneData::initOcclusionQuery() { IMaterialInfo info; info.effectName = "occlusion-query"; _occlusionQueryMaterial->initialize(info); - _occlusionQueryPass = (*_occlusionQueryMaterial->getPasses())[0]; + _occlusionQueryPass = (*_occlusionQueryMaterial->getPasses())[0]; _occlusionQueryShader = _occlusionQueryPass->getShaderVariant(); } } @@ -107,7 +107,7 @@ void PipelineSceneData::initGeometryRenderer() { IMaterialInfo materialInfo; materialInfo.effectName = "geometry-renderer"; - materialInfo.technique = tech; + materialInfo.technique = tech; _geometryRendererMaterials[tech]->initialize(materialInfo); const auto &passes = _geometryRendererMaterials[tech]->getPasses().get(); @@ -125,7 +125,7 @@ void PipelineSceneData::initDebugRenderer() { IMaterialInfo info; info.effectName = "debug-renderer"; _debugRendererMaterial->initialize(info); - _debugRendererPass = (*_debugRendererMaterial->getPasses())[0]; + _debugRendererPass = (*_debugRendererMaterial->getPasses())[0]; _debugRendererShader = _debugRendererPass->getShaderVariant(); } } @@ -142,8 +142,8 @@ scene::Pass *PipelineSceneData::getOcclusionQueryPass() { gfx::InputAssembler *PipelineSceneData::createOcclusionQueryIA() { // create vertex buffer const float vertices[] = {-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1}; - uint32_t vbStride = sizeof(float) * 3; - uint32_t vbSize = vbStride * 8; + uint32_t vbStride = sizeof(float) * 3; + uint32_t vbSize = vbStride * 8; _occlusionQueryVertexBuffer = _device->createBuffer(gfx::BufferInfo{ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, @@ -151,9 +151,9 @@ gfx::InputAssembler *PipelineSceneData::createOcclusionQueryIA() { _occlusionQueryVertexBuffer->update(vertices); // create index buffer - const uint16_t indices[] = {0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 1, 3, 7, 1, 7, 5, 0, 4, 6, 0, 6, 2, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3}; - uint32_t ibStride = sizeof(uint16_t); - uint32_t ibSize = ibStride * 36; + const uint16_t indices[] = {0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 1, 3, 7, 1, 7, 5, 0, 4, 6, 0, 6, 2, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3}; + uint32_t ibStride = sizeof(uint16_t); + uint32_t ibSize = ibStride * 36; _occlusionQueryIndicesBuffer = _device->createBuffer(gfx::BufferInfo{ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, ibSize, ibStride}); diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.h b/native/cocos/renderer/pipeline/PipelineSceneData.h index 373daca4b5..7df2294fcc 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.h +++ b/native/cocos/renderer/pipeline/PipelineSceneData.h @@ -51,80 +51,80 @@ public: PipelineSceneData(); ~PipelineSceneData() override; virtual void activate(gfx::Device *device); - void destroy(); + void destroy(); virtual void updatePipelineSceneData() {} - inline void setShadowFramebuffer(const scene::Light *light, gfx::Framebuffer *framebuffer) { _shadowFrameBufferMap.emplace(light, framebuffer); } + inline void setShadowFramebuffer(const scene::Light *light, gfx::Framebuffer *framebuffer) { _shadowFrameBufferMap.emplace(light, framebuffer); } inline const ccstd::unordered_map &getShadowFramebufferMap() const { return _shadowFrameBufferMap; } - inline const RenderObjectList & getRenderObjects() const { return _renderObjects; } - inline const RenderObjectList & getDirShadowObjects() const { return _dirShadowObjects; } - inline void setRenderObjects(RenderObjectList &&ro) { _renderObjects = std::forward(ro); } - inline void setDirShadowObjects(RenderObjectList &&ro) { _dirShadowObjects = std::forward(ro); } - inline const RenderObjectList & isCastShadowObjects() const { return _castShadowObjects; } - inline void setCastShadowObjects(RenderObjectList &&ro) { _castShadowObjects = std::forward(ro); } - inline const ccstd::vector & getValidPunctualLights() const { return _validPunctualLights; } - inline void setValidPunctualLights(ccstd::vector &&validPunctualLights) { _validPunctualLights = std::forward>(validPunctualLights); } - inline bool isHDR() const { return _isHDR; } - inline void setHDR(bool val) { _isHDR = val; } - inline scene::Shadows * getShadows() const { return _shadow; } - inline scene::Ambient * getAmbient() const { return _ambient; } - inline scene::Skybox * getSkybox() const { return _skybox; } - inline scene::Fog * getFog() const { return _fog; } - inline scene::Octree * getOctree() const { return _octree; } - inline gfx::InputAssembler * getOcclusionQueryInputAssembler() const { return _occlusionQueryInputAssembler; } - inline scene::Pass * getOcclusionQueryPass() const { return _occlusionQueryPass; } - inline gfx::Shader * getOcclusionQueryShader() const { return _occlusionQueryShader; } - inline const ccstd::vector> & getGeometryRendererMaterials() const { return _geometryRendererMaterials; } - inline const ccstd::vector & getGeometryRendererPasses() const { return _geometryRendererPasses; } - inline const ccstd::vector & getGeometryRendererShaders() const { return _geometryRendererShaders; } - inline scene::Pass * getDebugRendererPass() const { return _debugRendererPass; } - inline gfx::Shader * getDebugRendererShader() const { return _debugRendererShader; } - inline void addRenderObject(RenderObject &&obj) { _renderObjects.emplace_back(obj); } - inline void clearRenderObjects() { _renderObjects.clear(); } - inline void addValidPunctualLight(scene::Light *light) { _validPunctualLights.emplace_back(light); } - inline void clearValidPunctualLights() { _validPunctualLights.clear(); } - inline float getShadingScale() const { return _shadingScale; } - inline void setShadingScale(float val) { _shadingScale = val; } + inline const RenderObjectList &getRenderObjects() const { return _renderObjects; } + inline const RenderObjectList &getDirShadowObjects() const { return _dirShadowObjects; } + inline void setRenderObjects(RenderObjectList &&ro) { _renderObjects = std::forward(ro); } + inline void setDirShadowObjects(RenderObjectList &&ro) { _dirShadowObjects = std::forward(ro); } + inline const RenderObjectList &isCastShadowObjects() const { return _castShadowObjects; } + inline void setCastShadowObjects(RenderObjectList &&ro) { _castShadowObjects = std::forward(ro); } + inline const ccstd::vector &getValidPunctualLights() const { return _validPunctualLights; } + inline void setValidPunctualLights(ccstd::vector &&validPunctualLights) { _validPunctualLights = std::forward>(validPunctualLights); } + inline bool isHDR() const { return _isHDR; } + inline void setHDR(bool val) { _isHDR = val; } + inline scene::Shadows *getShadows() const { return _shadow; } + inline scene::Ambient *getAmbient() const { return _ambient; } + inline scene::Skybox *getSkybox() const { return _skybox; } + inline scene::Fog *getFog() const { return _fog; } + inline scene::Octree *getOctree() const { return _octree; } + inline gfx::InputAssembler *getOcclusionQueryInputAssembler() const { return _occlusionQueryInputAssembler; } + inline scene::Pass *getOcclusionQueryPass() const { return _occlusionQueryPass; } + inline gfx::Shader *getOcclusionQueryShader() const { return _occlusionQueryShader; } + inline const ccstd::vector> &getGeometryRendererMaterials() const { return _geometryRendererMaterials; } + inline const ccstd::vector &getGeometryRendererPasses() const { return _geometryRendererPasses; } + inline const ccstd::vector &getGeometryRendererShaders() const { return _geometryRendererShaders; } + inline scene::Pass *getDebugRendererPass() const { return _debugRendererPass; } + inline gfx::Shader *getDebugRendererShader() const { return _debugRendererShader; } + inline void addRenderObject(RenderObject &&obj) { _renderObjects.emplace_back(obj); } + inline void clearRenderObjects() { _renderObjects.clear(); } + inline void addValidPunctualLight(scene::Light *light) { _validPunctualLights.emplace_back(light); } + inline void clearValidPunctualLights() { _validPunctualLights.clear(); } + inline float getShadingScale() const { return _shadingScale; } + inline void setShadingScale(float val) { _shadingScale = val; } scene::Pass *getOcclusionQueryPass(); protected: - void initOcclusionQuery(); - void initGeometryRenderer(); - void initDebugRenderer(); + void initOcclusionQuery(); + void initGeometryRenderer(); + void initDebugRenderer(); gfx::InputAssembler *createOcclusionQueryIA(); static constexpr uint32_t GEOMETRY_RENDERER_TECHNIQUE_COUNT{6}; - RenderObjectList _renderObjects; - RenderObjectList _dirShadowObjects; - RenderObjectList _castShadowObjects; + RenderObjectList _renderObjects; + RenderObjectList _dirShadowObjects; + RenderObjectList _castShadowObjects; ccstd::vector _validPunctualLights; - gfx::Buffer * _occlusionQueryVertexBuffer{nullptr}; - gfx::Buffer * _occlusionQueryIndicesBuffer{nullptr}; - gfx::InputAssembler * _occlusionQueryInputAssembler{nullptr}; + gfx::Buffer *_occlusionQueryVertexBuffer{nullptr}; + gfx::Buffer *_occlusionQueryIndicesBuffer{nullptr}; + gfx::InputAssembler *_occlusionQueryInputAssembler{nullptr}; IntrusivePtr _occlusionQueryMaterial{nullptr}; - gfx::Shader * _occlusionQueryShader{nullptr}; // weak reference - scene::Pass * _occlusionQueryPass{nullptr}; // weak reference + gfx::Shader *_occlusionQueryShader{nullptr}; // weak reference + scene::Pass *_occlusionQueryPass{nullptr}; // weak reference ccstd::vector> _geometryRendererMaterials; - ccstd::vector _geometryRendererPasses; // weak reference - ccstd::vector _geometryRendererShaders; // weak reference + ccstd::vector _geometryRendererPasses; // weak reference + ccstd::vector _geometryRendererShaders; // weak reference IntrusivePtr _debugRendererMaterial{nullptr}; - gfx::Shader * _debugRendererShader{nullptr}; - scene::Pass * _debugRendererPass{nullptr}; - gfx::Device * _device{nullptr}; + gfx::Shader *_debugRendererShader{nullptr}; + scene::Pass *_debugRendererPass{nullptr}; + gfx::Device *_device{nullptr}; - scene::Fog * _fog{nullptr}; + scene::Fog *_fog{nullptr}; scene::Ambient *_ambient{nullptr}; - scene::Skybox * _skybox{nullptr}; + scene::Skybox *_skybox{nullptr}; scene::Shadows *_shadow{nullptr}; - scene::Octree * _octree{nullptr}; - bool _isHDR{true}; - float _shadingScale{1.0F}; + scene::Octree *_octree{nullptr}; + bool _isHDR{true}; + float _shadingScale{1.0F}; ccstd::unordered_map _shadowFrameBufferMap; }; diff --git a/native/cocos/renderer/pipeline/PipelineStateManager.cpp b/native/cocos/renderer/pipeline/PipelineStateManager.cpp index 64524d6941..511f528546 100644 --- a/native/cocos/renderer/pipeline/PipelineStateManager.cpp +++ b/native/cocos/renderer/pipeline/PipelineStateManager.cpp @@ -33,16 +33,16 @@ namespace pipeline { ccstd::unordered_map> PipelineStateManager::psoHashMap; -gfx::PipelineState *PipelineStateManager::getOrCreatePipelineState(const scene::Pass * pass, - gfx::Shader * shader, +gfx::PipelineState *PipelineStateManager::getOrCreatePipelineState(const scene::Pass *pass, + gfx::Shader *shader, gfx::InputAssembler *inputAssembler, - gfx::RenderPass * renderPass, - uint subpass) { - const auto passHash = pass->getHash(); + gfx::RenderPass *renderPass, + uint subpass) { + const auto passHash = pass->getHash(); const auto renderPassHash = renderPass->getHash(); - const auto iaHash = inputAssembler->getAttributesHash(); - const auto shaderID = shader->getTypedID(); - auto hash = passHash ^ renderPassHash ^ iaHash ^ shaderID; + const auto iaHash = inputAssembler->getAttributesHash(); + const auto shaderID = shader->getTypedID(); + auto hash = passHash ^ renderPassHash ^ iaHash ^ shaderID; if (subpass != 0) { hash = hash << subpass; } diff --git a/native/cocos/renderer/pipeline/PipelineStateManager.h b/native/cocos/renderer/pipeline/PipelineStateManager.h index a7ff715625..31f1567d6f 100644 --- a/native/cocos/renderer/pipeline/PipelineStateManager.h +++ b/native/cocos/renderer/pipeline/PipelineStateManager.h @@ -36,12 +36,12 @@ namespace pipeline { class CC_DLL PipelineStateManager { public: - static gfx::PipelineState *getOrCreatePipelineState(const scene::Pass * pass, - gfx::Shader * shader, + static gfx::PipelineState *getOrCreatePipelineState(const scene::Pass *pass, + gfx::Shader *shader, gfx::InputAssembler *inputAssembler, - gfx::RenderPass * renderPass, - uint subpass = 0); - static void destroyAll(); + gfx::RenderPass *renderPass, + uint subpass = 0); + static void destroyAll(); private: static ccstd::unordered_map> psoHashMap; diff --git a/native/cocos/renderer/pipeline/PipelineUBO.cpp b/native/cocos/renderer/pipeline/PipelineUBO.cpp index f4ed5bd941..4475ee098b 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.cpp +++ b/native/cocos/renderer/pipeline/PipelineUBO.cpp @@ -56,11 +56,11 @@ namespace pipeline { Mat4 matShadowViewProj; void PipelineUBO::updateGlobalUBOView(const scene::Camera *camera, ccstd::array *bufferView) { - auto *const root = Root::getInstance(); - const gfx::Device * device = gfx::Device::getInstance(); + auto *const root = Root::getInstance(); + const gfx::Device *device = gfx::Device::getInstance(); ccstd::array &uboGlobalView = *bufferView; - const auto shadingWidth = std::floor(camera->getWindow()->getWidth()); + const auto shadingWidth = std::floor(camera->getWindow()->getWidth()); const auto shadingHeight = std::floor(camera->getWindow()->getHeight()); // update UBOGlobal @@ -80,17 +80,17 @@ void PipelineUBO::updateGlobalUBOView(const scene::Camera *camera, ccstd::array< } void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera) { - const auto *const scene = camera->getScene(); - const scene::DirectionalLight *mainLight = scene->getMainLight(); - const auto * sceneData = pipeline->getPipelineSceneData(); - const scene::Shadows *const shadowInfo = sceneData->getShadows(); - const auto * ambient = sceneData->getAmbient(); - auto * fog = sceneData->getFog(); - const auto isHDR = sceneData->isHDR(); + const auto *const scene = camera->getScene(); + const scene::DirectionalLight *mainLight = scene->getMainLight(); + const auto *sceneData = pipeline->getPipelineSceneData(); + const scene::Shadows *const shadowInfo = sceneData->getShadows(); + const auto *ambient = sceneData->getAmbient(); + auto *fog = sceneData->getFog(); + const auto isHDR = sceneData->isHDR(); auto *device = gfx::Device::getInstance(); - const auto shadingWidth = static_cast(std::floor(camera->getWindow()->getWidth())); + const auto shadingWidth = static_cast(std::floor(camera->getWindow()->getWidth())); const auto shadingHeight = static_cast(std::floor(camera->getWindow()->getHeight())); output[UBOCamera::SCREEN_SCALE_OFFSET + 0] = sceneData->getShadingScale(); @@ -98,7 +98,7 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out output[UBOCamera::SCREEN_SCALE_OFFSET + 2] = 1.0F / output[UBOCamera::SCREEN_SCALE_OFFSET]; output[UBOCamera::SCREEN_SCALE_OFFSET + 3] = 1.0F / output[UBOCamera::SCREEN_SCALE_OFFSET + 1]; - const auto exposure = camera->getExposure(); + const auto exposure = camera->getExposure(); output[UBOCamera::EXPOSURE_OFFSET + 0] = exposure; output[UBOCamera::EXPOSURE_OFFSET + 1] = 1.0F / exposure; output[UBOCamera::EXPOSURE_OFFSET + 2] = isHDR ? 1.0F : 0.0F; @@ -106,7 +106,7 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out if (mainLight) { const float shadowEnable = (mainLight->isShadowEnabled() && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) ? 1.0F : 0.0F; - const Vec4 lightDir(mainLight->getDirection().x, mainLight->getDirection().y, mainLight->getDirection().z, shadowEnable); + const Vec4 lightDir(mainLight->getDirection().x, mainLight->getDirection().y, mainLight->getDirection().z, shadowEnable); TO_VEC4(output, lightDir, UBOCamera::MAIN_LIT_DIR_OFFSET) TO_VEC3(output, mainLight->getColor(), UBOCamera::MAIN_LIT_COLOR_OFFSET) if (mainLight->isUseColorTemperature()) { @@ -140,7 +140,7 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out output[UBOCamera::AMBIENT_SKY_OFFSET + 2] = skyColor.z; output[UBOCamera::AMBIENT_SKY_OFFSET + 3] = skyColor.w; - const auto &groundAlbedo = ambient->getGroundAlbedo(); + const auto &groundAlbedo = ambient->getGroundAlbedo(); output[UBOCamera::AMBIENT_GROUND_OFFSET + 0] = groundAlbedo.x; output[UBOCamera::AMBIENT_GROUND_OFFSET + 1] = groundAlbedo.y; output[UBOCamera::AMBIENT_GROUND_OFFSET + 2] = groundAlbedo.z; @@ -165,8 +165,8 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out output[UBOCamera::SURFACE_TRANSFORM_OFFSET + 0] = static_cast(camera->getSurfaceTransform()); if (fog != nullptr) { - const auto &colorTempRGB = fog->getColorArray(); - output[UBOCamera::GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; + const auto &colorTempRGB = fog->getColorArray(); + output[UBOCamera::GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; output[UBOCamera::GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y; output[UBOCamera::GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z; output[UBOCamera::GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z; @@ -190,28 +190,28 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out } void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Camera *camera) { - const scene::RenderScene *const scene = camera->getScene(); - const scene::DirectionalLight * mainLight = scene->getMainLight(); - gfx::Device * device = gfx::Device::getInstance(); - const PipelineSceneData * sceneData = pipeline->getPipelineSceneData(); - scene::Shadows *const shadowInfo = sceneData->getShadows(); - ccstd::array &shadowUBO = *bufferView; - const bool hFTexture = supportsR32FloatTexture(device); + const scene::RenderScene *const scene = camera->getScene(); + const scene::DirectionalLight *mainLight = scene->getMainLight(); + gfx::Device *device = gfx::Device::getInstance(); + const PipelineSceneData *sceneData = pipeline->getPipelineSceneData(); + scene::Shadows *const shadowInfo = sceneData->getShadows(); + ccstd::array &shadowUBO = *bufferView; + const bool hFTexture = supportsR32FloatTexture(device); if (shadowInfo->isEnabled()) { if (mainLight && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) { - const Mat4 &matShadowView = shadowInfo->getMatShadowView(); - const Mat4 &matShadowProj = shadowInfo->getMatShadowProj(); + const Mat4 &matShadowView = shadowInfo->getMatShadowView(); + const Mat4 &matShadowProj = shadowInfo->getMatShadowProj(); const Mat4 &matShadowViewProj = shadowInfo->getMatShadowViewProj(); float nearClamp; float farClamp; if (mainLight->isShadowFixedArea()) { nearClamp = mainLight->getShadowNear(); - farClamp = mainLight->getShadowFar(); + farClamp = mainLight->getShadowFar(); } else { nearClamp = 1.0F; - farClamp = shadowInfo->getShadowCameraFar(); + farClamp = shadowInfo->getShadowCameraFar(); } memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView)); @@ -224,14 +224,14 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET, matShadowViewProj.m, sizeof(matShadowViewProj)); - const float linear = 0.0F; + const float linear = 0.0F; const float shadowNFLSInfos[4] = {nearClamp, farClamp, linear, 1.0F - mainLight->getShadowSaturation()}; memcpy(shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos)); const float shadowWHPBInfos[4] = {shadowInfo->getSize().x, shadowInfo->getSize().y, mainLight->getShadowPcf(), mainLight->getShadowBias()}; memcpy(shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos)); - const float packing = hFTexture ? 0.0F : 1.0F; + const float packing = hFTexture ? 0.0F : 1.0F; const float shadowLPNNInfos[4] = {0.0F, packing, mainLight->getShadowNormalBias(), 0.0F}; memcpy(shadowUBO.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos)); } else if (mainLight && shadowInfo->getType() == scene::ShadowType::PLANAR) { @@ -245,28 +245,28 @@ void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, ccstd::arr void PipelineUBO::updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Light *light) { - const auto *sceneData = pipeline->getPipelineSceneData(); + const auto *sceneData = pipeline->getPipelineSceneData(); const auto *shadowInfo = sceneData->getShadows(); - auto * device = gfx::Device::getInstance(); - auto & shadowUBO = *bufferView; - const bool hFTexture = supportsR32FloatTexture(device); - const float linear = 0.0F; - const float packing = hFTexture ? 0.0F : 1.0F; + auto *device = gfx::Device::getInstance(); + auto &shadowUBO = *bufferView; + const bool hFTexture = supportsR32FloatTexture(device); + const float linear = 0.0F; + const float packing = hFTexture ? 0.0F : 1.0F; switch (light->getType()) { case scene::LightType::DIRECTIONAL: { - const auto *mainLight = static_cast(light); - const Mat4 &matShadowView = shadowInfo->getMatShadowView(); - const Mat4 &matShadowProj = shadowInfo->getMatShadowProj(); + const auto *mainLight = static_cast(light); + const Mat4 &matShadowView = shadowInfo->getMatShadowView(); + const Mat4 &matShadowProj = shadowInfo->getMatShadowProj(); const Mat4 &matShadowViewProj = shadowInfo->getMatShadowViewProj(); float nearClamp; float farClamp; if (mainLight->isShadowFixedArea()) { nearClamp = mainLight->getShadowNear(); - farClamp = mainLight->getShadowFar(); + farClamp = mainLight->getShadowFar(); } else { nearClamp = 1.0F; - farClamp = shadowInfo->getShadowCameraFar(); + farClamp = shadowInfo->getShadowCameraFar(); } memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView)); @@ -289,9 +289,9 @@ void PipelineUBO::updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd memcpy(shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos)); } break; case scene::LightType::SPOT: { - const auto *spotLight = static_cast(light); + const auto *spotLight = static_cast(light); const auto &matShadowCamera = spotLight->getNode()->getWorldMatrix(); - const auto matShadowView = matShadowCamera.getInversed(); + const auto matShadowView = matShadowCamera.getInversed(); memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView)); Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowViewProj); @@ -318,18 +318,18 @@ void PipelineUBO::updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd } static uint8_t combineSignY = 0; -uint8_t PipelineUBO::getCombineSignY() { +uint8_t PipelineUBO::getCombineSignY() { return combineSignY; } void PipelineUBO::initCombineSignY() { const float screenSpaceSignY = _device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F; - const float clipSpaceSignY = _device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; - combineSignY = static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY); + const float clipSpaceSignY = _device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F; + combineSignY = static_cast(screenSpaceSignY) << 1 | static_cast(clipSpaceSignY); } void PipelineUBO::activate(gfx::Device *device, RenderPipeline *pipeline) { - _device = device; + _device = device; _pipeline = pipeline; auto *descriptorSet = pipeline->getDescriptorSet(); @@ -383,7 +383,7 @@ void PipelineUBO::destroy() { void PipelineUBO::updateGlobalUBO(const scene::Camera *camera) { auto *const globalDSManager = _pipeline->getGlobalDSManager(); - auto *const ds = _pipeline->getDescriptorSet(); + auto *const ds = _pipeline->getDescriptorSet(); ds->update(); PipelineUBO::updateGlobalUBOView(camera, &_globalUBO); ds->getBuffer(UBOGlobal::BINDING)->update(_globalUBO.data(), UBOGlobal::SIZE); @@ -399,7 +399,7 @@ void PipelineUBO::updateCameraUBO(const scene::Camera *camera) { } void PipelineUBO::updateMultiCameraUBO(const ccstd::vector &cameras) { - const auto cameraCount = cameras.size(); + const auto cameraCount = cameras.size(); const auto totalUboSize = static_cast(_alignedCameraUBOSize * cameraCount); if (_cameraBuffer->getSize() < totalUboSize) { @@ -409,7 +409,7 @@ void PipelineUBO::updateMultiCameraUBO(const ccstd::vector &cam for (uint cameraIdx = 0; cameraIdx < cameraCount; ++cameraIdx) { const auto *camera = cameras[cameraIdx]; - const auto offset = cameraIdx * _alignedCameraUBOSize / sizeof(float); + const auto offset = cameraIdx * _alignedCameraUBOSize / sizeof(float); PipelineUBO::updateCameraUBOView(_pipeline, &_cameraUBOs[offset], camera); } _cameraBuffer->update(_cameraUBOs.data()); @@ -418,17 +418,17 @@ void PipelineUBO::updateMultiCameraUBO(const ccstd::vector &cam } void PipelineUBO::updateShadowUBO(const scene::Camera *camera) { - auto *const ds = _pipeline->getDescriptorSet(); - auto *const cmdBuffer = _pipeline->getCommandBuffers()[0]; - const auto * sceneData = _pipeline->getPipelineSceneData(); - const auto * shadowInfo = sceneData->getShadows(); - const auto *const scene = camera->getScene(); + auto *const ds = _pipeline->getDescriptorSet(); + auto *const cmdBuffer = _pipeline->getCommandBuffers()[0]; + const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto *shadowInfo = sceneData->getShadows(); + const auto *const scene = camera->getScene(); if (shadowInfo == nullptr || !shadowInfo->isEnabled()) { return; } - const auto & shadowFrameBufferMap = sceneData->getShadowFramebufferMap(); - const scene::DirectionalLight *mainLight = scene->getMainLight(); + const auto &shadowFrameBufferMap = sceneData->getShadowFramebufferMap(); + const scene::DirectionalLight *mainLight = scene->getMainLight(); if (mainLight && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) { if (shadowFrameBufferMap.count(mainLight) > 0) { auto *texture = shadowFrameBufferMap.at(mainLight)->getColorTextures()[0]; diff --git a/native/cocos/renderer/pipeline/PipelineUBO.h b/native/cocos/renderer/pipeline/PipelineUBO.h index 141f35889f..a82e1cd6f3 100644 --- a/native/cocos/renderer/pipeline/PipelineUBO.h +++ b/native/cocos/renderer/pipeline/PipelineUBO.h @@ -37,13 +37,13 @@ namespace pipeline { class RenderPipeline; class CC_DLL PipelineUBO final { public: - static void updateGlobalUBOView(const scene::Camera *camera, ccstd::array *bufferView); - static void updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera); - static void updateShadowUBOView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Camera *camera); - static void updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Light *light); + static void updateGlobalUBOView(const scene::Camera *camera, ccstd::array *bufferView); + static void updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera); + static void updateShadowUBOView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Camera *camera); + static void updateShadowUBOLightView(const RenderPipeline *pipeline, ccstd::array *bufferView, const scene::Light *light); static uint8_t getCombineSignY(); - PipelineUBO() = default; + PipelineUBO() = default; ~PipelineUBO() = default; void activate(gfx::Device *device, RenderPipeline *pipeline); void destroy(); @@ -59,17 +59,17 @@ public: private: RenderPipeline *_pipeline = nullptr; - gfx::Device * _device = nullptr; + gfx::Device *_device = nullptr; ccstd::array _globalUBO; ccstd::array _shadowUBO; ccstd::vector _ubos; - void initCombineSignY(); - ccstd::vector _cameraUBOs; - gfx::Buffer * _cameraBuffer{nullptr}; - uint _currentCameraUBOOffset{0}; - uint _alignedCameraUBOSize{0}; + void initCombineSignY(); + ccstd::vector _cameraUBOs; + gfx::Buffer *_cameraBuffer{nullptr}; + uint _currentCameraUBOOffset{0}; + uint _alignedCameraUBOSize{0}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp index 802bde4106..643c4c15bb 100644 --- a/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp +++ b/native/cocos/renderer/pipeline/PlanarShadowQueue.cpp @@ -52,14 +52,14 @@ PlanarShadowQueue::~PlanarShadowQueue() = default; void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { clear(); - const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); - const scene::Shadows * shadowInfo = sceneData->getShadows(); + const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); + const scene::Shadows *shadowInfo = sceneData->getShadows(); if (shadowInfo == nullptr || !shadowInfo->isEnabled() || shadowInfo->getType() != scene::ShadowType::PLANAR || shadowInfo->getNormal().length() < 0.000001F) { return; } - const auto *scene = camera->getScene(); - const bool shadowVisible = camera->getVisibility() & static_cast(LayerList::DEFAULT); + const auto *scene = camera->getScene(); + const bool shadowVisible = camera->getVisibility() & static_cast(LayerList::DEFAULT); if (!scene->getMainLight() || !shadowVisible) { return; } @@ -75,7 +75,7 @@ void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBu } } - const auto & passes = *shadowInfo->getInstancingMaterial()->getPasses(); + const auto &passes = *shadowInfo->getInstancingMaterial()->getPasses(); InstancedBuffer *instancedBuffer = passes[0]->getInstancedBuffer(); geometry::AABB ab; @@ -108,8 +108,8 @@ void PlanarShadowQueue::clear() { } void PlanarShadowQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer, uint32_t subpassID) { - const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); - const auto * shadowInfo = sceneData->getShadows(); + const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); + const auto *shadowInfo = sceneData->getShadows(); if (shadowInfo == nullptr || !shadowInfo->isEnabled() || shadowInfo->getType() != scene::ShadowType::PLANAR || shadowInfo->getNormal().length() < 0.000001F) { return; } @@ -126,8 +126,8 @@ void PlanarShadowQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass for (const auto *model : _pendingModels) { for (const auto &subModel : model->getSubModels()) { auto *const shader = subModel->getPlanarShader(); - auto *const ia = subModel->getInputAssembler(); - auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass, subpassID); + auto *const ia = subModel->getInputAssembler(); + auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass, subpassID); cmdBuffer->bindPipelineState(pso); cmdBuffer->bindDescriptorSet(localSet, subModel->getDescriptorSet()); diff --git a/native/cocos/renderer/pipeline/PlanarShadowQueue.h b/native/cocos/renderer/pipeline/PlanarShadowQueue.h index 8dd084e236..4ff7913004 100644 --- a/native/cocos/renderer/pipeline/PlanarShadowQueue.h +++ b/native/cocos/renderer/pipeline/PlanarShadowQueue.h @@ -53,8 +53,8 @@ public: void destroy(); private: - RenderPipeline * _pipeline = nullptr; - RenderInstancedQueue * _instancedQueue = nullptr; + RenderPipeline *_pipeline = nullptr; + RenderInstancedQueue *_instancedQueue = nullptr; ccstd::vector _castModels; ccstd::vector _pendingModels; }; diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index bd2d1c4a1b..972c7948f1 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -55,17 +55,17 @@ namespace pipeline { RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _pipeline(pipeline), _instancedQueue(ccnew RenderInstancedQueue), _batchedQueue(ccnew RenderBatchedQueue) { - auto * device = gfx::Device::getInstance(); - const auto alignment = device->getCapabilities().uboOffsetAlignment; - _lightBufferStride = ((UBOForwardLight::SIZE + alignment - 1) / alignment) * alignment; + auto *device = gfx::Device::getInstance(); + const auto alignment = device->getCapabilities().uboOffsetAlignment; + _lightBufferStride = ((UBOForwardLight::SIZE + alignment - 1) / alignment) * alignment; _lightBufferElementCount = _lightBufferStride / sizeof(float); - _lightBuffer = device->createBuffer({ + _lightBuffer = device->createBuffer({ gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE, _lightBufferStride * _lightBufferCount, _lightBufferStride, }); - _firstLightBufferView = device->createBuffer({_lightBuffer, 0, UBOForwardLight::SIZE}); + _firstLightBufferView = device->createBuffer({_lightBuffer, 0, UBOForwardLight::SIZE}); _lightBufferData.resize(static_cast(_lightBufferElementCount) * _lightBufferCount); _dynamicOffsets.resize(1, 0); _phaseID = getPhaseID("forward-add"); @@ -83,28 +83,28 @@ void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, scene::C _instancedQueue->recordCommandBuffer(device, renderPass, cmdBuffer); _batchedQueue->recordCommandBuffer(device, renderPass, cmdBuffer); const bool enableOcclusionQuery = _pipeline->isOcclusionQueryEnabled(); - const auto offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); + const auto offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); for (const auto &lightPass : _lightPasses) { const auto *const subModel = lightPass.subModel; if (!enableOcclusionQuery || !_pipeline->isOccluded(camera, subModel)) { - const auto *pass = lightPass.pass; + const auto *pass = lightPass.pass; const auto &dynamicOffsets = lightPass.dynamicOffsets; - auto * shader = lightPass.shader; - const auto lights = lightPass.lights; - auto * ia = subModel->getInputAssembler(); - auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); - auto * descriptorSet = subModel->getDescriptorSet(); + auto *shader = lightPass.shader; + const auto lights = lightPass.lights; + auto *ia = subModel->getInputAssembler(); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); + auto *descriptorSet = subModel->getDescriptorSet(); cmdBuffer->bindPipelineState(pso); cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuffer->bindInputAssembler(ia); for (size_t i = 0; i < dynamicOffsets.size(); ++i) { - const auto light = lights[i]; - auto * globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); - _dynamicOffsets[0] = dynamicOffsets[i]; + const auto light = lights[i]; + auto *globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); + _dynamicOffsets[0] = dynamicOffsets[i]; cmdBuffer->bindDescriptorSet(globalSet, globalDescriptorSet, 1, &offset); cmdBuffer->bindDescriptorSet(localSet, descriptorSet, _dynamicOffsets); cmdBuffer->draw(ia); @@ -139,8 +139,8 @@ void RenderAdditiveLightQueue::gatherLightPasses(const scene::Camera *camera, gf for (const auto &subModel : model->getSubModels()) { const auto lightPassIdx = lightPassIndices[i]; if (lightPassIdx == UINT_MAX) continue; - const auto *pass = subModel->getPass(lightPassIdx); - const bool isTransparent = subModel->getPass(0)->getBlendState()->targets[0].blend; + const auto *pass = subModel->getPass(lightPassIdx); + const bool isTransparent = subModel->getPass(0)->getBlendState()->targets[0].blend; if (isTransparent) { continue; } @@ -193,11 +193,11 @@ void RenderAdditiveLightQueue::addRenderQueue(const scene::Pass *pass, const sce _batchedQueue->add(buffer); } } else { // standard draw - const auto count = _lightIndices.size(); + const auto count = _lightIndices.size(); AdditiveLightPass lightPass; lightPass.subModel = subModel; - lightPass.pass = pass; - lightPass.shader = subModel->getShader(lightPassIdx); + lightPass.pass = pass; + lightPass.shader = subModel->getShader(lightPassIdx); lightPass.dynamicOffsets.resize(count); for (unsigned idx = 0; idx < count; idx++) { const auto lightIdx = _lightIndices[idx]; @@ -210,10 +210,10 @@ void RenderAdditiveLightQueue::addRenderQueue(const scene::Pass *pass, const sce } void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { - const auto exposure = camera->getExposure(); - const auto validLightCount = _validPunctualLights.size(); - const auto *sceneData = _pipeline->getPipelineSceneData(); - const auto *shadowInfo = sceneData->getShadows(); + const auto exposure = camera->getExposure(); + const auto validLightCount = _validPunctualLights.size(); + const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto *shadowInfo = sceneData->getShadows(); size_t offset = 0; if (validLightCount > _lightBufferCount) { @@ -226,25 +226,25 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm } for (unsigned l = 0; l < validLightCount; l++, offset += _lightBufferElementCount) { - const auto *light = _validPunctualLights[l]; - const bool isSpotLight = scene::LightType::SPOT == light->getType(); - const auto *spotLight = isSpotLight ? static_cast(light) : nullptr; + const auto *light = _validPunctualLights[l]; + const bool isSpotLight = scene::LightType::SPOT == light->getType(); + const auto *spotLight = isSpotLight ? static_cast(light) : nullptr; const auto *sphereLight = isSpotLight ? nullptr : static_cast(light); - auto index = offset + UBOForwardLight::LIGHT_POS_OFFSET; - const auto &position = isSpotLight ? spotLight->getPosition() : sphereLight->getPosition(); + auto index = offset + UBOForwardLight::LIGHT_POS_OFFSET; + const auto &position = isSpotLight ? spotLight->getPosition() : sphereLight->getPosition(); _lightBufferData[index++] = position.x; _lightBufferData[index++] = position.y; - _lightBufferData[index] = position.z; + _lightBufferData[index] = position.z; - index = offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET; + index = offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET; _lightBufferData[index++] = isSpotLight ? spotLight->getSize() : sphereLight->getSize(); - _lightBufferData[index] = isSpotLight ? spotLight->getRange() : sphereLight->getRange(); + _lightBufferData[index] = isSpotLight ? spotLight->getRange() : sphereLight->getRange(); - index = offset + UBOForwardLight::LIGHT_COLOR_OFFSET; + index = offset + UBOForwardLight::LIGHT_COLOR_OFFSET; const auto &color = light->getColor(); if (light->isUseColorTemperature()) { - const auto &tempRGB = light->getColorTemperatureRGB(); + const auto &tempRGB = light->getColorTemperatureRGB(); _lightBufferData[index++] = color.x * tempRGB.x; _lightBufferData[index++] = color.y * tempRGB.y; _lightBufferData[index++] = color.z * tempRGB.z; @@ -264,20 +264,20 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm switch (light->getType()) { case scene::LightType::SPHERE: - _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 0; + _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 0; _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; break; case scene::LightType::SPOT: { - _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 1.0F; + _lightBufferData[offset + UBOForwardLight::LIGHT_POS_OFFSET + 3] = 1.0F; _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = spotLight->getSpotAngle(); _lightBufferData[offset + UBOForwardLight::LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = (spotLight->isShadowEnabled() && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) ? 1.0F : 0.0F; - index = offset + UBOForwardLight::LIGHT_DIR_OFFSET; - const auto &direction = spotLight->getDirection(); + index = offset + UBOForwardLight::LIGHT_DIR_OFFSET; + const auto &direction = spotLight->getDirection(); _lightBufferData[index++] = direction.x; _lightBufferData[index++] = direction.y; - _lightBufferData[index] = direction.z; + _lightBufferData[index] = direction.z; } break; default: break; @@ -288,18 +288,18 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm } void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { - const auto * sceneData = _pipeline->getPipelineSceneData(); - auto * shadowInfo = sceneData->getShadows(); - const auto *const scene = camera->getScene(); - auto * device = gfx::Device::getInstance(); - const bool hFTexture = supportsR32FloatTexture(device); - const float linear = 0.0F; - const float packing = hFTexture ? 0.0F : 1.0F; - const scene::Light *mainLight = scene->getMainLight(); + const auto *sceneData = _pipeline->getPipelineSceneData(); + auto *shadowInfo = sceneData->getShadows(); + const auto *const scene = camera->getScene(); + auto *device = gfx::Device::getInstance(); + const bool hFTexture = supportsR32FloatTexture(device); + const float linear = 0.0F; + const float packing = hFTexture ? 0.0F : 1.0F; + const scene::Light *mainLight = scene->getMainLight(); for (uint i = 0; i < _validPunctualLights.size(); ++i) { - const auto *light = _validPunctualLights[i]; - auto * descriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(i); + const auto *light = _validPunctualLights[i]; + auto *descriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(i); if (!descriptorSet) { continue; } @@ -315,8 +315,8 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam } // Reserve sphere light shadow interface - const auto &shadowSize = shadowInfo->getSize(); - float shadowWHPBInfos[4] = {shadowSize.x, shadowSize.y, 1.0F, 0.0F}; + const auto &shadowSize = shadowInfo->getSize(); + float shadowWHPBInfos[4] = {shadowSize.x, shadowSize.y, 1.0F, 0.0F}; memcpy(_shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(float) * 4); float shadowLPNNInfos[4] = {2.0F, packing, 0.0F, 0.0F}; @@ -331,12 +331,12 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam } const auto &matShadowCamera = light->getNode()->getWorldMatrix(); - const auto matShadowView = matShadowCamera.getInversed(); + const auto matShadowView = matShadowCamera.getInversed(); cc::Mat4 matShadowProj; cc::Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowProj); cc::Mat4 matShadowViewProj = matShadowProj; - cc::Mat4 matShadowInvProj = matShadowProj; + cc::Mat4 matShadowInvProj = matShadowProj; matShadowInvProj.inverse(); matShadowViewProj.multiply(matShadowView); @@ -348,8 +348,8 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam float shadowNFLSInfos[4] = {0.1F, spotLight->getRange(), linear, 0.0F}; memcpy(_shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos)); - const auto &shadowSize = shadowInfo->getSize(); - float shadowWHPBInfos[4] = {shadowSize.x, shadowSize.y, spotLight->getShadowPcf(), spotLight->getShadowBias()}; + const auto &shadowSize = shadowInfo->getSize(); + float shadowWHPBInfos[4] = {shadowSize.x, shadowSize.y, spotLight->getShadowPcf(), spotLight->getShadowBias()}; memcpy(_shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos)); float shadowLPNNInfos[4] = {1.0F, packing, spotLight->getShadowNormalBias(), 0.0F}; diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h index 8014c35265..416b274714 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h @@ -45,10 +45,10 @@ class ForwardPipeline; struct AdditiveLightPass { const scene::SubModel *subModel = nullptr; - const scene::Pass * pass = nullptr; - gfx::Shader * shader = nullptr; - ccstd::vector dynamicOffsets; - ccstd::vector lights; + const scene::Pass *pass = nullptr; + gfx::Shader *shader = nullptr; + ccstd::vector dynamicOffsets; + ccstd::vector lights; }; class RenderAdditiveLightQueue final { @@ -70,26 +70,26 @@ private: bool getLightPassIndex(const scene::Model *model, ccstd::vector *lightPassIndices) const; void lightCulling(const scene::Model *model); - RenderPipeline * _pipeline = nullptr; + RenderPipeline *_pipeline = nullptr; ccstd::vector> _sortedSubModelsArray; - ccstd::vector> _sortedPSOCIArray; - ccstd::vector _validPunctualLights; - ccstd::vector _lightIndices; - ccstd::vector _lightPasses; - ccstd::vector _dynamicOffsets; - ccstd::vector _lightBufferData; - RenderInstancedQueue * _instancedQueue = nullptr; - RenderBatchedQueue * _batchedQueue = nullptr; - gfx::Buffer * _lightBuffer = nullptr; - gfx::Buffer * _firstLightBufferView = nullptr; + ccstd::vector> _sortedPSOCIArray; + ccstd::vector _validPunctualLights; + ccstd::vector _lightIndices; + ccstd::vector _lightPasses; + ccstd::vector _dynamicOffsets; + ccstd::vector _lightBufferData; + RenderInstancedQueue *_instancedQueue = nullptr; + RenderBatchedQueue *_batchedQueue = nullptr; + gfx::Buffer *_lightBuffer = nullptr; + gfx::Buffer *_firstLightBufferView = nullptr; ccstd::array _shadowUBO{}; - uint _lightBufferStride = 0; - uint _lightBufferElementCount = 0; - uint _lightBufferCount = 16; - float _lightMeterScale = 10000.0F; - uint _phaseID = 0; + uint _lightBufferStride = 0; + uint _lightBufferElementCount = 0; + uint _lightBufferCount = 16; + float _lightMeterScale = 10000.0F; + uint _phaseID = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderBatchedQueue.cpp b/native/cocos/renderer/pipeline/RenderBatchedQueue.cpp index 1ee292e76f..87f13e7997 100644 --- a/native/cocos/renderer/pipeline/RenderBatchedQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderBatchedQueue.cpp @@ -59,8 +59,8 @@ void RenderBatchedQueue::uploadBuffers(gfx::CommandBuffer *cmdBuffer) { void RenderBatchedQueue::recordCommandBuffer(gfx::Device * /*device*/, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) { for (auto *batchedBuffer : _queues) { - bool boundPSO = false; - const auto &batches = batchedBuffer->getBatches(); + bool boundPSO = false; + const auto &batches = batchedBuffer->getBatches(); for (const auto &batch : batches) { if (!batch.mergeCount) continue; if (!boundPSO) { diff --git a/native/cocos/renderer/pipeline/RenderBatchedQueue.h b/native/cocos/renderer/pipeline/RenderBatchedQueue.h index 4d26d2d63f..b1988990f8 100644 --- a/native/cocos/renderer/pipeline/RenderBatchedQueue.h +++ b/native/cocos/renderer/pipeline/RenderBatchedQueue.h @@ -35,7 +35,7 @@ class BatchedBuffer; class CC_DLL RenderBatchedQueue final { public: - RenderBatchedQueue() = default; + RenderBatchedQueue() = default; ~RenderBatchedQueue() = default; void clear(); diff --git a/native/cocos/renderer/pipeline/RenderFlow.cpp b/native/cocos/renderer/pipeline/RenderFlow.cpp index 660e9cc0e4..2cb35655a9 100644 --- a/native/cocos/renderer/pipeline/RenderFlow.cpp +++ b/native/cocos/renderer/pipeline/RenderFlow.cpp @@ -36,10 +36,10 @@ RenderFlow::RenderFlow() = default; RenderFlow::~RenderFlow() = default; bool RenderFlow::initialize(const RenderFlowInfo &info) { - _name = info.name; + _name = info.name; _priority = info.priority; - _tag = info.tag; - _stages = info.stages; + _tag = info.tag; + _stages = info.stages; return true; } diff --git a/native/cocos/renderer/pipeline/RenderFlow.h b/native/cocos/renderer/pipeline/RenderFlow.h index 576eb7a9b9..9860d76c42 100644 --- a/native/cocos/renderer/pipeline/RenderFlow.h +++ b/native/cocos/renderer/pipeline/RenderFlow.h @@ -37,9 +37,9 @@ class RenderPipeline; class RenderStage; struct CC_DLL RenderFlowInfo { - ccstd::string name; - uint priority = 0; - uint tag = 0; + ccstd::string name; + uint priority = 0; + uint tag = 0; RenderStageList stages; }; @@ -54,16 +54,16 @@ public: virtual void destroy(); inline const ccstd::string &getName() const { return _name; } - inline uint getPriority() const { return _priority; } - inline uint getTag() const { return _tag; } - RenderStage * getRenderstageByName(const ccstd::string &name) const; + inline uint getPriority() const { return _priority; } + inline uint getTag() const { return _tag; } + RenderStage *getRenderstageByName(const ccstd::string &name) const; protected: RenderStageList _stages; - ccstd::string _name; + ccstd::string _name; RenderPipeline *_pipeline = nullptr; - uint _priority = 0; - uint _tag = 0; + uint _priority = 0; + uint _tag = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp b/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp index fd730cad9b..cad9fdb62a 100644 --- a/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderInstancedQueue.cpp @@ -51,7 +51,7 @@ void RenderInstancedQueue::recordCommandBuffer(gfx::Device * /*device*/, gfx::Re if (!instanceBuffer->hasPendingModels()) continue; const auto &instances = instanceBuffer->getInstances(); - const auto *pass = instanceBuffer->getPass(); + const auto *pass = instanceBuffer->getPass(); cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); gfx::PipelineState *lastPSO = nullptr; for (const auto &instance : instances) { diff --git a/native/cocos/renderer/pipeline/RenderInstancedQueue.h b/native/cocos/renderer/pipeline/RenderInstancedQueue.h index 02e0a8a05b..49ae8aae0e 100644 --- a/native/cocos/renderer/pipeline/RenderInstancedQueue.h +++ b/native/cocos/renderer/pipeline/RenderInstancedQueue.h @@ -42,7 +42,7 @@ class InstancedBuffer; class CC_DLL RenderInstancedQueue final { public: - RenderInstancedQueue() = default; + RenderInstancedQueue() = default; ~RenderInstancedQueue() = default; void recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index 7f7d215406..c4858a1fc4 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -60,7 +60,7 @@ RenderPipeline::RenderPipeline() RenderPipeline::instance = this; _globalDSManager = ccnew GlobalDSManager(); - _pipelineUBO = ccnew PipelineUBO(); + _pipelineUBO = ccnew PipelineUBO(); } RenderPipeline::~RenderPipeline() { @@ -69,7 +69,7 @@ RenderPipeline::~RenderPipeline() { bool RenderPipeline::initialize(const RenderPipelineInfo &info) { _flows = info.flows; - _tag = info.tag; + _tag = info.tag; return true; } @@ -156,7 +156,7 @@ bool RenderPipeline::destroy() { gfx::Color RenderPipeline::getClearcolor(scene::Camera *camera) const { auto *const sceneData = getPipelineSceneData(); - gfx::Color clearColor{0.0F, 0.0F, 0.0F, 1.0F}; + gfx::Color clearColor{0.0F, 0.0F, 0.0F, 1.0F}; if (static_cast(camera->getClearFlag()) & static_cast(gfx::ClearFlagBit::COLOR)) { clearColor = camera->getClearColor(); } @@ -186,7 +186,7 @@ gfx::InputAssembler *RenderPipeline::getIAByRenderArea(const gfx::Rect &renderAr return iter->second; } - gfx::Buffer * vb = nullptr; + gfx::Buffer *vb = nullptr; gfx::InputAssembler *ia = nullptr; createQuadInputAssembler(_quadIB, &vb, &ia); _quadVB.push_back(vb); @@ -200,7 +200,7 @@ gfx::InputAssembler *RenderPipeline::getIAByRenderArea(const gfx::Rect &renderAr bool RenderPipeline::createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer **quadVB, gfx::InputAssembler **quadIA) { // step 1 create vertex buffer uint vbStride = sizeof(float) * 4; - uint vbSize = vbStride * 4; + uint vbSize = vbStride * 4; if (*quadVB == nullptr) { *quadVB = _device->createBuffer({gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, @@ -213,19 +213,19 @@ bool RenderPipeline::createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer * info.attributes.push_back({"a_texCoord", gfx::Format::RG32F}); info.vertexBuffers.push_back(*quadVB); info.indexBuffer = quadIB; - *quadIA = _device->createInputAssembler(info); + *quadIA = _device->createInputAssembler(info); return (*quadIA) != nullptr; } void RenderPipeline::ensureEnoughSize(const ccstd::vector &cameras) { for (auto *camera : cameras) { - _width = std::max(camera->getWindow()->getWidth(), _width); + _width = std::max(camera->getWindow()->getWidth(), _width); _height = std::max(camera->getWindow()->getHeight(), _height); } } gfx::Viewport RenderPipeline::getViewport(scene::Camera *camera) { - auto scale{_pipelineSceneData->getShadingScale()}; + auto scale{_pipelineSceneData->getShadingScale()}; const gfx::Rect &rect = getRenderArea(camera); return { static_cast(static_cast(rect.x) * scale), @@ -235,7 +235,7 @@ gfx::Viewport RenderPipeline::getViewport(scene::Camera *camera) { } gfx::Rect RenderPipeline::getScissor(scene::Camera *camera) { - auto scale{_pipelineSceneData->getShadingScale()}; + auto scale{_pipelineSceneData->getShadingScale()}; const gfx::Rect &rect = getRenderArea(camera); return { static_cast(static_cast(rect.x) * scale), @@ -273,7 +273,7 @@ void RenderPipeline::genQuadVertexData(const Vec4 &viewport, float *vbData) { if (_device->getCapabilities().screenSpaceSignY > 0) { std::swap(minY, maxY); } - int n = 0; + int n = 0; vbData[n++] = -1.0F; vbData[n++] = -1.0F; vbData[n++] = minX; // uv @@ -323,7 +323,7 @@ RenderStage *RenderPipeline::getRenderstageByName(const ccstd::string &name) con } bool RenderPipeline::isOccluded(const scene::Camera *camera, const scene::SubModel *subModel) { - auto *model = subModel->getOwner(); + auto *model = subModel->getOwner(); auto *worldBound = model->getWorldBounds(); // assume visible if there is no worldBound. @@ -347,7 +347,7 @@ bool RenderPipeline::isOccluded(const scene::Camera *camera, const scene::SubMod } void RenderPipeline::framegraphGC() { - static uint64_t frameCount{0U}; + static uint64_t frameCount{0U}; static constexpr uint32_t INTERVAL_IN_SECONDS = 30; if (++frameCount % (INTERVAL_IN_SECONDS * 60) == 0) { framegraph::FrameGraph::gc(INTERVAL_IN_SECONDS * 60); diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index ca1440f680..62bb76198d 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -51,68 +51,68 @@ class PipelineSceneData; class GlobalDSManager; class RenderStage; struct CC_DLL RenderPipelineInfo { - uint tag = 0; + uint tag = 0; RenderFlowList flows; }; class CC_DLL RenderPipeline : public Asset { public: using Super = Asset; - static RenderPipeline * getInstance(); + static RenderPipeline *getInstance(); static framegraph::StringHandle fgStrHandleOutDepthTexture; static framegraph::StringHandle fgStrHandleOutColorTexture; static framegraph::StringHandle fgStrHandlePostprocessPass; static framegraph::StringHandle fgStrHandleBloomOutTexture; - static gfx::Rect getRenderArea(scene::Camera *camera); + static gfx::Rect getRenderArea(scene::Camera *camera); RenderPipeline(); ~RenderPipeline() override; virtual bool activate(gfx::Swapchain *swapchain); - bool destroy() override; + bool destroy() override; virtual bool initialize(const RenderPipelineInfo &info); virtual void render(const ccstd::vector &cameras); virtual void onGlobalPipelineStateChanged(); - inline const RenderFlowList & getFlows() const { return _flows; } - inline uint getTag() const { return _tag; } + inline const RenderFlowList &getFlows() const { return _flows; } + inline uint getTag() const { return _tag; } inline const ccstd::unordered_map &getGlobalBindings() const { return _globalBindings; } - inline const MacroRecord & getMacros() const { return _macros; } - inline void setValue(const ccstd::string &name, int32_t value) { _macros[name] = value; } - inline void setValue(const ccstd::string &name, bool value) { _macros[name] = value; } - inline void setValue(const ccstd::string &name, const ccstd::string &value) { _macros[name] = value; } - inline GlobalDSManager * getGlobalDSManager() const { return _globalDSManager; } - inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptorSet; } - gfx::DescriptorSetLayout * getDescriptorSetLayout() const; - inline PipelineSceneData * getPipelineSceneData() const { return _pipelineSceneData; } - inline const gfx::CommandBufferList & getCommandBuffers() const { return _commandBuffers; } - inline const gfx::QueryPoolList & getQueryPools() const { return _queryPools; } - inline PipelineUBO * getPipelineUBO() const { return _pipelineUBO; } - inline const ccstd::string & getConstantMacros() const { return _constantMacros; } - inline gfx::Device * getDevice() const { return _device; } - RenderStage * getRenderstageByName(const ccstd::string &name) const; - bool isOccluded(const scene::Camera *camera, const scene::SubModel *subModel); - bool isOcclusionQueryEnabled() const { return _occlusionQueryEnabled && _device->getCapabilities().supportQuery; } - void setOcclusionQueryEnabled(bool enable) { _occlusionQueryEnabled = enable; } - bool isEnvmapEnabled() const; + inline const MacroRecord &getMacros() const { return _macros; } + inline void setValue(const ccstd::string &name, int32_t value) { _macros[name] = value; } + inline void setValue(const ccstd::string &name, bool value) { _macros[name] = value; } + inline void setValue(const ccstd::string &name, const ccstd::string &value) { _macros[name] = value; } + inline GlobalDSManager *getGlobalDSManager() const { return _globalDSManager; } + inline gfx::DescriptorSet *getDescriptorSet() const { return _descriptorSet; } + gfx::DescriptorSetLayout *getDescriptorSetLayout() const; + inline PipelineSceneData *getPipelineSceneData() const { return _pipelineSceneData; } + inline const gfx::CommandBufferList &getCommandBuffers() const { return _commandBuffers; } + inline const gfx::QueryPoolList &getQueryPools() const { return _queryPools; } + inline PipelineUBO *getPipelineUBO() const { return _pipelineUBO; } + inline const ccstd::string &getConstantMacros() const { return _constantMacros; } + inline gfx::Device *getDevice() const { return _device; } + RenderStage *getRenderstageByName(const ccstd::string &name) const; + bool isOccluded(const scene::Camera *camera, const scene::SubModel *subModel); + bool isOcclusionQueryEnabled() const { return _occlusionQueryEnabled && _device->getCapabilities().supportQuery; } + void setOcclusionQueryEnabled(bool enable) { _occlusionQueryEnabled = enable; } + bool isEnvmapEnabled() const; - gfx::Viewport getViewport(scene::Camera *camera); - gfx::Rect getScissor(scene::Camera *camera); - void genQuadVertexData(const Vec4 &viewport, float *data); - uint getWidth() const { return _width; } - uint getHeight() const { return _height; } + gfx::Viewport getViewport(scene::Camera *camera); + gfx::Rect getScissor(scene::Camera *camera); + void genQuadVertexData(const Vec4 &viewport, float *data); + uint getWidth() const { return _width; } + uint getHeight() const { return _height; } framegraph::FrameGraph &getFrameGraph() { return _fg; } - gfx::Color getClearcolor(scene::Camera *camera) const; - gfx::InputAssembler * getIAByRenderArea(const gfx::Rect &renderArea); - void updateQuadVertexData(const Vec4 &viewport, gfx::Buffer *buffer); - void ensureEnoughSize(const ccstd::vector &cameras); - bool createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer **quadVB, gfx::InputAssembler **quadIA); + gfx::Color getClearcolor(scene::Camera *camera) const; + gfx::InputAssembler *getIAByRenderArea(const gfx::Rect &renderArea); + void updateQuadVertexData(const Vec4 &viewport, gfx::Buffer *buffer); + void ensureEnoughSize(const ccstd::vector &cameras); + bool createQuadInputAssembler(gfx::Buffer *quadIB, gfx::Buffer **quadVB, gfx::InputAssembler **quadIA); float getShadingScale() const; - void setShadingScale(float scale); + void setShadingScale(float scale); inline scene::Model *getProfiler() const { return _profiler; } - inline void setProfiler(scene::Model *value) { _profiler = value; } + inline void setProfiler(scene::Model *value) { _profiler = value; } inline bool isClusterEnabled() const { return _clusterEnabled; } inline void setClusterEnabled(bool enable) { _clusterEnabled = enable; } @@ -128,30 +128,30 @@ protected: static void framegraphGC(); - gfx::CommandBufferList _commandBuffers; - gfx::QueryPoolList _queryPools; - RenderFlowList _flows; + gfx::CommandBufferList _commandBuffers; + gfx::QueryPoolList _queryPools; + RenderFlowList _flows; ccstd::unordered_map _globalBindings; - MacroRecord _macros; - uint _tag = 0; - ccstd::string _constantMacros; + MacroRecord _macros; + uint _tag = 0; + ccstd::string _constantMacros; - gfx::Device * _device{nullptr}; - GlobalDSManager * _globalDSManager{nullptr}; - gfx::DescriptorSet * _descriptorSet{nullptr}; - PipelineUBO * _pipelineUBO{nullptr}; - scene::Model * _profiler{nullptr}; + gfx::Device *_device{nullptr}; + GlobalDSManager *_globalDSManager{nullptr}; + gfx::DescriptorSet *_descriptorSet{nullptr}; + PipelineUBO *_pipelineUBO{nullptr}; + scene::Model *_profiler{nullptr}; IntrusivePtr _pipelineSceneData; // has not initBuiltinRes, // create temporary default Texture to binding sampler2d - uint _width{0}; - uint _height{0}; - gfx::Buffer * _quadIB{nullptr}; - ccstd::vector _quadVB; + uint _width{0}; + uint _height{0}; + gfx::Buffer *_quadIB{nullptr}; + ccstd::vector _quadVB; ccstd::unordered_map> _quadIA; - framegraph::FrameGraph _fg; + framegraph::FrameGraph _fg; ccstd::unordered_map _renderPasses; // use cluster culling or not diff --git a/native/cocos/renderer/pipeline/RenderQueue.cpp b/native/cocos/renderer/pipeline/RenderQueue.cpp index a61e0b2258..76d0382956 100644 --- a/native/cocos/renderer/pipeline/RenderQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderQueue.cpp @@ -48,19 +48,19 @@ void RenderQueue::clear() { } bool RenderQueue::insertRenderPass(const RenderObject &renderObj, uint subModelIdx, uint passIdx) { - const auto * subModel = renderObj.model->getSubModels()[subModelIdx].get(); - const auto *const pass = subModel->getPass(passIdx); - const bool isTransparent = pass->getBlendState()->targets[0].blend; + const auto *subModel = renderObj.model->getSubModels()[subModelIdx].get(); + const auto *const pass = subModel->getPass(passIdx); + const bool isTransparent = pass->getBlendState()->targets[0].blend; if (isTransparent != _passDesc.isTransparent || !(pass->getPhase() & _passDesc.phases)) { return false; } - auto passPriority = static_cast(pass->getPriority()); - auto modelPriority = static_cast(subModel->getPriority()); - auto shaderId = static_cast(reinterpret_cast(subModel->getShader(passIdx))); - const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx; - RenderPass renderPass = {hash, renderObj.depth, shaderId, passIdx, subModel}; + auto passPriority = static_cast(pass->getPriority()); + auto modelPriority = static_cast(subModel->getPriority()); + auto shaderId = static_cast(reinterpret_cast(subModel->getShader(passIdx))); + const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx; + RenderPass renderPass = {hash, renderObj.depth, shaderId, passIdx, subModel}; _queue.emplace_back(renderPass); return true; @@ -78,9 +78,9 @@ void RenderQueue::sort() { } void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex) { - PipelineSceneData *const sceneData = _pipeline->getPipelineSceneData(); - bool enableOcclusionQuery = _pipeline->isOcclusionQueryEnabled() && _useOcclusionQuery; - auto * queryPool = _pipeline->getQueryPools()[0]; + PipelineSceneData *const sceneData = _pipeline->getPipelineSceneData(); + bool enableOcclusionQuery = _pipeline->isOcclusionQueryEnabled() && _useOcclusionQuery; + auto *queryPool = _pipeline->getQueryPools()[0]; for (auto &i : _queue) { const auto *subModel = i.subModel; if (enableOcclusionQuery) { @@ -89,9 +89,9 @@ void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, scene::Camera *c if (enableOcclusionQuery && _pipeline->isOccluded(camera, subModel)) { gfx::InputAssembler *inputAssembler = sceneData->getOcclusionQueryInputAssembler(); - const scene::Pass * pass = sceneData->getOcclusionQueryPass(); - gfx::Shader * shader = sceneData->getOcclusionQueryShader(); - auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); + const scene::Pass *pass = sceneData->getOcclusionQueryPass(); + gfx::Shader *shader = sceneData->getOcclusionQueryShader(); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); @@ -99,11 +99,11 @@ void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, scene::Camera *c cmdBuff->bindInputAssembler(inputAssembler); cmdBuff->draw(inputAssembler); } else { - const auto passIdx = i.passIndex; - auto * inputAssembler = subModel->getInputAssembler(); - const auto *pass = subModel->getPass(passIdx); - auto * shader = subModel->getShader(passIdx); - auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); + const auto passIdx = i.passIndex; + auto *inputAssembler = subModel->getInputAssembler(); + const auto *pass = subModel->getPass(passIdx); + auto *shader = subModel->getShader(passIdx); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); diff --git a/native/cocos/renderer/pipeline/RenderQueue.h b/native/cocos/renderer/pipeline/RenderQueue.h index cbc7f48baa..5082c0f6e7 100644 --- a/native/cocos/renderer/pipeline/RenderQueue.h +++ b/native/cocos/renderer/pipeline/RenderQueue.h @@ -46,10 +46,10 @@ public: bool empty() { return _queue.empty(); } private: - RenderPipeline * _pipeline = nullptr; - RenderPassList _queue; + RenderPipeline *_pipeline = nullptr; + RenderPassList _queue; RenderQueueCreateInfo _passDesc; - bool _useOcclusionQuery{false}; + bool _useOcclusionQuery{false}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderStage.cpp b/native/cocos/renderer/pipeline/RenderStage.cpp index d4681ce726..50dd64acfd 100644 --- a/native/cocos/renderer/pipeline/RenderStage.cpp +++ b/native/cocos/renderer/pipeline/RenderStage.cpp @@ -35,16 +35,16 @@ RenderStage::RenderStage() RenderStage::~RenderStage() = default; bool RenderStage::initialize(const RenderStageInfo &info) { - _name = info.name; + _name = info.name; _priority = info.priority; - _tag = info.tag; + _tag = info.tag; return true; } void RenderStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { _pipeline = pipeline; - _flow = flow; + _flow = flow; } void RenderStage::destroy() { diff --git a/native/cocos/renderer/pipeline/RenderStage.h b/native/cocos/renderer/pipeline/RenderStage.h index 02b3485f12..3213330e20 100644 --- a/native/cocos/renderer/pipeline/RenderStage.h +++ b/native/cocos/renderer/pipeline/RenderStage.h @@ -42,9 +42,9 @@ class RenderPipeline; class RenderQueue; struct CC_DLL RenderStageInfo { - ccstd::string name; - uint priority = 0; - uint tag = 0; + ccstd::string name; + uint priority = 0; + uint tag = 0; RenderQueueDescList renderQueues; }; @@ -60,23 +60,23 @@ public: virtual void render(scene::Camera *camera) = 0; inline const ccstd::string &getName() const { return _name; } - inline uint getPriority() const { return _priority; } - inline uint getTag() const { return _tag; } - inline RenderFlow * getFlow() const { return _flow; } + inline uint getPriority() const { return _priority; } + inline uint getTag() const { return _tag; } + inline RenderFlow *getFlow() const { return _flow; } protected: gfx::Rect _renderArea; // Generate quad ia, cannot be updated inside renderpass - gfx::InputAssembler * _inputAssembler{nullptr}; - RenderQueueDescList _renderQueueDescriptors; + gfx::InputAssembler *_inputAssembler{nullptr}; + RenderQueueDescList _renderQueueDescriptors; ccstd::vector _renderQueues; - RenderPipeline * _pipeline = nullptr; - RenderFlow * _flow = nullptr; - gfx::Device * _device = nullptr; - ccstd::string _name; - uint _priority = 0; - uint _tag = 0; - gfx::ColorList _clearColors = {{0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}}; + RenderPipeline *_pipeline = nullptr; + RenderFlow *_flow = nullptr; + gfx::Device *_device = nullptr; + ccstd::string _name; + uint _priority = 0; + uint _tag = 0; + gfx::ColorList _clearColors = {{0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F, 0.0F}}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/SceneCulling.cpp b/native/cocos/renderer/pipeline/SceneCulling.cpp index 64d99edb66..47e8c52329 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.cpp +++ b/native/cocos/renderer/pipeline/SceneCulling.cpp @@ -51,7 +51,7 @@ namespace pipeline { RenderObject genRenderObject(const scene::Model *model, const scene::Camera *camera) { float depth = 0; if (model->getNode()) { - auto * node = model->getTransform(); + auto *node = model->getTransform(); cc::Vec3 position; cc::Vec3::subtract(node->getWorldPosition(), camera->getPosition(), &position); depth = position.dot(camera->getForward()); @@ -79,82 +79,82 @@ void updateSphereLight(scene::Shadows *shadowInfo, const scene::Light *light, cc shadowInfo->setShadowMapDirty(false); const auto &position = node->getWorldPosition(); - const auto &normal = shadowInfo->getNormal(); - const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting - const auto ndL = normal.dot(position); - const auto lx = position.x; - const auto ly = position.y; - const auto lz = position.z; - const auto nx = normal.x; - const auto ny = normal.y; - const auto nz = normal.z; - auto & matLight = shadowInfo->getMatLight(); - matLight.m[0] = ndL - distance - lx * nx; - matLight.m[1] = -ly * nx; - matLight.m[2] = -lz * nx; - matLight.m[3] = -nx; - matLight.m[4] = -lx * ny; - matLight.m[5] = ndL - distance - ly * ny; - matLight.m[6] = -lz * ny; - matLight.m[7] = -ny; - matLight.m[8] = -lx * nz; - matLight.m[9] = -ly * nz; - matLight.m[10] = ndL - distance - lz * nz; - matLight.m[11] = -nz; - matLight.m[12] = lx * distance; - matLight.m[13] = ly * distance; - matLight.m[14] = lz * distance; - matLight.m[15] = ndL; + const auto &normal = shadowInfo->getNormal(); + const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting + const auto ndL = normal.dot(position); + const auto lx = position.x; + const auto ly = position.y; + const auto lz = position.z; + const auto nx = normal.x; + const auto ny = normal.y; + const auto nz = normal.z; + auto &matLight = shadowInfo->getMatLight(); + matLight.m[0] = ndL - distance - lx * nx; + matLight.m[1] = -ly * nx; + matLight.m[2] = -lz * nx; + matLight.m[3] = -nx; + matLight.m[4] = -lx * ny; + matLight.m[5] = ndL - distance - ly * ny; + matLight.m[6] = -lz * ny; + matLight.m[7] = -ny; + matLight.m[8] = -lx * nz; + matLight.m[9] = -ly * nz; + matLight.m[10] = ndL - distance - lz * nz; + matLight.m[11] = -nz; + matLight.m[12] = lx * distance; + matLight.m[13] = ly * distance; + matLight.m[14] = lz * distance; + matLight.m[15] = ndL; memcpy(shadowUBO->data() + UBOShadow::MAT_LIGHT_PLANE_PROJ_OFFSET, matLight.m, sizeof(matLight)); } void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *shadowUBO) { - const auto * node = light->getNode(); - const auto & rotation = node->getWorldRotation(); + const auto *node = light->getNode(); + const auto &rotation = node->getWorldRotation(); const Quaternion qt(rotation.x, rotation.y, rotation.z, rotation.w); - cc::Vec3 forward(0.0F, 0.0F, -1.0F); + cc::Vec3 forward(0.0F, 0.0F, -1.0F); forward.transformQuat(qt); - const auto &normal = shadowInfo->getNormal(); - const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting - const auto ndL = normal.dot(forward); - const auto scale = 1.0F / ndL; - const auto lx = forward.x * scale; - const auto ly = forward.y * scale; - const auto lz = forward.z * scale; - const auto nx = normal.x; - const auto ny = normal.y; - const auto nz = normal.z; - auto & matLight = shadowInfo->getMatLight(); - matLight.m[0] = 1 - nx * lx; - matLight.m[1] = -nx * ly; - matLight.m[2] = -nx * lz; - matLight.m[3] = 0; - matLight.m[4] = -ny * lx; - matLight.m[5] = 1 - ny * ly; - matLight.m[6] = -ny * lz; - matLight.m[7] = 0; - matLight.m[8] = -nz * lx; - matLight.m[9] = -nz * ly; - matLight.m[10] = 1 - nz * lz; - matLight.m[11] = 0; - matLight.m[12] = lx * distance; - matLight.m[13] = ly * distance; - matLight.m[14] = lz * distance; - matLight.m[15] = 1; + const auto &normal = shadowInfo->getNormal(); + const auto distance = shadowInfo->getDistance() + 0.001F; // avoid z-fighting + const auto ndL = normal.dot(forward); + const auto scale = 1.0F / ndL; + const auto lx = forward.x * scale; + const auto ly = forward.y * scale; + const auto lz = forward.z * scale; + const auto nx = normal.x; + const auto ny = normal.y; + const auto nz = normal.z; + auto &matLight = shadowInfo->getMatLight(); + matLight.m[0] = 1 - nx * lx; + matLight.m[1] = -nx * ly; + matLight.m[2] = -nx * lz; + matLight.m[3] = 0; + matLight.m[4] = -ny * lx; + matLight.m[5] = 1 - ny * ly; + matLight.m[6] = -ny * lz; + matLight.m[7] = 0; + matLight.m[8] = -nz * lx; + matLight.m[9] = -nz * ly; + matLight.m[10] = 1 - nz * lz; + matLight.m[11] = 0; + matLight.m[12] = lx * distance; + matLight.m[13] = ly * distance; + matLight.m[14] = lz * distance; + matLight.m[15] = 1; memcpy(shadowUBO->data() + UBOShadow::MAT_LIGHT_PLANE_PROJ_OFFSET, matLight.m, sizeof(matLight)); memcpy(shadowUBO->data() + UBOShadow::SHADOW_COLOR_OFFSET, shadowInfo->getShadowColor4f().data(), sizeof(float) * 4); } void updatePlanarNormalAndDistance(scene::Shadows *shadowInfo, ccstd::array *shadowUBO) { - const Vec3 normal = shadowInfo->getNormal().getNormalized(); + const Vec3 normal = shadowInfo->getNormal().getNormalized(); const float planarNDInfo[4] = {normal.x, normal.y, normal.z, shadowInfo->getDistance()}; memcpy(shadowUBO->data() + UBOShadow::PLANAR_NORMAL_DISTANCE_INFO_OFFSET, &planarNDInfo, sizeof(planarNDInfo)); } void validPunctualLightsCulling(RenderPipeline *pipeline, scene::Camera *camera) { - const auto *const scene = camera->getScene(); + const auto *const scene = camera->getScene(); PipelineSceneData *sceneData = pipeline->getPipelineSceneData(); sceneData->clearValidPunctualLights(); @@ -191,9 +191,9 @@ Mat4 getCameraWorldMatrix(const scene::Camera *camera) { return out; } - const Node * cameraNode = camera->getNode(); - const cc::Vec3 & position = cameraNode->getWorldPosition(); - const Quaternion &rotation = cameraNode->getWorldRotation(); + const Node *cameraNode = camera->getNode(); + const cc::Vec3 &position = cameraNode->getWorldPosition(); + const Quaternion &rotation = cameraNode->getWorldRotation(); Mat4::fromRT(rotation, position, &out); out.m[8] *= -1.0F; @@ -204,9 +204,9 @@ Mat4 getCameraWorldMatrix(const scene::Camera *camera) { } void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quaternion &rotation, float range, geometry::Frustum *dirLightFrustum) { - const float radius = cameraBoundingSphere->getRadius(); + const float radius = cameraBoundingSphere->getRadius(); const cc::Vec3 &position = cameraBoundingSphere->getCenter(); - Mat4 matWorldTrans; + Mat4 matWorldTrans; Mat4::fromRT(rotation, position, &matWorldTrans); matWorldTrans.m[8] *= -1.0F; matWorldTrans.m[9] *= -1.0F; @@ -216,30 +216,30 @@ void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quater } void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera *camera, geometry::Frustum *out) { - const gfx::Device * device = gfx::Device::getInstance(); - PipelineSceneData *const sceneData = pipeline->getPipelineSceneData(); - scene::Shadows * shadowInfo = sceneData->getShadows(); - const scene::RenderScene *const scene = camera->getScene(); - const scene::DirectionalLight * mainLight = scene->getMainLight(); - const float invisibleOcclusionRange = mainLight->getShadowInvisibleOcclusionRange(); - const float shadowMapWidth = shadowInfo->getSize().x; - const auto * node = mainLight->getNode(); - const Quaternion & rotation = node->getWorldRotation(); - const bool fixedArea = mainLight->isShadowFixedArea(); + const gfx::Device *device = gfx::Device::getInstance(); + PipelineSceneData *const sceneData = pipeline->getPipelineSceneData(); + scene::Shadows *shadowInfo = sceneData->getShadows(); + const scene::RenderScene *const scene = camera->getScene(); + const scene::DirectionalLight *mainLight = scene->getMainLight(); + const float invisibleOcclusionRange = mainLight->getShadowInvisibleOcclusionRange(); + const float shadowMapWidth = shadowInfo->getSize().x; + const auto *node = mainLight->getNode(); + const Quaternion &rotation = node->getWorldRotation(); + const bool fixedArea = mainLight->isShadowFixedArea(); if (fixedArea) { - const float x = mainLight->getShadowOrthoSize(); - const float y = mainLight->getShadowOrthoSize(); + const float x = mainLight->getShadowOrthoSize(); + const float y = mainLight->getShadowOrthoSize(); const float nearClamp = mainLight->getShadowNear(); - const float farClamp = mainLight->getShadowFar(); + const float farClamp = mainLight->getShadowFar(); Mat4 matShadowTrans; Mat4::fromRT(rotation, node->getWorldPosition(), &matShadowTrans); - Mat4 matShadowView = matShadowTrans.getInversed(); - Mat4 matShadowViewInv = matShadowTrans.clone(); - const float projectionSinY = device->getCapabilities().clipSpaceSignY; - const float clipSpaceMinZ = device->getCapabilities().clipSpaceMinZ; - Mat4 matShadowProj; + Mat4 matShadowView = matShadowTrans.getInversed(); + Mat4 matShadowViewInv = matShadowTrans.clone(); + const float projectionSinY = device->getCapabilities().clipSpaceSignY; + const float clipSpaceMinZ = device->getCapabilities().clipSpaceMinZ; + Mat4 matShadowProj; Mat4::createOrthographicOffCenter(-x, x, -y, y, -nearClamp, farClamp, clipSpaceMinZ, projectionSinY, 0, &matShadowProj); Mat4 matShadowViewProj = matShadowProj * matShadowView; @@ -250,7 +250,7 @@ void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera out->createOrtho(x * 2.0F, y * 2.0F, nearClamp, farClamp, matShadowViewInv); } else { // Raw data. - const Mat4 matWorldTrans = getCameraWorldMatrix(camera); + const Mat4 matWorldTrans = getCameraWorldMatrix(camera); geometry::Frustum validFrustum; validFrustum.setType(geometry::ShapeEnum::SHAPE_FRUSTUM_ACCURATE); validFrustum.split(0.1F, mainLight->getShadowDistance(), camera->getAspect(), camera->getFov(), matWorldTrans); @@ -260,7 +260,7 @@ void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera // view matrix with range back. Mat4 matShadowTrans; Mat4::fromRT(rotation, Vec3::ZERO, &matShadowTrans); - Mat4 matShadowView = matShadowTrans.getInversed(); + Mat4 matShadowView = matShadowTrans.getInversed(); Mat4 matShadowViewInv = matShadowTrans.clone(); const Mat4 shadowViewArbitraryPos = matShadowView.clone(); @@ -271,12 +271,12 @@ void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera castLightViewBounds.merge(lightViewFrustum); const float r = castLightViewBounds.getHalfExtents().z * 2.0F; - Vec3 shadowPos(castLightViewBounds.getCenter().x, castLightViewBounds.getCenter().y, + Vec3 shadowPos(castLightViewBounds.getCenter().x, castLightViewBounds.getCenter().y, castLightViewBounds.getCenter().z + castLightViewBounds.getHalfExtents().z + invisibleOcclusionRange); shadowPos.transformMat4(shadowPos, matShadowViewInv); Mat4::fromRT(rotation, shadowPos, &matShadowTrans); - matShadowView = matShadowTrans.getInversed(); + matShadowView = matShadowTrans.getInversed(); matShadowViewInv = matShadowTrans.clone(); // calculate projection matrix params. @@ -294,27 +294,27 @@ void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera // snap to whole texels const float halfOrthoSize = orthoSize * 0.5F; - Mat4 matShadowProj; + Mat4 matShadowProj; const float projectionSinY = device->getCapabilities().clipSpaceSignY; - const float clipSpaceMinZ = device->getCapabilities().clipSpaceMinZ; + const float clipSpaceMinZ = device->getCapabilities().clipSpaceMinZ; Mat4::createOrthographicOffCenter(-halfOrthoSize, halfOrthoSize, -halfOrthoSize, halfOrthoSize, 0.1F, shadowInfo->getShadowCameraFar(), clipSpaceMinZ, projectionSinY, 0, &matShadowProj); if (shadowMapWidth > 0.0F) { const Mat4 matShadowViewProjArbitraryPos = matShadowProj * shadowViewArbitraryPos; - Vec3 projPos; + Vec3 projPos; projPos.transformMat4(shadowPos, matShadowViewProjArbitraryPos); const float invActualSize = 2.0F / shadowMapWidth; - const Vec2 texelSize(invActualSize, invActualSize); + const Vec2 texelSize(invActualSize, invActualSize); const float modX = fmodf(projPos.x, texelSize.x); const float modY = fmodf(projPos.y, texelSize.y); - const Vec3 projSnap(projPos.x - modX, projPos.y - modY, projPos.z); + const Vec3 projSnap(projPos.x - modX, projPos.y - modY, projPos.z); const Mat4 matShadowViewProjArbitaryPosInv = matShadowViewProjArbitraryPos.getInversed(); - Vec3 snap; + Vec3 snap; snap.transformMat4(projSnap, matShadowViewProjArbitaryPosInv); Mat4::fromRT(rotation, snap, &matShadowTrans); - matShadowView = matShadowTrans.getInversed(); + matShadowView = matShadowTrans.getInversed(); matShadowViewInv = matShadowTrans.clone(); out->createOrtho(orthoSize, orthoSize, 0.1F, shadowInfo->getShadowCameraFar(), matShadowViewInv); } else { @@ -332,15 +332,15 @@ void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera } void sceneCulling(RenderPipeline *pipeline, scene::Camera *camera) { CC_PROFILE(SceneCulling); - PipelineSceneData *const sceneData = pipeline->getPipelineSceneData(); - const scene::Shadows * shadowInfo = sceneData->getShadows(); - const scene::Skybox * skyBox = sceneData->getSkybox(); - const scene::RenderScene *const scene = camera->getScene(); - const scene::DirectionalLight * mainLight = scene->getMainLight(); - geometry::Frustum dirLightFrustum; + PipelineSceneData *const sceneData = pipeline->getPipelineSceneData(); + const scene::Shadows *shadowInfo = sceneData->getShadows(); + const scene::Skybox *skyBox = sceneData->getSkybox(); + const scene::RenderScene *const scene = camera->getScene(); + const scene::DirectionalLight *mainLight = scene->getMainLight(); + geometry::Frustum dirLightFrustum; RenderObjectList dirShadowObjects; - bool isShadowMap = false; + bool isShadowMap = false; if (shadowInfo != nullptr && shadowInfo->isEnabled() && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) { isShadowMap = true; @@ -372,8 +372,8 @@ void sceneCulling(RenderPipeline *pipeline, scene::Camera *camera) { castShadowObject.emplace_back(genRenderObject(model, camera)); } - const auto visibility = camera->getVisibility(); - const auto *const node = model->getNode(); + const auto visibility = camera->getVisibility(); + const auto *const node = model->getNode(); if ((model->getNode() && ((visibility & node->getLayer()) == node->getLayer())) || (visibility & static_cast(model->getVisFlags()))) { @@ -407,8 +407,8 @@ void sceneCulling(RenderPipeline *pipeline, scene::Camera *camera) { for (const auto &model : scene->getModels()) { // filter model by view visibility if (model->isEnabled()) { - const auto visibility = camera->getVisibility(); - const auto *const node = model->getNode(); + const auto visibility = camera->getVisibility(); + const auto *const node = model->getNode(); // cast shadow render Object if (model->isCastShadow()) { diff --git a/native/cocos/renderer/pipeline/SceneCulling.h b/native/cocos/renderer/pipeline/SceneCulling.h index c3f65cebf8..8659570616 100644 --- a/native/cocos/renderer/pipeline/SceneCulling.h +++ b/native/cocos/renderer/pipeline/SceneCulling.h @@ -45,14 +45,14 @@ struct RenderObject; class RenderPipeline; RenderObject genRenderObject(const scene::Model *, const scene::Camera *); -void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera *camera, geometry::Frustum *out); -void validPunctualLightsCulling(RenderPipeline *pipeline, scene::Camera *camera); -void sceneCulling(RenderPipeline *, scene::Camera *); -void updateSphereLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); -void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); -void updatePlanarNormalAndDistance(scene::Shadows *shadowInfo, ccstd::array *shadowUBO); -void getShadowWorldMatrix(const geometry::Sphere *sphere, const cc::Quaternion &rotation, const cc::Vec3 &dir, cc::Mat4 *shadowWorldMat, cc::Vec3 *out); -Mat4 getCameraWorldMatrix(const scene::Camera *camera); -void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quaternion &rotation, float range, geometry::Frustum *dirLightFrustum); +void quantizeDirLightShadowCamera(RenderPipeline *pipeline, const scene::Camera *camera, geometry::Frustum *out); +void validPunctualLightsCulling(RenderPipeline *pipeline, scene::Camera *camera); +void sceneCulling(RenderPipeline *, scene::Camera *); +void updateSphereLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); +void updateDirLight(scene::Shadows *shadowInfo, const scene::Light *light, ccstd::array *); +void updatePlanarNormalAndDistance(scene::Shadows *shadowInfo, ccstd::array *shadowUBO); +void getShadowWorldMatrix(const geometry::Sphere *sphere, const cc::Quaternion &rotation, const cc::Vec3 &dir, cc::Mat4 *shadowWorldMat, cc::Vec3 *out); +Mat4 getCameraWorldMatrix(const scene::Camera *camera); +void updateDirFrustum(const geometry::Sphere *cameraBoundingSphere, const Quaternion &rotation, float range, geometry::Frustum *dirLightFrustum); } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp index 7294d9c9fb..b92009f85c 100644 --- a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp +++ b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.cpp @@ -45,10 +45,10 @@ namespace pipeline { ShadowMapBatchedQueue::ShadowMapBatchedQueue(RenderPipeline *pipeline) : _phaseID(getPhaseID("shadow-caster")) { - _pipeline = pipeline; - _buffer = pipeline->getDescriptorSet()->getBuffer(UBOShadow::BINDING); + _pipeline = pipeline; + _buffer = pipeline->getDescriptorSet()->getBuffer(UBOShadow::BINDING); _instancedQueue = ccnew RenderInstancedQueue; - _batchedQueue = ccnew RenderBatchedQueue; + _batchedQueue = ccnew RenderBatchedQueue; } ShadowMapBatchedQueue::~ShadowMapBatchedQueue() = default; @@ -56,10 +56,10 @@ ShadowMapBatchedQueue::~ShadowMapBatchedQueue() = default; void ShadowMapBatchedQueue::gatherLightPasses(const scene::Camera *camera, const scene::Light *light, gfx::CommandBuffer *cmdBuffer) { clear(); - const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); - const scene::Shadows * shadowInfo = sceneData->getShadows(); + const PipelineSceneData *sceneData = _pipeline->getPipelineSceneData(); + const scene::Shadows *shadowInfo = sceneData->getShadows(); if (light && shadowInfo->isEnabled() && shadowInfo->getType() == scene::ShadowType::SHADOW_MAP) { - const RenderObjectList &dirShadowObjects = sceneData->getDirShadowObjects(); + const RenderObjectList &dirShadowObjects = sceneData->getDirShadowObjects(); const RenderObjectList &castShadowObjects = sceneData->isCastShadowObjects(); switch (light->getType()) { case scene::LightType::DIRECTIONAL: { @@ -70,11 +70,11 @@ void ShadowMapBatchedQueue::gatherLightPasses(const scene::Camera *camera, const } break; case scene::LightType::SPOT: { - const auto *spotLight = static_cast(light); - const Mat4 matShadowView = light->getNode()->getWorldMatrix().getInversed(); - Mat4 matShadowProj; + const auto *spotLight = static_cast(light); + const Mat4 matShadowView = light->getNode()->getWorldMatrix().getInversed(); + Mat4 matShadowProj; Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowProj); - const Mat4 matShadowViewProj = matShadowProj * matShadowView; + const Mat4 matShadowViewProj = matShadowProj * matShadowView; geometry::AABB ab; for (const auto ro : castShadowObjects) { const auto *model = ro.model; @@ -122,8 +122,8 @@ void ShadowMapBatchedQueue::add(const scene::Model *model) { } for (const auto &subModel : model->getSubModels()) { - const auto *pass = subModel->getPass(shadowPassIdx); - const auto batchingScheme = pass->getBatchingScheme(); + const auto *pass = subModel->getPass(shadowPassIdx); + const auto batchingScheme = pass->getBatchingScheme(); if (batchingScheme == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = InstancedBuffer::get(subModel->getPass(shadowPassIdx)); @@ -147,10 +147,10 @@ void ShadowMapBatchedQueue::recordCommandBuffer(gfx::Device *device, gfx::Render for (size_t i = 0; i < _subModels.size(); i++) { const auto *const subModel = _subModels[i]; - auto *const shader = _shaders[i]; - const auto * pass = _passes[i]; - auto *const ia = subModel->getInputAssembler(); - auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); + auto *const shader = _shaders[i]; + const auto *pass = _passes[i]; + auto *const ia = subModel->getInputAssembler(); + auto *const pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); cmdBuffer->bindPipelineState(pso); cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); diff --git a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h index d38202855c..d77bf8480e 100644 --- a/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h +++ b/native/cocos/renderer/pipeline/ShadowMapBatchedQueue.h @@ -54,14 +54,14 @@ public: private: int getShadowPassIndex(const scene::Model *model) const; - RenderPipeline * _pipeline = nullptr; + RenderPipeline *_pipeline = nullptr; ccstd::vector _subModels; - ccstd::vector _passes; - ccstd::vector _shaders; - RenderInstancedQueue * _instancedQueue = nullptr; - RenderBatchedQueue * _batchedQueue = nullptr; - gfx::Buffer * _buffer = nullptr; - uint _phaseID = 0; + ccstd::vector _passes; + ccstd::vector _shaders; + RenderInstancedQueue *_instancedQueue = nullptr; + RenderBatchedQueue *_batchedQueue = nullptr; + gfx::Buffer *_buffer = nullptr; + uint _phaseID = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/UIPhase.cpp b/native/cocos/renderer/pipeline/UIPhase.cpp index 30e77d5848..902f3d597d 100644 --- a/native/cocos/renderer/pipeline/UIPhase.cpp +++ b/native/cocos/renderer/pipeline/UIPhase.cpp @@ -38,7 +38,7 @@ namespace pipeline { void UIPhase::activate(RenderPipeline *pipeline) { _pipeline = pipeline; - _phaseID = getPhaseID("default"); + _phaseID = getPhaseID("default"); }; void UIPhase::render(scene::Camera *camera, gfx::RenderPass *renderPass) { @@ -51,10 +51,10 @@ void UIPhase::render(scene::Camera *camera, gfx::RenderPass *renderPass) { for (size_t i = 0; i < batch->shaders.size(); ++i) { const auto *pass = batch->passes[i]; if (pass->getPhase() != _phaseID) continue; - auto *shader = batch->shaders[i]; + auto *shader = batch->shaders[i]; auto *inputAssembler = batch->inputAssembler; - auto *ds = batch->descriptorSet; - auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); + auto *ds = batch->descriptorSet; + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass); cmdBuff->bindPipelineState(pso); cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); cmdBuff->bindInputAssembler(inputAssembler); diff --git a/native/cocos/renderer/pipeline/UIPhase.h b/native/cocos/renderer/pipeline/UIPhase.h index 27a85b7ead..769d4a3a5a 100644 --- a/native/cocos/renderer/pipeline/UIPhase.h +++ b/native/cocos/renderer/pipeline/UIPhase.h @@ -45,7 +45,7 @@ public: protected: RenderPipeline *_pipeline = nullptr; - uint _phaseID = 0; + uint _phaseID = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index c9cccc69f4..65fde78fa0 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -39,21 +39,21 @@ namespace render { #pragma region predefine using PmrString = ccstd::pmr::string; -using RAG = ResourceAccessGraph; -using LGD = LayoutGraphData; -using BarrierMap = FlatMap; -using AccessVertex = ResourceAccessGraph::vertex_descriptor; +using RAG = ResourceAccessGraph; +using LGD = LayoutGraphData; +using BarrierMap = FlatMap; +using AccessVertex = ResourceAccessGraph::vertex_descriptor; using InputStatusTuple = std::tuple; -using ResourceHandle = ResourceGraph::vertex_descriptor; -using ResourceNames = PmrFlatSet; +using ResourceHandle = ResourceGraph::vertex_descriptor; +using ResourceNames = PmrFlatSet; -auto defaultAccess = gfx::MemoryAccessBit::NONE; +auto defaultAccess = gfx::MemoryAccessBit::NONE; auto defaultVisibility = gfx::ShaderStageFlagBit::NONE; constexpr uint32_t EXPECT_START_ID = 0; -constexpr uint32_t INVALID_ID = 0xFFFFFFFF; +constexpr uint32_t INVALID_ID = 0xFFFFFFFF; -using AccessTable = PmrFlatMap; +using AccessTable = PmrFlatMap; using ExternalResMap = PmrFlatMap; // for scoped enum only @@ -69,7 +69,7 @@ public: static auto toGfxAccess = GfxTypeConverter(); //AccessStatus.vertID : in resourceNode it's resource ID; in barrierNode it's pass ID. -AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex curVertID, const InputStatusTuple &status); +AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex curVertID, const InputStatusTuple &status); gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, const PmrString &slotName); void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, InputStatusTuple status, const Range &range); @@ -134,8 +134,8 @@ void buildAccessGraph(const RenderGraph &renderGraph, const LayoutGraphData &lgd struct BarrierVisitor : public boost::bfs_visitor<> { using Vertex = ResourceAccessGraph::vertex_descriptor; - using Edge = ResourceAccessGraph::edge_descriptor; - using Graph = ResourceAccessGraph; + using Edge = ResourceAccessGraph::edge_descriptor; + using Graph = ResourceAccessGraph; explicit BarrierVisitor(const ResourceGraph &rg, BarrierMap &barriers, ExternalResMap &extMap, ResourceNames &externalNames) : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), externalResNames(externalNames) { @@ -151,16 +151,16 @@ struct BarrierVisitor : public boost::bfs_visitor<> { // - beginAccess: NONE, endAccess: not NONE ===> split end barrier Vertex from = source(e, g); - Vertex to = target(e, g); + Vertex to = target(e, g); bool isAdjacent = isPassExecAdjecent(from, to); const ResourceAccessNode &fromAccess = get(ResourceAccessGraph::AccessNode, g, from); - const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNode, g, to); + const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNode, g, to); - std::vector commonResources; + std::vector commonResources; const std::vector &fromStatus = fromAccess.attachemntStatus; - const std::vector &toStatus = toAccess.attachemntStatus; + const std::vector &toStatus = toAccess.attachemntStatus; std::set_intersection(fromStatus.begin(), fromStatus.end(), toStatus.begin(), toStatus.end(), @@ -176,15 +176,15 @@ struct BarrierVisitor : public boost::bfs_visitor<> { barrierMap.emplace(to, BarrierNode{}); } - std::vector &srcRearBarriers = barrierMap[from].rearBarriers; + std::vector &srcRearBarriers = barrierMap[from].rearBarriers; std::vector &dstFrontBarriers = barrierMap[to].frontBarriers; // NOLINTNEXTLINE for (uint32_t i = 0; i < commonResources.size(); ++i) { - const uint32_t resourceID = commonResources[i].vertID; - auto findAccessByID = [resourceID](const AccessStatus &resAccess) { return resAccess.vertID == resourceID; }; - auto fromIter = std::find_if(fromStatus.begin(), fromStatus.end(), findAccessByID); - auto toIter = std::find_if(toStatus.begin(), toStatus.end(), findAccessByID); + const uint32_t resourceID = commonResources[i].vertID; + auto findAccessByID = [resourceID](const AccessStatus &resAccess) { return resAccess.vertID == resourceID; }; + auto fromIter = std::find_if(fromStatus.begin(), fromStatus.end(), findAccessByID); + auto toIter = std::find_if(toStatus.begin(), toStatus.end(), findAccessByID); // can't happen CC_ASSERT(fromIter != fromStatus.end()); @@ -220,25 +220,25 @@ struct BarrierVisitor : public boost::bfs_visitor<> { } else { if (isAdjacent) { - (*srcBarrierIter).beginStatus.vertID = from; + (*srcBarrierIter).beginStatus.vertID = from; (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; - (*srcBarrierIter).beginStatus.access = (*fromIter).access; - (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; - (*srcBarrierIter).beginStatus.range = (*fromIter).range; + (*srcBarrierIter).beginStatus.access = (*fromIter).access; + (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; + (*srcBarrierIter).beginStatus.range = (*fromIter).range; - (*srcBarrierIter).endStatus.vertID = to; + (*srcBarrierIter).endStatus.vertID = to; (*srcBarrierIter).endStatus.visibility = (*toIter).visibility; - (*srcBarrierIter).endStatus.access = (*toIter).access; - (*srcBarrierIter).endStatus.passType = (*toIter).passType; - (*srcBarrierIter).endStatus.range = (*toIter).range; + (*srcBarrierIter).endStatus.access = (*toIter).access; + (*srcBarrierIter).endStatus.passType = (*toIter).passType; + (*srcBarrierIter).endStatus.range = (*toIter).range; } else { if (from > (*srcBarrierIter).beginStatus.vertID) { - uint32_t siblingPass = (*srcBarrierIter).beginStatus.vertID; - (*srcBarrierIter).beginStatus.vertID = from; + uint32_t siblingPass = (*srcBarrierIter).beginStatus.vertID; + (*srcBarrierIter).beginStatus.vertID = from; (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; - (*srcBarrierIter).beginStatus.access = (*fromIter).access; - (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; - (*srcBarrierIter).beginStatus.range = (*fromIter).range; + (*srcBarrierIter).beginStatus.access = (*fromIter).access; + (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; + (*srcBarrierIter).beginStatus.range = (*fromIter).range; auto siblingIter = std::find_if(barrierMap[siblingPass].rearBarriers.begin(), barrierMap[siblingPass].rearBarriers.end(), [resourceID](const Barrier &barrier) { @@ -274,17 +274,17 @@ struct BarrierVisitor : public boost::bfs_visitor<> { } else { if (isAdjacent) { //adjacent, barrier should be commit at fromPass, and remove this iter from dstBarriers - (*srcBarrierIter).beginStatus.vertID = from; + (*srcBarrierIter).beginStatus.vertID = from; (*srcBarrierIter).beginStatus.visibility = (*fromIter).visibility; - (*srcBarrierIter).beginStatus.access = (*fromIter).access; - (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; - (*srcBarrierIter).beginStatus.range = (*fromIter).range; + (*srcBarrierIter).beginStatus.access = (*fromIter).access; + (*srcBarrierIter).beginStatus.passType = (*fromIter).passType; + (*srcBarrierIter).beginStatus.range = (*fromIter).range; - (*srcBarrierIter).endStatus.vertID = to; + (*srcBarrierIter).endStatus.vertID = to; (*srcBarrierIter).endStatus.visibility = (*toIter).visibility; - (*srcBarrierIter).endStatus.access = (*toIter).access; - (*srcBarrierIter).endStatus.passType = (*toIter).passType; - (*srcBarrierIter).endStatus.range = (*toIter).range; + (*srcBarrierIter).endStatus.access = (*toIter).access; + (*srcBarrierIter).endStatus.passType = (*toIter).passType; + (*srcBarrierIter).endStatus.range = (*toIter).range; dstFrontBarriers.erase(dstBarrierIter); } else { @@ -302,12 +302,12 @@ struct BarrierVisitor : public boost::bfs_visitor<> { // 5 and 6 logically adjacent but not adjacent in execution order. // barrier for ResA between 2 - 6 can be totally replace by 5 - 6 if (to < (*dstBarrierIter).endStatus.vertID) { - uint32_t siblingPass = (*dstBarrierIter).endStatus.vertID; - (*dstBarrierIter).endStatus.vertID = to; + uint32_t siblingPass = (*dstBarrierIter).endStatus.vertID; + (*dstBarrierIter).endStatus.vertID = to; (*dstBarrierIter).endStatus.visibility = (*toIter).visibility; - (*dstBarrierIter).endStatus.access = (*toIter).access; - (*dstBarrierIter).endStatus.passType = (*toIter).passType; - (*dstBarrierIter).endStatus.range = (*toIter).range; + (*dstBarrierIter).endStatus.access = (*toIter).access; + (*dstBarrierIter).endStatus.passType = (*toIter).passType; + (*dstBarrierIter).endStatus.range = (*toIter).range; //remove the further redundant barrier auto siblingIter = std::find_if(barrierMap[siblingPass].frontBarriers.begin(), barrierMap[siblingPass].frontBarriers.end(), @@ -324,12 +324,12 @@ struct BarrierVisitor : public boost::bfs_visitor<> { //----------------------------------------------check external---------------------------------------------- auto barrierExternalRes = [&](const AccessStatus &rescAccess, bool isFrom) { - uint32_t rescID = rescAccess.vertID; - bool externalRes = get(get(ResourceGraph::Traits, resourceGraph), rescID).hasSideEffects(); - Vertex vert = isFrom ? from : to; + uint32_t rescID = rescAccess.vertID; + bool externalRes = get(get(ResourceGraph::Traits, resourceGraph), rescID).hasSideEffects(); + Vertex vert = isFrom ? from : to; if (externalRes) { const PmrString &resName = get(ResourceGraph::Name, resourceGraph, rescID); - auto iter = externalMap.find(resName); + auto iter = externalMap.find(resName); //first meet in this frame if (externalResNames.find(resName) == externalResNames.end()) { //first meet in whole program @@ -400,11 +400,11 @@ struct BarrierVisitor : public boost::bfs_visitor<> { batchBarriers(e, g); } - BarrierMap & barrierMap; + BarrierMap &barrierMap; const ResourceGraph &resourceGraph; - ExternalResMap &externalMap; //last frame to curr frame status transition - ResourceNames & externalResNames; //first meet in this frame + ExternalResMap &externalMap; //last frame to curr frame status transition + ResourceNames &externalResNames; //first meet in this frame }; void FrameGraphDispatcher::buildBarriers() { @@ -416,12 +416,12 @@ void FrameGraphDispatcher::buildBarriers() { // found pass id in this map ? barriers you should commit when run into this pass // : or no extra barrier needed. - BarrierMap batchedBarriers; + BarrierMap batchedBarriers; ResourceNames namesSet; { // _externalResNames records external resource between frames - BarrierVisitor visitor(resourceGraph, batchedBarriers, _externalResMap, namesSet); - auto colors = rag.colors(scratch); + BarrierVisitor visitor(resourceGraph, batchedBarriers, _externalResMap, namesSet); + auto colors = rag.colors(scratch); boost::queue q; boost::breadth_first_visit( @@ -450,10 +450,10 @@ bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, InputStatusTuple status, const Range &range) { // std::tie(passType, rescName, visibility, access) ; - PassType passType = std::get<0>(status); - const PmrString & rescName = std::get<1>(status); + PassType passType = std::get<0>(status); + const PmrString &rescName = std::get<1>(status); gfx::ShaderStageFlagBit visibility = std::get<2>(status); - gfx::MemoryAccessBit access = std::get<3>(status); + gfx::MemoryAccessBit access = std::get<3>(status); CC_EXPECTS(rg.valueIndex.find(rescName) != rg.valueIndex.end()); uint32_t rescID = rg.valueIndex.at(rescName); @@ -472,15 +472,15 @@ void addAccessNode(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, } AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex curVertID, const InputStatusTuple &status) { - PassType passType = std::get<0>(status); - const PmrString & rescName = std::get<1>(status); + PassType passType = std::get<0>(status); + const PmrString &rescName = std::get<1>(status); gfx::ShaderStageFlagBit visibility = std::get<2>(status); - gfx::MemoryAccessBit access = std::get<3>(status); + gfx::MemoryAccessBit access = std::get<3>(status); AccessVertex lastVertID = INVALID_ID; CC_EXPECTS(rag.resourceIndex.find(rescName) != rag.resourceIndex.end()); auto resourceID = rag.resourceIndex[rescName]; - auto iter = accessRecord.find(resourceID); + auto iter = accessRecord.find(resourceID); if (iter == accessRecord.end()) { accessRecord.emplace( resourceID, @@ -497,13 +497,13 @@ AccessVertex dependencyCheck(RAG &rag, AccessTable &accessRecord, AccessVertex c CC_ENSURES(res.second); } trans.currStatus = {curVertID, visibility, access, passType, Range{}}; - lastVertID = trans.lastStatus.vertID; + lastVertID = trans.lastStatus.vertID; } else { bool needTransition = (trans.currStatus.access != access) || (trans.currStatus.passType != passType) || (trans.currStatus.visibility != visibility); if (needTransition) { trans.lastStatus = trans.currStatus; trans.currStatus = {curVertID, visibility, access, passType, Range{}}; - auto res = add_edge(trans.lastStatus.vertID, curVertID, rag); + auto res = add_edge(trans.lastStatus.vertID, curVertID, rag); CC_ENSURES(res.second); lastVertID = trans.lastStatus.vertID; } @@ -516,7 +516,7 @@ gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, auto vis = gfx::ShaderStageFlagBit::NONE; const auto &layout = get(LGD::Layout, lgd, passID); - bool found = false; + bool found = false; auto compare = [](const PmrString &name, const uint32_t slot) { return boost::lexical_cast(name) == slot; @@ -524,7 +524,7 @@ gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, for (const auto &pair : layout.descriptorSets) { const auto &descriptorSetData = pair.second; - const auto &tables = descriptorSetData.tables; + const auto &tables = descriptorSetData.tables; for (const auto &attrPair : tables) { const auto descriptorBlocks = attrPair.second.descriptorBlocks; for (const auto &block : descriptorBlocks) { @@ -545,13 +545,13 @@ gfx::ShaderStageFlagBit getVisibilityByDescName(const LGD &lgd, uint32_t passID, }; void processRasterPass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RasterPass &pass) { - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; + auto vertID = add_vertex(rag, passID); + auto &node = get(RAG::AccessNode, rag, vertID); + bool dependent = false; for (const auto &pair : pass.rasterViews) { - const auto & rasterView = pair.second; + const auto &rasterView = pair.second; gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); - auto access = toGfxAccess(rasterView.accessType); + auto access = toGfxAccess(rasterView.accessType); addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::RASTER, rasterView.slotName, visibility, access}, Range{}); auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::RASTER, rasterView.slotName, visibility, access}); if (lastVertId != INVALID_ID) { @@ -561,7 +561,7 @@ void processRasterPass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, } } for (const auto &pair : pass.computeViews) { - const auto & values = pair.second; + const auto &values = pair.second; gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); for (const auto &computeView : values) { auto access = toGfxAccess(computeView.accessType); @@ -581,11 +581,11 @@ void processRasterPass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, } void processComputePass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const ComputePass &pass) { - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; + auto vertID = add_vertex(rag, passID); + auto &node = get(RAG::AccessNode, rag, vertID); + bool dependent = false; for (const auto &pair : pass.computeViews) { - const auto & values = pair.second; + const auto &values = pair.second; gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); for (const auto &computeView : values) { auto access = toGfxAccess(computeView.accessType); @@ -605,9 +605,9 @@ void processComputePass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph } void processCopyPass(RAG &rag, const LGD & /*lgd*/, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const CopyPass &pass) { - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; + auto vertID = add_vertex(rag, passID); + auto &node = get(RAG::AccessNode, rag, vertID); + bool dependent = false; for (const auto &pair : pass.copyPairs) { auto sourceRange = Range{ pair.mipLevels, @@ -645,11 +645,11 @@ void processCopyPass(RAG &rag, const LGD & /*lgd*/, const ResourceGraph &rescGra } void processRaytracePass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const RaytracePass &pass) { - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; + auto vertID = add_vertex(rag, passID); + auto &node = get(RAG::AccessNode, rag, vertID); + bool dependent = false; for (const auto &pair : pass.computeViews) { - const auto & values = pair.second; + const auto &values = pair.second; gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); for (const auto &computeView : values) { auto access = toGfxAccess(computeView.accessType); @@ -669,12 +669,12 @@ void processRaytracePass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGrap } void processPresentPass(RAG &rag, const LGD &lgd, const ResourceGraph &rescGraph, AccessTable &accessRecord, uint32_t passID, const PresentPass &pass) { - auto vertID = add_vertex(rag, passID); - auto &node = get(RAG::AccessNode, rag, vertID); - bool dependent = false; + auto vertID = add_vertex(rag, passID); + auto &node = get(RAG::AccessNode, rag, vertID); + bool dependent = false; for (const auto &pair : pass.presents) { gfx::ShaderStageFlagBit visibility = getVisibilityByDescName(lgd, passID, pair.first); - auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::PRESENT, pair.first, visibility, gfx::MemoryAccessBit::WRITE_ONLY}); + auto lastVertId = dependencyCheck(rag, accessRecord, vertID, InputStatusTuple{PassType::PRESENT, pair.first, visibility, gfx::MemoryAccessBit::WRITE_ONLY}); addAccessNode(rag, rescGraph, node, InputStatusTuple{PassType::PRESENT, pair.first, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY}, Range{}); if (lastVertId != INVALID_ID) { auto res = add_edge(lastVertId, vertID, rag); diff --git a/native/cocos/renderer/pipeline/custom/GraphImpl.h b/native/cocos/renderer/pipeline/custom/GraphImpl.h index 56b0c4fda4..515c4f18ea 100644 --- a/native/cocos/renderer/pipeline/custom/GraphImpl.h +++ b/native/cocos/renderer/pipeline/custom/GraphImpl.h @@ -47,9 +47,9 @@ struct VectorVertexBundlePropertyMap : public boost::put_get_helper< Reference, VectorVertexBundlePropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexBundlePropertyMap(Graph &g) noexcept // NOLINT(google-explicit-constructor) : graph(&g) {} @@ -69,9 +69,9 @@ struct PointerVertexBundlePropertyMap : public boost::put_get_helper< Reference, PointerVertexBundlePropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; PointerVertexBundlePropertyMap(Graph &g) noexcept // NOLINT(google-explicit-constructor) : graph(&g) {} @@ -92,9 +92,9 @@ struct VectorVertexBundleMemberPropertyMap : public boost::put_get_helper< Reference, VectorVertexBundleMemberPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexBundleMemberPropertyMap(Graph &g, MemberPointer ptr) noexcept : graph(&g), memberPointer(ptr) {} @@ -106,7 +106,7 @@ struct VectorVertexBundleMemberPropertyMap return operator[](v); } - Graph * graph{}; + Graph *graph{}; MemberPointer memberPointer{}; }; @@ -115,9 +115,9 @@ struct PointerVertexBundleMemberPropertyMap : public boost::put_get_helper< Reference, PointerVertexBundleMemberPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; PointerVertexBundleMemberPropertyMap(Graph &g, MemberPointer ptr) noexcept : graph(&g), memberPointer(ptr) {} @@ -130,7 +130,7 @@ struct PointerVertexBundleMemberPropertyMap return operator[](v); } - Graph * graph{}; + Graph *graph{}; MemberPointer memberPointer{}; }; @@ -139,9 +139,9 @@ struct VectorVertexComponentPropertyMap : public boost::put_get_helper< Reference, VectorVertexComponentPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexComponentPropertyMap(Container &c) noexcept // NOLINT(google-explicit-constructor) : container(&c) {} @@ -161,9 +161,9 @@ struct VectorVertexComponentMemberPropertyMap : public boost::put_get_helper< Reference, VectorVertexComponentMemberPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexComponentMemberPropertyMap(Container &c, MemberPointer ptr) noexcept : container(&c), memberPointer(ptr) {} @@ -175,7 +175,7 @@ struct VectorVertexComponentMemberPropertyMap return operator[](v); } - Container * container{}; + Container *container{}; MemberPointer memberPointer{}; }; @@ -184,9 +184,9 @@ struct VectorVertexIteratorComponentPropertyMap : public boost::put_get_helper< Reference, VectorVertexIteratorComponentPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexIteratorComponentPropertyMap(Graph &g, ComponentPointer component) noexcept : graph(&g), componentPointer(component) {} @@ -198,7 +198,7 @@ struct VectorVertexIteratorComponentPropertyMap return operator[](v); } - Graph * graph{}; + Graph *graph{}; ComponentPointer componentPointer{}; }; @@ -207,9 +207,9 @@ struct VectorVertexIteratorComponentMemberPropertyMap : public boost::put_get_helper< Reference, VectorVertexIteratorComponentMemberPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::vertex_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::vertex_descriptor; + using category = Category; VectorVertexIteratorComponentMemberPropertyMap(Graph &g, ComponentPointer component, MemberPointer ptr) noexcept : graph(&g), componentPointer(component), memberPointer(ptr) {} @@ -221,9 +221,9 @@ struct VectorVertexIteratorComponentMemberPropertyMap return operator[](v); } - Graph * graph{}; + Graph *graph{}; ComponentPointer componentPointer{}; - MemberPointer memberPointer{}; + MemberPointer memberPointer{}; }; template @@ -231,9 +231,9 @@ struct VectorPathPropertyMap : public boost::put_get_helper< Reference, VectorPathPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = VertexDescriptor; - using category = Category; + using reference = Reference; + using key_type = VertexDescriptor; + using category = Category; VectorPathPropertyMap(Container &c) noexcept // NOLINT(google-explicit-constructor) : container(&c) {} @@ -253,9 +253,9 @@ struct EdgeBundlePropertyMap : public boost::put_get_helper< Reference, EdgeBundlePropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::edge_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::edge_descriptor; + using category = Category; EdgeBundlePropertyMap(Graph &g) noexcept // NOLINT(google-explicit-constructor) : graph(&g) {} @@ -275,9 +275,9 @@ struct EdgeBundleMemberPropertyMap : public boost::put_get_helper< Reference, EdgeBundleMemberPropertyMap> { using value_type = Value; - using reference = Reference; - using key_type = typename Graph::edge_descriptor; - using category = Category; + using reference = Reference; + using key_type = typename Graph::edge_descriptor; + using category = Category; EdgeBundleMemberPropertyMap(Graph &g, MemberPointer ptr) noexcept : graph(&g), memberPointer(ptr) {} @@ -290,7 +290,7 @@ struct EdgeBundleMemberPropertyMap return operator[](e); } - Graph * graph{}; + Graph *graph{}; MemberPointer memberPointer{}; }; @@ -353,7 +353,7 @@ inline void removeIncidenceEdge( template inline void removeDirectedAllEdgeProperties(Graph &g, IncidenceList &el, VertexDescriptor v) noexcept { - auto i = el.begin(); + auto i = el.begin(); auto end = el.end(); for (; i != end; ++i) { if ((*i).get_target() == v) { @@ -403,8 +403,8 @@ inline void associativeRemoveIncidenceEdgeIf(IncidenceIterator first, IncidenceI template inline void removeUndirectedEdge(Graph &g, EdgeDescriptor e, EdgeProperty &p) noexcept { - auto & outEdgeList = g.getOutEdgeList(source(e, g)); - auto outEdgeIter = outEdgeList.begin(); + auto &outEdgeList = g.getOutEdgeList(source(e, g)); + auto outEdgeIter = outEdgeList.begin(); decltype((*outEdgeIter).get_iter()) edgeIterToErase; for (; outEdgeIter != outEdgeList.end(); ++outEdgeIter) { if (&(*outEdgeIter).get_property() == &p) { @@ -414,7 +414,7 @@ inline void removeUndirectedEdge(Graph &g, EdgeDescriptor e, EdgeProperty &p) no } } auto &inEdgeList = g.getOutEdgeList(target(e, g)); - auto inEdgeIter = inEdgeList.begin(); + auto inEdgeIter = inEdgeList.begin(); for (; inEdgeIter != inEdgeList.end(); ++inEdgeIter) { if (&(*inEdgeIter).get_property() == &p) { inEdgeList.erase(inEdgeIter); @@ -425,14 +425,14 @@ inline void removeUndirectedEdge(Graph &g, EdgeDescriptor e, EdgeProperty &p) no } template -inline void sequenceRemoveUndirectedOutEdgeIf(Graph & g, +inline void sequenceRemoveUndirectedOutEdgeIf(Graph &g, IncidenceIterator first, IncidenceIterator last, IncidenceList &el, Predicate &&pred) noexcept { // remove_if while (first != last && !pred(*first)) { ++first; } - auto i = first; + auto i = first; bool selfLoopRemoved = false; if (first != last) { for (; i != last; ++i) { @@ -462,7 +462,7 @@ inline void sequenceRemoveUndirectedOutEdgeIf(Graph & g, } template -inline void associativeRemoveUndirectedOutEdgeIf(Graph & g, +inline void associativeRemoveUndirectedOutEdgeIf(Graph &g, IncidenceIterator first, IncidenceIterator last, IncidenceList &el, Predicate &&pred) noexcept { for (auto next = first; first != last; first = next) { @@ -485,7 +485,7 @@ inline void associativeRemoveUndirectedOutEdgeIf(Graph & g, // list/vector out_edge_list template inline void reindexEdgeList(IncidenceList &el, VertexDescriptor u) { - auto ei = el.begin(); + auto ei = el.begin(); auto eEnd = el.end(); for (; ei != eEnd; ++ei) { if ((*ei).get_target() > u) { @@ -528,7 +528,7 @@ inline void removeVectorVertex(Graph &g, VertexDescriptor u, boost::undirected_t reindexEdgeList(g.getOutEdgeList(v), u); } - auto ei = g.edges.begin(); + auto ei = g.edges.begin(); auto eiEnd = g.edges.end(); for (; ei != eiEnd; ++ei) { if (ei->source > u) { @@ -557,7 +557,7 @@ inline void removeVectorVertex(Graph &g, VertexDescriptor u, boost::bidirectiona } template -inline void removeVectorVertex(Graph & g, EdgeList & /*edges*/, +inline void removeVectorVertex(Graph &g, EdgeList & /*edges*/, VertexDescriptor u, boost::bidirectional_tag /*tag*/) { g.vertices.erase(g.vertices.begin() + u); VertexDescriptor numV = num_vertices(g); @@ -571,7 +571,7 @@ inline void removeVectorVertex(Graph & g, EdgeList & /*edges*/, reindexEdgeList(g.getInEdgeList(v), u); } - auto ei = g.edges.begin(); + auto ei = g.edges.begin(); auto eiEnd = g.edges.end(); for (; ei != eiEnd; ++ei) { if (ei->source > u) { @@ -622,7 +622,7 @@ inline std::ptrdiff_t pathLength(typename AddressableGraph::vertex_descriptor u, template inline void pathComposite( std::basic_string, Allocator> &str, - std::ptrdiff_t & sz, + std::ptrdiff_t &sz, typename AddressableGraph::vertex_descriptor u, const AddressableGraph &g, typename AddressableGraph::vertex_descriptor parentID = AddressableGraph::null_vertex()) noexcept { const auto &pmap = get(boost::vertex_name, g); @@ -644,9 +644,9 @@ inline void pathComposite( template struct ColorMap : public boost::put_get_helper> { using value_type = boost::default_color_type; - using reference = boost::default_color_type &; - using key_type = Key; - using category = boost::lvalue_property_map_tag; + using reference = boost::default_color_type &; + using key_type = Key; + using category = boost::lvalue_property_map_tag; ColorMap(ccstd::pmr::vector &vec) noexcept // NOLINT(google-explicit-constructor) : container{&vec} {} diff --git a/native/cocos/renderer/pipeline/custom/GraphTypes.h b/native/cocos/renderer/pipeline/custom/GraphTypes.h index adf4413754..ebece8e294 100644 --- a/native/cocos/renderer/pipeline/custom/GraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/GraphTypes.h @@ -261,7 +261,7 @@ public: } protected: - size_t _id{static_cast(-1)}; + size_t _id{static_cast(-1)}; EdgeVec *_vector{}; }; @@ -412,11 +412,11 @@ template class DirectedEdgeIterator { public: using iterator_category = std::forward_iterator_tag; - using value_type = typename OutEdgeIterator::value_type; - using reference = typename OutEdgeIterator::reference; - using pointer = typename OutEdgeIterator::pointer; - using difference_type = typename OutEdgeIterator::difference_type; - using distance_type = difference_type; + using value_type = typename OutEdgeIterator::value_type; + using reference = typename OutEdgeIterator::reference; + using pointer = typename OutEdgeIterator::pointer; + using difference_type = typename OutEdgeIterator::difference_type; + using distance_type = difference_type; DirectedEdgeIterator() = default; template @@ -461,11 +461,11 @@ public: } protected: - VertexIterator _begin{}; - VertexIterator _curr{}; - VertexIterator _end{}; + VertexIterator _begin{}; + VertexIterator _curr{}; + VertexIterator _end{}; boost::optional> _edges; - const Graph * _g{}; + const Graph *_g{}; }; //-------------------------------------------------------------------- @@ -483,15 +483,15 @@ struct ListEdge { : source(s), target(t), property(p) {} template - ListEdge(VertexDescriptor s, VertexDescriptor t, T &&...args) // NOLINT + ListEdge(VertexDescriptor s, VertexDescriptor t, T &&... args) // NOLINT : source(s), target(t), property(std::forward(args)...) {} - EdgeProperty & get_property() noexcept { return property; } // NOLINT + EdgeProperty &get_property() noexcept { return property; } // NOLINT const EdgeProperty &get_property() const noexcept { return property; } // NOLINT VertexDescriptor source{}; VertexDescriptor target{}; - EdgeProperty property; + EdgeProperty property; }; // template @@ -512,7 +512,7 @@ struct PmrListEdge { : source(s), target(t), property(p, alloc) {} template - PmrListEdge(VertexDescriptor s, VertexDescriptor t, T &&...args) // NOLINT + PmrListEdge(VertexDescriptor s, VertexDescriptor t, T &&... args) // NOLINT : source(s), target(t), property(std::forward(args)...) {} // move/copy cntrs @@ -523,12 +523,12 @@ struct PmrListEdge { PmrListEdge(const PmrListEdge &) = delete; - EdgeProperty & get_property() noexcept { return property; } // NOLINT + EdgeProperty &get_property() noexcept { return property; } // NOLINT const EdgeProperty &get_property() const noexcept { return property; } // NOLINT VertexDescriptor source{}; VertexDescriptor target{}; - EdgeProperty property; + EdgeProperty property; }; // Polymorphic Graph @@ -553,7 +553,7 @@ struct ValueHandle : Tag { ValueHandle(Handle &&handle) noexcept // NOLINT(google-explicit-constructor) : value(std::move(handle)) {} template - ValueHandle(Args &&...args) noexcept // NOLINT(google-explicit-constructor) + ValueHandle(Args &&... args) noexcept // NOLINT(google-explicit-constructor) : value(std::forward(args)...) {} Handle value{}; @@ -565,11 +565,11 @@ template class OwnershipIterator { public: using iterator_category = std::forward_iterator_tag; - using value_type = typename OutEdgeIterator::value_type; - using reference = typename OutEdgeIterator::reference; - using pointer = typename OutEdgeIterator::pointer; - using difference_type = typename OutEdgeIterator::difference_type; - using distance_type = difference_type; + using value_type = typename OutEdgeIterator::value_type; + using reference = typename OutEdgeIterator::reference; + using pointer = typename OutEdgeIterator::pointer; + using difference_type = typename OutEdgeIterator::difference_type; + using distance_type = difference_type; OwnershipIterator() = default; template @@ -614,11 +614,11 @@ public: } protected: - VertexIterator _begin{}; - VertexIterator _curr{}; - VertexIterator _end{}; + VertexIterator _begin{}; + VertexIterator _curr{}; + VertexIterator _end{}; boost::optional> _edges; - const Graph * _g{}; + const Graph *_g{}; }; } // namespace impl diff --git a/native/cocos/renderer/pipeline/custom/JsbConversion.h b/native/cocos/renderer/pipeline/custom/JsbConversion.h index e5e0b5e984..2b60a6c281 100644 --- a/native/cocos/renderer/pipeline/custom/JsbConversion.h +++ b/native/cocos/renderer/pipeline/custom/JsbConversion.h @@ -34,7 +34,7 @@ inline bool nativevalue_to_se( // NOLINT(readability-identifier-naming) const ccstd::vector &from, se::Value &to, se::Object *ctx) { se::Object *array = se::Object::createArrayObject(from.size()); - se::Value tmp; + se::Value tmp; for (size_t i = 0; i < from.size(); i++) { nativevalue_to_se(from[i], tmp, ctx); array->setArrayElement(static_cast(i), tmp); @@ -76,8 +76,8 @@ bool sevalue_to_native(const se::Value &from, ccstd::vector *to, s if (array->isTypedArray()) { CC_ASSERT(std::is_arithmetic::value); - uint8_t *data = nullptr; - size_t dataLen = 0; + uint8_t *data = nullptr; + size_t dataLen = 0; array->getTypedArrayData(&data, &dataLen); to->assign(reinterpret_cast(data), reinterpret_cast(data + dataLen)); return true; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp index e7123bea88..fdf040845e 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineImpl.cpp @@ -135,7 +135,7 @@ void generateConstantMacros( // NOLINTNEXTLINE bool NativePipeline::activate(gfx::Swapchain *swapchainIn) { - swapchain = swapchainIn; + swapchain = swapchainIn; macros["CC_PIPELINE_TYPE"] = 0; globalDSManager->activate(device); pipelineSceneData->activate(device); @@ -166,9 +166,9 @@ bool NativePipeline::destroy() noexcept { // NOLINTNEXTLINE void NativePipeline::render(const ccstd::vector &cameras) { - const auto *sceneData = pipelineSceneData.get(); - auto * commandBuffer = device->getCommandBuffer(); - float shadingScale = sceneData->getShadingScale(); + const auto *sceneData = pipelineSceneData.get(); + auto *commandBuffer = device->getCommandBuffer(); + float shadingScale = sceneData->getShadingScale(); struct RenderData2 { framegraph::TextureHandle outputTex; @@ -190,8 +190,8 @@ void NativePipeline::render(const ccstd::vector &cameras) { // color framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = sceneData->isHDR() ? gfx::Format::RGBA16F : gfx::Format::RGBA8; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT; - colorTexInfo.width = static_cast(static_cast(camera->getWindow()->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT; + colorTexInfo.width = static_cast(static_cast(camera->getWindow()->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(camera->getWindow()->getHeight()) * shadingScale); if (shadingScale != 1.F) { colorTexInfo.usage |= gfx::TextureUsageBit::TRANSFER_SRC; @@ -199,9 +199,9 @@ void NativePipeline::render(const ccstd::vector &cameras) { data.outputTex = builder.create(colorHandle, colorTexInfo); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; colorAttachmentInfo.clearColor = clearColor; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; @@ -266,7 +266,7 @@ void NativePipeline::render(const ccstd::vector &cameras) { commandBuffer->end(); { - static uint64_t frameCount{0U}; + static uint64_t frameCount{0U}; static constexpr uint64_t INTERVAL_IN_SECONDS = 30; if (++frameCount % (INTERVAL_IN_SECONDS * 60) == 0) { framegraph::FrameGraph::gc(INTERVAL_IN_SECONDS * 60); diff --git a/native/cocos/renderer/pipeline/custom/Overload.h b/native/cocos/renderer/pipeline/custom/Overload.h index f6fa82534d..5e0bdef2d8 100644 --- a/native/cocos/renderer/pipeline/custom/Overload.h +++ b/native/cocos/renderer/pipeline/custom/Overload.h @@ -47,7 +47,7 @@ struct Overloaded : T0 { template struct Overloaded : T0, Overloaded { - using T0:: operator(); + using T0::operator(); using Overloaded::operator(); Overloaded(T0 t0, T1 t1, Ts... ts) : T0(std::move(t0)), Overloaded(std::move(t1), std::move(ts)...) {} @@ -61,7 +61,7 @@ Overloaded overload(Ts... ts) { template auto variantFromIndex(size_t index) -> V { // NOLINT return boost::mp11::mp_with_index>(index, - [](auto i) { return V(boost::variant2::in_place_index); }); + [](auto i) { return V(boost::variant2::in_place_index); }); } } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/PathUtils.h b/native/cocos/renderer/pipeline/custom/PathUtils.h index fef02ab136..55a5b4721a 100644 --- a/native/cocos/renderer/pipeline/custom/PathUtils.h +++ b/native/cocos/renderer/pipeline/custom/PathUtils.h @@ -38,8 +38,8 @@ namespace impl { template inline void cleanPath(std::basic_string, Allocator> &str) noexcept { - using string_t = std::basic_string, Allocator>; - constexpr CharT slash[] = {'/', '\0'}; + using string_t = std::basic_string, Allocator>; + constexpr CharT slash[] = {'/', '\0'}; constexpr CharT doubleSlash[] = {'/', '/', '\0'}; CC_EXPECTS(!str.empty()); @@ -71,7 +71,7 @@ inline void cleanPath(std::basic_string, Allocato // try remove /.. constexpr ccstd::array previous = {CharT('/'), CharT('.'), CharT('.'), CharT('\0')}; - auto pos = str.find(previous.data()); + auto pos = str.find(previous.data()); while (pos != string_t::npos) { if (pos == 0) { // root element has not parent path diff --git a/native/cocos/renderer/pipeline/custom/RenderCompilerImpl.cpp b/native/cocos/renderer/pipeline/custom/RenderCompilerImpl.cpp index 0c0ea757ab..b3e81f5542 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCompilerImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCompilerImpl.cpp @@ -30,8 +30,8 @@ namespace cc { namespace render { int RenderCompiler::compile() { - auto& rg = graph; - const auto& resg = resourceGraph; + auto& rg = graph; + const auto& resg = resourceGraph; return 0; } diff --git a/native/cocos/renderer/pipeline/custom/RenderExampleImpl.cpp b/native/cocos/renderer/pipeline/custom/RenderExampleImpl.cpp index 960e62119b..84a51bf709 100644 --- a/native/cocos/renderer/pipeline/custom/RenderExampleImpl.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderExampleImpl.cpp @@ -43,16 +43,16 @@ namespace example { namespace { -using RDG = RenderDependencyGraph; +using RDG = RenderDependencyGraph; using RESG = ResourceGraph; // validation void checkComputeValue(const PmrTransparentMap> &values0) { for (const auto &pair : values0) { - const auto &name = pair.first; + const auto &name = pair.first; const auto &values = pair.second; - bool bWrite = false; - int count = 0; + bool bWrite = false; + int count = 0; for (const auto &v : values) { if (v.clearFlags != gfx::ClearFlagBit::NONE) { if (!v.isWrite()) { @@ -173,33 +173,33 @@ void buildRenderDependencyGraph(const RenderGraph &rg, RenderDependencyGraph &rd visitObject( passID, rg, [&](const RasterPass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.rasterViews) { const auto &valueName = pair.first; - const auto &value = pair.second; + const auto &value = pair.second; addPassNodeValue(rdg, node, valueIDs, valueName, value.accessType); } for (const auto &pair : pass.computeViews) { const auto &valueName = pair.first; - const auto &values = pair.second; + const auto &values = pair.second; addPassNodeValue(rdg, node, valueIDs, valueName, makeAccessType(values)); } }, [&](const ComputePass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.computeViews) { const auto &valueName = pair.first; - const auto &values = pair.second; + const auto &values = pair.second; addPassNodeValue(rdg, node, valueIDs, valueName, makeAccessType(values)); } }, [&](const CopyPass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.copyPairs) { @@ -208,8 +208,8 @@ void buildRenderDependencyGraph(const RenderGraph &rg, RenderDependencyGraph &rd } }, [&](const MovePass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.movePairs) { @@ -218,18 +218,18 @@ void buildRenderDependencyGraph(const RenderGraph &rg, RenderDependencyGraph &rd } }, [&](const RaytracePass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.computeViews) { const auto &valueName = pair.first; - const auto &values = pair.second; + const auto &values = pair.second; addPassNodeValue(rdg, node, valueIDs, valueName, makeAccessType(values)); } }, [&](const PresentPass &pass) { - auto vertID = add_vertex(rdg, passID); - auto &node = get(RDG::Pass, rdg, vertID); + auto vertID = add_vertex(rdg, passID); + auto &node = get(RDG::Pass, rdg, vertID); auto &valueIDs = get(RDG::ValueID, rdg, vertID); for (const auto &pair : pass.presents) { @@ -263,7 +263,7 @@ void buildRenderValueGraphAndInitialPass(RenderDependencyGraph &rdg, RenderValue // build value graph edges auto initPassID = vertex(0xFFFFFFFF, rdg); CC_EXPECTS(initPassID == 0); - auto &initPass = get(RDG::Pass, rdg, initPassID); + auto &initPass = get(RDG::Pass, rdg, initPassID); auto &initValueIDs = get(RDG::ValueID, rdg, initPassID); for (uint32_t dstPassID = num_vertices(rdg); dstPassID-- > 0;) { @@ -320,7 +320,7 @@ void buildRenderDependencyGraphResourceIndex(const ResourceGraph &resg, RenderDe uint32_t valueID = 0; for (const auto &valueName : rdg.valueNames) { - auto handleID = vertex(valueName, resg); + auto handleID = vertex(valueName, resg); rdg.resourceHandles[valueID] = handleID; ++valueID; } @@ -328,15 +328,15 @@ void buildRenderDependencyGraphResourceIndex(const ResourceGraph &resg, RenderDe struct CullingVisitor : boost::dfs_visitor<> { CullingVisitor( - const ResourceGraph & resg0, - const RenderGraph & rg0, + const ResourceGraph &resg0, + const RenderGraph &rg0, const RenderDependencyGraph &rdg0, - boost::property_map::const_type passes, + boost::property_map::const_type passes, boost::property_map::const_type valueIDs, - boost::property_map::const_type passIDs, - boost::property_map::type traits, - boost::property_map::const_type resourceTraits) + boost::property_map::const_type passIDs, + boost::property_map::type traits, + boost::property_map::const_type resourceTraits) : resg(resg0), rg(rg0), rdg(rdg0), @@ -353,7 +353,7 @@ struct CullingVisitor : boost::dfs_visitor<> { void markVertex(Graph::edge_descriptor e, const Graph &g) const { auto sourceID = source(e, g); auto targetID = target(e, g); - auto keep = get(traits, sourceID).keep; + auto keep = get(traits, sourceID).keep; get(traits, targetID).keep |= keep; } @@ -400,14 +400,14 @@ struct CullingVisitor : boost::dfs_visitor<> { // currently, do nothing } - const ResourceGraph & resg; - const RenderGraph & rg; + const ResourceGraph &resg; + const RenderGraph &rg; const RenderDependencyGraph &rdg; - boost::property_map::const_type mPasses; + boost::property_map::const_type mPasses; boost::property_map::const_type valueIDs; - boost::property_map::const_type passIDs; - boost::property_map::type traits; + boost::property_map::const_type passIDs; + boost::property_map::type traits; boost::property_map::const_type mResourceTraits; }; @@ -415,7 +415,7 @@ struct CullingVisitor : boost::dfs_visitor<> { } // namespace int RenderCompiler::compile() { - auto & rg = graph; + auto &rg = graph; const auto &resg = resourceGraph; try { @@ -461,7 +461,7 @@ int RenderCompiler::compile() { // d) found back-edge, rdg is not DAG, abort // 3. any pass is not marked as keep, is culled { - const auto &crdg = rdg; + const auto &crdg = rdg; const auto &cresg = resg; CullingVisitor visitor( @@ -472,7 +472,7 @@ int RenderCompiler::compile() { get(RDG::Traits, rdg), get(RESG::Traits, cresg)); - auto colors = rdg.colors(scratch); + auto colors = rdg.colors(scratch); auto reverseGraph = boost::make_reverse_graph(crdg); boost::depth_first_search( reverseGraph, diff --git a/native/cocos/renderer/pipeline/custom/invoke.hpp b/native/cocos/renderer/pipeline/custom/invoke.hpp index 68db1fa27f..3a98158b1e 100644 --- a/native/cocos/renderer/pipeline/custom/invoke.hpp +++ b/native/cocos/renderer/pipeline/custom/invoke.hpp @@ -37,264 +37,232 @@ #include #define INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN(...) \ - noexcept(noexcept(__VA_ARGS__)) -> decltype (__VA_ARGS__) { return __VA_ARGS__; } + noexcept(noexcept(__VA_ARGS__))->decltype(__VA_ARGS__) { return __VA_ARGS__; } // // void_t // -namespace invoke_hpp -{ - namespace impl - { - template < typename... Args > - struct make_void { // NOLINT - using type = void; - }; - } +namespace invoke_hpp { +namespace impl { +template +struct make_void { // NOLINT + using type = void; +}; +} // namespace impl - template < typename... Args > - using void_t = typename impl::make_void::type; +template +using void_t = typename impl::make_void::type; } // namespace invoke_hpp // // integer_sequence // -namespace invoke_hpp -{ - template < typename T, T... Ints > - struct integer_sequence { // NOLINT - using value_type = T; - static constexpr std::size_t size() noexcept { return sizeof...(Ints); } - }; +namespace invoke_hpp { +template +struct integer_sequence { // NOLINT + using value_type = T; + static constexpr std::size_t size() noexcept { return sizeof...(Ints); } +}; - template < std::size_t... Ints > - using index_sequence = integer_sequence; +template +using index_sequence = integer_sequence; - namespace impl - { - template < typename T, std::size_t N, T... Ints > - struct make_integer_sequence_impl // NOLINT - : make_integer_sequence_impl {}; +namespace impl { +template +struct make_integer_sequence_impl // NOLINT +: make_integer_sequence_impl {}; - template < typename T, T... Ints > - struct make_integer_sequence_impl - : integer_sequence {}; - } +template +struct make_integer_sequence_impl +: integer_sequence {}; +} // namespace impl - template < typename T, std::size_t N > - using make_integer_sequence = impl::make_integer_sequence_impl; +template +using make_integer_sequence = impl::make_integer_sequence_impl; - template < std::size_t N > - using make_index_sequence = make_integer_sequence; +template +using make_index_sequence = make_integer_sequence; - template < typename... Ts > - using index_sequence_for = make_index_sequence; +template +using index_sequence_for = make_index_sequence; } // namespace invoke_hpp // // is_reference_wrapper // -namespace invoke_hpp -{ - namespace impl - { - template < typename T > - struct is_reference_wrapper_impl // NOLINT - : std::false_type {}; +namespace invoke_hpp { +namespace impl { +template +struct is_reference_wrapper_impl // NOLINT +: std::false_type {}; - template < typename U > - struct is_reference_wrapper_impl> - : std::true_type {}; - } +template +struct is_reference_wrapper_impl> +: std::true_type {}; +} // namespace impl - template < typename T > - struct is_reference_wrapper // NOLINT - : impl::is_reference_wrapper_impl::type> {}; +template +struct is_reference_wrapper // NOLINT +: impl::is_reference_wrapper_impl::type> {}; } // namespace invoke_hpp // // invoke // -namespace invoke_hpp -{ - namespace impl - { - // - // invoke_member_object_impl - // +namespace invoke_hpp { +namespace impl { +// +// invoke_member_object_impl +// - template - < - typename Base, typename F, typename Derived, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke_member_object_impl(F Base::* f, Derived&& ref) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - std::forward(ref).*f) +template < + typename Base, typename F, typename Derived, + typename std::enable_if::type>::value, int>::type = 0> +constexpr auto invoke_member_object_impl(F Base::*f, Derived&& ref) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + std::forward(ref).*f) - template - < + template < typename Base, typename F, typename RefWrap, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke_member_object_impl(F Base::* f, RefWrap&& ref) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - ref.get().*f) + typename std::enable_if::type>::value, int>::type = 0> + constexpr auto invoke_member_object_impl(F Base::*f, RefWrap&& ref) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + ref.get().*f) - template - < + template < typename Base, typename F, typename Pointer, typename std::enable_if< !std::is_base_of::type>::value && - !is_reference_wrapper::type>::value - , int>::type = 0 - > - constexpr auto invoke_member_object_impl(F Base::* f, Pointer&& ptr) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - (*std::forward(ptr)).*f) + !is_reference_wrapper::type>::value, + int>::type = 0> + constexpr auto invoke_member_object_impl(F Base::*f, Pointer&& ptr) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + (*std::forward(ptr)).*f) - // - // invoke_member_function_impl - // + // + // invoke_member_function_impl + // - template - < - typename Base, typename F, typename Derived, typename... Args, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke_member_function_impl(F Base::* f, Derived&& ref, Args&&... args) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - (std::forward(ref).*f)(std::forward(args)...)) + template < + typename Base, typename F, typename Derived, typename... Args, + typename std::enable_if::type>::value, int>::type = 0> + constexpr auto invoke_member_function_impl(F Base::*f, Derived&& ref, Args&&... args) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + (std::forward(ref).*f)(std::forward(args)...)) - template - < + template < typename Base, typename F, typename RefWrap, typename... Args, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke_member_function_impl(F Base::* f, RefWrap&& ref, Args&&... args) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - (ref.get().*f)(std::forward(args)...)) + typename std::enable_if::type>::value, int>::type = 0> + constexpr auto invoke_member_function_impl(F Base::*f, RefWrap&& ref, Args&&... args) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + (ref.get().*f)(std::forward(args)...)) - template - < + template < typename Base, typename F, typename Pointer, typename... Args, typename std::enable_if< !std::is_base_of::type>::value && - !is_reference_wrapper::type>::value - , int>::type = 0 - > - constexpr auto invoke_member_function_impl(F Base::* f, Pointer&& ptr, Args&&... args) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - ((*std::forward(ptr)).*f)(std::forward(args)...)) - } // namespace impl + !is_reference_wrapper::type>::value, + int>::type = 0> + constexpr auto invoke_member_function_impl(F Base::*f, Pointer&& ptr, Args&&... args) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + ((*std::forward(ptr)).*f)(std::forward(args)...)) +} // namespace impl - template - < - typename F, typename... Args, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke(F&& f, Args&&... args) +template < + typename F, typename... Args, + typename std::enable_if::type>::value, int>::type = 0> +constexpr auto invoke(F&& f, Args&&... args) INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( std::forward(f)(std::forward(args)...)) - template - < - typename F, typename T, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke(F&& f, T&& t) - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - impl::invoke_member_object_impl(std::forward(f), std::forward(t))) + template < + typename F, typename T, + typename std::enable_if::type>::value, int>::type = 0> + constexpr auto invoke(F&& f, T&& t) + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + impl::invoke_member_object_impl(std::forward(f), std::forward(t))) - template - < - typename F, typename... Args, - typename std::enable_if::type>::value, int>::type = 0 - > - constexpr auto invoke(F&& f, Args&&... args) - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - impl::invoke_member_function_impl(std::forward(f), std::forward(args)...)) + template < + typename F, typename... Args, + typename std::enable_if::type>::value, int>::type = 0> + constexpr auto invoke(F&& f, Args&&... args) + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + impl::invoke_member_function_impl(std::forward(f), std::forward(args)...)) } // namespace invoke_hpp // // invoke_result // -namespace invoke_hpp -{ - namespace impl - { - struct invoke_result_impl_tag {}; // NOLINT +namespace invoke_hpp { +namespace impl { +struct invoke_result_impl_tag {}; // NOLINT - template < typename Void, typename F, typename... Args > - struct invoke_result_impl {}; // NOLINT +template +struct invoke_result_impl {}; // NOLINT - template < typename F, typename... Args > - struct invoke_result_impl(), std::declval()...))>, F, Args...> { - using type = decltype(invoke_hpp::invoke(std::declval(), std::declval()...)); - }; - } // namespace impl +template +struct invoke_result_impl(), std::declval()...))>, F, Args...> { + using type = decltype(invoke_hpp::invoke(std::declval(), std::declval()...)); +}; +} // namespace impl - template < typename F, typename... Args > - struct invoke_result // NOLINT - : impl::invoke_result_impl {}; +template +struct invoke_result // NOLINT +: impl::invoke_result_impl {}; - template < typename F, typename... Args > - using invoke_result_t = typename invoke_result::type; +template +using invoke_result_t = typename invoke_result::type; } // namespace invoke_hpp // // is_invocable // -namespace invoke_hpp -{ - namespace impl - { - struct is_invocable_r_impl_tag {}; // NOLINT +namespace invoke_hpp { +namespace impl { +struct is_invocable_r_impl_tag {}; // NOLINT - template < typename Void, typename R, typename F, typename... Args > - struct is_invocable_r_impl // NOLINT - : std::false_type {}; +template +struct is_invocable_r_impl // NOLINT +: std::false_type {}; - template < typename R, typename F, typename... Args > - struct is_invocable_r_impl>, R, F, Args...> - : std::conditional< - std::is_void::value, - std::true_type, - std::is_convertible, R>>::type {}; - } // namespace impl +template +struct is_invocable_r_impl>, R, F, Args...> +: std::conditional< + std::is_void::value, + std::true_type, + std::is_convertible, R>>::type {}; +} // namespace impl - template < typename R, typename F, typename... Args > - struct is_invocable_r // NOLINT - : impl::is_invocable_r_impl {}; +template +struct is_invocable_r // NOLINT +: impl::is_invocable_r_impl {}; - template < typename F, typename... Args > - using is_invocable = is_invocable_r; +template +using is_invocable = is_invocable_r; } // namespace invoke_hpp // // apply // -namespace invoke_hpp -{ - namespace impl - { - template < typename F, typename Tuple, std::size_t... I > - constexpr auto apply_impl(F&& f, Tuple&& args, index_sequence) // NOLINT - INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( - invoke_hpp::invoke( - std::forward(f), - std::get(std::forward(args))...)) - } +namespace invoke_hpp { +namespace impl { +template +constexpr auto apply_impl(F&& f, Tuple&& args, index_sequence) // NOLINT + INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( + invoke_hpp::invoke( + std::forward(f), + std::get(std::forward(args))...)) +} - template < typename F, typename Tuple > - constexpr auto apply(F&& f, Tuple&& args) +template +constexpr auto apply(F&& f, Tuple&& args) INVOKE_HPP_NOEXCEPT_DECLTYPE_RETURN( impl::apply_impl( std::forward(f), diff --git a/native/cocos/renderer/pipeline/deferred/BloomStage.cpp b/native/cocos/renderer/pipeline/deferred/BloomStage.cpp index cab9cf7e12..e51637911e 100644 --- a/native/cocos/renderer/pipeline/deferred/BloomStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/BloomStage.cpp @@ -65,16 +65,16 @@ void initStrHandle() { ccstd::string tmp; for (int i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) { - tmp = ccstd::string("bloomDownsamplePass") + std::to_string(i); + tmp = ccstd::string("bloomDownsamplePass") + std::to_string(i); downsamplePassHandles[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("bloomDownsampleTex") + std::to_string(i); + tmp = ccstd::string("bloomDownsampleTex") + std::to_string(i); downsampleTexHandles[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("bloomUpsamplePass") + std::to_string(i); + tmp = ccstd::string("bloomUpsamplePass") + std::to_string(i); upsamplePassHandles[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("bloomUpsampleTex") + std::to_string(i); + tmp = ccstd::string("bloomUpsampleTex") + std::to_string(i); upsampleTexHandles[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); } @@ -123,10 +123,10 @@ void BloomStage::render(scene::Camera *camera) { if (_prefilterUBO == nullptr) { _prefilterUBO = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); - _combineUBO = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); + _combineUBO = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); for (int i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) { _downsampleUBO[i] = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); - _upsampleUBO[i] = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); + _upsampleUBO[i] = _device->createBuffer({gfx::BufferUsage::UNIFORM, gfx::MemoryUsage::DEVICE | gfx::MemoryUsage::HOST, UBOBloom::SIZE}); } gfx::SamplerInfo info{ @@ -148,9 +148,9 @@ void BloomStage::render(scene::Camera *camera) { _clearColors[0].w = camera->getClearColor().w; framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = _clearColors[0]; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = _clearColors[0]; colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; uint insertPoint = static_cast(CommonInsertPoint::DIP_BLOOM); @@ -159,23 +159,23 @@ void BloomStage::render(scene::Camera *camera) { struct PrefilterRenderData { framegraph::TextureHandle inputTexHandle; framegraph::TextureHandle outputTexHandle; - gfx::Sampler * sampler; - gfx::Buffer * bloomUBO; - float textureSize[4]; + gfx::Sampler *sampler; + gfx::Buffer *bloomUBO; + float textureSize[4]; }; auto *stage = static_cast(pipeline->getRenderstageByName(BLOOM_STAGE_NAME)); CC_ASSERT(stage != nullptr); - int iterations = stage->getIterations(); - float intensity = stage->getIntensity(); - float threshold = stage->getThreshold(); + int iterations = stage->getIterations(); + float intensity = stage->getIntensity(); + float threshold = stage->getThreshold(); - _renderArea = RenderPipeline::getRenderArea(camera); + _renderArea = RenderPipeline::getRenderArea(camera); _inputAssembler = pipeline->getIAByRenderArea(_renderArea); _renderArea.width >>= 1; _renderArea.height >>= 1; float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; - auto prefilterSetup = [&](framegraph::PassNodeBuilder &builder, PrefilterRenderData &data) { + auto prefilterSetup = [&](framegraph::PassNodeBuilder &builder, PrefilterRenderData &data) { data.sampler = _sampler; // read lightingout as input data.inputTexHandle = framegraph::TextureHandle( @@ -183,8 +183,8 @@ void BloomStage::render(scene::Camera *camera) { if (!data.inputTexHandle.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(pipeline->getHeight()) * shadingScale); data.inputTexHandle = builder.create( @@ -199,8 +199,8 @@ void BloomStage::render(scene::Camera *camera) { if (!data.outputTexHandle.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); colorTexInfo.height = static_cast(static_cast(_renderArea.height) * shadingScale); data.outputTexHandle = builder.create(prefilterTexHandle, colorTexInfo); @@ -209,22 +209,22 @@ void BloomStage::render(scene::Camera *camera) { builder.writeToBlackboard(prefilterTexHandle, data.outputTexHandle); // Update threshold - data.bloomUBO = stage->getPrefilterUBO(); + data.bloomUBO = stage->getPrefilterUBO(); data.textureSize[2] = threshold; }; auto prefilterExec = [this, camera](PrefilterRenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = _pipeline; + auto *pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); - auto * cmdBf = pipeline->getCommandBuffers()[0]; + auto *cmdBf = pipeline->getCommandBuffers()[0]; const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBf->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); - auto * sceneData = static_cast(pipeline->getPipelineSceneData()); - scene::Pass * pass = sceneData->getBloomPrefilterPass(); - gfx::Shader * shader = sceneData->getBloomPrefilterPassShader(); - gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( + auto *sceneData = static_cast(pipeline->getPipelineSceneData()); + scene::Pass *pass = sceneData->getBloomPrefilterPass(); + gfx::Shader *shader = sceneData->getBloomPrefilterPassShader(); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( pass, shader, _inputAssembler, renderPass); CC_ASSERT(pso != nullptr); @@ -246,10 +246,10 @@ void BloomStage::render(scene::Camera *camera) { struct ScalingSampleRenderData { framegraph::TextureHandle inputTexHandle; framegraph::TextureHandle outputTexHandle; - gfx::Sampler * sampler; - gfx::Buffer * bloomUBO; - float textureSize[4]; - int index; + gfx::Sampler *sampler; + gfx::Buffer *bloomUBO; + float textureSize[4]; + int index; }; // downsample pass for (int i = 0; i < iterations; ++i) { @@ -258,7 +258,7 @@ void BloomStage::render(scene::Camera *camera) { auto downsampleSetup = [&, i](framegraph::PassNodeBuilder &builder, ScalingSampleRenderData &data) { data.sampler = _sampler; - data.index = i; + data.index = i; // read from prefilter texture or last downsample texture if (data.index == 0) { data.inputTexHandle = builder.read(framegraph::TextureHandle( @@ -276,8 +276,8 @@ void BloomStage::render(scene::Camera *camera) { if (!data.outputTexHandle.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); colorTexInfo.height = static_cast(static_cast(_renderArea.height) * shadingScale); data.outputTexHandle = builder.create(downsampleTexHandles[data.index], colorTexInfo); @@ -286,23 +286,23 @@ void BloomStage::render(scene::Camera *camera) { builder.writeToBlackboard(downsampleTexHandles[data.index], data.outputTexHandle); // Update cc_textureSize - data.bloomUBO = stage->getDownsampleUBO()[data.index]; + data.bloomUBO = stage->getDownsampleUBO()[data.index]; data.textureSize[0] = static_cast(static_cast(static_cast(_renderArea.width) * shadingScale) << 1); data.textureSize[1] = static_cast(static_cast(static_cast(_renderArea.height) * shadingScale) << 1); }; auto downsampleExec = [this, camera](ScalingSampleRenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = _pipeline; + auto *pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); - auto * cmdBf = pipeline->getCommandBuffers()[0]; + auto *cmdBf = pipeline->getCommandBuffers()[0]; const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBf->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); - auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); - scene::Pass * pass = sceneData->getBloomDownSamplePasses()[data.index]; - gfx::Shader * shader = sceneData->getBloomDownSamplePassShader(); - gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( + auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); + scene::Pass *pass = sceneData->getBloomDownSamplePasses()[data.index]; + gfx::Shader *shader = sceneData->getBloomDownSamplePassShader(); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( pass, shader, _inputAssembler, renderPass); CC_ASSERT(pso != nullptr); @@ -328,7 +328,7 @@ void BloomStage::render(scene::Camera *camera) { _renderArea.height <<= 1; auto upsampleSetup = [&, i](framegraph::PassNodeBuilder &builder, ScalingSampleRenderData &data) { - data.index = i; + data.index = i; data.sampler = _sampler; // read from last downsample texture or last upsample texture if (data.index == 0) { @@ -347,8 +347,8 @@ void BloomStage::render(scene::Camera *camera) { if (!data.outputTexHandle.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); colorTexInfo.height = static_cast(static_cast(_renderArea.height) * shadingScale); data.outputTexHandle = builder.create( @@ -358,23 +358,23 @@ void BloomStage::render(scene::Camera *camera) { builder.writeToBlackboard(upsampleTexHandles[data.index], data.outputTexHandle); // Update cc_textureSize - data.bloomUBO = stage->getUpsampleUBO()[data.index]; + data.bloomUBO = stage->getUpsampleUBO()[data.index]; data.textureSize[0] = static_cast(static_cast(static_cast(_renderArea.width) * shadingScale) >> 1); data.textureSize[1] = static_cast(static_cast(static_cast(_renderArea.height) * shadingScale) >> 1); }; auto upsampleExec = [this, camera](ScalingSampleRenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = _pipeline; + auto *pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); - auto * cmdBf = pipeline->getCommandBuffers()[0]; + auto *cmdBf = pipeline->getCommandBuffers()[0]; const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBf->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); - auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); - scene::Pass * pass = sceneData->getBloomUpSamplePasses()[data.index]; - gfx::Shader * shader = sceneData->getBloomUpSamplePassShader(); - gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( + auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); + scene::Pass *pass = sceneData->getBloomUpSamplePasses()[data.index]; + gfx::Shader *shader = sceneData->getBloomUpSamplePassShader(); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( pass, shader, _inputAssembler, renderPass); CC_ASSERT(pso != nullptr); @@ -399,9 +399,9 @@ void BloomStage::render(scene::Camera *camera) { framegraph::TextureHandle lightingOutTexHandle; framegraph::TextureHandle upsampleTexHandle; framegraph::TextureHandle bloomOutTexHandle; - gfx::Sampler * sampler; - gfx::Buffer * bloomUBO; - float textureSize[4]; + gfx::Sampler *sampler; + gfx::Buffer *bloomUBO; + float textureSize[4]; }; _renderArea.width <<= 1; @@ -425,8 +425,8 @@ void BloomStage::render(scene::Camera *camera) { if (!data.bloomOutTexHandle.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(_renderArea.width) * shadingScale); colorTexInfo.height = static_cast(static_cast(_renderArea.height) * shadingScale); data.bloomOutTexHandle = builder.create( @@ -436,22 +436,22 @@ void BloomStage::render(scene::Camera *camera) { builder.writeToBlackboard(RenderPipeline::fgStrHandleBloomOutTexture, data.bloomOutTexHandle); // Update intensity - data.bloomUBO = stage->getCombineUBO(); + data.bloomUBO = stage->getCombineUBO(); data.textureSize[3] = intensity; }; auto combineExec = [this, camera](CombineRenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = _pipeline; + auto *pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); - auto * cmdBf = pipeline->getCommandBuffers()[0]; + auto *cmdBf = pipeline->getCommandBuffers()[0]; const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBf->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); - auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); - scene::Pass * pass = sceneData->getBloomCombinePass(); - gfx::Shader * shader = sceneData->getBloomCombinePassShader(); - gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( + auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); + scene::Pass *pass = sceneData->getBloomCombinePass(); + gfx::Shader *shader = sceneData->getBloomCombinePassShader(); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState( pass, shader, _inputAssembler, renderPass); CC_ASSERT(pso != nullptr); diff --git a/native/cocos/renderer/pipeline/deferred/BloomStage.h b/native/cocos/renderer/pipeline/deferred/BloomStage.h index 54a01d1f0c..8137fbe860 100644 --- a/native/cocos/renderer/pipeline/deferred/BloomStage.h +++ b/native/cocos/renderer/pipeline/deferred/BloomStage.h @@ -37,8 +37,8 @@ namespace pipeline { struct CC_DLL UBOBloom { static constexpr uint TEXTURE_SIZE_OFFSET = 0; - static constexpr uint COUNT = UBOBloom::TEXTURE_SIZE_OFFSET + 4; - static constexpr uint SIZE = UBOBloom::COUNT * 4; + static constexpr uint COUNT = UBOBloom::TEXTURE_SIZE_OFFSET + 4; + static constexpr uint SIZE = UBOBloom::COUNT * 4; }; class CC_DLL BloomStage : public RenderStage { @@ -47,23 +47,23 @@ public: ~BloomStage() override = default; static const RenderStageInfo &getInitializeInfo(); - bool initialize(const RenderStageInfo &info) override; - void activate(RenderPipeline *pipeline, RenderFlow *flow) override; - void destroy() override; - void render(scene::Camera *camera) override; + bool initialize(const RenderStageInfo &info) override; + void activate(RenderPipeline *pipeline, RenderFlow *flow) override; + void destroy() override; + void render(scene::Camera *camera) override; - gfx::Buffer * getPrefilterUBO() { return _prefilterUBO; } - auto & getDownsampleUBO() { return _downsampleUBO; } - auto & getUpsampleUBO() { return _upsampleUBO; } - gfx::Buffer * getCombineUBO() { return _combineUBO; } + gfx::Buffer *getPrefilterUBO() { return _prefilterUBO; } + auto &getDownsampleUBO() { return _downsampleUBO; } + auto &getUpsampleUBO() { return _upsampleUBO; } + gfx::Buffer *getCombineUBO() { return _combineUBO; } gfx::Sampler *getSampler() const { return _sampler; } inline float getThreshold() const { return _threshold; } - inline void setThreshold(float value) { _threshold = value; } + inline void setThreshold(float value) { _threshold = value; } inline float getIntensity() const { return _intensity; } - inline void setIntensity(float value) { _intensity = value; } - inline int getIterations() const { return _iterations; } - inline void setIterations(int value) { + inline void setIntensity(float value) { _intensity = value; } + inline int getIterations() const { return _iterations; } + inline void setIterations(int value) { _iterations = std::max(1, std::min(value, MAX_BLOOM_FILTER_PASS_NUM)); } @@ -72,15 +72,15 @@ private: static RenderStageInfo initInfo; - float _threshold = 1.0F; - float _intensity = 0.8F; - int _iterations = 2; - gfx::Sampler * _sampler = nullptr; - gfx::Buffer * _prefilterUBO = nullptr; + float _threshold = 1.0F; + float _intensity = 0.8F; + int _iterations = 2; + gfx::Sampler *_sampler = nullptr; + gfx::Buffer *_prefilterUBO = nullptr; ccstd::array _downsampleUBO{}; ccstd::array _upsampleUBO{}; - gfx::Buffer * _combineUBO = nullptr; - framegraph::StringHandle _fgStrHandleBloomOut; + gfx::Buffer *_combineUBO = nullptr; + framegraph::StringHandle _fgStrHandleBloomOut; }; } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp index c099b8a728..71bd1e3fae 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp @@ -47,11 +47,11 @@ namespace cc { namespace pipeline { #define TO_VEC3(dst, src, offset) \ - dst[offset] = (src).x; \ + dst[offset] = (src).x; \ (dst)[(offset) + 1] = (src).y; \ (dst)[(offset) + 2] = (src).z; #define TO_VEC4(dst, src, offset) \ - dst[offset] = (src).x; \ + dst[offset] = (src).x; \ (dst)[(offset) + 1] = (src).y; \ (dst)[(offset) + 2] = (src).z; \ (dst)[(offset) + 3] = (src).w; @@ -67,10 +67,10 @@ framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferTexture[GBUFFER_COU framegraph::FrameGraph::stringToHandle("gbufferNormalTexture"), framegraph::FrameGraph::stringToHandle("gbufferEmissiveTexture")}; -framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferPass = framegraph::FrameGraph::stringToHandle("deferredGbufferPass"); -framegraph::StringHandle DeferredPipeline::fgStrHandleLightingPass = framegraph::FrameGraph::stringToHandle("deferredLightingPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferPass = framegraph::FrameGraph::stringToHandle("deferredGbufferPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleLightingPass = framegraph::FrameGraph::stringToHandle("deferredLightingPass"); framegraph::StringHandle DeferredPipeline::fgStrHandleTransparentPass = framegraph::FrameGraph::stringToHandle("deferredTransparentPass"); -framegraph::StringHandle DeferredPipeline::fgStrHandleSsprPass = framegraph::FrameGraph::stringToHandle("deferredSSPRPass"); +framegraph::StringHandle DeferredPipeline::fgStrHandleSsprPass = framegraph::FrameGraph::stringToHandle("deferredSSPRPass"); bool DeferredPipeline::initialize(const RenderPipelineInfo &info) { RenderPipeline::initialize(info); @@ -105,8 +105,8 @@ bool DeferredPipeline::activate(gfx::Swapchain *swapchain) { void DeferredPipeline::render(const ccstd::vector &cameras) { CC_PROFILE(DeferredPipelineRender); - auto *device = gfx::Device::getInstance(); - bool enableOcclusionQuery = isOcclusionQueryEnabled(); + auto *device = gfx::Device::getInstance(); + bool enableOcclusionQuery = isOcclusionQueryEnabled(); if (enableOcclusionQuery) { device->getQueryPoolResults(_queryPools[0]); } @@ -166,12 +166,12 @@ bool DeferredPipeline::activeRenderer(gfx::Swapchain *swapchain) { _descriptorSet->update(); // update global defines when all states initialized. - _macros["CC_USE_HDR"] = static_cast(_pipelineSceneData->isHDR()); + _macros["CC_USE_HDR"] = static_cast(_pipelineSceneData->isHDR()); _macros["CC_SUPPORT_FLOAT_TEXTURE"] = hasAnyFlags(_device->getFormatFeatures(gfx::Format::RGBA32F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); // step 2 create index buffer uint ibStride = 4; - uint ibSize = ibStride * 6; + uint ibSize = ibStride * 6; if (_quadIB == nullptr) { _quadIB = _device->createBuffer({gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, ibSize, ibStride}); @@ -184,7 +184,7 @@ bool DeferredPipeline::activeRenderer(gfx::Swapchain *swapchain) { unsigned int ibData[] = {0, 1, 2, 1, 3, 2}; _quadIB->update(ibData, sizeof(ibData)); - _width = swapchain->getWidth(); + _width = swapchain->getWidth(); _height = swapchain->getHeight(); if (_clusterEnabled) { diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h index 5db4a042ad..e172cdb8ec 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.h @@ -50,20 +50,20 @@ public: void render(const ccstd::vector &cameras) override; void onGlobalPipelineStateChanged() override; - inline gfx::Buffer * getLightsUBO() const { return _lightsUBO; } - inline const LightList & getValidLights() const { return _validLights; } + inline gfx::Buffer *getLightsUBO() const { return _lightsUBO; } + inline const LightList &getValidLights() const { return _validLights; } inline const gfx::BufferList &getLightBuffers() const { return _lightBuffers; } - inline const UintList & getLightIndexOffsets() const { return _lightIndexOffsets; } - inline const UintList & getLightIndices() const { return _lightIndices; } + inline const UintList &getLightIndexOffsets() const { return _lightIndexOffsets; } + inline const UintList &getLightIndices() const { return _lightIndices; } private: bool activeRenderer(gfx::Swapchain *swapchain); - gfx::Buffer * _lightsUBO = nullptr; - LightList _validLights; + gfx::Buffer *_lightsUBO = nullptr; + LightList _validLights; gfx::BufferList _lightBuffers; - UintList _lightIndexOffsets; - UintList _lightIndices; + UintList _lightIndexOffsets; + UintList _lightIndices; ClusterLightCulling *_clusterComp{nullptr}; diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.cpp b/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.cpp index 1cee6e40c0..f0ee5d7d80 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.cpp +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.cpp @@ -7,7 +7,7 @@ namespace cc { namespace pipeline { -DeferredPipelineSceneData::DeferredPipelineSceneData() = default; +DeferredPipelineSceneData::DeferredPipelineSceneData() = default; DeferredPipelineSceneData::~DeferredPipelineSceneData() = default; void DeferredPipelineSceneData::activate(gfx::Device *device) { @@ -59,10 +59,10 @@ void DeferredPipelineSceneData::setAntiAliasing(AntiAliasing value) { if (_postProcessMaterial) { auto &defines = (*_postProcessMaterial->getPasses())[0]->getDefines(); defines.emplace("ANTIALIAS_TYPE", static_cast(value)); - auto * renderMat = ccnew Material(); + auto *renderMat = ccnew Material(); IMaterialInfo materialInfo; materialInfo.effectAsset = _postProcessMaterial->getEffectAsset(); - materialInfo.defines = defines; + materialInfo.defines = defines; renderMat->initialize(materialInfo); for (const auto &pass : *renderMat->getPasses()) { pass->tryCompile(); @@ -76,7 +76,7 @@ void DeferredPipelineSceneData::updateBloomPass() { return; } - auto &bloomPasses = *_bloomMaterial->getPasses(); + auto &bloomPasses = *_bloomMaterial->getPasses(); _bloomPrefilterPass = bloomPasses[BLOOM_PREFILTERPASS_INDEX]; _bloomPrefilterPass->beginChangeStatesSilently(); _bloomPrefilterPass->tryCompile(); @@ -104,7 +104,7 @@ void DeferredPipelineSceneData::updateBloomPass() { _bloomCombinePass->endChangeStatesSilently(); _bloomCombinePassShader = _bloomCombinePass->getShaderVariant(); - _bloomUpSamplePassShader = bloomPasses[BLOOM_UPSAMPLEPASS_INDEX]->getShaderVariant(); + _bloomUpSamplePassShader = bloomPasses[BLOOM_UPSAMPLEPASS_INDEX]->getShaderVariant(); _bloomDownSamplePassShader = bloomPasses[BLOOM_DOWNSAMPLEPASS_INDEX]->getShaderVariant(); } @@ -138,7 +138,7 @@ void DeferredPipelineSceneData::updateDeferredLightPass() { // It's temporary solution for main light shadowmap if (_shadow->isEnabled()) { - if (RenderPipeline::getInstance()){ + if (RenderPipeline::getInstance()) { RenderPipeline::getInstance()->setValue("CC_RECEIVE_SHADOW", 1); } } diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.h b/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.h index 5fbecf69dc..9fb591527d 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.h +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipelineSceneData.h @@ -26,11 +26,11 @@ public: void initPipelinePassInfo(); - void setAntiAliasing(AntiAliasing value); + void setAntiAliasing(AntiAliasing value); inline AntiAliasing getAntiAliasing() const { return _antiAliasing; } inline Material *getBloomMaterial() const { return _bloomMaterial; } - inline void setBloomMaterial(Material *mat) { + inline void setBloomMaterial(Material *mat) { if (mat == _bloomMaterial.get()) { return; } @@ -39,7 +39,7 @@ public: } inline Material *getPostProcessMaterial() const { return _postProcessMaterial; } - inline void setPostProcessMaterial(Material *mat) { + inline void setPostProcessMaterial(Material *mat) { if (mat == _postProcessMaterial.get()) { return; } @@ -47,18 +47,18 @@ public: updatePipelinePassInfo(); } - inline void setLightingMaterial(Material *mat) { _lightingMaterial = mat; } - inline Material * getLightingMaterial() const { return _lightingMaterial; } - inline gfx::Shader * getLightPassShader() const { return _lightPassShader; } - inline scene::Pass * getLightPass() const { return _lightPass; } - inline gfx::Shader * getBloomPrefilterPassShader() const { return _bloomPrefilterPassShader; } - inline scene::Pass * getBloomPrefilterPass() const { return _bloomPrefilterPass; } + inline void setLightingMaterial(Material *mat) { _lightingMaterial = mat; } + inline Material *getLightingMaterial() const { return _lightingMaterial; } + inline gfx::Shader *getLightPassShader() const { return _lightPassShader; } + inline scene::Pass *getLightPass() const { return _lightPass; } + inline gfx::Shader *getBloomPrefilterPassShader() const { return _bloomPrefilterPassShader; } + inline scene::Pass *getBloomPrefilterPass() const { return _bloomPrefilterPass; } inline const ccstd::vector &getBloomUpSamplePasses() const { return _bloomUpSamplePasses; } - inline gfx::Shader * getBloomUpSamplePassShader() const { return _bloomUpSamplePassShader; } + inline gfx::Shader *getBloomUpSamplePassShader() const { return _bloomUpSamplePassShader; } inline const ccstd::vector &getBloomDownSamplePasses() const { return _bloomDownSamplePasses; } - inline gfx::Shader * getBloomDownSamplePassShader() const { return _bloomDownSamplePassShader; } - inline scene::Pass * getBloomCombinePass() const { return _bloomCombinePass; } - inline gfx::Shader * getBloomCombinePassShader() const { return _bloomCombinePassShader; } + inline gfx::Shader *getBloomDownSamplePassShader() const { return _bloomDownSamplePassShader; } + inline scene::Pass *getBloomCombinePass() const { return _bloomCombinePass; } + inline gfx::Shader *getBloomCombinePassShader() const { return _bloomCombinePassShader; } inline gfx::Shader *getPostPassShader() const { return _postPassShader; } inline scene::Pass *getPostPass() const { return _postPass; } @@ -71,22 +71,22 @@ private: void updateDeferredLightPass(); IntrusivePtr _postProcessMaterial; - gfx::Shader * _postPassShader{nullptr}; // weak reference - scene::Pass * _postPass{nullptr}; // weak reference + gfx::Shader *_postPassShader{nullptr}; // weak reference + scene::Pass *_postPass{nullptr}; // weak reference IntrusivePtr _lightingMaterial; - gfx::Shader * _lightPassShader{nullptr}; // weak reference - scene::Pass * _lightPass{nullptr}; // weak reference + gfx::Shader *_lightPassShader{nullptr}; // weak reference + scene::Pass *_lightPass{nullptr}; // weak reference - IntrusivePtr _bloomMaterial; - scene::Pass * _bloomPrefilterPass{nullptr}; // weak reference - gfx::Shader * _bloomPrefilterPassShader{nullptr}; // weak reference - scene::Pass * _bloomCombinePass{nullptr}; // weak reference - gfx::Shader * _bloomCombinePassShader{nullptr}; // weak reference - ccstd::vector _bloomUpSamplePasses; // weak reference - gfx::Shader * _bloomUpSamplePassShader{nullptr}; // weak reference - ccstd::vector _bloomDownSamplePasses; // weak reference - gfx::Shader * _bloomDownSamplePassShader{nullptr}; // weak reference + IntrusivePtr _bloomMaterial; + scene::Pass *_bloomPrefilterPass{nullptr}; // weak reference + gfx::Shader *_bloomPrefilterPassShader{nullptr}; // weak reference + scene::Pass *_bloomCombinePass{nullptr}; // weak reference + gfx::Shader *_bloomCombinePassShader{nullptr}; // weak reference + ccstd::vector _bloomUpSamplePasses; // weak reference + gfx::Shader *_bloomUpSamplePassShader{nullptr}; // weak reference + ccstd::vector _bloomDownSamplePasses; // weak reference + gfx::Shader *_bloomDownSamplePassShader{nullptr}; // weak reference AntiAliasing _antiAliasing{AntiAliasing::NONE}; }; diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp index 922c1b5327..6e9311f5db 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp @@ -52,7 +52,7 @@ RenderStageInfo GbufferStage::initInfo = { const RenderStageInfo &GbufferStage::getInitializeInfo() { return GbufferStage::initInfo; } GbufferStage::GbufferStage() { - _batchedQueue = ccnew RenderBatchedQueue; + _batchedQueue = ccnew RenderBatchedQueue; _instancedQueue = ccnew RenderInstancedQueue; } @@ -61,7 +61,7 @@ GbufferStage::~GbufferStage() = default; bool GbufferStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; - _phaseID = getPhaseID("default"); + _phaseID = getPhaseID("default"); return true; } @@ -69,9 +69,9 @@ void GbufferStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { RenderStage::activate(pipeline, flow); for (const auto &descriptor : _renderQueueDescriptors) { - uint phase = convertPhase(descriptor.stages); - RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); - RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; + uint phase = convertPhase(descriptor.stages); + RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); + RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; _renderQueues.emplace_back(ccnew RenderQueue(_pipeline, std::move(info), true)); } _planarShadowQueue = ccnew PlanarShadowQueue(_pipeline); @@ -93,17 +93,17 @@ void GbufferStage::dispenseRenderObject2Queues() { queue->clear(); } - uint subModelIdx = 0; - uint passIdx = 0; - size_t k = 0; + uint subModelIdx = 0; + uint passIdx = 0; + size_t k = 0; for (auto ro : renderObjects) { - const auto *const model = ro.model; - const auto & subModels = model->getSubModels(); - auto subModelCount = subModels.size(); + const auto *const model = ro.model; + const auto &subModels = model->getSubModels(); + auto subModelCount = subModels.size(); for (subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { - const auto &subModel = subModels[subModelIdx]; - const auto &passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto &subModel = subModels[subModelIdx]; + const auto &passes = subModel->getPasses(); + auto passCount = passes.size(); for (passIdx = 0; passIdx < passCount; ++passIdx) { const auto &pass = passes[passIdx]; if (pass->getPhase() != _phaseID) continue; @@ -189,11 +189,11 @@ void GbufferStage::render(scene::Camera *camera) { gfx::Color clearColor{0.0, 0.0, 0.0, 0.0}; framegraph::RenderTargetAttachment::Descriptor colorInfo; - colorInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorInfo.loadOp = gfx::LoadOp::CLEAR; - colorInfo.clearColor = clearColor; + colorInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorInfo.loadOp = gfx::LoadOp::CLEAR; + colorInfo.clearColor = clearColor; colorInfo.beginAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT; - colorInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT; + colorInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT; for (int i = 0; i < DeferredPipeline::GBUFFER_COUNT; ++i) { data.gbuffer[i] = builder.write(data.gbuffer[i], colorInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i], data.gbuffer[i]); @@ -213,12 +213,12 @@ void GbufferStage::render(scene::Camera *camera) { data.depth = builder.create(DeferredPipeline::fgStrHandleOutDepthTexture, depthTexInfo); framegraph::RenderTargetAttachment::Descriptor depthInfo; - depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthInfo.loadOp = gfx::LoadOp::CLEAR; - depthInfo.clearDepth = camera->getClearDepth(); + depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthInfo.loadOp = gfx::LoadOp::CLEAR; + depthInfo.clearDepth = camera->getClearDepth(); depthInfo.clearStencil = camera->getClearStencil(); - depthInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; - data.depth = builder.write(data.depth, depthInfo); + depthInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; + data.depth = builder.write(data.depth, depthInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleOutDepthTexture, data.depth); // viewport setup diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.h b/native/cocos/renderer/pipeline/deferred/GbufferStage.h index b823cc8ddc..11b57f974e 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.h +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.h @@ -59,10 +59,10 @@ private: void recordCommands(DeferredPipeline *pipeline, scene::Camera *camera, gfx::RenderPass *renderPass); static RenderStageInfo initInfo; - PlanarShadowQueue * _planarShadowQueue = nullptr; - RenderBatchedQueue * _batchedQueue = nullptr; - RenderInstancedQueue * _instancedQueue = nullptr; - uint _phaseID = 0; + PlanarShadowQueue *_planarShadowQueue = nullptr; + RenderBatchedQueue *_batchedQueue = nullptr; + RenderInstancedQueue *_instancedQueue = nullptr; + uint _phaseID = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp index 452ae3f584..dd0e2b19ba 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp @@ -51,35 +51,35 @@ namespace cc { namespace pipeline { namespace { -const ccstd::string STAGE_NAME = "LightingStage"; -const uint MAX_REFLECTOR_SIZE = 5; -framegraph::StringHandle reflectTexHandle = framegraph::FrameGraph::stringToHandle("reflectionTex"); +const ccstd::string STAGE_NAME = "LightingStage"; +const uint MAX_REFLECTOR_SIZE = 5; +framegraph::StringHandle reflectTexHandle = framegraph::FrameGraph::stringToHandle("reflectionTex"); framegraph::StringHandle denoiseTexHandle[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprClearPass[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprCompReflectPass[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprCompDenoisePass[MAX_REFLECTOR_SIZE]; framegraph::StringHandle ssprRenderPass[MAX_REFLECTOR_SIZE]; -framegraph::StringHandle fgStrHandleClusterLightBuffer = framegraph::FrameGraph::stringToHandle("clusterLightBuffer"); +framegraph::StringHandle fgStrHandleClusterLightBuffer = framegraph::FrameGraph::stringToHandle("clusterLightBuffer"); framegraph::StringHandle fgStrHandleClusterLightIndexBuffer = framegraph::FrameGraph::stringToHandle("lightIndexBuffer"); -framegraph::StringHandle fgStrHandleClusterLightGridBuffer = framegraph::FrameGraph::stringToHandle("lightGridBuffer"); +framegraph::StringHandle fgStrHandleClusterLightGridBuffer = framegraph::FrameGraph::stringToHandle("lightGridBuffer"); void initStrHandle() { ccstd::string tmp; for (int i = 0; i < MAX_REFLECTOR_SIZE; ++i) { - tmp = ccstd::string("denoiseTexureHandle") + std::to_string(i); + tmp = ccstd::string("denoiseTexureHandle") + std::to_string(i); denoiseTexHandle[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("ssprClearPss") + std::to_string(i); + tmp = ccstd::string("ssprClearPss") + std::to_string(i); ssprClearPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("ssprReflectPass") + std::to_string(i); + tmp = ccstd::string("ssprReflectPass") + std::to_string(i); ssprCompReflectPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("ssprDenoisePass") + std::to_string(i); + tmp = ccstd::string("ssprDenoisePass") + std::to_string(i); ssprCompDenoisePass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); - tmp = ccstd::string("ssprRenderPass") + std::to_string(i); + tmp = ccstd::string("ssprRenderPass") + std::to_string(i); ssprRenderPass[i] = framegraph::FrameGraph::stringToHandle(tmp.c_str()); } } @@ -103,27 +103,27 @@ LightingStage::~LightingStage() { bool LightingStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; - _phaseID = getPhaseID("default"); - _reflectionPhaseID = getPhaseID("reflection"); + _phaseID = getPhaseID("default"); + _reflectionPhaseID = getPhaseID("reflection"); initStrHandle(); return true; } void LightingStage::gatherLights(scene::Camera *camera) { - auto * pipeline = static_cast(_pipeline); + auto *pipeline = static_cast(_pipeline); auto *const sceneData = _pipeline->getPipelineSceneData(); gfx::CommandBuffer *cmdBuf = pipeline->getCommandBuffers()[0]; - const auto * scene = camera->getScene(); + const auto *scene = camera->getScene(); geometry::Sphere sphere; - auto exposure = camera->getExposure(); - uint idx = 0; - int elementLen = sizeof(cc::Vec4) / sizeof(float); - uint fieldLen = elementLen * _maxDeferredLights; - uint offset = 0; - cc::Vec4 tmpArray; + auto exposure = camera->getExposure(); + uint idx = 0; + int elementLen = sizeof(cc::Vec4) / sizeof(float); + uint fieldLen = elementLen * _maxDeferredLights; + uint offset = 0; + cc::Vec4 tmpArray; for (const auto &light : scene->getSphereLights()) { if (idx >= _maxDeferredLights) { @@ -137,15 +137,15 @@ void LightingStage::gatherLights(scene::Camera *camera) { continue; } // position - offset = idx * elementLen; - _lightBufferData[offset] = position.x; + offset = idx * elementLen; + _lightBufferData[offset] = position.x; _lightBufferData[offset + 1] = position.y; _lightBufferData[offset + 2] = position.z; _lightBufferData[offset + 3] = 0; // color const auto &color = light->getColor(); - offset = idx * elementLen + fieldLen; + offset = idx * elementLen + fieldLen; tmpArray.set(color.x, color.y, color.z, 0); if (light->isUseColorTemperature()) { const auto &colorTemperatureRGB = light->getColorTemperatureRGB(); @@ -166,8 +166,8 @@ void LightingStage::gatherLights(scene::Camera *camera) { _lightBufferData[offset + 3] = tmpArray.w; // size range angle - offset = idx * elementLen + fieldLen * 2; - _lightBufferData[offset] = light->getSize(); + offset = idx * elementLen + fieldLen * 2; + _lightBufferData[offset] = light->getSize(); _lightBufferData[offset + 1] = light->getRange(); _lightBufferData[offset + 2] = 0; @@ -186,14 +186,14 @@ void LightingStage::gatherLights(scene::Camera *camera) { continue; } // position - offset = idx * elementLen; - _lightBufferData[offset] = position.x; + offset = idx * elementLen; + _lightBufferData[offset] = position.x; _lightBufferData[offset + 1] = position.y; _lightBufferData[offset + 2] = position.z; _lightBufferData[offset + 3] = 1; // color - offset = idx * elementLen + fieldLen; + offset = idx * elementLen + fieldLen; const auto &color = light->getColor(); tmpArray.set(color.x, color.y, color.z, 0); if (light->isUseColorTemperature()) { @@ -215,15 +215,15 @@ void LightingStage::gatherLights(scene::Camera *camera) { _lightBufferData[offset + 3] = tmpArray.w; // size range angle - offset = idx * elementLen + fieldLen * 2; - _lightBufferData[offset] = light->getSize(); + offset = idx * elementLen + fieldLen * 2; + _lightBufferData[offset] = light->getSize(); _lightBufferData[offset + 1] = light->getRange(); _lightBufferData[offset + 2] = light->getSpotAngle(); // dir - const auto &direction = light->getDirection(); - offset = idx * elementLen + fieldLen * 3; - _lightBufferData[offset] = direction.x; + const auto &direction = light->getDirection(); + offset = idx * elementLen + fieldLen * 3; + _lightBufferData[offset] = direction.x; _lightBufferData[offset + 1] = direction.y; _lightBufferData[offset + 2] = direction.z; @@ -239,7 +239,7 @@ void LightingStage::initLightingBuffer() { auto *const device = _pipeline->getDevice(); // color/pos/dir/angle 都是vec4存储, 最后一个vec4只要x存储光源个数 - uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); + uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); uint totalSize = stride * _maxDeferredLights; // create lighting buffer and view @@ -255,7 +255,7 @@ void LightingStage::initLightingBuffer() { if (_deferredLitsBufView == nullptr) { gfx::BufferViewInfo bvInfo = {_deferredLitsBufs, 0, totalSize}; - _deferredLitsBufView = device->createBuffer(bvInfo); + _deferredLitsBufView = device->createBuffer(bvInfo); _descriptorSet->bindBuffer(static_cast(ModelLocalBindings::UBO_FORWARD_LIGHTS), _deferredLitsBufView); } @@ -268,9 +268,9 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { auto *const device = pipeline->getDevice(); for (const auto &descriptor : _renderQueueDescriptors) { - uint phase = convertPhase(descriptor.stages); - RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); - RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; + uint phase = convertPhase(descriptor.stages); + RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); + RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; _renderQueues.emplace_back(ccnew RenderQueue(_pipeline, std::move(info), true)); } @@ -278,10 +278,10 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { if (!pipeline->isClusterEnabled()) { // create descriptor set/layout gfx::DescriptorSetLayoutInfo layoutInfo = {localDescriptorSetLayout.bindings}; - _descLayout = device->createDescriptorSetLayout(layoutInfo); + _descLayout = device->createDescriptorSetLayout(layoutInfo); gfx::DescriptorSetInfo setInfo = {_descLayout}; - _descriptorSet = device->createDescriptorSet(setInfo); + _descriptorSet = device->createDescriptorSet(setInfo); // create lighting buffer and view initLightingBuffer(); @@ -291,7 +291,7 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { // create reflection resource RenderQueueCreateInfo info = {true, _reflectionPhaseID, transparentCompareFn}; - _reflectionComp = ccnew ReflectionComp(); + _reflectionComp = ccnew ReflectionComp(); _reflectionComp->init(_device, 8, 8); _reflectionRenderQueue = ccnew RenderQueue(_pipeline, std::move(info)); @@ -323,15 +323,15 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { framegraph::TextureHandle outputTex; // output texture framegraph::TextureHandle depth; framegraph::TextureHandle depthStencil; - framegraph::BufferHandle lightBuffer; // light storage buffer - framegraph::BufferHandle lightIndexBuffer; // light index storage buffer - framegraph::BufferHandle lightGridBuffer; // light grid storage buffer + framegraph::BufferHandle lightBuffer; // light storage buffer + framegraph::BufferHandle lightIndexBuffer; // light index storage buffer + framegraph::BufferHandle lightGridBuffer; // light grid storage buffer }; - auto * pipeline = static_cast(_pipeline); + auto *pipeline = static_cast(_pipeline); gfx::Color clearColor = pipeline->getClearcolor(camera); - float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; - _renderArea = RenderPipeline::getRenderArea(camera); + float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; + _renderArea = RenderPipeline::getRenderArea(camera); _inputAssembler = pipeline->getIAByRenderArea(_renderArea); _planarShadowQueue->gatherShadowPasses(camera, pipeline->getCommandBuffers()[0]); auto lightingSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { @@ -347,13 +347,13 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { data.depth = builder.read(data.depth); framegraph::RenderTargetAttachment::Descriptor depthInfo; - depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthInfo.loadOp = gfx::LoadOp::LOAD; - depthInfo.clearColor = gfx::Color(); + depthInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthInfo.loadOp = gfx::LoadOp::LOAD; + depthInfo.clearColor = gfx::Color(); depthInfo.beginAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; - depthInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; + depthInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; - data.depthStencil = builder.write(data.depth, depthInfo); + data.depthStencil = builder.write(data.depth, depthInfo); builder.writeToBlackboard(RenderPipeline::fgStrHandleOutDepthTexture, data.depthStencil); if (_pipeline->isClusterEnabled()) { @@ -375,25 +375,25 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { // write to lighting output framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(pipeline->getHeight()) * shadingScale); - data.outputTex = builder.create(RenderPipeline::fgStrHandleOutColorTexture, colorTexInfo); + data.outputTex = builder.create(RenderPipeline::fgStrHandleOutColorTexture, colorTexInfo); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = clearColor; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = clearColor; colorAttachmentInfo.beginAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; - colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; - data.outputTex = builder.write(data.outputTex, colorAttachmentInfo); + colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; + data.outputTex = builder.write(data.outputTex, colorAttachmentInfo); builder.writeToBlackboard(RenderPipeline::fgStrHandleOutColorTexture, data.outputTex); // set render area builder.setViewport(pipeline->getViewport(camera), pipeline->getScissor(camera)); }; auto lightingExec = [this, camera](RenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = static_cast(_pipeline); + auto *pipeline = static_cast(_pipeline); auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); auto *cmdBuff = pipeline->getCommandBuffers()[0]; @@ -407,9 +407,9 @@ void LightingStage::fgLightingPass(scene::Camera *camera) { const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); // get PSO and draw quad - scene::Pass * pass = sceneData->getLightPass(); - gfx::Shader * shader = sceneData->getLightPassShader(); - gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, _inputAssembler, table.getRenderPass(), table.getSubpassIndex()); + scene::Pass *pass = sceneData->getLightPass(); + gfx::Shader *shader = sceneData->getLightPassShader(); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, _inputAssembler, table.getRenderPass(), table.getSubpassIndex()); for (uint i = 0; i < DeferredPipeline::GBUFFER_COUNT; ++i) { pass->getDescriptorSet()->bindTexture(i, table.getRead(data.gbuffer[i])); @@ -452,27 +452,27 @@ void LightingStage::fgTransparent(scene::Camera *camera) { framegraph::TextureHandle depth; }; - auto * pipeline = static_cast(_pipeline); + auto *pipeline = static_cast(_pipeline); gfx::Color clearColor = pipeline->getClearcolor(camera); - float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; - auto transparentSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { + float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; + auto transparentSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { // write to lighting output framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; colorAttachmentInfo.beginAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; - colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; + colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; - data.outputTex = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleOutColorTexture)); + data.outputTex = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleOutColorTexture)); bool lightingPassValid = data.outputTex.isValid(); if (!lightingPassValid) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(pipeline->getHeight()) * shadingScale); - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; colorAttachmentInfo.clearColor = clearColor; data.outputTex = builder.create(DeferredPipeline::fgStrHandleOutColorTexture, colorTexInfo); @@ -482,10 +482,10 @@ void LightingStage::fgTransparent(scene::Camera *camera) { builder.writeToBlackboard(DeferredPipeline::fgStrHandleOutColorTexture, data.outputTex); framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; depthAttachmentInfo.beginAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; - depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; + depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; data.depth = framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleOutDepthTexture)); if (!data.depth.isValid()) { // when there is no opaque object present @@ -496,7 +496,7 @@ void LightingStage::fgTransparent(scene::Camera *camera) { static_cast(static_cast(pipeline->getWidth()) * shadingScale), static_cast(static_cast(pipeline->getHeight()) * shadingScale), }; - data.depth = builder.create(DeferredPipeline::fgStrHandleOutDepthTexture, depthTexInfo); + data.depth = builder.create(DeferredPipeline::fgStrHandleOutDepthTexture, depthTexInfo); depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; } data.depth = builder.write(data.depth, depthAttachmentInfo); @@ -508,7 +508,7 @@ void LightingStage::fgTransparent(scene::Camera *camera) { auto transparentExec = [this, camera](RenderData const & /*data*/, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); - auto *cmdBuff = pipeline->getCommandBuffers()[0]; + auto *cmdBuff = pipeline->getCommandBuffers()[0]; // no need to bind localSet in cluster if (!_pipeline->isClusterEnabled()) { @@ -540,14 +540,14 @@ void LightingStage::putTransparentObj2Queue() { queue->clear(); } - auto *const sceneData = _pipeline->getPipelineSceneData(); + auto *const sceneData = _pipeline->getPipelineSceneData(); const auto &renderObjects = sceneData->getRenderObjects(); - _isTransparentQueueEmpty = true; - uint m = 0; - uint p = 0; - size_t k = 0; + _isTransparentQueueEmpty = true; + uint m = 0; + uint p = 0; + size_t k = 0; for (auto ro : renderObjects) { - m = 0; + m = 0; const auto *const model = ro.model; for (const auto &subModel : model->getSubModels()) { p = 0; @@ -578,18 +578,18 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto *pipeline = static_cast(_pipeline); _denoiseIndex = 0; - _matViewProj = camera->getMatViewProj(); + _matViewProj = camera->getMatViewProj(); _reflectionElems.clear(); // step 1 prepare clear model's reflection texture pass. should switch to image clear command after available uint minSize = 512; - uint width = pipeline->getWidth(); - uint height = pipeline->getHeight(); + uint width = pipeline->getWidth(); + uint height = pipeline->getHeight(); if (height < width) { - _ssprTexWidth = minSize * width / height; + _ssprTexWidth = minSize * width / height; _ssprTexHeight = minSize; } else { - _ssprTexWidth = minSize; + _ssprTexWidth = minSize; _ssprTexHeight = minSize * height / width; } @@ -600,18 +600,18 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto clearSetup = [&](framegraph::PassNodeBuilder &builder, DataClear &data) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA8; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::STORAGE | + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC | gfx::TextureUsageBit::TRANSFER_DST; - colorTexInfo.width = _ssprTexWidth; + colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - data.reflection = builder.create(reflectTexHandle, colorTexInfo); + data.reflection = builder.create(reflectTexHandle, colorTexInfo); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - colorAttachmentInfo.clearColor = {0.F, 0.F, 0.F, 0.F}; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.clearColor = {0.F, 0.F, 0.F, 0.F}; colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COMPUTE_SHADER_WRITE; - data.reflection = builder.write(data.reflection, colorAttachmentInfo); + data.reflection = builder.write(data.reflection, colorAttachmentInfo); builder.writeToBlackboard(reflectTexHandle, data.reflection); builder.sideEffect(); }; @@ -639,10 +639,10 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { if (!data.reflection.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA8; - colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC | gfx::TextureUsageBit::TRANSFER_DST; - colorTexInfo.width = _ssprTexWidth; + colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC | gfx::TextureUsageBit::TRANSFER_DST; + colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - data.reflection = builder.create(reflectTexHandle, colorTexInfo); + data.reflection = builder.create(reflectTexHandle, colorTexInfo); } data.reflection = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(reflectTexHandle))); @@ -655,15 +655,15 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto compReflectExec = [this, camera](DataCompReflect const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); - gfx::Viewport vp = pipeline->getViewport(camera); - Vec4 value = Vec4(static_cast(vp.left), static_cast(vp.top), + gfx::Viewport vp = pipeline->getViewport(camera); + Vec4 value = Vec4(static_cast(vp.left), static_cast(vp.top), static_cast(vp.width), static_cast(vp.height)); _reflectionComp->applyTexSize(_ssprTexWidth, _ssprTexHeight, camera->getMatView(), camera->getMatViewProj(), camera->getMatViewProjInv(), camera->getMatProjInv(), value); - auto *texReflection = static_cast(table.getWrite(data.reflection)); + auto *texReflection = static_cast(table.getWrite(data.reflection)); auto *texLightingOut = static_cast(table.getRead(data.lightingOut)); - auto *texDepth = static_cast(table.getRead(data.depth)); + auto *texDepth = static_cast(table.getRead(data.depth)); // step 1 pipeline barrier before exec auto *cmdBuff = pipeline->getCommandBuffers()[0]; @@ -677,8 +677,8 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // step 2 bind descriptors gfx::DescriptorSet *reflectDesc = _reflectionComp->getDescriptorSet(); - gfx::Sampler * sampler = _reflectionComp->getSampler(); - gfx::Buffer * constBuffer = _reflectionComp->getConstantsBuffer(); + gfx::Sampler *sampler = _reflectionComp->getSampler(); + gfx::Buffer *constBuffer = _reflectionComp->getConstantsBuffer(); reflectDesc->bindBuffer(0, constBuffer); reflectDesc->bindSampler(1, sampler); @@ -711,10 +711,10 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // write to reflection framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA8; - colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC; - colorTexInfo.width = _ssprTexWidth; + colorTexInfo.usage = gfx::TextureUsageBit::STORAGE | gfx::TextureUsageBit::SAMPLED | gfx::TextureUsageBit::TRANSFER_SRC; + colorTexInfo.width = _ssprTexWidth; colorTexInfo.height = _ssprTexHeight; - data.denoise = builder.create(denoiseTexHandle[_denoiseIndex], colorTexInfo); + data.denoise = builder.create(denoiseTexHandle[_denoiseIndex], colorTexInfo); data.depth = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleOutDepthTexture))); builder.writeToBlackboard(RenderPipeline::fgStrHandleOutDepthTexture, data.depth); @@ -726,10 +726,10 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto compDenoiseExec = [this](DataCompDenoise const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); - auto *denoiseTex = static_cast(table.getWrite(data.denoise)); + auto *denoiseTex = static_cast(table.getWrite(data.denoise)); auto *reflectionTex = static_cast(table.getRead(data.reflection)); - auto *depth = static_cast(table.getRead(data.depth)); - auto &elem = _reflectionElems[_denoiseIndex]; + auto *depth = static_cast(table.getRead(data.depth)); + auto &elem = _reflectionElems[_denoiseIndex]; // pipeline barrier auto *cmdBuff = pipeline->getCommandBuffers()[0]; @@ -783,22 +783,22 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { // write lighting out, as an attachment framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; - colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - colorAttachmentInfo.clearColor = gfx::Color(); + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + colorAttachmentInfo.clearColor = gfx::Color(); colorAttachmentInfo.beginAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; - colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; + colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; data.lightingOut = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleOutColorTexture)), colorAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleOutColorTexture, data.lightingOut); // read depth, as an attachment framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; - depthAttachmentInfo.clearColor = gfx::Color(); + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; + depthAttachmentInfo.clearColor = gfx::Color(); depthAttachmentInfo.beginAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; - depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; + depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_READ; data.depth = builder.write(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleOutDepthTexture)), depthAttachmentInfo); builder.writeToBlackboard(DeferredPipeline::fgStrHandleOutDepthTexture, data.depth); @@ -808,14 +808,14 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { auto renderExec = [this, camera](DataRender const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); - auto *cmdBuff = pipeline->getCommandBuffers()[0]; - auto &elem = _reflectionElems[_denoiseIndex]; + auto *cmdBuff = pipeline->getCommandBuffers()[0]; + auto &elem = _reflectionElems[_denoiseIndex]; // bind descriptor cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet()); - gfx::DescriptorSet *descLocal = elem.set; // sub model descriptor set - auto * denoiseTex = static_cast(table.getRead(data.denoise)); + gfx::DescriptorSet *descLocal = elem.set; // sub model descriptor set + auto *denoiseTex = static_cast(table.getRead(data.denoise)); descLocal->bindTexture(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), denoiseTex); descLocal->bindSampler(static_cast(ModelLocalBindings::SAMPLER_REFLECTION), _defaultSampler); @@ -831,17 +831,17 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { }; // step 5 add framegraph passes - auto *const sceneData = _pipeline->getPipelineSceneData(); + auto *const sceneData = _pipeline->getPipelineSceneData(); const auto &renderObjects = sceneData->getRenderObjects(); - uint m = 0; - uint p = 0; + uint m = 0; + uint p = 0; for (const auto &ro : renderObjects) { - const auto *model = ro.model; + const auto *model = ro.model; const auto &subModels = model->getSubModels(); for (m = 0; m < subModels.size(); ++m) { - const auto &subModel = subModels[m]; - const auto &passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto &subModel = subModels[m]; + const auto &passes = subModel->getPasses(); + auto passCount = passes.size(); for (p = 0; p < passCount; ++p) { const auto &pass = passes[p]; if (pass->getPhase() == _reflectionPhaseID) { diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.h b/native/cocos/renderer/pipeline/deferred/LightingStage.h index 30e6f2cc41..db6ff689be 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.h +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.h @@ -41,10 +41,10 @@ struct DeferredRenderData; class DeferredPipeline; struct RenderElem { - RenderObject renderObject; + RenderObject renderObject; gfx::DescriptorSet *set; - uint modelIndex; - uint passIndex; + uint modelIndex; + uint passIndex; }; class CC_DLL LightingStage : public RenderStage { @@ -69,31 +69,31 @@ private: void putTransparentObj2Queue(); static RenderStageInfo initInfo; - PlanarShadowQueue * _planarShadowQueue{nullptr}; - uint _phaseID{0}; + PlanarShadowQueue *_planarShadowQueue{nullptr}; + uint _phaseID{0}; - gfx::Buffer * _deferredLitsBufs{nullptr}; - gfx::Buffer * _deferredLitsBufView{nullptr}; - ccstd::vector _lightBufferData; - uint _lightBufferStride{0}; - uint _lightBufferElementCount{0}; - bool _isTransparentQueueEmpty{true}; - float _lightMeterScale{10000.0}; - gfx::DescriptorSet * _descriptorSet{nullptr}; + gfx::Buffer *_deferredLitsBufs{nullptr}; + gfx::Buffer *_deferredLitsBufView{nullptr}; + ccstd::vector _lightBufferData; + uint _lightBufferStride{0}; + uint _lightBufferElementCount{0}; + bool _isTransparentQueueEmpty{true}; + float _lightMeterScale{10000.0}; + gfx::DescriptorSet *_descriptorSet{nullptr}; gfx::DescriptorSetLayout *_descLayout{nullptr}; - uint _maxDeferredLights{UBODeferredLight::LIGHTS_PER_PASS}; + uint _maxDeferredLights{UBODeferredLight::LIGHTS_PER_PASS}; ReflectionComp *_reflectionComp{nullptr}; - RenderQueue * _reflectionRenderQueue{nullptr}; - uint _reflectionPhaseID{0}; + RenderQueue *_reflectionRenderQueue{nullptr}; + uint _reflectionPhaseID{0}; ccstd::vector _reflectionElems; - uint _denoiseIndex = 0; // use to get corrrect texture string handle + uint _denoiseIndex = 0; // use to get corrrect texture string handle gfx::Sampler *_defaultSampler{nullptr}; // SSPR texture size - uint _ssprTexWidth = 0; + uint _ssprTexWidth = 0; uint _ssprTexHeight = 0; Mat4 _matViewProj; }; diff --git a/native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp b/native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp index 7eecf132c6..6a9aa2defa 100644 --- a/native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/PostProcessStage.cpp @@ -116,11 +116,11 @@ void PostProcessStage::render(scene::Camera *camera) { _clearColors[0].z = camera->getClearColor().z; } _clearColors[0].w = camera->getClearColor().w; - _renderArea = RenderPipeline::getRenderArea(camera); - _inputAssembler = _pipeline->getIAByRenderArea(_renderArea); - auto *pipeline = _pipeline; + _renderArea = RenderPipeline::getRenderArea(camera); + _inputAssembler = _pipeline->getIAByRenderArea(_renderArea); + auto *pipeline = _pipeline; float shadingScale{_pipeline->getPipelineSceneData()->getShadingScale()}; - auto postSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { + auto postSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) { if (pipeline->isBloomEnabled()) { data.outColorTex = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleBloomOutTexture)); } else { @@ -130,8 +130,8 @@ void PostProcessStage::render(scene::Camera *camera) { if (!data.outColorTex.isValid()) { framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = gfx::Format::RGBA16F; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; - colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT | gfx::TextureUsageBit::SAMPLED; + colorTexInfo.width = static_cast(static_cast(pipeline->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(pipeline->getHeight()) * shadingScale); data.outColorTex = builder.create(RenderPipeline::fgStrHandleOutColorTexture, colorTexInfo); @@ -141,9 +141,9 @@ void PostProcessStage::render(scene::Camera *camera) { builder.writeToBlackboard(RenderPipeline::fgStrHandleOutColorTexture, data.outColorTex); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; colorAttachmentInfo.clearColor = _clearColors[0]; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; auto clearFlags = static_cast(camera->getClearFlag()); if (!hasFlag(clearFlags, gfx::ClearFlagBit::COLOR)) { @@ -156,8 +156,8 @@ void PostProcessStage::render(scene::Camera *camera) { colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = camera->getWindow()->getSwapchain() - ? gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE - : gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; + ? gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE + : gfx::AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE; gfx::TextureInfo textureInfo = { gfx::TextureType::TEX2D, @@ -175,8 +175,8 @@ void PostProcessStage::render(scene::Camera *camera) { // depth framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; depthAttachmentInfo.beginAccesses = depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; data.depth = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleOutDepthTexture)); @@ -197,23 +197,23 @@ void PostProcessStage::render(scene::Camera *camera) { }; auto postExec = [this, camera](RenderData const &data, const framegraph::DevicePassResourceTable &table) { - auto * pipeline = _pipeline; + auto *pipeline = _pipeline; gfx::RenderPass *renderPass = table.getRenderPass(); - auto * cmdBuff = pipeline->getCommandBuffers()[0]; + auto *cmdBuff = pipeline->getCommandBuffers()[0]; const ccstd::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); if (!pipeline->getPipelineSceneData()->getRenderObjects().empty()) { // post process - auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); - scene::Pass *pv = sceneData->getPostPass(); - gfx::Shader *sd = sceneData->getPostPassShader(); - float shadingScale{sceneData->getShadingScale()}; + auto *const sceneData = static_cast(pipeline->getPipelineSceneData()); + scene::Pass *pv = sceneData->getPostPass(); + gfx::Shader *sd = sceneData->getPostPassShader(); + float shadingScale{sceneData->getShadingScale()}; // get pso and draw quad - gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, _inputAssembler, renderPass); + gfx::PipelineState *pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, _inputAssembler, renderPass); pipeline::GlobalDSManager *globalDS = pipeline->getGlobalDSManager(); - gfx::Sampler * sampler = shadingScale < 1.F ? globalDS->getPointSampler() : globalDS->getLinearSampler(); + gfx::Sampler *sampler = shadingScale < 1.F ? globalDS->getPointSampler() : globalDS->getLinearSampler(); pv->getDescriptorSet()->bindTexture(0, table.getRead(data.outColorTex)); pv->getDescriptorSet()->bindSampler(0, sampler); diff --git a/native/cocos/renderer/pipeline/deferred/PostProcessStage.h b/native/cocos/renderer/pipeline/deferred/PostProcessStage.h index 4628481ccf..5a770e3b71 100644 --- a/native/cocos/renderer/pipeline/deferred/PostProcessStage.h +++ b/native/cocos/renderer/pipeline/deferred/PostProcessStage.h @@ -46,8 +46,8 @@ public: void render(scene::Camera *camera) override; private: - UIPhase * _uiPhase = nullptr; - uint _phaseID = 0; + UIPhase *_uiPhase = nullptr; + uint _phaseID = 0; static RenderStageInfo initInfo; }; diff --git a/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp b/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp index 72f16fed79..5c0d698d01 100644 --- a/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp +++ b/native/cocos/renderer/pipeline/deferred/ReflectionComp.cpp @@ -42,22 +42,22 @@ struct ConstantBuffer { void ReflectionComp::applyTexSize(uint width, uint height, const Mat4 &matView, const Mat4 &matViewProj, const Mat4 &matViewProjInv, const Mat4 &matProjInv, const Vec4 &viewPort) { - uint globalWidth = width; + uint globalWidth = width; uint globalHeight = height; - uint groupWidth = this->getGroupSizeX(); - uint groupHeight = this->getGroupSizeY(); + uint groupWidth = this->getGroupSizeX(); + uint groupHeight = this->getGroupSizeY(); - _dispatchInfo = {(globalWidth - 1) / groupWidth + 1, (globalHeight - 1) / groupHeight + 1, 1}; + _dispatchInfo = {(globalWidth - 1) / groupWidth + 1, (globalHeight - 1) / groupHeight + 1, 1}; _denoiseDispatchInfo = {((globalWidth - 1) / 2) / groupWidth + 1, ((globalHeight - 1) / 2) / groupHeight + 1, 1}; ConstantBuffer constants; - constants.matView = matView; - constants.matProjInv = matProjInv; - constants.matViewProj = matViewProj; + constants.matView = matView; + constants.matProjInv = matProjInv; + constants.matViewProj = matViewProj; constants.matViewProjInv = matViewProjInv; - constants.viewPort = viewPort; - constants.texSize = {float(width), float(height)}; - constants.viewPort = viewPort; + constants.viewPort = viewPort; + constants.texSize = {float(width), float(height)}; + constants.viewPort = viewPort; if (_compConstantsBuffer) { _compConstantsBuffer->update(&constants, sizeof(constants)); @@ -67,21 +67,21 @@ void ReflectionComp::applyTexSize(uint width, uint height, const Mat4 &matView, void ReflectionComp::init(gfx::Device *dev, uint groupSizeX, uint groupSizeY) { if (!dev->hasFeature(gfx::Feature::COMPUTE_SHADER)) return; - _device = dev; + _device = dev; _groupSizeX = groupSizeX; _groupSizeY = groupSizeY; gfx::SamplerInfo samplerInfo; samplerInfo.minFilter = gfx::Filter::POINT; samplerInfo.magFilter = gfx::Filter::POINT; - _sampler = _device->getSampler(samplerInfo); + _sampler = _device->getSampler(samplerInfo); uint maxInvocations = _device->getCapabilities().maxComputeWorkGroupInvocations; CC_ASSERT(_groupSizeX * _groupSizeY <= maxInvocations); // maxInvocations is too small CC_LOG_INFO(" work group size: %dx%d", _groupSizeX, _groupSizeY); gfx::DescriptorSetLayoutInfo layoutInfo = {pipeline::localDescriptorSetLayout.bindings}; - _localDescriptorSetLayout = _device->createDescriptorSetLayout(layoutInfo); + _localDescriptorSetLayout = _device->createDescriptorSetLayout(layoutInfo); gfx::GeneralBarrierInfo infoPre = { gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE, @@ -262,7 +262,7 @@ void ReflectionComp::initReflectionRes() { getReflectorShader(sources, i); gfx::ShaderInfo shaderInfo; - shaderInfo.name = "Compute "; + shaderInfo.name = "Compute "; shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getAppropriateShaderSource(sources)}}; shaderInfo.blocks = { {0, 0, "Constants", { @@ -291,15 +291,15 @@ void ReflectionComp::initReflectionRes() { dslInfo.bindings.push_back({4, gfx::DescriptorType::STORAGE_IMAGE, 1, gfx::ShaderStageFlagBit::COMPUTE}); _compDescriptorSetLayout = _device->createDescriptorSetLayout(dslInfo); - _compDescriptorSet = _device->createDescriptorSet({_compDescriptorSetLayout}); + _compDescriptorSet = _device->createDescriptorSet({_compDescriptorSetLayout}); _compPipelineLayout = _device->createPipelineLayout({{_compDescriptorSetLayout}}); for (int i = 0; i < 2; ++i) { gfx::PipelineStateInfo pipelineInfo; - pipelineInfo.shader = _compShader[i]; + pipelineInfo.shader = _compShader[i]; pipelineInfo.pipelineLayout = _compPipelineLayout; - pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; + pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; _compPipelineState[i] = _device->createPipelineState(pipelineInfo); } @@ -501,11 +501,11 @@ void ReflectionComp::initDenoiseRes() { getDenoiseShader(sources, i); gfx::ShaderInfo shaderInfo; - shaderInfo.name = "Compute "; + shaderInfo.name = "Compute "; shaderInfo.stages = {{gfx::ShaderStageFlagBit::COMPUTE, getAppropriateShaderSource(sources)}}; if (i == 0) { - shaderInfo.blocks = {}; + shaderInfo.blocks = {}; shaderInfo.samplerTextures = { {0, 1, "reflectionTex", gfx::Type::SAMPLER2D, 1}}; } else { @@ -538,14 +538,14 @@ void ReflectionComp::initDenoiseRes() { dslInfo.bindings.push_back({2, gfx::DescriptorType::SAMPLER_TEXTURE, 1, gfx::ShaderStageFlagBit::COMPUTE}); dslInfo.bindings.push_back({3, gfx::DescriptorType::SAMPLER_TEXTURE, 1, gfx::ShaderStageFlagBit::COMPUTE}); _compDenoiseDescriptorSetLayout = _device->createDescriptorSetLayout(dslInfo); - _compDenoisePipelineLayout = _device->createPipelineLayout({{_compDenoiseDescriptorSetLayout, _localDescriptorSetLayout}}); - _compDenoiseDescriptorSet = _device->createDescriptorSet({_compDenoiseDescriptorSetLayout}); + _compDenoisePipelineLayout = _device->createPipelineLayout({{_compDenoiseDescriptorSetLayout, _localDescriptorSetLayout}}); + _compDenoiseDescriptorSet = _device->createDescriptorSet({_compDenoiseDescriptorSetLayout}); for (int i = 0; i < 2; ++i) { gfx::PipelineStateInfo pipelineInfo; - pipelineInfo.shader = _compDenoiseShader[i]; + pipelineInfo.shader = _compDenoiseShader[i]; pipelineInfo.pipelineLayout = _compDenoisePipelineLayout; - pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; + pipelineInfo.bindPoint = gfx::PipelineBindPoint::COMPUTE; _compDenoisePipelineState[i] = _device->createPipelineState(pipelineInfo); } diff --git a/native/cocos/renderer/pipeline/deferred/ReflectionComp.h b/native/cocos/renderer/pipeline/deferred/ReflectionComp.h index c781a6f7e7..720eaf6942 100644 --- a/native/cocos/renderer/pipeline/deferred/ReflectionComp.h +++ b/native/cocos/renderer/pipeline/deferred/ReflectionComp.h @@ -32,20 +32,20 @@ public: const Mat4 &matViewProj, const Mat4 &matViewProjInv, const Mat4 &matProjInv, const Vec4 &viewPort); - inline gfx::DescriptorSet * getDescriptorSet() { return _compDescriptorSet; } - inline const gfx::PipelineState * getPipelineState(bool useEnvmap) { return _compPipelineState[useEnvmap]; } - inline gfx::DescriptorSet * getDenoiseDescriptorSet() { return _compDenoiseDescriptorSet; } - inline const gfx::PipelineState * getDenoisePipelineState(bool useEnvmap) { return _compDenoisePipelineState[useEnvmap]; } - inline const gfx::PipelineState * getDenoisePipelineStateEnvmap() { return _compDenoisePipelineStateEnvmap; } - inline const gfx::GeneralBarrier * getBarrierPre() { return _barrierPre; } + inline gfx::DescriptorSet *getDescriptorSet() { return _compDescriptorSet; } + inline const gfx::PipelineState *getPipelineState(bool useEnvmap) { return _compPipelineState[useEnvmap]; } + inline gfx::DescriptorSet *getDenoiseDescriptorSet() { return _compDenoiseDescriptorSet; } + inline const gfx::PipelineState *getDenoisePipelineState(bool useEnvmap) { return _compDenoisePipelineState[useEnvmap]; } + inline const gfx::PipelineState *getDenoisePipelineStateEnvmap() { return _compDenoisePipelineStateEnvmap; } + inline const gfx::GeneralBarrier *getBarrierPre() { return _barrierPre; } inline const gfx::TextureBarrierList &getBarrierBeforeDenoise() { return _barrierBeforeDenoise; } inline const gfx::TextureBarrierList &getBarrierAfterDenoise() { return _barrierAfterDenoise; } - inline const gfx::DispatchInfo & getDispatchInfo() { return _dispatchInfo; } - inline const gfx::DispatchInfo & getDenoiseDispatchInfo() { return _denoiseDispatchInfo; } - inline uint getGroupSizeX() const { return _groupSizeX; } - inline uint getGroupSizeY() const { return _groupSizeY; } + inline const gfx::DispatchInfo &getDispatchInfo() { return _dispatchInfo; } + inline const gfx::DispatchInfo &getDenoiseDispatchInfo() { return _denoiseDispatchInfo; } + inline uint getGroupSizeX() const { return _groupSizeX; } + inline uint getGroupSizeY() const { return _groupSizeY; } - inline gfx::Buffer * getConstantsBuffer() { return _compConstantsBuffer; } + inline gfx::Buffer *getConstantsBuffer() { return _compConstantsBuffer; } inline gfx::Sampler *getSampler() { return _sampler; } private: @@ -54,22 +54,22 @@ private: gfx::Device *_device{nullptr}; - gfx::Shader * _compShader[2]{nullptr}; + gfx::Shader *_compShader[2]{nullptr}; gfx::DescriptorSetLayout *_compDescriptorSetLayout{nullptr}; - gfx::PipelineLayout * _compPipelineLayout{nullptr}; - gfx::PipelineState * _compPipelineState[2]{nullptr}; - gfx::DescriptorSet * _compDescriptorSet{nullptr}; + gfx::PipelineLayout *_compPipelineLayout{nullptr}; + gfx::PipelineState *_compPipelineState[2]{nullptr}; + gfx::DescriptorSet *_compDescriptorSet{nullptr}; - gfx::Shader * _compDenoiseShader[2]{nullptr}; + gfx::Shader *_compDenoiseShader[2]{nullptr}; gfx::DescriptorSetLayout *_compDenoiseDescriptorSetLayout{nullptr}; - gfx::PipelineLayout * _compDenoisePipelineLayout{nullptr}; - gfx::PipelineState * _compDenoisePipelineState[2]{nullptr}; - gfx::PipelineState * _compDenoisePipelineStateEnvmap{nullptr}; - gfx::DescriptorSet * _compDenoiseDescriptorSet{nullptr}; + gfx::PipelineLayout *_compDenoisePipelineLayout{nullptr}; + gfx::PipelineState *_compDenoisePipelineState[2]{nullptr}; + gfx::PipelineState *_compDenoisePipelineStateEnvmap{nullptr}; + gfx::DescriptorSet *_compDenoiseDescriptorSet{nullptr}; gfx::DescriptorSetLayout *_localDescriptorSetLayout{nullptr}; - gfx::Buffer * _compConstantsBuffer{nullptr}; + gfx::Buffer *_compConstantsBuffer{nullptr}; gfx::Sampler *_sampler{nullptr}; gfx::GeneralBarrier *_barrierPre{nullptr}; diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 252f764d40..3b1438f291 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -55,7 +55,7 @@ ForwardPipeline::ForwardPipeline() { framegraph::StringHandle ForwardPipeline::fgStrHandleForwardColorTexture = framegraph::FrameGraph::stringToHandle("forwardColorTexture"); framegraph::StringHandle ForwardPipeline::fgStrHandleForwardDepthTexture = framegraph::FrameGraph::stringToHandle("forwardDepthTexture"); -framegraph::StringHandle ForwardPipeline::fgStrHandleForwardPass = framegraph::FrameGraph::stringToHandle("forwardPass"); +framegraph::StringHandle ForwardPipeline::fgStrHandleForwardPass = framegraph::FrameGraph::stringToHandle("forwardPass"); bool ForwardPipeline::initialize(const RenderPipelineInfo &info) { RenderPipeline::initialize(info); @@ -91,7 +91,7 @@ bool ForwardPipeline::activate(gfx::Swapchain *swapchain) { void ForwardPipeline::render(const ccstd::vector &cameras) { CC_PROFILE(ForwardPipelineRender); - auto * device = gfx::Device::getInstance(); + auto *device = gfx::Device::getInstance(); const bool enableOcclusionQuery = isOcclusionQueryEnabled(); if (enableOcclusionQuery) { device->getQueryPoolResults(_queryPools[0]); @@ -143,12 +143,12 @@ bool ForwardPipeline::activeRenderer(gfx::Swapchain *swapchain) { _descriptorSet->update(); // update global defines when all states initialized. - _macros["CC_USE_HDR"] = static_cast(_pipelineSceneData->isHDR()); + _macros["CC_USE_HDR"] = static_cast(_pipelineSceneData->isHDR()); _macros["CC_SUPPORT_FLOAT_TEXTURE"] = hasAnyFlags(_device->getFormatFeatures(gfx::Format::RGBA32F), gfx::FormatFeature::RENDER_TARGET | gfx::FormatFeature::SAMPLED_TEXTURE); // step 2 create index buffer uint ibStride = 4; - uint ibSize = ibStride * 6; + uint ibSize = ibStride * 6; if (_quadIB == nullptr) { _quadIB = _device->createBuffer({gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, ibSize, ibStride}); @@ -161,7 +161,7 @@ bool ForwardPipeline::activeRenderer(gfx::Swapchain *swapchain) { uint ibData[] = {0, 1, 2, 1, 3, 2}; _quadIB->update(ibData, sizeof(ibData)); - _width = swapchain->getWidth(); + _width = swapchain->getWidth(); _height = swapchain->getHeight(); return true; } diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.h b/native/cocos/renderer/pipeline/forward/ForwardPipeline.h index b5f1067bdc..2c3e54fa5d 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.h +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.h @@ -46,11 +46,11 @@ public: bool activate(gfx::Swapchain *swapchain) override; void render(const ccstd::vector &cameras) override; - inline gfx::Buffer * getLightsUBO() const { return _lightsUBO; } - inline const LightList & getValidLights() const { return _validLights; } + inline gfx::Buffer *getLightsUBO() const { return _lightsUBO; } + inline const LightList &getValidLights() const { return _validLights; } inline const gfx::BufferList &getLightBuffers() const { return _lightBuffers; } - inline const UintList & getLightIndexOffsets() const { return _lightIndexOffsets; } - inline const UintList & getLightIndices() const { return _lightIndices; } + inline const UintList &getLightIndexOffsets() const { return _lightIndexOffsets; } + inline const UintList &getLightIndices() const { return _lightIndices; } static framegraph::StringHandle fgStrHandleForwardColorTexture; static framegraph::StringHandle fgStrHandleForwardDepthTexture; @@ -61,11 +61,11 @@ private: bool activeRenderer(gfx::Swapchain *swapchain); void updateUBO(scene::Camera *); - gfx::Buffer * _lightsUBO = nullptr; - LightList _validLights; + gfx::Buffer *_lightsUBO = nullptr; + LightList _validLights; gfx::BufferList _lightBuffers; - UintList _lightIndexOffsets; - UintList _lightIndices; + UintList _lightIndexOffsets; + UintList _lightIndices; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index b589515505..96efb428a1 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -55,9 +55,9 @@ RenderStageInfo ForwardStage::initInfo = { const RenderStageInfo &ForwardStage::getInitializeInfo() { return ForwardStage::initInfo; } ForwardStage::ForwardStage() { - _batchedQueue = ccnew RenderBatchedQueue; + _batchedQueue = ccnew RenderBatchedQueue; _instancedQueue = ccnew RenderInstancedQueue; - _uiPhase = ccnew UIPhase; + _uiPhase = ccnew UIPhase; } ForwardStage::~ForwardStage() = default; @@ -65,7 +65,7 @@ ForwardStage::~ForwardStage() = default; bool ForwardStage::initialize(const RenderStageInfo &info) { RenderStage::initialize(info); _renderQueueDescriptors = info.renderQueues; - _phaseID = getPhaseID("default"); + _phaseID = getPhaseID("default"); return true; } @@ -73,14 +73,14 @@ void ForwardStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { RenderStage::activate(pipeline, flow); for (const auto &descriptor : _renderQueueDescriptors) { - uint phase = convertPhase(descriptor.stages); - RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); - RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; + uint phase = convertPhase(descriptor.stages); + RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); + RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; _renderQueues.emplace_back(ccnew RenderQueue(_pipeline, std::move(info), true)); } _additiveLightQueue = ccnew RenderAdditiveLightQueue(_pipeline); - _planarShadowQueue = ccnew PlanarShadowQueue(_pipeline); + _planarShadowQueue = ccnew PlanarShadowQueue(_pipeline); _uiPhase->activate(pipeline); } @@ -97,7 +97,7 @@ void ForwardStage::dispenseRenderObject2Queues() { _instancedQueue->clear(); _batchedQueue->clear(); - const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto *sceneData = _pipeline->getPipelineSceneData(); const auto &renderObjects = sceneData->getRenderObjects(); for (auto *queue : _renderQueues) { @@ -105,13 +105,13 @@ void ForwardStage::dispenseRenderObject2Queues() { } for (const auto &ro : renderObjects) { - const auto *const model = ro.model; - const auto & subModels = model->getSubModels(); - const auto subModelCount = subModels.size(); + const auto *const model = ro.model; + const auto &subModels = model->getSubModels(); + const auto subModelCount = subModels.size(); for (uint subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { - const auto &subModel = subModels[subModelIdx]; - const auto &passes = subModel->getPasses(); - const auto passCount = passes.size(); + const auto &subModel = subModels[subModelIdx]; + const auto &passes = subModel->getPasses(); + const auto passCount = passes.size(); for (uint passIdx = 0; passIdx < passCount; ++passIdx) { const auto &pass = passes[passIdx]; if (pass->getPhase() != _phaseID) continue; @@ -143,7 +143,7 @@ void ForwardStage::render(scene::Camera *camera) { framegraph::TextureHandle outputTex; framegraph::TextureHandle depth; }; - auto * pipeline = static_cast(_pipeline); + auto *pipeline = static_cast(_pipeline); auto *const sceneData = _pipeline->getPipelineSceneData(); float shadingScale{sceneData->getShadingScale()}; @@ -167,18 +167,18 @@ void ForwardStage::render(scene::Camera *camera) { // color framegraph::Texture::Descriptor colorTexInfo; colorTexInfo.format = sceneData->isHDR() ? gfx::Format::RGBA16F : gfx::Format::RGBA8; - colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT; - colorTexInfo.width = static_cast(static_cast(camera->getWindow()->getWidth()) * shadingScale); + colorTexInfo.usage = gfx::TextureUsageBit::COLOR_ATTACHMENT; + colorTexInfo.width = static_cast(static_cast(camera->getWindow()->getWidth()) * shadingScale); colorTexInfo.height = static_cast(static_cast(camera->getWindow()->getHeight()) * shadingScale); if (shadingScale != 1.F) { colorTexInfo.usage |= gfx::TextureUsageBit::TRANSFER_SRC; } data.outputTex = builder.create(RenderPipeline::fgStrHandleOutColorTexture, colorTexInfo); framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; + colorAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::COLOR; colorAttachmentInfo.clearColor = _clearColors[0]; - colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - auto clearFlags = static_cast(camera->getClearFlag()); + colorAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + auto clearFlags = static_cast(camera->getClearFlag()); if (!hasFlag(clearFlags, gfx::ClearFlagBit::COLOR)) { if (hasFlag(clearFlags, static_cast(skyboxFlag))) { colorAttachmentInfo.loadOp = gfx::LoadOp::DISCARD; @@ -200,12 +200,12 @@ void ForwardStage::render(scene::Camera *camera) { }; framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo; - depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; - depthAttachmentInfo.clearDepth = camera->getClearDepth(); - depthAttachmentInfo.clearStencil = camera->getClearStencil(); + depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; + depthAttachmentInfo.loadOp = gfx::LoadOp::CLEAR; + depthAttachmentInfo.clearDepth = camera->getClearDepth(); + depthAttachmentInfo.clearStencil = camera->getClearStencil(); depthAttachmentInfo.beginAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; - depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; + depthAttachmentInfo.endAccesses = gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE; if (static_cast(clearFlags & gfx::ClearFlagBit::DEPTH_STENCIL) != gfx::ClearFlagBit::DEPTH_STENCIL && (!hasFlag(clearFlags, gfx::ClearFlagBit::DEPTH) || !hasFlag(clearFlags, gfx::ClearFlagBit::STENCIL))) { depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD; } @@ -215,10 +215,10 @@ void ForwardStage::render(scene::Camera *camera) { builder.setViewport(pipeline->getViewport(camera), pipeline->getScissor(camera)); }; - auto offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); + auto offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); auto forwardExec = [this, camera, offset, pipeline](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) { auto *renderPass = table.getRenderPass(); - auto *cmdBuff = _pipeline->getCommandBuffers()[0]; + auto *cmdBuff = _pipeline->getCommandBuffers()[0]; cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), 1, &offset); if (!_pipeline->getPipelineSceneData()->getRenderObjects().empty()) { _renderQueues[0]->recordCommandBuffer(_device, camera, renderPass, cmdBuff); diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.h b/native/cocos/renderer/pipeline/forward/ForwardStage.h index bcf7352d06..a0c0e146e3 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.h +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.h @@ -51,16 +51,16 @@ public: void render(scene::Camera *camera) override; private: - void dispenseRenderObject2Queues(); - static RenderStageInfo initInfo; - ForwardPipeline * _forwrdPipeline = nullptr; - PlanarShadowQueue * _planarShadowQueue = nullptr; - RenderBatchedQueue * _batchedQueue = nullptr; - RenderInstancedQueue * _instancedQueue = nullptr; + void dispenseRenderObject2Queues(); + static RenderStageInfo initInfo; + ForwardPipeline *_forwrdPipeline = nullptr; + PlanarShadowQueue *_planarShadowQueue = nullptr; + RenderBatchedQueue *_batchedQueue = nullptr; + RenderInstancedQueue *_instancedQueue = nullptr; RenderAdditiveLightQueue *_additiveLightQueue = nullptr; - UIPhase * _uiPhase = nullptr; - gfx::Rect _renderArea; - uint _phaseID = 0; + UIPhase *_uiPhase = nullptr; + gfx::Rect _renderArea; + uint _phaseID = 0; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/helper/Utils.cpp b/native/cocos/renderer/pipeline/helper/Utils.cpp index 2e3c4635b9..91ad676185 100644 --- a/native/cocos/renderer/pipeline/helper/Utils.cpp +++ b/native/cocos/renderer/pipeline/helper/Utils.cpp @@ -52,12 +52,12 @@ void decideProfilerCamera(const ccstd::vector &cameras) { void renderProfiler(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, scene::Model *profiler, const scene::Camera *camera) { if (profiler && profiler->isEnabled() && camera == profilerCamera) { const auto &submodel = profiler->getSubModels()[0]; - auto * pass = submodel->getPass(0); - auto * ia = submodel->getInputAssembler(); - auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, submodel->getShader(0), ia, renderPass); + auto *pass = submodel->getPass(0); + auto *ia = submodel->getInputAssembler(); + auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, submodel->getShader(0), ia, renderPass); gfx::Viewport profilerViewport; - gfx::Rect profilerScissor; + gfx::Rect profilerScissor; profilerViewport.width = profilerScissor.width = camera->getWindow()->getWidth(); profilerViewport.height = profilerScissor.height = camera->getWindow()->getHeight(); cmdBuff->setViewport(profilerViewport); @@ -69,13 +69,13 @@ void renderProfiler(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, sc cmdBuff->bindInputAssembler(ia); cmdBuff->draw(ia); } -} - -void renderDebugRenderer(gfx::RenderPass* renderPass, gfx::CommandBuffer* cmdBuff, PipelineSceneData* sceneData, const scene::Camera* camera) { +} + +void renderDebugRenderer(gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, PipelineSceneData *sceneData, const scene::Camera *camera) { if (camera != profilerCamera) { - return; - } - + return; + } + CC_DEBUG_RENDERER->render(renderPass, cmdBuff, sceneData); } diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 7ae7169ab7..a19919509c 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -51,7 +51,7 @@ RenderFlowInfo ShadowFlow::initInfo = { }; const RenderFlowInfo &ShadowFlow::getInitializeInfo() { return ShadowFlow::initInfo; } -ShadowFlow::ShadowFlow() = default; +ShadowFlow::ShadowFlow() = default; ShadowFlow::~ShadowFlow() = default; bool ShadowFlow::initialize(const RenderFlowInfo &info) { @@ -71,8 +71,8 @@ void ShadowFlow::activate(RenderPipeline *pipeline) { void ShadowFlow::render(scene::Camera *camera) { CC_PROFILE(ShadowFlowRender); - const auto *sceneData = _pipeline->getPipelineSceneData(); - auto * shadowInfo = sceneData->getShadows(); + const auto *sceneData = _pipeline->getPipelineSceneData(); + auto *shadowInfo = sceneData->getShadows(); if (shadowInfo == nullptr || !shadowInfo->isEnabled() || shadowInfo->getType() != scene::ShadowType::SHADOW_MAP) { return; } @@ -88,8 +88,8 @@ void ShadowFlow::render(scene::Camera *camera) { resizeShadowMap(); } - const auto & shadowFramebufferMap = sceneData->getShadowFramebufferMap(); - const scene::DirectionalLight *mainLight = camera->getScene()->getMainLight(); + const auto &shadowFramebufferMap = sceneData->getShadowFramebufferMap(); + const scene::DirectionalLight *mainLight = camera->getScene()->getMainLight(); if (mainLight) { gfx::DescriptorSet *globalDS = _pipeline->getDescriptorSet(); if (!shadowFramebufferMap.count(mainLight)) { @@ -105,7 +105,7 @@ void ShadowFlow::render(scene::Camera *camera) { } for (uint l = 0; l < _validLights.size(); ++l) { - const scene::Light *light = _validLights[l]; + const scene::Light *light = _validLights[l]; gfx::DescriptorSet *globalDS = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(l); if (!shadowFramebufferMap.count(light)) { @@ -134,9 +134,9 @@ void ShadowFlow::lightCollecting() { } void ShadowFlow::clearShadowMap(scene::Camera *camera) { - const auto * sceneData = _pipeline->getPipelineSceneData(); - const auto & shadowFramebufferMap = sceneData->getShadowFramebufferMap(); - const scene::DirectionalLight *mainLight = camera->getScene()->getMainLight(); + const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto &shadowFramebufferMap = sceneData->getShadowFramebufferMap(); + const scene::DirectionalLight *mainLight = camera->getScene()->getMainLight(); if (mainLight) { gfx::DescriptorSet *globalDS = _pipeline->getDescriptorSet(); @@ -153,7 +153,7 @@ void ShadowFlow::clearShadowMap(scene::Camera *camera) { } for (uint l = 0; l < _validLights.size(); ++l) { - const scene::Light *light = _validLights[l]; + const scene::Light *light = _validLights[l]; gfx::DescriptorSet *globalDS = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(l); if (!shadowFramebufferMap.count(light)) { @@ -170,12 +170,12 @@ void ShadowFlow::clearShadowMap(scene::Camera *camera) { } void ShadowFlow::resizeShadowMap() { - const auto *sceneData = _pipeline->getPipelineSceneData(); - auto * shadowInfo = sceneData->getShadows(); - auto * device = gfx::Device::getInstance(); - const auto width = static_cast(shadowInfo->getSize().x); - const auto height = static_cast(shadowInfo->getSize().y); - const auto format = supportsR32FloatTexture(device) ? gfx::Format::R32F : gfx::Format::RGBA8; + const auto *sceneData = _pipeline->getPipelineSceneData(); + auto *shadowInfo = sceneData->getShadows(); + auto *device = gfx::Device::getInstance(); + const auto width = static_cast(shadowInfo->getSize().x); + const auto height = static_cast(shadowInfo->getSize().y); + const auto format = supportsR32FloatTexture(device) ? gfx::Format::R32F : gfx::Format::RGBA8; for (const auto &pair : sceneData->getShadowFramebufferMap()) { gfx::Framebuffer *framebuffer = pair.second; @@ -223,13 +223,13 @@ void ShadowFlow::resizeShadowMap() { } void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Light *light) { - auto * device = gfx::Device::getInstance(); - const auto *sceneData = _pipeline->getPipelineSceneData(); - const auto *shadowInfo = sceneData->getShadows(); + auto *device = gfx::Device::getInstance(); + const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto *shadowInfo = sceneData->getShadows(); const auto &shadowMapSize = shadowInfo->getSize(); - const auto width = static_cast(shadowMapSize.x); - const auto height = static_cast(shadowMapSize.y); - const auto format = supportsR32FloatTexture(device) ? gfx::Format::R32F : gfx::Format::RGBA8; + const auto width = static_cast(shadowMapSize.x); + const auto height = static_cast(shadowMapSize.y); + const auto format = supportsR32FloatTexture(device) ? gfx::Format::R32F : gfx::Format::RGBA8; const gfx::ColorAttachment colorAttachment = { format, @@ -260,7 +260,7 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li rpInfo.depthStencilAttachment = depthStencilAttachment; size_t rpHash = cc::gfx::RenderPass::computeHash(rpInfo); - auto iter = renderPassHashMap.find(rpHash); + auto iter = renderPassHashMap.find(rpHash); if (iter != renderPassHashMap.end()) { _renderPass = iter->second; } else { diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h index ea00c0d60a..a6b80c3680 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.h +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.h @@ -61,7 +61,7 @@ private: gfx::RenderPass *_renderPass = nullptr; ccstd::vector _validLights; - ccstd::vector _usedTextures; + ccstd::vector _usedTextures; static ccstd::unordered_map renderPassHashMap; }; diff --git a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp index a4c9370ea1..73acb3a94e 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp @@ -39,7 +39,7 @@ namespace cc { namespace pipeline { -ShadowStage::ShadowStage() = default; +ShadowStage::ShadowStage() = default; ShadowStage::~ShadowStage() = default; RenderStageInfo ShadowStage::initInfo = { @@ -65,7 +65,7 @@ void ShadowStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { void ShadowStage::render(scene::Camera *camera) { CC_PROFILE(ShadowStageRender); - const auto *sceneData = _pipeline->getPipelineSceneData(); + const auto *sceneData = _pipeline->getPipelineSceneData(); const auto *shadowInfo = sceneData->getShadows(); if (!_light || !_framebuffer) { @@ -77,13 +77,13 @@ void ShadowStage::render(scene::Camera *camera) { _additiveShadowQueue->gatherLightPasses(camera, _light, cmdBuffer); const auto &shadowMapSize = shadowInfo->getSize(); - const auto &viewport = camera->getViewport(); - _renderArea.x = static_cast(viewport.x * shadowMapSize.x); - _renderArea.y = static_cast(viewport.y * shadowMapSize.y); - _renderArea.width = static_cast(viewport.z * shadowMapSize.x * sceneData->getShadingScale()); - _renderArea.height = static_cast(viewport.w * shadowMapSize.y * sceneData->getShadingScale()); + const auto &viewport = camera->getViewport(); + _renderArea.x = static_cast(viewport.x * shadowMapSize.x); + _renderArea.y = static_cast(viewport.y * shadowMapSize.y); + _renderArea.width = static_cast(viewport.z * shadowMapSize.x * sceneData->getShadingScale()); + _renderArea.height = static_cast(viewport.w * shadowMapSize.y * sceneData->getShadingScale()); - _clearColors[0] = {1.0F, 1.0F, 1.0F, 1.0F}; + _clearColors[0] = {1.0F, 1.0F, 1.0F, 1.0F}; auto *renderPass = _framebuffer->getRenderPass(); cmdBuffer->beginRenderPass(renderPass, _framebuffer, _renderArea, @@ -98,8 +98,8 @@ void ShadowStage::render(scene::Camera *camera) { void ShadowStage::destroy() { _framebuffer = nullptr; - _globalDS = nullptr; - _light = nullptr; + _globalDS = nullptr; + _light = nullptr; CC_SAFE_DESTROY_AND_DELETE(_additiveShadowQueue); @@ -113,7 +113,7 @@ void ShadowStage::clearFramebuffer(scene::Camera *camera) { auto *cmdBuffer = _pipeline->getCommandBuffers()[0]; - _clearColors[0] = {1.0F, 1.0F, 1.0F, 1.0F}; + _clearColors[0] = {1.0F, 1.0F, 1.0F, 1.0F}; auto *renderPass = _framebuffer->getRenderPass(); cmdBuffer->beginRenderPass(renderPass, _framebuffer, _renderArea, diff --git a/native/cocos/renderer/pipeline/shadow/ShadowStage.h b/native/cocos/renderer/pipeline/shadow/ShadowStage.h index 2947adc407..656d2e7cdf 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowStage.h +++ b/native/cocos/renderer/pipeline/shadow/ShadowStage.h @@ -45,8 +45,8 @@ public: inline void setFramebuffer(gfx::Framebuffer *framebuffer) { _framebuffer = framebuffer; } inline void setUsage(gfx::DescriptorSet *globalDS, const scene::Light *light, gfx::Framebuffer *framebuffer) { - _globalDS = globalDS; - _light = light; + _globalDS = globalDS; + _light = light; _framebuffer = framebuffer; } @@ -55,10 +55,10 @@ public: private: static RenderStageInfo initInfo; - gfx::Rect _renderArea; - gfx::DescriptorSet *_globalDS = nullptr; - const scene::Light *_light = nullptr; - gfx::Framebuffer * _framebuffer = nullptr; + gfx::Rect _renderArea; + gfx::DescriptorSet *_globalDS = nullptr; + const scene::Light *_light = nullptr; + gfx::Framebuffer *_framebuffer = nullptr; ShadowMapBatchedQueue *_additiveShadowQueue = nullptr; }; diff --git a/native/cocos/scene/Ambient.cpp b/native/cocos/scene/Ambient.cpp index 3bb05209cd..11f25d2c0e 100644 --- a/native/cocos/scene/Ambient.cpp +++ b/native/cocos/scene/Ambient.cpp @@ -47,7 +47,7 @@ namespace cc { namespace scene { void AmbientInfo::setSkyLightingColor(const Color &val) { - Vec4 v4(static_cast(val.r) / 255.F, static_cast(val.g) / 255.F, static_cast(val.b) / 255.F, static_cast(val.a) / 255.F); + Vec4 v4(static_cast(val.r) / 255.F, static_cast(val.g) / 255.F, static_cast(val.b) / 255.F, static_cast(val.a) / 255.F); const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { _skyColorHDR.set(v4); @@ -61,7 +61,7 @@ void AmbientInfo::setSkyLightingColor(const Color &val) { const Color &AmbientInfo::getSkyLightingColor() const { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); - Vec4 v4(isHDR ? _skyColorHDR : _skyColorLDR); + Vec4 v4(isHDR ? _skyColorHDR : _skyColorLDR); normalizeHDRColor(v4); col.set(static_cast(v4.x) * 255, static_cast(v4.y) * 255, static_cast(v4.z) * 255, 255); return col; @@ -99,7 +99,7 @@ float AmbientInfo::getSkyIllum() const { } void AmbientInfo::setGroundLightingColor(const Color &val) { - Vec4 v4(static_cast(val.r) / 255.F, static_cast(val.g) / 255.F, static_cast(val.b) / 255.F, static_cast(val.a) / 255.F); + Vec4 v4(static_cast(val.r) / 255.F, static_cast(val.g) / 255.F, static_cast(val.b) / 255.F, static_cast(val.a) / 255.F); const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { _groundAlbedoHDR.set(v4); @@ -114,7 +114,7 @@ void AmbientInfo::setGroundLightingColor(const Color &val) { const Color &AmbientInfo::getGroundLightingColor() const { const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); - Vec4 v4(isHDR ? _groundAlbedoHDR : _groundAlbedoLDR); + Vec4 v4(isHDR ? _groundAlbedoHDR : _groundAlbedoLDR); normalizeHDRColor(v4); col.set(static_cast(v4.x) * 255, static_cast(v4.y) * 255, static_cast(v4.z) * 255, 255); return col; @@ -145,12 +145,12 @@ void Ambient::initialize(AmbientInfo *info) { // _skyIllum = info->getSkyIllum(); // Init HDR/LDR from serialized data on load - _skyColorHDR = info->getSkyColorHDR(); + _skyColorHDR = info->getSkyColorHDR(); _groundAlbedoHDR.set(info->getGroundAlbedoHDR()); - _skyIllumHDR = info->getSkyIllumHDR(); - _skyColorLDR = info->getSkyColorLDR(); + _skyIllumHDR = info->getSkyIllumHDR(); + _skyColorLDR = info->getSkyColorLDR(); _groundAlbedoLDR.set(info->getGroundAlbedoLDR()); - _skyIllumLDR = info->getSkyIllumLDR(); + _skyIllumLDR = info->getSkyIllumLDR(); } Vec4 &Ambient::getSkyColor() { diff --git a/native/cocos/scene/Ambient.h b/native/cocos/scene/Ambient.h index 979bf1380e..7b3f423a9c 100644 --- a/native/cocos/scene/Ambient.h +++ b/native/cocos/scene/Ambient.h @@ -43,7 +43,7 @@ public: static constexpr float SKY_ILLUM{20000.0F}; Ambient(/* args */) = default; - ~Ambient() = default; + ~Ambient() = default; void initialize(AmbientInfo *info); @@ -60,33 +60,33 @@ public: */ Vec4 &getSkyColor(); - void setSkyColor(const Vec4 &color); + void setSkyColor(const Vec4 &color); /** * @en Sky illuminance * @zh 天空亮度 */ float getSkyIllum() const; - void setSkyIllum(float illum); + void setSkyIllum(float illum); /** * @en Ground color * @zh 地面颜色 */ const Vec4 &getGroundAlbedo() const; - void setGroundAlbedo(const Vec4 &color); + void setGroundAlbedo(const Vec4 &color); inline uint8_t getMipmapCount() const { return _mipmapCount; } - inline void setMipmapCount(uint8_t count) { _mipmapCount = count; } + inline void setMipmapCount(uint8_t count) { _mipmapCount = count; } protected: - Vec4 _groundAlbedoHDR{0.2F, 0.2F, 0.2F, 1.F}; - Vec4 _skyColorHDR{0.2F, 0.5F, 0.8F, 1.F}; + Vec4 _groundAlbedoHDR{0.2F, 0.2F, 0.2F, 1.F}; + Vec4 _skyColorHDR{0.2F, 0.5F, 0.8F, 1.F}; float _skyIllumHDR{0.F}; - Vec4 _groundAlbedoLDR{0.2F, 0.2F, 0.2F, 1.F}; - Vec4 _skyColorLDR{0.2F, 0.5F, 0.8F, 1.F}; - float _skyIllumLDR{0.F}; + Vec4 _groundAlbedoLDR{0.2F, 0.2F, 0.2F, 1.F}; + Vec4 _skyColorLDR{0.2F, 0.5F, 0.8F, 1.F}; + float _skyIllumLDR{0.F}; uint8_t _mipmapCount{1}; bool _enabled{false}; @@ -105,15 +105,15 @@ public: AmbientInfo(/* args */) = default; ~AmbientInfo() override = default; - inline void setSkyColorHDR(const Vec4 &val) { _skyColorHDR.set(val); }; + inline void setSkyColorHDR(const Vec4 &val) { _skyColorHDR.set(val); }; inline const Vec4 &getSkyColorHDR() const { return _skyColorHDR; }; inline const Vec4 &getSkyColorLDR() const { return _skyColorLDR; }; - inline void setGroundAlbedoHDR(const Vec4 &val) { _groundAlbedoHDR.set(val); }; + inline void setGroundAlbedoHDR(const Vec4 &val) { _groundAlbedoHDR.set(val); }; inline const Vec4 &getGroundAlbedoHDR() const { return _groundAlbedoHDR; }; inline const Vec4 &getGroundAlbedoLDR() const { return _groundAlbedoLDR; }; - inline void setSkyIllumHDR(float val) { _skyIllumHDR = val; }; + inline void setSkyIllumHDR(float val) { _skyIllumHDR = val; }; inline const float &getSkyIllumHDR() const { return _skyIllumHDR; }; inline const float &getSkyIllumLDR() const { return _skyIllumLDR; }; @@ -132,7 +132,7 @@ public: // }) // @editable // @tooltip('i18n:ambient.skyLightingColor') - void setSkyLightingColor(const Color &val); + void setSkyLightingColor(const Color &val); const Color &getSkyLightingColor() const; void setSkyColor(const Vec4 &val); @@ -144,7 +144,7 @@ public: // @editable // @type(CCFloat) // @tooltip('i18n:ambient.skyIllum') - void setSkyIllum(float val); + void setSkyIllum(float val); float getSkyIllum() const; /** @@ -162,7 +162,7 @@ public: // }) // @editable // @tooltip('i18n:ambient.groundLightingColor') - void setGroundLightingColor(const Color &val); + void setGroundLightingColor(const Color &val); const Color &getGroundLightingColor() const; void setGroundAlbedo(const Vec4 &val); diff --git a/native/cocos/scene/Camera.cpp b/native/cocos/scene/Camera.cpp index 82f5573c4f..90813cea1b 100644 --- a/native/cocos/scene/Camera.cpp +++ b/native/cocos/scene/Camera.cpp @@ -64,11 +64,11 @@ const ccstd::vector Camera::ISOS{100.0F, 200.0F, 400.0F, 800.0F}; Camera::Camera(gfx::Device *device) : _device(device) { _apertureValue = Camera::FSTOPS.at(static_cast(_aperture)); - _shutterValue = Camera::SHUTTERS.at(static_cast(_shutter)); - _isoValue = Camera::ISOS[static_cast(_iso)]; + _shutterValue = Camera::SHUTTERS.at(static_cast(_shutter)); + _isoValue = Camera::ISOS[static_cast(_iso)]; _aspect = _screenScale = 1.F; - _frustum = ccnew geometry::Frustum(); + _frustum = ccnew geometry::Frustum(); _frustum->addRef(); _frustum->setAccurate(true); @@ -85,15 +85,15 @@ Camera::Camera(gfx::Device *device) } bool Camera::initialize(const ICameraInfo &info) { - _node = info.node; - _width = 1.F; - _height = 1.F; - _clearFlag = gfx::ClearFlagBit::NONE; + _node = info.node; + _width = 1.F; + _height = 1.F; + _clearFlag = gfx::ClearFlagBit::NONE; _clearDepth = 1.0F; _visibility = pipeline::CAMERA_DEFAULT_MASK; - _name = info.name; - _proj = info.projection; - _priority = info.priority; + _name = info.name; + _proj = info.projection; + _priority = info.priority; _aspect = _screenScale = 1.F; updateExposure(); changeTargetWindow(info.window); @@ -112,12 +112,12 @@ void Camera::destroy() { void Camera::attachToScene(RenderScene *scene) { _enabled = true; - _scene = scene; + _scene = scene; } void Camera::detachFromScene() { _enabled = false; - _scene = nullptr; + _scene = nullptr; } void Camera::resize(uint32_t width, uint32_t height) { @@ -125,13 +125,13 @@ void Camera::resize(uint32_t width, uint32_t height) { return; } - _width = width; + _width = width; _height = height; updateAspect(); } void Camera::setFixedSize(uint32_t width, uint32_t height) { - _width = width; + _width = width; _height = height; updateAspect(false); _isWindowSize = false; @@ -140,11 +140,11 @@ void Camera::setFixedSize(uint32_t width, uint32_t height) { // Editor specific gizmo camera logic void Camera::syncCameraEditor(const Camera &camera) { #if CC_EDITOR - this->_position = camera._position; - this->_forward = camera._forward; - this->_matView = camera._matView; - this->_matProj = camera._matProj; - this->_matProjInv = camera._matProjInv; + this->_position = camera._position; + this->_forward = camera._forward; + this->_matView = camera._matView; + this->_matProj = camera._matProj; + this->_matProjInv = camera._matProjInv; this->_matViewProj = camera._matViewProj; #endif } @@ -165,11 +165,11 @@ void Camera::update(bool forceUpdate /*false*/) { } // projection matrix - auto * swapchain = _window->getSwapchain(); + auto *swapchain = _window->getSwapchain(); const auto &orientation = swapchain ? swapchain->getSurfaceTransform() : gfx::SurfaceTransform::IDENTITY; if (_isProjDirty || _curTransform != orientation) { - _curTransform = orientation; + _curTransform = orientation; const float projectionSignY = _device->getCapabilities().clipSpaceSignY; // Only for rendertexture processing if (_proj == CameraProjection::PERSPECTIVE) { @@ -182,9 +182,9 @@ void Camera::update(bool forceUpdate /*false*/) { _device->getCapabilities().clipSpaceMinZ, projectionSignY, static_cast(orientation), &_matProj); } - _matProjInv = _matProj.getInversed(); + _matProjInv = _matProj.getInversed(); viewProjDirty = true; - _isProjDirty = false; + _isProjDirty = false; } // view-projection @@ -204,7 +204,7 @@ void Camera::changeTargetWindow(RenderWindow *window) { _window = win; // window size is pre-rotated - auto * swapchain = win->getSwapchain(); + auto *swapchain = win->getSwapchain(); const auto orientation = swapchain ? swapchain->getSurfaceTransform() : gfx::SurfaceTransform::IDENTITY; if (static_cast(orientation) % 2) { resize(win->getHeight(), win->getWidth()); @@ -222,12 +222,12 @@ void Camera::detachCamera() { geometry::Ray Camera::screenPointToRay(float x, float y) { CC_ASSERT(_node != nullptr); - const float cx = _orientedViewport.x * static_cast(_width); - const float cy = _orientedViewport.y * static_cast(_height); - const float cw = _orientedViewport.z * static_cast(_width); - const float ch = _orientedViewport.w * static_cast(_height); - const bool isProj = _proj == CameraProjection::PERSPECTIVE; - const float ySign = _device->getCapabilities().clipSpaceSignY; + const float cx = _orientedViewport.x * static_cast(_width); + const float cy = _orientedViewport.y * static_cast(_height); + const float cw = _orientedViewport.z * static_cast(_width); + const float ch = _orientedViewport.w * static_cast(_height); + const bool isProj = _proj == CameraProjection::PERSPECTIVE; + const float ySign = _device->getCapabilities().clipSpaceSignY; const ccstd::array &preTransform = PRE_TRANSFORMS[static_cast(_curTransform)]; Vec3 tmpVec3{ @@ -256,13 +256,13 @@ geometry::Ray Camera::screenPointToRay(float x, float y) { } Vec3 Camera::screenToWorld(const Vec3 &screenPos) { - const float cx = _orientedViewport.x * static_cast(_width); - const float cy = _orientedViewport.y * static_cast(_height); - const float cw = _orientedViewport.z * static_cast(_width); - const float ch = _orientedViewport.w * static_cast(_height); - const float ySign = _device->getCapabilities().clipSpaceSignY; + const float cx = _orientedViewport.x * static_cast(_width); + const float cy = _orientedViewport.y * static_cast(_height); + const float cw = _orientedViewport.z * static_cast(_width); + const float ch = _orientedViewport.w * static_cast(_height); + const float ySign = _device->getCapabilities().clipSpaceSignY; const ccstd::array &preTransform = PRE_TRANSFORMS[static_cast(_curTransform)]; - Vec3 out; + Vec3 out; if (_proj == CameraProjection::PERSPECTIVE) { // calculate screen pos in far clip plane @@ -299,9 +299,9 @@ Vec3 Camera::screenToWorld(const Vec3 &screenPos) { } Vec3 Camera::worldToScreen(const Vec3 &worldPos) { - const float ySign = _device->getCapabilities().clipSpaceSignY; + const float ySign = _device->getCapabilities().clipSpaceSignY; const ccstd::array &preTransform = PRE_TRANSFORMS[static_cast(_curTransform)]; - Vec3 out; + Vec3 out; Vec3::transformMat4(worldPos, _matViewProj, &out); out.x = out.x * preTransform[0] + out.y * preTransform[2] * ySign; @@ -324,9 +324,9 @@ Mat4 Camera::worldMatrixToScreen(const Mat4 &worldMatrix, uint32_t width, uint32 Mat4::multiply(_matViewProj, worldMatrix, &out); Mat4::multiply(correctionMatrices[static_cast(_curTransform)], out, &out); - const float halfWidth = static_cast(width) / 2; + const float halfWidth = static_cast(width) / 2; const float halfHeight = static_cast(height) / 2; - Mat4 tmpMat4(Mat4::IDENTITY); + Mat4 tmpMat4(Mat4::IDENTITY); tmpMat4.translate(halfWidth, halfHeight, 0); tmpMat4.scale(halfWidth, halfHeight, 1); @@ -350,7 +350,7 @@ void Camera::updateAspect(bool oriented) { _aspect = (static_cast(getWindow()->getWidth()) * _viewport.z) / (static_cast(getWindow()->getHeight()) * _viewport.w); // window size/viewport is pre-rotated, but aspect should be oriented to acquire the correct projection if (oriented) { - auto * swapchain = getWindow()->getSwapchain(); + auto *swapchain = getWindow()->getSwapchain(); const auto orientation = swapchain ? swapchain->getSurfaceTransform() : gfx::SurfaceTransform::IDENTITY; if (static_cast(orientation) % 2) _aspect = 1 / _aspect; } @@ -363,13 +363,13 @@ void Camera::setViewport(const Vec4 &val) { } void Camera::setViewportInOrientedSpace(const Vec4 &val) { - const float x = val.x; - const float width = val.z; + const float x = val.x; + const float width = val.z; const float height = val.w; const float y = _device->getCapabilities().screenSpaceSignY < 0 ? 1 - val.y - height : val.y; - auto * swapchain = getWindow()->getSwapchain(); + auto *swapchain = getWindow()->getSwapchain(); const auto orientation = swapchain ? swapchain->getSurfaceTransform() : gfx::SurfaceTransform::IDENTITY; switch (orientation) { case gfx::SurfaceTransform::ROTATE_90: diff --git a/native/cocos/scene/Camera.h b/native/cocos/scene/Camera.h index dd711d49bc..9f32448033 100644 --- a/native/cocos/scene/Camera.h +++ b/native/cocos/scene/Camera.h @@ -115,12 +115,12 @@ enum class CameraShutter { }; struct ICameraInfo { - ccstd::string name; - Node * node{nullptr}; - CameraProjection projection; - cc::optional targetDisplay; - RenderWindow * window{nullptr}; - uint32_t priority{0}; + ccstd::string name; + Node *node{nullptr}; + CameraProjection projection; + cc::optional targetDisplay; + RenderWindow *window{nullptr}; + uint32_t priority{0}; cc::optional pipeline; }; @@ -180,7 +180,7 @@ public: */ Mat4 worldMatrixToScreen(const Mat4 &worldMatrix, uint32_t width, uint32_t height); - void setNode(Node *val); + void setNode(Node *val); inline Node *getNode() const { return _node.get(); } inline void setEnabled(bool val) { _enabled = val; } @@ -193,78 +193,78 @@ public: inline float getOrthoHeight() const { return _orthoHeight; } inline void setProjectionType(CameraProjection val) { - _proj = val; + _proj = val; _isProjDirty = true; } inline CameraProjection getProjectionType() const { return _proj; } inline void setFovAxis(CameraFOVAxis axis) { - _fovAxis = axis; + _fovAxis = axis; _isProjDirty = true; } inline CameraFOVAxis getFovAxis() const { return _fovAxis; } inline void setFov(float fov) { - _fov = fov; + _fov = fov; _isProjDirty = true; } inline float getFov() const { return _fov; } inline void setNearClip(float nearClip) { - _nearClip = nearClip; + _nearClip = nearClip; _isProjDirty = true; } inline float getNearClip() const { return _nearClip; } inline void setFarClip(float farClip) { - _farClip = farClip; + _farClip = farClip; _isProjDirty = true; } inline float getFarClip() const { return _farClip; } - inline void setClearColor(const gfx::Color &val) { _clearColor = val; } + inline void setClearColor(const gfx::Color &val) { _clearColor = val; } inline const gfx::Color &getClearColor() const { return _clearColor; } /** * Pre-rotated (i.e. always in identity/portrait mode) if possible. */ inline const Vec4 &getViewport() const { return _viewport; } - void setViewport(const Vec4 &val); - void setViewportInOrientedSpace(const Vec4 &val); + void setViewport(const Vec4 &val); + void setViewportInOrientedSpace(const Vec4 &val); - inline RenderScene * getScene() const { return _scene; } + inline RenderScene *getScene() const { return _scene; } inline const ccstd::string &getName() const { return _name; } - inline uint32_t getWidth() const { return _width; } - inline uint32_t getHeight() const { return _height; } - inline float getAspect() const { return _aspect; } - inline const Mat4 & getMatView() const { return _matView; } - inline const Mat4 & getMatProj() const { return _matProj; } - inline const Mat4 & getMatProjInv() const { return _matProjInv; } - inline const Mat4 & getMatViewProj() const { return _matViewProj; } - inline const Mat4 & getMatViewProjInv() const { return _matViewProjInv; } + inline uint32_t getWidth() const { return _width; } + inline uint32_t getHeight() const { return _height; } + inline float getAspect() const { return _aspect; } + inline const Mat4 &getMatView() const { return _matView; } + inline const Mat4 &getMatProj() const { return _matProj; } + inline const Mat4 &getMatProjInv() const { return _matProjInv; } + inline const Mat4 &getMatViewProj() const { return _matViewProj; } + inline const Mat4 &getMatViewProjInv() const { return _matViewProjInv; } inline void setFrustum(const geometry::Frustum &val) { *_frustum = val; } inline const geometry::Frustum &getFrustum() const { return *_frustum; } - inline void setWindow(RenderWindow *val) { _window = val; } + inline void setWindow(RenderWindow *val) { _window = val; } inline RenderWindow *getWindow() const { return _window; } - inline void setForward(const Vec3 &val) { _forward = val; } + inline void setForward(const Vec3 &val) { _forward = val; } inline const Vec3 &getForward() const { return _forward; } - inline void setPosition(const Vec3 &val) { _position = val; } + inline void setPosition(const Vec3 &val) { _position = val; } inline const Vec3 &getPosition() const { return _position; } - inline void setVisibility(uint32_t vis) { _visibility = vis; } + inline void setVisibility(uint32_t vis) { _visibility = vis; } inline uint32_t getVisibility() const { return _visibility; } inline uint32_t getPriority() const { return _priority; } - inline void setPriority(uint32_t val) { _priority = val; } + inline void setPriority(uint32_t val) { _priority = val; } inline void setAperture(CameraAperture val) { - _aperture = val; + _aperture = val; _apertureValue = Camera::FSTOPS[static_cast(_aperture)]; updateExposure(); } @@ -273,7 +273,7 @@ public: inline float getApertureValue() const { return _apertureValue; } inline void setShutter(CameraShutter val) { - _shutter = val; + _shutter = val; _shutterValue = Camera::SHUTTERS[static_cast(_shutter)]; updateExposure(); } @@ -282,7 +282,7 @@ public: inline float getShutterValue() const { return _shutterValue; } inline void setIso(CameraISO val) { - _iso = val; + _iso = val; _isoValue = Camera::ISOS[static_cast(_iso)]; updateExposure(); } @@ -290,25 +290,25 @@ public: inline float getIsoValue() const { return _isoValue; } - inline void setEc(float val) { _ec = val; } + inline void setEc(float val) { _ec = val; } inline float getEc() const { return _ec; } inline float getExposure() const { return _exposure; } inline gfx::ClearFlagBit getClearFlag() const { return _clearFlag; } - inline void setClearFlag(gfx::ClearFlagBit flag) { _clearFlag = flag; } + inline void setClearFlag(gfx::ClearFlagBit flag) { _clearFlag = flag; } inline float getClearDepth() const { return _clearDepth; } - inline void setClearDepth(float depth) { _clearDepth = depth; } + inline void setClearDepth(float depth) { _clearDepth = depth; } inline uint32_t getClearStencil() const { return _clearStencil; } - inline void setClearStencil(uint32_t stencil) { _clearStencil = stencil; } + inline void setClearStencil(uint32_t stencil) { _clearStencil = stencil; } inline bool isWindowSize() const { return _isWindowSize; } inline void setWindowSize(bool val) { _isWindowSize = val; } inline float getScreenScale() const { return _screenScale; } - inline void setScreenScale(float val) { _screenScale = val; } + inline void setScreenScale(float val) { _screenScale = val; } inline gfx::SurfaceTransform getSurfaceTransform() const { return _curTransform; } @@ -323,46 +323,46 @@ private: void updateExposure(); void updateAspect(bool oriented = true); - bool _isWindowSize{true}; - float _screenScale{0.F}; - gfx::Device * _device{nullptr}; - RenderScene * _scene{nullptr}; - IntrusivePtr _node; - ccstd::string _name; - bool _enabled{false}; - CameraProjection _proj{CameraProjection::UNKNOWN}; - float _aspect{0.F}; - float _orthoHeight{10.0F}; - CameraFOVAxis _fovAxis{CameraFOVAxis::VERTICAL}; - float _fov{static_cast(mathutils::toRadian(45.F))}; - float _nearClip{1.0F}; - float _farClip{1000.0F}; - gfx::Color _clearColor{0.2, 0.2, 0.2, 1}; - Vec4 _viewport{0, 0, 1, 1}; - Vec4 _orientedViewport{0, 0, 1, 1}; + bool _isWindowSize{true}; + float _screenScale{0.F}; + gfx::Device *_device{nullptr}; + RenderScene *_scene{nullptr}; + IntrusivePtr _node; + ccstd::string _name; + bool _enabled{false}; + CameraProjection _proj{CameraProjection::UNKNOWN}; + float _aspect{0.F}; + float _orthoHeight{10.0F}; + CameraFOVAxis _fovAxis{CameraFOVAxis::VERTICAL}; + float _fov{static_cast(mathutils::toRadian(45.F))}; + float _nearClip{1.0F}; + float _farClip{1000.0F}; + gfx::Color _clearColor{0.2, 0.2, 0.2, 1}; + Vec4 _viewport{0, 0, 1, 1}; + Vec4 _orientedViewport{0, 0, 1, 1}; gfx::SurfaceTransform _curTransform{gfx::SurfaceTransform::IDENTITY}; - bool _isProjDirty{true}; - Mat4 _matView; - Mat4 _matProj; - Mat4 _matProjInv; - Mat4 _matViewProj; - Mat4 _matViewProjInv; - geometry::Frustum * _frustum{nullptr}; - Vec3 _forward; - Vec3 _position; - uint32_t _priority{0}; - CameraAperture _aperture{CameraAperture::F16_0}; - float _apertureValue{0.F}; - CameraShutter _shutter{CameraShutter::D125}; - float _shutterValue{0.F}; - CameraISO _iso{CameraISO::ISO100}; - float _isoValue{0.F}; - float _ec = {0.F}; - RenderWindow * _window{nullptr}; - uint32_t _width{0}; - uint32_t _height{0}; - gfx::ClearFlagBit _clearFlag{gfx::ClearFlagBit::NONE}; - float _clearDepth{1.0F}; + bool _isProjDirty{true}; + Mat4 _matView; + Mat4 _matProj; + Mat4 _matProjInv; + Mat4 _matViewProj; + Mat4 _matViewProjInv; + geometry::Frustum *_frustum{nullptr}; + Vec3 _forward; + Vec3 _position; + uint32_t _priority{0}; + CameraAperture _aperture{CameraAperture::F16_0}; + float _apertureValue{0.F}; + CameraShutter _shutter{CameraShutter::D125}; + float _shutterValue{0.F}; + CameraISO _iso{CameraISO::ISO100}; + float _isoValue{0.F}; + float _ec = {0.F}; + RenderWindow *_window{nullptr}; + uint32_t _width{0}; + uint32_t _height{0}; + gfx::ClearFlagBit _clearFlag{gfx::ClearFlagBit::NONE}; + float _clearDepth{1.0F}; IntrusivePtr _geometryRenderer; @@ -371,7 +371,7 @@ private: static const ccstd::vector ISOS; uint32_t _visibility = pipeline::CAMERA_DEFAULT_MASK; - float _exposure{0.F}; + float _exposure{0.F}; uint32_t _clearStencil{0}; CC_DISALLOW_COPY_MOVE_ASSIGN(Camera); diff --git a/native/cocos/scene/Define.h b/native/cocos/scene/Define.h index be3e6999c5..84504802e9 100644 --- a/native/cocos/scene/Define.h +++ b/native/cocos/scene/Define.h @@ -33,7 +33,7 @@ namespace scene { struct IMacroPatch { ccstd::string name; - MacroValue value; + MacroValue value; }; } // namespace scene diff --git a/native/cocos/scene/DirectionalLight.h b/native/cocos/scene/DirectionalLight.h index 79cbec3ecf..5f78bc55d2 100644 --- a/native/cocos/scene/DirectionalLight.h +++ b/native/cocos/scene/DirectionalLight.h @@ -52,31 +52,31 @@ public: inline void setShadowFar(float farValue) { _shadowFar = farValue; } inline void setShadowOrthoSize(float orthoSize) { _shadowOrthoSize = orthoSize; } - inline bool isShadowEnabled() const { return _shadowEnabled; } + inline bool isShadowEnabled() const { return _shadowEnabled; } inline float getShadowPcf() const { return _shadowPcf; } inline float getShadowBias() const { return _shadowBias; } inline float getShadowNormalBias() const { return _shadowNormalBias; } inline float getShadowSaturation() const { return _shadowSaturation; } inline float getShadowDistance() const { return _shadowDistance; } inline float getShadowInvisibleOcclusionRange() const { return _shadowInvisibleOcclusionRange; } - inline bool isShadowFixedArea() const { return _shadowFixedArea; } + inline bool isShadowFixedArea() const { return _shadowFixedArea; } inline float getShadowNear() const { return _shadowNear; } inline float getShadowFar() const { return _shadowFar; } inline float getShadowOrthoSize() const { return _shadowOrthoSize; } inline const Vec3 &getDirection() const { return _dir; } - inline void setDirection(const Vec3 &dir) { _dir = dir; } - inline void setIlluminanceHDR(float value) { _illuminanceHDR = value; } - inline void setIlluminanceLDR(float value) { _illuminanceLDR = value; } - inline float getIlluminanceHDR() const { return _illuminanceHDR; } - inline float getIlluminanceLDR() const { return _illuminanceLDR; } - float getIlluminance() const; - void setIlluminance(float value); + inline void setDirection(const Vec3 &dir) { _dir = dir; } + inline void setIlluminanceHDR(float value) { _illuminanceHDR = value; } + inline void setIlluminanceLDR(float value) { _illuminanceLDR = value; } + inline float getIlluminanceHDR() const { return _illuminanceHDR; } + inline float getIlluminanceLDR() const { return _illuminanceLDR; } + float getIlluminance() const; + void setIlluminance(float value); private: float _illuminanceHDR{Ambient::SUN_ILLUM}; float _illuminanceLDR{1.F}; - Vec3 _dir{1.0F, -1.0F, -1.0F}; + Vec3 _dir{1.0F, -1.0F, -1.0F}; // shadow info bool _shadowEnabled{false}; @@ -87,7 +87,7 @@ private: float _shadowSaturation{0.75F}; float _shadowDistance{100.0F}; float _shadowInvisibleOcclusionRange{200.0F}; - bool _shadowFixedArea{false}; + bool _shadowFixedArea{false}; float _shadowNear{0.1F}; float _shadowFar{10.0F}; float _shadowOrthoSize{1.0F}; diff --git a/native/cocos/scene/DrawBatch2D.h b/native/cocos/scene/DrawBatch2D.h index 6f5d41f778..1c0a166f6a 100644 --- a/native/cocos/scene/DrawBatch2D.h +++ b/native/cocos/scene/DrawBatch2D.h @@ -33,10 +33,10 @@ namespace scene { class Pass; struct DrawBatch2D final { - uint32_t visFlags{0}; - gfx::DescriptorSet * descriptorSet{nullptr}; - gfx::InputAssembler * inputAssembler{nullptr}; - ccstd::vector passes; + uint32_t visFlags{0}; + gfx::DescriptorSet *descriptorSet{nullptr}; + gfx::InputAssembler *inputAssembler{nullptr}; + ccstd::vector passes; ccstd::vector shaders; }; diff --git a/native/cocos/scene/Fog.cpp b/native/cocos/scene/Fog.cpp index ae11abdd9b..48f0beb532 100644 --- a/native/cocos/scene/Fog.cpp +++ b/native/cocos/scene/Fog.cpp @@ -109,29 +109,29 @@ void FogInfo::activate(Fog *resource) { // void Fog::initialize(const FogInfo &fogInfo) { setFogColor(fogInfo.getFogColor()); - _enabled = fogInfo.isEnabled(); - _accurate = fogInfo.isAccurate(); - _type = _enabled ? fogInfo.getType() : FogType::NONE; + _enabled = fogInfo.isEnabled(); + _accurate = fogInfo.isAccurate(); + _type = _enabled ? fogInfo.getType() : FogType::NONE; _fogDensity = fogInfo.getFogDensity(); - _fogStart = fogInfo.getFogStart(); - _fogEnd = fogInfo.getFogEnd(); - _fogAtten = fogInfo.getFogAtten(); - _fogTop = fogInfo.getFogTop(); - _fogRange = fogInfo.getFogRange(); + _fogStart = fogInfo.getFogStart(); + _fogEnd = fogInfo.getFogEnd(); + _fogAtten = fogInfo.getFogAtten(); + _fogTop = fogInfo.getFogTop(); + _fogRange = fogInfo.getFogRange(); } void Fog::updatePipeline() { - auto * root = Root::getInstance(); - const FogType value = _enabled ? _type : FogType::NONE; - const int32_t accurateValue = isAccurate() ? 1 : 0; - auto * pipeline = root->getPipeline(); - auto iterMacroFog = pipeline->getMacros().find("CC_USE_FOG"); - auto iterMacroAccurateFog = pipeline->getMacros().find("CC_USE_ACCURATE_FOG"); + auto *root = Root::getInstance(); + const FogType value = _enabled ? _type : FogType::NONE; + const int32_t accurateValue = isAccurate() ? 1 : 0; + auto *pipeline = root->getPipeline(); + auto iterMacroFog = pipeline->getMacros().find("CC_USE_FOG"); + auto iterMacroAccurateFog = pipeline->getMacros().find("CC_USE_ACCURATE_FOG"); if (iterMacroFog != pipeline->getMacros().end() && iterMacroAccurateFog != pipeline->getMacros().end()) { - const MacroValue ¯oFog = iterMacroFog->second; - const MacroValue ¯oAccurateFog = iterMacroAccurateFog->second; - const int32_t * macroFogPtr = cc::get_if(¯oFog); - const int32_t * macroAccurateFogPtr = cc::get_if(¯oAccurateFog); + const MacroValue ¯oFog = iterMacroFog->second; + const MacroValue ¯oAccurateFog = iterMacroAccurateFog->second; + const int32_t *macroFogPtr = cc::get_if(¯oFog); + const int32_t *macroAccurateFogPtr = cc::get_if(¯oAccurateFog); if (macroFogPtr != nullptr && *macroFogPtr == static_cast(value) && macroAccurateFogPtr != nullptr && *macroAccurateFogPtr == accurateValue) return; } diff --git a/native/cocos/scene/Fog.h b/native/cocos/scene/Fog.h index 37343f354e..3247af53ab 100644 --- a/native/cocos/scene/Fog.h +++ b/native/cocos/scene/Fog.h @@ -66,14 +66,14 @@ enum class FogType { * @readonly */ LAYERED = 3, - NONE = 4 + NONE = 4 }; class FogInfo; class Fog final { public: - Fog() = default; + Fog() = default; ~Fog() = default; void initialize(const FogInfo &fogInfo); @@ -109,7 +109,7 @@ public: * @zh 全局雾颜色 * @en Global fog color */ - void setFogColor(const Color &val); + void setFogColor(const Color &val); inline const Color &getFogColor() const { return _fogColor; } /** @@ -124,7 +124,7 @@ public: * - 3:Layered fog */ inline FogType getType() const { return _type; } - inline void setType(FogType val) { + inline void setType(FogType val) { _type = _enabled ? val : FogType::NONE; if (_enabled) { updatePipeline(); @@ -136,28 +136,28 @@ public: * @en Global fog density */ inline float getFogDensity() const { return _fogDensity; } - inline void setFogDensity(float val) { _fogDensity = val; } + inline void setFogDensity(float val) { _fogDensity = val; } /** * @zh 雾效起始位置,只适用于线性雾 * @en Global fog start position, only for linear fog */ inline float getFogStart() const { return _fogStart; } - inline void setFogStart(float val) { _fogStart = val; } + inline void setFogStart(float val) { _fogStart = val; } /** * @zh 雾效结束位置,只适用于线性雾 * @en Global fog end position, only for linear fog */ float getFogEnd() const { return _fogEnd; } - void setFogEnd(float val) { _fogEnd = val; } + void setFogEnd(float val) { _fogEnd = val; } /** * @zh 雾效衰减 * @en Global fog attenuation */ inline float getFogAtten() const { return _fogAtten; } - inline void setFogAtten(float val) { _fogAtten = val; } + inline void setFogAtten(float val) { _fogAtten = val; } /** * @zh 雾效顶部范围,只适用于层级雾 @@ -172,37 +172,37 @@ public: * @en Global fog range, only for layered fog */ inline float getFogRange() const { return _fogRange; } - inline void setfogRange(float val) { _fogRange = val; } + inline void setfogRange(float val) { _fogRange = val; } const Vec4 &getColorArray() const { return _colorArray; } private: void updatePipeline(); - Color _fogColor{200, 200, 200, 255}; - Vec4 _colorArray{0.2F, 0.2F, 0.2F, 1.0F}; - bool _enabled{false}; - bool _accurate{false}; + Color _fogColor{200, 200, 200, 255}; + Vec4 _colorArray{0.2F, 0.2F, 0.2F, 1.0F}; + bool _enabled{false}; + bool _accurate{false}; FogType _type{FogType::LINEAR}; - float _fogDensity{0.3F}; - float _fogStart{0.5F}; - float _fogEnd{300.F}; - float _fogAtten{5.F}; - float _fogTop{1.5F}; - float _fogRange{1.2F}; + float _fogDensity{0.3F}; + float _fogStart{0.5F}; + float _fogEnd{300.F}; + float _fogAtten{5.F}; + float _fogTop{1.5F}; + float _fogRange{1.2F}; CC_DISALLOW_COPY_MOVE_ASSIGN(Fog); }; class FogInfo : public RefCounted { public: - FogInfo() = default; + FogInfo() = default; ~FogInfo() override = default; /** * @zh 是否启用全局雾效 * @en Enable global fog */ - void setEnabled(bool val) const; + void setEnabled(bool val) const; inline bool isEnabled() const { return _isEnabled; } /** @@ -229,7 +229,7 @@ public: */ // @editable // @tooltip('i18n:fog.fogColor') - void setFogColor(const Color &val); + void setFogColor(const Color &val); inline const Color &getFogColor() const { return _fogColor; } /** @@ -239,7 +239,7 @@ public: // @editable // @type(FogType) // @tooltip('i18n:fog.type') - void setType(FogType val); + void setType(FogType val); inline FogType getType() const { return _type; } /** @@ -255,7 +255,7 @@ public: // @slide // @displayOrder(3) // @tooltip('i18n:fog.fogDensity') - void setFogDensity(float val); + void setFogDensity(float val); inline float getFogDensity() const { return _fogDensity; } // /** @@ -267,7 +267,7 @@ public: // @rangeStep(0.01) // @displayOrder(4) // @tooltip('i18n:fog.fogStart') - void setFogStart(float val); + void setFogStart(float val); inline float getFogStart() const { return _fogStart; } // /** @@ -279,7 +279,7 @@ public: // @rangeStep(0.01) // @displayOrder(5) // @tooltip('i18n:fog.fogEnd') - void setFogEnd(float val); + void setFogEnd(float val); inline float getFogEnd() const { return _fogEnd; } /** @@ -292,7 +292,7 @@ public: // @rangeStep(0.01) // @displayOrder(6) // @tooltip('i18n:fog.fogAtten') - void setFogAtten(float val); + void setFogAtten(float val); inline float getFogAtten() const { return _fogAtten; } /** @@ -304,7 +304,7 @@ public: // @rangeStep(0.01) // @displayOrder(7) // @tooltip('i18n:fog.fogTop') - void setFogTop(float val); + void setFogTop(float val); inline float getFogTop() const { return _fogTop; } /** @@ -316,7 +316,7 @@ public: // @rangeStep(0.01) // @displayOrder(8) // @tooltip('i18n:fog.fogRange') - void setFogRange(float val); + void setFogRange(float val); inline float getFogRange() const { return _fogRange; } void activate(Fog *resource); diff --git a/native/cocos/scene/Light.h b/native/cocos/scene/Light.h index 2dae3ca2d1..d94fe53d9d 100644 --- a/native/cocos/scene/Light.h +++ b/native/cocos/scene/Light.h @@ -54,7 +54,7 @@ public: void destroy(); virtual void initialize() { - _color = Vec3(1, 1, 1); + _color = Vec3(1, 1, 1); _colorTemp = 6550.F; } @@ -64,41 +64,41 @@ public: inline void setBaked(bool val) { _baked = val; } inline const Vec3 &getColor() const { return _color; } - inline void setColor(const Vec3 &color) { _color = color; } + inline void setColor(const Vec3 &color) { _color = color; } inline bool isUseColorTemperature() const { return _useColorTemperature; } inline void setUseColorTemperature(bool value) { _useColorTemperature = value; } inline float getColorTemperature() const { return _colorTemp; } - inline void setColorTemperature(float val) { _colorTemp = val; } + inline void setColorTemperature(float val) { _colorTemp = val; } inline Node *getNode() const { return _node.get(); } - void setNode(Node *node); + void setNode(Node *node); inline LightType getType() const { return _type; } - inline void setType(LightType type) { _type = type; } + inline void setType(LightType type) { _type = type; } inline const ccstd::string &getName() const { return _name; } - inline void setName(const ccstd::string &name) { _name = name; } + inline void setName(const ccstd::string &name) { _name = name; } inline RenderScene *getScene() const { return _scene; } inline const Vec3 &getColorTemperatureRGB() const { return _colorTemperatureRGB; } - inline void setColorTemperatureRGB(const Vec3 &value) { _colorTemperatureRGB = value; } + inline void setColorTemperatureRGB(const Vec3 &value) { _colorTemperatureRGB = value; } static float nt2lm(float size); protected: - bool _useColorTemperature{false}; - bool _baked{false}; + bool _useColorTemperature{false}; + bool _baked{false}; IntrusivePtr _node; - float _colorTemp{6550.F}; - LightType _type{LightType::UNKNOWN}; - ccstd::string _name; - RenderScene * _scene{nullptr}; - Vec3 _color{1, 1, 1}; - Vec3 _colorTemperatureRGB; - Vec3 _forward{0, 0, -1}; + float _colorTemp{6550.F}; + LightType _type{LightType::UNKNOWN}; + ccstd::string _name; + RenderScene *_scene{nullptr}; + Vec3 _color{1, 1, 1}; + Vec3 _colorTemperatureRGB; + Vec3 _forward{0, 0, -1}; private: CC_DISALLOW_COPY_MOVE_ASSIGN(Light); diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index 238c5291bd..8a2cf4ead2 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -106,7 +106,7 @@ const cc::gfx::SamplerInfo LIGHTMAP_SAMPLER_WITH_MIP_HASH{ }; const ccstd::vector SHADOW_MAP_PATCHES{{"CC_RECEIVE_SHADOW", true}}; -const ccstd::string INST_MAT_WORLD = "a_matWorld0"; +const ccstd::string INST_MAT_WORLD = "a_matWorld0"; } // namespace namespace cc { @@ -121,10 +121,10 @@ Model::~Model() = default; void Model::initialize() { if (_inited) return; _receiveShadow = true; - _castShadow = false; - _enabled = true; - _visFlags = Layers::Enum::NONE; - _inited = true; + _castShadow = false; + _enabled = true; + _visFlags = Layers::Enum::NONE; + _inited = true; _localData.reset(pipeline::UBOLocal::COUNT); } @@ -137,18 +137,18 @@ void Model::destroy() { CC_SAFE_DESTROY_NULL(_localBuffer); CC_SAFE_DESTROY_NULL(_worldBoundBuffer); - _worldBounds = nullptr; - _modelBounds = nullptr; - _inited = false; - _localDataUpdated = true; - _transform = nullptr; - _node = nullptr; + _worldBounds = nullptr; + _modelBounds = nullptr; + _inited = false; + _localDataUpdated = true; + _transform = nullptr; + _node = nullptr; _isDynamicBatching = false; } void Model::uploadMat4AsVec4x3(const Mat4 &mat, Float32Array &v1, Float32Array &v2, Float32Array &v3) { uint32_t copyBytes = sizeof(float) * 3; - auto * buffer = const_cast(v1.buffer()->getData()); + auto *buffer = const_cast(v1.buffer()->getData()); uint8_t *dst = buffer + v1.byteOffset(); memcpy(dst, mat.m, copyBytes); @@ -208,7 +208,7 @@ void Model::updateWorldBoundsForJSSkinningModel(const Vec3 &min, const Vec3 &max } void Model::updateWorldBoundsForJSBakedSkinningModel(geometry::AABB *aabb) { - _worldBounds->center = aabb->center; + _worldBounds->center = aabb->center; _worldBounds->halfExtents = aabb->halfExtents; } @@ -232,8 +232,8 @@ void Model::updateUBOs(uint32_t stamp) { _localDataUpdated = false; getTransform()->updateWorldTransform(); const auto &worldMatrix = getTransform()->getWorldMatrix(); - Mat4 mat4; - int idx = _instMatWorldIdx; + Mat4 mat4; + int idx = _instMatWorldIdx; if (idx >= 0) { ccstd::vector &attrs = getInstancedAttributeBlock()->views; uploadMat4AsVec4x3(worldMatrix, cc::get(attrs[idx]), cc::get(attrs[idx + 1]), cc::get(attrs[idx + 2])); @@ -253,10 +253,10 @@ void Model::updateUBOs(uint32_t stamp) { void Model::updateWorldBoundUBOs() { if (_worldBoundBuffer) { ccstd::array worldBoundBufferView; - const Vec3 & center = _worldBounds ? _worldBounds->getCenter() : Vec3{0.0F, 0.0F, 0.0F}; - const Vec3 & halfExtents = _worldBounds ? _worldBounds->getHalfExtents() : Vec3{1.0F, 1.0F, 1.0F}; - const Vec4 worldBoundCenter{center.x, center.y, center.z, 0.0F}; - const Vec4 worldBoundHalfExtents{halfExtents.x, halfExtents.y, halfExtents.z, 1.0F}; + const Vec3 ¢er = _worldBounds ? _worldBounds->getCenter() : Vec3{0.0F, 0.0F, 0.0F}; + const Vec3 &halfExtents = _worldBounds ? _worldBounds->getHalfExtents() : Vec3{1.0F, 1.0F, 1.0F}; + const Vec4 worldBoundCenter{center.x, center.y, center.z, 0.0F}; + const Vec4 worldBoundHalfExtents{halfExtents.x, halfExtents.y, halfExtents.z, 1.0F}; memcpy(worldBoundBufferView.data() + pipeline::UBOWorldBound::WORLD_BOUND_CENTER, &worldBoundCenter.x, sizeof(Vec4)); memcpy(worldBoundBufferView.data() + pipeline::UBOWorldBound::WORLD_BOUND_HALF_EXTENTS, &worldBoundHalfExtents.x, sizeof(Vec4)); _worldBoundBuffer->update(worldBoundBufferView.data(), pipeline::UBOWorldBound::SIZE); @@ -292,7 +292,7 @@ void Model::initSubModel(index_t idx, cc::RenderingSubMesh *subMeshData, Materia if (_subModels[idx] == nullptr) { _subModels[idx] = createSubModel(); - isNewSubModel = true; + isNewSubModel = true; } else { CC_SAFE_DESTROY(_subModels[idx]); } @@ -337,8 +337,8 @@ void Model::onGeometryChanged() { void Model::updateLightingmap(Texture2D *texture, const Vec4 &uvParam) { vec4ToFloat32Array(uvParam, _localData, pipeline::UBOLocal::LIGHTINGMAP_UVPARAM); //TODO(xwx): toArray not implemented in Math _localDataUpdated = true; - _lightmap = texture; - _lightmapUVParam = uvParam; + _lightmap = texture; + _lightmapUVParam = uvParam; if (texture == nullptr) { texture = BuiltinResMgr::getInstance()->get(ccstd::string("empty-texture")); @@ -414,7 +414,7 @@ void Model::updateInstancedAttributes(const ccstd::vector &attri if (!attribute.isInstanced) continue; size += gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)].size; } - auto &attrs = _instanceAttributeBlock; + auto &attrs = _instanceAttributeBlock; attrs.buffer = Uint8Array(size); attrs.views.clear(); attrs.attributes.clear(); @@ -423,14 +423,14 @@ void Model::updateInstancedAttributes(const ccstd::vector &attri for (const gfx::Attribute &attribute : attributes) { if (!attribute.isInstanced) continue; gfx::Attribute attr; - attr.format = attribute.format; - attr.name = attribute.name; + attr.format = attribute.format; + attr.name = attribute.name; attr.isNormalized = attribute.isNormalized; - attr.location = attribute.location; + attr.location = attribute.location; attrs.attributes.emplace_back(attr); - const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; - auto * buffer = attrs.buffer.buffer(); - auto typeViewArray = getTypedArrayConstructor(info, buffer, offset, info.count); + const auto &info = gfx::GFX_FORMAT_INFOS[static_cast(attribute.format)]; + auto *buffer = attrs.buffer.buffer(); + auto typeViewArray = getTypedArrayConstructor(info, buffer, offset, info.count); attrs.views.emplace_back(typeViewArray); offset += info.size; } @@ -499,7 +499,7 @@ void Model::updateLocalShadowBias() { _localData[pipeline::UBOLocal::LOCAL_SHADOW_BIAS + 1] = _shadowNormalBias; _localData[pipeline::UBOLocal::LOCAL_SHADOW_BIAS + 2] = 0; _localData[pipeline::UBOLocal::LOCAL_SHADOW_BIAS + 3] = 0; - _localDataUpdated = true; + _localDataUpdated = true; } } // namespace scene diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 67f86879af..c0d04df793 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -56,8 +56,8 @@ class Octree; class Pass; struct IMacroPatch; struct InstancedAttributeBlock { - Uint8Array buffer; - ccstd::vector views; + Uint8Array buffer; + ccstd::vector views; ccstd::vector attributes; }; @@ -77,29 +77,29 @@ public: Model(); ~Model() override; - void initialize(); - virtual void destroy(); - void updateWorldBound(); - void updateWorldBoundsForJSSkinningModel(const Vec3 &min, const Vec3 &max); - void updateWorldBoundsForJSBakedSkinningModel(geometry::AABB *aabb); - void createBoundingShape(const cc::optional &minPos, const cc::optional &maxPos); - virtual void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat); - void setSubModelMesh(index_t idx, RenderingSubMesh *subMesh) const; - virtual void setSubModelMaterial(index_t idx, Material *mat); - void onGlobalPipelineStateChanged() const; - void onMacroPatchesStateChanged(); - void onGeometryChanged(); - void updateLightingmap(Texture2D *texture, const Vec4 &uvParam); + void initialize(); + virtual void destroy(); + void updateWorldBound(); + void updateWorldBoundsForJSSkinningModel(const Vec3 &min, const Vec3 &max); + void updateWorldBoundsForJSBakedSkinningModel(geometry::AABB *aabb); + void createBoundingShape(const cc::optional &minPos, const cc::optional &maxPos); + virtual void initSubModel(index_t idx, RenderingSubMesh *subMeshData, Material *mat); + void setSubModelMesh(index_t idx, RenderingSubMesh *subMesh) const; + virtual void setSubModelMaterial(index_t idx, Material *mat); + void onGlobalPipelineStateChanged() const; + void onMacroPatchesStateChanged(); + void onGeometryChanged(); + void updateLightingmap(Texture2D *texture, const Vec4 &uvParam); virtual ccstd::vector getMacroPatches(index_t subModelIndex); - virtual void updateInstancedAttributes(const ccstd::vector &attributes, Pass *pass); + virtual void updateInstancedAttributes(const ccstd::vector &attributes, Pass *pass); virtual void updateTransform(uint32_t stamp); virtual void updateUBOs(uint32_t stamp); - void updateWorldBoundUBOs(); - void updateLocalShadowBias(); + void updateWorldBoundUBOs(); + void updateLocalShadowBias(); inline void attachToScene(RenderScene *scene) { - _scene = scene; + _scene = scene; _localDataUpdated = true; }; inline void detachFromScene() { _scene = nullptr; }; @@ -124,7 +124,7 @@ public: } inline void setInstancedAttributeBlock(const InstancedAttributeBlock &val) { _instanceAttributeBlock = val; - _localDataUpdated = true; + _localDataUpdated = true; } inline void setOctreeNode(OctreeNode *node) { _octreeNode = node; } inline void setScene(RenderScene *scene) { @@ -132,35 +132,35 @@ public: if (scene) _localDataUpdated = true; } - inline bool isInited() const { return _inited; }; - inline bool isCastShadow() const { return _castShadow; } - inline bool isEnabled() const { return _enabled; } - inline bool isInstancingEnabled() const { return _instMatWorldIdx >= 0; }; - inline int32_t getInstMatWorldIdx() const { return _instMatWorldIdx; } - inline const ccstd::vector & getInstanceAttributes() const { return _instanceAttributeBlock.attributes; } - inline InstancedAttributeBlock * getInstancedAttributeBlock() { return &_instanceAttributeBlock; } - inline const uint8_t * getInstancedBuffer() const { return _instanceAttributeBlock.buffer.buffer()->getData(); } - inline uint32_t getInstancedBufferSize() const { return _instanceAttributeBlock.buffer.length(); } - inline gfx::Buffer * getLocalBuffer() const { return _localBuffer.get(); } - inline gfx::Buffer * getWorldBoundBuffer() const { return _worldBoundBuffer.get(); } - inline Float32Array getLocalData() const { return _localData; } - inline geometry::AABB * getModelBounds() const { return _modelBounds; } - inline Node * getNode() const { return _node.get(); } - inline bool isReceiveShadow() const { return _receiveShadow; } + inline bool isInited() const { return _inited; }; + inline bool isCastShadow() const { return _castShadow; } + inline bool isEnabled() const { return _enabled; } + inline bool isInstancingEnabled() const { return _instMatWorldIdx >= 0; }; + inline int32_t getInstMatWorldIdx() const { return _instMatWorldIdx; } + inline const ccstd::vector &getInstanceAttributes() const { return _instanceAttributeBlock.attributes; } + inline InstancedAttributeBlock *getInstancedAttributeBlock() { return &_instanceAttributeBlock; } + inline const uint8_t *getInstancedBuffer() const { return _instanceAttributeBlock.buffer.buffer()->getData(); } + inline uint32_t getInstancedBufferSize() const { return _instanceAttributeBlock.buffer.length(); } + inline gfx::Buffer *getLocalBuffer() const { return _localBuffer.get(); } + inline gfx::Buffer *getWorldBoundBuffer() const { return _worldBoundBuffer.get(); } + inline Float32Array getLocalData() const { return _localData; } + inline geometry::AABB *getModelBounds() const { return _modelBounds; } + inline Node *getNode() const { return _node.get(); } + inline bool isReceiveShadow() const { return _receiveShadow; } inline const ccstd::vector> &getSubModels() const { return _subModels; } - inline Node * getTransform() const { return _transform.get(); } - inline bool isLocalDataUpdated() const { return _localDataUpdated; } - inline uint32_t getUpdateStamp() const { return _updateStamp; } - inline Layers::Enum getVisFlags() const { return _visFlags; } - inline geometry::AABB * getWorldBounds() const { return _worldBounds; } - inline Type getType() const { return _type; }; - inline void setType(Type type) { _type = type; } - inline OctreeNode * getOctreeNode() const { return _octreeNode; } - inline RenderScene * getScene() const { return _scene; } - inline void setDynamicBatching(bool val) { _isDynamicBatching = val; } - inline bool isDynamicBatching() const { return _isDynamicBatching; } - inline float getShadowBias() const { return _shadowBias; } - inline float getShadowNormalBias() const { return _shadowNormalBias; } + inline Node *getTransform() const { return _transform.get(); } + inline bool isLocalDataUpdated() const { return _localDataUpdated; } + inline uint32_t getUpdateStamp() const { return _updateStamp; } + inline Layers::Enum getVisFlags() const { return _visFlags; } + inline geometry::AABB *getWorldBounds() const { return _worldBounds; } + inline Type getType() const { return _type; }; + inline void setType(Type type) { _type = type; } + inline OctreeNode *getOctreeNode() const { return _octreeNode; } + inline RenderScene *getScene() const { return _scene; } + inline void setDynamicBatching(bool val) { _isDynamicBatching = val; } + inline bool isDynamicBatching() const { return _isDynamicBatching; } + inline float getShadowBias() const { return _shadowBias; } + inline float getShadowNormalBias() const { return _shadowNormalBias; } void initLocalDescriptors(index_t subModelIndex); void initWorldBoundDescriptors(index_t subModelIndex); @@ -171,13 +171,13 @@ public: int32_t getInstancedAttributeIndex(const ccstd::string &name) const; // For JS - inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } + inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } inline CallbacksInvoker &getEventProcessor() { return _eventProcessor; } - void setInstancedAttributesViewData(index_t viewIdx, index_t arrIdx, float value); - inline void setLocalDataUpdated(bool v) { _localDataUpdated = v; } - inline void setWorldBounds(geometry::AABB *bounds) { _worldBounds = bounds; } - inline void setModelBounds(geometry::AABB *bounds) { _modelBounds = bounds; } - inline bool isModelImplementedInJS() const { return (_type != Type::DEFAULT && _type != Type::SKINNING && _type != Type::BAKED_SKINNING); }; + void setInstancedAttributesViewData(index_t viewIdx, index_t arrIdx, float value); + inline void setLocalDataUpdated(bool v) { _localDataUpdated = v; } + inline void setWorldBounds(geometry::AABB *bounds) { _worldBounds = bounds; } + inline void setModelBounds(geometry::AABB *bounds) { _modelBounds = bounds; } + inline bool isModelImplementedInJS() const { return (_type != Type::DEFAULT && _type != Type::SKINNING && _type != Type::BAKED_SKINNING); }; protected: static void uploadMat4AsVec4x3(const Mat4 &mat, Float32Array &v1, Float32Array &v2, Float32Array &v3); @@ -186,41 +186,41 @@ protected: static SubModel *createSubModel(); - Type _type{Type::DEFAULT}; - bool _localDataUpdated{false}; + Type _type{Type::DEFAULT}; + bool _localDataUpdated{false}; IntrusivePtr _worldBounds; IntrusivePtr _modelBounds; - OctreeNode * _octreeNode{nullptr}; - RenderScene * _scene{nullptr}; - gfx::Device * _device{nullptr}; - bool _inited{false}; - uint32_t _descriptorSetCount{1}; - float _shadowBias{0.0F}; - float _shadowNormalBias{0.0F}; + OctreeNode *_octreeNode{nullptr}; + RenderScene *_scene{nullptr}; + gfx::Device *_device{nullptr}; + bool _inited{false}; + uint32_t _descriptorSetCount{1}; + float _shadowBias{0.0F}; + float _shadowNormalBias{0.0F}; bool _enabled{false}; bool _castShadow{false}; bool _receiveShadow{false}; bool _isDynamicBatching{false}; - int32_t _instMatWorldIdx{-1}; - Layers::Enum _visFlags{Layers::Enum::NONE}; - uint32_t _updateStamp{0}; - IntrusivePtr _transform; - IntrusivePtr _node; - Float32Array _localData; - std::tuple _instancedBuffer{nullptr, 0}; - IntrusivePtr _localBuffer; - IntrusivePtr _worldBoundBuffer; - InstancedAttributeBlock _instanceAttributeBlock{}; + int32_t _instMatWorldIdx{-1}; + Layers::Enum _visFlags{Layers::Enum::NONE}; + uint32_t _updateStamp{0}; + IntrusivePtr _transform; + IntrusivePtr _node; + Float32Array _localData; + std::tuple _instancedBuffer{nullptr, 0}; + IntrusivePtr _localBuffer; + IntrusivePtr _worldBoundBuffer; + InstancedAttributeBlock _instanceAttributeBlock{}; ccstd::vector> _subModels; IntrusivePtr _lightmap; - Vec4 _lightmapUVParam; + Vec4 _lightmapUVParam; // For JS CallbacksInvoker _eventProcessor; - bool _isCalledFromJS{false}; + bool _isCalledFromJS{false}; // private: diff --git a/native/cocos/scene/Octree.cpp b/native/cocos/scene/Octree.cpp index a99fc60c66..80c014a400 100644 --- a/native/cocos/scene/Octree.cpp +++ b/native/cocos/scene/Octree.cpp @@ -98,8 +98,8 @@ OctreeNode::~OctreeNode() { } BBox OctreeNode::getChildBox(uint32_t index) const { - cc::Vec3 min = _aabb.min; - cc::Vec3 max = _aabb.max; + cc::Vec3 min = _aabb.min; + cc::Vec3 max = _aabb.max; const cc::Vec3 center = _aabb.getCenter(); if (index & 0x1) { @@ -125,7 +125,7 @@ BBox OctreeNode::getChildBox(uint32_t index) const { OctreeNode *OctreeNode::getOrCreateChild(uint32_t index) { if (!_children[index]) { - BBox childBox = getChildBox(index); + BBox childBox = getChildBox(index); auto *child = _children[index] = ccnew OctreeNode(_owner, this); child->setBox(childBox); child->setDepth(_depth + 1); @@ -145,9 +145,9 @@ void OctreeNode::deleteChild(uint32_t index) { void OctreeNode::insert(Model *model) { // NOLINT(misc-no-recursion) bool split = false; if (_depth < _owner->getMaxDepth() - 1) { - BBox modelBox(*model->getWorldBounds()); + BBox modelBox(*model->getWorldBounds()); const cc::Vec3 &modelCenter = modelBox.getCenter(); - const cc::Vec3 &nodeCenter = _aabb.getCenter(); + const cc::Vec3 &nodeCenter = _aabb.getCenter(); uint32_t index = modelCenter.x < nodeCenter.x ? 0 : 1; index += modelCenter.y < nodeCenter.y ? 0 : 2; @@ -308,8 +308,8 @@ Octree::~Octree() { void Octree::initialize(const OctreeInfo &info) { const Vec3 expand{OCTREE_BOX_EXPAND_SIZE, OCTREE_BOX_EXPAND_SIZE, OCTREE_BOX_EXPAND_SIZE}; - _minPos = info.getMinPos(); - _maxPos = info.getMaxPos(); + _minPos = info.getMinPos(); + _maxPos = info.getMaxPos(); _maxDepth = std::max(info.getDepth(), 1U); setEnabled(info.isEnabled()); _root->setBox(BBox{_minPos - expand, _maxPos}); @@ -338,7 +338,7 @@ void Octree::setMaxDepth(uint32_t val) { void Octree::resize(const Vec3 &minPos, const Vec3 &maxPos, uint32_t maxDepth) { const Vec3 expand{OCTREE_BOX_EXPAND_SIZE, OCTREE_BOX_EXPAND_SIZE, OCTREE_BOX_EXPAND_SIZE}; - BBox rootBox = _root->getBox(); + BBox rootBox = _root->getBox(); if ((minPos - expand) == rootBox.min && maxPos == rootBox.max && maxDepth == _maxDepth) { return; } @@ -403,15 +403,15 @@ void Octree::queryVisibility(Camera *camera, const geometry::Frustum &frustum, b } bool Octree::isInside(Model *model) const { - const BBox &rootBox = _root->getBox(); - BBox modelBox = BBox(*model->getWorldBounds()); + const BBox &rootBox = _root->getBox(); + BBox modelBox = BBox(*model->getWorldBounds()); return rootBox.contain(modelBox); } bool Octree::isOutside(Model *model) const { - const BBox &rootBox = _root->getBox(); - BBox modelBox = BBox(*model->getWorldBounds()); + const BBox &rootBox = _root->getBox(); + BBox modelBox = BBox(*model->getWorldBounds()); return !rootBox.intersect(modelBox); } diff --git a/native/cocos/scene/Octree.h b/native/cocos/scene/Octree.h index f2a8f2c08c..7184b81ca4 100644 --- a/native/cocos/scene/Octree.h +++ b/native/cocos/scene/Octree.h @@ -38,52 +38,52 @@ class Camera; class Model; class Octree; -constexpr int OCTREE_CHILDREN_NUM = 8; -constexpr int DEFAULT_OCTREE_DEPTH = 8; -const Vec3 DEFAULT_WORLD_MIN_POS = {-1024.0F, -1024.0F, -1024.0F}; -const Vec3 DEFAULT_WORLD_MAX_POS = {1024.0F, 1024.0F, 1024.0F}; -const float OCTREE_BOX_EXPAND_SIZE = 10.0F; -constexpr int USE_MULTI_THRESHOLD = 1024; // use parallel culling if greater than this value +constexpr int OCTREE_CHILDREN_NUM = 8; +constexpr int DEFAULT_OCTREE_DEPTH = 8; +const Vec3 DEFAULT_WORLD_MIN_POS = {-1024.0F, -1024.0F, -1024.0F}; +const Vec3 DEFAULT_WORLD_MAX_POS = {1024.0F, 1024.0F, 1024.0F}; +const float OCTREE_BOX_EXPAND_SIZE = 10.0F; +constexpr int USE_MULTI_THRESHOLD = 1024; // use parallel culling if greater than this value class CC_DLL OctreeInfo final : public RefCounted { public: - OctreeInfo() = default; + OctreeInfo() = default; ~OctreeInfo() override = default; /** * @en Whether activate octree * @zh 是否启用八叉树加速剔除? */ - void setEnabled(bool val); + void setEnabled(bool val); inline bool isEnabled() const { return _enabled; } /** * @en min pos of scene bounding box * @zh 场景包围盒最小值 */ - void setMinPos(const Vec3 &val); + void setMinPos(const Vec3 &val); inline const Vec3 &getMinPos() const { return _minPos; } /** * @en max pos of scene bounding box * @zh 场景包围盒最大值 */ - void setMaxPos(const Vec3 &val); + void setMaxPos(const Vec3 &val); inline const Vec3 &getMaxPos() const { return _maxPos; } /** * @en depth of octree * @zh 八叉树深度 */ - void setDepth(uint32_t val); + void setDepth(uint32_t val); inline uint32_t getDepth() const { return _depth; } void activate(Octree *resource); // JS deserialization require the properties to be public // private: - bool _enabled{false}; - Vec3 _minPos{DEFAULT_WORLD_MIN_POS}; - Vec3 _maxPos{DEFAULT_WORLD_MAX_POS}; + bool _enabled{false}; + Vec3 _minPos{DEFAULT_WORLD_MIN_POS}; + Vec3 _maxPos{DEFAULT_WORLD_MAX_POS}; uint32_t _depth{DEFAULT_OCTREE_DEPTH}; Octree *_resource{nullptr}; @@ -141,27 +141,27 @@ private: inline void setDepth(uint32_t depth) { _depth = depth; } inline void setIndex(uint32_t index) { _index = index; } - inline Octree * getOwner() const { return _owner; } + inline Octree *getOwner() const { return _owner; } inline const BBox &getBox() const { return _aabb; } - BBox getChildBox(uint32_t index) const; - OctreeNode * getOrCreateChild(uint32_t index); - void deleteChild(uint32_t index); - void insert(Model *model); - void add(Model *model); - void remove(Model *model); - void onRemoved(); - void gatherModels(ccstd::vector &results) const; - void doQueryVisibility(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; - void queryVisibilityParallelly(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; - void queryVisibilitySequentially(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; + BBox getChildBox(uint32_t index) const; + OctreeNode *getOrCreateChild(uint32_t index); + void deleteChild(uint32_t index); + void insert(Model *model); + void add(Model *model); + void remove(Model *model); + void onRemoved(); + void gatherModels(ccstd::vector &results) const; + void doQueryVisibility(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; + void queryVisibilityParallelly(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; + void queryVisibilitySequentially(const Camera *camera, const geometry::Frustum &frustum, bool isShadow, ccstd::vector &results) const; - Octree * _owner{nullptr}; - OctreeNode * _parent{nullptr}; + Octree *_owner{nullptr}; + OctreeNode *_parent{nullptr}; ccstd::array _children{}; - ccstd::vector _models; - BBox _aabb{}; - uint32_t _depth{0}; - uint32_t _index{0}; + ccstd::vector _models; + BBox _aabb{}; + uint32_t _depth{0}; + uint32_t _index{0}; friend class Octree; }; @@ -180,21 +180,21 @@ public: * @en Whether activate octree * @zh 是否启用八叉树加速剔除? */ - void setEnabled(bool val); + void setEnabled(bool val); inline bool isEnabled() const { return _enabled; } /** * @en min pos of scene bounding box * @zh 场景包围盒最小值 */ - void setMinPos(const Vec3 &val); + void setMinPos(const Vec3 &val); inline const Vec3 &getMinPos() const { return _minPos; } /** * @en max pos of scene bounding box * @zh 场景包围盒最大值 */ - void setMaxPos(const Vec3 &val); + void setMaxPos(const Vec3 &val); inline const Vec3 &getMaxPos() const { return _maxPos; } // reinsert all models in the tree when you change the aabb or max depth in editor @@ -225,8 +225,8 @@ private: bool isOutside(Model *model) const; OctreeNode *_root{nullptr}; - uint32_t _maxDepth{DEFAULT_OCTREE_DEPTH}; - uint32_t _totalCount{0}; + uint32_t _maxDepth{DEFAULT_OCTREE_DEPTH}; + uint32_t _totalCount{0}; bool _enabled{false}; Vec3 _minPos; diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 35d3f36c04..fa659c996d 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -90,7 +90,7 @@ void Pass::fillPipelineInfo(Pass *pass, const IPassInfoFull &info) { } if (info.phase.has_value()) { pass->_phaseString = info.phase.value(); - pass->_phase = pipeline::getPhaseID(pass->_phaseString); + pass->_phase = pipeline::getPhaseID(pass->_phaseString); } if (info.blendState.has_value()) { @@ -109,14 +109,14 @@ void Pass::fillPipelineInfo(Pass *pass, const IPassInfoFull &info) { /* static */ uint64_t Pass::getPassHash(Pass *pass) { const ccstd::string &shaderKey = ProgramLib::getInstance()->getKey(pass->getProgram(), pass->getDefines()); - std::stringstream res; + std::stringstream res; res << shaderKey << "," << static_cast(pass->_primitive) << "," << static_cast(pass->_dynamicStates); res << serializeBlendState(pass->_blendState); res << serializeDepthStencilState(pass->_depthStencilState); res << serializeRasterizerState(pass->_rs); ccstd::string str{res.str()}; - std::size_t seed = 666; + std::size_t seed = 666; boost::hash_range(seed, str.begin(), str.end()); return static_cast(seed); } @@ -124,10 +124,10 @@ uint64_t Pass::getPassHash(Pass *pass) { Pass::Pass() : Pass(Root::getInstance()) {} Pass::Pass(Root *root) { - _device = root->getDevice(); - _root = root; + _device = root->getDevice(); + _root = root; _phaseString = "default"; - _phase = pipeline::getPhaseID(_phaseString); + _phase = pipeline::getPhaseID(_phaseString); } void Pass::initialize(const IPassInfoFull &info) { @@ -139,7 +139,7 @@ void Pass::initialize(const IPassInfoFull &info) { uint32_t Pass::getHandle(const ccstd::string &name, uint32_t offset /* = 0 */, gfx::Type targetType /* = gfx::Type::UNKNOWN */) const { uint32_t handle = 0; - auto iter = _propertyHandleMap.find(name); // handle = _propertyHandleMap[name]; + auto iter = _propertyHandleMap.find(name); // handle = _propertyHandleMap[name]; if (iter == _propertyHandleMap.end()) { return 0; } @@ -163,11 +163,11 @@ uint32_t Pass::getBinding(const ccstd::string &name) const { } void Pass::setUniform(uint32_t handle, const MaterialProperty &value) { - const uint32_t binding = Pass::getBindingFromHandle(handle); - const gfx::Type type = Pass::getTypeFromHandle(handle); - const uint32_t ofs = Pass::getOffsetFromHandle(handle); - auto & block = _blocks[binding]; - auto iter = type2writer.find(type); + const uint32_t binding = Pass::getBindingFromHandle(handle); + const gfx::Type type = Pass::getTypeFromHandle(handle); + const uint32_t ofs = Pass::getOffsetFromHandle(handle); + auto &block = _blocks[binding]; + auto iter = type2writer.find(type); if (iter != type2writer.end()) { iter->second(block.data, value, static_cast(ofs)); } @@ -176,11 +176,11 @@ void Pass::setUniform(uint32_t handle, const MaterialProperty &value) { } MaterialProperty &Pass::getUniform(uint32_t handle, MaterialProperty &out) const { - const uint32_t binding = Pass::getBindingFromHandle(handle); - const gfx::Type type = Pass::getTypeFromHandle(handle); - const uint32_t ofs = Pass::getOffsetFromHandle(handle); - const auto & block = _blocks[binding]; - auto iter = type2reader.find(type); + const uint32_t binding = Pass::getBindingFromHandle(handle); + const gfx::Type type = Pass::getTypeFromHandle(handle); + const uint32_t ofs = Pass::getOffsetFromHandle(handle); + const auto &block = _blocks[binding]; + auto iter = type2reader.find(type); if (iter != type2reader.end()) { iter->second(block.data, out, static_cast(ofs)); } @@ -188,11 +188,11 @@ MaterialProperty &Pass::getUniform(uint32_t handle, MaterialProperty &out) const } void Pass::setUniformArray(uint32_t handle, const MaterialPropertyList &value) { - const uint32_t binding = Pass::getBindingFromHandle(handle); - const gfx::Type type = Pass::getTypeFromHandle(handle); - const uint32_t stride = gfx::getTypeSize(type) >> 2; - auto & block = _blocks[binding]; - uint32_t ofs = Pass::getOffsetFromHandle(handle); + const uint32_t binding = Pass::getBindingFromHandle(handle); + const gfx::Type type = Pass::getTypeFromHandle(handle); + const uint32_t stride = gfx::getTypeSize(type) >> 2; + auto &block = _blocks[binding]; + uint32_t ofs = Pass::getOffsetFromHandle(handle); for (size_t i = 0; i < value.size(); i++, ofs += stride) { if (value[i].index() == 0) { continue; @@ -245,7 +245,7 @@ pipeline::InstancedBuffer *Pass::getInstancedBuffer(int32_t extraKey) { if (iter != _instancedBuffers.end()) { return iter->second.get(); } - auto *instancedBuffer = ccnew pipeline::InstancedBuffer(this); + auto *instancedBuffer = ccnew pipeline::InstancedBuffer(this); _instancedBuffers[extraKey] = instancedBuffer; return instancedBuffer; } @@ -255,7 +255,7 @@ pipeline::BatchedBuffer *Pass::getBatchedBuffer(int32_t extraKey) { if (iter != _batchedBuffers.end()) { return iter->second.get(); } - auto *batchedBuffers = ccnew pipeline::BatchedBuffer(this); + auto *batchedBuffers = ccnew pipeline::BatchedBuffer(this); _batchedBuffers[extraKey] = batchedBuffers; return batchedBuffers; } @@ -290,13 +290,13 @@ void Pass::resetUniform(const ccstd::string &name) { if (0 == handle) { return; } - const gfx::Type type = Pass::getTypeFromHandle(handle); - const uint32_t binding = Pass::getBindingFromHandle(handle); - const uint32_t ofs = Pass::getOffsetFromHandle(handle); - const uint32_t count = Pass::getCountFromHandle(handle); - auto & block = _blocks[binding]; - IPropertyValue givenDefaultOpt; - auto iter = _properties.find(name); + const gfx::Type type = Pass::getTypeFromHandle(handle); + const uint32_t binding = Pass::getBindingFromHandle(handle); + const uint32_t ofs = Pass::getOffsetFromHandle(handle); + const uint32_t count = Pass::getCountFromHandle(handle); + auto &block = _blocks[binding]; + IPropertyValue givenDefaultOpt; + auto iter = _properties.find(name); if (iter != _properties.end()) { givenDefaultOpt = iter->second.value; } @@ -305,7 +305,7 @@ void Pass::resetUniform(const ccstd::string &name) { const auto &value = givenDefaultOpt.value(); if (cc::holds_alternative>(value)) { const auto &floatArr = cc::get>(value); - auto iter = type2writer.find(type); + auto iter = type2writer.find(type); if (iter != type2writer.end()) { CC_ASSERT(floatArr.size() == 2); iter->second(block.data, toMaterialProperty(type, floatArr), static_cast(ofs)); @@ -321,14 +321,14 @@ void Pass::resetTexture(const ccstd::string &name, index_t index /* = CC_INVALID if (0 == handle) { return; } - const gfx::Type type = Pass::getTypeFromHandle(handle); - const uint32_t binding = Pass::getBindingFromHandle(handle); - ccstd::string texName; - IPropertyInfo * info = nullptr; - auto iter = _properties.find(name); + const gfx::Type type = Pass::getTypeFromHandle(handle); + const uint32_t binding = Pass::getBindingFromHandle(handle); + ccstd::string texName; + IPropertyInfo *info = nullptr; + auto iter = _properties.find(name); if (iter != _properties.end()) { if (iter->second.value.has_value()) { - info = &iter->second; + info = &iter->second; ccstd::string *pStrVal = cc::get_if(&iter->second.value.value()); if (pStrVal != nullptr) { texName = (*pStrVal) + "-texture"; @@ -340,8 +340,8 @@ void Pass::resetTexture(const ccstd::string &name, index_t index /* = CC_INVALID texName = getDefaultStringFromType(type); } - auto * textureBase = BuiltinResMgr::getInstance()->get(texName); - gfx::Texture * texture = textureBase != nullptr ? textureBase->getGFXTexture() : nullptr; + auto *textureBase = BuiltinResMgr::getInstance()->get(texName); + gfx::Texture *texture = textureBase != nullptr ? textureBase->getGFXTexture() : nullptr; cc::optional samplerInfo; if (info != nullptr && info->samplerHash.has_value()) { samplerInfo = gfx::Sampler::unpackFromHash(static_cast(info->samplerHash.value())); @@ -362,11 +362,11 @@ void Pass::resetUBOs() { for (auto &u : _shaderInfo->blocks) { uint32_t ofs = 0; for (auto &cur : u.members) { - const auto & block = _blocks[u.binding]; - const auto & info = _properties[cur.name]; - const auto & givenDefault = info.value; - const auto & value = (givenDefault.has_value() ? cc::get>(givenDefault.value()) : getDefaultFloatArrayFromType(cur.type)); - const uint32_t size = (gfx::getTypeSize(cur.type) >> 2) * cur.count; + const auto &block = _blocks[u.binding]; + const auto &info = _properties[cur.name]; + const auto &givenDefault = info.value; + const auto &value = (givenDefault.has_value() ? cc::get>(givenDefault.value()) : getDefaultFloatArrayFromType(cur.type)); + const uint32_t size = (gfx::getTypeSize(cur.type) >> 2) * cur.count; for (size_t k = 0; (k + value.size()) <= size; k += value.size()) { std::copy(value.begin(), value.end(), block.data + ofs + k); } @@ -395,9 +395,9 @@ bool Pass::tryCompile() { CC_LOG_WARNING("create shader %s failed", _programName.c_str()); return false; } - _shader = shader; + _shader = shader; _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; - _hash = Pass::getPassHash(this); + _hash = Pass::getPassHash(this); return true; } @@ -443,15 +443,15 @@ gfx::Shader *Pass::getShaderVariant(const ccstd::vector &patches) { IPassInfoFull Pass::getPassInfoFull() const { IPassInfoFull ret; ret.passIndex = _passIndex; - ret.defines = _defines; + ret.defines = _defines; - ret.program = _programName; + ret.program = _programName; ret.propertyIndex = _propertyIndex; - ret.properties = _properties; - ret.priority = static_cast(_priority); + ret.properties = _properties; + ret.priority = static_cast(_priority); ret.primitive = _primitive; - ret.stage = _stage; + ret.stage = _stage; RasterizerStateInfo rsInfo; rsInfo.fromGFXRasterizerState(_rs); @@ -466,32 +466,32 @@ IPassInfoFull Pass::getPassInfoFull() const { ret.blendState = bsInfo; ret.dynamicStates = _dynamicStates; - ret.phase = _phaseString; + ret.phase = _phaseString; return ret; } void Pass::setState(const gfx::BlendState &bs, const gfx::DepthStencilState &dss, const gfx::RasterizerState &rs, gfx::DescriptorSet *ds) { // cjh how to control lifecycle? - _blendState = bs; + _blendState = bs; _depthStencilState = dss; - _rs = rs; - _descriptorSet = ds; + _rs = rs; + _descriptorSet = ds; } void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) { auto *programLib = ProgramLib::getInstance(); - _priority = pipeline::RenderPriority::DEFAULT; - _stage = pipeline::RenderPassStage::DEFAULT; - _phaseString = "default"; - _phase = pipeline::getPhaseID(_phaseString); - _primitive = gfx::PrimitiveMode::TRIANGLE_LIST; + _priority = pipeline::RenderPriority::DEFAULT; + _stage = pipeline::RenderPassStage::DEFAULT; + _phaseString = "default"; + _phase = pipeline::getPhaseID(_phaseString); + _primitive = gfx::PrimitiveMode::TRIANGLE_LIST; - _passIndex = info.passIndex; + _passIndex = info.passIndex; _propertyIndex = info.propertyIndex != CC_INVALID_INDEX ? info.propertyIndex : info.passIndex; - _programName = info.program; - _defines = info.defines; // cjh c++ always does copy by assignment. copyDefines ? ({ ...info.defines }) : info.defines; - _shaderInfo = programLib->getTemplate(info.program); + _programName = info.program; + _defines = info.defines; // cjh c++ always does copy by assignment. copyDefines ? ({ ...info.defines }) : info.defines; + _shaderInfo = programLib->getTemplate(info.program); if (info.properties.has_value()) { _properties = info.properties.value(); } @@ -504,19 +504,19 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) // init descriptor set gfx::DescriptorSetInfo dsInfo; - dsInfo.layout = programLib->getDescriptorSetLayout(_device, info.program); + dsInfo.layout = programLib->getDescriptorSetLayout(_device, info.program); _descriptorSet = _device->createDescriptorSet(dsInfo); // calculate total size required - const auto & blocks = _shaderInfo->blocks; - const auto * tmplInfo = programLib->getTemplateInfo(info.program); + const auto &blocks = _shaderInfo->blocks; + const auto *tmplInfo = programLib->getTemplateInfo(info.program); const ccstd::vector &blockSizes = tmplInfo->blockSizes; - const auto & handleMap = tmplInfo->handleMap; + const auto &handleMap = tmplInfo->handleMap; - const auto alignment = device->getCapabilities().uboOffsetAlignment; + const auto alignment = device->getCapabilities().uboOffsetAlignment; ccstd::vector startOffsets; startOffsets.reserve(blocks.size()); - uint32_t lastSize = 0; + uint32_t lastSize = 0; uint32_t lastOffset = 0; for (size_t i = 0; i < blocks.size(); i++) { const auto &size = blockSizes[i]; @@ -529,48 +529,48 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */) uint32_t totalSize = !startOffsets.empty() ? (startOffsets[startOffsets.size() - 1] + lastSize) : 0; if (totalSize > 0) { gfx::BufferInfo bufferInfo; - bufferInfo.usage = gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST; + bufferInfo.usage = gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST; bufferInfo.memUsage = gfx::MemoryUsageBit::DEVICE; // https://bugs.chromium.org/p/chromium/issues/detail?id=988988 bufferInfo.size = static_cast(std::ceil(static_cast(totalSize) / 16.F)) * 16; - _rootBuffer = device->createBuffer(bufferInfo); - _rootBlock = ccnew ArrayBuffer(totalSize); + _rootBuffer = device->createBuffer(bufferInfo); + _rootBlock = ccnew ArrayBuffer(totalSize); } gfx::BufferViewInfo bufferViewInfo; // create buffer views for (size_t i = 0, count = 0; i < blocks.size(); i++) { - int32_t binding = blocks[i].binding; - int32_t size = blockSizes[i]; + int32_t binding = blocks[i].binding; + int32_t size = blockSizes[i]; bufferViewInfo.buffer = _rootBuffer; bufferViewInfo.offset = startOffsets[count++]; - bufferViewInfo.range = static_cast(std::ceil(static_cast(size) / 16.F)) * 16; + bufferViewInfo.range = static_cast(std::ceil(static_cast(size) / 16.F)) * 16; if (binding >= _buffers.size()) { _buffers.resize(binding + 1); } - auto *bufferView = device->createBuffer(bufferViewInfo); + auto *bufferView = device->createBuffer(bufferViewInfo); _buffers[binding] = bufferView; // non-builtin UBO data pools, note that the effect compiler // guarantees these bindings to be consecutive, starting from 0 and non-array-typed if (binding >= _blocks.size()) { _blocks.resize(binding + 1); } - _blocks[binding].data = reinterpret_cast(const_cast(_rootBlock->getData()) + bufferViewInfo.offset); - _blocks[binding].count = size / 4; + _blocks[binding].data = reinterpret_cast(const_cast(_rootBlock->getData()) + bufferViewInfo.offset); + _blocks[binding].count = size / 4; _blocks[binding].offset = bufferViewInfo.offset / 4; _descriptorSet->bindBuffer(binding, bufferView); } // store handles - _propertyHandleMap = handleMap; - auto & directHandleMap = _propertyHandleMap; + _propertyHandleMap = handleMap; + auto &directHandleMap = _propertyHandleMap; Record indirectHandleMap; for (const auto &properties : _properties) { if (!properties.second.handleInfo.has_value()) { continue; } - const auto &propVal = properties.second.handleInfo.value(); + const auto &propVal = properties.second.handleInfo.value(); indirectHandleMap[properties.first] = getHandle(std::get<0>(propVal), std::get<1>(propVal), std::get<2>(propVal)); } @@ -583,7 +583,7 @@ void Pass::syncBatchingScheme() { if (_device->hasFeature(gfx::Feature::INSTANCED_ARRAYS)) { _batchingScheme = BatchingSchemes::INSTANCING; } else { - iter->second = false; + iter->second = false; _batchingScheme = BatchingSchemes::NONE; } } else { @@ -597,30 +597,30 @@ void Pass::syncBatchingScheme() { } void Pass::initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, const gfx::BlendState &bs, uint64_t hashFactor) { - _priority = target->_priority; - _stage = target->_stage; - _phase = target->_phase; - _batchingScheme = target->_batchingScheme; - _primitive = target->_primitive; - _dynamicStates = target->_dynamicStates; - _blendState = bs; // cjh lifecycle? + _priority = target->_priority; + _stage = target->_stage; + _phase = target->_phase; + _batchingScheme = target->_batchingScheme; + _primitive = target->_primitive; + _dynamicStates = target->_dynamicStates; + _blendState = bs; // cjh lifecycle? _depthStencilState = dss; - _descriptorSet = target->_descriptorSet; - _rs = *target->getRasterizerState(); - _passIndex = target->_passIndex; - _propertyIndex = target->_propertyIndex; - _programName = target->getProgram(); - _defines = target->_defines; - _shaderInfo = target->_shaderInfo; // cjh how to release? - _properties = target->_properties; + _descriptorSet = target->_descriptorSet; + _rs = *target->getRasterizerState(); + _passIndex = target->_passIndex; + _propertyIndex = target->_propertyIndex; + _programName = target->getProgram(); + _defines = target->_defines; + _shaderInfo = target->_shaderInfo; // cjh how to release? + _properties = target->_properties; - _blocks = target->_blocks; + _blocks = target->_blocks; _dynamics = target->_dynamics; _shader = target->_shader; _pipelineLayout = ProgramLib::getInstance()->getTemplateInfo(_programName)->pipelineLayout; - _hash = target->_hash ^ hashFactor; + _hash = target->_hash ^ hashFactor; } gfx::DescriptorSetLayout *Pass::getLocalSetLayout() const { diff --git a/native/cocos/scene/Pass.h b/native/cocos/scene/Pass.h index 1a64f20680..5fecefd6dc 100644 --- a/native/cocos/scene/Pass.h +++ b/native/cocos/scene/Pass.h @@ -52,13 +52,13 @@ namespace scene { struct IMacroPatch; struct PassDynamicsValue { - bool dirty{false}; + bool dirty{false}; float value{0.F}; }; using IPassDynamics = ccstd::unordered_map; enum class BatchingSchemes { - NONE = 0, + NONE = 0, INSTANCING = 1, VB_MERGING = 2, }; @@ -210,7 +210,7 @@ public: void update(); pipeline::InstancedBuffer *getInstancedBuffer(int32_t extraKey = 0); - pipeline::BatchedBuffer * getBatchedBuffer(int32_t extraKey = 0); + pipeline::BatchedBuffer *getBatchedBuffer(int32_t extraKey = 0); /** * @en Destroy the current pass. @@ -261,40 +261,40 @@ public: IPassInfoFull getPassInfoFull() const; // infos - inline Root * getRoot() const { return _root; } - inline gfx::Device * getDevice() const { return _device; } - inline IProgramInfo * getShaderInfo() const { return _shaderInfo; } - gfx::DescriptorSetLayout * getLocalSetLayout() const; - inline const ccstd::string & getProgram() const { return _programName; } + inline Root *getRoot() const { return _root; } + inline gfx::Device *getDevice() const { return _device; } + inline IProgramInfo *getShaderInfo() const { return _shaderInfo; } + gfx::DescriptorSetLayout *getLocalSetLayout() const; + inline const ccstd::string &getProgram() const { return _programName; } inline const Record &getProperties() const { return _properties; } - inline const MacroRecord & getDefines() const { return _defines; } - inline MacroRecord & getDefines() { return _defines; } - inline index_t getPassIndex() const { return _passIndex; } - inline index_t getPropertyIndex() const { return _propertyIndex; } + inline const MacroRecord &getDefines() const { return _defines; } + inline MacroRecord &getDefines() { return _defines; } + inline index_t getPassIndex() const { return _passIndex; } + inline index_t getPropertyIndex() const { return _propertyIndex; } // data - inline const IPassDynamics & getDynamics() const { return _dynamics; } + inline const IPassDynamics &getDynamics() const { return _dynamics; } inline const ccstd::vector &getBlocks() const { return _blocks; } - inline ArrayBuffer * getRootBlock() { return _rootBlock; } - inline bool isRootBufferDirty() const { return _rootBufferDirty; } + inline ArrayBuffer *getRootBlock() { return _rootBlock; } + inline bool isRootBufferDirty() const { return _rootBufferDirty; } //NOTE: _setRootBufferDirty must contain a _ prefix to make bindings-generator work correctly. // In ts engine, Pass has rootBufferDirty getter and without setter, but it contains a protected function named _setRootBufferDirty. // If we remove _ prefix in C++, bindings-generator doesn't support to bind rootBufferDirty property as getter and ignore to bind setRootBufferDirty as setter at the same time. // So let's keep the _ prefix temporarily. inline void _setRootBufferDirty(bool val) { _rootBufferDirty = val; } // NOLINT(readability-identifier-naming) // states - inline pipeline::RenderPriority getPriority() const { return _priority; } - inline gfx::PrimitiveMode getPrimitive() const { return _primitive; } - inline pipeline::RenderPassStage getStage() const { return _stage; } - inline uint32_t getPhase() const { return _phase; } - inline const gfx::RasterizerState * getRasterizerState() const { return &_rs; } + inline pipeline::RenderPriority getPriority() const { return _priority; } + inline gfx::PrimitiveMode getPrimitive() const { return _primitive; } + inline pipeline::RenderPassStage getStage() const { return _stage; } + inline uint32_t getPhase() const { return _phase; } + inline const gfx::RasterizerState *getRasterizerState() const { return &_rs; } inline const gfx::DepthStencilState *getDepthStencilState() const { return &_depthStencilState; } - inline const gfx::BlendState * getBlendState() const { return &_blendState; } - inline gfx::DynamicStateFlagBit getDynamicStates() const { return _dynamicStates; } - inline BatchingSchemes getBatchingScheme() const { return _batchingScheme; } - inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptorSet; } - inline uint64_t getHash() const { return _hash; } - inline double getHashForJS() const { return static_cast(getHash()); } - inline gfx::PipelineLayout * getPipelineLayout() const { return _pipelineLayout; } + inline const gfx::BlendState *getBlendState() const { return &_blendState; } + inline gfx::DynamicStateFlagBit getDynamicStates() const { return _dynamicStates; } + inline BatchingSchemes getBatchingScheme() const { return _batchingScheme; } + inline gfx::DescriptorSet *getDescriptorSet() const { return _descriptorSet; } + inline uint64_t getHash() const { return _hash; } + inline double getHashForJS() const { return static_cast(getHash()); } + inline gfx::PipelineLayout *getPipelineLayout() const { return _pipelineLayout; } // Only for UI void initPassFromTarget(Pass *target, const gfx::DepthStencilState &dss, const gfx::BlendState &bs, uint64_t hashFactor); @@ -307,44 +307,44 @@ public: virtual void endChangeStatesSilently() {} protected: - void setState(const gfx::BlendState &bs, const gfx::DepthStencilState &dss, const gfx::RasterizerState &rs, gfx::DescriptorSet *ds); - void doInit(const IPassInfoFull &info, bool copyDefines = false); + void setState(const gfx::BlendState &bs, const gfx::DepthStencilState &dss, const gfx::RasterizerState &rs, gfx::DescriptorSet *ds); + void doInit(const IPassInfoFull &info, bool copyDefines = false); virtual void syncBatchingScheme(); // internal resources - IntrusivePtr _rootBuffer; + IntrusivePtr _rootBuffer; ccstd::vector> _buffers; - IntrusivePtr _descriptorSet; - IntrusivePtr _pipelineLayout; + IntrusivePtr _descriptorSet; + IntrusivePtr _pipelineLayout; // internal data - index_t _passIndex{0}; - index_t _propertyIndex{0}; - ccstd::string _programName; - IPassDynamics _dynamics; + index_t _passIndex{0}; + index_t _propertyIndex{0}; + ccstd::string _programName; + IPassDynamics _dynamics; Record _propertyHandleMap; - IntrusivePtr _rootBlock; - ccstd::vector _blocks; // Point to position in _rootBlock + IntrusivePtr _rootBlock; + ccstd::vector _blocks; // Point to position in _rootBlock - IProgramInfo * _shaderInfo; // weakref to template of ProgramLib - MacroRecord _defines; - Record _properties; - IntrusivePtr _shader; - gfx::BlendState _blendState{}; - gfx::DepthStencilState _depthStencilState{}; - gfx::RasterizerState _rs{}; - pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; - pipeline::RenderPassStage _stage{pipeline::RenderPassStage::DEFAULT}; - uint32_t _phase{0}; - ccstd::string _phaseString; - gfx::PrimitiveMode _primitive{gfx::PrimitiveMode::TRIANGLE_LIST}; - BatchingSchemes _batchingScheme{BatchingSchemes::NONE}; - gfx::DynamicStateFlagBit _dynamicStates{gfx::DynamicStateFlagBit::NONE}; + IProgramInfo *_shaderInfo; // weakref to template of ProgramLib + MacroRecord _defines; + Record _properties; + IntrusivePtr _shader; + gfx::BlendState _blendState{}; + gfx::DepthStencilState _depthStencilState{}; + gfx::RasterizerState _rs{}; + pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; + pipeline::RenderPassStage _stage{pipeline::RenderPassStage::DEFAULT}; + uint32_t _phase{0}; + ccstd::string _phaseString; + gfx::PrimitiveMode _primitive{gfx::PrimitiveMode::TRIANGLE_LIST}; + BatchingSchemes _batchingScheme{BatchingSchemes::NONE}; + gfx::DynamicStateFlagBit _dynamicStates{gfx::DynamicStateFlagBit::NONE}; Record> _instancedBuffers; - Record> _batchedBuffers; + Record> _batchedBuffers; uint64_t _hash{0}; // external references - Root * _root{nullptr}; + Root *_root{nullptr}; gfx::Device *_device{nullptr}; bool _rootBufferDirty{false}; diff --git a/native/cocos/scene/RenderScene.cpp b/native/cocos/scene/RenderScene.cpp index 20f65a21f4..2d22bb210a 100644 --- a/native/cocos/scene/RenderScene.cpp +++ b/native/cocos/scene/RenderScene.cpp @@ -51,7 +51,7 @@ RenderScene::~RenderScene() = default; void RenderScene::activate() { const auto *sceneData = Root::getInstance()->getPipeline()->getPipelineSceneData(); - _octree = sceneData->getOctree(); + _octree = sceneData->getOctree(); } bool RenderScene::initialize(const IRenderSceneInfo &info) { diff --git a/native/cocos/scene/RenderScene.h b/native/cocos/scene/RenderScene.h index 0f458c8fab..ca8b2b2980 100644 --- a/native/cocos/scene/RenderScene.h +++ b/native/cocos/scene/RenderScene.h @@ -96,31 +96,31 @@ public: void onGlobalPipelineStateChanged(); inline DirectionalLight *getMainLight() const { return _mainLight.get(); } - void setMainLight(DirectionalLight *dl); + void setMainLight(DirectionalLight *dl); - inline uint64_t generateModelId() { return _modelId++; } - inline const ccstd::string & getName() const { return _name; } - inline const ccstd::vector> & getCameras() const { return _cameras; } + inline uint64_t generateModelId() { return _modelId++; } + inline const ccstd::string &getName() const { return _name; } + inline const ccstd::vector> &getCameras() const { return _cameras; } inline const ccstd::vector> &getSphereLights() const { return _sphereLights; } - inline const ccstd::vector> & getSpotLights() const { return _spotLights; } - inline const ccstd::vector> & getModels() const { return _models; } - inline Octree * getOctree() const { return _octree; } - void updateOctree(Model *model); + inline const ccstd::vector> &getSpotLights() const { return _spotLights; } + inline const ccstd::vector> &getModels() const { return _models; } + inline Octree *getOctree() const { return _octree; } + void updateOctree(Model *model); // FIXME: remove getDrawBatch2Ds inline const ccstd::vector &getBatches() const { return _batches; } inline const ccstd::vector &getDrawBatch2Ds() const { return _batches; } private: - ccstd::string _name; - uint64_t _modelId{0}; - IntrusivePtr _mainLight; - ccstd::vector> _models; - ccstd::vector> _cameras; + ccstd::string _name; + uint64_t _modelId{0}; + IntrusivePtr _mainLight; + ccstd::vector> _models; + ccstd::vector> _cameras; ccstd::vector> _directionalLights; - ccstd::vector> _sphereLights; - ccstd::vector> _spotLights; - ccstd::vector _batches; - Octree * _octree{nullptr}; + ccstd::vector> _sphereLights; + ccstd::vector> _spotLights; + ccstd::vector _batches; + Octree *_octree{nullptr}; CC_DISALLOW_COPY_MOVE_ASSIGN(RenderScene); }; diff --git a/native/cocos/scene/RenderWindow.cpp b/native/cocos/scene/RenderWindow.cpp index 9acacc6a7e..79c47a550c 100644 --- a/native/cocos/scene/RenderWindow.cpp +++ b/native/cocos/scene/RenderWindow.cpp @@ -45,7 +45,7 @@ const ccstd::unordered_map ORIENTAT } -RenderWindow::RenderWindow() = default; +RenderWindow::RenderWindow() = default; RenderWindow::~RenderWindow() = default; bool RenderWindow::initialize(gfx::Device *device, IRenderWindowInfo &info) { @@ -57,7 +57,7 @@ bool RenderWindow::initialize(gfx::Device *device, IRenderWindowInfo &info) { _swapchain = info.swapchain; } - _width = info.width; + _width = info.width; _height = info.height; _renderPass = device->createRenderPass(info.renderPassInfo); @@ -109,7 +109,7 @@ void RenderWindow::destroy() { void RenderWindow::resize(uint32_t width, uint32_t height) { if (_swapchain != nullptr) { _swapchain->resize(width, height, ORIENTATION_MAP.at(Device::getDeviceOrientation())); - _width = _swapchain->getWidth(); + _width = _swapchain->getWidth(); _height = _swapchain->getHeight(); } else { for (auto *colorTexture : _colorTextures) { @@ -118,7 +118,7 @@ void RenderWindow::resize(uint32_t width, uint32_t height) { if (_depthStencilTexture != nullptr) { _depthStencilTexture->resize(width, height); } - _width = width; + _width = width; _height = height; } diff --git a/native/cocos/scene/RenderWindow.h b/native/cocos/scene/RenderWindow.h index bf66f867ac..5a6a27b1ca 100644 --- a/native/cocos/scene/RenderWindow.h +++ b/native/cocos/scene/RenderWindow.h @@ -36,10 +36,10 @@ class Camera; struct IRenderWindowInfo { cc::optional title; - uint32_t width{0}; - uint32_t height{0}; - gfx::RenderPassInfo renderPassInfo; - gfx::Swapchain * swapchain{nullptr}; + uint32_t width{0}; + uint32_t height{0}; + gfx::RenderPassInfo renderPassInfo; + gfx::Swapchain *swapchain{nullptr}; }; /** @@ -117,15 +117,15 @@ public: inline const ccstd::vector> &getCameras() const { return _cameras; } private: - uint32_t _width{1}; - uint32_t _height{1}; - gfx::Swapchain * _swapchain{nullptr}; - ccstd::string _title; - IntrusivePtr _renderPass; - IntrusivePtr _depthStencilTexture; - IntrusivePtr _frameBuffer; + uint32_t _width{1}; + uint32_t _height{1}; + gfx::Swapchain *_swapchain{nullptr}; + ccstd::string _title; + IntrusivePtr _renderPass; + IntrusivePtr _depthStencilTexture; + IntrusivePtr _frameBuffer; ccstd::vector> _cameras; - RefVector _colorTextures; + RefVector _colorTextures; CC_DISALLOW_COPY_MOVE_ASSIGN(RenderWindow); }; diff --git a/native/cocos/scene/Shadow.cpp b/native/cocos/scene/Shadow.cpp index 9f3055cd30..b2aa9c0361 100644 --- a/native/cocos/scene/Shadow.cpp +++ b/native/cocos/scene/Shadow.cpp @@ -93,7 +93,7 @@ void ShadowsInfo::setShadowMapSize(float value) { void ShadowsInfo::setPlaneFromNode(Node *node) { const auto &qt = node->getWorldRotation(); - _normal = Vec3::UNIT_Y; + _normal = Vec3::UNIT_Y; _normal.transformQuat(qt); _distance = _normal.dot(node->getWorldPosition()); } diff --git a/native/cocos/scene/Shadow.h b/native/cocos/scene/Shadow.h index 2db980ac90..9cdf62320c 100644 --- a/native/cocos/scene/Shadow.h +++ b/native/cocos/scene/Shadow.h @@ -134,18 +134,18 @@ class Shadows; class ShadowsInfo : public RefCounted { public: - ShadowsInfo() = default; + ShadowsInfo() = default; ~ShadowsInfo() override = default; /** * @en Whether activate planar shadow * @zh 是否启用平面阴影? */ - void setEnabled(bool val); + void setEnabled(bool val); inline bool isEnabled() const { return _enabled; } - void setType(ShadowType val); + void setType(ShadowType val); inline ShadowType getType() const { return _type; } @@ -154,7 +154,7 @@ public: * @en Shadow color * @zh 阴影颜色 */ - void setShadowColor(const Color &val); + void setShadowColor(const Color &val); inline const Color &getShadowColor() const { return _shadowColor; } @@ -163,7 +163,7 @@ public: * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ - void setNormal(const Vec3 &val); + void setNormal(const Vec3 &val); inline const Vec3 &getNormal() const { return _normal; } @@ -172,7 +172,7 @@ public: * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离 */ - void setDistance(float val); + void setDistance(float val); inline float getDistance() const { return _distance; } @@ -181,7 +181,7 @@ public: * @en get or set shadow max received * @zh 获取或者设置阴影接收的最大光源数量 */ - void setMaxReceived(uint32_t val); + void setMaxReceived(uint32_t val); inline uint32_t getMaxReceived() const { return _maxReceived; } @@ -190,7 +190,7 @@ public: * @en get or set shadow map size * @zh 获取或者设置阴影纹理大小 */ - void setShadowMapSize(float value); + void setShadowMapSize(float value); inline float getShadowMapSize() const { return _size.x; } @@ -208,13 +208,13 @@ public: void activate(Shadows *resource); - bool _enabled{false}; + bool _enabled{false}; ShadowType _type{ShadowType::PLANAR}; - Vec3 _normal{0.F, 1.F, 0.F}; - float _distance{0.F}; - Color _shadowColor{0, 0, 0, 76}; - uint32_t _maxReceived{4}; - Vec2 _size{512.F, 512.F}; + Vec3 _normal{0.F, 1.F, 0.F}; + float _distance{0.F}; + Color _shadowColor{0, 0, 0, 76}; + uint32_t _maxReceived{4}; + Vec2 _size{512.F, 512.F}; Shadows *_resource{nullptr}; }; @@ -233,14 +233,14 @@ public: */ static const float COEFFICIENT_OF_EXPANSION; - Shadows() = default; + Shadows() = default; ~Shadows() = default; - void initialize(const ShadowsInfo &shadowsInfo); - void destroy(); + void initialize(const ShadowsInfo &shadowsInfo); + void destroy(); gfx::Shader *getPlanarShader(const ccstd::vector &patches); gfx::Shader *getPlanarInstanceShader(const ccstd::vector &patches); - void activate(); + void activate(); /** * @en Whether activate shadow. @@ -257,21 +257,21 @@ public: * @zh 阴影接收平面的法线。 */ inline const Vec3 &getNormal() const { return _normal; } - inline void setNormal(const Vec3 &val) { _normal.set(val); } + inline void setNormal(const Vec3 &val) { _normal.set(val); } /** * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离。 */ inline float getDistance() const { return _distance; } - inline void setDistance(float val) { _distance = val; } + inline void setDistance(float val) { _distance = val; } /** * @en Shadow color. * @zh 阴影颜色。 */ inline const Color &getShadowColor() const { return _shadowColor; } - inline void setShadowColor(const Color &color) { + inline void setShadowColor(const Color &color) { _shadowColor.set(color); _shadowColor4f[0] = static_cast(color.r) / 255.F; _shadowColor4f[1] = static_cast(color.g) / 255.F; @@ -285,7 +285,7 @@ public: * @zh 阴影类型。 */ inline ShadowType getType() const { return _type; } - inline void setType(ShadowType val) { + inline void setType(ShadowType val) { _type = _enabled ? val : ShadowType::NONE; activate(); } @@ -295,7 +295,7 @@ public: * @zh 获取或者设置阴影纹理大小。 */ inline const Vec2 &getSize() const { return _size; } - inline void setSize(const Vec2 &val) { + inline void setSize(const Vec2 &val) { _size.set(val); _shadowMapDirty = true; } @@ -315,7 +315,7 @@ public: inline void setShadowMapDirty(bool val) { _shadowMapDirty = val; } inline const Mat4 &getMatLight() const { return _matLight; } - inline Mat4 & getMatLight() { return _matLight; } + inline Mat4 &getMatLight() { return _matLight; } inline Material *getMaterial() const { return _material.get(); } inline Material *getInstancingMaterial() const { return _instancingMaterial.get(); } @@ -324,11 +324,11 @@ public: * @en get or set shadow max received * @zh 获取或者设置阴影接收的最大光源数量 */ - inline void setMaxReceived(uint32_t val) { _maxReceived = val; } + inline void setMaxReceived(uint32_t val) { _maxReceived = val; } inline uint32_t getMaxReceived() const { return _maxReceived; } inline float getShadowCameraFar() const { return _shadowCameraFar; } - inline void setShadowCameraFar(float shadowDistance) { _shadowCameraFar = shadowDistance; } + inline void setShadowCameraFar(float shadowDistance) { _shadowCameraFar = shadowDistance; } inline Mat4 getMatShadowView() const { return _matShadowView; } inline void setMatShadowView(const Mat4 &matShadowView) { _matShadowView = matShadowView; } @@ -358,22 +358,22 @@ private: // local set float _shadowCameraFar{0.0F}; - Mat4 _matShadowView; - Mat4 _matShadowProj; - Mat4 _matShadowViewProj; + Mat4 _matShadowView; + Mat4 _matShadowProj; + Mat4 _matShadowViewProj; // public properties of shadow - Vec3 _normal{0.F, 1.F, 0.F}; - Color _shadowColor{0, 0, 0, 76}; + Vec3 _normal{0.F, 1.F, 0.F}; + Color _shadowColor{0, 0, 0, 76}; ccstd::array _shadowColor4f{0.F, 0.F, 0.F, 76.F / 255.F}; - Mat4 _matLight; + Mat4 _matLight; IntrusivePtr _material{nullptr}; IntrusivePtr _instancingMaterial{nullptr}; - Vec2 _size{512.F, 512.F}; - bool _enabled{false}; - float _distance{0.F}; - ShadowType _type{ShadowType::NONE}; - bool _shadowMapDirty{false}; + Vec2 _size{512.F, 512.F}; + bool _enabled{false}; + float _distance{0.F}; + ShadowType _type{ShadowType::NONE}; + bool _shadowMapDirty{false}; }; } // namespace scene diff --git a/native/cocos/scene/Skybox.cpp b/native/cocos/scene/Skybox.cpp index a8a48a63c8..a10228619b 100644 --- a/native/cocos/scene/Skybox.cpp +++ b/native/cocos/scene/Skybox.cpp @@ -48,7 +48,7 @@ namespace cc { namespace scene { SkyboxInfo::SkyboxInfo(/* args */) = default; -SkyboxInfo::~SkyboxInfo() = default; +SkyboxInfo::~SkyboxInfo() = default; void SkyboxInfo::setEnabled(bool val) { _enabled = val; @@ -213,15 +213,15 @@ void Skybox::setDiffuseMap(TextureCube *val) { } void Skybox::initialize(const SkyboxInfo &skyboxInfo) { - _enabled = skyboxInfo.isEnabled(); - _useIBL = skyboxInfo.isUseIBL(); + _enabled = skyboxInfo.isEnabled(); + _useIBL = skyboxInfo.isUseIBL(); _useDiffuseMap = skyboxInfo.isApplyDiffuseMap(); - _useHDR = skyboxInfo.isUseHDR(); + _useHDR = skyboxInfo.isUseHDR(); } void Skybox::setEnvMaps(TextureCube *envmapHDR, TextureCube *envmapLDR) { - _envmapHDR = envmapHDR; - _envmapLDR = envmapLDR; + _envmapHDR = envmapHDR; + _envmapLDR = envmapLDR; const bool isHDR = Root::getInstance()->getPipeline()->getPipelineSceneData()->isHDR(); if (isHDR) { if (envmapHDR) { @@ -243,9 +243,9 @@ void Skybox::setDiffuseMaps(TextureCube *diffuseMapHDR, TextureCube *diffuseMapL } void Skybox::activate() { - auto *pipeline = Root::getInstance()->getPipeline(); + auto *pipeline = Root::getInstance()->getPipeline(); _globalDSManager = pipeline->getGlobalDSManager(); - _default = BuiltinResMgr::getInstance()->get("default-cube-texture"); + _default = BuiltinResMgr::getInstance()->get("default-cube-texture"); if (!_model) { _model = Root::getInstance()->createModel(); @@ -253,18 +253,18 @@ void Skybox::activate() { _model->initWorldBoundDescriptors(CC_INVALID_INDEX); } auto *envmap = getEnvmap(); - bool isRGBE = envmap != nullptr ? envmap->isRGBE : _default->isRGBE; + bool isRGBE = envmap != nullptr ? envmap->isRGBE : _default->isRGBE; if (!skyboxMaterial) { auto *mat = ccnew Material(); - MacroRecord defines{{"USE_RGBE_CUBEMAP", isRGBE}}; - IMaterialInfo matInfo; + MacroRecord defines{{"USE_RGBE_CUBEMAP", isRGBE}}; + IMaterialInfo matInfo; matInfo.effectName = ccstd::string{"skybox"}; - matInfo.defines = IMaterialInfo::DefinesType{defines}; + matInfo.defines = IMaterialInfo::DefinesType{defines}; mat->initialize({matInfo}); IMaterialInstanceInfo matInstInfo; matInstInfo.parent = mat; - skyboxMaterial = ccnew MaterialInstance(matInstInfo); + skyboxMaterial = ccnew MaterialInstance(matInstInfo); skyboxMaterial->addRef(); EventDispatcher::addCustomEventListener(EVENT_CLOSE, [](const CustomEvent & /*unused*/) { skyboxMaterial->release(); @@ -275,7 +275,7 @@ void Skybox::activate() { if (_enabled) { if (!_mesh) { IBoxOptions options; - options.width = 2; + options.width = 2; options.height = 2; options.length = 2; @@ -308,19 +308,19 @@ void Skybox::updatePipeline() const { _model->setSubModelMaterial(0, skyboxMaterial); } - Root *root = Root::getInstance(); + Root *root = Root::getInstance(); auto *pipeline = root->getPipeline(); - const bool useRGBE = isRGBE(); - const int32_t useIBLValue = isUseIBL() ? (useRGBE ? 2 : 1) : 0; + const bool useRGBE = isRGBE(); + const int32_t useIBLValue = isUseIBL() ? (useRGBE ? 2 : 1) : 0; const int32_t useDiffuseMapValue = (isUseIBL() && isUseDiffuseMap() && getDiffuseMap() != nullptr) ? (useRGBE ? 2 : 1) : 0; - const bool useHDRValue = isUseHDR(); + const bool useHDRValue = isUseHDR(); bool valueChanged = false; - auto iter = pipeline->getMacros().find("CC_USE_IBL"); + auto iter = pipeline->getMacros().find("CC_USE_IBL"); if (iter != pipeline->getMacros().end()) { - const MacroValue ¯oIBL = iter->second; - const int32_t * macroIBLPtr = cc::get_if(¯oIBL); + const MacroValue ¯oIBL = iter->second; + const int32_t *macroIBLPtr = cc::get_if(¯oIBL); if (macroIBLPtr != nullptr && (*macroIBLPtr != useIBLValue)) { pipeline->setValue("CC_USE_IBL", useIBLValue); valueChanged = true; @@ -329,8 +329,8 @@ void Skybox::updatePipeline() const { auto iterDiffuseMap = pipeline->getMacros().find("CC_USE_DIFFUSEMAP"); if (iterDiffuseMap != pipeline->getMacros().end()) { - const MacroValue ¯oDIFFUSEMAP = iterDiffuseMap->second; - const int32_t * macroDIFFUSEMAPPtr = cc::get_if(¯oDIFFUSEMAP); + const MacroValue ¯oDIFFUSEMAP = iterDiffuseMap->second; + const int32_t *macroDIFFUSEMAPPtr = cc::get_if(¯oDIFFUSEMAP); if (macroDIFFUSEMAPPtr != nullptr && ((*macroDIFFUSEMAPPtr != 0) != useDiffuseMapValue)) { pipeline->setValue("CC_USE_DIFFUSEMAP", useDiffuseMapValue); valueChanged = true; @@ -339,8 +339,8 @@ void Skybox::updatePipeline() const { auto iterUseHDR = pipeline->getMacros().find("CC_USE_HDR"); if (iterUseHDR != pipeline->getMacros().end()) { - const MacroValue ¯oHDR = iterUseHDR->second; - const int32_t * macroHDRPtr = cc::get_if(¯oHDR); + const MacroValue ¯oHDR = iterUseHDR->second; + const int32_t *macroHDRPtr = cc::get_if(¯oHDR); if (macroHDRPtr != nullptr && ((*macroHDRPtr != 0) != useHDRValue)) { pipeline->setValue("CC_USE_HDR", useHDRValue); valueChanged = true; diff --git a/native/cocos/scene/Skybox.h b/native/cocos/scene/Skybox.h index 1cde1fd2f7..78ca68825c 100644 --- a/native/cocos/scene/Skybox.h +++ b/native/cocos/scene/Skybox.h @@ -97,7 +97,7 @@ public: bool isApplyDiffuseMap() const { return EnvironmentLightingType::DIFFUSEMAP_WITH_REFLECTION == _envLightingType; } - void setEnvLightingType(EnvironmentLightingType val); + void setEnvLightingType(EnvironmentLightingType val); EnvironmentLightingType getEnvLightingType() const { return _envLightingType; } @@ -108,7 +108,7 @@ public: */ // @editable // @tooltip('i18n:skybox.enabled') - void setEnabled(bool val); + void setEnabled(bool val); inline bool isEnabled() const { return _enabled; } /** @@ -117,7 +117,7 @@ public: */ // @editable // @tooltip('i18n:skybox.useIBL') - void setUseIBL(bool val) const; + void setUseIBL(bool val) const; inline bool isUseIBL() const { return EnvironmentLightingType::HEMISPHERE_DIFFUSE != _envLightingType; } @@ -137,7 +137,7 @@ public: // @editable // @type(TextureCube) // @tooltip('i18n:skybox.envmap') - void setEnvmap(TextureCube *val); + void setEnvmap(TextureCube *val); TextureCube *getEnvmap() const; inline void setEnvmapForJS(TextureCube *val) { @@ -160,7 +160,7 @@ public: // @editable // @readOnly // @type(TextureCube) - void setDiffuseMap(TextureCube *val); + void setDiffuseMap(TextureCube *val); TextureCube *getDiffuseMap() const; void activate(Skybox *resource); @@ -183,14 +183,14 @@ public: // @serializable bool _enabled{false}; // @serializable - bool _useHDR{true}; + bool _useHDR{true}; EnvironmentLightingType _envLightingType{EnvironmentLightingType::HEMISPHERE_DIFFUSE}; - Skybox * _resource{nullptr}; + Skybox *_resource{nullptr}; }; class Skybox final { public: - Skybox() = default; + Skybox() = default; ~Skybox() = default; void initialize(const SkyboxInfo &skyboxInfo); @@ -252,7 +252,7 @@ public: * @zh 使用的立方体贴图 */ TextureCube *getEnvmap() const; - void setEnvmap(TextureCube *val); + void setEnvmap(TextureCube *val); /** * @en Whether enable RGBE data support in skybox shader @@ -265,24 +265,24 @@ public: * @zh 使用的漫反射卷积图 */ TextureCube *getDiffuseMap() const; - void setDiffuseMap(TextureCube *val); + void setDiffuseMap(TextureCube *val); private: void updatePipeline() const; void updateGlobalBinding(); - IntrusivePtr _envmapLDR; - IntrusivePtr _envmapHDR; - IntrusivePtr _diffuseMapLDR; - IntrusivePtr _diffuseMapHDR; + IntrusivePtr _envmapLDR; + IntrusivePtr _envmapHDR; + IntrusivePtr _diffuseMapLDR; + IntrusivePtr _diffuseMapHDR; pipeline::GlobalDSManager *_globalDSManager{nullptr}; - IntrusivePtr _model; - IntrusivePtr _mesh; - IntrusivePtr _default; - bool _enabled{false}; - bool _useIBL{false}; - bool _useHDR{true}; - bool _useDiffuseMap{false}; + IntrusivePtr _model; + IntrusivePtr _mesh; + IntrusivePtr _default; + bool _enabled{false}; + bool _useIBL{false}; + bool _useHDR{true}; + bool _useDiffuseMap{false}; CC_DISALLOW_COPY_MOVE_ASSIGN(Skybox); }; diff --git a/native/cocos/scene/SphereLight.cpp b/native/cocos/scene/SphereLight.cpp index bc5501db92..6d1155f401 100644 --- a/native/cocos/scene/SphereLight.cpp +++ b/native/cocos/scene/SphereLight.cpp @@ -37,7 +37,7 @@ SphereLight::SphereLight() { void SphereLight::initialize() { Light::initialize(); - _size = 0.15F; + _size = 0.15F; _range = 1.0F; setLuminance(1700 / Light::nt2lm(_size)); _luminanceLDR = 1.0; @@ -54,13 +54,13 @@ void SphereLight::update() { float SphereLight::getLuminance() const { auto *sceneData = Root::getInstance()->getPipeline()->getPipelineSceneData(); - auto isHDR = sceneData->isHDR(); + auto isHDR = sceneData->isHDR(); return isHDR ? _luminanceHDR : _luminanceLDR; } void SphereLight::setLuminance(float value) { auto *sceneData = Root::getInstance()->getPipeline()->getPipelineSceneData(); - auto isHDR = sceneData->isHDR(); + auto isHDR = sceneData->isHDR(); if (isHDR) { _luminanceHDR = value; } else { diff --git a/native/cocos/scene/SphereLight.h b/native/cocos/scene/SphereLight.h index 57f37a363f..62fa6af4ea 100644 --- a/native/cocos/scene/SphereLight.h +++ b/native/cocos/scene/SphereLight.h @@ -41,35 +41,35 @@ public: void update() override; inline const Vec3 &getPosition() const { return _pos; } - inline void setPosition(const Vec3 &pos) { _pos = pos; } + inline void setPosition(const Vec3 &pos) { _pos = pos; } inline float getSize() const { return _size; } - inline void setSize(float size) { _size = size; } + inline void setSize(float size) { _size = size; } inline float getRange() const { return _range; } - inline void setRange(float range) { - _range = range; + inline void setRange(float range) { + _range = range; _needUpdate = true; } float getLuminance() const; - void setLuminance(float); + void setLuminance(float); - inline void setLuminanceHDR(float illum) { _luminanceHDR = illum; } + inline void setLuminanceHDR(float illum) { _luminanceHDR = illum; } inline float getLuminanceHDR() const { return _luminanceHDR; } - inline void setLuminanceLDR(float illum) { _luminanceLDR = illum; } + inline void setLuminanceLDR(float illum) { _luminanceLDR = illum; } inline float getLuminanceLDR() const { return _luminanceLDR; } inline const geometry::AABB &getAABB() const { return _aabb; } private: - bool _needUpdate{false}; - float _luminanceHDR{0.F}; - float _luminanceLDR{0.F}; - float _range{0.F}; - float _size{0.F}; - Vec3 _pos; + bool _needUpdate{false}; + float _luminanceHDR{0.F}; + float _luminanceLDR{0.F}; + float _range{0.F}; + float _size{0.F}; + Vec3 _pos; geometry::AABB _aabb; CC_DISALLOW_COPY_MOVE_ASSIGN(SphereLight); diff --git a/native/cocos/scene/SpotLight.cpp b/native/cocos/scene/SpotLight.cpp index d7fbf28ac4..a4a2784869 100644 --- a/native/cocos/scene/SpotLight.cpp +++ b/native/cocos/scene/SpotLight.cpp @@ -50,7 +50,7 @@ SpotLight::~SpotLight() { void SpotLight::initialize() { Light::initialize(); - _size = 0.15F; + _size = 0.15F; _aspect = 1.0F; setLuminance(1700 / Light::nt2lm(_size)); setLuminanceLDR(1.F); diff --git a/native/cocos/scene/SpotLight.h b/native/cocos/scene/SpotLight.h index c5e397642f..673dec7d23 100644 --- a/native/cocos/scene/SpotLight.h +++ b/native/cocos/scene/SpotLight.h @@ -43,11 +43,11 @@ public: inline const Vec3 &getPosition() const { return _pos; } inline float getSize() const { return _size; } - inline void setSize(float size) { _size = size; } + inline void setSize(float size) { _size = size; } inline float getRange() const { return _range; } - inline void setRange(float range) { - _range = range; + inline void setRange(float range) { + _range = range; _needUpdate = true; } @@ -55,30 +55,30 @@ public: inline void setLuminanceLDR(float value) { _luminanceLDR = value; } float getLuminance() const; - void setLuminance(float value); + void setLuminance(float value); inline const Vec3 &getDirection() const { return _dir; } inline float getSpotAngle() const { return _spotAngle; } - inline void setSpotAngle(float val) { - _angle = val; - _spotAngle = cos(val * 0.5F); + inline void setSpotAngle(float val) { + _angle = val; + _spotAngle = cos(val * 0.5F); _needUpdate = true; } inline float getAngle() const { return _angle; } inline float getAspect() const { return _aspect; } - inline void setAspect(float aspect) { - _aspect = aspect; + inline void setAspect(float aspect) { + _aspect = aspect; _needUpdate = true; } inline const geometry::AABB &getAABB() const { return *_aabb; } inline const geometry::Frustum &getFrustum() const { return *_frustum; } - inline float getLuminanceHDR() const { return _luminanceHDR; } - inline float getLuminanceLDR() const { return _luminanceLDR; } + inline float getLuminanceHDR() const { return _luminanceHDR; } + inline float getLuminanceLDR() const { return _luminanceLDR; } inline void setFrustum(const geometry::Frustum &frustum) { *_frustum = frustum; } @@ -86,26 +86,26 @@ public: inline bool isShadowEnabled() const { return _shadowEnabled; } inline float getShadowPcf() const { return _shadowPcf; } - inline void setShadowPcf(float pcf) { _shadowPcf = pcf; } + inline void setShadowPcf(float pcf) { _shadowPcf = pcf; } - inline void setShadowBias(float bias) { _shadowBias = bias; } + inline void setShadowBias(float bias) { _shadowBias = bias; } inline float getShadowBias() const { return _shadowBias; } - inline void setShadowNormalBias(float normalBias) { _shadowNormalBias = normalBias; } + inline void setShadowNormalBias(float normalBias) { _shadowNormalBias = normalBias; } inline float getShadowNormalBias() const { return _shadowNormalBias; } private: - bool _needUpdate{false}; - float _luminanceHDR{0.F}; - float _luminanceLDR{0.F}; - float _range{0.F}; - float _size{0.F}; - float _angle{0.F}; - float _spotAngle{0.F}; - float _aspect{0.F}; - Vec3 _dir; - Vec3 _pos; - geometry::AABB * _aabb{nullptr}; + bool _needUpdate{false}; + float _luminanceHDR{0.F}; + float _luminanceLDR{0.F}; + float _range{0.F}; + float _size{0.F}; + float _angle{0.F}; + float _spotAngle{0.F}; + float _aspect{0.F}; + Vec3 _dir; + Vec3 _pos; + geometry::AABB *_aabb{nullptr}; geometry::Frustum *_frustum{nullptr}; // shadow info diff --git a/native/cocos/scene/SubModel.cpp b/native/cocos/scene/SubModel.cpp index 5a7340f0ff..970193b309 100644 --- a/native/cocos/scene/SubModel.cpp +++ b/native/cocos/scene/SubModel.cpp @@ -41,7 +41,7 @@ SubModel::SubModel() { _id = generateId(); } -const static uint32_t MAX_PASS_COUNT = 8; +const static uint32_t MAX_PASS_COUNT = 8; void SubModel::update() { const auto &passes = *_passes; @@ -69,7 +69,7 @@ void SubModel::setPasses(const std::shared_ptr> if (_descriptorSet) { _descriptorSet->destroy(); gfx::DescriptorSetInfo dsInfo; - dsInfo.layout = passes[0]->getLocalSetLayout(); + dsInfo.layout = passes[0]->getLocalSetLayout(); _descriptorSet = _device->createDescriptorSet(dsInfo); } } @@ -96,16 +96,16 @@ void SubModel::initialize(RenderingSubMesh *subMesh, const std::shared_ptrempty()); gfx::DescriptorSetInfo dsInfo; dsInfo.layout = (*pPasses)[0]->getLocalSetLayout(); - _inputAssembler = _device->createInputAssembler(subMesh->getIaInfo()); - _descriptorSet = _device->createDescriptorSet(dsInfo); - const auto * pipeline = Root::getInstance()->getPipeline(); - const auto * occlusionPass = pipeline->getPipelineSceneData()->getOcclusionQueryPass(); + _inputAssembler = _device->createInputAssembler(subMesh->getIaInfo()); + _descriptorSet = _device->createDescriptorSet(dsInfo); + const auto *pipeline = Root::getInstance()->getPipeline(); + const auto *occlusionPass = pipeline->getPipelineSceneData()->getOcclusionQueryPass(); cc::gfx::DescriptorSetInfo occlusionDSInfo; - occlusionDSInfo.layout = occlusionPass->getLocalSetLayout(); + occlusionDSInfo.layout = occlusionPass->getLocalSetLayout(); _worldBoundDescriptorSet = _device->createDescriptorSet(occlusionDSInfo); - _subMesh = subMesh; - _patches = patches; - _passes = pPasses; + _subMesh = subMesh; + _patches = patches; + _passes = pPasses; flushPassInfo(); @@ -117,15 +117,15 @@ void SubModel::initialize(RenderingSubMesh *subMesh, const std::shared_ptrgetPhase() == pipeline::getPhaseID("reflection")) { - const auto * mainWindow = Root::getInstance()->getMainWindow(); - uint32_t texWidth = mainWindow->getWidth(); - uint32_t texHeight = mainWindow->getHeight(); - const uint32_t minSize = 512; + const auto *mainWindow = Root::getInstance()->getMainWindow(); + uint32_t texWidth = mainWindow->getWidth(); + uint32_t texHeight = mainWindow->getHeight(); + const uint32_t minSize = 512; if (texHeight < texWidth) { - texWidth = minSize * texWidth / texHeight; + texWidth = minSize * texWidth / texHeight; texHeight = minSize; } else { - texWidth = minSize; + texWidth = minSize; texHeight = minSize * texHeight / texWidth; } _reflectionTex = _device->createTexture(gfx::TextureInfo{ @@ -155,8 +155,8 @@ void SubModel::initialize(RenderingSubMesh *subMesh, const std::shared_ptrgetPipeline(); - Shadows * shadowInfo = pipeline->getPipelineSceneData()->getShadows(); + const auto *pipeline = Root::getInstance()->getPipeline(); + Shadows *shadowInfo = pipeline->getPipelineSceneData()->getShadows(); if (shadowInfo != nullptr) { _planarShader = shadowInfo->getPlanarShader(_patches); } else { @@ -168,8 +168,8 @@ void SubModel::initPlanarShadowShader() { // This is a temporary solution // It should not be written in a fixed way, or modified by the user void SubModel::initPlanarShadowInstanceShader() { - const auto *pipeline = Root::getInstance()->getPipeline(); - Shadows * shadowInfo = pipeline->getPipelineSceneData()->getShadows(); + const auto *pipeline = Root::getInstance()->getPipeline(); + Shadows *shadowInfo = pipeline->getPipelineSceneData()->getShadows(); if (shadowInfo != nullptr) { _planarInstanceShader = shadowInfo->getPlanarInstanceShader(_patches); } else { @@ -206,7 +206,7 @@ void SubModel::onPipelineStateChanged() { } void SubModel::onMacroPatchesStateChanged(const ccstd::vector &patches) { - _patches = patches; + _patches = patches; const auto &passes = *_passes; if (passes.empty()) return; for (Pass *pass : passes) { diff --git a/native/cocos/scene/SubModel.h b/native/cocos/scene/SubModel.h index 27ec585752..596799614e 100644 --- a/native/cocos/scene/SubModel.h +++ b/native/cocos/scene/SubModel.h @@ -45,31 +45,31 @@ public: void update(); gfx::Shader *getShader(uint) const; - Pass * getPass(uint) const; + Pass *getPass(uint) const; inline void setWorldBoundDescriptorSet(gfx::DescriptorSet *descriptorSet) { _worldBoundDescriptorSet = descriptorSet; } inline void setDescriptorSet(gfx::DescriptorSet *descriptorSet) { _descriptorSet = descriptorSet; } inline void setInputAssembler(gfx::InputAssembler *ia) { _inputAssembler = ia; } inline void setShaders(const ccstd::vector> &shaders) { _shaders = shaders; } - void setPasses(const std::shared_ptr>> &passes); + void setPasses(const std::shared_ptr>> &passes); inline void setPlanarInstanceShader(gfx::Shader *shader) { _planarInstanceShader = shader; } inline void setPlanarShader(gfx::Shader *shader) { _planarShader = shader; } inline void setPriority(pipeline::RenderPriority priority) { _priority = priority; } inline void setOwner(Model *model) { _owner = model; } - void setSubMesh(RenderingSubMesh *subMesh); + void setSubMesh(RenderingSubMesh *subMesh); - inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptorSet; } - inline gfx::DescriptorSet * getWorldBoundDescriptorSet() const { return _worldBoundDescriptorSet; } - inline gfx::InputAssembler * getInputAssembler() const { return _inputAssembler; } + inline gfx::DescriptorSet *getDescriptorSet() const { return _descriptorSet; } + inline gfx::DescriptorSet *getWorldBoundDescriptorSet() const { return _worldBoundDescriptorSet; } + inline gfx::InputAssembler *getInputAssembler() const { return _inputAssembler; } inline const ccstd::vector> &getShaders() const { return _shaders; } - inline const ccstd::vector> & getPasses() const { return *_passes; } - inline const ccstd::vector & getPatches() const { return _patches; } - inline gfx::Shader * getPlanarInstanceShader() const { return _planarInstanceShader; } - inline gfx::Shader * getPlanarShader() const { return _planarShader; } - inline pipeline::RenderPriority getPriority() const { return _priority; } - inline RenderingSubMesh * getSubMesh() const { return _subMesh; } - inline Model * getOwner() const { return _owner; } - inline uint32_t getId() const { return _id; } + inline const ccstd::vector> &getPasses() const { return *_passes; } + inline const ccstd::vector &getPatches() const { return _patches; } + inline gfx::Shader *getPlanarInstanceShader() const { return _planarInstanceShader; } + inline gfx::Shader *getPlanarShader() const { return _planarShader; } + inline pipeline::RenderPriority getPriority() const { return _priority; } + inline RenderingSubMesh *getSubMesh() const { return _subMesh; } + inline Model *getOwner() const { return _owner; } + inline uint32_t getId() const { return _id; } void initialize(RenderingSubMesh *subMesh, const std::shared_ptr>> &passes, const ccstd::vector &patches); void initPlanarShadowShader(); @@ -82,22 +82,22 @@ public: protected: void flushPassInfo(); - gfx::Device * _device{nullptr}; - ccstd::vector _patches; + gfx::Device *_device{nullptr}; + ccstd::vector _patches; IntrusivePtr _inputAssembler; - IntrusivePtr _descriptorSet; - IntrusivePtr _worldBoundDescriptorSet; + IntrusivePtr _descriptorSet; + IntrusivePtr _worldBoundDescriptorSet; - IntrusivePtr _reflectionTex; - gfx::Sampler * _reflectionSampler{nullptr}; - pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; - IntrusivePtr _planarShader; - IntrusivePtr _planarInstanceShader; - IntrusivePtr _subMesh; + IntrusivePtr _reflectionTex; + gfx::Sampler *_reflectionSampler{nullptr}; + pipeline::RenderPriority _priority{pipeline::RenderPriority::DEFAULT}; + IntrusivePtr _planarShader; + IntrusivePtr _planarInstanceShader; + IntrusivePtr _subMesh; std::shared_ptr>> _passes; - ccstd::vector> _shaders; - Model * _owner{nullptr}; - int32_t _id{-1}; + ccstd::vector> _shaders; + Model *_owner{nullptr}; + int32_t _id{-1}; private: static inline int32_t generateId() { diff --git a/native/cocos/storage/local-storage/LocalStorage-android.cpp b/native/cocos/storage/local-storage/LocalStorage-android.cpp index ba6dbbbfbe..bc4afd0b8d 100644 --- a/native/cocos/storage/local-storage/LocalStorage-android.cpp +++ b/native/cocos/storage/local-storage/LocalStorage-android.cpp @@ -43,7 +43,7 @@ static int gInitialized = 0; static void splitFilename(ccstd::string &str) { size_t found = 0; - found = str.find_last_of("/\\"); + found = str.find_last_of("/\\"); if (found != ccstd::string::npos) { str = str.substr(found + 1); } @@ -83,7 +83,7 @@ bool localStorageGetItem(const ccstd::string &key, ccstd::string *outItem) { if (JniHelper::getStaticMethodInfo(t, JCLS_LOCALSTORAGE, "getItem", "(Ljava/lang/String;)Ljava/lang/String;")) { jstring jkey = t.env->NewStringUTF(key.c_str()); - auto * jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey)); + auto *jret = static_cast(t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey)); if (jret == nullptr) { ccDeleteLocalRef(t.env, jret); ccDeleteLocalRef(t.env, jkey); diff --git a/native/cocos/storage/local-storage/LocalStorage.cpp b/native/cocos/storage/local-storage/LocalStorage.cpp index 5de7bd9b8c..2ce47dc6d2 100644 --- a/native/cocos/storage/local-storage/LocalStorage.cpp +++ b/native/cocos/storage/local-storage/LocalStorage.cpp @@ -66,8 +66,8 @@ #include "base/Macros.h" -static int _initialized = 0; -static sqlite3 * _db; +static int _initialized = 0; +static sqlite3 *_db; static sqlite3_stmt *_stmt_select; static sqlite3_stmt *_stmt_remove; static sqlite3_stmt *_stmt_update; @@ -76,9 +76,9 @@ static sqlite3_stmt *_stmt_key; static sqlite3_stmt *_stmt_count; static void localStorageCreateTable() { - const char * sql_createtable = "CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY,value TEXT);"; + const char *sql_createtable = "CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY,value TEXT);"; sqlite3_stmt *stmt; - int ok = sqlite3_prepare_v2(_db, sql_createtable, -1, &stmt, nullptr); + int ok = sqlite3_prepare_v2(_db, sql_createtable, -1, &stmt, nullptr); ok |= sqlite3_step(stmt); ok |= sqlite3_finalize(stmt); @@ -210,8 +210,8 @@ void localStorageGetKey(const int nIndex, ccstd::string *outKey) { ok |= sqlite3_step(_stmt_key); - int nCount = 0; - const unsigned char *text = nullptr; + int nCount = 0; + const unsigned char *text = nullptr; while (ok == SQLITE_ROW) { if (nCount == nIndex) { text = sqlite3_column_text(_stmt_key, 0); diff --git a/native/cocos/ui/edit-box/EditBox-android.cpp b/native/cocos/ui/edit-box/EditBox-android.cpp index b8d8c48187..7deab95cbf 100644 --- a/native/cocos/ui/edit-box/EditBox-android.cpp +++ b/native/cocos/ui/edit-box/EditBox-android.cpp @@ -46,7 +46,7 @@ void getTextInputCallback() { return; } - auto * global = se::ScriptEngine::getInstance()->getGlobalObject(); + auto *global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &textInputCallback); @@ -61,7 +61,7 @@ void callJSFunc(const ccstd::string &type, const ccstd::string &text) { getTextInputCallback(); se::AutoHandleScope scope; - se::ValueArray args; + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); textInputCallback.toObject()->call(args, nullptr); diff --git a/native/cocos/ui/edit-box/EditBox-ios.mm b/native/cocos/ui/edit-box/EditBox-ios.mm index 413daf9383..20c7b147e5 100644 --- a/native/cocos/ui/edit-box/EditBox-ios.mm +++ b/native/cocos/ui/edit-box/EditBox-ios.mm @@ -327,11 +327,11 @@ void removeKeyboardEventLisnters() { - (void)keyboardWillHide:(NSNotification *)notification { NSDictionary *info = [notification userInfo]; - + CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]; CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y; - + if (yOffset <= 0) { cc::EditBox::hide(); } diff --git a/native/cocos/ui/edit-box/EditBox-mac.mm b/native/cocos/ui/edit-box/EditBox-mac.mm index 1be70a399e..93ce3bf04f 100644 --- a/native/cocos/ui/edit-box/EditBox-mac.mm +++ b/native/cocos/ui/edit-box/EditBox-mac.mm @@ -77,7 +77,7 @@ se::Value g_textInputCallback; return TRUE; } -- (void) textDidEndEditing:(NSNotification *)notification { +- (void)textDidEndEditing:(NSNotification *)notification { cc::EditBox::complete(); } @end diff --git a/native/cocos/ui/edit-box/EditBox-ohos.cpp b/native/cocos/ui/edit-box/EditBox-ohos.cpp index 4132b5323a..5b7e2af372 100644 --- a/native/cocos/ui/edit-box/EditBox-ohos.cpp +++ b/native/cocos/ui/edit-box/EditBox-ohos.cpp @@ -47,7 +47,7 @@ void getTextInputCallback() { return; } - auto global = se::ScriptEngine::getInstance()->getGlobalObject(); + auto global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &textInputCallback); @@ -62,7 +62,7 @@ void callJSFunc(const ccstd::string &type, const ccstd::string &text) { getTextInputCallback(); se::AutoHandleScope scope; - se::ValueArray args; + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); textInputCallback.toObject()->call(args, nullptr); diff --git a/native/cocos/ui/edit-box/EditBox-win32.cpp b/native/cocos/ui/edit-box/EditBox-win32.cpp index 8fd35a9eaa..d09df6d801 100644 --- a/native/cocos/ui/edit-box/EditBox-win32.cpp +++ b/native/cocos/ui/edit-box/EditBox-win32.cpp @@ -44,10 +44,10 @@ namespace cc { ************************************************************************/ namespace { -bool g_isMultiline = false; -HWND g_hwndEditBox = nullptr; -WNDPROC g_prevMainWindowProc = nullptr; -WNDPROC g_prevEditWindowProc = nullptr; +bool g_isMultiline = false; +HWND g_hwndEditBox = nullptr; +WNDPROC g_prevMainWindowProc = nullptr; +WNDPROC g_prevEditWindowProc = nullptr; se::Value g_textInputCallback; HWND getCurrentWindowHwnd() { @@ -73,7 +73,7 @@ void getTextInputCallback() { if (!g_textInputCallback.isUndefined()) return; - auto global = se::ScriptEngine::getInstance()->getGlobalObject(); + auto global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &g_textInputCallback); @@ -88,19 +88,19 @@ void callJSFunc(const ccstd::string &type, const ccstd::string &text) { getTextInputCallback(); se::AutoHandleScope scope; - se::ValueArray args; + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); g_textInputCallback.toObject()->call(args, nullptr); } ccstd::string getText(HWND hwnd) { - int length = GetWindowTextLength(hwnd); - LPWSTR str = (LPWSTR)malloc(sizeof(WCHAR) * (length + 1)); + int length = GetWindowTextLength(hwnd); + LPWSTR str = (LPWSTR)malloc(sizeof(WCHAR) * (length + 1)); GetWindowText(hwnd, str, length + 1); std::wstring_convert> convert; - ccstd::string ret(convert.to_bytes(str)); + ccstd::string ret(convert.to_bytes(str)); free(str); return ret; @@ -110,7 +110,7 @@ std::wstring str2ws(const ccstd::string &text) { if (text.empty()) return std::wstring(); - int sz = MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), 0, 0); + int sz = MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), 0, 0); std::wstring res(sz, 0); MultiByteToWideChar(CP_UTF8, 0, &text[0], (int)text.size(), &res[0], sz); return res; @@ -162,7 +162,7 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { if (!g_hwndEditBox) { HWND parent = getCurrentWindowHwnd(); - UINT32 flags = WS_CHILD | showInfo.textAlignment | WS_TABSTOP | ES_AUTOHSCROLL; + UINT32 flags = WS_CHILD | showInfo.textAlignment | WS_TABSTOP | ES_AUTOHSCROLL; g_isMultiline = showInfo.isMultiline; if (g_isMultiline) { flags |= ES_MULTILINE; @@ -241,7 +241,7 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { SendMessage(g_hwndEditBox, EM_SETSEL, (WPARAM)0, (LPARAM)index); // int height = CC_GET_PLATFORM_INTERFACE(ISystemWindow)->kheight; CHARFORMAT2 cf; - RECT rect; + RECT rect; GetWindowRect(getCurrentWindowHwnd(), &rect); float WindowRatio = (float)(rect.bottom - rect.top) / (float)CC_GET_PLATFORM_INTERFACE(ISystemWindow)->getViewSize().y; @@ -258,12 +258,12 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { /* Set the caret to the end of the text in the box */ SendMessage(g_hwndEditBox, EM_SETSEL, (WPARAM)index, (LPARAM)index); - cf.cbSize = sizeof(CHARFORMAT2); + cf.cbSize = sizeof(CHARFORMAT2); cf.crTextColor = RGB((showInfo.fontColor & 0x000000ff), (showInfo.fontColor & 0x0000ff00) >> 8, (showInfo.fontColor & 0x00ff0000) >> 16); - cf.crBackColor = RGB((showInfo.backColor & 0x000000ff), (showInfo.backColor & 0x0000ff00) >> 8, (showInfo.backColor & 0x00ff0000) >> 16); - cf.dwMask = CFM_COLOR | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE; - cf.dwEffects = (showInfo.isUnderline ? CFE_UNDERLINE : 0) | (showInfo.isBold ? CFE_BOLD : 0) | (showInfo.isItalic ? CFE_ITALIC : 0); + cf.crBackColor = RGB((showInfo.backColor & 0x000000ff), (showInfo.backColor & 0x0000ff00) >> 8, (showInfo.backColor & 0x00ff0000) >> 16); + cf.dwMask = CFM_COLOR | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE; + cf.dwEffects = (showInfo.isUnderline ? CFE_UNDERLINE : 0) | (showInfo.isBold ? CFE_BOLD : 0) | (showInfo.isItalic ? CFE_ITALIC : 0); cf.bUnderlineColor = showInfo.underlineColor; SendMessage(g_hwndEditBox, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf); } diff --git a/native/cocos/ui/edit-box/EditBox.h b/native/cocos/ui/edit-box/EditBox.h index 630d49f478..923f3fcd84 100644 --- a/native/cocos/ui/edit-box/EditBox.h +++ b/native/cocos/ui/edit-box/EditBox.h @@ -41,23 +41,23 @@ public: ccstd::string defaultValue; ccstd::string confirmType; ccstd::string inputType; - int maxLength = 0; - int x = 0; - int y = 0; - int width = 0; - int height = 0; - bool confirmHold = false; - bool isMultiline = false; + int maxLength = 0; + int x = 0; + int y = 0; + int width = 0; + int height = 0; + bool confirmHold = false; + bool isMultiline = false; //NEW PROPERTIES - uint32_t fontSize = 20; - uint32_t fontColor = 0x00000000; - uint32_t backColor = 0x00000000; //font back color + uint32_t fontSize = 20; + uint32_t fontColor = 0x00000000; + uint32_t backColor = 0x00000000; //font back color uint32_t backgroundColor = 0x00000000; - bool isBold = false; - bool isItalic = false; - bool isUnderline = false; - uint32_t underlineColor = 0x00000000; - uint32_t textAlignment = LEFT; //By default, override with left, center or right + bool isBold = false; + bool isItalic = false; + bool isUnderline = false; + uint32_t underlineColor = 0x00000000; + uint32_t textAlignment = LEFT; //By default, override with left, center or right }; static void show(const ShowInfo &showInfo); diff --git a/native/cocos/ui/videoplayer/VideoPlayer-java.cpp b/native/cocos/ui/videoplayer/VideoPlayer-java.cpp index 470e71061e..abda6b172d 100644 --- a/native/cocos/ui/videoplayer/VideoPlayer-java.cpp +++ b/native/cocos/ui/videoplayer/VideoPlayer-java.cpp @@ -53,7 +53,7 @@ void Java_com_cocos_lib_CocosVideoHelper_nativeExecuteVideoCallback(JNIEnv *env, int createVideoWidgetJNI() { JniMethodInfo t; - int ret = -1; + int ret = -1; if (JniHelper::getStaticMethodInfo(t, VIDEO_HELPER_CLASS_NAME.c_str(), "createVideoWidget", "()I")) { ret = t.env->CallStaticIntMethod(t.classID, t.methodID); @@ -72,7 +72,7 @@ VideoPlayer::VideoPlayer() _fullScreenEnabled(false), _fullScreenDirty(false), _keepAspectRatioEnabled(false) { - _videoPlayerIndex = createVideoWidgetJNI(); + _videoPlayerIndex = createVideoWidgetJNI(); sAllVideoPlayers[_videoPlayerIndex] = this; #if CC_VIDEOPLAYER_DEBUG_DRAW @@ -88,10 +88,10 @@ VideoPlayer::~VideoPlayer() { void VideoPlayer::setURL(const ccstd::string &videoUrl) { if (videoUrl.find("://") == ccstd::string::npos) { - _videoURL = FileUtils::getInstance()->fullPathForFilename(videoUrl); + _videoURL = FileUtils::getInstance()->fullPathForFilename(videoUrl); _videoSource = VideoPlayer::Source::FILENAME; } else { - _videoURL = videoUrl; + _videoURL = videoUrl; _videoSource = VideoPlayer::Source::URL; } diff --git a/native/cocos/ui/videoplayer/VideoPlayer.h b/native/cocos/ui/videoplayer/VideoPlayer.h index c72f73870d..fa34e05286 100644 --- a/native/cocos/ui/videoplayer/VideoPlayer.h +++ b/native/cocos/ui/videoplayer/VideoPlayer.h @@ -164,9 +164,9 @@ protected: bool _keepAspectRatioEnabled; ccstd::string _videoURL; - Source _videoSource; + Source _videoSource; - int _videoPlayerIndex; + int _videoPlayerIndex; ccstd::unordered_map _eventCallback; void *_videoView; diff --git a/native/cocos/ui/webview/WebView-inl.h b/native/cocos/ui/webview/WebView-inl.h index 74f01afac7..74391e64d5 100644 --- a/native/cocos/ui/webview/WebView-inl.h +++ b/native/cocos/ui/webview/WebView-inl.h @@ -62,7 +62,7 @@ void WebView::setJavascriptInterfaceScheme(const ccstd::string &scheme) { _impl->setJavascriptInterfaceScheme(scheme); } -void WebView::loadData(const cc::Data & data, +void WebView::loadData(const cc::Data &data, const ccstd::string &MIMEType, const ccstd::string &encoding, const ccstd::string &baseURL) { @@ -147,7 +147,7 @@ void WebView::setOnJSCallback(const ccWebViewCallback &callback) { } std::function WebView::getOnShouldStartLoading() const { diff --git a/native/cocos/ui/webview/WebView.h b/native/cocos/ui/webview/WebView.h index e37eafbc73..4840785388 100644 --- a/native/cocos/ui/webview/WebView.h +++ b/native/cocos/ui/webview/WebView.h @@ -70,7 +70,7 @@ public: * @param encoding The encoding of the data. * @param baseURL The base URL for the content. */ - void loadData(const cc::Data & data, + void loadData(const cc::Data &data, const ccstd::string &mimeType, const ccstd::string &encoding, const ccstd::string &baseURL); diff --git a/native/cocos/ui/webview/WebViewImpl-android.cpp b/native/cocos/ui/webview/WebViewImpl-android.cpp index 0f3b1e2fd0..655e961cf4 100644 --- a/native/cocos/ui/webview/WebViewImpl-android.cpp +++ b/native/cocos/ui/webview/WebViewImpl-android.cpp @@ -72,8 +72,8 @@ extern "C" { JNIEXPORT jboolean JNICALL Java_com_cocos_lib_CocosWebViewHelper_shouldStartLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); return cc::WebViewImpl::shouldStartLoading(index, url); } @@ -87,8 +87,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_didFinishLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { // LOGD("didFinishLoading"); - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); cc::WebViewImpl::didFinishLoading(index, url); } @@ -102,8 +102,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_didFailLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { // LOGD("didFailLoading"); - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); cc::WebViewImpl::didFailLoading(index, url); } @@ -117,8 +117,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_onJsCallback(JNIEnv *env, jclass, jint index, //NOLINT jstring jmessage) { // LOGD("jsCallback"); - auto charMessage = env->GetStringUTFChars(jmessage, nullptr); - ccstd::string message = charMessage; + auto charMessage = env->GetStringUTFChars(jmessage, nullptr); + ccstd::string message = charMessage; env->ReleaseStringUTFChars(jmessage, charMessage); cc::WebViewImpl::onJsCallback(index, message); } @@ -140,7 +140,7 @@ int createWebViewJNI() { ccstd::string getUrlStringByFileName(const ccstd::string &fileName) { // LOGD("error: %s,%d",__func__,__LINE__); const ccstd::string basePath("file:///android_asset/"); - ccstd::string fullPath = cc::FileUtils::getInstance()->fullPathForFilename(fileName); + ccstd::string fullPath = cc::FileUtils::getInstance()->fullPathForFilename(fileName); const ccstd::string assetsPath("assets/"); ccstd::string urlString; @@ -161,7 +161,7 @@ static ccstd::unordered_map sWebViewImpls; WebViewImpl::WebViewImpl(WebView *webView) : _viewTag(-1), _webView(webView) { - _viewTag = createWebViewJNI(); + _viewTag = createWebViewJNI(); sWebViewImpls[_viewTag] = this; } @@ -230,7 +230,7 @@ void WebViewImpl::setScalesPageToFit(bool scalesPageToFit) { bool WebViewImpl::shouldStartLoading(int viewTag, const ccstd::string &url) { bool allowLoad = true; - auto it = sWebViewImpls.find(viewTag); + auto it = sWebViewImpls.find(viewTag); if (it != sWebViewImpls.end()) { auto webView = it->second->_webView; if (webView->_onShouldStartLoading) { diff --git a/native/cocos/ui/webview/WebViewImpl-ios.h b/native/cocos/ui/webview/WebViewImpl-ios.h index 53132e5fb6..18cf8cf2b3 100644 --- a/native/cocos/ui/webview/WebViewImpl-ios.h +++ b/native/cocos/ui/webview/WebViewImpl-ios.h @@ -46,7 +46,7 @@ public: void setJavascriptInterfaceScheme(const ccstd::string &scheme); - void loadData(const cc::Data & data, + void loadData(const cc::Data &data, const ccstd::string &MIMEType, const ccstd::string &encoding, const ccstd::string &baseURL); @@ -83,7 +83,7 @@ public: private: UIWebViewWrapper *_uiWebViewWrapper; - WebView * _webView; + WebView *_webView; }; } //namespace cc diff --git a/native/cocos/ui/webview/WebViewImpl-ios.mm b/native/cocos/ui/webview/WebViewImpl-ios.mm index a73672c623..32a27539b6 100644 --- a/native/cocos/ui/webview/WebViewImpl-ios.mm +++ b/native/cocos/ui/webview/WebViewImpl-ios.mm @@ -222,7 +222,7 @@ [self.uiWebView setBackgroundColor:isTransparent ? [UIColor clearColor] : [UIColor whiteColor]]; } - #pragma mark - WKNavigationDelegate +#pragma mark - WKNavigationDelegate - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *url = [[navigationAction request].URL.absoluteString stringByRemovingPercentEncoding]; NSString *scheme = [navigationAction request].URL.scheme; @@ -259,7 +259,7 @@ } } - #pragma WKUIDelegate +#pragma WKUIDelegate // Implement js alert function. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler { @@ -324,7 +324,6 @@ void WebViewImpl::loadData(const Data &data, const ccstd::string &MIMEType, const ccstd::string &encoding, const ccstd::string &baseURL) { - ccstd::string dataString(reinterpret_cast(data.getBytes()), static_cast(data.getSize())); [_uiWebViewWrapper loadData:dataString MIMEType:MIMEType textEncodingName:encoding baseURL:baseURL]; } diff --git a/native/cocos/ui/webview/WebViewImpl-java.h b/native/cocos/ui/webview/WebViewImpl-java.h index 17b0fa925d..310d500251 100644 --- a/native/cocos/ui/webview/WebViewImpl-java.h +++ b/native/cocos/ui/webview/WebViewImpl-java.h @@ -86,7 +86,7 @@ public: static void onJsCallback(int viewTag, const ccstd::string &message); private: - int _viewTag; + int _viewTag; WebView *_webView; }; diff --git a/native/cocos/ui/webview/WebViewImpl-ohos.cpp b/native/cocos/ui/webview/WebViewImpl-ohos.cpp index 778fb4662b..664caaf30f 100644 --- a/native/cocos/ui/webview/WebViewImpl-ohos.cpp +++ b/native/cocos/ui/webview/WebViewImpl-ohos.cpp @@ -74,8 +74,8 @@ extern "C" { JNIEXPORT jboolean JNICALL Java_com_cocos_lib_CocosWebViewHelper_shouldStartLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); return cc::WebViewImpl::shouldStartLoading(index, url); } @@ -89,8 +89,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_didFinishLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { // LOGD("didFinishLoading"); - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); cc::WebViewImpl::didFinishLoading(index, url); } @@ -104,8 +104,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_didFailLoading(JNIEnv *env, jclass, jint index, //NOLINT jstring jurl) { // LOGD("didFailLoading"); - auto charUrl = env->GetStringUTFChars(jurl, nullptr); - ccstd::string url = charUrl; + auto charUrl = env->GetStringUTFChars(jurl, nullptr); + ccstd::string url = charUrl; env->ReleaseStringUTFChars(jurl, charUrl); cc::WebViewImpl::didFailLoading(index, url); } @@ -119,8 +119,8 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosWebViewHelper_onJsCallback(JNIEnv *env, jclass, jint index, //NOLINT jstring jmessage) { // LOGD("jsCallback"); - auto charMessage = env->GetStringUTFChars(jmessage, nullptr); - ccstd::string message = charMessage; + auto charMessage = env->GetStringUTFChars(jmessage, nullptr); + ccstd::string message = charMessage; env->ReleaseStringUTFChars(jmessage, charMessage); cc::WebViewImpl::onJsCallback(index, message); } @@ -142,7 +142,7 @@ int createWebViewJNI() { ccstd::string getUrlStringByFileName(const ccstd::string &fileName) { // LOGD("error: %s,%d",__func__,__LINE__); const ccstd::string basePath("file:///android_asset/"); - ccstd::string fullPath = cc::FileUtils::getInstance()->fullPathForFilename(fileName); + ccstd::string fullPath = cc::FileUtils::getInstance()->fullPathForFilename(fileName); const ccstd::string assetsPath("assets/"); ccstd::string urlString; @@ -163,7 +163,7 @@ static ccstd::unordered_map sWebViewImpls; WebViewImpl::WebViewImpl(WebView *webView) : _viewTag(-1), _webView(webView) { - _viewTag = createWebViewJNI(); + _viewTag = createWebViewJNI(); sWebViewImpls[_viewTag] = this; } @@ -232,7 +232,7 @@ void WebViewImpl::setScalesPageToFit(bool scalesPageToFit) { bool WebViewImpl::shouldStartLoading(int viewTag, const ccstd::string &url) { bool allowLoad = true; - auto it = sWebViewImpls.find(viewTag); + auto it = sWebViewImpls.find(viewTag); if (it != sWebViewImpls.end()) { auto webView = it->second->_webView; if (webView->_onShouldStartLoading) { diff --git a/native/extensions/assets-manager/AssetsManagerEx.cpp b/native/extensions/assets-manager/AssetsManagerEx.cpp index ce1e78f17b..d2f352a803 100644 --- a/native/extensions/assets-manager/AssetsManagerEx.cpp +++ b/native/extensions/assets-manager/AssetsManagerEx.cpp @@ -54,7 +54,7 @@ NS_CC_EXT_BEGIN #define SAVE_POINT_INTERVAL 0.1 -const std::string AssetsManagerEx::VERSION_ID = "@version"; +const std::string AssetsManagerEx::VERSION_ID = "@version"; const std::string AssetsManagerEx::MANIFEST_ID = "@manifest"; // Implementation of AssetsManagerEx @@ -71,16 +71,16 @@ AssetsManagerEx::AssetsManagerEx(const std::string &manifestUrl, const std::stri void AssetsManagerEx::init(const std::string &manifestUrl, const std::string &storagePath) { // Init variables std::string pointer = StringUtils::format("%p", this); - _eventName = "__cc_assets_manager_" + pointer; - _fileUtils = FileUtils::getInstance(); + _eventName = "__cc_assets_manager_" + pointer; + _fileUtils = FileUtils::getInstance(); network::DownloaderHints hints = { static_cast(_maxConcurrentTask), DEFAULT_CONNECTION_TIMEOUT, ".tmp"}; - _downloader = std::shared_ptr(new network::Downloader(hints)); - _downloader->onTaskError = [this](auto &&pH1, auto &&pH2, auto &&pH3, auto &&pH4) { onError(std::forward(pH1), std::forward(pH2), std::forward(pH3), std::forward(pH4)); }; + _downloader = std::shared_ptr(new network::Downloader(hints)); + _downloader->onTaskError = [this](auto &&pH1, auto &&pH2, auto &&pH3, auto &&pH4) { onError(std::forward(pH1), std::forward(pH2), std::forward(pH3), std::forward(pH4)); }; _downloader->onTaskProgress = [this](const network::DownloadTask &task, int64_t /*bytesReceived*/, int64_t totalBytesReceived, @@ -91,9 +91,9 @@ void AssetsManagerEx::init(const std::string &manifestUrl, const std::string &st this->onSuccess(task.requestURL, task.storagePath, task.identifier); }; setStoragePath(storagePath); - _tempVersionPath = _tempStoragePath + VERSION_FILENAME; + _tempVersionPath = _tempStoragePath + VERSION_FILENAME; _cacheManifestPath = _storagePath + MANIFEST_FILENAME; - _tempManifestPath = _tempStoragePath + TEMP_MANIFEST_FILENAME; + _tempManifestPath = _tempStoragePath + TEMP_MANIFEST_FILENAME; if (!manifestUrl.empty()) { loadLocalManifest(manifestUrl); @@ -101,9 +101,9 @@ void AssetsManagerEx::init(const std::string &manifestUrl, const std::string &st } AssetsManagerEx::~AssetsManagerEx() { - _downloader->onTaskError = (nullptr); + _downloader->onTaskError = (nullptr); _downloader->onFileTaskSuccess = (nullptr); - _downloader->onTaskProgress = (nullptr); + _downloader->onTaskProgress = (nullptr); CC_SAFE_RELEASE(_localManifest); // _tempManifest could share a ptr with _remoteManifest or _localManifest if (_tempManifest != _localManifest && _tempManifest != _remoteManifest) { @@ -151,8 +151,8 @@ void AssetsManagerEx::initManifests() { CC_SAFE_RELEASE(_localManifest); CC_SAFE_RELEASE(_tempManifest); CC_SAFE_RELEASE(_remoteManifest); - _localManifest = nullptr; - _tempManifest = nullptr; + _localManifest = nullptr; + _tempManifest = nullptr; _remoteManifest = nullptr; } } @@ -176,9 +176,9 @@ bool AssetsManagerEx::loadLocalManifest(Manifest *localManifest, const std::stri // Reset storage path if (!storagePath.empty()) { setStoragePath(storagePath); - _tempVersionPath = _tempStoragePath + VERSION_FILENAME; + _tempVersionPath = _tempStoragePath + VERSION_FILENAME; _cacheManifestPath = _storagePath + MANIFEST_FILENAME; - _tempManifestPath = _tempStoragePath + TEMP_MANIFEST_FILENAME; + _tempManifestPath = _tempStoragePath + TEMP_MANIFEST_FILENAME; } // Release existing local manifest if (_localManifest) { @@ -255,7 +255,7 @@ bool AssetsManagerEx::loadLocalManifest(const std::string &manifestUrl) { std::vector searchPaths = _fileUtils->getSearchPaths(); if (cachedManifest) { std::vector cacheSearchPaths = cachedManifest->getSearchPaths(); - std::vector trimmedPaths = searchPaths; + std::vector trimmedPaths = searchPaths; for (const auto &path : cacheSearchPaths) { const auto pos = std::find(trimmedPaths.begin(), trimmedPaths.end(), path); if (pos != trimmedPaths.end()) { @@ -399,7 +399,7 @@ bool AssetsManagerEx::decompress(const std::string &filename) { for (i = 0; i < globalInfo.number_entry; ++i) { // Get info about current file. unz_file_info fileInfo; - char fileName[MAX_FILENAME]; + char fileName[MAX_FILENAME]; if (unzGetCurrentFileInfo(zipfile, &fileInfo, fileName, @@ -493,13 +493,13 @@ void AssetsManagerEx::decompressDownloadedZip(const std::string &customId, const struct AsyncData { std::string customId; std::string zipFile; - bool succeed; + bool succeed; }; - auto *asyncData = new AsyncData; + auto *asyncData = new AsyncData; asyncData->customId = customId; - asyncData->zipFile = storagePath; - asyncData->succeed = false; + asyncData->zipFile = storagePath; + asyncData->succeed = false; std::function decompressFinished = [this](void *param) { auto *dataInner = reinterpret_cast(param); @@ -661,11 +661,11 @@ void AssetsManagerEx::prepareUpdate() { _failedUnits.clear(); _downloadUnits.clear(); _totalWaitToDownload = _totalToDownload = 0; - _nextSavePoint = 0; + _nextSavePoint = 0; _percent = _percentByFile = 0.F; - _sizeCollected = 0; + _sizeCollected = 0; _totalDownloaded = _totalSize = 0.0; - _downloadResumed = false; + _downloadResumed = false; _downloadedSize.clear(); _totalEnabled = false; @@ -674,7 +674,7 @@ void AssetsManagerEx::prepareUpdate() { _tempManifest->saveToFile(_tempManifestPath); _tempManifest->genResumeAssetsList(&_downloadUnits); _totalWaitToDownload = _totalToDownload = static_cast(_downloadUnits.size()); - _downloadResumed = true; + _downloadResumed = true; // Collect total size for (const auto &iter : _downloadUnits) { @@ -709,12 +709,12 @@ void AssetsManagerEx::prepareUpdate() { for (auto &it : diffMap) { Manifest::AssetDiff diff = it.second; if (diff.type != Manifest::DiffType::DELETED) { - std::string path = diff.asset.path; + std::string path = diff.asset.path; DownloadUnit unit; - unit.customId = it.first; - unit.srcUrl = packageUrl + path + "?md5=" + diff.asset.md5; + unit.customId = it.first; + unit.srcUrl = packageUrl + path + "?md5=" + diff.asset.md5; unit.storagePath = _tempStoragePath + path; - unit.size = diff.asset.size; + unit.size = diff.asset.size; _downloadUnits.emplace(unit.customId, unit); _tempManifest->setAssetDownloadState(it.first, Manifest::DownloadState::UNSTARTED); _totalSize += unit.size; @@ -735,7 +735,7 @@ void AssetsManagerEx::startUpdate() { prepareUpdate(); } if (_updateState == State::READY_TO_UPDATE) { - _totalSize = 0; + _totalSize = 0; _updateState = State::UPDATING; std::string msg; if (_downloadResumed) { @@ -768,7 +768,7 @@ void AssetsManagerEx::updateSucceed() { // Merging all files in temp storage path to storage path std::vector files; _fileUtils->listFilesRecursively(_tempStoragePath, &files); - int baseOffset = static_cast(_tempStoragePath.length()); + int baseOffset = static_cast(_tempStoragePath.length()); std::string relativePath; std::string dstPath; for (auto &file : files) { @@ -927,11 +927,11 @@ void AssetsManagerEx::updateAssets(const DownloadUnits &assets) { _downloadUnits.clear(); _downloadedSize.clear(); _percent = _percentByFile = 0.F; - _sizeCollected = 0; + _sizeCollected = 0; _totalDownloaded = _totalSize = 0.0; _totalWaitToDownload = _totalToDownload = static_cast(assets.size()); - _nextSavePoint = 0; - _totalEnabled = false; + _nextSavePoint = 0; + _totalEnabled = false; if (_totalToDownload > 0) { _downloadUnits = assets; this->batchDownload(); @@ -994,9 +994,9 @@ void AssetsManagerEx::fileSuccess(const std::string &customId, const std::string } void AssetsManagerEx::onError(const network::DownloadTask &task, - int errorCode, - int errorCodeInternal, - const std::string & errorStr) { + int errorCode, + int errorCodeInternal, + const std::string &errorStr) { // Skip version error occurred if (task.identifier == VERSION_ID) { CC_LOG_DEBUG("AssetsManagerEx : Fail to download version file, step skipped\n"); @@ -1017,12 +1017,12 @@ void AssetsManagerEx::onProgress(double total, double downloaded, const std::str dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, customId); return; } // Calculate total downloaded - bool found = false; + bool found = false; _totalDownloaded = 0; for (auto &it : _downloadedSize) { if (it.first == customId) { it.second = downloaded; - found = true; + found = true; } _totalDownloaded += it.second; } @@ -1062,9 +1062,9 @@ void AssetsManagerEx::onSuccess(const std::string & /*srcUrl*/, const std::strin _updateState = State::MANIFEST_LOADED; parseManifest(); } else { - bool ok = true; - const auto &assets = _remoteManifest->getAssets(); - auto assetIt = assets.find(customId); + bool ok = true; + const auto &assets = _remoteManifest->getAssets(); + auto assetIt = assets.find(customId); if (assetIt != assets.end()) { Manifest::Asset asset = assetIt->second; if (_verifyCallback != nullptr) { diff --git a/native/extensions/assets-manager/AssetsManagerEx.h b/native/extensions/assets-manager/AssetsManagerEx.h index d75a18a7f8..08504b5131 100644 --- a/native/extensions/assets-manager/AssetsManagerEx.h +++ b/native/extensions/assets-manager/AssetsManagerEx.h @@ -70,8 +70,8 @@ public: const static std::string MANIFEST_ID; using VersionCompareHandle = std::function; - using VerifyCallback = std::function; - using EventCallback = std::function; + using VerifyCallback = std::function; + using EventCallback = std::function; /** @brief Create function for creating a new AssetsManagerEx @param manifestUrl The url for the local manifest file @@ -267,9 +267,9 @@ protected: * @lua NA */ virtual void onError(const network::DownloadTask &task, - int errorCode, - int errorCodeInternal, - const std::string & errorStr); + int errorCode, + int errorCodeInternal, + const std::string &errorStr); /** @brief Call back function for recording downloading percent of the current asset, the progression will then be reported to user's listener registed in addUpdateProgressEventListener diff --git a/native/extensions/assets-manager/AsyncTaskPool.h b/native/extensions/assets-manager/AsyncTaskPool.h index 0d9a630b0c..4001d3fe59 100644 --- a/native/extensions/assets-manager/AsyncTaskPool.h +++ b/native/extensions/assets-manager/AsyncTaskPool.h @@ -37,7 +37,6 @@ THE SOFTWARE. #include #include - /** * @addtogroup base * @{ @@ -97,7 +96,7 @@ protected: class ThreadTasks { struct AsyncTaskCallBack { TaskCallBack callback; - void * callbackParam; + void *callbackParam; }; public: @@ -106,7 +105,7 @@ protected: [this] { for (;;) { std::function task; - AsyncTaskCallBack callback; + AsyncTaskCallBack callback; { std::unique_lock lock(this->_queueMutex); this->_condition.wait(lock, @@ -114,7 +113,7 @@ protected: if (this->_stop && this->_tasks.empty()) { return; } - task = std::move(this->_tasks.front()); + task = std::move(this->_tasks.front()); callback = std::move(this->_taskCallBacks.front()); this->_tasks.pop(); this->_taskCallBacks.pop(); @@ -163,7 +162,7 @@ protected: } AsyncTaskCallBack taskCallBack; - taskCallBack.callback = callback; + taskCallBack.callback = callback; taskCallBack.callbackParam = callbackParam; _tasks.emplace([task]() { task(); }); _taskCallBacks.emplace(taskCallBack); @@ -176,12 +175,12 @@ protected: std::thread _thread; // the task queue std::queue> _tasks; - std::queue _taskCallBacks; + std::queue _taskCallBacks; // synchronization - std::mutex _queueMutex; + std::mutex _queueMutex; std::condition_variable _condition; - bool _stop{false}; + bool _stop{false}; }; //tasks diff --git a/native/extensions/assets-manager/Manifest.cpp b/native/extensions/assets-manager/Manifest.cpp index ea48352e0e..4a4d22ed0d 100644 --- a/native/extensions/assets-manager/Manifest.cpp +++ b/native/extensions/assets-manager/Manifest.cpp @@ -56,7 +56,7 @@ NS_CC_EXT_BEGIN static int cmpVersion(const std::string &v1, const std::string &v2) { int i; - int octV1[4] = {0}; + int octV1[4] = {0}; int octV2[4] = {0}; int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &octV1[0], &octV1[1], &octV1[2], &octV1[3]); int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &octV2[0], &octV2[1], &octV2[2], &octV2[3]); @@ -185,7 +185,7 @@ bool Manifest::versionEquals(const Manifest *b) const { return false; } // Check group versions - std::vector bGroups = b->getGroups(); + std::vector bGroups = b->getGroups(); std::unordered_map bGroupVer = b->getGroupVerions(); // Check group size if (bGroups.size() != _groups.size()) { @@ -209,8 +209,8 @@ bool Manifest::versionEquals(const Manifest *b) const { bool Manifest::versionGreaterOrEquals(const Manifest *b, const std::function &handle) const { std::string localVersion = getVersion(); - const std::string& bVersion = b->getVersion(); - bool greater; + const std::string &bVersion = b->getVersion(); + bool greater; if (handle) { greater = handle(localVersion, bVersion) >= 0; } else { @@ -221,8 +221,8 @@ bool Manifest::versionGreaterOrEquals(const Manifest *b, const std::function &handle) const { std::string localVersion = getVersion(); - const std::string& bVersion = b->getVersion(); - bool greater; + const std::string &bVersion = b->getVersion(); + bool greater; if (handle) { greater = handle(localVersion, bVersion) > 0; } else { @@ -232,17 +232,17 @@ bool Manifest::versionGreater(const Manifest *b, const std::function Manifest::genDiff(const Manifest *b) const { - std::unordered_map diffMap; + std::unordered_map diffMap; const std::unordered_map &bAssets = b->getAssets(); std::string key; - Asset valueA; - Asset valueB; + Asset valueA; + Asset valueB; std::unordered_map::const_iterator valueIt; std::unordered_map::const_iterator it; for (it = _assets.begin(); it != _assets.end(); ++it) { - key = it->first; + key = it->first; valueA = it->second; // Deleted @@ -250,7 +250,7 @@ std::unordered_map Manifest::genDiff(const Man if (valueIt == bAssets.cend()) { AssetDiff diff; diff.asset = valueA; - diff.type = DiffType::DELETED; + diff.type = DiffType::DELETED; diffMap.emplace(key, diff); continue; } @@ -260,13 +260,13 @@ std::unordered_map Manifest::genDiff(const Man if (valueA.md5 != valueB.md5) { AssetDiff diff; diff.asset = valueB; - diff.type = DiffType::MODIFIED; + diff.type = DiffType::MODIFIED; diffMap.emplace(key, diff); } } for (it = bAssets.begin(); it != bAssets.end(); ++it) { - key = it->first; + key = it->first; valueB = it->second; // Added @@ -274,7 +274,7 @@ std::unordered_map Manifest::genDiff(const Man if (valueIt == _assets.cend()) { AssetDiff diff; diff.asset = valueB; - diff.type = DiffType::ADDED; + diff.type = DiffType::ADDED; diffMap.emplace(key, diff); } } @@ -288,10 +288,10 @@ void Manifest::genResumeAssetsList(DownloadUnits *units) const { if (asset.downloadState != DownloadState::SUCCESSED && asset.downloadState != DownloadState::UNMARKED) { DownloadUnit unit; - unit.customId = it.first; - unit.srcUrl = _packageUrl + asset.path; + unit.customId = it.first; + unit.srcUrl = _packageUrl + asset.path; unit.storagePath = _manifestRoot + asset.path; - unit.size = asset.size; + unit.size = asset.size; units->emplace(unit.customId, unit); } } @@ -313,9 +313,9 @@ std::vector Manifest::getSearchPaths() const { } void Manifest::prependSearchPaths() { - std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); - auto iter = searchPaths.begin(); - bool needChangeSearchPaths = false; + std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); + auto iter = searchPaths.begin(); + bool needChangeSearchPaths = false; if (std::find(searchPaths.begin(), searchPaths.end(), _manifestRoot) == searchPaths.end()) { searchPaths.insert(iter, _manifestRoot); needChangeSearchPaths = true; @@ -398,9 +398,9 @@ void Manifest::clear() { _groupVer.clear(); _remoteManifestUrl = ""; - _remoteVersionUrl = ""; - _version = ""; - _engineVer = ""; + _remoteVersionUrl = ""; + _version = ""; + _engineVer = ""; _versionLoaded = false; } @@ -468,7 +468,7 @@ void Manifest::loadVersion(const rapidjson::Document &json) { const rapidjson::Value &groupVers = json[KEY_GROUP_VERSIONS]; if (groupVers.IsObject()) { for (rapidjson::Value::ConstMemberIterator itr = groupVers.MemberBegin(); itr != groupVers.MemberEnd(); ++itr) { - std::string group = itr->name.GetString(); + std::string group = itr->name.GetString(); std::string version = "0"; if (itr->value.IsString()) { version = itr->value.GetString(); @@ -509,8 +509,8 @@ void Manifest::loadManifest(const rapidjson::Document &json) { const rapidjson::Value &assets = json[KEY_ASSETS]; if (assets.IsObject()) { for (rapidjson::Value::ConstMemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr) { - std::string key = itr->name.GetString(); - Asset asset = parseAsset(key, itr->value); + std::string key = itr->name.GetString(); + Asset asset = parseAsset(key, itr->value); _assets.emplace(key, asset); } } @@ -532,7 +532,7 @@ void Manifest::loadManifest(const rapidjson::Document &json) { } void Manifest::saveToFile(const std::string &filepath) { - rapidjson::StringBuffer buffer; + rapidjson::StringBuffer buffer; rapidjson::PrettyWriter writer(buffer); _json.Accept(writer); diff --git a/native/extensions/assets-manager/Manifest.h b/native/extensions/assets-manager/Manifest.h index ac231cfc62..9b42040ee9 100644 --- a/native/extensions/assets-manager/Manifest.h +++ b/native/extensions/assets-manager/Manifest.h @@ -44,15 +44,15 @@ struct DownloadUnit { std::string srcUrl; std::string storagePath; std::string customId; - float size; + float size; }; struct ManifestAsset { std::string md5; std::string path; - bool compressed; - float size; - int downloadState; + bool compressed; + float size; + int downloadState; }; using DownloadUnits = std::unordered_map; @@ -80,7 +80,7 @@ public: //! Object indicate the difference between two Assets struct AssetDiff { - Asset asset; + Asset asset; DiffType type; }; diff --git a/native/extensions/cocos-ext.h b/native/extensions/cocos-ext.h index 6e915c4088..2e6793d22e 100644 --- a/native/extensions/cocos-ext.h +++ b/native/extensions/cocos-ext.h @@ -27,7 +27,7 @@ #define __COCOS2D_EXT_H__ #ifdef _MSC_VER -#pragma warning(disable:4996) + #pragma warning(disable : 4996) #endif #include "ExtensionMacros.h" diff --git a/native/tests/module-tests/bindings/test-bindings.cpp b/native/tests/module-tests/bindings/test-bindings.cpp index 638813abca..9441e451a9 100644 --- a/native/tests/module-tests/bindings/test-bindings.cpp +++ b/native/tests/module-tests/bindings/test-bindings.cpp @@ -7,16 +7,15 @@ #include "cocos/bindings/manual/jsb_global_init.h" int main(int argc, char **argv) { - std::string scriptPath = "index.js"; - if(argc > 1) { + if (argc > 1) { scriptPath = argv[1]; } auto *engine = se::ScriptEngine::getInstance(); auto *fu = cc::FileUtils::getInstance(); - + // TODO: replace search path auto *currentDir = getenv("PWD"); fu->addSearchPath(currentDir); @@ -28,9 +27,8 @@ int main(int argc, char **argv) { engine->evalString("console.log('begin execute')"); auto ret = engine->runScript(scriptPath); engine->evalString("console.log('end')"); - if(!ret) return EXIT_FAILURE; + if (!ret) return EXIT_FAILURE; - se::ScriptEngine::destroyInstance(); cc::FileUtils::destroyInstance(); return 0; diff --git a/native/tests/module-tests/filesystem/test-fs.cpp b/native/tests/module-tests/filesystem/test-fs.cpp index f2c1933307..fffba44c95 100644 --- a/native/tests/module-tests/filesystem/test-fs.cpp +++ b/native/tests/module-tests/filesystem/test-fs.cpp @@ -2,7 +2,6 @@ #include #include "platform/FileUtils.h" - int main(int argc, char **argv) { auto *fu = cc::FileUtils::getInstance(); cc::FileUtils::destroyInstance(); diff --git a/native/tests/unit-test/src/geometry_capsule_test.cpp b/native/tests/unit-test/src/geometry_capsule_test.cpp index 41db2a285c..13cea3be17 100644 --- a/native/tests/unit-test/src/geometry_capsule_test.cpp +++ b/native/tests/unit-test/src/geometry_capsule_test.cpp @@ -35,12 +35,12 @@ THE SOFTWARE. TEST(geometryCapsuleTest, testTransform) { cc::geometry::Capsule capsule{1.0, 2.0}; cc::geometry::Capsule capsuleNew{}; - cc::Mat4 trans; - cc::Quaternion quat{}; - cc::Vec3 scale{1.0F, 2.0F, 3.0F}; + cc::Mat4 trans; + cc::Quaternion quat{}; + cc::Vec3 scale{1.0F, 2.0F, 3.0F}; { - cc::Vec3 axis = {1.0, 0.0, 0.0}; - float angle = M_PI; + cc::Vec3 axis = {1.0, 0.0, 0.0}; + float angle = M_PI; cc::Quaternion::createFromAxisAngle(axis, angle, &quat); trans.translate(0, 1, 0); } diff --git a/native/tests/unit-test/src/math_geometry_test.cpp b/native/tests/unit-test/src/math_geometry_test.cpp index 45edf40f15..07684d4e81 100644 --- a/native/tests/unit-test/src/math_geometry_test.cpp +++ b/native/tests/unit-test/src/math_geometry_test.cpp @@ -88,4 +88,3 @@ TEST(mathGeometryTest, test7) { size.setSize(230, 190); ExpectEq(rect.size.equals(size), true); } - diff --git a/native/tests/unit-test/src/math_mat3_test.cpp b/native/tests/unit-test/src/math_mat3_test.cpp index e8c05392f5..7b3f8ce0dd 100644 --- a/native/tests/unit-test/src/math_mat3_test.cpp +++ b/native/tests/unit-test/src/math_mat3_test.cpp @@ -104,7 +104,7 @@ TEST(mathMat3Test, test4) { ExpectEq(copyMat.m[0] == 3 && copyMat.m[3] == 6 && copyMat.m[4] == 7, true); // fromQuat logLabel = "test the mat3 fromQuat function"; - cc::Mat3 fromQuat; + cc::Mat3 fromQuat; cc::Quaternion quat(0, 0, 3, 1); cc::Mat3::fromQuat(quat, &fromQuat); ExpectEq(copyMat.m[0] == 3 && copyMat.m[3] == 6 && copyMat.m[4] == 7, true); diff --git a/native/tests/unit-test/src/math_mat4_test.cpp b/native/tests/unit-test/src/math_mat4_test.cpp index 2baef8054c..1e6dc5c0d3 100644 --- a/native/tests/unit-test/src/math_mat4_test.cpp +++ b/native/tests/unit-test/src/math_mat4_test.cpp @@ -117,7 +117,7 @@ TEST(mathMat4Test, test5) { // fromRT logLabel = "test the mat4 fromRT function"; cc::Quaternion rotVec(1, 0, 1, 1); - cc::Vec3 transVec(1, 1, 2); + cc::Vec3 transVec(1, 1, 2); cc::Mat4::fromRT(rotVec, transVec, &outMat); ExpectEq(outMat.m[5] == -3 && outMat.m[9] == -2 && outMat.m[14] == 2, true); // decompose @@ -127,16 +127,16 @@ TEST(mathMat4Test, test5) { // determinant logLabel = "test the mat4 determinant function"; cc::Mat4 det; - det.m[0] = 5; - det.m[1] = 7; - det.m[6] = 2; + det.m[0] = 5; + det.m[1] = 7; + det.m[6] = 2; float detVal = det.determinant(); ExpectEq(detVal == 5, true); // getScale logLabel = "test the mat4 getScale function"; cc::Mat4 getScaleMat; - getScaleMat.m[0] = 5; - getScaleMat.m[5] = 7; + getScaleMat.m[0] = 5; + getScaleMat.m[5] = 7; getScaleMat.m[10] = 2; cc::Vec3 scaleOut; getScaleMat.getScale(&scaleOut); @@ -181,15 +181,15 @@ TEST(mathMat4Test, test5) { outMat.getBackVector(&backVec3); ExpectEq(backVec3.x == 2 && backVec3.y == -2 && backVec3.z == -1, true); // inverse - logLabel = "test the mat4 inverse function"; + logLabel = "test the mat4 inverse function"; bool isInverse = outMat.inverse(); ExpectEq(isInverse == true, true); // getInversed logLabel = "test the mat4 getInversed function"; cc::Mat4 inversed; - inversed.m[1] = 10; - inversed.m[2] = 13; - inversed.m[4] = 2; + inversed.m[1] = 10; + inversed.m[2] = 13; + inversed.m[4] = 2; cc::Mat4 inversedMat = inversed.getInversed(); ExpectEq(IsEqualF(inversedMat.m[6], -1.36842108), true); // identity diff --git a/native/tests/unit-test/src/math_quaternion_test.cpp b/native/tests/unit-test/src/math_quaternion_test.cpp index cc24225bdd..15f5163362 100644 --- a/native/tests/unit-test/src/math_quaternion_test.cpp +++ b/native/tests/unit-test/src/math_quaternion_test.cpp @@ -34,7 +34,7 @@ THE SOFTWARE. TEST(mathQuaternionTest, test6) { // identity logLabel = "test the quaternion identity function"; - cc::Quaternion quat(1,2,1,1); + cc::Quaternion quat(1, 2, 1, 1); quat = cc::Quaternion::identity(); ExpectEq(quat.x == 0 && quat.y == 0 && quat.z == 0 && quat.w == 1, true); // isIdentity @@ -44,7 +44,7 @@ TEST(mathQuaternionTest, test6) { ExpectEq(quat.isIdentity(), true); // zero logLabel = "test the quaternion zero function"; - cc::Quaternion zero(1,2,1,1); + cc::Quaternion zero(1, 2, 1, 1); zero = cc::Quaternion::zero(); ExpectEq(zero.x == 0 && zero.y == 0 && zero.z == 0 && zero.w == 0, true); // isZero @@ -105,7 +105,4 @@ TEST(mathQuaternionTest, test6) { q2.set(30, 10, 20, 1); cc::Quaternion::slerp(q1, q2, 0, &quat); ExpectEq(IsEqualF(1, quat.x) && IsEqualF(10, quat.z), true); - - } - diff --git a/native/tests/unit-test/src/math_vec3_test.cpp b/native/tests/unit-test/src/math_vec3_test.cpp index 5306ead391..08676ea293 100644 --- a/native/tests/unit-test/src/math_vec3_test.cpp +++ b/native/tests/unit-test/src/math_vec3_test.cpp @@ -30,7 +30,7 @@ THE SOFTWARE. #include TEST(mathVec3Test, test2) { - cc::Vec3 vec3(1, 2, 3); + cc::Vec3 vec3(1, 2, 3); // isZero logLabel = "test whether vec3 is 0"; ExpectEq(vec3.isZero(), false); @@ -156,4 +156,3 @@ TEST(mathVec3Test, test2) { vec3 = cc::Vec3::fromColor(255); ExpectEq(vec3.z == 1, true); } - diff --git a/native/tests/unit-test/src/math_vec4_test.cpp b/native/tests/unit-test/src/math_vec4_test.cpp index 7ae41df1b4..c01cfb8a07 100644 --- a/native/tests/unit-test/src/math_vec4_test.cpp +++ b/native/tests/unit-test/src/math_vec4_test.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. #include TEST(mathVec4Test, test3) { - cc::Vec4 vec4(1, 2, 3, 1); + cc::Vec4 vec4(1, 2, 3, 1); // isZero logLabel = "test whether vec4 is 0"; ExpectEq(vec4.isZero(), false); @@ -106,4 +106,3 @@ TEST(mathVec4Test, test3) { vec4 = cc::Vec4::fromColor(255); ExpectEq(vec4.w == 1, true); } - diff --git a/native/tests/unit-test/src/math_vertex_test.cpp b/native/tests/unit-test/src/math_vertex_test.cpp index debcbe8ca9..b2db465cc1 100644 --- a/native/tests/unit-test/src/math_vertex_test.cpp +++ b/native/tests/unit-test/src/math_vertex_test.cpp @@ -39,6 +39,6 @@ TEST(mathVertexTest, test8) { // ccVertexLineIntersect logLabel = "test the vertex ccVertexLineIntersect function"; float res; - bool isFind = cc::ccVertexLineIntersect(5, 5, 1, 10, 12, 20, 12, 40, &res); + bool isFind = cc::ccVertexLineIntersect(5, 5, 1, 10, 12, 20, 12, 40, &res); ExpectEq(isFind, true); } \ No newline at end of file diff --git a/native/tests/unit-test/src/pool_test.cpp b/native/tests/unit-test/src/pool_test.cpp index fcc8c57598..c5d79d5b49 100644 --- a/native/tests/unit-test/src/pool_test.cpp +++ b/native/tests/unit-test/src/pool_test.cpp @@ -43,7 +43,7 @@ PoolTest *createTest() { } const int32_t ARRAY_SIZE = 10; -auto * pool = new memop::Pool(createTest, ARRAY_SIZE); +auto *pool = new memop::Pool(createTest, ARRAY_SIZE); } // namespace @@ -62,7 +62,7 @@ TEST(PoolTest, free) { } TEST(PoolTest, freeArray) { - const int32_t TEST_SIZE = 5; + const int32_t TEST_SIZE = 5; std::vector tmpArr(TEST_SIZE); for (int32_t i = 0; i < TEST_SIZE; ++i) { PoolTest *a = createTest(); diff --git a/native/tests/unit-test/src/utils.h b/native/tests/unit-test/src/utils.h index d8e27ae259..da80d6c298 100644 --- a/native/tests/unit-test/src/utils.h +++ b/native/tests/unit-test/src/utils.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include "gtest/gtest.h" static std::string logLabel; -static bool IsEqualF(float l, float r) { +static bool IsEqualF(float l, float r) { return cc::math::IsEqualF(l, r); }; static void ExpectEq(bool lf, bool rt) {